brumate 0.1.1 → 0.2.0

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 (108) hide show
  1. package/dist/{boot-DN1ZU8Hg.d.ts → boot-D-IdPy7B.d.ts} +24 -2
  2. package/dist/cli.js +2 -2
  3. package/dist/client-C0UCNL3J.js +1643 -0
  4. package/dist/client-C0UCNL3J.js.map +1 -0
  5. package/dist/{client-DwJInP_a.d.ts → client-MD0ZmcFR.d.ts} +101 -26
  6. package/dist/{client-routes-DakuM32C.js → client-routes-JTbGtukf.js} +28 -15
  7. package/dist/client-routes-JTbGtukf.js.map +1 -0
  8. package/dist/context-CTiSzQRc.js +27 -0
  9. package/dist/context-CTiSzQRc.js.map +1 -0
  10. package/dist/context-btHuB01Z.d.ts +42 -0
  11. package/dist/defer-D0bo1Gqx.js +52 -0
  12. package/dist/defer-D0bo1Gqx.js.map +1 -0
  13. package/dist/{devtools-BKjnHrnv.js → devtools-C50VH8gZ.js} +2 -2
  14. package/dist/devtools-C50VH8gZ.js.map +1 -0
  15. package/dist/{devtools-panel-AWOn0VK2.js → devtools-panel-AYjfwPhj.js} +4 -3
  16. package/dist/devtools-panel-AYjfwPhj.js.map +1 -0
  17. package/dist/events-BKWRqtMg.js +52 -0
  18. package/dist/events-BKWRqtMg.js.map +1 -0
  19. package/dist/{files-DdT84mPy.js → files-Bnn1JqHx.js} +18 -3
  20. package/dist/files-Bnn1JqHx.js.map +1 -0
  21. package/dist/{html-DEeoepg3.js → html-bHZbkK-h.js} +26 -8
  22. package/dist/html-bHZbkK-h.js.map +1 -0
  23. package/dist/{html-Du8jY2Cc.d.ts → html-y1q7-t7D.d.ts} +12 -5
  24. package/dist/index.d.ts +77 -29
  25. package/dist/index.js +12 -4
  26. package/dist/index.js.map +1 -1
  27. package/dist/{inspect-BPchdWbU.js → inspect-BJtACnQp.js} +784 -82
  28. package/dist/inspect-BJtACnQp.js.map +1 -0
  29. package/dist/{loader-Dc9OwY5I.js → loader-B18i3_-T.js} +46 -11
  30. package/dist/loader-B18i3_-T.js.map +1 -0
  31. package/dist/{navigate-CzLjnoPH.js → navigate-BwuZveDF.js} +71 -12
  32. package/dist/navigate-BwuZveDF.js.map +1 -0
  33. package/dist/{produce-BRGHP7e0.js → produce-CWfJ4byV.js} +43 -2
  34. package/dist/produce-CWfJ4byV.js.map +1 -0
  35. package/dist/{produce-CtZ32UGG.d.ts → produce-D4K7qpaL.d.ts} +23 -11
  36. package/dist/routes-BZNt7DSZ.d.ts +38 -0
  37. package/dist/{rpc-9fSqL_YK.js → rpc-B-Zkn6Ch.js} +24 -18
  38. package/dist/rpc-B-Zkn6Ch.js.map +1 -0
  39. package/dist/runtime/batch.d.ts +23 -0
  40. package/dist/runtime/batch.js +69 -0
  41. package/dist/runtime/batch.js.map +1 -0
  42. package/dist/runtime/client.d.ts +5 -5
  43. package/dist/runtime/client.js +5 -1345
  44. package/dist/runtime/context.d.ts +2 -2
  45. package/dist/runtime/context.js +1 -1
  46. package/dist/runtime/devtools.d.ts +5 -4
  47. package/dist/runtime/devtools.js +1 -1
  48. package/dist/runtime/env.d.ts +44 -0
  49. package/dist/runtime/env.js +61 -0
  50. package/dist/runtime/env.js.map +1 -0
  51. package/dist/runtime/events.d.ts +27 -0
  52. package/dist/runtime/events.js +1 -0
  53. package/dist/runtime/hot.d.ts +1 -1
  54. package/dist/runtime/html.d.ts +2 -2
  55. package/dist/runtime/html.js +1 -1
  56. package/dist/runtime/loader.d.ts +2 -2
  57. package/dist/runtime/loader.js +2 -2
  58. package/dist/runtime/routes.d.ts +2 -21
  59. package/dist/runtime/routes.js +31 -1
  60. package/dist/runtime/routes.js.map +1 -1
  61. package/dist/runtime/server.d.ts +6 -5
  62. package/dist/runtime/server.js +5 -6
  63. package/dist/runtime/signals.d.ts +22 -1
  64. package/dist/runtime/signals.js +29 -1
  65. package/dist/runtime/signals.js.map +1 -1
  66. package/dist/runtime/static-loader.d.ts +2 -2
  67. package/dist/runtime/static-loader.js +1 -1
  68. package/dist/runtime/testing.d.ts +46 -5
  69. package/dist/runtime/testing.js +240 -33
  70. package/dist/runtime/testing.js.map +1 -1
  71. package/dist/secrets-BxagsJxJ.js +23 -0
  72. package/dist/secrets-BxagsJxJ.js.map +1 -0
  73. package/dist/{server-BxqjLUnV.d.ts → server-BA9SJ2Vm.d.ts} +544 -106
  74. package/dist/server-BqfM95r1.js +2762 -0
  75. package/dist/server-BqfM95r1.js.map +1 -0
  76. package/dist/skew-FRmAy9iy.js +49 -0
  77. package/dist/skew-FRmAy9iy.js.map +1 -0
  78. package/dist/standard-schema-BNY82yX3.d.ts +63 -0
  79. package/dist/{static-loader-BcFh4ebX.d.ts → static-loader-BzE9SRaj.d.ts} +2 -2
  80. package/dist/{static-loader-ClNkHZGn.js → static-loader-DOygOFj5.js} +52 -21
  81. package/dist/static-loader-DOygOFj5.js.map +1 -0
  82. package/dist/{stream-bgNCMcaA.js → stream-JaMHMdBD.js} +126 -61
  83. package/dist/stream-JaMHMdBD.js.map +1 -0
  84. package/dist/vite.d.ts +42 -1
  85. package/dist/vite.js +435 -55
  86. package/dist/vite.js.map +1 -1
  87. package/package.json +15 -2
  88. package/types.d.ts +9 -1
  89. package/dist/client-routes-DakuM32C.js.map +0 -1
  90. package/dist/context-BG8KCF3v.js +0 -15
  91. package/dist/context-BG8KCF3v.js.map +0 -1
  92. package/dist/context-aeo9esY9.d.ts +0 -16
  93. package/dist/devtools-BKjnHrnv.js.map +0 -1
  94. package/dist/devtools-panel-AWOn0VK2.js.map +0 -1
  95. package/dist/files-DdT84mPy.js.map +0 -1
  96. package/dist/html-DEeoepg3.js.map +0 -1
  97. package/dist/inspect-BPchdWbU.js.map +0 -1
  98. package/dist/loader-Dc9OwY5I.js.map +0 -1
  99. package/dist/navigate-CzLjnoPH.js.map +0 -1
  100. package/dist/produce-BRGHP7e0.js.map +0 -1
  101. package/dist/rpc-9fSqL_YK.js.map +0 -1
  102. package/dist/runtime/client.js.map +0 -1
  103. package/dist/server-DZsgnPKS.js +0 -1615
  104. package/dist/server-DZsgnPKS.js.map +0 -1
  105. package/dist/shared-CWYOd0H3.js +0 -40
  106. package/dist/shared-CWYOd0H3.js.map +0 -1
  107. package/dist/static-loader-ClNkHZGn.js.map +0 -1
  108. package/dist/stream-bgNCMcaA.js.map +0 -1
