@krate/runtime 0.5.0-rc.1 → 0.5.0-rc.3

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 (153) hide show
  1. package/dist/actions.d.ts +7 -0
  2. package/dist/actions.js +23 -8
  3. package/dist/actions.test.js +8 -410
  4. package/dist/after.d.ts +28 -0
  5. package/dist/after.js +48 -0
  6. package/dist/after.test.js +58 -0
  7. package/dist/assets-static.d.ts +10 -1
  8. package/dist/assets-static.js +10 -2
  9. package/dist/base-path.d.ts +7 -0
  10. package/dist/base-path.js +20 -0
  11. package/dist/builtin-tags.d.ts +12 -0
  12. package/dist/builtin-tags.js +42 -0
  13. package/dist/builtin-tags.test.js +12 -0
  14. package/dist/cache-adapter.test.js +4 -203
  15. package/dist/cache-scope.d.ts +2 -0
  16. package/dist/cache.test.js +1 -197
  17. package/dist/cloudflare-workers.d.ts +2 -0
  18. package/dist/cloudflare-workers.js +27 -0
  19. package/dist/dev-overlay.d.ts +54 -3
  20. package/dist/dev-overlay.js +469 -76
  21. package/dist/dom.js +17 -2
  22. package/dist/events.test.js +2 -407
  23. package/dist/handler-html.test.js +1 -202
  24. package/dist/handler-routing.js +3 -0
  25. package/dist/handler-segments.d.ts +6 -0
  26. package/dist/handler-segments.js +16 -2
  27. package/dist/handler-segments.test.js +8 -200
  28. package/dist/head-tags.d.ts +9 -0
  29. package/dist/head-tags.js +85 -1
  30. package/dist/head-tags.test.js +18 -125
  31. package/dist/index.d.ts +1 -0
  32. package/dist/index.js +3 -0
  33. package/dist/inline-action-token.test.js +31 -0
  34. package/dist/jsx-svg-types.test.js +58 -0
  35. package/dist/jsx-types.d.ts +92 -1
  36. package/dist/krate-core.js +1 -1
  37. package/dist/krate-dev.js +384 -65
  38. package/dist/krate-f-actions.js +1 -1
  39. package/dist/krate-f-navigation.js +1 -1
  40. package/dist/krate-f-router-lite.js +1 -1
  41. package/dist/krate-f-router.js +1 -1
  42. package/dist/krate-features.json +2 -0
  43. package/dist/krate-hydrate-lite.js +5 -5
  44. package/dist/krate-hydrate.js +5 -5
  45. package/dist/krate-runtime.js +5 -5
  46. package/dist/link-base-path.test.js +28 -0
  47. package/dist/metadata.js +3 -0
  48. package/dist/node-server.test.js +1 -355
  49. package/dist/platform.d.ts +52 -0
  50. package/dist/platform.js +57 -0
  51. package/dist/platform.test.js +44 -0
  52. package/dist/router-lite.js +3 -9
  53. package/dist/router-nav.test.js +15 -444
  54. package/dist/router.js +51 -18
  55. package/dist/server-handler.d.ts +49 -0
  56. package/dist/server-handler.js +311 -21
  57. package/dist/server-handler.test.js +56 -344
  58. package/dist/server-renderer.test.js +0 -104
  59. package/dist/server.d.ts +15 -5
  60. package/dist/server.js +150 -22
  61. package/dist/server.test.js +52 -60
  62. package/dist/site-config.d.ts +13 -0
  63. package/dist/site-config.js +28 -0
  64. package/dist/site-config.test.js +30 -0
  65. package/dist/ssr-core-behavior.test.js +3 -515
  66. package/dist/testing.d.ts +59 -0
  67. package/dist/testing.js +88 -0
  68. package/dist/testing.test.js +73 -0
  69. package/package.json +9 -1
  70. package/dist/action-context.test.js +0 -72
  71. package/dist/class-component.test.js +0 -462
  72. package/dist/class-helpers.test.js +0 -169
  73. package/dist/context.test.js +0 -57
  74. package/dist/derived.test.js +0 -140
  75. package/dist/dev-overlay.test.js +0 -165
  76. package/dist/discrete.test.js +0 -100
  77. package/dist/dom.test.js +0 -39
  78. package/dist/effect-errors.test.d.ts +0 -1
  79. package/dist/effect-errors.test.js +0 -199
  80. package/dist/effects.test.d.ts +0 -1
  81. package/dist/effects.test.js +0 -485
  82. package/dist/handler-routing.test.d.ts +0 -1
  83. package/dist/handler-routing.test.js +0 -99
  84. package/dist/highlight-bind.test.d.ts +0 -1
  85. package/dist/highlight-bind.test.js +0 -124
  86. package/dist/highlight.test.d.ts +0 -1
  87. package/dist/highlight.test.js +0 -56
  88. package/dist/lanes.test.d.ts +0 -1
  89. package/dist/lanes.test.js +0 -59
  90. package/dist/list.test.d.ts +0 -1
  91. package/dist/list.test.js +0 -435
  92. package/dist/metadata.test.d.ts +0 -1
  93. package/dist/metadata.test.js +0 -167
  94. package/dist/navigation.test.d.ts +0 -1
  95. package/dist/navigation.test.js +0 -130
  96. package/dist/optimistic-lanes.test.d.ts +0 -1
  97. package/dist/optimistic-lanes.test.js +0 -45
  98. package/dist/patterns.test.d.ts +0 -1
  99. package/dist/patterns.test.js +0 -125
  100. package/dist/portal.test.d.ts +0 -1
  101. package/dist/portal.test.js +0 -99
  102. package/dist/react-effects.test.d.ts +0 -1
  103. package/dist/react-effects.test.js +0 -133
  104. package/dist/react-suspense.test.d.ts +0 -1
  105. package/dist/react-suspense.test.js +0 -194
  106. package/dist/react.test.d.ts +0 -1
  107. package/dist/react.test.js +0 -60
  108. package/dist/react19.test.d.ts +0 -1
  109. package/dist/react19.test.js +0 -176
  110. package/dist/reactivity-core.test.d.ts +0 -1
  111. package/dist/reactivity-core.test.js +0 -152
  112. package/dist/reconcile.test.d.ts +0 -1
  113. package/dist/reconcile.test.js +0 -110
  114. package/dist/refs.test.d.ts +0 -1
  115. package/dist/refs.test.js +0 -257
  116. package/dist/router-layout.test.d.ts +0 -1
  117. package/dist/router-layout.test.js +0 -249
  118. package/dist/router-slots.test.d.ts +0 -1
  119. package/dist/router-slots.test.js +0 -144
  120. package/dist/router-speculation.test.d.ts +0 -1
  121. package/dist/router-speculation.test.js +0 -25
  122. package/dist/router-styles.test.d.ts +0 -1
  123. package/dist/router-styles.test.js +0 -98
  124. package/dist/router.test.d.ts +0 -1
  125. package/dist/router.test.js +0 -36
  126. package/dist/server-async.test.d.ts +0 -1
  127. package/dist/server-async.test.js +0 -216
  128. package/dist/server-highlight.test.d.ts +0 -1
  129. package/dist/server-highlight.test.js +0 -32
  130. package/dist/signal-lanes.test.d.ts +0 -1
  131. package/dist/signal-lanes.test.js +0 -32
  132. package/dist/slots.test.d.ts +0 -1
  133. package/dist/slots.test.js +0 -187
  134. package/dist/snapshots.test.d.ts +0 -1
  135. package/dist/snapshots.test.js +0 -208
  136. package/dist/ssr-core.test.d.ts +0 -1
  137. package/dist/ssr-core.test.js +0 -324
  138. package/dist/static-memory.test.d.ts +0 -1
  139. package/dist/static-memory.test.js +0 -26
  140. package/dist/storage.test.d.ts +0 -1
  141. package/dist/storage.test.js +0 -46
  142. package/dist/suspense-actions.test.d.ts +0 -1
  143. package/dist/suspense-actions.test.js +0 -72
  144. package/dist/suspense.test.d.ts +0 -1
  145. package/dist/suspense.test.js +0 -556
  146. /package/dist/{action-context.test.d.ts → after.test.d.ts} +0 -0
  147. /package/dist/{class-component.test.d.ts → builtin-tags.test.d.ts} +0 -0
  148. /package/dist/{class-helpers.test.d.ts → inline-action-token.test.d.ts} +0 -0
  149. /package/dist/{context.test.d.ts → jsx-svg-types.test.d.ts} +0 -0
  150. /package/dist/{derived.test.d.ts → link-base-path.test.d.ts} +0 -0
  151. /package/dist/{dev-overlay.test.d.ts → platform.test.d.ts} +0 -0
  152. /package/dist/{discrete.test.d.ts → site-config.test.d.ts} +0 -0
  153. /package/dist/{dom.test.d.ts → testing.test.d.ts} +0 -0
