@ogygia/compiler 0.0.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +62 -1
  3. package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js +5 -0
  4. package/dist/app-spec.d.ts +18 -0
  5. package/dist/app-spec.js +22 -0
  6. package/dist/blank-styles.d.ts +1 -0
  7. package/dist/blank-styles.js +24 -0
  8. package/dist/bom.d.ts +2 -0
  9. package/dist/bom.js +7 -0
  10. package/dist/build-cache.d.ts +13 -0
  11. package/dist/build-cache.js +65 -0
  12. package/dist/ctx.d.ts +238 -0
  13. package/dist/ctx.js +221 -0
  14. package/dist/dev/css-scope.d.ts +16 -0
  15. package/dist/dev/css-scope.js +32 -0
  16. package/dist/dev/dev-hmr.d.ts +24 -0
  17. package/dist/dev/dev-hmr.js +51 -0
  18. package/dist/dev/hmr.d.ts +34 -0
  19. package/dist/dev/hmr.js +52 -0
  20. package/dist/driver.d.ts +349 -0
  21. package/dist/driver.js +1401 -0
  22. package/dist/exports/index.d.ts +77 -0
  23. package/dist/exports/index.js +349 -0
  24. package/dist/exports/parse.d.ts +65 -0
  25. package/dist/exports/parse.js +251 -0
  26. package/dist/fouc-css.d.ts +102 -0
  27. package/dist/fouc-css.js +304 -0
  28. package/dist/free-vars.d.ts +32 -0
  29. package/dist/free-vars.js +454 -0
  30. package/dist/fs.d.ts +31 -0
  31. package/dist/fs.js +82 -0
  32. package/dist/ids.d.ts +49 -0
  33. package/dist/ids.js +52 -0
  34. package/dist/index.d.ts +23 -0
  35. package/dist/index.js +23 -0
  36. package/dist/kit.d.ts +204 -0
  37. package/dist/kit.js +554 -0
  38. package/dist/leg.d.ts +34 -0
  39. package/dist/leg.js +26 -0
  40. package/dist/link/analyses.d.ts +26 -0
  41. package/dist/link/analyses.js +237 -0
  42. package/dist/link/build-output.d.ts +47 -0
  43. package/dist/link/build-output.js +168 -0
  44. package/dist/link/caps.d.ts +32 -0
  45. package/dist/link/caps.js +39 -0
  46. package/dist/link/context-detect.d.ts +28 -0
  47. package/dist/link/context-detect.js +143 -0
  48. package/dist/link/emit-gate.d.ts +43 -0
  49. package/dist/link/emit-gate.js +55 -0
  50. package/dist/link/file-token.d.ts +11 -0
  51. package/dist/link/file-token.js +15 -0
  52. package/dist/link/island-deps.d.ts +183 -0
  53. package/dist/link/island-deps.js +802 -0
  54. package/dist/link/location-map.d.ts +24 -0
  55. package/dist/link/location-map.js +51 -0
  56. package/dist/link/own-reach.d.ts +15 -0
  57. package/dist/link/own-reach.js +188 -0
  58. package/dist/link/registry-stub.d.ts +50 -0
  59. package/dist/link/registry-stub.js +163 -0
  60. package/dist/link/relocations.d.ts +79 -0
  61. package/dist/link/relocations.js +198 -0
  62. package/dist/link/router-css.d.ts +38 -0
  63. package/dist/link/router-css.js +124 -0
  64. package/dist/link/runtime-entry.d.ts +103 -0
  65. package/dist/link/runtime-entry.js +183 -0
  66. package/dist/link/server-manifest.d.ts +25 -0
  67. package/dist/link/server-manifest.js +102 -0
  68. package/dist/link/transport.d.ts +42 -0
  69. package/dist/link/transport.js +91 -0
  70. package/dist/macros/dollar.d.ts +24 -0
  71. package/dist/macros/dollar.js +397 -0
  72. package/dist/macros/pipeline.d.ts +50 -0
  73. package/dist/macros/pipeline.js +133 -0
  74. package/dist/macros/source.d.ts +9 -0
  75. package/dist/macros/source.js +115 -0
  76. package/dist/macros/store.d.ts +22 -0
  77. package/dist/macros/store.js +217 -0
  78. package/dist/macros/wire.d.ts +17 -0
  79. package/dist/macros/wire.js +116 -0
  80. package/dist/map-chain.d.ts +18 -0
  81. package/dist/map-chain.js +42 -0
  82. package/dist/messages.d.ts +672 -0
  83. package/dist/messages.js +938 -0
  84. package/dist/ownership-stamps.d.ts +9 -0
  85. package/dist/ownership-stamps.js +101 -0
  86. package/dist/parse/oxc.d.ts +36 -0
  87. package/dist/parse/oxc.js +35 -0
  88. package/dist/parse/roots.d.ts +4 -0
  89. package/dist/parse/roots.js +27 -0
  90. package/dist/parse/scan.d.ts +65 -0
  91. package/dist/parse/scan.js +297 -0
  92. package/dist/parse/svelte-ast.d.ts +7 -0
  93. package/dist/parse/svelte-ast.js +99 -0
  94. package/dist/program.d.ts +140 -0
  95. package/dist/program.js +304 -0
  96. package/dist/queries.d.ts +105 -0
  97. package/dist/queries.js +326 -0
  98. package/dist/region/emit.d.ts +168 -0
  99. package/dist/region/emit.js +292 -0
  100. package/dist/region/identity.d.ts +32 -0
  101. package/dist/region/identity.js +46 -0
  102. package/dist/region/ir.d.ts +56 -0
  103. package/dist/region/ir.js +0 -0
  104. package/dist/region/marked-imports.d.ts +27 -0
  105. package/dist/region/marked-imports.js +265 -0
  106. package/dist/region/transform.d.ts +189 -0
  107. package/dist/region/transform.js +1565 -0
  108. package/dist/scan-facts.d.ts +36 -0
  109. package/dist/scan-facts.js +54 -0
  110. package/dist/script-request.d.ts +1 -0
  111. package/dist/script-request.js +33 -0
  112. package/dist/splice.d.ts +11 -0
  113. package/dist/splice.js +33 -0
  114. package/dist/transportables.d.ts +23 -0
  115. package/dist/transportables.js +144 -0
  116. package/dist/virtual/core.d.ts +158 -0
  117. package/dist/virtual/core.js +588 -0
  118. package/dist/virtual/resolver.d.ts +56 -0
  119. package/dist/virtual/resolver.js +249 -0
  120. package/dist/virtual/specifier.d.ts +10 -0
  121. package/dist/virtual/specifier.js +6 -0
  122. package/dist/virtual/table.d.ts +118 -0
  123. package/dist/virtual/table.js +54 -0
  124. package/dist/virtual/types.d.ts +17 -0
  125. package/dist/virtual/types.js +100 -0
  126. package/dist/virtual/value-names.d.ts +2 -0
  127. package/dist/virtual/value-names.js +18 -0
  128. package/dist/vite/definers.d.ts +16 -0
  129. package/dist/vite/definers.js +69 -0
  130. package/dist/vite/dev-maps.d.ts +34 -0
  131. package/dist/vite/dev-maps.js +91 -0
  132. package/dist/vite/index.d.ts +21 -0
  133. package/dist/vite/index.js +874 -0
  134. package/dist/vite/kit-dirs.d.ts +6 -0
  135. package/dist/vite/kit-dirs.js +53 -0
  136. package/dist/vite/late-island.d.ts +11 -0
  137. package/dist/vite/late-island.js +19 -0
  138. package/dist/vite/lazy-files.d.ts +2 -0
  139. package/dist/vite/lazy-files.js +72 -0
  140. package/dist/vite/options.d.ts +195 -0
  141. package/dist/vite/options.js +72 -0
  142. package/dist/vite/package-files.d.ts +3 -0
  143. package/dist/vite/package-files.js +88 -0
  144. package/dist/vite/paths.d.ts +14 -0
  145. package/dist/vite/paths.js +37 -0
  146. package/dist/vite/plugin-api.d.ts +316 -0
  147. package/dist/vite/plugin-api.js +328 -0
  148. package/dist/vite/session.d.ts +28 -0
  149. package/dist/vite/session.js +43 -0
  150. package/dist/vite/sourcemaps.d.ts +19 -0
  151. package/dist/vite/sourcemaps.js +75 -0
  152. package/dist/vite/style-preprocess.d.ts +2 -0
  153. package/dist/vite/style-preprocess.js +84 -0
  154. package/dist/vite/svelte-entries.d.ts +4 -0
  155. package/dist/vite/svelte-entries.js +10 -0
  156. package/package.json +87 -12
