@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
@@ -1,132 +1,132 @@
1
- import { beforeEach, describe, expect, test } from "bun:test";
2
- import {
3
- _resetAfterResponseForTest,
4
- afterResponse,
5
- drainAfterResponse,
6
- withAfterResponse,
7
- } from "../src/server/after-response.ts";
8
-
9
- const req = () => new Request("http://localhost/");
10
-
11
- beforeEach(() => {
12
- _resetAfterResponseForTest();
13
- });
14
-
15
- describe("afterResponse", () => {
16
- test("does not run before the body is consumed", async () => {
17
- let ran = false;
18
- const res = await withAfterResponse(req(), async () => {
19
- afterResponse(() => {
20
- ran = true;
21
- });
22
- return new Response("hello");
23
- });
24
- expect(ran).toBe(false);
25
- await res.text();
26
- await Bun.sleep(10);
27
- expect(ran).toBe(true);
28
- });
29
-
30
- test("a body Bun types itself is still typed when served", async () => {
31
- const server = Bun.serve({
32
- port: 0,
33
- fetch: (r) =>
34
- withAfterResponse(r, async () => {
35
- afterResponse(() => {});
36
- return new Response("not found", { status: 404 });
37
- }),
38
- });
39
- try {
40
- const res = await fetch(`http://localhost:${server.port}/`);
41
- expect(res.status).toBe(404);
42
- expect(res.headers.get("content-type")).toStartWith("text/plain");
43
- expect(await res.text()).toBe("not found");
44
- } finally {
45
- server.stop(true);
46
- }
47
- });
48
-
49
- test("runs for a response with no body", async () => {
50
- let ran = false;
51
- await withAfterResponse(req(), async () => {
52
- afterResponse(() => {
53
- ran = true;
54
- });
55
- return new Response(null, { status: 204 });
56
- });
57
- await Bun.sleep(10);
58
- expect(ran).toBe(true);
59
- });
60
-
61
- test("a throwing task does not corrupt the response", async () => {
62
- const res = await withAfterResponse(req(), async () => {
63
- afterResponse(() => {
64
- throw new Error("boom");
65
- });
66
- return new Response("still fine");
67
- });
68
- expect(await res.text()).toBe("still fine");
69
- await Bun.sleep(10);
70
- });
71
-
72
- test("tasks are isolated per request under concurrency", async () => {
73
- const order: string[] = [];
74
- const make = (tag: string) =>
75
- withAfterResponse(req(), async () => {
76
- afterResponse(() => order.push(tag));
77
- return new Response(tag);
78
- });
79
-
80
- const [a, b] = await Promise.all([make("A"), make("B")]);
81
- await Promise.all([a.text(), b.text()]);
82
- await Bun.sleep(20);
83
-
84
- expect(order.sort()).toEqual(["A", "B"]);
85
- });
86
-
87
- test("preserves status, statusText and headers through the rewrap", async () => {
88
- const res = await withAfterResponse(
89
- req(),
90
- async () =>
91
- new Response("x", {
92
- status: 404,
93
- statusText: "Nope",
94
- headers: { "x-test": "1" },
95
- }),
96
- );
97
- expect(res.status).toBe(404);
98
- expect(res.headers.get("x-test")).toBe("1");
99
- expect(await res.text()).toBe("x");
100
- });
101
-
102
- test("drain waits for a task that is still running", async () => {
103
- let done = false;
104
- const res = await withAfterResponse(req(), async () => {
105
- afterResponse(async () => {
106
- await Bun.sleep(50);
107
- done = true;
108
- });
109
- return new Response("y");
110
- });
111
- await res.text();
112
- await drainAfterResponse(1000);
113
- expect(done).toBe(true);
114
- });
115
-
116
- test("drain returns promptly when nothing is pending", async () => {
117
- const t = Date.now();
118
- await drainAfterResponse(500);
119
- expect(Date.now() - t).toBeLessThan(200);
120
- });
121
-
122
- test("drain gives up rather than hanging on a stuck task", async () => {
123
- const res = await withAfterResponse(req(), async () => {
124
- afterResponse(() => Bun.sleep(60_000));
125
- return new Response("z");
126
- });
127
- await res.text();
128
- const t = Date.now();
129
- await drainAfterResponse(200);
130
- expect(Date.now() - t).toBeLessThan(1500);
131
- });
132
- });
1
+ import { beforeEach, describe, expect, test } from "bun:test";
2
+ import {
3
+ _resetAfterResponseForTest,
4
+ afterResponse,
5
+ drainAfterResponse,
6
+ withAfterResponse,
7
+ } from "../src/server/after-response.ts";
8
+
9
+ const req = () => new Request("http://localhost/");
10
+
11
+ beforeEach(() => {
12
+ _resetAfterResponseForTest();
13
+ });
14
+
15
+ describe("afterResponse", () => {
16
+ test("does not run before the body is consumed", async () => {
17
+ let ran = false;
18
+ const res = await withAfterResponse(req(), async () => {
19
+ afterResponse(() => {
20
+ ran = true;
21
+ });
22
+ return new Response("hello");
23
+ });
24
+ expect(ran).toBe(false);
25
+ await res.text();
26
+ await Bun.sleep(10);
27
+ expect(ran).toBe(true);
28
+ });
29
+
30
+ test("a body Bun types itself is still typed when served", async () => {
31
+ const server = Bun.serve({
32
+ port: 0,
33
+ fetch: (r) =>
34
+ withAfterResponse(r, async () => {
35
+ afterResponse(() => {});
36
+ return new Response("not found", { status: 404 });
37
+ }),
38
+ });
39
+ try {
40
+ const res = await fetch(`http://localhost:${server.port}/`);
41
+ expect(res.status).toBe(404);
42
+ expect(res.headers.get("content-type")).toStartWith("text/plain");
43
+ expect(await res.text()).toBe("not found");
44
+ } finally {
45
+ server.stop(true);
46
+ }
47
+ });
48
+
49
+ test("runs for a response with no body", async () => {
50
+ let ran = false;
51
+ await withAfterResponse(req(), async () => {
52
+ afterResponse(() => {
53
+ ran = true;
54
+ });
55
+ return new Response(null, { status: 204 });
56
+ });
57
+ await Bun.sleep(10);
58
+ expect(ran).toBe(true);
59
+ });
60
+
61
+ test("a throwing task does not corrupt the response", async () => {
62
+ const res = await withAfterResponse(req(), async () => {
63
+ afterResponse(() => {
64
+ throw new Error("boom");
65
+ });
66
+ return new Response("still fine");
67
+ });
68
+ expect(await res.text()).toBe("still fine");
69
+ await Bun.sleep(10);
70
+ });
71
+
72
+ test("tasks are isolated per request under concurrency", async () => {
73
+ const order: string[] = [];
74
+ const make = (tag: string) =>
75
+ withAfterResponse(req(), async () => {
76
+ afterResponse(() => order.push(tag));
77
+ return new Response(tag);
78
+ });
79
+
80
+ const [a, b] = await Promise.all([make("A"), make("B")]);
81
+ await Promise.all([a.text(), b.text()]);
82
+ await Bun.sleep(20);
83
+
84
+ expect(order.sort()).toEqual(["A", "B"]);
85
+ });
86
+
87
+ test("preserves status, statusText and headers through the rewrap", async () => {
88
+ const res = await withAfterResponse(
89
+ req(),
90
+ async () =>
91
+ new Response("x", {
92
+ status: 404,
93
+ statusText: "Nope",
94
+ headers: { "x-test": "1" },
95
+ }),
96
+ );
97
+ expect(res.status).toBe(404);
98
+ expect(res.headers.get("x-test")).toBe("1");
99
+ expect(await res.text()).toBe("x");
100
+ });
101
+
102
+ test("drain waits for a task that is still running", async () => {
103
+ let done = false;
104
+ const res = await withAfterResponse(req(), async () => {
105
+ afterResponse(async () => {
106
+ await Bun.sleep(50);
107
+ done = true;
108
+ });
109
+ return new Response("y");
110
+ });
111
+ await res.text();
112
+ await drainAfterResponse(1000);
113
+ expect(done).toBe(true);
114
+ });
115
+
116
+ test("drain returns promptly when nothing is pending", async () => {
117
+ const t = Date.now();
118
+ await drainAfterResponse(500);
119
+ expect(Date.now() - t).toBeLessThan(200);
120
+ });
121
+
122
+ test("drain gives up rather than hanging on a stuck task", async () => {
123
+ const res = await withAfterResponse(req(), async () => {
124
+ afterResponse(() => Bun.sleep(60_000));
125
+ return new Response("z");
126
+ });
127
+ await res.text();
128
+ const t = Date.now();
129
+ await drainAfterResponse(200);
130
+ expect(Date.now() - t).toBeLessThan(1500);
131
+ });
132
+ });
@@ -1,96 +1,96 @@
1
- import { describe, expect, test } from "bun:test";
2
- import {
3
- CACHE_CONTROL,
4
- cacheControlFor,
5
- isContentAddressed,
6
- } from "../src/server/asset-cache.ts";
7
-
8
- /**
9
- * The policy, tested directly rather than through a booted server.
10
- *
11
- * This is where the bug lived — a caching decision, not a routing one — so
12
- * it is the decision worth pinning. Importing the real function rather than
13
- * restating it here: a test that keeps its own copy passes no matter what
14
- * the server does, which is worse than no test at all.
15
- */
16
- describe("isContentAddressed", () => {
17
- test("a hash in the filename counts", () => {
18
- expect(isContentAddressed("/style.a1b2c3d4.css", "")).toBe(true);
19
- expect(isContentAddressed("/glyphs/ok.9f8e7d6c.svg", "")).toBe(true);
20
- });
21
-
22
- test("a longer hash still counts", () => {
23
- expect(isContentAddressed("/style.deadbeef0123456789.css", "")).toBe(true);
24
- });
25
-
26
- test("a bundler chunk name counts", () => {
27
- // Shared chunks are named for their contents, and every page load
28
- // fetches them. Without this they revalidated each time.
29
- expect(isContentAddressed("/__grimoire__/chunk-jp4kgm87.js", "")).toBe(true);
30
- expect(cacheControlFor("/__grimoire__/chunk-1pk15q3t.js", "")).toBe("immutable");
31
- });
32
-
33
- test("chunk- must be the whole stem, not a lookalike", () => {
34
- expect(isContentAddressed("/chunk-list.js", "")).toBe(false);
35
- expect(isContentAddressed("/img/hero-background.png", "")).toBe(false);
36
- expect(isContentAddressed("/notchunk-abcdef12.js", "")).toBe(false);
37
- });
38
-
39
- test("a bare filename does not count", () => {
40
- // The bug this policy exists to prevent: a year-long cache at a URL
41
- // that never changes, so an edited stylesheet is never seen.
42
- expect(isContentAddressed("/style.css", "")).toBe(false);
43
- expect(isContentAddressed("/mark.svg", "")).toBe(false);
44
- });
45
-
46
- test("a version query counts", () => {
47
- expect(isContentAddressed("/style.css", "?v=1")).toBe(true);
48
- expect(isContentAddressed("/style.css", "?v=abc123")).toBe(true);
49
- expect(isContentAddressed("/style.css", "?a=1&v=2")).toBe(true);
50
- });
51
-
52
- test("an empty version value does not count", () => {
53
- // /style.css? and /style.css are the same resource, so treating it
54
- // as addressed would cache it forever without it ever changing.
55
- expect(isContentAddressed("/style.css", "?v=")).toBe(false);
56
- expect(isContentAddressed("/style.css", "?")).toBe(false);
57
- });
58
-
59
- test("an unrelated query does not count", () => {
60
- expect(isContentAddressed("/style.css", "?theme=dark")).toBe(false);
61
- expect(isContentAddressed("/style.css", "?cachebust=1")).toBe(false);
62
- });
63
-
64
- test("a non-hash dotted name is not treated as addressed", () => {
65
- // theme.min.css is common and 3 hex chars is not a hash.
66
- expect(isContentAddressed("/app.min.css", "")).toBe(false);
67
- expect(isContentAddressed("/style.abc.css", "")).toBe(false);
68
- });
69
- });
70
-
71
- describe("cacheControlFor", () => {
72
- test("the document is never cached", () => {
73
- expect(cacheControlFor("/", "")).toBe("no-cache");
74
- expect(cacheControlFor("/index.html", "")).toBe("no-cache");
75
- });
76
-
77
- test("a content-addressed asset is immutable", () => {
78
- expect(cacheControlFor("/style.a1b2c3d4.css", "")).toBe("immutable");
79
- expect(cacheControlFor("/style.css", "?v=2")).toBe("immutable");
80
- });
81
-
82
- test("everything else revalidates", () => {
83
- expect(cacheControlFor("/style.css", "")).toBe("revalidate");
84
- expect(cacheControlFor("/mark.svg", "")).toBe("revalidate");
85
- });
86
-
87
- test("every policy has a header", () => {
88
- expect(CACHE_CONTROL[cacheControlFor("/", "")]).toBe("no-cache");
89
- expect(CACHE_CONTROL[cacheControlFor("/a.12345678.css", "")]).toContain(
90
- "immutable",
91
- );
92
- expect(CACHE_CONTROL[cacheControlFor("/a.css", "")]).toContain(
93
- "must-revalidate",
94
- );
95
- });
96
- });
1
+ import { describe, expect, test } from "bun:test";
2
+ import {
3
+ CACHE_CONTROL,
4
+ cacheControlFor,
5
+ isContentAddressed,
6
+ } from "../src/server/asset-cache.ts";
7
+
8
+ /**
9
+ * The policy, tested directly rather than through a booted server.
10
+ *
11
+ * This is where the bug lived — a caching decision, not a routing one — so
12
+ * it is the decision worth pinning. Importing the real function rather than
13
+ * restating it here: a test that keeps its own copy passes no matter what
14
+ * the server does, which is worse than no test at all.
15
+ */
16
+ describe("isContentAddressed", () => {
17
+ test("a hash in the filename counts", () => {
18
+ expect(isContentAddressed("/style.a1b2c3d4.css", "")).toBe(true);
19
+ expect(isContentAddressed("/glyphs/ok.9f8e7d6c.svg", "")).toBe(true);
20
+ });
21
+
22
+ test("a longer hash still counts", () => {
23
+ expect(isContentAddressed("/style.deadbeef0123456789.css", "")).toBe(true);
24
+ });
25
+
26
+ test("a bundler chunk name counts", () => {
27
+ // Shared chunks are named for their contents, and every page load
28
+ // fetches them. Without this they revalidated each time.
29
+ expect(isContentAddressed("/__grimoire__/chunk-jp4kgm87.js", "")).toBe(true);
30
+ expect(cacheControlFor("/__grimoire__/chunk-1pk15q3t.js", "")).toBe("immutable");
31
+ });
32
+
33
+ test("chunk- must be the whole stem, not a lookalike", () => {
34
+ expect(isContentAddressed("/chunk-list.js", "")).toBe(false);
35
+ expect(isContentAddressed("/img/hero-background.png", "")).toBe(false);
36
+ expect(isContentAddressed("/notchunk-abcdef12.js", "")).toBe(false);
37
+ });
38
+
39
+ test("a bare filename does not count", () => {
40
+ // The bug this policy exists to prevent: a year-long cache at a URL
41
+ // that never changes, so an edited stylesheet is never seen.
42
+ expect(isContentAddressed("/style.css", "")).toBe(false);
43
+ expect(isContentAddressed("/mark.svg", "")).toBe(false);
44
+ });
45
+
46
+ test("a version query counts", () => {
47
+ expect(isContentAddressed("/style.css", "?v=1")).toBe(true);
48
+ expect(isContentAddressed("/style.css", "?v=abc123")).toBe(true);
49
+ expect(isContentAddressed("/style.css", "?a=1&v=2")).toBe(true);
50
+ });
51
+
52
+ test("an empty version value does not count", () => {
53
+ // /style.css? and /style.css are the same resource, so treating it
54
+ // as addressed would cache it forever without it ever changing.
55
+ expect(isContentAddressed("/style.css", "?v=")).toBe(false);
56
+ expect(isContentAddressed("/style.css", "?")).toBe(false);
57
+ });
58
+
59
+ test("an unrelated query does not count", () => {
60
+ expect(isContentAddressed("/style.css", "?theme=dark")).toBe(false);
61
+ expect(isContentAddressed("/style.css", "?cachebust=1")).toBe(false);
62
+ });
63
+
64
+ test("a non-hash dotted name is not treated as addressed", () => {
65
+ // theme.min.css is common and 3 hex chars is not a hash.
66
+ expect(isContentAddressed("/app.min.css", "")).toBe(false);
67
+ expect(isContentAddressed("/style.abc.css", "")).toBe(false);
68
+ });
69
+ });
70
+
71
+ describe("cacheControlFor", () => {
72
+ test("the document is never cached", () => {
73
+ expect(cacheControlFor("/", "")).toBe("no-cache");
74
+ expect(cacheControlFor("/index.html", "")).toBe("no-cache");
75
+ });
76
+
77
+ test("a content-addressed asset is immutable", () => {
78
+ expect(cacheControlFor("/style.a1b2c3d4.css", "")).toBe("immutable");
79
+ expect(cacheControlFor("/style.css", "?v=2")).toBe("immutable");
80
+ });
81
+
82
+ test("everything else revalidates", () => {
83
+ expect(cacheControlFor("/style.css", "")).toBe("revalidate");
84
+ expect(cacheControlFor("/mark.svg", "")).toBe("revalidate");
85
+ });
86
+
87
+ test("every policy has a header", () => {
88
+ expect(CACHE_CONTROL[cacheControlFor("/", "")]).toBe("no-cache");
89
+ expect(CACHE_CONTROL[cacheControlFor("/a.12345678.css", "")]).toContain(
90
+ "immutable",
91
+ );
92
+ expect(CACHE_CONTROL[cacheControlFor("/a.css", "")]).toContain(
93
+ "must-revalidate",
94
+ );
95
+ });
96
+ });
@@ -0,0 +1,134 @@
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 {
6
+ normalizeBase,
7
+ outsideBaseMessage,
8
+ setBase,
9
+ stripBase,
10
+ withBase,
11
+ } from "../src/base";
12
+ import { createApp } from "../src/server";
13
+ import { extractLinks } from "../src/server/prerender";
14
+
15
+ describe("normalizeBase", () => {
16
+ test("accepts the root and a plain path", () => {
17
+ expect(normalizeBase(undefined)).toBe("");
18
+ expect(normalizeBase("")).toBe("");
19
+ expect(normalizeBase("/")).toBe("");
20
+ expect(normalizeBase("/repo")).toBe("/repo");
21
+ expect(normalizeBase("/a/b")).toBe("/a/b");
22
+ });
23
+
24
+ test("each mistake is named, with the fix", () => {
25
+ expect(() => normalizeBase("repo")).toThrow(/must start with a slash: "\/repo"/);
26
+ expect(() => normalizeBase("/repo/")).toThrow(/must not end with a slash: "\/repo"/);
27
+ expect(() => normalizeBase("https://u.github.io/repo")).toThrow(/full URL/);
28
+ expect(() => normalizeBase("//cdn/repo")).toThrow(/full URL/);
29
+ expect(() => normalizeBase("/a b")).toThrow(/plain path/);
30
+ expect(() => normalizeBase('/a"b')).toThrow(/plain path/);
31
+ });
32
+ });
33
+
34
+ describe("withBase and stripBase", () => {
35
+ test("withBase prefixes root-relative paths only", () => {
36
+ expect(withBase("/about", "/repo")).toBe("/repo/about");
37
+ expect(withBase("/", "/repo")).toBe("/repo/");
38
+ expect(withBase("/a?x=1#h", "/repo")).toBe("/repo/a?x=1#h");
39
+ expect(withBase("https://x.dev/a", "/repo")).toBe("https://x.dev/a");
40
+ expect(withBase("//cdn/a", "/repo")).toBe("//cdn/a");
41
+ expect(withBase("a", "/repo")).toBe("a");
42
+ expect(withBase("/about", "")).toBe("/about");
43
+ });
44
+
45
+ test("withBase is not idempotent: a route may share the base's first segment", () => {
46
+ expect(withBase("/repo/x", "/repo")).toBe("/repo/repo/x");
47
+ });
48
+
49
+ test("stripBase gives the route path, or null outside the base", () => {
50
+ expect(stripBase("/repo/about", "/repo")).toBe("/about");
51
+ expect(stripBase("/repo/", "/repo")).toBe("/");
52
+ expect(stripBase("/repo", "/repo")).toBe("/");
53
+ expect(stripBase("/repository", "/repo")).toBeNull();
54
+ expect(stripBase("/about", "/repo")).toBeNull();
55
+ expect(stripBase("/about", "")).toBe("/about");
56
+ });
57
+ });
58
+
59
+ describe("extractLinks under a base", () => {
60
+ const page = `<a href="/repo/a">a</a> <a href="/repo">home</a> <a href="/other">no</a> <a href="/repo/f.xml">no</a>`;
61
+ test("strips the base and skips links outside it", () => {
62
+ expect(extractLinks(page, "http://localhost", "/repo").sort()).toEqual(["/", "/a"]);
63
+ });
64
+ });
65
+
66
+ describe("a server under a base", () => {
67
+ let dir: string;
68
+ beforeAll(async () => {
69
+ dir = join(tmpdir(), `grimoire-base-${Date.now()}`);
70
+ await mkdir(join(dir, "where"), { recursive: true });
71
+ await mkdir(join(dir, "go"), { recursive: true });
72
+ await writeFile(
73
+ join(dir, "where", "+server.ts"),
74
+ "export const GET = ({ url }) => new Response(url.pathname + url.search);",
75
+ );
76
+ await writeFile(
77
+ join(dir, "go", "+server.ts"),
78
+ "export const GET = () => new Response(null, { status: 302, headers: { Location: '/repo/where' } });",
79
+ );
80
+ });
81
+ afterAll(async () => {
82
+ setBase("");
83
+ await rm(dir, { recursive: true, force: true });
84
+ });
85
+
86
+ const make = () =>
87
+ createApp({
88
+ routes: dir,
89
+ base: "/repo",
90
+ _skipBuild: true,
91
+ _forceProduction: true,
92
+ });
93
+ const get = (app: { fetch(r: Request): Response | Promise<Response> }, path: string) =>
94
+ Promise.resolve(app.fetch(new Request(`http://localhost${path}`)));
95
+
96
+ test("routes see the route path, not the full one", async () => {
97
+ const app = await make();
98
+ const res = await get(app, "/repo/where?x=1");
99
+ expect(res.status).toBe(200);
100
+ expect(await res.text()).toBe("/where?x=1");
101
+ });
102
+
103
+ test("a path outside the base is a 404", async () => {
104
+ const app = await make();
105
+ expect((await get(app, "/where")).status).toBe(404);
106
+ expect((await get(app, "/repository/where")).status).toBe(404);
107
+ });
108
+
109
+ test("/repo goes to /repo/, keeping the query", async () => {
110
+ const app = await make();
111
+ const res = await get(app, "/repo?a=1");
112
+ expect(res.status).toBe(308);
113
+ expect(res.headers.get("location")).toBe("/repo/?a=1");
114
+ });
115
+
116
+ test("a redirect the route wrote is passed through as written", async () => {
117
+ const app = await make();
118
+ const res = await get(app, "/repo/go");
119
+ expect(res.headers.get("location")).toBe("/repo/where");
120
+ });
121
+
122
+ test("in dev the 404 names the URL it should have been", () => {
123
+ const text = outsideBaseMessage("/where", "/repo", true);
124
+ expect(text).toContain("/repo/where");
125
+ expect(text).toContain('withBase("/where")');
126
+ expect(outsideBaseMessage("/where", "/repo", false)).toBe("Not found");
127
+ });
128
+
129
+ test("a bad base stops startup", async () => {
130
+ await expect(
131
+ createApp({ routes: dir, base: "/repo/", _skipBuild: true, _forceProduction: true }),
132
+ ).rejects.toThrow(/must not end with a slash/);
133
+ });
134
+ });