@krate/runtime 0.5.0-alpha.4 → 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.
Files changed (165) hide show
  1. package/dist/action-context.d.ts +5 -1
  2. package/dist/action-context.js +33 -3
  3. package/dist/action-context.test.js +26 -1
  4. package/dist/actions.d.ts +12 -1
  5. package/dist/actions.js +84 -4
  6. package/dist/actions.test.js +61 -1
  7. package/dist/assets-static.d.ts +5 -0
  8. package/dist/assets-static.js +31 -0
  9. package/dist/boundary.d.ts +12 -0
  10. package/dist/boundary.js +53 -13
  11. package/dist/cache-adapter.d.ts +113 -0
  12. package/dist/cache-adapter.js +217 -0
  13. package/dist/cache-adapter.test.d.ts +1 -0
  14. package/dist/cache-adapter.test.js +244 -0
  15. package/dist/cache-redis.d.ts +27 -0
  16. package/dist/cache-redis.js +110 -0
  17. package/dist/cache-scope.d.ts +25 -9
  18. package/dist/cache-scope.js +64 -13
  19. package/dist/cache.d.ts +1 -0
  20. package/dist/cache.js +3 -3
  21. package/dist/cache.test.js +16 -0
  22. package/dist/class-component.js +6 -0
  23. package/dist/class-component.test.js +53 -2
  24. package/dist/class-helpers.d.ts +4 -4
  25. package/dist/class-helpers.js +357 -32
  26. package/dist/class-helpers.test.d.ts +1 -0
  27. package/dist/class-helpers.test.js +169 -0
  28. package/dist/context.d.ts +16 -2
  29. package/dist/context.js +44 -3
  30. package/dist/dev-overlay.js +85 -12
  31. package/dist/dev-overlay.test.js +22 -0
  32. package/dist/dom.d.ts +15 -0
  33. package/dist/dom.js +97 -3
  34. package/dist/effect-errors.test.d.ts +1 -0
  35. package/dist/effect-errors.test.js +163 -0
  36. package/dist/effects.d.ts +8 -0
  37. package/dist/effects.js +13 -0
  38. package/dist/error-overlay.js +7 -7
  39. package/dist/handler-html.d.ts +63 -0
  40. package/dist/handler-html.js +285 -0
  41. package/dist/handler-html.test.d.ts +1 -0
  42. package/dist/handler-html.test.js +256 -0
  43. package/dist/handler-routing.d.ts +83 -0
  44. package/dist/handler-routing.js +579 -0
  45. package/dist/handler-routing.test.d.ts +1 -0
  46. package/dist/handler-routing.test.js +99 -0
  47. package/dist/handler-segments.d.ts +43 -0
  48. package/dist/handler-segments.js +115 -0
  49. package/dist/handler-segments.test.d.ts +1 -0
  50. package/dist/handler-segments.test.js +217 -0
  51. package/dist/head-tags.d.ts +51 -0
  52. package/dist/head-tags.js +329 -0
  53. package/dist/head-tags.test.d.ts +1 -0
  54. package/dist/head-tags.test.js +131 -0
  55. package/dist/highlight-bind.d.ts +42 -0
  56. package/dist/highlight-bind.js +176 -0
  57. package/dist/highlight-bind.test.d.ts +1 -0
  58. package/dist/highlight-bind.test.js +124 -0
  59. package/dist/highlight.d.ts +93 -0
  60. package/dist/highlight.js +426 -0
  61. package/dist/highlight.test.d.ts +1 -0
  62. package/dist/highlight.test.js +56 -0
  63. package/dist/hints.d.ts +19 -0
  64. package/dist/hints.js +97 -0
  65. package/dist/hook-args.d.ts +7 -0
  66. package/dist/hook-args.js +10 -0
  67. package/dist/htmlspec-attributes.d.ts +1 -0
  68. package/dist/htmlspec-attributes.js +159 -0
  69. package/dist/index.d.ts +4 -0
  70. package/dist/index.js +3 -0
  71. package/dist/jsx-types.d.ts +11 -0
  72. package/dist/krate-core.js +2 -0
  73. package/dist/krate-dev.js +75 -12
  74. package/dist/krate-f-actions.js +2 -0
  75. package/dist/krate-f-classes.js +8 -0
  76. package/dist/krate-f-helpers.js +2 -0
  77. package/dist/krate-f-highlight.js +2 -0
  78. package/dist/krate-f-list.js +2 -0
  79. package/dist/krate-f-navigation.js +2 -0
  80. package/dist/krate-f-router-lite.js +2 -0
  81. package/dist/krate-f-router.js +2 -0
  82. package/dist/krate-features.json +493 -0
  83. package/dist/krate-hydrate-lite.js +5 -5
  84. package/dist/krate-hydrate.js +5 -5
  85. package/dist/krate-runtime.js +5 -5
  86. package/dist/list.js +4 -2
  87. package/dist/metadata-routes.d.ts +75 -0
  88. package/dist/metadata-routes.js +76 -0
  89. package/dist/metadata.d.ts +222 -0
  90. package/dist/metadata.js +452 -0
  91. package/dist/metadata.test.d.ts +1 -0
  92. package/dist/metadata.test.js +167 -0
  93. package/dist/navigation-server.d.ts +27 -0
  94. package/dist/navigation-server.js +90 -0
  95. package/dist/navigation.d.ts +37 -0
  96. package/dist/navigation.js +195 -0
  97. package/dist/navigation.test.d.ts +1 -0
  98. package/dist/navigation.test.js +130 -0
  99. package/dist/node-server.d.ts +22 -0
  100. package/dist/node-server.js +436 -0
  101. package/dist/node-server.test.d.ts +1 -0
  102. package/dist/node-server.test.js +492 -0
  103. package/dist/og-files.d.ts +2 -0
  104. package/dist/og-files.js +19 -0
  105. package/dist/og.d.ts +56 -0
  106. package/dist/og.js +156 -0
  107. package/dist/patterns.test.d.ts +1 -0
  108. package/dist/patterns.test.js +98 -0
  109. package/dist/react.d.ts +47 -0
  110. package/dist/react.js +59 -1
  111. package/dist/react19.test.d.ts +1 -0
  112. package/dist/react19.test.js +176 -0
  113. package/dist/reactivity-core.test.d.ts +1 -0
  114. package/dist/reactivity-core.test.js +152 -0
  115. package/dist/reconcile.js +4 -2
  116. package/dist/request-context.d.ts +23 -0
  117. package/dist/request-context.js +45 -0
  118. package/dist/resp.d.ts +55 -0
  119. package/dist/resp.js +239 -0
  120. package/dist/router-layout.test.js +70 -0
  121. package/dist/router-nav.test.js +65 -0
  122. package/dist/router-speculation.test.d.ts +1 -0
  123. package/dist/router-speculation.test.js +25 -0
  124. package/dist/router-styles.test.d.ts +1 -0
  125. package/dist/router-styles.test.js +98 -0
  126. package/dist/router.js +175 -36
  127. package/dist/segmented-lru.d.ts +19 -0
  128. package/dist/segmented-lru.js +87 -0
  129. package/dist/server-async.test.js +43 -1
  130. package/dist/server-handler.d.ts +165 -0
  131. package/dist/server-handler.js +1826 -0
  132. package/dist/server-handler.test.d.ts +1 -0
  133. package/dist/server-handler.test.js +522 -0
  134. package/dist/server-highlight.test.d.ts +1 -0
  135. package/dist/server-highlight.test.js +32 -0
  136. package/dist/server-renderer.js +165 -720
  137. package/dist/server-renderer.test.d.ts +1 -0
  138. package/dist/server-renderer.test.js +266 -0
  139. package/dist/server.d.ts +13 -1
  140. package/dist/server.js +131 -16
  141. package/dist/server.test.js +20 -0
  142. package/dist/sha256.d.ts +1 -0
  143. package/dist/sha256.js +66 -0
  144. package/dist/sha256.test.d.ts +1 -0
  145. package/dist/sha256.test.js +13 -0
  146. package/dist/shared-isr.d.ts +31 -0
  147. package/dist/shared-isr.js +142 -0
  148. package/dist/signal.d.ts +3 -2
  149. package/dist/signal.js +163 -23
  150. package/dist/slots.js +12 -1
  151. package/dist/ssr-core-behavior.test.d.ts +1 -0
  152. package/dist/ssr-core-behavior.test.js +620 -0
  153. package/dist/ssr-core.d.ts +175 -0
  154. package/dist/ssr-core.js +940 -0
  155. package/dist/ssr-core.test.d.ts +1 -0
  156. package/dist/ssr-core.test.js +324 -0
  157. package/dist/static-memory.d.ts +3 -0
  158. package/dist/static-memory.js +47 -0
  159. package/dist/static-memory.test.d.ts +1 -0
  160. package/dist/static-memory.test.js +26 -0
  161. package/dist/test-redis.d.ts +12 -0
  162. package/dist/test-redis.js +131 -0
  163. package/dist/use-id.d.ts +8 -0
  164. package/dist/use-id.js +40 -0
  165. package/package.json +30 -2
