@ogygia/compiler 0.14.1 → 0.15.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.
@@ -0,0 +1,500 @@
1
+ import { parse_module } from "../parse/oxc.js";
2
+ import { free_references } from "../free-vars.js";
3
+ import { warn } from "../messages.js";
4
+ import path from "node:path";
5
+ import { createRequire } from "node:module";
6
+ import MagicString from "magic-string";
7
+ import { walk } from "estree-walker";
8
+ import remapping from "@jridgewell/remapping";
9
+ import { pathToFileURL } from "node:url";
10
+ // src/link/dead-exports.ts
11
+ /**
12
+ * THE SERVER'S DEAD EXPORTS: a pass over a finished server bundle that drops what a shared chunk
13
+ * exports and no chunk imports, and the code only those exports reached.
14
+ *
15
+ * The bundler fixes a shared chunk's export list before the build's feature word folds its tests
16
+ * (`HAS & F_x`, the word a const of a virtual module, inlined late). An importer whose call folds
17
+ * away stops importing, but the chunk still exports the helper, so the helper and everything only it
18
+ * reaches stays. This pass reads the finished chunks as they are written: what each one imports,
19
+ * statically or by a literal `import()`, is the whole demand on a chunk that is no entry. Exports
20
+ * outside that demand go, the bundler itself re-shakes the chunk to say which top-level declarations
21
+ * nothing reaches any more, and those are cut from the chunk's text; every other byte stays as
22
+ * written. A chunk shrinks, its imports shrink, so the pass runs again until nothing changes.
23
+ *
24
+ * It only removes what it proves dead. An entry, a chunk loaded by `import()`, one imported whole
25
+ * (`import *`, `export *`), one named as text elsewhere in the bundle, or one whose exports are not one
26
+ * plain list keeps every export. A declaration is cut only when the re-shake dropped it and no kept
27
+ * code names it.
28
+ *
29
+ * @packageDocumentation
30
+ */
31
+ const QUOTES = /* @__PURE__ */ new Set([
32
+ "\"",
33
+ "'",
34
+ "`"
35
+ ]);
36
+ const DECLARATIONS = /* @__PURE__ */ new Set([
37
+ "FunctionDeclaration",
38
+ "ClassDeclaration",
39
+ "VariableDeclaration"
40
+ ]);
41
+ const KEYED = /* @__PURE__ */ new Set([
42
+ "Property",
43
+ "MethodDefinition",
44
+ "PropertyDefinition",
45
+ "AccessorProperty"
46
+ ]);
47
+ const FUNCTIONS = /* @__PURE__ */ new Set([
48
+ "FunctionDeclaration",
49
+ "FunctionExpression",
50
+ "ArrowFunctionExpression"
51
+ ]);
52
+ const B64 = new Map("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").map((c, i) => [c, i]));
53
+ function target_of(from, spec) {
54
+ if (!spec.startsWith("./") && !spec.startsWith("../")) return null;
55
+ return path.posix.normalize(path.posix.join(path.posix.dirname(from), spec));
56
+ }
57
+ function name_of(node) {
58
+ return node.type === "Identifier" ? node.name : String(node.value);
59
+ }
60
+ function read_chunk(chunk) {
61
+ const parsed = parse_module(chunk.code, chunk.fileName);
62
+ if (!parsed.ok) return null;
63
+ const body = parsed.program.body;
64
+ const specifiers = [];
65
+ const demands = [];
66
+ const demand = (source, names) => {
67
+ specifiers.push([source.start, source.end]);
68
+ const target = target_of(chunk.fileName, String(source.value));
69
+ if (target !== null) demands.push({
70
+ target,
71
+ names
72
+ });
73
+ };
74
+ let list = null;
75
+ let plain = true;
76
+ for (const node of body) if (node.type === "ImportDeclaration") {
77
+ const names = /* @__PURE__ */ new Set();
78
+ let whole = false;
79
+ for (const s of node.specifiers) if (s.type === "ImportNamespaceSpecifier") whole = true;
80
+ else if (s.type === "ImportDefaultSpecifier") names.add("default");
81
+ else names.add(name_of(s.imported));
82
+ demand(node.source, whole ? "all" : names);
83
+ } else if (node.type === "ExportAllDeclaration") {
84
+ plain = false;
85
+ demand(node.source, "all");
86
+ } else if (node.type === "ExportNamedDeclaration" && node.source) {
87
+ plain = false;
88
+ demand(node.source, new Set(node.specifiers.map((s) => name_of(s.local))));
89
+ } else if (node.type === "ExportNamedDeclaration" && !node.declaration && list === null) list = node;
90
+ else if (node.type === "ExportNamedDeclaration" || node.type === "ExportDefaultDeclaration") plain = false;
91
+ walk(parsed.program, { enter(node) {
92
+ const n = node;
93
+ if (n.type === "ImportExpression" && n.source.type === "Literal") demand(n.source, "all");
94
+ } });
95
+ return {
96
+ code: chunk.code,
97
+ body,
98
+ comments: parsed.comments,
99
+ specifier_spans: specifiers,
100
+ demands,
101
+ plain_export_list: plain ? list : null
102
+ };
103
+ }
104
+ function file_name_in_text(file, facts) {
105
+ const base = path.posix.basename(file);
106
+ for (const { code, specifier_spans } of facts.values()) for (let at = code.indexOf(base); at !== -1; at = code.indexOf(base, at + 1)) {
107
+ if (!QUOTES.has(code[at + base.length] ?? "")) continue;
108
+ if (!specifier_spans.some(([s, e]) => at >= s && at < e)) return true;
109
+ }
110
+ return false;
111
+ }
112
+ function mapped_source_offsets(mappings, starts) {
113
+ const out = [];
114
+ const field = [
115
+ 0,
116
+ 0,
117
+ 0,
118
+ 0,
119
+ 0
120
+ ];
121
+ let line = 0;
122
+ let col = 0;
123
+ let n = 0;
124
+ let value = 0;
125
+ let shift = 0;
126
+ const flush = () => {
127
+ if (n >= 4) {
128
+ line += field[2];
129
+ col += field[3];
130
+ out.push((starts[line] ?? Infinity) + col);
131
+ }
132
+ n = 0;
133
+ };
134
+ for (const c of mappings) {
135
+ if (c === "," || c === ";") {
136
+ flush();
137
+ continue;
138
+ }
139
+ const digit = B64.get(c) ?? 0;
140
+ value += (digit & 31) << shift;
141
+ shift += 5;
142
+ if (digit & 32) continue;
143
+ field[n++] = value & 1 ? -(value >>> 1) : value >>> 1;
144
+ value = 0;
145
+ shift = 0;
146
+ }
147
+ flush();
148
+ return out.sort((a, b) => a - b);
149
+ }
150
+ function line_starts(text) {
151
+ const out = [0];
152
+ for (let i = text.indexOf("\n"); i !== -1; i = text.indexOf("\n", i + 1)) out.push(i + 1);
153
+ return out;
154
+ }
155
+ function any_in_span(sorted, start, end) {
156
+ let lo = 0;
157
+ let hi = sorted.length;
158
+ while (lo < hi) {
159
+ const mid = lo + hi >>> 1;
160
+ if (sorted[mid] < start) lo = mid + 1;
161
+ else hi = mid;
162
+ }
163
+ return lo < sorted.length && sorted[lo] < end;
164
+ }
165
+ function bindings(node, out) {
166
+ if (node === null) return out;
167
+ if (node.type === "Identifier") out.push(node.name);
168
+ else if (node.type === "ObjectPattern") for (const p of node.properties) bindings(p.type === "RestElement" ? p.argument : p.value, out);
169
+ else if (node.type === "ArrayPattern") for (const e of node.elements) bindings(e, out);
170
+ else if (node.type === "RestElement") bindings(node.argument, out);
171
+ else if (node.type === "AssignmentPattern") bindings(node.left, out);
172
+ return out;
173
+ }
174
+ function declared(node) {
175
+ if (node.type === "VariableDeclaration") return node.declarations.flatMap((d) => bindings(d.id, []));
176
+ return node.id ? [node.id.name] : [];
177
+ }
178
+ function outside_names(node) {
179
+ const out = new Set(free_references(node));
180
+ walk(node, { enter(child) {
181
+ const n = child;
182
+ if (FUNCTIONS.has(n.type)) for (const p of n.params) param_reads(p, out);
183
+ } });
184
+ return out;
185
+ }
186
+ function param_reads(node, out) {
187
+ if (node === null) return;
188
+ if (node.type === "AssignmentPattern") {
189
+ names_in(node.right, out);
190
+ param_reads(node.left, out);
191
+ } else if (node.type === "ObjectPattern") for (const p of node.properties) if (p.type === "RestElement") param_reads(p.argument, out);
192
+ else {
193
+ if (p.computed) names_in(p.key, out);
194
+ param_reads(p.value, out);
195
+ }
196
+ else if (node.type === "ArrayPattern") for (const e of node.elements) param_reads(e, out);
197
+ else if (node.type === "RestElement") param_reads(node.argument, out);
198
+ }
199
+ function names_in(node, out) {
200
+ walk(node, { enter(child, parent, key) {
201
+ const n = child;
202
+ if (n.type !== "Identifier") return;
203
+ const p = parent;
204
+ if (p?.type === "MemberExpression" && key === "property" && !p.computed) return;
205
+ if (p && KEYED.has(p.type) && key === "key" && !p.computed) return;
206
+ out.add(n.name);
207
+ } });
208
+ }
209
+ function cut_span(code, facts, at) {
210
+ const node = facts.body[at];
211
+ const floor = at === 0 ? 0 : facts.body[at - 1].end;
212
+ let start = node.start;
213
+ for (let i = facts.comments.length - 1; i >= 0; i--) {
214
+ const c = facts.comments[i];
215
+ if (c.end > start || c.start < floor) continue;
216
+ if (c.type !== "Block" || code.slice(c.end, start).trim() !== "") break;
217
+ start = c.start;
218
+ }
219
+ return whole_lines(code, start, node.end);
220
+ }
221
+ function whole_lines(code, start, end) {
222
+ const from = code.lastIndexOf("\n", start - 1) + 1;
223
+ if (code.slice(from, start).trim() !== "") return [start, end];
224
+ const eol = code.indexOf("\n", end);
225
+ const to = eol === -1 ? code.length : eol + 1;
226
+ return code.slice(end, to).trim() === "" ? [from, to] : [start, end];
227
+ }
228
+ function import_text(code, node, live) {
229
+ const specs = node.specifiers;
230
+ const kept = specs.filter((s) => live.has(s.local.name));
231
+ if (kept.length === specs.length || (node.attributes?.length ?? 0) > 0) return null;
232
+ const source = code.slice(node.source.start, node.source.end);
233
+ if (kept.length === 0) return `import ${source};`;
234
+ const slice = (s) => code.slice(s.start, s.end);
235
+ const head = kept.filter((s) => s.type !== "ImportSpecifier").map(slice);
236
+ const named = kept.filter((s) => s.type === "ImportSpecifier").map(slice);
237
+ if (named.length) head.push(`{ ${named.join(", ")} }`);
238
+ return `import ${head.join(", ")} from ${source};`;
239
+ }
240
+ async function shake_chunk(chunk, facts, demand, reshake) {
241
+ const { code, body } = facts;
242
+ const list = facts.plain_export_list;
243
+ const specs = list.specifiers;
244
+ const kept_specs = specs.filter((s) => demand.has(name_of(s.exported)));
245
+ const dropped = specs.filter((s) => !demand.has(name_of(s.exported))).map((s) => name_of(s.exported));
246
+ const list_text = kept_specs.length ? `export { ${kept_specs.map((s) => code.slice(s.start, s.end)).join(", ")} };` : "";
247
+ const probe = `${code.slice(0, list.start)}${list_text.padEnd(list.end - list.start)}${code.slice(list.end)}`;
248
+ let mappings;
249
+ try {
250
+ mappings = await reshake(probe);
251
+ } catch (e) {
252
+ return {
253
+ ok: false,
254
+ reason: `the re-shake failed (${e.message})`,
255
+ failed: true
256
+ };
257
+ }
258
+ if (mappings === null) return {
259
+ ok: false,
260
+ reason: "the re-shake wrote no map",
261
+ failed: true
262
+ };
263
+ const offsets = mapped_source_offsets(mappings, line_starts(probe));
264
+ const cut = /* @__PURE__ */ new Set();
265
+ const owners = /* @__PURE__ */ new Map();
266
+ body.forEach((node, i) => {
267
+ if (!DECLARATIONS.has(node.type)) return;
268
+ for (const name of declared(node)) owners.set(name, [...owners.get(name) ?? [], i]);
269
+ if (!any_in_span(offsets, node.start, node.end)) cut.add(i);
270
+ });
271
+ const live = /* @__PURE__ */ new Set();
272
+ for (const s of kept_specs) {
273
+ const name = s.local.name;
274
+ live.add(name);
275
+ if (owners.get(name)?.some((i) => cut.has(i))) return {
276
+ ok: false,
277
+ reason: `the re-shake dropped ${name}, which the chunk still exports`,
278
+ failed: true
279
+ };
280
+ }
281
+ const queue = [...body.keys()].filter((i) => body[i] !== list && body[i].type !== "ImportDeclaration" && !cut.has(i));
282
+ for (let i = queue.pop(); i !== void 0; i = queue.pop()) for (const name of outside_names(body[i])) {
283
+ live.add(name);
284
+ for (const o of owners.get(name) ?? []) if (cut.delete(o)) queue.push(o);
285
+ }
286
+ if (live.has("eval")) return {
287
+ ok: false,
288
+ reason: "it calls eval, which may read any name",
289
+ failed: false
290
+ };
291
+ const s = new MagicString(code);
292
+ const statements = [];
293
+ body.forEach((node, i) => {
294
+ if (cut.has(i)) {
295
+ const [from, to] = cut_span(code, facts, i);
296
+ s.remove(from, to);
297
+ return;
298
+ }
299
+ let text = null;
300
+ if (node === list) text = list_text;
301
+ else if (node.type === "ImportDeclaration") text = import_text(code, node, live);
302
+ if (text === null) statements.push(code.slice(node.start, node.end));
303
+ else if (text !== "") {
304
+ s.overwrite(node.start, node.end, text);
305
+ statements.push(text);
306
+ } else {
307
+ const [from, to] = whole_lines(code, node.start, node.end);
308
+ s.remove(from, to);
309
+ }
310
+ });
311
+ drop_emptied_module_headers(code, facts, cut, s);
312
+ const next = s.toString();
313
+ const reread = parse_module(next, chunk.fileName);
314
+ const read_as = reread.ok ? reread.program.body.map((n) => next.slice(n.start, n.end)) : [];
315
+ if (read_as.length !== statements.length || read_as.some((t, i) => t !== statements[i])) return {
316
+ ok: false,
317
+ reason: "the chunk reads differently once cut",
318
+ failed: true
319
+ };
320
+ return {
321
+ ok: true,
322
+ code: next,
323
+ map: chunk.map ? remapping([s.generateMap({
324
+ hires: true,
325
+ source: chunk.fileName,
326
+ file: chunk.fileName
327
+ }), chunk.map], () => null) : null,
328
+ exports: kept_specs.map((x) => name_of(x.exported)),
329
+ dropped
330
+ };
331
+ }
332
+ function drop_emptied_module_headers(code, facts, cut, s) {
333
+ const { body, comments } = facts;
334
+ const heads = [];
335
+ let i = 0;
336
+ for (const c of comments) {
337
+ if (c.type !== "Line") continue;
338
+ while (i < body.length && body[i].end <= c.start) i++;
339
+ if (i < body.length && body[i].start < c.end) continue;
340
+ heads.push({
341
+ at: i,
342
+ c
343
+ });
344
+ }
345
+ heads.forEach(({ at, c }, k) => {
346
+ const until = heads[k + 1]?.at ?? body.length;
347
+ let any = false;
348
+ for (let j = at; j < until; j++) {
349
+ const node = body[j];
350
+ if (node === facts.plain_export_list || node.type === "ImportDeclaration") continue;
351
+ if (!cut.has(j)) return;
352
+ any = true;
353
+ }
354
+ if (!any) return;
355
+ const [from, to] = whole_lines(code, c.start, c.end);
356
+ if (from === c.start && to === c.end) return;
357
+ s.remove(from, to);
358
+ });
359
+ }
360
+ /**
361
+ * Drop each non-entry chunk's exports that no chunk imports, and the code only they reached, until
362
+ * nothing changes. Chunks are edited in place (code, map, exports).
363
+ */
364
+ async function drop_dead_exports(chunks, reshake) {
365
+ const report = {
366
+ dropped: /* @__PURE__ */ new Map(),
367
+ kept: [],
368
+ bytes: 0
369
+ };
370
+ const settled = /* @__PURE__ */ new Set();
371
+ const by_file = new Map(chunks.map((c) => [c.fileName, c]));
372
+ for (;;) {
373
+ const facts = /* @__PURE__ */ new Map();
374
+ for (const c of chunks) {
375
+ const f = read_chunk(c);
376
+ if (f === null) {
377
+ report.kept.push({
378
+ file: c.fileName,
379
+ reason: "it does not parse, so what it imports is unknown",
380
+ failed: true
381
+ });
382
+ return report;
383
+ }
384
+ facts.set(c.fileName, f);
385
+ }
386
+ const demand = /* @__PURE__ */ new Map();
387
+ for (const f of facts.values()) for (const d of f.demands) {
388
+ if (!by_file.has(d.target)) continue;
389
+ const had = demand.get(d.target) ?? /* @__PURE__ */ new Set();
390
+ if (had === "all" || d.names === "all") demand.set(d.target, "all");
391
+ else demand.set(d.target, /* @__PURE__ */ new Set([...had, ...d.names]));
392
+ }
393
+ let changed = false;
394
+ for (const c of chunks) {
395
+ if (c.isEntry || c.isDynamicEntry || settled.has(c.fileName)) continue;
396
+ const asked = demand.get(c.fileName) ?? /* @__PURE__ */ new Set();
397
+ if (asked === "all") continue;
398
+ const f = facts.get(c.fileName);
399
+ if (f.plain_export_list === null) {
400
+ if (c.exports.some((e) => !asked.has(e))) report.kept.push({
401
+ file: c.fileName,
402
+ reason: "its exports are not one plain list",
403
+ failed: false
404
+ });
405
+ settled.add(c.fileName);
406
+ continue;
407
+ }
408
+ if (f.plain_export_list.specifiers.every((s) => asked.has(name_of(s.exported)))) continue;
409
+ if (file_name_in_text(c.fileName, facts)) {
410
+ report.kept.push({
411
+ file: c.fileName,
412
+ reason: "its file name is written in the bundle as text",
413
+ failed: false
414
+ });
415
+ settled.add(c.fileName);
416
+ continue;
417
+ }
418
+ const out = await shake_chunk(c, f, asked, reshake);
419
+ if (!out.ok) {
420
+ report.kept.push({
421
+ file: c.fileName,
422
+ reason: out.reason,
423
+ failed: out.failed
424
+ });
425
+ settled.add(c.fileName);
426
+ continue;
427
+ }
428
+ report.bytes += Buffer.byteLength(c.code) - Buffer.byteLength(out.code);
429
+ report.dropped.set(c.fileName, [...report.dropped.get(c.fileName) ?? [], ...out.dropped]);
430
+ c.code = out.code;
431
+ if (out.map) c.map = out.map;
432
+ c.exports = out.exports;
433
+ changed = true;
434
+ }
435
+ if (!changed) return report;
436
+ }
437
+ }
438
+ function vite_own_rolldown() {
439
+ return createRequire(createRequire(import.meta.url).resolve("vite")).resolve("rolldown");
440
+ }
441
+ /** The bundler at `locate()`, as a {@link Reshake}; null when it cannot be loaded. */
442
+ async function bundler_reshake(locate = vite_own_rolldown) {
443
+ let rolldown;
444
+ try {
445
+ ({rolldown} = await import(pathToFileURL(locate()).href));
446
+ } catch {
447
+ return null;
448
+ }
449
+ const ID = "ogygia-chunk.js";
450
+ return async (code) => {
451
+ const bundle = await rolldown({
452
+ input: ID,
453
+ external: (id) => id !== ID,
454
+ logLevel: "silent",
455
+ treeshake: { moduleSideEffects: true },
456
+ plugins: [{
457
+ name: "ogygia:chunk",
458
+ resolveId: (id) => id === ID ? id : null,
459
+ load: (id) => id === ID ? code : null
460
+ }]
461
+ });
462
+ try {
463
+ const [out] = (await bundle.generate({
464
+ format: "esm",
465
+ sourcemap: true
466
+ })).output;
467
+ if (out.map) return out.map.mappings;
468
+ const parsed = parse_module(out.code, ID);
469
+ return parsed.ok && parsed.program.body.every((n) => n.type === "ImportDeclaration") ? "" : null;
470
+ } finally {
471
+ await bundle.close();
472
+ }
473
+ };
474
+ }
475
+ /** The server leg's pass: {@link drop_dead_exports} with the bundler Vite builds with, over a
476
+ * finished bundle (a changed chunk's map file written again). A chunk a step failed on stays as
477
+ * written, and the build says `server_exports_kept`. */
478
+ async function shake_server_bundle(bundle, reshake) {
479
+ if (reshake === null) {
480
+ warn("server_exports_kept", {
481
+ file: "every chunk",
482
+ reason: "the bundler Vite builds with could not be loaded"
483
+ });
484
+ return null;
485
+ }
486
+ const chunks = [];
487
+ for (const item of Object.values(bundle)) if (item.type === "chunk") chunks.push(item);
488
+ const report = await drop_dead_exports(chunks, reshake);
489
+ for (const k of report.kept) if (k.failed) warn("server_exports_kept", {
490
+ file: k.file,
491
+ reason: k.reason
492
+ });
493
+ for (const file of report.dropped.keys()) {
494
+ const chunk = bundle[file];
495
+ const asset = bundle[`${file}.map`];
496
+ if (chunk?.type === "chunk" && chunk.map && asset?.type === "asset") asset.source = JSON.stringify(chunk.map);
497
+ }
498
+ return report;
499
+ }
500
+ export { bundler_reshake, drop_dead_exports, shake_server_bundle };
@@ -1,3 +1,4 @@
1
+ import { RuntimeMarks } from "./runtime-entry.js";
1
2
  export declare const SERVER_HANDOFF = "og-server-handoff.json";
