@fudanda/create-arcbase 2.20261026.1-beta.1 → 2.20261107.1-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/.runtime/npm/index.json +18 -18
  2. package/.runtime/sdk.json +3 -3
  3. package/LICENSE +21 -21
  4. package/README.md +99 -91
  5. package/cli.mjs +42 -39
  6. package/package.json +10 -5
  7. package/src/assistant.mjs +76 -0
  8. package/src/delivery.mjs +20 -20
  9. package/src/enhance.mjs +103 -104
  10. package/src/evolve.mjs +66 -66
  11. package/src/fields.mjs +73 -73
  12. package/src/goa-contracts.mjs +331 -331
  13. package/src/goa.mjs +202 -202
  14. package/src/history.mjs +16 -16
  15. package/src/layout.mjs +1 -1
  16. package/src/module.mjs +439 -477
  17. package/src/packages.mjs +12 -4
  18. package/src/page-antd.mjs +98 -77
  19. package/src/page-webmcp.mjs +51 -0
  20. package/src/project.mjs +112 -105
  21. package/src/records.mjs +15 -15
  22. package/src/release-vite.mjs +1 -0
  23. package/src/release.mjs +455 -0
  24. package/src/templates.mjs +20 -20
  25. package/src/upgrade.mjs +415 -249
  26. package/templates/module/02-migrations.go.txt +10 -10
  27. package/templates/module/03-service.go.txt +52 -52
  28. package/templates/module/04-module.go.txt +12 -12
  29. package/templates/module/06-queries.ts.txt +15 -15
  30. package/templates/module/08-service_test.go.txt +9 -9
  31. package/templates/module/09-TransferPanel.tsx.txt +16 -0
  32. package/templates/module-runtime-test.go.txt +86 -86
  33. package/templates/module-transfer.go.txt +74 -74
  34. package/templates/project-v2/.agents/skills/arcbase/SKILL.md +32 -0
  35. package/templates/project-v2/.agents/skills/goa-service-designer/SKILL.md +31 -0
  36. package/templates/project-v2/AGENTS.md +38 -0
  37. package/templates/project-v2/DEVELOPMENT.md +115 -84
  38. package/templates/project-v2/README.md +76 -74
  39. package/templates/project-v2/RELEASE.md +88 -0
  40. package/templates/project-v2/TEAM-TRIAL.md +32 -32
  41. package/templates/project-v2/arcbase.release.json +23 -0
  42. package/templates/project-v2/cmd/server/main.go +62 -36
  43. package/templates/project-v2/cmd/server/modules.gen.go +6 -6
  44. package/templates/project-v2/eslint.config.mjs +9 -9
  45. package/templates/project-v2/internal/dashboard/dist/README.txt +1 -1
  46. package/templates/project-v2/internal/dashboard/embed.go +11 -11
  47. package/templates/project-v2/package.json +11 -4
  48. package/templates/project-v2/scripts/application-version.mjs +138 -0
  49. package/templates/project-v2/scripts/assets.mjs +13 -14
  50. package/templates/project-v2/scripts/build-backend.mjs +11 -9
  51. package/templates/project-v2/scripts/build.mjs +12 -0
  52. package/templates/project-v2/scripts/check-generated.mjs +79 -48
  53. package/templates/project-v2/scripts/config.mjs +55 -54
  54. package/templates/project-v2/scripts/dev-watch.mjs +78 -78
  55. package/templates/project-v2/scripts/dev.mjs +50 -49
  56. package/templates/project-v2/scripts/doctor.mjs +94 -94
  57. package/templates/project-v2/scripts/generate-contracts.mjs +88 -88
  58. package/templates/project-v2/scripts/go-build-identity/main.go +210 -0
  59. package/templates/project-v2/scripts/go.mjs +17 -15
  60. package/templates/project-v2/scripts/layout.mjs +10 -10
  61. package/templates/project-v2/scripts/lifecycle.mjs +245 -245
  62. package/templates/project-v2/scripts/openobserve-build.mjs +115 -0
  63. package/templates/project-v2/scripts/project-info.mjs +105 -0
  64. package/templates/project-v2/scripts/release-metadata.mjs +13 -0
  65. package/templates/project-v2/scripts/release-vite.mjs +23 -0
  66. package/templates/project-v2/scripts/release.mjs +3 -0
  67. package/templates/project-v2/scripts/run.mjs +11 -11
  68. package/templates/project-v2/scripts/sdk-integrity.mjs +39 -39
  69. package/templates/project-v2/scripts/setup.mjs +44 -44
  70. package/templates/project-v2/web/admin/index.html +5 -5
  71. package/templates/project-v2/web/admin/package.json +3 -2
  72. package/templates/project-v2/web/admin/src/brand.json +1 -1
  73. package/templates/project-v2/web/admin/src/extensions.gen.ts +6 -6
  74. package/templates/project-v2/web/admin/src/extensions.ts +1 -1
  75. package/templates/project-v2/web/admin/src/main.tsx +20 -14
  76. package/templates/project-v2/web/admin/tsconfig.json +17 -17
  77. package/templates/project-v2/web/admin/vite.config.ts +47 -27
  78. package/src/page.mjs +0 -66
  79. package/templates/module/07-Page.tsx.txt +0 -20
