brumate 0.2.0 → 0.3.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 (101) hide show
  1. package/dist/{boot-D-IdPy7B.d.ts → boot-C25Sa6vq.d.ts} +5 -2
  2. package/dist/cli.js +2 -2
  3. package/dist/{client-C0UCNL3J.js → client-BD6XT-s5.js} +435 -110
  4. package/dist/client-BD6XT-s5.js.map +1 -0
  5. package/dist/{client-MD0ZmcFR.d.ts → client-D0CqSxoO.d.ts} +114 -8
  6. package/dist/{cookies-Av5WFmcf.js → cookies-BzllthiF.js} +2 -1
  7. package/dist/cookies-BzllthiF.js.map +1 -0
  8. package/dist/{defer-D0bo1Gqx.js → defer-BbD7JQhj.js} +6 -2
  9. package/dist/defer-BbD7JQhj.js.map +1 -0
  10. package/dist/devtools-CQgD7NPB.js +623 -0
  11. package/dist/devtools-CQgD7NPB.js.map +1 -0
  12. package/dist/devtools-panel-BVB-W5q4.js +1930 -0
  13. package/dist/devtools-panel-BVB-W5q4.js.map +1 -0
  14. package/dist/events-CSs7OwIC.js +85 -0
  15. package/dist/events-CSs7OwIC.js.map +1 -0
  16. package/dist/{files-Bnn1JqHx.js → files-BXSSrQgc.js} +18 -5
  17. package/dist/files-BXSSrQgc.js.map +1 -0
  18. package/dist/forms-Bg-CwGqX.js +406 -0
  19. package/dist/forms-Bg-CwGqX.js.map +1 -0
  20. package/dist/forms-Cl21hkHt.d.ts +281 -0
  21. package/dist/highlight.d.ts +17 -0
  22. package/dist/highlight.js +269 -0
  23. package/dist/highlight.js.map +1 -0
  24. package/dist/{html-y1q7-t7D.d.ts → html-Bq1rFxX_.d.ts} +36 -4
  25. package/dist/{html-bHZbkK-h.js → html-mNTKzaDD.js} +79 -8
  26. package/dist/html-mNTKzaDD.js.map +1 -0
  27. package/dist/index.d.ts +47 -2
  28. package/dist/index.js +3 -3
  29. package/dist/index.js.map +1 -1
  30. package/dist/{inspect-BJtACnQp.js → inspect-BHpOw1LF.js} +625 -48
  31. package/dist/inspect-BHpOw1LF.js.map +1 -0
  32. package/dist/{loader-B18i3_-T.js → loader-Dos_3NP0.js} +5 -4
  33. package/dist/loader-Dos_3NP0.js.map +1 -0
  34. package/dist/{navigate-BwuZveDF.js → navigate-O78d_zGN.js} +45 -2
  35. package/dist/navigate-O78d_zGN.js.map +1 -0
  36. package/dist/{produce-D4K7qpaL.d.ts → produce-D0V0ICkz.d.ts} +45 -3
  37. package/dist/{produce-CWfJ4byV.js → produce-Doc91GkX.js} +113 -6
  38. package/dist/produce-Doc91GkX.js.map +1 -0
  39. package/dist/{rpc-B-Zkn6Ch.js → rpc-ygMRPmN4.js} +20 -10
  40. package/dist/rpc-ygMRPmN4.js.map +1 -0
  41. package/dist/runtime/client.d.ts +4 -4
  42. package/dist/runtime/client.js +4 -4
  43. package/dist/runtime/devtools.d.ts +188 -3
  44. package/dist/runtime/devtools.js +1 -1
  45. package/dist/runtime/events.d.ts +15 -0
  46. package/dist/runtime/events.js +1 -1
  47. package/dist/runtime/forms.d.ts +2 -0
  48. package/dist/runtime/forms.js +1 -0
  49. package/dist/runtime/gather.d.ts +25 -0
  50. package/dist/runtime/gather.js +33 -0
  51. package/dist/runtime/gather.js.map +1 -0
  52. package/dist/runtime/hot.d.ts +1 -1
  53. package/dist/runtime/html.d.ts +2 -2
  54. package/dist/runtime/html.js +1 -1
  55. package/dist/runtime/loader.d.ts +2 -2
  56. package/dist/runtime/loader.js +2 -2
  57. package/dist/runtime/server.d.ts +5 -4
  58. package/dist/runtime/server.js +5 -5
  59. package/dist/runtime/signals.d.ts +38 -2
  60. package/dist/runtime/signals.js +12 -2
  61. package/dist/runtime/signals.js.map +1 -1
  62. package/dist/runtime/static-loader.d.ts +2 -2
  63. package/dist/runtime/static-loader.js +1 -1
  64. package/dist/runtime/testing.d.ts +2 -2
  65. package/dist/runtime/testing.js +2 -2
  66. package/dist/runtime/values.d.ts +2 -0
  67. package/dist/runtime/values.js +24 -0
  68. package/dist/runtime/values.js.map +1 -0
  69. package/dist/{server-BqfM95r1.js → server-CxVDYE_V.js} +776 -121
  70. package/dist/server-CxVDYE_V.js.map +1 -0
  71. package/dist/{server-BA9SJ2Vm.d.ts → server-DuFYRXrd.d.ts} +284 -15
  72. package/dist/{static-loader-BzE9SRaj.d.ts → static-loader-Drpr0AzI.d.ts} +2 -2
  73. package/dist/{static-loader-DOygOFj5.js → static-loader-nZssh66R.js} +168 -51
  74. package/dist/static-loader-nZssh66R.js.map +1 -0
  75. package/dist/{stream-JaMHMdBD.js → stream-DCYZO4IF.js} +89 -10
  76. package/dist/stream-DCYZO4IF.js.map +1 -0
  77. package/dist/values-B8C7CLvG.d.ts +63 -0
  78. package/dist/vite.d.ts +8 -1
  79. package/dist/vite.js +170 -20
  80. package/dist/vite.js.map +1 -1
  81. package/forms/forms.brm.ts +141 -0
  82. package/package.json +31 -2
  83. package/dist/client-C0UCNL3J.js.map +0 -1
  84. package/dist/cookies-Av5WFmcf.js.map +0 -1
  85. package/dist/defer-D0bo1Gqx.js.map +0 -1
  86. package/dist/devtools-C50VH8gZ.js +0 -113
  87. package/dist/devtools-C50VH8gZ.js.map +0 -1
  88. package/dist/devtools-panel-AYjfwPhj.js +0 -435
  89. package/dist/devtools-panel-AYjfwPhj.js.map +0 -1
  90. package/dist/events-BKWRqtMg.js +0 -52
  91. package/dist/events-BKWRqtMg.js.map +0 -1
  92. package/dist/files-Bnn1JqHx.js.map +0 -1
  93. package/dist/html-bHZbkK-h.js.map +0 -1
  94. package/dist/inspect-BJtACnQp.js.map +0 -1
  95. package/dist/loader-B18i3_-T.js.map +0 -1
  96. package/dist/navigate-BwuZveDF.js.map +0 -1
  97. package/dist/produce-CWfJ4byV.js.map +0 -1
  98. package/dist/rpc-B-Zkn6Ch.js.map +0 -1
  99. package/dist/server-BqfM95r1.js.map +0 -1
  100. package/dist/static-loader-DOygOFj5.js.map +0 -1
  101. package/dist/stream-JaMHMdBD.js.map +0 -1
@@ -1,17 +1,56 @@
1
- import { n as MODIFIERS } from "./events-BKWRqtMg.js";
2
- import { c as escape, d as isRaw, g as styleElement, h as spread$1, l as escapeAttribute, m as rawHTML, n as actionAttributes, t as VOID_ELEMENTS, u as insertValue } from "./html-bHZbkK-h.js";
3
- import { a as disabledFeatures, c as functionReferences, i as callPlugins, o as plugins, r as toChunkStream, s as syncPlugins, t as STREAM_TYPE } from "./stream-JaMHMdBD.js";
4
- import { a as parseId, i as isAsyncIterable, n as ElementReference, r as FunctionReference } from "./produce-CWfJ4byV.js";
1
+ import { n as MODIFIERS } from "./events-CSs7OwIC.js";
2
+ import { _ as rawHTML, d as handlerEntry, f as insertValue, h as onAttribute, l as escape, n as actionAttributes, o as bindEntry, p as isRaw, t as VOID_ELEMENTS, u as escapeAttribute, v as spread$1, y as styleElement } from "./html-mNTKzaDD.js";
3
+ import { n as deleteCookie, o as setCookie, r as getCookies } from "./cookies-BzllthiF.js";
4
+ import { a as plugins, c as functionReferences, i as callPlugins, o as serialOptions, r as toChunkStream, s as syncPlugins, t as STREAM_TYPE } from "./stream-DCYZO4IF.js";
5
+ import { a as SlotReference, d as parseId, i as FunctionReference, n as Binding, o as isAsyncIterable, r as ElementReference, s as isBinding } from "./produce-Doc91GkX.js";
5
6
  import { n as serverSecrets } from "./secrets-BxagsJxJ.js";
