@cosmicdrift/kumiko-dev-server 1.0.0 → 2.0.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 (66) hide show
  1. package/bin/kumiko-schema-check.ts +7 -0
  2. package/package.json +12 -7
  3. package/src/__tests__/build-prod-bundle.integration.test.ts +1 -1
  4. package/src/__tests__/build-server-bundle.test.ts +62 -0
  5. package/src/__tests__/compose-stacks.test.ts +271 -0
  6. package/src/__tests__/create-kumiko-server-errors.test.ts +54 -0
  7. package/src/__tests__/create-kumiko-server-options.test.ts +33 -0
  8. package/src/__tests__/create-kumiko-server.integration.test.ts +128 -1
  9. package/src/__tests__/discover-format.test.ts +1 -1
  10. package/src/__tests__/env-schema.integration.test.ts +1 -1
  11. package/src/__tests__/few-shot-corpus.test.ts +16 -11
  12. package/src/__tests__/merge-extra-context.test.ts +56 -0
  13. package/src/__tests__/resolve-stylesheet.test.ts +16 -0
  14. package/src/__tests__/saas-identity-wire.integration.test.ts +430 -0
  15. package/src/__tests__/scaffold-app-feature.test.ts +59 -6
  16. package/src/__tests__/scaffold-app.test.ts +34 -2
  17. package/src/__tests__/schema-apply.integration.test.ts +5 -2
  18. package/src/__tests__/setup-test-stack-from-features.integration.test.ts +30 -0
  19. package/src/__tests__/walkthrough.integration.test.ts +22 -6
  20. package/src/build-server-bundle.ts +33 -15
  21. package/src/build.ts +1 -2
  22. package/src/codegen/__tests__/render-codegen.test.ts +2 -1
  23. package/src/codegen/__tests__/run-codegen.test.ts +2 -2
  24. package/src/codegen/__tests__/strict-mode-diagnostics.test.ts +6 -1
  25. package/src/codegen/__tests__/watch.test.ts +1 -2
  26. package/src/codegen/render.ts +6 -1
  27. package/src/codegen/scan-events.ts +7 -5
  28. package/src/codegen/watch.ts +7 -4
  29. package/src/compose-stacks.ts +184 -0
  30. package/src/create-kumiko-server.ts +28 -5
  31. package/src/few-shot-corpus.ts +4 -3
  32. package/src/index.ts +30 -12
  33. package/src/run-dev-app.ts +195 -61
  34. package/src/scaffold-app-feature.ts +118 -15
  35. package/src/scaffold-app.ts +151 -79
  36. package/src/scaffold-demo-tasks.ts +233 -0
  37. package/src/schema-apply.ts +15 -2
  38. package/src/schema-check-core.ts +1 -1
  39. package/src/setup-test-stack-from-features.ts +61 -0
  40. package/src/welcome-banner.ts +1 -4
  41. package/src/__tests__/boot-extra-context.test.ts +0 -140
  42. package/src/__tests__/build-prod-bundle.test.ts +0 -311
  43. package/src/__tests__/cache-headers.test.ts +0 -83
  44. package/src/__tests__/compose-features-wiring.integration.test.ts +0 -382
  45. package/src/__tests__/compose-features.test.ts +0 -129
  46. package/src/__tests__/config-seed-boot.integration.test.ts +0 -158
  47. package/src/__tests__/inject-schema.test.ts +0 -62
  48. package/src/__tests__/renderer-web-css-relocation.integration.test.ts +0 -85
  49. package/src/__tests__/renderer-web-shell-sentinel.test.ts +0 -35
  50. package/src/__tests__/require-env.test.ts +0 -29
  51. package/src/__tests__/resolve-auth-mail.test.ts +0 -69
  52. package/src/__tests__/resolve-tailwind-cli.test.ts +0 -81
  53. package/src/__tests__/run-prod-app-env-source.test.ts +0 -157
  54. package/src/__tests__/run-prod-app-spec.test.ts +0 -57
  55. package/src/__tests__/run-prod-app.integration.test.ts +0 -840
  56. package/src/__tests__/session-wiring.test.ts +0 -51
  57. package/src/__tests__/try-hono-first.test.ts +0 -63
  58. package/src/boot/apply-boot-seeds.ts +0 -18
  59. package/src/build-prod-bundle.ts +0 -697
  60. package/src/compose-features.ts +0 -145
  61. package/src/extra-routes-deps.ts +0 -47
  62. package/src/inject-schema.ts +0 -24
  63. package/src/resolve-tailwind-cli.ts +0 -45
  64. package/src/run-prod-app.ts +0 -1492
  65. package/src/session-wiring.ts +0 -29
  66. package/src/try-hono-first.ts +0 -46