@@ -1,6 +1,6 @@
1
1
  // @vitest-environment node
2
2
  import { describe, expect, it, vi } from "vitest";
3
- import { createKrateHandler } from "./server-handler.js";
3
+ import { createKrateHandler, matchMetaRoute } from "./server-handler.js";
4
4
  import { jsx } from "./server.js";
5
5
  const config = {
6
6
  basePath: "",
@@ -61,19 +61,6 @@ describe("createKrateHandler", () => {
61
61
  expect(r.headers.get("permissions-policy")).toBeNull();
62
62
  expect((await get("/new")).headers.get("x-rule")).toBe("yes");
63
63
  });
64
- it("serves ISR pages from the cache with the CDN policy", async () => {
65
- const a = await get("/live/");
66
- const b = await get("/live/");
67
- expect(a.headers.get("cache-control")).toBe("public, s-maxage=30, stale-while-revalidate=60");
68
- expect(a.headers.get("x-krate-cache")).toBe("MISS");
69
- expect(b.headers.get("x-krate-cache")).toBe("HIT");
70
- expect(await b.text()).toContain("render 1");
71
- expect(renders).toBe(1);
72
- });
73
- it("runs middleware and answers its responses", async () => {
74
- expect((await get("/blocked")).status).toBe(403);
75
- expect((await get("/api/hello")).headers.get("x-mw")).toBe("1");
76
- });
77
64
  it("routes API requests with 404, 405 and params", async () => {
78
65
  expect(await (await get("/api/items/7")).json()).toEqual({ id: "7" });
79
66
  expect((await get("/api/none")).status).toBe(404);
@@ -89,65 +76,39 @@ describe("createKrateHandler", () => {
89
76
  const bad = await get("/__krate/action/act1", { method: "POST", headers: { ...headers, "sec-fetch-site": "cross-site" }, body: "{}" });
90
77
  expect(bad.status).toBe(403);
91
78
  });
92
- it("answers unknown pages with the custom 404 and hides internals", async () => {
93
- const r = await get("/nope/");
94
- expect(r.status).toBe(404);
95
- expect(await r.text()).toContain("custom 404");
96
- expect((await get("/.krate/x")).status).toBe(404);
97
- });
98
- it("reports revalidation honestly on multi-instance targets", async () => {
99
- let seen;
100
- const h = createKrateHandler({
101
- target: "vercel",
102
- data: data({ actions: [{ id: "rv", export: "rv", file: "acts" }] }),
103
- modules: {
104
- ...modules,
105
- actions: { acts: { rv: async () => { const { revalidatePath } = await import("./cache.js"); revalidatePath("/live"); return 1; } } },
106
- },
107
- });
108
- const res = await h(new Request("http://localhost/__krate/action/rv", { method: "POST", headers: { "x-krate-action": "fetch", "content-type": "application/json", "sec-fetch-site": "same-origin" }, body: '{"args":[]}' }));
109
- seen = await res.json();
110
- expect(seen.revalidated).toBe(true);
111
- expect(seen.revalidation.paths).toEqual([{ path: "/live", type: "page" }]);
112
- });
113
79
  });
114
- describe("middleware without a matcher", () => {
115
- const seen = [];
116
- const mw = {
117
- middleware: (req) => {
118
- const p = new URL(req.url).pathname;
119
- seen.push(p);
120
- if (req.headers.get("x-auth") !== "yes")
121
- return new Response("denied", { status: 401 });
122
- return new Response(null, { headers: { "x-middleware-next": "1" } });
80
+ describe("API maxDuration", () => {
81
+ const sleep = (ms, signal) => new Promise((resolve) => {
82
+ const t = setTimeout(() => resolve(false), ms);
83
+ signal.addEventListener("abort", () => (clearTimeout(t), resolve(true)), { once: true });
84
+ });
85
+ let sawAbort = false;
86
+ const mods = {
87
+ ...modules,
88
+ api: {
89
+ ...modules.api,
90
+ slow: { GET: async (r) => ((sawAbort = await sleep(2000, r.signal)), Response.json({ late: true })) },
91
+ ok: { GET: async (r) => (await sleep(50, r.signal), Response.json({ done: true })) },
123
92
  },
124
93
  };
125
- const staticLayer = {
126
- exists: (p) => p === "/doc.pdf",
127
- isAsset: (p) => p === "/doc.pdf",
128
- serve: async (_r, p) => (p === "/doc.pdf" ? new Response("pdf") : null),
129
- };
130
94
  const h = createKrateHandler({
131
95
  target: "node",
132
- data: data({ apiRoutes: ["files/[name]"] }),
133
- modules: { ...modules, api: { "files/[name]": { GET: () => Response.json({ secret: "TOP" }) } }, middleware: mw },
134
- static: staticLayer,
96
+ data: data({ hasMiddleware: false, apiRoutes: ["slow", "ok"], apiMaxDuration: { slow: 0.1, ok: 5 } }),
97
+ modules: mods,
135
98
  });
136
99
  const get = (path) => h(new Request("http://localhost" + path));
137
- it("does not skip dynamic API routes that end in a static extension", async () => {
138
- for (const ext of ["pdf", "txt", "xml", "zip", "js", "css"]) {
139
- const r = await get("/api/files/report." + ext);
140
- expect(r.status, ext).toBe(401);
141
- }
142
- });
143
- it("still skips a real static file", async () => {
144
- seen.length = 0;
145
- const r = await get("/doc.pdf");
100
+ it("answers 504 and aborts request.signal at the deadline", async () => {
101
+ const err = vi.spyOn(console, "error").mockImplementation(() => { });
102
+ const r = await get("/api/slow");
103
+ expect(r.status).toBe(504);
104
+ expect(await r.json()).toEqual({ error: "Gateway Timeout" });
105
+ expect(sawAbort).toBe(true);
106
+ err.mockRestore();
107
+ });
108
+ it("lets a handler that finishes inside its budget through", async () => {
109
+ const r = await get("/api/ok");
146
110
  expect(r.status).toBe(200);
147
- expect(seen).not.toContain("/doc.pdf");
148
- });
149
- it("runs middleware for a static-looking page path that is not a file", async () => {
150
- expect((await get("/missing.pdf")).status).toBe(401);
111
+ expect(await r.json()).toEqual({ done: true });
151
112
  });
152
113
  });
153
114
  describe("canonical slash redirect", () => {
@@ -166,108 +127,6 @@ describe("canonical slash redirect", () => {
166
127
  expect(new URL(loc, "http://localhost/plain/" + seg).origin, seg).toBe("http://localhost");
167
128
  }
168
129
  });
169
- it("keeps the query on an ordinary segment", async () => {
170
- const r = await get("/plain/7?a=1");
171
- expect(r.headers.get("location")).toBe("./7/?a=1");
172
- });
173
- });
174
- describe("action cookies", () => {
175
- const h = createKrateHandler({
176
- target: "node",
177
- data: data({ hasMiddleware: false, actions: [{ id: "setc", export: "setc", file: "acts" }, { id: "flash", export: "flash", file: "acts" }] }),
178
- modules: {
179
- ...modules,
180
- actions: {
181
- acts: {
182
- setc: async () => {
183
- const { cookies } = await import("./action-context.js");
184
- cookies().set("none", "1", { sameSite: "None" });
185
- cookies().set("plain", "2");
186
- cookies().set("optout", "3", { secure: false });
187
- return 1;
188
- },
189
- flash: () => ({ error: "bad" }),
190
- },
191
- },
192
- },
193
- });
194
- const post = (id, headers) => h(new Request("http://localhost/__krate/action/" + id, { method: "POST", headers: { "sec-fetch-site": "same-origin", ...headers }, body: "{}" }));
195
- const cookiesOf = (r) => r.headers.getSetCookie();
196
- it("marks SameSite=None cookies Secure and defaults Secure on https", async () => {
197
- const insecure = cookiesOf(await post("setc", { "x-krate-action": "fetch", "content-type": "application/json" }));
198
- expect(insecure.find((c) => c.startsWith("none="))).toContain("; Secure");
199
- expect(insecure.find((c) => c.startsWith("plain="))).not.toContain("Secure");
200
- const https = cookiesOf(await post("setc", { "x-krate-action": "fetch", "content-type": "application/json", "x-forwarded-proto": "https" }));
201
- expect(https.find((c) => c.startsWith("plain="))).toContain("; Secure");
202
- expect(https.find((c) => c.startsWith("optout="))).not.toContain("Secure");
203
- });
204
- it("marks the flash cookie Secure on https", async () => {
205
- const r = await post("flash", { "content-type": "application/x-www-form-urlencoded", "x-forwarded-proto": "https", referer: "http://localhost/form" });
206
- const flash = cookiesOf(r).find((c) => c.startsWith("krate_flash="));
207
- expect(flash).toContain("; Secure");
208
- });
209
- });
210
- describe("rewrites to a slashless page path", () => {
211
- const h = createKrateHandler({
212
- target: "node",
213
- data: data({
214
- hasMiddleware: true,
215
- templates: [{ pattern: "feedback", html: "<p>feedback form</p>" }],
216
- config: { ...config, rewrites: [{ source: "/contact", destination: "/feedback" }] },
217
- }),
218
- modules: {
219
- ...modules,
220
- middleware: {
221
- middleware: (req) => {
222
- if (new URL(req.url).pathname === "/go")
223
- return new Response(null, { headers: { "x-middleware-rewrite": "/feedback" } });
224
- return undefined;
225
- },
226
- config: { matcher: ["/go"] },
227
- },
228
- },
229
- static: {
230
- exists: (p) => p === "/feedback/",
231
- isAsset: () => false,
232
- serve: async (_r, p) => (p === "/feedback/" ? new Response("<p>feedback form</p>", { headers: { "content-type": "text/html" } }) : null),
233
- },
234
- });
235
- const get = (path) => h(new Request("http://localhost" + path, { redirect: "manual" }));
236
- it("serves a middleware rewrite in place (no 301)", async () => {
237
- const r = await get("/go");
238
- expect(r.status).toBe(200);
239
- expect(await r.text()).toContain("feedback form");
240
- });
241
- it("serves a config rewrite in place (no 301)", async () => {
242
- const r = await get("/contact");
243
- expect(r.status).toBe(200);
244
- expect(await r.text()).toContain("feedback form");
245
- });
246
- });
247
- describe("page region title swap", () => {
248
- it("keeps the page markers intact when the title length changes", async () => {
249
- const h = createKrateHandler({
250
- target: "node",
251
- data: data({
252
- pages: [{ route: "/titled", mode: "ssr", bundlePath: "titled" }],
253
- allPages: [{ route: "/titled", mode: "ssr" }],
254
- shells: { "/titled": "<html><head><title>t</title></head><body><!--suspense:page-->baked<!--/suspense:page--></body></html>" },
255
- hasMiddleware: false,
256
- }),
257
- modules: {
258
- ...modules,
259
- pages: {
260
- titled: {
261
- default: () => jsx("div", { children: [jsx("title", { children: "A much longer title" }), jsx("h1", { children: "hello" })] }),
262
- },
263
- },
264
- },
265
- });
266
- const r = await h(new Request("http://localhost/titled/"));
267
- const body = await r.text();
268
- expect(body).toContain("<title>A much longer title</title></head><body><!--suspense:page--><div><h1>hello</h1></div><!--/suspense:page--></body>");
269
- expect(body.match(/<title/g)?.length).toBe(1);
270
- });
271
130
  });
272
131
  describe("signed flash cookies", () => {
273
132
  const shell = "<html><head><title>t</title></head><body><!--suspense:page-->baked<!--/suspense:page--></body></html>";
@@ -290,23 +149,7 @@ describe("signed flash cookies", () => {
290
149
  actions: { acts: { bad: () => ({ error: "Name is required" }) } },
291
150
  },
292
151
  });
293
- const submit = (h) => h(new Request("http://localhost/__krate/action/act9", {
294
- method: "POST",
295
- headers: { "sec-fetch-site": "same-origin", "content-type": "application/x-www-form-urlencoded", referer: "http://localhost/form/" },
296
- body: "x=1",
297
- }));
298
- const flashOf = (r) => r.headers.getSetCookie().find((c) => c.startsWith("krate_flash="));
299
152
  const page = (h, cookie) => h(new Request("http://localhost/form/", { headers: { cookie } }));
300
- it("signs the cookie and shows the notice when it comes back", async () => {
301
- const h = mk("node", "a-shared-flash-secret-for-this-test");
302
- const set = flashOf(await submit(h));
303
- expect(set).toBeDefined();
304
- const value = set.split(";")[0].slice("krate_flash=".length);
305
- expect(value).toMatch(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{43}$/);
306
- const body = await (await page(h, "krate_flash=" + value)).text();
307
- expect(body).toContain("krate-flash");
308
- expect(body).toContain("Name is required");
309
- });
310
153
  it("ignores a cookie planted without a valid signature", async () => {
311
154
  const h = mk("node", "a-shared-flash-secret-for-this-test");
312
155
  const planted = Buffer.from(JSON.stringify({ a: "act9", r: { error: "Your account was suspended" } })).toString("base64url");
@@ -316,65 +159,6 @@ describe("signed flash cookies", () => {
316
159
  expect(body, cookie).not.toContain("krate-flash");
317
160
  }
318
161
  });
319
- it("serverless instances that share the secret accept each other's cookies, others do not", async () => {
320
- const a = mk("vercel", "a-shared-flash-secret-for-this-test");
321
- const b = mk("vercel", "a-shared-flash-secret-for-this-test");
322
- const stranger = mk("vercel", "some-other-deployments-secret-value");
323
- const value = flashOf(await submit(a)).split(";")[0].slice("krate_flash=".length);
324
- expect(await (await page(b, "krate_flash=" + value)).text()).toContain("Name is required");
325
- expect(await (await page(stranger, "krate_flash=" + value)).text()).not.toContain("Name is required");
326
- });
327
- it("the node target without a secret signs with a per-process key", async () => {
328
- const saved = process.env.KRATE_FLASH_SECRET;
329
- delete process.env.KRATE_FLASH_SECRET;
330
- try {
331
- const one = mk("node");
332
- const other = mk("node");
333
- const value = flashOf(await submit(one)).split(";")[0].slice("krate_flash=".length);
334
- expect(value).toContain(".");
335
- expect(await (await page(one, "krate_flash=" + value)).text()).toContain("Name is required");
336
- expect(await (await page(other, "krate_flash=" + value)).text()).not.toContain("Name is required");
337
- }
338
- finally {
339
- if (saved !== undefined)
340
- process.env.KRATE_FLASH_SECRET = saved;
341
- }
342
- });
343
- it("a serverless target without a secret carries no flash and says why", async () => {
344
- const saved = process.env.KRATE_FLASH_SECRET;
345
- delete process.env.KRATE_FLASH_SECRET;
346
- const warn = vi.spyOn(console, "warn").mockImplementation(() => { });
347
- try {
348
- const h = mk("cloudflare");
349
- const r = await submit(h);
350
- expect(r.status).toBe(303);
351
- expect(flashOf(r)).toBeUndefined();
352
- expect(warn).toHaveBeenCalledWith(expect.stringContaining("KRATE_FLASH_SECRET"));
353
- // A cookie from anywhere is not read either.
354
- const planted = Buffer.from(JSON.stringify({ a: "act9", r: { error: "planted" } })).toString("base64url");
355
- expect(await (await page(h, "krate_flash=" + planted)).text()).not.toContain("planted");
356
- }
357
- finally {
358
- warn.mockRestore();
359
- if (saved !== undefined)
360
- process.env.KRATE_FLASH_SECRET = saved;
361
- }
362
- });
363
- it("reads the key from KRATE_FLASH_SECRET", async () => {
364
- const saved = process.env.KRATE_FLASH_SECRET;
365
- process.env.KRATE_FLASH_SECRET = "env-flash-secret-env-flash-secret";
366
- try {
367
- const h = mk("vercel");
368
- const value = flashOf(await submit(h)).split(";")[0].slice("krate_flash=".length);
369
- expect(await (await page(mk("vercel"), "krate_flash=" + value)).text()).toContain("Name is required");
370
- }
371
- finally {
372
- if (saved === undefined)
373
- delete process.env.KRATE_FLASH_SECRET;
374
- else
375
- process.env.KRATE_FLASH_SECRET = saved;
376
- }
377
- });
378
162
  });
379
163
  describe("forwarded headers per platform", () => {
380
164
  const mk = (target, trustProxy) => {
@@ -402,53 +186,11 @@ describe("forwarded headers per platform", () => {
402
186
  const echo = async (h, headers) => (await h(new Request("http://app.internal/api/echo", { headers }))).json();
403
187
  // What a hostile client adds on top of whatever the platform sets.
404
188
  const spoof = { "x-forwarded-host": "evil.example", "x-forwarded-proto": "https", "x-forwarded-for": "6.6.6.6, 7.7.7.7", "x-real-ip": "6.6.6.6", forwarded: "for=6.6.6.6;host=evil.example" };
405
- it("vercel: uses the host, protocol and client address Vercel sets", async () => {
406
- const out = await echo(mk("vercel"), { "x-forwarded-host": "shop.example", "x-forwarded-proto": "https", "x-forwarded-for": "203.0.113.9", "x-real-ip": "203.0.113.9", forwarded: "for=6.6.6.6" });
407
- expect(out.url).toBe("https://shop.example/api/echo");
408
- expect(out.xff).toBe("203.0.113.9");
409
- expect(out.realIp).toBe("203.0.113.9");
410
- expect(out.forwarded).toBeNull();
411
- });
412
189
  it("vercel: a client-written forwarded chain never becomes the client address", async () => {
413
190
  const out = await echo(mk("vercel"), { ...spoof, "x-forwarded-host": "shop.example", "x-real-ip": "203.0.113.9" });
414
191
  expect(out.xff).toBe("203.0.113.9");
415
192
  expect(out.forwarded).toBeNull();
416
193
  });
417
- it("vercel with server.trustProxy: false trusts no forwarded header", async () => {
418
- const out = await echo(mk("vercel", false), { "x-forwarded-host": "shop.example", "x-forwarded-proto": "https", "x-forwarded-for": "203.0.113.9", "x-real-ip": "203.0.113.9" });
419
- expect(out.url).toBe("http://app.internal/api/echo");
420
- expect(out.host).toBe("app.internal");
421
- expect(out.proto).toBe("http");
422
- expect(out.xff).toBeNull();
423
- expect(out.realIp).toBeNull();
424
- });
425
- for (const [target, ipHeader] of [["netlify", "x-nf-client-connection-ip"], ["cloudflare", "cf-connecting-ip"]]) {
426
- it(`${target}: host and protocol come from the request URL, the address from ${ipHeader}`, async () => {
427
- const out = await echo(mk(target), { ...spoof, [ipHeader]: "203.0.113.9" });
428
- expect(out.url).toBe("http://app.internal/api/echo");
429
- expect(out.host).toBe("app.internal");
430
- expect(out.proto).toBe("http");
431
- expect(out.xff).toBe("203.0.113.9");
432
- expect(out.realIp).toBe("203.0.113.9");
433
- expect(out.forwarded).toBeNull();
434
- });
435
- it(`${target}: without the platform address header there is no client address`, async () => {
436
- const out = await echo(mk(target), spoof);
437
- expect(out.xff).toBeNull();
438
- expect(out.realIp).toBeNull();
439
- });
440
- it(`${target} with server.trustProxy: true trusts the proxy of yours in front`, async () => {
441
- const out = await echo(mk(target, true), { ...spoof, [ipHeader]: "203.0.113.9" });
442
- expect(out.url).toBe("https://evil.example/api/echo");
443
- expect(out.xff).toBe("6.6.6.6, 7.7.7.7");
444
- });
445
- it(`${target} with server.trustProxy: false ignores everything forwarded, the platform address included`, async () => {
446
- const out = await echo(mk(target, false), { ...spoof, [ipHeader]: "203.0.113.9" });
447
- expect(out.url).toBe("http://app.internal/api/echo");
448
- expect(out.xff).toBeNull();
449
- expect(out.realIp).toBeNull();
450
- });
451
- }
452
194
  it("the server-action origin check is not fooled by a spoofed X-Forwarded-Host", async () => {
453
195
  const post = (h) => h(new Request("http://app.internal/__krate/action/act1", {
454
196
  method: "POST",
@@ -463,69 +205,9 @@ describe("forwarded headers per platform", () => {
463
205
  // Behind a proxy of yours that sets the header, it is the real host.
464
206
  expect((await post(mk("cloudflare", true))).status).toBe(200);
465
207
  });
466
- it("node: forwarded headers are read only with trustProxy: true", async () => {
467
- const headers = { "x-forwarded-host": "shop.example", "x-forwarded-proto": "https" };
468
- expect((await echo(mk("node"), headers)).url).toBe("http://app.internal/api/echo");
469
- expect((await echo(mk("node", true), headers)).url).toBe("https://shop.example/api/echo");
470
- });
471
- });
472
- // Serverless targets run many instances. Passing a cache adapter to
473
- // createKrateHandler (or setting cache.adapter in krate.config) shares the ISR
474
- // and data caches between them, and revalidateTag on one reaches the others.
475
- describe("createKrateHandler with a shared cache adapter", () => {
476
- it("serves one instance's page from another and revalidates for both", async () => {
477
- const { MemoryAdapter } = await import("./cache-adapter.js");
478
- const { revalidateTag } = await import("./cache.js");
479
- let renders = 0;
480
- const shared = new MemoryAdapter();
481
- const make = () => createKrateHandler({
482
- target: "vercel",
483
- data: data({
484
- apiRoutes: ["bump"],
485
- pages: [{ route: "/tagged", mode: "isr", revalidate: 300, bundlePath: "tagged" }],
486
- allPages: [{ route: "/tagged", mode: "isr" }],
487
- shells: { "/tagged": "<html><head></head><body><!--suspense:page-->x<!--/suspense:page--></body></html>" },
488
- hasMiddleware: false,
489
- }),
490
- modules: {
491
- pages: {
492
- tagged: {
493
- default: async () => {
494
- // A tagged read: revalidateTag("posts") must drop this page everywhere.
495
- const { recordCacheRead } = await import("./cache-scope.js");
496
- recordCacheRead(["posts"], undefined);
497
- return jsx("main", { children: "render " + ++renders });
498
- },
499
- },
500
- },
501
- api: { bump: { POST: () => (revalidateTag("posts"), Response.json({ ok: true })) } },
502
- actions: {},
503
- },
504
- cache: shared,
505
- });
506
- const a = make();
507
- const b = make();
508
- const get = (h, path, init) => h(new Request("http://localhost" + path, init));
509
- const first = await get(a, "/tagged/");
510
- expect(first.headers.get("x-krate-cache")).toBe("MISS");
511
- const other = await get(b, "/tagged/");
512
- expect(other.headers.get("x-krate-cache")).toBe("HIT");
513
- expect(await other.text()).toContain("render 1");
514
- expect(renders).toBe(1);
515
- const bump = await get(a, "/api/bump", { method: "POST" });
516
- expect(bump.status).toBe(200);
517
- const after = await get(b, "/tagged/");
518
- expect(after.headers.get("x-krate-cache")).toBe("MISS");
519
- expect(await after.text()).toContain("render 2");
520
- expect(renders).toBe(2);
521
- });
522
208
  });
523
209
  describe("middleware exports", () => {
524
- const deny = () => new Response("no", { status: 403 });
525
210
  const run = (middleware) => createKrateHandler({ target: "node", data: data(), modules: { ...modules, middleware } })(new Request("http://localhost/live"));
526
- it("runs a default export", async () => {
527
- expect((await run({ default: deny })).status).toBe(403);
528
- });
529
211
  it("fails closed when the module has no handler", async () => {
530
212
  const error = vi.spyOn(console, "error").mockImplementation(() => { });
531
213
  expect((await run({ other: 1 })).status).toBe(503);
@@ -533,3 +215,33 @@ describe("middleware exports", () => {
533
215
  error.mockRestore();
534
216
  });
535
217
  });
218
+ describe("per-request metadata routes", () => {
219
+ const metaRoutes = [
220
+ { path: "/robots.txt", key: "__krate_meta/robots" },
221
+ { prefix: "/sitemap/", suffix: ".xml", key: "__krate_meta/sitemap/[id]" },
222
+ ];
223
+ it("maps public URLs to API route keys", () => {
224
+ expect(matchMetaRoute(metaRoutes, "/robots.txt")).toBe("__krate_meta/robots");
225
+ expect(matchMetaRoute(metaRoutes, "/sitemap/3.xml")).toBe("__krate_meta/sitemap/3");
226
+ for (const p of ["/sitemap/.xml", "/sitemap/a/b.xml", "/robots.txt/x", "/other"])
227
+ expect(matchMetaRoute(metaRoutes, p)).toBe("");
228
+ expect(matchMetaRoute(undefined, "/robots.txt")).toBe("");
229
+ });
230
+ it("serves them through the API handler after middleware", async () => {
231
+ const handler = createKrateHandler({
232
+ target: "node",
233
+ data: data({ metaRoutes, apiRoutes: ["__krate_meta/robots", "__krate_meta/sitemap/[id]"], hasMiddleware: false }),
234
+ modules: {
235
+ api: {
236
+ "__krate_meta/robots": { GET: (r) => new Response("User-agent: *\n# " + new URL(r.url).pathname, { headers: { "content-type": "text/plain" } }) },
237
+ "__krate_meta/sitemap/[id]": { GET: (_r, ctx) => new Response("sitemap " + ctx.params.id) },
238
+ },
239
+ },
240
+ });
241
+ const robots = await handler(new Request("http://localhost/robots.txt"));
242
+ expect(robots.status).toBe(200);
243
+ expect(await robots.text()).toContain("User-agent: *");
244
+ expect(await (await handler(new Request("http://localhost/sitemap/7.xml"))).text()).toBe("sitemap 7");
245
+ expect((await handler(new Request("http://localhost/robots.txt", { method: "POST" }))).status).not.toBe(200);
246
+ });
247
+ });
@@ -140,10 +140,6 @@ describe.skipIf(!built)("server-renderer sidecar", () => {
140
140
  await stop();
141
141
  fs.rmSync(tmp, { recursive: true, force: true });
142
142
  });
143
- it("reports health with the number of SSR pages", async () => {
144
- const r = await fetch(url("/__krate/ssr/health"));
145
- expect(await r.json()).toEqual({ ok: true, pages: 6 });
146
- });
147
143
  describe("internal endpoints need the host's secret", () => {
148
144
  it("refuses regions, revalidation and direct renders without it", async () => {
149
145
  expect((await regions({ route: "/regions", url: "/regions" }, {})).res.status).toBe(403);
@@ -151,34 +147,8 @@ describe.skipIf(!built)("server-renderer sidecar", () => {
151
147
  expect((await fetch(url("/__krate/ssr/cache-invalidate"), { method: "POST", body: "{}", headers: { "x-krate-internal": "wrong" } })).status).toBe(403);
152
148
  expect((await fetch(url("/ssr/[id]"))).status).toBe(403);
153
149
  });
154
- it("answers 405 to a GET on a mutating endpoint, before the secret check", async () => {
155
- const r = await fetch(url("/__krate/ssr/revalidate"));
156
- expect(r.status).toBe(405);
157
- expect(r.headers.get("allow")).toBe("POST");
158
- });
159
- it("applies an authorised invalidation and reports the counts", async () => {
160
- const r = await fetch(url("/__krate/ssr/cache-invalidate"), { method: "POST", headers: secret, body: JSON.stringify({ tags: ["nothing"] }) });
161
- expect(r.status).toBe(200);
162
- expect(await r.json()).toMatchObject({ ok: true, workers: 1, isrEntries: 0, regionEntries: 0 });
163
- const bad = await fetch(url("/__krate/ssr/cache-invalidate"), { method: "POST", headers: secret, body: "{not json" });
164
- expect(bad.status).toBe(500);
165
- });
166
150
  });
167
151
  describe("direct page requests", () => {
168
- it("renders a request-time page; a direct request carries no params or query", async () => {
169
- // The Go host asks for regions instead and forwards both (see below).
170
- const r = await fetch(url("/ssr/[id]?q=1"), { headers: secret });
171
- expect(r.status).toBe(200);
172
- expect(r.headers.get("content-type")).toBe("text/html; charset=utf-8");
173
- expect(await r.text()).toContain("<p>q=</p>");
174
- });
175
- it("serves the build's 404 page for an unknown route and for notFound()", async () => {
176
- for (const p of ["/nowhere", "/missing"]) {
177
- const r = await fetch(url(p), { headers: secret });
178
- expect(r.status, p).toBe(404);
179
- expect(await r.text()).toBe("<h1>custom not found</h1>");
180
- }
181
- });
182
152
  it("serves the build's 500 page for a failing render, without the error text", async () => {
183
153
  const r = await fetch(url("/boom"), { headers: secret });
184
154
  expect(r.status).toBe(500);
@@ -188,79 +158,5 @@ describe.skipIf(!built)("server-renderer sidecar", () => {
188
158
  const digest = createHash("sha256").update("secret detail\nat x").digest("hex").slice(0, 10);
189
159
  expect(logs).toContain(`digest ${digest}`);
190
160
  });
191
- it("redirects with 307 and a Location header", async () => {
192
- const r = await fetch(url("/redirect"), { headers: secret, redirect: "manual" });
193
- expect(r.status).toBe(307);
194
- expect(r.headers.get("location")).toBe("/login");
195
- });
196
- it("marks ISR responses from the cache", async () => {
197
- const a = await fetch(url("/isr"), { headers: secret });
198
- const first = await a.text();
199
- expect(a.headers.get("x-krate-cache")).toBeNull();
200
- const b = await fetch(url("/isr"), { headers: secret });
201
- expect(b.headers.get("x-krate-cache")).toBe("HIT");
202
- expect(await b.text()).toBe(first);
203
- });
204
- });
205
- describe("/__krate/regions", () => {
206
- const body = (extra = {}) => ({ route: "/regions", url: "/regions", method: "GET", headers: {}, ...extra });
207
- it("streams frames as regions finish, not in document order, and ends with a count", async () => {
208
- const { res, frames } = await regions(body({ regions: [{ id: "slow" }, { id: "fast" }, { id: "price" }], params: { id: "9" } }));
209
- expect(res.headers.get("content-type")).toContain("application/x-ndjson");
210
- expect(res.headers.get("cache-control")).toBe("no-store");
211
- expect(frames[frames.length - 1]).toEqual({ type: "end", count: 3 });
212
- const ids = frames.filter((f) => f.type === "region").map((f) => f.id);
213
- expect(ids).toHaveLength(3);
214
- expect(ids.indexOf("slow")).toBe(2); // the 250ms region is written last
215
- const byId = Object.fromEntries(frames.filter((f) => f.type === "region").map((f) => [f.id, f.html]));
216
- expect(byId).toEqual({ slow: "<i>slow</i>", fast: "<i>fast</i>", price: "<b>12/9</b>" });
217
- });
218
- it("reports a failing server component region as a fatal error frame with a digest", async () => {
219
- const { frames } = await regions(body({ regions: [{ id: "bad" }, { id: "fast" }] }));
220
- const bad = frames.find((f) => f.id === "bad");
221
- expect(bad).toMatchObject({ type: "error", status: 500, fatal: true, error: "region failed" });
222
- expect(bad.digest).toMatch(/^[0-9a-f]{10}$/);
223
- expect(frames.find((f) => f.id === "fast")).toMatchObject({ type: "region", html: "<i>fast</i>" });
224
- expect(frames[frames.length - 1]).toEqual({ type: "end", count: 2 });
225
- });
226
- it("falls back to the manifest's regions when the host sends no list", async () => {
227
- const { frames } = await regions(body());
228
- expect(frames.filter((f) => f.type !== "end").map((f) => f.id).sort()).toEqual(["bad", "fast", "price", "slow"]);
229
- });
230
- it("skips an unknown region id, so its baked content stays", async () => {
231
- const { frames } = await regions(body({ regions: [{ id: "ghost" }] }));
232
- expect(frames).toEqual([{ type: "skip", id: "ghost" }, { type: "end", count: 1 }]);
233
- });
234
- it("renders a coarse page region through the page ISR path", async () => {
235
- const { frames } = await regions({ route: "/ssr/[id]", url: "/ssr/5", method: "GET", headers: {}, params: { id: "5" }, query: { q: "z" }, regions: [{ id: "page", kind: "page" }] });
236
- expect(frames[0]).toMatchObject({ type: "region", id: "page", kind: "page", status: 200, title: "T 5" });
237
- expect(String(frames[0].html)).toContain("<p>q=z</p>");
238
- });
239
- it("answers an unknown route with an error frame and an end frame", async () => {
240
- const { frames } = await regions({ route: "/none", url: "/none", method: "GET", headers: {} });
241
- expect(frames).toEqual([{ type: "error", status: 404, error: "no such page" }, { type: "end", count: 0 }]);
242
- });
243
- it("turns a malformed body into an error frame, not a crash", async () => {
244
- const res = await fetch(url("/__krate/regions"), { method: "POST", headers: secret, body: "{nope" });
245
- const frames = (await res.text()).split("\n").filter(Boolean).map((l) => JSON.parse(l));
246
- expect(frames[0]).toMatchObject({ type: "error", status: 500 });
247
- expect((await fetch(url("/__krate/ssr/health"))).status).toBe(200);
248
- });
249
161
  });
250
- it("keeps rendered ISR pages across a restart", async () => {
251
- // Warm an ISR variant, wait for the debounced write, bounce the process.
252
- const first = await (await fetch(url("/isr"), { headers: secret })).text();
253
- const deadline = Date.now() + 5000;
254
- while (!fs.existsSync(isrFile) && Date.now() < deadline)
255
- await new Promise((ok) => setTimeout(ok, 100));
256
- expect(fs.existsSync(isrFile)).toBe(true);
257
- const saved = JSON.parse(fs.readFileSync(isrFile, "utf-8"));
258
- expect(saved.entries.some((e) => e.key === "/isr" && e.html === first)).toBe(true);
259
- await stop();
260
- await start();
261
- const again = await fetch(url("/isr"), { headers: secret });
262
- expect(again.headers.get("x-krate-cache")).toBe("HIT");
263
- expect(await again.text()).toBe(first);
264
- expect(logs).toContain("Loaded 1 persisted ISR entries");
265
- }, 30000);
266
162
  });
package/dist/server.d.ts CHANGED
@@ -1,6 +1,10 @@
1
1
  export { getActionContext, headers, cookies, redirect } from './action-context.js';
2
2
  export type { ActionContext, ActionCookies, ActionCookieOptions } from './action-context.js';
3
3
  export { revalidatePath, revalidateTag, unstable_cache, unstable_noStore } from './cache.js';
4
+ export { after } from './after.js';
5
+ export { getPlatform, getCloudflareContext } from './platform.js';
6
+ export type { PlatformContext, PlatformTarget, PlatformExecutionContext, CloudflareContext, KrateCloudflareEnv } from './platform.js';
7
+ export type { AfterTask, KrateRequest, KrateRequestCookies, KrateNextURL } from './after.js';
4
8
  export type { RevalidatePathType, UnstableCacheOptions } from './cache.js';
5
9
  export { getRequestContext, notFound, forbidden, unauthorized } from './request-context.js';
6
10
  export { usePathname, useSearchParams, useParams, useRouter, useSelectedLayoutSegment, useSelectedLayoutSegments, permanentRedirect, } from './navigation-server.js';
@@ -55,13 +59,19 @@ interface SuspenseProps {
55
59
  export declare function Suspense(props: SuspenseProps): JSXNode;
56
60
  type ClientRender = (component: unknown, props: Record<string, unknown>, childrenHTML: string | null) => string;
57
61
  /**
58
- * clientBoundary wraps an export of a `"use client"` module for the server
59
- * bundle of a page that renders server components. The server renders the
60
- * component's initial HTML (render) into a <krate-island> marker carrying its
62
+ * clientBoundary wraps an export of a `"use client"` module, or a component
63
+ * of a React package, for the server bundle of a page that renders server
64
+ * components. The server renders the component's initial HTML (render) and,
65
+ * when it hydrates, puts it in a <krate-island> marker carrying its
61
66
  * serialized props; the per-module client chunk at src hydrates it in the
62
- * browser. Children are rendered on the server and passed as HTML.
67
+ * browser. A component without state or effects (hydrate false, an icon)
68
+ * is plain HTML. Children are rendered on the server and passed as HTML, or,
69
+ * when they hold client components of their own, as a tree that keeps those
70
+ * components in the same Preact tree. A namespace export (Radix's Dialog) is
71
+ * wrapped member by member. With `flight` the children always travel as a
72
+ * tree (a real-React island rebuilds them as elements, not HTML).
63
73
  */
64
- export declare function clientBoundary(moduleId: string, exportName: string, src: string, impl: unknown, render: ClientRender): unknown;
74
+ export declare function clientBoundary(moduleId: string, exportName: string, src: string, impl: unknown, render: ClientRender, hydrate?: boolean, flight?: boolean): unknown;
65
75
  export declare const HEAD_OPEN = "<!--krate-head-->";
66
76
  export declare const HEAD_CLOSE = "<!--/krate-head-->";
67
77
  export declare function Head(props: {