@krate/runtime 0.5.0-beta.3 → 0.5.0-rc.10

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 (219) hide show
  1. package/dist/action-context.js +1 -1
  2. package/dist/actions.d.ts +7 -0
  3. package/dist/actions.js +34 -10
  4. package/dist/after.d.ts +28 -0
  5. package/dist/after.js +48 -0
  6. package/dist/assets-static.d.ts +10 -1
  7. package/dist/assets-static.js +10 -2
  8. package/dist/base-path.d.ts +7 -0
  9. package/dist/base-path.js +20 -0
  10. package/dist/boundary.js +1 -1
  11. package/dist/builtin-tags.d.ts +12 -0
  12. package/dist/builtin-tags.js +42 -0
  13. package/dist/cache-adapter.js +1 -1
  14. package/dist/cache-scope.d.ts +8 -0
  15. package/dist/cache-scope.js +14 -1
  16. package/dist/cloudflare-workers.d.ts +2 -0
  17. package/dist/cloudflare-workers.js +27 -0
  18. package/dist/context.d.ts +5 -0
  19. package/dist/context.js +28 -17
  20. package/dist/dev-overlay.d.ts +54 -3
  21. package/dist/dev-overlay.js +496 -91
  22. package/dist/dom.d.ts +4 -0
  23. package/dist/dom.js +62 -16
  24. package/dist/effects.js +43 -10
  25. package/dist/events.d.ts +2 -0
  26. package/dist/events.js +18 -0
  27. package/dist/flight-props.d.ts +7 -0
  28. package/dist/flight-props.js +105 -0
  29. package/dist/handler-html.js +4 -4
  30. package/dist/handler-routing.d.ts +2 -23
  31. package/dist/handler-routing.js +9 -190
  32. package/dist/handler-segments.d.ts +6 -0
  33. package/dist/handler-segments.js +18 -4
  34. package/dist/head-tags.d.ts +9 -0
  35. package/dist/head-tags.js +93 -6
  36. package/dist/highlight-bind.js +1 -1
  37. package/dist/highlight.d.ts +3 -2
  38. package/dist/highlight.js +17 -12
  39. package/dist/hints.d.ts +25 -2
  40. package/dist/hints.js +147 -74
  41. package/dist/index.d.ts +2 -0
  42. package/dist/index.js +3 -0
  43. package/dist/island-swap.d.ts +47 -0
  44. package/dist/island-swap.js +635 -0
  45. package/dist/jsx-dev-runtime.d.ts +1 -1
  46. package/dist/jsx-types.d.ts +99 -3
  47. package/dist/krate-core.js +1 -1
  48. package/dist/krate-dev.js +407 -80
  49. package/dist/krate-f-actions.js +1 -1
  50. package/dist/krate-f-classes.js +1 -1
  51. package/dist/krate-f-highlight.js +1 -1
  52. package/dist/krate-f-list.js +1 -1
  53. package/dist/krate-f-navigation.js +1 -1
  54. package/dist/krate-f-router-lite.js +1 -1
  55. package/dist/krate-f-router.js +1 -1
  56. package/dist/krate-features.json +455 -0
  57. package/dist/krate-hydrate-lite.js +5 -5
  58. package/dist/krate-hydrate.js +5 -5
  59. package/dist/krate-island-swap.js +1 -0
  60. package/dist/krate-runtime.js +5 -5
  61. package/dist/krate-suspense.js +1 -1
  62. package/dist/list.d.ts +14 -4
  63. package/dist/list.js +30 -23
  64. package/dist/metadata.js +5 -2
  65. package/dist/navigation-react.d.ts +13 -0
  66. package/dist/navigation-react.js +86 -0
  67. package/dist/navigation.d.ts +19 -0
  68. package/dist/navigation.js +35 -0
  69. package/dist/node-server.js +3 -3
  70. package/dist/og.js +1 -1
  71. package/dist/platform.d.ts +52 -0
  72. package/dist/platform.js +57 -0
  73. package/dist/react-compat.d.ts +39 -0
  74. package/dist/react-compat.js +359 -0
  75. package/dist/react-server.d.ts +63 -0
  76. package/dist/react-server.js +125 -0
  77. package/dist/region-wire.d.ts +10 -0
  78. package/dist/region-wire.js +154 -0
  79. package/dist/request-context.js +1 -1
  80. package/dist/request-extras.d.ts +4 -0
  81. package/dist/request-extras.js +51 -0
  82. package/dist/resp.js +1 -1
  83. package/dist/route-source.d.ts +39 -0
  84. package/dist/route-source.js +532 -0
  85. package/dist/router-lite.js +3 -9
  86. package/dist/router.d.ts +1 -1
  87. package/dist/router.js +675 -100
  88. package/dist/server-handler.d.ts +69 -1
  89. package/dist/server-handler.js +515 -96
  90. package/dist/server-renderer.js +16 -7
  91. package/dist/server.d.ts +73 -16
  92. package/dist/server.js +619 -102
  93. package/dist/sha256.js +9 -9
  94. package/dist/signal.js +47 -20
  95. package/dist/site-config.d.ts +15 -0
  96. package/dist/site-config.js +28 -0
  97. package/dist/slot.d.ts +12 -0
  98. package/dist/slot.js +23 -0
  99. package/dist/ssr-core.d.ts +2 -0
  100. package/dist/ssr-core.js +12 -4
  101. package/dist/suspense.js +34 -2
  102. package/dist/testing.d.ts +62 -0
  103. package/dist/testing.js +90 -0
  104. package/dist/use-id.js +1 -1
  105. package/package.json +28 -3
  106. package/dist/action-context.test.d.ts +0 -1
  107. package/dist/action-context.test.js +0 -72
  108. package/dist/actions.test.d.ts +0 -1
  109. package/dist/actions.test.js +0 -477
  110. package/dist/cache-adapter.test.d.ts +0 -1
  111. package/dist/cache-adapter.test.js +0 -244
  112. package/dist/cache.test.d.ts +0 -1
  113. package/dist/cache.test.js +0 -233
  114. package/dist/class-component.test.d.ts +0 -1
  115. package/dist/class-component.test.js +0 -462
  116. package/dist/class-helpers.test.d.ts +0 -1
  117. package/dist/class-helpers.test.js +0 -169
  118. package/dist/context.test.d.ts +0 -1
  119. package/dist/context.test.js +0 -57
  120. package/dist/derived.test.d.ts +0 -1
  121. package/dist/derived.test.js +0 -140
  122. package/dist/dev-overlay.test.d.ts +0 -1
  123. package/dist/dev-overlay.test.js +0 -152
  124. package/dist/discrete.test.d.ts +0 -1
  125. package/dist/discrete.test.js +0 -100
  126. package/dist/dom.test.d.ts +0 -1
  127. package/dist/dom.test.js +0 -31
  128. package/dist/effect-errors.test.d.ts +0 -1
  129. package/dist/effect-errors.test.js +0 -163
  130. package/dist/effects.test.d.ts +0 -1
  131. package/dist/effects.test.js +0 -485
  132. package/dist/events.test.d.ts +0 -1
  133. package/dist/events.test.js +0 -447
  134. package/dist/handler-html.test.d.ts +0 -1
  135. package/dist/handler-html.test.js +0 -256
  136. package/dist/handler-routing.test.d.ts +0 -1
  137. package/dist/handler-routing.test.js +0 -99
  138. package/dist/handler-segments.test.d.ts +0 -1
  139. package/dist/handler-segments.test.js +0 -217
  140. package/dist/head-tags.test.d.ts +0 -1
  141. package/dist/head-tags.test.js +0 -131
  142. package/dist/highlight-bind.test.d.ts +0 -1
  143. package/dist/highlight-bind.test.js +0 -124
  144. package/dist/highlight.test.d.ts +0 -1
  145. package/dist/highlight.test.js +0 -56
  146. package/dist/lanes.test.d.ts +0 -1
  147. package/dist/lanes.test.js +0 -59
  148. package/dist/list.test.d.ts +0 -1
  149. package/dist/list.test.js +0 -344
  150. package/dist/metadata.test.d.ts +0 -1
  151. package/dist/metadata.test.js +0 -167
  152. package/dist/navigation.test.d.ts +0 -1
  153. package/dist/navigation.test.js +0 -130
  154. package/dist/node-server.test.d.ts +0 -1
  155. package/dist/node-server.test.js +0 -492
  156. package/dist/optimistic-lanes.test.d.ts +0 -1
  157. package/dist/optimistic-lanes.test.js +0 -45
  158. package/dist/patterns.test.d.ts +0 -1
  159. package/dist/patterns.test.js +0 -98
  160. package/dist/portal.test.d.ts +0 -1
  161. package/dist/portal.test.js +0 -99
  162. package/dist/react-effects.test.d.ts +0 -1
  163. package/dist/react-effects.test.js +0 -96
  164. package/dist/react-suspense.test.d.ts +0 -1
  165. package/dist/react-suspense.test.js +0 -194
  166. package/dist/react.test.d.ts +0 -1
  167. package/dist/react.test.js +0 -60
  168. package/dist/react19.test.d.ts +0 -1
  169. package/dist/react19.test.js +0 -176
  170. package/dist/reactivity-core.test.d.ts +0 -1
  171. package/dist/reactivity-core.test.js +0 -152
  172. package/dist/reconcile.test.d.ts +0 -1
  173. package/dist/reconcile.test.js +0 -110
  174. package/dist/refs.test.d.ts +0 -1
  175. package/dist/refs.test.js +0 -257
  176. package/dist/router-layout.test.d.ts +0 -1
  177. package/dist/router-layout.test.js +0 -249
  178. package/dist/router-nav.test.d.ts +0 -1
  179. package/dist/router-nav.test.js +0 -464
  180. package/dist/router-slots.test.d.ts +0 -1
  181. package/dist/router-slots.test.js +0 -144
  182. package/dist/router-speculation.test.d.ts +0 -1
  183. package/dist/router-speculation.test.js +0 -25
  184. package/dist/router-styles.test.d.ts +0 -1
  185. package/dist/router-styles.test.js +0 -98
  186. package/dist/router.test.d.ts +0 -1
  187. package/dist/router.test.js +0 -36
  188. package/dist/server-async.test.d.ts +0 -1
  189. package/dist/server-async.test.js +0 -216
  190. package/dist/server-handler.test.d.ts +0 -1
  191. package/dist/server-handler.test.js +0 -535
  192. package/dist/server-highlight.test.d.ts +0 -1
  193. package/dist/server-highlight.test.js +0 -32
  194. package/dist/server-renderer.test.d.ts +0 -1
  195. package/dist/server-renderer.test.js +0 -266
  196. package/dist/server.test.d.ts +0 -1
  197. package/dist/server.test.js +0 -88
  198. package/dist/sha256.test.d.ts +0 -1
  199. package/dist/sha256.test.js +0 -13
  200. package/dist/signal-lanes.test.d.ts +0 -1
  201. package/dist/signal-lanes.test.js +0 -32
  202. package/dist/signal.test.d.ts +0 -1
  203. package/dist/signal.test.js +0 -68
  204. package/dist/slots.test.d.ts +0 -1
  205. package/dist/slots.test.js +0 -169
  206. package/dist/snapshots.test.d.ts +0 -1
  207. package/dist/snapshots.test.js +0 -208
  208. package/dist/ssr-core-behavior.test.d.ts +0 -1
  209. package/dist/ssr-core-behavior.test.js +0 -620
  210. package/dist/ssr-core.test.d.ts +0 -1
  211. package/dist/ssr-core.test.js +0 -324
  212. package/dist/static-memory.test.d.ts +0 -1
  213. package/dist/static-memory.test.js +0 -26
  214. package/dist/storage.test.d.ts +0 -1
  215. package/dist/storage.test.js +0 -46
  216. package/dist/suspense-actions.test.d.ts +0 -1
  217. package/dist/suspense-actions.test.js +0 -72
  218. package/dist/suspense.test.d.ts +0 -1
  219. package/dist/suspense.test.js +0 -518