@@ -1,840 +0,0 @@
1
- // runProdApp Integration: bootet die komplette Production-Chain mit
2
- // echtem Postgres + Redis. Beweist:
3
- // - Migration ist idempotent (2× boot mit gleicher DB → kein Crash)
4
- // - Seeds laufen einmal, beim 2. Boot no-op (idempotent-by-design)
5
- // - HTTP-Server antwortet auf /api/health
6
- // - SIGTERM-handler räumt sauber auf
7
- //
8
- // NICHT getestet: Bun.serve über echte TCP-Verbindung — wir treiben
9
- // fetch direkt. Bun.serve-Wiring ist in Production-Coolify selbst
10
- // getestet wenn der Container hochfährt.
11
-
12
- import { afterEach, beforeAll, describe, expect, test } from "bun:test";
13
- import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
14
- import { tmpdir } from "node:os";
15
- import { dirname, join } from "node:path";
16
- import { asRawClient } from "@cosmicdrift/kumiko-framework/bun-db";
17
- import { createDbConnection } from "@cosmicdrift/kumiko-framework/db";
18
- import {
19
- createBooleanField,
20
- createEntity,
21
- createTextField,
22
- defineFeature,
23
- } from "@cosmicdrift/kumiko-framework/engine";
24
- import {
25
- createArchivedStreamsTable,
26
- createEventsTable,
27
- } from "@cosmicdrift/kumiko-framework/event-store";
28
- import {
29
- createEventConsumerStateTable,
30
- createProjectionStateTable,
31
- } from "@cosmicdrift/kumiko-framework/pipeline";
32
- import { unsafeEnsureEntityTable } from "@cosmicdrift/kumiko-framework/stack";
33
- import { Queue } from "bullmq";
34
- import postgres from "postgres";
35
- import { z } from "zod";
36
- import { type ProdAppHandle, runProdApp } from "../run-prod-app";
37
-
38
- // tmp-Verzeichnisse pro Test, in afterEach geräumt. Tests die staticDir
39
- // brauchen registrieren ihren Pfad hier.
40
- const tempDirs: string[] = [];
41
-
42
- async function createTempStaticDir(files: Record<string, string>): Promise<string> {
43
- const dir = await mkdtemp(join(tmpdir(), "kumiko-prod-static-"));
44
- tempDirs.push(dir);
45
- for (const [name, content] of Object.entries(files)) {
46
- const fullPath = join(dir, name);
47
- await mkdir(dirname(fullPath), { recursive: true });
48
- await writeFile(fullPath, content);
49
- }
50
- return dir;
51
- }
52
-
53
- const widgetEntity = createEntity({
54
- fields: {
55
- name: createTextField({ required: true }),
56
- active: createBooleanField({ default: true }),
57
- },
58
- table: "prod_widgets",
59
- });
60
-
61
- const widgetFeature = defineFeature("prod-probe", (r) => {
62
- r.entity("widget", widgetEntity);
63
- // Anonymous query — covers the "anonymousAccess flows from runProdApp
64
- // through createApiEntrypoint to the auth-middleware" wiring that
65
- // earlier silently dropped the option in the entrypoint layer.
66
- r.queryHandler({
67
- name: "ping",
68
- schema: z.object({}),
69
- access: { roles: ["anonymous"] },
70
- handler: async () => ({ pong: true }),
71
- });
72
- // SystemAdmin-gated write — Ziel des extraRoutes.dispatchSystemWrite-
73
- // Tests: Echo von user.tenantId + roles beweist, dass der Dispatch
74
- // durch den echten Dispatcher (Zod + Access-Check) läuft und der
75
- // auto-konstruierte SystemUser den Ziel-Tenant trägt.
76
- r.writeHandler({
77
- name: "probe-write",
78
- schema: z.object({ note: z.string() }),
79
- access: { roles: ["SystemAdmin"] },
80
- handler: async (event) => ({
81
- isSuccess: true as const,
82
- data: { tenantSeen: event.user.tenantId, roles: event.user.roles },
83
- }),
84
- });
85
- // Event + MSP-Paar für den lokalen Event-Dispatcher (2026-06-11):
86
- // runProdApp ist Single-Container — ohne lokalen Dispatcher wendet KEINE
87
- // multiStreamProjection jemals an (Prod hatte deshalb leere Projektionen
88
- // + leere kumiko_event_consumers). Der Write appended das Event; die MSP
89
- // schreibt async in prod_probe_pings — der Test pollt darauf.
90
- const pingedEvent = r.defineEvent("probe-pinged", z.object({ note: z.string() }));
91
- r.writeHandler({
92
- name: "probe-append",
93
- schema: z.object({ aggregateId: z.string(), note: z.string() }),
94
- access: { roles: ["SystemAdmin"] },
95
- handler: async (event, ctx) => {
96
- const payload = event.payload as { aggregateId: string; note: string }; // @cast-boundary engine-payload
97
- // unsafeAppendEvent: das Test-Feature augmentiert keine Event-Type-Map,
98
- // der strict-typed appendEvent narrowt hier auf never.
99
- await ctx.unsafeAppendEvent({
100
- aggregateId: payload.aggregateId,
101
- aggregateType: "probe",
102
- type: pingedEvent.name,
103
- payload: { note: payload.note },
104
- });
105
- return { isSuccess: true as const, data: { ok: true as const } };
106
- },
107
- });
108
- r.multiStreamProjection({
109
- name: "probe-ping-projection",
110
- apply: {
111
- [pingedEvent.name]: async (event, tx) => {
112
- const payload = event.payload as { note: string }; // @cast-boundary engine-payload
113
- await asRawClient(tx).unsafe(
114
- `INSERT INTO prod_probe_pings (aggregate_id, note) VALUES ($1, $2)`,
115
- [event.aggregateId, payload.note],
116
- );
117
- },
118
- },
119
- });
120
- });
121
-
122
- // Worker-lane cron — the lane the data-export job (run-export-jobs) lives on.
123
- // runProdApp must schedule it (single-instance runs both lanes); on the old
124
- // createApiEntrypoint path it was silently never registered → exports hung.
125
- const cronProbeFeature = defineFeature("cron-probe", (r) => {
126
- r.job("worker-lane-cron", { trigger: { cron: "0 0 1 1 *" }, runIn: "worker" }, async () => {});
127
- });
128
-
129
- async function workerLaneSchedulers(prefix: string): Promise<{ name?: string; key?: string }[]> {
130
- const url = new URL(process.env["REDIS_URL"] ?? "redis://localhost:16379");
131
- const queue = new Queue(`${prefix}-worker`, {
132
- connection: { host: url.hostname, port: Number(url.port) },
133
- });
134
- // Read-only: do NOT obliterate — the running all-in-one worker consumes this
135
- // same queue, and deleting its keys mid-flight aborts the worker's blocking
136
- // Redis read with "Connection is closed". The unique prefix isolates the
137
- // leftover scheduler; the test Redis is ephemeral.
138
- try {
139
- return await queue.getJobSchedulers();
140
- } finally {
141
- await queue.close();
142
- }
143
- }
144
-
145
- const TENANT_ID = "00000000-0000-4000-8000-000000000001";
146
-
147
- // Per-suite DB so reboots can be tested without conflicting with other
148
- // test suites. Created in beforeAll, dropped at module end via the admin
149
- // connection.
150
- const TEST_DB = `kumiko_runprod_${Date.now().toString(36)}`;
151
- const ADMIN_URL = process.env["TEST_DATABASE_URL"] ?? "";
152
-
153
- let prodAppHandles: ProdAppHandle[] = [];
154
-
155
- beforeAll(async () => {
156
- if (!ADMIN_URL) throw new Error("TEST_DATABASE_URL must be set");
157
- const adminClient = postgres(ADMIN_URL.replace(/\/[^/]+$/, "/postgres"));
158
- try {
159
- await adminClient.unsafe(`CREATE DATABASE "${TEST_DB}"`);
160
- } finally {
161
- await adminClient.end();
162
- }
163
- });
164
-
165
- afterEach(async () => {
166
- for (const handle of prodAppHandles) {
167
- await handle.stop();
168
- }
169
- prodAppHandles = [];
170
- for (const dir of tempDirs) {
171
- await rm(dir, { recursive: true, force: true });
172
- }
173
- tempDirs.length = 0;
174
- });
175
-
176
- // Production-Apps booten gegen eine VORHER migrierte DB (CI-Step
177
- // `kumiko migrate apply`). In diesem Test gibt's keine drizzle-Migration-
178
- // Files, also imitieren wir den Migration-Step direkt: Framework-Infra-
179
- // Tables + die widget-Entity-Tabelle anlegen, dann runProdApp mit
180
- // `migrations: false` (= kein Schema-Drift-Gate) starten. So bleibt der
181
- // Test fokussiert auf Boot-Wiring (Entrypoint, Hono-Routes, Seeds), ohne
182
- // den Migrationspfad zu duplizieren.
183
- async function migrateTestDb(): Promise<void> {
184
- const url = ADMIN_URL.replace(/\/[^/]+$/, `/${TEST_DB}`);
185
- const { db, close } = createDbConnection(url);
186
- try {
187
- await createEventsTable(db);
188
- await createArchivedStreamsTable(db);
189
- await createProjectionStateTable(db);
190
- await createEventConsumerStateTable(db);
191
- await unsafeEnsureEntityTable(db, widgetEntity, "widget");
192
- await asRawClient(db).unsafe(
193
- `CREATE TABLE IF NOT EXISTS prod_probe_pings (
194
- id BIGSERIAL PRIMARY KEY,
195
- aggregate_id UUID NOT NULL,
196
- note TEXT NOT NULL
197
- )`,
198
- );
199
- } finally {
200
- await close();
201
- }
202
- }
203
-
204
- let testDbMigrated = false;
205
-
206
- async function boot(
207
- seedFn?: (deps: { db: import("@cosmicdrift/kumiko-framework/db").DbConnection }) => Promise<void>,
208
- extra?: Partial<Parameters<typeof runProdApp>[0]>,
209
- ): Promise<ProdAppHandle> {
210
- // Override env per boot to point at the suite's DB.
211
- const originalDbUrl = process.env["DATABASE_URL"];
212
- process.env["DATABASE_URL"] = ADMIN_URL.replace(/\/[^/]+$/, `/${TEST_DB}`);
213
- process.env["REDIS_URL"] = process.env["REDIS_URL"] ?? "redis://localhost:16379";
214
- process.env["JWT_SECRET"] = "test-runprod-secret-32-chars-min!!";
215
- process.env["PORT"] = "0"; // Bun.serve picks an ephemeral port
216
-
217
- if (!testDbMigrated) {
218
- await migrateTestDb();
219
- testDbMigrated = true;
220
- }
221
-
222
- try {
223
- const handle = await runProdApp({
224
- features: [widgetFeature],
225
- autoListen: false,
226
- migrations: false,
227
- ...(seedFn && { seeds: [seedFn] }),
228
- ...(extra ?? {}),
229
- });
230
- prodAppHandles.push(handle);
231
- return handle;
232
- } finally {
233
- if (originalDbUrl !== undefined) process.env["DATABASE_URL"] = originalDbUrl;
234
- else delete process.env["DATABASE_URL"];
235
- }
236
- }
237
-
238
- describe("runProdApp", () => {
239
- test("first boot creates entity tables, /api/health responds", async () => {
240
- const handle = await boot();
241
-
242
- const res = await handle.entrypoint.app.fetch(new Request("http://test/health"));
243
- expect(res.status).toBe(200);
244
- });
245
-
246
- test("second boot against the same DB is idempotent — no crash, no duplicate tables", async () => {
247
- await boot();
248
- // First boot left tables in place. Restart on the same DB —
249
- // unsafeEnsureEntityTable should be a no-op for the existing rows.
250
- const second = await boot();
251
-
252
- const res = await second.entrypoint.app.fetch(new Request("http://test/health"));
253
- expect(res.status).toBe(200);
254
- });
255
-
256
- test("extraRoutes-callback mounts custom HTTP-routes on the Hono-app", async () => {
257
- // Beweist dass die runProdApp.extraRoutes-Option den Hono-app
258
- // bekommt und Routes daran VOR dem static-fallback greifen — das
259
- // ist das Fundament für /feed.xml, /sitemap.xml, /og-image etc.
260
- let extraInvoked = false;
261
- const handle = await boot(undefined, {
262
- extraRoutes: (app, deps) => {
263
- extraInvoked = true;
264
- // deps.db + deps.redis sind die runProdApp-Connections — die
265
- // Route kann gegen die Domain queryen, hier reicht ein simple
266
- // Echo zum Beweis dass wir ans App-Object kommen.
267
- app.get("/feed.xml", (c) => {
268
- const dbAvailable = deps.db !== undefined;
269
- return c.body(`<?xml version="1.0"?><probe ok="${dbAvailable}" />`, 200, {
270
- "content-type": "application/rss+xml",
271
- });
272
- });
273
- },
274
- });
275
-
276
- expect(extraInvoked).toBe(true);
277
-
278
- // handle.fetch durchläuft den static-fallback wrapper — dort liegt
279
- // die "Hono-First, dann Disk"-Logik. entrypoint.app.fetch würde den
280
- // wrapper umgehen und damit die regression nicht erkennen.
281
- const res = await handle.fetch(new Request("http://test/feed.xml"));
282
- expect(res.status).toBe(200);
283
- expect(res.headers.get("content-type")).toBe("application/rss+xml");
284
- const body = await res.text();
285
- expect(body).toContain('<probe ok="true" />');
286
- });
287
-
288
- test("extraRoutes-deps: dispatchSystemWrite schreibt als SystemAdmin des Ziel-Tenants, registry verfügbar", async () => {
289
- // Das ist das Wiring für Provider-Webhook-Routes (billing-foundation
290
- // createSubscriptionWebhookHandler): die Route authentifiziert via
291
- // Provider-Signatur und schreibt dann am JWT-Pfad vorbei durch den
292
- // Command-Dispatcher. Beweist: (a) registry liegt in den deps,
293
- // (b) dispatchSystemWrite geht durch Zod + Access-Check des Handlers,
294
- // (c) der SystemUser trägt den Ziel-Tenant (Event-Store-Konsistenz).
295
- let registryHasProbe = false;
296
- const handle = await boot(undefined, {
297
- extraRoutes: (app, deps) => {
298
- registryHasProbe = deps.registry.features.has("prod-probe");
299
- app.post("/webhook-probe", async (c) => {
300
- const result = await deps.dispatchSystemWrite({
301
- handlerQn: "prod-probe:write:probe-write",
302
- payload: { note: "from-webhook" },
303
- tenantId: TENANT_ID as import("@cosmicdrift/kumiko-framework/engine").TenantId,
304
- });
305
- return c.json(result);
306
- });
307
- },
308
- });
309
-
310
- expect(registryHasProbe).toBe(true);
311
-
312
- const res = await handle.fetch(new Request("http://test/webhook-probe", { method: "POST" }));
313
- expect(res.status).toBe(200);
314
- const body = (await res.json()) as {
315
- isSuccess: boolean;
316
- data?: { tenantSeen: string; roles: string[] };
317
- };
318
- expect(body.isSuccess).toBe(true);
319
- expect(body.data?.tenantSeen).toBe(TENANT_ID);
320
- expect(body.data?.roles).toContain("SystemAdmin");
321
- });
322
-
323
- test("static-fallback: extraRoute beats Disk-File at colliding path (Hono-First)", async () => {
324
- // Regression-Test für den static-fallback-Bug von Phase 2 Step 1:
325
- // wenn ein extraRoute (z.B. /feed.xml) UND eine gleichnamige Disk-
326
- // Datei in staticDir existieren, gewinnt der extraRoute. Sonst
327
- // schluckt der SPA-Fallback unbekannte Pfade als index.html und
328
- // der App-Author wundert sich warum sein /feed.xml nichts macht.
329
- const tmpStaticDir = await createTempStaticDir({
330
- "feed.xml": "<this-is-the-disk-version />",
331
- "index.html": "<html>SPA shell</html>",
332
- });
333
-
334
- const handle = await boot(undefined, {
335
- staticDir: tmpStaticDir,
336
- extraRoutes: (app) => {
337
- app.get("/feed.xml", (c) =>
338
- c.body("<this-is-the-hono-version />", 200, {
339
- "content-type": "application/rss+xml",
340
- }),
341
- );
342
- },
343
- });
344
-
345
- const res = await handle.fetch(new Request("http://test/feed.xml"));
346
- expect(res.status).toBe(200);
347
- expect(await res.text()).toContain("<this-is-the-hono-version />");
348
- });
349
-
350
- test("static-fallback: Disk-File served when no extraRoute matches", async () => {
351
- // Komplement-Test: ohne kollidierenden extraRoute liefert der
352
- // static-fallback die Disk-Datei. Beweist dass der Hono-First-Pfad
353
- // nicht versehentlich Static-Files schluckt.
354
- const tmpStaticDir = await createTempStaticDir({
355
- "robots.txt": "User-agent: *\nAllow: /",
356
- "index.html": "<html>SPA shell</html>",
357
- });
358
-
359
- const handle = await boot(undefined, { staticDir: tmpStaticDir });
360
-
361
- const res = await handle.fetch(new Request("http://test/robots.txt"));
362
- expect(res.status).toBe(200);
363
- expect(await res.text()).toContain("User-agent: *");
364
- expect(res.headers.get("etag")).toBeTruthy();
365
- });
366
-
367
- test("static-fallback: If-None-Match → 304 on disk file", async () => {
368
- const tmpStaticDir = await createTempStaticDir({
369
- "robots.txt": "User-agent: *\nAllow: /",
370
- "index.html": "<html>SPA shell</html>",
371
- });
372
-
373
- const handle = await boot(undefined, { staticDir: tmpStaticDir });
374
- const first = await handle.fetch(new Request("http://test/robots.txt"));
375
- const etag = first.headers.get("etag");
376
- expect(etag).toBeTruthy();
377
-
378
- const second = await handle.fetch(
379
- new Request("http://test/robots.txt", { headers: { "if-none-match": etag ?? "" } }),
380
- );
381
- expect(second.status).toBe(304);
382
- expect(await second.text()).toBe("");
383
- });
384
-
385
- test("static-fallback: If-None-Match → 304 on SPA index.html", async () => {
386
- const tmpStaticDir = await createTempStaticDir({
387
- "index.html": "<html>SPA shell</html>",
388
- });
389
-
390
- const handle = await boot(undefined, { staticDir: tmpStaticDir });
391
- const first = await handle.fetch(new Request("http://test/some/spa/route"));
392
- const etag = first.headers.get("etag");
393
- expect(etag).toBeTruthy();
394
-
395
- const second = await handle.fetch(
396
- new Request("http://test/some/spa/route", {
397
- headers: { "if-none-match": etag ?? "" },
398
- }),
399
- );
400
- expect(second.status).toBe(304);
401
- });
402
-
403
- test("static-fallback: unknown path → SPA-fallback to index.html", async () => {
404
- // Path ohne extraRoute, ohne Disk-File, mit existierendem
405
- // index.html → liefert die SPA-Shell. Standard-SPA-Routing-Pattern,
406
- // aber wir wollen sicher sein dass der Hono-First-Refactor das
407
- // nicht gebrochen hat.
408
- const tmpStaticDir = await createTempStaticDir({
409
- "index.html": "<html>SPA shell</html>",
410
- });
411
-
412
- const handle = await boot(undefined, { staticDir: tmpStaticDir });
413
-
414
- const res = await handle.fetch(new Request("http://test/some/spa/route"));
415
- expect(res.status).toBe(200);
416
- expect(await res.text()).toContain("SPA shell");
417
- });
418
-
419
- test("static-fallback: non-GET ohne Hono-Match → 404, nicht SPA-Shell (#259)", async () => {
420
- // Prod-Szenario: POST auf einen falsch konfigurierten Webhook-Pfad
421
- // (Route nicht gemountet). 200 index.html würde dem Provider
422
- // "delivered" signalisieren — Events gingen still verloren.
423
- const tmpStaticDir = await createTempStaticDir({
424
- "index.html": "<html>SPA shell</html>",
425
- "robots.txt": "User-agent: *\nAllow: /",
426
- });
427
-
428
- const handle = await boot(undefined, { staticDir: tmpStaticDir });
429
-
430
- const unmatched = await handle.fetch(
431
- new Request("http://test/webhooks/subscription/stripe", { method: "POST" }),
432
- );
433
- expect(unmatched.status).toBe(404);
434
-
435
- // Disk-Files werden ebenfalls nicht auf non-GET serviert.
436
- const diskFile = await handle.fetch(new Request("http://test/robots.txt", { method: "POST" }));
437
- expect(diskFile.status).toBe(404);
438
- });
439
-
440
- test("static-fallback: HEAD auf SPA-Route bleibt 200 (spiegelt GET)", async () => {
441
- const tmpStaticDir = await createTempStaticDir({
442
- "index.html": "<html>SPA shell</html>",
443
- });
444
-
445
- const handle = await boot(undefined, { staticDir: tmpStaticDir });
446
-
447
- const res = await handle.fetch(new Request("http://test/some/spa/route", { method: "HEAD" }));
448
- expect(res.status).toBe(200);
449
- });
450
-
451
- test("hostDispatch: per-host html-Datei + Schema-Gating", async () => {
452
- // Multi-App-Deployment: zwei HTML-Dateien für unterschiedliche
453
- // Hosts. Schema wird NUR für admin-Host injected — Public-Host
454
- // bekommt das pure HTML ohne __KUMIKO_SCHEMA__ Tag (Sicherheit).
455
- const tmpStaticDir = await createTempStaticDir({
456
- "index.html": "<html><body>PUBLIC</body><script src=/client.js></script></html>",
457
- "admin.html": "<html><body>ADMIN</body><script src=/client.js></script></html>",
458
- });
459
-
460
- const handle = await boot(undefined, {
461
- staticDir: tmpStaticDir,
462
- hostDispatch: ({ host }) => {
463
- if (host.startsWith("admin.")) {
464
- return { kind: "html", file: "admin.html", injectSchema: true };
465
- }
466
- return { kind: "html", file: "index.html", injectSchema: false };
467
- },
468
- });
469
-
470
- // Public host: index.html, KEIN schema-Tag.
471
- const pubRes = await handle.fetch(
472
- new Request("http://demo.example.test/", { headers: { host: "demo.example.test" } }),
473
- );
474
- expect(pubRes.status).toBe(200);
475
- const pubBody = await pubRes.text();
476
- expect(pubBody).toContain("PUBLIC");
477
- expect(pubBody).not.toContain("__KUMIKO_SCHEMA__");
478
-
479
- // Admin host: admin.html MIT schema-Tag.
480
- const adminRes = await handle.fetch(
481
- new Request("http://admin.example.test/", { headers: { host: "admin.example.test" } }),
482
- );
483
- expect(adminRes.status).toBe(200);
484
- const adminBody = await adminRes.text();
485
- expect(adminBody).toContain("ADMIN");
486
- expect(adminBody).toContain("__KUMIKO_SCHEMA__");
487
- });
488
-
489
- test("hostDispatch: redirect-Modus", async () => {
490
- const tmpStaticDir = await createTempStaticDir({
491
- "index.html": "<html>fallback</html>",
492
- });
493
- const handle = await boot(undefined, {
494
- staticDir: tmpStaticDir,
495
- hostDispatch: ({ host }) =>
496
- host === "apex.example.test"
497
- ? { kind: "redirect", to: "https://target.example", status: 302 }
498
- : { kind: "html", file: "index.html", injectSchema: false },
499
- });
500
-
501
- const res = await handle.fetch(
502
- new Request("http://apex.example.test/", { headers: { host: "apex.example.test" } }),
503
- );
504
- expect(res.status).toBe(302);
505
- expect(res.headers.get("Location")).toBe("https://target.example");
506
- });
507
-
508
- test("hostDispatch: 404-Modus für unbekannte Hosts", async () => {
509
- const tmpStaticDir = await createTempStaticDir({
510
- "index.html": "<html>fallback</html>",
511
- });
512
- const handle = await boot(undefined, {
513
- staticDir: tmpStaticDir,
514
- hostDispatch: ({ host }) =>
515
- host === "known.example.test"
516
- ? { kind: "html", file: "index.html", injectSchema: false }
517
- : { kind: "not-found" },
518
- });
519
-
520
- const res = await handle.fetch(
521
- new Request("http://unknown.example.test/", { headers: { host: "unknown.example.test" } }),
522
- );
523
- expect(res.status).toBe(404);
524
- });
525
-
526
- test("hostDispatch: CSP-Header-Passthrough pro Host", async () => {
527
- const tmpStaticDir = await createTempStaticDir({
528
- "index.html": "<html>x</html>",
529
- });
530
- const csp = "default-src 'self'; script-src 'self'";
531
- const handle = await boot(undefined, {
532
- staticDir: tmpStaticDir,
533
- hostDispatch: () => ({ kind: "html", file: "index.html", injectSchema: false, csp }),
534
- });
535
-
536
- const res = await handle.fetch(new Request("http://x.example.test/"));
537
- expect(res.status).toBe(200);
538
- expect(res.headers.get("content-security-policy")).toBe(csp);
539
- });
540
-
541
- test("hostDispatch: assets bleiben host-unabhängig erreichbar", async () => {
542
- // /assets/* darf NICHT durch hostDispatch laufen — Bundles werden
543
- // vom client per absoluter URL nachgeladen, host-Sniffing wäre falsch.
544
- const tmpStaticDir = await createTempStaticDir({
545
- "index.html": "<html>x</html>",
546
- "assets/app-abc.js": "console.log('app');",
547
- });
548
- const handle = await boot(undefined, {
549
- staticDir: tmpStaticDir,
550
- hostDispatch: () => ({ kind: "not-found" }),
551
- });
552
-
553
- const res = await handle.fetch(new Request("http://x.example.test/assets/app-abc.js"));
554
- expect(res.status).toBe(200);
555
- expect(await res.text()).toContain("console.log('app')");
556
- });
557
-
558
- test("anonymousAccess flows from runProdApp through entrypoint into the auth-middleware", async () => {
559
- // Regression for the silent-drop bug: ApiEntrypointOptions had no
560
- // anonymousAccess field, so runProdApp's option went into createApi
561
- // Entrypoint's spread, vanished, and the auth-middleware never saw
562
- // it → 401 missing_token even on `roles: ["anonymous"]` handlers.
563
- const handle = await boot(undefined, {
564
- anonymousAccess: { defaultTenantId: TENANT_ID },
565
- });
566
-
567
- const res = await handle.entrypoint.app.fetch(
568
- new Request("http://test/api/query", {
569
- method: "POST",
570
- headers: { "content-type": "application/json" },
571
- body: JSON.stringify({
572
- type: "prod-probe:query:ping",
573
- payload: {},
574
- }),
575
- }),
576
- );
577
- expect(res.status).toBe(200);
578
- const body = (await res.json()) as { data?: { pong?: boolean } };
579
- expect(body.data?.pong).toBe(true);
580
- });
581
-
582
- test("anonymousAccess as factory: receives {db, redis, registry}, resolver closures over db", async () => {
583
- // Use case: tenantResolver looks up subdomain → tenantId in the DB
584
- // at request time. The factory is called once at boot with db
585
- // wired, the resolver inside captures it.
586
- const seenDeps: { db: boolean; redis: boolean; registry: boolean } = {
587
- db: false,
588
- redis: false,
589
- registry: false,
590
- };
591
-
592
- const handle = await boot(undefined, {
593
- anonymousAccess: ({ db, redis, registry }) => {
594
- seenDeps.db = db !== undefined;
595
- seenDeps.redis = redis !== undefined;
596
- seenDeps.registry = registry !== undefined;
597
- return { defaultTenantId: TENANT_ID };
598
- },
599
- });
600
-
601
- expect(seenDeps).toEqual({ db: true, redis: true, registry: true });
602
-
603
- const res = await handle.entrypoint.app.fetch(
604
- new Request("http://test/api/query", {
605
- method: "POST",
606
- headers: { "content-type": "application/json" },
607
- body: JSON.stringify({ type: "prod-probe:query:ping", payload: {} }),
608
- }),
609
- );
610
- expect(res.status).toBe(200);
611
- });
612
-
613
- test("extraContext as factory: factory called with {db, redis, registry} at boot", async () => {
614
- // Factory-form for extraContext closes over db like anonymousAccess.
615
- // In auth-mode the framework auto-sets configResolver; Factory-Result
616
- // wird drauf gemerged. Wichtig: Factory wird genau einmal aufgerufen
617
- // beim Boot, NACHDEM db/redis/registry konstruiert sind.
618
- let invocations = 0;
619
- let factoryDeps: { db: boolean; redis: boolean; registry: boolean } | null = null;
620
-
621
- const handle = await boot(undefined, {
622
- extraContext: ({ db, redis, registry }) => {
623
- invocations++;
624
- factoryDeps = {
625
- db: db !== undefined,
626
- redis: redis !== undefined,
627
- registry: registry !== undefined,
628
- };
629
- return { _appCustomKey: "from-factory" };
630
- },
631
- });
632
-
633
- expect(invocations).toBe(1);
634
- expect(factoryDeps!).toEqual({ db: true, redis: true, registry: true });
635
- // Smoke: handle is functional (boot completed without error).
636
- expect(handle.entrypoint).toBeDefined();
637
- });
638
-
639
- test("seed runs once on first boot, but the seed's own idempotence prevents duplication on reboot", async () => {
640
- let seedInvocations = 0;
641
- let inserted = false;
642
-
643
- const seed = async ({
644
- db,
645
- }: {
646
- db: import("@cosmicdrift/kumiko-framework/db").DbConnection;
647
- }) => {
648
- seedInvocations++;
649
- // Seed-side idempotence: check before inserting. runProdApp doesn't
650
- // gate seeds — the seed itself is responsible.
651
- const existing = await asRawClient(db).unsafe(`SELECT 1 FROM prod_widgets LIMIT 1`);
652
- if ((existing as Array<Record<string, unknown>>).length > 0) return;
653
- await asRawClient(db).unsafe(`INSERT INTO prod_widgets (id, tenant_id, name) VALUES
654
- (gen_random_uuid(), '00000000-0000-4000-8000-000000000001', 'seeded')`);
655
- inserted = true;
656
- };
657
-
658
- await boot(seed);
659
- expect(seedInvocations).toBe(1);
660
- expect(inserted).toBe(true);
661
-
662
- await boot(seed);
663
- // Seed function was called both times (runProdApp doesn't track),
664
- // but the seed's own check kept it from inserting again.
665
- expect(seedInvocations).toBe(2);
666
-
667
- // Probe DB — exactly one row.
668
- const second = prodAppHandles[1];
669
- if (!second) throw new Error("expected second handle");
670
- // Use the entrypoint's DB context to query (clean shutdown handles
671
- // the connection lifecycle).
672
- const ctx = second.entrypoint as unknown as { app: { fetch: typeof fetch } };
673
- const res = await ctx.app.fetch(new Request("http://test/health"));
674
- expect(res.status).toBe(200);
675
- });
676
-
677
- test("Hard Boot-Gate: pending kumiko-Migration → SchemaDriftError, kein Boot", async () => {
678
- // Synthetisches kumiko/migrations-Dir mit einer checked-in Migration die
679
- // nie applied wurde (kein _kumiko_migrations-Eintrag). runProdApp soll mit
680
- // SchemaDriftError abbrechen bevor irgendetwas anderes initialisiert wird.
681
- const driftDir = await mkdtemp(join(tmpdir(), "kumiko-drift-boot-"));
682
- tempDirs.push(driftDir);
683
- await writeFile(
684
- join(driftDir, "0001_pending.sql"),
685
- `CREATE TABLE "never_created_table" ("id" uuid PRIMARY KEY);`,
686
- );
687
- await writeFile(
688
- join(driftDir, ".snapshot.json"),
689
- JSON.stringify({
690
- version: 1,
691
- tables: [{ tableName: "never_created_table", columns: [] }],
692
- }),
693
- );
694
-
695
- await expect(boot(undefined, { migrations: { dir: driftDir } })).rejects.toThrow(
696
- /Schema drift detected/,
697
- );
698
- });
699
- });
700
-
701
- describe("runProdApp: lokaler Event-Dispatcher (MSP-Anwendung im Single-Container)", () => {
702
- // Regression für den 2026-06-11-Incident: runProdApp baute den
703
- // Event-Dispatcher nie ({disabled:true} im API-Entrypoint) — jede
704
- // multiStreamProjection blieb in Prod unangewendet, kumiko_event_consumers
705
- // blieb leer. Der Test schreibt über den ECHTEN Boot-Pfad und pollt auf
706
- // die async projizierte Row.
707
- async function pollFor<T>(probe: () => Promise<T | undefined>, timeoutMs = 8000): Promise<T> {
708
- const deadline = Date.now() + timeoutMs;
709
- for (;;) {
710
- const result = await probe();
711
- if (result !== undefined) return result;
712
- if (Date.now() > deadline) throw new Error("pollFor: timeout");
713
- await new Promise((resolve) => setTimeout(resolve, 100));
714
- }
715
- }
716
-
717
- test("Write → appendEvent → MSP wendet async an; Consumer-Cursor wandert", async () => {
718
- let dispatchSystemWrite: import("../extra-routes-deps").ExtraRoutesSystemDeps["dispatchSystemWrite"];
719
- const handle = await boot(undefined, {
720
- eventDispatcher: { pollIntervalMs: 50 },
721
- extraRoutes: (_app, deps) => {
722
- dispatchSystemWrite = deps.dispatchSystemWrite;
723
- },
724
- });
725
-
726
- // Default-Boot baut den lokalen Dispatcher und start() hat ihn gestartet.
727
- expect(handle.entrypoint.eventDispatcher).toBeDefined();
728
-
729
- const aggregateId = crypto.randomUUID();
730
- const result = await dispatchSystemWrite!({
731
- handlerQn: "prod-probe:write:probe-append",
732
- payload: { aggregateId, note: "dispatched" },
733
- tenantId: TENANT_ID as import("@cosmicdrift/kumiko-framework/engine").TenantId,
734
- });
735
- expect(result.isSuccess).toBe(true);
736
-
737
- const url = ADMIN_URL.replace(/\/[^/]+$/, `/${TEST_DB}`);
738
- const { db, close } = createDbConnection(url);
739
- try {
740
- const row = await pollFor(async () => {
741
- const rows = (await asRawClient(db).unsafe(
742
- `SELECT note FROM prod_probe_pings WHERE aggregate_id = $1`,
743
- [aggregateId],
744
- )) as Array<{ note: string }>;
745
- return rows[0];
746
- });
747
- expect(row.note).toBe("dispatched");
748
-
749
- // Consumer-Registrierung + Cursor-Fortschritt — in Prod war diese
750
- // Tabelle komplett leer, DER Beweis dass nie ein Dispatcher lief.
751
- const consumers = (await asRawClient(db).unsafe(
752
- `SELECT name, last_processed_event_id FROM kumiko_event_consumers
753
- WHERE name = 'prod-probe:projection:probe-ping-projection'
754
- OR name LIKE '%probe-ping-projection%'`,
755
- )) as Array<{ name: string; last_processed_event_id: string | number }>;
756
- expect(consumers.length).toBeGreaterThan(0);
757
- expect(Number(consumers[0]?.last_processed_event_id)).toBeGreaterThan(0);
758
- } finally {
759
- await close();
760
- }
761
- });
762
-
763
- test("eventDispatcher.disabled: kein lokaler Dispatcher gebaut", async () => {
764
- const handle = await boot(undefined, {
765
- eventDispatcher: { disabled: true },
766
- });
767
- expect(handle.entrypoint.eventDispatcher).toBeUndefined();
768
- });
769
- });
770
-
771
- // Origin-guard config (framework #340) flows from runProdApp's auth options
772
- // through to buildServer. Before the forwarding fix, RunProdAppAuthOptions had
773
- // no `allowedOrigins`, so a cookieDomain app could not satisfy the fail-closed
774
- // guard — it could only CrashLoop.
775
- describe("runProdApp — auth allowedOrigins forwarding", () => {
776
- const ADMIN = {
777
- email: "origin-guard@example.eu",
778
- password: "test-pw-strong-1234",
779
- displayName: "Admin",
780
- memberships: [],
781
- };
782
-
783
- test("cookieDomain without allowedOrigins fails closed — guard is wired through runProdApp", async () => {
784
- await expect(
785
- boot(undefined, { auth: { admin: ADMIN, cookieDomain: "example.eu" } }),
786
- ).rejects.toThrow(/allowedOrigins is empty/);
787
- });
788
-
789
- test("cookieDomain + allowedOrigins clears the guard — allowlist reaches buildServer", async () => {
790
- // Without the forwarding fix this would ALSO throw /allowedOrigins is empty/.
791
- // It may still fail later on the minimal harness (no auth tables migrated),
792
- // but never on the origin guard — that is the forwarding proof.
793
- let bootError: unknown;
794
- try {
795
- const handle = await boot(undefined, {
796
- auth: {
797
- admin: ADMIN,
798
- cookieDomain: "example.eu",
799
- allowedOrigins: ["https://app.example.eu"],
800
- },
801
- });
802
- expect(handle).toBeDefined();
803
- } catch (error) {
804
- bootError = error;
805
- }
806
- if (bootError !== undefined) {
807
- expect(String(bootError)).not.toMatch(/allowedOrigins is empty/);
808
- }
809
- });
810
- });
811
-
812
- describe("runProdApp job-lane wiring (runSingleInstance)", () => {
813
- // Red-then-green for the export bug: on createApiEntrypoint (old default) the
814
- // worker-lane cron was never registered. createAllInOneEntrypoint (new
815
- // single-instance default) runs two runners, so it IS registered.
816
- test("default single-instance schedules the WORKER-lane cron", async () => {
817
- const prefix = `test-rsi-${Date.now().toString(36)}`;
818
- const handle = await boot(undefined, {
819
- features: [cronProbeFeature],
820
- jobs: { queueNamePrefix: prefix },
821
- });
822
- expect(handle.entrypoint.mode).toBe("all-in-one");
823
- const schedulers = await workerLaneSchedulers(prefix);
824
- expect(schedulers.some((s) => (s.name ?? s.key ?? "").includes("worker-lane-cron"))).toBe(true);
825
- });
826
-
827
- test("runSingleInstance:false → api-only, worker lane left to a dedicated worker", async () => {
828
- const prefix = `test-rsi-api-${Date.now().toString(36)}`;
829
- const handle = await boot(undefined, {
830
- features: [cronProbeFeature],
831
- jobs: { queueNamePrefix: prefix },
832
- runSingleInstance: false,
833
- });
834
- expect(handle.entrypoint.mode).toBe("api");
835
- const schedulers = await workerLaneSchedulers(prefix);
836
- expect(schedulers.some((s) => (s.name ?? s.key ?? "").includes("worker-lane-cron"))).toBe(
837
- false,
838
- );
839
- });
840
- });