@cosmicdrift/kumiko-dev-server 0.328.1 → 0.330.0

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 (125) hide show
  1. package/README.md +17 -0
  2. package/bin/kumiko-build.ts +3 -2
  3. package/bin/kumiko-dev.ts +1 -1
  4. package/bin/kumiko-init-deploy.ts +1 -1
  5. package/bin/kumiko-schema-check.ts +4 -1
  6. package/dist/build-server-bundle.d.ts +31 -0
  7. package/dist/build-server-bundle.js +282 -0
  8. package/dist/build.d.ts +2 -0
  9. package/dist/build.js +5 -0
  10. package/dist/cli.d.ts +5 -0
  11. package/dist/cli.js +9 -0
  12. package/dist/codegen/index.d.ts +4 -0
  13. package/dist/codegen/index.js +4 -0
  14. package/dist/codegen/render.d.ts +55 -0
  15. package/dist/codegen/render.js +273 -0
  16. package/dist/codegen/run-codegen.d.ts +20 -0
  17. package/dist/codegen/run-codegen.js +219 -0
  18. package/dist/codegen/scan-events.d.ts +76 -0
  19. package/dist/codegen/scan-events.js +447 -0
  20. package/dist/codegen/watch.d.ts +33 -0
  21. package/dist/codegen/watch.js +112 -0
  22. package/dist/compose-stacks.d.ts +60 -0
  23. package/dist/compose-stacks.js +127 -0
  24. package/dist/crash-tracker.d.ts +17 -0
  25. package/dist/crash-tracker.js +37 -0
  26. package/dist/create-kumiko-server.d.ts +195 -0
  27. package/dist/create-kumiko-server.js +1040 -0
  28. package/dist/env-schema.d.ts +15 -0
  29. package/dist/env-schema.js +60 -0
  30. package/dist/few-shot-corpus.d.ts +72 -0
  31. package/dist/few-shot-corpus.js +262 -0
  32. package/dist/framework-version.d.ts +1 -0
  33. package/dist/framework-version.js +31 -0
  34. package/dist/index.d.ts +22 -0
  35. package/dist/index.js +33 -0
  36. package/dist/init-deploy-cli.d.ts +10 -0
  37. package/dist/init-deploy-cli.js +111 -0
  38. package/dist/kebab.d.ts +1 -0
  39. package/{src/kebab.ts → dist/kebab.js} +2 -3
  40. package/dist/run-dev-app.d.ts +174 -0
  41. package/dist/run-dev-app.js +403 -0
  42. package/dist/scaffold-app-feature.d.ts +16 -0
  43. package/dist/scaffold-app-feature.js +240 -0
  44. package/dist/scaffold-app.d.ts +45 -0
  45. package/dist/scaffold-app.js +852 -0
  46. package/dist/scaffold-demo-tasks.d.ts +8 -0
  47. package/{src/scaffold-demo-tasks.ts → dist/scaffold-demo-tasks.js} +69 -98
  48. package/dist/scaffold-deploy.d.ts +92 -0
  49. package/dist/scaffold-deploy.js +254 -0
  50. package/dist/scaffold-feature.d.ts +26 -0
  51. package/dist/scaffold-feature.js +163 -0
  52. package/dist/schema-apply.d.ts +11 -0
  53. package/dist/schema-apply.js +95 -0
  54. package/dist/schema-check-core.d.ts +2 -0
  55. package/{src/schema-check-core.ts → dist/schema-check-core.js} +8 -10
  56. package/dist/schema-tables-auth-mode.d.ts +2 -0
  57. package/{src/schema-tables-auth-mode.ts → dist/schema-tables-auth-mode.js} +2 -10
  58. package/dist/schema-tables-minimal.d.ts +2 -0
  59. package/{src/schema-tables-minimal.ts → dist/schema-tables-minimal.js} +2 -11
  60. package/dist/setup-test-stack-from-features.d.ts +11 -0
  61. package/dist/setup-test-stack-from-features.js +42 -0
  62. package/dist/welcome-banner.d.ts +15 -0
  63. package/dist/welcome-banner.js +27 -0
  64. package/package.json +71 -24
  65. package/src/changes.json +6 -0
  66. package/src/__tests__/build-prod-bundle.integration.test.ts +0 -282
  67. package/src/__tests__/build-server-bundle.test.ts +0 -228
  68. package/src/__tests__/classify-change.test.ts +0 -87
  69. package/src/__tests__/compose-stacks.test.ts +0 -273
  70. package/src/__tests__/config-resolver-default.integration.test.ts +0 -165
  71. package/src/__tests__/crash-tracker.test.ts +0 -89
  72. package/src/__tests__/create-kumiko-server-errors.test.ts +0 -54
  73. package/src/__tests__/create-kumiko-server-options.test.ts +0 -33
  74. package/src/__tests__/create-kumiko-server.integration.test.ts +0 -1007
  75. package/src/__tests__/discover-format.test.ts +0 -32
  76. package/src/__tests__/env-schema.integration.test.ts +0 -248
  77. package/src/__tests__/env-schema.test.ts +0 -132
  78. package/src/__tests__/few-shot-corpus.test.ts +0 -316
  79. package/src/__tests__/framework-version.test.ts +0 -45
  80. package/src/__tests__/init-deploy-cli.test.ts +0 -113
  81. package/src/__tests__/kumiko-schema-check.test.ts +0 -56
  82. package/src/__tests__/merge-extra-context.test.ts +0 -67
  83. package/src/__tests__/resolve-stylesheet.test.ts +0 -132
  84. package/src/__tests__/run-dev-app-boot-validation.test.ts +0 -38
  85. package/src/__tests__/run-dev-app.integration.test.ts +0 -290
  86. package/src/__tests__/runtime-classification.test.ts +0 -26
  87. package/src/__tests__/saas-identity-wire.integration.test.ts +0 -427
  88. package/src/__tests__/scaffold-app-feature.test.ts +0 -216
  89. package/src/__tests__/scaffold-app.test.ts +0 -630
  90. package/src/__tests__/scaffold-demo-tasks.test.ts +0 -47
  91. package/src/__tests__/scaffold-deploy.test.ts +0 -464
  92. package/src/__tests__/scaffold-dev-cycle.integration.test.ts +0 -109
  93. package/src/__tests__/scaffold-feature.test.ts +0 -143
  94. package/src/__tests__/schema-apply.integration.test.ts +0 -191
  95. package/src/__tests__/setup-test-stack-from-features.integration.test.ts +0 -30
  96. package/src/__tests__/setup-test-stack-job-run-logger.integration.test.ts +0 -72
  97. package/src/__tests__/walkthrough.integration.test.ts +0 -140
  98. package/src/__tests__/welcome-banner.test.ts +0 -42
  99. package/src/build-server-bundle.ts +0 -346
  100. package/src/build.ts +0 -28
  101. package/src/codegen/__tests__/render-codegen.test.ts +0 -100
  102. package/src/codegen/__tests__/run-codegen.test.ts +0 -665
  103. package/src/codegen/__tests__/strict-mode-diagnostics.test.ts +0 -347
  104. package/src/codegen/__tests__/watch.test.ts +0 -222
  105. package/src/codegen/index.ts +0 -19
  106. package/src/codegen/render.ts +0 -305
  107. package/src/codegen/run-codegen.ts +0 -278
  108. package/src/codegen/scan-events.ts +0 -565
  109. package/src/codegen/watch.ts +0 -140
  110. package/src/compose-stacks.ts +0 -193
  111. package/src/crash-tracker.ts +0 -56
  112. package/src/create-kumiko-server.ts +0 -1397
  113. package/src/env-schema.ts +0 -72
  114. package/src/few-shot-corpus.ts +0 -370
  115. package/src/framework-version.ts +0 -39
  116. package/src/index.ts +0 -105
  117. package/src/init-deploy-cli.ts +0 -148
  118. package/src/run-dev-app.ts +0 -694
  119. package/src/scaffold-app-feature.ts +0 -283
  120. package/src/scaffold-app.ts +0 -1033
  121. package/src/scaffold-deploy.ts +0 -393
  122. package/src/scaffold-feature.ts +0 -226
  123. package/src/schema-apply.ts +0 -123
  124. package/src/setup-test-stack-from-features.ts +0 -80
  125. package/src/welcome-banner.ts +0 -43
