@ogygia/compiler 0.14.2 → 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.
package/dist/driver.d.ts CHANGED
@@ -3,6 +3,7 @@ import { FileEvent } from "./kit.js";
3
3
  import { RelocateCx } from "./link/relocations.js";
4
4
  import { CoreApp, CorePlugins } from "./virtual/core.js";
5
5
  import { Leg, Part } from "./virtual/table.js";
6
+ import { HandedRuntime, ServerHandoff } from "./link/emit-gate.js";
6
7
  import { StepMap } from "./map-chain.js";
7
8
  import { BuildLeg } from "./leg.js";
8
9
  import { Program } from "./program.js";
@@ -21,6 +22,10 @@ export interface Scan {
21
22
  * URL when the app's features change. Both legs scan the same source, so both name it alike. */
22
23
  readonly feature_hash: string;
23
24
  }
25
+ type EmittedSource = string | {
26
+ code: string;
27
+ moduleSideEffects: false;
28
+ };
24
29
  /** Shared OGYGIA_PROFILE instrument — the adapter owns the maps/counters; the driver writes into
25
30
  * them so the transform-phase metrics (and the determinism digest source) live with the transform. */
26
31
  export interface Profiler {
@@ -61,9 +66,11 @@ export declare class Compiler implements CoreApp {
61
66
  * Node). A leg that already ran in this build begins the next one (watch, a second `build()` in
62
67
  * one process): everything the last build learned is dropped. Dev is one build for the session.
63
68
  * True when this leg begins a build, so the caller runs its once-per-build work; Kit's route
64
- * answers are read afresh from there.
69
+ * answers are read afresh from there. `handoff`: what the server leg handed this client leg: the
70
+ * build's scan reads every module it compiled, and ships the runtime it named
71
+ * (test/runtime-marks-reached.test.ts).
65
72
  */
66
- start_leg(name: string, server: boolean): boolean;
73
+ start_leg(name: string, server: boolean, handoff?: ServerHandoff | null): boolean;
67
74
  /**
68
75
  * The leg a hook runs in: its environment's, else (a hook the bundler calls without one) the one
69
76
  * leg open now. Refused when that is not one leg (`build_leg_unclear`): two legs open at once
@@ -176,6 +183,12 @@ export declare class Compiler implements CoreApp {
176
183
  * adapter can call it from any hook. Populates the `Program`; the fs walk is the only side effect.
177
184
  */
178
185
  prescan(): Scan;
186
+ /**
187
+ * BUILD, server leg, once it has compiled every module (`buildEnd`): the runtime its pages name.
188
+ * It reads what the leg compiled as the client leg's scan reads its handoff, so both legs name one
189
+ * runtime, and the client leg ships exactly it (test/runtime-marks-reached.test.ts).
190
+ */
191
+ server_runtime(): HandedRuntime;
179
192
  /** DEV: take the modules newly marked as island code since the last drain (see above). */
180
193
  drain_closure_marks(): string[];
181
194
  /**
@@ -232,6 +245,8 @@ export declare class Compiler implements CoreApp {
232
245
  has_hydrate_regions(): boolean;
233
246
  /** The server leg's real module graph, for the client-leg handoff (link/emit-gate.ts). */
234
247
  ssr_transformed_hosts(): string[];
248
+ /** The feature word the server bundle was made with, for the handoff (null: it never loaded). */
249
+ server_word(): number | null;
235
250
  /**
236
251
  * Client leg: the runtime chunk + one deterministic chunk per deduped hydrate region. `loaded` —
237
252
  * the server leg's transformed-module set (the handoff the plugin reads) — gates the emit to
@@ -279,12 +294,11 @@ export declare class Compiler implements CoreApp {
279
294
  * region-endpoint), and the registered island/region sources (with the client leg's `$app/*`-shim +
280
295
  * lake-placeholder rewrites). Returns the source string, or `null` if `id` is not an ogygia virtual —
281
296
  * the adapter owns only the FOUC-css virtuals (they carry a Vite `moduleType`) and the Vite build
282
- * value threaded in here (the `universalHooks` path).
297
+ * value threaded in here (the `universalHooks` path). On a build's server leg, a module whose
298
+ * source is the runtime the bundle needs (`settles`) is answered once the bundler has compiled
299
+ * every other module, each read into the marks first, so the server's code is made for them all.
283
300
  */
284
- emit(id: string, leg: Leg): string | {
285
- code: string;
286
- moduleSideEffects: false;
287
- } | Promise<string> | null;
301
+ emit(id: string, leg: Leg): EmittedSource | Promise<EmittedSource | null> | null;
288
302
  /**
289
303
  * Resolve an ogygia-owned import id: the virtual-module vocabulary (config/manifest virtuals + FOUC
290
304
  * graph + client-binding stub), and the island CLIENT graph — `$app/*` shims for island importers,
@@ -348,4 +362,5 @@ export declare class Compiler implements CoreApp {
348
362
  deleted?: boolean;
349
363
  invalidate: (id: string) => void;
350
364
  }): boolean;
351
- }
365
+ }
366
+ export {};
package/dist/driver.js CHANGED
@@ -29,7 +29,7 @@ import { is_generated_specifier } from "./virtual/table.js";
29
29
  import { OgygiaError, warn } from "./messages.js";
30
30
  import { new_leg } from "./leg.js";
31
31
  import path from "node:path";
32
- import { fnv1a32, key_label, key_of } from "@ogygia/core/contract";
32
+ import { OWN_FILE_RE, feature_word, fnv1a32, key_label, key_of } from "@ogygia/core/contract";
33
33
  import { createHash } from "node:crypto";
34
34
  import { cache, say } from "@ogygia/machine";
35
35
  // src/driver.ts
@@ -48,6 +48,8 @@ const new_build = (program) => ({
48
48
  transform_cache: /* @__PURE__ */ new Map(),
49
49
  dollar_hoists: /* @__PURE__ */ new Map(),
50
50
  scan: null,
51
+ handoff: null,
52
+ server_runtime: null,
51
53
  router_css_roots: null,
52
54
  resolve_memo: /* @__PURE__ */ new Map(),
53
55
  reach_memo: /* @__PURE__ */ new Map(),
@@ -141,14 +143,17 @@ var Compiler = class Compiler {
141
143
  * Node). A leg that already ran in this build begins the next one (watch, a second `build()` in
142
144
  * one process): everything the last build learned is dropped. Dev is one build for the session.
143
145
  * True when this leg begins a build, so the caller runs its once-per-build work; Kit's route
144
- * answers are read afresh from there.
146
+ * answers are read afresh from there. `handoff`: what the server leg handed this client leg: the
147
+ * build's scan reads every module it compiled, and ships the runtime it named
148
+ * (test/runtime-marks-reached.test.ts).
145
149
  */
146
- start_leg(name, server) {
150
+ start_leg(name, server, handoff = null) {
147
151
  if (this.#build.legs.has(name) && this.#ctx.is_build) this.#build = new_build(this.#build.program.fresh());
148
152
  const build = this.#build;
149
153
  if (!build.legs.has(name)) build.legs.set(name, new_leg(name, server));
150
154
  if (build.begun) return false;
151
155
  build.begun = true;
156
+ build.handoff = handoff;
152
157
  this.#ctx.routes.db.reread();
153
158
  return true;
154
159
  }
@@ -581,7 +586,7 @@ var Compiler = class Compiler {
581
586
  const ctx = this.#ctx;
582
587
  const { prof, P } = this.profiler;
583
588
  const program = this.program;
584
- const { registry, island_graph, runtime_marks } = program;
589
+ const { island_graph, runtime_marks } = program;
585
590
  const root = ctx.root;
586
591
  const src_dir = path.join(root, "src");
587
592
  clean_stale_ogygia_dirs(src_dir);
@@ -601,11 +606,10 @@ var Compiler = class Compiler {
601
606
  key
602
607
  });
603
608
  };
604
- const scan_file = (full, name) => {
605
- const kind = scan_kind(name);
606
- if (!kind) return;
607
- const src = ctx.read_file(full);
608
- if (src == null) return;
609
+ const scan_file = (full) => {
610
+ const readable = this.#readable(full);
611
+ if (!readable) return;
612
+ const { kind, src } = readable;
609
613
  say_one_off_keys(full, src, kind);
610
614
  read_for_plugins(full, src, this.#scan_facts(full, src, kind));
611
615
  if (kind === "svelte") {
@@ -624,7 +628,7 @@ var Compiler = class Compiler {
624
628
  if (entry.kind === "dir") {
625
629
  if (entry.name === "node_modules" || entry.name === ".ogygia") continue;
626
630
  walk(full);
627
- } else scan_file(full, entry.name);
631
+ } else scan_file(full);
628
632
  }
629
633
  };
630
634
  {
@@ -632,8 +636,9 @@ var Compiler = class Compiler {
632
636
  walk(src_dir);
633
637
  for (const p of ctx.pkg_scan) {
634
638
  for (const d of p.dirs) walk(d);
635
- for (const f of p.files) scan_file(f, f.slice(f.lastIndexOf("/") + 1));
639
+ for (const f of p.files) scan_file(f);
636
640
  }
641
+ for (const f of this.#compiled_unread(this.#build.handoff?.hosts ?? [])) scan_file(f);
637
642
  for (const f of ctx.page_files) {
638
643
  if (program.scan.has(f)) continue;
639
644
  const src = ctx.read_file(f);
@@ -651,11 +656,7 @@ var Compiler = class Compiler {
651
656
  plugin: PLUGIN_PACKAGES[pkg],
652
657
  file
653
658
  }));
654
- {
655
- const __ws = P ? performance.now() : 0;
656
- for (const entry of registry.values()) if (entry.componentPath) this.mark_island_closure(entry.componentPath);
657
- if (P) prof.prescanMs += performance.now() - __ws;
658
- }
659
+ this.#walk_closures();
659
660
  if (!runtime_marks.context) {
660
661
  const reads = [];
661
662
  const island_set = /* @__PURE__ */ new Set();
@@ -678,14 +679,133 @@ var Compiler = class Compiler {
678
679
  });
679
680
  }
680
681
  }
682
+ const feature_hash = this.#seal_marks();
683
+ const handoff = this.#build.handoff;
684
+ if (!handoff) return { feature_hash };
685
+ const handed = handoff.runtime;
686
+ if (!handed) throw new OgygiaError("server_runtime_unnamed");
687
+ const named = new Set(resolveFeatures(handed.marks));
688
+ const unnamed = resolveFeatures(runtime_marks).filter((f) => !named.has(f));
689
+ if (unnamed.length) throw new OgygiaError("runtime_features_unnamed", { features: unnamed.join(", ") });
690
+ for (const key of Object.keys(runtime_marks)) delete runtime_marks[key];
691
+ Object.assign(runtime_marks, structuredClone(handed.marks));
692
+ return { feature_hash: handed.feature_hash };
693
+ }
694
+ /** A file the scan reads for regions, as the transform reads it (`#region_reading`): its kind and
695
+ * source, or null. */
696
+ #readable(full) {
697
+ const kind = scan_kind(path.basename(full));
698
+ if (!kind) return null;
699
+ const reading = this.#region_reading(full, kind);
700
+ if (reading === "never") return null;
701
+ const src = this.#ctx.read_file(full);
702
+ if (src == null) return null;
703
+ if (reading === "hinted" && !this.#ctx.has_island_hint(src)) return null;
704
+ return {
705
+ kind,
706
+ src
707
+ };
708
+ }
709
+ /** The modules a server leg compiled that the scan has not read: never a region's own module, nor
710
+ * ogygia's (its entry re-exports every feature, so it would turn each one on). */
711
+ #compiled_unread(compiled) {
712
+ const { scan } = this.program;
713
+ return [...compiled].filter((f) => !scan.has(f) && !is_island_path(f) && !OWN_FILE_RE.test(f));
714
+ }
715
+ /** Walk each registered region's island closure (what reaches Kit's page world); `page_by`
716
+ * hears the component whose closure first reads the page. */
717
+ #walk_closures(page_by) {
718
+ const { prof, P } = this.profiler;
719
+ const __ws = P ? performance.now() : 0;
720
+ for (const entry of this.program.registry.values()) {
721
+ if (!entry.componentPath) continue;
722
+ const read = this.program.island_reads_page;
723
+ this.mark_island_closure(entry.componentPath);
724
+ if (!read && this.program.island_reads_page) page_by?.(entry.componentPath);
725
+ }
726
+ if (P) prof.prescanMs += performance.now() - __ws;
727
+ }
728
+ /** Fold the build's options into the runtime marks and close them: the feature hash the runtime
729
+ * is named by. */
730
+ #seal_marks() {
731
+ const ctx = this.#ctx;
732
+ const { runtime_marks } = this.program;
681
733
  runtime_marks.foreign = ctx.foreign_hydrate;
682
- runtime_marks.page = program.island_reads_page || runtime_marks.foreign || ctx.client_plugins.length > 0;
734
+ runtime_marks.page = this.program.island_reads_page || runtime_marks.foreign;
683
735
  runtime_marks.complete = true;
684
- return { feature_hash: createHash("sha256").update(resolveFeatures(runtime_marks).join(",")).digest("hex").slice(0, 8) };
736
+ return createHash("sha256").update(resolveFeatures(runtime_marks).join(",")).digest("hex").slice(0, 8);
737
+ }
738
+ /**
739
+ * BUILD, server leg, once it has compiled every module (`buildEnd`): the runtime its pages name.
740
+ * It reads what the leg compiled as the client leg's scan reads its handoff, so both legs name one
741
+ * runtime, and the client leg ships exactly it (test/runtime-marks-reached.test.ts).
742
+ */
743
+ server_runtime() {
744
+ return this.#build.server_runtime ??= this.#seal_server_runtime();
745
+ }
746
+ /** Read each module the server leg compiled that the scan has not, as the scan reads `src/`, then
747
+ * close the marks; `read` hears each file it read. Returns the feature hash. */
748
+ #read_server_compiled(read, page_by) {
749
+ this.prescan();
750
+ for (const f of this.#compiled_unread(this.program.ssr_transformed)) {
751
+ const readable = this.#readable(f);
752
+ if (!readable) continue;
753
+ this.#scan_facts(f, readable.src, readable.kind);
754
+ read?.(f);
755
+ }
756
+ this.#walk_closures(page_by);
757
+ return this.#seal_marks();
758
+ }
759
+ #seal_server_runtime() {
760
+ const word = this.program.server_word;
761
+ const needed_by = new Map(this.program.server_late);
762
+ const feature_hash = this.#read_server_compiled((f) => {
763
+ if (word === null) return;
764
+ for (const id of resolveFeatures({
765
+ ...this.program.runtime_marks,
766
+ complete: true
767
+ })) if (!(word & feature_word([id])) && !needed_by.has(id)) needed_by.set(id, f);
768
+ }, (component) => needed_by.set("page", component));
769
+ const marks = structuredClone(this.program.runtime_marks);
770
+ if (word !== null) this.#refuse_late_features(marks, word, needed_by);
771
+ const shipped = this.program.shipped_features;
772
+ if (!shipped) return {
773
+ marks,
774
+ feature_hash
775
+ };
776
+ const unnamed = resolveFeatures(marks).filter((f) => !shipped.has(f));
777
+ if (unnamed.length) throw new OgygiaError("runtime_features_unnamed", { features: unnamed.join(", ") });
778
+ return {
779
+ marks,
780
+ feature_hash: this.#build.scan?.feature_hash ?? feature_hash
781
+ };
782
+ }
783
+ /** Stops the build when the server's settled runtime needs a feature its bundle's word, fixed as
784
+ * `ogygia:server/runtime-flags` loaded, left out: the server code for it is not in the bundle. */
785
+ #refuse_late_features(marks, word, needed_by) {
786
+ const left = resolveFeatures(marks).filter((id) => !(word & feature_word([id])));
787
+ if (!left.length) return;
788
+ const modules = /* @__PURE__ */ new Set();
789
+ for (const id of left) {
790
+ const file = needed_by.get(id);
791
+ if (file) modules.add(prescan_rel(this.#ctx, file));
792
+ }
793
+ throw new OgygiaError("server_features_late", {
794
+ features: left.join(", "),
795
+ modules: [...modules].join(", ") || "a region one of them reaches"
796
+ });
797
+ }
798
+ /** Whether the regions of `id` are read: always (app source, a declared `ogygia.files` file), when
799
+ * its source names an import key (any other installed component), or never (any other installed
800
+ * script). The transform and the scan share it, so the scan knows each region the bundle places. */
801
+ #region_reading(id, kind) {
802
+ const p = id.split(path.sep).join("/");
803
+ if (!p.includes("/node_modules/") || this.#ctx.in_declared_pkg(p)) return "always";
804
+ return kind === "svelte" ? "hinted" : "never";
685
805
  }
686
806
  /** The scan's feature hash; empty before the scan ran. */
687
807
  get #feature_hash() {
688
- return this.#build.scan?.feature_hash ?? "";
808
+ return this.#build.server_runtime?.feature_hash ?? this.#build.scan?.feature_hash ?? "";
689
809
  }
