@krate/runtime 0.5.0-rc.2 → 0.5.0-rc.4
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.d.ts +7 -0
- package/dist/actions.js +21 -3
- package/dist/actions.test.js +8 -410
- package/dist/after.d.ts +28 -0
- package/dist/after.js +48 -0
- package/dist/after.test.js +58 -0
- package/dist/assets-static.d.ts +10 -1
- package/dist/assets-static.js +10 -2
- package/dist/base-path.js +4 -3
- package/dist/builtin-tags.d.ts +12 -0
- package/dist/builtin-tags.js +42 -0
- package/dist/builtin-tags.test.js +12 -0
- package/dist/cache-adapter.test.js +4 -203
- package/dist/cache-scope.d.ts +2 -0
- package/dist/cache.test.js +1 -197
- package/dist/cloudflare-workers.d.ts +2 -0
- package/dist/cloudflare-workers.js +27 -0
- package/dist/dev-overlay.d.ts +54 -3
- package/dist/dev-overlay.js +469 -76
- package/dist/dom.js +3 -1
- package/dist/events.test.js +2 -407
- package/dist/handler-html.test.js +1 -202
- package/dist/handler-routing.js +3 -0
- package/dist/handler-segments.d.ts +6 -0
- package/dist/handler-segments.js +16 -2
- package/dist/handler-segments.test.js +8 -200
- package/dist/head-tags.d.ts +9 -0
- package/dist/head-tags.js +85 -1
- package/dist/head-tags.test.js +18 -125
- package/dist/index.d.ts +1 -5
- package/dist/index.js +3 -0
- package/dist/inline-action-token.test.js +31 -0
- package/dist/jsx-svg-types.test.js +58 -0
- package/dist/jsx-types.d.ts +92 -1
- package/dist/krate-core.js +1 -1
- package/dist/krate-dev.js +384 -65
- package/dist/krate-f-actions.js +1 -1
- package/dist/krate-f-navigation.js +1 -1
- package/dist/krate-f-router-lite.js +1 -1
- package/dist/krate-f-router.js +1 -1
- package/dist/krate-features.json +2 -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/link-base-path.test.js +28 -0
- package/dist/node-server.test.js +1 -355
- package/dist/platform.d.ts +52 -0
- package/dist/platform.js +57 -0
- package/dist/platform.test.js +44 -0
- package/dist/router-nav.test.js +15 -444
- package/dist/router.js +39 -1
- package/dist/server-handler.d.ts +48 -0
- package/dist/server-handler.js +279 -17
- package/dist/server-handler.test.js +54 -388
- package/dist/server-renderer.test.js +0 -104
- package/dist/server.d.ts +15 -5
- package/dist/server.js +149 -22
- package/dist/server.test.js +52 -60
- package/dist/site-config.d.ts +13 -0
- package/dist/site-config.js +28 -0
- package/dist/site-config.test.js +30 -0
- package/dist/slot.d.ts +12 -0
- package/dist/slot.js +23 -0
- package/dist/slot.test.js +25 -0
- package/dist/ssr-core-behavior.test.js +3 -515
- package/dist/testing.d.ts +59 -0
- package/dist/testing.js +88 -0
- package/dist/testing.test.js +73 -0
- package/package.json +9 -1
- package/dist/action-context.test.js +0 -72
- package/dist/base-path.test.js +0 -88
- package/dist/class-component.test.js +0 -462
- package/dist/class-helpers.test.js +0 -169
- package/dist/context.test.js +0 -57
- package/dist/derived.test.js +0 -140
- package/dist/dev-overlay.test.js +0 -165
- package/dist/discrete.test.js +0 -100
- package/dist/dom.test.js +0 -39
- package/dist/effect-errors.test.d.ts +0 -1
- package/dist/effect-errors.test.js +0 -199
- package/dist/effects.test.d.ts +0 -1
- package/dist/effects.test.js +0 -485
- package/dist/handler-routing.test.d.ts +0 -1
- package/dist/handler-routing.test.js +0 -99
- package/dist/highlight-bind.test.d.ts +0 -1
- package/dist/highlight-bind.test.js +0 -124
- package/dist/highlight.test.d.ts +0 -1
- package/dist/highlight.test.js +0 -56
- package/dist/lanes.test.d.ts +0 -1
- package/dist/lanes.test.js +0 -59
- package/dist/list.test.d.ts +0 -1
- package/dist/list.test.js +0 -435
- package/dist/metadata.test.d.ts +0 -1
- package/dist/metadata.test.js +0 -167
- package/dist/navigation.test.d.ts +0 -1
- package/dist/navigation.test.js +0 -130
- package/dist/optimistic-lanes.test.d.ts +0 -1
- package/dist/optimistic-lanes.test.js +0 -45
- package/dist/patterns.test.d.ts +0 -1
- package/dist/patterns.test.js +0 -125
- package/dist/portal.test.d.ts +0 -1
- package/dist/portal.test.js +0 -99
- package/dist/react-effects.test.d.ts +0 -1
- package/dist/react-effects.test.js +0 -133
- package/dist/react-suspense.test.d.ts +0 -1
- package/dist/react-suspense.test.js +0 -194
- package/dist/react.test.d.ts +0 -1
- package/dist/react.test.js +0 -60
- package/dist/react19.test.d.ts +0 -1
- package/dist/react19.test.js +0 -176
- package/dist/reactivity-core.test.d.ts +0 -1
- package/dist/reactivity-core.test.js +0 -152
- package/dist/reconcile.test.d.ts +0 -1
- package/dist/reconcile.test.js +0 -110
- package/dist/refs.test.d.ts +0 -1
- package/dist/refs.test.js +0 -257
- package/dist/router-layout.test.d.ts +0 -1
- package/dist/router-layout.test.js +0 -249
- package/dist/router-slots.test.d.ts +0 -1
- package/dist/router-slots.test.js +0 -144
- package/dist/router-speculation.test.d.ts +0 -1
- package/dist/router-speculation.test.js +0 -25
- package/dist/router-styles.test.d.ts +0 -1
- package/dist/router-styles.test.js +0 -98
- package/dist/router.test.d.ts +0 -1
- package/dist/router.test.js +0 -36
- package/dist/server-async.test.d.ts +0 -1
- package/dist/server-async.test.js +0 -216
- package/dist/server-highlight.test.d.ts +0 -1
- package/dist/server-highlight.test.js +0 -32
- package/dist/signal-lanes.test.d.ts +0 -1
- package/dist/signal-lanes.test.js +0 -32
- package/dist/slots.test.d.ts +0 -1
- package/dist/slots.test.js +0 -187
- package/dist/snapshots.test.d.ts +0 -1
- package/dist/snapshots.test.js +0 -208
- package/dist/ssr-core.test.d.ts +0 -1
- package/dist/ssr-core.test.js +0 -324
- package/dist/static-memory.test.d.ts +0 -1
- package/dist/static-memory.test.js +0 -26
- package/dist/storage.test.d.ts +0 -1
- package/dist/storage.test.js +0 -46
- package/dist/suspense-actions.test.d.ts +0 -1
- package/dist/suspense-actions.test.js +0 -72
- package/dist/suspense.test.d.ts +0 -1
- package/dist/suspense.test.js +0 -556
- /package/dist/{action-context.test.d.ts → after.test.d.ts} +0 -0
- /package/dist/{base-path.test.d.ts → builtin-tags.test.d.ts} +0 -0
- /package/dist/{class-component.test.d.ts → inline-action-token.test.d.ts} +0 -0
- /package/dist/{class-helpers.test.d.ts → jsx-svg-types.test.d.ts} +0 -0
- /package/dist/{context.test.d.ts → link-base-path.test.d.ts} +0 -0
- /package/dist/{derived.test.d.ts → platform.test.d.ts} +0 -0
- /package/dist/{dev-overlay.test.d.ts → site-config.test.d.ts} +0 -0
- /package/dist/{discrete.test.d.ts → slot.test.d.ts} +0 -0
- /package/dist/{dom.test.d.ts → testing.test.d.ts} +0 -0
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
|
2
|
+
import { Link, renderToString } from './server';
|
|
3
|
+
import { h } from './dom';
|
|
4
|
+
beforeEach(() => {
|
|
5
|
+
globalThis.__KRATE_CFG__ = { basePath: '/app' };
|
|
6
|
+
});
|
|
7
|
+
afterEach(() => {
|
|
8
|
+
delete globalThis.__KRATE_CFG__;
|
|
9
|
+
});
|
|
10
|
+
describe('<Link basePath={false}>', () => {
|
|
11
|
+
it('server render: adds the base path by default and not when opted out', () => {
|
|
12
|
+
const inSite = renderToString(Link({ href: '/pricing', children: 'a' }));
|
|
13
|
+
expect(inSite).toContain('href="/app/pricing"');
|
|
14
|
+
expect(inSite).toContain('data-krate-link');
|
|
15
|
+
const outside = renderToString(Link({ href: '/pricing', basePath: false, children: 'a' }));
|
|
16
|
+
expect(outside).toContain('href="/pricing"');
|
|
17
|
+
expect(outside).toContain('data-krate-external');
|
|
18
|
+
expect(outside).toContain('data-krate-no-base');
|
|
19
|
+
expect(outside).not.toContain('data-krate-link');
|
|
20
|
+
expect(outside).not.toContain('basePath');
|
|
21
|
+
});
|
|
22
|
+
it('client render: data-krate-no-base keeps the href as written', () => {
|
|
23
|
+
const link = h('a', { href: '/pricing', 'data-krate-link': true }, 'a');
|
|
24
|
+
expect(link.getAttribute('href')).toBe('/app/pricing');
|
|
25
|
+
const outside = h('a', { href: '/pricing', 'data-krate-external': true, 'data-krate-no-base': true }, 'a');
|
|
26
|
+
expect(outside.getAttribute('href')).toBe('/pricing');
|
|
27
|
+
});
|
|
28
|
+
});
|
package/dist/node-server.test.js
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
// @vitest-environment node
|
|
2
2
|
import fs from "node:fs";
|
|
3
3
|
import http from "node:http";
|
|
4
|
-
import net from "node:net";
|
|
5
4
|
import os from "node:os";
|
|
6
5
|
import path from "node:path";
|
|
7
6
|
import zlib from "node:zlib";
|
|
8
7
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
|
9
|
-
import { createNodeStaticLayer,
|
|
8
|
+
import { createNodeStaticLayer, nodeRequestListener } from "./node-server.js";
|
|
10
9
|
let tmp;
|
|
11
10
|
let dist;
|
|
12
11
|
function write(rel, data) {
|
|
@@ -51,13 +50,6 @@ describe("createNodeStaticLayer", () => {
|
|
|
51
50
|
expect(r.headers.get("last-modified")).toMatch(/GMT$/);
|
|
52
51
|
expect(await r.text()).toBe("0123456789");
|
|
53
52
|
});
|
|
54
|
-
it("answers HEAD without a body and refuses other methods", async () => {
|
|
55
|
-
const head = (await layer().serve(req("/data.bin", { method: "HEAD" }), "/data.bin"));
|
|
56
|
-
expect(head.status).toBe(200);
|
|
57
|
-
expect(head.headers.get("content-length")).toBe("10");
|
|
58
|
-
expect(await head.text()).toBe("");
|
|
59
|
-
expect(await layer().serve(req("/data.bin", { method: "POST", body: "x" }), "/data.bin")).toBeNull();
|
|
60
|
-
});
|
|
61
53
|
it.each([
|
|
62
54
|
["dotfile", "/.env"],
|
|
63
55
|
["encoded dotfile", "/%2eenv"],
|
|
@@ -75,111 +67,6 @@ describe("createNodeStaticLayer", () => {
|
|
|
75
67
|
expect(await l.serve(req(p), decodeURIComponentSafe(p))).toBeNull();
|
|
76
68
|
expect(await l.exists(decodeURIComponentSafe(p))).toBe(false);
|
|
77
69
|
});
|
|
78
|
-
it("publishes .well-known", async () => {
|
|
79
|
-
const r = (await layer().serve(req("/.well-known/security.txt"), "/.well-known/security.txt"));
|
|
80
|
-
expect(r.status).toBe(200);
|
|
81
|
-
expect(await r.text()).toContain("Contact");
|
|
82
|
-
});
|
|
83
|
-
it("redirects a directory to its slash form and keeps the query", async () => {
|
|
84
|
-
const r = (await layer().serve(req("/about?x=1"), "/about"));
|
|
85
|
-
expect(r.status).toBe(301);
|
|
86
|
-
expect(r.headers.get("location")).toBe("about/?x=1");
|
|
87
|
-
});
|
|
88
|
-
it("serves a directory index, and redirects /dir/index.html to /dir/", async () => {
|
|
89
|
-
const l = layer();
|
|
90
|
-
const dir = (await l.serve(req("/about/"), "/about/"));
|
|
91
|
-
expect(await dir.text()).toBe("<h1>about</h1>");
|
|
92
|
-
const idx = (await l.serve(req("/about/index.html?a=b"), "/about/index.html"));
|
|
93
|
-
expect(idx.status).toBe(301);
|
|
94
|
-
expect(idx.headers.get("location")).toBe("./?a=b");
|
|
95
|
-
expect(await l.serve(req("/empty/"), "/empty/")).toBeNull();
|
|
96
|
-
});
|
|
97
|
-
it("does not answer a file requested with a trailing slash", async () => {
|
|
98
|
-
expect(await layer().serve(req("/data.bin/"), "/data.bin/")).toBeNull();
|
|
99
|
-
});
|
|
100
|
-
it("handles ranges: closed, suffix, open-ended, unsatisfiable, multiple", async () => {
|
|
101
|
-
const l = layer();
|
|
102
|
-
const get = (range) => l.serve(req("/data.bin", { headers: { range } }), "/data.bin");
|
|
103
|
-
const a = (await get("bytes=2-4"));
|
|
104
|
-
expect(a.status).toBe(206);
|
|
105
|
-
expect(a.headers.get("content-range")).toBe("bytes 2-4/10");
|
|
106
|
-
expect(await a.text()).toBe("234");
|
|
107
|
-
const suffix = (await get("bytes=-3"));
|
|
108
|
-
expect(suffix.headers.get("content-range")).toBe("bytes 7-9/10");
|
|
109
|
-
expect(await suffix.text()).toBe("789");
|
|
110
|
-
const open = (await get("bytes=8-"));
|
|
111
|
-
expect(await open.text()).toBe("89");
|
|
112
|
-
const past = (await get("bytes=50-60"));
|
|
113
|
-
expect(past.status).toBe(416);
|
|
114
|
-
expect(past.headers.get("content-range")).toBe("bytes */10");
|
|
115
|
-
const multi = (await get("bytes=0-1,3-4"));
|
|
116
|
-
expect(multi.status).toBe(200);
|
|
117
|
-
expect(await multi.text()).toBe("0123456789");
|
|
118
|
-
const end = (await get("bytes=0-99"));
|
|
119
|
-
expect(end.headers.get("content-range")).toBe("bytes 0-9/10");
|
|
120
|
-
});
|
|
121
|
-
it("answers 304 for an If-Modified-Since at or after the file time", async () => {
|
|
122
|
-
const l = layer();
|
|
123
|
-
const first = (await l.serve(req("/data.bin"), "/data.bin"));
|
|
124
|
-
const lm = first.headers.get("last-modified");
|
|
125
|
-
const r = (await l.serve(req("/data.bin", { headers: { "if-modified-since": lm } }), "/data.bin"));
|
|
126
|
-
expect(r.status).toBe(304);
|
|
127
|
-
expect(await r.text()).toBe("");
|
|
128
|
-
const old = (await l.serve(req("/data.bin", { headers: { "if-modified-since": "Thu, 01 Jan 1970 00:00:00 GMT" } }), "/data.bin"));
|
|
129
|
-
expect(old.status).toBe(200);
|
|
130
|
-
});
|
|
131
|
-
describe("precompressed siblings", () => {
|
|
132
|
-
const get = async (headers) => (await layer().serve(req("/app.abc123.js", { headers }), "/app.abc123.js"));
|
|
133
|
-
it("prefers brotli, then gzip, keeping the original content type", async () => {
|
|
134
|
-
const br = await get({ "accept-encoding": "gzip, br" });
|
|
135
|
-
expect(br.headers.get("content-encoding")).toBe("br");
|
|
136
|
-
expect(br.headers.get("content-type")).toBe("text/javascript; charset=utf-8");
|
|
137
|
-
expect(br.headers.get("vary")).toBe("Accept-Encoding");
|
|
138
|
-
expect(zlib.brotliDecompressSync(Buffer.from(await br.arrayBuffer())).toString()).toBe("br-body");
|
|
139
|
-
const gz = await get({ "accept-encoding": "gzip" });
|
|
140
|
-
expect(gz.headers.get("content-encoding")).toBe("gzip");
|
|
141
|
-
expect(zlib.gunzipSync(Buffer.from(await gz.arrayBuffer())).toString()).toBe("gz-body");
|
|
142
|
-
});
|
|
143
|
-
it("serves the plain file when the client refuses the coding (q=0) or sends none", async () => {
|
|
144
|
-
const refused = await get({ "accept-encoding": "br;q=0, gzip;q=0" });
|
|
145
|
-
expect(refused.headers.get("content-encoding")).toBeNull();
|
|
146
|
-
expect(await refused.text()).toContain("0123456789");
|
|
147
|
-
const none = await get({});
|
|
148
|
-
expect(none.headers.get("content-encoding")).toBeNull();
|
|
149
|
-
expect(none.headers.get("vary")).toBe("Accept-Encoding");
|
|
150
|
-
});
|
|
151
|
-
it("honours a wildcard", async () => {
|
|
152
|
-
const r = await get({ "accept-encoding": "*" });
|
|
153
|
-
expect(r.headers.get("content-encoding")).toBe("br");
|
|
154
|
-
});
|
|
155
|
-
it("never uses a compressed sibling for a range request or a page carrying flash state", async () => {
|
|
156
|
-
const ranged = await get({ "accept-encoding": "br", range: "bytes=0-3" });
|
|
157
|
-
expect(ranged.headers.get("content-encoding")).toBeNull();
|
|
158
|
-
expect(ranged.status).toBe(206);
|
|
159
|
-
const flashed = await get({ "accept-encoding": "br", cookie: "krate_flash=" + Buffer.from('{"a":"x","r":"hi"}').toString("base64url") });
|
|
160
|
-
expect(flashed.headers.get("content-encoding")).toBeNull();
|
|
161
|
-
});
|
|
162
|
-
it("does not add Vary for a type that is not compressible", async () => {
|
|
163
|
-
const r = (await layer().serve(req("/logo.png"), "/logo.png"));
|
|
164
|
-
expect(r.headers.get("content-type")).toBe("image/png");
|
|
165
|
-
expect(r.headers.get("vary")).toBeNull();
|
|
166
|
-
});
|
|
167
|
-
});
|
|
168
|
-
it("exists() maps URLs to files and folder indexes, and isAsset() only to non-HTML files", async () => {
|
|
169
|
-
const l = layer();
|
|
170
|
-
expect(await l.exists("/")).toBe(true);
|
|
171
|
-
expect(await l.exists("/about")).toBe(true);
|
|
172
|
-
expect(await l.exists("/about/")).toBe(true);
|
|
173
|
-
expect(await l.exists("/page.html")).toBe(true);
|
|
174
|
-
expect(await l.exists("/empty")).toBe(false);
|
|
175
|
-
expect(await l.exists("/nope")).toBe(false);
|
|
176
|
-
expect(await l.isAsset("/app.abc123.js")).toBe(true);
|
|
177
|
-
expect(await l.isAsset("/page.html")).toBe(false);
|
|
178
|
-
expect(await l.isAsset("/about")).toBe(false);
|
|
179
|
-
expect(await l.isAsset("/.env")).toBe(false);
|
|
180
|
-
expect(await l.isAsset("/missing.js")).toBe(false);
|
|
181
|
-
expect(await l.isAsset("/about/")).toBe(false);
|
|
182
|
-
});
|
|
183
70
|
});
|
|
184
71
|
function decodeURIComponentSafe(p) {
|
|
185
72
|
try {
|
|
@@ -248,245 +135,4 @@ describe("requestFromNode", () => {
|
|
|
248
135
|
expect(j.url).toBe("http://site.test/p?q=1");
|
|
249
136
|
});
|
|
250
137
|
});
|
|
251
|
-
it("keeps them when the server sits behind a trusted proxy", async () => {
|
|
252
|
-
await withServer(echo, true, async (port) => {
|
|
253
|
-
const r = await call(port, "/", { "x-forwarded-for": "9.9.9.9", "x-forwarded-proto": "https", "x-real-ip": "9.9.9.9" });
|
|
254
|
-
const j = JSON.parse(r.body.toString());
|
|
255
|
-
expect(j.xff).toBe("9.9.9.9");
|
|
256
|
-
expect(j.proto).toBe("https");
|
|
257
|
-
expect(j.realIp).toBe("9.9.9.9");
|
|
258
|
-
});
|
|
259
|
-
});
|
|
260
|
-
it("streams a request body to the handler and joins repeated headers", async () => {
|
|
261
|
-
await withServer(echo, false, async (port) => {
|
|
262
|
-
const r = await call(port, "/", { "content-type": "text/plain" }, { method: "POST", body: "hello body" });
|
|
263
|
-
expect(JSON.parse(r.body.toString()).body).toBe("hello body");
|
|
264
|
-
});
|
|
265
|
-
});
|
|
266
|
-
it("builds the URL from the Host header, falling back to localhost", () => {
|
|
267
|
-
const fake = (headers, url) => ({ headers, url, method: "get", socket: { remoteAddress: "10.0.0.1" } });
|
|
268
|
-
expect(requestFromNode(fake({ host: "a.test:8080" }, "/x?y=2"), true).url).toBe("http://a.test:8080/x?y=2");
|
|
269
|
-
expect(requestFromNode(fake({}, "/"), true).url).toBe("http://localhost/");
|
|
270
|
-
expect(requestFromNode(fake({}, "/"), true).method).toBe("GET");
|
|
271
|
-
const tls = { headers: { host: "s.test" }, url: "/", method: "GET", socket: { encrypted: true, remoteAddress: "10.0.0.1" } };
|
|
272
|
-
expect(requestFromNode(tls, false).url).toBe("https://s.test/");
|
|
273
|
-
expect(requestFromNode(tls, false).headers.get("x-forwarded-proto")).toBe("https");
|
|
274
|
-
});
|
|
275
|
-
});
|
|
276
|
-
describe("writeResponse", () => {
|
|
277
|
-
const html = "<p>" + "hello ".repeat(200) + "</p>";
|
|
278
|
-
it("gzips compressible bodies for clients that accept it and fixes the headers", async () => {
|
|
279
|
-
const h = async () => new Response(html, { headers: { "content-type": "text/html; charset=utf-8", "content-length": String(html.length), vary: "Cookie" } });
|
|
280
|
-
await withServer(h, false, async (port) => {
|
|
281
|
-
const r = await call(port, "/", { "accept-encoding": "gzip" });
|
|
282
|
-
expect(r.headers["content-encoding"]).toBe("gzip");
|
|
283
|
-
expect(r.headers["content-length"]).toBeUndefined();
|
|
284
|
-
expect(r.headers.vary).toBe("Cookie, Accept-Encoding");
|
|
285
|
-
expect(zlib.gunzipSync(r.body).toString()).toBe(html);
|
|
286
|
-
const plain = await call(port, "/", {});
|
|
287
|
-
expect(plain.headers["content-encoding"]).toBeUndefined();
|
|
288
|
-
expect(plain.body.toString()).toBe(html);
|
|
289
|
-
expect(plain.headers.vary).toBe("Cookie, Accept-Encoding");
|
|
290
|
-
});
|
|
291
|
-
});
|
|
292
|
-
it("does not compress images, ranges, partial content or an already encoded body", async () => {
|
|
293
|
-
const png = async () => new Response("png-bytes", { headers: { "content-type": "image/png" } });
|
|
294
|
-
const partial = async () => new Response("part", { status: 206, headers: { "content-type": "text/plain", "content-range": "bytes 0-3/10" } });
|
|
295
|
-
const encoded = async () => new Response("xx", { headers: { "content-type": "text/css", "content-encoding": "br" } });
|
|
296
|
-
const plain = async () => new Response(html, { headers: { "content-type": "text/plain" } });
|
|
297
|
-
await withServer(png, false, async (port) => {
|
|
298
|
-
const r = await call(port, "/", { "accept-encoding": "gzip" });
|
|
299
|
-
expect(r.headers["content-encoding"]).toBeUndefined();
|
|
300
|
-
expect(r.headers.vary).toBeUndefined();
|
|
301
|
-
});
|
|
302
|
-
await withServer(partial, false, async (port) => {
|
|
303
|
-
const r = await call(port, "/", { "accept-encoding": "gzip" });
|
|
304
|
-
expect(r.status).toBe(206);
|
|
305
|
-
expect(r.headers["content-encoding"]).toBeUndefined();
|
|
306
|
-
});
|
|
307
|
-
await withServer(encoded, false, async (port) => {
|
|
308
|
-
const r = await call(port, "/", { "accept-encoding": "gzip" });
|
|
309
|
-
expect(r.headers["content-encoding"]).toBe("br");
|
|
310
|
-
});
|
|
311
|
-
await withServer(plain, false, async (port) => {
|
|
312
|
-
const r = await call(port, "/", { "accept-encoding": "gzip", range: "bytes=0-3" });
|
|
313
|
-
expect(r.headers["content-encoding"]).toBeUndefined();
|
|
314
|
-
});
|
|
315
|
-
});
|
|
316
|
-
it("sends every Set-Cookie as its own header and nothing for HEAD", async () => {
|
|
317
|
-
const h = async () => {
|
|
318
|
-
const headers = new Headers({ "content-type": "text/plain" });
|
|
319
|
-
headers.append("set-cookie", "a=1; Path=/; HttpOnly");
|
|
320
|
-
headers.append("set-cookie", "b=2; Path=/; Secure");
|
|
321
|
-
return new Response("body", { headers });
|
|
322
|
-
};
|
|
323
|
-
await withServer(h, false, async (port) => {
|
|
324
|
-
const r = await call(port, "/", {});
|
|
325
|
-
expect(r.headers["set-cookie"]).toEqual(["a=1; Path=/; HttpOnly", "b=2; Path=/; Secure"]);
|
|
326
|
-
const head = await call(port, "/", {}, { method: "HEAD" });
|
|
327
|
-
expect(head.status).toBe(200);
|
|
328
|
-
expect(head.body.length).toBe(0);
|
|
329
|
-
});
|
|
330
|
-
});
|
|
331
|
-
it("flushes each chunk of a streamed page as soon as it exists, also through gzip", async () => {
|
|
332
|
-
// The second chunk is produced only after the client saw the first one, so
|
|
333
|
-
// a server that buffered the response would never finish.
|
|
334
|
-
for (const enc of ["identity", "gzip"]) {
|
|
335
|
-
let release;
|
|
336
|
-
const gate = new Promise((ok) => (release = ok));
|
|
337
|
-
const h = async () => {
|
|
338
|
-
const enqueue = new TextEncoder();
|
|
339
|
-
let step = 0;
|
|
340
|
-
const stream = new ReadableStream({
|
|
341
|
-
async pull(controller) {
|
|
342
|
-
if (step === 0)
|
|
343
|
-
controller.enqueue(enqueue.encode("<p>first</p>"));
|
|
344
|
-
else if (step === 1) {
|
|
345
|
-
await gate;
|
|
346
|
-
controller.enqueue(enqueue.encode("<p>second</p>"));
|
|
347
|
-
}
|
|
348
|
-
else
|
|
349
|
-
controller.close();
|
|
350
|
-
step++;
|
|
351
|
-
},
|
|
352
|
-
});
|
|
353
|
-
return new Response(stream, { headers: { "content-type": "text/html" } });
|
|
354
|
-
};
|
|
355
|
-
const server = http.createServer(nodeRequestListener(h, false));
|
|
356
|
-
const port = await listen(server);
|
|
357
|
-
try {
|
|
358
|
-
const body = await new Promise((resolve, reject) => {
|
|
359
|
-
const r = http.request({ host: "127.0.0.1", port, path: "/", headers: { "accept-encoding": enc } }, (res) => {
|
|
360
|
-
const stream = enc === "gzip" ? res.pipe(zlib.createGunzip()) : res;
|
|
361
|
-
let seen = "";
|
|
362
|
-
stream.on("data", (c) => {
|
|
363
|
-
seen += c.toString();
|
|
364
|
-
if (seen.includes("first"))
|
|
365
|
-
release();
|
|
366
|
-
});
|
|
367
|
-
stream.on("end", () => resolve(seen));
|
|
368
|
-
stream.on("error", reject);
|
|
369
|
-
});
|
|
370
|
-
r.on("error", reject);
|
|
371
|
-
r.end();
|
|
372
|
-
});
|
|
373
|
-
expect(body, enc).toBe("<p>first</p><p>second</p>");
|
|
374
|
-
}
|
|
375
|
-
finally {
|
|
376
|
-
server.closeAllConnections();
|
|
377
|
-
await new Promise((ok) => server.close(ok));
|
|
378
|
-
}
|
|
379
|
-
}
|
|
380
|
-
}, 10000);
|
|
381
|
-
it("answers 500 when the handler throws before the response starts", async () => {
|
|
382
|
-
const h = async () => {
|
|
383
|
-
throw new Error("handler exploded");
|
|
384
|
-
};
|
|
385
|
-
const spy = console.error;
|
|
386
|
-
console.error = () => { };
|
|
387
|
-
try {
|
|
388
|
-
await withServer(h, false, async (port) => {
|
|
389
|
-
const r = await call(port, "/", {});
|
|
390
|
-
expect(r.status).toBe(500);
|
|
391
|
-
expect(r.body.toString()).toBe("Internal Server Error\n");
|
|
392
|
-
expect(r.body.toString()).not.toContain("exploded");
|
|
393
|
-
});
|
|
394
|
-
}
|
|
395
|
-
finally {
|
|
396
|
-
console.error = spy;
|
|
397
|
-
}
|
|
398
|
-
});
|
|
399
|
-
it("aborts the connection when the body fails after headers were sent", async () => {
|
|
400
|
-
const h = async () => {
|
|
401
|
-
let sent = false;
|
|
402
|
-
const stream = new ReadableStream({
|
|
403
|
-
pull(controller) {
|
|
404
|
-
if (!sent) {
|
|
405
|
-
sent = true;
|
|
406
|
-
controller.enqueue(new TextEncoder().encode("partial"));
|
|
407
|
-
}
|
|
408
|
-
else
|
|
409
|
-
controller.error(new Error("render failed midway"));
|
|
410
|
-
},
|
|
411
|
-
});
|
|
412
|
-
return new Response(stream, { headers: { "content-type": "text/plain" } });
|
|
413
|
-
};
|
|
414
|
-
await withServer(h, false, async (port) => {
|
|
415
|
-
await expect(call(port, "/", {})).rejects.toBeTruthy();
|
|
416
|
-
});
|
|
417
|
-
});
|
|
418
|
-
it("writeResponse is exported for hosts that own the socket", () => {
|
|
419
|
-
expect(typeof writeResponse).toBe("function");
|
|
420
|
-
});
|
|
421
|
-
});
|
|
422
|
-
describe("startNodeServer and defaultDistDir", () => {
|
|
423
|
-
it("binds PORT/HOST, serves the handler and reports the port", async () => {
|
|
424
|
-
const probe = net.createServer();
|
|
425
|
-
const port = await listen(probe);
|
|
426
|
-
await new Promise((ok) => probe.close(ok));
|
|
427
|
-
const prev = { PORT: process.env.PORT, HOST: process.env.HOST };
|
|
428
|
-
process.env.PORT = String(port);
|
|
429
|
-
process.env.HOST = "127.0.0.1";
|
|
430
|
-
const log = console.log;
|
|
431
|
-
const lines = [];
|
|
432
|
-
console.log = (...a) => lines.push(a.join(" "));
|
|
433
|
-
let server;
|
|
434
|
-
try {
|
|
435
|
-
server = await startNodeServer({ handler: async () => new Response("up"), distDir: dist, trustProxy: false });
|
|
436
|
-
const r = await call(port, "/", {});
|
|
437
|
-
expect(r.body.toString()).toBe("up");
|
|
438
|
-
expect(lines.join("\n")).toContain(`http://127.0.0.1:${port}`);
|
|
439
|
-
expect(server.headersTimeout).toBe(10000);
|
|
440
|
-
}
|
|
441
|
-
finally {
|
|
442
|
-
console.log = log;
|
|
443
|
-
server?.closeAllConnections();
|
|
444
|
-
await new Promise((ok) => (server ? server.close(ok) : ok(undefined)));
|
|
445
|
-
if (prev.PORT === undefined)
|
|
446
|
-
delete process.env.PORT;
|
|
447
|
-
else
|
|
448
|
-
process.env.PORT = prev.PORT;
|
|
449
|
-
if (prev.HOST === undefined)
|
|
450
|
-
delete process.env.HOST;
|
|
451
|
-
else
|
|
452
|
-
process.env.HOST = prev.HOST;
|
|
453
|
-
}
|
|
454
|
-
});
|
|
455
|
-
it("fails to start when the port is taken", async () => {
|
|
456
|
-
const blocker = http.createServer();
|
|
457
|
-
const port = await listen(blocker);
|
|
458
|
-
const prev = { PORT: process.env.PORT, HOST: process.env.HOST };
|
|
459
|
-
process.env.PORT = String(port);
|
|
460
|
-
process.env.HOST = "127.0.0.1";
|
|
461
|
-
try {
|
|
462
|
-
await expect(startNodeServer({ handler: async () => new Response("x"), distDir: dist, trustProxy: false })).rejects.toMatchObject({ code: "EADDRINUSE" });
|
|
463
|
-
}
|
|
464
|
-
finally {
|
|
465
|
-
await new Promise((ok) => blocker.close(ok));
|
|
466
|
-
if (prev.PORT === undefined)
|
|
467
|
-
delete process.env.PORT;
|
|
468
|
-
else
|
|
469
|
-
process.env.PORT = prev.PORT;
|
|
470
|
-
if (prev.HOST === undefined)
|
|
471
|
-
delete process.env.HOST;
|
|
472
|
-
else
|
|
473
|
-
process.env.HOST = prev.HOST;
|
|
474
|
-
}
|
|
475
|
-
});
|
|
476
|
-
it("defaultDistDir is two levels above dist/.krate/server, unless KRATE_DIST is set", () => {
|
|
477
|
-
const prev = process.env.KRATE_DIST;
|
|
478
|
-
delete process.env.KRATE_DIST;
|
|
479
|
-
try {
|
|
480
|
-
const meta = "file://" + path.join(dist, ".krate", "server", "server.mjs");
|
|
481
|
-
expect(defaultDistDir(meta)).toBe(path.resolve(dist));
|
|
482
|
-
process.env.KRATE_DIST = "/srv/site";
|
|
483
|
-
expect(defaultDistDir(meta)).toBe(path.resolve("/srv/site"));
|
|
484
|
-
}
|
|
485
|
-
finally {
|
|
486
|
-
if (prev === undefined)
|
|
487
|
-
delete process.env.KRATE_DIST;
|
|
488
|
-
else
|
|
489
|
-
process.env.KRATE_DIST = prev;
|
|
490
|
-
}
|
|
491
|
-
});
|
|
492
138
|
});
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Platform access for server code, exported from `@krate/runtime/server`.
|
|
3
|
+
*
|
|
4
|
+
* The portable server handler runs every request inside an AsyncLocalStorage
|
|
5
|
+
* scope published on `globalThis[Symbol.for('krate.platform.store')]` (the
|
|
6
|
+
* same pattern as the request store), so pages, API routes, server actions
|
|
7
|
+
* and middleware all see the same `{ env, ctx, cf }` of the request in flight.
|
|
8
|
+
* On the cloudflare target `env` holds the Worker bindings (D1, KV, R2,
|
|
9
|
+
* Durable Objects, secrets); it is never copied into `process.env`.
|
|
10
|
+
*/
|
|
11
|
+
/** The deploy target the handler runs on, or "none" outside a handler (dev, tests). */
|
|
12
|
+
export type PlatformTarget = 'cloudflare' | 'vercel' | 'netlify' | 'node' | 'none';
|
|
13
|
+
/** Keeps the instance alive for work that outlives the response. */
|
|
14
|
+
export interface PlatformExecutionContext {
|
|
15
|
+
waitUntil(work: Promise<unknown>): void;
|
|
16
|
+
/** Cloudflare only: let the request fall through to the origin when the Worker throws. */
|
|
17
|
+
passThroughOnException?(): void;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Augment this interface with your bindings to type `env`:
|
|
21
|
+
*
|
|
22
|
+
* declare module '@krate/runtime/server' {
|
|
23
|
+
* interface KrateCloudflareEnv { DB: D1Database; CACHE: KVNamespace }
|
|
24
|
+
* }
|
|
25
|
+
*/
|
|
26
|
+
export interface KrateCloudflareEnv {
|
|
27
|
+
}
|
|
28
|
+
export interface PlatformContext<Env = Record<string, unknown>> {
|
|
29
|
+
target: PlatformTarget;
|
|
30
|
+
/** The Worker `env` on cloudflare; an empty object elsewhere. */
|
|
31
|
+
env: Env;
|
|
32
|
+
ctx: PlatformExecutionContext;
|
|
33
|
+
/** Cloudflare's `request.cf` properties (colo, country, ...), when present. */
|
|
34
|
+
cf: Record<string, unknown> | undefined;
|
|
35
|
+
}
|
|
36
|
+
export interface CloudflareContext<Env = KrateCloudflareEnv & Record<string, any>> extends PlatformContext<Env> {
|
|
37
|
+
target: 'cloudflare';
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The platform of the request being served. Outside a request handler (`krate
|
|
41
|
+
* dev`, tests) it returns an empty environment and a `waitUntil` that just
|
|
42
|
+
* detaches the promise, so code that only uses it opportunistically keeps working.
|
|
43
|
+
*/
|
|
44
|
+
export declare function getPlatform<Env = Record<string, unknown>>(): PlatformContext<Env>;
|
|
45
|
+
/**
|
|
46
|
+
* The Cloudflare `{ env, ctx, cf }` of the request being served. Throws
|
|
47
|
+
* outside a Worker request, so a missing binding is an error at the call
|
|
48
|
+
* site rather than an `undefined` later.
|
|
49
|
+
*/
|
|
50
|
+
export declare function getCloudflareContext<Env = KrateCloudflareEnv & Record<string, any>>(): CloudflareContext<Env>;
|
|
51
|
+
/** Runs work after the response is sent, through the platform's waitUntil when there is one. */
|
|
52
|
+
export declare function platformWaitUntil(work: Promise<unknown>): boolean;
|
package/dist/platform.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Platform access for server code, exported from `@krate/runtime/server`.
|
|
3
|
+
*
|
|
4
|
+
* The portable server handler runs every request inside an AsyncLocalStorage
|
|
5
|
+
* scope published on `globalThis[Symbol.for('krate.platform.store')]` (the
|
|
6
|
+
* same pattern as the request store), so pages, API routes, server actions
|
|
7
|
+
* and middleware all see the same `{ env, ctx, cf }` of the request in flight.
|
|
8
|
+
* On the cloudflare target `env` holds the Worker bindings (D1, KV, R2,
|
|
9
|
+
* Durable Objects, secrets); it is never copied into `process.env`.
|
|
10
|
+
*/
|
|
11
|
+
const PLATFORM_STORE = Symbol.for('krate.platform.store');
|
|
12
|
+
function current() {
|
|
13
|
+
const store = globalThis[PLATFORM_STORE];
|
|
14
|
+
return store && typeof store.getStore === 'function' ? store.getStore() : undefined;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* The platform of the request being served. Outside a request handler (`krate
|
|
18
|
+
* dev`, tests) it returns an empty environment and a `waitUntil` that just
|
|
19
|
+
* detaches the promise, so code that only uses it opportunistically keeps working.
|
|
20
|
+
*/
|
|
21
|
+
export function getPlatform() {
|
|
22
|
+
const c = current();
|
|
23
|
+
if (c)
|
|
24
|
+
return c;
|
|
25
|
+
return {
|
|
26
|
+
target: 'none',
|
|
27
|
+
env: {},
|
|
28
|
+
ctx: {
|
|
29
|
+
waitUntil(work) {
|
|
30
|
+
Promise.resolve(work).catch((err) => console.error(`[krate] waitUntil task failed: ${(err && err.stack) || err}`));
|
|
31
|
+
},
|
|
32
|
+
},
|
|
33
|
+
cf: undefined,
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The Cloudflare `{ env, ctx, cf }` of the request being served. Throws
|
|
38
|
+
* outside a Worker request, so a missing binding is an error at the call
|
|
39
|
+
* site rather than an `undefined` later.
|
|
40
|
+
*/
|
|
41
|
+
export function getCloudflareContext() {
|
|
42
|
+
const c = current();
|
|
43
|
+
if (!c || c.target !== 'cloudflare') {
|
|
44
|
+
throw new Error('getCloudflareContext() works only while a request is served by the cloudflare target (krate deploy --target cloudflare); ' +
|
|
45
|
+
(c ? `this request is served by "${c.target}"` : 'there is no request in flight here (krate dev and krate serve run on Node and have no Worker bindings)') +
|
|
46
|
+
'. Use getPlatform() for code that also has to run elsewhere.');
|
|
47
|
+
}
|
|
48
|
+
return c;
|
|
49
|
+
}
|
|
50
|
+
/** Runs work after the response is sent, through the platform's waitUntil when there is one. */
|
|
51
|
+
export function platformWaitUntil(work) {
|
|
52
|
+
const c = current();
|
|
53
|
+
if (!c || c.target === 'none' || !c.ctx || typeof c.ctx.waitUntil !== 'function')
|
|
54
|
+
return false;
|
|
55
|
+
c.ctx.waitUntil(work);
|
|
56
|
+
return true;
|
|
57
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { after } from './after.js';
|
|
3
|
+
import { env as shimEnv } from './cloudflare-workers.js';
|
|
4
|
+
import { getCloudflareContext, getPlatform } from './platform.js';
|
|
5
|
+
import { runWithPlatform } from './server-handler.js';
|
|
6
|
+
function fakeContext() {
|
|
7
|
+
const waited = [];
|
|
8
|
+
return { waited, ctx: { env: { DB: 'db-binding', GREETING: 'hi' }, cf: { country: 'NL' }, waitUntil: (p) => waited.push(p) } };
|
|
9
|
+
}
|
|
10
|
+
describe('platform access', () => {
|
|
11
|
+
it('returns an empty environment outside a request', () => {
|
|
12
|
+
const p = getPlatform();
|
|
13
|
+
expect(p.target).toBe('none');
|
|
14
|
+
expect(p.env).toEqual({});
|
|
15
|
+
expect(() => getCloudflareContext()).toThrow(/outside|no request|cloudflare target/);
|
|
16
|
+
});
|
|
17
|
+
it('exposes env, ctx and cf of the request being served', async () => {
|
|
18
|
+
const { ctx } = fakeContext();
|
|
19
|
+
const seen = await runWithPlatform('cloudflare', ctx, async () => {
|
|
20
|
+
await Promise.resolve();
|
|
21
|
+
const cf = getCloudflareContext();
|
|
22
|
+
return { db: cf.env.DB, country: cf.cf?.country, target: getPlatform().target };
|
|
23
|
+
});
|
|
24
|
+
expect(seen).toEqual({ db: 'db-binding', country: 'NL', target: 'cloudflare' });
|
|
25
|
+
expect(getPlatform().target).toBe('none');
|
|
26
|
+
});
|
|
27
|
+
it('refuses getCloudflareContext on other targets', () => {
|
|
28
|
+
const { ctx } = fakeContext();
|
|
29
|
+
expect(() => runWithPlatform('node', ctx, () => getCloudflareContext())).toThrow(/"node"/);
|
|
30
|
+
});
|
|
31
|
+
it('backs after() with ctx.waitUntil', async () => {
|
|
32
|
+
const { ctx, waited } = fakeContext();
|
|
33
|
+
let ran = false;
|
|
34
|
+
runWithPlatform('cloudflare', ctx, () => after(() => { ran = true; }));
|
|
35
|
+
expect(waited).toHaveLength(1);
|
|
36
|
+
await waited[0];
|
|
37
|
+
expect(ran).toBe(true);
|
|
38
|
+
});
|
|
39
|
+
it('serves the cloudflare:workers stand-in from the same request env', () => {
|
|
40
|
+
const { ctx } = fakeContext();
|
|
41
|
+
expect(runWithPlatform('cloudflare', ctx, () => shimEnv.DB)).toBe('db-binding');
|
|
42
|
+
expect(() => shimEnv.DB).toThrow(/cloudflare target/);
|
|
43
|
+
});
|
|
44
|
+
});
|