@sigil-dev/grimoire 0.9.28 → 0.9.30

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 (105) hide show
  1. package/bin/sigil.ts +4 -0
  2. package/index.ts +16 -10
  3. package/package.json +14 -6
  4. package/server.ts +2 -2
  5. package/src/adapters/bun.ts +17 -17
  6. package/src/adapters/static.ts +41 -41
  7. package/src/adapters/types.ts +36 -36
  8. package/src/base.ts +4 -1
  9. package/src/client/csrf.ts +47 -47
  10. package/src/client/deferred.ts +1 -4
  11. package/src/client/enhance.ts +160 -160
  12. package/src/client/router.ts +927 -926
  13. package/src/config-file.ts +84 -0
  14. package/src/dev/compile-module.ts +199 -193
  15. package/src/dev/hmr-client.ts +229 -229
  16. package/src/dev/hmr-server.ts +274 -266
  17. package/src/dev/loader.ts +144 -144
  18. package/src/dev/runtime-bundle.ts +5 -3
  19. package/src/duration.ts +46 -0
  20. package/src/env/modules.ts +62 -62
  21. package/src/env/required.ts +42 -42
  22. package/src/env/typegen.ts +61 -61
  23. package/src/headers.ts +105 -105
  24. package/src/logger/transports.ts +117 -117
  25. package/src/plugin-order.ts +88 -0
  26. package/src/rendering/head.ts +49 -49
  27. package/src/rendering/hydrate.ts +162 -162
  28. package/src/rendering/images.ts +43 -43
  29. package/src/rendering/preload.ts +22 -8
  30. package/src/rendering/ssrPlugin.ts +107 -107
  31. package/src/rendering/timing.ts +40 -40
  32. package/src/routing/route-ids.ts +65 -0
  33. package/src/routing/route.ts +65 -0
  34. package/src/routing/router.ts +84 -32
  35. package/src/routing/scanner.ts +18 -5
  36. package/src/routing/transform-routes.ts +102 -102
  37. package/src/server/after-response.ts +206 -206
  38. package/src/server/asset-cache.ts +57 -57
  39. package/src/server/build.ts +304 -295
  40. package/src/server/cached.ts +114 -114
  41. package/src/server/client-address.ts +82 -82
  42. package/src/server/client-dir.ts +63 -63
  43. package/src/server/client-entry.ts +44 -44
  44. package/src/server/context.ts +18 -10
  45. package/src/server/cookie-utils.ts +80 -80
  46. package/src/server/coordinator.ts +476 -476
  47. package/src/server/hooks.ts +122 -122
  48. package/src/server/index.ts +8 -0
  49. package/src/server/plugins.ts +172 -172
  50. package/src/server/prerender.ts +473 -473
  51. package/src/server/reserved.ts +17 -17
  52. package/src/server/resolver.ts +149 -123
  53. package/src/server/rewrite.ts +28 -28
  54. package/src/server/warm.ts +9 -3
  55. package/src/server/with-headers.ts +27 -27
  56. package/src/server/worker.ts +2 -6
  57. package/src/server-only.ts +78 -0
  58. package/src/testing/dom.ts +73 -73
  59. package/src/testing/index.ts +169 -169
  60. package/src/testing/server.ts +1 -0
  61. package/src/typegen/index.ts +97 -2
  62. package/src/types.ts +140 -19
  63. package/test/after-response.test.ts +132 -132
  64. package/test/asset-cache-policy.test.ts +6 -2
  65. package/test/base.test.ts +20 -6
  66. package/test/cached.test.ts +126 -126
  67. package/test/client-address.test.ts +78 -78
  68. package/test/client-csrf.test.ts +61 -61
  69. package/test/client-dir.test.ts +101 -101
  70. package/test/client-router.test.ts +37 -5
  71. package/test/config-file.test.ts +84 -0
  72. package/test/coordinator.test.ts +9 -2
  73. package/test/deferred.test.ts +4 -2
  74. package/test/dev-loader.test.ts +30 -30
  75. package/test/env.test.ts +171 -171
  76. package/test/force-production.test.ts +7 -2
  77. package/test/images.test.ts +20 -8
  78. package/test/locals-header.test.ts +61 -61
  79. package/test/middleware.test.ts +243 -243
  80. package/test/parser-plugins.test.ts +98 -92
  81. package/test/plugin-handle.test.ts +62 -62
  82. package/test/plugin-order.test.ts +98 -0
  83. package/test/plugin-routes.test.ts +47 -42
  84. package/test/plugin-services-context.test.ts +7 -2
  85. package/test/preload.test.ts +4 -1
  86. package/test/prerender.test.ts +3 -1
  87. package/test/rendering.test.ts +3 -2
  88. package/test/required-env.test.ts +32 -32
  89. package/test/resolver-windows.test.ts +22 -23
  90. package/test/rewrite-html.test.ts +90 -90
  91. package/test/route-group-layouts.test.ts +38 -36
  92. package/test/route.test.ts +103 -0
  93. package/test/routing.test.ts +225 -197
  94. package/test/scanning.test.ts +53 -33
  95. package/test/server-context.test.ts +22 -0
  96. package/test/server-only.test.ts +110 -0
  97. package/test/server.test.ts +640 -640
  98. package/test/services.test.ts +3 -3
  99. package/test/streaming.test.ts +11 -6
  100. package/test/testing-helpers.test.ts +166 -166
  101. package/test/typegen.test.ts +209 -112
  102. package/test/warm.test.ts +96 -96
  103. package/test/worker-context.test.ts +59 -59
  104. package/test/workspace-files.test.ts +26 -10
  105. package/test/workspace-versions.test.ts +146 -131
