-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprojectBuilder.ts
More file actions
348 lines (305 loc) · 10.5 KB
/
projectBuilder.ts
File metadata and controls
348 lines (305 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
import dedent from 'dedent';
import { join } from 'path';
import { writeFile } from '../../utils/writeFile.js';
import type { GeneratorOptions } from '../interface.js';
import { generateApp } from './app.js';
import { generateAppExtensions } from './appExtensions.js';
import { generateCrypto } from './crypto.js';
import { generateDatabase } from './database.js';
import { generateOauth } from './oauth.js';
import { generatePipedriveClient } from './pipedriveClient.js';
import { envVarAccess } from '../../utils/templates.js';
export interface BuildStep {
execute(outputDir: string, options: GeneratorOptions): Promise<void>;
}
class OAuthStep implements BuildStep {
async execute(outputDir: string, options: GeneratorOptions): Promise<void> {
await generateOauth(outputDir, options);
}
}
class DatabaseStep implements BuildStep {
async execute(outputDir: string, options: GeneratorOptions): Promise<void> {
await generateDatabase(outputDir, options);
}
}
class AppStep implements BuildStep {
async execute(outputDir: string, options: GeneratorOptions): Promise<void> {
await generateApp(outputDir, options);
}
}
class AppExtensionsStep implements BuildStep {
async execute(outputDir: string, options: GeneratorOptions): Promise<void> {
await generateAppExtensions(outputDir, options);
}
}
class PipedriveClientStep implements BuildStep {
async execute(outputDir: string, options: GeneratorOptions): Promise<void> {
await generatePipedriveClient(outputDir, options);
}
}
class CryptoStep implements BuildStep {
async execute(outputDir: string, _options: GeneratorOptions): Promise<void> {
await generateCrypto(outputDir);
}
}
class ServerEntryStep implements BuildStep {
async execute(outputDir: string, _options: GeneratorOptions): Promise<void> {
await writeFile(
join(outputDir, 'src/index.ts'),
dedent`
import { runMigrations } from './database/migrate.js';
import app from './app.js';
const PORT = ${envVarAccess('PORT', '3000')};
const STARTUP_RETRY_ATTEMPTS = 60;
const STARTUP_RETRY_DELAY_MS = 1000;
async function waitForDatabase(): Promise<void> {
for (let attempt = 1; attempt <= STARTUP_RETRY_ATTEMPTS; attempt++) {
try {
await runMigrations();
return;
} catch (error) {
if (attempt === STARTUP_RETRY_ATTEMPTS) throw error;
const message = error instanceof Error ? error.message : String(error);
console.warn(
\`Database is not ready yet (\${attempt}/\${STARTUP_RETRY_ATTEMPTS}): \${message}\`,
);
await new Promise<void>((resolve) => setTimeout(resolve, STARTUP_RETRY_DELAY_MS));
}
}
}
await waitForDatabase();
app.listen(PORT, () => {
console.log(\`Server running at http://localhost:\${PORT}\`);
});
`,
);
}
}
class PackageJsonStep implements BuildStep {
async execute(outputDir: string, options: GeneratorOptions): Promise<void> {
const hasAppExtensions = options.appExtensions.length > 0;
const dbDrivers: Record<GeneratorOptions['database'], Record<string, string>> = {
postgres: { postgres: '^3.4.0' },
mysql: { mysql2: '^3.9.0' },
sqlite: { '@libsql/client': '^0.14.0' },
};
const dbDevDrivers: Record<GeneratorOptions['database'], Record<string, string>> = {
postgres: {},
mysql: {},
sqlite: {},
};
const pkg = {
name: options.projectName,
version: '0.1.0',
type: 'module',
scripts: {
'dev': 'tsx watch --env-file=.env src/index.ts',
...(hasAppExtensions
? {
'dev:frontend': 'vite --config frontend/app-extension-ui/vite.config.ts',
'build:frontend': 'vite build --config frontend/app-extension-ui/vite.config.ts',
'preview:frontend': 'vite preview --config frontend/app-extension-ui/vite.config.ts',
}
: {}),
'build': hasAppExtensions
? 'tsc && vite build --config frontend/app-extension-ui/vite.config.ts'
: 'tsc',
'start': 'node --env-file=.env dist/index.js',
'typecheck': hasAppExtensions
? 'tsc --noEmit && tsc --noEmit -p frontend/app-extension-ui/tsconfig.json'
: 'tsc --noEmit',
'db:migrate': 'drizzle-kit migrate',
},
dependencies: {
'express': '^4.19.0',
'drizzle-orm': '^0.45.0',
'pipedrive': '^32.0.0',
...(hasAppExtensions
? {
'@pipedrive/app-extensions-sdk': '^0.13.1',
'react': '^18.2.0',
'react-dom': '^18.2.0',
'react-router-dom': '^6.22.0',
}
: {}),
...dbDrivers[options.database],
},
devDependencies: {
'typescript': '^5.4.0',
'@types/express': '^4.17.0',
'@types/node': '^20.0.0',
'tsx': '^4.21.0',
'drizzle-kit': '^0.31.0',
...(hasAppExtensions
? {
'@types/react': '^18.2.0',
'@types/react-dom': '^18.2.0',
'@vitejs/plugin-react': '^4.2.0',
'vite': '^5.2.0',
}
: {}),
...dbDevDrivers[options.database],
},
};
await writeFile(join(outputDir, 'package.json'), JSON.stringify(pkg, null, 2));
}
}
class TsConfigStep implements BuildStep {
async execute(outputDir: string, _options: GeneratorOptions): Promise<void> {
const tsconfig = {
compilerOptions: {
target: 'ESNext',
module: 'ESNext',
moduleResolution: 'bundler',
outDir: 'dist',
rootDir: 'src',
strict: true,
esModuleInterop: true,
skipLibCheck: true,
},
include: ['src'],
};
await writeFile(join(outputDir, 'tsconfig.json'), JSON.stringify(tsconfig, null, 2));
}
}
class EnvExampleStep implements BuildStep {
async execute(outputDir: string, options: GeneratorOptions): Promise<void> {
const databaseUrlExample: Record<GeneratorOptions['database'], string> = {
postgres: `postgresql://app:app@localhost:5432/${options.projectName}`,
mysql: `mysql://app:app@localhost:3307/${options.projectName}`,
sqlite: 'file:./data.db',
};
const extensionUrls = appExtensionEnvExample(options);
await writeFile(
join(outputDir, '.env.example'),
dedent`
PIPEDRIVE_CLIENT_ID=
PIPEDRIVE_CLIENT_SECRET=
PIPEDRIVE_REDIRECT_URI=http://localhost:3000/oauth/callback
DATABASE_URL=${databaseUrlExample[options.database]}
PORT=3000
ENCRYPTION_KEY=
# generate with: openssl rand -hex 32
${extensionUrls}
`,
);
}
}
class ReadmeStep implements BuildStep {
async execute(outputDir: string, options: GeneratorOptions): Promise<void> {
await writeFile(join(outputDir, 'README.md'), readmeContent(options));
}
}
function appExtensionEnvExample(options: GeneratorOptions): string {
const lines: string[] = [];
if (options.appExtensions.includes('custom-panel')) {
lines.push(
'# Custom panel iframe URLs:',
'# Local: https://<your-vite-tunnel>/extensions/panel',
'# Production: https://<your-backend-domain>/extensions/panel',
);
}
if (options.appExtensions.includes('custom-modal')) {
lines.push(
'# Custom modal iframe URLs:',
'# Local: https://<your-vite-tunnel>/extensions/modal',
'# Production: https://<your-backend-domain>/extensions/modal',
'VITE_CUSTOM_MODAL_ACTION_ID=',
'# Paste the "Extension identifier" from Marketplace Developer Hub → App Extensions',
);
}
return lines.length > 0 ? `\n${lines.join('\n')}` : '';
}
function readmeContent(options: GeneratorOptions): string {
const needsDocker = options.database === 'postgres' || options.database === 'mysql';
const setupCommands =
options.appExtensions.length > 0
? ['cp .env.example .env', 'docker-compose up --watch']
: [
'cp .env.example .env',
...(needsDocker ? ['docker-compose up -d db'] : []),
'npm install',
'npm run dev',
];
const appExtensionsSection =
options.appExtensions.length > 0
? dedent`
## App Extensions
This project includes a React + Vite custom UI extension under \`frontend/app-extension-ui\`. It initializes \`@pipedrive/app-extensions-sdk\`, reads iframe query params, follows the user's light or dark theme, and exposes example SDK actions.
For local development, run \`docker-compose up --watch\`. It starts the backend and Vite dev server in containers, then syncs code changes into both services. Expose the Vite server through a public HTTPS tunnel and configure Developer Hub iframe URLs to use the tunnel:
${options.appExtensions.includes('custom-panel') ? '- Custom panel: `https://<your-vite-tunnel>/extensions/panel`' : ''}
${options.appExtensions.includes('custom-modal') ? '- Custom modal: `https://<your-vite-tunnel>/extensions/modal`' : ''}
For production, run \`npm run build\` and point Developer Hub to your backend-hosted URLs:
${options.appExtensions.includes('custom-panel') ? '- Custom panel: `https://<your-backend-domain>/extensions/panel`' : ''}
${options.appExtensions.includes('custom-modal') ? '- Custom modal: `https://<your-backend-domain>/extensions/modal`' : ''}
`
: '';
return dedent`
# ${options.projectName}
Generated Pipedrive Marketplace app using Express, TypeScript, and Drizzle ORM.
## Setup
\`\`\`bash
${setupCommands.join('\n')}
\`\`\`
Fill in \`PIPEDRIVE_CLIENT_ID\`, \`PIPEDRIVE_CLIENT_SECRET\`, \`PIPEDRIVE_REDIRECT_URI\`, and \`DATABASE_URL\` in \`.env\`.
## Scripts
- \`npm run dev\` starts the backend server locally.
- \`npm run typecheck\` checks TypeScript.
- \`npm run build\` builds the generated project.
${options.appExtensions.length > 0 ? '- `docker-compose up --watch` starts the backend and App Extensions Vite server in containers with Compose Watch.' : ''}
${appExtensionsSection}
`;
}
export class NodeProjectBuilder {
private steps: BuildStep[] = [];
constructor(
private outputDir: string,
private options: GeneratorOptions,
) {}
addStep(step: BuildStep): this {
this.steps.push(step);
return this;
}
addOAuth(): this {
return this.addStep(new OAuthStep());
}
addDatabase(): this {
return this.addStep(new DatabaseStep());
}
addApp(): this {
return this.addStep(new AppStep());
}
addAppExtensions(): this {
return this.addStep(new AppExtensionsStep());
}
addPipedriveClient(): this {
return this.addStep(new PipedriveClientStep());
}
addCrypto(): this {
return this.addStep(new CryptoStep());
}
addServerEntry(): this {
return this.addStep(new ServerEntryStep());
}
addPackageJson(): this {
return this.addStep(new PackageJsonStep());
}
addTsConfig(): this {
return this.addStep(new TsConfigStep());
}
addEnvExample(): this {
return this.addStep(new EnvExampleStep());
}
addReadme(): this {
return this.addStep(new ReadmeStep());
}
when(condition: boolean, fn: (b: this) => void): this {
if (condition) fn(this);
return this;
}
async build(): Promise<void> {
for (const step of this.steps) {
await step.execute(this.outputDir, this.options);
}
}
}