@krate/runtime 0.5.0-beta.1 → 0.5.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/actions.js +2 -1
- package/dist/assets-static.d.ts +5 -0
- package/dist/assets-static.js +31 -0
- package/dist/boundary.d.ts +12 -0
- package/dist/boundary.js +53 -13
- package/dist/cache-adapter.d.ts +113 -0
- package/dist/cache-adapter.js +217 -0
- package/dist/cache-adapter.test.d.ts +1 -0
- package/dist/cache-adapter.test.js +244 -0
- package/dist/cache-redis.d.ts +27 -0
- package/dist/cache-redis.js +110 -0
- package/dist/cache-scope.d.ts +25 -9
- package/dist/cache-scope.js +60 -12
- package/dist/cache.d.ts +1 -0
- package/dist/cache.js +3 -3
- package/dist/class-component.js +6 -0
- package/dist/class-component.test.js +53 -2
- package/dist/dev-overlay.js +10 -10
- package/dist/dom.d.ts +8 -0
- package/dist/dom.js +28 -0
- package/dist/effect-errors.test.d.ts +1 -0
- package/dist/effect-errors.test.js +163 -0
- package/dist/effects.d.ts +8 -0
- package/dist/effects.js +13 -0
- package/dist/error-overlay.js +4 -4
- package/dist/handler-html.d.ts +63 -0
- package/dist/handler-html.js +285 -0
- package/dist/handler-html.test.d.ts +1 -0
- package/dist/handler-html.test.js +256 -0
- package/dist/handler-routing.d.ts +83 -0
- package/dist/handler-routing.js +579 -0
- package/dist/handler-routing.test.d.ts +1 -0
- package/dist/handler-routing.test.js +99 -0
- package/dist/handler-segments.d.ts +43 -0
- package/dist/handler-segments.js +115 -0
- package/dist/handler-segments.test.d.ts +1 -0
- package/dist/handler-segments.test.js +217 -0
- package/dist/head-tags.d.ts +51 -0
- package/dist/head-tags.js +329 -0
- package/dist/head-tags.test.d.ts +1 -0
- package/dist/head-tags.test.js +131 -0
- package/dist/highlight-bind.d.ts +42 -0
- package/dist/highlight-bind.js +176 -0
- package/dist/highlight-bind.test.d.ts +1 -0
- package/dist/highlight-bind.test.js +124 -0
- package/dist/highlight.d.ts +93 -0
- package/dist/highlight.js +426 -0
- package/dist/highlight.test.d.ts +1 -0
- package/dist/highlight.test.js +56 -0
- package/dist/hints.d.ts +19 -0
- package/dist/hints.js +97 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +2 -0
- package/dist/jsx-types.d.ts +11 -0
- package/dist/krate-core.js +1 -1
- package/dist/krate-dev.js +10 -10
- package/dist/krate-f-actions.js +1 -1
- package/dist/krate-f-classes.js +5 -5
- package/dist/krate-f-highlight.js +2 -0
- package/dist/krate-f-list.js +1 -1
- package/dist/krate-f-navigation.js +2 -0
- package/dist/krate-f-router.js +1 -1
- package/dist/krate-features.json +254 -0
- package/dist/krate-hydrate-lite.js +5 -5
- package/dist/krate-hydrate.js +5 -5
- package/dist/krate-runtime.js +5 -5
- package/dist/list.js +4 -2
- package/dist/metadata-routes.d.ts +75 -0
- package/dist/metadata-routes.js +76 -0
- package/dist/metadata.d.ts +222 -0
- package/dist/metadata.js +452 -0
- package/dist/metadata.test.d.ts +1 -0
- package/dist/metadata.test.js +167 -0
- package/dist/navigation-server.d.ts +27 -0
- package/dist/navigation-server.js +90 -0
- package/dist/navigation.d.ts +37 -0
- package/dist/navigation.js +195 -0
- package/dist/navigation.test.d.ts +1 -0
- package/dist/navigation.test.js +130 -0
- package/dist/node-server.d.ts +22 -0
- package/dist/node-server.js +436 -0
- package/dist/node-server.test.d.ts +1 -0
- package/dist/node-server.test.js +492 -0
- package/dist/og-files.d.ts +2 -0
- package/dist/og-files.js +19 -0
- package/dist/og.d.ts +56 -0
- package/dist/og.js +156 -0
- package/dist/react.d.ts +47 -0
- package/dist/react.js +59 -1
- package/dist/react19.test.d.ts +1 -0
- package/dist/react19.test.js +176 -0
- package/dist/request-context.d.ts +23 -0
- package/dist/request-context.js +45 -0
- package/dist/resp.d.ts +55 -0
- package/dist/resp.js +239 -0
- package/dist/router-layout.test.js +70 -0
- package/dist/router-nav.test.js +27 -0
- package/dist/router.js +59 -4
- package/dist/segmented-lru.d.ts +19 -0
- package/dist/segmented-lru.js +87 -0
- package/dist/server-async.test.js +23 -1
- package/dist/server-handler.d.ts +165 -0
- package/dist/server-handler.js +1826 -0
- package/dist/server-handler.test.d.ts +1 -0
- package/dist/server-handler.test.js +522 -0
- package/dist/server-highlight.test.d.ts +1 -0
- package/dist/server-highlight.test.js +32 -0
- package/dist/server-renderer.js +146 -788
- package/dist/server-renderer.test.d.ts +1 -0
- package/dist/server-renderer.test.js +266 -0
- package/dist/server.d.ts +12 -1
- package/dist/server.js +42 -6
- package/dist/sha256.d.ts +1 -0
- package/dist/sha256.js +66 -0
- package/dist/sha256.test.d.ts +1 -0
- package/dist/sha256.test.js +13 -0
- package/dist/shared-isr.d.ts +31 -0
- package/dist/shared-isr.js +142 -0
- package/dist/signal.js +63 -8
- package/dist/ssr-core-behavior.test.d.ts +1 -0
- package/dist/ssr-core-behavior.test.js +620 -0
- package/dist/ssr-core.d.ts +175 -0
- package/dist/ssr-core.js +940 -0
- package/dist/ssr-core.test.d.ts +1 -0
- package/dist/ssr-core.test.js +324 -0
- package/dist/static-memory.d.ts +3 -0
- package/dist/static-memory.js +47 -0
- package/dist/static-memory.test.d.ts +1 -0
- package/dist/static-memory.test.js +26 -0
- package/dist/test-redis.d.ts +12 -0
- package/dist/test-redis.js +131 -0
- package/dist/use-id.d.ts +8 -0
- package/dist/use-id.js +40 -0
- package/package.json +29 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
// @vitest-environment node
|
|
2
|
+
//
|
|
3
|
+
// End-to-end test of the Node SSR sidecar. server-renderer.ts starts a server
|
|
4
|
+
// when it is loaded, so the test runs the built dist/server-renderer.js as the
|
|
5
|
+
// Go host does: with KRATE_* environment variables, a server manifest and page
|
|
6
|
+
// bundles on disk, and talks to it over HTTP. Skipped when the runtime has not
|
|
7
|
+
// been built (KRATE_REQUIRE_E2E=1 turns that into a failure, as in CI).
|
|
8
|
+
import { spawn } from "node:child_process";
|
|
9
|
+
import { createHash } from "node:crypto";
|
|
10
|
+
import fs from "node:fs";
|
|
11
|
+
import net from "node:net";
|
|
12
|
+
import os from "node:os";
|
|
13
|
+
import path from "node:path";
|
|
14
|
+
import { pathToFileURL } from "node:url";
|
|
15
|
+
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
|
16
|
+
const here = path.dirname(new URL(import.meta.url).pathname);
|
|
17
|
+
const renderer = path.resolve(here, "..", "dist", "server-renderer.js");
|
|
18
|
+
const serverJs = path.resolve(here, "..", "dist", "server.js");
|
|
19
|
+
const built = fs.existsSync(renderer) && fs.existsSync(serverJs);
|
|
20
|
+
if (!built && process.env.KRATE_REQUIRE_E2E) {
|
|
21
|
+
throw new Error("dist/server-renderer.js is missing (KRATE_REQUIRE_E2E is set): build @krate/runtime first");
|
|
22
|
+
}
|
|
23
|
+
const SECRET = "test-secret";
|
|
24
|
+
let tmp = "";
|
|
25
|
+
let out = "";
|
|
26
|
+
let isrFile = "";
|
|
27
|
+
let child = null;
|
|
28
|
+
let port = 0;
|
|
29
|
+
let logs = "";
|
|
30
|
+
function freePort() {
|
|
31
|
+
return new Promise((resolve, reject) => {
|
|
32
|
+
const s = net.createServer();
|
|
33
|
+
s.once("error", reject);
|
|
34
|
+
s.listen(0, "127.0.0.1", () => {
|
|
35
|
+
const p = s.address().port;
|
|
36
|
+
s.close(() => resolve(p));
|
|
37
|
+
});
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
function write(rel, data) {
|
|
41
|
+
const f = path.join(out, rel);
|
|
42
|
+
fs.mkdirSync(path.dirname(f), { recursive: true });
|
|
43
|
+
fs.writeFileSync(f, data);
|
|
44
|
+
}
|
|
45
|
+
const jsxImport = `import { jsx } from ${JSON.stringify(pathToFileURL(serverJs).href)};\n`;
|
|
46
|
+
function bundles() {
|
|
47
|
+
write("pages/ssr.mjs", jsxImport +
|
|
48
|
+
`export default (props) => jsx("main", { children: [jsx("title", { children: "T " + ((props.params || {}).id || "") }), jsx("p", { children: "q=" + ((props.query || {}).q || "") })] });\n`);
|
|
49
|
+
write("pages/isr.mjs", jsxImport + `let n = 0;\nexport default () => jsx("p", { children: "isr-render-" + (++n) });\n`);
|
|
50
|
+
write("pages/boom.mjs", jsxImport + `export default () => { const e = new Error("secret detail"); e.stack = "at x"; throw e; };\n`);
|
|
51
|
+
write("pages/redirect.mjs", jsxImport + `export default () => { throw Object.assign(new Error("r"), { __krateRedirect: "/login" }); };\n`);
|
|
52
|
+
write("pages/missing.mjs", jsxImport + `export default () => { throw Object.assign(new Error("NEXT_NOT_FOUND"), { __krateNotFound: true, digest: "NEXT_NOT_FOUND" }); };\n`);
|
|
53
|
+
write("pages/regions.mjs", jsxImport +
|
|
54
|
+
`export const Slow = async () => { await new Promise((ok) => setTimeout(ok, 250)); return jsx("i", { children: "slow" }); };\n` +
|
|
55
|
+
`export const Fast = async () => jsx("i", { children: "fast" });\n` +
|
|
56
|
+
`export const Bad = async () => { throw new Error("region failed"); };\n` +
|
|
57
|
+
`export default () => jsx("p", { children: "whole page" });\n`);
|
|
58
|
+
write("rt/price.js", `globalThis.__krate_render = (json) => { const p = typeof json === "string" ? JSON.parse(json) : json; return "<b>" + p.price + "/" + (p.params ? p.params.id : "-") + "</b>"; };\n`);
|
|
59
|
+
write("404.html", "<h1>custom not found</h1>");
|
|
60
|
+
write("500.html", "<h1>custom error</h1>");
|
|
61
|
+
const page = (route, mode, bundle, extra = {}) => ({ route, source: route + ".tsx", mode, bundlePath: "pages/" + bundle + ".mjs", ...extra });
|
|
62
|
+
write(".krate/server-manifest.json", JSON.stringify({
|
|
63
|
+
pages: [
|
|
64
|
+
page("/ssr/[id]", "ssr", "ssr"),
|
|
65
|
+
page("/isr", "isr", "isr", { revalidate: 300 }),
|
|
66
|
+
page("/boom", "ssr", "boom"),
|
|
67
|
+
page("/redirect", "ssr", "redirect"),
|
|
68
|
+
page("/missing", "ssr", "missing"),
|
|
69
|
+
page("/regions", "ssr", "regions", { serverComponents: true }),
|
|
70
|
+
],
|
|
71
|
+
regions: {
|
|
72
|
+
"/regions": [
|
|
73
|
+
{ id: "slow", serverExport: "Slow" },
|
|
74
|
+
{ id: "fast", serverExport: "Fast" },
|
|
75
|
+
{ id: "bad", serverExport: "Bad" },
|
|
76
|
+
{ id: "price", bundlePath: "rt/price.js", props: { price: 12 } },
|
|
77
|
+
],
|
|
78
|
+
},
|
|
79
|
+
}));
|
|
80
|
+
}
|
|
81
|
+
async function start() {
|
|
82
|
+
port = await freePort();
|
|
83
|
+
logs = "";
|
|
84
|
+
child = spawn(process.execPath, [renderer], {
|
|
85
|
+
env: {
|
|
86
|
+
PATH: process.env.PATH,
|
|
87
|
+
KRATE_SSR_PORT: String(port),
|
|
88
|
+
KRATE_OUT_DIR: out,
|
|
89
|
+
KRATE_ROOT: tmp,
|
|
90
|
+
KRATE_INTERNAL_SECRET: SECRET,
|
|
91
|
+
KRATE_ISR_CACHE: isrFile,
|
|
92
|
+
},
|
|
93
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
94
|
+
});
|
|
95
|
+
child.stdout.on("data", (d) => (logs += d));
|
|
96
|
+
child.stderr.on("data", (d) => (logs += d));
|
|
97
|
+
const deadline = Date.now() + 15000;
|
|
98
|
+
for (;;) {
|
|
99
|
+
try {
|
|
100
|
+
const r = await fetch(`http://127.0.0.1:${port}/__krate/ssr/health`);
|
|
101
|
+
if (r.ok)
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
// not listening yet
|
|
106
|
+
}
|
|
107
|
+
if (child.exitCode !== null)
|
|
108
|
+
throw new Error("renderer exited early:\n" + logs);
|
|
109
|
+
if (Date.now() > deadline)
|
|
110
|
+
throw new Error("renderer did not start:\n" + logs);
|
|
111
|
+
await new Promise((ok) => setTimeout(ok, 50));
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
async function stop() {
|
|
115
|
+
const c = child;
|
|
116
|
+
child = null;
|
|
117
|
+
if (!c || c.exitCode !== null)
|
|
118
|
+
return;
|
|
119
|
+
await new Promise((ok) => {
|
|
120
|
+
c.once("exit", () => ok());
|
|
121
|
+
c.kill("SIGKILL");
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
const secret = { "x-krate-internal": SECRET };
|
|
125
|
+
const url = (p) => `http://127.0.0.1:${port}${p}`;
|
|
126
|
+
async function regions(body, headers = secret) {
|
|
127
|
+
const res = await fetch(url("/__krate/regions"), { method: "POST", headers, body: JSON.stringify(body) });
|
|
128
|
+
const text = await res.text();
|
|
129
|
+
return { res, frames: text.split("\n").filter(Boolean).map((l) => JSON.parse(l)) };
|
|
130
|
+
}
|
|
131
|
+
describe.skipIf(!built)("server-renderer sidecar", () => {
|
|
132
|
+
beforeAll(async () => {
|
|
133
|
+
tmp = fs.mkdtempSync(path.join(os.tmpdir(), "krate-ssr-"));
|
|
134
|
+
out = path.join(tmp, "dist");
|
|
135
|
+
isrFile = path.join(tmp, "isr-cache.json");
|
|
136
|
+
bundles();
|
|
137
|
+
await start();
|
|
138
|
+
}, 30000);
|
|
139
|
+
afterAll(async () => {
|
|
140
|
+
await stop();
|
|
141
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
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
|
+
describe("internal endpoints need the host's secret", () => {
|
|
148
|
+
it("refuses regions, revalidation and direct renders without it", async () => {
|
|
149
|
+
expect((await regions({ route: "/regions", url: "/regions" }, {})).res.status).toBe(403);
|
|
150
|
+
expect((await fetch(url("/__krate/ssr/cache-invalidate"), { method: "POST", body: "{}" })).status).toBe(403);
|
|
151
|
+
expect((await fetch(url("/__krate/ssr/cache-invalidate"), { method: "POST", body: "{}", headers: { "x-krate-internal": "wrong" } })).status).toBe(403);
|
|
152
|
+
expect((await fetch(url("/ssr/[id]"))).status).toBe(403);
|
|
153
|
+
});
|
|
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
|
+
});
|
|
167
|
+
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
|
+
it("serves the build's 500 page for a failing render, without the error text", async () => {
|
|
183
|
+
const r = await fetch(url("/boom"), { headers: secret });
|
|
184
|
+
expect(r.status).toBe(500);
|
|
185
|
+
const body = await r.text();
|
|
186
|
+
expect(body).toBe("<h1>custom error</h1>");
|
|
187
|
+
expect(body).not.toContain("secret detail");
|
|
188
|
+
const digest = createHash("sha256").update("secret detail\nat x").digest("hex").slice(0, 10);
|
|
189
|
+
expect(logs).toContain(`digest ${digest}`);
|
|
190
|
+
});
|
|
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
|
+
});
|
|
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
|
+
});
|
package/dist/server.d.ts
CHANGED
|
@@ -2,8 +2,16 @@ export { getActionContext, headers, cookies, redirect } from './action-context.j
|
|
|
2
2
|
export type { ActionContext, ActionCookies, ActionCookieOptions } from './action-context.js';
|
|
3
3
|
export { revalidatePath, revalidateTag, unstable_cache, unstable_noStore } from './cache.js';
|
|
4
4
|
export type { RevalidatePathType, UnstableCacheOptions } from './cache.js';
|
|
5
|
-
export { getRequestContext, notFound } from './request-context.js';
|
|
5
|
+
export { getRequestContext, notFound, forbidden, unauthorized } from './request-context.js';
|
|
6
|
+
export { usePathname, useSearchParams, useParams, useRouter, useSelectedLayoutSegment, useSelectedLayoutSegments, permanentRedirect, } from './navigation-server.js';
|
|
7
|
+
export type { AppRouterInstance } from './navigation-server.js';
|
|
6
8
|
export type { RequestContext, RequestCookies } from './request-context.js';
|
|
9
|
+
export { resolveMetadata, renderMetadataTags, metadataHeadTags } from './metadata.js';
|
|
10
|
+
export { renderSitemapXML, renderRobotsTXT, renderManifestJSON } from './metadata-routes.js';
|
|
11
|
+
export type { MetadataRoute, SitemapEntry, RobotsFile, RobotsRule, ManifestFile } from './metadata-routes.js';
|
|
12
|
+
export { ImageResponse } from './og.js';
|
|
13
|
+
export type { ImageResponseOptions } from './og.js';
|
|
14
|
+
export type { Metadata, ResolvingMetadata, ResolvingViewport, Viewport, MetadataSegment, MetadataModule, MetadataProps } from './metadata.js';
|
|
7
15
|
export declare function createSignal<T>(initial: T): [() => T, (v: T | ((prev: T) => T)) => void];
|
|
8
16
|
export declare function createEffect(_fn: () => void): () => void;
|
|
9
17
|
export declare function createMemo<T>(fn: () => T): () => T;
|
|
@@ -54,6 +62,8 @@ type ClientRender = (component: unknown, props: Record<string, unknown>, childre
|
|
|
54
62
|
* browser. Children are rendered on the server and passed as HTML.
|
|
55
63
|
*/
|
|
56
64
|
export declare function clientBoundary(moduleId: string, exportName: string, src: string, impl: unknown, render: ClientRender): unknown;
|
|
65
|
+
export declare const HEAD_OPEN = "<!--krate-head-->";
|
|
66
|
+
export declare const HEAD_CLOSE = "<!--/krate-head-->";
|
|
57
67
|
export declare function Head(props: {
|
|
58
68
|
children?: JSXNode;
|
|
59
69
|
}): JSXNode;
|
|
@@ -85,5 +95,6 @@ export declare function Icon(_props: {
|
|
|
85
95
|
}): JSXNode;
|
|
86
96
|
export declare function SyntaxHighlight(props: {
|
|
87
97
|
lang?: string;
|
|
98
|
+
highlight?: string;
|
|
88
99
|
children?: any;
|
|
89
100
|
}): JSXNode;
|
package/dist/server.js
CHANGED
|
@@ -1,9 +1,14 @@
|
|
|
1
1
|
// @krate/runtime/server - Server-side rendering runtime
|
|
2
2
|
// Provides the same API as the client runtime but renders to HTML strings.
|
|
3
3
|
import { ATTR_ALIASES } from './htmlspec-attributes.js';
|
|
4
|
+
import { highlight as highlightCode, trimSpace } from './highlight.js';
|
|
4
5
|
export { getActionContext, headers, cookies, redirect } from './action-context.js';
|
|
5
6
|
export { revalidatePath, revalidateTag, unstable_cache, unstable_noStore } from './cache.js';
|
|
6
|
-
export { getRequestContext, notFound } from './request-context.js';
|
|
7
|
+
export { getRequestContext, notFound, forbidden, unauthorized } from './request-context.js';
|
|
8
|
+
export { usePathname, useSearchParams, useParams, useRouter, useSelectedLayoutSegment, useSelectedLayoutSegments, permanentRedirect, } from './navigation-server.js';
|
|
9
|
+
export { resolveMetadata, renderMetadataTags, metadataHeadTags } from './metadata.js';
|
|
10
|
+
export { renderSitemapXML, renderRobotsTXT, renderManifestJSON } from './metadata-routes.js';
|
|
11
|
+
export { ImageResponse } from './og.js';
|
|
7
12
|
// Signal (server: returns initial value, no reactivity)
|
|
8
13
|
export function createSignal(initial) {
|
|
9
14
|
let value = initial;
|
|
@@ -287,6 +292,21 @@ async function resolveTree(node) {
|
|
|
287
292
|
out = await out;
|
|
288
293
|
return resolveTree(out);
|
|
289
294
|
}
|
|
295
|
+
// rawTextContent renders the children of <script>/<style>: their text is raw
|
|
296
|
+
// text in HTML, so entity escaping would corrupt JSON-LD and inline code. The
|
|
297
|
+
// static compiler emits it the same way; only a sequence that could end the
|
|
298
|
+
// element or open a comment is neutralised.
|
|
299
|
+
function rawTextContent(tag, children) {
|
|
300
|
+
let out = "";
|
|
301
|
+
for (const c of children) {
|
|
302
|
+
if (typeof c === "string")
|
|
303
|
+
out += c;
|
|
304
|
+
else
|
|
305
|
+
out += renderNode(c);
|
|
306
|
+
}
|
|
307
|
+
out = out.replace(tag === "script" ? /<\/(script)/gi : /<\/(style)/gi, "<\\/$1");
|
|
308
|
+
return tag === "script" ? out.replace(/<!--/g, "<\\!--") : out;
|
|
309
|
+
}
|
|
290
310
|
function renderElement(el) {
|
|
291
311
|
const { type, props, children } = el;
|
|
292
312
|
// Component
|
|
@@ -319,7 +339,9 @@ function renderElement(el) {
|
|
|
319
339
|
const dangerous = props.dangerouslySetInnerHTML;
|
|
320
340
|
const inner = dangerous && typeof dangerous === "object" && typeof dangerous.__html === "string"
|
|
321
341
|
? dangerous.__html
|
|
322
|
-
:
|
|
342
|
+
: tag === "script" || tag === "style"
|
|
343
|
+
? rawTextContent(tag, children)
|
|
344
|
+
: children.map(renderNode).join("");
|
|
323
345
|
return `<${tag}${attrs}>${inner}</${tag}>`;
|
|
324
346
|
}
|
|
325
347
|
// Streaming SSR via Suspense
|
|
@@ -440,10 +462,15 @@ export function clientBoundary(moduleId, exportName, src, impl, render) {
|
|
|
440
462
|
return Boundary;
|
|
441
463
|
}
|
|
442
464
|
// Built-in Components (server stubs)
|
|
443
|
-
// Head - renders children into the page head
|
|
444
|
-
//
|
|
465
|
+
// Head - renders children into the page head. At build time the compiler
|
|
466
|
+
// hoists them. In a request-time render the children come out between two
|
|
467
|
+
// comment markers, and the host (ssr-core takeHead) moves what sits between
|
|
468
|
+
// them into the document <head> of the response instead of leaving it in the
|
|
469
|
+
// body.
|
|
470
|
+
export const HEAD_OPEN = "<!--krate-head-->";
|
|
471
|
+
export const HEAD_CLOSE = "<!--/krate-head-->";
|
|
445
472
|
export function Head(props) {
|
|
446
|
-
return props.children ?? "";
|
|
473
|
+
return [raw(HEAD_OPEN), props.children ?? "", raw(HEAD_CLOSE)];
|
|
447
474
|
}
|
|
448
475
|
// Script - renders a <script> tag.
|
|
449
476
|
export function Script(props) {
|
|
@@ -509,10 +536,19 @@ export function Image(props) {
|
|
|
509
536
|
export function Icon(_props) {
|
|
510
537
|
return raw("<span></span>");
|
|
511
538
|
}
|
|
512
|
-
// SyntaxHighlight - renders a <pre><code> block
|
|
539
|
+
// SyntaxHighlight - renders a <pre><code> block. The Go compiler highlights code it knows at build
|
|
540
|
+
// time; code that only exists at request time is highlighted here with the same lexers (see
|
|
541
|
+
// highlight.ts), when the language's tables are loaded and the text is within its limits, and is
|
|
542
|
+
// written as plain text otherwise.
|
|
513
543
|
export function SyntaxHighlight(props) {
|
|
514
544
|
const lang = props.lang || "";
|
|
515
545
|
const code = props.children != null ? String(props.children) : "";
|
|
546
|
+
const lines = props.highlight || "";
|
|
547
|
+
const html = lang ? highlightCode(trimSpace(code), lang, lines || undefined) : null;
|
|
548
|
+
if (html !== null) {
|
|
549
|
+
const attr = lines ? ` data-highlight-lines="${escapeHTML(lines)}"` : "";
|
|
550
|
+
return raw(`<pre class="chroma"${attr}><code class="language-${escapeHTML(lang)}">${html}</code></pre>`);
|
|
551
|
+
}
|
|
516
552
|
const cls = lang ? `chroma language-${lang}` : "chroma";
|
|
517
553
|
return raw(`<pre class="chroma"><code class="${escapeHTML(cls)}">${escapeHTML(code)}</code></pre>`);
|
|
518
554
|
}
|
package/dist/sha256.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function sha256Hex(input: string): string;
|
package/dist/sha256.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// Portable synchronous SHA-256 (no node:crypto, no Web Crypto) so the render
|
|
2
|
+
// core can compute the same error digest on Node, Workers and edge hosts.
|
|
3
|
+
const K = new Uint32Array([
|
|
4
|
+
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
|
5
|
+
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
|
6
|
+
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
|
7
|
+
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
|
8
|
+
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
|
9
|
+
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
|
10
|
+
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
|
11
|
+
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
|
|
12
|
+
]);
|
|
13
|
+
export function sha256Hex(input) {
|
|
14
|
+
const msg = new TextEncoder().encode(input);
|
|
15
|
+
const bitLen = msg.length * 8;
|
|
16
|
+
const total = (((msg.length + 9 + 63) >> 6) << 6);
|
|
17
|
+
const buf = new Uint8Array(total);
|
|
18
|
+
buf.set(msg);
|
|
19
|
+
buf[msg.length] = 0x80;
|
|
20
|
+
const view = new DataView(buf.buffer);
|
|
21
|
+
view.setUint32(total - 8, Math.floor(bitLen / 0x100000000), false);
|
|
22
|
+
view.setUint32(total - 4, bitLen >>> 0, false);
|
|
23
|
+
const h = new Uint32Array([
|
|
24
|
+
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
|
|
25
|
+
]);
|
|
26
|
+
const w = new Uint32Array(64);
|
|
27
|
+
const rotr = (x, n) => (x >>> n) | (x << (32 - n));
|
|
28
|
+
for (let off = 0; off < total; off += 64) {
|
|
29
|
+
for (let i = 0; i < 16; i++)
|
|
30
|
+
w[i] = view.getUint32(off + i * 4, false);
|
|
31
|
+
for (let i = 16; i < 64; i++) {
|
|
32
|
+
const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >>> 3);
|
|
33
|
+
const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >>> 10);
|
|
34
|
+
w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0;
|
|
35
|
+
}
|
|
36
|
+
let [a, b, c, d, e, f, g, hh] = h;
|
|
37
|
+
for (let i = 0; i < 64; i++) {
|
|
38
|
+
const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
|
|
39
|
+
const ch = (e & f) ^ (~e & g);
|
|
40
|
+
const t1 = (hh + S1 + ch + K[i] + w[i]) | 0;
|
|
41
|
+
const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
|
|
42
|
+
const maj = (a & b) ^ (a & c) ^ (b & c);
|
|
43
|
+
const t2 = (S0 + maj) | 0;
|
|
44
|
+
hh = g;
|
|
45
|
+
g = f;
|
|
46
|
+
f = e;
|
|
47
|
+
e = (d + t1) | 0;
|
|
48
|
+
d = c;
|
|
49
|
+
c = b;
|
|
50
|
+
b = a;
|
|
51
|
+
a = (t1 + t2) | 0;
|
|
52
|
+
}
|
|
53
|
+
h[0] += a;
|
|
54
|
+
h[1] += b;
|
|
55
|
+
h[2] += c;
|
|
56
|
+
h[3] += d;
|
|
57
|
+
h[4] += e;
|
|
58
|
+
h[5] += f;
|
|
59
|
+
h[6] += g;
|
|
60
|
+
h[7] += hh;
|
|
61
|
+
}
|
|
62
|
+
let out = "";
|
|
63
|
+
for (let i = 0; i < 8; i++)
|
|
64
|
+
out += h[i].toString(16).padStart(8, "0");
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { sha256Hex } from "./sha256.js";
|
|
4
|
+
describe("portable sha256", () => {
|
|
5
|
+
it("matches node:crypto across block boundaries and UTF-8", () => {
|
|
6
|
+
for (const s of ["", "abc", "a".repeat(55), "a".repeat(56), "a".repeat(63), "a".repeat(64), "a".repeat(1000), "héllo 世界 😀"]) {
|
|
7
|
+
expect(sha256Hex(s)).toBe(createHash("sha256").update(s).digest("hex"));
|
|
8
|
+
}
|
|
9
|
+
});
|
|
10
|
+
it("error digest fixed vector", () => {
|
|
11
|
+
expect(sha256Hex("boom\nat x").slice(0, 10)).toBe("8a2474a04d");
|
|
12
|
+
});
|
|
13
|
+
});
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { type CacheEntry, type IsrStore } from './ssr-core.js';
|
|
2
|
+
import { type CacheAdapter, type CacheGuard, type CacheSpec } from './cache-adapter.js';
|
|
3
|
+
/**
|
|
4
|
+
* The ISR page cache on a shared adapter. Entries live in the adapter, so every
|
|
5
|
+
* instance serves and invalidates the same pages. When the adapter is down the
|
|
6
|
+
* store falls back to process memory, and the page is rendered rather than failed.
|
|
7
|
+
*/
|
|
8
|
+
export declare class SharedIsrStore implements IsrStore {
|
|
9
|
+
private readonly guard;
|
|
10
|
+
private readonly ttlSeconds;
|
|
11
|
+
private readonly memory;
|
|
12
|
+
constructor(guard: CacheGuard, ttlSeconds?: number, maxMemory?: number);
|
|
13
|
+
get(key: string): Promise<CacheEntry | undefined>;
|
|
14
|
+
set(key: string, entry: CacheEntry): Promise<void>;
|
|
15
|
+
deleteRoute(route: string): Promise<number>;
|
|
16
|
+
deleteVariant(route: string, params: Record<string, string>): Promise<number>;
|
|
17
|
+
deleteTags(tags: string[]): Promise<number>;
|
|
18
|
+
entriesForRoute(route: string): Promise<Array<[string, CacheEntry]>>;
|
|
19
|
+
}
|
|
20
|
+
/** Where an ISR store came from: the shared cache once its adapter is up. */
|
|
21
|
+
export interface IsrStoreSetup {
|
|
22
|
+
store: IsrStore;
|
|
23
|
+
/** Resolves with the adapter once it started (null when none is configured or it failed). */
|
|
24
|
+
ready: Promise<CacheAdapter | null>;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* The ISR store for a cache spec: `fallback` (process memory) without an
|
|
28
|
+
* adapter or while it starts; the shared store after. A spec that fails to load
|
|
29
|
+
* logs and keeps `fallback`, so a bad cache setting never takes the site down.
|
|
30
|
+
*/
|
|
31
|
+
export declare function isrStoreFor(specOrAdapter: CacheSpec | CacheAdapter | Promise<CacheAdapter> | undefined, fallback: IsrStore): IsrStoreSetup;
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// The ISR page cache on a shared cache adapter (see cache-adapter.ts).
|
|
2
|
+
import { MemoryIsrStore, variantKey } from './ssr-core.js';
|
|
3
|
+
import { installCacheAdapter, loadCacheAdapter, tagName } from './cache-adapter.js';
|
|
4
|
+
const ISR_PREFIX = 'isr:';
|
|
5
|
+
/**
|
|
6
|
+
* The ISR page cache on a shared adapter. Entries live in the adapter, so every
|
|
7
|
+
* instance serves and invalidates the same pages. When the adapter is down the
|
|
8
|
+
* store falls back to process memory, and the page is rendered rather than failed.
|
|
9
|
+
*/
|
|
10
|
+
export class SharedIsrStore {
|
|
11
|
+
constructor(guard, ttlSeconds = 7 * 24 * 3600, maxMemory = 512) {
|
|
12
|
+
this.guard = guard;
|
|
13
|
+
this.ttlSeconds = ttlSeconds;
|
|
14
|
+
this.memory = new MemoryIsrStore(maxMemory);
|
|
15
|
+
}
|
|
16
|
+
async get(key) {
|
|
17
|
+
const r = await this.guard.call((a) => a.get(ISR_PREFIX + key));
|
|
18
|
+
if (r.ok) {
|
|
19
|
+
if (r.value === null)
|
|
20
|
+
return undefined;
|
|
21
|
+
try {
|
|
22
|
+
return JSON.parse(r.value);
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return this.memory.get(key);
|
|
29
|
+
}
|
|
30
|
+
async set(key, entry) {
|
|
31
|
+
const route = routeOfKey(key);
|
|
32
|
+
const tags = (entry.tags || []).map(tagName).concat(routeTag(route));
|
|
33
|
+
const r = await this.guard.call((a) => a.set(ISR_PREFIX + key, JSON.stringify(entry), { ttlSeconds: this.ttlSeconds, tags }));
|
|
34
|
+
// Without the shared store this instance still caches for itself.
|
|
35
|
+
if (!r.ok)
|
|
36
|
+
this.memory.set(key, entry);
|
|
37
|
+
}
|
|
38
|
+
async deleteRoute(route) {
|
|
39
|
+
let n = this.memory.deleteRoute(route);
|
|
40
|
+
const r = await this.guard.call((a) => a.deleteByTags([routeTag(route)]));
|
|
41
|
+
if (r.ok)
|
|
42
|
+
n += r.value;
|
|
43
|
+
return n;
|
|
44
|
+
}
|
|
45
|
+
async deleteVariant(route, params) {
|
|
46
|
+
let n = this.memory.deleteVariant(route, params);
|
|
47
|
+
const base = variantKey({ route, params });
|
|
48
|
+
const keys = await this.guard.call((a) => a.keysByTag(routeTag(route)));
|
|
49
|
+
if (keys.ok) {
|
|
50
|
+
const stale = keys.value.filter((k) => {
|
|
51
|
+
const bare = k.startsWith(ISR_PREFIX) ? k.slice(ISR_PREFIX.length) : k;
|
|
52
|
+
return bare === base || bare.startsWith(base + '#');
|
|
53
|
+
});
|
|
54
|
+
for (const k of stale) {
|
|
55
|
+
const d = await this.guard.call((a) => a.delete(k));
|
|
56
|
+
if (d.ok)
|
|
57
|
+
n++;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return n;
|
|
61
|
+
}
|
|
62
|
+
async deleteTags(tags) {
|
|
63
|
+
let n = this.memory.deleteTags(tags);
|
|
64
|
+
const r = await this.guard.call((a) => a.deleteByTags(tags.map(tagName)));
|
|
65
|
+
if (r.ok)
|
|
66
|
+
n += r.value;
|
|
67
|
+
return n;
|
|
68
|
+
}
|
|
69
|
+
async entriesForRoute(route) {
|
|
70
|
+
const keys = await this.guard.call((a) => a.keysByTag(routeTag(route)));
|
|
71
|
+
if (!keys.ok)
|
|
72
|
+
return this.memory.entriesForRoute(route);
|
|
73
|
+
const out = [];
|
|
74
|
+
for (const k of keys.value) {
|
|
75
|
+
if (!k.startsWith(ISR_PREFIX))
|
|
76
|
+
continue;
|
|
77
|
+
const r = await this.guard.call((a) => a.get(k));
|
|
78
|
+
if (!r.ok || r.value === null)
|
|
79
|
+
continue;
|
|
80
|
+
try {
|
|
81
|
+
out.push([k.slice(ISR_PREFIX.length), JSON.parse(r.value)]);
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
/* skip an unreadable entry */
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return out;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
function routeOfKey(key) {
|
|
91
|
+
return key.split('?')[0].split('#')[0];
|
|
92
|
+
}
|
|
93
|
+
function routeTag(route) {
|
|
94
|
+
return 'route:' + route;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* The ISR store for a cache spec: `fallback` (process memory) without an
|
|
98
|
+
* adapter or while it starts; the shared store after. A spec that fails to load
|
|
99
|
+
* logs and keeps `fallback`, so a bad cache setting never takes the site down.
|
|
100
|
+
*/
|
|
101
|
+
export function isrStoreFor(specOrAdapter, fallback) {
|
|
102
|
+
const promised = specOrAdapter && typeof specOrAdapter.then === 'function' ? specOrAdapter : undefined;
|
|
103
|
+
if (promised) {
|
|
104
|
+
let active = fallback;
|
|
105
|
+
const ready = promised.then((adapter) => {
|
|
106
|
+
const installed = installCacheAdapter(adapter, {});
|
|
107
|
+
active = new SharedIsrStore(installed.guard);
|
|
108
|
+
return adapter;
|
|
109
|
+
}, (err) => {
|
|
110
|
+
console.error('[krate] the cache adapter failed to start; using the in-process caches:', err);
|
|
111
|
+
return null;
|
|
112
|
+
});
|
|
113
|
+
return { store: delegating(() => active, ready), ready };
|
|
114
|
+
}
|
|
115
|
+
const given = specOrAdapter && typeof specOrAdapter.get === 'function' ? specOrAdapter : undefined;
|
|
116
|
+
const spec = given ? {} : specOrAdapter;
|
|
117
|
+
if (!given && (!spec || !spec.adapter || spec.adapter === 'memory'))
|
|
118
|
+
return { store: fallback, ready: Promise.resolve(null) };
|
|
119
|
+
let active = fallback;
|
|
120
|
+
const load = given ? Promise.resolve(given) : loadCacheAdapter(spec);
|
|
121
|
+
const ready = load.then((adapter) => {
|
|
122
|
+
if (!adapter)
|
|
123
|
+
return null;
|
|
124
|
+
const installed = installCacheAdapter(adapter, spec || {});
|
|
125
|
+
active = new SharedIsrStore(installed.guard, spec?.ttlSeconds, 512);
|
|
126
|
+
return adapter;
|
|
127
|
+
}, (err) => {
|
|
128
|
+
console.error('[krate] the cache adapter failed to start; using the in-process caches:', err);
|
|
129
|
+
return null;
|
|
130
|
+
});
|
|
131
|
+
return { store: delegating(() => active, ready), ready };
|
|
132
|
+
}
|
|
133
|
+
function delegating(current, ready) {
|
|
134
|
+
return {
|
|
135
|
+
get: async (key) => (await ready, current().get(key)),
|
|
136
|
+
set: async (key, entry) => (await ready, current().set(key, entry)),
|
|
137
|
+
deleteRoute: async (route) => (await ready, current().deleteRoute(route)),
|
|
138
|
+
deleteVariant: async (route, params) => (await ready, current().deleteVariant(route, params)),
|
|
139
|
+
deleteTags: async (tags) => (await ready, current().deleteTags(tags)),
|
|
140
|
+
entriesForRoute: async (route) => (await ready, current().entriesForRoute(route)),
|
|
141
|
+
};
|
|
142
|
+
}
|