@@ -1,305 +0,0 @@
1
- // Renders the three generated files under `<appRoot>/.kumiko/`:
2
- //
3
- // 1. `types.generated.d.ts` — augments `KumikoEventTypeMap` with every
4
- // `r.defineEvent` entry. Pure declarations, no runtime code.
5
- //
6
- // 2. `schemas.generated.ts` — re-exports of inline zod schemas, one
7
- // per `r.defineEvent("name", z.object({...}))` call that wasn't
8
- // already an imported named export. This file is referenced
9
- // EXCLUSIVELY via `import type` (in types.generated.d.ts) — the
10
- // ts-typescript-strip pass elides it at build time, no runtime
11
- // duplication. Only emitted when at least one inline schema exists.
12
- //
13
- // 3. `define.ts` — the local `defineWriteHandler` /
14
- // `defineQueryHandler` wrappers that pin TMap explicitly. THIS is
15
- // where strict mode actually takes effect (see project_x1_typemap_
16
- // findings memory): cross-package generic functions with the
17
- // default TMap do NOT see the augmentation — only a local wrapper
18
- // with an explicit TMap gets it.
19
- //
20
- // All three files are written idempotently — same inputs ⇒ same string.
21
- // The codegen run compares new vs existing content and only writes on
22
- // actual change, so mtime doesn't tick and the TS language server
23
- // doesn't reload every 100ms.
24
-
25
- import { basename, relative } from "node:path";
26
- import type { ScannedEvent } from "./scan-events";
27
- import { rewriteImportPath } from "./scan-events";
28
-
29
- /**
30
- * Start-of-block markers for the two handler-derived sections that
31
- * `run-codegen.ts` may need to carry forward verbatim from a previous
32
- * run (when the current run has no `handlerQns` to render a fresh
33
- * block from). Each marker is always the last thing its renderer
34
- * emits, so a caller can locate it in a previously-written file and
35
- * slice from the marker to EOF to recover the whole block.
36
- */
37
- export const WRITE_HANDLER_QN_MARKER =
38
- "// --- WriteHandlerQn (generated from live registry / feature-manifest.json) ---";
39
- export const TYPED_DISPATCHER_MARKER =
40
- "// --- TypedDispatcher (generated from live registry / feature-manifest.json) ---";
41
-
42
- const HEADER = [
43
- "// =====================================================================",
44
- "// AUTO-GENERATED — DO NOT EDIT BY HAND",
45
- "// Regenerated by `bun run build` (kumiko-build) or by the dev-server's",
46
- "// file-watcher, which runs codegen on every r.defineEvent change.",
47
- "// =====================================================================",
48
- ].join("\n");
49
-
50
- /**
51
- * Render `types.generated.d.ts`. Imports the schema-identifiers as
52
- * type-only — sources can be either named exports of feature-events
53
- * files (kind: "imported") or extracted const-exports of the
54
- * co-generated schemas.generated.ts (kind: "inline"). Result is wired
55
- * via `z.infer<typeof X>` into the augmentation. Empty events list →
56
- * minimal but valid file (still augmentable, just no entries yet —
57
- * useful first-time scaffold).
58
- */
59
- export function renderTypesAugmentation(
60
- events: readonly ScannedEvent[],
61
- outputDirAbs: string,
62
- ): string {
63
- // Group identifiers by their resolved (rewritten) module path so each
64
- // schema file imports once. Multiple events sharing the same events.ts
65
- // file is the common case for the "imported" kind. Inline-events all
66
- // share the same module path: "./schemas.generated".
67
- const importsByPath = new Map<string, Set<string>>();
68
- for (const ev of events) {
69
- if (ev.schemaSource.kind === "imported") {
70
- const rewritten = rewriteImportPath(
71
- ev.schemaSource.schemaModulePath,
72
- ev.featureFilePath,
73
- outputDirAbs,
74
- );
75
- if (!importsByPath.has(rewritten)) importsByPath.set(rewritten, new Set());
76
- importsByPath.get(rewritten)?.add(ev.schemaSource.schemaIdentifier);
77
- } else {
78
- const path = "./schemas.generated";
79
- if (!importsByPath.has(path)) importsByPath.set(path, new Set());
80
- importsByPath.get(path)?.add(ev.schemaSource.generatedConstName);
81
- }
82
- }
83
-
84
- const importLines: string[] = [];
85
- // `z` from zod is needed for `z.infer<typeof X>`; we import it once.
86
- importLines.push(`import type { z } from "zod";`);
87
- // Stable order — sort module paths alphabetically; identifiers within
88
- // a module also alphabetically. Idempotent output.
89
- for (const [modPath, idents] of [...importsByPath.entries()].sort(([a], [b]) =>
90
- a.localeCompare(b),
91
- )) {
92
- const sortedIdents = [...idents].sort();
93
- importLines.push(`import type { ${sortedIdents.join(", ")} } from "${modPath}";`);
94
- }
95
-
96
- const mapEntries = [...events]
97
- .sort((a, b) => a.qualifiedName.localeCompare(b.qualifiedName))
98
- .map((ev) => {
99
- const refName =
100
- ev.schemaSource.kind === "imported"
101
- ? ev.schemaSource.schemaIdentifier
102
- : ev.schemaSource.generatedConstName;
103
- return ` "${ev.qualifiedName}": z.infer<typeof ${refName}>;`;
104
- });
105
-
106
- // Body block — `declare module` in module-form (because we have an
107
- // `export {}` at the end). Module-form makes the augmentation merge
108
- // into the target interface; a script-form (`export {}` removed)
109
- // would REPLACE the module's exports.
110
- const body = [
111
- 'declare module "@cosmicdrift/kumiko-framework/engine" {',
112
- " interface KumikoEventTypeMap {",
113
- ...(mapEntries.length === 0 ? [" // (no r.defineEvent calls discovered yet)"] : mapEntries),
114
- " }",
115
- "}",
116
- "",
117
- "export {};",
118
- "",
119
- ].join("\n");
120
-
121
- return [HEADER, "", ...importLines, "", body].join("\n");
122
- }
123
-
124
- /**
125
- * Render `schemas.generated.ts`. One `export const` per inline-schema
126
- * event, named via the qualifiedName-derived stable identifier. The
127
- * source-text of the original `z.*(...)` expression is replayed — we
128
- * don't try to be cleverer than the zod compiler about reconstructing
129
- * the schema. Returns undefined when no inline-schemas exist (so the
130
- * runner can skip writing the file entirely).
131
- */
132
- export function renderInlineSchemasFile(
133
- events: readonly ScannedEvent[],
134
- appRootAbs: string,
135
- ): string | undefined {
136
- const inlines = events.filter((ev) => ev.schemaSource.kind === "inline");
137
- if (inlines.length === 0) return undefined;
138
-
139
- const lines: string[] = [
140
- HEADER,
141
- "",
142
- "// Schema extracts purely for type inference: this file is referenced",
143
- "// from types.generated.d.ts via `import type`. ts-strip elides it at",
144
- "// build time, so there is NO runtime duplication of the inline schemas",
145
- "// in feature files. When an event schema changes: rebuild (`bun run",
146
- "// build`) or let the dev-server regenerate it — otherwise the z.infer",
147
- "// type drifts from the runtime schema.",
148
- "",
149
- `import { z } from "zod";`,
150
- "",
151
- ];
152
- // Sort by const-name for stable output.
153
- const sorted = [...inlines].sort((a, b) => {
154
- const aName = a.schemaSource.kind === "inline" ? a.schemaSource.generatedConstName : "";
155
- const bName = b.schemaSource.kind === "inline" ? b.schemaSource.generatedConstName : "";
156
- return aName.localeCompare(bName);
157
- });
158
- for (const ev of sorted) {
159
- if (ev.schemaSource.kind !== "inline") continue;
160
- const rel = relative(appRootAbs, ev.featureFilePath).split("\\").join("/");
161
- // Feature files outside the app root (e.g. a bundled dependency) yield a
162
- // `../../..`-walk that clutters the source comment; fall back to the bare
163
- // filename. Comment-only — the generated schema is unaffected.
164
- const sourcePath = rel.startsWith("..") ? basename(ev.featureFilePath) : rel;
165
- lines.push(
166
- `// ${ev.qualifiedName} — from ${sourcePath}:${ev.source.line}`,
167
- `export const ${ev.schemaSource.generatedConstName} = ${ev.schemaSource.schemaSource};`,
168
- "",
169
- );
170
- }
171
- return lines.join("\n");
172
- }
173
-
174
- /**
175
- * Render `define.ts` — local thin wrappers that fix TMap to
176
- * KumikoEventTypeMap. Apps import `defineWriteHandler` /
177
- * `defineQueryHandler` from this file; framework's strict-overload
178
- * becomes the only matching overload because TMap is no longer the
179
- * eager-resolved default.
180
- *
181
- * The wrappers are intentionally *thin* — same signature as the
182
- * framework's, just with TMap pre-bound. Apps stay portable: switch
183
- * the import back to "@cosmicdrift/kumiko-framework/engine" and you're back on the
184
- * loose default. Migration is reversible, no behavioural surface change.
185
- */
186
- export function renderDefineFile(handlerQns: readonly string[] = []): string {
187
- const typedDispatcherBlock =
188
- handlerQns.length > 0
189
- ? [
190
- "",
191
- TYPED_DISPATCHER_MARKER,
192
- `import type { Dispatcher, WriteOpts, WriteResult } from "@cosmicdrift/kumiko-headless";`,
193
- `import type { WriteHandlerQn } from "./types.generated";`,
194
- "",
195
- // Plain `export type { WriteHandlerQn } from "./types.generated"`
196
- // only re-exports — with verbatimModuleSyntax it does NOT bind the
197
- // name locally, so the `TypedDispatcher` reference below would fail
198
- // to resolve. Import above + bare re-export here does both.
199
- `export type { WriteHandlerQn };`,
200
- "",
201
- `/** Dispatcher with write() narrowed to registered handler QNs. */`,
202
- `export type TypedDispatcher = Omit<Dispatcher, "write"> & {`,
203
- ` write<TData = unknown>(`,
204
- ` type: WriteHandlerQn,`,
205
- ` payload: unknown,`,
206
- ` opts?: WriteOpts,`,
207
- ` ): Promise<WriteResult<TData>>;`,
208
- `};`,
209
- "",
210
- `/** Wrap any Dispatcher so write() only accepts registered QNs at compile time. */`,
211
- `export function createTypedDispatcher(dispatcher: Dispatcher): TypedDispatcher {`,
212
- ` return {`,
213
- ` ...dispatcher,`,
214
- ` write: (type, payload, opts) => dispatcher.write(type, payload, opts),`,
215
- ` };`,
216
- `}`,
217
- "",
218
- ].join("\n")
219
- : "";
220
-
221
- const body = [
222
- HEADER,
223
- "",
224
- "// Triple-slash reference pulls the augmentation into this compile-",
225
- "// unit. Belt-and-suspenders against include-glob variations:",
226
- "// - Apps that include `.kumiko/` in tsconfig pick up the .d.ts",
227
- "// transitively; the reference is redundant but harmless.",
228
- "// - Tooling that compiles a narrow file-set (probes, isolated",
229
- "// test programs) typically ignores .d.ts unless explicitly",
230
- "// referenced — without this line, the augmentation is invisible",
231
- "// and `keyof KumikoEventTypeMap` collapses to `never`. Verified",
232
- "// empirically; see strict-mode-diagnostics.test.ts.",
233
- '// NOT a `import "./types.generated"` side-effect — the file is .d.ts',
234
- "// (declarations only), runtime tools (Vitest, Bun, Node) can't load",
235
- "// it. Triple-slash is type-only, fully elided from JS output.",
236
- `/// <reference path="./types.generated.d.ts" />`,
237
- "",
238
- "// Re-export the entire engine surface — apps can switch their imports",
239
- "// from `@cosmicdrift/kumiko-framework/engine` to `./.kumiko/define` with a single",
240
- "// sed-replace, no fine-grained import-splitting needed. The strict",
241
- "// `defineWriteHandler` / `defineQueryHandler` overrides below shadow",
242
- "// the loose framework versions in the local module's export table.",
243
- `export * from "@cosmicdrift/kumiko-framework/engine";`,
244
- "",
245
- `import {`,
246
- ` defineWriteHandler as fwDefineWriteHandler,`,
247
- ` defineQueryHandler as fwDefineQueryHandler,`,
248
- `} from "@cosmicdrift/kumiko-framework/engine";`,
249
- `import type {`,
250
- ` KumikoEventTypeMap,`,
251
- ` WriteHandlerDefinition,`,
252
- ` WriteHandlerInput,`,
253
- ` QueryHandlerDefinition,`,
254
- `} from "@cosmicdrift/kumiko-framework/engine";`,
255
- `import type { ZodType } from "zod";`,
256
- "",
257
- `// Strict defineWriteHandler — TMap fixed to the global`,
258
- `// KumikoEventTypeMap (which the augmentation extends). ctx.appendEvent`,
259
- `// inside the handler resolves K against the FULL augmented map.`,
260
- `export function defineWriteHandler<`,
261
- ` const TName extends string,`,
262
- ` TSchema extends ZodType,`,
263
- ` TData = unknown,`,
264
- `>(`,
265
- ` def: WriteHandlerInput<TName, TSchema, TData, KumikoEventTypeMap>,`,
266
- `): WriteHandlerDefinition<TName, TSchema, TData, KumikoEventTypeMap> {`,
267
- ` return fwDefineWriteHandler<TName, TSchema, TData, KumikoEventTypeMap>(def);`,
268
- `}`,
269
- "",
270
- `export function defineQueryHandler<`,
271
- ` const TName extends string,`,
272
- ` TSchema extends ZodType,`,
273
- ` TResult = unknown,`,
274
- `>(`,
275
- ` def: QueryHandlerDefinition<TName, TSchema, TResult, KumikoEventTypeMap>,`,
276
- `): QueryHandlerDefinition<TName, TSchema, TResult, KumikoEventTypeMap> {`,
277
- ` return fwDefineQueryHandler<TName, TSchema, TResult, KumikoEventTypeMap>(def);`,
278
- `}`,
279
- typedDispatcherBlock,
280
- ].join("\n");
281
-
282
- return body;
283
- }
284
-
285
- /**
286
- * Render `WriteHandlerQn` type lines — exports a union of all registered
287
- * write handler QNs so custom-screen code can type-check dispatcher.write
288
- * calls at compile time:
289
- *
290
- * ```ts
291
- * import type { WriteHandlerQn } from "@app/define";
292
- * dispatcher.write<WriteHandlerQn>("tenant:write:create", payload); // ✓
293
- * dispatcher.write<WriteHandlerQn>("tenant:write:creat", payload); // ✗ TS error
294
- * ```
295
- */
296
- export function renderWriteHandlerTypes(handlerQns: readonly string[]): string {
297
- if (handlerQns.length === 0) return "";
298
-
299
- // Stable order — callers pass registration order (dev-server) or manifest
300
- // order (CLI); bare sort keeps both byte-identical.
301
- const lines = [...handlerQns].sort().map((qn) => ` | "${qn}"`);
302
- return ["", WRITE_HANDLER_QN_MARKER, `export type WriteHandlerQn =`, ...lines, ";", ""].join(
303
- "\n",
304
- );
305
- }
@@ -1,278 +0,0 @@
1
- // runCodegen — top-level entry point. Called by the dev-server (on boot,
2
- // then on every watched file-change) and by `kumiko-build` (before
3
- // bundling).
4
- //
5
- // Lifecycle:
6
- // 1. Scan `<appRoot>/src/**` nach r.defineEvent.
7
- // 2. Render bis zu drei Files unter `<appRoot>/.kumiko/`:
8
- // - types.generated.d.ts (immer wenn Events oder bestehende Datei)
9
- // - schemas.generated.ts (nur wenn ≥1 inline-Schema)
10
- // - define.ts (immer)
11
- // 3. Schreibe nur bei tatsächlicher Änderung — sonst kein touch
12
- // (TS-Sprachserver bleibt cached, Watcher feuert nicht).
13
- // 4. Wenn 0 Events UND noch kein .kumiko/ existiert: bail. Apps die
14
- // `r.defineEvent` nicht nutzen brauchen keinen Wrapper-Pfad und
15
- // kein leeres Verzeichnis.
16
-
17
- import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
18
- import { join } from "node:path";
19
- import {
20
- renderDefineFile,
21
- renderInlineSchemasFile,
22
- renderTypesAugmentation,
23
- renderWriteHandlerTypes,
24
- TYPED_DISPATCHER_MARKER,
25
- WRITE_HANDLER_QN_MARKER,
26
- } from "./render";
27
- import { type ScanWarning, scanEvents } from "./scan-events";
28
-
29
- export type CodegenOptions = {
30
- /** App-Root — `<appRoot>/.kumiko/` ist der Output-Ordner. */
31
- readonly appRoot: string;
32
- /** Optional: alle registrierten Write-Handler-QNs. Wenn nicht gesetzt,
33
- * versucht der Codegen `feature-manifest.json` im appRoot zu lesen.
34
- * Die Dev-Server-Integration übergibt die QNs direkt aus der gebooteten
35
- * Registry — CLI ruft sie aus dem Manifest. */
36
- readonly handlerQns?: readonly string[];
37
- };
38
-
39
- export type CodegenResult = {
40
- readonly outputDir: string;
41
- readonly eventCount: number;
42
- readonly warnings: readonly ScanWarning[];
43
- readonly didWriteTypes: boolean;
44
- readonly didWriteSchemas: boolean;
45
- readonly didWriteDefine: boolean;
46
- readonly skipped: boolean;
47
- };
48
-
49
- export function runCodegen(opts: CodegenOptions): CodegenResult {
50
- const outputDir = join(opts.appRoot, ".kumiko");
51
- const outputExists = existsSync(outputDir);
52
-
53
- const scan = scanEvents({ appRoot: opts.appRoot });
54
-
55
- const typesPath = join(outputDir, "types.generated.d.ts");
56
- const definePath = join(outputDir, "define.ts");
57
- const schemasPath = join(outputDir, "schemas.generated.ts");
58
- const packageJsonPath = join(outputDir, "package.json");
59
-
60
- // Skip-Pfad: keine Events gefunden + keine bestehende Output-Dir
61
- // bedeutet die App nutzt r.defineEvent nicht (oder noch nicht). Kein
62
- // leeres `.kumiko/` zurücklassen — das hilft niemandem und produziert
63
- // false-positives in CI ("eh, was ist denn das hier"). Wenn die Dir
64
- // schon existiert (alter Run), generieren wir trotzdem — ein Refactor
65
- // der den letzten r.defineEvent löscht soll das Output dann auch
66
- // bereinigen, statt eine stale Augmentation liegen zu lassen.
67
- if (scan.events.length === 0 && !outputExists) {
68
- return {
69
- outputDir,
70
- eventCount: 0,
71
- warnings: scan.warnings,
72
- didWriteTypes: false,
73
- didWriteSchemas: false,
74
- didWriteDefine: false,
75
- skipped: true,
76
- };
77
- }
78
-
79
- mkdirSync(outputDir, { recursive: true });
80
-
81
- const typesContent = renderTypesAugmentation(scan.events, outputDir);
82
- // `opts.handlerQns` undefined means the caller (kumiko-build) has no
83
- // live feature registry to draw from and relies on the manifest
84
- // fallback. That fallback can't tell "no handlers exist" apart from
85
- // "the manifest doesn't exist" — both come back as an empty array —
86
- // so an empty result here is a known-lossy read, not authoritative
87
- // data the way run-dev-app's live registry is.
88
- const usingManifestFallback = opts.handlerQns === undefined;
89
- const handlerQns = opts.handlerQns ?? readHandlerQnsFromManifest(opts.appRoot);
90
- const hasHandlerQns = handlerQns.length > 0;
91
- const defineContent = renderDefineFile(handlerQns);
92
- const schemasContent = renderInlineSchemasFile(scan.events, opts.appRoot);
93
- // package.json — turns `.kumiko/` into a real installable package
94
- // named `@app/define`. Apps that declare
95
- // "@app/define": "link:./.kumiko"
96
- // in their package.json get a node_modules symlink that the runtime
97
- // (Node, Vitest, Bun) all resolve via standard module-lookup. Yarn 4
98
- // is required — yarn classic v1 ignored deps in versionless workspaces.
99
- const packageJsonContent = renderKumikoPackageJson();
100
-
101
- // WriteHandlerQn-Union an den types-Content anhängen (optional). Der
102
- // Dev-Server übergibt handlerQns aus der lebenden Registry (genauer);
103
- // der CLI-Fallback liest das feature-manifest.json falls vorhanden.
104
- //
105
- // Preserve only applies to the manifest-fallback path: a caller that
106
- // explicitly passes `handlerQns: []` (the dev-server, when an app
107
- // truly registers zero write handlers) means it — that's real data,
108
- // not a missing-manifest gap, so it clears the block like before.
109
- // Only the manifest fallback coming back empty is ambiguous enough to
110
- // warrant carrying the previous block forward instead of dropping it.
111
- const shouldPreserveStaleBlock = !hasHandlerQns && usingManifestFallback;
112
- const finalTypesContent = shouldPreserveStaleBlock
113
- ? withPreservedBlock(
114
- typesContent,
115
- typesPath,
116
- WRITE_HANDLER_QN_MARKER,
117
- LEGACY_WRITE_HANDLER_QN_ANCHOR,
118
- )
119
- : `${typesContent}${renderWriteHandlerTypes(handlerQns)}`;
120
- const finalDefineContent = shouldPreserveStaleBlock
121
- ? withPreservedBlock(
122
- defineContent,
123
- definePath,
124
- TYPED_DISPATCHER_MARKER,
125
- LEGACY_TYPED_DISPATCHER_ANCHOR,
126
- )
127
- : defineContent;
128
-
129
- const didWriteTypes = writeIfChanged(typesPath, finalTypesContent);
130
- const didWriteDefine = writeIfChanged(definePath, finalDefineContent);
131
- writeIfChanged(packageJsonPath, packageJsonContent);
132
- const didWriteSchemas =
133
- schemasContent !== undefined
134
- ? writeIfChanged(schemasPath, schemasContent)
135
- : removeIfExists(schemasPath);
136
-
137
- const warnings: readonly ScanWarning[] = shouldPreserveStaleBlock
138
- ? [
139
- ...scan.warnings,
140
- {
141
- message:
142
- "No feature-manifest.json found — the WriteHandlerQn/TypedDispatcher block could not be determined from here; run the dev-server to get the exact handler list.",
143
- },
144
- ]
145
- : scan.warnings;
146
-
147
- return {
148
- outputDir,
149
- eventCount: scan.events.length,
150
- warnings,
151
- didWriteTypes,
152
- didWriteSchemas,
153
- didWriteDefine,
154
- skipped: false,
155
- };
156
- }
157
-
158
- /**
159
- * Static package.json content — turns `.kumiko/` into an installable
160
- * package called `@app/define`. The shape never depends on event-scans,
161
- * so we don't bother passing the events in.
162
- *
163
- * Two things to keep stable:
164
- * - `name: "@app/define"` matches what handler imports use.
165
- * - `exports."."` points at the wrapper, `exports."./*"` lets apps
166
- * reach into types.generated etc. via `@app/types.generated`.
167
- */
168
- function renderKumikoPackageJson(): string {
169
- const pkg = {
170
- name: "@app/define",
171
- private: true,
172
- // license: keep the generated package out of unknown-license territory
173
- // for the License-Check guard. The repo is BUSL-1.1-licensed, the generated
174
- // wrapper inherits that — the file just re-exports framework code,
175
- // there's no original IP in `.kumiko/` worth a different license.
176
- license: "BUSL-1.1",
177
- version: "0.0.0",
178
- type: "module",
179
- main: "./define.ts",
180
- types: "./define.ts",
181
- exports: {
182
- ".": "./define.ts",
183
- "./*": "./*",
184
- },
185
- };
186
- return `${JSON.stringify(pkg, null, 2)}\n`;
187
- }
188
-
189
- /**
190
- * Idempotent write — only touches the file when its content actually
191
- * changed. Critical for the dev-server watcher: a no-op codegen pass
192
- * must NOT trigger a full TS-language-server rebuild (which would
193
- * happen on every mtime change).
194
- */
195
- function writeIfChanged(path: string, content: string): boolean {
196
- const existing = readExistingOrUndefined(path);
197
- if (existing === content) return false;
198
- writeFileSync(path, content, "utf-8");
199
- return true;
200
- }
201
-
202
- function readExistingOrUndefined(path: string): string | undefined {
203
- try {
204
- return readFileSync(path, "utf-8");
205
- } catch {
206
- return undefined;
207
- }
208
- }
209
-
210
- // Pre-marker renderer output has no WRITE_HANDLER_QN_MARKER/TYPED_DISPATCHER_MARKER
211
- // line to find — a file generated before this fix still needs to round-trip.
212
- // Each anchor is the first line of its block under the old renderer, so slicing
213
- // from the preceding newline recovers the same block the marker path recovers.
214
- const LEGACY_WRITE_HANDLER_QN_ANCHOR = `export type WriteHandlerQn =`;
215
- const LEGACY_TYPED_DISPATCHER_ANCHOR = `import type { Dispatcher, WriteOpts, WriteResult } from "@cosmicdrift/kumiko-headless";`;
216
-
217
- /**
218
- * Appends whichever handler-derived block a previous run left behind
219
- * in `existingPath`, found via its start-of-block `marker` (or, for a
220
- * file generated before markers existed, `legacyAnchor`). Used when
221
- * the current run has no `handlerQns` of its own — the block can't be
222
- * re-derived, so the only options are "delete it" (the #2757 bug) or
223
- * "leave it exactly as it was". The marker is always emitted as the
224
- * last thing its renderer produces, so slicing from it to EOF recovers
225
- * the whole block regardless of how many times this preserve-path runs
226
- * in a row.
227
- */
228
- function withPreservedBlock(
229
- freshContent: string,
230
- existingPath: string,
231
- marker: string,
232
- legacyAnchor: string,
233
- ): string {
234
- const existing = readExistingOrUndefined(existingPath);
235
- const preserved = extractBlock(existing, marker) ?? extractBlock(existing, legacyAnchor);
236
- return preserved !== undefined ? `${freshContent}${preserved}` : freshContent;
237
- }
238
-
239
- function extractBlock(content: string | undefined, anchor: string): string | undefined {
240
- if (content === undefined) return undefined;
241
- const idx = content.indexOf(`\n${anchor}`);
242
- return idx === -1 ? undefined : content.slice(idx);
243
- }
244
-
245
- /**
246
- * Remove a previously-generated file when the latest scan no longer
247
- * produces it (e.g. the last inline-schema was refactored to a named
248
- * export). Returns true when an actual unlink happened.
249
- */
250
- function removeIfExists(path: string): boolean {
251
- if (!existsSync(path)) return false;
252
- rmSync(path, { force: true });
253
- return true;
254
- }
255
-
256
- /**
257
- * Fallback: liest `feature-manifest.json` aus dem appRoot und extrahiert
258
- * alle Write-Handler-QNs. Fehlende/stale Manifeste sind kein Fehler —
259
- * dann wird schlicht keine `WriteHandlerQn`-Union generiert (CLI ohne
260
- * Manifest oder CI-Setup ohne Manifest-Generator).
261
- */
262
- function readHandlerQnsFromManifest(appRoot: string): readonly string[] {
263
- try {
264
- const manifestPath = join(appRoot, "feature-manifest.json");
265
- const raw = readFileSync(manifestPath, "utf-8");
266
- const manifest = JSON.parse(raw) as {
267
- readonly features: ReadonlyArray<{ readonly writeHandlers?: readonly string[] }>;
268
- };
269
- const qns: string[] = [];
270
- for (const f of manifest.features) {
271
- if (f.writeHandlers) qns.push(...f.writeHandlers);
272
- }
273
- qns.sort();
274
- return qns;
275
- } catch {
276
- return [];
277
- }
278
- }