2
3
  /** `<outDir>/og-server-handoff.json`: written by the server leg, read by the client leg. */
3
4
  export declare function server_handoff_path(out_dir: string): string;
@@ -14,15 +15,25 @@ export interface ServerRegionRoot {
14
15
  * secret check (link/build-output.ts `refuse_client_secrets`). `server_regions`: its FINAL
15
16
  * server-only regions, a library host it reached late included: the client leg builds each one's
16
17
  * styles from this list, since in Kit 2 its own program never sees a host only the server bundle
17
- * imports (test/server-region-late.test.ts).
18
+ * imports (test/server-region-late.test.ts). `word`: the feature word the server bundle was made
19
+ * with (`ogygia:server/runtime-flags`), null when it never loaded; what the server's code for each
20
+ * feature is checked against (apps/palaestra/e2e/server-size.ts, the leak gate).
18
21
  */
19
22
  export interface ServerHandoff {
20
23
  readonly hosts: Set<string>;
21
24
  readonly build_key: string;
22
25
  readonly server_regions: ServerRegionRoot[];
26
+ readonly runtime: HandedRuntime | null;
27
+ readonly word: number | null;
28
+ }
29
+ /** The runtime the server leg named in the pages it renders, made once its bundle was complete: the
30
+ * client leg ships exactly these features under this name (test/runtime-marks-reached.test.ts). */
31
+ export interface HandedRuntime {
32
+ readonly marks: RuntimeMarks;
33
+ readonly feature_hash: string;
23
34
  }
24
35
  /** The handoff file's text. */
25
- export declare function server_handoff_json(hosts: readonly string[], build_key: string, server_regions: readonly ServerRegionRoot[]): string;
36
+ export declare function server_handoff_json(hosts: readonly string[], build_key: string, server_regions: readonly ServerRegionRoot[], runtime?: HandedRuntime | null, word?: number | null): string;
26
37
  /** The handoff file's contents. A malformed field reads as empty: nothing gated, no region named,
27
38
  * never a throw. */
28
39
  export declare function parse_server_handoff(json: string): ServerHandoff;
@@ -8,11 +8,13 @@ function server_handoff_path(out_dir) {
8
8
  return path.join(out_dir, SERVER_HANDOFF);
9
9
  }
10
10
  /** The handoff file's text. */
11
- function server_handoff_json(hosts, build_key, server_regions) {
11
+ function server_handoff_json(hosts, build_key, server_regions, runtime = null, word = null) {
12
12
  return JSON.stringify({
13
13
  hosts,
14
14
  build_key,
15
- server_regions
15
+ server_regions,
16
+ runtime,
17
+ word
16
18
  });
17
19
  }
18
20
  /** The handoff file's contents. A malformed field reads as empty: nothing gated, no region named,
@@ -21,10 +23,16 @@ function parse_server_handoff(json) {
21
23
  const o = JSON.parse(json);
22
24
  const hosts = Array.isArray(o?.hosts) ? o.hosts.filter((x) => typeof x === "string") : [];
23
25
  const regions = Array.isArray(o?.server_regions) ? o.server_regions : [];
26
+ const rt = o?.runtime;
24
27
  return {
28
+ runtime: rt && typeof rt === "object" && rt.marks && typeof rt.marks === "object" && typeof rt.feature_hash === "string" ? {
29
+ marks: rt.marks,
30
+ feature_hash: rt.feature_hash
31
+ } : null,
25
32
  hosts: new Set(hosts),
26
33
  build_key: typeof o?.build_key === "string" ? o.build_key : "",
27
- server_regions: regions.filter((r) => !!r && typeof r === "object" && typeof r.iid === "string" && typeof r.abs === "string")
34
+ server_regions: regions.filter((r) => !!r && typeof r === "object" && typeof r.iid === "string" && typeof r.abs === "string"),
35
+ word: typeof o?.word === "number" ? o.word : null
28
36
  };
29
37
  }
30
38
  /** The server leg's handoff under `out_dir`, or null when there is none (a standalone or
@@ -0,0 +1,17 @@
1
+ import { ClientRealmFile } from "./caps.js";
2
+ /**
3
+ * Emit `ogygia:boot/hooks`: each runtime hook the app's client realms subscribe to, as the runtime's
4
+ * `told` function (it tells every realm that subscribes, in realm order), and every other hook `0`,
5
+ * so the runtime's `if (hook) hook(…)` folds out where nobody hears it. `realm_count`: how many
6
+ * realms the entry hands the boot. `lazy_hooks`: the lazy chunks' hooks the realms subscribe to,
7
+ * as one object for the boot link (`0`: none).
8
+ * @param runtimeDir Absolute directory containing the runtime's modules (`hook-told.js`).
9
+ */
10
+ export declare function generateHooksSource(clients: readonly ClientRealmFile[], runtimeDir: string, ext?: string): string;
11
+ /**
12
+ * Emit `ogygia:boot/hook-bits`: each lazy chunk's hook as `1` where a client realm subscribes to it,
13
+ * else `0`. One character each: the bundler inlines a shared constant that short into every chunk
14
+ * that reads it, so a lazy chunk imports no module of the boot's (no extra file under Kit's
15
+ * chunking), and its `if (HOOK_X)` folds as the boot's `if (hook)` does.
16
+ */
17
+ export declare function generateHookBitsSource(clients: readonly ClientRealmFile[]): string;
@@ -0,0 +1,35 @@
1
+ import { runtime_path } from "./runtime-entry.js";
2
+ import { LAZY_HOOK_NAMES, RUNTIME_HOOK_NAMES } from "@ogygia/core/contract";
3
+ // src/link/hooks.ts
4
+ function subscribed_by(clients) {
5
+ return new Set(clients.flatMap((c) => c.hooks));
6
+ }
7
+ /**
8
+ * Emit `ogygia:boot/hooks`: each runtime hook the app's client realms subscribe to, as the runtime's
9
+ * `told` function (it tells every realm that subscribes, in realm order), and every other hook `0`,
10
+ * so the runtime's `if (hook) hook(…)` folds out where nobody hears it. `realm_count`: how many
11
+ * realms the entry hands the boot. `lazy_hooks`: the lazy chunks' hooks the realms subscribe to,
12
+ * as one object for the boot link (`0`: none).
13
+ * @param runtimeDir Absolute directory containing the runtime's modules (`hook-told.js`).
14
+ */
15
+ function generateHooksSource(clients, runtimeDir, ext = ".js") {
16
+ const on = subscribed_by(clients);
17
+ const lines = [];
18
+ if (on.size) lines.push(`import { told } from ${JSON.stringify(runtime_path(runtimeDir, `hook-told${ext}`))};`);
19
+ for (const name of RUNTIME_HOOK_NAMES) lines.push(on.has(name) ? `export const ${name} = /* @__PURE__ */ told(${JSON.stringify(name)});` : `export const ${name} = 0;`);
20
+ lines.push(`export const realm_count = ${clients.length};`);
21
+ const lazy = LAZY_HOOK_NAMES.filter((h) => on.has(h));
22
+ lines.push(`export const lazy_hooks = ${lazy.length ? `{ ${lazy.join(", ")} }` : "0"};`);
23
+ return `${lines.join("\n")}\n`;
24
+ }
25
+ /**
26
+ * Emit `ogygia:boot/hook-bits`: each lazy chunk's hook as `1` where a client realm subscribes to it,
27
+ * else `0`. One character each: the bundler inlines a shared constant that short into every chunk
28
+ * that reads it, so a lazy chunk imports no module of the boot's (no extra file under Kit's
29
+ * chunking), and its `if (HOOK_X)` folds as the boot's `if (hook)` does.
30
+ */
31
+ function generateHookBitsSource(clients) {
32
+ const on = subscribed_by(clients);
33
+ return `${LAZY_HOOK_NAMES.map((h) => `export const ${h} = ${on.has(h) ? 1 : 0};`).join("\n")}\n`;
34
+ }
35
+ export { generateHookBitsSource, generateHooksSource };
@@ -45,6 +45,11 @@ export declare function remote_hash_of(module_id: string, cwd: string): string |
45
45
  * @param entries Which emitted file is which entry. Every map is keyed by an entry's IDENTITY (the
46
46
  * stable public URL SSR bakes), never by its hashed name. `islands`: hashed file name →
47
47
  * identity; `runtime`: the runtime's identity. Absent → a facade-named file is its own identity.
48
+ * @param hydrate_core The hydrate core's module id (`<runtime dir>/hydrate-core.js`, real path).
49
+ * The chunk that bundles it and that chunk's static imports are `wake`: what the runtime's first
50
+ * island wake imports, which a page whose islands wake at load can start early. Matched exactly.
51
+ * The runtime's own static imports are left out (the runtime's bootstrap preloads them). Absent →
52
+ * `wake` is empty.
48
53
  * @internal Exported for unit tests.
49
54
  */
50
55
  export declare function collectIslandDepModulepreloads(bundle: Record<string, {
@@ -61,8 +66,10 @@ export declare function collectIslandDepModulepreloads(bundle: Record<string, {
61
66
  }>, page_reader_files?: readonly string[], remote_hash?: ((module_id: string) => string | null) | null, page_keys_of?: ((module_id: string) => PageKeys | null) | null, read_source?: ((id: string) => string | null) | null, runtime_file?: string | null, entries?: {
62
67
  islands: ReadonlyMap<string, string>;
63
68
  runtime: string | null;
64
- } | null): {
69
+ } | null, hydrate_core?: string | null): {
65
70
  js: Record<string, string[]>;
71
+ /** the hydrate core's chunk, then its static imports (public hrefs): the first wake's code */
72
+ wake: string[];
66
73
  css: Record<string, string[]>;
67
74
  page: Record<string, boolean>;
68
75
  page_keys: Record<string, string[] | null>;