@@ -1,492 +0,0 @@
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
- });
@@ -1 +0,0 @@
1
- import './effects';
@@ -1,45 +0,0 @@
1
- import { describe, it, expect, beforeEach } from 'vitest';
2
- import { createSignal, createEffect, disposeAll, krateHookState } from './signal';
3
- import './effects';
4
- import { __krateOptimistic, runActionTransition } from './actions';
5
- const tick = () => new Promise((r) => setTimeout(r, 0));
6
- async function settle() {
7
- for (let i = 0; i < 6; i++)
8
- await tick();
9
- }
10
- describe('state written at the end of an async action', () => {
11
- beforeEach(() => disposeAll());
12
- // The update cascades through several effects (optimistic state, a list
13
- // binding, row bindings). The action settles, and its optimistic revert
14
- // reads the committed state, in a microtask that used to run between two
15
- // passes of that cascade, before the state was committed.
16
- for (const hops of [0, 1, 2, 3, 4])
17
- it('survives an unrelated plain signal write in a later microtask (' + hops + ' hops)', async () => {
18
- const [messages, setMessages] = createSignal([{ text: 'hi' }], krateHookState);
19
- const [optimistic, setOptimistic] = createSignal(messages());
20
- const add = __krateOptimistic(() => messages(), setOptimistic, (s, text) => [...s, { text, sending: true }]);
21
- const [rows, setRows] = createSignal([]);
22
- createEffect(() => setRows(optimistic().map((m) => m.text + (m.sending ? '*' : ''))));
23
- const [label, setLabel] = createSignal('');
24
- createEffect(() => setLabel(rows().join(',')));
25
- const shown = [];
26
- createEffect(() => void shown.push(label()));
27
- await settle();
28
- void runActionTransition(async () => {
29
- add('hello');
30
- await new Promise((r) => setTimeout(r, 5));
31
- // A startTransition that writes its own pending signal afterwards.
32
- const s = createSignal(true);
33
- setMessages((m) => [...m, { text: 'hello' }]);
34
- queueMicrotask(() => s[1](false));
35
- // The action resolves a few microtasks later (the form action wrapper).
36
- for (let i = 0; i < hops; i++)
37
- await null;
38
- });
39
- await settle();
40
- await new Promise((r) => setTimeout(r, 20));
41
- expect(messages().map((m) => m.text)).toEqual(['hi', 'hello']);
42
- expect(optimistic().map((m) => m.text)).toEqual(['hi', 'hello']);
43
- expect(shown[shown.length - 1]).toBe('hi,hello');
44
- });
45
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,98 +0,0 @@
1
- import { describe, it, expect } from 'vitest';
2
- import { h, krateSpread } from './dom';
3
- import { createContext, krateContextRows } from './context';
4
- import { createSignal, krateDerived } from './signal';
5
- import { krateParam } from './hook-args';
6
- import { krateCondSwap } from './slots';
7
- import { krateOn } from './events';
8
- const tick = () => new Promise((r) => setTimeout(r, 0));
9
- const SVG_NS = 'http://www.w3.org/2000/svg';
10
- describe('SVG elements created by h()', () => {
11
- it('uses the SVG namespace for SVG-only tags and their children', () => {
12
- const svg = h('svg', { width: '10' }, h('g', null, h('circle', { r: '2' })));
13
- expect(svg.namespaceURI).toBe(SVG_NS);
14
- const circle = svg.querySelector('circle');
15
- expect(circle.namespaceURI).toBe(SVG_NS);
16
- expect(circle.parentElement.localName).toBe('g');
17
- });
18
- it('re-creates an ambiguous tag appended to an SVG parent in the SVG namespace', () => {
19
- const svg = h('svg', null, h('a', { href: '#x' }, h('path', { d: 'M0 0' })));
20
- const a = svg.querySelector('a');
21
- expect(a.namespaceURI).toBe(SVG_NS);
22
- expect(a.getAttribute('href')).toBe('#x');
23
- expect(a.firstElementChild.namespaceURI).toBe(SVG_NS);
24
- });
25
- it('keeps HTML inside a foreignObject', () => {
26
- const fo = h('svg', null, h('foreignObject', null, h('a', { href: '#y' }, 'x')));
27
- expect(fo.querySelector('a').namespaceURI).toBe('http://www.w3.org/1999/xhtml');
28
- });
29
- });
30
- describe('krateCondSwap with an SVG template', () => {
31
- it('unwraps the <svg> wrapper so the branch keeps the SVG namespace', () => {
32
- document.body.innerHTML =
33
- '<svg id="s"><!--k:c--><!--/k:c--></svg><template data-kc="c" data-kb="c" data-kns="svg"><svg><g id="grp"><path d="M0 0"></path></g></svg></template>';
34
- const start = document.querySelector('svg').firstChild;
35
- const tpl = document.querySelector('template');
36
- krateCondSwap(start, true, tpl);
37
- const g = document.getElementById('grp');
38
- expect(g.namespaceURI).toBe(SVG_NS);
39
- expect(g.parentElement.id).toBe('s');
40
- expect(g.firstElementChild.namespaceURI).toBe(SVG_NS);
41
- });
42
- });
43
- describe('krateSpread', () => {
44
- it('applies attributes and handlers and removes keys that disappear', async () => {
45
- const [on, setOn] = createSignal(true);
46
- const el = document.createElement('button');
47
- document.body.appendChild(el);
48
- let clicks = 0;
49
- krateSpread(el, () => (on() ? { title: 'x', className: 'a', onClick: () => clicks++ } : { className: 'b' }));
50
- expect(el.getAttribute('title')).toBe('x');
51
- expect(el.getAttribute('class')).toBe('a');
52
- el.dispatchEvent(new Event('click', { bubbles: true }));
53
- expect(clicks).toBe(1);
54
- setOn(false);
55
- await tick();
56
- expect(el.hasAttribute('title')).toBe(false);
57
- expect(el.getAttribute('class')).toBe('b');
58
- el.dispatchEvent(new Event('click', { bubbles: true }));
59
- expect(clicks).toBe(1);
60
- });
61
- });
62
- describe('krateContextRows', () => {
63
- it('shows live provider values to rows created under it', async () => {
64
- const Sel = createContext('');
65
- const [sel, setSel] = createSignal('a');
66
- const row = krateContextRows([[Sel, () => sel()]], () => Sel.useContextLive());
67
- const read = row();
68
- expect(read()).toBe('a');
69
- setSel('b');
70
- expect(read()).toBe('b');
71
- // Outside the rows the context has its default again.
72
- expect(Sel.useContext()).toBe('');
73
- });
74
- });
75
- describe('krateParam', () => {
76
- it('unwraps a derived getter argument and passes other values through', () => {
77
- const [n, setN] = createSignal(1);
78
- const arg = krateDerived(() => n() * 2);
79
- expect(krateParam(arg)).toBe(2);
80
- setN(2);
81
- expect(krateParam(arg)).toBe(4);
82
- expect(krateParam(5)).toBe(5);
83
- const fn = () => 1;
84
- expect(krateParam(fn)).toBe(fn);
85
- });
86
- });
87
- describe('krateOn unaffected by spread removal', () => {
88
- it('removes a handler with null', () => {
89
- const el = document.createElement('div');
90
- document.body.appendChild(el);
91
- let n = 0;
92
- krateOn(el, 'onClick', () => n++);
93
- el.dispatchEvent(new Event('click', { bubbles: true }));
94
- krateOn(el, 'onClick', null);
95
- el.dispatchEvent(new Event('click', { bubbles: true }));
96
- expect(n).toBe(1);
97
- });
98
- });
@@ -1 +0,0 @@
1
- export {};