-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcli.ts
More file actions
507 lines (474 loc) · 14.6 KB
/
Copy pathcli.ts
File metadata and controls
507 lines (474 loc) · 14.6 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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
#!/usr/bin/env node
import {existsSync} from 'fs';
import {dirname, join} from 'path';
import {
createCLI,
detectPackageManager,
TemplateEngine,
type FileConfig,
type TemplateContext,
} from 'tinycreate';
import {fileURLToPath} from 'url';
const __dirname = dirname(fileURLToPath(import.meta.url));
const templateRoot = join(__dirname, 'templates');
const APP_TYPES = [
{title: 'Todo app', value: 'todos'},
{title: 'Chat app', value: 'chat'},
{title: 'Drawing app', value: 'drawing'},
{title: 'Charting app', value: 'charting'},
{title: 'Tic-tac-toe game', value: 'game'},
] as const;
const LANGUAGES = [
{title: 'TypeScript', value: 'typescript'},
{title: 'JavaScript', value: 'javascript'},
] as const;
const FRAMEWORKS = [
{title: 'Vanilla', value: 'vanilla'},
{title: 'React', value: 'react'},
{title: 'Solid', value: 'solid'},
{title: 'Svelte', value: 'svelte'},
] as const;
const SYNC_TYPES = [
{title: 'None', value: 'none'},
{title: 'Via remote demo server (stateless)', value: 'remote'},
{title: 'Via local node server (stateless)', value: 'node'},
{
title: 'Via local DurableObjects server (stateful)',
value: 'durable-objects',
},
] as const;
const PERSISTENCE_TYPES = [
{title: 'None', value: 'none'},
{title: 'Local Storage', value: 'local-storage'},
{title: 'SQLite', value: 'sqlite'},
{title: 'PGlite', value: 'pglite'},
] as const;
const values = <Value extends string>(
choices: ReadonlyArray<{value: Value}>,
): Value[] => choices.map(({value}) => value);
const optionCatalog = {
command: 'npm create tinybase@latest --',
nonInteractiveFlag: '--non-interactive',
options: {
projectName: {type: 'string', required: true},
appType: {values: values(APP_TYPES), required: true},
language: {values: values(LANGUAGES), required: true},
framework: {
values: values(FRAMEWORKS),
requiredUnless: {appType: 'charting'},
},
tinyWidgets: {
values: [true, false],
appliesWhenAny: [{framework: 'react'}, {appType: 'charting'}],
},
schemas: {values: [true, false], appliesWhen: {language: 'typescript'}},
syncType: {values: values(SYNC_TYPES), required: true},
persistenceType: {values: values(PERSISTENCE_TYPES), required: true},
prettier: {values: [true, false], required: true},
eslint: {values: [true, false], required: true},
installAndRun: {
values: [true, false],
recommendedForAgents: false,
},
},
};
const printHelp = () => {
console.log(`create-tinybase
Interactively scaffold a local-first TinyBase application:
npm create tinybase@latest
Run non-interactively by providing every applicable option:
npm create tinybase@latest -- --non-interactive \\
--projectName my-app --appType todos --language typescript \\
--framework react --tinyWidgets false --schemas true \\
--syncType none --persistenceType local-storage \\
--prettier true --eslint true --installAndRun false
Agent and automation commands:
--list-options Print the current option catalog as JSON
--help Show this help
Use --installAndRun false for unattended generation.`);
};
const args = process.argv.slice(2);
if (args.includes('--help') || args.includes('-h')) {
printHelp();
process.exit(0);
}
if (args.includes('--list-options')) {
console.log(JSON.stringify(optionCatalog, null, 2));
process.exit(0);
}
const registerSharedPartials = () => {
const processTemplate = TemplateEngine.prototype.processTemplate;
const partials = new Map<string, string>();
TemplateEngine.prototype.processTemplate = async function (
templatePath: string,
) {
const {readFile} = await import('fs/promises');
const handlebars = (
this as unknown as {
handlebars: {registerPartial: (name: string, partial: string) => void};
}
).handlebars;
for (const partialName of ['title.hbs', 'info.hbs']) {
if (!partials.has(partialName)) {
partials.set(
partialName,
await readFile(
join(templateRoot, 'client/src/shared', partialName),
'utf-8',
),
);
}
handlebars.registerPartial(partialName, partials.get(partialName) ?? '');
}
return processTemplate.call(this, templatePath);
};
};
registerSharedPartials();
const config = {
welcomeMessage: '🎉 Welcome to TinyBase!\n',
questions: [
{
type: 'text' as const,
name: 'projectName',
message: 'Project name:',
initial: 'my-tinybase-app',
validate: (value: string) => {
if (value.length === 0) {
return 'Project name is required';
}
const targetPath = join(process.cwd(), value);
if (existsSync(targetPath)) {
return `Directory "${
value
}" already exists. Please choose a different name.`;
}
return true;
},
},
{
type: 'select' as const,
name: 'appType',
message: 'App type:',
choices: [...APP_TYPES],
initial: 0,
},
{
type: 'select' as const,
name: 'language',
message: 'Language:',
choices: [...LANGUAGES],
initial: 0,
},
{
type: (prev: unknown, answers: Record<string, unknown>) =>
answers.appType === 'charting' ? null : ('select' as const),
name: 'framework',
message: 'Framework:',
choices: [...FRAMEWORKS],
initial: 0,
},
{
type: (prev: unknown, answers: Record<string, unknown>) =>
answers.framework === 'react' || answers.appType === 'charting'
? ('confirm' as const)
: null,
name: 'tinyWidgets',
message: 'Use TinyWidgets components?',
initial: false,
},
{
type: (prev: unknown, answers: Record<string, unknown>) =>
answers.language === 'typescript' ? ('confirm' as const) : null,
name: 'schemas',
message: 'Include store schemas?',
initial: false,
},
{
type: 'select' as const,
name: 'syncType',
message: 'Synchronization:',
choices: [...SYNC_TYPES],
initial: 1,
},
{
type: 'select' as const,
name: 'persistenceType',
message: 'Persistence:',
choices: [...PERSISTENCE_TYPES],
initial: 1,
},
{
type: 'confirm' as const,
name: 'prettier',
message: 'Include Prettier?',
initial: true,
},
{
type: 'confirm' as const,
name: 'eslint',
message: 'Include ESLint?',
initial: true,
},
{
type: (prev: unknown, answers: Record<string, unknown>) =>
answers.syncType !== 'node' && answers.syncType !== 'durable-objects'
? ('confirm' as const)
: null,
name: 'installAndRun',
message: 'Install dependencies and start dev server?',
initial: true,
},
],
createContext: (answers: Record<string, unknown>) => {
const {
projectName,
language,
framework,
appType,
prettier,
eslint,
tinyWidgets,
schemas,
syncType,
persistenceType,
installAndRun,
} = answers;
const typescript = language === 'typescript';
const javascript = !typescript;
const resolvedFramework = appType === 'charting' ? 'react' : framework;
const react = resolvedFramework === 'react';
const solid = resolvedFramework === 'solid';
const vanilla = resolvedFramework === 'vanilla';
const svelte = resolvedFramework === 'svelte';
const useTinyWidgets =
react && (tinyWidgets === true || tinyWidgets === 'true');
const scriptExt = typescript ? 'ts' : 'js';
const componentExt = svelte
? 'svelte'
: typescript
? react || solid
? 'tsx'
: 'ts'
: react || solid
? 'jsx'
: 'js';
const entryExt = svelte ? scriptExt : componentExt;
const normalizedSyncType = syncType || 'remote';
const sync = normalizedSyncType !== 'none';
const server =
normalizedSyncType === 'node' || normalizedSyncType === 'durable-objects';
const serverType =
normalizedSyncType === 'durable-objects' ? 'durable-objects' : 'node';
const isDurableObject = normalizedSyncType === 'durable-objects';
const normalizedPersistenceType = persistenceType || 'local-storage';
const persist = normalizedPersistenceType !== 'none';
const persistLocalStorage = normalizedPersistenceType === 'local-storage';
const persistSqlite = normalizedPersistenceType === 'sqlite';
const persistPglite = normalizedPersistenceType === 'pglite';
const needsViteConfig =
react ||
solid ||
svelte ||
persistSqlite ||
persistPglite ||
useTinyWidgets;
const appSurface =
appType === 'chat'
? 'chat interface'
: appType === 'drawing'
? 'drawing canvas'
: appType === 'charting'
? 'charting app'
: appType === 'game'
? 'game'
: 'todo list';
const frameworkName = react
? 'React'
: solid
? 'Solid'
: vanilla
? 'Vanilla JS'
: 'Svelte';
const clientFrameworkDescription = react
? 'React-based'
: solid
? 'Solid-based'
: vanilla
? 'vanilla JavaScript'
: 'Svelte-based';
const entryFileDescription = react
? 'Entry point that bootstraps and renders the React app'
: solid
? 'Entry point that bootstraps and renders the Solid app'
: svelte
? 'Entry point that bootstraps and mounts the Svelte app'
: 'Entry point that bootstraps the app';
const appFileStem = vanilla ? 'app' : 'App';
const appFileExt = vanilla ? scriptExt : componentExt;
const appFileDescription = react
? `Main React component that renders the ${appSurface}`
: solid
? `Main Solid component that renders the ${appSurface}`
: vanilla
? 'Main application logic'
: `Main Svelte component that renders the ${appSurface}`;
const primaryStoreStem =
react || solid
? appType === 'chat'
? 'ChatStore'
: appType === 'drawing'
? 'CanvasStore'
: 'Store'
: appType === 'chat'
? 'chatStore'
: appType === 'drawing'
? 'canvasStore'
: 'store';
const primaryStoreExt = react || solid ? componentExt : scriptExt;
const primaryStoreDescription = `TinyBase ${
appType === 'chat'
? 'chat messages'
: appType === 'drawing'
? 'drawing canvas'
: appType === 'charting'
? 'charting app'
: 'main'
} store configuration`;
const needsSettingsStore = appType === 'chat' || appType === 'drawing';
const settingsStoreStem =
react || solid ? 'SettingsStore' : 'settingsStore';
const settingsStoreExt = react || solid ? componentExt : scriptExt;
const configExt = react || solid ? componentExt : scriptExt;
const techIcons = [
typescript
? {src: '/ts.svg', title: 'Written in TypeScript'}
: {src: '/js.svg', title: 'Written in JavaScript'},
...(react ? [{src: '/react.svg', title: 'Built with React'}] : []),
...(solid ? [{src: '/solid.svg', title: 'Built with Solid'}] : []),
...(useTinyWidgets
? [{src: '/tinywidgets.svg', title: 'Uses TinyWidgets components'}]
: []),
...(svelte ? [{src: '/svelte.svg', title: 'Built with Svelte'}] : []),
...(persistSqlite
? [{src: '/sqlite.svg', title: 'Persists data to SQLite'}]
: persistPglite
? [{src: '/pglite.svg', title: 'Persists data to PGlite'}]
: []),
...(sync
? [{src: '/sync.svg', title: 'Data synchronization enabled'}]
: []),
];
return {
projectName,
language,
framework: resolvedFramework,
appType,
prettier,
eslint,
tinyWidgets: useTinyWidgets,
schemas: typescript && (schemas === true || schemas === 'true'),
syncType: normalizedSyncType,
sync,
server,
serverType,
isDurableObject,
persistenceType: normalizedPersistenceType,
persist,
persistLocalStorage,
persistSqlite,
persistPglite,
needsViteConfig,
appSurface,
frameworkName,
clientFrameworkDescription,
entryFileDescription,
appFileStem,
appFileExt,
appFileDescription,
primaryStoreStem,
primaryStoreExt,
primaryStoreDescription,
needsSettingsStore,
settingsStoreStem,
settingsStoreExt,
configExt,
techIcons,
installAndRun: installAndRun === true || installAndRun === 'true',
typescript,
javascript,
react,
solid,
vanilla,
svelte,
scriptExt,
componentExt,
entryExt,
ext: entryExt,
};
},
createDirectories: async (
targetDir: string,
context: Record<string, unknown>,
) => {
const {mkdir} = await import('fs/promises');
const {join} = await import('path');
const server = context.server as boolean;
await mkdir(join(targetDir, 'client/src'), {recursive: true});
await mkdir(join(targetDir, 'client/public'), {recursive: true});
if (server) {
await mkdir(join(targetDir, 'server'), {recursive: true});
}
},
getFiles: () => [
{
template: 'README.md.hbs',
output: 'README.md',
prettier: true,
},
{
template: 'AGENTS.md.hbs',
output: 'AGENTS.md',
prettier: true,
},
],
processIncludedFile: (file: FileConfig, context: TemplateContext) => {
const {javascript} = context;
const prettier =
file.prettier ??
/\.(js|jsx|ts|tsx|css|json|html|md|svelte)$/.test(file.output);
const transpile =
file.transpile ??
(/\.(ts|tsx)\.hbs$/.test(file.template) && javascript === true);
return {
...file,
prettier,
transpile,
};
},
templateRoot,
installCommand: '{pm} install',
devCommand: '{pm} run dev',
workingDirectory: 'client',
onSuccess: (projectName: string, context: Record<string, unknown>) => {
const syncType = context.syncType as string;
const server = syncType === 'node' || syncType === 'durable-objects';
const pm = detectPackageManager();
console.log(`Next steps:`);
console.log();
if (server) {
console.log('To run the server:');
console.log(` cd ${projectName}/server`);
console.log(` ${pm} install`);
console.log(` ${pm} run dev`);
console.log();
}
console.log('To run the client:');
console.log(` cd ${projectName}/client`);
console.log(` ${pm} install`);
console.log(` ${pm} run dev`);
},
};
createCLI(config).catch((error: unknown) => {
console.error(error);
process.exit(1);
});