690
810
  /** DEV: modules `mark_island_closure` marked for the first time AFTER prescan — an island a later
691
811
  * transform registered (a file added while the server runs). Each may already sit in the dev
@@ -843,6 +963,10 @@ var Compiler = class Compiler {
843
963
  ssr_transformed_hosts() {
844
964
  return [...this.program.ssr_transformed].sort();
845
965
  }
966
+ /** The feature word the server bundle was made with, for the handoff (null: it never loaded). */
967
+ server_word() {
968
+ return this.program.server_word;
969
+ }
846
970
  /**
847
971
  * Client leg: the runtime chunk + one deterministic chunk per deduped hydrate region. `loaded` —
848
972
  * the server leg's transformed-module set (the handoff the plugin reads) — gates the emit to
@@ -961,9 +1085,12 @@ var Compiler = class Compiler {
961
1085
  * region-endpoint), and the registered island/region sources (with the client leg's `$app/*`-shim +
962
1086
  * lake-placeholder rewrites). Returns the source string, or `null` if `id` is not an ogygia virtual —
963
1087
  * the adapter owns only the FOUC-css virtuals (they carry a Vite `moduleType`) and the Vite build
964
- * value threaded in here (the `universalHooks` path).
1088
+ * value threaded in here (the `universalHooks` path). On a build's server leg, a module whose
1089
+ * source is the runtime the bundle needs (`settles`) is answered once the bundler has compiled
1090
+ * every other module, each read into the marks first, so the server's code is made for them all.
965
1091
  */
