@sigil-dev/grimoire 0.9.21 → 0.9.23

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 (94) hide show
  1. package/README.md +83 -83
  2. package/index.ts +50 -48
  3. package/package.json +22 -10
  4. package/public/__grimoire__/grimoire-client.js +12 -0
  5. package/public/__grimoire__/runtime.js +1241 -0
  6. package/server.ts +22 -20
  7. package/src/adapters/bun.ts +17 -0
  8. package/src/adapters/static.ts +41 -0
  9. package/src/adapters/types.ts +36 -0
  10. package/src/base.ts +91 -0
  11. package/src/client/csrf.ts +47 -47
  12. package/src/client/deferred.ts +179 -179
  13. package/src/client/enhance.ts +160 -160
  14. package/src/client/router.ts +871 -833
  15. package/src/dev/compile-module.ts +211 -211
  16. package/src/dev/loader.ts +141 -141
  17. package/src/dev/resolve.ts +70 -70
  18. package/src/dev/runtime-bundle.ts +51 -51
  19. package/src/env/modules.ts +62 -62
  20. package/src/env/required.ts +42 -0
  21. package/src/env/typegen.ts +61 -61
  22. package/src/headers.ts +105 -105
  23. package/src/logger/transports.ts +117 -117
  24. package/src/rendering/head.ts +49 -49
  25. package/src/rendering/hydrate.ts +161 -161
  26. package/src/rendering/images.ts +43 -43
  27. package/src/rendering/index.ts +755 -749
  28. package/src/rendering/preload.ts +102 -101
  29. package/src/rendering/ssrPlugin.ts +1 -1
  30. package/src/rendering/timing.ts +40 -40
  31. package/src/routing/router.ts +186 -186
  32. package/src/routing/scanner.ts +225 -196
  33. package/src/routing/transform-routes.ts +102 -102
  34. package/src/server/after-response.ts +206 -206
  35. package/src/server/asset-cache.ts +57 -57
  36. package/src/server/build.ts +262 -262
  37. package/src/server/cached.ts +114 -114
  38. package/src/server/client-address.ts +82 -82
  39. package/src/server/client-dir.ts +57 -57
  40. package/src/server/client-entry.ts +44 -44
  41. package/src/server/cookie-utils.ts +80 -80
  42. package/src/server/coordinator.ts +476 -471
  43. package/src/server/hooks.ts +122 -122
  44. package/src/server/index.ts +211 -80
  45. package/src/server/plugins.ts +172 -172
  46. package/src/server/prerender.ts +444 -0
  47. package/src/server/reserved.ts +17 -0
  48. package/src/server/resolver.ts +98 -98
  49. package/src/server/rewrite.ts +28 -0
  50. package/src/server/warm.ts +91 -91
  51. package/src/server/with-headers.ts +27 -27
  52. package/src/server/worker.ts +74 -72
  53. package/src/testing/dom.ts +73 -0
  54. package/src/testing/index.ts +169 -0
  55. package/src/testing/server.ts +162 -0
  56. package/src/typegen/index.ts +450 -450
  57. package/src/types.ts +501 -432
  58. package/test/after-response.test.ts +132 -132
  59. package/test/asset-cache-policy.test.ts +96 -96
  60. package/test/base.test.ts +134 -0
  61. package/test/cached.test.ts +126 -126
  62. package/test/client-address.test.ts +78 -78
  63. package/test/client-csrf.test.ts +61 -61
  64. package/test/client-dir.test.ts +101 -101
  65. package/test/client-router.test.ts +789 -734
  66. package/test/coordinator.test.ts +96 -94
  67. package/test/deferred.test.ts +256 -256
  68. package/test/dev-loader.test.ts +30 -30
  69. package/test/env.test.ts +168 -168
  70. package/test/force-production.test.ts +44 -0
  71. package/test/images.test.ts +49 -49
  72. package/test/locals-header.test.ts +61 -0
  73. package/test/middleware.test.ts +243 -243
  74. package/test/parser-plugins.test.ts +1 -1
  75. package/test/plugin-handle.test.ts +62 -62
  76. package/test/plugin-services-context.test.ts +97 -97
  77. package/test/preload.test.ts +48 -48
  78. package/test/prerender.test.ts +353 -0
  79. package/test/rendering.test.ts +799 -798
  80. package/test/required-env.test.ts +32 -0
  81. package/test/rewrite-html.test.ts +90 -0
  82. package/test/scanning.test.ts +349 -314
  83. package/test/server.test.ts +640 -619
  84. package/test/services.test.ts +90 -90
  85. package/test/streaming.test.ts +381 -378
  86. package/test/testing-helpers.test.ts +166 -0
  87. package/test/typegen.test.ts +808 -799
  88. package/test/warm.test.ts +96 -96
  89. package/test/worker-context.test.ts +59 -59
  90. package/test/workspace-files.test.ts +149 -146
  91. package/test/workspace-versions.test.ts +1 -1
  92. package/.grimoire/_routes.ts +0 -4
  93. package/public/__grimoire__/client.js +0 -55
  94. package/public/__grimoire__/hydrate.js +0 -63