@@ -0,0 +1,492 @@
1
+ // @vitest-environment node
2
+ import fs from "node:fs";
3
+ import http from "node:http";
4
+ import net from "node:net";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import zlib from "node:zlib";
8
+ import { afterAll, beforeAll, describe, expect, it } from "vitest";
9
+ import { createNodeStaticLayer, defaultDistDir, nodeRequestListener, requestFromNode, startNodeServer, writeResponse } from "./node-server.js";
10
+ let tmp;
11
+ let dist;
12
+ function write(rel, data) {
13
+ const f = path.join(dist, rel);
14
+ fs.mkdirSync(path.dirname(f), { recursive: true });
15
+ fs.writeFileSync(f, data);
16
+ }
17
+ beforeAll(() => {
18
+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), "krate-node-server-"));
19
+ dist = path.join(tmp, "dist");
20
+ write("index.html", "<h1>home</h1>");
21
+ write("about/index.html", "<h1>about</h1>");
22
+ write("empty/readme.txt", "no index here");
23
+ write("app.abc123.js", "console.log('0123456789');");
24
+ write("app.abc123.js.gz", zlib.gzipSync("gz-body"));
25
+ write("app.abc123.js.br", zlib.brotliCompressSync("br-body"));
26
+ write("data.bin", Buffer.from("0123456789"));
27
+ write("logo.png", Buffer.from("not really a png"));
28
+ write("page.html", "<p>page</p>");
29
+ write(".env", "SECRET=1");
30
+ write(".well-known/security.txt", "Contact: a@example.com");
31
+ write(".krate/manifest.json", "{}");
32
+ write("server-manifest.json", "{}");
33
+ write("api-node/hello.mjs", "export {}");
34
+ fs.writeFileSync(path.join(tmp, "outside.txt"), "outside the site");
35
+ fs.symlinkSync(path.join(tmp, "outside.txt"), path.join(dist, "escape.txt"));
36
+ });
37
+ afterAll(() => {
38
+ fs.rmSync(tmp, { recursive: true, force: true });
39
+ });
40
+ function req(url, init = {}) {
41
+ return new Request("http://localhost" + url, init);
42
+ }
43
+ describe("createNodeStaticLayer", () => {
44
+ const layer = () => createNodeStaticLayer(dist);
45
+ it("serves a file with type, length, validators and range support", async () => {
46
+ const r = (await layer().serve(req("/data.bin"), "/data.bin"));
47
+ expect(r.status).toBe(200);
48
+ expect(r.headers.get("content-type")).toBe("application/octet-stream");
49
+ expect(r.headers.get("content-length")).toBe("10");
50
+ expect(r.headers.get("accept-ranges")).toBe("bytes");
51
+ expect(r.headers.get("last-modified")).toMatch(/GMT$/);
52
+ expect(await r.text()).toBe("0123456789");
53
+ });
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
+ it.each([
62
+ ["dotfile", "/.env"],
63
+ ["encoded dotfile", "/%2eenv"],
64
+ ["dotfile inside a path", "/about/../.env"],
65
+ ["krate internals", "/.krate/manifest.json"],
66
+ ["server manifest", "/server-manifest.json"],
67
+ ["api bundles", "/api-node/hello.mjs"],
68
+ ["parent traversal", "/../outside.txt"],
69
+ ["encoded traversal", "/%2e%2e/outside.txt"],
70
+ ["backslash traversal", "/..%5coutside.txt"],
71
+ ["symlink out of the site", "/escape.txt"],
72
+ ["null byte", "/data.bin%00.html"],
73
+ ])("does not serve %s", async (_name, p) => {
74
+ const l = layer();
75
+ expect(await l.serve(req(p), decodeURIComponentSafe(p))).toBeNull();
76
+ expect(await l.exists(decodeURIComponentSafe(p))).toBe(false);
77
+ });
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
+ });
184
+ function decodeURIComponentSafe(p) {
185
+ try {
186
+ return decodeURIComponent(p);
187
+ }
188
+ catch {
189
+ return p;
190
+ }
191
+ }
192
+ function listen(server) {
193
+ return new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve(server.address().port)));
194
+ }
195
+ function call(port, p, headers = {}, opts = {}) {
196
+ return new Promise((resolve, reject) => {
197
+ const r = http.request({ host: "127.0.0.1", port, path: p, method: opts.method || "GET", headers }, (res) => {
198
+ const chunks = [];
199
+ res.on("data", (c) => chunks.push(c));
200
+ res.on("end", () => resolve({ status: res.statusCode || 0, headers: res.headers, rawHeaders: res.rawHeaders, body: Buffer.concat(chunks) }));
201
+ res.on("error", reject);
202
+ });
203
+ r.on("error", reject);
204
+ if (opts.body !== undefined)
205
+ r.write(opts.body);
206
+ r.end();
207
+ });
208
+ }
209
+ async function withServer(handler, trustProxy, fn) {
210
+ const server = http.createServer(nodeRequestListener(handler, trustProxy));
211
+ const port = await listen(server);
212
+ try {
213
+ return await fn(port);
214
+ }
215
+ finally {
216
+ server.closeAllConnections();
217
+ await new Promise((ok) => server.close(ok));
218
+ }
219
+ }
220
+ describe("requestFromNode", () => {
221
+ const echo = async (request) => Response.json({
222
+ url: request.url,
223
+ method: request.method,
224
+ xff: request.headers.get("x-forwarded-for"),
225
+ host: request.headers.get("x-forwarded-host"),
226
+ proto: request.headers.get("x-forwarded-proto"),
227
+ forwarded: request.headers.get("forwarded"),
228
+ realIp: request.headers.get("x-real-ip"),
229
+ body: request.method === "POST" ? await request.text() : null,
230
+ cookie: request.headers.get("cookie"),
231
+ });
232
+ it("replaces client-supplied forwarding headers with what the socket shows", async () => {
233
+ await withServer(echo, false, async (port) => {
234
+ const r = await call(port, "/p?q=1", {
235
+ "x-forwarded-for": "1.2.3.4",
236
+ "x-forwarded-host": "evil.example",
237
+ "x-forwarded-proto": "https",
238
+ forwarded: "for=1.2.3.4",
239
+ "x-real-ip": "1.2.3.4",
240
+ host: "site.test",
241
+ });
242
+ const j = JSON.parse(r.body.toString());
243
+ expect(j.xff).toBe("127.0.0.1");
244
+ expect(j.host).toBe("site.test");
245
+ expect(j.proto).toBe("http");
246
+ expect(j.forwarded).toBeNull();
247
+ expect(j.realIp).toBeNull();
248
+ expect(j.url).toBe("http://site.test/p?q=1");
249
+ });
250
+ });
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
+ });
@@ -0,0 +1,2 @@
1
+ /** Returns the bytes of src (under public/ or the project root), or null when absent. */
2
+ export declare function readLocalImage(src: string, root: string): Promise<Uint8Array | null>;
@@ -0,0 +1,19 @@
1
+ // Reads a local image for ImageResponse. This is the only Node-file-system
2
+ // use in the image path; the Cloudflare and other non-Node server bundles
3
+ // replace this module with a stub (see serverdeploy.go), because per-request
4
+ // image reads happen on the Krate host, never in a Worker.
5
+ /** Returns the bytes of src (under public/ or the project root), or null when absent. */
6
+ export async function readLocalImage(src, root) {
7
+ const fs = await import('node:fs/promises');
8
+ const path = await import('node:path');
9
+ const rel = src.replace(/^\//, '');
10
+ for (const base of [path.join(root, 'public', rel), path.join(root, rel), src]) {
11
+ try {
12
+ return await fs.readFile(base);
13
+ }
14
+ catch {
15
+ /* try the next place */
16
+ }
17
+ }
18
+ return null;
19
+ }
package/dist/og.d.ts ADDED
@@ -0,0 +1,56 @@
1
+ export interface ImageResponseFont {
2
+ name: string;
3
+ data: ArrayBuffer | ArrayBufferView;
4
+ weight?: number;
5
+ style?: 'normal' | 'italic';
6
+ }
7
+ export interface ImageResponseOptions {
8
+ /** Width in pixels (default 1200). */
9
+ width?: number;
10
+ /** Height in pixels (default 630). */
11
+ height?: number;
12
+ /** TrueType or OpenType fonts to draw with (the built-in Go fonts cover Latin text). */
13
+ fonts?: ImageResponseFont[];
14
+ status?: number;
15
+ statusText?: string;
16
+ headers?: HeadersInit;
17
+ }
18
+ /** What the renderer takes: see internal/ogimage/spec.go. */
19
+ export interface ImageNode {
20
+ type: 'element' | 'text';
21
+ tag?: string;
22
+ style?: Record<string, unknown>;
23
+ src?: string;
24
+ text?: string;
25
+ children?: ImageNode[];
26
+ }
27
+ export interface ImageSpec {
28
+ width: number;
29
+ height: number;
30
+ fonts?: Array<{
31
+ name: string;
32
+ data: string;
33
+ weight?: number;
34
+ style?: string;
35
+ }>;
36
+ tree: ImageNode;
37
+ }
38
+ /** Serializes a JSX value to the renderer's tree. Function components are called. */
39
+ export declare function serializeElement(node: unknown, path?: string): ImageNode[];
40
+ /** The renderer spec for an element and options. */
41
+ export declare function buildImageSpec(element: unknown, options?: ImageResponseOptions): ImageSpec;
42
+ /**
43
+ * Replaces the src of every <img> (a file path under root or public/, or an
44
+ * http(s) URL) with a data: URI, so the Go renderer needs no network or file
45
+ * access. Run at build time and before a per-request render.
46
+ */
47
+ export declare function inlineImages(spec: ImageSpec, root: string): Promise<void>;
48
+ /**
49
+ * A Response that carries a PNG. Built from JSX with the same options as
50
+ * Next.js's ImageResponse (width, height, fonts, status, headers).
51
+ */
52
+ export declare class ImageResponse extends Response {
53
+ /** The renderer spec; the build reads it instead of the body. */
54
+ readonly __krateImage: ImageSpec;
55
+ constructor(element: unknown, options?: ImageResponseOptions);
56
+ }