966
1092
  emit(id, leg) {
1093
+ if (leg.ssr && leg.compiled && this.#virtuals.settles(id)) return this.#emit_settled(id, leg, leg.compiled);
967
1094
  const ctx = this.#ctx;
968
1095
  const program = this.program;
969
1096
  const { ssr } = leg;
@@ -992,6 +1119,12 @@ var Compiler = class Compiler {
992
1119
  if (ctx.is_dev && this.#virtuals.claims(id)) this.#unanswered.add(id);
993
1120
  return null;
994
1121
  }
1122
+ async #emit_settled(id, leg, compiled) {
1123
+ await compiled((m) => this.#virtuals.settles(m));
1124
+ this.#read_server_compiled();
1125
+ const { compiled: _, ...answered } = leg;
1126
+ return this.emit(id, answered);
1127
+ }
995
1128
  /** DEV: the registry's modules a load answered null for while no host held them (`moved`). */
996
1129
  #unanswered = /* @__PURE__ */ new Set();
997
1130
  /**
@@ -1281,7 +1414,7 @@ var Compiler = class Compiler {
1281
1414
  const in_node_modules = id_n.includes("/node_modules/");
1282
1415
  const bare_v = id_n.startsWith("/@id/") ? id_n.slice(5) : id_n;
1283
1416
  const portable_entry = id_n.endsWith(".svelte") && is_island_path(bare_v) && registry.get(bare_v)?.portable === true;
1284
- if (id_n.endsWith(".svelte") && is_script_request(id) && (!is_island_path(bare_v) || portable_entry) && (!in_node_modules || ctx.in_declared_pkg(bare_v) || ctx.has_island_hint(code))) {
1417
+ if (id_n.endsWith(".svelte") && is_script_request(id) && (!is_island_path(bare_v) || portable_entry) && (this.#region_reading(bare_v, "svelte") === "always" || ctx.has_island_hint(code))) {
1285
1418
  const result = this.transform(out, id_n, { ssr });
1286
1419
  if (result) {
1287
1420
  this.#register(result, id_n);
@@ -1302,7 +1435,7 @@ var Compiler = class Compiler {
1302
1435
  }
1303
1436
  const nm_ts = id_n.endsWith(".ts") || id_n.endsWith(".js") || id_n.endsWith(".mjs") ? id_n.includes("/node_modules/") : null;
1304
1437
  if (nm_ts === true && !id_n.startsWith(ctx.pkg_root) && !ctx.in_declared_pkg(id_n) && ctx.has_island_hint(out) && ctx.has_marked_import(out, id_n)) warn_undeclared_pkg_marks(id_n);
1305
- if (nm_ts !== null && (nm_ts === false || ctx.in_declared_pkg(id_n)) && !is_island_path(id_n)) {
1438
+ if (nm_ts !== null && this.#region_reading(id_n, "script") === "always" && !is_island_path(id_n)) {
1306
1439
  const result = this.ts_regions(out, id_n);
1307
1440
  if (result) {
1308
1441
  this.#register(result, id_n);
@@ -1358,7 +1491,8 @@ var Compiler = class Compiler {
1358
1491
  facade_file: bundle.facade_file,
1359
1492
  graph: bundle.graph,
1360
1493
  module_ids: bundle.module_ids,
1361
- page_reads: ctx.page_reads
1494
+ page_reads: ctx.page_reads,
1495
+ runtime_url: () => ctx.runtime_chunk_url(this.server_runtime().feature_hash)
1362
1496
  });
1363
1497
  if (out === null) return null;
1364
1498
  const { s, mapped } = out;
package/dist/kit.d.ts CHANGED
@@ -20,6 +20,8 @@ export interface Routes {
20
20
  readonly at: Query<string, "file" | "dir" | null>;
21
21
  /** Each option file's `csr`. */
22
22
  readonly csr_of_file: Query<string, boolean | undefined>;
23
+ /** Each option file: does it export `csr` in a form the build cannot read (not a literal)? */
24
+ readonly csr_unread_of_file: Query<string, boolean>;
23
25
  /** Each module's claimed `config` keys. */
24
26
  readonly config_of_file: Query<Keyed, Record<string, unknown>>;
25
27
  /** routesDir → Kit's route tree of it (its shape: which nodes, which layouts each page uses). */
@@ -91,6 +93,13 @@ export interface KitConfig {
91
93
  export declare function default_kit_dirs(root: string): KitDirs;
92
94
  /** Read `export const csr = true|false` from a route options file; `undefined` if unset/absent. */
93
95
  export declare function read_csr(r: Routes, file: string): boolean | undefined;
96
+ /**
97
+ * Does `export const csr` here take a value only Kit's run can know (an expression, a re-export,
98
+ * `export *`)? {@link read_csr} reads such a file as declaring nothing; a caller that must PROVE
99
+ * a document's csr (`kit_may_hydrate`) treats it as possibly true. A file that does not parse is
100
+ * unread too.
101
+ */
102
+ export declare function read_csr_unread(r: Routes, file: string): boolean;
94
103
  /**
95
104
  * The claimed keys `export const config = {…}` sets in one route module: its literal-valued top-level
96
105
  * properties named in `keys`. `{}` when the file, the export or the keys are absent (a spread or a
@@ -136,6 +145,14 @@ export declare function errorCsrTrueRouteIds(r: Routes, routesDir: string): stri
136
145
  /** The error-render csr of a ROUTELESS response (no route matched: Kit renders the root layout and
137
146
  * the root error page) — the root layout's own option, Kit's default `true` when unset. */
138
147
  export declare function rootLayoutCsrTrue(r: Routes, routesDir: string): boolean;
148
+ /**
149
+ * Can Kit hydrate a document this app serves? False only when the build PROVES it cannot: every
150
+ * node of the route tree (each layout, page and error page, Kit's fallback root layout included)
151
+ * resolves to `csr = false`, so no page, error render or routeless response is Kit-hydrated, and no
152
+ * option file declares `csr` in a form only Kit's run can read ({@link read_csr_unread}). The
153
+ * runtime's mixed-mode paths ship exactly when this is true (the `kit-pages` feature).
154
+ */
155
+ export declare function kit_may_hydrate(r: Routes, routesDir: string): boolean;
139
156
  /**
140
157
  * Kit-effective `csr === false` for a page or layout host. A page reads Kit's chain: its own
141
158
  * option, else the layouts it renders in (a `@` reset skips the ones between). A LAYOUT is
package/dist/kit.js CHANGED
@@ -27,6 +27,7 @@ function route_reader(files) {
27
27
  listing,
28
28
  at,
29
29
  csr_of_file: derived("route csr", own, (cx, file) => csr_of_text(cx.get(text, file), file)),
30
+ csr_unread_of_file: derived("route csr unread", own, (cx, file) => csr_unread_of_text(cx.get(text, file), file)),
30
31
  config_of_file: derived("route config", keyed, (cx, [file, keys]) => route_config_of_text(cx.get(text, file), file, keys)),
31
32
  route_tree,
32
33
  node_csr: derived("route node csr", own, (cx, routesDir) => {
@@ -147,6 +148,38 @@ function csr_of_text(src, file) {
147
148
  const value = literal_value(page_option(program, "csr"));
148
149
  return typeof value === "boolean" ? value : void 0;
149
150
  }
151
+ /**
152
+ * Does `export const csr` here take a value only Kit's run can know (an expression, a re-export,
153
+ * `export *`)? {@link read_csr} reads such a file as declaring nothing; a caller that must PROVE
154
+ * a document's csr (`kit_may_hydrate`) treats it as possibly true. A file that does not parse is
155
+ * unread too.
156
+ */
157
+ function read_csr_unread(r, file) {
158
+ return r.db.get(r.csr_unread_of_file, file);
159
+ }
160
+ function csr_unread_of_text(src, file) {
161
+ if (src === null) return false;
162
+ if (!src.includes("export *") && !src.includes("csr")) return false;
163
+ const { program } = parse_module(src, file);
164
+ if (!program) return true;
165
+ if (!may_export(program, "csr")) return false;
166
+ return typeof literal_value(page_option(program, "csr")) !== "boolean";
167
+ }
168
+ function may_export(program, name) {
169
+ for (const statement of program.body ?? []) {
170
+ if (statement.type === "ExportAllDeclaration") {
171
+ const as = statement.exported;
172
+ if (!as || as.name === name || as.value === name) return true;
173
+ continue;
174
+ }
175
+ if (statement.type !== "ExportNamedDeclaration") continue;
176
+ const declaration = statement.declaration;
177
+ if (declaration?.id?.name === name) return true;
178
+ for (const d of declaration?.declarations ?? []) if (d.id?.name === name) return true;
179
+ for (const s of statement.specifiers ?? []) if (s.exported?.name === name || s.exported?.value === name) return true;
180
+ }
181
+ return false;
182
+ }
150
183
  function unwrap_expression(node) {
151
184
  let n = node ?? null;
152
185
  while (n && (n.type === "TSAsExpression" || n.type === "TSSatisfiesExpression" || n.type === "TSTypeAssertion" || n.type === "TSNonNullExpression" || n.type === "ParenthesizedExpression")) n = n.expression;
@@ -377,6 +410,23 @@ function rootLayoutCsrTrue(r, routesDir) {
377
410
  const tree = route_tree(r, routesDir);
378
411
  return node_csr(r, tree, tree.routes[0].layout) !== false;
379
412
  }
413
+ /**
414
+ * Can Kit hydrate a document this app serves? False only when the build PROVES it cannot: every
415
+ * node of the route tree (each layout, page and error page, Kit's fallback root layout included)
416
+ * resolves to `csr = false`, so no page, error render or routeless response is Kit-hydrated, and no
417
+ * option file declares `csr` in a form only Kit's run can read ({@link read_csr_unread}). The
418
+ * runtime's mixed-mode paths ship exactly when this is true (the `kit-pages` feature).
419
+ */
420
+ function kit_may_hydrate(r, routesDir) {
421
+ const tree = route_tree(r, routesDir);
422
+ for (const route of tree.routes) for (const f of [
423
+ ...LAYOUT_SERVER,
424
+ ...LAYOUT_UNIVERSAL,
425
+ ...PAGE_SERVER,
426
+ ...PAGE_UNIVERSAL
427
+ ]) if (read_csr_unread(r, path.join(route.dir, f))) return true;
428
+ return tree.nodes.some((node) => node_csr(r, tree, node) !== false);
429
+ }
380
430
  function layout_page_worlds(r, tree, layout) {
381
431
  let any_false = false;
382
432
  let any_true = false;
@@ -551,4 +601,4 @@ function clean_stale_ogygia_dirs(dir) {
551
601
  clean_stale_ogygia_dirs(full);
552
602
  }
553
603
  }
554
- export { DEFAULT_KIT_DIRS, KEEP_CLIENT_DIR, clean_stale_ogygia_dirs, clientBuildWillSkip, csrTrueRouteIds, default_kit_dirs, errorCsrTrueRouteIds, hasAnyCsrFalseRoute, hasAnyCsrTrueRoute, inject_keep_client_route, is_route_component, keep_client_dir, kit_major, normalize_route_id, page_route_config, read_csr, read_route_config, resolve_kit_paths, rootLayoutCsrTrue, routeCsrIsFalse, routeCsrIsTrue, route_reader };
604
+ export { DEFAULT_KIT_DIRS, KEEP_CLIENT_DIR, clean_stale_ogygia_dirs, clientBuildWillSkip, csrTrueRouteIds, default_kit_dirs, errorCsrTrueRouteIds, hasAnyCsrFalseRoute, hasAnyCsrTrueRoute, inject_keep_client_route, is_route_component, keep_client_dir, kit_major, kit_may_hydrate, normalize_route_id, page_route_config, read_csr, read_csr_unread, read_route_config, resolve_kit_paths, rootLayoutCsrTrue, routeCsrIsFalse, routeCsrIsTrue, route_reader };
@@ -1,4 +1,5 @@
1
1
  import { Routes } from "../kit.js";
2
+ import { RuntimeHookName, ServerHookName } from "@ogygia/core/contract";
2
3
  /** One plugin's server realm, as the build wires it. */
3
4
  export interface ServerRealm {
4
5
  /** the plugin's (package) name */
@@ -7,6 +8,8 @@ export interface ServerRealm {
7
8
  module: string;
8
9
  /** the plugin's options (JSON) */
9
10
  options: unknown;
11
+ /** core's shared server hooks it implements (the keys of its `defineServer({ … })`) */
12
+ hooks: readonly ServerHookName[];
10
13
  }
11
14
  /** A plugin's browser realm, as the boot entry imports it. */
12
15
  export interface ClientRealmFile {
@@ -14,6 +17,8 @@ export interface ClientRealmFile {
14
17
  name: string;
15
18
  /** the realm module's absolute POSIX path (the plugin's `client`) */
16
19
  module: string;
20
+ /** the runtime hooks it subscribes to (its `defineClient({ hooks })`, read from the file) */
21
+ hooks: readonly RuntimeHookName[];
17
22
  }
18
23
  /** The boot entry's plugin list (`[{ name, client }, …]`) and the imports it names, in plugin order. */
19
24
  export declare function client_realms_source(clients: readonly ClientRealmFile[]): {
@@ -23,7 +28,8 @@ export declare function client_realms_source(clients: readonly ClientRealmFile[]
23
28
  /**
24
29
  * `server-plugins` — SERVER only: each plugin's server half, one static import per plugin, in the
25
30
  * order the app listed them. The handle runs their stages straight off this list; an app with no
26
- * plugins gets an empty one (and the client always does).
31
+ * plugins gets an empty one (and the client always does). Beside it, `plugin_count`, and a `0`/`1`
32
+ * per shared hook core calls on a request (`measures`): where no server half has it, the call folds.
27
33
  */
28
34
  export declare function server_plugins_module(ssr: boolean, realms: readonly ServerRealm[]): string;
29
35
  /** `route-config` — SERVER only: every Kit page route id → the keys the plugins claim inside Kit's
package/dist/link/caps.js CHANGED
@@ -15,10 +15,16 @@ function client_realms_source(clients) {
15
15
  /**
16
16
  * `server-plugins` — SERVER only: each plugin's server half, one static import per plugin, in the
17
17
  * order the app listed them. The handle runs their stages straight off this list; an app with no
18
- * plugins gets an empty one (and the client always does).
18
+ * plugins gets an empty one (and the client always does). Beside it, `plugin_count`, and a `0`/`1`
19
+ * per shared hook core calls on a request (`measures`): where no server half has it, the call folds.
19
20
  */
20
21
  function server_plugins_module(ssr, realms) {
21
- if (!ssr || realms.length === 0) return `export const plugins = [];`;
22
+ const measures = realms.some((r) => r.hooks.includes("measures")) ? 1 : 0;
23
+ if (!ssr || realms.length === 0) return dedent`
24
+ export const plugins = [];
25
+ export const plugin_count = 0;
26
+ export const measures = 0;
27
+ `;
22
28
  const imports = realms.map((r, i) => `import p${i} from ${JSON.stringify(r.module)};`).join("\n");
23
29
  const list = realms.map((r, i) => `{ name: ${JSON.stringify(r.name)}, options: ${JSON.stringify(r.options)}, server: p${i} }`).join(",\n ");
24
30
  return dedent`
@@ -27,6 +33,8 @@ function server_plugins_module(ssr, realms) {
27
33
  export const plugins = [
28
34
  ${list}
29
35
  ];
36
+ export const plugin_count = ${realms.length};
37
+ export const measures = ${measures};
30
38
  `;
31
39
  }
32
40
  /** `route-config` — SERVER only: every Kit page route id → the keys the plugins claim inside Kit's
@@ -0,0 +1,49 @@
1
+ import { SourceMapInput } from "@jridgewell/remapping";
2
+ /** A chunk of a finished server bundle: the fields of the bundler's output chunk this pass reads and
3
+ * writes. */
4
+ export interface ShakeChunk {
5
+ readonly fileName: string;
6
+ code: string;
7
+ map: SourceMapInput | null;
8
+ exports: string[];
9
+ readonly isEntry: boolean;
10
+ readonly isDynamicEntry: boolean;
11
+ }
12
+ /** Re-bundle one module (every import external) and give its output map's `mappings`, or null
13
+ * when the bundler wrote no map. */
14
+ export type Reshake = (code: string) => Promise<string | null>;
15
+ /** What the pass did. */
16
+ export interface ShakeReport {
17
+ /** Each changed chunk's dropped exports (their exported names). */
18
+ readonly dropped: Map<string, string[]>;
19
+ /** Chunks with dead exports the pass kept, and why: by a rule, or because a step failed
20
+ * (`failed`, which the build says). */
21
+ readonly kept: Kept[];
22
+ /** Bytes the pass took out of the bundle's code. */
23
+ bytes: number;
24
+ }
25
+ /** A chunk that keeps its dead exports. */
26
+ export interface Kept {
27
+ readonly file: string;
28
+ readonly reason: string;
29
+ readonly failed: boolean;
30
+ }
31
+ /**
32
+ * Drop each non-entry chunk's exports that no chunk imports, and the code only they reached, until
33
+ * nothing changes. Chunks are edited in place (code, map, exports).
34
+ */
35
+ export declare function drop_dead_exports(chunks: readonly ShakeChunk[], reshake: Reshake): Promise<ShakeReport>;
36
+ /** The bundler at `locate()`, as a {@link Reshake}; null when it cannot be loaded. */
37
+ export declare function bundler_reshake(locate?: () => string): Promise<Reshake | null>;
38
+ /** A finished bundle as `generateBundle` holds it: chunks, and assets (a chunk's map among them). */
39
+ export type ShakeBundle = Record<string, ({
40
+ type: "chunk";
41
+ } & ShakeChunk) | {
42
+ type: "asset";
43
+ fileName: string;
44
+ source: string | Uint8Array;
45
+ }>;
46
+ /** The server leg's pass: {@link drop_dead_exports} with the bundler Vite builds with, over a
47
+ * finished bundle (a changed chunk's map file written again). A chunk a step failed on stays as
48
+ * written, and the build says `server_exports_kept`. */
49
+ export declare function shake_server_bundle(bundle: ShakeBundle, reshake: Reshake | null): Promise<ShakeReport | null>;