package/src/module.mjs CHANGED
@@ -1,477 +1,439 @@
1
- import { renderTemplate } from "./templates.mjs";
2
- import { rewritePublicImports } from './packages.mjs';
3
- import {
4
- existsSync,
5
- readFileSync,
6
- writeFileSync,
7
- lstatSync,
8
- mkdirSync,
9
- } from "node:fs";
10
- import { dirname, resolve } from "node:path";
11
- import { checkedProject, checkedOutput, writeNew } from "./project.mjs";
12
- import {
13
- columnSQL,
14
- entField,
15
- isNumber,
16
- isText,
17
- normalizeField,
18
- sampleValue,
19
- snake,
20
- quote,
21
- } from "./fields.mjs";
22
- import { enhanceRendering } from "./enhance.mjs";
23
- import { recordHistory } from "./history.mjs";
24
- import { execFileSync } from "node:child_process";
25
- import { projectLayout } from "./layout.mjs";
26
- import { addRecordEvents } from "./records.mjs";
27
- import { addGoaModule } from "./goa.mjs";
28
- const reserved = new Set([
29
- "id",
30
- "createdBy",
31
- "updatedBy",
32
- "createdAt",
33
- "updatedAt",
34
- "type",
35
- "func",
36
- "package",
37
- "import",
38
- "var",
39
- "const",
40
- "password",
41
- "token",
42
- "secret",
43
- ]);
44
- export function validateSpec(input) {
45
- if (
46
- !input ||
47
- !/^[a-z][a-z0-9-]{0,40}$/.test(input.id) ||
48
- !/^[A-Z][a-zA-Z0-9]{0,30}$/.test(input.entity)
49
- )
50
- throw new Error(
51
- "Module id must be lowercase-kebab-case; entity must be PascalCase",
52
- );
53
- if (
54
- typeof input.title !== "string" ||
55
- !input.title.trim() ||
56
- input.title.length > 50
57
- )
58
- throw new Error("Module title is required (1-50 characters)");
59
- if (
60
- input.icon !== undefined &&
61
- (typeof input.icon !== "string" ||
62
- !/^[A-Z][a-zA-Z0-9]{0,63}$/.test(input.icon))
63
- )
64
- throw new Error("icon must be a Lucide PascalCase component name");
65
- if (
66
- !Array.isArray(input.fields) ||
67
- !input.fields.length ||
68
- input.fields.length > 20
69
- )
70
- throw new Error("Supply 1-20 fields");
71
- if (input.scope !== undefined && !["owner", "all"].includes(input.scope))
72
- throw new Error("scope must be owner or all");
73
- const names = new Set();
74
- const fields = input.fields.map((field) => {
75
- if (
76
- !/^[a-z][a-z0-9]*(?:[A-Z][a-z0-9]+)*$/.test(field.name) ||
77
- field.name.length > 31 ||
78
- reserved.has(field.name) ||
79
- [...reserved].some((name) => snake(name) === snake(field.name)) ||
80
- names.has(snake(field.name))
81
- )
82
- throw new Error("Use a non-reserved lowerCamelCase field name");
83
- names.add(snake(field.name));
84
- if (
85
- (field.required !== undefined && typeof field.required !== "boolean") ||
86
- (field.unique !== undefined && typeof field.unique !== "boolean")
87
- )
88
- throw new Error("required/unique must be booleans");
89
- if (
90
- field.title !== undefined &&
91
- (typeof field.title !== "string" || field.title.length > 64)
92
- )
93
- throw new Error("Invalid field title");
94
- return normalizeField(field);
95
- });
96
- if (
97
- input.features &&
98
- (Object.keys(input.features).some(
99
- (key) => !["batch", "importExport"].includes(key),
100
- ) ||
101
- Object.values(input.features).some((value) => typeof value !== "boolean"))
102
- )
103
- throw new Error("features supports boolean batch/importExport switches");
104
- return {
105
- id: input.id,
106
- entity: input.entity,
107
- title: input.title,
108
- ...(input.icon !== undefined ? { icon: input.icon } : {}),
109
- scope: input.scope ?? "owner",
110
- fields,
111
- ...(input.features ? { features: input.features } : {}),
112
- table: `host_${snake(input.id.replaceAll("-", "_"))}_${snake(input.entity)}s`,
113
- };
114
- }
115
-
116
- export function generateModule(project, input) {
117
- const { root, manifest, marker, layout } = checkedProject(project);
118
- const spec = validateSpec(input);
119
- if (
120
- manifest.modules.some(
121
- (module) =>
122
- module.id === spec.id ||
123
- module.entity === spec.entity ||
124
- module.table === spec.table,
125
- )
126
- )
127
- throw new Error("Module, entity or table already registered");
128
- const files = moduleFiles(spec, manifest);
129
- // Referenced domains must expose their own authorized lookup adapter.
130
- for (const field of spec.fields.filter(
131
- (field) => field.type === "reference",
132
- )) {
133
- const target = manifest.modules.find(
134
- (module) => module.id === field.reference.module,
135
- );
136
- const name = `${layout.pages}/${target.id}/lookup.ts`;
137
- if (!existsSync(checkedOutput(root, name)))
138
- throw new Error(`Referenced module ${target.id} must expose lookup.ts`);
139
- }
140
- const header = "// Code generated by create-arcbase. DO NOT EDIT.";
141
- for (const name of [
142
- ...Object.keys(files),
143
- layout.goRegistry,
144
- layout.webRegistry,
145
- ])
146
- checkedOutput(root, name);
147
- for (const name of [layout.goRegistry, layout.webRegistry]) {
148
- const path = resolve(root, name);
149
- if (
150
- existsSync(path) &&
151
- (lstatSync(path).isSymbolicLink() ||
152
- !readFileSync(path, "utf8").startsWith(header))
153
- )
154
- throw new Error(`Refusing to overwrite non-generated registry ${name}`);
155
- }
156
- for (const name of Object.keys(files))
157
- if (existsSync(resolve(root, name)))
158
- throw new Error(`Refusing to overwrite ${name}`);
159
- for (const [name, content] of Object.entries(files))
160
- writeNew(root, name, content);
161
- manifest.modules.push({ ...spec, version: 1 });
162
- for (const name of [layout.goRegistry, layout.webRegistry])
163
- mkdirSync(dirname(resolve(root, name)), { recursive: true });
164
- writeFileSync(marker, JSON.stringify(manifest, null, 2) + "\n");
165
- writeFileSync(
166
- resolve(root, layout.goRegistry),
167
- `// Code generated by create-arcbase. DO NOT EDIT.\npackage main\nimport (\n arcbase "github.com/fudanda/arcbase/backend/v2"\n${manifest.modules.map((module, index) => ` module${index} "${layout.goImports}/${module.id}"`).join("\n")}\n)\nfunc configuredModules() []arcbase.Module { return []arcbase.Module{${manifest.modules.map((_, index) => `&module${index}.Module{}`).join(",")}} }\n`,
168
- );
169
- writeFileSync(
170
- resolve(root, layout.webRegistry),
171
- `// Code generated by create-arcbase. DO NOT EDIT.\nimport type { ArcBaseAdminModule } from '@fudanda/${manifest.ui === 'antd' ? 'admin-antd' : 'admin'}';\nimport type { GoaOperation } from '@fudanda/client/core';\n${manifest.modules.map((module, index) => `import { module as module${index}, operations as operations${index} } from '${layout.webImports}/${module.id}/index';`).join("\n")}\nexport const modules: ArcBaseAdminModule[] = [${manifest.modules.map((_, index) => `module${index}`).join(",")}];\nexport const operations: GoaOperation[] = [${manifest.modules.map((_, index) => `...operations${index}`).join(",")}];\n`,
172
- );
173
- recordHistory(root, spec, 1, Object.keys(files));
174
- return {
175
- module: spec.id,
176
- files: Object.keys(files),
177
- next: [
178
- "npm run generate",
179
- "npm run check",
180
- "npm run build",
181
- "npm run db:migrate",
182
- "npm run db:seed",
183
- "npm test",
184
- "npm start",
185
- ],
186
- };
187
- }
188
- export function moduleFiles(spec, manifest, version = 1) {
189
- projectLayout(manifest);
190
- const modules = manifest.modules
191
- .filter((module) => module.id !== spec.id)
192
- .map((module) => {
193
- const normalized = validateSpec(module);
194
- if (normalized.table !== module.table)
195
- throw new Error("Registered module table metadata differs");
196
- return normalized;
197
- });
198
- return Object.fromEntries(
199
- Object.entries(
200
- renderModule(spec, manifest.backendModule, modules, version, manifest.ui ?? 'semi'),
201
- ).map(([name, content]) => [name, formatSource(content, name)]),
202
- );
203
- }
204
-
205
- function formatSource(value, name) {
206
- value = value.replace(/[ \t]+$/gm, "");
207
- return name.endsWith(".go")
208
- ? execFileSync("gofmt", [], {
209
- input: value,
210
- encoding: "utf8",
211
- windowsHide: true,
212
- })
213
- : value;
214
- }
215
-
216
- export function renderModule(s, goModule, modules = [], version = 1, ui = 'semi') {
217
- const E = s.entity,
218
- id = s.id,
219
- pkg = E.toLowerCase(),
220
- page = `/extensions/${id}/records`;
221
- const permission = (action) => `host:${id}:${action}`;
222
- const entFields = s.fields.map(entField).join(",\n");
223
- const indexes = s.fields
224
- .filter((f) => f.unique)
225
- .map((f) => `index.Fields(${quote(snake(f.name))}).Unique()`)
226
- .join(",");
227
- const column = (f) => columnSQL(f);
228
- const ddl = (pg) => [
229
- `CREATE TABLE ${s.table} (id ${pg ? "INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY" : "INTEGER PRIMARY KEY AUTOINCREMENT"}, ${s.fields.map((f) => column(f, pg)).join(", ")}, created_by INTEGER NOT NULL REFERENCES users(id), updated_by INTEGER NOT NULL REFERENCES users(id), created_at ${pg ? "TIMESTAMPTZ" : "DATETIME"} NOT NULL, updated_at ${pg ? "TIMESTAMPTZ" : "DATETIME"} NOT NULL)`,
230
- ...s.fields
231
- .filter((f) => f.unique)
232
- .map(
233
- (f) =>
234
- `CREATE UNIQUE INDEX ${s.table}_${snake(f.name)}_unique ON ${s.table}(${snake(f.name)})`,
235
- ),
236
- `CREATE INDEX ${s.table}_created_by ON ${s.table}(created_by)`,
237
- ];
238
- const fields = s.fields
239
- .map(
240
- (f) =>
241
- `{${quote(f.name)},${quote(snake(f.name))},${quote(isNumber(f) ? "int" : isText(f) ? "string" : "bool")}}`,
242
- )
243
- .join(",");
244
- const mapping = s.fields
245
- .map((f) => `result[${quote(f.name)}]=raw[${quote(snake(f.name))}]`)
246
- .join("\n");
247
- const scopes =
248
- s.scope === "owner"
249
- ? `if !actor.SuperAdmin { q.Where(func(selector *entsql.Selector){selector.Where(entsql.EQ(selector.C("created_by"),actor.UserID))}) }`
250
- : "// Shared organization-wide records; action permissions still apply.";
251
- const stringColumns = s.fields
252
- .filter((f) => f.type === "string")
253
- .map(
254
- (f) => `entsql.ContainsFold(selector.C(${quote(snake(f.name))}),keyword)`,
255
- )
256
- .join(",");
257
- const search = stringColumns
258
- ? `if keyword!="" { q.Where(func(selector *entsql.Selector){selector.Where(entsql.Or(${stringColumns}))}) }`
259
- : "";
260
- const files = {};
261
- const columnWidth = (field, index) =>
262
- index === 0 ? 220 : field.type === "string" ? 180 : 100;
263
- files[`web/admin/src/pages/${id}/Page.css`] =
264
- `.host-module-${id} .semi-table-pagination-outer { flex-wrap: wrap; gap: 12px; }\n.host-module-${id} .semi-table-pagination-info { white-space: nowrap; flex-shrink: 0; }\n`;
265
- files[`web/admin/src/pages/${id}/permissions.ts`] =
266
- `import type { Permission } from '@fudanda/client/core';\ndeclare module '@fudanda/client/core' { interface HostPermissionRegistry { ${["list", "create", "update", "remove"].map((action) => `${quote(permission(action))}: true;`).join(" ")} } }\nexport const permissions = { ${["list", "create", "update", "remove"].map((action) => `${action}:${quote(permission(action))}`).join(",")} } as const satisfies Record<string,Permission>;\n`;
267
- files[`internal/ent/schema/${pkg}.go`] = `package schema
268
- import ( "time"; "entgo.io/ent"; "entgo.io/ent/schema"; "entgo.io/ent/schema/field"; "entgo.io/ent/schema/index"; "entgo.io/ent/dialect/entsql" )
269
- type ${E} struct { ent.Schema }
270
- func (${E}) Annotations() []schema.Annotation { return []schema.Annotation{entsql.Annotation{Table:"${s.table}"}} }
271
- func (${E}) Fields() []ent.Field { return []ent.Field{ ${entFields}, field.Int("created_by"),field.Int("updated_by"),field.Time("created_at").Default(time.Now),field.Time("updated_at").Default(time.Now).UpdateDefault(time.Now) } }
272
- func (${E}) Indexes() []ent.Index { return []ent.Index{index.Fields("created_by")${indexes ? "," + indexes : ""}} }
273
- `;
274
- files[`internal/modules/${id}/migrations.go`] = renderTemplate(
275
- "02-migrations.go.txt",
276
- [
277
- ddl(true).map(quote).join(","),
278
- ddl(false).map(quote).join(","),
279
- id,
280
- id,
281
- id,
282
- id,
283
- quote(s.title),
284
- quote(s.icon ?? "Database"),
285
- id,
286
- quote(s.title),
287
- permission("list"),
288
- page,
289
- id,
290
- id,
291
- quote(s.icon ?? "Database"),
292
- ["create", "update", "remove"]
293
- .map(
294
- (action) =>
295
- `{Name:"${permission(action)}",Title:"${action}",Permission:"${permission(action)}",ParentName:"host:${id}:records",Type:"button"},`,
296
- )
297
- .join("\n"),
298
- ],
299
- );
300
- files[`internal/modules/${id}/service.go`] = renderTemplate(
301
- "03-service.go.txt",
302
- [
303
- goModule,
304
- E,
305
- E,
306
- scopes,
307
- E,
308
- mapping,
309
- fields,
310
- permission("list"),
311
- search,
312
- E,
313
- permission("list"),
314
- permission("create"),
315
- E,
316
- id,
317
- s.table,
318
- E,
319
- permission("update"),
320
- E,
321
- id,
322
- s.table,
323
- E,
324
- permission("remove"),
325
- id,
326
- s.table,
327
- E,
328
- ],
329
- );
330
- files[`internal/modules/${id}/module.go`] = renderTemplate(
331
- "04-module.go.txt",
332
- [
333
- id,
334
- page,
335
- permission("list"),
336
- ["list", "create", "update", "remove"]
337
- .map((action) => quote(permission(action)))
338
- .join(","),
339
- s.table,
340
- permission("list"),
341
- id,
342
- E,
343
- E,
344
- E,
345
- E,
346
- E,
347
- ],
348
- );
349
- files[`web/admin/src/pages/${id}/queries.ts`] = renderTemplate(
350
- "06-queries.ts.txt",
351
- [s.table],
352
- );
353
- files[`web/admin/src/pages/${id}/Page.tsx`] = renderTemplate(
354
- "07-Page.tsx.txt",
355
- [
356
- s.fields
357
- .map(
358
- (f, index) =>
359
- `{title:${quote(f.title)},dataIndex:${quote(f.name)},width:${columnWidth(f, index)}${f.type === "bool" ? ',render:(value:boolean|null)=>value===null?"":value?"是":"否"' : ""}}`,
360
- )
361
- .join(","),
362
- id,
363
- s.title
364
- .replaceAll("<", "&lt;")
365
- .replaceAll(">", "&gt;")
366
- .replaceAll("{", "&#123;"),
367
- s.fields.reduce(
368
- (total, field, index) => total + columnWidth(field, index),
369
- 180,
370
- ),
371
- s.fields
372
- .filter((f) => f.type === "bool" && f.required)
373
- .map((f) => `${f.name}:false`)
374
- .join(","),
375
- s.fields
376
- .map(
377
- (f) =>
378
- `${f.name}:${!f.required ? `values.${f.name}===undefined${f.type === "string" ? `||values.${f.name}===''` : ""}?null:values.${f.name}` : f.type === "bool" ? `values.${f.name}??false` : `values.${f.name}`}`,
379
- )
380
- .join(","),
381
- s.fields
382
- .map(
383
- (f) =>
384
- `<Form.${f.type === "string" ? "Input" : f.type === "int" ? "InputNumber" : "Switch"} field=${quote(f.name)} label=${quote(f.title)} ${f.type === "string" ? `maxLength={${f.maxLength}}` : f.type === "bool" && f.required ? `initValue={editing?.${f.name}??false}` : ""} rules={[{required:${f.required && f.type !== "bool"},message:${quote("请填写" + f.title)}}]}/>`,
385
- )
386
- .join("\n"),
387
- ],
388
- );
389
- files[`web/admin/src/pages/${id}/index.ts`] =
390
- `import type { ArcBaseAdminModule } from '@fudanda/admin';\nimport Page from './Page';\nimport { contract } from './contracts.ts';\nimport { permissions } from './permissions.ts';\nexport const module:ArcBaseAdminModule={id:${quote(id)},title:${quote(s.title)},icon:${quote(s.icon ?? "Database")},pages:[{id:'records',title:${quote(s.title)},icon:${quote(s.icon ?? "Database")},path:${quote(page)},permission:permissions.list,component:Page}]};\nexport const operations=[contract.list,contract.detail,contract.create,contract.update,contract.remove];\n`;
391
- files[`internal/modules/${id}/service_test.go`] = renderTemplate(
392
- "08-service_test.go.txt",
393
- [id, id, id, s.table],
394
- );
395
- const referenceValue = (f) => ({
396
- go: `fixture${modules.findIndex((module) => module.id === f.reference.module)}`,
397
- });
398
- const input = Object.fromEntries(
399
- s.fields.map((f) => [
400
- f.name,
401
- f.type === "reference" ? referenceValue(f) : sampleValue(f),
402
- ]),
403
- );
404
- const second = Object.fromEntries(
405
- s.fields.map((f) => [
406
- f.name,
407
- f.type === "reference" ? referenceValue(f) : sampleValue(f, true),
408
- ]),
409
- );
410
- const goValue = (value) =>
411
- value === null
412
- ? "nil"
413
- : (value?.go ??
414
- (typeof value === "string"
415
- ? quote(value)
416
- : typeof value === "number"
417
- ? `float64(${value})`
418
- : String(value)));
419
- const goInput = (value) =>
420
- "map[string]any{" +
421
- Object.entries(value)
422
- .map(([name, value]) => `${quote(name)}:${goValue(value)}`)
423
- .join(",") +
424
- "}";
425
- const patch = s.fields.find((f) => f.type !== "reference") ?? s.fields[0],
426
- unchanged = s.fields.find((f) => f.name !== patch.name) ?? patch;
427
- const patchValue =
428
- patch.type === "reference"
429
- ? referenceValue(patch)
430
- : sampleValue(patch, true);
431
- const nullable = s.fields.find((f) => !f.required);
432
- const unique = s.fields.find((f) => f.unique);
433
- const scope =
434
- s.scope === "owner"
435
- ? `if status,_=call(other,"GET",detail,nil,"");status!=404{t.Fatal("owner read scope",status)};if status,_=call(other,"PUT",detail,map[string]any{${quote(patch.name)}:${goValue(patchValue)}},otherCSRF);status!=404{t.Fatal("owner write scope",status)};if status,payload=call(other,"GET",base,nil,"");status!=200||payload["data"].(map[string]any)["total"].(float64)!=0{t.Fatal("owner list scope",status)}`
436
- : 'if status,_=call(other,"GET",detail,nil,"");status!=200{t.Fatal("shared scope",status)}';
437
- const tokens = {
438
- MODULE: id,
439
- TABLE: s.table,
440
- INPUT: goInput(input),
441
- SECOND_INPUT: goInput(second),
442
- SCOPE_ASSERTIONS: scope,
443
- REQUIRED_FIELD: quote(s.fields.find((f) => f.required)?.name ?? "unknown"),
444
- PATCH_FIELD: quote(patch.name),
445
- PATCH_VALUE: goValue(patchValue),
446
- UNCHANGED_FIELD: quote(unchanged.name),
447
- UNCHANGED_VALUE: goValue(
448
- unchanged === patch ? patchValue : input[unchanged.name],
449
- ),
450
- NULLABLE_ASSERTIONS: nullable
451
- ? `if status,payload=call(owner,"PUT",detail,map[string]any{${quote(nullable.name)}:nil},csrf);status!=200||payload["data"].(map[string]any)[${quote(nullable.name)}]!=nil{t.Fatal("nullable patch",status)}`
452
- : "",
453
- UNIQUE_ASSERTIONS:
454
- unique && unique !== patch
455
- ? `if status,_=call(owner,"POST",base,${goInput(input)},csrf);status!=409{t.Fatal("unique conflict",status)}`
456
- : "",
457
- };
458
- const testTemplate = readFileSync(
459
- new URL("../templates/module-runtime-test.go.txt", import.meta.url),
460
- "utf8",
461
- );
462
- files[`internal/modules/${id}/runtime_test.go`] = testTemplate.replace(
463
- /__([A-Z_]+)__/g,
464
- (_match, key) => tokens[key],
465
- );
466
- files[`modules/${id}.json`] = JSON.stringify(s, null, 2) + "\n";
467
- const enhanced = enhanceRendering(files, s, modules, version, ui);
468
- for (const name of Object.keys(enhanced)) if (name.endsWith('.ts') || name.endsWith('.tsx')) enhanced[name] = enhanced[name].replaceAll("from '@fudanda/elements'", "from '@fudanda/admin-antd/hooks'").replaceAll("from '@fudanda/admin'", "from '@fudanda/" + (ui === 'antd' ? 'admin-antd' : 'admin') + "'");
469
- return Object.fromEntries(
470
- Object.entries(addGoaModule(addRecordEvents(enhanced, s, goModule), s, goModule)).map(
471
- ([name, value]) => {
472
- const source=value.replaceAll("__GO_MODULE__", goModule);
473
- return [name,ui==='antd'&&/\.[cm]?[jt]sx?$/.test(name)?rewritePublicImports(source):source];
474
- },
475
- ),
476
- );
477
- }
1
+ import { renderTemplate } from "./templates.mjs";
2
+ import { rewritePublicImports } from './packages.mjs';
3
+ import {
4
+ existsSync,
5
+ readFileSync,
6
+ writeFileSync,
7
+ lstatSync,
8
+ mkdirSync,
9
+ } from "node:fs";
10
+ import { dirname, resolve } from "node:path";
11
+ import { checkedProject, checkedOutput, writeNew } from "./project.mjs";
12
+ import {
13
+ columnSQL,
14
+ entField,
15
+ isNumber,
16
+ isText,
17
+ normalizeField,
18
+ sampleValue,
19
+ snake,
20
+ quote,
21
+ } from "./fields.mjs";
22
+ import { enhanceRendering } from "./enhance.mjs";
23
+ import { recordHistory } from "./history.mjs";
24
+ import { execFileSync } from "node:child_process";
25
+ import { projectLayout } from "./layout.mjs";
26
+ import { addRecordEvents } from "./records.mjs";
27
+ import { addGoaModule } from "./goa.mjs";
28
+ const reserved = new Set([
29
+ "id",
30
+ "createdBy",
31
+ "updatedBy",
32
+ "createdAt",
33
+ "updatedAt",
34
+ "type",
35
+ "func",
36
+ "package",
37
+ "import",
38
+ "var",
39
+ "const",
40
+ "password",
41
+ "token",
42
+ "secret",
43
+ ]);
44
+ export function validateSpec(input) {
45
+ if (
46
+ !input ||
47
+ !/^[a-z][a-z0-9-]{0,40}$/.test(input.id) ||
48
+ !/^[A-Z][a-zA-Z0-9]{0,30}$/.test(input.entity)
49
+ )
50
+ throw new Error(
51
+ "Module id must be lowercase-kebab-case; entity must be PascalCase",
52
+ );
53
+ if (
54
+ typeof input.title !== "string" ||
55
+ !input.title.trim() ||
56
+ input.title.length > 50
57
+ )
58
+ throw new Error("Module title is required (1-50 characters)");
59
+ if (
60
+ input.icon !== undefined &&
61
+ (typeof input.icon !== "string" ||
62
+ !/^[A-Z][a-zA-Z0-9]{0,63}$/.test(input.icon))
63
+ )
64
+ throw new Error("icon must be a Lucide PascalCase component name");
65
+ if (
66
+ !Array.isArray(input.fields) ||
67
+ !input.fields.length ||
68
+ input.fields.length > 20
69
+ )
70
+ throw new Error("Supply 1-20 fields");
71
+ if (input.scope !== undefined && !["owner", "all"].includes(input.scope))
72
+ throw new Error("scope must be owner or all");
73
+ const names = new Set();
74
+ const fields = input.fields.map((field) => {
75
+ if (
76
+ !/^[a-z][a-z0-9]*(?:[A-Z][a-z0-9]+)*$/.test(field.name) ||
77
+ field.name.length > 31 ||
78
+ reserved.has(field.name) ||
79
+ [...reserved].some((name) => snake(name) === snake(field.name)) ||
80
+ names.has(snake(field.name))
81
+ )
82
+ throw new Error("Use a non-reserved lowerCamelCase field name");
83
+ names.add(snake(field.name));
84
+ if (
85
+ (field.required !== undefined && typeof field.required !== "boolean") ||
86
+ (field.unique !== undefined && typeof field.unique !== "boolean")
87
+ )
88
+ throw new Error("required/unique must be booleans");
89
+ if (
90
+ field.title !== undefined &&
91
+ (typeof field.title !== "string" || field.title.length > 64)
92
+ )
93
+ throw new Error("Invalid field title");
94
+ return normalizeField(field);
95
+ });
96
+ if (
97
+ input.features &&
98
+ (Object.keys(input.features).some(
99
+ (key) => !["batch", "importExport"].includes(key),
100
+ ) ||
101
+ Object.values(input.features).some((value) => typeof value !== "boolean"))
102
+ )
103
+ throw new Error("features supports boolean batch/importExport switches");
104
+ return {
105
+ id: input.id,
106
+ entity: input.entity,
107
+ title: input.title,
108
+ ...(input.icon !== undefined ? { icon: input.icon } : {}),
109
+ scope: input.scope ?? "owner",
110
+ fields,
111
+ ...(input.features ? { features: input.features } : {}),
112
+ table: `host_${snake(input.id.replaceAll("-", "_"))}_${snake(input.entity)}s`,
113
+ };
114
+ }
115
+
116
+ export function generateModule(project, input) {
117
+ const { root, manifest, marker, layout } = checkedProject(project);
118
+ const spec = validateSpec(input);
119
+ if (
120
+ manifest.modules.some(
121
+ (module) =>
122
+ module.id === spec.id ||
123
+ module.entity === spec.entity ||
124
+ module.table === spec.table,
125
+ )
126
+ )
127
+ throw new Error("Module, entity or table already registered");
128
+ const files = moduleFiles(spec, manifest);
129
+ // Referenced domains must expose their own authorized lookup adapter.
130
+ for (const field of spec.fields.filter(
131
+ (field) => field.type === "reference",
132
+ )) {
133
+ const target = manifest.modules.find(
134
+ (module) => module.id === field.reference.module,
135
+ );
136
+ const name = `${layout.pages}/${target.id}/lookup.ts`;
137
+ if (!existsSync(checkedOutput(root, name)))
138
+ throw new Error(`Referenced module ${target.id} must expose lookup.ts`);
139
+ }
140
+ const header = "// Code generated by create-arcbase. DO NOT EDIT.";
141
+ for (const name of [
142
+ ...Object.keys(files),
143
+ layout.goRegistry,
144
+ layout.webRegistry,
145
+ ])
146
+ checkedOutput(root, name);
147
+ for (const name of [layout.goRegistry, layout.webRegistry]) {
148
+ const path = resolve(root, name);
149
+ if (
150
+ existsSync(path) &&
151
+ (lstatSync(path).isSymbolicLink() ||
152
+ !readFileSync(path, "utf8").startsWith(header))
153
+ )
154
+ throw new Error(`Refusing to overwrite non-generated registry ${name}`);
155
+ }
156
+ for (const name of Object.keys(files))
157
+ if (existsSync(resolve(root, name)))
158
+ throw new Error(`Refusing to overwrite ${name}`);
159
+ for (const [name, content] of Object.entries(files))
160
+ writeNew(root, name, content);
161
+ manifest.modules.push({ ...spec, version: 1 });
162
+ for (const name of [layout.goRegistry, layout.webRegistry])
163
+ mkdirSync(dirname(resolve(root, name)), { recursive: true });
164
+ writeFileSync(marker, JSON.stringify(manifest, null, 2) + "\n");
165
+ writeFileSync(
166
+ resolve(root, layout.goRegistry),
167
+ `// Code generated by create-arcbase. DO NOT EDIT.\npackage main\nimport (\n arcbase "github.com/fudanda/arcbase/backend/v2"\n${manifest.modules.map((module, index) => ` module${index} "${layout.goImports}/${module.id}"`).join("\n")}\n)\nfunc configuredModules() []arcbase.Module { return []arcbase.Module{${manifest.modules.map((_, index) => `&module${index}.Module{}`).join(",")}} }\n`,
168
+ );
169
+ writeFileSync(
170
+ resolve(root, layout.webRegistry),
171
+ `// Code generated by create-arcbase. DO NOT EDIT.\nimport type { ArcBaseAdminModule } from '@fudanda/admin-antd';\nimport type { GoaOperation } from '@fudanda/client/core';\n${manifest.modules.map((module, index) => `import { module as module${index}, operations as operations${index} } from '${layout.webImports}/${module.id}/index';`).join("\n")}\nexport const modules: ArcBaseAdminModule[] = [${manifest.modules.map((_, index) => `module${index}`).join(",")}];\nexport const operations: GoaOperation[] = [${manifest.modules.map((_, index) => `...operations${index}`).join(",")}];\n`,
172
+ );
173
+ recordHistory(root, spec, 1, Object.keys(files));
174
+ return {
175
+ module: spec.id,
176
+ files: Object.keys(files),
177
+ next: [
178
+ "npm run generate",
179
+ "npm run check",
180
+ "npm run build",
181
+ "npm run db:migrate",
182
+ "npm run db:seed",
183
+ "npm test",
184
+ "npm start",
185
+ ],
186
+ };
187
+ }
188
+ export function moduleFiles(spec, manifest, version = 1) {
189
+ projectLayout(manifest);
190
+ const modules = manifest.modules
191
+ .filter((module) => module.id !== spec.id)
192
+ .map((module) => {
193
+ const normalized = validateSpec(module);
194
+ if (normalized.table !== module.table)
195
+ throw new Error("Registered module table metadata differs");
196
+ return normalized;
197
+ });
198
+ return Object.fromEntries(
199
+ Object.entries(
200
+ renderModule(spec, manifest.backendModule, modules, version, manifest.ui),
201
+ ).map(([name, content]) => [name, formatSource(content, name)]),
202
+ );
203
+ }
204
+
205
+ function formatSource(value, name) {
206
+ value = value.replace(/[ \t]+$/gm, "");
207
+ return name.endsWith(".go")
208
+ ? execFileSync("gofmt", [], {
209
+ input: value,
210
+ encoding: "utf8",
211
+ windowsHide: true,
212
+ })
213
+ : value;
214
+ }
215
+
216
+ export function renderModule(s, goModule, modules = [], version = 1, ui = 'antd') {
217
+ if (ui !== 'antd') throw new Error('Module generation supports Ant Design only');
218
+ const E = s.entity,
219
+ id = s.id,
220
+ pkg = E.toLowerCase(),
221
+ page = `/extensions/${id}/records`;
222
+ const permission = (action) => `host:${id}:${action}`;
223
+ const entFields = s.fields.map(entField).join(",\n");
224
+ const indexes = s.fields
225
+ .filter((f) => f.unique)
226
+ .map((f) => `index.Fields(${quote(snake(f.name))}).Unique()`)
227
+ .join(",");
228
+ const column = (f) => columnSQL(f);
229
+ const ddl = (pg) => [
230
+ `CREATE TABLE ${s.table} (id ${pg ? "INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY" : "INTEGER PRIMARY KEY AUTOINCREMENT"}, ${s.fields.map((f) => column(f, pg)).join(", ")}, created_by INTEGER NOT NULL REFERENCES users(id), updated_by INTEGER NOT NULL REFERENCES users(id), created_at ${pg ? "TIMESTAMPTZ" : "DATETIME"} NOT NULL, updated_at ${pg ? "TIMESTAMPTZ" : "DATETIME"} NOT NULL)`,
231
+ ...s.fields
232
+ .filter((f) => f.unique)
233
+ .map(
234
+ (f) =>
235
+ `CREATE UNIQUE INDEX ${s.table}_${snake(f.name)}_unique ON ${s.table}(${snake(f.name)})`,
236
+ ),
237
+ `CREATE INDEX ${s.table}_created_by ON ${s.table}(created_by)`,
238
+ ];
239
+ const fields = s.fields
240
+ .map(
241
+ (f) =>
242
+ `{${quote(f.name)},${quote(snake(f.name))},${quote(isNumber(f) ? "int" : isText(f) ? "string" : "bool")}}`,
243
+ )
244
+ .join(",");
245
+ const mapping = s.fields
246
+ .map((f) => `result[${quote(f.name)}]=raw[${quote(snake(f.name))}]`)
247
+ .join("\n");
248
+ const scopes =
249
+ s.scope === "owner"
250
+ ? `if !actor.SuperAdmin { q.Where(func(selector *entsql.Selector){selector.Where(entsql.EQ(selector.C("created_by"),actor.UserID))}) }`
251
+ : "// Shared organization-wide records; action permissions still apply.";
252
+ const stringColumns = s.fields
253
+ .filter((f) => f.type === "string")
254
+ .map(
255
+ (f) => `entsql.ContainsFold(selector.C(${quote(snake(f.name))}),keyword)`,
256
+ )
257
+ .join(",");
258
+ const search = stringColumns
259
+ ? `if keyword!="" { q.Where(func(selector *entsql.Selector){selector.Where(entsql.Or(${stringColumns}))}) }`
260
+ : "";
261
+ const files = {};
262
+ files[`web/admin/src/pages/${id}/Page.css`] =
263
+ `.host-module-${id} .ant-table-pagination { flex-wrap: wrap; gap: 12px; }\n`;
264
+ files[`web/admin/src/pages/${id}/permissions.ts`] =
265
+ `import type { Permission } from '@fudanda/client/core';\ndeclare module '@fudanda/client/core' { interface HostPermissionRegistry { ${["list", "create", "update", "remove"].map((action) => `${quote(permission(action))}: true;`).join(" ")} } }\nexport const permissions = { ${["list", "create", "update", "remove"].map((action) => `${action}:${quote(permission(action))}`).join(",")} } as const satisfies Record<string,Permission>;\n`;
266
+ files[`internal/ent/schema/${pkg}.go`] = `package schema
267
+ import ( "time"; "entgo.io/ent"; "entgo.io/ent/schema"; "entgo.io/ent/schema/field"; "entgo.io/ent/schema/index"; "entgo.io/ent/dialect/entsql" )
268
+ type ${E} struct { ent.Schema }
269
+ func (${E}) Annotations() []schema.Annotation { return []schema.Annotation{entsql.Annotation{Table:"${s.table}"}} }
270
+ func (${E}) Fields() []ent.Field { return []ent.Field{ ${entFields}, field.Int("created_by"),field.Int("updated_by"),field.Time("created_at").Default(time.Now),field.Time("updated_at").Default(time.Now).UpdateDefault(time.Now) } }
271
+ func (${E}) Indexes() []ent.Index { return []ent.Index{index.Fields("created_by")${indexes ? "," + indexes : ""}} }
272
+ `;
273
+ files[`internal/modules/${id}/migrations.go`] = renderTemplate(
274
+ "02-migrations.go.txt",
275
+ [
276
+ ddl(true).map(quote).join(","),
277
+ ddl(false).map(quote).join(","),
278
+ id,
279
+ id,
280
+ id,
281
+ id,
282
+ quote(s.title),
283
+ quote(s.icon ?? "Database"),
284
+ id,
285
+ quote(s.title),
286
+ permission("list"),
287
+ page,
288
+ id,
289
+ id,
290
+ quote(s.icon ?? "Database"),
291
+ ["create", "update", "remove"]
292
+ .map(
293
+ (action) =>
294
+ `{Name:"${permission(action)}",Title:"${action}",Permission:"${permission(action)}",ParentName:"host:${id}:records",Type:"button"},`,
295
+ )
296
+ .join("\n"),
297
+ ],
298
+ );
299
+ files[`internal/modules/${id}/service.go`] = renderTemplate(
300
+ "03-service.go.txt",
301
+ [
302
+ goModule,
303
+ E,
304
+ E,
305
+ scopes,
306
+ E,
307
+ mapping,
308
+ fields,
309
+ permission("list"),
310
+ search,
311
+ E,
312
+ permission("list"),
313
+ permission("create"),
314
+ E,
315
+ id,
316
+ s.table,
317
+ E,
318
+ permission("update"),
319
+ E,
320
+ id,
321
+ s.table,
322
+ E,
323
+ permission("remove"),
324
+ id,
325
+ s.table,
326
+ E,
327
+ ],
328
+ );
329
+ files[`internal/modules/${id}/module.go`] = renderTemplate(
330
+ "04-module.go.txt",
331
+ [
332
+ id,
333
+ page,
334
+ permission("list"),
335
+ ["list", "create", "update", "remove"]
336
+ .map((action) => quote(permission(action)))
337
+ .join(","),
338
+ s.table,
339
+ permission("list"),
340
+ id,
341
+ E,
342
+ E,
343
+ E,
344
+ E,
345
+ E,
346
+ ],
347
+ );
348
+ files[`web/admin/src/pages/${id}/queries.ts`] = renderTemplate(
349
+ "06-queries.ts.txt",
350
+ [s.table],
351
+ );
352
+ files[`web/admin/src/pages/${id}/index.ts`] =
353
+ `import type { ArcBaseAdminModule } from '@fudanda/admin-antd';\nimport Page from './Page';\nimport { contract } from './contracts.ts';\nimport { permissions } from './permissions.ts';\nexport const module:ArcBaseAdminModule={id:${quote(id)},title:${quote(s.title)},icon:${quote(s.icon ?? "Database")},pages:[{id:'records',title:${quote(s.title)},icon:${quote(s.icon ?? "Database")},path:${quote(page)},permission:permissions.list,component:Page}]};\nexport const operations=[contract.list,contract.detail,contract.create,contract.update,contract.remove];\n`;
354
+ files[`internal/modules/${id}/service_test.go`] = renderTemplate(
355
+ "08-service_test.go.txt",
356
+ [id, id, id, s.table],
357
+ );
358
+ const referenceValue = (f) => ({
359
+ go: `fixture${modules.findIndex((module) => module.id === f.reference.module)}`,
360
+ });
361
+ const input = Object.fromEntries(
362
+ s.fields.map((f) => [
363
+ f.name,
364
+ f.type === "reference" ? referenceValue(f) : sampleValue(f),
365
+ ]),
366
+ );
367
+ const second = Object.fromEntries(
368
+ s.fields.map((f) => [
369
+ f.name,
370
+ f.type === "reference" ? referenceValue(f) : sampleValue(f, true),
371
+ ]),
372
+ );
373
+ const goValue = (value) =>
374
+ value === null
375
+ ? "nil"
376
+ : (value?.go ??
377
+ (typeof value === "string"
378
+ ? quote(value)
379
+ : typeof value === "number"
380
+ ? `float64(${value})`
381
+ : String(value)));
382
+ const goInput = (value) =>
383
+ "map[string]any{" +
384
+ Object.entries(value)
385
+ .map(([name, value]) => `${quote(name)}:${goValue(value)}`)
386
+ .join(",") +
387
+ "}";
388
+ const patch = s.fields.find((f) => f.type !== "reference") ?? s.fields[0],
389
+ unchanged = s.fields.find((f) => f.name !== patch.name) ?? patch;
390
+ const patchValue =
391
+ patch.type === "reference"
392
+ ? referenceValue(patch)
393
+ : sampleValue(patch, true);
394
+ const nullable = s.fields.find((f) => !f.required);
395
+ const unique = s.fields.find((f) => f.unique);
396
+ const scope =
397
+ s.scope === "owner"
398
+ ? `if status,_=call(other,"GET",detail,nil,"");status!=404{t.Fatal("owner read scope",status)};if status,_=call(other,"PUT",detail,map[string]any{${quote(patch.name)}:${goValue(patchValue)}},otherCSRF);status!=404{t.Fatal("owner write scope",status)};if status,payload=call(other,"GET",base,nil,"");status!=200||payload["data"].(map[string]any)["total"].(float64)!=0{t.Fatal("owner list scope",status)}`
399
+ : 'if status,_=call(other,"GET",detail,nil,"");status!=200{t.Fatal("shared scope",status)}';
400
+ const tokens = {
401
+ MODULE: id,
402
+ TABLE: s.table,
403
+ INPUT: goInput(input),
404
+ SECOND_INPUT: goInput(second),
405
+ SCOPE_ASSERTIONS: scope,
406
+ REQUIRED_FIELD: quote(s.fields.find((f) => f.required)?.name ?? "unknown"),
407
+ PATCH_FIELD: quote(patch.name),
408
+ PATCH_VALUE: goValue(patchValue),
409
+ UNCHANGED_FIELD: quote(unchanged.name),
410
+ UNCHANGED_VALUE: goValue(
411
+ unchanged === patch ? patchValue : input[unchanged.name],
412
+ ),
413
+ NULLABLE_ASSERTIONS: nullable
414
+ ? `if status,payload=call(owner,"PUT",detail,map[string]any{${quote(nullable.name)}:nil},csrf);status!=200||payload["data"].(map[string]any)[${quote(nullable.name)}]!=nil{t.Fatal("nullable patch",status)}`
415
+ : "",
416
+ UNIQUE_ASSERTIONS:
417
+ unique && unique !== patch
418
+ ? `if status,_=call(owner,"POST",base,${goInput(input)},csrf);status!=409{t.Fatal("unique conflict",status)}`
419
+ : "",
420
+ };
421
+ const testTemplate = readFileSync(
422
+ new URL("../templates/module-runtime-test.go.txt", import.meta.url),
423
+ "utf8",
424
+ );
425
+ files[`internal/modules/${id}/runtime_test.go`] = testTemplate.replace(
426
+ /__([A-Z_]+)__/g,
427
+ (_match, key) => tokens[key],
428
+ );
429
+ files[`modules/${id}.json`] = JSON.stringify(s, null, 2) + "\n";
430
+ const enhanced = enhanceRendering(files, s, modules, version);
431
+ return Object.fromEntries(
432
+ Object.entries(addGoaModule(addRecordEvents(enhanced, s, goModule), s, goModule)).map(
433
+ ([name, value]) => {
434
+ const source=value.replaceAll("__GO_MODULE__", goModule);
435
+ return [name,/\.[cm]?[jt]sx?$/.test(name)?rewritePublicImports(source):source];
436
+ },
437
+ ),
438
+ );
439
+ }