@cosmicdrift/kumiko-dev-server 0.367.0 → 0.368.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.
- package/README.md +1 -1
- package/bin/kumiko-build.ts +1 -32
- package/dist/cli.d.ts +0 -1
- package/dist/cli.js +0 -1
- package/dist/compose-stacks.js +16 -17
- package/dist/create-kumiko-server.d.ts +1 -1
- package/dist/create-kumiko-server.js +2 -1
- package/dist/index.d.ts +0 -1
- package/dist/index.js +0 -1
- package/dist/run-dev-app.d.ts +1 -1
- package/dist/run-dev-app.js +2 -18
- package/dist/scaffold-agent-docs.d.ts +11 -1
- package/dist/scaffold-agent-docs.js +46 -12
- package/dist/scaffold-app.js +23 -19
- package/dist/scaffold-demo-tasks.js +1 -1
- package/dist/schema-apply.js +1 -1
- package/dist/setup-test-stack-from-features.d.ts +1 -1
- package/dist/setup-test-stack-from-features.js +1 -1
- package/package.json +15 -10
- package/src/changes.json +13 -0
- package/templates/AGENTS.app.md +27 -0
- package/dist/codegen/index.d.ts +0 -4
- package/dist/codegen/index.js +0 -4
- package/dist/codegen/render.d.ts +0 -55
- package/dist/codegen/render.js +0 -273
- package/dist/codegen/run-codegen.d.ts +0 -23
- package/dist/codegen/run-codegen.js +0 -229
- package/dist/codegen/scan-events.d.ts +0 -81
- package/dist/codegen/scan-events.js +0 -447
- package/dist/codegen/watch.d.ts +0 -42
- package/dist/codegen/watch.js +0 -112
package/dist/codegen/render.d.ts
DELETED
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
import type { ScannedEvent } from "./scan-events.js";
|
|
2
|
-
/**
|
|
3
|
-
* Start-of-block markers for the two handler-derived sections that
|
|
4
|
-
* `run-codegen.ts` may need to carry forward verbatim from a previous
|
|
5
|
-
* run (when the current run has no `handlerQns` to render a fresh
|
|
6
|
-
* block from). Each marker is always the last thing its renderer
|
|
7
|
-
* emits, so a caller can locate it in a previously-written file and
|
|
8
|
-
* slice from the marker to EOF to recover the whole block.
|
|
9
|
-
*/
|
|
10
|
-
export declare const WRITE_HANDLER_QN_MARKER = "// --- WriteHandlerQn (generated from live registry / feature-manifest.json) ---";
|
|
11
|
-
export declare const TYPED_DISPATCHER_MARKER = "// --- TypedDispatcher (generated from live registry / feature-manifest.json) ---";
|
|
12
|
-
/**
|
|
13
|
-
* Render `types.generated.d.ts`. Imports the schema-identifiers as
|
|
14
|
-
* type-only — sources can be either named exports of feature-events
|
|
15
|
-
* files (kind: "imported") or extracted const-exports of the
|
|
16
|
-
* co-generated schemas.generated.ts (kind: "inline"). Result is wired
|
|
17
|
-
* via `z.infer<typeof X>` into the augmentation. Empty events list →
|
|
18
|
-
* minimal but valid file (still augmentable, just no entries yet —
|
|
19
|
-
* useful first-time scaffold).
|
|
20
|
-
*/
|
|
21
|
-
export declare function renderTypesAugmentation(events: readonly ScannedEvent[], outputDirAbs: string): string;
|
|
22
|
-
/**
|
|
23
|
-
* Render `schemas.generated.ts`. One `export const` per inline-schema
|
|
24
|
-
* event, named via the qualifiedName-derived stable identifier. The
|
|
25
|
-
* source-text of the original `z.*(...)` expression is replayed — we
|
|
26
|
-
* don't try to be cleverer than the zod compiler about reconstructing
|
|
27
|
-
* the schema. Returns undefined when no inline-schemas exist (so the
|
|
28
|
-
* runner can skip writing the file entirely).
|
|
29
|
-
*/
|
|
30
|
-
export declare function renderInlineSchemasFile(events: readonly ScannedEvent[], appRootAbs: string): string | undefined;
|
|
31
|
-
/**
|
|
32
|
-
* Render `define.ts` — local thin wrappers that fix TMap to
|
|
33
|
-
* KumikoEventTypeMap. Apps import `defineWriteHandler` /
|
|
34
|
-
* `defineQueryHandler` from this file; framework's strict-overload
|
|
35
|
-
* becomes the only matching overload because TMap is no longer the
|
|
36
|
-
* eager-resolved default.
|
|
37
|
-
*
|
|
38
|
-
* The wrappers are intentionally *thin* — same signature as the
|
|
39
|
-
* framework's, just with TMap pre-bound. Apps stay portable: switch
|
|
40
|
-
* the import back to "@cosmicdrift/kumiko-framework/engine" and you're back on the
|
|
41
|
-
* loose default. Migration is reversible, no behavioural surface change.
|
|
42
|
-
*/
|
|
43
|
-
export declare function renderDefineFile(handlerQns?: readonly string[]): string;
|
|
44
|
-
/**
|
|
45
|
-
* Render `WriteHandlerQn` type lines — exports a union of all registered
|
|
46
|
-
* write handler QNs so custom-screen code can type-check dispatcher.write
|
|
47
|
-
* calls at compile time:
|
|
48
|
-
*
|
|
49
|
-
* ```ts
|
|
50
|
-
* import type { WriteHandlerQn } from "@app/define";
|
|
51
|
-
* dispatcher.write<WriteHandlerQn>("tenant:write:create", payload); // ✓
|
|
52
|
-
* dispatcher.write<WriteHandlerQn>("tenant:write:creat", payload); // ✗ TS error
|
|
53
|
-
* ```
|
|
54
|
-
*/
|
|
55
|
-
export declare function renderWriteHandlerTypes(handlerQns: readonly string[]): string;
|
package/dist/codegen/render.js
DELETED
|
@@ -1,273 +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
|
-
import { basename, relative } from "node:path";
|
|
25
|
-
import { rewriteImportPath } from "./scan-events.js";
|
|
26
|
-
/**
|
|
27
|
-
* Start-of-block markers for the two handler-derived sections that
|
|
28
|
-
* `run-codegen.ts` may need to carry forward verbatim from a previous
|
|
29
|
-
* run (when the current run has no `handlerQns` to render a fresh
|
|
30
|
-
* block from). Each marker is always the last thing its renderer
|
|
31
|
-
* emits, so a caller can locate it in a previously-written file and
|
|
32
|
-
* slice from the marker to EOF to recover the whole block.
|
|
33
|
-
*/
|
|
34
|
-
export const WRITE_HANDLER_QN_MARKER = "// --- WriteHandlerQn (generated from live registry / feature-manifest.json) ---";
|
|
35
|
-
export const TYPED_DISPATCHER_MARKER = "// --- TypedDispatcher (generated from live registry / feature-manifest.json) ---";
|
|
36
|
-
const HEADER = [
|
|
37
|
-
"// =====================================================================",
|
|
38
|
-
"// AUTO-GENERATED — DO NOT EDIT BY HAND",
|
|
39
|
-
"// Regenerated by `bun run build` (kumiko-build) or by the dev-server's",
|
|
40
|
-
"// file-watcher, which runs codegen on every r.defineEvent change.",
|
|
41
|
-
"// =====================================================================",
|
|
42
|
-
].join("\n");
|
|
43
|
-
/**
|
|
44
|
-
* Render `types.generated.d.ts`. Imports the schema-identifiers as
|
|
45
|
-
* type-only — sources can be either named exports of feature-events
|
|
46
|
-
* files (kind: "imported") or extracted const-exports of the
|
|
47
|
-
* co-generated schemas.generated.ts (kind: "inline"). Result is wired
|
|
48
|
-
* via `z.infer<typeof X>` into the augmentation. Empty events list →
|
|
49
|
-
* minimal but valid file (still augmentable, just no entries yet —
|
|
50
|
-
* useful first-time scaffold).
|
|
51
|
-
*/
|
|
52
|
-
export function renderTypesAugmentation(events, outputDirAbs) {
|
|
53
|
-
// Group identifiers by their resolved (rewritten) module path so each
|
|
54
|
-
// schema file imports once. Multiple events sharing the same events.ts
|
|
55
|
-
// file is the common case for the "imported" kind. Inline-events all
|
|
56
|
-
// share the same module path: "./schemas.generated".
|
|
57
|
-
const importsByPath = new Map();
|
|
58
|
-
for (const ev of events) {
|
|
59
|
-
if (ev.schemaSource.kind === "imported") {
|
|
60
|
-
const rewritten = rewriteImportPath(ev.schemaSource.schemaModulePath, ev.featureFilePath, outputDirAbs);
|
|
61
|
-
if (!importsByPath.has(rewritten))
|
|
62
|
-
importsByPath.set(rewritten, new Set());
|
|
63
|
-
importsByPath.get(rewritten)?.add(ev.schemaSource.schemaIdentifier);
|
|
64
|
-
}
|
|
65
|
-
else {
|
|
66
|
-
const path = "./schemas.generated";
|
|
67
|
-
if (!importsByPath.has(path))
|
|
68
|
-
importsByPath.set(path, new Set());
|
|
69
|
-
importsByPath.get(path)?.add(ev.schemaSource.generatedConstName);
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
const importLines = [];
|
|
73
|
-
// `z` from zod is needed for `z.infer<typeof X>`; we import it once.
|
|
74
|
-
importLines.push(`import type * as z from "zod";`);
|
|
75
|
-
// Stable order — sort module paths alphabetically; identifiers within
|
|
76
|
-
// a module also alphabetically. Idempotent output.
|
|
77
|
-
for (const [modPath, idents] of [...importsByPath.entries()].sort(([a], [b]) => a.localeCompare(b))) {
|
|
78
|
-
const sortedIdents = [...idents].sort();
|
|
79
|
-
importLines.push(`import type { ${sortedIdents.join(", ")} } from "${modPath}";`);
|
|
80
|
-
}
|
|
81
|
-
const mapEntries = [...events]
|
|
82
|
-
.sort((a, b) => a.qualifiedName.localeCompare(b.qualifiedName))
|
|
83
|
-
.map((ev) => {
|
|
84
|
-
const refName = ev.schemaSource.kind === "imported"
|
|
85
|
-
? ev.schemaSource.schemaIdentifier
|
|
86
|
-
: ev.schemaSource.generatedConstName;
|
|
87
|
-
return ` "${ev.qualifiedName}": z.infer<typeof ${refName}>;`;
|
|
88
|
-
});
|
|
89
|
-
// Body block — `declare module` in module-form (because we have an
|
|
90
|
-
// `export {}` at the end). Module-form makes the augmentation merge
|
|
91
|
-
// into the target interface; a script-form (`export {}` removed)
|
|
92
|
-
// would REPLACE the module's exports.
|
|
93
|
-
const body = [
|
|
94
|
-
'declare module "@cosmicdrift/kumiko-framework/engine" {',
|
|
95
|
-
" interface KumikoEventTypeMap {",
|
|
96
|
-
...(mapEntries.length === 0 ? [" // (no r.defineEvent calls discovered yet)"] : mapEntries),
|
|
97
|
-
" }",
|
|
98
|
-
"}",
|
|
99
|
-
"",
|
|
100
|
-
"export {};",
|
|
101
|
-
"",
|
|
102
|
-
].join("\n");
|
|
103
|
-
return [HEADER, "", ...importLines, "", body].join("\n");
|
|
104
|
-
}
|
|
105
|
-
/**
|
|
106
|
-
* Render `schemas.generated.ts`. One `export const` per inline-schema
|
|
107
|
-
* event, named via the qualifiedName-derived stable identifier. The
|
|
108
|
-
* source-text of the original `z.*(...)` expression is replayed — we
|
|
109
|
-
* don't try to be cleverer than the zod compiler about reconstructing
|
|
110
|
-
* the schema. Returns undefined when no inline-schemas exist (so the
|
|
111
|
-
* runner can skip writing the file entirely).
|
|
112
|
-
*/
|
|
113
|
-
export function renderInlineSchemasFile(events, appRootAbs) {
|
|
114
|
-
const inlines = events.filter((ev) => ev.schemaSource.kind === "inline");
|
|
115
|
-
if (inlines.length === 0)
|
|
116
|
-
return undefined;
|
|
117
|
-
const lines = [
|
|
118
|
-
HEADER,
|
|
119
|
-
"",
|
|
120
|
-
"// Schema extracts purely for type inference: this file is referenced",
|
|
121
|
-
"// from types.generated.d.ts via `import type`. ts-strip elides it at",
|
|
122
|
-
"// build time, so there is NO runtime duplication of the inline schemas",
|
|
123
|
-
"// in feature files. When an event schema changes: rebuild (`bun run",
|
|
124
|
-
"// build`) or let the dev-server regenerate it — otherwise the z.infer",
|
|
125
|
-
"// type drifts from the runtime schema.",
|
|
126
|
-
"",
|
|
127
|
-
`import * as z from "zod";`,
|
|
128
|
-
"",
|
|
129
|
-
];
|
|
130
|
-
// Sort by const-name for stable output.
|
|
131
|
-
const sorted = [...inlines].sort((a, b) => {
|
|
132
|
-
const aName = a.schemaSource.kind === "inline" ? a.schemaSource.generatedConstName : "";
|
|
133
|
-
const bName = b.schemaSource.kind === "inline" ? b.schemaSource.generatedConstName : "";
|
|
134
|
-
return aName.localeCompare(bName);
|
|
135
|
-
});
|
|
136
|
-
for (const ev of sorted) {
|
|
137
|
-
if (ev.schemaSource.kind !== "inline")
|
|
138
|
-
continue;
|
|
139
|
-
const rel = relative(appRootAbs, ev.featureFilePath).split("\\").join("/");
|
|
140
|
-
// Feature files outside the app root (e.g. a bundled dependency) yield a
|
|
141
|
-
// `../../..`-walk that clutters the source comment; fall back to the bare
|
|
142
|
-
// filename. Comment-only — the generated schema is unaffected.
|
|
143
|
-
const sourcePath = rel.startsWith("..") ? basename(ev.featureFilePath) : rel;
|
|
144
|
-
lines.push(`// ${ev.qualifiedName} — from ${sourcePath}:${ev.source.line}`, `export const ${ev.schemaSource.generatedConstName} = ${ev.schemaSource.schemaSource};`, "");
|
|
145
|
-
}
|
|
146
|
-
return lines.join("\n");
|
|
147
|
-
}
|
|
148
|
-
/**
|
|
149
|
-
* Render `define.ts` — local thin wrappers that fix TMap to
|
|
150
|
-
* KumikoEventTypeMap. Apps import `defineWriteHandler` /
|
|
151
|
-
* `defineQueryHandler` from this file; framework's strict-overload
|
|
152
|
-
* becomes the only matching overload because TMap is no longer the
|
|
153
|
-
* eager-resolved default.
|
|
154
|
-
*
|
|
155
|
-
* The wrappers are intentionally *thin* — same signature as the
|
|
156
|
-
* framework's, just with TMap pre-bound. Apps stay portable: switch
|
|
157
|
-
* the import back to "@cosmicdrift/kumiko-framework/engine" and you're back on the
|
|
158
|
-
* loose default. Migration is reversible, no behavioural surface change.
|
|
159
|
-
*/
|
|
160
|
-
export function renderDefineFile(handlerQns = []) {
|
|
161
|
-
const typedDispatcherBlock = handlerQns.length > 0
|
|
162
|
-
? [
|
|
163
|
-
"",
|
|
164
|
-
TYPED_DISPATCHER_MARKER,
|
|
165
|
-
`import type { Dispatcher, WriteOpts, WriteResult } from "@cosmicdrift/kumiko-headless";`,
|
|
166
|
-
`import type { WriteHandlerQn } from "./types.generated";`,
|
|
167
|
-
"",
|
|
168
|
-
// Plain `export type { WriteHandlerQn } from "./types.generated"`
|
|
169
|
-
// only re-exports — with verbatimModuleSyntax it does NOT bind the
|
|
170
|
-
// name locally, so the `TypedDispatcher` reference below would fail
|
|
171
|
-
// to resolve. Import above + bare re-export here does both.
|
|
172
|
-
`export type { WriteHandlerQn };`,
|
|
173
|
-
"",
|
|
174
|
-
`/** Dispatcher with write() narrowed to registered handler QNs. */`,
|
|
175
|
-
`export type TypedDispatcher = Omit<Dispatcher, "write"> & {`,
|
|
176
|
-
` write<TData = unknown>(`,
|
|
177
|
-
` type: WriteHandlerQn,`,
|
|
178
|
-
` payload: unknown,`,
|
|
179
|
-
` opts?: WriteOpts,`,
|
|
180
|
-
` ): Promise<WriteResult<TData>>;`,
|
|
181
|
-
`};`,
|
|
182
|
-
"",
|
|
183
|
-
`/** Wrap any Dispatcher so write() only accepts registered QNs at compile time. */`,
|
|
184
|
-
`export function createTypedDispatcher(dispatcher: Dispatcher): TypedDispatcher {`,
|
|
185
|
-
` return {`,
|
|
186
|
-
` ...dispatcher,`,
|
|
187
|
-
` write: (type, payload, opts) => dispatcher.write(type, payload, opts),`,
|
|
188
|
-
` };`,
|
|
189
|
-
`}`,
|
|
190
|
-
"",
|
|
191
|
-
].join("\n")
|
|
192
|
-
: "";
|
|
193
|
-
const body = [
|
|
194
|
-
HEADER,
|
|
195
|
-
"",
|
|
196
|
-
"// Triple-slash reference pulls the augmentation into this compile-",
|
|
197
|
-
"// unit. Belt-and-suspenders against include-glob variations:",
|
|
198
|
-
"// - Apps that include `.kumiko/` in tsconfig pick up the .d.ts",
|
|
199
|
-
"// transitively; the reference is redundant but harmless.",
|
|
200
|
-
"// - Tooling that compiles a narrow file-set (probes, isolated",
|
|
201
|
-
"// test programs) typically ignores .d.ts unless explicitly",
|
|
202
|
-
"// referenced — without this line, the augmentation is invisible",
|
|
203
|
-
"// and `keyof KumikoEventTypeMap` collapses to `never`. Verified",
|
|
204
|
-
"// empirically; see strict-mode-diagnostics.test.ts.",
|
|
205
|
-
'// NOT a `import "./types.generated"` side-effect — the file is .d.ts',
|
|
206
|
-
"// (declarations only), runtime tools (Vitest, Bun, Node) can't load",
|
|
207
|
-
"// it. Triple-slash is type-only, fully elided from JS output.",
|
|
208
|
-
`/// <reference path="./types.generated.d.ts" />`,
|
|
209
|
-
"",
|
|
210
|
-
"// Re-export the entire engine surface — apps can switch their imports",
|
|
211
|
-
"// from `@cosmicdrift/kumiko-framework/engine` to `./.kumiko/define` with a single",
|
|
212
|
-
"// sed-replace, no fine-grained import-splitting needed. The strict",
|
|
213
|
-
"// `defineWriteHandler` / `defineQueryHandler` overrides below shadow",
|
|
214
|
-
"// the loose framework versions in the local module's export table.",
|
|
215
|
-
`export * from "@cosmicdrift/kumiko-framework/engine";`,
|
|
216
|
-
"",
|
|
217
|
-
`import {`,
|
|
218
|
-
` defineWriteHandler as fwDefineWriteHandler,`,
|
|
219
|
-
` defineQueryHandler as fwDefineQueryHandler,`,
|
|
220
|
-
`} from "@cosmicdrift/kumiko-framework/engine";`,
|
|
221
|
-
`import type {`,
|
|
222
|
-
` KumikoEventTypeMap,`,
|
|
223
|
-
` WriteHandlerDefinition,`,
|
|
224
|
-
` WriteHandlerInput,`,
|
|
225
|
-
` QueryHandlerDefinition,`,
|
|
226
|
-
`} from "@cosmicdrift/kumiko-framework/engine";`,
|
|
227
|
-
`import type { ZodType } from "zod";`,
|
|
228
|
-
"",
|
|
229
|
-
`// Strict defineWriteHandler — TMap fixed to the global`,
|
|
230
|
-
`// KumikoEventTypeMap (which the augmentation extends). ctx.appendEvent`,
|
|
231
|
-
`// inside the handler resolves K against the FULL augmented map.`,
|
|
232
|
-
`export function defineWriteHandler<`,
|
|
233
|
-
` const TName extends string,`,
|
|
234
|
-
` TSchema extends ZodType,`,
|
|
235
|
-
` TData = unknown,`,
|
|
236
|
-
`>(`,
|
|
237
|
-
` def: WriteHandlerInput<TName, TSchema, TData, KumikoEventTypeMap>,`,
|
|
238
|
-
`): WriteHandlerDefinition<TName, TSchema, TData, KumikoEventTypeMap> {`,
|
|
239
|
-
` return fwDefineWriteHandler<TName, TSchema, TData, KumikoEventTypeMap>(def);`,
|
|
240
|
-
`}`,
|
|
241
|
-
"",
|
|
242
|
-
`export function defineQueryHandler<`,
|
|
243
|
-
` const TName extends string,`,
|
|
244
|
-
` TSchema extends ZodType,`,
|
|
245
|
-
` TResult = unknown,`,
|
|
246
|
-
`>(`,
|
|
247
|
-
` def: QueryHandlerDefinition<TName, TSchema, TResult, KumikoEventTypeMap>,`,
|
|
248
|
-
`): QueryHandlerDefinition<TName, TSchema, TResult, KumikoEventTypeMap> {`,
|
|
249
|
-
` return fwDefineQueryHandler<TName, TSchema, TResult, KumikoEventTypeMap>(def);`,
|
|
250
|
-
`}`,
|
|
251
|
-
typedDispatcherBlock,
|
|
252
|
-
].join("\n");
|
|
253
|
-
return body;
|
|
254
|
-
}
|
|
255
|
-
/**
|
|
256
|
-
* Render `WriteHandlerQn` type lines — exports a union of all registered
|
|
257
|
-
* write handler QNs so custom-screen code can type-check dispatcher.write
|
|
258
|
-
* calls at compile time:
|
|
259
|
-
*
|
|
260
|
-
* ```ts
|
|
261
|
-
* import type { WriteHandlerQn } from "@app/define";
|
|
262
|
-
* dispatcher.write<WriteHandlerQn>("tenant:write:create", payload); // ✓
|
|
263
|
-
* dispatcher.write<WriteHandlerQn>("tenant:write:creat", payload); // ✗ TS error
|
|
264
|
-
* ```
|
|
265
|
-
*/
|
|
266
|
-
export function renderWriteHandlerTypes(handlerQns) {
|
|
267
|
-
if (handlerQns.length === 0)
|
|
268
|
-
return "";
|
|
269
|
-
// Stable order — callers pass registration order (dev-server) or manifest
|
|
270
|
-
// order (CLI); bare sort keeps both byte-identical.
|
|
271
|
-
const lines = [...handlerQns].sort().map((qn) => ` | "${qn}"`);
|
|
272
|
-
return ["", WRITE_HANDLER_QN_MARKER, `export type WriteHandlerQn =`, ...lines, ";", ""].join("\n");
|
|
273
|
-
}
|
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import { type ScanWarning } from "./scan-events.js";
|
|
2
|
-
export type CodegenOptions = {
|
|
3
|
-
/** App-Root — `<appRoot>/.kumiko/` ist der Output-Ordner. */
|
|
4
|
-
readonly appRoot: string;
|
|
5
|
-
/** Optional: alle registrierten Write-Handler-QNs. Wenn nicht gesetzt,
|
|
6
|
-
* versucht der Codegen `feature-manifest.json` im appRoot zu lesen.
|
|
7
|
-
* Die Dev-Server-Integration übergibt die QNs direkt aus der gebooteten
|
|
8
|
-
* Registry — CLI ruft sie aus dem Manifest. */
|
|
9
|
-
readonly handlerQns?: readonly string[];
|
|
10
|
-
/** Drift check for CI: nothing is written or removed; the `didWrite*` flags
|
|
11
|
-
* report which files would have changed. */
|
|
12
|
-
readonly checkOnly?: boolean;
|
|
13
|
-
};
|
|
14
|
-
export type CodegenResult = {
|
|
15
|
-
readonly outputDir: string;
|
|
16
|
-
readonly eventCount: number;
|
|
17
|
-
readonly warnings: readonly ScanWarning[];
|
|
18
|
-
readonly didWriteTypes: boolean;
|
|
19
|
-
readonly didWriteSchemas: boolean;
|
|
20
|
-
readonly didWriteDefine: boolean;
|
|
21
|
-
readonly skipped: boolean;
|
|
22
|
-
};
|
|
23
|
-
export declare function runCodegen(opts: CodegenOptions): CodegenResult;
|
|
@@ -1,229 +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
|
-
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
17
|
-
import { join } from "node:path";
|
|
18
|
-
import * as z from "zod";
|
|
19
|
-
import { renderDefineFile, renderInlineSchemasFile, renderTypesAugmentation, renderWriteHandlerTypes, TYPED_DISPATCHER_MARKER, WRITE_HANDLER_QN_MARKER, } from "./render.js";
|
|
20
|
-
import { scanEvents } from "./scan-events.js";
|
|
21
|
-
export function runCodegen(opts) {
|
|
22
|
-
const outputDir = join(opts.appRoot, ".kumiko");
|
|
23
|
-
const outputExists = existsSync(outputDir);
|
|
24
|
-
const scan = scanEvents({ appRoot: opts.appRoot });
|
|
25
|
-
const typesPath = join(outputDir, "types.generated.d.ts");
|
|
26
|
-
const definePath = join(outputDir, "define.ts");
|
|
27
|
-
const schemasPath = join(outputDir, "schemas.generated.ts");
|
|
28
|
-
const packageJsonPath = join(outputDir, "package.json");
|
|
29
|
-
// Skip-Pfad: keine Events gefunden + keine bestehende Output-Dir
|
|
30
|
-
// bedeutet die App nutzt r.defineEvent nicht (oder noch nicht). Kein
|
|
31
|
-
// leeres `.kumiko/` zurücklassen — das hilft niemandem und produziert
|
|
32
|
-
// false-positives in CI ("eh, was ist denn das hier"). Wenn die Dir
|
|
33
|
-
// schon existiert (alter Run), generieren wir trotzdem — ein Refactor
|
|
34
|
-
// der den letzten r.defineEvent löscht soll das Output dann auch
|
|
35
|
-
// bereinigen, statt eine stale Augmentation liegen zu lassen.
|
|
36
|
-
if (scan.events.length === 0 && !outputExists) {
|
|
37
|
-
return {
|
|
38
|
-
outputDir,
|
|
39
|
-
eventCount: 0,
|
|
40
|
-
warnings: scan.warnings,
|
|
41
|
-
didWriteTypes: false,
|
|
42
|
-
didWriteSchemas: false,
|
|
43
|
-
didWriteDefine: false,
|
|
44
|
-
skipped: true,
|
|
45
|
-
};
|
|
46
|
-
}
|
|
47
|
-
const checkOnly = opts.checkOnly === true;
|
|
48
|
-
if (!checkOnly)
|
|
49
|
-
mkdirSync(outputDir, { recursive: true });
|
|
50
|
-
const typesContent = renderTypesAugmentation(scan.events, outputDir);
|
|
51
|
-
// `opts.handlerQns` undefined means the caller (kumiko-build) has no
|
|
52
|
-
// live feature registry to draw from and relies on the manifest
|
|
53
|
-
// fallback. That fallback can't tell "no handlers exist" apart from
|
|
54
|
-
// "the manifest doesn't exist" — both come back as an empty array —
|
|
55
|
-
// so an empty result here is a known-lossy read, not authoritative
|
|
56
|
-
// data the way run-dev-app's live registry is.
|
|
57
|
-
const manifestRead = opts.handlerQns === undefined ? readHandlerQnsFromManifest(opts.appRoot) : undefined;
|
|
58
|
-
const handlerQns = opts.handlerQns ?? (manifestRead?.kind === "ok" ? manifestRead.qns : []);
|
|
59
|
-
const defineContent = renderDefineFile(handlerQns);
|
|
60
|
-
const schemasContent = renderInlineSchemasFile(scan.events, opts.appRoot);
|
|
61
|
-
// package.json — turns `.kumiko/` into a real installable package
|
|
62
|
-
// named `@app/define`. Apps that declare
|
|
63
|
-
// "@app/define": "link:./.kumiko"
|
|
64
|
-
// in their package.json get a node_modules symlink that the runtime
|
|
65
|
-
// (Node, Vitest, Bun) all resolve via standard module-lookup. Yarn 4
|
|
66
|
-
// is required — yarn classic v1 ignored deps in versionless workspaces.
|
|
67
|
-
const packageJsonContent = renderKumikoPackageJson();
|
|
68
|
-
// WriteHandlerQn-Union an den types-Content anhängen (optional). Der
|
|
69
|
-
// Dev-Server übergibt handlerQns aus der lebenden Registry (genauer);
|
|
70
|
-
// der CLI-Fallback liest das feature-manifest.json falls vorhanden.
|
|
71
|
-
//
|
|
72
|
-
// Preserve only applies to the manifest-fallback path: a caller that
|
|
73
|
-
// explicitly passes `handlerQns: []` (the dev-server, when an app
|
|
74
|
-
// truly registers zero write handlers) means it — that's real data,
|
|
75
|
-
// not a missing-manifest gap, so it clears the block like before.
|
|
76
|
-
// Only the manifest fallback coming back empty is ambiguous enough to
|
|
77
|
-
// warrant carrying the previous block forward instead of dropping it.
|
|
78
|
-
// A valid manifest that lists zero handlers is real data and clears the block;
|
|
79
|
-
// only a missing or unreadable manifest is ambiguous.
|
|
80
|
-
const shouldPreserveStaleBlock = manifestRead !== undefined && manifestRead.kind !== "ok";
|
|
81
|
-
const finalTypesContent = shouldPreserveStaleBlock
|
|
82
|
-
? withPreservedBlock(typesContent, typesPath, WRITE_HANDLER_QN_MARKER, LEGACY_WRITE_HANDLER_QN_ANCHOR)
|
|
83
|
-
: `${typesContent}${renderWriteHandlerTypes(handlerQns)}`;
|
|
84
|
-
const finalDefineContent = shouldPreserveStaleBlock
|
|
85
|
-
? withPreservedBlock(defineContent, definePath, TYPED_DISPATCHER_MARKER, LEGACY_TYPED_DISPATCHER_ANCHOR)
|
|
86
|
-
: defineContent;
|
|
87
|
-
const didWriteTypes = writeIfChanged(typesPath, finalTypesContent, checkOnly);
|
|
88
|
-
const didWriteDefine = writeIfChanged(definePath, finalDefineContent, checkOnly);
|
|
89
|
-
writeIfChanged(packageJsonPath, packageJsonContent, checkOnly);
|
|
90
|
-
const didWriteSchemas = schemasContent !== undefined
|
|
91
|
-
? writeIfChanged(schemasPath, schemasContent, checkOnly)
|
|
92
|
-
: removeIfExists(schemasPath, checkOnly);
|
|
93
|
-
const warnings = shouldPreserveStaleBlock
|
|
94
|
-
? [
|
|
95
|
-
...scan.warnings,
|
|
96
|
-
{
|
|
97
|
-
message: manifestRead?.kind === "invalid"
|
|
98
|
-
? `feature-manifest.json invalid: ${manifestRead.reason} — the WriteHandlerQn/TypedDispatcher block could not be determined from here; fix or regenerate the manifest, or run the dev-server.`
|
|
99
|
-
: "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.",
|
|
100
|
-
},
|
|
101
|
-
]
|
|
102
|
-
: scan.warnings;
|
|
103
|
-
return {
|
|
104
|
-
outputDir,
|
|
105
|
-
eventCount: scan.events.length,
|
|
106
|
-
warnings,
|
|
107
|
-
didWriteTypes,
|
|
108
|
-
didWriteSchemas,
|
|
109
|
-
didWriteDefine,
|
|
110
|
-
skipped: false,
|
|
111
|
-
};
|
|
112
|
-
}
|
|
113
|
-
/**
|
|
114
|
-
* Static package.json content — turns `.kumiko/` into an installable
|
|
115
|
-
* package called `@app/define`. The shape never depends on event-scans,
|
|
116
|
-
* so we don't bother passing the events in.
|
|
117
|
-
*
|
|
118
|
-
* Two things to keep stable:
|
|
119
|
-
* - `name: "@app/define"` matches what handler imports use.
|
|
120
|
-
* - `exports."."` points at the wrapper, `exports."./*"` lets apps
|
|
121
|
-
* reach into types.generated etc. via `@app/types.generated`.
|
|
122
|
-
*/
|
|
123
|
-
function renderKumikoPackageJson() {
|
|
124
|
-
const pkg = {
|
|
125
|
-
name: "@app/define",
|
|
126
|
-
private: true,
|
|
127
|
-
// license: keep the generated package out of unknown-license territory
|
|
128
|
-
// for the License-Check guard. The repo is BUSL-1.1-licensed, the generated
|
|
129
|
-
// wrapper inherits that — the file just re-exports framework code,
|
|
130
|
-
// there's no original IP in `.kumiko/` worth a different license.
|
|
131
|
-
license: "BUSL-1.1",
|
|
132
|
-
version: "0.0.0",
|
|
133
|
-
type: "module",
|
|
134
|
-
main: "./define.ts",
|
|
135
|
-
types: "./define.ts",
|
|
136
|
-
exports: {
|
|
137
|
-
".": "./define.ts",
|
|
138
|
-
"./*": "./*",
|
|
139
|
-
},
|
|
140
|
-
};
|
|
141
|
-
return `${JSON.stringify(pkg, null, 2)}\n`;
|
|
142
|
-
}
|
|
143
|
-
/**
|
|
144
|
-
* Idempotent write — only touches the file when its content actually
|
|
145
|
-
* changed. Critical for the dev-server watcher: a no-op codegen pass
|
|
146
|
-
* must NOT trigger a full TS-language-server rebuild (which would
|
|
147
|
-
* happen on every mtime change).
|
|
148
|
-
*/
|
|
149
|
-
function writeIfChanged(path, content, checkOnly) {
|
|
150
|
-
const existing = readExistingOrUndefined(path);
|
|
151
|
-
if (existing === content)
|
|
152
|
-
return false;
|
|
153
|
-
if (!checkOnly)
|
|
154
|
-
writeFileSync(path, content, "utf-8");
|
|
155
|
-
return true;
|
|
156
|
-
}
|
|
157
|
-
function readExistingOrUndefined(path) {
|
|
158
|
-
try {
|
|
159
|
-
return readFileSync(path, "utf-8");
|
|
160
|
-
}
|
|
161
|
-
catch {
|
|
162
|
-
return undefined;
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
// Pre-marker renderer output has no WRITE_HANDLER_QN_MARKER/TYPED_DISPATCHER_MARKER
|
|
166
|
-
// line to find — a file generated before this fix still needs to round-trip.
|
|
167
|
-
// Each anchor is the first line of its block under the old renderer, so slicing
|
|
168
|
-
// from the preceding newline recovers the same block the marker path recovers.
|
|
169
|
-
const LEGACY_WRITE_HANDLER_QN_ANCHOR = `export type WriteHandlerQn =`;
|
|
170
|
-
const LEGACY_TYPED_DISPATCHER_ANCHOR = `import type { Dispatcher, WriteOpts, WriteResult } from "@cosmicdrift/kumiko-headless";`;
|
|
171
|
-
/**
|
|
172
|
-
* Appends whichever handler-derived block a previous run left behind
|
|
173
|
-
* in `existingPath`, found via its start-of-block `marker` (or, for a
|
|
174
|
-
* file generated before markers existed, `legacyAnchor`). Used when
|
|
175
|
-
* the current run has no `handlerQns` of its own — the block can't be
|
|
176
|
-
* re-derived, so the only options are "delete it" (the #2757 bug) or
|
|
177
|
-
* "leave it exactly as it was". The marker is always emitted as the
|
|
178
|
-
* last thing its renderer produces, so slicing from it to EOF recovers
|
|
179
|
-
* the whole block regardless of how many times this preserve-path runs
|
|
180
|
-
* in a row.
|
|
181
|
-
*/
|
|
182
|
-
function withPreservedBlock(freshContent, existingPath, marker, legacyAnchor) {
|
|
183
|
-
const existing = readExistingOrUndefined(existingPath);
|
|
184
|
-
const preserved = extractBlock(existing, marker) ?? extractBlock(existing, legacyAnchor);
|
|
185
|
-
return preserved !== undefined ? `${freshContent}${preserved}` : freshContent;
|
|
186
|
-
}
|
|
187
|
-
function extractBlock(content, anchor) {
|
|
188
|
-
if (content === undefined)
|
|
189
|
-
return undefined;
|
|
190
|
-
const idx = content.indexOf(`\n${anchor}`);
|
|
191
|
-
return idx === -1 ? undefined : content.slice(idx);
|
|
192
|
-
}
|
|
193
|
-
/**
|
|
194
|
-
* Remove a previously-generated file when the latest scan no longer
|
|
195
|
-
* produces it (e.g. the last inline-schema was refactored to a named
|
|
196
|
-
* export). Returns true when an actual unlink happened.
|
|
197
|
-
*/
|
|
198
|
-
function removeIfExists(path, checkOnly) {
|
|
199
|
-
if (!existsSync(path))
|
|
200
|
-
return false;
|
|
201
|
-
if (!checkOnly)
|
|
202
|
-
rmSync(path, { force: true });
|
|
203
|
-
return true;
|
|
204
|
-
}
|
|
205
|
-
const featureManifestSchema = z.object({
|
|
206
|
-
features: z.array(z.object({ writeHandlers: z.array(z.string()).optional() })),
|
|
207
|
-
});
|
|
208
|
-
/**
|
|
209
|
-
* Fallback: reads `feature-manifest.json` from appRoot and extracts all
|
|
210
|
-
* write-handler QNs. A missing manifest is not an error (CLI without a
|
|
211
|
-
* manifest generator); a broken one is reported separately. Either way the
|
|
212
|
-
* existing block is left untouched.
|
|
213
|
-
*/
|
|
214
|
-
function readHandlerQnsFromManifest(appRoot) {
|
|
215
|
-
const manifestPath = join(appRoot, "feature-manifest.json");
|
|
216
|
-
if (!existsSync(manifestPath))
|
|
217
|
-
return { kind: "missing" };
|
|
218
|
-
try {
|
|
219
|
-
const parsed = featureManifestSchema.safeParse(JSON.parse(readFileSync(manifestPath, "utf-8")));
|
|
220
|
-
if (!parsed.success)
|
|
221
|
-
return { kind: "invalid", reason: z.prettifyError(parsed.error) };
|
|
222
|
-
const qns = parsed.data.features.flatMap((f) => f.writeHandlers ?? []);
|
|
223
|
-
qns.sort();
|
|
224
|
-
return { kind: "ok", qns };
|
|
225
|
-
}
|
|
226
|
-
catch (e) {
|
|
227
|
-
return { kind: "invalid", reason: e instanceof Error ? e.message : String(e) };
|
|
228
|
-
}
|
|
229
|
-
}
|
|
@@ -1,81 +0,0 @@
|
|
|
1
|
-
export type ScannedEvent = {
|
|
2
|
-
/** Qualified event-name as it appears in the events table:
|
|
3
|
-
* `<feature>:event:<inner>`. The KumikoEventTypeMap key. */
|
|
4
|
-
readonly qualifiedName: string;
|
|
5
|
-
/** Where the type for this event's payload comes from. Two flavours:
|
|
6
|
-
*
|
|
7
|
-
* { kind: "imported", schemaIdentifier, schemaModulePath }
|
|
8
|
-
* Schema is a named export of another file. Augmentation
|
|
9
|
-
* `import type`-s it from there.
|
|
10
|
-
*
|
|
11
|
-
* { kind: "inline", schemaSource, generatedConstName }
|
|
12
|
-
* Schema was inlined at the call-site. We extract the source
|
|
13
|
-
* text into `schemas.generated.ts` under `generatedConstName`
|
|
14
|
-
* and import-type from there. */
|
|
15
|
-
readonly schemaSource: SchemaSource;
|
|
16
|
-
/** Absolute disk-path of the feature file (for relative-path
|
|
17
|
-
* resolution + diagnostics). */
|
|
18
|
-
readonly featureFilePath: string;
|
|
19
|
-
/** For diagnostics + dedup logging. */
|
|
20
|
-
readonly source: {
|
|
21
|
-
readonly file: string;
|
|
22
|
-
readonly line: number;
|
|
23
|
-
};
|
|
24
|
-
};
|
|
25
|
-
export type SchemaSource = {
|
|
26
|
-
readonly kind: "imported";
|
|
27
|
-
readonly schemaIdentifier: string;
|
|
28
|
-
readonly schemaModulePath: string;
|
|
29
|
-
} | {
|
|
30
|
-
readonly kind: "inline";
|
|
31
|
-
/** zod source text — `z.object({ id: z.string() })` etc. */
|
|
32
|
-
readonly schemaSource: string;
|
|
33
|
-
/** Name we'll generate inside `schemas.generated.ts`. Stable
|
|
34
|
-
* + qualified-name-derived so reorder of features doesn't
|
|
35
|
-
* rename them. */
|
|
36
|
-
readonly generatedConstName: string;
|
|
37
|
-
};
|
|
38
|
-
/** `file` + `line` come as a pair; the location-less variant covers warnings
|
|
39
|
-
* that aren't tied to a scanned source line (e.g. a codegen-level warning
|
|
40
|
-
* about a missing manifest file). */
|
|
41
|
-
export type ScanWarning = {
|
|
42
|
-
readonly file: string;
|
|
43
|
-
readonly line: number;
|
|
44
|
-
readonly message: string;
|
|
45
|
-
} | {
|
|
46
|
-
readonly file?: undefined;
|
|
47
|
-
readonly line?: undefined;
|
|
48
|
-
readonly message: string;
|
|
49
|
-
};
|
|
50
|
-
export type ScanResult = {
|
|
51
|
-
readonly events: readonly ScannedEvent[];
|
|
52
|
-
readonly warnings: readonly ScanWarning[];
|
|
53
|
-
};
|
|
54
|
-
/** Renders a `ScanWarning` for terminal output; omits the location prefix when the warning has no source line. */
|
|
55
|
-
export declare function formatScanWarning(warning: ScanWarning): string;
|
|
56
|
-
export type ScanOptions = {
|
|
57
|
-
/** App-Wurzel — alles unter `<root>/src` wird gescannt. Tests +
|
|
58
|
-
* generated-files (`.kumiko`, `dist*`, `node_modules`) sind raus. */
|
|
59
|
-
readonly appRoot: string;
|
|
60
|
-
};
|
|
61
|
-
/**
|
|
62
|
-
* Scant `appRoot/src/**` nach `r.defineEvent(...)`-Aufrufen und liefert
|
|
63
|
-
* eine deduplizierte Liste aus ScannedEvent. Doppelte qualifiedName
|
|
64
|
-
* landen mit einer Warnung in der Result — Codegen schreibt nur den
|
|
65
|
-
* ERSTEN, sodass das generated File compile-stabil bleibt.
|
|
66
|
-
*/
|
|
67
|
-
export declare function scanEvents(opts: ScanOptions): ScanResult;
|
|
68
|
-
/**
|
|
69
|
-
* Stable identifier-safe rewrite of a qualifiedName like
|
|
70
|
-
* `pubsubOrders:event:order-placed` → `_kg_pubsubOrders__orderPlaced`.
|
|
71
|
-
* Used for the `export const` name in `schemas.generated.ts`. Same
|
|
72
|
-
* transform in scan + render keeps the two sides in sync.
|
|
73
|
-
*/
|
|
74
|
-
export declare function qualifiedNameToConstName(qualifiedName: string): string;
|
|
75
|
-
/**
|
|
76
|
-
* Resolves the relative schema-import path from the feature-file's
|
|
77
|
-
* point-of-view to a path relative to `.kumiko/` (which is where the
|
|
78
|
-
* generated d.ts file lives). Workspace-package specifiers
|
|
79
|
-
* (`@cosmicdrift/kumiko-...`) are returned as-is.
|
|
80
|
-
*/
|
|
81
|
-
export declare function rewriteImportPath(schemaModulePath: string, featureFilePath: string, outputDirAbs: string): string;
|