6
- import { n as deleteCookie, o as setCookie, r as getCookies } from "./cookies-Av5WFmcf.js";
7
7
  import "./context-CTiSzQRc.js";
8
+ import { a as applyIntent, d as formValues, f as formatPath, m as groupIssues, p as getAt, r as INTENT, v as parseIntent, y as parsePath } from "./forms-Bg-CwGqX.js";
8
9
  import { crossSerialize, crossSerializeStream, fromJSON, toJSON } from "seroval";
9
10
  //#region src/runtime/request.ts
11
+ function noTrace() {}
12
+ /** Ends an entry of the trace when a value settles, if it is a promise, or at once. */
13
+ function traceValue(value, end) {
14
+ const thenable = value;
15
+ if (thenable && typeof thenable.then === "function") thenable.then(() => end(), () => end(true));
16
+ else end();
17
+ return value;
18
+ }
19
+ /** The headers that tell who the user is. */
20
+ const PERSONAL = /* @__PURE__ */ new Set(["cookie", "authorization"]);
10
21
  /**
11
- * A request that the server handles: a server function call, a form post,
12
- * a page render, or a call of middleware or an endpoint. Its methods read
13
- * the request and change the response. Get it with `getEvent()`.
22
+ * Calls `read` when code reads the headers that tell who the user is, by
23
+ * name or by going through all the headers.
14
24
  */
