@sigil-dev/grimoire 0.9.20 → 0.9.22
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/README.md +83 -83
- package/index.ts +50 -48
- package/package.json +16 -5
- package/public/__grimoire__/grimoire-client.js +12 -0
- package/public/__grimoire__/runtime.js +1241 -0
- package/server.ts +22 -20
- package/src/adapters/bun.ts +17 -0
- package/src/adapters/static.ts +41 -0
- package/src/adapters/types.ts +36 -0
- package/src/base.ts +91 -0
- package/src/client/csrf.ts +47 -47
- package/src/client/deferred.ts +179 -179
- package/src/client/enhance.ts +160 -160
- package/src/client/router.ts +870 -833
- package/src/dev/compile-module.ts +211 -211
- package/src/dev/loader.ts +141 -141
- package/src/dev/resolve.ts +70 -70
- package/src/dev/runtime-bundle.ts +51 -51
- package/src/env/modules.ts +62 -62
- package/src/env/required.ts +42 -0
- package/src/env/typegen.ts +61 -61
- package/src/headers.ts +105 -114
- package/src/logger/transports.ts +117 -117
- package/src/rendering/head.ts +49 -49
- package/src/rendering/hydrate.ts +161 -161
- package/src/rendering/images.ts +43 -43
- package/src/rendering/index.ts +755 -745
- package/src/rendering/preload.ts +101 -95
- package/src/rendering/ssrPlugin.ts +108 -108
- package/src/rendering/timing.ts +40 -40
- package/src/routing/router.ts +186 -186
- package/src/routing/scanner.ts +225 -196
- package/src/routing/transform-routes.ts +102 -102
- package/src/server/after-response.ts +206 -194
- package/src/server/asset-cache.ts +57 -55
- package/src/server/build.ts +262 -249
- package/src/server/cached.ts +114 -114
- package/src/server/client-address.ts +82 -82
- package/src/server/client-dir.ts +57 -57
- package/src/server/client-entry.ts +44 -0
- package/src/server/cookie-utils.ts +80 -80
- package/src/server/coordinator.ts +476 -471
- package/src/server/hooks.ts +122 -122
- package/src/server/index.ts +1138 -1022
- package/src/server/plugins.ts +172 -172
- package/src/server/prerender.ts +444 -0
- package/src/server/reserved.ts +17 -0
- package/src/server/resolver.ts +98 -98
- package/src/server/rewrite.ts +28 -0
- package/src/server/warm.ts +91 -91
- package/src/server/with-headers.ts +27 -0
- package/src/server/worker.ts +74 -72
- package/src/testing/dom.ts +73 -0
- package/src/testing/index.ts +169 -0
- package/src/testing/server.ts +162 -0
- package/src/typegen/index.ts +450 -450
- package/src/types.ts +501 -432
- package/test/after-response.test.ts +132 -113
- package/test/asset-cache-policy.test.ts +96 -96
- package/test/base.test.ts +134 -0
- package/test/cached.test.ts +126 -126
- package/test/client-address.test.ts +78 -78
- package/test/client-csrf.test.ts +61 -61
- package/test/client-dir.test.ts +101 -69
- package/test/client-router.test.ts +789 -734
- package/test/coordinator.test.ts +96 -94
- package/test/deferred.test.ts +256 -256
- package/test/dev-loader.test.ts +30 -30
- package/test/env.test.ts +168 -168
- package/test/force-production.test.ts +44 -0
- package/test/images.test.ts +49 -49
- package/test/locals-header.test.ts +61 -0
- package/test/middleware.test.ts +243 -243
- package/test/parser-plugins.test.ts +92 -92
- package/test/plugin-handle.test.ts +62 -62
- package/test/plugin-services-context.test.ts +97 -97
- package/test/preload.test.ts +48 -48
- package/test/prerender.test.ts +353 -0
- package/test/rendering.test.ts +798 -798
- package/test/required-env.test.ts +32 -0
- package/test/rewrite-html.test.ts +90 -0
- package/test/scanning.test.ts +349 -314
- package/test/server.test.ts +640 -619
- package/test/services.test.ts +90 -90
- package/test/streaming.test.ts +378 -378
- package/test/testing-helpers.test.ts +166 -0
- package/test/typegen.test.ts +805 -799
- package/test/warm.test.ts +96 -96
- package/test/worker-context.test.ts +59 -59
- package/test/workspace-files.test.ts +149 -146
- package/test/workspace-versions.test.ts +131 -131
- package/.grimoire/_routes.ts +0 -4
- package/public/__grimoire__/client.js +0 -55
- package/public/__grimoire__/hydrate.js +0 -63
package/test/streaming.test.ts
CHANGED
|
@@ -1,378 +1,378 @@
|
|
|
1
|
-
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
|
|
2
|
-
import { mkdir, rm, writeFile } from "node:fs/promises";
|
|
3
|
-
import { tmpdir } from "node:os";
|
|
4
|
-
import { join } from "node:path";
|
|
5
|
-
import { renderRoute } from "../src/rendering";
|
|
6
|
-
import { matchRoute } from "../src/routing/router";
|
|
7
|
-
import { scanRoutes } from "../src/routing/scanner";
|
|
8
|
-
|
|
9
|
-
function makeMatched(path: string, filePath: string, params = {}) {
|
|
10
|
-
return {
|
|
11
|
-
route: { path, params: {}, filePath },
|
|
12
|
-
params,
|
|
13
|
-
layouts: [],
|
|
14
|
-
layoutServers: [],
|
|
15
|
-
} as any;
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
describe("Streaming SSR", () => {
|
|
19
|
-
test("returns a ReadableStream response", async () => {
|
|
20
|
-
const matched = makeMatched(
|
|
21
|
-
"/",
|
|
22
|
-
"data:text/javascript,export default (p) => '<div>hello</div>'",
|
|
23
|
-
);
|
|
24
|
-
const res = await renderRoute(matched, new Request("http://localhost/"));
|
|
25
|
-
expect(res.body).toBeInstanceOf(ReadableStream);
|
|
26
|
-
});
|
|
27
|
-
|
|
28
|
-
test("stream contains full HTML document", async () => {
|
|
29
|
-
const matched = makeMatched(
|
|
30
|
-
"/test",
|
|
31
|
-
"data:text/javascript,export default (p) => '<p>streaming works</p>'",
|
|
32
|
-
);
|
|
33
|
-
|
|
34
|
-
const res = await renderRoute(
|
|
35
|
-
matched,
|
|
36
|
-
new Request("http://localhost/test"),
|
|
37
|
-
);
|
|
38
|
-
const html = await res.text();
|
|
39
|
-
|
|
40
|
-
expect(html).toContain("<!DOCTYPE html>");
|
|
41
|
-
expect(html).toContain('<meta charset="UTF-8" />');
|
|
42
|
-
expect(html).toContain("streaming works");
|
|
43
|
-
expect(html).toContain("</html>");
|
|
44
|
-
expect(html).toContain("__grimoire_state__");
|
|
45
|
-
});
|
|
46
|
-
|
|
47
|
-
test("stream includes state JSON with route pattern", async () => {
|
|
48
|
-
const matched = makeMatched(
|
|
49
|
-
"/spells/:id",
|
|
50
|
-
"data:text/javascript,export default (p) => '<div>spell</div>'",
|
|
51
|
-
{ id: "fireball" },
|
|
52
|
-
);
|
|
53
|
-
|
|
54
|
-
const res = await renderRoute(
|
|
55
|
-
matched,
|
|
56
|
-
new Request("http://localhost/spells/fireball"),
|
|
57
|
-
);
|
|
58
|
-
const html = await res.text();
|
|
59
|
-
|
|
60
|
-
expect(html).toContain('"pattern":"/spells/:id"');
|
|
61
|
-
expect(html).toContain('"id":"fireball"');
|
|
62
|
-
});
|
|
63
|
-
|
|
64
|
-
test("late head tags survive quotes and scripts in a streaming page", async () => {
|
|
65
|
-
const dir = join(tmpdir(), `grimoire-late-head-${Date.now()}`);
|
|
66
|
-
await mkdir(dir, { recursive: true });
|
|
67
|
-
const file = join(dir, "page.js");
|
|
68
|
-
const head = join(import.meta.dir, "../src/rendering/head.ts");
|
|
69
|
-
await writeFile(
|
|
70
|
-
file,
|
|
71
|
-
[
|
|
72
|
-
`import { Head } from ${JSON.stringify(head)};`,
|
|
73
|
-
`export const loading = () => "<p>wait</p>";`,
|
|
74
|
-
`export default () => { Head({ children: "<title>You've read it</title><script>var a = 1</script>" }); return "<p>done</p>"; };`,
|
|
75
|
-
].join("\n"),
|
|
76
|
-
);
|
|
77
|
-
// <Head> collects for the server only where there is no DOM
|
|
78
|
-
const g = globalThis as { document?: unknown };
|
|
79
|
-
const dom = g.document;
|
|
80
|
-
delete g.document;
|
|
81
|
-
try {
|
|
82
|
-
const res = await renderRoute(
|
|
83
|
-
makeMatched("/late", file),
|
|
84
|
-
new Request("http://localhost/late"),
|
|
85
|
-
);
|
|
86
|
-
const html = await res.text();
|
|
87
|
-
g.document = dom;
|
|
88
|
-
const script =
|
|
89
|
-
/<script>(\(function\(\)\{var p=new DOMParser[^]*?)<\/script>/.exec(
|
|
90
|
-
html,
|
|
91
|
-
)?.[1];
|
|
92
|
-
expect(script).toBeDefined();
|
|
93
|
-
// valid JavaScript, and nothing in it can close the <script> early
|
|
94
|
-
expect(() => new Function(script!)).not.toThrow();
|
|
95
|
-
expect(script).not.toContain("</");
|
|
96
|
-
expect(script).toContain("You've read it");
|
|
97
|
-
} finally {
|
|
98
|
-
g.document = dom;
|
|
99
|
-
await rm(dir, { recursive: true, force: true });
|
|
100
|
-
}
|
|
101
|
-
});
|
|
102
|
-
|
|
103
|
-
test("head script tag comes before head content", async () => {
|
|
104
|
-
const matched = makeMatched(
|
|
105
|
-
"/head-test",
|
|
106
|
-
"data:text/javascript,export default (p) => '<div>head</div>'",
|
|
107
|
-
);
|
|
108
|
-
|
|
109
|
-
const res = await renderRoute(
|
|
110
|
-
matched,
|
|
111
|
-
new Request("http://localhost/head-test"),
|
|
112
|
-
);
|
|
113
|
-
const html = await res.text();
|
|
114
|
-
|
|
115
|
-
const hydrateScript = html.indexOf("hydrate.js");
|
|
116
|
-
const headClosing = html.indexOf("</head>");
|
|
117
|
-
// hydrate.js should be in <head>
|
|
118
|
-
expect(hydrateScript).toBeGreaterThan(-1);
|
|
119
|
-
expect(hydrateScript).toBeLessThan(headClosing);
|
|
120
|
-
});
|
|
121
|
-
|
|
122
|
-
test("stream chunks arrive incrementally", async () => {
|
|
123
|
-
const matched = makeMatched(
|
|
124
|
-
"/chunked",
|
|
125
|
-
"data:text/javascript,export default (p) => '<div>chunked</div>'",
|
|
126
|
-
);
|
|
127
|
-
|
|
128
|
-
const res = await renderRoute(
|
|
129
|
-
matched,
|
|
130
|
-
new Request("http://localhost/chunked"),
|
|
131
|
-
);
|
|
132
|
-
const reader = res.body!.getReader();
|
|
133
|
-
const chunks: string[] = [];
|
|
134
|
-
|
|
135
|
-
while (true) {
|
|
136
|
-
const { done, value } = await reader.read();
|
|
137
|
-
if (done) break;
|
|
138
|
-
// Bun ReadableStream returns Uint8Array
|
|
139
|
-
chunks.push(
|
|
140
|
-
typeof value === "string"
|
|
141
|
-
? value
|
|
142
|
-
: new TextDecoder().decode(value.buffer),
|
|
143
|
-
);
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
// Should have multiple chunks (at least DOCTYPE + body)
|
|
147
|
-
expect(chunks.length).toBeGreaterThan(1);
|
|
148
|
-
// First chunk should start with DOCTYPE
|
|
149
|
-
expect(chunks[0]).toContain("<!DOCTYPE html>");
|
|
150
|
-
// Last chunk should close the document
|
|
151
|
-
expect(chunks[chunks.length - 1]).toContain("</html>");
|
|
152
|
-
});
|
|
153
|
-
|
|
154
|
-
test("navigation request returns JSON not stream", async () => {
|
|
155
|
-
const matched = makeMatched(
|
|
156
|
-
"/nav",
|
|
157
|
-
"data:text/javascript,export default (p) => '<div>nav</div>'",
|
|
158
|
-
);
|
|
159
|
-
|
|
160
|
-
const req = new Request("http://localhost/nav", {
|
|
161
|
-
headers: { "x-grimoire-navigate": "1" },
|
|
162
|
-
});
|
|
163
|
-
const res = await renderRoute(matched, req);
|
|
164
|
-
const json = await res.json();
|
|
165
|
-
|
|
166
|
-
expect(json.pattern).toBe("/nav");
|
|
167
|
-
expect(json.data).toBeDefined();
|
|
168
|
-
});
|
|
169
|
-
|
|
170
|
-
// The JSON payload and the HTML document share one URL and are picked by a
|
|
171
|
-
// request header. Without Vary any cache may serve the JSON to a plain
|
|
172
|
-
// document request, which rendered the raw state object as the page.
|
|
173
|
-
test("navigation JSON declares Vary on the navigate header", async () => {
|
|
174
|
-
const matched = makeMatched(
|
|
175
|
-
"/nav-vary",
|
|
176
|
-
"data:text/javascript,export default (p) => '<div>nav</div>'",
|
|
177
|
-
);
|
|
178
|
-
|
|
179
|
-
const res = await renderRoute(
|
|
180
|
-
matched,
|
|
181
|
-
new Request("http://localhost/nav-vary", {
|
|
182
|
-
headers: { "x-grimoire-navigate": "1" },
|
|
183
|
-
}),
|
|
184
|
-
);
|
|
185
|
-
|
|
186
|
-
expect(res.headers.get("content-type")).toContain("application/json");
|
|
187
|
-
expect(res.headers.get("vary")?.toLowerCase()).toContain(
|
|
188
|
-
"x-grimoire-navigate",
|
|
189
|
-
);
|
|
190
|
-
});
|
|
191
|
-
|
|
192
|
-
test("HTML document declares Vary on the navigate header", async () => {
|
|
193
|
-
const matched = makeMatched(
|
|
194
|
-
"/doc-vary",
|
|
195
|
-
"data:text/javascript,export default (p) => '<div>doc</div>'",
|
|
196
|
-
);
|
|
197
|
-
|
|
198
|
-
const res = await renderRoute(
|
|
199
|
-
matched,
|
|
200
|
-
new Request("http://localhost/doc-vary"),
|
|
201
|
-
);
|
|
202
|
-
|
|
203
|
-
expect(res.headers.get("content-type")).toContain("text/html");
|
|
204
|
-
expect(res.headers.get("vary")?.toLowerCase()).toContain(
|
|
205
|
-
"x-grimoire-navigate",
|
|
206
|
-
);
|
|
207
|
-
});
|
|
208
|
-
|
|
209
|
-
test("state JSON escapes </script> in data (XSS)", async () => {
|
|
210
|
-
const evil = "</script><script>alert(1)</script>";
|
|
211
|
-
const src = [
|
|
212
|
-
"export const load = async () => ({ evil })",
|
|
213
|
-
"const evil = " + JSON.stringify(evil),
|
|
214
|
-
'export default () => "<div>ok</div>"',
|
|
215
|
-
].join(";\n");
|
|
216
|
-
const matched = makeMatched(
|
|
217
|
-
"/xss",
|
|
218
|
-
`data:text/javascript,${encodeURIComponent(src)}`,
|
|
219
|
-
);
|
|
220
|
-
|
|
221
|
-
const res = await renderRoute(matched, new Request("http://localhost/xss"));
|
|
222
|
-
const html = await res.text();
|
|
223
|
-
|
|
224
|
-
const tagStart = html.indexOf('<script id="__grimoire_state__"');
|
|
225
|
-
expect(tagStart).toBeGreaterThan(-1);
|
|
226
|
-
const payloadStart = html.indexOf(">", tagStart) + 1;
|
|
227
|
-
const payloadEnd = html.indexOf("</script>", payloadStart);
|
|
228
|
-
const payload = html.slice(payloadStart, payloadEnd);
|
|
229
|
-
|
|
230
|
-
// no literal closing tag inside the JSON payload
|
|
231
|
-
expect(payload).not.toContain("</script>");
|
|
232
|
-
// `<` escaped as \u003c — JSON.parse decodes it back
|
|
233
|
-
expect(payload).toContain("\\u003c/script");
|
|
234
|
-
const parsed = JSON.parse(payload);
|
|
235
|
-
expect(parsed.data.evil).toBe(evil);
|
|
236
|
-
});
|
|
237
|
-
});
|
|
238
|
-
|
|
239
|
-
describe("streamed promises (deferred data)", () => {
|
|
240
|
-
let root: string;
|
|
241
|
-
|
|
242
|
-
beforeAll(async () => {
|
|
243
|
-
root = join(tmpdir(), `grimoire-defer-${Date.now()}`);
|
|
244
|
-
await mkdir(root, { recursive: true });
|
|
245
|
-
});
|
|
246
|
-
|
|
247
|
-
afterAll(async () => {
|
|
248
|
-
await rm(root, { recursive: true });
|
|
249
|
-
});
|
|
250
|
-
|
|
251
|
-
async function readChunks(res: Response): Promise<string[]> {
|
|
252
|
-
const reader = res.body!.getReader();
|
|
253
|
-
const chunks: string[] = [];
|
|
254
|
-
while (true) {
|
|
255
|
-
const { done, value } = await reader.read();
|
|
256
|
-
if (done) break;
|
|
257
|
-
chunks.push(String(value));
|
|
258
|
-
}
|
|
259
|
-
return chunks;
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
async function setup(name: string, serverSrc: string): Promise<string[]> {
|
|
263
|
-
// unique dir per test — Bun caches modules by resolved path
|
|
264
|
-
const dir = join(root, name);
|
|
265
|
-
await mkdir(dir, { recursive: true });
|
|
266
|
-
await writeFile(join(dir, "+page.server.ts"), serverSrc);
|
|
267
|
-
await writeFile(
|
|
268
|
-
join(dir, "+page.tsx"),
|
|
269
|
-
"export default function P({ data }) { return <div>{data.fast}{String(data.slow)}{String(data.boom)}{data.slow === undefined ? \"[pending]\" : \"\"}</div>; }",
|
|
270
|
-
);
|
|
271
|
-
const tree = await scanRoutes(dir);
|
|
272
|
-
const matched = matchRoute(tree, new URL("http://localhost/"));
|
|
273
|
-
const res = await renderRoute(matched!, new Request("http://localhost/"));
|
|
274
|
-
return readChunks(res);
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
test("slow promise flushes after the document shell", async () => {
|
|
278
|
-
const chunks = await setup(
|
|
279
|
-
"slow",
|
|
280
|
-
[
|
|
281
|
-
"export async function load() {",
|
|
282
|
-
" return {",
|
|
283
|
-
' fast: "now",',
|
|
284
|
-
' slow: new Promise((r) => setTimeout(() => r("late"), 30)),',
|
|
285
|
-
" };",
|
|
286
|
-
"}",
|
|
287
|
-
].join("\n"),
|
|
288
|
-
);
|
|
289
|
-
const all = chunks.join("");
|
|
290
|
-
|
|
291
|
-
// state payload marks the field as deferred
|
|
292
|
-
expect(all).toContain('"__deferred":"gd-0"');
|
|
293
|
-
// the shell flushed before the promise settled
|
|
294
|
-
const shell = chunks.find((c) => c.includes("__grimoire_state__"))!;
|
|
295
|
-
expect(shell).not.toContain('"late"');
|
|
296
|
-
// the page rendered with the pending value as undefined, not a marker
|
|
297
|
-
expect(shell).toContain("[pending]");
|
|
298
|
-
// a later chunk carries the self-contained patch script
|
|
299
|
-
const late = chunks.find((c) => c.includes("grimoire:deferred"));
|
|
300
|
-
expect(late).toBeDefined();
|
|
301
|
-
expect(late).toContain('"late"');
|
|
302
|
-
expect(late).toContain("__grimoire_state__");
|
|
303
|
-
expect(late).toContain('data["slow"]');
|
|
304
|
-
});
|
|
305
|
-
|
|
306
|
-
test("rejected promise emits error detail and null value", async () => {
|
|
307
|
-
const all = (
|
|
308
|
-
await setup(
|
|
309
|
-
"reject",
|
|
310
|
-
[
|
|
311
|
-
"export async function load() {",
|
|
312
|
-
" const boom = Promise.reject(new Error('nope'));",
|
|
313
|
-
" boom.catch(() => {});",
|
|
314
|
-
" return { boom };",
|
|
315
|
-
"}",
|
|
316
|
-
].join("\n"),
|
|
317
|
-
)
|
|
318
|
-
).join("");
|
|
319
|
-
expect(all).toContain("error:true");
|
|
320
|
-
expect(all).toContain('data["boom"]');
|
|
321
|
-
});
|
|
322
|
-
|
|
323
|
-
// The end-to-end version: a real streamed render, a component that reads
|
|
324
|
-
// the late value through the helper, and the real patch script run
|
|
325
|
-
// against a real event target. The unit tests in deferred.test.ts cover
|
|
326
|
-
// the helper alone; this one proves the two halves fit.
|
|
327
|
-
test("a component reading through deferred() shows the late value", async () => {
|
|
328
|
-
const dir = join(root, "deferred-helper");
|
|
329
|
-
await mkdir(dir, { recursive: true });
|
|
330
|
-
await writeFile(
|
|
331
|
-
join(dir, "+page.server.ts"),
|
|
332
|
-
[
|
|
333
|
-
"export async function load() {",
|
|
334
|
-
" return {",
|
|
335
|
-
' title: "Book",',
|
|
336
|
-
' reviews: new Promise((r) => setTimeout(() => r(["great"]), 25)),',
|
|
337
|
-
" };",
|
|
338
|
-
"}",
|
|
339
|
-
].join("\n"),
|
|
340
|
-
);
|
|
341
|
-
// The page renders the fallback while the value is in flight.
|
|
342
|
-
//
|
|
343
|
-
// Imported by absolute path because the fixture lives in a tmpdir,
|
|
344
|
-
// where neither a bare specifier nor a relative one can reach this
|
|
345
|
-
// package. That is a limitation of the fixture, not of the import a
|
|
346
|
-
// user would write; deferred.test.ts covers the helper itself.
|
|
347
|
-
await writeFile(
|
|
348
|
-
join(dir, "+page.tsx"),
|
|
349
|
-
[
|
|
350
|
-
'import { deferred } from "/opt/sigil/packages/grimoire/src/client/deferred.ts";',
|
|
351
|
-
"export default function P({ data }) {",
|
|
352
|
-
" const reviews = deferred(data.reviews, []);",
|
|
353
|
-
" return (",
|
|
354
|
-
" <div>",
|
|
355
|
-
" <h1>{data.title}</h1>",
|
|
356
|
-
" {reviews.done ? reviews.value.join() : \"[pending]\"}",
|
|
357
|
-
" </div>",
|
|
358
|
-
" );",
|
|
359
|
-
"}",
|
|
360
|
-
].join("\n"),
|
|
361
|
-
);
|
|
362
|
-
const tree = await scanRoutes(dir);
|
|
363
|
-
const matched = matchRoute(tree, new URL("http://localhost/"));
|
|
364
|
-
const chunks = await readChunks(await renderRoute(matched!, new Request("http://localhost/")));
|
|
365
|
-
|
|
366
|
-
// The shell goes out first, with the fallback rendered.
|
|
367
|
-
const shell = chunks.find((c) => c.includes("__grimoire_state__"))!;
|
|
368
|
-
expect(shell).toContain("Book");
|
|
369
|
-
expect(shell).toContain("[pending]");
|
|
370
|
-
expect(shell).not.toContain("great");
|
|
371
|
-
|
|
372
|
-
// The value arrives in a later chunk as the real patch script.
|
|
373
|
-
const late = chunks.find((c) => c.includes("grimoire:deferred"));
|
|
374
|
-
expect(late).toBeDefined();
|
|
375
|
-
expect(late).toContain("great");
|
|
376
|
-
expect(late).toContain('data["reviews"]');
|
|
377
|
-
});
|
|
378
|
-
});
|
|
1
|
+
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
|
|
2
|
+
import { mkdir, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { renderRoute } from "../src/rendering";
|
|
6
|
+
import { matchRoute } from "../src/routing/router";
|
|
7
|
+
import { scanRoutes } from "../src/routing/scanner";
|
|
8
|
+
|
|
9
|
+
function makeMatched(path: string, filePath: string, params = {}) {
|
|
10
|
+
return {
|
|
11
|
+
route: { path, params: {}, filePath },
|
|
12
|
+
params,
|
|
13
|
+
layouts: [],
|
|
14
|
+
layoutServers: [],
|
|
15
|
+
} as any;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
describe("Streaming SSR", () => {
|
|
19
|
+
test("returns a ReadableStream response", async () => {
|
|
20
|
+
const matched = makeMatched(
|
|
21
|
+
"/",
|
|
22
|
+
"data:text/javascript,export default (p) => '<div>hello</div>'",
|
|
23
|
+
);
|
|
24
|
+
const res = await renderRoute(matched, new Request("http://localhost/"));
|
|
25
|
+
expect(res.body).toBeInstanceOf(ReadableStream);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test("stream contains full HTML document", async () => {
|
|
29
|
+
const matched = makeMatched(
|
|
30
|
+
"/test",
|
|
31
|
+
"data:text/javascript,export default (p) => '<p>streaming works</p>'",
|
|
32
|
+
);
|
|
33
|
+
|
|
34
|
+
const res = await renderRoute(
|
|
35
|
+
matched,
|
|
36
|
+
new Request("http://localhost/test"),
|
|
37
|
+
);
|
|
38
|
+
const html = await res.text();
|
|
39
|
+
|
|
40
|
+
expect(html).toContain("<!DOCTYPE html>");
|
|
41
|
+
expect(html).toContain('<meta charset="UTF-8" />');
|
|
42
|
+
expect(html).toContain("streaming works");
|
|
43
|
+
expect(html).toContain("</html>");
|
|
44
|
+
expect(html).toContain("__grimoire_state__");
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test("stream includes state JSON with route pattern", async () => {
|
|
48
|
+
const matched = makeMatched(
|
|
49
|
+
"/spells/:id",
|
|
50
|
+
"data:text/javascript,export default (p) => '<div>spell</div>'",
|
|
51
|
+
{ id: "fireball" },
|
|
52
|
+
);
|
|
53
|
+
|
|
54
|
+
const res = await renderRoute(
|
|
55
|
+
matched,
|
|
56
|
+
new Request("http://localhost/spells/fireball"),
|
|
57
|
+
);
|
|
58
|
+
const html = await res.text();
|
|
59
|
+
|
|
60
|
+
expect(html).toContain('"pattern":"/spells/:id"');
|
|
61
|
+
expect(html).toContain('"id":"fireball"');
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
test("late head tags survive quotes and scripts in a streaming page", async () => {
|
|
65
|
+
const dir = join(tmpdir(), `grimoire-late-head-${Date.now()}`);
|
|
66
|
+
await mkdir(dir, { recursive: true });
|
|
67
|
+
const file = join(dir, "page.js");
|
|
68
|
+
const head = join(import.meta.dir, "../src/rendering/head.ts");
|
|
69
|
+
await writeFile(
|
|
70
|
+
file,
|
|
71
|
+
[
|
|
72
|
+
`import { Head } from ${JSON.stringify(head)};`,
|
|
73
|
+
`export const loading = () => "<p>wait</p>";`,
|
|
74
|
+
`export default () => { Head({ children: "<title>You've read it</title><script>var a = 1</script>" }); return "<p>done</p>"; };`,
|
|
75
|
+
].join("\n"),
|
|
76
|
+
);
|
|
77
|
+
// <Head> collects for the server only where there is no DOM
|
|
78
|
+
const g = globalThis as { document?: unknown };
|
|
79
|
+
const dom = g.document;
|
|
80
|
+
delete g.document;
|
|
81
|
+
try {
|
|
82
|
+
const res = await renderRoute(
|
|
83
|
+
makeMatched("/late", file),
|
|
84
|
+
new Request("http://localhost/late"),
|
|
85
|
+
);
|
|
86
|
+
const html = await res.text();
|
|
87
|
+
g.document = dom;
|
|
88
|
+
const script =
|
|
89
|
+
/<script>(\(function\(\)\{var p=new DOMParser[^]*?)<\/script>/.exec(
|
|
90
|
+
html,
|
|
91
|
+
)?.[1];
|
|
92
|
+
expect(script).toBeDefined();
|
|
93
|
+
// valid JavaScript, and nothing in it can close the <script> early
|
|
94
|
+
expect(() => new Function(script!)).not.toThrow();
|
|
95
|
+
expect(script).not.toContain("</");
|
|
96
|
+
expect(script).toContain("You've read it");
|
|
97
|
+
} finally {
|
|
98
|
+
g.document = dom;
|
|
99
|
+
await rm(dir, { recursive: true, force: true });
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
test("head script tag comes before head content", async () => {
|
|
104
|
+
const matched = makeMatched(
|
|
105
|
+
"/head-test",
|
|
106
|
+
"data:text/javascript,export default (p) => '<div>head</div>'",
|
|
107
|
+
);
|
|
108
|
+
|
|
109
|
+
const res = await renderRoute(
|
|
110
|
+
matched,
|
|
111
|
+
new Request("http://localhost/head-test"),
|
|
112
|
+
);
|
|
113
|
+
const html = await res.text();
|
|
114
|
+
|
|
115
|
+
const hydrateScript = html.indexOf("hydrate.js");
|
|
116
|
+
const headClosing = html.indexOf("</head>");
|
|
117
|
+
// hydrate.js should be in <head>
|
|
118
|
+
expect(hydrateScript).toBeGreaterThan(-1);
|
|
119
|
+
expect(hydrateScript).toBeLessThan(headClosing);
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
test("stream chunks arrive incrementally", async () => {
|
|
123
|
+
const matched = makeMatched(
|
|
124
|
+
"/chunked",
|
|
125
|
+
"data:text/javascript,export default (p) => '<div>chunked</div>'",
|
|
126
|
+
);
|
|
127
|
+
|
|
128
|
+
const res = await renderRoute(
|
|
129
|
+
matched,
|
|
130
|
+
new Request("http://localhost/chunked"),
|
|
131
|
+
);
|
|
132
|
+
const reader = res.body!.getReader();
|
|
133
|
+
const chunks: string[] = [];
|
|
134
|
+
|
|
135
|
+
while (true) {
|
|
136
|
+
const { done, value } = await reader.read();
|
|
137
|
+
if (done) break;
|
|
138
|
+
// Bun ReadableStream returns Uint8Array
|
|
139
|
+
chunks.push(
|
|
140
|
+
typeof value === "string"
|
|
141
|
+
? value
|
|
142
|
+
: new TextDecoder().decode(value.buffer),
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Should have multiple chunks (at least DOCTYPE + body)
|
|
147
|
+
expect(chunks.length).toBeGreaterThan(1);
|
|
148
|
+
// First chunk should start with DOCTYPE
|
|
149
|
+
expect(chunks[0]).toContain("<!DOCTYPE html>");
|
|
150
|
+
// Last chunk should close the document
|
|
151
|
+
expect(chunks[chunks.length - 1]).toContain("</html>");
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
test("navigation request returns JSON not stream", async () => {
|
|
155
|
+
const matched = makeMatched(
|
|
156
|
+
"/nav",
|
|
157
|
+
"data:text/javascript,export default (p) => '<div>nav</div>'",
|
|
158
|
+
);
|
|
159
|
+
|
|
160
|
+
const req = new Request("http://localhost/nav", {
|
|
161
|
+
headers: { "x-grimoire-navigate": "1" },
|
|
162
|
+
});
|
|
163
|
+
const res = await renderRoute(matched, req);
|
|
164
|
+
const json = await res.json();
|
|
165
|
+
|
|
166
|
+
expect(json.pattern).toBe("/nav");
|
|
167
|
+
expect(json.data).toBeDefined();
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
// The JSON payload and the HTML document share one URL and are picked by a
|
|
171
|
+
// request header. Without Vary any cache may serve the JSON to a plain
|
|
172
|
+
// document request, which rendered the raw state object as the page.
|
|
173
|
+
test("navigation JSON declares Vary on the navigate header", async () => {
|
|
174
|
+
const matched = makeMatched(
|
|
175
|
+
"/nav-vary",
|
|
176
|
+
"data:text/javascript,export default (p) => '<div>nav</div>'",
|
|
177
|
+
);
|
|
178
|
+
|
|
179
|
+
const res = await renderRoute(
|
|
180
|
+
matched,
|
|
181
|
+
new Request("http://localhost/nav-vary", {
|
|
182
|
+
headers: { "x-grimoire-navigate": "1" },
|
|
183
|
+
}),
|
|
184
|
+
);
|
|
185
|
+
|
|
186
|
+
expect(res.headers.get("content-type")).toContain("application/json");
|
|
187
|
+
expect(res.headers.get("vary")?.toLowerCase()).toContain(
|
|
188
|
+
"x-grimoire-navigate",
|
|
189
|
+
);
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
test("HTML document declares Vary on the navigate header", async () => {
|
|
193
|
+
const matched = makeMatched(
|
|
194
|
+
"/doc-vary",
|
|
195
|
+
"data:text/javascript,export default (p) => '<div>doc</div>'",
|
|
196
|
+
);
|
|
197
|
+
|
|
198
|
+
const res = await renderRoute(
|
|
199
|
+
matched,
|
|
200
|
+
new Request("http://localhost/doc-vary"),
|
|
201
|
+
);
|
|
202
|
+
|
|
203
|
+
expect(res.headers.get("content-type")).toContain("text/html");
|
|
204
|
+
expect(res.headers.get("vary")?.toLowerCase()).toContain(
|
|
205
|
+
"x-grimoire-navigate",
|
|
206
|
+
);
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
test("state JSON escapes </script> in data (XSS)", async () => {
|
|
210
|
+
const evil = "</script><script>alert(1)</script>";
|
|
211
|
+
const src = [
|
|
212
|
+
"export const load = async () => ({ evil })",
|
|
213
|
+
"const evil = " + JSON.stringify(evil),
|
|
214
|
+
'export default () => "<div>ok</div>"',
|
|
215
|
+
].join(";\n");
|
|
216
|
+
const matched = makeMatched(
|
|
217
|
+
"/xss",
|
|
218
|
+
`data:text/javascript,${encodeURIComponent(src)}`,
|
|
219
|
+
);
|
|
220
|
+
|
|
221
|
+
const res = await renderRoute(matched, new Request("http://localhost/xss"));
|
|
222
|
+
const html = await res.text();
|
|
223
|
+
|
|
224
|
+
const tagStart = html.indexOf('<script id="__grimoire_state__"');
|
|
225
|
+
expect(tagStart).toBeGreaterThan(-1);
|
|
226
|
+
const payloadStart = html.indexOf(">", tagStart) + 1;
|
|
227
|
+
const payloadEnd = html.indexOf("</script>", payloadStart);
|
|
228
|
+
const payload = html.slice(payloadStart, payloadEnd);
|
|
229
|
+
|
|
230
|
+
// no literal closing tag inside the JSON payload
|
|
231
|
+
expect(payload).not.toContain("</script>");
|
|
232
|
+
// `<` escaped as \u003c — JSON.parse decodes it back
|
|
233
|
+
expect(payload).toContain("\\u003c/script");
|
|
234
|
+
const parsed = JSON.parse(payload);
|
|
235
|
+
expect(parsed.data.evil).toBe(evil);
|
|
236
|
+
});
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
describe("streamed promises (deferred data)", () => {
|
|
240
|
+
let root: string;
|
|
241
|
+
|
|
242
|
+
beforeAll(async () => {
|
|
243
|
+
root = join(tmpdir(), `grimoire-defer-${Date.now()}`);
|
|
244
|
+
await mkdir(root, { recursive: true });
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
afterAll(async () => {
|
|
248
|
+
await rm(root, { recursive: true });
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
async function readChunks(res: Response): Promise<string[]> {
|
|
252
|
+
const reader = res.body!.getReader();
|
|
253
|
+
const chunks: string[] = [];
|
|
254
|
+
while (true) {
|
|
255
|
+
const { done, value } = await reader.read();
|
|
256
|
+
if (done) break;
|
|
257
|
+
chunks.push(String(value));
|
|
258
|
+
}
|
|
259
|
+
return chunks;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
async function setup(name: string, serverSrc: string): Promise<string[]> {
|
|
263
|
+
// unique dir per test — Bun caches modules by resolved path
|
|
264
|
+
const dir = join(root, name);
|
|
265
|
+
await mkdir(dir, { recursive: true });
|
|
266
|
+
await writeFile(join(dir, "+page.server.ts"), serverSrc);
|
|
267
|
+
await writeFile(
|
|
268
|
+
join(dir, "+page.tsx"),
|
|
269
|
+
"export default function P({ data }) { return <div>{data.fast}{String(data.slow)}{String(data.boom)}{data.slow === undefined ? \"[pending]\" : \"\"}</div>; }",
|
|
270
|
+
);
|
|
271
|
+
const tree = await scanRoutes(dir);
|
|
272
|
+
const matched = matchRoute(tree, new URL("http://localhost/"));
|
|
273
|
+
const res = await renderRoute(matched!, new Request("http://localhost/"));
|
|
274
|
+
return readChunks(res);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
test("slow promise flushes after the document shell", async () => {
|
|
278
|
+
const chunks = await setup(
|
|
279
|
+
"slow",
|
|
280
|
+
[
|
|
281
|
+
"export async function load() {",
|
|
282
|
+
" return {",
|
|
283
|
+
' fast: "now",',
|
|
284
|
+
' slow: new Promise((r) => setTimeout(() => r("late"), 30)),',
|
|
285
|
+
" };",
|
|
286
|
+
"}",
|
|
287
|
+
].join("\n"),
|
|
288
|
+
);
|
|
289
|
+
const all = chunks.join("");
|
|
290
|
+
|
|
291
|
+
// state payload marks the field as deferred
|
|
292
|
+
expect(all).toContain('"__deferred":"gd-0"');
|
|
293
|
+
// the shell flushed before the promise settled
|
|
294
|
+
const shell = chunks.find((c) => c.includes("__grimoire_state__"))!;
|
|
295
|
+
expect(shell).not.toContain('"late"');
|
|
296
|
+
// the page rendered with the pending value as undefined, not a marker
|
|
297
|
+
expect(shell).toContain("[pending]");
|
|
298
|
+
// a later chunk carries the self-contained patch script
|
|
299
|
+
const late = chunks.find((c) => c.includes("grimoire:deferred"));
|
|
300
|
+
expect(late).toBeDefined();
|
|
301
|
+
expect(late).toContain('"late"');
|
|
302
|
+
expect(late).toContain("__grimoire_state__");
|
|
303
|
+
expect(late).toContain('data["slow"]');
|
|
304
|
+
});
|
|
305
|
+
|
|
306
|
+
test("rejected promise emits error detail and null value", async () => {
|
|
307
|
+
const all = (
|
|
308
|
+
await setup(
|
|
309
|
+
"reject",
|
|
310
|
+
[
|
|
311
|
+
"export async function load() {",
|
|
312
|
+
" const boom = Promise.reject(new Error('nope'));",
|
|
313
|
+
" boom.catch(() => {});",
|
|
314
|
+
" return { boom };",
|
|
315
|
+
"}",
|
|
316
|
+
].join("\n"),
|
|
317
|
+
)
|
|
318
|
+
).join("");
|
|
319
|
+
expect(all).toContain("error:true");
|
|
320
|
+
expect(all).toContain('data["boom"]');
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
// The end-to-end version: a real streamed render, a component that reads
|
|
324
|
+
// the late value through the helper, and the real patch script run
|
|
325
|
+
// against a real event target. The unit tests in deferred.test.ts cover
|
|
326
|
+
// the helper alone; this one proves the two halves fit.
|
|
327
|
+
test("a component reading through deferred() shows the late value", async () => {
|
|
328
|
+
const dir = join(root, "deferred-helper");
|
|
329
|
+
await mkdir(dir, { recursive: true });
|
|
330
|
+
await writeFile(
|
|
331
|
+
join(dir, "+page.server.ts"),
|
|
332
|
+
[
|
|
333
|
+
"export async function load() {",
|
|
334
|
+
" return {",
|
|
335
|
+
' title: "Book",',
|
|
336
|
+
' reviews: new Promise((r) => setTimeout(() => r(["great"]), 25)),',
|
|
337
|
+
" };",
|
|
338
|
+
"}",
|
|
339
|
+
].join("\n"),
|
|
340
|
+
);
|
|
341
|
+
// The page renders the fallback while the value is in flight.
|
|
342
|
+
//
|
|
343
|
+
// Imported by absolute path because the fixture lives in a tmpdir,
|
|
344
|
+
// where neither a bare specifier nor a relative one can reach this
|
|
345
|
+
// package. That is a limitation of the fixture, not of the import a
|
|
346
|
+
// user would write; deferred.test.ts covers the helper itself.
|
|
347
|
+
await writeFile(
|
|
348
|
+
join(dir, "+page.tsx"),
|
|
349
|
+
[
|
|
350
|
+
'import { deferred } from "/opt/sigil/packages/grimoire/src/client/deferred.ts";',
|
|
351
|
+
"export default function P({ data }) {",
|
|
352
|
+
" const reviews = deferred(data.reviews, []);",
|
|
353
|
+
" return (",
|
|
354
|
+
" <div>",
|
|
355
|
+
" <h1>{data.title}</h1>",
|
|
356
|
+
" {reviews.done ? reviews.value.join() : \"[pending]\"}",
|
|
357
|
+
" </div>",
|
|
358
|
+
" );",
|
|
359
|
+
"}",
|
|
360
|
+
].join("\n"),
|
|
361
|
+
);
|
|
362
|
+
const tree = await scanRoutes(dir);
|
|
363
|
+
const matched = matchRoute(tree, new URL("http://localhost/"));
|
|
364
|
+
const chunks = await readChunks(await renderRoute(matched!, new Request("http://localhost/")));
|
|
365
|
+
|
|
366
|
+
// The shell goes out first, with the fallback rendered.
|
|
367
|
+
const shell = chunks.find((c) => c.includes("__grimoire_state__"))!;
|
|
368
|
+
expect(shell).toContain("Book");
|
|
369
|
+
expect(shell).toContain("[pending]");
|
|
370
|
+
expect(shell).not.toContain("great");
|
|
371
|
+
|
|
372
|
+
// The value arrives in a later chunk as the real patch script.
|
|
373
|
+
const late = chunks.find((c) => c.includes("grimoire:deferred"));
|
|
374
|
+
expect(late).toBeDefined();
|
|
375
|
+
expect(late).toContain("great");
|
|
376
|
+
expect(late).toContain('data["reviews"]');
|
|
377
|
+
});
|
|
378
|
+
});
|