@@ -1,49 +1,49 @@
1
- import { createContext, getContext, setContext } from "@sigil-dev/runtime";
2
-
3
- const HeadKey = createContext<string[]>();
4
- const NonceKey = createContext<string>();
5
-
6
- export function initHead(nonce?: string): void {
7
- setContext(HeadKey, []);
8
- if (nonce) setContext(NonceKey, nonce);
9
- }
10
-
11
- export function setHeadNonce(nonce: string): void {
12
- setContext(NonceKey, nonce);
13
- }
14
-
15
- export function getHeadNonce(): string {
16
- return getContext(NonceKey) ?? "";
17
- }
18
-
19
- export function collectHead(): string {
20
- return (getContext(HeadKey) ?? []).join("\n ");
21
- }
22
-
23
- /** Puts its children in the page's <head>. */
24
- export function Head({ children }: { children?: unknown }): string | Comment {
25
- if (typeof document === "undefined") {
26
- const buf = getContext(HeadKey);
27
- if (buf) {
28
- // Dynamic text inside <Head> children arrives wrapped in hydration
29
- // claim markers; those belong to the body runtime and must never
30
- // reach document.title or meta content.
31
- const nonce = getContext(NonceKey);
32
- const clean = String(children).replace(/<!--\/?g[^>]*-->/g, "");
33
- if (nonce) {
34
- buf.push(
35
- clean
36
- .replace(/<script /g, `<script nonce="${nonce}" `)
37
- .replace(/<style /g, `<style nonce="${nonce}" `),
38
- );
39
- } else {
40
- buf.push(clean);
41
- }
42
- }
43
- return "";
44
- }
45
- if (children instanceof Node) {
46
- document.head.appendChild(children);
47
- }
48
- return document.createComment("head");
49
- }
1
+ import { createContext, getContext, setContext } from "@sigil-dev/runtime";
2
+
3
+ const HeadKey = createContext<string[]>();
4
+ const NonceKey = createContext<string>();
5
+
6
+ export function initHead(nonce?: string): void {
7
+ setContext(HeadKey, []);
8
+ if (nonce) setContext(NonceKey, nonce);
9
+ }
10
+
11
+ export function setHeadNonce(nonce: string): void {
12
+ setContext(NonceKey, nonce);
13
+ }
14
+
15
+ export function getHeadNonce(): string {
16
+ return getContext(NonceKey) ?? "";
17
+ }
18
+
19
+ export function collectHead(): string {
20
+ return (getContext(HeadKey) ?? []).join("\n ");
21
+ }
22
+
23
+ /** Puts its children in the page's <head>. */
24
+ export function Head({ children }: { children?: unknown }): string | Comment {
25
+ if (typeof document === "undefined") {
26
+ const buf = getContext(HeadKey);
27
+ if (buf) {
28
+ // Dynamic text inside <Head> children arrives wrapped in hydration
29
+ // claim markers; those belong to the body runtime and must never
30
+ // reach document.title or meta content.
31
+ const nonce = getContext(NonceKey);
32
+ const clean = String(children).replace(/<!--\/?g[^>]*-->/g, "");
33
+ if (nonce) {
34
+ buf.push(
35
+ clean
36
+ .replace(/<script /g, `<script nonce="${nonce}" `)
37
+ .replace(/<style /g, `<style nonce="${nonce}" `),
38
+ );
39
+ } else {
40
+ buf.push(clean);
41
+ }
42
+ }
43
+ return "";
44
+ }
45
+ if (children instanceof Node) {
46
+ document.head.appendChild(children);
47
+ }
48
+ return document.createComment("head");
49
+ }
@@ -1,162 +1,162 @@
1
- import {
2
- claim,
3
- flushDeferredEffects,
4
- getHydrationNodes,
5
- insert,
6
- popHydrationNodes,
7
- pushHydrationNodes,
8
- __component,
9
- } from "@sigil-dev/runtime";
10
- //@ts-expect-error compiler generated
11
- import { layouts, matchers, routes } from "#grimoire-routes";
12
- import {
13
- afterNavigate,
14
- beforeNavigate,
15
- navigate,
16
- onNavigate,
17
- } from "../client/router";
18
- import { initRouter } from "../client/router.ts";
19
- import { withEffectScope } from "../client/scope.ts";
20
- import { Head } from "./head";
21
-
22
- // expose for HMR module shim
23
- (globalThis as any).__grimoire_Head__ = Head;
24
- (globalThis as any).__grimoire_navigate__ = navigate;
25
- (globalThis as any).__grimoire_beforeNavigate__ = beforeNavigate;
26
- (globalThis as any).__grimoire_onNavigate__ = onNavigate;
27
- (globalThis as any).__grimoire_afterNavigate__ = afterNavigate;
28
-
29
- async function resolveInitialPage(pattern: string): Promise<any> {
30
- const entry = routes[pattern];
31
- if (!entry) return null;
32
- if (typeof entry === "function") return entry;
33
- return (await entry.__lazy()).default;
34
- }
35
-
36
- async function hydrate(): Promise<(() => void) | undefined> {
37
- const stateEl = document.getElementById("__grimoire_state__");
38
- if (!stateEl) return undefined;
39
-
40
- const state = JSON.parse(stateEl.textContent!);
41
- const Page = await resolveInitialPage(state.pattern);
42
- if (!Page) return undefined;
43
- const slot = document.getElementById("grimoire-root");
44
- if (!slot) return undefined;
45
-
46
- const matchedLayouts = layouts
47
- .filter(
48
- (l: any) =>
49
- l.path === "/" ||
50
- state.pattern === l.path ||
51
- state.pattern.startsWith(`${l.path}/`),
52
- )
53
- .sort((a: any, b: any) => a.path.length - b.path.length);
54
-
55
- // The page's SSR container is findable by id, so the page can hydrate
56
- // in place inside it while a single root layout claims from the
57
- // top-level pool. With nested layouts (>1) the inner layout's DOM
58
- // position can't be located in the flat pool — fall back to clearing
59
- // the SSR content and re-rendering in DOM mode (empty pool).
60
- const pageHost = document.getElementById("grimoire-page");
61
- const hasLayouts = matchedLayouts.length > 0;
62
- const inPlace = !hasLayouts || (matchedLayouts.length === 1 && !!pageHost);
63
- if (!inPlace) {
64
- slot.replaceChildren();
65
- }
66
-
67
- const ssrClones = inPlace
68
- ? Array.from(slot.childNodes).map((n) => n.cloneNode(true))
69
- : [];
70
- pushHydrationNodes(
71
- inPlace ? (Array.from(slot.childNodes) as ChildNode[]) : [],
72
- );
73
- let initialDispose: (() => void) | undefined;
74
- try {
75
- initialDispose = withEffectScope(() => {
76
- try {
77
- let renderFn = () => {
78
- const pageDiv =
79
- hasLayouts && inPlace && pageHost
80
- ? pageHost
81
- : claim(getHydrationNodes(), "div");
82
- pageDiv.id = "grimoire-page";
83
-
84
- if (pageDiv.childNodes.length > 0) {
85
- pushHydrationNodes(Array.from(pageDiv.childNodes) as ChildNode[]);
86
- let pageNode: unknown;
87
- try {
88
- pageNode = __component(Page, {
89
- data: state.data,
90
- params: state.params,
91
- form: state.form,
92
- });
93
- } finally {
94
- // always rebalance the global hydration stack — a throwing
95
- // page component must not corrupt claims for the whole session
96
- popHydrationNodes();
97
- }
98
- insert(pageDiv, pageNode);
99
- } else {
100
- const pageNode = __component(Page, {
101
- data: state.data,
102
- params: state.params,
103
- form: state.form,
104
- });
105
- insert(pageDiv, pageNode);
106
- }
107
-
108
- return pageDiv;
109
- };
110
-
111
- for (let i = matchedLayouts.length - 1; i >= 0; i--) {
112
- const LayoutComponent = matchedLayouts[i].component;
113
- const innerRender = renderFn;
114
- const layoutData = state.layoutData?.[i];
115
- renderFn = () => {
116
- // Pre-render inner content so children is a Node (insert() doesn't call functions)
117
- const childNode = innerRender();
118
- return __component(LayoutComponent, {
119
- data: layoutData,
120
- params: state.params,
121
- path: state.pattern,
122
- children: childNode,
123
- });
124
- };
125
- }
126
-
127
- // Defer effects during hydration render — they'll run after DOM insertion,
128
- // so document.querySelector() etc. can find elements that are in the document.
129
- (globalThis as any).__sigilDeferEffects = true;
130
- try {
131
- const rootNode = renderFn();
132
- insert(slot, rootNode);
133
- } finally {
134
- // finally: a throwing render must not leave the flag set forever
135
- (globalThis as any).__sigilDeferEffects = false;
136
- flushDeferredEffects();
137
- }
138
- } finally {
139
- popHydrationNodes();
140
- }
141
- });
142
- } catch (e) {
143
- console.warn("[grimoire] hydration error:", e);
144
- }
145
-
146
- if (!slot.hasChildNodes() && ssrClones.length > 0) {
147
- slot.replaceChildren(...ssrClones);
148
- }
149
- return initialDispose;
150
- }
151
-
152
- hydrate().then((initialDispose) => {
153
- const stateEl = document.getElementById("__grimoire_state__");
154
- const state = stateEl ? JSON.parse(stateEl.textContent!) : null;
155
- initRouter(routes, layouts, initialDispose, {
156
- matchers,
157
- deps:
158
- state && Array.isArray(state.deps)
159
- ? { [state.pattern]: state.deps }
160
- : undefined,
161
- });
162
- });
1
+ import {
2
+ __component,
3
+ claim,
4
+ flushDeferredEffects,
5
+ getHydrationNodes,
6
+ insert,
7
+ popHydrationNodes,
8
+ pushHydrationNodes,
9
+ } from "@sigil-dev/runtime";
10
+ //@ts-expect-error compiler generated
11
+ import { layouts, matchers, routes } from "#grimoire-routes";
12
+ import {
13
+ afterNavigate,
14
+ beforeNavigate,
15
+ navigate,
16
+ onNavigate,
17
+ } from "../client/router";
18
+ import { initRouter } from "../client/router.ts";
19
+ import { withEffectScope } from "../client/scope.ts";
20
+ import { Head } from "./head";
21
+
22
+ // expose for HMR module shim
23
+ (globalThis as any).__grimoire_Head__ = Head;
24
+ (globalThis as any).__grimoire_navigate__ = navigate;
25
+ (globalThis as any).__grimoire_beforeNavigate__ = beforeNavigate;
26
+ (globalThis as any).__grimoire_onNavigate__ = onNavigate;
27
+ (globalThis as any).__grimoire_afterNavigate__ = afterNavigate;
28
+
29
+ async function resolveInitialPage(pattern: string): Promise<any> {
30
+ const entry = routes[pattern];
31
+ if (!entry) return null;
32
+ if (typeof entry === "function") return entry;
33
+ return (await entry.__lazy()).default;
34
+ }
35
+
36
+ async function hydrate(): Promise<(() => void) | undefined> {
37
+ const stateEl = document.getElementById("__grimoire_state__");
38
+ if (!stateEl) return undefined;
39
+
40
+ const state = JSON.parse(stateEl.textContent!);
41
+ const Page = await resolveInitialPage(state.pattern);
42
+ if (!Page) return undefined;
43
+ const slot = document.getElementById("grimoire-root");
44
+ if (!slot) return undefined;
45
+
46
+ const matchedLayouts = layouts
47
+ .filter(
48
+ (l: any) =>
49
+ l.path === "/" ||
50
+ state.pattern === l.path ||
51
+ state.pattern.startsWith(`${l.path}/`),
52
+ )
53
+ .sort((a: any, b: any) => a.path.length - b.path.length);
54
+
55
+ // The page's SSR container is findable by id, so the page can hydrate
56
+ // in place inside it while a single root layout claims from the
57
+ // top-level pool. With nested layouts (>1) the inner layout's DOM
58
+ // position can't be located in the flat pool — fall back to clearing
59
+ // the SSR content and re-rendering in DOM mode (empty pool).
60
+ const pageHost = document.getElementById("grimoire-page");
61
+ const hasLayouts = matchedLayouts.length > 0;
62
+ const inPlace = !hasLayouts || (matchedLayouts.length === 1 && !!pageHost);
63
+ if (!inPlace) {
64
+ slot.replaceChildren();
65
+ }
66
+
67
+ const ssrClones = inPlace
68
+ ? Array.from(slot.childNodes).map((n) => n.cloneNode(true))
69
+ : [];
70
+ pushHydrationNodes(
71
+ inPlace ? (Array.from(slot.childNodes) as ChildNode[]) : [],
72
+ );
73
+ let initialDispose: (() => void) | undefined;
74
+ try {
75
+ initialDispose = withEffectScope(() => {
76
+ try {
77
+ let renderFn = () => {
78
+ const pageDiv =
79
+ hasLayouts && inPlace && pageHost
80
+ ? pageHost
81
+ : claim(getHydrationNodes(), "div");
82
+ pageDiv.id = "grimoire-page";
83
+
84
+ if (pageDiv.childNodes.length > 0) {
85
+ pushHydrationNodes(Array.from(pageDiv.childNodes) as ChildNode[]);
86
+ let pageNode: unknown;
87
+ try {
88
+ pageNode = __component(Page, {
89
+ data: state.data,
90
+ params: state.params,
91
+ form: state.form,
92
+ });
93
+ } finally {
94
+ // always rebalance the global hydration stack — a throwing
95
+ // page component must not corrupt claims for the whole session
96
+ popHydrationNodes();
97
+ }
98
+ insert(pageDiv, pageNode);
99
+ } else {
100
+ const pageNode = __component(Page, {
101
+ data: state.data,
102
+ params: state.params,
103
+ form: state.form,
104
+ });
105
+ insert(pageDiv, pageNode);
106
+ }
107
+
108
+ return pageDiv;
109
+ };
110
+
111
+ for (let i = matchedLayouts.length - 1; i >= 0; i--) {
112
+ const LayoutComponent = matchedLayouts[i].component;
113
+ const innerRender = renderFn;
114
+ const layoutData = state.layoutData?.[i];
115
+ renderFn = () => {
116
+ // Pre-render inner content so children is a Node (insert() doesn't call functions)
117
+ const childNode = innerRender();
118
+ return __component(LayoutComponent, {
119
+ data: layoutData,
120
+ params: state.params,
121
+ path: state.pattern,
122
+ children: childNode,
123
+ });
124
+ };
125
+ }
126
+
127
+ // Defer effects during hydration render — they'll run after DOM insertion,
128
+ // so document.querySelector() etc. can find elements that are in the document.
129
+ (globalThis as any).__sigilDeferEffects = true;
130
+ try {
131
+ const rootNode = renderFn();
132
+ insert(slot, rootNode);
133
+ } finally {
134
+ // finally: a throwing render must not leave the flag set forever
135
+ (globalThis as any).__sigilDeferEffects = false;
136
+ flushDeferredEffects();
137
+ }
138
+ } finally {
139
+ popHydrationNodes();
140
+ }
141
+ });
142
+ } catch (e) {
143
+ console.warn("[grimoire] hydration error:", e);
144
+ }
145
+
146
+ if (!slot.hasChildNodes() && ssrClones.length > 0) {
147
+ slot.replaceChildren(...ssrClones);
148
+ }
149
+ return initialDispose;
150
+ }
151
+
152
+ hydrate().then((initialDispose) => {
153
+ const stateEl = document.getElementById("__grimoire_state__");
154
+ const state = stateEl ? JSON.parse(stateEl.textContent!) : null;
155
+ initRouter(routes, layouts, initialDispose, {
156
+ matchers,
157
+ deps:
158
+ state && Array.isArray(state.deps)
159
+ ? { [state.pattern]: state.deps }
160
+ : undefined,
161
+ });
162
+ });
@@ -1,43 +1,43 @@
1
- /**
2
- * Default image loading for server-rendered pages.
3
- *
4
- * The first few images are left alone: they are what the visitor sees first
5
- * and lazy-loading them would delay the largest paint. Every later `<img>`
6
- * gets `loading="lazy"` and `decoding="async"` so a long grid of thumbnails
7
- * does not compete with the stylesheet and scripts for the first seconds of
8
- * bandwidth. An author's own `loading` / `decoding` always wins.
9
- *
10
- * `data-sigil-priority` marks the image that should paint first (the hero,
11
- * the likely largest paint): it stays eager and is fetched at high priority,
12
- * and does not count toward the eager budget above.
13
- */
14
- export const EAGER_IMAGE_COUNT = 4;
15
-
16
- const IMG_TAG = /<img\b[^>]*>/gi;
17
- // inline scripts and styles may contain "<img" inside strings
18
- const RAW_BLOCK = /<(script|style|template)\b[\s\S]*?<\/\1>/gi;
19
-
20
- export function optimizeImages(html: string): string {
21
- if (!html.includes("<img")) return html;
22
- let seen = 0;
23
- const tag = (t: string) => {
24
- if (/\sdata-sigil-priority\b/i.test(t)) {
25
- return /\sfetchpriority\s*=/i.test(t)
26
- ? t
27
- : t.replace(/(\s*\/?>)$/, ' fetchpriority="high"$1');
28
- }
29
- if (seen++ < EAGER_IMAGE_COUNT) return t;
30
- let extra = "";
31
- if (!/\sloading\s*=/i.test(t)) extra += ' loading="lazy"';
32
- if (!/\sdecoding\s*=/i.test(t)) extra += ' decoding="async"';
33
- // attributes go before the tag's own trailing space and `/>`
34
- return extra ? t.replace(/(\s*\/?>)$/, `${extra}$1`) : t;
35
- };
36
- let out = "";
37
- let last = 0;
38
- for (const m of html.matchAll(RAW_BLOCK)) {
39
- out += html.slice(last, m.index).replace(IMG_TAG, tag) + m[0];
40
- last = m.index + m[0].length;
41
- }
42
- return out + html.slice(last).replace(IMG_TAG, tag);
43
- }
1
+ /**
2
+ * Default image loading for server-rendered pages.
3
+ *
4
+ * The first few images are left alone: they are what the visitor sees first
5
+ * and lazy-loading them would delay the largest paint. Every later `<img>`
6
+ * gets `loading="lazy"` and `decoding="async"` so a long grid of thumbnails
7
+ * does not compete with the stylesheet and scripts for the first seconds of
8
+ * bandwidth. An author's own `loading` / `decoding` always wins.
9
+ *
10
+ * `data-sigil-priority` marks the image that should paint first (the hero,
11
+ * the likely largest paint): it stays eager and is fetched at high priority,
12
+ * and does not count toward the eager budget above.
13
+ */
14
+ export const EAGER_IMAGE_COUNT = 4;
15
+
16
+ const IMG_TAG = /<img\b[^>]*>/gi;
17
+ // inline scripts and styles may contain "<img" inside strings
18
+ const RAW_BLOCK = /<(script|style|template)\b[\s\S]*?<\/\1>/gi;
19
+
20
+ export function optimizeImages(html: string): string {
21
+ if (!html.includes("<img")) return html;
22
+ let seen = 0;
23
+ const tag = (t: string) => {
24
+ if (/\sdata-sigil-priority\b/i.test(t)) {
25
+ return /\sfetchpriority\s*=/i.test(t)
26
+ ? t
27
+ : t.replace(/(\s*\/?>)$/, ' fetchpriority="high"$1');
28
+ }
29
+ if (seen++ < EAGER_IMAGE_COUNT) return t;
30
+ let extra = "";
31
+ if (!/\sloading\s*=/i.test(t)) extra += ' loading="lazy"';
32
+ if (!/\sdecoding\s*=/i.test(t)) extra += ' decoding="async"';
33
+ // attributes go before the tag's own trailing space and `/>`
34
+ return extra ? t.replace(/(\s*\/?>)$/, `${extra}$1`) : t;
35
+ };
36
+ let out = "";
37
+ let last = 0;
38
+ for (const m of html.matchAll(RAW_BLOCK)) {
39
+ out += html.slice(last, m.index).replace(IMG_TAG, tag) + m[0];
40
+ last = m.index + m[0].length;
41
+ }
42
+ return out + html.slice(last).replace(IMG_TAG, tag);
43
+ }
@@ -27,9 +27,10 @@ const DIR = "/__grimoire__/";
27
27
  let graph: ChunkGraph | null | undefined;