@@ -0,0 +1,102 @@
1
+ import { V_SERVER_REGIONS } from "../ids.js";
2
+ import { by_code_unit } from "./location-map.js";
3
+ import { dedent } from "@ogygia/core/contract";
4
+ // src/link/server-manifest.ts
5
+ /** The SERVER regions (deferred / server-picked), sorted by id: what the server leg writes is a
6
+ * function of the set, never of the order hosts registered in (test/server-manifest-late-order.test.ts). */
7
+ function server_regions(program) {
8
+ const out = [];
9
+ for (const [iid, virtualPath] of program.by_id) {
10
+ const reg = program.registry.get(virtualPath);
11
+ if (reg?.server) out.push([
12
+ iid,
13
+ virtualPath,
14
+ reg
15
+ ]);
16
+ }
17
+ return out.sort(([a], [b]) => by_code_unit(a, b));
18
+ }
19
+ /** The SERVER-island ids the manifest carries right now (deferred / server-picked regions). */
20
+ function server_island_ids(program) {
21
+ return server_regions(program).map(([iid]) => iid);
22
+ }
23
+ /** The manifest's maps from the program's registry; `url_for` names a region's CSS-key URL. */
24
+ function server_manifest_maps(program, url_for) {
25
+ const maps = {
26
+ region_url: {},
27
+ region_name: {},
28
+ region_render: {},
29
+ render_region: {}
30
+ };
31
+ const by_render = /* @__PURE__ */ new Map();
32
+ for (const [iid, virtualPath, reg] of server_regions(program)) {
33
+ if (reg.renderId) {
34
+ maps.region_render[iid] = reg.renderId;
35
+ const seen = by_render.get(reg.renderId);
36
+ if (seen === void 0 || iid < seen) by_render.set(reg.renderId, iid);
37
+ }
38
+ const file = reg.componentPath ?? "";
39
+ const base = file.slice(file.lastIndexOf("/") + 1);
40
+ if (base.endsWith(".svelte")) maps.region_name[iid] = base.slice(0, -7);
41
+ maps.region_url[iid] = url_for(iid, virtualPath);
42
+ }
43
+ for (const [r, iid] of by_render) maps.render_region[r] = iid;
44
+ return maps;
45
+ }
46
+ /** The token a build writes for each map, inside a string literal the bundler cannot fold. */
47
+ const SERVER_MAP_TOKENS = {
48
+ region_url: "__OGYGIA_SERVER_REGION_URL__",
49
+ region_name: "__OGYGIA_SERVER_REGION_NAME__",
50
+ region_render: "__OGYGIA_SERVER_REGION_RENDER__",
51
+ render_region: "__OGYGIA_SERVER_RENDER_REGION__"
52
+ };
53
+ function server_manifest_module(ssr, program, is_dev, devUrlFor) {
54
+ if (!ssr) return dedent`
55
+ export const load_server_regions = () => Promise.resolve({ regions: {} });
56
+ export const region_url = {};
57
+ export const region_name = {};
58
+ export const region_render = {};
59
+ export const render_region = {};
60
+ export const region_reads_page_data = null;
61
+ `;
62
+ const maps = is_dev ? server_manifest_maps(program, (_iid, vp) => devUrlFor(vp)) : null;
63
+ const value = (name) => maps ? JSON.stringify(maps[name]) : `JSON.parse("${SERVER_MAP_TOKENS[name]}")`;
64
+ return dedent`
65
+ export const load_server_regions = () => import(${JSON.stringify(V_SERVER_REGIONS)});
66
+
67
+ export const region_url = ${value("region_url")};
68
+
69
+ export const region_name = ${value("region_name")};
70
+
71
+ export const region_render = ${value("region_render")};
72
+
73
+ export const render_region = ${value("render_region")};
74
+
75
+ // id → does the hole's SERVER tree read \`page.data\` (the page lookup a hole needs: server/
76
+ // render-page.ts). Known only once every module is transformed: a build patches the
77
+ // placeholder in renderChunk (link/relocations.ts); dev leaves \`null\` (unknown → look up).
78
+ export const region_reads_page_data = ${is_dev ? "null" : PAGE_DATA_READS_PLACEHOLDER};
79
+ `;
80
+ }
81
+ /** In a build's `server-regions`, the loaders of the regions found after it was written: an
82
+ * identifier no module defines, so the bundler keeps it as written (link/relocations.ts). */
83
+ const LATE_SERVER_REGIONS_TOKEN = "__OGYGIA_LATE_SERVER_REGIONS__";
84
+ /** `ogygia:server/server-regions`: each SERVER island's loader, `id → () => import(entry)` (empty on
85
+ * the client). Imported only by the manifest's `load_islands()` — never statically. `late`: a
86
+ * build's, which names the loaders of regions found after it (`Program.server_regions_written`). */
87
+ function server_regions_module(ssr, program, late) {
88
+ const entries = [];
89
+ if (ssr) for (const [iid, virtualPath] of server_regions(program)) entries.push(`${JSON.stringify(iid)}: () => import(${JSON.stringify(virtualPath)})`);
90
+ if (ssr && late) entries.push(`...${LATE_SERVER_REGIONS_TOKEN}`);
91
+ return dedent`
92
+ export const regions = {
93
+ ${entries.join(",\n ")}
94
+ };
95
+ `;
96
+ }
97
+ /** The token the build replaces with its answer (link/relocations.ts), inside a string literal the
98
+ * bundler cannot fold: a plain `null` placeholder was inlined into every reader as the constant it
99
+ * was (every hole then looked its page up). Unpatched it parses to nothing → `null`. */
100
+ const PAGE_DATA_READS_TOKEN = "__OGYGIA_PAGE_DATA_READS__";
101
+ const PAGE_DATA_READS_PLACEHOLDER = `(() => { try { return JSON.parse("${PAGE_DATA_READS_TOKEN}"); } catch { return null; } })()`;
102
+ export { LATE_SERVER_REGIONS_TOKEN, PAGE_DATA_READS_PLACEHOLDER, PAGE_DATA_READS_TOKEN, SERVER_MAP_TOKENS, server_island_ids, server_manifest_maps, server_manifest_module, server_regions, server_regions_module };
@@ -0,0 +1,42 @@
1
+ /**
2
+ * `ogygia:region/transport` emitter — re-exports the app's universal `transport` hook (or an empty
3
+ * map) for the client remote wire codec. Universal hooks are isomorphic, so this is client-safe.
4
+ * Pure over the resolved absolute path to the app's universal hooks module (or null).
5
+ */
6
+ export declare function transport_module(universal_hooks: string | null, kit_codec?: string | null): string;
7
+ /**
8
+ * `ogygia:region/kit-transport` emitter — the value behind the barrel's `ogygia.transport` (the Kit
9
+ * `transport` hook the app spreads into its universal hooks). GENERATED per-app, not a fixed export:
10
+ * the real `ogygiaTransport` statically pulls the whole codec cluster (wire/store/snippet/fn + region,
11
+ * ~9 kB) since a wired value can nest any other kind. A **pure-island** app crosses NOTHING through
12
+ * Kit's transport, so it gets an empty map and never bundles a decoder it can't use. `app_crosses_wire`
13
+ * is the compiler's own knowledge (a transportable class / portable snippet → the `wire` mark, plus a
14
+ * remote file or a `region`/content import) — never a scan for `ogygia.transport` in app source.
15
+ * `dist_dir` is the resolvable path to ogygia's own dist.
16
+ *
17
+ * The REALM picks the transport: the browser's decodes every kind the server sends; the server's
18
+ * (server/transport.ts) decodes only what a browser sent, a remote function's argument, and refuses
19
+ * every ogygia kind there.
20
+ */
21
+ export declare function kit_transport_module(app_crosses_wire: boolean, dist_dir: string, ssr: boolean): string;
22
+ /**
23
+ * `ogygia:region/transportables` emitter — where the `[ogygia.wire]` codecs come from, so an island
24
+ * receiving a transportable prop never has to import the class itself. Per leg:
25
+ * - SERVER: side-effect-imports every module that defines a transportable class (the region endpoint
26
+ * decodes signed props of any island; loaded once per process).
27
+ * - CLIENT: NO eager import — every island page used to download every transportable class of the
28
+ * app. It exports `wire_loaders`, a class module's tag path (root-relative, the part of a tag
29
+ * before `#`) → a lazy import, with the file it imports and the URL that file is relative to (a
30
+ * failed download is asked for again there: vite/lazy-files.ts); the runtime loads just the ones
31
+ * an island's props carry (the server stamps them on its props sidecar) before it decodes them.
32
+ * `modules` is the Program's set of transportable module paths (absolute).
33
+ */
34
+ export declare function transportables_server_module(modules: Iterable<string>): string;
35
+ /**
36
+ * The CLIENT leg of {@link transportables_server_module}'s module; `rel` makes a tag path.
37
+ *
38
+ * @param crosses_wire the app sends wired values through Kit's `transport` (remote functions,
39
+ * loads): those decode synchronously, whenever they arrive, so every class must be in before any
40
+ * island wakes (`wire_all`)
41
+ */
42
+ export declare function transportables_client_module(modules: Iterable<string>, rel: (abs: string) => string, crosses_wire?: boolean): string;
@@ -0,0 +1,91 @@
1
+ import { file_token } from "./file-token.js";
2
+ import { dedent } from "@ogygia/core/contract";
3
+ // src/link/transport.ts
4
+ /**
5
+ * `ogygia:region/transport` emitter — re-exports the app's universal `transport` hook (or an empty
6
+ * map) for the client remote wire codec. Universal hooks are isomorphic, so this is client-safe.
7
+ * Pure over the resolved absolute path to the app's universal hooks module (or null).
8
+ */
9
+ function transport_module(universal_hooks, kit_codec = null) {
10
+ if (!universal_hooks) return dedent`
11
+ export const transport = {};
12
+ export const encoders = {};
13
+ export const decoders = {};
14
+ `;
15
+ const src = dedent`
16
+ import * as hooks from ${JSON.stringify(universal_hooks)};
17
+
18
+ export const transport = hooks.transport || {};
19
+ const codecs = Object.entries(transport);
20
+ export const encoders = Object.fromEntries(codecs.map(([k, v]) => [k, v.encode]));
21
+ export const decoders = Object.fromEntries(codecs.map(([k, v]) => [k, v.decode]));
22
+ `;
23
+ if (!kit_codec) return src;
24
+ return dedent`
25
+ import { init_transport } from ${JSON.stringify(kit_codec)};
26
+ ${src}
27
+
28
+ // Kit 3 (client leg): Kit's own codec module is a reader too — its remote argument encoding
29
+ // reads it, and only Kit's client boot fills it otherwise (never on a csr=false page). Kit's
30
+ // boot later fills it again with the same transport.
31
+ init_transport(transport);
32
+ `;
33
+ }
34
+ /**
35
+ * `ogygia:region/kit-transport` emitter — the value behind the barrel's `ogygia.transport` (the Kit
36
+ * `transport` hook the app spreads into its universal hooks). GENERATED per-app, not a fixed export:
37
+ * the real `ogygiaTransport` statically pulls the whole codec cluster (wire/store/snippet/fn + region,
38
+ * ~9 kB) since a wired value can nest any other kind. A **pure-island** app crosses NOTHING through
39
+ * Kit's transport, so it gets an empty map and never bundles a decoder it can't use. `app_crosses_wire`
40
+ * is the compiler's own knowledge (a transportable class / portable snippet → the `wire` mark, plus a
41
+ * remote file or a `region`/content import) — never a scan for `ogygia.transport` in app source.
42
+ * `dist_dir` is the resolvable path to ogygia's own dist.
43
+ *
44
+ * The REALM picks the transport: the browser's decodes every kind the server sends; the server's
45
+ * (server/transport.ts) decodes only what a browser sent, a remote function's argument, and refuses
46
+ * every ogygia kind there.
47
+ */
48
+ function kit_transport_module(app_crosses_wire, dist_dir, ssr) {
49
+ if (!app_crosses_wire) return `export const transport = {};`;
50
+ return ssr ? `export { ogygiaServerTransport as transport } from ${JSON.stringify(`${dist_dir}/server/transport.js`)};` : `export { ogygiaTransport as transport } from ${JSON.stringify(`${dist_dir}/transport.js`)};`;
51
+ }
52
+ /**
53
+ * `ogygia:region/transportables` emitter — where the `[ogygia.wire]` codecs come from, so an island
54
+ * receiving a transportable prop never has to import the class itself. Per leg:
55
+ * - SERVER: side-effect-imports every module that defines a transportable class (the region endpoint
56
+ * decodes signed props of any island; loaded once per process).
57
+ * - CLIENT: NO eager import — every island page used to download every transportable class of the
58
+ * app. It exports `wire_loaders`, a class module's tag path (root-relative, the part of a tag
59
+ * before `#`) → a lazy import, with the file it imports and the URL that file is relative to (a
60
+ * failed download is asked for again there: vite/lazy-files.ts); the runtime loads just the ones
61
+ * an island's props carry (the server stamps them on its props sidecar) before it decodes them.
62
+ * `modules` is the Program's set of transportable module paths (absolute).
63
+ */
64
+ function transportables_server_module(modules) {
65
+ const imports = [];
66
+ for (const abs of modules) imports.push(`import ${JSON.stringify(abs)};`);
67
+ return dedent`
68
+ ${imports.join("\n")}
69
+
70
+ export const wire_loaders = {};
71
+ export const wire_all = false;
72
+ `;
73
+ }
74
+ /**
75
+ * The CLIENT leg of {@link transportables_server_module}'s module; `rel` makes a tag path.
76
+ *
77
+ * @param crosses_wire the app sends wired values through Kit's `transport` (remote functions,
78
+ * loads): those decode synchronously, whenever they arrive, so every class must be in before any
79
+ * island wakes (`wire_all`)
80
+ */
81
+ function transportables_client_module(modules, rel, crosses_wire = false) {
82
+ const entries = [];
83
+ for (const abs of modules) entries.push(`${JSON.stringify(rel(abs))}: [() => import(${JSON.stringify(abs)}), ${file_token(abs)}, import.meta.url]`);
84
+ return dedent`
85
+ export const wire_loaders = {
86
+ ${entries.join(",\n ")}
87
+ };
88
+ export const wire_all = ${crosses_wire && entries.length > 0};
89
+ `;
90
+ }
91
+ export { kit_transport_module, transport_module, transportables_client_module, transportables_server_module };
@@ -0,0 +1,24 @@
1
+ import { Edit } from "../splice.js";
2
+ /** One hoisted factory, destined for the fn manifest. `factory_src` is self-contained. */
3
+ export interface DollarHoist {
4
+ tag: string;
5
+ factory_src: string;
6
+ }
7
+ export interface DollarResult {
8
+ code: string;
9
+ hoists: DollarHoist[];
10
+ }
11
+ /** The fn-manifest's entries (tag → factory source), sorted by tag: the manifest is a function of
12
+ * the hoists, not of the order modules transformed in (test/standalone-driver.test.ts). */
13
+ export declare function fn_manifest_entries(hoists: ReadonlyMap<string, string>): Array<[string, string]>;
14
+ /**
15
+ * Rewrite every `import.meta.og.$` mark in `src`. Returns the input (same reference, empty
16
+ * hoists) when there is nothing to do. Throws build-error voice on misuse. `rel_id` is the
17
+ * root-relative module path used for tags; `markup_exts` as in og-wire (['.svelte']).
18
+ */
19
+ export declare function rewrite_dollar(src: string, id: string, rel_id: string, markup_exts: readonly string[]): DollarResult;
20
+ /** The edits `rewrite_dollar` makes to `src`, and its hoists: none when there is nothing to do. */
21
+ export declare function dollar_edits(src: string, id: string, rel_id: string, markup_exts: readonly string[]): {
22
+ edits: Edit[];
23
+ hoists: DollarHoist[];
24
+ };
@@ -0,0 +1,397 @@
1
+ import { match_close, og_js_regions } from "../parse/scan.js";
2
+ import { parse_module } from "../parse/oxc.js";
3
+ import { og_member } from "./wire.js";
4
+ import { OgygiaError } from "../messages.js";
5
+ import { splice_text } from "../splice.js";
6
+ import { free_references, scope_bindings } from "../free-vars.js";
7
+ // src/macros/dollar.ts
8
+ const SERVER_MODULE_RE = /\.server(\.|$|\/)/;
9
+ const WS_RE = /\s/;
10
+ const MARKER = "import.meta.og.$";
11
+ const KNOWN_GLOBALS = /* @__PURE__ */ new Set([
12
+ "undefined",
13
+ "null",
14
+ "true",
15
+ "false",
16
+ "NaN",
17
+ "Infinity",
18
+ "globalThis",
19
+ "console",
20
+ "Math",
21
+ "JSON",
22
+ "Date",
23
+ "RegExp",
24
+ "Error",
25
+ "TypeError",
26
+ "RangeError",
27
+ "Object",
28
+ "Array",
29
+ "String",
30
+ "Number",
31
+ "Boolean",
32
+ "Symbol",
33
+ "BigInt",
34
+ "Map",
35
+ "Set",
36
+ "WeakMap",
37
+ "WeakSet",
38
+ "Promise",
39
+ "Proxy",
40
+ "Reflect",
41
+ "ArrayBuffer",
42
+ "Uint8Array",
43
+ "TextEncoder",
44
+ "TextDecoder",
45
+ "URL",
46
+ "URLSearchParams",
47
+ "fetch",
48
+ "Request",
49
+ "Response",
50
+ "Headers",
51
+ "FormData",
52
+ "AbortController",
53
+ "structuredClone",
54
+ "queueMicrotask",
55
+ "setTimeout",
56
+ "clearTimeout",
57
+ "setInterval",
58
+ "clearInterval",
59
+ "crypto",
60
+ "performance",
61
+ "atob",
62
+ "btoa",
63
+ "isNaN",
64
+ "isFinite",
65
+ "parseInt",
66
+ "parseFloat",
67
+ "encodeURIComponent",
68
+ "decodeURIComponent",
69
+ "window",
70
+ "document",
71
+ "navigator",
72
+ "location",
73
+ "arguments"
74
+ ]);
75
+ function walk(node, visit, ancestors = []) {
76
+ visit(node, ancestors);
77
+ ancestors.push(node);
78
+ for (const key in node) {
79
+ if (key === "type" || key === "start" || key === "end") continue;
80
+ const child = node[key];
81
+ if (Array.isArray(child)) {
82
+ for (const c of child) if (c && typeof c === "object" && typeof c.type === "string") walk(c, visit, ancestors);
83
+ } else if (child && typeof child === "object" && typeof child.type === "string") walk(child, visit, ancestors);
84
+ }
85
+ ancestors.pop();
86
+ }
87
+ function line_of(src, offset) {
88
+ let line = 1;
89
+ for (let i = 0; i < offset && i < src.length; i++) if (src[i] === "\n") line++;
90
+ return line;
91
+ }
92
+ function misuse(id, src, offset, what) {
93
+ throw new OgygiaError("macro_dollar_misuse", {
94
+ file: id,
95
+ line: line_of(src, offset),
96
+ problem: what
97
+ });
98
+ }
99
+ function captures_of(fn, around) {
100
+ const bound = /* @__PURE__ */ new Set();
101
+ for (const scope of around) for (const name of scope_bindings(scope)) bound.add(name);
102
+ return free_references(fn).filter((name) => !KNOWN_GLOBALS.has(name) || bound.has(name));
103
+ }
104
+ function holds_mark(fn) {
105
+ let found = false;
106
+ walk(fn, (n) => {
107
+ if (!found && n.type === "CallExpression" && og_member(n.callee) === "$") found = true;
108
+ });
109
+ return found;
110
+ }
111
+ const ERASED_NODES = /* @__PURE__ */ new Set([
112
+ "TSTypeAnnotation",
113
+ "TSTypeParameterDeclaration",
114
+ "TSTypeParameterInstantiation",
115
+ "TSTypeAliasDeclaration",
116
+ "TSInterfaceDeclaration",
117
+ "TSDeclareFunction",
118
+ "TSAbstractMethodDefinition",
119
+ "TSAbstractPropertyDefinition",
120
+ "TSAbstractAccessorProperty",
121
+ "TSIndexSignature"
122
+ ]);
123
+ const TYPE_AROUND_EXPRESSION = /* @__PURE__ */ new Set([
124
+ "TSAsExpression",
125
+ "TSSatisfiesExpression",
126
+ "TSNonNullExpression",
127
+ "TSInstantiationExpression",
128
+ "TSTypeAssertion"
129
+ ]);
130
+ const RUNTIME_TS = /* @__PURE__ */ new Map([["TSEnumDeclaration", "an enum"], ["TSParameterProperty", "a parameter property"]]);
131
+ const CLASS_MEMBERS = /* @__PURE__ */ new Set([
132
+ "PropertyDefinition",
133
+ "MethodDefinition",
134
+ "AccessorProperty"
135
+ ]);
136
+ const MEMBER_MODIFIER_RE = /(?<![\w$@.])(?:public|private|protected|readonly|override|declare)(?![\w$])/g;
137
+ const ABSTRACT_RE = /(?<![\w$@.])abstract(?![\w$])/g;
138
+ function type_only_namespace(n) {
139
+ if (n.declare === true) return true;
140
+ const body = n.body;
141
+ if (!body) return true;
142
+ if (body.type === "TSModuleDeclaration") return type_only_namespace(body);
143
+ return (body.body ?? []).every((s) => {
144
+ const d = s.type === "ExportNamedDeclaration" ? s.declaration : s;
145
+ if (!d) return false;
146
+ if (d.type === "TSModuleDeclaration") return type_only_namespace(d);
147
+ return ERASED_NODES.has(d.type) || d.declare === true;
148
+ });
149
+ }
150
+ function strip_ts_types(fn, code, refuse) {
151
+ const base = fn.start;
152
+ const chars = code.slice(base, fn.end).split("");
153
+ const blank = (s, e) => {
154
+ for (let i = s - base; i < e - base; i++) if (i >= 0 && i < chars.length) chars[i] = " ";
155
+ };
156
+ const blank_mark = (from, mark, to) => {
157
+ const at = code.indexOf(mark, from);
158
+ if (at >= 0 && at < to) blank(at, at + 1);
159
+ };
160
+ const blank_words = (re, from, to) => {
161
+ for (const m of code.slice(from, to).matchAll(re)) blank(from + m.index, from + m.index + m[0].length);
162
+ };
163
+ const visit = (n) => {
164
+ const t = n.type;
165
+ if (n.declare === true || ERASED_NODES.has(t)) return blank(n.start, n.end);
166
+ if (t === "TSModuleDeclaration") {
167
+ if (!type_only_namespace(n)) refuse(n.start, `a namespace with values has runtime meaning, so $() cannot erase it`);
168
+ return blank(n.start, n.end);
169
+ }
170
+ const runtime = RUNTIME_TS.get(t);
171
+ if (runtime) refuse(n.start, `${runtime} has runtime meaning, so $() cannot erase it`);
172
+ if (TYPE_AROUND_EXPRESSION.has(t)) {
173
+ const expr = n.expression;
174
+ blank(n.start, expr.start);
175
+ blank(expr.end, n.end);
176
+ }
177
+ if (t === "Identifier" && n.optional === true) blank_mark(n.start + n.name.length, "?", n.end);
178
+ if (t === "VariableDeclarator" && n.definite === true) blank_mark(n.id.start + n.id.name.length, "!", n.end);
179
+ if (CLASS_MEMBERS.has(t)) {
180
+ const key = n.key;
181
+ blank_words(MEMBER_MODIFIER_RE, n.start, key.start);
182
+ const value = n.value;
183
+ if (n.optional === true) blank_mark(key.end, "?", value?.start ?? n.end);
184
+ if (n.definite === true) blank_mark(key.end, "!", n.end);
185
+ }
186
+ if (t === "ClassDeclaration" || t === "ClassExpression") {
187
+ if (n.abstract === true) blank_words(ABSTRACT_RE, n.start, code.indexOf("class", n.start));
188
+ const impl = n.implements ?? [];
189
+ if (impl.length) blank(code.lastIndexOf("implements", impl[0].start), impl[impl.length - 1].end);
190
+ }
191
+ const params = n.params;
192
+ if (params?.[0]?.type === "Identifier" && params[0].name === "this") blank(params[0].start, params[1]?.start ?? params[0].end);
193
+ for (const key in n) {
194
+ if (key === "type" || key === "start" || key === "end") continue;
195
+ const child = n[key];
196
+ if (Array.isArray(child)) {
197
+ for (const c of child) if (c && typeof c === "object" && typeof c.type === "string") visit(c);
198
+ } else if (child && typeof child === "object" && typeof child.type === "string") visit(child);
199
+ }
200
+ };
201
+ visit(fn);
202
+ return chars.join("");
203
+ }
204
+ /** The fn-manifest's entries (tag → factory source), sorted by tag: the manifest is a function of
205
+ * the hoists, not of the order modules transformed in (test/standalone-driver.test.ts). */
206
+ function fn_manifest_entries(hoists) {
207
+ return [...hoists].sort(([a], [b]) => {
208
+ if (a < b) return -1;
209
+ return a > b ? 1 : 0;
210
+ });
211
+ }
212
+ /**
213
+ * Rewrite every `import.meta.og.$` mark in `src`. Returns the input (same reference, empty
214
+ * hoists) when there is nothing to do. Throws build-error voice on misuse. `rel_id` is the
215
+ * root-relative module path used for tags; `markup_exts` as in og-wire (['.svelte']).
216
+ */
217
+ function rewrite_dollar(src, id, rel_id, markup_exts) {
218
+ const { edits, hoists } = dollar_edits(src, id, rel_id, markup_exts);
219
+ return {
220
+ code: splice_text(src, edits),
221
+ hoists
222
+ };
223
+ }
224
+ /** The edits `rewrite_dollar` makes to `src`, and its hoists: none when there is nothing to do. */
225
+ function dollar_edits(src, id, rel_id, markup_exts) {
226
+ if (!src.includes(MARKER)) return {
227
+ edits: [],
228
+ hoists: []
229
+ };
230
+ const regions = og_js_regions(src, id, markup_exts);
231
+ if (!regions) return {
232
+ edits: [],
233
+ hoists: []
234
+ };
235
+ const edits = [];
236
+ const hoists = [];
237
+ let seq = 0;
238
+ let needs_import = false;
239
+ let needs_boundary_import = false;
240
+ const script_scopes = [];
241
+ for (const region of regions) {
242
+ const { program, ok } = parse_module(region.code, id.endsWith(".svelte") ? `${id}.ts` : id);
243
+ if (!ok || !program) continue;
244
+ script_scopes.push(program);
245
+ const server_only = /* @__PURE__ */ new Map();
246
+ for (const node of program.body ?? []) {
247
+ if (node.type !== "ImportDeclaration") continue;
248
+ const src_val = node.source?.value;
249
+ if (!src_val) continue;
250
+ if (!(src_val === "$app/server" || src_val.startsWith("$env/static/private") || src_val.startsWith("$env/dynamic/private") || SERVER_MODULE_RE.test(src_val))) continue;
251
+ for (const sp of node.specifiers ?? []) if (sp.local?.name) server_only.set(sp.local.name, src_val);
252
+ }
253
+ const claimed = /* @__PURE__ */ new Set();
254
+ const refuse_at = (at, problem) => misuse(id, src, region.offset + at, problem);
255
+ walk(program, (n, ancestors) => {
256
+ if (n.type === "CallExpression" && og_member(n.callee) === "$") {
257
+ const abs = region.offset + n.start;
258
+ const args = n.arguments;
259
+ if (!args || args.length !== 1) misuse(id, src, abs, `$() takes exactly one argument — the function to hoist`);
260
+ const fn = args[0];
261
+ if (fn.type !== "ArrowFunctionExpression" && fn.type !== "FunctionExpression") {
262
+ claimed.add(n);
263
+ claimed.add(n.callee);
264
+ const expr_text = strip_ts_types(fn, region.code, refuse_at);
265
+ const site = `${rel_id}:${line_of(src, abs)}`;
266
+ needs_boundary_import = true;
267
+ edits.push({
268
+ start: abs,
269
+ end: region.offset + n.end,
270
+ text: `__og_boundary((${expr_text}), ${JSON.stringify(site)})`
271
+ });
272
+ return;
273
+ }
274
+ if (holds_mark(fn)) misuse(id, src, abs, `a $() inside another $() — mark the outer one only`);
275
+ claimed.add(n);
276
+ claimed.add(n.callee);
277
+ const captures = captures_of(fn, ancestors);
278
+ for (const c of captures) {
279
+ const from = server_only.get(c);
280
+ if (from) misuse(id, src, abs, `$() captures \`${c}\` from the server-only module '${from}' — its value would ship into client HTML. Do the server work in a remote function and capture ITS result, or pass a derived, non-secret value instead`);
281
+ }
282
+ const fn_text = strip_ts_types(fn, region.code, refuse_at);
283
+ const tag = `${rel_id}#$${seq++}`;
284
+ const factory = `(${captures.join(", ")}) => (${fn_text})`;
285
+ hoists.push({
286
+ tag,
287
+ factory_src: factory
288
+ });
289
+ needs_import = true;
290
+ edits.push({
291
+ start: abs,
292
+ end: region.offset + n.end,
293
+ text: `__og_$(${JSON.stringify(tag)}, [${captures.join(", ")}], ${factory})`
294
+ });
295
+ return;
296
+ }
297
+ if (og_member(n) === "$" && !claimed.has(n)) misuse(id, src, region.offset + n.start, `bare import.meta.og.$ used as a value`);
298
+ });
299
+ if ((needs_import || needs_boundary_import) && !edits.some((e) => e.text.startsWith("import"))) {
300
+ const names = [needs_import ? "__og_$" : "", needs_boundary_import ? "__og_boundary" : ""].filter(Boolean).join(", ");
301
+ edits.push({
302
+ start: region.offset,
303
+ end: region.offset,
304
+ text: `import { ${names} } from 'ogygia/internal';`
305
+ });
306
+ needs_import = false;
307
+ needs_boundary_import = false;
308
+ }
309
+ }
310
+ const in_region = (pos) => regions.some((r) => pos >= r.offset && pos < r.offset + r.code.length);
311
+ const template_calls = [];
312
+ {
313
+ const M = "import.meta.og.$";
314
+ let at = -1;
315
+ while ((at = src.indexOf(M, at + 1)) !== -1) {
316
+ if (in_region(at)) continue;
317
+ let open = at + 16;
318
+ while (open < src.length && WS_RE.test(src[open])) open++;
319
+ if (src[open] !== "(") continue;
320
+ let before = at - 1;
321
+ while (before >= 0 && WS_RE.test(src[before])) before--;
322
+ if (src[before] !== "{" && src[before] !== "(") continue;
323
+ const close = match_close(src, open);
324
+ if (close < 0) continue;
325
+ template_calls.push({
326
+ start: at,
327
+ end: close + 1,
328
+ args: src.slice(open + 1, close)
329
+ });
330
+ at = close;
331
+ }
332
+ }
333
+ let template_needs = null;
334
+ for (const call of template_calls) {
335
+ const arg_text = call.args.trim();
336
+ if (!arg_text) misuse(id, src, call.start, `$() takes exactly one argument`);
337
+ const wrapped = `(${arg_text})`;
338
+ const { program, ok } = parse_module(wrapped, id.endsWith(".svelte") ? `${id}.expr.ts` : id);
339
+ if (!ok || !program) misuse(id, src, call.start, `$()'s argument does not parse as an expression`);
340
+ let expr = (program.body?.[0] ?? {}).expression ?? {};
341
+ while (expr.type === "ParenthesizedExpression") expr = expr.expression;
342
+ const expr_text = strip_ts_types(expr, wrapped, (_at, problem) => misuse(id, src, call.start, problem));
343
+ if (expr.type === "ArrowFunctionExpression" || expr.type === "FunctionExpression") {
344
+ if (holds_mark(expr)) misuse(id, src, call.start, `a $() inside another $() — mark the outer one only`);
345
+ const captures = captures_of(expr, script_scopes);
346
+ const tag = `${rel_id}#$${seq++}`;
347
+ const factory = `(${captures.join(", ")}) => (${expr_text})`;
348
+ hoists.push({
349
+ tag,
350
+ factory_src: factory
351
+ });
352
+ (template_needs ??= {
353
+ fn: false,
354
+ boundary: false
355
+ }).fn = true;
356
+ edits.push({
357
+ start: call.start,
358
+ end: call.end,
359
+ text: `__og_$(${JSON.stringify(tag)}, [${captures.join(", ")}], ${factory})`
360
+ });
361
+ } else {
362
+ const site = `${rel_id}:${line_of(src, call.start)}`;
363
+ (template_needs ??= {
364
+ fn: false,
365
+ boundary: false
366
+ }).boundary = true;
367
+ edits.push({
368
+ start: call.start,
369
+ end: call.end,
370
+ text: `__og_boundary((${expr_text}), ${JSON.stringify(site)})`
371
+ });
372
+ }
373
+ }
374
+ if (template_needs) {
375
+ const first = regions[0];
376
+ if (!first) misuse(id, src, 0, `og.$ in markup needs a <script> block to receive its runtime import`);
377
+ const names = [template_needs.fn ? "__og_$" : "", template_needs.boundary ? "__og_boundary" : ""].filter(Boolean).join(", ");
378
+ const existing = edits.find((e) => e.start === first.offset && e.text.startsWith("import { "));
379
+ if (existing) {
380
+ const have = existing.text.slice(9, existing.text.indexOf(" }"));
381
+ existing.text = `import { ${[.../* @__PURE__ */ new Set([...have.split(", "), ...names.split(", ")])].filter(Boolean).join(", ")} } from 'ogygia/internal';`;
382
+ } else edits.push({
383
+ start: first.offset,
384
+ end: first.offset,
385
+ text: `import { ${names} } from 'ogygia/internal';`
386
+ });
387
+ }
388
+ if (!edits.length) return {
389
+ edits: [],
390
+ hoists: []
391
+ };
392
+ return {
393
+ edits,
394
+ hoists
395
+ };
396
+ }
397
+ export { dollar_edits, fn_manifest_entries, rewrite_dollar };