@cosmicdrift/kumiko-server-runtime 0.329.0 → 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.
- package/README.md +15 -0
- package/dist/boot/apply-boot-seeds.d.ts +8 -0
- package/{src/boot/apply-boot-seeds.ts → dist/boot/apply-boot-seeds.js} +2 -10
- package/dist/boot/boot-crypto.d.ts +9 -0
- package/dist/boot/boot-crypto.js +39 -0
- package/dist/boot/job-run-logger.d.ts +19 -0
- package/dist/boot/job-run-logger.js +44 -0
- package/dist/boot/pii-event-backfill-on-boot.d.ts +13 -0
- package/dist/boot/pii-event-backfill-on-boot.js +25 -0
- package/dist/build-prod-bundle.d.ts +103 -0
- package/dist/build-prod-bundle.js +751 -0
- package/dist/bun-serve-options.d.ts +32 -0
- package/dist/bun-serve-options.js +49 -0
- package/dist/compose-features.d.ts +31 -0
- package/dist/compose-features.js +124 -0
- package/dist/extra-routes-deps.d.ts +30 -0
- package/dist/extra-routes-deps.js +4 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +7 -0
- package/dist/pii-boot-gate.d.ts +13 -0
- package/dist/pii-boot-gate.js +46 -0
- package/dist/renderer-web-fonts.d.ts +9 -0
- package/{src/renderer-web-fonts.ts → dist/renderer-web-fonts.js} +14 -18
- package/dist/resolve-tailwind-cli.d.ts +14 -0
- package/dist/resolve-tailwind-cli.js +36 -0
- package/dist/run-prod-app-boot-context.d.ts +43 -0
- package/dist/run-prod-app-boot-context.js +198 -0
- package/dist/run-prod-app-static-files.d.ts +32 -0
- package/dist/run-prod-app-static-files.js +280 -0
- package/dist/run-prod-app.d.ts +471 -0
- package/dist/run-prod-app.js +741 -0
- package/dist/run-worker-app.d.ts +92 -0
- package/dist/run-worker-app.js +220 -0
- package/dist/security-headers.d.ts +20 -0
- package/dist/security-headers.js +49 -0
- package/dist/session-boot-gate.d.ts +11 -0
- package/dist/session-boot-gate.js +22 -0
- package/dist/session-wiring.d.ts +11 -0
- package/{src/session-wiring.ts → dist/session-wiring.js} +2 -6
- package/dist/try-hono-first.d.ts +24 -0
- package/{src/try-hono-first.ts → dist/try-hono-first.js} +8 -36
- package/package.json +102 -36
- package/src/changes.json +6 -0
- package/src/__tests__/boot-extra-context.test.ts +0 -163
- package/src/__tests__/boot-probe-fixture.ts +0 -64
- package/src/__tests__/build-prod-bundle.inprocess.test.ts +0 -233
- package/src/__tests__/build-prod-bundle.test.ts +0 -724
- package/src/__tests__/cache-headers.test.ts +0 -83
- package/src/__tests__/compose-features-mfa-wiring.integration.test.ts +0 -308
- package/src/__tests__/compose-features-wiring.integration.test.ts +0 -609
- package/src/__tests__/compose-features.test.ts +0 -206
- package/src/__tests__/config-seed-boot.integration.test.ts +0 -158
- package/src/__tests__/pii-boot-gate.test.ts +0 -112
- package/src/__tests__/renderer-web-css-relocation.integration.test.ts +0 -85
- package/src/__tests__/renderer-web-shell-sentinel.test.ts +0 -35
- package/src/__tests__/renderer-web-theme-plugin.integration.test.ts +0 -77
- package/src/__tests__/require-env.test.ts +0 -34
- package/src/__tests__/resolve-auth-mail.test.ts +0 -144
- package/src/__tests__/resolve-tailwind-cli.test.ts +0 -81
- package/src/__tests__/run-prod-app-dry-run.test.ts +0 -135
- package/src/__tests__/run-prod-app-env-source.test.ts +0 -118
- package/src/__tests__/run-prod-app-kms-slots.test.ts +0 -108
- package/src/__tests__/run-prod-app-spec.test.ts +0 -167
- package/src/__tests__/run-prod-app-static-files.test.ts +0 -298
- package/src/__tests__/run-prod-app.integration.test.ts +0 -1525
- package/src/__tests__/run-worker-app-boot.test.ts +0 -183
- package/src/__tests__/run-worker-app.integration.test.ts +0 -218
- package/src/__tests__/security-headers.test.ts +0 -88
- package/src/__tests__/session-boot-gate.test.ts +0 -70
- package/src/__tests__/session-wiring.test.ts +0 -16
- package/src/__tests__/try-hono-first.test.ts +0 -108
- package/src/__tests__/websocket-route.integration.test.ts +0 -695
- package/src/boot/__tests__/job-run-logger.integration.test.ts +0 -262
- package/src/boot/__tests__/job-run-logger.test.ts +0 -26
- package/src/boot/boot-crypto.ts +0 -67
- package/src/boot/job-run-logger.ts +0 -63
- package/src/boot/pii-event-backfill-on-boot.ts +0 -43
- package/src/build-prod-bundle.ts +0 -996
- package/src/bun-serve-options.ts +0 -110
- package/src/compose-features.ts +0 -197
- package/src/extra-routes-deps.ts +0 -38
- package/src/index.ts +0 -27
- package/src/pii-boot-gate.ts +0 -80
- package/src/resolve-tailwind-cli.ts +0 -45
- package/src/run-prod-app-boot-context.ts +0 -319
- package/src/run-prod-app-static-files.ts +0 -359
- package/src/run-prod-app.ts +0 -1420
- package/src/run-worker-app.ts +0 -366
- package/src/security-headers.ts +0 -67
- package/src/session-boot-gate.ts +0 -34
|
@@ -0,0 +1,751 @@
|
|
|
1
|
+
// buildProdBundle — Production-Build für Kumiko-Apps. Ein generischer
|
|
2
|
+
// Build-Step ohne App-spezifisches Wissen: Convention-Discovery liest
|
|
3
|
+
// die App-Struktur, Bun.build + Tailwind + Public-Folder-Copy
|
|
4
|
+
// produzieren ein deploybares dist/.
|
|
5
|
+
//
|
|
6
|
+
// Client entries (fw#2320 — explicit, no filename inference):
|
|
7
|
+
//
|
|
8
|
+
// package.json "kumiko.clientEntries": [{ name, sourceFile, htmlPath? }]
|
|
9
|
+
// → one Bun.build bundle per declared entry
|
|
10
|
+
// package.json "kumiko.clientEntry": "./src/…"
|
|
11
|
+
// → single bundle, name "client"
|
|
12
|
+
// (neither declared) → convention: src/client.tsx | src/client.ts
|
|
13
|
+
//
|
|
14
|
+
// Convention for everything else (all optional, missing → skipped):
|
|
15
|
+
//
|
|
16
|
+
// src/styles.css → Tailwind one-shot
|
|
17
|
+
// (oder fallback auf @cosmicdrift/kumiko-renderer-web/styles.css
|
|
18
|
+
// wenn nur clientEntry da ist und kein eigenes CSS)
|
|
19
|
+
// public/ → rsync 1:1 (kein Hash — User-bewusste URLs)
|
|
20
|
+
// public/index.html | index.html → Template, Placeholder-Tags ersetzt:
|
|
21
|
+
// <script type="module" src="/client.js"> → /assets/client-<hash>.js
|
|
22
|
+
// <link href="/styles.css"> → /assets/styles-<hash>.css
|
|
23
|
+
// (kein HTML, vanilla) → Default-HTML ohne Asset-Tags
|
|
24
|
+
//
|
|
25
|
+
// Fehler-Modus: hat client.tsx oder Tailwind etwas produziert, aber das HTML
|
|
26
|
+
// hat keinen passenden Placeholder, wirft der Build mit dem exakten Snippet
|
|
27
|
+
// zum Reinkopieren. Keine silent-injection — das HTML soll lesen wie's
|
|
28
|
+
// auch im Dev-Server liefert.
|
|
29
|
+
//
|
|
30
|
+
// Output:
|
|
31
|
+
//
|
|
32
|
+
// dist/
|
|
33
|
+
// index.html ← Tags mit gehashten URLs
|
|
34
|
+
// assets/
|
|
35
|
+
// client-<hash>.js ← entry
|
|
36
|
+
// <chunk>-<hash>.js ← split chunks
|
|
37
|
+
// styles-<hash>.css ← Tailwind output
|
|
38
|
+
// <asset>-<hash>.<ext> ← imported file-loader assets
|
|
39
|
+
// manifest.json ← logical → hashed-URL mapping
|
|
40
|
+
// <public/* 1:1> ← favicon.ico, robots.txt, og-image.png, …
|
|
41
|
+
//
|
|
42
|
+
// Cache-Header (von runProdApp gesetzt, nicht hier):
|
|
43
|
+
//
|
|
44
|
+
// /assets/* → public, max-age=31536000, immutable
|
|
45
|
+
// /index.html, /sw.js → no-cache, must-revalidate
|
|
46
|
+
// /manifest.json → no-cache
|
|
47
|
+
// alles andere (public/) → default (auto-cache)
|
|
48
|
+
import { createHash } from "node:crypto";
|
|
49
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
50
|
+
import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
51
|
+
import { tmpdir } from "node:os";
|
|
52
|
+
import { isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
53
|
+
import { isPlainObject, parseJsonOrThrow } from "@cosmicdrift/kumiko-framework/utils";
|
|
54
|
+
import { Temporal } from "temporal-polyfill";
|
|
55
|
+
import { RENDERER_WEB_FONT_FILE_PATTERN, RENDERER_WEB_FONTS_DIST_DIR, resolveRendererWebFontsDir, } from "./renderer-web-fonts.js";
|
|
56
|
+
import { canResolveTailwindStylesheet, resolveTailwindCli } from "./resolve-tailwind-cli.js";
|
|
57
|
+
// Bun-Runtime-Check als module-level Konstante: alle Build-Schritte
|
|
58
|
+
// (Tailwind via Bun.spawn, Client-Bundle via Bun.build, Stylesheet-
|
|
59
|
+
// Resolution via Bun.resolveSync) sind Bun-only. Pro-Funktions-Inline-
|
|
60
|
+
// Checks driften sonst — eine Konstante hier hält das konsistent.
|
|
61
|
+
const hasBun = typeof globalThis.Bun !== "undefined";
|
|
62
|
+
// Default-HTML wird nur genutzt wenn der App-Author KEIN index.html liefert.
|
|
63
|
+
// Hat keine Asset-Placeholder, weil der Default-Pfad für vanilla apps
|
|
64
|
+
// (nur public/) gedacht ist — wer JS/CSS will, schreibt ein eigenes
|
|
65
|
+
// index.html mit den richtigen Placeholder-Tags.
|
|
66
|
+
// interactive-widget=resizes-content (fw#1918): keeps `position: fixed`
|
|
67
|
+
// bottom bars anchored above a mobile keyboard instead of behind it.
|
|
68
|
+
const DEFAULT_HTML = `<!doctype html>
|
|
69
|
+
<html lang="en">
|
|
70
|
+
<head>
|
|
71
|
+
<meta charset="utf-8" />
|
|
72
|
+
<meta name="viewport" content="width=device-width,initial-scale=1,interactive-widget=resizes-content" />
|
|
73
|
+
<title>Kumiko</title>
|
|
74
|
+
</head>
|
|
75
|
+
<body>
|
|
76
|
+
<div id="root"></div>
|
|
77
|
+
</body>
|
|
78
|
+
</html>
|
|
79
|
+
`;
|
|
80
|
+
/** Folder name relative to dist/ for hashed assets (JS, CSS, file-loader
|
|
81
|
+
* outputs). Exported damit runProdApp dieselbe Konvention für Cache-
|
|
82
|
+
* Header nutzt — Drift verhindern. */
|
|
83
|
+
export const ASSETS_DIR = "assets";
|
|
84
|
+
const ASSET_LOADERS = {
|
|
85
|
+
".png": "file",
|
|
86
|
+
".jpg": "file",
|
|
87
|
+
".jpeg": "file",
|
|
88
|
+
".gif": "file",
|
|
89
|
+
".svg": "file",
|
|
90
|
+
".webp": "file",
|
|
91
|
+
".ico": "file",
|
|
92
|
+
".woff": "file",
|
|
93
|
+
".woff2": "file",
|
|
94
|
+
".ttf": "file",
|
|
95
|
+
".otf": "file",
|
|
96
|
+
};
|
|
97
|
+
export async function buildProdBundle(options = {}) {
|
|
98
|
+
const cwd = resolve(options.cwd ?? process.cwd());
|
|
99
|
+
const outDir = resolve(cwd, options.outDir ?? "dist");
|
|
100
|
+
const assetsDir = join(outDir, ASSETS_DIR);
|
|
101
|
+
// 1. Discovery: was ist da?
|
|
102
|
+
const clientEntries = resolveClientEntries(cwd, options);
|
|
103
|
+
const firstClientSource = clientEntries[0]?.sourceFile;
|
|
104
|
+
const stylesheet = resolveStylesheetEntry(cwd, firstClientSource, options.stylesheet);
|
|
105
|
+
const publicDir = resolve(cwd, "public");
|
|
106
|
+
const hasPublicDir = existsSync(publicDir);
|
|
107
|
+
if (clientEntries.length === 0 && !hasPublicDir) {
|
|
108
|
+
throw new Error(`[kumiko build] nothing to build in ${cwd} — expected one of: ` +
|
|
109
|
+
`package.json "kumiko.clientEntry"/"kumiko.clientEntries", src/client.tsx, public/`);
|
|
110
|
+
}
|
|
111
|
+
// 2. Clean + scaffold
|
|
112
|
+
await rm(outDir, { recursive: true, force: true });
|
|
113
|
+
await mkdir(outDir, { recursive: true });
|
|
114
|
+
await mkdir(assetsDir, { recursive: true });
|
|
115
|
+
const manifest = {};
|
|
116
|
+
// 3. Tailwind one-shot (vor JS, weil JS' loader auf .css trifft falls
|
|
117
|
+
// der client.tsx ein "import './foo.css'" macht — den Fall lassen
|
|
118
|
+
// wir hier raus, Tailwind ist die einzige CSS-Quelle).
|
|
119
|
+
if (stylesheet) {
|
|
120
|
+
const css = await runTailwindOnce(stylesheet.path, cwd);
|
|
121
|
+
assertRendererWebShellPresent(css, stylesheet);
|
|
122
|
+
const hash = shortHash(css);
|
|
123
|
+
const filename = `styles-${hash}.css`;
|
|
124
|
+
await writeFile(join(assetsDir, filename), css);
|
|
125
|
+
manifest["styles.css"] = `/${ASSETS_DIR}/${filename}`;
|
|
126
|
+
await copyRendererWebFonts(cwd, outDir);
|
|
127
|
+
}
|
|
128
|
+
// 4. Bun.build pro Entry (multi-entry produces N bundles + shared chunks).
|
|
129
|
+
// Ein einzelner Bun.build-Call mit allen entrypoints würde shared
|
|
130
|
+
// chunks deduplizieren, hashes deterministisch halten — passt zu
|
|
131
|
+
// dem split-tree-Pattern von publicstatus (admin + public teilen
|
|
132
|
+
// sich den renderer-web-core).
|
|
133
|
+
if (clientEntries.length > 0) {
|
|
134
|
+
const built = await buildClientBundles(clientEntries, assetsDir);
|
|
135
|
+
for (const [manifestKey, filename] of Object.entries(built)) {
|
|
136
|
+
manifest[manifestKey] = `/${ASSETS_DIR}/${filename}`;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
// 5. Public-Folder rsync (ohne index.html / *.html-templates — werden
|
|
140
|
+
// separat gerendert). Filter-list = template-basenames der entries.
|
|
141
|
+
const templateBasenames = new Set(clientEntries.map((e) => basenameOf(e.htmlPath)));
|
|
142
|
+
if (hasPublicDir) {
|
|
143
|
+
await copyPublicFolder(publicDir, outDir, templateBasenames);
|
|
144
|
+
}
|
|
145
|
+
// 5b. Build-Identität: Hash über die content-gehashten Asset-URLs +
|
|
146
|
+
// lesbarer Zeitstempel. Wird in index.html gebacken und als
|
|
147
|
+
// build-info.json geschrieben (Update-Awareness, default an).
|
|
148
|
+
// ponytail: id hängt nur an Assets — ein reiner Server-Deploy ohne
|
|
149
|
+
// Client-Bundle-Change behält die id → kein Banner (die UI ist dann
|
|
150
|
+
// nicht stale). Bei Bedarf an Server-Versionierung koppeln.
|
|
151
|
+
const buildInfo = Object.keys(manifest).length > 0
|
|
152
|
+
? { id: computeBuildId(manifest), builtAt: Temporal.Now.instant().toString() }
|
|
153
|
+
: undefined;
|
|
154
|
+
// 6. HTML pro Entry rendern. Convention: ein HTML-File pro Client-Entry,
|
|
155
|
+
// jede mit ihrem eigenen Script-Tag. Server (runProdApp.hostDispatch)
|
|
156
|
+
// serviert je nach Host das passende File.
|
|
157
|
+
if (clientEntries.length === 0) {
|
|
158
|
+
// Vanilla-public-only-app: keine HTML-Files zu rendern, public-Folder
|
|
159
|
+
// wurde schon kopiert.
|
|
160
|
+
}
|
|
161
|
+
else {
|
|
162
|
+
for (const entry of clientEntries) {
|
|
163
|
+
const templatePath = resolve(cwd, entry.htmlPath);
|
|
164
|
+
const templateExists = existsSync(templatePath);
|
|
165
|
+
const html = await renderHtml(templateExists ? templatePath : undefined, manifest, entry, buildInfo);
|
|
166
|
+
const outFile = basenameOf(entry.htmlPath);
|
|
167
|
+
await writeFile(join(outDir, outFile), html);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
// 7. Manifest + Build-Info.
|
|
171
|
+
await writeFile(join(outDir, "manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`);
|
|
172
|
+
if (buildInfo) {
|
|
173
|
+
await writeFile(join(outDir, "build-info.json"), `${JSON.stringify(buildInfo)}\n`);
|
|
174
|
+
}
|
|
175
|
+
return { outDir, manifest, ...(buildInfo && { buildInfo }) };
|
|
176
|
+
}
|
|
177
|
+
const ENTRY_NAME_PATTERN = /^[a-z][a-z0-9-]*$/;
|
|
178
|
+
// The extension guard and both basename derivations (collision check, Bun.build
|
|
179
|
+
// output mapping) must agree, otherwise an accepted entry maps to no bundle.
|
|
180
|
+
const SOURCE_EXTENSION_PATTERN = /\.(?:tsx?|jsx?)$/;
|
|
181
|
+
/** Resolves the client entries to build. Public — also called from
|
|
182
|
+
* `kumiko-build`/`kumiko build` via `@cosmicdrift/kumiko-dev-server/build`,
|
|
183
|
+
* not just from unit tests.
|
|
184
|
+
*
|
|
185
|
+
* Precedence (fw#2320 — explicit declaration, no filename inference):
|
|
186
|
+
* 1. `declared.clientEntry` and `declared.clientEntries` both set → throw.
|
|
187
|
+
* 2. `declared.clientEntries` (non-empty) → one entry per declaration.
|
|
188
|
+
* 3. `declared.clientEntry` → single entry, name "client".
|
|
189
|
+
* 4. Neither → convention: src/client.tsx | src/client.ts (name "client").
|
|
190
|
+
* If that convention finds nothing but src/ still has legacy
|
|
191
|
+
* `client-<suffix>.tsx` files, throws a migration error instead of
|
|
192
|
+
* silently shipping a build without their bundles. */
|
|
193
|
+
export function resolveClientEntries(cwd, declared) {
|
|
194
|
+
const hasClientEntry = declared.clientEntry !== undefined;
|
|
195
|
+
const hasClientEntries = declared.clientEntries !== undefined;
|
|
196
|
+
if (hasClientEntry && hasClientEntries) {
|
|
197
|
+
throw new Error('[kumiko build] package.json "kumiko.clientEntry" and "kumiko.clientEntries" ' +
|
|
198
|
+
"are mutually exclusive — declare only one.");
|
|
199
|
+
}
|
|
200
|
+
if (declared.clientEntries !== undefined) {
|
|
201
|
+
return resolveDeclaredMultiEntries(cwd, declared.clientEntries);
|
|
202
|
+
}
|
|
203
|
+
if (declared.clientEntry !== undefined) {
|
|
204
|
+
return [resolveDeclaredSingleEntry(cwd, declared.clientEntry)];
|
|
205
|
+
}
|
|
206
|
+
return resolveConventionEntries(cwd);
|
|
207
|
+
}
|
|
208
|
+
function resolveDeclaredMultiEntries(cwd, declarations) {
|
|
209
|
+
if (declarations.length === 0) {
|
|
210
|
+
throw new Error('[kumiko build] package.json "kumiko.clientEntries" is empty — omit the key ' +
|
|
211
|
+
"entirely to use the src/client.tsx convention.");
|
|
212
|
+
}
|
|
213
|
+
const entries = declarations.map((decl) => resolveDeclaredEntry(cwd, decl));
|
|
214
|
+
const seenNames = new Set();
|
|
215
|
+
for (const entry of entries) {
|
|
216
|
+
if (seenNames.has(entry.name)) {
|
|
217
|
+
throw new Error(`[kumiko build] duplicate "kumiko.clientEntries[].name" "${entry.name}" — names must be unique.`);
|
|
218
|
+
}
|
|
219
|
+
seenNames.add(entry.name);
|
|
220
|
+
}
|
|
221
|
+
const seenHtmlBasenames = new Set();
|
|
222
|
+
for (const entry of entries) {
|
|
223
|
+
const base = basenameOf(entry.htmlPath);
|
|
224
|
+
if (seenHtmlBasenames.has(base)) {
|
|
225
|
+
throw new Error(`[kumiko build] two "kumiko.clientEntries" entries resolve to the same HTML ` +
|
|
226
|
+
`output file "${base}" — set an explicit "htmlPath" on one of them.`);
|
|
227
|
+
}
|
|
228
|
+
seenHtmlBasenames.add(base);
|
|
229
|
+
}
|
|
230
|
+
// Bun.build's output → ClientEntry mapping (buildClientBundles) matches on
|
|
231
|
+
// the source basename without extension. Two entries sharing it would
|
|
232
|
+
// silently map to the same bundle.
|
|
233
|
+
const seenSourceBasenames = new Set();
|
|
234
|
+
for (const entry of entries) {
|
|
235
|
+
const base = basenameOf(entry.sourceFile).replace(SOURCE_EXTENSION_PATTERN, "");
|
|
236
|
+
if (seenSourceBasenames.has(base)) {
|
|
237
|
+
throw new Error(`[kumiko build] two "kumiko.clientEntries" entries share the source basename ` +
|
|
238
|
+
`"${base}" ("${entry.sourceFile}") — rename one of the source files.`);
|
|
239
|
+
}
|
|
240
|
+
seenSourceBasenames.add(base);
|
|
241
|
+
}
|
|
242
|
+
return [...entries].sort((a, b) => a.name.localeCompare(b.name));
|
|
243
|
+
}
|
|
244
|
+
function resolveDeclaredEntry(cwd, decl) {
|
|
245
|
+
if (!ENTRY_NAME_PATTERN.test(decl.name)) {
|
|
246
|
+
throw new Error(`[kumiko build] invalid "kumiko.clientEntries[].name" "${decl.name}" — must match ` +
|
|
247
|
+
`^[a-z][a-z0-9-]*$ (it becomes the output filename client-${decl.name}.js).`);
|
|
248
|
+
}
|
|
249
|
+
const sourceFile = resolveWithinCwd(cwd, decl.sourceFile, `kumiko.clientEntries["${decl.name}"].sourceFile`);
|
|
250
|
+
assertValidSourceExtension(decl.sourceFile, `kumiko.clientEntries["${decl.name}"].sourceFile`);
|
|
251
|
+
if (!isExistingFile(sourceFile)) {
|
|
252
|
+
throw new Error(`[kumiko build] kumiko.clientEntries["${decl.name}"].sourceFile "${decl.sourceFile}" ` +
|
|
253
|
+
`does not exist (resolved: ${sourceFile}).`);
|
|
254
|
+
}
|
|
255
|
+
const htmlPath = decl.htmlPath !== undefined
|
|
256
|
+
? resolveDeclaredHtmlPath(cwd, decl.name, decl.htmlPath)
|
|
257
|
+
: decl.name === "public"
|
|
258
|
+
? (discoverHtmlTemplateFor(cwd, "index") ?? "index.html")
|
|
259
|
+
: (discoverHtmlTemplateFor(cwd, decl.name) ?? `${decl.name}.html`);
|
|
260
|
+
return { name: decl.name, sourceFile, manifestKey: `client-${decl.name}.js`, htmlPath };
|
|
261
|
+
}
|
|
262
|
+
function resolveDeclaredHtmlPath(cwd, entryName, htmlPath) {
|
|
263
|
+
const label = `kumiko.clientEntries["${entryName}"].htmlPath`;
|
|
264
|
+
const resolved = resolveWithinCwd(cwd, htmlPath, label);
|
|
265
|
+
assertValidHtmlExtension(htmlPath, label);
|
|
266
|
+
return resolved;
|
|
267
|
+
}
|
|
268
|
+
function resolveDeclaredSingleEntry(cwd, clientEntry) {
|
|
269
|
+
const sourceFile = resolveWithinCwd(cwd, clientEntry, "kumiko.clientEntry");
|
|
270
|
+
assertValidSourceExtension(clientEntry, "kumiko.clientEntry");
|
|
271
|
+
if (!isExistingFile(sourceFile)) {
|
|
272
|
+
throw new Error(`[kumiko build] kumiko.clientEntry "${clientEntry}" does not exist (resolved: ${sourceFile}).`);
|
|
273
|
+
}
|
|
274
|
+
return {
|
|
275
|
+
name: "client",
|
|
276
|
+
sourceFile,
|
|
277
|
+
manifestKey: "client.js",
|
|
278
|
+
htmlPath: discoverHtmlTemplateFor(cwd, "index") ?? "index.html",
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
function resolveConventionEntries(cwd) {
|
|
282
|
+
for (const candidate of ["src/client.tsx", "src/client.ts"]) {
|
|
283
|
+
const sourceFile = resolve(cwd, candidate);
|
|
284
|
+
if (existsSync(sourceFile)) {
|
|
285
|
+
return [
|
|
286
|
+
{
|
|
287
|
+
name: "client",
|
|
288
|
+
sourceFile,
|
|
289
|
+
manifestKey: "client.js",
|
|
290
|
+
htmlPath: discoverHtmlTemplateFor(cwd, "index") ?? "index.html",
|
|
291
|
+
},
|
|
292
|
+
];
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
const legacyEntries = findLegacyClientFiles(cwd);
|
|
296
|
+
if (legacyEntries.length > 0) {
|
|
297
|
+
throw new Error(buildLegacyMultiEntryMigrationError(legacyEntries));
|
|
298
|
+
}
|
|
299
|
+
return [];
|
|
300
|
+
}
|
|
301
|
+
// Pre-fw#2320 multi-entry convention: any src/client-<suffix>.tsx(x) became
|
|
302
|
+
// its own bundle. Detecting these without a declaration means an unmigrated
|
|
303
|
+
// app would silently ship without their bundles — throw instead.
|
|
304
|
+
function findLegacyClientFiles(cwd) {
|
|
305
|
+
const srcDir = resolve(cwd, "src");
|
|
306
|
+
if (!existsSync(srcDir))
|
|
307
|
+
return [];
|
|
308
|
+
let files;
|
|
309
|
+
try {
|
|
310
|
+
files = readdirSync(srcDir);
|
|
311
|
+
}
|
|
312
|
+
catch {
|
|
313
|
+
return [];
|
|
314
|
+
}
|
|
315
|
+
const found = [];
|
|
316
|
+
for (const file of files) {
|
|
317
|
+
const match = /^client-([a-z][a-z0-9-]*)\.tsx?$/.exec(file);
|
|
318
|
+
if (match?.[1])
|
|
319
|
+
found.push({ name: match[1], file });
|
|
320
|
+
}
|
|
321
|
+
return found.sort((a, b) => a.name.localeCompare(b.name));
|
|
322
|
+
}
|
|
323
|
+
function buildLegacyMultiEntryMigrationError(entries) {
|
|
324
|
+
const fileNames = entries.map((e) => `src/${e.file}`).join(", ");
|
|
325
|
+
const snippet = entries
|
|
326
|
+
.map((e) => ` { "name": "${e.name}", "sourceFile": "./src/${e.file}" }`)
|
|
327
|
+
.join(",\n");
|
|
328
|
+
return (`[kumiko build] found ${fileNames} but no "kumiko.clientEntries" declaration in ` +
|
|
329
|
+
`package.json — production builds no longer infer entries from filenames (fw#2320). Add:\n\n` +
|
|
330
|
+
` "kumiko": {\n` +
|
|
331
|
+
` "clientEntries": [\n` +
|
|
332
|
+
`${snippet}\n` +
|
|
333
|
+
` ]\n` +
|
|
334
|
+
` }\n`);
|
|
335
|
+
}
|
|
336
|
+
function resolveWithinCwd(cwd, value, label) {
|
|
337
|
+
const resolved = resolve(cwd, value);
|
|
338
|
+
const rel = relative(cwd, resolved);
|
|
339
|
+
if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
|
|
340
|
+
throw new Error(`[kumiko build] ${label} "${value}" resolves outside the app root ${cwd}.`);
|
|
341
|
+
}
|
|
342
|
+
return resolved;
|
|
343
|
+
}
|
|
344
|
+
function isExistingFile(path) {
|
|
345
|
+
return existsSync(path) && statSync(path).isFile();
|
|
346
|
+
}
|
|
347
|
+
// The basename of htmlPath becomes a dist output filename (e.g. "manifest.json"
|
|
348
|
+
// would collide with a file the build writes itself) — restrict it to .html.
|
|
349
|
+
function assertValidHtmlExtension(value, label) {
|
|
350
|
+
if (!value.endsWith(".html")) {
|
|
351
|
+
throw new Error(`[kumiko build] ${label} "${value}" must point to an .html file.`);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
function assertValidSourceExtension(value, label) {
|
|
355
|
+
if (!SOURCE_EXTENSION_PATTERN.test(value)) {
|
|
356
|
+
throw new Error(`[kumiko build] ${label} "${value}" must point to a .ts, .tsx, .js or .jsx file.`);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
/** Reads package.json → `kumiko.clientEntry` / `kumiko.clientEntries`.
|
|
360
|
+
* Missing file or missing keys → `{}` (falls back to convention mode). A
|
|
361
|
+
* malformed value under either key throws — a typo here must fail the
|
|
362
|
+
* build loudly instead of silently dropping declared entries. */
|
|
363
|
+
export function readClientEntriesConfig(cwd) {
|
|
364
|
+
const pkgJsonPath = resolve(cwd, "package.json");
|
|
365
|
+
if (!existsSync(pkgJsonPath))
|
|
366
|
+
return {};
|
|
367
|
+
const raw = readFileSync(pkgJsonPath, "utf8");
|
|
368
|
+
const parsed = parseJsonOrThrow(raw, pkgJsonPath);
|
|
369
|
+
if (!isPlainObject(parsed))
|
|
370
|
+
return {};
|
|
371
|
+
const kumiko = parsed["kumiko"];
|
|
372
|
+
if (!isPlainObject(kumiko))
|
|
373
|
+
return {};
|
|
374
|
+
const result = {};
|
|
375
|
+
if ("clientEntry" in kumiko) {
|
|
376
|
+
const value = kumiko["clientEntry"];
|
|
377
|
+
if (typeof value !== "string") {
|
|
378
|
+
throw new Error(`[kumiko build] package.json "kumiko.clientEntry" must be a string, got ${typeof value}.`);
|
|
379
|
+
}
|
|
380
|
+
result.clientEntry = value;
|
|
381
|
+
}
|
|
382
|
+
if ("clientEntries" in kumiko) {
|
|
383
|
+
const value = kumiko["clientEntries"];
|
|
384
|
+
if (!Array.isArray(value)) {
|
|
385
|
+
throw new Error(`[kumiko build] package.json "kumiko.clientEntries" must be an array, got ${typeof value}.`);
|
|
386
|
+
}
|
|
387
|
+
result.clientEntries = value.map((item, index) => parseClientEntryDeclaration(item, index));
|
|
388
|
+
}
|
|
389
|
+
return result;
|
|
390
|
+
}
|
|
391
|
+
function parseClientEntryDeclaration(item, index) {
|
|
392
|
+
if (!isPlainObject(item)) {
|
|
393
|
+
throw new Error(`[kumiko build] package.json "kumiko.clientEntries[${index}]" must be an object.`);
|
|
394
|
+
}
|
|
395
|
+
const name = item["name"];
|
|
396
|
+
const sourceFile = item["sourceFile"];
|
|
397
|
+
const htmlPath = item["htmlPath"];
|
|
398
|
+
if (typeof name !== "string" || name.length === 0) {
|
|
399
|
+
throw new Error(`[kumiko build] package.json "kumiko.clientEntries[${index}].name" must be a non-empty string.`);
|
|
400
|
+
}
|
|
401
|
+
if (typeof sourceFile !== "string" || sourceFile.length === 0) {
|
|
402
|
+
throw new Error(`[kumiko build] package.json "kumiko.clientEntries[${index}].sourceFile" must be a non-empty string.`);
|
|
403
|
+
}
|
|
404
|
+
if (htmlPath !== undefined && typeof htmlPath !== "string") {
|
|
405
|
+
throw new Error(`[kumiko build] package.json "kumiko.clientEntries[${index}].htmlPath" must be a string when set.`);
|
|
406
|
+
}
|
|
407
|
+
return { name, sourceFile, ...(htmlPath !== undefined && { htmlPath }) };
|
|
408
|
+
}
|
|
409
|
+
function discoverHtmlTemplateFor(cwd, basename) {
|
|
410
|
+
for (const candidate of [`${basename}.html`, `public/${basename}.html`]) {
|
|
411
|
+
const path = resolve(cwd, candidate);
|
|
412
|
+
if (existsSync(path))
|
|
413
|
+
return path;
|
|
414
|
+
}
|
|
415
|
+
return undefined;
|
|
416
|
+
}
|
|
417
|
+
// Äußerster Wrapper von DefaultAppShell/WorkspaceShell trägt diese Utility
|
|
418
|
+
// (app-layout.tsx: "flex min-h-screen …"). Echtes Tailwind-Utility (landet
|
|
419
|
+
// also im kompilierten Output) ohne CSS-Escaping → stabiler Substring-Sentinel.
|
|
420
|
+
const RENDERER_WEB_SHELL_SENTINEL = "min-h-screen";
|
|
421
|
+
function resolveStylesheetEntry(cwd, clientEntry, override) {
|
|
422
|
+
if (override === false)
|
|
423
|
+
return undefined;
|
|
424
|
+
if (typeof override === "string") {
|
|
425
|
+
return { path: resolve(cwd, override), isRendererWebFallback: false };
|
|
426
|
+
}
|
|
427
|
+
// App-eigenes styles.css schlägt den Default.
|
|
428
|
+
const local = resolve(cwd, "src/styles.css");
|
|
429
|
+
if (existsSync(local))
|
|
430
|
+
return { path: local, isRendererWebFallback: false };
|
|
431
|
+
// Sonst: nur wenn ein client da ist, fallback auf renderer-web/styles.css.
|
|
432
|
+
// Sample-Apps und Showcases nutzen das alle — gleiche Logik wie der dev-
|
|
433
|
+
// server, damit lokal/prod identisch bauen.
|
|
434
|
+
if (!clientEntry)
|
|
435
|
+
return undefined;
|
|
436
|
+
if (!hasBun)
|
|
437
|
+
return undefined;
|
|
438
|
+
try {
|
|
439
|
+
const resolved = globalThis.Bun.resolveSync("@cosmicdrift/kumiko-renderer-web/styles.css", cwd);
|
|
440
|
+
const bun = globalThis.Bun;
|
|
441
|
+
if (!canResolveTailwindStylesheet(resolved, { bun, cwd })) {
|
|
442
|
+
return undefined;
|
|
443
|
+
}
|
|
444
|
+
return { path: resolved, isRendererWebFallback: true };
|
|
445
|
+
}
|
|
446
|
+
catch {
|
|
447
|
+
return undefined;
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
// Build-Zeit-Guard gegen unstyled prod (#359): fällt der Build auf renderer-
|
|
451
|
+
// web/styles.css zurück und fehlt im kompilierten CSS die Shell-Sentinel-
|
|
452
|
+
// Klasse, wurden die DefaultAppShell-Styles nicht gescannt (renderer-web
|
|
453
|
+
// nicht dort installiert wo Tailwind scannt, oder ein @source-Regress).
|
|
454
|
+
// Laut failen statt ein 15KB-Image zu liefern, das in prod nackt rendert.
|
|
455
|
+
// @internal — exportiert nur für Unit-Tests.
|
|
456
|
+
export function assertRendererWebShellPresent(css, stylesheet) {
|
|
457
|
+
// skip: not the renderer-web fallback stylesheet, invariant doesn't apply
|
|
458
|
+
if (!stylesheet.isRendererWebFallback)
|
|
459
|
+
return;
|
|
460
|
+
// skip: shell sentinel class present, styles were scanned correctly
|
|
461
|
+
if (css.includes(RENDERER_WEB_SHELL_SENTINEL))
|
|
462
|
+
return;
|
|
463
|
+
throw new Error(`[kumiko build] renderer-web-Fallback-CSS ohne Shell-Klasse "${RENDERER_WEB_SHELL_SENTINEL}" — ` +
|
|
464
|
+
"die DefaultAppShell/WorkspaceShell-Styles fehlen, prod würde unstyled rendern. Meist ist " +
|
|
465
|
+
"@cosmicdrift/kumiko-renderer-web nicht dort installiert wo Tailwind seine Source scannt. " +
|
|
466
|
+
'Fix: src/styles.css anlegen mit `@import "@cosmicdrift/kumiko-renderer-web/styles.css";` ' +
|
|
467
|
+
'(+ `@source "./**/*.{ts,tsx}";` um auch eigene Komponenten zu scannen).');
|
|
468
|
+
}
|
|
469
|
+
// The compiled CSS points at absolute /assets/kumiko/fonts/<file>.woff2 URLs
|
|
470
|
+
// (see renderer-web-fonts.ts), so the files have to sit at exactly that path in
|
|
471
|
+
// dist. Skipped when renderer-web isn't resolvable — then no such CSS exists.
|
|
472
|
+
async function copyRendererWebFonts(cwd, outDir) {
|
|
473
|
+
const fontsDir = resolveRendererWebFontsDir([cwd]);
|
|
474
|
+
// skip: renderer-web not resolvable, so no font-referencing CSS exists.
|
|
475
|
+
if (fontsDir === undefined || !existsSync(fontsDir))
|
|
476
|
+
return;
|
|
477
|
+
const target = join(outDir, RENDERER_WEB_FONTS_DIST_DIR);
|
|
478
|
+
await mkdir(target, { recursive: true });
|
|
479
|
+
for (const file of readdirSync(fontsDir)) {
|
|
480
|
+
if (RENDERER_WEB_FONT_FILE_PATTERN.test(file)) {
|
|
481
|
+
await cp(join(fontsDir, file), join(target, file));
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
// @internal — exported nur für Unit-Tests.
|
|
486
|
+
export function discoverHtmlTemplate(cwd) {
|
|
487
|
+
for (const candidate of ["index.html", "public/index.html"]) {
|
|
488
|
+
const path = resolve(cwd, candidate);
|
|
489
|
+
if (existsSync(path))
|
|
490
|
+
return path;
|
|
491
|
+
}
|
|
492
|
+
return undefined;
|
|
493
|
+
}
|
|
494
|
+
// ---------------------------------------------------------------------------
|
|
495
|
+
// Build steps
|
|
496
|
+
// ---------------------------------------------------------------------------
|
|
497
|
+
// @internal — exportiert nur für Unit-Tests (Relocation-Test des @source-Layouts).
|
|
498
|
+
export async function runTailwindOnce(entry, cwd) {
|
|
499
|
+
if (!hasBun) {
|
|
500
|
+
throw new Error("[kumiko build] Tailwind one-shot requires Bun (Bun.spawn) — run via `bun run …` or `bun kumiko build`.");
|
|
501
|
+
}
|
|
502
|
+
const bunResolver = globalThis
|
|
503
|
+
.Bun;
|
|
504
|
+
const cliPath = resolveTailwindCli({ bun: bunResolver, cwd });
|
|
505
|
+
if (cliPath === undefined) {
|
|
506
|
+
throw new Error("[kumiko build] @tailwindcss/cli nicht auflösbar — `bun install` im App-Root ausführen.");
|
|
507
|
+
}
|
|
508
|
+
if (!canResolveTailwindStylesheet(entry, { bun: bunResolver, cwd })) {
|
|
509
|
+
throw new Error(`[kumiko build] tailwindcss nicht auflösbar für ${entry} — peer dependency fehlt am Stylesheet-Ort.`);
|
|
510
|
+
}
|
|
511
|
+
const tmpDir = await mkdtemp(join(tmpdir(), "kumiko-build-tw-"));
|
|
512
|
+
const outPath = join(tmpDir, "styles.css");
|
|
513
|
+
const bunPath = process.argv[0] ?? "bun";
|
|
514
|
+
const proc = Bun.spawn([bunPath, "run", cliPath, "-i", entry, "-o", outPath, "--minify"], {
|
|
515
|
+
cwd,
|
|
516
|
+
stdout: "inherit",
|
|
517
|
+
stderr: "inherit",
|
|
518
|
+
});
|
|
519
|
+
const code = await proc.exited;
|
|
520
|
+
if (code !== 0) {
|
|
521
|
+
throw new Error(`[kumiko build] tailwind exit ${code}`);
|
|
522
|
+
}
|
|
523
|
+
const css = await readFile(outPath, "utf8");
|
|
524
|
+
await rm(tmpDir, { recursive: true, force: true });
|
|
525
|
+
return css;
|
|
526
|
+
}
|
|
527
|
+
/** Multi-entry-build: ein Bun.build-Call mit allen entrypoints — shared
|
|
528
|
+
* chunks werden dedupliziert, hashes deterministisch. Returns map
|
|
529
|
+
* manifestKey → hashed-filename (basename, ohne /assets/-Prefix). */
|
|
530
|
+
async function buildClientBundles(entries, outDir) {
|
|
531
|
+
if (!hasBun) {
|
|
532
|
+
throw new Error("[kumiko build] requires Bun — run via `bun run …` or `bun kumiko build`.");
|
|
533
|
+
}
|
|
534
|
+
const built = await Bun.build({
|
|
535
|
+
entrypoints: entries.map((e) => e.sourceFile),
|
|
536
|
+
outdir: outDir,
|
|
537
|
+
target: "browser",
|
|
538
|
+
splitting: true,
|
|
539
|
+
minify: true,
|
|
540
|
+
// Keine Source-Maps in Prod: 1.6 MB+ Müll im Container, plus
|
|
541
|
+
// exposed Source-Code reverse-engineerable. Dev hat seine eigenen
|
|
542
|
+
// sourcemaps via create-kumiko-server.ts.
|
|
543
|
+
sourcemap: "none",
|
|
544
|
+
naming: {
|
|
545
|
+
entry: "[name]-[hash].[ext]",
|
|
546
|
+
chunk: "[name]-[hash].[ext]",
|
|
547
|
+
asset: "[name]-[hash].[ext]",
|
|
548
|
+
},
|
|
549
|
+
loader: ASSET_LOADERS,
|
|
550
|
+
define: {
|
|
551
|
+
"process.env.NODE_ENV": JSON.stringify("production"),
|
|
552
|
+
},
|
|
553
|
+
});
|
|
554
|
+
if (!built.success) {
|
|
555
|
+
const errs = built.logs.map((log) => String(log)).join("\n");
|
|
556
|
+
throw new Error(`[kumiko build] Bun.build failed:\n${errs}`);
|
|
557
|
+
}
|
|
558
|
+
const entryOutputs = built.outputs.filter((o) => o.kind === "entry-point");
|
|
559
|
+
if (entryOutputs.length !== entries.length) {
|
|
560
|
+
throw new Error(`[kumiko build] expected ${entries.length} entry-point outputs, got ${entryOutputs.length}`);
|
|
561
|
+
}
|
|
562
|
+
// Bun.build benennt entry-files nach Source-Basename (ohne extension):
|
|
563
|
+
// `src/client-admin.tsx` → `client-admin-<hash>.js`. Wir mappen jedes
|
|
564
|
+
// entry-output zurück auf seinen ClientEntry via Basename-match.
|
|
565
|
+
const result = {};
|
|
566
|
+
for (const entry of entries) {
|
|
567
|
+
const baseName = (entry.sourceFile.split("/").pop() ?? "").replace(SOURCE_EXTENSION_PATTERN, "");
|
|
568
|
+
const match = entryOutputs.find((o) => {
|
|
569
|
+
const outName = o.path.split("/").pop() ?? "";
|
|
570
|
+
return outName.startsWith(`${baseName}-`);
|
|
571
|
+
});
|
|
572
|
+
if (!match) {
|
|
573
|
+
throw new Error(`[kumiko build] no entry-point output for "${entry.sourceFile}" (looked for "${baseName}-*.js")`);
|
|
574
|
+
}
|
|
575
|
+
result[entry.manifestKey] = match.path.split("/").pop() ?? match.path;
|
|
576
|
+
}
|
|
577
|
+
return result;
|
|
578
|
+
}
|
|
579
|
+
function basenameOf(p) {
|
|
580
|
+
return p.split("/").pop() ?? p;
|
|
581
|
+
}
|
|
582
|
+
async function copyPublicFolder(src, dst, templateBasenames) {
|
|
583
|
+
// HTML-templates werden separat gerendert — nicht blind kopieren, sonst
|
|
584
|
+
// überschreibt das die injizierte Version. (z.B. index.html, admin.html
|
|
585
|
+
// bei multi-entry).
|
|
586
|
+
await cp(src, dst, {
|
|
587
|
+
recursive: true,
|
|
588
|
+
filter: (source) => {
|
|
589
|
+
const normalized = source.replace(/\\/g, "/");
|
|
590
|
+
const srcNormalized = src.replace(/\\/g, "/");
|
|
591
|
+
const base = normalized.startsWith(`${srcNormalized}/`)
|
|
592
|
+
? normalized.slice(srcNormalized.length + 1)
|
|
593
|
+
: "";
|
|
594
|
+
return !templateBasenames.has(base);
|
|
595
|
+
},
|
|
596
|
+
});
|
|
597
|
+
}
|
|
598
|
+
// ---------------------------------------------------------------------------
|
|
599
|
+
// HTML render
|
|
600
|
+
// ---------------------------------------------------------------------------
|
|
601
|
+
async function renderHtml(templatePath, manifest, entry, buildInfo) {
|
|
602
|
+
// Edge-Case: kein eigenes HTML-Template + Bun.build oder Tailwind hat
|
|
603
|
+
// Output produziert. DEFAULT_HTML hat keine Placeholder (vanilla
|
|
604
|
+
// template), also würde injectAssetTags eh fehlschlagen. Klarer Fehler
|
|
605
|
+
// mit Vorschlag-Snippet zum Reinkopieren.
|
|
606
|
+
if (!templatePath && Object.keys(manifest).length > 0) {
|
|
607
|
+
throw new Error(buildMissingTemplateError(manifest, entry));
|
|
608
|
+
}
|
|
609
|
+
const template = templatePath ? await readFile(templatePath, "utf8") : DEFAULT_HTML;
|
|
610
|
+
return injectAssetTags(template, manifest, entry, buildInfo);
|
|
611
|
+
}
|
|
612
|
+
// @internal — exported for unit tests only. See #2305: the message must
|
|
613
|
+
// name the source file and, for a declared multi-entry, which package.json
|
|
614
|
+
// "kumiko.clientEntries" entry it came from.
|
|
615
|
+
export function buildMissingTemplateError(manifest, entry) {
|
|
616
|
+
const cssLine = manifest["styles.css"]
|
|
617
|
+
? ` <link rel="stylesheet" href="/styles.css" />\n`
|
|
618
|
+
: "";
|
|
619
|
+
const jsLine = manifest[entry.manifestKey]
|
|
620
|
+
? // html-ok: Error-Hilfetext (Tag-Snippet als Text), wird nie gerendert.
|
|
621
|
+
` <script type="module" src="/${entry.manifestKey}"></script>\n`
|
|
622
|
+
: "";
|
|
623
|
+
const sourceBasename = basenameOf(entry.sourceFile);
|
|
624
|
+
// Single-mode entries always carry manifestKey "client.js"; any other
|
|
625
|
+
// value came from a declared package.json "kumiko.clientEntries" entry.
|
|
626
|
+
const isMultiEntry = entry.manifestKey !== "client.js";
|
|
627
|
+
const discoveryHint = isMultiEntry
|
|
628
|
+
? `Entry "${entry.name}" comes from package.json "kumiko.clientEntries" ` +
|
|
629
|
+
`(sourceFile: "src/${sourceBasename}").\n\n`
|
|
630
|
+
: "";
|
|
631
|
+
return (`[kumiko build] kein ${entry.htmlPath} gefunden für Entry "src/${sourceBasename}", ` +
|
|
632
|
+
`aber es gibt JS/CSS-Output.\n` +
|
|
633
|
+
discoveryHint +
|
|
634
|
+
`Leg ein public/${basenameOf(entry.htmlPath)} oder ${basenameOf(entry.htmlPath)} im App-Root an, z. B.:\n` +
|
|
635
|
+
`\n` +
|
|
636
|
+
`<!doctype html>\n` +
|
|
637
|
+
`<html>\n` +
|
|
638
|
+
` <head>\n` +
|
|
639
|
+
` <meta charset="utf-8" />\n` +
|
|
640
|
+
` <title>Meine App</title>\n` +
|
|
641
|
+
cssLine +
|
|
642
|
+
` </head>\n` +
|
|
643
|
+
` <body>\n` +
|
|
644
|
+
` <div id="root"></div>\n` +
|
|
645
|
+
jsLine +
|
|
646
|
+
` </body>\n` +
|
|
647
|
+
`</html>\n` +
|
|
648
|
+
`\n` +
|
|
649
|
+
`Der Build ersetzt /styles.css und /${entry.manifestKey} durch die gehashten URLs.`);
|
|
650
|
+
}
|
|
651
|
+
// @internal — exported nur für Unit-Tests.
|
|
652
|
+
//
|
|
653
|
+
// Convention: das HTML-Template MUSS Placeholder-Tags für jedes Asset
|
|
654
|
+
// dieses Entries enthalten:
|
|
655
|
+
// - `<script type="module" src="/client.js">` für single-mode entry "client"
|
|
656
|
+
// - `<script type="module" src="/client-<name>.js">` für multi-mode entry "<name>"
|
|
657
|
+
// - `<link href="/styles.css">` für styles (gemeinsam über alle entries)
|
|
658
|
+
// Der Build ersetzt sie durch die gehashten URLs.
|
|
659
|
+
//
|
|
660
|
+
// Fehlt ein erwarteter Tag, wirft der Build einen Fehler mit dem exakten
|
|
661
|
+
// Snippet zum Reinkopieren — kein silent injection mehr, weil das den
|
|
662
|
+
// Diff zwischen Dev- und Prod-HTML unsichtbar macht.
|
|
663
|
+
export function injectAssetTags(html, manifest, entry, buildInfo) {
|
|
664
|
+
let result = html;
|
|
665
|
+
// Build-Stand vor </head> backen. Ohne </head> (z.B. Fragment) still skip.
|
|
666
|
+
if (buildInfo && result.includes("</head>")) {
|
|
667
|
+
// html-ok: id/builtAt sind Hex bzw. ISO — kein `<` möglich, kein Breakout.
|
|
668
|
+
const tag = `<script>window.__KUMIKO_BUILD__=${JSON.stringify(buildInfo)};</script>`;
|
|
669
|
+
result = result.replace("</head>", ` ${tag}\n </head>`);
|
|
670
|
+
}
|
|
671
|
+
const cssUrl = manifest["styles.css"];
|
|
672
|
+
if (cssUrl && !result.includes(cssUrl)) {
|
|
673
|
+
const placeholder = /<link\s+rel="stylesheet"\s+href="\/styles\.css"\s*\/?>/.exec(result);
|
|
674
|
+
if (!placeholder) {
|
|
675
|
+
throw new Error(buildMissingTagError({
|
|
676
|
+
htmlPath: entry.htmlPath,
|
|
677
|
+
assetKey: "styles.css",
|
|
678
|
+
tagSnippet: `<link rel="stylesheet" href="/styles.css" />`,
|
|
679
|
+
insertHint: "ins <head>",
|
|
680
|
+
hashedAssetHint: "/assets/styles-<hash>.css",
|
|
681
|
+
}));
|
|
682
|
+
}
|
|
683
|
+
// html-ok: cssUrl ist ein selbst-generierter Manifest-Asset-Pfad (Hash-Name).
|
|
684
|
+
result = result.replace(placeholder[0], `<link rel="stylesheet" href="${cssUrl}" />`);
|
|
685
|
+
}
|
|
686
|
+
const jsUrl = manifest[entry.manifestKey];
|
|
687
|
+
if (jsUrl && !result.includes(jsUrl)) {
|
|
688
|
+
// Placeholder-pattern: src="/client.js" oder src="/client-<name>.js"
|
|
689
|
+
const placeholderRx = new RegExp(`<script\\b[^>]*src="\\/${entry.manifestKey.replace(/\./g, "\\.")}"[^>]*><\\/script>`);
|
|
690
|
+
const placeholder = placeholderRx.exec(result);
|
|
691
|
+
if (!placeholder) {
|
|
692
|
+
const baseAssetName = entry.manifestKey.replace(/\.js$/, "");
|
|
693
|
+
throw new Error(buildMissingTagError({
|
|
694
|
+
htmlPath: entry.htmlPath,
|
|
695
|
+
assetKey: entry.manifestKey,
|
|
696
|
+
tagSnippet: `<script type="module" src="/${entry.manifestKey}"></script>`,
|
|
697
|
+
insertHint: "vor </body>",
|
|
698
|
+
hashedAssetHint: `/assets/${baseAssetName}-<hash>.js`,
|
|
699
|
+
}));
|
|
700
|
+
}
|
|
701
|
+
// html-ok: jsUrl ist ein selbst-generierter Manifest-Asset-Pfad (Hash-Name).
|
|
702
|
+
result = result.replace(placeholder[0], `<script type="module" src="${jsUrl}"></script>`);
|
|
703
|
+
}
|
|
704
|
+
return result;
|
|
705
|
+
}
|
|
706
|
+
/** Einheitliche Error-Form für fehlende Asset-Tags im HTML-Template
|
|
707
|
+
* (script-tag fürs JS-Bundle ODER stylesheet-link für Tailwind). */
|
|
708
|
+
function buildMissingTagError(args) {
|
|
709
|
+
const tpl = basenameOf(args.htmlPath);
|
|
710
|
+
return (`[kumiko build] ${tpl} hat keinen Entry-Tag für /${args.assetKey} — füg ${args.insertHint} ein:\n` +
|
|
711
|
+
`\n` +
|
|
712
|
+
` ${args.tagSnippet}\n` +
|
|
713
|
+
`\n` +
|
|
714
|
+
`Der Build ersetzt das durch ${args.hashedAssetHint}. Im Dev-Server liefert er die Datei direkt.`);
|
|
715
|
+
}
|
|
716
|
+
// ---------------------------------------------------------------------------
|
|
717
|
+
// Hash helpers
|
|
718
|
+
// ---------------------------------------------------------------------------
|
|
719
|
+
function shortHash(content) {
|
|
720
|
+
return createHash("sha256").update(content).digest("hex").slice(0, 8);
|
|
721
|
+
}
|
|
722
|
+
// Build-Identität aus den content-gehashten Asset-URLs. Sortiert →
|
|
723
|
+
// deterministisch (Manifest-Key-Reihenfolge egal). Identischer Source →
|
|
724
|
+
// gleiche id, geändertes Asset → andere id.
|
|
725
|
+
// @internal — exported nur für Unit-Tests.
|
|
726
|
+
export function computeBuildId(manifest) {
|
|
727
|
+
return createHash("sha256")
|
|
728
|
+
.update(Object.values(manifest).sort().join("\n"))
|
|
729
|
+
.digest("hex")
|
|
730
|
+
.slice(0, 12);
|
|
731
|
+
}
|
|
732
|
+
// ---------------------------------------------------------------------------
|
|
733
|
+
// CLI output
|
|
734
|
+
// ---------------------------------------------------------------------------
|
|
735
|
+
/** Formatiert ein BuildResult als CLI-freundliche Mehrzeilen-Zusammenfassung
|
|
736
|
+
* mit ANSI-Farben. Wird sowohl von `kumiko build` als auch von dem
|
|
737
|
+
* hoisted `kumiko-build`-Bin verwendet, damit das Output konsistent ist. */
|
|
738
|
+
export function formatBuildResult(result, durationMs) {
|
|
739
|
+
const dim = "\x1b[2m";
|
|
740
|
+
const green = "\x1b[32m";
|
|
741
|
+
const reset = "\x1b[0m";
|
|
742
|
+
const lines = [
|
|
743
|
+
"",
|
|
744
|
+
` ${green}✓${reset} built ${result.outDir} ${dim}(${durationMs}ms)${reset}`,
|
|
745
|
+
];
|
|
746
|
+
for (const [logical, hashed] of Object.entries(result.manifest)) {
|
|
747
|
+
lines.push(` ${dim}${logical.padEnd(14)}${reset} ${hashed}`);
|
|
748
|
+
}
|
|
749
|
+
lines.push("");
|
|
750
|
+
return lines.join("\n");
|
|
751
|
+
}
|