@@ -1,6 +1,81 @@
1
- import { g as render, s as handleRequest } from "../server-DZsgnPKS.js";
2
- import { t as start } from "../loader-Dc9OwY5I.js";
1
+ import { c as handleRequest, y as render } from "../server-BqfM95r1.js";
2
+ import { t as start } from "../loader-B18i3_-T.js";
3
+ //#region src/runtime/nodes.ts
4
+ const VOID = /* @__PURE__ */ new Set([
5
+ "area",
6
+ "base",
7
+ "br",
8
+ "col",
9
+ "embed",
10
+ "hr",
11
+ "img",
12
+ "input",
13
+ "link",
14
+ "meta",
15
+ "source",
16
+ "track",
17
+ "wbr"
18
+ ]);
19
+ /**
20
+ * The end of the last whole node at the top level of markup that streams in,
21
+ * so a chunk that ends inside a tag, the text of a script or a template
22
+ * waits for the rest. A `>` in an attribute or a script does not end a node.
23
+ */
24
+ function wholeNodes(markup) {
25
+ const tag = /<(\/?)([a-zA-Z][\w-]*)(?:[^>"']|"[^"]*"|'[^']*')*>/g;
26
+ const lower = markup.toLowerCase();
27
+ let depth = 0;
28
+ let end = 0;
29
+ let match;
30
+ while (match = tag.exec(markup)) {
31
+ const [whole, closing, name] = match;
32
+ const element = name.toLowerCase();
33
+ if (!closing && element === "script") {
34
+ const close = lower.indexOf("<\/script", tag.lastIndex);
35
+ const after = close < 0 ? -1 : markup.indexOf(">", close);
36
+ if (after < 0) return end;
37
+ tag.lastIndex = after + 1;
38
+ } else if (!VOID.has(element) && !whole.endsWith("/>")) depth += closing ? -1 : 1;
39
+ if (depth === 0) end = tag.lastIndex;
40
+ }
41
+ return end;
42
+ }
43
+ //#endregion
3
44
  //#region src/runtime/testing.ts
45
+ /** The actions on the elements inside `root`. */
46
+ function actions(root) {
47
+ const get = (selector) => {
48
+ const element = root.querySelector(selector);
49
+ if (!element) throw new Error(`No element matches ${selector}`);
50
+ return element;
51
+ };
52
+ return {
53
+ get,
54
+ text: (selector) => get(selector).textContent ?? "",
55
+ click: (selector) => get(selector).click(),
56
+ input: (selector, value) => {
57
+ const field = get(selector);
58
+ field.value = value;
59
+ field.dispatchEvent(new Event("input", { bubbles: true }));
60
+ },
61
+ submit: (selector) => {
62
+ get(selector).dispatchEvent(new Event("submit", {
63
+ bubbles: true,
64
+ cancelable: true
65
+ }));
66
+ },
67
+ waitFor: async (assertion, timeout = 2e3) => {
68
+ const until = Date.now() + timeout;
69
+ for (;;) try {
70
+ assertion();
71
+ return;
72
+ } catch (error) {
73
+ if (Date.now() > until) throw error;
74
+ await new Promise((resolve) => setTimeout(resolve, 10));
75
+ }
76
+ }
77
+ };
78
+ }
4
79
  /**
5
80
  * Runs an inline script, as a browser does when it adds one. The DOM of a
6
81
  * test does not run scripts. The script is `document.currentScript` while it
@@ -72,37 +147,9 @@ function createMount(options) {
72
147
  (async () => {
73
148
  for await (const chunk of pending) append(container, chunk);
74
149
  })();
75
- const get = (selector) => {
76
- const element = container.querySelector(selector);
77
- if (!element) throw new Error(`No element matches ${selector}`);
78
- return element;
79
- };
80
150
  return {
81
151
  container,
82
- get,
83
- text: (selector) => get(selector).textContent ?? "",
84
- click: (selector) => get(selector).click(),
85
- input: (selector, value) => {
86
- const field = get(selector);
87
- field.value = value;
88
- field.dispatchEvent(new Event("input", { bubbles: true }));
89
- },
90
- submit: (selector) => {
91
- get(selector).dispatchEvent(new Event("submit", {
92
- bubbles: true,
93
- cancelable: true
94
- }));
95
- },
96
- waitFor: async (assertion, timeout = 2e3) => {
97
- const until = Date.now() + timeout;
98
- for (;;) try {
99
- assertion();
100
- return;
101
- } catch (error) {
102
- if (Date.now() > until) throw error;
103
- await new Promise((resolve) => setTimeout(resolve, 10));
104
- }
105
- },
152
+ ...actions(container),
106
153
  unmount: () => {
107
154
  stop();
108
155
  container.remove();
@@ -152,7 +199,12 @@ function answerCalls(functions, options = {}) {
152
199
  loaded ??= Promise.resolve(typeof functions === "function" ? functions() : functions);
153
200
  const registry = await loaded;
154
201
  const request = input instanceof Request ? new Request(input, init) : new Request(url, init);
155
- const handle = () => handleRequest(registry, request, prefix);
202
+ const guards = options.fileMiddleware;
203
+ const fileMiddleware = typeof guards === "function" ? await guards() : guards;
204
+ const handle = () => handleRequest(registry, request, prefix, {
205
+ middleware: options.middleware,
206
+ fileMiddleware
207
+ });
156
208
  const response = await (calls ? calls.run(id, handle) : handle());
157
209
  if (failure) {
158
210
  const error = failure;
@@ -166,7 +218,162 @@ function answerCalls(functions, options = {}) {
166
218
  if (globalThis.fetch === answer) globalThis.fetch = original;
167
219
  };
168
220
  }
221
+ const REDIRECTS = /* @__PURE__ */ new Set([
222
+ 301,
223
+ 302,
224
+ 303,
225
+ 307,
226
+ 308
227
+ ]);
228
+ /** Reads the `set-cookie` headers of a response into the cookies of the browser. */
229
+ function storeCookies(jar, response) {
230
+ for (const header of response.headers.getSetCookie()) {
231
+ const [pair = "", ...attributes] = header.split(";");
232
+ const equals = pair.indexOf("=");
233
+ const name = pair.slice(0, equals).trim();
234
+ if (equals < 1) continue;
235
+ if (attributes.some((attribute) => {
236
+ const [key = "", value = ""] = attribute.trim().split("=");
237
+ const lower = key.toLowerCase();
238
+ return lower === "max-age" && Number(value) <= 0 || lower === "expires" && Date.parse(value) <= Date.now();
239
+ })) jar.delete(name);
240
+ else jar.set(name, pair.slice(equals + 1).trim());
241
+ }
242
+ }
243
+ /** The page that a visit holds, so a new visit closes the one before. */
244
+ let visited;
245
+ /** Returns `visit`, which answers the requests of the page with the routes of the app. */
246
+ function createVisit(options) {
247
+ const prefix = options.rpc ?? "/_brumate";
248
+ /**
249
+ * Answers the path with the routes of the app, puts the page in the
250
+ * document, and starts the loader with client navigation. Links, forms,
251
+ * server function calls and `#defer` requests of the page go to the same
252
+ * routes, without a server, with the cookies that the answers set.
253
+ */
254
+ return async function visit(path, visitOptions = {}) {
255
+ visited?.close();
256
+ const jar = new Map(Object.entries(visitOptions.cookies ?? {}));
257
+ const original = globalThis.fetch;
258
+ const origin = location.origin;
259
+ history.replaceState(null, "", new URL(path, origin));
260
+ const answer = async (input, init) => {
261
+ let url = new URL(input instanceof Request ? input.url : String(input), location.href);
262
+ if (url.origin !== origin) return original(input, init);
263
+ let method = (init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase();
264
+ let body = init?.body ?? void 0;
265
+ const extra = new Headers(input instanceof Request ? input.headers : void 0);
266
+ new Headers(init?.headers).forEach((value, name) => extra.set(name, value));
267
+ for (let hops = 0;; hops++) {
268
+ const request = new Request(url, {
269
+ method,
270
+ body,
271
+ signal: init?.signal ?? null
272
+ });
273
+ new Headers(visitOptions.headers).forEach((value, name) => request.headers.set(name, value));
274
+ extra.forEach((value, name) => request.headers.set(name, value));
275
+ if (jar.size > 0) request.headers.set("cookie", [...jar].map(([name, value]) => `${name}=${value}`).join("; "));
276
+ if (method !== "GET" && method !== "HEAD") request.headers.set("origin", origin);
277
+ const response = await (url.pathname.startsWith(`${prefix}/`) ? options.calls : options.routes)().then((handler) => handler(request)) ?? new Response("Not found", { status: 404 });
278
+ storeCookies(jar, response);
279
+ const location = response.headers.get("location");
280
+ if (!REDIRECTS.has(response.status) || !location || init?.redirect === "manual") {
281
+ Object.defineProperty(response, "url", { value: url.href });
282
+ return response;
283
+ }
284
+ if (hops === 20) throw new TypeError(`Too many redirects from ${path}`);
285
+ url = new URL(location, url);
286
+ if (response.status === 303 && method !== "HEAD" || method === "POST" && (response.status === 301 || response.status === 302)) {
287
+ method = "GET";
288
+ body = void 0;
289
+ extra.delete("content-type");
290
+ }
291
+ }
292
+ };
293
+ globalThis.fetch = answer;
294
+ const ran = /* @__PURE__ */ new WeakSet();
295
+ const runOnce = (script) => {
296
+ if (!ran.has(script) && !script.hasAttribute("src") && !script.hasAttribute("type")) {
297
+ ran.add(script);
298
+ run(script);
299
+ }
300
+ };
301
+ const scripts = new MutationObserver((records) => {
302
+ for (const record of records) for (const node of record.addedNodes) if (node.nodeName === "SCRIPT") runOnce(node);
303
+ else if (node instanceof Element) node.querySelectorAll("script").forEach(runOnce);
304
+ });
305
+ const response = await answer(path);
306
+ history.replaceState(null, "", response.url);
307
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
308
+ let html = "";
309
+ let end = -1;
310
+ let done = false;
311
+ while (end < 0 && !done) {
312
+ const chunk = await reader.read();
313
+ done = chunk.done;
314
+ html += chunk.value ?? "";
315
+ end = html.search(/<\/html>/i);
316
+ }
317
+ const cut = end < 0 ? html.length : end + 7;
318
+ const page = new DOMParser().parseFromString(html.slice(0, cut), "text/html");
319
+ for (const name of document.documentElement.getAttributeNames()) document.documentElement.removeAttribute(name);
320
+ for (const attribute of page.documentElement.attributes) document.documentElement.setAttribute(attribute.name, attribute.value);
321
+ document.head.replaceChildren(...[...page.head.childNodes].map((node) => document.importNode(node, true)));
322
+ document.body.replaceChildren(...[...page.body.childNodes].map((node) => document.importNode(node, true)));
323
+ document.querySelectorAll("script").forEach(runOnce);
324
+ scripts.observe(document, {
325
+ childList: true,
326
+ subtree: true
327
+ });
328
+ const stop = start({
329
+ load: options.load,
330
+ rpc: prefix,
331
+ navigate: true,
332
+ preload: false
333
+ });
334
+ let rest = html.slice(cut);
335
+ let open = true;
336
+ (async () => {
337
+ while (!done) {
338
+ const chunk = await reader.read();
339
+ done = chunk.done;
340
+ rest += chunk.value ?? "";
341
+ const last = done ? rest.length : wholeNodes(rest);
342
+ if (last > 0 && open) {
343
+ const template = document.createElement("template");
344
+ template.innerHTML = rest.slice(0, last);
345
+ document.body.append(template.content);
346
+ rest = rest.slice(last);
347
+ }
348
+ }
349
+ })();
350
+ const current = {
351
+ ...actions(document),
352
+ get url() {
353
+ return location.pathname + location.search;
354
+ },
355
+ status: response.status,
356
+ get cookies() {
357
+ return Object.fromEntries(jar);
358
+ },
359
+ close: () => {
360
+ if (!open) return;
361
+ open = false;
362
+ visited = void 0;
363
+ stop();
364
+ scripts.disconnect();
365
+ reader.cancel().catch(() => {});
366
+ if (globalThis.fetch === answer) globalThis.fetch = original;
367
+ import("./client.js").then((core) => core.leavePage());
368
+ document.head.replaceChildren();
369
+ document.body.replaceChildren();
370
+ }
371
+ };
372
+ visited = current;
373
+ return current;
374
+ };
375
+ }
169
376
  //#endregion
170
- export { answerCalls, createMount };
377
+ export { answerCalls, createMount, createVisit };
171
378
 
172
379
  //# sourceMappingURL=testing.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"testing.js","names":[],"sources":["../../src/runtime/testing.ts"],"sourcesContent":["// Renders a component on the server and resumes it in the DOM of a test, as\n// a page does: the HTML and the state first, then the loader, which loads\n// client code when an event fires.\n\nimport type { ClientModule } from './client.ts';\nimport { start } from './loader.ts';\nimport { handleRequest, render } from './server.ts';\nimport type { Component, RenderOptions } from './server.ts';\n\nexport interface TestingOptions {\n /** Imports the client module of a component, by component ID. */\n load: (id: string) => Promise<ClientModule>;\n /** The URL prefix of server function calls. */\n rpc?: string;\n}\n\nexport interface Mounted {\n /** The element that holds the component. */\n container: HTMLElement;\n /** The first element that matches a selector. Throws if none does. */\n get: (selector: string) => HTMLElement;\n /** The text of the first element that matches a selector. */\n text: (selector: string) => string;\n /** Clicks an element. */\n click: (selector: string) => void;\n /** Types a value into a field, and fires `input`. */\n input: (selector: string, value: string) => void;\n /** Submits a form, as its submit button does. */\n submit: (selector: string) => void;\n /**\n * Retries an assertion until it passes. The first event of a test loads\n * client code, so its effects arrive a moment later.\n */\n waitFor: (assertion: () => void, timeout?: number) => Promise<void>;\n /** Stops the loader and removes the component. */\n unmount: () => void;\n}\n\n/**\n * Runs an inline script, as a browser does when it adds one. The DOM of a\n * test does not run scripts. The script is `document.currentScript` while it\n * runs, so a state record hands its script to the core.\n */\nfunction run(script: Element): void {\n Object.defineProperty(document, 'currentScript', { configurable: true, value: script });\n try {\n // oxlint-disable-next-line no-eval -- The script is a state record or the swap code from the server.\n (0, eval)(script.textContent!);\n } finally {\n delete (document as { currentScript?: unknown }).currentScript;\n }\n}\n\n/**\n * Appends markup that streams in later, such as a `#loading` body, and runs\n * its inline scripts in order.\n */\nfunction append(container: HTMLElement, html: string): void {\n const template = document.createElement('template');\n template.innerHTML = html;\n // A copy, because appending moves nodes out of the live list.\n // oxlint-disable-next-line unicorn/no-useless-spread\n for (const node of [...template.content.childNodes]) {\n container.append(node);\n if (node.nodeName === 'SCRIPT' && !(node as Element).hasAttribute('type')) {\n run(node as Element);\n }\n }\n}\n\n/** Renders a component on the server and resumes it in the document of a test. */\nexport type Mount = <P>(\n component: Component<P>,\n props: P,\n renderOptions?: RenderOptions,\n) => Promise<Mounted>;\n\n/** Mounts so far, so each starts its scope IDs at a number of its own. */\nlet mounts = 0;\n/** The loader that the mounts of the document share, and how many mounts use it. */\nlet loader: { stop: () => void; users: number } | undefined;\n\n/** Returns `mount`, which loads client modules with `options.load`. */\nexport function createMount(options: TestingOptions): Mount {\n /**\n * Renders a component on the server, puts it in the document with its\n * state, and starts the loader. Markup that streams in later is added as\n * it arrives.\n */\n return async function mount<P>(\n component: Component<P>,\n props: P,\n renderOptions: RenderOptions = {},\n ): Promise<Mounted> {\n // IDs of their own, so two mounts in a file do not share scopes or state references.\n const base = renderOptions.base ?? ++mounts * 1_000_000;\n const { html, state, pending } = await render(component, props, { ...renderOptions, base });\n const container = document.createElement('div');\n container.innerHTML = html + state;\n document.body.append(container);\n // The page state, which waits for the core.\n container.querySelectorAll('script[b-state]').forEach(run);\n // One loader for the document, as a page has, however many mounts are in it.\n loader ??= {\n stop: start({ load: options.load, rpc: options.rpc, navigate: false, preload: false }),\n users: 0,\n };\n loader.users++;\n let mounted = true;\n const stop = (): void => {\n if (!mounted || !loader) {\n return;\n }\n mounted = false;\n if (--loader.users === 0) {\n loader.stop();\n loader = undefined;\n }\n };\n void (async () => {\n for await (const chunk of pending) {\n append(container, chunk);\n }\n })();\n const get = (selector: string): HTMLElement => {\n const element = container.querySelector<HTMLElement>(selector);\n if (!element) {\n throw new Error(`No element matches ${selector}`);\n }\n return element;\n };\n return {\n container,\n get,\n text: (selector) => get(selector).textContent ?? '',\n click: (selector) => get(selector).click(),\n input: (selector, value) => {\n const field = get(selector) as HTMLInputElement;\n field.value = value;\n field.dispatchEvent(new Event('input', { bubbles: true }));\n },\n submit: (selector) => {\n get(selector).dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));\n },\n waitFor: async (assertion, timeout = 2000) => {\n const until = Date.now() + timeout;\n for (;;) {\n try {\n assertion();\n return;\n } catch (error) {\n if (Date.now() > until) {\n throw error;\n }\n // oxlint-disable-next-line no-await-in-loop -- It waits between tries.\n await new Promise((resolve) => setTimeout(resolve, 10));\n }\n }\n },\n unmount: () => {\n stop();\n container.remove();\n // The core forgets the scopes of this mount, so a refresh later does not load its memos.\n void import('./client.ts').then((core) => core.removeRoot(String(base)));\n },\n };\n };\n}\n\n/** Server functions by ID, as `functions` of `virtual:brumate/server` has them. */\n// oxlint-disable-next-line typescript/no-explicit-any -- Server functions take any arguments.\nexport type ServerFunctions = Record<string, (...args: any[]) => unknown>;\n\nexport interface AnswerOptions {\n /** The URL prefix of server function calls. Defaults to `/_brumate`. */\n rpc?: string;\n /** Called with the ID of each call, such as `issues_1a2b#toggleStar`, before it runs. */\n onCall?: (id: string) => void;\n}\n\n/** What `run` of `AsyncLocalStorage` looks like, the part that `answerCalls` uses. */\ninterface Storage {\n run: <T>(store: string, callback: () => T) => T;\n getStore: () => string | undefined;\n}\n\nlet storage: Promise<Storage | undefined> | undefined;\n\n/**\n * Tells the calls that a server function makes while it is answered. Node\n * has `AsyncLocalStorage`. Elsewhere, such as in a browser, there is none,\n * and nested calls are not told apart.\n */\nfunction callStorage(): Promise<Storage | undefined> {\n storage ??= import('node:async_hooks').then(\n ({ AsyncLocalStorage }) => new AsyncLocalStorage<string>() as Storage,\n () => undefined,\n );\n return storage;\n}\n\n/**\n * Answers the server function calls of the page in the test, with\n * `functions`, through the same request and answer as a server. Calls go\n * through `fetch`, so it replaces `fetch` until the returned function\n * restores it. Other requests go to the `fetch` from before.\n *\n * `functions` can be a function that returns them, so they are imported on\n * the first call. A server function that calls a server function through\n * `fetch`, as a browser stub does, throws: it would call itself without end.\n */\nexport function answerCalls(\n functions: ServerFunctions | (() => Promise<ServerFunctions>),\n options: AnswerOptions = {},\n): () => void {\n const prefix = options.rpc ?? '/_brumate';\n const original = globalThis.fetch;\n let loaded: Promise<ServerFunctions> | undefined;\n /** The error of a call that a server function made through `fetch`. */\n let failure: Error | undefined;\n const answer = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n const base = globalThis.location?.href ?? 'http://localhost/';\n const url = new URL(input instanceof Request ? input.url : String(input), base);\n if (!url.pathname.startsWith(`${prefix}/`)) {\n return original(input, init);\n }\n const id = decodeURIComponent(url.pathname.slice(prefix.length + 1));\n const calls = await callStorage();\n const caller = calls?.getStore();\n if (caller !== undefined) {\n // The outer call answers with a generic error, so the error goes to its caller too.\n failure ??= new Error(\n `The server function \"${caller}\" called \"${id}\" through fetch, as a browser stub does. In a test, server code imports the server code of a 'use server' file: import components with ?brumate-server, and answer calls with the functions of virtual:brumate/server`,\n );\n throw failure;\n }\n options.onCall?.(id);\n loaded ??= Promise.resolve(typeof functions === 'function' ? functions() : functions);\n const registry = await loaded;\n const request = input instanceof Request ? new Request(input, init) : new Request(url, init);\n const handle = (): Promise<Response | undefined> => handleRequest(registry, request, prefix);\n const response = await (calls ? calls.run(id, handle) : handle());\n if (failure) {\n const error = failure;\n failure = undefined;\n throw error;\n }\n return response ?? original(input, init);\n };\n globalThis.fetch = answer as typeof fetch;\n return () => {\n // A later `answerCalls` or stub keeps its own `fetch`.\n if (globalThis.fetch === answer) {\n globalThis.fetch = original;\n }\n };\n}\n"],"mappings":";;;;;;;;AA2CA,SAAS,IAAI,QAAuB;CAClC,OAAO,eAAe,UAAU,iBAAiB;EAAE,cAAc;EAAM,OAAO;CAAO,CAAC;CACtF,IAAI;EAEF,CA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I,CAAC,IAAI,SAAS,WAAW,GAAG,OAAO,EAAE,GACvC,OAAO,SAAS,OAAO,IAAI;EAE7B,MAAM,KAAK,mBAAmB,IAAI,SAAS,MAAM,OAAO,SAAS,CAAC,CAAC;EACnE,MAAM,QAAQ,MAAM,YAAY;EAChC,MAAM,SAAS,OAAO,SAAS;EAC/B,IAAI,WAAW,KAAA,GAAW;GAExB,4BAAY,IAAI,MACd,wBAAwB,OAAO,YAAY,GAAG,sNAChD;GACA,MAAM;EACR;EACA,QAAQ,SAAS,EAAE;EACnB,WAAW,QAAQ,QAAQ,OAAO,cAAc,aAAa,UAAU,IAAI,SAAS;EACpF,MAAM,WAAW,MAAM;EACvB,MAAM,UAAU,iBAAiB,UAAU,IAAI,QAAQ,OAAO,IAAI,IAAI,IAAI,QAAQ,KAAK,IAAI;EAC3F,MAAM,eAA8C,cAAc,UAAU,SAAS,MAAM;EAC3F,MAAM,WAAW,OAAO,QAAQ,MAAM,IAAI,IAAI,MAAM,IAAI,OAAO;EAC/D,IAAI,SAAS;GACX,MAAM,QAAQ;GACd,UAAU,KAAA;GACV,MAAM;EACR;EACA,OAAO,YAAY,SAAS,OAAO,IAAI;CACzC;CACA,WAAW,QAAQ;CACnB,aAAa;EAEX,IAAI,WAAW,UAAU,QACvB,WAAW,QAAQ;CAEvB;AACF"}
1
+ {"version":3,"file":"testing.js","names":[],"sources":["../../src/runtime/nodes.ts","../../src/runtime/testing.ts"],"sourcesContent":["// Finds where whole nodes end in markup that arrives in pieces.\n\nconst VOID = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'source',\n 'track',\n 'wbr',\n]);\n\n/**\n * The end of the last whole node at the top level of markup that streams in,\n * so a chunk that ends inside a tag, the text of a script or a template\n * waits for the rest. A `>` in an attribute or a script does not end a node.\n */\nexport function wholeNodes(markup: string): number {\n const tag = /<(\\/?)([a-zA-Z][\\w-]*)(?:[^>\"']|\"[^\"]*\"|'[^']*')*>/g;\n const lower = markup.toLowerCase();\n let depth = 0;\n let end = 0;\n let match: RegExpExecArray | null;\n while ((match = tag.exec(markup))) {\n const [whole, closing, name] = match;\n const element = name!.toLowerCase();\n if (!closing && element === 'script') {\n // The text of a script is not markup, and ends only at `</script`.\n const close = lower.indexOf('</script', tag.lastIndex);\n const after = close < 0 ? -1 : markup.indexOf('>', close);\n if (after < 0) {\n return end;\n }\n tag.lastIndex = after + 1;\n } else if (!VOID.has(element) && !whole.endsWith('/>')) {\n depth += closing ? -1 : 1;\n }\n if (depth === 0) {\n end = tag.lastIndex;\n }\n }\n return end;\n}\n","// Renders a component on the server and resumes it in the DOM of a test, as\n// a page does: the HTML and the state first, then the loader, which loads\n// client code when an event fires. `visit` does the same for a route, with\n// the requests of the page answered by the routes of the app.\n\nimport type { ClientModule } from './client.ts';\nimport { start } from './loader.ts';\nimport { wholeNodes } from './nodes.ts';\nimport { handleRequest, render } from './server.ts';\nimport type { Component, EntryMiddleware, RenderOptions } from './server.ts';\n\n/** The middleware of files of server functions, by function ID. */\ntype FileMiddleware = Record<string, EntryMiddleware>;\n\nexport interface TestingOptions {\n /** Imports the client module of a component, by component ID. */\n load: (id: string) => Promise<ClientModule>;\n /** The URL prefix of server function calls. */\n rpc?: string;\n}\n\n/** What a test does with the page, as a user does. */\nexport interface Actions {\n /** The first element that matches a selector. Throws if none does. */\n get: (selector: string) => HTMLElement;\n /** The text of the first element that matches a selector. */\n text: (selector: string) => string;\n /** Clicks an element. */\n click: (selector: string) => void;\n /** Types a value into a field, and fires `input`. */\n input: (selector: string, value: string) => void;\n /** Submits a form, as its submit button does. */\n submit: (selector: string) => void;\n /**\n * Retries an assertion until it passes. The first event of a test loads\n * client code, so its effects arrive a moment later.\n */\n waitFor: (assertion: () => void, timeout?: number) => Promise<void>;\n}\n\nexport interface Mounted extends Actions {\n /** The element that holds the component. */\n container: HTMLElement;\n /** Stops the loader and removes the component. */\n unmount: () => void;\n}\n\n/** The actions on the elements inside `root`. */\nfunction actions(root: ParentNode): Actions {\n const get = (selector: string): HTMLElement => {\n const element = root.querySelector<HTMLElement>(selector);\n if (!element) {\n throw new Error(`No element matches ${selector}`);\n }\n return element;\n };\n return {\n get,\n text: (selector) => get(selector).textContent ?? '',\n click: (selector) => get(selector).click(),\n input: (selector, value) => {\n const field = get(selector) as HTMLInputElement;\n field.value = value;\n field.dispatchEvent(new Event('input', { bubbles: true }));\n },\n submit: (selector) => {\n get(selector).dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));\n },\n waitFor: async (assertion, timeout = 2000) => {\n const until = Date.now() + timeout;\n for (;;) {\n try {\n assertion();\n return;\n } catch (error) {\n if (Date.now() > until) {\n throw error;\n }\n // oxlint-disable-next-line no-await-in-loop -- It waits between tries.\n await new Promise((resolve) => setTimeout(resolve, 10));\n }\n }\n },\n };\n}\n\n/**\n * Runs an inline script, as a browser does when it adds one. The DOM of a\n * test does not run scripts. The script is `document.currentScript` while it\n * runs, so a state record hands its script to the core.\n */\nfunction run(script: Element): void {\n Object.defineProperty(document, 'currentScript', { configurable: true, value: script });\n try {\n // oxlint-disable-next-line no-eval -- The script is a state record or the swap code from the server.\n (0, eval)(script.textContent!);\n } finally {\n delete (document as { currentScript?: unknown }).currentScript;\n }\n}\n\n/**\n * Appends markup that streams in later, such as a `#loading` body, and runs\n * its inline scripts in order.\n */\nfunction append(container: HTMLElement, html: string): void {\n const template = document.createElement('template');\n template.innerHTML = html;\n // A copy, because appending moves nodes out of the live list.\n // oxlint-disable-next-line unicorn/no-useless-spread\n for (const node of [...template.content.childNodes]) {\n container.append(node);\n if (node.nodeName === 'SCRIPT' && !(node as Element).hasAttribute('type')) {\n run(node as Element);\n }\n }\n}\n\n/** Renders a component on the server and resumes it in the document of a test. */\nexport type Mount = <P>(\n component: Component<P>,\n props: P,\n renderOptions?: RenderOptions,\n) => Promise<Mounted>;\n\n/** Mounts so far, so each starts its scope IDs at a number of its own. */\nlet mounts = 0;\n/** The loader that the mounts of the document share, and how many mounts use it. */\nlet loader: { stop: () => void; users: number } | undefined;\n\n/** Returns `mount`, which loads client modules with `options.load`. */\nexport function createMount(options: TestingOptions): Mount {\n /**\n * Renders a component on the server, puts it in the document with its\n * state, and starts the loader. Markup that streams in later is added as\n * it arrives.\n */\n return async function mount<P>(\n component: Component<P>,\n props: P,\n renderOptions: RenderOptions = {},\n ): Promise<Mounted> {\n // IDs of their own, so two mounts in a file do not share scopes or state references.\n const base = renderOptions.base ?? ++mounts * 1_000_000;\n const { html, state, pending } = await render(component, props, { ...renderOptions, base });\n const container = document.createElement('div');\n container.innerHTML = html + state;\n document.body.append(container);\n // The page state, which waits for the core.\n container.querySelectorAll('script[b-state]').forEach(run);\n // One loader for the document, as a page has, however many mounts are in it.\n loader ??= {\n stop: start({ load: options.load, rpc: options.rpc, navigate: false, preload: false }),\n users: 0,\n };\n loader.users++;\n let mounted = true;\n const stop = (): void => {\n if (!mounted || !loader) {\n return;\n }\n mounted = false;\n if (--loader.users === 0) {\n loader.stop();\n loader = undefined;\n }\n };\n void (async () => {\n for await (const chunk of pending) {\n append(container, chunk);\n }\n })();\n return {\n container,\n ...actions(container),\n unmount: () => {\n stop();\n container.remove();\n // The core forgets the scopes of this mount, so a refresh later does not load its memos.\n void import('./client.ts').then((core) => core.removeRoot(String(base)));\n },\n };\n };\n}\n\n/** Server functions by ID, as `functions` of `virtual:brumate/server` has them. */\n// oxlint-disable-next-line typescript/no-explicit-any -- Server functions take any arguments.\nexport type ServerFunctions = Record<string, (...args: any[]) => unknown>;\n\nexport interface AnswerOptions {\n /** The URL prefix of server function calls. Defaults to `/_brumate`. */\n rpc?: string;\n /** Called with the ID of each call, such as `issues_1a2b#toggleStar`, before it runs. */\n onCall?: (id: string) => void;\n /** The middleware of the entry, which runs before each call. `virtual:brumate/testing` passes the app's. */\n middleware?: EntryMiddleware;\n /**\n * The middleware of each `'use server'` file, by function ID, or a\n * function that imports them. `virtual:brumate/testing` passes them.\n */\n fileMiddleware?: FileMiddleware | (() => Promise<FileMiddleware>);\n}\n\n/** What `run` of `AsyncLocalStorage` looks like, the part that `answerCalls` uses. */\ninterface Storage {\n run: <T>(store: string, callback: () => T) => T;\n getStore: () => string | undefined;\n}\n\nlet storage: Promise<Storage | undefined> | undefined;\n\n/**\n * Tells the calls that a server function makes while it is answered. Node\n * has `AsyncLocalStorage`. Elsewhere, such as in a browser, there is none,\n * and nested calls are not told apart.\n */\nfunction callStorage(): Promise<Storage | undefined> {\n storage ??= import('node:async_hooks').then(\n ({ AsyncLocalStorage }) => new AsyncLocalStorage<string>() as Storage,\n () => undefined,\n );\n return storage;\n}\n\n/**\n * Answers the server function calls of the page in the test, with\n * `functions`, through the same request and answer as a server. Calls go\n * through `fetch`, so it replaces `fetch` until the returned function\n * restores it. Other requests go to the `fetch` from before.\n *\n * `functions` can be a function that returns them, so they are imported on\n * the first call. A server function that calls a server function through\n * `fetch`, as a browser stub does, throws: it would call itself without end.\n */\nexport function answerCalls(\n functions: ServerFunctions | (() => Promise<ServerFunctions>),\n options: AnswerOptions = {},\n): () => void {\n const prefix = options.rpc ?? '/_brumate';\n const original = globalThis.fetch;\n let loaded: Promise<ServerFunctions> | undefined;\n /** The error of a call that a server function made through `fetch`. */\n let failure: Error | undefined;\n const answer = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n const base = globalThis.location?.href ?? 'http://localhost/';\n const url = new URL(input instanceof Request ? input.url : String(input), base);\n if (!url.pathname.startsWith(`${prefix}/`)) {\n return original(input, init);\n }\n const id = decodeURIComponent(url.pathname.slice(prefix.length + 1));\n const calls = await callStorage();\n const caller = calls?.getStore();\n if (caller !== undefined) {\n // The outer call answers with a generic error, so the error goes to its caller too.\n failure ??= new Error(\n `The server function \"${caller}\" called \"${id}\" through fetch, as a browser stub does. In a test, server code imports the server code of a 'use server' file: import components with ?brumate-server, and answer calls with the functions of virtual:brumate/server`,\n );\n throw failure;\n }\n options.onCall?.(id);\n loaded ??= Promise.resolve(typeof functions === 'function' ? functions() : functions);\n const registry = await loaded;\n const request = input instanceof Request ? new Request(input, init) : new Request(url, init);\n const guards = options.fileMiddleware;\n const fileMiddleware = typeof guards === 'function' ? await guards() : guards;\n const handle = (): Promise<Response | undefined> =>\n handleRequest(registry, request, prefix, { middleware: options.middleware, fileMiddleware });\n const response = await (calls ? calls.run(id, handle) : handle());\n if (failure) {\n const error = failure;\n failure = undefined;\n throw error;\n }\n return response ?? original(input, init);\n };\n globalThis.fetch = answer as typeof fetch;\n return () => {\n // A later `answerCalls` or stub keeps its own `fetch`.\n if (globalThis.fetch === answer) {\n globalThis.fetch = original;\n }\n };\n}\n\n/** Answers a request as the server of the app does, or undefined when nothing does. */\nexport type RequestHandler = (request: Request) => Promise<Response | undefined>;\n\nexport interface VisitorOptions extends TestingOptions {\n /** Answers the requests for pages, forms without scripts, `#defer` bodies and endpoints. */\n routes: () => Promise<RequestHandler>;\n /** Answers server function calls. */\n calls: () => Promise<RequestHandler>;\n}\n\nexport interface VisitOptions {\n /** Cookies that the browser has before the first request, by name. */\n cookies?: Record<string, string>;\n /** Headers of every request, such as `accept-language`. */\n headers?: HeadersInit;\n}\n\nexport interface Visited extends Actions {\n /** The path and the query of the page, such as `/issues?q=bug`. It changes with client navigation. */\n readonly url: string;\n /** The status of the first page. */\n status: number;\n /** The cookies that the browser has now, by name. */\n readonly cookies: Record<string, string>;\n /** Stops the loader, puts `fetch` back and empties the document. */\n close: () => void;\n}\n\n/** Visits a path of the app, as a browser that runs scripts does. */\nexport type Visit = (path: string, options?: VisitOptions) => Promise<Visited>;\n\nconst REDIRECTS = new Set([301, 302, 303, 307, 308]);\n\n/** Reads the `set-cookie` headers of a response into the cookies of the browser. */\nfunction storeCookies(jar: Map<string, string>, response: Response): void {\n for (const header of response.headers.getSetCookie()) {\n const [pair = '', ...attributes] = header.split(';');\n const equals = pair.indexOf('=');\n const name = pair.slice(0, equals).trim();\n if (equals < 1) {\n continue;\n }\n const gone = attributes.some((attribute) => {\n const [key = '', value = ''] = attribute.trim().split('=');\n const lower = key.toLowerCase();\n return (\n (lower === 'max-age' && Number(value) <= 0) ||\n (lower === 'expires' && Date.parse(value) <= Date.now())\n );\n });\n if (gone) {\n jar.delete(name);\n } else {\n jar.set(name, pair.slice(equals + 1).trim());\n }\n }\n}\n\n/** The page that a visit holds, so a new visit closes the one before. */\nlet visited: Visited | undefined;\n\n/** Returns `visit`, which answers the requests of the page with the routes of the app. */\nexport function createVisit(options: VisitorOptions): Visit {\n const prefix = options.rpc ?? '/_brumate';\n /**\n * Answers the path with the routes of the app, puts the page in the\n * document, and starts the loader with client navigation. Links, forms,\n * server function calls and `#defer` requests of the page go to the same\n * routes, without a server, with the cookies that the answers set.\n */\n return async function visit(path, visitOptions = {}) {\n visited?.close();\n const jar = new Map(Object.entries(visitOptions.cookies ?? {}));\n const original = globalThis.fetch;\n const origin = location.origin;\n history.replaceState(null, '', new URL(path, origin));\n\n // A browser follows redirects, sends its cookies, and keeps the ones that the answers set.\n const answer = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n let url = new URL(input instanceof Request ? input.url : String(input), location.href);\n if (url.origin !== origin) {\n return original(input, init);\n }\n let method = (\n init?.method ?? (input instanceof Request ? input.method : 'GET')\n ).toUpperCase();\n let body = init?.body ?? undefined;\n const extra = new Headers(input instanceof Request ? input.headers : undefined);\n new Headers(init?.headers).forEach((value, name) => extra.set(name, value));\n for (let hops = 0; ; hops++) {\n const request = new Request(url, { method, body, signal: init?.signal ?? null });\n // Set after the request is made, since a DOM environment drops these from its init.\n new Headers(visitOptions.headers).forEach((value, name) =>\n request.headers.set(name, value),\n );\n extra.forEach((value, name) => request.headers.set(name, value));\n if (jar.size > 0) {\n request.headers.set(\n 'cookie',\n [...jar].map(([name, value]) => `${name}=${value}`).join('; '),\n );\n }\n if (method !== 'GET' && method !== 'HEAD') {\n request.headers.set('origin', origin);\n }\n const handle = url.pathname.startsWith(`${prefix}/`) ? options.calls : options.routes;\n const answered = handle().then((handler) => handler(request));\n // oxlint-disable-next-line no-await-in-loop -- Each redirect is a request of its own.\n const response = (await answered) ?? new Response('Not found', { status: 404 });\n storeCookies(jar, response);\n const location = response.headers.get('location');\n if (!REDIRECTS.has(response.status) || !location || init?.redirect === 'manual') {\n Object.defineProperty(response, 'url', { value: url.href });\n return response;\n }\n if (hops === 20) {\n throw new TypeError(`Too many redirects from ${path}`);\n }\n url = new URL(location, url);\n // As in fetch: 303 asks for the page with GET, and so do 301 and 302 after a POST.\n // 307 and 308 send the request again as it was.\n if (\n (response.status === 303 && method !== 'HEAD') ||\n (method === 'POST' && (response.status === 301 || response.status === 302))\n ) {\n method = 'GET';\n body = undefined;\n extra.delete('content-type');\n }\n }\n };\n globalThis.fetch = answer as typeof fetch;\n\n // The DOM of a test does not run scripts, so the ones that the page adds run here, once each.\n const ran = new WeakSet<Element>();\n const runOnce = (script: Element): void => {\n if (!ran.has(script) && !script.hasAttribute('src') && !script.hasAttribute('type')) {\n ran.add(script);\n run(script);\n }\n };\n const scripts = new MutationObserver((records) => {\n for (const record of records) {\n for (const node of record.addedNodes) {\n if (node.nodeName === 'SCRIPT') {\n runOnce(node as Element);\n } else if (node instanceof Element) {\n node.querySelectorAll('script').forEach(runOnce);\n }\n }\n }\n });\n\n const response = await answer(path);\n // The page is at the URL of the last redirect.\n history.replaceState(null, '', response.url);\n const reader = response.body!.pipeThrough(new TextDecoderStream()).getReader();\n let html = '';\n let end = -1;\n let done = false;\n while (end < 0 && !done) {\n // oxlint-disable-next-line no-await-in-loop -- The page arrives in pieces.\n const chunk = await reader.read();\n done = chunk.done;\n html += chunk.value ?? '';\n end = html.search(/<\\/html>/i);\n }\n const cut = end < 0 ? html.length : end + '</html>'.length;\n const page = new DOMParser().parseFromString(html.slice(0, cut), 'text/html');\n for (const name of document.documentElement.getAttributeNames()) {\n document.documentElement.removeAttribute(name);\n }\n for (const attribute of page.documentElement.attributes) {\n document.documentElement.setAttribute(attribute.name, attribute.value);\n }\n document.head.replaceChildren(\n ...[...page.head.childNodes].map((node) => document.importNode(node, true)),\n );\n document.body.replaceChildren(\n ...[...page.body.childNodes].map((node) => document.importNode(node, true)),\n );\n document.querySelectorAll('script').forEach(runOnce);\n scripts.observe(document, { childList: true, subtree: true });\n\n const stop = start({ load: options.load, rpc: prefix, navigate: true, preload: false });\n let rest = html.slice(cut);\n let open = true;\n void (async () => {\n while (!done) {\n // oxlint-disable-next-line no-await-in-loop -- Later markup arrives in pieces.\n const chunk = await reader.read();\n done = chunk.done;\n rest += chunk.value ?? '';\n // A chunk can end inside a tag, a script or a template, so only whole nodes move in.\n const last = done ? rest.length : wholeNodes(rest);\n if (last > 0 && open) {\n // The observer runs its scripts.\n const template = document.createElement('template');\n template.innerHTML = rest.slice(0, last);\n document.body.append(template.content);\n rest = rest.slice(last);\n }\n }\n })();\n\n const current: Visited = {\n ...actions(document),\n get url() {\n return location.pathname + location.search;\n },\n status: response.status,\n get cookies() {\n return Object.fromEntries(jar);\n },\n close: () => {\n if (!open) {\n return;\n }\n open = false;\n visited = undefined;\n stop();\n scripts.disconnect();\n reader.cancel().catch(() => {});\n if (globalThis.fetch === answer) {\n globalThis.fetch = original;\n }\n // The core forgets the page, so the next visit starts its IDs again.\n void import('./client.ts').then((core) => core.leavePage());\n document.head.replaceChildren();\n document.body.replaceChildren();\n },\n };\n visited = current;\n return current;\n };\n}\n"],"mappings":";;;AAEA,MAAM,uBAAO,IAAI,IAAI;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;AAOD,SAAgB,WAAW,QAAwB;CACjD,MAAM,MAAM;CACZ,MAAM,QAAQ,OAAO,YAAY;CACjC,IAAI,QAAQ;CACZ,IAAI,MAAM;CACV,IAAI;CACJ,OAAQ,QAAQ,IAAI,KAAK,MAAM,GAAI;EACjC,MAAM,CAAC,OAAO,SAAS,QAAQ;EAC/B,MAAM,UAAU,KAAM,YAAY;EAClC,IAAI,CAAC,WAAW,YAAY,UAAU;GAEpC,MAA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mB;GACvB,GAAG,QAAQ,QAAQ;GACnB,IAAI,MAAM;IACR,OAAO,SAAS,WAAW,SAAS;GACtC;GACA,QAAQ,SAAS;GACjB,IAAI,UAAU;IACZ,OAAO,OAAO,YAAY,GAAG;GAC/B;GACA,aAAa;IACX,IAAI,CAAC,MACH;IAEF,OAAO;IACP,UAAU,KAAA;IACV,KAAK;IACL,QAAQ,WAAW;IACnB,OAAO,OAAO,CAAC,CAAC,YAAY,CAAC,CAAC;IAC9B,IAAI,WAAW,UAAU,QACvB,WAAW,QAAQ;IAGrB,OAAY,cAAc,CAAC,MAAM,SAAS,KAAK,UAAU,CAAC;IAC1D,SAAS,KAAK,gBAAgB;IAC9B,SAAS,KAAK,gBAAgB;GAChC;EACF;EACA,UAAU;EACV,OAAO;CACT;AACF"}
@@ -0,0 +1,23 @@
1
+ //#region src/runtime/secrets.ts
2
+ const SECRETS = Symbol.for("brumate.secrets");
3
+ /**
4
+ * The values of the server variables. The server refuses to send a page
5
+ * whose state holds one. They live on `globalThis`, so a second copy of
6
+ * this module, such as one that Vite loads, shares them.
7
+ */
8
+ function serverSecrets() {
9
+ const store = globalThis;
10
+ return store[SECRETS] ??= /* @__PURE__ */ new Set();
11
+ }
12
+ /**
13
+ * Keeps the value of a server variable, as it came and as its schema gave
14
+ * it. A value under 8 characters is not kept, because a page can hold the
15
+ * same text for another reason, such as `true` or `3000`.
16
+ */
17
+ function addSecret(value) {
18
+ if (typeof value === "string" && value.length >= 8) serverSecrets().add(value);
19
+ }
20
+ //#endregion
21
+ export { serverSecrets as n, addSecret as t };
22
+
23
+ //# sourceMappingURL=secrets-BxagsJxJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secrets-BxagsJxJ.js","names":[],"sources":["../src/runtime/secrets.ts"],"sourcesContent":["// The values of the server environment variables, which `defineEnv` keeps\n// when the server starts. The server refuses to send a page whose state\n// holds one, so a secret that a helper reads cannot reach the browser.\n\nconst SECRETS = Symbol.for('brumate.secrets');\n\n/**\n * The values of the server variables. The server refuses to send a page\n * whose state holds one. They live on `globalThis`, so a second copy of\n * this module, such as one that Vite loads, shares them.\n */\nexport function serverSecrets(): Set<string> {\n const store = globalThis as { [SECRETS]?: Set<string> };\n return (store[SECRETS] ??= new Set());\n}\n\n/**\n * Keeps the value of a server variable, as it came and as its schema gave\n * it. A value under 8 characters is not kept, because a page can hold the\n * same text for another reason, such as `true` or `3000`.\n */\nexport function addSecret(value: unknown): void {\n if (typeof value === 'string' && value.length >= 8) {\n serverSecrets().add(value);\n }\n}\n"],"mappings":";AAIA,MAAM,UAAU,OAAO,IAAI,iBAAiB;;;;;;AAO5C,SAAgB,gBAA6B;CAC3C,MAAM,QAAQ;CACd,OAAQ,MAAM,6BAAa,IAAI,IAAI;AACrC;;;;;;AAOA,SAAgB,UAAU,OAAsB;CAC9C,IAAI,OAAO,UAAU,YAAY,MAAM,UAAU,GAC/C,cAAc,CAAC,CAAC,IAAI,KAAK;AAE7B"}