package/test/env.test.ts CHANGED
@@ -1,168 +1,168 @@
1
- // packages/grimoire/src/env/env.test.ts
2
- import { afterEach, beforeEach, describe, expect, test } from "bun:test";
3
- import { mkdir, rm, writeFile } from "node:fs/promises";
4
- import { tmpdir } from "node:os";
5
- import { join } from "node:path";
6
- import { envModuleSource } from "../src/env/modules.ts";
7
- import { resolverPlugin, rewriteAliases } from "../src/server/resolver.ts";
8
-
9
- describe("$env/dynamic/public", () => {
10
- let orig: Record<string, string | undefined> = {};
11
-
12
- beforeEach(() => {
13
- orig = {
14
- PUBLIC_APP_NAME: process.env.PUBLIC_APP_NAME,
15
- PUBLIC_API_URL: process.env.PUBLIC_API_URL,
16
- SECRET_KEY: process.env.SECRET_KEY,
17
- };
18
- });
19
-
20
- afterEach(() => {
21
- for (const [k, v] of Object.entries(orig)) {
22
- if (v === undefined) delete process.env[k];
23
- else process.env[k] = v;
24
- }
25
- });
26
-
27
- test("reads PUBLIC_ vars at call time", async () => {
28
- process.env.PUBLIC_APP_NAME = "grimoire";
29
- const { env } = await import("../src/env/dynamic-public.ts");
30
- expect(env.PUBLIC_APP_NAME).toBe("grimoire");
31
- });
32
-
33
- test("reflects changes after import", async () => {
34
- const { env } = await import("../src/env/dynamic-public.ts");
35
- process.env.PUBLIC_APP_NAME = "changed";
36
- expect(env.PUBLIC_APP_NAME).toBe("changed");
37
- });
38
-
39
- test("does not expose non-PUBLIC_ vars", async () => {
40
- process.env.SECRET_KEY = "supersecret";
41
- const { env } = await import("../src/env/dynamic-public.ts");
42
- expect(env.SECRET_KEY).toBeUndefined();
43
- });
44
-
45
- test("returns empty string for missing PUBLIC_ key", async () => {
46
- delete process.env.PUBLIC_API_URL;
47
- const { env } = await import("../src/env/dynamic-public.ts");
48
- expect(env.PUBLIC_API_URL).toBe("");
49
- });
50
-
51
- test("ownKeys only includes PUBLIC_ vars", async () => {
52
- process.env.PUBLIC_APP_NAME = "grimoire";
53
- process.env.SECRET_KEY = "secret";
54
- const { env } = await import("../src/env/dynamic-public.ts");
55
- const keys = Object.keys(env);
56
- expect(keys.every((k) => k.startsWith("PUBLIC_"))).toBe(true);
57
- });
58
- });
59
-
60
- describe("$env/dynamic/private", () => {
61
- let orig: string | undefined;
62
-
63
- beforeEach(() => {
64
- orig = process.env.DATABASE_URL;
65
- });
66
-
67
- afterEach(() => {
68
- if (orig === undefined) delete process.env.DATABASE_URL;
69
- else process.env.DATABASE_URL = orig;
70
- });
71
-
72
- test("reads any env var at call time", async () => {
73
- process.env.DATABASE_URL = "postgres://localhost/test";
74
- const { env } = await import("../src/env/dynamic-private.ts");
75
- expect(env.DATABASE_URL).toBe("postgres://localhost/test");
76
- });
77
-
78
- test("reflects changes after import", async () => {
79
- const { env } = await import("../src/env/dynamic-private.ts");
80
- process.env.DATABASE_URL = "postgres://localhost/changed";
81
- expect(env.DATABASE_URL).toBe("postgres://localhost/changed");
82
- });
83
-
84
- test("returns empty string for missing key", async () => {
85
- delete process.env.DATABASE_URL;
86
- const { env } = await import("../src/env/dynamic-private.ts");
87
- expect(env.DATABASE_URL).toBe("");
88
- });
89
-
90
- test("exposes PUBLIC_ vars too", async () => {
91
- process.env.PUBLIC_APP_NAME = "grimoire";
92
- const { env } = await import("../src/env/dynamic-private.ts");
93
- expect(env.PUBLIC_APP_NAME).toBe("grimoire");
94
- });
95
- });
96
-
97
- describe("$env modules in builds", () => {
98
- test("static modules export each variable by name, and env", () => {
99
- process.env.PUBLIC_SITE = "docs";
100
- const src: string = envModuleSource("$env/static/public", "browser");
101
- expect(src).toContain('export const PUBLIC_SITE = env["PUBLIC_SITE"];');
102
- expect(src).not.toContain("SECRET");
103
- delete process.env.PUBLIC_SITE;
104
- });
105
-
106
- test("private modules can't be built for the browser", () => {
107
- for (const kind of ["static", "dynamic"]) {
108
- expect(() => envModuleSource(`$env/${kind}/private`, "browser")).toThrow(
109
- /server secrets/,
110
- );
111
- }
112
- });
113
-
114
- test("a browser build resolves $env and $lib, and inlines no secrets", async () => {
115
- const dir = join(tmpdir(), `grimoire-env-build-${Date.now()}`);
116
- await mkdir(join(dir, "src/lib"), { recursive: true });
117
- await writeFile(
118
- join(dir, "src/lib/greet.ts"),
119
- 'export const greet = (s: string) => "hi " + s;',
120
- );
121
- await writeFile(
122
- join(dir, "entry.ts"),
123
- [
124
- 'import { PUBLIC_WHO } from "$env/static/public";',
125
- 'import { env } from "$env/dynamic/public";',
126
- 'import { greet } from "$lib/greet";',
127
- "console.log(greet(PUBLIC_WHO), env.PUBLIC_WHO);",
128
- ].join("\n"),
129
- );
130
- process.env.PUBLIC_WHO = "world";
131
- process.env.SECRET_WHO = "hunter2";
132
- const cwd = process.cwd();
133
- process.chdir(dir);
134
- try {
135
- const result = await Bun.build({
136
- entrypoints: [join(dir, "entry.ts")],
137
- plugins: [resolverPlugin({}, "browser")],
138
- throw: false,
139
- });
140
- expect(result.success).toBe(true);
141
- const code = await result.outputs[0]!.text();
142
- expect(code).toContain('"world"');
143
- expect(code).toContain('"hi "');
144
- expect(code).not.toContain("hunter2");
145
- } finally {
146
- process.chdir(cwd);
147
- delete process.env.PUBLIC_WHO;
148
- delete process.env.SECRET_WHO;
149
- await rm(dir, { recursive: true, force: true });
150
- }
151
- });
152
-
153
- test("server modules get aliased imports rewritten to files", async () => {
154
- const dir = join(tmpdir(), `grimoire-alias-${Date.now()}`);
155
- await mkdir(join(dir, "lib"), { recursive: true });
156
- await writeFile(join(dir, "lib/db.ts"), "export const db = 1;");
157
- try {
158
- const out = rewriteAliases(
159
- 'import { db } from "$lib/db";\nimport x from "other";',
160
- { $lib: join(dir, "lib") },
161
- );
162
- expect(out).toContain(`from "${join(dir, "lib/db.ts")}"`);
163
- expect(out).toContain('from "other"');
164
- } finally {
165
- await rm(dir, { recursive: true, force: true });
166
- }
167
- });
168
- });
1
+ // packages/grimoire/src/env/env.test.ts
2
+ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
3
+ import { mkdir, rm, writeFile } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { envModuleSource } from "../src/env/modules.ts";
7
+ import { resolverPlugin, rewriteAliases } from "../src/server/resolver.ts";
8
+
9
+ describe("$env/dynamic/public", () => {
10
+ let orig: Record<string, string | undefined> = {};
11
+
12
+ beforeEach(() => {
13
+ orig = {
14
+ PUBLIC_APP_NAME: process.env.PUBLIC_APP_NAME,
15
+ PUBLIC_API_URL: process.env.PUBLIC_API_URL,
16
+ SECRET_KEY: process.env.SECRET_KEY,
17
+ };
18
+ });
19
+
20
+ afterEach(() => {
21
+ for (const [k, v] of Object.entries(orig)) {
22
+ if (v === undefined) delete process.env[k];
23
+ else process.env[k] = v;
24
+ }
25
+ });
26
+
27
+ test("reads PUBLIC_ vars at call time", async () => {
28
+ process.env.PUBLIC_APP_NAME = "grimoire";
29
+ const { env } = await import("../src/env/dynamic-public.ts");
30
+ expect(env.PUBLIC_APP_NAME).toBe("grimoire");
31
+ });
32
+
33
+ test("reflects changes after import", async () => {
34
+ const { env } = await import("../src/env/dynamic-public.ts");
35
+ process.env.PUBLIC_APP_NAME = "changed";
36
+ expect(env.PUBLIC_APP_NAME).toBe("changed");
37
+ });
38
+
39
+ test("does not expose non-PUBLIC_ vars", async () => {
40
+ process.env.SECRET_KEY = "supersecret";
41
+ const { env } = await import("../src/env/dynamic-public.ts");
42
+ expect(env.SECRET_KEY).toBeUndefined();
43
+ });
44
+
45
+ test("returns empty string for missing PUBLIC_ key", async () => {
46
+ delete process.env.PUBLIC_API_URL;
47
+ const { env } = await import("../src/env/dynamic-public.ts");
48
+ expect(env.PUBLIC_API_URL).toBe("");
49
+ });
50
+
51
+ test("ownKeys only includes PUBLIC_ vars", async () => {
52
+ process.env.PUBLIC_APP_NAME = "grimoire";
53
+ process.env.SECRET_KEY = "secret";
54
+ const { env } = await import("../src/env/dynamic-public.ts");
55
+ const keys = Object.keys(env);
56
+ expect(keys.every((k) => k.startsWith("PUBLIC_"))).toBe(true);
57
+ });
58
+ });
59
+
60
+ describe("$env/dynamic/private", () => {
61
+ let orig: string | undefined;
62
+
63
+ beforeEach(() => {
64
+ orig = process.env.DATABASE_URL;
65
+ });
66
+
67
+ afterEach(() => {
68
+ if (orig === undefined) delete process.env.DATABASE_URL;
69
+ else process.env.DATABASE_URL = orig;
70
+ });
71
+
72
+ test("reads any env var at call time", async () => {
73
+ process.env.DATABASE_URL = "postgres://localhost/test";
74
+ const { env } = await import("../src/env/dynamic-private.ts");
75
+ expect(env.DATABASE_URL).toBe("postgres://localhost/test");
76
+ });
77
+
78
+ test("reflects changes after import", async () => {
79
+ const { env } = await import("../src/env/dynamic-private.ts");
80
+ process.env.DATABASE_URL = "postgres://localhost/changed";
81
+ expect(env.DATABASE_URL).toBe("postgres://localhost/changed");
82
+ });
83
+
84
+ test("returns empty string for missing key", async () => {
85
+ delete process.env.DATABASE_URL;
86
+ const { env } = await import("../src/env/dynamic-private.ts");
87
+ expect(env.DATABASE_URL).toBe("");
88
+ });
89
+
90
+ test("exposes PUBLIC_ vars too", async () => {
91
+ process.env.PUBLIC_APP_NAME = "grimoire";
92
+ const { env } = await import("../src/env/dynamic-private.ts");
93
+ expect(env.PUBLIC_APP_NAME).toBe("grimoire");
94
+ });
95
+ });
96
+
97
+ describe("$env modules in builds", () => {
98
+ test("static modules export each variable by name, and env", () => {
99
+ process.env.PUBLIC_SITE = "docs";
100
+ const src: string = envModuleSource("$env/static/public", "browser");
101
+ expect(src).toContain('export const PUBLIC_SITE = env["PUBLIC_SITE"];');
102
+ expect(src).not.toContain("SECRET");
103
+ delete process.env.PUBLIC_SITE;
104
+ });
105
+
106
+ test("private modules can't be built for the browser", () => {
107
+ for (const kind of ["static", "dynamic"]) {
108
+ expect(() => envModuleSource(`$env/${kind}/private`, "browser")).toThrow(
109
+ /server secrets/,
110
+ );
111
+ }
112
+ });
113
+
114
+ test("a browser build resolves $env and $lib, and inlines no secrets", async () => {
115
+ const dir = join(tmpdir(), `grimoire-env-build-${Date.now()}`);
116
+ await mkdir(join(dir, "src/lib"), { recursive: true });
117
+ await writeFile(
118
+ join(dir, "src/lib/greet.ts"),
119
+ 'export const greet = (s: string) => "hi " + s;',
120
+ );
121
+ await writeFile(
122
+ join(dir, "entry.ts"),
123
+ [
124
+ 'import { PUBLIC_WHO } from "$env/static/public";',
125
+ 'import { env } from "$env/dynamic/public";',
126
+ 'import { greet } from "$lib/greet";',
127
+ "console.log(greet(PUBLIC_WHO), env.PUBLIC_WHO);",
128
+ ].join("\n"),
129
+ );
130
+ process.env.PUBLIC_WHO = "world";
131
+ process.env.SECRET_WHO = "hunter2";
132
+ const cwd = process.cwd();
133
+ process.chdir(dir);
134
+ try {
135
+ const result = await Bun.build({
136
+ entrypoints: [join(dir, "entry.ts")],
137
+ plugins: [resolverPlugin({}, "browser")],
138
+ throw: false,
139
+ });
140
+ expect(result.success).toBe(true);
141
+ const code = await result.outputs[0]!.text();
142
+ expect(code).toContain('"world"');
143
+ expect(code).toContain('"hi "');
144
+ expect(code).not.toContain("hunter2");
145
+ } finally {
146
+ process.chdir(cwd);
147
+ delete process.env.PUBLIC_WHO;
148
+ delete process.env.SECRET_WHO;
149
+ await rm(dir, { recursive: true, force: true });
150
+ }
151
+ });
152
+
153
+ test("server modules get aliased imports rewritten to files", async () => {
154
+ const dir = join(tmpdir(), `grimoire-alias-${Date.now()}`);
155
+ await mkdir(join(dir, "lib"), { recursive: true });
156
+ await writeFile(join(dir, "lib/db.ts"), "export const db = 1;");
157
+ try {
158
+ const out = rewriteAliases(
159
+ 'import { db } from "$lib/db";\nimport x from "other";',
160
+ { $lib: join(dir, "lib") },
161
+ );
162
+ expect(out).toContain(`from "${join(dir, "lib/db.ts")}"`);
163
+ expect(out).toContain('from "other"');
164
+ } finally {
165
+ await rm(dir, { recursive: true, force: true });
166
+ }
167
+ });
168
+ });
@@ -0,0 +1,44 @@
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 { createApp } from "../src/server";
6
+ import type { GrimoirePlugin } from "../src/types";
7
+
8
+ /**
9
+ * Dev mode serves the HMR client, the dependency-source endpoints and
10
+ * `/__grimoire__/open`, which spawns an editor from a query string. A plugin's
11
+ * `config` hook runs inside createApp and can return `dev: true`; anything that
12
+ * serves the public sets `_forceProduction` so that hook does not get the last
13
+ * word.
14
+ */
15
+
16
+ let dir: string;
17
+
18
+ beforeAll(async () => {
19
+ dir = join(tmpdir(), `grimoire-force-prod-${Date.now()}`);
20
+ await mkdir(join(dir, "ping"), { recursive: true });
21
+ await writeFile(join(dir, "ping", "+server.ts"), "export const GET = () => new Response('pong');");
22
+ });
23
+
24
+ afterAll(() => rm(dir, { recursive: true, force: true }));
25
+
26
+ const wantsDev: GrimoirePlugin = {
27
+ name: "wants-dev",
28
+ config: (c) => ({ ...c, dev: true }),
29
+ };
30
+
31
+ describe("_forceProduction", () => {
32
+ test("keeps dev endpoints off even when a plugin's config hook turns dev on", async () => {
33
+ const app = await createApp({
34
+ routes: dir,
35
+ _skipBuild: true,
36
+ _forceProduction: true,
37
+ plugins: [wantsDev],
38
+ });
39
+ expect(app.config.dev).toBe(false);
40
+ // the probe is the HMR client script: harmless, and only served in dev
41
+ const res = await app.fetch(new Request("http://localhost/__grimoire__/hmr-client.js"));
42
+ expect(res.status).toBe(404);
43
+ });
44
+ });
@@ -1,49 +1,49 @@
1
- import { describe, expect, test } from "bun:test";
2
- import { optimizeImages, EAGER_IMAGE_COUNT } from "../src/rendering/images.ts";
3
-
4
- const imgs = (n: number, attrs = "") =>
5
- Array.from({ length: n }, (_, i) => `<img src="/${i}.png"${attrs}>`).join("");
6
-
7
- describe("optimizeImages", () => {
8
- test("leaves the first images eager and defers the rest", () => {
9
- const out = optimizeImages(imgs(EAGER_IMAGE_COUNT + 2));
10
- const tags = out.match(/<img[^>]*>/g)!;
11
- for (const t of tags.slice(0, EAGER_IMAGE_COUNT))
12
- expect(t).not.toContain("loading");
13
- for (const t of tags.slice(EAGER_IMAGE_COUNT))
14
- expect(t).toBe(`<img src="/${tags.indexOf(t)}.png" loading="lazy" decoding="async">`);
15
- });
16
-
17
- test("respects the author's loading and decoding", () => {
18
- const out = optimizeImages(
19
- imgs(EAGER_IMAGE_COUNT) + `<img src="/x.png" loading="eager" decoding="sync" />`,
20
- );
21
- expect(out.endsWith(`<img src="/x.png" loading="eager" decoding="sync" />`)).toBe(true);
22
- });
23
-
24
- test("handles self-closing tags and never touches script strings", () => {
25
- const script = `<script>var s='<img src="q.png">'</script>`;
26
- const out = optimizeImages(imgs(EAGER_IMAGE_COUNT) + script + `<img src="/y.png" />`);
27
- expect(out).toContain(script);
28
- expect(out).toContain(`<img src="/y.png" loading="lazy" decoding="async" />`);
29
- });
30
-
31
- test("a priority image is fetched first and does not use up the eager budget", () => {
32
- const hero = `<img src="/hero.png" data-sigil-priority>`;
33
- const out = optimizeImages(hero + imgs(EAGER_IMAGE_COUNT + 1));
34
- const tags = out.match(/<img[^>]*>/g)!;
35
- expect(tags[0]).toBe(`<img src="/hero.png" data-sigil-priority fetchpriority="high">`);
36
- // the four after it are still eager, the fifth is deferred
37
- for (const t of tags.slice(1, 1 + EAGER_IMAGE_COUNT)) expect(t).not.toContain("loading");
38
- expect(tags.at(-1)).toContain('loading="lazy"');
39
- });
40
-
41
- test("an explicit fetchpriority on a priority image is kept", () => {
42
- const t = `<img src="/h.png" data-sigil-priority fetchpriority="low">`;
43
- expect(optimizeImages(t)).toBe(t);
44
- });
45
-
46
- test("html without images is returned as is", () => {
47
- expect(optimizeImages("<p>hi</p>")).toBe("<p>hi</p>");
48
- });
49
- });
1
+ import { describe, expect, test } from "bun:test";
2
+ import { optimizeImages, EAGER_IMAGE_COUNT } from "../src/rendering/images.ts";
3
+
4
+ const imgs = (n: number, attrs = "") =>
5
+ Array.from({ length: n }, (_, i) => `<img src="/${i}.png"${attrs}>`).join("");
6
+
7
+ describe("optimizeImages", () => {
8
+ test("leaves the first images eager and defers the rest", () => {
9
+ const out = optimizeImages(imgs(EAGER_IMAGE_COUNT + 2));
10
+ const tags = out.match(/<img[^>]*>/g)!;
11
+ for (const t of tags.slice(0, EAGER_IMAGE_COUNT))
12
+ expect(t).not.toContain("loading");
13
+ for (const t of tags.slice(EAGER_IMAGE_COUNT))
14
+ expect(t).toBe(`<img src="/${tags.indexOf(t)}.png" loading="lazy" decoding="async">`);
15
+ });
16
+
17
+ test("respects the author's loading and decoding", () => {
18
+ const out = optimizeImages(
19
+ imgs(EAGER_IMAGE_COUNT) + `<img src="/x.png" loading="eager" decoding="sync" />`,
20
+ );
21
+ expect(out.endsWith(`<img src="/x.png" loading="eager" decoding="sync" />`)).toBe(true);
22
+ });
23
+
24
+ test("handles self-closing tags and never touches script strings", () => {
25
+ const script = `<script>var s='<img src="q.png">'</script>`;
26
+ const out = optimizeImages(imgs(EAGER_IMAGE_COUNT) + script + `<img src="/y.png" />`);
27
+ expect(out).toContain(script);
28
+ expect(out).toContain(`<img src="/y.png" loading="lazy" decoding="async" />`);
29
+ });
30
+
31
+ test("a priority image is fetched first and does not use up the eager budget", () => {
32
+ const hero = `<img src="/hero.png" data-sigil-priority>`;
33
+ const out = optimizeImages(hero + imgs(EAGER_IMAGE_COUNT + 1));
34
+ const tags = out.match(/<img[^>]*>/g)!;
35
+ expect(tags[0]).toBe(`<img src="/hero.png" data-sigil-priority fetchpriority="high">`);
36
+ // the four after it are still eager, the fifth is deferred
37
+ for (const t of tags.slice(1, 1 + EAGER_IMAGE_COUNT)) expect(t).not.toContain("loading");
38
+ expect(tags.at(-1)).toContain('loading="lazy"');
39
+ });
40
+
41
+ test("an explicit fetchpriority on a priority image is kept", () => {
42
+ const t = `<img src="/h.png" data-sigil-priority fetchpriority="low">`;
43
+ expect(optimizeImages(t)).toBe(t);
44
+ });
45
+
46
+ test("html without images is returned as is", () => {
47
+ expect(optimizeImages("<p>hi</p>")).toBe("<p>hi</p>");
48
+ });
49
+ });
@@ -0,0 +1,61 @@
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 { createApp } from "../src/server";
6
+ import type { GrimoirePlugin } from "../src/types";
7
+
8
+ /**
9
+ * `X-Grimoire-Locals` is how the coordinator tells a worker who the user is.
10
+ * A server that answers the public directly has no coordinator, so the header
11
+ * is just something a client typed: honouring it would let anyone choose their
12
+ * own `locals`, including a session.
13
+ */
14
+
15
+ let dir: string;
16
+
17
+ beforeAll(async () => {
18
+ dir = join(tmpdir(), `grimoire-locals-${Date.now()}`);
19
+ await mkdir(join(dir, "who"), { recursive: true });
20
+ await writeFile(
21
+ join(dir, "who", "+server.ts"),
22
+ "export function GET({ locals }) { return Response.json({ user: locals.user ?? null }); }",
23
+ );
24
+ });
25
+
26
+ afterAll(() => rm(dir, { recursive: true, force: true }));
27
+
28
+ // What a signing plugin would do once it has verified the coordinator's mark.
29
+ const trusting: GrimoirePlugin = {
30
+ name: "trusting",
31
+ deserializeLocals: (raw) => ({ user: raw }) as unknown as App.Locals,
32
+ };
33
+
34
+ async function whoAmI(
35
+ behindCoordinator: boolean | undefined,
36
+ ): Promise<unknown> {
37
+ const app = await createApp({
38
+ routes: dir,
39
+ _skipBuild: true,
40
+ plugins: [trusting],
41
+ _behindCoordinator: behindCoordinator,
42
+ });
43
+ const res = await app.fetch(
44
+ new Request("http://localhost/who", {
45
+ headers: { "X-Grimoire-Locals": "admin" },
46
+ }),
47
+ );
48
+ // no close(): it starts a process-wide shutdown, and nothing here holds a resource
49
+ return ((await res.json()) as { user: unknown }).user;
50
+ }
51
+
52
+ describe("X-Grimoire-Locals", () => {
53
+ test("is ignored by a server with no coordinator in front of it", async () => {
54
+ expect(await whoAmI(undefined)).toBeNull();
55
+ expect(await whoAmI(false)).toBeNull();
56
+ });
57
+
58
+ test("is honoured by a worker behind the coordinator", async () => {
59
+ expect(await whoAmI(true)).toBe("admin");
60
+ });
61
+ });