create.mjs
19.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
/**
* 项目生成器:从当前基座复制出一个全新的、干净的项目基座。
* `venus create <name> [--dir <parent> | --out <abs-path>]` -> <parent>/<name>/
*
* 生成结果:
* - 完整的 .kernel/(内核,带新生成的 manifest,含根配置哈希)
* - cli/(工具链)
* - 根配置(package.json 包名换成 <name>;pnpm-workspace/turbo/tsconfig 原样)
* - apps/example:一个最小占位子应用(派生应用可删可改)
* - packages/common:一个业务公共模块示例(派生应用可改可扩)
* - packages/brand:登录界面品牌配置(改这里即可定制登录页,无需碰内核)
* - packages/profile:角色码/资源码/权限点示例(按自己后端替换)
* - packages/protocols:协议适配层(按自己的登录/权限/菜单规则接管内核流程)
* - githooks/、docs/、README.md:提交门禁与文档(随基座分发)
* 不含:node_modules、dist、.git、备份、生成物。
*/
import fs from 'node:fs';
import path from 'node:path';
import { TEMPLATE_ROOT, writeManifestAt } from './kernel.mjs';
const KERNEL_DIR = path.join(TEMPLATE_ROOT, '.kernel');
const SKIP_DIRS = new Set([
'node_modules', '.git', 'dist', '.turbo', '.tmp', 'coverage',
'miniprogram_dist', '.kernel-backups',
]);
function copyDir(src, dst, transform) {
fs.mkdirSync(dst, { recursive: true });
for (const ent of fs.readdirSync(src, { withFileTypes: true })) {
if (ent.isDirectory()) {
if (SKIP_DIRS.has(ent.name)) continue;
copyDir(path.join(src, ent.name), path.join(dst, ent.name), transform);
} else {
const s = path.join(src, ent.name);
const d = path.join(dst, ent.name);
if (transform) {
const out = transform(d, fs.readFileSync(s, 'utf8'));
fs.writeFileSync(d, out ?? fs.readFileSync(s));
} else {
fs.copyFileSync(s, d);
}
}
}
}
/** 生成一个最小占位子应用(如果源基座没有 example 时用) */
function ensureExample(targetApps) {
const exampleDir = path.join(targetApps, 'example');
if (fs.existsSync(exampleDir)) return;
fs.mkdirSync(path.join(exampleDir, 'src'), { recursive: true });
fs.writeFileSync(
path.join(exampleDir, 'package.json'),
JSON.stringify(
{
name: '@app/example',
version: '0.0.0',
private: true,
type: 'module',
scripts: {
dev: 'vite',
build: 'vite build',
lint: 'eslint . --max-warnings=0',
typecheck: 'tsc --noEmit',
},
venus: { route: 'example', entry: 'http://localhost:5174/' },
},
null,
2,
) + '\n',
);
}
/** 业务公共模块骨架 —— 派生应用自己的公共代码放这里,内核升级不触碰。 */
function ensureBusinessPackages(target) {
const dir = path.join(target, 'packages', 'common');
fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
const pkgName = '@app/common';
fs.writeFileSync(
path.join(dir, 'package.json'),
JSON.stringify(
{
name: pkgName,
version: '0.0.0',
private: true,
type: 'module',
main: './src/index.ts',
types: './src/index.ts',
exports: { '.': './src/index.ts' },
scripts: { typecheck: 'tsc --noEmit' },
},
null,
2,
) + '\n',
);
fs.writeFileSync(
path.join(dir, 'tsconfig.json'),
JSON.stringify(
{
extends: '../../.kernel/packages/typescript-config/react-lib.json',
compilerOptions: { noEmit: true, rootDir: 'src' },
include: ['src/**/*'],
},
null,
2,
) + '\n',
);
if (!fs.existsSync(path.join(dir, 'src', 'index.ts'))) {
fs.writeFileSync(
path.join(dir, 'src', 'index.ts'),
'/**\n * 业务公共模块示例。\n * 这里放派生应用自己的通用能力(工具、常量、领域类型),内核升级不会覆盖。\n * 子应用通过 `@app/common` 引用(vite alias 已内置 @app/* -> packages/*/src)。\n */\nexport const APP_NAME = "{{APP_NAME}}";\n\nexport function hello(name = "world"): string {\n return `Hello, ${name} from ${APP_NAME}`;\n}\n'.replace('{{APP_NAME}}', path.basename(target)),
);
}
fs.writeFileSync(
path.join(target, 'packages', 'README.md'),
'# 业务公共模块(packages/)\n\n' +
'这里放**派生应用自己的**公共代码,与内核(`.kernel/`)物理分离。\n\n' +
'- 新增包:`packages/<name>/`,包名用 `@app/<name>`\n' +
'- 子应用引用:`import { xxx } from "@app/<name>"`(alias 已配好)\n' +
'- 内核升级只覆盖 `.kernel/`,本目录不会被触碰\n\n' +
'默认已带一个 `@app/common` 示例包,可直接改或删。\n',
);
}
/**
* 业务品牌包 —— 登录界面/侧边栏的「门面文案」定制入口。
*
* 派生应用改这个文件的 brand 配置即可改标题、Logo 字标/配色、标语、价值主张、
* 版权与欢迎语;slots.tsx 可进一步替换登录页的区块组件(左侧展示区、表单附加区、
* 页脚)。登录逻辑在内核,与此完全隔离。内核 alias 检测到本包存在即读它,
* 不存在则回退内核默认,因此老项目升级内核也不会报错。
*
* packages/ 属于业务区,内核升级不触碰本文件。
*/
function ensureBrandPackage(target) {
const dir = path.join(target, 'packages', 'brand');
fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
const pkgName = '@app/brand';
fs.writeFileSync(
path.join(dir, 'package.json'),
JSON.stringify(
{
name: pkgName,
version: '0.0.0',
private: true,
type: 'module',
main: './src/index.ts',
types: './src/index.ts',
exports: { '.': './src/index.ts' },
scripts: { typecheck: 'tsc --noEmit' },
dependencies: { '@venus/contracts': 'workspace:*' },
},
null,
2,
) + '\n',
);
fs.writeFileSync(
path.join(dir, 'tsconfig.json'),
JSON.stringify(
{
extends: '../../.kernel/packages/typescript-config/react-lib.json',
compilerOptions: {
noEmit: true,
rootDir: 'src',
paths: {
'@venus/contracts': ['../../.kernel/packages/contracts/src/index.ts'],
},
},
include: ['src/**/*'],
},
null,
2,
) + '\n',
);
if (!fs.existsSync(path.join(dir, 'src', 'index.ts'))) {
fs.writeFileSync(
path.join(dir, 'src', 'index.ts'),
[
'/**',
' * 登录界面品牌配置(业务区 · 内核升级不触碰)。',
' *',
' * 改这里即可定制:应用名、Logo 字标与渐变色、登录页主标语、价值主张、',
' * 欢迎语与页脚版权。未覆盖的字段沿用内核默认值。',
' *',
' * 登录逻辑(签名、令牌、权限、跳转)在内核,与此无关,改本文件不影响登录功能。',
' */',
"import { defineBrand } from '@venus/contracts';",
'',
'export const brand = defineBrand({',
' // appName: "我的系统",',
' // appShort: "MY", // Logo 方块里的字标(2~5 个英文字符)',
' // appSubtitle: "运营管理平台",',
' // heroLines: ["让业务", "更简单"],',
' // welcomeTitle: "欢迎登录",',
' // welcomeDesc: "请输入账号密码",',
' // copyrightName: "我的系统",',
' // copyrightSuffix: "运营管理平台",',
' // logoFrom: "#2B5CE6",',
' // logoTo: "#5B8DEF",',
' // features: [',
' // { title: "高效", desc: "一站式业务处理" },',
' // { title: "安全", desc: "权限边界清晰可控" },',
' // { title: "可扩展", desc: "能力随内核持续升级" },',
' // ],',
'});',
'',
].join('\n'),
);
}
if (!fs.existsSync(path.join(dir, 'src', 'slots.tsx'))) {
fs.writeFileSync(
path.join(dir, 'src', 'slots.tsx'),
[
'/**',
' * 登录界面交互插槽(业务区 · 内核升级不触碰)。',
' *',
' * 这里替换的是「区块组件」,不是登录逻辑。签名、令牌、权限注入与跳转始终',
' * 由内核 LoginForm 持有,插槽不会接管它们。',
' *',
' * 可用插槽:',
' * LoginAside 整体替换登录页左侧品牌展示区',
' * LoginFormExtra 追加在登录按钮之后(注册入口、第三方登录、找回密码等)',
' * LoginFooter 整体替换登录页底部版权区',
' *',
' * 用法示例:',
" * import type { BrandSlots } from '@venus/contracts';",
' * export const slots: BrandSlots = {',
' * LoginFormExtra: () => <a href="/register">注册账号</a>,',
' * };',
' *',
' * 留空即沿用内核默认实现。',
' */',
"import type { BrandSlots } from '@venus/contracts';",
'',
'export const slots: BrandSlots = {};',
'',
].join('\n'),
);
}
fs.writeFileSync(
path.join(target, 'packages', 'README.md'),
'# 业务公共模块(packages/)\n\n' +
'这里放**派生应用自己的**公共代码,与内核(`.kernel/`)物理分离。\n\n' +
'- 新增包:`packages/<name>/`,包名用 `@app/<name>`\n' +
'- 子应用引用:`import { xxx } from "@app/<name>"`(alias 已配好)\n' +
'- 内核升级只覆盖 `.kernel/`,本目录不会被触碰\n\n' +
'默认带三个示例包:\n\n' +
'- `@app/common`:通用工具示例,可改可删\n' +
'- `@app/brand`:**登录界面定制**。`src/index.ts` 改文案,`src/slots.tsx` 替换区块组件,无需碰内核。详见 README「定制登录界面」。\n' +
'- `@app/profile`:**访问配置**。`src/index.ts` 里的角色码/资源码/权限点是示例,必须按自己后端替换。\n' +
'- `@app/protocols`:**协议适配**。`src/index.ts` 实现 auth/access/menu 协议即可按自己的规则接管登录/权限/菜单流程;留空则用内核默认。\n',
);
}
/**
* 业务访问配置包 —— 角色码/资源码/权限点的唯一业务真源。
*
* 内核里那套 SYS_ADMIN / store:* 只是"能跑起来"的示例,不属于框架能力。
* 新项目自带一份同结构副本,业务按自己后端改;host 与子应用都经 @/access-profile
* 读到它。内核升级只写 .kernel/,本包不会被覆盖。
*
* 示例数据直接从内核 defaultProfile 复制,避免两处维护漂移。
*/
function ensureProfilePackage(target) {
const dir = path.join(target, 'packages', 'profile');
fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
fs.writeFileSync(
path.join(dir, 'package.json'),
JSON.stringify(
{
name: '@app/profile',
version: '0.0.0',
private: true,
type: 'module',
main: './src/index.ts',
types: './src/index.ts',
exports: { '.': './src/index.ts' },
scripts: { typecheck: 'tsc --noEmit' },
},
null,
2,
) + '\n',
);
fs.writeFileSync(
path.join(dir, 'tsconfig.json'),
JSON.stringify(
{
extends: '../../.kernel/packages/typescript-config/react-lib.json',
compilerOptions: { noEmit: true, rootDir: 'src' },
include: ['src/**/*'],
},
null,
2,
) + '\n',
);
if (!fs.existsSync(path.join(dir, 'src', 'index.ts'))) {
const seed = path.join(KERNEL_DIR, 'packages/platform-core/src/access/defaultProfile.ts');
const seedText = fs.existsSync(seed) ? fs.readFileSync(seed, 'utf8') : '';
const marker = seedText.indexOf('export type PermissionState');
const body = marker >= 0 ? seedText.slice(marker) : seedText;
fs.writeFileSync(
path.join(dir, 'src', 'index.ts'),
[
'/**',
' * 业务访问配置(业务区 · 内核升级不触碰)。',
' *',
' * 这里的角色码、资源码、权限点必须按自己后端替换——它们是示例,不是框架能力。',
' * 内核 @/access-profile 通道会优先读本文件:主壳(platform-core)与子应用',
' * (platform-sdk compat)共用同一份配置,改一次两边同时生效。',
' *',
' * 三态权限模型(ck.on / half / na)和判定逻辑在内核,不在这里。',
' */',
'',
body,
].join('\n'),
);
}
}
/**
* 协议适配包 —— 业务按自己的规则接管内核流程的唯一入口。
*
* 内核预设了登录 / 权限 / 菜单规则。派生系统若已有既定规则(自己的登录接口、
* 自己的权限码体系、自己的菜单结构),在这里实现对应协议方法即可:
* 内核走 @/protocols 读到本文件,只覆盖实现了的方法,其余沿用内核默认。
* 不实现任何方法 = 完全用内核默认,行为与升级前一模一样。
*
* 老项目升级内核后没有这个包时,alias 自动回退内核默认协议,零改动。
*/
function ensureProtocolsPackage(target) {
const dir = path.join(target, 'packages', 'protocols');
fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
fs.writeFileSync(
path.join(dir, 'package.json'),
JSON.stringify(
{
name: '@app/protocols',
version: '0.0.0',
private: true,
type: 'module',
main: './src/index.ts',
types: './src/index.ts',
exports: { '.': './src/index.ts' },
scripts: { typecheck: 'tsc --noEmit' },
dependencies: { '@venus/contracts': 'workspace:*' },
},
null,
2,
) + '\n',
);
fs.writeFileSync(
path.join(dir, 'tsconfig.json'),
JSON.stringify(
{
extends: '../../.kernel/packages/typescript-config/react-lib.json',
compilerOptions: {
noEmit: true,
rootDir: 'src',
paths: {
'@venus/contracts': ['../../.kernel/packages/contracts/src/index.ts'],
},
},
include: ['src/**/*'],
},
null,
2,
) + '\n',
);
if (!fs.existsSync(path.join(dir, 'src', 'index.ts'))) {
fs.writeFileSync(
path.join(dir, 'src', 'index.ts'),
[
'/**',
' * 协议适配层(业务区 · 内核升级不触碰)。',
' *',
' * 你的系统如果和内核预设规则不一致,在这里实现对应协议方法即可让内核按你的规则跑。',
' * 只实现要改的方法,其余自动沿用内核默认;全部留空 = 完全用内核默认。',
' *',
' * 三组协议:',
' * auth —— 登录主流程(整体接管 run,或逐阶段换 request/normalize/persist/apply/redirect)',
' * access —— 权限规则(normalizePermissions / resolveRole / can / canPoint / basePoints)',
' * menu —— 菜单规则(load / buildGroups / fixedGroups / fallbackGroups / isVisible)',
' *',
' * 完整契约见 @venus/contracts 的 AuthProtocol / AccessProtocol / MenuProtocol。',
' * 详细示例见 docs/ARCHITECTURE.md「协议适配」一节。',
' */',
"import type { VenusProtocols } from '@venus/contracts';",
'',
'export const protocols: VenusProtocols = {',
' // auth: {',
' // // 例:换成自己的登录接口,其余阶段(落库/权限注入/跳转)仍走内核',
' // async request(credentials) {',
' // const res = await fetch("/api/my-login", {',
' // method: "POST",',
' // body: JSON.stringify(credentials),',
' // }).then((r) => r.json());',
' // return res;',
' // },',
' // normalize(raw) {',
' // const r = raw as { accessToken: string; user: { name: string; roles: string[] } };',
' // return {',
' // token: r.accessToken, tokenType: "Bearer", expireAt: "",',
' // userId: 0, account: "", name: r.user.name, orgId: 0, dataScope: 1,',
' // roleCodes: r.user.roles, permCodes: [],',
' // };',
' // },',
' // },',
' // access: {',
' // // 例:自己的权限码体系(点号分隔而非冒号)',
' // canPoint(point, ctx) { return ctx.points.has(point.toLowerCase()); },',
' // },',
' // menu: {',
' // // 例:自己的菜单树结构',
' // buildGroups(tree, owned, deps) { /* 返回 VenusMenuGroup[] */ return []; },',
' // },',
'};',
'',
].join('\n'),
);
}
}
/**
* @param {string} name 项目名(小写 kebab)
* @param {string} parentDir 父目录
*/
export function createProject(name, parentDir) {
if (!/^[a-z0-9][a-z0-9-]*$/.test(name)) {
return { ok: false, message: `项目名不合法:${name}(只允许小写字母、数字、连字符,且以字母或数字开头)` };
}
const target = path.resolve(parentDir, name);
if (fs.existsSync(target)) {
return { ok: false, message: `目标目录已存在:${target}` };
}
try {
fs.mkdirSync(target, { recursive: true });
// 1. 复制内核(transform 不动内容,保持哈希一致)
copyDir(KERNEL_DIR, path.join(target, '.kernel'));
// 2. 复制 CLI 工具链
copyDir(path.join(TEMPLATE_ROOT, 'cli'), path.join(target, 'cli'));
// 2b. 复制提交门禁 hook 与文档(门禁必须随基座分发,否则派生项目无法拦截内核篡改)
for (const dir of ['githooks', 'docs']) {
const s = path.join(TEMPLATE_ROOT, dir);
if (fs.existsSync(s)) copyDir(s, path.join(target, dir));
}
// 3. 复制根配置,替换包名
const rootFiles = [
'package.json', 'pnpm-workspace.yaml', 'tsconfig.base.json', 'turbo.json',
'eslint.config.js', '.env.example', '.editorconfig', '.prettierrc.json',
'.prettierignore', '.npmrc', '.gitignore', '.gitattributes', 'README.md',
];
for (const f of rootFiles) {
const s = path.join(TEMPLATE_ROOT, f);
if (!fs.existsSync(s)) continue;
const d = path.join(target, f);
let content = fs.readFileSync(s, 'utf8');
if (f === 'package.json') {
content = content.replace(/"name":\s*"@venus\/base"/, `"name": "${name}"`);
}
fs.writeFileSync(d, content);
}
// 4. 复制业务区(只保留 example 作为起点)
const appsDst = path.join(target, 'apps');
const ex = path.join(TEMPLATE_ROOT, 'apps', 'example');
if (fs.existsSync(ex)) copyDir(ex, path.join(appsDst, 'example'));
ensureExample(appsDst);
// 5. 业务公共模块骨架(packages/)
ensureBusinessPackages(target);
ensureBrandPackage(target);
ensureProfilePackage(target);
ensureProtocolsPackage(target);
// 6. 生成新项目的内核清单(在新目录就地生成,含根配置哈希)
writeManifestAt(path.join(target, '.kernel'), target);
return {
ok: true,
target,
message: `已生成项目基座 ${name} 于 ${target}\n` +
` 业务区:apps/example(子应用示例)、packages/common、packages/brand(登录定制)、packages/profile(访问配置)、packages/protocols(流程协议适配)\n` +
` 定制登录界面:改 packages/brand/src/index.ts(文案)与 slots.tsx(交互区块)\n` +
` 按自己的规则运行:改 packages/protocols/src/index.ts(登录/权限/菜单协议,留空即用内核默认)\n` +
` 下一步:cd ${name} && pnpm install && pnpm dev`,
};
} catch (err) {
try { fs.rmSync(target, { recursive: true, force: true }); } catch { /* ignore */ }
return { ok: false, message: `生成失败:${err.message}` };
}
}