25
+ function watchPersonal(headers, read) {
26
+ const get = headers.get.bind(headers);
27
+ const has = headers.has.bind(headers);
28
+ Object.assign(headers, {
29
+ get: (name) => {
30
+ if (PERSONAL.has(name.toLowerCase())) read();
31
+ return get(name);
32
+ },
33
+ has: (name) => {
34
+ if (PERSONAL.has(name.toLowerCase())) read();
35
+ return has(name);
36
+ }
37
+ });
38
+ for (const method of [
39
+ "entries",
40
+ "forEach",
41
+ "values",
42
+ Symbol.iterator
43
+ ]) {
44
+ const all = headers[method].bind(headers);
45
+ Object.defineProperty(headers, method, {
46
+ value: (...args) => {
47
+ read();
48
+ return all(...args);
49
+ },
50
+ configurable: true
51
+ });
52
+ }
53
+ }
15
54
  var RequestEvent = class {
16
55
  request;
17
56
  /** What the request is for. */
@@ -38,6 +77,39 @@ var RequestEvent = class {
38
77
  refreshed;
39
78
  /** Cookies that this request set, or deleted with undefined, so later reads see them. */
40
79
  cookies;
80
+ /**
81
+ * True once the request read its cookies or its `authorization` header, or
82
+ * set a cookie, such as for a session. The answer then depends on the user,
83
+ * so a page with `cache` is not cached for everyone.
84
+ */
85
+ personal = false;
86
+ /**
87
+ * In development, what the render of the page did and when, in
88
+ * milliseconds from its start, for the Server tab of the devtools.
89
+ */
90
+ trace;
91
+ /** When the trace started, by `performance.now()`. */
92
+ traceStart = 0;
93
+ /** Starts an entry of the trace, when there is one, and returns what ends it. */
94
+ traced(kind, label) {
95
+ const trace = this.trace;
96
+ if (!trace) return noTrace;
97
+ const entry = {
98
+ kind,
99
+ label,
100
+ start: performance.now() - this.traceStart
101
+ };
102
+ trace.push(entry);
103
+ return (failed) => {
104
+ entry.end = performance.now() - this.traceStart;
105
+ if (failed) entry.failed = true;
106
+ };
107
+ }
108
+ /**
109
+ * The tags of the `cached` functions that the request called, with the
110
+ * version that each had then, so `revalidate` drops the page that it renders.
111
+ */
112
+ cacheTags = /* @__PURE__ */ new Map();
41
113
  controller = new AbortController();
42
114
  /**
43
115
  * Aborts when the request no longer needs an answer: the request's own
@@ -53,6 +125,9 @@ var RequestEvent = class {
53
125
  this.keepGoing = options.waitUntil;
54
126
  this.address = options.address;
55
127
  this.prerender = options.prerender ?? false;
128
+ watchPersonal(request.headers, () => {
129
+ this.personal = true;
130
+ });
56
131
  const outer = request.signal;
57
132
  if (outer?.aborted) this.controller.abort(outer.reason);
58
133
  else outer?.addEventListener("abort", () => this.abort(outer.reason), { once: true });
@@ -138,6 +213,10 @@ function withEvent(event, callback, calls) {
138
213
  currentCalls = outerCalls;
139
214
  }
140
215
  }
216
+ /** The event of the request being handled, or undefined, without throwing as `getEvent` does. */
217
+ function currentEvent() {
218
+ return current;
219
+ }
141
220
  /**
142
221
  * Returns the event of the request that the server handles: in a server
143
222
  * function, middleware or an endpoint, or while a component renders.
@@ -186,7 +265,17 @@ function runEntry(middleware, event, answer) {
186
265
  * requests of their own, always run, so a function that changes something
187
266
  * runs each time.
188
267
  */
268
+ /** Marks the functions that `idempotent` made. A symbol of the registry. */
269
+ const IDEMPOTENT = Symbol.for("brumate.idempotent");
270
+ /** The IDs of the server functions that `idempotent` made, which `dedupe` records. */
271
+ const idempotentIds = /* @__PURE__ */ new Set();
272
+ /** The ID of each function that `idempotent` made, once the server registered it. */
273
+ const idempotentId = /* @__PURE__ */ new WeakMap();
189
274
  function dedupe(fn, id) {
275
+ if (IDEMPOTENT in fn) {
276
+ idempotentIds.add(id);
277
+ idempotentId.set(fn, id);
278
+ }
190
279
  const wrapper = ((...args) => {
191
280
  const cache = currentCalls;
192
281
  if (!cache) return fn(...args);
@@ -194,12 +283,12 @@ function dedupe(fn, id) {
194
283
  try {
195
284
  key = `${id} ${JSON.stringify(toJSON(args, {
196
285
  plugins: syncPlugins,
197
- disabledFeatures
286
+ ...serialOptions()
198
287
  }))}`;
199
288
  } catch {
200
289
  return fn(...args);
201
290
  }
202
- if (!cache.has(key)) cache.set(key, fn(...args));
291
+ if (!cache.has(key)) cache.set(key, traceValue(fn(...args), current?.traced("call", id) ?? noTrace));
203
292
  return cache.get(key);
204
293
  });
205
294
  Object.defineProperty(wrapper, ORIGINAL, { value: fn });
@@ -254,6 +343,141 @@ function isRedirect(error) {
254
343
  return error instanceof Redirect;
255
344
  }
256
345
  //#endregion
346
+ //#region src/runtime/cache.ts
347
+ /** Tags live longer than any result, so a result never outlives the version of its tag. */
348
+ const TAG_AGE = 31536e3;
349
+ /**
350
+ * A store in the memory of the server, the default. Each process has its
351
+ * own, and it keeps at most `size` values, dropping the oldest first.
352
+ */
353
+ function memoryStore(size = 1e3) {
354
+ const values = /* @__PURE__ */ new Map();
355
+ return {
356
+ memory: true,
357
+ get(key) {
358
+ const item = values.get(key);
359
+ if (!item) return;
360
+ if (item.expires <= Date.now()) {
361
+ values.delete(key);
362
+ return;
363
+ }
364
+ return item.value;
365
+ },
366
+ set(key, value, maxAge) {
367
+ values.delete(key);
368
+ values.set(key, {
369
+ value,
370
+ expires: Date.now() + maxAge * 1e3
371
+ });
372
+ for (const oldest of values.keys()) {
373
+ if (values.size <= size) break;
374
+ values.delete(oldest);
375
+ }
376
+ }
377
+ };
378
+ }
379
+ let store = memoryStore();
380
+ /**
381
+ * Sets the store of `cached`, such as one that keeps results in Redis for
382
+ * every process of the app. Set it before the first request.
383
+ */
384
+ function setCacheStore(next) {
385
+ store = next;
386
+ }
387
+ /**
388
+ * A store of `cached` from an unstorage storage, such as Nitro's
389
+ * `useStorage('cache')`. It reads and writes the values as they are, since
390
+ * `getItem` would parse text that looks like JSON.
391
+ */
392
+ function storageStore(storage) {
393
+ return {
394
+ get: async (key) => {
395
+ const value = await (storage.getItemRaw ?? storage.getItem).call(storage, key);
396
+ if (value instanceof Uint8Array) return new TextDecoder().decode(value);
397
+ return typeof value === "string" ? value : void 0;
398
+ },
399
+ set: (key, value, maxAge) => (storage.setItemRaw ?? storage.setItem).call(storage, key, value, { ttl: maxAge })
400
+ };
401
+ }
402
+ /** Calls that are running, by key, so calls with the same arguments share one run. */
403
+ const running$1 = /* @__PURE__ */ new Map();
404
+ let unnamed = 0;
405
+ /** The text of a value, as the store keeps it. */
406
+ function write(value) {
407
+ return toJSON(value, {
408
+ plugins: syncPlugins,
409
+ ...serialOptions()
410
+ });
411
+ }
412
+ /**
413
+ * Makes a function that keeps its results for `maxAge` seconds, by its
414
+ * arguments, and returns a kept result in place of running again. Use it for
415
+ * data that every user sees the same, such as a list of products.
416
+ *
417
+ * - The function runs without the request: `getEvent()` throws in it, so a
418
+ * result never holds one user's data. Pass what it needs as arguments.
419
+ * - Arguments and results are values that brumate can send, such as plain
420
+ * objects, arrays, dates and maps.
421
+ * - Calls with the same arguments while one runs share that run.
422
+ * - `revalidate(tag)` drops the results of a tag.
423
+ */
424
+ function cached(fn, options) {
425
+ const id = options.name ?? `#${unnamed++}`;
426
+ return async (...args) => {
427
+ if (options.name === void 0 && !("memory" in store)) throw new Error("Give cached a name, such as cached(fn, { name: \"products\", maxAge: 60 }), so every process finds its results in the store");
428
+ const key = `brumate:cache:${id}:${JSON.stringify(write(args))}`;
429
+ const tags = typeof options.tags === "function" ? options.tags(...args) : options.tags ?? [];
430
+ const event = currentEvent();
431
+ for (const tag of tags) if (!event?.cacheTags.has(tag)) event?.cacheTags.set(tag, void 0);
432
+ const versions = await tagVersions(tags);
433
+ for (const tag of tags) if (event?.cacheTags.get(tag) === void 0) event?.cacheTags.set(tag, versions[tag]);
434
+ const kept = await store.get(key);
435
+ if (kept) {
436
+ const entry = JSON.parse(kept);
437
+ if (entry.expires > Date.now() && tags.every((tag) => entry.tags[tag] === versions[tag])) return fromJSON(entry.value, { plugins: syncPlugins });
438
+ }
439
+ let run = running$1.get(key);
440
+ if (!run) {
441
+ const started = (async () => {
442
+ const value = await withEvent(void 0, () => fn(...args));
443
+ const entry = {
444
+ value: write(value),
445
+ expires: Date.now() + options.maxAge * 1e3,
446
+ tags: versions
447
+ };
448
+ await store.set(key, JSON.stringify(entry), options.maxAge);
449
+ return value;
450
+ })();
451
+ run = started;
452
+ running$1.set(key, started);
453
+ started.then(() => running$1.delete(key), () => running$1.delete(key));
454
+ }
455
+ return fromJSON(write(await run), { plugins: syncPlugins });
456
+ };
457
+ }
458
+ /** The store of `cached`, which the page cache of the server shares. */
459
+ function cacheStore() {
460
+ return store;
461
+ }
462
+ /** The versions of tags. A tag that was never revalidated has version `0`. */
463
+ async function tagVersions(tags) {
464
+ const versions = {};
465
+ await Promise.all([...tags].map(async (tag) => {
466
+ versions[tag] = await store.get(`brumate:tag:${tag}`) ?? "0";
467
+ }));
468
+ return versions;
469
+ }
470
+ let revalidations = 0;
471
+ /**
472
+ * Drops the results of `cached` functions with these tags, such as after a
473
+ * server function changes the data. The next call runs the function again.
474
+ * To show the new data on the page, call `refresh` too.
475
+ */
476
+ async function revalidate(...tags) {
477
+ const version = `${Date.now()}.${revalidations++}`;
478
+ await Promise.all(tags.map((tag) => store.set(`brumate:tag:${tag}`, version, TAG_AGE)));
479
+ }
480
+ //#endregion
257
481
  //#region src/runtime/router.ts
258
482
  function key(path, file, params) {
259
483
  return `${path}/${file} ${JSON.stringify(params)}`;
@@ -450,67 +674,6 @@ async function parse(schema, value) {
450
674
  if (result.issues) throw new ValidationError(result.issues);
451
675
  return result.value;
452
676
  }
453
- /** Names that would change the prototype of an object, or reach the one of its constructor. */
454
- const FORBIDDEN = /* @__PURE__ */ new Set([
455
- "__proto__",
456
- "constructor",
457
- "prototype"
458
- ]);
459
- /**
460
- * Turns the entries of a form into a plain object:
461
- *
462
- * - A name that appears once holds its value.
463
- * - A name that appears more than once holds an array of its values.
464
- * - A name that ends with `[]` always holds an array, under the name without `[]`.
465
- * - Dots nest objects: `address.city` is `{ address: { city } }`.
466
- * - Values stay strings and files.
467
- *
468
- * A name with an empty part, a part such as `__proto__`, or one that needs
469
- * an object where another field holds a value, is an issue, and the schema
470
- * does not run.
471
- */
472
- function formValues(form) {
473
- const root = {};
474
- const objects = /* @__PURE__ */ new Set([root]);
475
- const arrays = /* @__PURE__ */ new Set();
476
- const issues = [];
477
- for (const [name, value] of form) {
478
- const list = name.endsWith("[]");
479
- const parts = (list ? name.slice(0, -2) : name).split(".");
480
- if (parts.some((part) => part === "" || FORBIDDEN.has(part))) {
481
- issues.push({ message: "The form has a field name that is not allowed" });
482
- continue;
483
- }
484
- let target = root;
485
- let conflict = false;
486
- for (const part of parts.slice(0, -1)) {
487
- const next = Object.hasOwn(target, part) ? target[part] : void 0;
488
- if (next === void 0) {
489
- const child = {};
490
- objects.add(child);
491
- target[part] = child;
492
- target = child;
493
- } else if (objects.has(next)) target = next;
494
- else {
495
- conflict = true;
496
- break;
497
- }
498
- }
499
- const last = parts.at(-1);
500
- const current = Object.hasOwn(target, last) ? target[last] : void 0;
501
- if (conflict || objects.has(current)) issues.push({
502
- message: `Field "${name}" conflicts with another field`,
503
- path: parts
504
- });
505
- else if (arrays.has(current)) current.push(value);
506
- else if (current !== void 0 || list) {
507
- const values = current === void 0 ? [value] : [current, value];
508
- arrays.add(values);
509
- target[last] = values;
510
- } else target[last] = value;
511
- }
512
- return issues.length > 0 ? { issues } : { value: root };
513
- }
514
677
  /**
515
678
  * Validates the data of a form with a Standard Schema. The entries become a
516
679
  * plain object first. Returns `{ value }` or `{ issues }`, and does not throw
@@ -548,6 +711,124 @@ function fieldErrors(issues) {
548
711
  return errors;
549
712
  }
550
713
  //#endregion
714
+ //#region src/runtime/submission.ts
715
+ /** True for a file, so it is not sent back. */
716
+ const isBlob = (value) => typeof Blob !== "undefined" && value instanceof Blob;
717
+ /** The values to send back: without files and hidden fields. */
718
+ function echo(value, hidden, path = []) {
719
+ if (path.length > 0 && hidden.has(formatPath(path))) return;
720
+ if (isBlob(value)) return;
721
+ if (Array.isArray(value)) return value.map((item, index) => echo(item, hidden, [...path, index]));
722
+ if (typeof value === "object" && value !== null) {
723
+ const copy = {};
724
+ for (const [key, item] of Object.entries(value)) {
725
+ const next = echo(item, hidden, [...path, key]);
726
+ if (next !== void 0) copy[key] = next;
727
+ }
728
+ return copy;
729
+ }
730
+ return value;
731
+ }
732
+ /** A new ID for a reply, which the keys of the items of a changed list start with. */
733
+ function replyId() {
734
+ return Math.random().toString(36).slice(2, 10);
735
+ }
736
+ /**
737
+ * Reads the data of a form that `createForm` shows. It turns the entries
738
+ * into an object, as `parseForm` does, applies the intent of the button
739
+ * that was pressed, and validates the values with a Standard Schema when
740
+ * the button was not an intent. It does not throw for data that does not
741
+ * match. `reply()` gives what the function returns, for `createForm` to show.
742
+ *
743
+ * ```ts
744
+ * async function save(form: FormData) {
745
+ * 'use server';
746
+ * const submission = await parseSubmission(Order, form);
747
+ * if (submission.status !== 'success') {
748
+ * return submission.reply();
749
+ * }
750
+ * await db.orders.save(submission.value);
751
+ * return submission.reply({ reset: true });
752
+ * }
753
+ * ```
754
+ */
755
+ async function parseSubmission(schema, form, options = {}) {
756
+ const hidden = new Set(options.hide);
757
+ const id = replyId();
758
+ const make = (status, payload, issues, list) => ({
759
+ payload,
760
+ reply(reply = {}) {
761
+ const grouped = groupIssues(issues);
762
+ const errors = { ...grouped.errors };
763
+ for (const [name, messages] of Object.entries(reply.fieldErrors ?? {})) errors[name] = [...Object.hasOwn(errors, name) ? errors[name] : [], ...messages];
764
+ const keys = {};
765
+ const items = list === void 0 ? void 0 : getAt(payload, parsePath(list));
766
+ if (list !== void 0 && Array.isArray(items)) keys[list] = items.map((_, index) => `${id}-${index}`);
767
+ const result = {
768
+ status,
769
+ value: reply.reset ? void 0 : echo(payload, hidden),
770
+ errors: reply.reset ? {} : errors,
771
+ formErrors: [...grouped.formErrors, ...reply.formErrors ?? []],
772
+ keys: reply.reset ? {} : keys,
773
+ id
774
+ };
775
+ if (reply.reset) result.reset = true;
776
+ return result;
777
+ }
778
+ });
779
+ const raw = form.get(INTENT);
780
+ const values = formValues(form, (name) => name === INTENT);
781
+ if (values.issues) return {
782
+ status: "error",
783
+ issues: values.issues,
784
+ ...make("error", void 0, values.issues)
785
+ };
786
+ let payload = values.value;
787
+ if (raw === null) {
788
+ const result = await safeParse(schema, payload);
789
+ if (result.issues) return {
790
+ status: "error",
791
+ issues: result.issues,
792
+ ...make("error", payload, result.issues)
793
+ };
794
+ return {
795
+ status: "success",
796
+ value: result.value,
797
+ ...make("success", payload, [])
798
+ };
799
+ }
800
+ const intent = typeof raw === "string" ? parseIntent(raw) : void 0;
801
+ const applied = intent && applyIntent(payload, intent);
802
+ if (!intent || !applied) {
803
+ const issues = [{ message: "The form asked for a change that it cannot make" }];
804
+ return {
805
+ status: "error",
806
+ intent,
807
+ issues,
808
+ ...make("error", payload, issues)
809
+ };
810
+ }
811
+ payload = applied.value ?? void 0;
812
+ if (intent.type === "validate") {
813
+ const result = await safeParse(schema, payload);
814
+ const name = intent.name;
815
+ const issues = (result.issues ?? []).filter((issue) => {
816
+ const path = issue.path ? formatPath(issue.path) : "";
817
+ return path === name || path.startsWith(`${name}.`) || path.startsWith(`${name}[`);
818
+ });
819
+ return {
820
+ status: "intent",
821
+ intent,
822
+ ...make("intent", payload, issues)
823
+ };
824
+ }
825
+ return {
826
+ status: "intent",
827
+ intent,
828
+ ...make("intent", payload, [], applied.list)
829
+ };
830
+ }
831
+ //#endregion
551
832
  //#region src/runtime/rate-limit.ts
552
833
  /**
553
834
  * The error of a request over its limit. Its status is 429, and
@@ -815,7 +1096,127 @@ function clientAddress(event, proxies = config.proxies ?? []) {
815
1096
  return formatAddress(client);
816
1097
  }
817
1098
  //#endregion
1099
+ //#region src/runtime/idempotent.ts
1100
+ /** Runs that are going on, by key, so a second post while the first runs waits for it. */
1101
+ const running = /* @__PURE__ */ new Map();
1102
+ /**
1103
+ * Makes a server function that runs once for each form that the server
1104
+ * renders for it. A second post of the same form, such as a double click
1105
+ * before the page loaded or a post again after a reload, gets the result of
1106
+ * the first, or the same redirect, without running the function again.
1107
+ *
1108
+ * - It works for the exported functions of a `'use server'` file, used as the
1109
+ * `action` of a form.
1110
+ * - The key is in the URL of the form, so a page with such a form is not
1111
+ * cached for everyone. Each render has a new key.
1112
+ * - With scripts, the form gets a new key after each answer, so a post that
1113
+ * the user means again runs again.
1114
+ * - A call without a key, such as from a handler, runs as usual.
1115
+ */
1116
+ function idempotent(fn, options = {}) {
1117
+ const maxAge = options.maxAge ?? 600;
1118
+ const wrapper = ((...args) => {
1119
+ const event = currentEvent();
1120
+ const key = event && new URL(event.request.url).searchParams.get("__key");
1121
+ const id = idempotentId.get(wrapper);
1122
+ if (!event || !key || !id || !/^[\w-]{8,64}$/.test(key)) return fn(...args);
1123
+ const storeKey = `brumate:once:${id}:${key}`;
1124
+ let run = running.get(storeKey);
1125
+ if (!run) {
1126
+ run = (async () => {
1127
+ const kept = await cacheStore().get(storeKey);
1128
+ if (kept) return fromJSON(JSON.parse(kept), { plugins: syncPlugins });
1129
+ let outcome;
1130
+ try {
1131
+ outcome = { result: await withEvent(event, () => fn(...args)) };
1132
+ } catch (error) {
1133
+ if (!isRedirect(error)) throw error;
1134
+ outcome = { redirect: {
1135
+ location: error.location,
1136
+ status: error.status
1137
+ } };
1138
+ }
1139
+ const text = JSON.stringify(toJSON(outcome, {
1140
+ plugins: syncPlugins,
1141
+ ...serialOptions()
1142
+ }));
1143
+ await cacheStore().set(storeKey, text, maxAge);
1144
+ return outcome;
1145
+ })();
1146
+ running.set(storeKey, run);
1147
+ run.then(() => running.delete(storeKey), () => running.delete(storeKey));
1148
+ }
1149
+ return run.then((outcome) => {
1150
+ if ("redirect" in outcome) redirect(outcome.redirect.location, outcome.redirect.status);
1151
+ return outcome.result;
1152
+ });
1153
+ });
1154
+ Object.defineProperty(wrapper, IDEMPOTENT, { value: true });
1155
+ return wrapper;
1156
+ }
1157
+ //#endregion
818
1158
  //#region src/runtime/server.ts
1159
+ /** What `$bind(name)` passes a child: the value of the name, and the scope and slot it writes. */
1160
+ function binding(value, scope, slot, set) {
1161
+ return new Binding(value, new SlotReference(scope, slot), set);
1162
+ }
1163
+ /**
1164
+ * The `#loading` bodies of a `#reveal` block, in the order of the markup.
1165
+ * When a body is ready, the stream asks the group, which sends the bodies
1166
+ * that its order lets show. The data of every body still loads at once.
1167
+ */
1168
+ var RevealGroup = class {
1169
+ order;
1170
+ collapsed;
1171
+ /** The bodies that stream, each with how to send it once it is ready. */
1172
+ members = [];
1173
+ /** The fallbacks that `collapsed` hides until the body before them shows. */
1174
+ hidden = /* @__PURE__ */ new Set();
1175
+ closed = false;
1176
+ constructor(order, collapsed) {
1177
+ this.order = order;
1178
+ this.collapsed = collapsed;
1179
+ }
1180
+ /** True when a body that is ready can render in place, before the bodies that stream. */
1181
+ mayShow() {
1182
+ return this.order === "natural" || this.order === "sequential" && this.members.length === 0;
1183
+ }
1184
+ /** True when the fallback of the next body that streams waits, for `collapsed`. */
1185
+ hides() {
1186
+ return this.collapsed && this.members.length > 0;
1187
+ }
1188
+ add(id) {
1189
+ this.members.push({ id });
1190
+ }
1191
+ /** The body is ready, or failed with nothing to send. `send` writes it, and runs `after` with it. */
1192
+ ready(id, send) {
1193
+ const member = this.members.find((item) => item.id === id);
1194
+ if (member) {
1195
+ member.send = send;
1196
+ this.flush();
1197
+ } else send("");
1198
+ }
1199
+ /** The block ended, so the group knows its last body. */
1200
+ close() {
1201
+ this.closed = true;
1202
+ this.flush();
1203
+ }
1204
+ flush() {
1205
+ const { members } = this;
1206
+ const sendAt = (index) => {
1207
+ const member = members[index];
1208
+ member.sent = true;
1209
+ const next = members[index + 1];
1210
+ member.send(next && this.hidden.has(next.id) ? `$bF(${scriptJSON(next.id)})` : "");
1211
+ };
1212
+ if (this.order === "natural") members.forEach((member, index) => member.send && !member.sent && sendAt(index));
1213
+ else if (this.order === "sequential") {
1214
+ for (let index = 0; index < members.length && members[index].send; index++) if (!members[index].sent) sendAt(index);
1215
+ } else if (this.closed && this.order === "backwards") {
1216
+ for (let index = members.length - 1; index >= 0 && members[index].send; index--) if (!members[index].sent) sendAt(index);
1217
+ } else if (this.closed && members.every((member) => member.send)) members.forEach((member, index) => !member.sent && sendAt(index));
1218
+ }
1219
+ };
819
1220
  /** True if a boundary holds `target`, whose ID starts with the boundary's ID and a dot. */
820
1221
  function holdsBoundary(id, target) {
821
1222
  return typeof target === "string" && target.startsWith(`${id}.`);
@@ -908,6 +1309,14 @@ var Context = class Context {
908
1309
  if (!event) throw new Error("getEvent() works while a page renders with a request, such as in a route");
909
1310
  return event;
910
1311
  }
1312
+ /** Starts an entry of the trace of the request, in development. */
1313
+ traced(kind, label) {
1314
+ return this.root.event?.traced(kind, label);
1315
+ }
1316
+ /** Marks the request of the page as one that depends on the user, so the page is not cached for everyone. */
1317
+ personal() {
1318
+ if (this.root.event) this.root.event.personal = true;
1319
+ }
911
1320
  /** Runs code of the render with its event and its call results, such as a memo's compute. */
912
1321
  run(callback) {
913
1322
  return withEvent(this.root.event, callback, this.root.calls);
@@ -1207,6 +1616,17 @@ var Context = class Context {
1207
1616
  if (names) entry.names = names;
1208
1617
  }
1209
1618
  /**
1619
+ * Records the props that a parent bound with `$bind`, among the props that
1620
+ * the component writes: `slots` has the slot of each, by its name. Its
1621
+ * writes in the browser go to the parent's slots.
1622
+ */
1623
+ bindings(scope, props, slots) {
1624
+ for (const [name, slot] of Object.entries(slots)) {
1625
+ const value = props[name];
1626
+ if (isBinding(value)) (this.entry(scope).record.b ??= {})[slot] = value.target;
1627
+ }
1628
+ }
1629
+ /**
1210
1630
  * Records the item of a list that can change on the client. `source` is
1211
1631
  * the scope and slot that hold the list, when the compiler found one, so
1212
1632
  * the client can take the item from there.
@@ -1229,10 +1649,21 @@ var Context = class Context {
1229
1649
  element(scope, anchor) {
1230
1650
  return new ElementReference(scope, anchor);
1231
1651
  }
1232
- /** Marks a function as a client function, so it serializes as a reference. */
1233
- fn(value, ref, scope) {
1234
- if (typeof value === "function") functionReferences.set(value, new FunctionReference(ref, scope));
1235
- return value;
1652
+ /**
1653
+ * Marks a function as a client function, so it serializes as a reference.
1654
+ * `args` are the arguments of a handler that `$handler` made, which go
1655
+ * with the reference. Each call makes a new reference, so a function that
1656
+ * `$handler` marks gets a copy for its arguments.
1657
+ */
1658
+ fn(value, ref, scope, args) {
1659
+ if (typeof value !== "function") return value;
1660
+ if (args === void 0) {
1661
+ functionReferences.set(value, new FunctionReference(ref, scope));
1662
+ return value;
1663
+ }
1664
+ const bound = Object.assign((...rest) => value(...args, ...rest), value);
1665
+ functionReferences.set(bound, new FunctionReference(ref, scope, args));
1666
+ return bound;
1236
1667
  }
1237
1668
  /** Returns a component's stylesheet the first time the page renders the component. */
1238
1669
  style(id, css) {
@@ -1302,6 +1733,37 @@ var Context = class Context {
1302
1733
  }
1303
1734
  /** True when the bodies of `#defer` blocks render in place, for a page that renders in order. */
1304
1735
  inOrder = false;
1736
+ /** The `#reveal` blocks that are open in this context, the innermost last. */
1737
+ reveals = [];
1738
+ /** Starts a `#reveal` block: the `#loading` bodies until `revealEnd` show in its order. */
1739
+ revealStart(order, collapsed) {
1740
+ const group = new RevealGroup(order, collapsed);
1741
+ this.reveals.push(group);
1742
+ this.undo.push(() => group.close());
1743
+ }
1744
+ /** Ends the `#reveal` block that `revealStart` started. */
1745
+ revealEnd() {
1746
+ this.reveals.pop()?.close();
1747
+ }
1748
+ /** The group of the `#reveal` block around the next body, when the stream orders it. */
1749
+ get reveal() {
1750
+ return this.root.target ? void 0 : this.reveals.at(-1);
1751
+ }
1752
+ /** True when a `#loading` body that is ready can render in place, as its `#reveal` allows. */
1753
+ mayShow() {
1754
+ return this.reveal?.mayShow() ?? true;
1755
+ }
1756
+ /** Starts the fallback of a `#loading` body, which `collapsed` hides in a template. */
1757
+ fallbackStart(id) {
1758
+ const group = this.reveal;
1759
+ if (!group?.hides()) return "";
1760
+ group.hidden.add(id);
1761
+ return `<template b-f="${id}">`;
1762
+ }
1763
+ /** Ends the fallback that `fallbackStart` started. */
1764
+ fallbackEnd(id) {
1765
+ return this.reveal?.hidden.has(id) ? "</template>" : "";
1766
+ }
1305
1767
  /** Returns the ID of a new `#loading` boundary. */
1306
1768
  boundary() {
1307
1769
  return spaceId(this.space, this.space.boundary++);
@@ -1339,13 +1801,23 @@ var Context = class Context {
1339
1801
  register(id, renderBody, inTarget, around = false) {
1340
1802
  const child = new Context(this.root, void 0, 0, `${id}.`);
1341
1803
  child.inTarget = inTarget;
1804
+ const group = this.reveal;
1805
+ group?.add(id);
1806
+ const end = around ? void 0 : this.traced("body", `#loading ${id}`);
1342
1807
  const boundary = {
1343
1808
  id,
1344
- render: renderBody(child).then((html) => ({
1345
- html,
1346
- ctx: child
1347
- })),
1348
- around
1809
+ render: renderBody(child).then((html) => {
1810
+ end?.();
1811
+ return {
1812
+ html,
1813
+ ctx: child
1814
+ };
1815
+ }, (error) => {
1816
+ end?.(true);
1817
+ throw error;
1818
+ }),
1819
+ around,
1820
+ group
1349
1821
  };
1350
1822
  boundary.render.catch(() => {});
1351
1823
  const root = this.root;
@@ -1377,11 +1849,12 @@ var NotReady = class extends Error {
1377
1849
  }
1378
1850
  };
1379
1851
  /** Declares a memo. Its value is computed when it is first read. */
1380
- function memo(compute, ctx) {
1852
+ function memo(compute, ctx, name) {
1381
1853
  return {
1382
1854
  compute,
1383
1855
  ctx,
1384
- state: "idle"
1856
+ state: "idle",
1857
+ name
1385
1858
  };
1386
1859
  }
1387
1860
  /**
@@ -1405,7 +1878,8 @@ function read(node) {
1405
1878
  }
1406
1879
  if (value !== null && typeof value === "object" && (typeof value.then === "function" || isAsyncIterable(value))) {
1407
1880
  node.state = "pending";
1408
- node.load = Promise.resolve(value).then(firstValue).then((result) => {
1881
+ const end = node.ctx?.traced("memo", node.name ?? "memo");
1882
+ node.load = Promise.resolve(value).then(firstValue).finally(() => end?.()).then((result) => {
1409
1883
  node.state = "done";
1410
1884
  node.value = result;
1411
1885
  }, (error) => {
@@ -1532,7 +2006,12 @@ function isLazy(value) {
1532
2006
  }
1533
2007
  /** Renders the attributes of a form or button that posts to a server function. */
1534
2008
  function action(ctx, name, id, method, result) {
1535
- return actionAttributes(ctx.rpc(), name, id, method, result, ctx.buildId());
2009
+ let key;
2010
+ if (idempotentIds.has(id)) {
2011
+ key = crypto.randomUUID();
2012
+ ctx.personal();
2013
+ }
2014
+ return actionAttributes(ctx.rpc(), name, id, method, result, ctx.buildId(), key);
1536
2015
  }
1537
2016
  /**
1538
2017
  * The result of a server function that a form posted to this page, for
@@ -1594,7 +2073,11 @@ function holds(value, target, seen = /* @__PURE__ */ new Set()) {
1594
2073
  if (value === target) return true;
1595
2074
  if (typeof value !== "object" || value === null || seen.has(value)) return false;
1596
2075
  seen.add(value);
1597
- return (value instanceof Map ? [...value.keys(), ...value.values()] : value instanceof Set ? [...value] : Array.isArray(value) || Object.getPrototypeOf(value) === Object.prototype ? Object.values(value) : []).some((item) => holds(item, target, seen));
2076
+ let items = [];
2077
+ if (value instanceof Map) items = [...value.keys(), ...value.values()];
2078
+ else if (value instanceof Set) items = [...value];
2079
+ else if (Array.isArray(value) || Object.getPrototypeOf(value) === Object.prototype) items = Object.values(value);
2080
+ return items.some((item) => holds(item, target, seen));
1598
2081
  }
1599
2082
  /**
1600
2083
  * The error of a value in the state of a page that cannot be sent to the
@@ -1698,8 +2181,8 @@ function groupSource(record, group) {
1698
2181
  const source = entries[0].source;
1699
2182
  if (!source || !(group.flags & 3)) return;
1700
2183
  const value = record(source[0])?.s?.[source[1]];
1701
- const list = Array.isArray(value) ? value : value instanceof Set ? Array.from(value) : void 0;
1702
- if (!list || list.length < entries.length) return;
2184
+ const list = value instanceof Set ? Array.from(value) : value;
2185
+ if (!Array.isArray(list) || list.length < entries.length) return;
1703
2186
  for (let n = 0; n < entries.length; n++) {
1704
2187
  const entry = entries[n];
1705
2188
  if (entry.source !== source || !Object.is(list[n], entry.record.i)) return;
@@ -1828,7 +2311,7 @@ function serializeState(state, refs, onRecord, onError, onDone, sources, last =
1828
2311
  try {
1829
2312
  code = crossSerialize(packed, {
1830
2313
  plugins: syncPlugins,
1831
- disabledFeatures,
2314
+ ...serialOptions(),
1832
2315
  refs,
1833
2316
  assignSharedRefsOnly: true
1834
2317
  });
@@ -1843,7 +2326,7 @@ function serializeState(state, refs, onRecord, onError, onDone, sources, last =
1843
2326
  }
1844
2327
  crossSerializeStream(packed, {
1845
2328
  plugins,
1846
- disabledFeatures,
2329
+ ...serialOptions(),
1847
2330
  refs,
1848
2331
  onSerialize: send,
1849
2332
  onError,
@@ -1886,7 +2369,9 @@ function stateScript(code, scopes = false, attributes = {}) {
1886
2369
  return `<script${extra}>${attributes.define ? RECORD : ""}$bR(($R,$b)=>(${code}))<\/script>`;
1887
2370
  }
1888
2371
  const HEAD = `function $bH(i,t){var e=document.querySelector('template[b-h="'+i+'"]'),h=document.head;e&&(h.append(e.content),e.remove());t!=null&&(h.querySelector('title:not([b-t])')||h.prepend(document.createElement('title')),document.title=t)}`;
2372
+ const SHOW_FALLBACK = `function $bF(i){var t=document.querySelector('template[b-f="'+i+'"]');t&&t.replaceWith(t.content)}`;
1889
2373
  const SWAP = `function $bS(i){var t=document.querySelector('template[b-l="'+i+'"]'),w=document.createTreeWalker(document.body,128),s,n,d=0;while(n=w.nextNode())if(n.data==='l'+i){s=n;break}if(!s||!t)return;var p=s.parentNode;for(n=s.nextSibling;n;){if(n.nodeType===8){if(n.data==='/l'){if(!d)break;d--}else if(/^l\\d/.test(n.data))d++}var x=n.nextSibling;p.removeChild(n);n=x}p.insertBefore(t.content,s);p.removeChild(s);n&&p.removeChild(n);t.remove()}`;
2374
+ const SWAP_DEV = `function $bS(i){var t=document.querySelector('template[b-l="'+i+'"]'),w=document.createTreeWalker(document.body,128),s,n,d=0;while(n=w.nextNode())if(n.data==='l'+i){s=n;break}if(!s||!t)return;var p=s.parentNode,f=[];for(n=s.nextSibling;n;){if(n.nodeType===8){if(n.data==='/l'){if(!d)break;d--}else if(/^l\\d/.test(n.data))d++}var x=n.nextSibling;f.push(p.removeChild(n));n=x}(self.$bD||(self.$bD={}))[i]={f:f,b:[].slice.call(t.content.childNodes)};p.insertBefore(t.content,s);p.removeChild(s);n&&p.removeChild(n);t.remove()}`;
1890
2375
  /** The `pending` of a render that has nothing left to send. */
1891
2376
  const NOTHING_PENDING = { [Symbol.asyncIterator]: () => ({ next: () => Promise.resolve({
1892
2377
  done: true,
@@ -1964,6 +2449,13 @@ async function render(Root, props, options = {}) {
1964
2449
  if (open === 0) queue?.close();
1965
2450
  };
1966
2451
  let boundaries = 0;
2452
+ const swapScript = options.dev ? SWAP_DEV : SWAP;
2453
+ let fallbackDefined = false;
2454
+ const showFallback = () => {
2455
+ if (fallbackDefined) return "";
2456
+ fallbackDefined = true;
2457
+ return `${SHOW_FALLBACK};`;
2458
+ };
1967
2459
  const serialize = (target, onScopes, route, onError = (error) => pending().fail(unsendable(error, target)), last = false) => {
1968
2460
  open++;
1969
2461
  serializeState(target, refs, (code, initial) => {
@@ -1994,29 +2486,40 @@ async function render(Root, props, options = {}) {
1994
2486
  }
1995
2487
  boundaries++;
1996
2488
  open++;
2489
+ const skip = (after) => {
2490
+ if (after) pending().push(`${scriptTag}${showFallback()}${after}<\/script>`);
2491
+ finish();
2492
+ };
2493
+ const turn = (send) => {
2494
+ if (boundary.group) boundary.group.ready(boundary.id, send);
2495
+ else send("");
2496
+ };
1997
2497
  boundary.render.then((result) => {
1998
2498
  if (boundary.cancelled || boundary.around || stopped()) {
1999
- finish();
2499
+ turn(skip);
2000
2500
  return;
2001
2501
  }
2002
- serialize(result.ctx, (script) => {
2003
- const id = scriptJSON(boundary.id);
2004
- let call = `${swap ? "" : SWAP}$bS(${id})`;
2005
- swap = true;
2006
- const late = result.ctx.lateHead();
2007
- let head = "";
2008
- if (late.html || late.title !== void 0) {
2009
- head = `<template b-h="${boundary.id}">${late.html}</template>`;
2010
- const title = late.title === void 0 ? "" : `,${scriptJSON(late.title)}`;
2011
- call += `;${headSwap ? "" : HEAD}$bH(${id}${title})`;
2012
- headSwap = true;
2013
- }
2014
- pending().push(`<template b-l="${boundary.id}">${result.html}</template>${head}${result.ctx.portals.join("")}${scriptTag}${call}<\/script>${script}`);
2502
+ turn((after) => {
2503
+ serialize(result.ctx, (script) => {
2504
+ const id = scriptJSON(boundary.id);
2505
+ let call = `${swap ? "" : swapScript}$bS(${id})`;
2506
+ swap = true;
2507
+ if (after) call += `;${showFallback()}${after}`;
2508
+ const late = result.ctx.lateHead();
2509
+ let head = "";
2510
+ if (late.html || late.title !== void 0) {
2511
+ head = `<template b-h="${boundary.id}">${late.html}</template>`;
2512
+ const title = late.title === void 0 ? "" : `,${scriptJSON(late.title)}`;
2513
+ call += `;${headSwap ? "" : HEAD}$bH(${id}${title})`;
2514
+ headSwap = true;
2515
+ }
2516
+ pending().push(`<template b-l="${boundary.id}">${result.html}</template>${head}${result.ctx.portals.join("")}${scriptTag}${call}<\/script>${script}`);
2517
+ });
2518
+ finish();
2015
2519
  });
2016
- finish();
2017
2520
  }, (error) => {
2018
2521
  console.error(error);
2019
- finish();
2522
+ turn(skip);
2020
2523
  });
2021
2524
  });
2022
2525
  if (options.defer) return {
@@ -2327,12 +2830,12 @@ async function handleForm(invoke, event) {
2327
2830
  async function readArgs(request) {
2328
2831
  if (!request.headers.has("x-brumate-args")) return fromJSON(await request.json(), {
2329
2832
  plugins,
2330
- disabledFeatures
2833
+ ...serialOptions()
2331
2834
  });
2332
2835
  const form = await request.formData();
2333
2836
  return fromJSON(JSON.parse(String(form.get("args"))), {
2334
2837
  plugins: callPlugins(void 0, form),
2335
- disabledFeatures
2838
+ ...serialOptions()
2336
2839
  });
2337
2840
  }
2338
2841
  /**
@@ -2445,6 +2948,59 @@ function callFailure(error, headers) {
2445
2948
  headers
2446
2949
  });
2447
2950
  }
2951
+ /** The key of a page in the store: its URL, and the base of a client navigation, by build. */
2952
+ function pageKey(url, request, build) {
2953
+ const base = request.headers.get("x-brumate-base") ?? "";
2954
+ return `brumate:page:${build ?? ""}:${base}:${url.pathname}${url.search}`;
2955
+ }
2956
+ /** The page that the store keeps for a key, when it is still fresh. */
2957
+ async function keptPage(key) {
2958
+ const text = await cacheStore().get(key);
2959
+ if (!text) return;
2960
+ const page = JSON.parse(text);
2961
+ const tags = Object.keys(page.tags);
2962
+ const versions = await tagVersions(tags);
2963
+ if (page.expires <= Date.now() || tags.some((tag) => versions[tag] !== page.tags[tag])) return;
2964
+ const headers = new Headers(page.headers);
2965
+ const maxAge = Number(/max-age=(\d+)/.exec(headers.get("cache-control") ?? "")?.[1] ?? 0);
2966
+ headers.set("age", String(Math.max(0, Math.floor(maxAge - (page.expires - Date.now()) / 1e3))));
2967
+ headers.set("x-brumate-cache", "hit");
2968
+ return new Response(page.body, {
2969
+ status: page.status,
2970
+ headers
2971
+ });
2972
+ }
2973
+ /** Keeps a public page in the store until its `max-age` ends. */
2974
+ async function keepPage(key, response, event) {
2975
+ const maxAge = Number(/max-age=(\d+)/.exec(response.headers.get("cache-control") ?? "")?.[1] ?? 0);
2976
+ if (maxAge <= 0) return;
2977
+ const versions = await tagVersions([...event.cacheTags].filter(([, version]) => version === void 0).map(([tag]) => tag));
2978
+ const page = {
2979
+ status: response.status,
2980
+ headers: [...response.headers].filter(([name]) => name !== "set-cookie"),
2981
+ body: await response.clone().text(),
2982
+ expires: Date.now() + maxAge * 1e3,
2983
+ tags: Object.fromEntries([...event.cacheTags].map(([tag, version]) => [tag, version ?? versions[tag]]))
2984
+ };
2985
+ await cacheStore().set(key, JSON.stringify(page), maxAge);
2986
+ }
2987
+ /** The `cache` of the page of a view: the nearest one along its `children`. */
2988
+ function pageCache(view) {
2989
+ const inner = view.slots.children;
2990
+ return (inner && pageCache(inner)) ?? view.cache;
2991
+ }
2992
+ /**
2993
+ * The `cache-control` of a page with `cache`. It is public only when the
2994
+ * request did not read or set anything of the user, and the page is a
2995
+ * success without cookies.
2996
+ */
2997
+ function cacheControl(cache, event, response) {
2998
+ if (event?.personal || response.status !== 200 || response.headers.getSetCookie().length > 0) return "private, no-cache";
2999
+ const parts = ["public", `max-age=${Math.max(0, Math.floor(cache.maxAge))}`];
3000
+ if (cache.staleWhileRevalidate !== void 0) parts.push(`stale-while-revalidate=${Math.max(0, Math.floor(cache.staleWhileRevalidate))}`);
3001
+ return parts.join(", ");
3002
+ }
3003
+ const warnedPrivate = /* @__PURE__ */ new Set();
2448
3004
  /** Imports every module of a matched route before it renders. */
2449
3005
  async function resolveView(view) {
2450
3006
  const [module, loading, ...slots] = await Promise.all([
@@ -2457,6 +3013,7 @@ async function resolveView(view) {
2457
3013
  key: view.key,
2458
3014
  component: module.default,
2459
3015
  loading: loading?.default,
3016
+ cache: module.cache,
2460
3017
  slots: Object.fromEntries(names.map((name, index) => [name, slots[index]]))
2461
3018
  };
2462
3019
  }
@@ -2525,10 +3082,18 @@ async function renderPage(view, props, request, options, extra) {
2525
3082
  const base = Number(request.headers.get("x-brumate-base"));
2526
3083
  const defer = deferTarget(request);
2527
3084
  if (defer) return renderDeferred(view, props, request, options, defer, base);
3085
+ const event = options.event;
3086
+ if (options.dev && event) {
3087
+ event.trace = [];
3088
+ event.traceStart = performance.now();
3089
+ }
3090
+ const path = new URL(request.url).pathname;
3091
+ const endRender = event?.traced("render", path) ?? (() => {});
2528
3092
  const hints = request.headers.has("x-brumate-base") ? [] : options.hints ?? [];
2529
- const links = hints.map((url) => `<${url}>; rel=modulepreload`);
3093
+ const nonce = options.nonce === void 0 ? "" : ` nonce="${escapeAttribute(options.nonce)}"`;
3094
+ const links = nonce ? [] : hints.map((url) => `<${url}>; rel=modulepreload`);
2530
3095
  if (links.length > 0) options.earlyHints?.(links);
2531
- const preload = hints.map((url) => `<link rel="modulepreload" href="${escapeAttribute(url)}">`).join("");
3096
+ const preload = hints.map((url) => `<link rel="modulepreload"${nonce} href="${escapeAttribute(url)}">`).join("");
2532
3097
  const parts = await render(viewComponent(view, props), {}, {
2533
3098
  ...options,
2534
3099
  request,
@@ -2537,18 +3102,48 @@ async function renderPage(view, props, request, options, extra) {
2537
3102
  params: props.params,
2538
3103
  base: Number.isSafeInteger(base) && base > 0 ? base : void 0
2539
3104
  });
3105
+ endRender();
3106
+ const endStream = event?.traced("stream", "the rest of the page") ?? (() => {});
2540
3107
  const headers = new Headers(parts.headers);
2541
3108
  headers.set("content-type", "text/html; charset=utf-8");
2542
3109
  headers.append("vary", "x-brumate-defer");
2543
3110
  headers.append("vary", "x-brumate-base");
2544
3111
  for (const link of links) headers.append("link", link);
2545
- return respond(streamParts(parts, {
3112
+ let html = streamParts(parts, {
2546
3113
  ...options,
2547
3114
  head: preload + (options.head ?? "")
2548
- }).pipeThrough(new TextEncoderStream()), {
3115
+ });
3116
+ if (event?.trace) {
3117
+ const trace = event.trace;
3118
+ html = html.pipeThrough(new TransformStream({ flush(controller) {
3119
+ endStream();
3120
+ const json = JSON.stringify({
3121
+ route: path,
3122
+ entries: trace
3123
+ }).replace(/</g, "\\u003c");
3124
+ controller.enqueue(`<script type="application/json" b-trace>${json}<\/script>`);
3125
+ } }));
3126
+ }
3127
+ const body = html.pipeThrough(new TextEncoderStream());
3128
+ const cache = request.method === "GET" || request.method === "HEAD" ? pageCache(view) : void 0;
3129
+ if (!cache) return respond(body, {
2549
3130
  status: extra.status ?? parts.status,
2550
3131
  headers
2551
3132
  });
3133
+ const response = respond(await new Response(body).arrayBuffer(), {
3134
+ status: extra.status ?? parts.status,
3135
+ headers
3136
+ });
3137
+ const control = cacheControl(cache, options.event, response);
3138
+ if (options.dev) {
3139
+ response.headers.set("cache-control", "no-cache");
3140
+ response.headers.set("x-brumate-cache", control);
3141
+ if (control.startsWith("private") && !warnedPrivate.has(view.key)) {
3142
+ warnedPrivate.add(view.key);
3143
+ console.warn(`The page ${new URL(request.url).pathname} exports cache, but it read cookies or the authorization header, or set a cookie, so it is not cached for everyone. Move what reads the user into #defer.`);
3144
+ }
3145
+ } else response.headers.set("cache-control", control);
3146
+ return response;
2552
3147
  }
2553
3148
  /**
2554
3149
  * The `#defer` block that a request asks for, from `x-brumate-defer:
@@ -2634,6 +3229,7 @@ async function runMiddleware(loaders, request, event, answer) {
2634
3229
  * middleware. A `redirect` while the page renders answers with a redirect.
2635
3230
  */
2636
3231
  async function handleRoute(tree, request, options = {}) {
3232
+ if (options.shell !== void 0 && (request.method === "GET" || request.method === "HEAD") && !deferTarget(request) && !request.headers.has("x-brumate-base")) return fillHoles(tree, request, options.shell, options);
2637
3233
  const url = new URL(request.url);
2638
3234
  const match = matchRoute(tree, url.pathname);
2639
3235
  const event = options.event ?? new RequestEvent(request, {
@@ -2661,6 +3257,58 @@ async function requestKind(request, match) {
2661
3257
  }
2662
3258
  return "page";
2663
3259
  }
3260
+ /**
3261
+ * The `#defer` blocks of a prerendered page that the server renders in the
3262
+ * response: those with the `load` or `idle` trigger. A `visible` block is
3263
+ * far down the page, so it waits for the browser to ask for it.
3264
+ */
3265
+ const HOLE = /<template b-b="([^"]+)" b-defer="(?:load|idle):([^:"]+):([^"]*)"/g;
3266
+ /**
3267
+ * Answers with a prerendered page, then with the body of each of its
3268
+ * `#defer` blocks as it is ready, as a `#loading` body streams. Each body
3269
+ * renders in a request of its own, as when the browser asks for it, so
3270
+ * middleware runs for it. The loader leaves the marked blocks alone, and a
3271
+ * block whose body fails keeps its fallback.
3272
+ */
3273
+ function fillHoles(tree, request, shell, options) {
3274
+ const holes = [...shell.matchAll(HOLE)];
3275
+ const headers = new Headers({ "content-type": "text/html; charset=utf-8" });
3276
+ if (holes.length === 0) return new Response(request.method === "HEAD" ? null : shell, { headers });
3277
+ headers.set("cache-control", "private, no-cache");
3278
+ headers.append("vary", "x-brumate-defer");
3279
+ headers.append("vary", "x-brumate-base");
3280
+ const marked = shell.replace(HOLE, (template) => `${template} b-hole`);
3281
+ const bodies = holes.map(async ([, at, boundary, base]) => {
3282
+ const asked = new Headers(request.headers);
3283
+ asked.set("x-brumate-defer", `${boundary} ${at}`);
3284
+ asked.set("x-brumate-base", base);
3285
+ try {
3286
+ const answer = await handleRoute(tree, new Request(request.url, { headers: asked }), {
3287
+ ...options,
3288
+ shell: void 0,
3289
+ event: void 0
3290
+ });
3291
+ return answer?.ok && answer.headers.get("x-brumate-defer") === boundary ? await answer.text() : "";
3292
+ } catch (error) {
3293
+ console.error(error);
3294
+ return "";
3295
+ }
3296
+ });
3297
+ const body = new ReadableStream({ async start(controller) {
3298
+ controller.enqueue(marked);
3299
+ const pending = new Map(bodies.map((body, index) => [index, body.then((html) => ({
3300
+ html,
3301
+ index
3302
+ }))]));
3303
+ while (pending.size > 0) {
3304
+ const { html, index } = await Promise.race(pending.values());
3305
+ pending.delete(index);
3306
+ if (html) controller.enqueue(html);
3307
+ }
3308
+ controller.close();
3309
+ } }).pipeThrough(new TextEncoderStream());
3310
+ return new Response(request.method === "HEAD" ? null : body, { headers });
3311
+ }
2664
3312
  /** A response with more headers, such as cookies that middleware set. */
2665
3313
  function withHeaders(answer, headers) {
2666
3314
  const sent = new Set(answer.headers.getSetCookie());
@@ -2668,6 +3316,7 @@ function withHeaders(answer, headers) {
2668
3316
  if (cookies.length === 0) return answer;
2669
3317
  const result = respond(answer.body, answer);
2670
3318
  for (const cookie of cookies) result.headers.append("set-cookie", cookie);
3319
+ if (/^\s*public\b/.test(result.headers.get("cache-control") ?? "")) result.headers.set("cache-control", "private, no-cache");
2671
3320
  return result;
2672
3321
  }
2673
3322
  async function routeAnswer(tree, match, url, options) {
@@ -2715,8 +3364,15 @@ async function renderRoute(match, request, url, options) {
2715
3364
  if ("answer" in outcome) return outcome.answer;
2716
3365
  actions = outcome.actions;
2717
3366
  }
3367
+ const key = !event.call && !options.dev && options.pageCache !== false && event.kind === "page" && (request.method === "GET" || request.method === "HEAD") ? pageKey(url, request, options.build) : void 0;
3368
+ if (key && !event.personal) {
3369
+ const kept = await keptPage(key);
3370
+ if (kept) return kept;
3371
+ }
2718
3372
  try {
2719
- return await renderPage(await resolveView(match.view), { params: match.params }, request, options, { actions });
3373
+ const response = await renderPage(await resolveView(match.view), { params: match.params }, request, options, { actions });
3374
+ if (key && /^\s*public\b/.test(response.headers.get("cache-control") ?? "")) await keepPage(key, response, event);
3375
+ return response;
2720
3376
  } catch (error) {
2721
3377
  if (isRedirect(error)) return new Response(null, {
2722
3378
  status: error.status,
@@ -2745,18 +3401,17 @@ function spread(attributes, on) {
2745
3401
  for (const [name, value] of Object.entries(attributes)) {
2746
3402
  const reference = on && /^on[A-Z]/.test(name) && typeof value === "function" ? functionReferences.get(value) : void 0;
2747
3403
  if (reference) {
2748
- const modifiers = value[MODIFIERS] ?? [];
2749
- on.push(`${[name.slice(2).toLowerCase(), ...modifiers].join(":")}=${reference.ref}@${reference.scope}`);
3404
+ const modifiers = value[MODIFIERS];
3405
+ on.push(handlerEntry(name, reference.ref, reference.scope, modifiers, reference.args));
3406
+ }
3407
+ if (on && (name === "value" || name === "checked") && isBinding(value)) {
3408
+ const setter = typeof value.set === "function" ? functionReferences.get(value.set) : void 0;
3409
+ on.push(bindEntry(name, value.ref, setter));
2750
3410
  }
2751
3411
  }
2752
3412
  return spread$1(attributes);
2753
3413
  }
2754
- /** The `b-on` attribute of an element with spreads: its own handlers, then those of its spreads. */
2755
- function onAttribute(on, own) {
2756
- const value = [own, ...on].filter(Boolean).join(" ");
2757
- return value ? ` b-on="${escapeAttribute(value)}"` : "";
2758
- }
2759
3414
  //#endregion
2760
- export { clientAddress as A, ServerError as B, stateScript as C, wait as D, streamState as E, parse as F, redirect as G, defineMiddleware as H, parseForm as I, withEvent as K, safeParse as L, rateLimit as M, ValidationError as N, waitAll as O, fieldErrors as P, matchRoute as R, spread as S, streamParts as T, getEvent as U, dedupe as V, isRedirect as W, read as _, children as a, renderToStream as b, handleRequest as c, insert as d, isCrossSite as f, packState as g, onAttribute as h, actionResult as i, configureRateLimit as j, RateLimitError as k, handleRoute as l, memo as m, NotReady as n, component as o, lazy as p, action as r, dynamic as s, Context as t, inlineBodies as u, ready as v, stateValue as w, settled as x, render as y, RequestEvent as z };
3415
+ export { withEvent as $, RateLimitError as A, matchRoute as B, stateScript as C, wait as D, streamState as E, ValidationError as F, storageStore as G, memoryStore as H, fieldErrors as I, dedupe as J, RequestEvent as K, parse as L, configureRateLimit as M, rateLimit as N, waitAll as O, parseSubmission as P, redirect as Q, parseForm as R, spread as S, streamParts as T, revalidate as U, cached as V, setCacheStore as W, getEvent as X, defineMiddleware as Y, isRedirect as Z, read as _, binding as a, renderToStream as b, dynamic as c, inlineBodies as d, insert as f, packState as g, memo as h, actionResult as i, clientAddress as j, idempotent as k, handleRequest as l, lazy as m, NotReady as n, children as o, isCrossSite as p, ServerError as q, action as r, component as s, Context as t, handleRoute as u, ready as v, stateValue as w, settled as x, render as y, safeParse as z };
2761
3416
 
2762
- //# sourceMappingURL=server-BqfM95r1.js.map
3417
+ //# sourceMappingURL=server-CxVDYE_V.js.map