28
28
 
29
29
  export function parseChunkGraph(source: string): ChunkGraph | null {
30
- const call = /^__chunks\(import\.meta\.url,(\[.*?\]),(\[\[.*?\]\]),(\d+)\)/m.exec(
31
- source,
32
- );
30
+ const call =
31
+ /^__chunks\(import\.meta\.url,(\[.*?\]),(\[\[.*?\]\]),(\d+)\)/m.exec(
32
+ source,
33
+ );
33
34
  if (!call) return null;
34
35
  let ids: string[];
35
36
  let raw: Array<Array<string | number>>;
@@ -43,7 +44,10 @@ export function parseChunkGraph(source: string): ChunkGraph | null {
43
44
  ids.forEach((id, i) => {
44
45
  const [file, ...deps] = raw[i] ?? [];
45
46
  if (typeof file !== "string") return;
46
- nodes.set(id, { file, deps: deps.map((d) => ids[Number(d)]).filter(Boolean) });
47
+ nodes.set(id, {
48
+ file,
49
+ deps: deps.map((d) => ids[Number(d)]).filter(Boolean),
50
+ });
47
51
  });
48
52
  const routes = new Map<string, string>();
49
53
  for (const m of source.matchAll(
@@ -62,7 +66,9 @@ function load(): ChunkGraph | null {
62
66
  if (graph !== undefined && graphOf === entry) return graph;
63
67
  graphOf = entry;
64
68
  const file = join(clientDir(), entry);
65
- graph = existsSync(file) ? parseChunkGraph(readFileSync(file, "utf-8")) : null;
69
+ graph = existsSync(file)
70
+ ? parseChunkGraph(readFileSync(file, "utf-8"))
71
+ : null;
66
72
  return graph;
67
73
  }
68
74
 
@@ -80,19 +86,27 @@ export function chunksFor(g: ChunkGraph, pattern: string): string[] {
80
86
  const node = g.nodes.get(id);
81
87
  if (!node) continue;
82
88
  // hydrate.js itself is already a <script> in the head
83
- if (!/(^|\/)hydrate\.js$/.test(node.file)) files.push(node.file.replace(/^\.\//, ""));
89
+ if (!/(^|\/)hydrate\.js$/.test(node.file))
90
+ files.push(node.file.replace(/^\.\//, ""));
84
91
  stack.push(...node.deps);
85
92
  }
86
93
  return files;
87
94
  }
88
95
 
89
96
  /** The preload tags for a route, or "" in dev / when there is no built graph. */
90
- export function preloadLinks(pattern: string, nonceAttr: string, dev?: boolean): string {
97
+ export function preloadLinks(
98
+ pattern: string,
99
+ nonceAttr: string,
100
+ dev?: boolean,
101
+ ): string {
91
102
  if (dev) return "";
92
103
  const g = load();
93
104
  if (!g) return "";
94
105
  return chunksFor(g, pattern)
95
- .map((f) => `\n <link rel="modulepreload" href="${withBase(DIR)}${f}" crossorigin${nonceAttr}>`)
106
+ .map(
107
+ (f) =>
108
+ `\n <link rel="modulepreload" href="${withBase(DIR)}${f}" crossorigin${nonceAttr}>`,
109
+ )
96
110
  .join("");
97
111
  }
98
112