scaffold.ts
13.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
import fs from 'node:fs';
import path from 'node:path';
import { writeFileSyncSafe } from '../../utils/file';
import type { ProjectProfile } from '../../types/project-profile';
import { buildShadcnUiFiles, shadcnDeps, isShadcnLibrary } from './shadcn-ui';
/**
* Framework-aware scaffold.
*
* The original INITIAL node hard-coded a React + Vite + TS + Tailwind scaffold.
* To support other frameworks (Vue 3, …) without touching the React template,
* scaffolding is now a small strategy layer: each framework supplies its own
* file map. Adding a new framework = append one `ScaffoldStrategy` here
* (Open-Closed Principle) — the INITIAL node and everything else stay untouched.
*/
export interface ScaffoldStrategy {
/** Lowercase framework id used for matching (mirrors the CODE strategy ids). */
id: string;
/** Files that MUST exist after scaffolding (validated by the INITIAL node). */
essentialFiles: string[];
/** Render the full file map for this framework. */
build(appName: string, profile: ProjectProfile | null): Record<string, string>;
}
// ============================================================
// React scaffold (default — behavior unchanged)
// ============================================================
function renderPackageJson(appName: string, extraDeps: Record<string, string> = {}): string {
return JSON.stringify(
{
name: appName || 'my-app',
private: true,
version: '0.0.0',
type: 'module',
scripts: {
dev: 'vite',
build: 'tsc && vite build',
preview: 'vite preview',
},
dependencies: {
react: '^18.3.1',
'react-dom': '^18.3.1',
...extraDeps,
},
devDependencies: {
'@tailwindcss/vite': '^4.1.4',
'@types/node': '^20.17.30',
'@types/react': '^18.3.20',
'@types/react-dom': '^18.3.6',
'@vitejs/plugin-react': '^4.4.1',
less: '^4.3.0',
tailwindcss: '^4.1.4',
typescript: '~5.8.3',
vite: '^6.3.5',
},
},
null,
2
);
}
function renderViteConfig(): string {
return `import path from "node:path";
import { fileURLToPath } from "node:url";
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import tailwindcss from "@tailwindcss/vite";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export default defineConfig({
plugins: [react(), tailwindcss()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
});
`;
}
function renderTsConfig(): string {
return `{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"skipLibCheck": true,
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
},
"include": ["src"]
}
`;
}
function renderIndexHtml(title: string): string {
return `<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>${title}</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
`;
}
function renderMainTsx(): string {
return `import React from "react";
import ReactDOM from "react-dom/client";
import App from "@/App";
import "@/globals.css";
import "@/App.less";
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
`;
}
function renderAppTsx(): string {
return `import ReviewDetailPage from '@/components';
export default function App() {
return <div><ReviewDetailPage /></div>;
}
`;
}
function renderGlobalsCss(): string {
return `@import "tailwindcss";
`;
}
function renderAppLess(): string {
return ``;
}
function renderViteEnvDts(): string {
return `/// <reference types="vite/client" />
`;
}
function renderGitignore(): string {
return `# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
# Dependencies
node_modules/
# Build output
dist/
build/
dist-ssr/
*.local
# Environment files
.env
.env.*
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea/
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
# Cache
.cache/
.eslintcache
.stylelintcache
*.tsbuildinfo
# Lock files
package-lock.json
yarn.lock
pnpm-lock.yaml
`;
}
const reactScaffold: ScaffoldStrategy = {
id: 'react',
essentialFiles: [
'package.json',
'src',
'vite.config.ts',
'tsconfig.json',
'index.html',
'src/main.tsx',
'src/App.tsx',
],
build(appName, profile) {
const isShadcn = isShadcnLibrary(profile?.componentLibrary);
return {
'package.json': renderPackageJson(appName, isShadcn ? shadcnDeps : {}),
'vite.config.ts': renderViteConfig(),
'tsconfig.json': renderTsConfig(),
'index.html': renderIndexHtml(appName || 'my-app'),
'src/main.tsx': renderMainTsx(),
'src/App.tsx': renderAppTsx(),
'src/globals.css': renderGlobalsCss(),
'src/App.less': renderAppLess(),
'src/vite-env.d.ts': renderViteEnvDts(),
'.gitignore': renderGitignore(),
...(isShadcn ? buildShadcnUiFiles() : {}),
};
},
};
// ============================================================
// Vue 3 scaffold (new)
// ============================================================
type VueLibrary = 'element-plus' | 'ant-design-vue' | null;
function detectVueLibrary(profile: ProjectProfile | null): VueLibrary {
const lib = (profile?.componentLibrary || '').toLowerCase();
if (lib.includes('ant-design-vue') || lib.includes('ant design vue')) return 'ant-design-vue';
if (lib.includes('element-plus') || lib.includes('element plus')) return 'element-plus';
return null;
}
function renderVuePackageJson(appName: string, lib: VueLibrary): string {
const dependencies: Record<string, string> = {
vue: '^3.5.13',
};
if (lib === 'element-plus') {
dependencies['element-plus'] = '^2.9.1';
dependencies['@element-plus/icons-vue'] = '^2.3.1';
} else if (lib === 'ant-design-vue') {
dependencies['ant-design-vue'] = '^4.2.6';
}
return JSON.stringify(
{
name: appName || 'my-app',
private: true,
version: '0.0.0',
type: 'module',
scripts: {
dev: 'vite',
build: 'vue-tsc -b && vite build',
preview: 'vite preview',
},
dependencies,
devDependencies: {
'@vitejs/plugin-vue': '^5.2.1',
'@tailwindcss/vite': '^4.1.4',
'@types/node': '^20.17.30',
typescript: '~5.8.3',
'vue-tsc': '^2.2.0',
vite: '^6.3.5',
less: '^4.3.0',
tailwindcss: '^4.1.4',
},
},
null,
2
);
}
function renderVueViteConfig(): string {
return `import path from "node:path";
import { fileURLToPath } from "node:url";
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import tailwindcss from "@tailwindcss/vite";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export default defineConfig({
plugins: [vue(), tailwindcss()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
// Include ".vue" so bare directory imports like "@/components" resolve to
// src/components/index.vue. Vite's defaults do NOT contain ".vue" for
// directory-index resolution, which is why "@/components" failed to resolve.
extensions: ['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.vue', '.json'],
},
});
`;
}
/**
* Barrel file so that `import X from '@/components'` always resolves.
* `.ts` is in Vite's default extensions, so the directory index resolves to
* this file (not relying on `.vue` directory-index resolution). It re-exports
* the root page component written by the CODE node at src/components/index.vue.
*/
function renderVueComponentsIndex(): string {
return `export { default } from './index.vue';\n`;
}
function renderVueTsConfig(): string {
return `{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"strict": true,
"skipLibCheck": true,
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
},
"types": ["vite/client"]
},
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.vue"]
}
`;
}
function renderVueIndexHtml(title: string): string {
return `<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>${title}</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
`;
}
function renderVueMainTs(lib: VueLibrary): string {
const libImport: string =
lib === 'element-plus'
? `import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css';
import * as ElementPlusIconsVue from '@element-plus/icons-vue';`
: lib === 'ant-design-vue'
? `import Antd from 'ant-design-vue';
import 'ant-design-vue/dist/reset.css';`
: '';
const libUse: string =
lib === 'element-plus'
? `app.use(ElementPlus);
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
app.component(key, component as any);
}`
: lib === 'ant-design-vue'
? `app.use(Antd);`
: '';
return `import { createApp } from 'vue';
${libImport}
import App from '@/App.vue';
import '@/globals.css';
const app = createApp(App);
${libUse}
app.mount('#app');
`;
}
function renderVueAppVue(): string {
return `<template>
<RootComponent />
</template>
<script setup lang="ts">
import RootComponent from '@/components';
</script>
`;
}
function renderVueShims(): string {
return `declare module '*.vue' {
import type { DefineComponent } from 'vue';
const component: DefineComponent<Record<string, unknown>, Record<string, unknown>, unknown>;
export default component;
}
`;
}
function renderVueGlobalsCss(): string {
return `/* global styles */
@import "tailwindcss";
@source "./src/**/*.{vue,js,ts,jsx,tsx}";
`;
}
const vue3Scaffold: ScaffoldStrategy = {
id: 'vue',
essentialFiles: [
'package.json',
'src',
'vite.config.ts',
'tsconfig.json',
'index.html',
'src/main.ts',
'src/App.vue',
],
build(appName, profile) {
const lib = detectVueLibrary(profile);
return {
'package.json': renderVuePackageJson(appName, lib),
'vite.config.ts': renderVueViteConfig(),
'tsconfig.json': renderVueTsConfig(),
'index.html': renderVueIndexHtml(appName || 'my-app'),
'src/main.ts': renderVueMainTs(lib),
'src/App.vue': renderVueAppVue(),
'src/components/index.ts': renderVueComponentsIndex(),
'src/shims-vue.d.ts': renderVueShims(),
'src/globals.css': renderVueGlobalsCss(),
'src/vite-env.d.ts': renderViteEnvDts(),
'.gitignore': renderGitignore(),
};
},
};
// ============================================================
// Registry
// ============================================================
const SCAFFOLDS: ScaffoldStrategy[] = [reactScaffold, vue3Scaffold];
/**
* Resolve a scaffold strategy from a framework string. Falls back to React
* (the legacy default) when nothing matches.
*/
export function getScaffoldForFramework(framework?: string): ScaffoldStrategy {
const fw = (framework || '').toLowerCase();
return SCAFFOLDS.find((s) => fw.includes(s.id)) ?? reactScaffold;
}
/**
* Write the framework-appropriate scaffold into `appPath`.
* @param appPath absolute path to the generated app folder
* @param appName project name (used in package.json and page title)
* @param profile the active project profile (drives framework + UI library)
*/
export function writeScaffold(appPath: string, appName: string, profile: ProjectProfile | null = null): void {
const strategy = getScaffoldForFramework(profile?.framework);
const files: Record<string, string> = strategy.build(appName, profile);
for (const [rel, content] of Object.entries(files)) {
const full = path.join(appPath, rel);
fs.mkdirSync(path.dirname(full), { recursive: true });
// 用安全写入:vite 监视器 / IDE / 杀软可能短暂停有该文件句柄,重试可吸收。
writeFileSyncSafe(full, content, 'utf8');
}
// Ensure the components directory exists (App imports from '@/components').
fs.mkdirSync(path.join(appPath, 'src', 'components'), { recursive: true });
}
/** Essential files the INITIAL node must validate for the active framework. */
export function getScaffoldEssentialFiles(profile: ProjectProfile | null): string[] {
return getScaffoldForFramework(profile?.framework).essentialFiles;
}