@ogygia/compiler 0.15.0 → 0.16.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/ctx.d.ts CHANGED
@@ -92,6 +92,9 @@ export interface CompileCtxInit {
92
92
  component_css?: ComponentCss;
93
93
  /** The plugins' `import.meta.og.*` macros (`b.macro`), in plugin order. Optional (default none). */
94
94
  macros?: readonly PluginMacro[];
95
+ /** The markdown formats' extensions (`b.markup()`), whose scripts the macro check reads.
96
+ * Optional (default none). */
97
+ markdown_exts?: readonly string[];
95
98
  /** The plugin that reads which `page.data` keys a module reads (`b.pageReads`), handed each
96
99
  * module the build compiles. Optional (default none: every region gets all of `page.data`). */
97
100
  page_reads?: PageReadsSink | null;
@@ -167,6 +170,7 @@ export declare class CompileCtx {
167
170
  get app_spec(): AppSpecCtx;
168
171
  readonly component_css: ComponentCss | undefined;
169
172
  readonly macros: readonly PluginMacro[];
173
+ readonly markdown_exts: readonly string[];
170
174
  readonly page_reads: PageReadsSink | null;
171
175
  readonly prescans: readonly PrescanHook[];
172
176
  readonly plugins: readonly string[];
package/dist/ctx.js CHANGED
@@ -43,6 +43,7 @@ var CompileCtx = class {
43
43
  }
44
44
  component_css;
45
45
  macros;
46
+ markdown_exts;
46
47
  page_reads;
47
48
  prescans;
48
49
  plugins;
@@ -96,6 +97,7 @@ var CompileCtx = class {
96
97
  this.resolve_alias = init.resolve_alias;
97
98
  this.component_css = init.component_css;
98
99
  this.macros = init.macros ?? [];
100
+ this.markdown_exts = init.markdown_exts ?? [];
99
101
  this.page_reads = init.page_reads ?? null;
100
102
  this.prescans = init.prescans ?? [];
101
103
  this.plugins = init.plugins ?? [];
package/dist/driver.js CHANGED
@@ -448,6 +448,7 @@ var Compiler = class Compiler {
448
448
  pkgRoot: ctx.pkg_root,
449
449
  dollarHoists: this.dollar_hoists,
450
450
  macros: ctx.macros,
451
+ markdownExts: ctx.markdown_exts,
451
452
  ownSource: (file) => ctx.is_own_source(file),
452
453
  watch
453
454
  }, this.profiler);
package/dist/index.d.ts CHANGED
@@ -1,15 +1,17 @@
1
1
  import { CLIENT_BINDING_STUB, DEFAULT_IMPORT_KEYS, ISLAND_DIR, ImportKeys, PRESET_KEYS, STABLE_NAME_DIR, import_keys_hint, is_island_path, islandChunkFileName, islandId, islandPublicUrl, normalize_hydrate_value, normalize_import_keys, normalize_region_value, transformHost, transformTsRegions } from "./region/transform.js";
2
2
  import { AstNode, parse_module } from "./parse/oxc.js";
3
+ import { NOT_LITERAL, line_of, literal_of, walk_ast } from "./parse/ast.js";
4
+ import { Edit } from "./splice.js";
3
5
  import { parse_roots } from "./parse/roots.js";
4
6
  import { ComponentCss, CssReachOptions, FOUC_CSS_PREFIX, FOUC_SCOPED_PREFIX, WalkResolve, buildFoucCssModuleSource, collectFoucCssReachable, compileFoucScopedCss, foucCssVirtualId, foucRelFromId, foucScopedVirtualId, isFoucCssId, isFoucScopedId, listStaticImports, scoped_component_css, svelteHasStyle, through_caller } from "./fouc-css.js";
5
- import { collectCaptureInfo, collectFreeIdentifiers, collectSnippetNames, collect_pattern_names, free_references, scope_bindings } from "./free-vars.js";
6
7
  import { regionId, regionIdentity, strategyKey } from "./region/identity.js";
8
+ import { collectCaptureInfo, collectFreeIdentifiers, collectSnippetNames, collect_pattern_names, free_references, scope_bindings } from "./free-vars.js";
7
9
  import { Compiler, Profiler } from "./driver.js";
8
10
  import { Program, host_key, strip_id } from "./program.js";
9
11
  import { CompileCtx, CompileCtxInit } from "./ctx.js";
10
12
  import { Fs, FsEntry, MemoryFs, memory_fs, node_fs } from "./fs.js";
11
- import { PROFILER_MAPS_GZ_PREFIX, PROFILER_MAPS_PLACEHOLDER, REGION_FAMILY, RESOLVED, V_RUNTIME_ENTRY, V_SERVER_MANIFEST, V_SERVER_REGIONS, V_TRANSPORT, V_TRANSPORTABLES, islandVirtualId, lazyEntryVirtualId, regionBindingVirtualId, region_family, wrapperVirtualId } from "./ids.js";
12
13
  import { OGYGIA_SCHEME } from "./virtual/specifier.js";
14
+ import { PROFILER_MAPS_GZ_PREFIX, PROFILER_MAPS_PLACEHOLDER, REGION_FAMILY, RESOLVED, V_RUNTIME_ENTRY, V_SERVER_MANIFEST, V_SERVER_REGIONS, V_TRANSPORT, V_TRANSPORTABLES, islandVirtualId, lazyEntryVirtualId, regionBindingVirtualId, region_family, wrapperVirtualId } from "./ids.js";
13
15
  import { Change, ExportIndex, ExportMap, Leaf, Policy, Shapes } from "./exports/index.js";
14
16
  import { ImportDecl, ImportSpec, analyze_imports } from "./exports/parse.js";
15
17
  import { blank_styles } from "./blank-styles.js";
@@ -20,4 +22,4 @@ import { JsRegion, OgCall, find_og_calls, is_js_module, og_js_regions, split_fir
20
22
  import { og_member } from "./macros/wire.js";
21
23
  import { BuildCache, __set_build_cache_root, configure_build_cache } from "./build-cache.js";
22
24
  import { OWN_FILE_RE, content_css_key, dedent } from "@ogygia/core/contract";
23
- export { type AstNode, BUILD_ERRORS, BUILD_WARNINGS, BuildCache, CLIENT_BINDING_STUB, type Change, CompileCtx, type CompileCtxInit, Compiler, ComponentCss, CssReachOptions, DEFAULT_IMPORT_KEYS, ExportIndex, type ExportMap, FOUC_CSS_PREFIX, FOUC_SCOPED_PREFIX, type Fs, type FsEntry, ISLAND_DIR, type ImportDecl, ImportKeys, type ImportSpec, type JsRegion, type Leaf, type MemoryFs, OGYGIA_SCHEME, OWN_FILE_RE, type OgCall, PRESET_KEYS, PROFILER_MAPS_GZ_PREFIX, PROFILER_MAPS_PLACEHOLDER, type Policy, type Profiler, Program, REGION_FAMILY, RESOLVED, STABLE_NAME_DIR, Shapes, V_RUNTIME_ENTRY, V_SERVER_MANIFEST, V_SERVER_REGIONS, V_TRANSPORT, V_TRANSPORTABLES, WalkResolve, __set_build_cache_root, analyze_imports, blank_styles, buildFoucCssModuleSource, collectCaptureInfo, collectFoucCssReachable, collectFreeIdentifiers, collectSnippetNames, collect_pattern_names, compileFoucScopedCss, configure_build_cache, content_css_key, dedent, find_og_calls, foucCssVirtualId, foucRelFromId, foucScopedVirtualId, free_references, host_key, import_keys_hint, isFoucCssId, isFoucScopedId, is_island_path, is_js_module, is_script_request, islandChunkFileName, islandId, islandPublicUrl, islandVirtualId, lazyEntryVirtualId, listStaticImports, memory_fs, node_fs, normalize_hydrate_value, normalize_import_keys, normalize_region_value, og_js_regions, og_member, parse_module, parse_roots, regionBindingVirtualId, regionId, regionIdentity, region_family, scope_bindings, scoped_component_css, split_first_string, strategyKey, strip_id, svelteHasStyle, through_caller, transformHost, transformTsRegions, wrapperVirtualId };
25
+ export { type AstNode, BUILD_ERRORS, BUILD_WARNINGS, BuildCache, CLIENT_BINDING_STUB, type Change, CompileCtx, type CompileCtxInit, Compiler, ComponentCss, CssReachOptions, DEFAULT_IMPORT_KEYS, type Edit, ExportIndex, type ExportMap, FOUC_CSS_PREFIX, FOUC_SCOPED_PREFIX, type Fs, type FsEntry, ISLAND_DIR, type ImportDecl, ImportKeys, type ImportSpec, type JsRegion, type Leaf, type MemoryFs, NOT_LITERAL, OGYGIA_SCHEME, OWN_FILE_RE, type OgCall, PRESET_KEYS, PROFILER_MAPS_GZ_PREFIX, PROFILER_MAPS_PLACEHOLDER, type Policy, type Profiler, Program, REGION_FAMILY, RESOLVED, STABLE_NAME_DIR, Shapes, V_RUNTIME_ENTRY, V_SERVER_MANIFEST, V_SERVER_REGIONS, V_TRANSPORT, V_TRANSPORTABLES, WalkResolve, __set_build_cache_root, analyze_imports, blank_styles, buildFoucCssModuleSource, collectCaptureInfo, collectFoucCssReachable, collectFreeIdentifiers, collectSnippetNames, collect_pattern_names, compileFoucScopedCss, configure_build_cache, content_css_key, dedent, find_og_calls, foucCssVirtualId, foucRelFromId, foucScopedVirtualId, free_references, host_key, import_keys_hint, isFoucCssId, isFoucScopedId, is_island_path, is_js_module, is_script_request, islandChunkFileName, islandId, islandPublicUrl, islandVirtualId, lazyEntryVirtualId, line_of, listStaticImports, literal_of, memory_fs, node_fs, normalize_hydrate_value, normalize_import_keys, normalize_region_value, og_js_regions, og_member, parse_module, parse_roots, regionBindingVirtualId, regionId, regionIdentity, region_family, scope_bindings, scoped_component_css, split_first_string, strategyKey, strip_id, svelteHasStyle, through_caller, transformHost, transformTsRegions, walk_ast, wrapperVirtualId };
package/dist/index.js CHANGED
@@ -1,16 +1,17 @@
1
1
  import { CLIENT_BINDING_STUB, DEFAULT_IMPORT_KEYS, ISLAND_DIR, PRESET_KEYS, STABLE_NAME_DIR, import_keys_hint, is_island_path, islandChunkFileName, islandId, islandPublicUrl, normalize_hydrate_value, normalize_import_keys, normalize_region_value, transformHost, transformTsRegions } from "./region/transform.js";
2
2
  import { parse_module } from "./parse/oxc.js";
3
+ import { NOT_LITERAL, line_of, literal_of, walk_ast } from "./parse/ast.js";
3
4
  import { parse_roots } from "./parse/roots.js";
4
5
  import { FOUC_CSS_PREFIX, FOUC_SCOPED_PREFIX, buildFoucCssModuleSource, collectFoucCssReachable, compileFoucScopedCss, foucCssVirtualId, foucRelFromId, foucScopedVirtualId, isFoucCssId, isFoucScopedId, listStaticImports, scoped_component_css, svelteHasStyle, through_caller } from "./fouc-css.js";
5
6
  import { collectCaptureInfo, collectFreeIdentifiers, collectSnippetNames, collect_pattern_names, free_references, scope_bindings } from "./free-vars.js";
6
7
  import { Compiler } from "./driver.js";
7
8
  import { Program, host_key, strip_id } from "./program.js";
8
- import { CompileCtx } from "./ctx.js";
9
9
  import { OGYGIA_SCHEME } from "./virtual/specifier.js";
10
+ import { CompileCtx } from "./ctx.js";
10
11
  import { memory_fs, node_fs } from "./fs.js";
11
12
  import { PROFILER_MAPS_GZ_PREFIX, PROFILER_MAPS_PLACEHOLDER, REGION_FAMILY, RESOLVED, V_RUNTIME_ENTRY, V_SERVER_MANIFEST, V_SERVER_REGIONS, V_TRANSPORT, V_TRANSPORTABLES, islandVirtualId, lazyEntryVirtualId, regionBindingVirtualId, region_family, wrapperVirtualId } from "./ids.js";
12
- import { ExportIndex, Shapes } from "./exports/index.js";
13
13
  import { regionId, regionIdentity, strategyKey } from "./region/identity.js";
14
+ import { ExportIndex, Shapes } from "./exports/index.js";
14
15
  import { analyze_imports } from "./exports/parse.js";
15
16
  import { blank_styles } from "./blank-styles.js";
16
17
  import { is_script_request } from "./script-request.js";
@@ -20,4 +21,4 @@ import { find_og_calls, is_js_module, og_js_regions, split_first_string } from "
20
21
  import { og_member } from "./macros/wire.js";
21
22
  import { BuildCache, __set_build_cache_root, configure_build_cache } from "./build-cache.js";
22
23
  import { OWN_FILE_RE, content_css_key, dedent } from "@ogygia/core/contract";
23
- export { BUILD_ERRORS, BUILD_WARNINGS, BuildCache, CLIENT_BINDING_STUB, CompileCtx, Compiler, DEFAULT_IMPORT_KEYS, ExportIndex, FOUC_CSS_PREFIX, FOUC_SCOPED_PREFIX, ISLAND_DIR, OGYGIA_SCHEME, OWN_FILE_RE, PRESET_KEYS, PROFILER_MAPS_GZ_PREFIX, PROFILER_MAPS_PLACEHOLDER, Program, REGION_FAMILY, RESOLVED, STABLE_NAME_DIR, Shapes, V_RUNTIME_ENTRY, V_SERVER_MANIFEST, V_SERVER_REGIONS, V_TRANSPORT, V_TRANSPORTABLES, __set_build_cache_root, analyze_imports, blank_styles, buildFoucCssModuleSource, collectCaptureInfo, collectFoucCssReachable, collectFreeIdentifiers, collectSnippetNames, collect_pattern_names, compileFoucScopedCss, configure_build_cache, content_css_key, dedent, find_og_calls, foucCssVirtualId, foucRelFromId, foucScopedVirtualId, free_references, host_key, import_keys_hint, isFoucCssId, isFoucScopedId, is_island_path, is_js_module, is_script_request, islandChunkFileName, islandId, islandPublicUrl, islandVirtualId, lazyEntryVirtualId, listStaticImports, memory_fs, node_fs, normalize_hydrate_value, normalize_import_keys, normalize_region_value, og_js_regions, og_member, parse_module, parse_roots, regionBindingVirtualId, regionId, regionIdentity, region_family, scope_bindings, scoped_component_css, split_first_string, strategyKey, strip_id, svelteHasStyle, through_caller, transformHost, transformTsRegions, wrapperVirtualId };
24
+ export { BUILD_ERRORS, BUILD_WARNINGS, BuildCache, CLIENT_BINDING_STUB, CompileCtx, Compiler, DEFAULT_IMPORT_KEYS, ExportIndex, FOUC_CSS_PREFIX, FOUC_SCOPED_PREFIX, ISLAND_DIR, NOT_LITERAL, OGYGIA_SCHEME, OWN_FILE_RE, PRESET_KEYS, PROFILER_MAPS_GZ_PREFIX, PROFILER_MAPS_PLACEHOLDER, Program, REGION_FAMILY, RESOLVED, STABLE_NAME_DIR, Shapes, V_RUNTIME_ENTRY, V_SERVER_MANIFEST, V_SERVER_REGIONS, V_TRANSPORT, V_TRANSPORTABLES, __set_build_cache_root, analyze_imports, blank_styles, buildFoucCssModuleSource, collectCaptureInfo, collectFoucCssReachable, collectFreeIdentifiers, collectSnippetNames, collect_pattern_names, compileFoucScopedCss, configure_build_cache, content_css_key, dedent, find_og_calls, foucCssVirtualId, foucRelFromId, foucScopedVirtualId, free_references, host_key, import_keys_hint, isFoucCssId, isFoucScopedId, is_island_path, is_js_module, is_script_request, islandChunkFileName, islandId, islandPublicUrl, islandVirtualId, lazyEntryVirtualId, line_of, listStaticImports, literal_of, memory_fs, node_fs, normalize_hydrate_value, normalize_import_keys, normalize_region_value, og_js_regions, og_member, parse_module, parse_roots, regionBindingVirtualId, regionId, regionIdentity, region_family, scope_bindings, scoped_component_css, split_first_string, strategyKey, strip_id, svelteHasStyle, through_caller, transformHost, transformTsRegions, walk_ast, wrapperVirtualId };
@@ -1,5 +1,6 @@
1
1
  import { match_close, og_js_regions } from "../parse/scan.js";
2
2
  import { parse_module } from "../parse/oxc.js";
3
+ import { line_of } from "../parse/ast.js";
3
4
  import { og_member } from "./wire.js";
4
5
  import { OgygiaError } from "../messages.js";
5
6
  import { splice_text } from "../splice.js";
@@ -84,11 +85,6 @@ function walk(node, visit, ancestors = []) {
84
85
  }
85
86
  ancestors.pop();
86
87
  }
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
88
  function misuse(id, src, offset, what) {
93
89
  throw new OgygiaError("macro_dollar_misuse", {
94
90
  file: id,
@@ -1,6 +1,8 @@
1
1
  import { StepMap } from "../map-chain.js";
2
+ import { Edit } from "../splice.js";
2
3
  import { Profiler } from "../driver.js";
3
4
  import { AppAlias } from "../app-spec.js";
5
+ import { JsRegion } from "../parse/scan.js";
4
6
  /** A resolved Vite alias (`resolve.alias`, normalized to its array form). */
5
7
  export type AliasEntry = AppAlias;
6
8
  /** What a macro knows about the module it rewrites. */
@@ -14,13 +16,21 @@ export interface MacroContext {
14
16
  readonly alias: readonly AliasEntry[];
15
17
  /** Markup extensions whose `<script>` blocks hold the macro calls (`.svelte`). */
16
18
  readonly markupExts: readonly string[];
19
+ /** The code a macro rewrites in this module's text `code`: a JS module whole, a `.svelte`
20
+ * component's `<script>` blocks, a markdown page's (`.svx`, `.md`) `<script>` blocks (not its
21
+ * fenced code); null for any other module. A call left outside them fails the build
22
+ * (`macro_in_markup`), and so does one a handler leaves in a markdown page's script. */
23
+ regions: (code: string) => JsRegion[] | null;
17
24
  /** Name a file the rewrite read: an edit to it transforms this module again (dev). */
18
25
  watch: (file: string) => void;
19
26
  }
27
+ /** What a macro answers: the new code (the same string when nothing changed), or the edits that make
28
+ * it, which keep the module's source map. */
29
+ export type MacroResult = string | readonly Edit[];
20
30
  /** A plugin's `import.meta.og.<name>` macro (registered with `b.macro`). */
21
31
  export interface PluginMacro {
22
32
  name: string;
23
- handler: (code: string, m: MacroContext) => string | Promise<string>;
33
+ handler: (code: string, m: MacroContext) => MacroResult | Promise<MacroResult>;
24
34
  }
25
35
  export interface MacroPipelineCtx {
26
36
  root: string;
@@ -35,6 +45,9 @@ export interface MacroPipelineCtx {
35
45
  /** Is `id` the app's own source, or a file a package declares in `ogygia.files`? Only those may
36
46
  * use a macro: anywhere else one fails the build (`macro_outside_app`), and no handler runs. */
37
47
  ownSource: (id: string) => boolean;
48
+ /** The markdown formats' extensions (`.svx`, `.md`, from `b.markup()`): their `<script>` blocks
49
+ * are code a macro call in fails the build without its plugin. Optional (default none). */
50
+ markdownExts?: readonly string[];
38
51
  /** The bundler's watch for the module being rewritten (Vite's `addWatchFile`); none outside one. */
39
52
  watch?: (file: string) => void;
40
53
  }
@@ -4,8 +4,11 @@ import { source_edits } from "./source.js";
4
4
  import { auto_brand_edits, store_edits } from "./store.js";
5
5
  import { splice_map, splice_text } from "../splice.js";
6
6
  import { OgygiaError } from "../messages.js";
7
- import { find_og_calls } from "../parse/scan.js";
7
+ import { MarkdownPage, find_og_calls, is_js_module, is_markup_module, og_js_regions } from "../parse/scan.js";
8
+ import { line_of, walk_ast } from "../parse/ast.js";
9
+ import { blank_styles } from "../blank-styles.js";
8
10
  import path from "node:path";
11
+ import { parse } from "svelte/compiler";
9
12
  import { noop } from "@ogygia/machine";
10
13
  // src/macros/pipeline.ts
11
14
  const EXPORT_CONST_RE = /export\s+const/;
@@ -29,12 +32,85 @@ const MACRO_PACKAGES = {
29
32
  bake: {
30
33
  package: "@ogygia/bake",
31
34
  plugin: "bake()"
35
+ },
36
+ image: {
37
+ package: "@ogygia/image",
38
+ plugin: "image()"
32
39
  }
33
40
  };
34
- function calls_macro(code, name) {
35
- return find_og_calls(code, "import.meta.og.").some((c) => c.method === name || c.method.startsWith(`${name}.`));
36
- }
37
41
  const CONSTRUCT_MARKUP_EXTS = [".svelte"];
42
+ const OG_PREFIX = "import.meta.og.";
43
+ function template_calls(code, id, scripts) {
44
+ let outside = false;
45
+ for (let at = code.indexOf(OG_PREFIX); at !== -1 && !outside; at = code.indexOf(OG_PREFIX, at + 1)) outside = !scripts.some((s) => at >= s.offset && at < s.offset + s.code.length);
46
+ if (!outside) return [];
47
+ let fragment;
48
+ try {
49
+ fragment = parse(blank_styles(code), {
50
+ modern: true,
51
+ filename: id
52
+ }).fragment;
53
+ } catch {
54
+ return [];
55
+ }
56
+ const calls = [];
57
+ walk_ast(fragment, (n) => {
58
+ if (n.type !== "CallExpression") return;
59
+ const callee = code.slice(n.callee.start, n.callee.end);
60
+ if (callee.startsWith(OG_PREFIX)) calls.push({
61
+ start: n.start,
62
+ end: n.end,
63
+ method: callee.slice(15),
64
+ args: ""
65
+ });
66
+ });
67
+ return calls;
68
+ }
69
+ function in_regions(regions, place) {
70
+ return regions.flatMap((r) => find_og_calls(r.code, OG_PREFIX).map((c) => ({
71
+ ...c,
72
+ start: c.start + r.offset,
73
+ end: c.end + r.offset,
74
+ place
75
+ })));
76
+ }
77
+ var ModuleCode = class {
78
+ #id;
79
+ #markdown;
80
+ #page = null;
81
+ constructor(id, markdown_exts) {
82
+ this.#id = id;
83
+ this.#markdown = !is_js_module(id) && is_markup_module(id, markdown_exts);
84
+ }
85
+ #page_of(code) {
86
+ if (this.#page === null || this.#page.src !== code) this.#page = new MarkdownPage(code);
87
+ return this.#page;
88
+ }
89
+ regions(code) {
90
+ if (this.#markdown) return this.#page_of(code).scripts();
91
+ return og_js_regions(code, this.#id, CONSTRUCT_MARKUP_EXTS);
92
+ }
93
+ calls(code) {
94
+ if (this.#markdown) {
95
+ const page = this.#page_of(code);
96
+ return [...in_regions(page.scripts(), "markdown script"), ...in_regions(page.expressions(), "markup")];
97
+ }
98
+ const regions = og_js_regions(code, this.#id, CONSTRUCT_MARKUP_EXTS) ?? [];
99
+ const calls = in_regions(regions, "script");
100
+ if (!is_js_module(this.#id) && is_markup_module(this.#id, CONSTRUCT_MARKUP_EXTS)) calls.push(...template_calls(code, this.#id, regions).map((c) => ({
101
+ ...c,
102
+ place: "markup"
103
+ })));
104
+ return calls;
105
+ }
106
+ calls_macro(code, name) {
107
+ return this.calls(code).some((c) => c.method === name || c.method.startsWith(`${name}.`));
108
+ }
109
+ };
110
+ const PLACE_TEXT = {
111
+ markup: "the markup (a template expression)",
112
+ "markdown script": "a markdown page's <script>"
113
+ };
38
114
  /**
39
115
  * Run the ordered macro passes over one module. `source` is the CURRENT text (a content-preset tag
40
116
  * or an earlier pass may already have edited it upstream) — never the raw file — because each pass
@@ -54,6 +130,7 @@ async function run_module_macros(source, id, ctx, profiler) {
54
130
  return true;
55
131
  };
56
132
  const own = ctx.ownSource(id.split("?")[0]);
133
+ const reading = new ModuleCode(id, ctx.markdownExts ?? []);
57
134
  const refuse = (macro) => {
58
135
  throw new OgygiaError("macro_outside_app", {
59
136
  file: id.split("?")[0],
@@ -88,7 +165,7 @@ async function run_module_macros(source, id, ctx, profiler) {
88
165
  for (const macro of ctx.macros) {
89
166
  if (!out.includes(`import.meta.og.${macro.name}`)) continue;
90
167
  if (!own) {
91
- if (calls_macro(out, macro.name)) refuse(macro.name);
168
+ if (reading.calls_macro(out, macro.name)) refuse(macro.name);
92
169
  continue;
93
170
  }
94
171
  rel ??= path.relative(ctx.root, id.split("?")[0]).split(path.sep).join("/");
@@ -99,28 +176,39 @@ async function run_module_macros(source, id, ctx, profiler) {
99
176
  root: ctx.root,
100
177
  alias: ctx.alias,
101
178
  markupExts: CONSTRUCT_MARKUP_EXTS,
179
+ regions: (code) => reading.regions(code),
102
180
  watch: ctx.watch ?? noop
103
181
  });
104
182
  if (profiler.P) {
105
183
  profiler.prof.macroMs += performance.now() - started;
106
184
  profiler.prof.macroN++;
107
185
  }
108
- if (rewritten !== out) {
186
+ if (typeof rewritten !== "string") apply(rewritten);
187
+ else if (rewritten !== out) {
109
188
  out = rewritten;
110
189
  touched = true;
111
190
  maps.push(null);
112
191
  }
113
192
  }
114
193
  }
115
- if (out.includes("import.meta.og.")) for (const call of find_og_calls(out, "import.meta.og.")) {
194
+ if (out.includes("import.meta.og.")) for (const call of reading.calls(out)) {
116
195
  const name = call.method.split(".")[0];
117
196
  const pkg = MACRO_PACKAGES[name];
118
- if (pkg === void 0 || ctx.macros?.some((m) => m.name === name)) continue;
119
- if (!own) refuse(name);
120
- throw new OgygiaError("macro_needs_plugin", {
121
- file: id.split("?")[0],
122
- macro: name,
123
- package: pkg.package,
197
+ if (pkg === void 0) continue;
198
+ if (!ctx.macros?.some((m) => m.name === name)) {
199
+ if (!own) refuse(name);
200
+ throw new OgygiaError("macro_needs_plugin", {
201
+ file: id.split("?")[0],
202
+ macro: name,
203
+ package: pkg.package,
204
+ plugin: pkg.plugin
205
+ });
206
+ }
207
+ if (call.place === "script") continue;
208
+ throw new OgygiaError("macro_in_markup", {
209
+ file: `${id.split("?")[0]}:${line_of(out, call.start)}`,
210
+ macro: call.method,
211
+ place: PLACE_TEXT[call.place],
124
212
  plugin: pkg.plugin
125
213
  });
126
214
  }
@@ -1,5 +1,6 @@
1
1
  import { find_og_calls, og_js_regions } from "../parse/scan.js";
2
2
  import { parse_module } from "../parse/oxc.js";
3
+ import { line_of, walk_ast } from "../parse/ast.js";
3
4
  import { og_member } from "./wire.js";
4
5
  import { OgygiaError } from "../messages.js";
5
6
  import { splice_text } from "../splice.js";
@@ -7,11 +8,6 @@ import { splice_text } from "../splice.js";
7
8
  const EXPORT_CONST_TAIL_RE = /\bexport\s+const\s+([A-Za-z_$][\w$]*)\s*=\s*$/;
8
9
  const MARKER = "import.meta.og.source";
9
10
  const IMPORT = `import { __og_source } from 'ogygia/internal';`;
10
- function line_of(src, offset) {
11
- let line = 1;
12
- for (let i = 0; i < offset && i < src.length; i++) if (src[i] === "\n") line++;
13
- return line;
14
- }
15
11
  function misuse(id, src, offset, what) {
16
12
  throw new OgygiaError("macro_source_misuse", {
17
13
  file: id,
@@ -19,16 +15,6 @@ function misuse(id, src, offset, what) {
19
15
  problem: what
20
16
  });
21
17
  }
22
- function walk(node, visit) {
23
- visit(node);
24
- for (const key in node) {
25
- if (key === "type" || key === "start" || key === "end") continue;
26
- const child = node[key];
27
- if (Array.isArray(child)) {
28
- for (const c of child) if (c && typeof c === "object" && typeof c.type === "string") walk(c, visit);
29
- } else if (child && typeof child === "object" && typeof child.type === "string") walk(child, visit);
30
- }
31
- }
32
18
  function ast_edits_or_null_unparsed(src, region, id, rel) {
33
19
  const { program, ok } = parse_module(region.code, id);
34
20
  if (!ok || !program) return null;
@@ -62,7 +48,7 @@ function ast_edits_or_null_unparsed(src, region, id, rel) {
62
48
  });
63
49
  }
64
50
  }
65
- walk(program, (n) => {
51
+ walk_ast(program, (n) => {
66
52
  if (n.type === "CallExpression" && og_member(n.callee) === "source" && !claimed.has(n)) misuse(id, src, region.offset + n.start, `source() outside an \`export const\` initializer`);
67
53
  if (og_member(n) === "source" && !claimed.has(n)) misuse(id, src, region.offset + n.start, `bare import.meta.og.source used as a value`);
68
54
  });
@@ -56,6 +56,15 @@ export declare const BUILD_ERRORS: {
56
56
  }) => string;
57
57
  details: () => string;
58
58
  };
59
+ macro_in_markup: {
60
+ text: (a: {
61
+ file: string;
62
+ macro: string;
63
+ place: string;
64
+ plugin: string;
65
+ }) => string;
66
+ details: () => string;
67
+ };
59
68
  kit_config_not_literal: {
60
69
  text: (a: {
61
70
  file: string;
package/dist/messages.js CHANGED
@@ -96,6 +96,18 @@ const BUILD_ERRORS = {
96
96
  \`plugins\` (before \`sveltekit()\`).
97
97
  `
98
98
  },
99
+ macro_in_markup: {
100
+ text: (a) => `${a.file} — import.meta.og.${a.macro}() sits in ${a.place}, where \`${a.plugin}\` does not compile it: it would reach the page as is and fail there.`,
101
+ details: () => prose`
102
+ A plugin's \`import.meta.og.*\` macro is compiled where the module's code is: a JS or TS
103
+ module, and the \`<script>\` of a \`.svelte\` component (\`image()\` compiles a markdown
104
+ page's \`<script>\` too). A call in a template expression (\`{…}\` in markup or in a
105
+ markdown page's prose), or in a markdown page's \`<script>\` for a macro that does not
106
+ compile there, is not rewritten. Call the macro in the component's \`<script>\` (or in a
107
+ \`.ts\` module it imports) and use its value in the markup. A call written as text (a code
108
+ span, fenced code, plain prose) is no call and needs no change.
109
+ `
110
+ },
99
111
  kit_config_not_literal: {
100
112
  text: (a) => `${a.file}: \`config.${a.key}\` must be a literal (true, false, a number, a string or null) — ogygia reads it at build time.`,
101
113
  details: () => prose`
@@ -212,7 +224,7 @@ const BUILD_ERRORS = {
212
224
  `
213
225
  },
214
226
  as_region_removed: {
215
- until: "0.15",
227
+ until: "0.16",
216
228
  text: (a) => `${a.host}: import.meta.og.asRegion is gone. Mark the import itself; a named import takes the same options:\n${a.fixes}`,
217
229
  details: () => prose`
218
230
  \`import.meta.og.asRegion(Component, options)\` was replaced by the import it stood for. A
@@ -362,7 +374,7 @@ const BUILD_ERRORS = {
362
374
  `
363
375
  },
364
376
  hole_wake_removed: {
365
- until: "0.15",
377
+ until: "0.16",
366
378
  text: (a) => prose`
367
379
  ${a.host}: ${a.said ?? "this import"} sets \`${a.wake_key}: '${a.wake}'\` on a
368
380
  \`${a.render_key}: 'deferred'\` region. A deferred region ships no JS, so \`${a.wake_key}\`
@@ -411,7 +423,7 @@ const BUILD_ERRORS = {
411
423
  `
412
424
  },
413
425
  barrels_option_removed: {
414
- until: "0.15",
426
+ until: "0.16",
415
427
  text: () => prose`
416
428
  \`ogygia({ barrels })\` is gone: the barrel rewrite is a plugin now. Install
417
429
  \`@ogygia/barrels\` and list \`barrels({ … })\` (from \`@ogygia/barrels\`) beside
@@ -0,0 +1,14 @@
1
+ import { AstNode } from "./oxc.js";
2
+ /** Calls `visit` on `node` and on every node below it, parents first, in source order. */
3
+ export declare function walk_ast(node: AstNode, visit: (n: AstNode) => void): void;
4
+ /** The 1-based line `offset` falls on in `src`. */
5
+ export declare function line_of(src: string, offset: number): number;
6
+ /** What {@link literal_of} returns for an expression that is not written out in place. */
7
+ export declare const NOT_LITERAL: unique symbol;
8
+ /**
9
+ * The value `n` writes when it is a literal: a string, number, boolean or `null`; a template with no
10
+ * `${…}`; a signed number; `a / b` or `a * b` of numbers; an array or object literal of those (no
11
+ * spreads, computed keys or methods); any of them wrapped in parentheses, `as` or `satisfies`.
12
+ * Anything else (a name, a call, a regex, a bigint) is {@link NOT_LITERAL}.
13
+ */
14
+ export declare function literal_of(n: AstNode): unknown;
@@ -0,0 +1,76 @@
1
+ // src/parse/ast.ts
2
+ /** Calls `visit` on `node` and on every node below it, parents first, in source order. */
3
+ function walk_ast(node, visit) {
4
+ visit(node);
5
+ for (const key in node) {
6
+ if (key === "type" || key === "start" || key === "end") continue;
7
+ const child = node[key];
8
+ if (Array.isArray(child)) {
9
+ for (const c of child) if (c && typeof c === "object" && typeof c.type === "string") walk_ast(c, visit);
10
+ } else if (child && typeof child === "object" && typeof child.type === "string") walk_ast(child, visit);
11
+ }
12
+ }
13
+ /** The 1-based line `offset` falls on in `src`. */
14
+ function line_of(src, offset) {
15
+ let line = 1;
16
+ const end = Math.min(offset, src.length);
17
+ for (let i = src.indexOf("\n"); i !== -1 && i < end; i = src.indexOf("\n", i + 1)) line++;
18
+ return line;
19
+ }
20
+ /** What {@link literal_of} returns for an expression that is not written out in place. */
21
+ const NOT_LITERAL = Symbol("not literal");
22
+ /**
23
+ * The value `n` writes when it is a literal: a string, number, boolean or `null`; a template with no
24
+ * `${…}`; a signed number; `a / b` or `a * b` of numbers; an array or object literal of those (no
25
+ * spreads, computed keys or methods); any of them wrapped in parentheses, `as` or `satisfies`.
26
+ * Anything else (a name, a call, a regex, a bigint) is {@link NOT_LITERAL}.
27
+ */
28
+ function literal_of(n) {
29
+ switch (n.type) {
30
+ case "Literal": return n.regex || n.bigint !== void 0 ? NOT_LITERAL : n.value;
31
+ case "TemplateLiteral": return n.expressions.length === 0 ? n.quasis.map((q) => q.value.cooked).join("") : NOT_LITERAL;
32
+ case "UnaryExpression": {
33
+ if (n.operator !== "-" && n.operator !== "+") return NOT_LITERAL;
34
+ const v = literal_of(n.argument);
35
+ if (typeof v !== "number") return NOT_LITERAL;
36
+ return n.operator === "-" ? -v : v;
37
+ }
38
+ case "BinaryExpression": {
39
+ const l = literal_of(n.left);
40
+ const r = literal_of(n.right);
41
+ if (typeof l !== "number" || typeof r !== "number") return NOT_LITERAL;
42
+ if (n.operator === "/") return l / r;
43
+ if (n.operator === "*") return l * r;
44
+ return NOT_LITERAL;
45
+ }
46
+ case "ArrayExpression": {
47
+ const out = [];
48
+ for (const e of n.elements) {
49
+ if (!e || e.type === "SpreadElement") return NOT_LITERAL;
50
+ const v = literal_of(e);
51
+ if (v === NOT_LITERAL) return NOT_LITERAL;
52
+ out.push(v);
53
+ }
54
+ return out;
55
+ }
56
+ case "ObjectExpression": {
57
+ const out = {};
58
+ for (const p of n.properties) {
59
+ if (p.type !== "Property" || p.computed || p.kind !== "init" || p.method) return NOT_LITERAL;
60
+ let key;
61
+ if (p.key.type === "Identifier") key = p.key.name;
62
+ else if (typeof p.key.value === "string") key = p.key.value;
63
+ else return NOT_LITERAL;
64
+ const v = literal_of(p.value);
65
+ if (v === NOT_LITERAL) return NOT_LITERAL;
66
+ out[key] = v;
67
+ }
68
+ return out;
69
+ }
70
+ case "TSAsExpression":
71
+ case "TSSatisfiesExpression":
72
+ case "ParenthesizedExpression": return literal_of(n.expression);
73
+ default: return NOT_LITERAL;
74
+ }
75
+ }
76
+ export { NOT_LITERAL, line_of, literal_of, walk_ast };
@@ -39,6 +39,31 @@ export declare function is_markup_module(id: string, markup_exts: readonly strin
39
39
  * (they end in `.ts`/`.js`), so a `.svelte`-suffixed markup ext never shadows them.
40
40
  */
41
41
  export declare function og_js_regions(src: string, id: string, markup_exts: readonly string[]): JsRegion[] | null;
42
+ /**
43
+ * The `<script>` blocks of a markdown page (`.svx`, `.md`): the ones its preprocessor keeps as
44
+ * script, so a block that starts a line outside code. A fence's text and a code span are text,
45
+ * blanked before the walk so a `<script>` written there is never a block. Offsets are the source's.
46
+ * test/macros-need-plugin.test.ts, test/markdown-code.test.ts.
47
+ */
48
+ export declare function markdown_scripts(src: string): JsRegion[];
49
+ /** One markdown page's text, parsed at most once: its {@link markdown_scripts} and its
50
+ * {@link markdown_expressions} read the same parse. */
51
+ export declare class MarkdownPage {
52
+ #private;
53
+ readonly src: string;
54
+ constructor(src: string);
55
+ /** The page's `<script>` blocks, as {@link markdown_scripts}. */
56
+ scripts(): JsRegion[];
57
+ /** The page's template expressions, as {@link markdown_expressions}. */
58
+ expressions(): JsRegion[];
59
+ }
60
+ /**
61
+ * The template expressions of a markdown page (`.svx`, `.md`): each `{…}` of its prose (in text or
62
+ * in an attribute), which its preprocessor hands Svelte as code. Fenced code, code spans, HTML
63
+ * comments and the page's `<script>` / `<style>` blocks are not prose; a `\{` is text. Offsets are
64
+ * the source's. test/macros-need-plugin.test.ts.
65
+ */
66
+ export declare function markdown_expressions(src: string): JsRegion[];
42
67
  /** A `<script>` or `<style>` block of a component's source. */
43
68
  export interface ComponentBlock {
44
69
  readonly kind: "script" | "style";
@@ -1,5 +1,6 @@
1
1
  import { OgygiaError } from "../messages.js";
2
2
  import { next_any_tag, tag_name } from "@ogygia/core/contract";
3
+ import { parse, postprocess, preprocess } from "micromark";
3
4
  // src/parse/scan.ts
4
5
  const WS_RE = /\s/;
5
6
  const TEMPLATE_INTERPOLATION_RE = /\$\{/;
@@ -267,6 +268,109 @@ function og_js_regions(src, id, markup_exts) {
267
268
  }));
268
269
  return null;
269
270
  }
271
+ const LINE_LEAD_RE = /^ {0,3}$/;
272
+ /**
273
+ * The `<script>` blocks of a markdown page (`.svx`, `.md`): the ones its preprocessor keeps as
274
+ * script, so a block that starts a line outside code. A fence's text and a code span are text,
275
+ * blanked before the walk so a `<script>` written there is never a block. Offsets are the source's.
276
+ * test/macros-need-plugin.test.ts, test/markdown-code.test.ts.
277
+ */
278
+ function markdown_scripts(src) {
279
+ return new MarkdownPage(src).scripts();
280
+ }
281
+ /** One markdown page's text, parsed at most once: its {@link markdown_scripts} and its
282
+ * {@link markdown_expressions} read the same parse. */
283
+ var MarkdownPage = class {
284
+ src;
285
+ #prose = null;
286
+ constructor(src) {
287
+ this.src = src;
288
+ }
289
+ #read() {
290
+ return this.#prose ??= markdown_prose(this.src);
291
+ }
292
+ /** The page's `<script>` blocks, as {@link markdown_scripts}. */
293
+ scripts() {
294
+ return script_blocks(this.#read()).map((b) => ({
295
+ code: this.src.slice(b.start, b.end),
296
+ offset: b.start
297
+ }));
298
+ }
299
+ /** The page's template expressions, as {@link markdown_expressions}. */
300
+ expressions() {
301
+ return prose_expressions(this.src, this.#read());
302
+ }
303
+ };
304
+ const COMMENT_RE = /<!--[\s\S]*?(?:-->|$)/g;
305
+ /**
306
+ * The template expressions of a markdown page (`.svx`, `.md`): each `{…}` of its prose (in text or
307
+ * in an attribute), which its preprocessor hands Svelte as code. Fenced code, code spans, HTML
308
+ * comments and the page's `<script>` / `<style>` blocks are not prose; a `\{` is text. Offsets are
309
+ * the source's. test/macros-need-plugin.test.ts.
310
+ */
311
+ function markdown_expressions(src) {
312
+ return new MarkdownPage(src).expressions();
313
+ }
314
+ function prose_expressions(src, read) {
315
+ const prose = read.replace(COMMENT_RE, blank);
316
+ let text = prose;
317
+ for (const b of script_blocks(prose).concat(component_blocks(prose).filter((b) => b.kind === "style"))) text = text.slice(0, b.open) + " ".repeat(b.close - b.open) + text.slice(b.close);
318
+ const out = [];
319
+ for (let at = text.indexOf("{"); at !== -1; at = text.indexOf("{", at + 1)) {
320
+ if (text[at - 1] === "\\") continue;
321
+ const close = expression_end(text, at);
322
+ if (close < 0) continue;
323
+ out.push({
324
+ code: src.slice(at + 1, close),
325
+ offset: at + 1
326
+ });
327
+ at = close;
328
+ }
329
+ return out;
330
+ }
331
+ function blank(text) {
332
+ return text.replace(/[^\n]/g, " ");
333
+ }
334
+ function expression_end(text, open) {
335
+ let depth = 0;
336
+ for (let i = open; i < text.length; i++) {
337
+ const c = text[i];
338
+ if (c === "\"" || c === "'" || c === "`") {
339
+ for (i++; i < text.length && text[i] !== c; i++) if (text[i] === "\\") i++;
340
+ } else if (c === "{") depth++;
341
+ else if (c === "}" && --depth === 0) return i;
342
+ }
343
+ return -1;
344
+ }
345
+ const NO_INDENTED_CODE = { extensions: [{ disable: { null: ["codeIndented"] } }] };
346
+ const FRONTMATTER_OPEN_RE = /^?(?:[ \t]*(?:\r\n|\r|\n))*---(?:\r\n|\r|\n)/;
347
+ const FRONTMATTER_CLOSE_RE = /(?<=[\r\n])---/g;
348
+ function frontmatter_end(src) {
349
+ const open = FRONTMATTER_OPEN_RE.exec(src);
350
+ if (open === null) return 0;
351
+ FRONTMATTER_CLOSE_RE.lastIndex = open[0].length - 1;
352
+ const close = FRONTMATTER_CLOSE_RE.exec(src);
353
+ return close === null ? 0 : close.index + 3;
354
+ }
355
+ function markdown_prose(page) {
356
+ const front = frontmatter_end(page);
357
+ const src = front === 0 ? page : blank(page.slice(0, front)) + page.slice(front);
358
+ const events = postprocess(parse(NO_INDENTED_CODE).document().write(preprocess()(src, void 0, true)));
359
+ let out = "";
360
+ let at = 0;
361
+ for (const [kind, token] of events) {
362
+ if (kind !== "enter" || token.type !== "codeFlowValue" && token.type !== "codeText") continue;
363
+ const start = token.start.offset;
364
+ const end = token.end.offset;
365
+ if (start < at) continue;
366
+ out += src.slice(at, start) + blank(src.slice(start, end));
367
+ at = end;
368
+ }
369
+ return out + src.slice(at);
370
+ }
371
+ function script_blocks(prose) {
372
+ return component_blocks(prose).filter((b) => b.kind === "script" && LINE_LEAD_RE.test(prose.slice(prose.lastIndexOf("\n", b.open - 1) + 1, b.open)));
373
+ }
270
374
  /**
271
375
  * Every `<script>` and `<style>` block of a component's source, in order, read with core's tag walk
272
376
  * (#1370): a value may hold `>` or the other quote, any quoting and case, a comment holds no block,
@@ -294,4 +398,4 @@ function component_blocks(src) {
294
398
  }
295
399
  return blocks;
296
400
  }
297
- export { component_blocks, find_og_calls, is_js_module, is_markup_module, match_close, og_js_regions, split_first_string };
401
+ export { MarkdownPage, component_blocks, find_og_calls, is_js_module, is_markup_module, markdown_expressions, markdown_scripts, match_close, og_js_regions, split_first_string };
@@ -1,10 +1,6 @@
1
1
  import { OgygiaError } from "../messages.js";
2
+ import { line_of } from "../parse/ast.js";
2
3
  // src/region/marked-imports.ts
3
- function line_of(src, offset) {
4
- let line = 1;
5
- for (let i = 0; i < offset; i++) if (src.charCodeAt(i) === 10) line++;
6
- return line;
7
- }
8
4
  function line_col(src, offset) {
9
5
  let line = 1;
10
6
  let last = -1;
@@ -1,10 +1,8 @@
1
1
  /** The part of a bundler's plugin context the wait reads (Rolldown's, Vite's build). */
2
2
  export interface CompiledGraph {
3
3
  getModuleIds(): Iterable<string>;
4
- getModuleInfo(id: string): {
5
- code: string | null;
6
- } | null;
7
- resolve(source: string): Promise<{
4
+ getModuleInfo(id: string): ModuleInfo | null;
5
+ resolve(source: string, importer?: string): Promise<{
8
6
  external?: unknown;
9
7
  } | null>;
10
8
  load(options: {
@@ -12,10 +10,16 @@ export interface CompiledGraph {
12
10
  resolveDependencies: boolean;
13
11
  }): Promise<unknown>;
14
12
  }
13
+ interface ModuleInfo {
14
+ code: string | null;
15
+ importedIds: readonly string[];
16
+ dynamicallyImportedIds: readonly string[];
17
+ }
15
18
  /**
16
- * Resolves once the bundler has compiled every module of the bundle (loaded, transformed, its
17
- * imports resolved), dynamic imports and their imports included, but the ones `skip` names: the
18
- * modules that wait here themselves, which would otherwise wait on each other. Each round loads
19
- * what the last one found, until a round finds nothing new. An external module is never loaded.
19
+ * Resolves once the bundler has compiled every module of the bundle, dynamic imports and their
20
+ * imports included, but the ones `skip` names (the modules that wait here themselves). It never
21
+ * starts a module's load: it waits on a module only once the bundler has begun it, and stops
22
+ * waiting for one after `quiet` ms in which no awaited module was begun.
20
23
  */
21
- export declare function graph_compiled(graph: CompiledGraph, skip: (id: string) => boolean): Promise<void>;
24
+ export declare function graph_compiled(graph: CompiledGraph, skip: (id: string) => boolean, quiet?: number): Promise<void>;
25
+ export {};
@@ -1,24 +1,95 @@
1
+ import { STALE, backoffAfter, clock, policy, scope } from "@ogygia/machine";
1
2
  // src/vite/graph-compiled.ts
3
+ const BEGUN = policy({
4
+ attempts: 1,
5
+ backoff: [
6
+ 1,
7
+ 2,
8
+ 4,
9
+ 8,
10
+ 16,
11
+ 32,
12
+ 50
13
+ ],
14
+ jitter: 0
15
+ });
2
16
  /**
3
- * Resolves once the bundler has compiled every module of the bundle (loaded, transformed, its
4
- * imports resolved), dynamic imports and their imports included, but the ones `skip` names: the
5
- * modules that wait here themselves, which would otherwise wait on each other. Each round loads
6
- * what the last one found, until a round finds nothing new. An external module is never loaded.
17
+ * Resolves once the bundler has compiled every module of the bundle, dynamic imports and their
18
+ * imports included, but the ones `skip` names (the modules that wait here themselves). It never
19
+ * starts a module's load: it waits on a module only once the bundler has begun it, and stops
20
+ * waiting for one after `quiet` ms in which no awaited module was begun.
7
21
  */
8
- async function graph_compiled(graph, skip) {
22
+ async function graph_compiled(graph, skip, quiet = 3e4) {
23
+ const owner = scope();
24
+ const begun = new BegunModules(graph, owner, quiet);
9
25
  const seen = /* @__PURE__ */ new Set();
10
- for (;;) {
11
- const next = [...graph.getModuleIds()].filter((id) => !seen.has(id) && !skip(id));
12
- if (next.length === 0) return;
13
- for (const id of next) seen.add(id);
14
- await Promise.all(next.map((id) => compiled(graph, id)));
26
+ let named = null;
27
+ const walk = async (id, importer) => {
28
+ if (seen.has(id) || skip(id)) return;
29
+ seen.add(id);
30
+ const info = await begun.info_once_begun(id);
31
+ if (info === STALE) return;
32
+ if (info.code === null) {
33
+ named ??= importer_of_each_import(graph);
34
+ if ((await graph.resolve(id, importer ?? named.get(id)))?.external) return;
35
+ await graph.load({
36
+ id,
37
+ resolveDependencies: true
38
+ });
39
+ }
40
+ const done = graph.getModuleInfo(id);
41
+ if (done === null) return;
42
+ await Promise.all([...done.importedIds, ...done.dynamicallyImportedIds].map((m) => walk(m, id)));
43
+ };
44
+ try {
45
+ for (;;) {
46
+ named = null;
47
+ const next = [...graph.getModuleIds()].filter((id) => !seen.has(id) && !skip(id));
48
+ if (next.length === 0) return;
49
+ await Promise.all(next.map((id) => walk(id, void 0)));
50
+ }
51
+ } finally {
52
+ owner.close();
15
53
  }
16
54
  }
17
- async function compiled(graph, id) {
18
- if (graph.getModuleInfo(id)?.code == null && (await graph.resolve(id))?.external) return;
19
- await graph.load({
20
- id,
21
- resolveDependencies: true
22
- });
55
+ function importer_of_each_import(graph) {
56
+ const named = /* @__PURE__ */ new Map();
57
+ for (const id of graph.getModuleIds()) {
58
+ const info = graph.getModuleInfo(id);
59
+ if (info === null) continue;
60
+ for (const m of info.importedIds) if (!named.has(m)) named.set(m, id);
61
+ for (const m of info.dynamicallyImportedIds) if (!named.has(m)) named.set(m, id);
62
+ }
63
+ return named;
23
64
  }
65
+ var BegunModules = class {
66
+ #graph;
67
+ #owner;
68
+ #quiet;
69
+ #waiting = 0;
70
+ #moved = 0;
71
+ constructor(graph, owner, quiet) {
72
+ this.#graph = graph;
73
+ this.#owner = owner;
74
+ this.#quiet = quiet;
75
+ }
76
+ info_once_begun(id) {
77
+ const now = this.#graph.getModuleInfo(id);
78
+ if (now !== null) return Promise.resolve(now);
79
+ if (this.#waiting++ === 0) this.#moved = clock.mono();
80
+ return this.#owner.task(() => new Promise((settle) => {
81
+ const check = (tries) => {
82
+ const info = this.#graph.getModuleInfo(id);
83
+ if (info !== null) this.#moved = clock.mono();
84
+ else if (clock.mono() - this.#moved < this.#quiet) {
85
+ this.#owner.timeout(() => check(tries + 1), backoffAfter(BEGUN, tries));
86
+ return;
87
+ }
88
+ this.#waiting--;
89
+ settle(info ?? STALE);
90
+ };
91
+ check(1);
92
+ }));
93
+ }
94
+ };
24
95
  export { graph_compiled };
@@ -2,9 +2,9 @@ import { regionId, regionIdentity, strategyKey } from "../region/identity.js";
2
2
  import { wrapperVirtualId } from "../ids.js";
3
3
  import { CLIENT_BINDING_STUB, DEFAULT_IMPORT_KEYS, ImportKeys, import_keys_hint, islandChunkFileName, islandId, islandPublicUrl, normalize_import_keys } from "../region/transform.js";
4
4
  import { rewrite_lake_import_to_placeholder } from "../region/emit.js";
5
- import { MacroContext } from "../macros/pipeline.js";
5
+ import { MacroContext, MacroResult } from "../macros/pipeline.js";
6
6
  import { PrescanHook } from "../ctx.js";
7
- import { BuildContext, ExportsSeam, MacroHandler, MarkupRegions, MarkupSource, OgygiaPlugin, PageReadWhy, PageReads, PageReadsResolve, PinnedDecl, PluginDefinition, RegionsSeam, StageTransform, StayedAnswer, TransformContext, TransformStage, definePlugin } from "./plugin-api.js";
7
+ import { BuildContext, ExportsSeam, MARKDOWN_EXTENSION_API, MacroHandler, MarkdownExtension, MarkdownFinish, MarkupRegions, MarkupSource, OgygiaPlugin, PageReadWhy, PageReads, PageReadsResolve, PinnedDecl, PluginDefinition, RegionsSeam, StageTransform, StayedAnswer, TransformContext, TransformStage, definePlugin } from "./plugin-api.js";
8
8
  import { Entry, ExportMap, Leaf, Policy } from "../exports/index.js";
9
9
  import { OgygiaOptions, OgygiaPreset, OgygiaRateLimit } from "./options.js";
10
10
  import { Plugin } from "vite";
@@ -18,4 +18,4 @@ import { Plugin } from "vite";
18
18
  * @returns Vite plugins (`ogygia` pre + island sourcemap fix post). Vite flattens the array.
19
19
  */
20
20
  export declare function ogygia(options?: OgygiaOptions): Plugin[];
21
- export { type BuildContext, CLIENT_BINDING_STUB, DEFAULT_IMPORT_KEYS, type Entry as ExportEntry, type Leaf as ExportLeaf, type ExportMap, type Policy as ExportPolicy, type ExportsSeam, type ImportKeys, type MacroContext, type MacroHandler, type MarkupRegions, type MarkupSource, type OgygiaOptions, type OgygiaPlugin, type OgygiaPreset, type OgygiaRateLimit, type PageReadWhy, type PageReads, type PageReadsResolve, type PinnedDecl, type PluginDefinition, type PrescanHook, type RegionsSeam, type StageTransform, type StayedAnswer, type TransformContext, type TransformStage, definePlugin, import_keys_hint, islandChunkFileName, islandId, islandPublicUrl, normalize_import_keys, regionId, regionIdentity, rewrite_lake_import_to_placeholder, strategyKey, wrapperVirtualId };
21
+ export { type BuildContext, CLIENT_BINDING_STUB, DEFAULT_IMPORT_KEYS, type Entry as ExportEntry, type Leaf as ExportLeaf, type ExportMap, type Policy as ExportPolicy, type ExportsSeam, type ImportKeys, MARKDOWN_EXTENSION_API, type MacroContext, type MacroHandler, type MacroResult, type MarkdownExtension, type MarkdownFinish, type MarkupRegions, type MarkupSource, type OgygiaOptions, type OgygiaPlugin, type OgygiaPreset, type OgygiaRateLimit, type PageReadWhy, type PageReads, type PageReadsResolve, type PinnedDecl, type PluginDefinition, type PrescanHook, type RegionsSeam, type StageTransform, type StayedAnswer, type TransformContext, type TransformStage, definePlugin, import_keys_hint, islandChunkFileName, islandId, islandPublicUrl, normalize_import_keys, regionId, regionIdentity, rewrite_lake_import_to_placeholder, strategyKey, wrapperVirtualId };
@@ -7,7 +7,7 @@ import { wrapperVirtualId } from "../ids.js";
7
7
  import { CLIENT_BINDING_STUB, DEFAULT_IMPORT_KEYS, import_keys_hint, is_island_path, islandChunkFileName, islandId, islandPublicUrl, normalize_import_keys } from "../region/transform.js";
8
8
  import { regionId, regionIdentity, strategyKey } from "../region/identity.js";
9
9
  import { rewrite_lake_import_to_placeholder } from "../region/emit.js";
10
- import { definePlugin, find_plugins, resolve_plugins } from "./plugin-api.js";
10
+ import { MARKDOWN_EXTENSION_API, definePlugin, find_plugins, resolve_plugins } from "./plugin-api.js";
11
11
  import { definers_plugin } from "./definers.js";
12
12
  import { assert_known_options, resolve_options, validate_region_presets } from "./options.js";
13
13
  import { clientBuildWillSkip, default_kit_dirs, hasAnyCsrFalseRoute, inject_keep_client_route, keep_client_dir, kit_major, kit_may_hydrate, resolve_kit_paths, route_reader } from "../kit.js";
@@ -195,7 +195,8 @@ function ogygia(options = {}) {
195
195
  names: () => compiler_of(session, "regions.names").region_names(),
196
196
  hosts: () => compiler_of(session, "regions.hosts").region_hosts(),
197
197
  whyStayed: (file, importers) => why_stayed(file, importers)
198
- }
198
+ },
199
+ routes_dir: () => kit.dirs.routes_dir
199
200
  };
200
201
  const why_stayed = (file, importers) => {
201
202
  const ids = [...importers];
@@ -434,6 +435,7 @@ function ogygia(options = {}) {
434
435
  resolve_alias,
435
436
  component_css,
436
437
  macros,
438
+ markdown_exts: markup.flatMap((m) => m.extensions),
437
439
  page_reads,
438
440
  prescans,
439
441
  plugins: listed_plugins,
@@ -903,4 +905,4 @@ function ogygia(options = {}) {
903
905
  lazy_files()
904
906
  ];
905
907
  }
906
- export { CLIENT_BINDING_STUB, DEFAULT_IMPORT_KEYS, definePlugin, import_keys_hint, islandChunkFileName, islandId, islandPublicUrl, normalize_import_keys, ogygia, regionId, regionIdentity, rewrite_lake_import_to_placeholder, strategyKey, wrapperVirtualId };
908
+ export { CLIENT_BINDING_STUB, DEFAULT_IMPORT_KEYS, MARKDOWN_EXTENSION_API, definePlugin, import_keys_hint, islandChunkFileName, islandId, islandPublicUrl, normalize_import_keys, ogygia, regionId, regionIdentity, rewrite_lake_import_to_placeholder, strategyKey, wrapperVirtualId };
@@ -1,7 +1,7 @@
1
1
  import { ExportMap, Policy } from "../exports/index.js";
2
2
  import { ClientRealmFile, ServerRealm } from "../link/caps.js";
3
3
  import { Definers } from "./definers.js";
4
- import { MacroContext } from "../macros/pipeline.js";
4
+ import { MacroContext, MacroResult } from "../macros/pipeline.js";
5
5
  import { PrescanHook } from "../ctx.js";
6
6
  import { BarrelLeftReason, RuntimeHookName, ServerHookName } from "@ogygia/core/contract";
7
7
  import MagicString from "magic-string";
@@ -41,8 +41,9 @@ export interface PluginDefinition<Options = unknown> {
41
41
  }
42
42
  /** A `import.meta.og.<name>` macro: rewrites a module that contains the marker (it is called only
43
43
  * then), before the island transform or region minting see it. Returns the new code (the same
44
- * string when nothing changed). */
45
- export type MacroHandler = (code: string, m: MacroContext) => string | Promise<string>;
44
+ * string when nothing changed), or the edits that make it: edits keep the module's source map, a
45
+ * string loses it. */
46
+ export type MacroHandler = (code: string, m: MacroContext) => MacroResult | Promise<MacroResult>;
46
47
  /** A source format that becomes Svelte only through a preprocessor (markdown → Svelte): how its
47
48
  * islands and its modules' CSS reach the build. */
48
49
  export interface MarkupSource {
@@ -60,6 +61,34 @@ export interface MarkupSource {
60
61
  * style imports). The plugin keeps filling it ([path, source] pairs); the build reads it late. */
61
62
  modules?: Iterable<readonly [string, string]>;
62
63
  }
64
+ /** What a markdown extension's `finish` hands back. */
65
+ export interface MarkdownFinish {
66
+ /** The compiled module, rewritten. */
67
+ code: string;
68
+ /** Module-script lines to add (imports, exports). */
69
+ lines: string[];
70
+ /** The body now renders a component or an expression: it is never emitted as a static region. */
71
+ dynamic: boolean;
72
+ /** Files the output names (an image a post shows): watched like the document's own, and a kept
73
+ * compile of the document whose file is gone compiles again, so the extension's check runs. */
74
+ files?: readonly string[];
75
+ }
76
+ /** A markdown extension one plugin offers another's markdown pipeline (its Vite plugin's
77
+ * `api[MARKDOWN_EXTENSION_API]`): the one contract both sides compile against. `R` is the
78
+ * pipeline's rehype entry. */
79
+ export interface MarkdownExtension<R = unknown> {
80
+ /** Who offers it: one extension per name, the last config's. */
81
+ name: string;
82
+ /** What changes the compiled output besides the document and the pipeline's own settings: part
83
+ * of the document cache key. Read on every compile. */
84
+ cache_key: () => string;
85
+ /** Rehype entries, staged like the pipeline's own (after the app's own entries of each stage). */
86
+ rehype?: readonly R[];
87
+ /** After mdsvex, before the island transform: rewrite the compiled module. */
88
+ finish?: (code: string, filename: string) => MarkdownFinish;
89
+ }
90
+ /** The Vite plugin `api` key a markdown extension is offered under. */
91
+ export declare const MARKDOWN_EXTENSION_API = "ogygiaMarkdown";
63
92
  /** What the build hands back for a markup source: run the region transform on preprocessed Svelte. */
64
93
  export interface MarkupRegions {
65
94
  /** Rewrite the marked imports in already-preprocessed Svelte and register its regions. The code,
@@ -129,6 +158,8 @@ export interface BuildContext {
129
158
  readonly regions: RegionsSeam;
130
159
  /** The app's root directory. */
131
160
  readonly root: string;
161
+ /** Kit's routes folder (`kit.files.routes`), absolute. */
162
+ readonly routesDir: string;
132
163
  /** `vite dev` (true) or `vite build` (false). */
133
164
  readonly dev: boolean;
134
165
  /** A key this plugin reads inside Kit's own `config` page option (`export const config = { <key>:
@@ -298,6 +329,8 @@ export interface BuildSeams {
298
329
  exports: ExportsSeam;
299
330
  pinned_imports: (code: string) => (decl: PinnedDecl) => boolean;
300
331
  regions: RegionsSeam;
332
+ /** Kit's routes folder (`kit.files.routes`), absolute. */
333
+ routes_dir: () => string;
301
334
  }
302
335
  /**
303
336
  * Config-time shape check of the definitions found: each named once, its realms locations, its
@@ -317,4 +350,4 @@ export declare function server_hook_names(file: string): ServerHookName[];
317
350
  * transform for preprocessed markup (what `b.markup()` hands back).
318
351
  */
319
352
  export declare function resolve_plugins(plugins: readonly PluginDefinition[], root: string, dev: boolean, markup_transform?: MarkupRegions["transform"], seams?: BuildSeams): ResolvedPlugins;
320
- export type { MacroContext, PrescanHook };
353
+ export type { MacroContext, MacroResult, PrescanHook };
@@ -9,6 +9,8 @@ import { fileURLToPath } from "node:url";
9
9
  /** Where `definePlugin` puts the definition on the Vite plugin it returns. A registered symbol, so a
10
10
  * second copy of ogygia in one app still recognizes the first's plugins. */
11
11
  const PLUGIN = Symbol.for("ogygia.plugin");
12
+ /** The Vite plugin `api` key a markdown extension is offered under. */
13
+ const MARKDOWN_EXTENSION_API = "ogygiaMarkdown";
12
14
  const OGYGIA_VITE_PLUGIN = "ogygia";
13
15
  /** A plugin, as the Vite plugin the app lists beside `ogygia()`. */
14
16
  function definePlugin(definition) {
@@ -76,6 +78,9 @@ const NO_SEAMS = {
76
78
  whyStayed: () => {
77
79
  throw new Error("resolve_plugins: no region table without ogygia()");
78
80
  }
81
+ },
82
+ routes_dir: () => {
83
+ throw new Error("resolve_plugins: no routes folder without ogygia()");
79
84
  }
80
85
  };
81
86
  /**
@@ -245,6 +250,9 @@ function resolve_plugins(plugins, root, dev, markup_transform = () => null, seam
245
250
  });
246
251
  plugin.build?.({
247
252
  root,
253
+ get routesDir() {
254
+ return seams.routes_dir();
255
+ },
248
256
  dev,
249
257
  exports: seams.exports,
250
258
  pinnedImports: seams.pinned_imports,
@@ -342,4 +350,4 @@ function resolve_plugins(plugins, root, dev, markup_transform = () => null, seam
342
350
  out.macros.push(...last_macros);
343
351
  return out;
344
352
  }
345
- export { PLUGIN, check_plugins, client_hook_names, definePlugin, find_plugins, resolve_plugins, server_hook_names };
353
+ export { MARKDOWN_EXTENSION_API, PLUGIN, check_plugins, client_hook_names, definePlugin, find_plugins, resolve_plugins, server_hook_names };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ogygia/compiler",
3
- "version": "0.15.0",
3
+ "version": "0.16.0",
4
4
  "description": "The compiler of ogygia (SSR islands for SvelteKit): the region transform, the build's link step and the Vite plugin",
5
5
  "keywords": [
6
6
  "compiler",
@@ -44,21 +44,23 @@
44
44
  },
45
45
  "dependencies": {
46
46
  "@jridgewell/remapping": "^2.3.5",
47
- "@ogygia/machine": "^0.14.0",
47
+ "@ogygia/machine": "^0.16.0",
48
48
  "devalue": "^5.9.3",
49
49
  "estree-walker": "^3.0.3",
50
50
  "magic-string": "^1.4.5",
51
+ "micromark": "^4.0.2",
51
52
  "tinyglobby": "^0.2.17"
52
53
  },
53
54
  "devDependencies": {
54
55
  "@jridgewell/trace-mapping": "^0.3.31",
55
56
  "@ogygia/config": "0.0.0",
56
- "@ogygia/core": "0.15.0",
57
+ "@ogygia/core": "0.16.0",
57
58
  "@sveltejs/kit": "^2.70.2",
58
59
  "@sveltejs/vite-plugin-svelte": "^7.2.0",
59
60
  "@types/node": "^26.1.2",
60
61
  "@typescript/native": "npm:typescript@^7.0.2",
61
62
  "fast-check": "^4.10.2",
63
+ "mdsvex": "^0.12.8",
62
64
  "rolldown": "^1.2.2",
63
65
  "sass-embedded": "^1.104.1",
64
66
  "svelte": "5.57.3",
@@ -68,7 +70,7 @@
68
70
  "vitest": "^4.1.12"
69
71
  },
70
72
  "peerDependencies": {
71
- "@ogygia/core": "^0.15.0",
73
+ "@ogygia/core": "^0.16.0",
72
74
  "@sveltejs/kit": ">=2.70.2 <4",
73
75
  "rolldown": ">=1.0.0",
74
76
  "svelte": "^5.56.8",