brumate 0.2.0 → 0.4.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.
- package/README.md +2 -2
- package/check.d.ts +49 -0
- package/dist/{boot-D-IdPy7B.d.ts → boot-DLlRmD9z.d.ts} +11 -10
- package/dist/cli.js +275 -15
- package/dist/cli.js.map +1 -1
- package/dist/client-BvDsC6Qr.js +3463 -0
- package/dist/client-BvDsC6Qr.js.map +1 -0
- package/dist/client-DBwL2wKQ.d.ts +669 -0
- package/dist/{client-routes-JTbGtukf.js → client-routes-BtGpYCef.js} +60 -30
- package/dist/client-routes-BtGpYCef.js.map +1 -0
- package/dist/{cookies-Av5WFmcf.js → cookies-Cnbf4w-S.js} +15 -7
- package/dist/cookies-Cnbf4w-S.js.map +1 -0
- package/dist/{defer-D0bo1Gqx.js → defer-CKWZLv2K.js} +8 -4
- package/dist/defer-CKWZLv2K.js.map +1 -0
- package/dist/devtools-4uTPwR_v.js +597 -0
- package/dist/devtools-4uTPwR_v.js.map +1 -0
- package/dist/devtools-panel-Be9pxYgv.js +1994 -0
- package/dist/devtools-panel-Be9pxYgv.js.map +1 -0
- package/dist/events-LgLdp1R7.js +114 -0
- package/dist/events-LgLdp1R7.js.map +1 -0
- package/dist/features-CHY5Ekku.js +30 -0
- package/dist/features-CHY5Ekku.js.map +1 -0
- package/dist/files-WW4RlajL.js +506 -0
- package/dist/files-WW4RlajL.js.map +1 -0
- package/dist/forms-j1xPAR14.d.ts +281 -0
- package/dist/forms-nXK7-Lv_.js +440 -0
- package/dist/forms-nXK7-Lv_.js.map +1 -0
- package/dist/highlight.d.ts +17 -0
- package/dist/highlight.js +278 -0
- package/dist/highlight.js.map +1 -0
- package/dist/html-BtKRyi7g.js +305 -0
- package/dist/html-BtKRyi7g.js.map +1 -0
- package/dist/html-Bw9Qwu6F.d.ts +107 -0
- package/dist/index.d.ts +142 -11
- package/dist/index.js +641 -106
- package/dist/index.js.map +1 -1
- package/dist/{inspect-BJtACnQp.js → inspect-Y6y4uNZp.js} +4333 -681
- package/dist/inspect-Y6y4uNZp.js.map +1 -0
- package/dist/{loader-B18i3_-T.js → loader-BjKGJzLN.js} +21 -14
- package/dist/loader-BjKGJzLN.js.map +1 -0
- package/dist/logo-DQ_OYhBi.js +10 -0
- package/dist/logo-DQ_OYhBi.js.map +1 -0
- package/dist/{navigate-BwuZveDF.js → navigate-CfOr-TRF.js} +130 -24
- package/dist/navigate-CfOr-TRF.js.map +1 -0
- package/dist/nesting-DA5vJw9X.js +265 -0
- package/dist/nesting-DA5vJw9X.js.map +1 -0
- package/dist/produce-B7X9ori9.js +402 -0
- package/dist/produce-B7X9ori9.js.map +1 -0
- package/dist/produce-DIgHBVwL.d.ts +148 -0
- package/dist/{rpc-B-Zkn6Ch.js → rpc-Q-XkLwFh.js} +28 -13
- package/dist/rpc-Q-XkLwFh.js.map +1 -0
- package/dist/runtime/batch.js +9 -7
- package/dist/runtime/batch.js.map +1 -1
- package/dist/runtime/client.d.ts +4 -4
- package/dist/runtime/client.js +4 -4
- package/dist/runtime/devtools.d.ts +172 -5
- package/dist/runtime/devtools.js +3 -1
- package/dist/runtime/env.js +14 -2
- package/dist/runtime/env.js.map +1 -1
- package/dist/runtime/events.d.ts +38 -1
- package/dist/runtime/events.js +1 -1
- package/dist/runtime/forms.d.ts +2 -0
- package/dist/runtime/forms.js +1 -0
- package/dist/runtime/gather.d.ts +25 -0
- package/dist/runtime/gather.js +33 -0
- package/dist/runtime/gather.js.map +1 -0
- package/dist/runtime/hot.d.ts +1 -1
- package/dist/runtime/hot.js +5 -2
- package/dist/runtime/hot.js.map +1 -1
- package/dist/runtime/html.d.ts +2 -2
- package/dist/runtime/html.js +1 -1
- package/dist/runtime/loader.d.ts +2 -2
- package/dist/runtime/loader.js +2 -2
- package/dist/runtime/routes.js +4 -1
- package/dist/runtime/routes.js.map +1 -1
- package/dist/runtime/server.d.ts +5 -4
- package/dist/runtime/server.js +5 -5
- package/dist/runtime/signals.d.ts +75 -2
- package/dist/runtime/signals.js +44 -2
- package/dist/runtime/signals.js.map +1 -1
- package/dist/runtime/static-loader.d.ts +2 -2
- package/dist/runtime/static-loader.js +1 -1
- package/dist/runtime/testing.d.ts +18 -3
- package/dist/runtime/testing.js +150 -33
- package/dist/runtime/testing.js.map +1 -1
- package/dist/runtime/values.d.ts +2 -0
- package/dist/runtime/values.js +24 -0
- package/dist/runtime/values.js.map +1 -0
- package/dist/{server-BA9SJ2Vm.d.ts → server-BvPIg9pT.d.ts} +363 -32
- package/dist/{server-BqfM95r1.js → server-DjyOVJtJ.js} +1309 -220
- package/dist/server-DjyOVJtJ.js.map +1 -0
- package/dist/{static-loader-BzE9SRaj.d.ts → static-loader-BGgdp_Y5.d.ts} +2 -2
- package/dist/static-loader-BZR17hSw.js +312 -0
- package/dist/static-loader-BZR17hSw.js.map +1 -0
- package/dist/{stream-JaMHMdBD.js → stream-BP5AVmg5.js} +182 -17
- package/dist/stream-BP5AVmg5.js.map +1 -0
- package/dist/values-B8C7CLvG.d.ts +63 -0
- package/dist/vite.d.ts +20 -20
- package/dist/vite.js +2031 -539
- package/dist/vite.js.map +1 -1
- package/elements.d.ts +951 -0
- package/forms/forms.brm.ts +141 -0
- package/package.json +41 -3
- package/skills/brumate/SKILL.md +58 -0
- package/skills/brumate/references/errors.md +2078 -0
- package/skills/brumate/references/events.md +117 -0
- package/skills/brumate/references/signals.md +61 -0
- package/skills/brumate/references/state.md +235 -0
- package/skills/brumate/references/syntax.md +250 -0
- package/types.d.ts +4 -4
- package/dist/client-C0UCNL3J.js +0 -1643
- package/dist/client-C0UCNL3J.js.map +0 -1
- package/dist/client-MD0ZmcFR.d.ts +0 -354
- package/dist/client-routes-JTbGtukf.js.map +0 -1
- package/dist/cookies-Av5WFmcf.js.map +0 -1
- package/dist/defer-D0bo1Gqx.js.map +0 -1
- package/dist/devtools-C50VH8gZ.js +0 -113
- package/dist/devtools-C50VH8gZ.js.map +0 -1
- package/dist/devtools-panel-AYjfwPhj.js +0 -435
- package/dist/devtools-panel-AYjfwPhj.js.map +0 -1
- package/dist/events-BKWRqtMg.js +0 -52
- package/dist/events-BKWRqtMg.js.map +0 -1
- package/dist/files-Bnn1JqHx.js +0 -192
- package/dist/files-Bnn1JqHx.js.map +0 -1
- package/dist/html-bHZbkK-h.js +0 -170
- package/dist/html-bHZbkK-h.js.map +0 -1
- package/dist/html-y1q7-t7D.d.ts +0 -60
- package/dist/inspect-BJtACnQp.js.map +0 -1
- package/dist/loader-B18i3_-T.js.map +0 -1
- package/dist/navigate-BwuZveDF.js.map +0 -1
- package/dist/produce-CWfJ4byV.js +0 -167
- package/dist/produce-CWfJ4byV.js.map +0 -1
- package/dist/produce-D4K7qpaL.d.ts +0 -72
- package/dist/rpc-B-Zkn6Ch.js.map +0 -1
- package/dist/server-BqfM95r1.js.map +0 -1
- package/dist/static-loader-DOygOFj5.js +0 -216
- package/dist/static-loader-DOygOFj5.js.map +0 -1
- package/dist/stream-JaMHMdBD.js.map +0 -1
|
@@ -1,17 +1,57 @@
|
|
|
1
|
-
import { n as
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
1
|
+
import { n as closesParagraph, r as firstTag } from "./nesting-DA5vJw9X.js";
|
|
2
|
+
import { n as MODIFIERS } from "./events-LgLdp1R7.js";
|
|
3
|
+
import { C as styleElement, S as spread$1, _ as onAttribute, d as escapeAttribute, f as handlerEntry, h as isRaw, n as VOID_ELEMENTS, p as insertValue, r as actionAttributes, s as bindEntry, u as escape, x as rawHTML, y as ownValue } from "./html-BtKRyi7g.js";
|
|
4
|
+
import { n as deleteCookie, o as setCookie, r as getCookies } from "./cookies-Cnbf4w-S.js";
|
|
5
|
+
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-BP5AVmg5.js";
|
|
6
|
+
import { a as ElementReference, b as parseId, c as PARTS, d as SlotReference, f as addEntryHandlers, g as isSlotReference, i as ChildrenReference, l as PropPromise, m as isBinding, n as Binding, o as FunctionReference, p as isAsyncIterable, r as CHILDREN_REF, s as MemoError } from "./produce-B7X9ori9.js";
|
|
5
7
|
import { n as serverSecrets } from "./secrets-BxagsJxJ.js";
|
|
6
|
-
import { n as deleteCookie, o as setCookie, r as getCookies } from "./cookies-Av5WFmcf.js";
|
|
7
8
|
import "./context-CTiSzQRc.js";
|
|
9
|
+
import { a as applyIntent, d as formatPath, f as getAt, m as groupIssues, r as INTENT, u as formValues, v as parseIntent, y as parsePath } from "./forms-nXK7-Lv_.js";
|
|
8
10
|
import { crossSerialize, crossSerializeStream, fromJSON, toJSON } from "seroval";
|
|
9
11
|
//#region src/runtime/request.ts
|
|
12
|
+
function noTrace() {}
|
|
13
|
+
/** Ends an entry of the trace when a value settles, if it is a promise, or at once. */
|
|
14
|
+
function traceValue(value, end) {
|
|
15
|
+
const thenable = value;
|
|
16
|
+
if (thenable && typeof thenable.then === "function") thenable.then(() => end(), () => end(true));
|
|
17
|
+
else end();
|
|
18
|
+
return value;
|
|
19
|
+
}
|
|
20
|
+
/** The headers that tell who the user is. */
|
|
21
|
+
const PERSONAL = /* @__PURE__ */ new Set(["cookie", "authorization"]);
|
|
10
22
|
/**
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
* the request and change the response. Get it with `getEvent()`.
|
|
23
|
+
* Calls `read` when code reads the headers that tell who the user is, by
|
|
24
|
+
* name or by going through all the headers.
|
|
14
25
|
*/
|
|
26
|
+
function watchPersonal(headers, read) {
|
|
27
|
+
const get = headers.get.bind(headers);
|
|
28
|
+
const has = headers.has.bind(headers);
|
|
29
|
+
Object.assign(headers, {
|
|
30
|
+
get: (name) => {
|
|
31
|
+
if (PERSONAL.has(name.toLowerCase())) read();
|
|
32
|
+
return get(name);
|
|
33
|
+
},
|
|
34
|
+
has: (name) => {
|
|
35
|
+
if (PERSONAL.has(name.toLowerCase())) read();
|
|
36
|
+
return has(name);
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
for (const method of [
|
|
40
|
+
"entries",
|
|
41
|
+
"forEach",
|
|
42
|
+
"values",
|
|
43
|
+
Symbol.iterator
|
|
44
|
+
]) {
|
|
45
|
+
const all = headers[method].bind(headers);
|
|
46
|
+
Object.defineProperty(headers, method, {
|
|
47
|
+
value: (...args) => {
|
|
48
|
+
read();
|
|
49
|
+
return all(...args);
|
|
50
|
+
},
|
|
51
|
+
configurable: true
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
}
|
|
15
55
|
var RequestEvent = class {
|
|
16
56
|
request;
|
|
17
57
|
/** What the request is for. */
|
|
@@ -38,6 +78,39 @@ var RequestEvent = class {
|
|
|
38
78
|
refreshed;
|
|
39
79
|
/** Cookies that this request set, or deleted with undefined, so later reads see them. */
|
|
40
80
|
cookies;
|
|
81
|
+
/**
|
|
82
|
+
* True once the request read its cookies or its `authorization` header, or
|
|
83
|
+
* set a cookie, such as for a session. The answer then depends on the user,
|
|
84
|
+
* so a page with `cache` is not cached for everyone.
|
|
85
|
+
*/
|
|
86
|
+
personal = false;
|
|
87
|
+
/**
|
|
88
|
+
* In development, what the render of the page did and when, in
|
|
89
|
+
* milliseconds from its start, for the Server tab of the devtools.
|
|
90
|
+
*/
|
|
91
|
+
trace;
|
|
92
|
+
/** When the trace started, by `performance.now()`. */
|
|
93
|
+
traceStart = 0;
|
|
94
|
+
/** Starts an entry of the trace, when there is one, and returns what ends it. */
|
|
95
|
+
traced(kind, label) {
|
|
96
|
+
const trace = this.trace;
|
|
97
|
+
if (!trace) return noTrace;
|
|
98
|
+
const entry = {
|
|
99
|
+
kind,
|
|
100
|
+
label,
|
|
101
|
+
start: performance.now() - this.traceStart
|
|
102
|
+
};
|
|
103
|
+
trace.push(entry);
|
|
104
|
+
return (failed) => {
|
|
105
|
+
entry.end = performance.now() - this.traceStart;
|
|
106
|
+
if (failed) entry.failed = true;
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* The tags of the `cached` functions that the request called, with the
|
|
111
|
+
* version that each had then, so `revalidate` drops the page that it renders.
|
|
112
|
+
*/
|
|
113
|
+
cacheTags = /* @__PURE__ */ new Map();
|
|
41
114
|
controller = new AbortController();
|
|
42
115
|
/**
|
|
43
116
|
* Aborts when the request no longer needs an answer: the request's own
|
|
@@ -53,6 +126,9 @@ var RequestEvent = class {
|
|
|
53
126
|
this.keepGoing = options.waitUntil;
|
|
54
127
|
this.address = options.address;
|
|
55
128
|
this.prerender = options.prerender ?? false;
|
|
129
|
+
watchPersonal(request.headers, () => {
|
|
130
|
+
this.personal = true;
|
|
131
|
+
});
|
|
56
132
|
const outer = request.signal;
|
|
57
133
|
if (outer?.aborted) this.controller.abort(outer.reason);
|
|
58
134
|
else outer?.addEventListener("abort", () => this.abort(outer.reason), { once: true });
|
|
@@ -138,6 +214,10 @@ function withEvent(event, callback, calls) {
|
|
|
138
214
|
currentCalls = outerCalls;
|
|
139
215
|
}
|
|
140
216
|
}
|
|
217
|
+
/** The event of the request being handled, or undefined, without throwing as `getEvent` does. */
|
|
218
|
+
function currentEvent() {
|
|
219
|
+
return current;
|
|
220
|
+
}
|
|
141
221
|
/**
|
|
142
222
|
* Returns the event of the request that the server handles: in a server
|
|
143
223
|
* function, middleware or an endpoint, or while a component renders.
|
|
@@ -186,7 +266,17 @@ function runEntry(middleware, event, answer) {
|
|
|
186
266
|
* requests of their own, always run, so a function that changes something
|
|
187
267
|
* runs each time.
|
|
188
268
|
*/
|
|
269
|
+
/** Marks the functions that `idempotent` made. A symbol of the registry. */
|
|
270
|
+
const IDEMPOTENT = Symbol.for("brumate.idempotent");
|
|
271
|
+
/** The IDs of the server functions that `idempotent` made, which `dedupe` records. */
|
|
272
|
+
const idempotentIds = /* @__PURE__ */ new Set();
|
|
273
|
+
/** The ID of each function that `idempotent` made, once the server registered it. */
|
|
274
|
+
const idempotentId = /* @__PURE__ */ new WeakMap();
|
|
189
275
|
function dedupe(fn, id) {
|
|
276
|
+
if (IDEMPOTENT in fn) {
|
|
277
|
+
idempotentIds.add(id);
|
|
278
|
+
idempotentId.set(fn, id);
|
|
279
|
+
}
|
|
190
280
|
const wrapper = ((...args) => {
|
|
191
281
|
const cache = currentCalls;
|
|
192
282
|
if (!cache) return fn(...args);
|
|
@@ -194,12 +284,12 @@ function dedupe(fn, id) {
|
|
|
194
284
|
try {
|
|
195
285
|
key = `${id} ${JSON.stringify(toJSON(args, {
|
|
196
286
|
plugins: syncPlugins,
|
|
197
|
-
|
|
287
|
+
...serialOptions()
|
|
198
288
|
}))}`;
|
|
199
289
|
} catch {
|
|
200
290
|
return fn(...args);
|
|
201
291
|
}
|
|
202
|
-
if (!cache.has(key)) cache.set(key, fn(...args));
|
|
292
|
+
if (!cache.has(key)) cache.set(key, traceValue(fn(...args), current?.traced("call", id) ?? noTrace));
|
|
203
293
|
return cache.get(key);
|
|
204
294
|
});
|
|
205
295
|
Object.defineProperty(wrapper, ORIGINAL, { value: fn });
|
|
@@ -254,6 +344,152 @@ function isRedirect(error) {
|
|
|
254
344
|
return error instanceof Redirect;
|
|
255
345
|
}
|
|
256
346
|
//#endregion
|
|
347
|
+
//#region src/runtime/cache.ts
|
|
348
|
+
/** Tags live longer than any result, so a result never outlives the version of its tag. */
|
|
349
|
+
const TAG_AGE = 31536e3;
|
|
350
|
+
/**
|
|
351
|
+
* A store in the memory of the server, the default. Each process has its
|
|
352
|
+
* own, and it keeps at most `size` values, dropping the oldest first.
|
|
353
|
+
*/
|
|
354
|
+
function memoryStore(size = 1e3) {
|
|
355
|
+
const values = /* @__PURE__ */ new Map();
|
|
356
|
+
return {
|
|
357
|
+
memory: true,
|
|
358
|
+
get(key) {
|
|
359
|
+
const item = values.get(key);
|
|
360
|
+
if (!item) return;
|
|
361
|
+
if (item.expires <= Date.now()) {
|
|
362
|
+
values.delete(key);
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
return item.value;
|
|
366
|
+
},
|
|
367
|
+
set(key, value, maxAge) {
|
|
368
|
+
values.delete(key);
|
|
369
|
+
values.set(key, {
|
|
370
|
+
value,
|
|
371
|
+
expires: Date.now() + maxAge * 1e3
|
|
372
|
+
});
|
|
373
|
+
for (const oldest of values.keys()) {
|
|
374
|
+
if (values.size <= size) break;
|
|
375
|
+
values.delete(oldest);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
let store = memoryStore();
|
|
381
|
+
/**
|
|
382
|
+
* Sets the store of `cached`, such as one that keeps results in Redis for
|
|
383
|
+
* every process of the app. Set it before the first request.
|
|
384
|
+
*/
|
|
385
|
+
function setCacheStore(next) {
|
|
386
|
+
store = next;
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* A store of `cached` from an unstorage storage, such as Nitro's
|
|
390
|
+
* `useStorage('cache')`. It reads and writes the values as they are, since
|
|
391
|
+
* `getItem` would parse text that looks like JSON.
|
|
392
|
+
*/
|
|
393
|
+
function storageStore(storage) {
|
|
394
|
+
return {
|
|
395
|
+
get: async (key) => {
|
|
396
|
+
const value = await (storage.getItemRaw ?? storage.getItem).call(storage, key);
|
|
397
|
+
if (value instanceof Uint8Array) return new TextDecoder().decode(value);
|
|
398
|
+
return typeof value === "string" ? value : void 0;
|
|
399
|
+
},
|
|
400
|
+
set: (key, value, maxAge) => (storage.setItemRaw ?? storage.setItem).call(storage, key, value, { ttl: maxAge })
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
/** Calls that are running, by key, so calls with the same arguments share one run. */
|
|
404
|
+
const running$1 = /* @__PURE__ */ new Map();
|
|
405
|
+
let unnamed = 0;
|
|
406
|
+
/** The text of a value, as the store keeps it. */
|
|
407
|
+
function write(value) {
|
|
408
|
+
return toJSON(value, {
|
|
409
|
+
plugins: syncPlugins,
|
|
410
|
+
...serialOptions()
|
|
411
|
+
});
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Makes a function that keeps its results for `maxAge` seconds, by its
|
|
415
|
+
* arguments, and returns a kept result in place of running again. Use it for
|
|
416
|
+
* data that every user sees the same, such as a list of products.
|
|
417
|
+
*
|
|
418
|
+
* - The function runs without the request: `getEvent()` throws in it, so a
|
|
419
|
+
* result never holds one user's data. Pass what it needs as arguments.
|
|
420
|
+
* - Arguments and results are values that brumate can send, such as plain
|
|
421
|
+
* objects, arrays, dates and maps.
|
|
422
|
+
* - Calls with the same arguments while one runs share that run.
|
|
423
|
+
* - `revalidate(tag)` drops the results of a tag.
|
|
424
|
+
*/
|
|
425
|
+
function cached(fn, options) {
|
|
426
|
+
const id = options.name ?? `#${unnamed++}`;
|
|
427
|
+
return async (...args) => {
|
|
428
|
+
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");
|
|
429
|
+
const key = `brumate:cache:${id}:${JSON.stringify(write(args))}`;
|
|
430
|
+
const tags = typeof options.tags === "function" ? options.tags(...args) : options.tags ?? [];
|
|
431
|
+
const event = currentEvent();
|
|
432
|
+
for (const tag of tags) if (!event?.cacheTags.has(tag)) event?.cacheTags.set(tag, void 0);
|
|
433
|
+
const versions = await tagVersions(tags);
|
|
434
|
+
for (const tag of tags) if (event?.cacheTags.get(tag) === void 0) event?.cacheTags.set(tag, versions[tag]);
|
|
435
|
+
const kept = await store.get(key);
|
|
436
|
+
if (kept) {
|
|
437
|
+
const entry = JSON.parse(kept);
|
|
438
|
+
let fresh = entry.expires > Date.now();
|
|
439
|
+
if (fresh) {
|
|
440
|
+
for (const tag of tags) if (entry.tags[tag] !== versions[tag]) {
|
|
441
|
+
fresh = false;
|
|
442
|
+
break;
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
if (fresh) return fromJSON(entry.value, { plugins: syncPlugins });
|
|
446
|
+
}
|
|
447
|
+
let run = running$1.get(key);
|
|
448
|
+
if (!run) {
|
|
449
|
+
const started = (async () => {
|
|
450
|
+
const value = await withEvent(void 0, () => fn(...args));
|
|
451
|
+
const entry = {
|
|
452
|
+
value: write(value),
|
|
453
|
+
expires: Date.now() + options.maxAge * 1e3,
|
|
454
|
+
tags: versions
|
|
455
|
+
};
|
|
456
|
+
await store.set(key, JSON.stringify(entry), options.maxAge);
|
|
457
|
+
return value;
|
|
458
|
+
})();
|
|
459
|
+
run = started;
|
|
460
|
+
running$1.set(key, started);
|
|
461
|
+
started.then(() => running$1.delete(key), () => running$1.delete(key));
|
|
462
|
+
}
|
|
463
|
+
return fromJSON(write(await run), { plugins: syncPlugins });
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
/** The store of `cached`, which the page cache of the server shares. */
|
|
467
|
+
function cacheStore() {
|
|
468
|
+
return store;
|
|
469
|
+
}
|
|
470
|
+
/** The versions of tags. A tag that was never revalidated has version `0`. */
|
|
471
|
+
async function tagVersions(tags) {
|
|
472
|
+
const versions = {};
|
|
473
|
+
const reads = [];
|
|
474
|
+
for (const tag of tags) reads.push((async () => {
|
|
475
|
+
versions[tag] = await store.get(`brumate:tag:${tag}`) ?? "0";
|
|
476
|
+
})());
|
|
477
|
+
await Promise.all(reads);
|
|
478
|
+
return versions;
|
|
479
|
+
}
|
|
480
|
+
let revalidations = 0;
|
|
481
|
+
/**
|
|
482
|
+
* Drops the results of `cached` functions with these tags, such as after a
|
|
483
|
+
* server function changes the data. The next call runs the function again.
|
|
484
|
+
* To show the new data on the page, call `refresh` too.
|
|
485
|
+
*/
|
|
486
|
+
async function revalidate(...tags) {
|
|
487
|
+
const version = `${Date.now()}.${revalidations++}`;
|
|
488
|
+
const writes = [];
|
|
489
|
+
for (const tag of tags) writes.push(store.set(`brumate:tag:${tag}`, version, TAG_AGE));
|
|
490
|
+
await Promise.all(writes);
|
|
491
|
+
}
|
|
492
|
+
//#endregion
|
|
257
493
|
//#region src/runtime/router.ts
|
|
258
494
|
function key(path, file, params) {
|
|
259
495
|
return `${path}/${file} ${JSON.stringify(params)}`;
|
|
@@ -270,7 +506,7 @@ function wrap(view, wrapper) {
|
|
|
270
506
|
} : view;
|
|
271
507
|
}
|
|
272
508
|
/** The layout of a folder, or undefined when it has none. */
|
|
273
|
-
function
|
|
509
|
+
function findWrapper(node, segments, index, params, path) {
|
|
274
510
|
return node.layout ? {
|
|
275
511
|
layout: node.layout,
|
|
276
512
|
key: key(path, "_layout", params),
|
|
@@ -344,8 +580,12 @@ function matchNode(node, segments, index, params, path = "") {
|
|
|
344
580
|
...inner.view,
|
|
345
581
|
loading: node.loading
|
|
346
582
|
} : inner.view;
|
|
347
|
-
const wrapper =
|
|
348
|
-
|
|
583
|
+
const wrapper = findWrapper(node, segments, index, params, path);
|
|
584
|
+
let errors = inner.errors;
|
|
585
|
+
if (wrapper) {
|
|
586
|
+
errors = [];
|
|
587
|
+
for (const view of inner.errors) errors.push(wrap(view, wrapper));
|
|
588
|
+
}
|
|
349
589
|
if (node.error) errors.push(errorIn(node.error, wrapper, params, path));
|
|
350
590
|
return {
|
|
351
591
|
view: wrap(content, wrapper),
|
|
@@ -364,7 +604,8 @@ const missingPage = () => {
|
|
|
364
604
|
function matchRoute(tree, pathname) {
|
|
365
605
|
let segments;
|
|
366
606
|
try {
|
|
367
|
-
segments =
|
|
607
|
+
segments = [];
|
|
608
|
+
for (const segment of pathname.split("/")) if (segment) segments.push(decodeURIComponent(segment));
|
|
368
609
|
} catch {
|
|
369
610
|
return;
|
|
370
611
|
}
|
|
@@ -376,7 +617,7 @@ function matchRoute(tree, pathname) {
|
|
|
376
617
|
*/
|
|
377
618
|
function notFound(tree) {
|
|
378
619
|
return {
|
|
379
|
-
errors: tree.error ? [errorIn(tree.error,
|
|
620
|
+
errors: tree.error ? [errorIn(tree.error, findWrapper(tree, [], 0, {}, ""), {}, "")] : [],
|
|
380
621
|
middleware: tree.middleware ? [tree.middleware] : []
|
|
381
622
|
};
|
|
382
623
|
}
|
|
@@ -414,10 +655,13 @@ function summary(issues) {
|
|
|
414
655
|
*/
|
|
415
656
|
function plainIssue(issue) {
|
|
416
657
|
const plain = { message: String(issue.message) };
|
|
417
|
-
if (issue.path && issue.path.length > 0)
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
658
|
+
if (issue.path && issue.path.length > 0) {
|
|
659
|
+
plain.path = [];
|
|
660
|
+
for (const segment of issue.path) {
|
|
661
|
+
const key = typeof segment === "object" && segment !== null ? segment.key : segment;
|
|
662
|
+
plain.path.push(typeof key === "number" ? key : String(key));
|
|
663
|
+
}
|
|
664
|
+
}
|
|
421
665
|
return plain;
|
|
422
666
|
}
|
|
423
667
|
/**
|
|
@@ -429,7 +673,11 @@ async function safeParse(schema, value) {
|
|
|
429
673
|
const props = schema["~standard"];
|
|
430
674
|
if (props?.version !== 1 || typeof props.validate !== "function") throw new TypeError("The schema is not a Standard Schema of version 1");
|
|
431
675
|
const result = await props.validate(value);
|
|
432
|
-
if (result.issues)
|
|
676
|
+
if (result.issues) {
|
|
677
|
+
const issues = [];
|
|
678
|
+
for (const issue of result.issues) issues.push(plainIssue(issue));
|
|
679
|
+
return { issues };
|
|
680
|
+
}
|
|
433
681
|
return { value: result.value };
|
|
434
682
|
}
|
|
435
683
|
/**
|
|
@@ -450,67 +698,6 @@ async function parse(schema, value) {
|
|
|
450
698
|
if (result.issues) throw new ValidationError(result.issues);
|
|
451
699
|
return result.value;
|
|
452
700
|
}
|
|
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
701
|
/**
|
|
515
702
|
* Validates the data of a form with a Standard Schema. The entries become a
|
|
516
703
|
* plain object first. Returns `{ value }` or `{ issues }`, and does not throw
|
|
@@ -548,6 +735,137 @@ function fieldErrors(issues) {
|
|
|
548
735
|
return errors;
|
|
549
736
|
}
|
|
550
737
|
//#endregion
|
|
738
|
+
//#region src/runtime/submission.ts
|
|
739
|
+
/** True for a file, so it is not sent back. */
|
|
740
|
+
function isBlob(value) {
|
|
741
|
+
return typeof Blob !== "undefined" && value instanceof Blob;
|
|
742
|
+
}
|
|
743
|
+
/** The values to send back: without files and hidden fields. */
|
|
744
|
+
function echo(value, hidden, path = []) {
|
|
745
|
+
if (path.length > 0 && hidden.has(formatPath(path))) return;
|
|
746
|
+
if (isBlob(value)) return;
|
|
747
|
+
if (Array.isArray(value)) {
|
|
748
|
+
const copy = new Array(value.length);
|
|
749
|
+
for (const [index, item] of value.entries()) if (index in value) copy[index] = echo(item, hidden, [...path, index]);
|
|
750
|
+
return copy;
|
|
751
|
+
}
|
|
752
|
+
if (typeof value === "object" && value !== null) {
|
|
753
|
+
const copy = {};
|
|
754
|
+
for (const [key, item] of Object.entries(value)) {
|
|
755
|
+
const next = echo(item, hidden, [...path, key]);
|
|
756
|
+
if (next !== void 0) copy[key] = next;
|
|
757
|
+
}
|
|
758
|
+
return copy;
|
|
759
|
+
}
|
|
760
|
+
return value;
|
|
761
|
+
}
|
|
762
|
+
/** A new ID for a reply, which the keys of the items of a changed list start with. */
|
|
763
|
+
function replyId() {
|
|
764
|
+
return Math.random().toString(36).slice(2, 10);
|
|
765
|
+
}
|
|
766
|
+
/**
|
|
767
|
+
* Reads the data of a form that `createForm` shows. It turns the entries
|
|
768
|
+
* into an object, as `parseForm` does, applies the intent of the button
|
|
769
|
+
* that was pressed, and validates the values with a Standard Schema when
|
|
770
|
+
* the button was not an intent. It does not throw for data that does not
|
|
771
|
+
* match. `reply()` gives what the function returns, for `createForm` to show.
|
|
772
|
+
*
|
|
773
|
+
* ```ts
|
|
774
|
+
* async function save(form: FormData) {
|
|
775
|
+
* 'use server';
|
|
776
|
+
* const submission = await parseSubmission(Order, form);
|
|
777
|
+
* if (submission.status !== 'success') {
|
|
778
|
+
* return submission.reply();
|
|
779
|
+
* }
|
|
780
|
+
* await db.orders.save(submission.value);
|
|
781
|
+
* return submission.reply({ reset: true });
|
|
782
|
+
* }
|
|
783
|
+
* ```
|
|
784
|
+
*/
|
|
785
|
+
async function parseSubmission(schema, form, options = {}) {
|
|
786
|
+
const hidden = new Set(options.hide);
|
|
787
|
+
const id = replyId();
|
|
788
|
+
function make(status, payload, issues, list) {
|
|
789
|
+
return {
|
|
790
|
+
payload,
|
|
791
|
+
reply(reply = {}) {
|
|
792
|
+
const grouped = groupIssues(issues);
|
|
793
|
+
const errors = { ...grouped.errors };
|
|
794
|
+
for (const [name, messages] of Object.entries(reply.fieldErrors ?? {})) errors[name] = [...Object.hasOwn(errors, name) ? errors[name] : [], ...messages];
|
|
795
|
+
const keys = {};
|
|
796
|
+
const items = list === void 0 ? void 0 : getAt(payload, parsePath(list));
|
|
797
|
+
if (list !== void 0 && Array.isArray(items)) {
|
|
798
|
+
const itemKeys = new Array(items.length);
|
|
799
|
+
for (let index = 0; index < items.length; index++) if (index in items) itemKeys[index] = `${id}-${index}`;
|
|
800
|
+
keys[list] = itemKeys;
|
|
801
|
+
}
|
|
802
|
+
const result = {
|
|
803
|
+
status,
|
|
804
|
+
value: reply.reset ? void 0 : echo(payload, hidden),
|
|
805
|
+
errors: reply.reset ? {} : errors,
|
|
806
|
+
formErrors: [...grouped.formErrors, ...reply.formErrors ?? []],
|
|
807
|
+
keys: reply.reset ? {} : keys,
|
|
808
|
+
id
|
|
809
|
+
};
|
|
810
|
+
if (reply.reset) result.reset = true;
|
|
811
|
+
return result;
|
|
812
|
+
}
|
|
813
|
+
};
|
|
814
|
+
}
|
|
815
|
+
const raw = form.get(INTENT);
|
|
816
|
+
const values = formValues(form, (name) => name === INTENT);
|
|
817
|
+
if (values.issues) return {
|
|
818
|
+
status: "error",
|
|
819
|
+
issues: values.issues,
|
|
820
|
+
...make("error", void 0, values.issues)
|
|
821
|
+
};
|
|
822
|
+
let payload = values.value;
|
|
823
|
+
if (raw === null) {
|
|
824
|
+
const result = await safeParse(schema, payload);
|
|
825
|
+
if (result.issues) return {
|
|
826
|
+
status: "error",
|
|
827
|
+
issues: result.issues,
|
|
828
|
+
...make("error", payload, result.issues)
|
|
829
|
+
};
|
|
830
|
+
return {
|
|
831
|
+
status: "success",
|
|
832
|
+
value: result.value,
|
|
833
|
+
...make("success", payload, [])
|
|
834
|
+
};
|
|
835
|
+
}
|
|
836
|
+
const intent = typeof raw === "string" ? parseIntent(raw) : void 0;
|
|
837
|
+
const applied = intent && applyIntent(payload, intent);
|
|
838
|
+
if (!intent || !applied) {
|
|
839
|
+
const issues = [{ message: "The form asked for a change that it cannot make" }];
|
|
840
|
+
return {
|
|
841
|
+
status: "error",
|
|
842
|
+
intent,
|
|
843
|
+
issues,
|
|
844
|
+
...make("error", payload, issues)
|
|
845
|
+
};
|
|
846
|
+
}
|
|
847
|
+
payload = applied.value ?? void 0;
|
|
848
|
+
if (intent.type === "validate") {
|
|
849
|
+
const result = await safeParse(schema, payload);
|
|
850
|
+
const name = intent.name;
|
|
851
|
+
const issues = [];
|
|
852
|
+
for (const issue of result.issues ?? []) {
|
|
853
|
+
const path = issue.path ? formatPath(issue.path) : "";
|
|
854
|
+
if (path === name || path.startsWith(`${name}.`) || path.startsWith(`${name}[`)) issues.push(issue);
|
|
855
|
+
}
|
|
856
|
+
return {
|
|
857
|
+
status: "intent",
|
|
858
|
+
intent,
|
|
859
|
+
...make("intent", payload, issues)
|
|
860
|
+
};
|
|
861
|
+
}
|
|
862
|
+
return {
|
|
863
|
+
status: "intent",
|
|
864
|
+
intent,
|
|
865
|
+
...make("intent", payload, [], applied.list)
|
|
866
|
+
};
|
|
867
|
+
}
|
|
868
|
+
//#endregion
|
|
551
869
|
//#region src/runtime/rate-limit.ts
|
|
552
870
|
/**
|
|
553
871
|
* The error of a request over its limit. Its status is 429, and
|
|
@@ -580,11 +898,11 @@ function windowMs(window) {
|
|
|
580
898
|
function createMemoryStore(now = Date.now) {
|
|
581
899
|
const counts = /* @__PURE__ */ new Map();
|
|
582
900
|
let sweeps = 0;
|
|
583
|
-
|
|
901
|
+
function sweep() {
|
|
584
902
|
if (++sweeps % 1e3 !== 0) return;
|
|
585
903
|
const time = now();
|
|
586
904
|
for (const [key, entry] of counts) if (entry.expires <= time) counts.delete(key);
|
|
587
|
-
}
|
|
905
|
+
}
|
|
588
906
|
return {
|
|
589
907
|
increment(key, ttl) {
|
|
590
908
|
sweep();
|
|
@@ -625,7 +943,7 @@ function isDevelopment() {
|
|
|
625
943
|
* What a limit counts per: the server function, the pattern of the route,
|
|
626
944
|
* such as `/api/[id]`, or one count for every path that no route matches.
|
|
627
945
|
*/
|
|
628
|
-
function
|
|
946
|
+
function getTarget(event) {
|
|
629
947
|
return event.call?.id ?? event.route ?? "(no route)";
|
|
630
948
|
}
|
|
631
949
|
/**
|
|
@@ -634,10 +952,10 @@ function targetOf(event) {
|
|
|
634
952
|
* up the limit of all. So it throws in production. In development it warns
|
|
635
953
|
* once and returns undefined, and the limit does not count.
|
|
636
954
|
*/
|
|
637
|
-
async function
|
|
955
|
+
async function readKey(event, options) {
|
|
638
956
|
const key = await options.key?.(event, event.call?.args ?? []) ?? clientAddress(event);
|
|
639
957
|
if (key !== void 0) return key;
|
|
640
|
-
const message = `rateLimit: the request to "${
|
|
958
|
+
const message = `rateLimit: the request to "${getTarget(event)}" has no key, because the server did not pass the address of the client. Pass \`address\` to the handler of the server, or set \`key\` on the limit.`;
|
|
641
959
|
if (!isDevelopment()) throw new Error(message);
|
|
642
960
|
if (!warned) {
|
|
643
961
|
warned = true;
|
|
@@ -650,9 +968,9 @@ async function keyOf(event, options) {
|
|
|
650
968
|
*/
|
|
651
969
|
async function check(event, options) {
|
|
652
970
|
if (event.prerender || !(options.enabled ?? config.enabled ?? true)) return;
|
|
653
|
-
const key = await
|
|
971
|
+
const key = await readKey(event, options);
|
|
654
972
|
if (key === void 0) return;
|
|
655
|
-
const name = `${key} ${
|
|
973
|
+
const name = `${key} ${getTarget(event)}`;
|
|
656
974
|
const store = options.store ?? config.store ?? (memory ??= createMemoryStore(clock));
|
|
657
975
|
const window = windowMs(options.window);
|
|
658
976
|
const now = clock();
|
|
@@ -716,13 +1034,12 @@ function parseAddress(text) {
|
|
|
716
1034
|
const value = text.trim().replace(/^\[|\]$/g, "");
|
|
717
1035
|
if (value.includes(":")) return parseIPv6(value);
|
|
718
1036
|
const parts = value.split(".");
|
|
719
|
-
if (parts.length !== 4
|
|
1037
|
+
if (parts.length !== 4) return;
|
|
1038
|
+
for (const part of parts) if (!/^\d{1,3}$/.test(part) || Number(part) >= 256) return;
|
|
720
1039
|
const bytes = /* @__PURE__ */ new Uint8Array(16);
|
|
721
1040
|
bytes[10] = 255;
|
|
722
1041
|
bytes[11] = 255;
|
|
723
|
-
parts.
|
|
724
|
-
bytes[12 + index] = Number(part);
|
|
725
|
-
});
|
|
1042
|
+
for (const [index, part] of parts.entries()) bytes[12 + index] = Number(part);
|
|
726
1043
|
return bytes;
|
|
727
1044
|
}
|
|
728
1045
|
function parseIPv6(value) {
|
|
@@ -754,7 +1071,8 @@ function parseIPv6(value) {
|
|
|
754
1071
|
return bytes;
|
|
755
1072
|
}
|
|
756
1073
|
function isIPv4(bytes) {
|
|
757
|
-
|
|
1074
|
+
for (const byte of bytes.slice(0, 10)) if (byte !== 0) return false;
|
|
1075
|
+
return bytes[10] === 255 && bytes[11] === 255;
|
|
758
1076
|
}
|
|
759
1077
|
/**
|
|
760
1078
|
* Reads a range: an address, or a CIDR such as `10.0.0.0/8` or `fd00::/8`.
|
|
@@ -801,10 +1119,15 @@ function formatAddress(bytes) {
|
|
|
801
1119
|
function clientAddress(event, proxies = config.proxies ?? []) {
|
|
802
1120
|
const seen = event.address === void 0 ? void 0 : parseAddress(event.address);
|
|
803
1121
|
if (!seen) return;
|
|
804
|
-
const ranges =
|
|
805
|
-
const
|
|
1122
|
+
const ranges = [];
|
|
1123
|
+
for (const proxy of proxies) ranges.push(parseRange(proxy));
|
|
1124
|
+
function trusted(address) {
|
|
1125
|
+
for (const range of ranges) if (inParsedRange(address, range)) return true;
|
|
1126
|
+
return false;
|
|
1127
|
+
}
|
|
806
1128
|
if (!trusted(seen)) return formatAddress(seen);
|
|
807
|
-
const hops =
|
|
1129
|
+
const hops = [];
|
|
1130
|
+
for (const hop of (event.request.headers.get("x-forwarded-for") ?? "").split(",")) if (hop.trim() !== "") hops.push(hop);
|
|
808
1131
|
let client = seen;
|
|
809
1132
|
for (let index = hops.length - 1; index >= 0; index--) {
|
|
810
1133
|
const address = parseAddress(hops[index]);
|
|
@@ -815,7 +1138,145 @@ function clientAddress(event, proxies = config.proxies ?? []) {
|
|
|
815
1138
|
return formatAddress(client);
|
|
816
1139
|
}
|
|
817
1140
|
//#endregion
|
|
1141
|
+
//#region src/runtime/idempotent.ts
|
|
1142
|
+
/** Runs that are going on, by key, so a second post while the first runs waits for it. */
|
|
1143
|
+
const running = /* @__PURE__ */ new Map();
|
|
1144
|
+
/**
|
|
1145
|
+
* Makes a server function that runs once for each form that the server
|
|
1146
|
+
* renders for it. A second post of the same form, such as a double click
|
|
1147
|
+
* before the page loaded or a post again after a reload, gets the result of
|
|
1148
|
+
* the first, or the same redirect, without running the function again.
|
|
1149
|
+
*
|
|
1150
|
+
* - It works for the exported functions of a `'use server'` file, used as the
|
|
1151
|
+
* `action` of a form.
|
|
1152
|
+
* - The key is in the URL of the form, so a page with such a form is not
|
|
1153
|
+
* cached for everyone. Each render has a new key.
|
|
1154
|
+
* - With scripts, the form gets a new key after each answer, so a post that
|
|
1155
|
+
* the user means again runs again.
|
|
1156
|
+
* - A call without a key, such as from a handler, runs as usual.
|
|
1157
|
+
*/
|
|
1158
|
+
function idempotent(fn, options = {}) {
|
|
1159
|
+
const maxAge = options.maxAge ?? 600;
|
|
1160
|
+
const wrapper = ((...args) => {
|
|
1161
|
+
const event = currentEvent();
|
|
1162
|
+
const key = event && new URL(event.request.url).searchParams.get("__key");
|
|
1163
|
+
const id = idempotentId.get(wrapper);
|
|
1164
|
+
if (!event || !key || !id || !/^[\w-]{8,64}$/.test(key)) return fn(...args);
|
|
1165
|
+
const storeKey = `brumate:once:${id}:${key}`;
|
|
1166
|
+
let run = running.get(storeKey);
|
|
1167
|
+
if (!run) {
|
|
1168
|
+
run = (async () => {
|
|
1169
|
+
const kept = await cacheStore().get(storeKey);
|
|
1170
|
+
if (kept) return fromJSON(JSON.parse(kept), { plugins: syncPlugins });
|
|
1171
|
+
let outcome;
|
|
1172
|
+
try {
|
|
1173
|
+
outcome = { result: await withEvent(event, () => fn(...args)) };
|
|
1174
|
+
} catch (error) {
|
|
1175
|
+
if (!isRedirect(error)) throw error;
|
|
1176
|
+
outcome = { redirect: {
|
|
1177
|
+
location: error.location,
|
|
1178
|
+
status: error.status
|
|
1179
|
+
} };
|
|
1180
|
+
}
|
|
1181
|
+
const text = JSON.stringify(toJSON(outcome, {
|
|
1182
|
+
plugins: syncPlugins,
|
|
1183
|
+
...serialOptions()
|
|
1184
|
+
}));
|
|
1185
|
+
await cacheStore().set(storeKey, text, maxAge);
|
|
1186
|
+
return outcome;
|
|
1187
|
+
})();
|
|
1188
|
+
running.set(storeKey, run);
|
|
1189
|
+
run.then(() => running.delete(storeKey), () => running.delete(storeKey));
|
|
1190
|
+
}
|
|
1191
|
+
return run.then((outcome) => {
|
|
1192
|
+
if ("redirect" in outcome) redirect(outcome.redirect.location, outcome.redirect.status);
|
|
1193
|
+
return outcome.result;
|
|
1194
|
+
});
|
|
1195
|
+
});
|
|
1196
|
+
Object.defineProperty(wrapper, IDEMPOTENT, { value: true });
|
|
1197
|
+
return wrapper;
|
|
1198
|
+
}
|
|
1199
|
+
//#endregion
|
|
818
1200
|
//#region src/runtime/server.ts
|
|
1201
|
+
/** What `$bind(name)` passes a child: the value of the name, and the scope and slot it writes. */
|
|
1202
|
+
function binding(value, scope, slot, set) {
|
|
1203
|
+
return new Binding(value, new SlotReference(scope, slot), set);
|
|
1204
|
+
}
|
|
1205
|
+
/**
|
|
1206
|
+
* The `#loading` bodies of a `#reveal` block, in the order of the markup.
|
|
1207
|
+
* When a body is ready, the stream asks the group, which sends the bodies
|
|
1208
|
+
* that its order lets show. The data of every body still loads at once.
|
|
1209
|
+
*/
|
|
1210
|
+
var RevealGroup = class {
|
|
1211
|
+
order;
|
|
1212
|
+
collapsed;
|
|
1213
|
+
/** The bodies that stream, each with how to send it once it is ready. */
|
|
1214
|
+
members = [];
|
|
1215
|
+
/** The fallbacks that `collapsed` hides until the body before them shows. */
|
|
1216
|
+
hidden = /* @__PURE__ */ new Set();
|
|
1217
|
+
closed = false;
|
|
1218
|
+
constructor(order, collapsed) {
|
|
1219
|
+
this.order = order;
|
|
1220
|
+
this.collapsed = collapsed;
|
|
1221
|
+
}
|
|
1222
|
+
/** True when a body that is ready can render in place, before the bodies that stream. */
|
|
1223
|
+
mayShow() {
|
|
1224
|
+
return this.order === "natural" || this.order === "sequential" && this.members.length === 0;
|
|
1225
|
+
}
|
|
1226
|
+
/** True when the fallback of the next body that streams waits, for `collapsed`. */
|
|
1227
|
+
hides() {
|
|
1228
|
+
return this.collapsed && this.members.length > 0;
|
|
1229
|
+
}
|
|
1230
|
+
add(id) {
|
|
1231
|
+
this.members.push({ id });
|
|
1232
|
+
}
|
|
1233
|
+
/** The body is ready, or failed with nothing to send. `send` writes it, and runs `after` with it. */
|
|
1234
|
+
ready(id, send) {
|
|
1235
|
+
let member;
|
|
1236
|
+
for (const item of this.members) if (item.id === id) {
|
|
1237
|
+
member = item;
|
|
1238
|
+
break;
|
|
1239
|
+
}
|
|
1240
|
+
if (member) {
|
|
1241
|
+
member.send = send;
|
|
1242
|
+
this.flush();
|
|
1243
|
+
} else send("");
|
|
1244
|
+
}
|
|
1245
|
+
/** The block ended, so the group knows its last body. */
|
|
1246
|
+
close() {
|
|
1247
|
+
this.closed = true;
|
|
1248
|
+
this.flush();
|
|
1249
|
+
}
|
|
1250
|
+
flush() {
|
|
1251
|
+
const { members } = this;
|
|
1252
|
+
const sendAt = (index) => {
|
|
1253
|
+
const member = members[index];
|
|
1254
|
+
member.sent = true;
|
|
1255
|
+
const next = members[index + 1];
|
|
1256
|
+
member.send(next && this.hidden.has(next.id) ? `$bF(${scriptJSON(next.id)})` : "");
|
|
1257
|
+
};
|
|
1258
|
+
if (this.order === "natural") {
|
|
1259
|
+
for (const [index, member] of members.entries()) if (member.send && !member.sent) sendAt(index);
|
|
1260
|
+
} else if (this.order === "sequential") {
|
|
1261
|
+
for (let index = 0; index < members.length && members[index].send; index++) if (!members[index].sent) sendAt(index);
|
|
1262
|
+
} else if (this.closed && this.order === "backwards") {
|
|
1263
|
+
for (let index = members.length - 1; index >= 0 && members[index].send; index--) if (!members[index].sent) sendAt(index);
|
|
1264
|
+
} else if (this.closed) {
|
|
1265
|
+
let allReady = true;
|
|
1266
|
+
for (const member of members) if (!member.send) {
|
|
1267
|
+
allReady = false;
|
|
1268
|
+
break;
|
|
1269
|
+
}
|
|
1270
|
+
if (allReady) {
|
|
1271
|
+
for (const [index, member] of members.entries()) if (!member.sent) sendAt(index);
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
};
|
|
1276
|
+
/** The last entry of the inserted children that comes from `from`. */
|
|
1277
|
+
function findLastInserted(inserted, from) {
|
|
1278
|
+
for (let index = inserted.length - 1; index >= 0; index--) if (inserted[index].from === from) return inserted[index];
|
|
1279
|
+
}
|
|
819
1280
|
/** True if a boundary holds `target`, whose ID starts with the boundary's ID and a dot. */
|
|
820
1281
|
function holdsBoundary(id, target) {
|
|
821
1282
|
return typeof target === "string" && target.startsWith(`${id}.`);
|
|
@@ -881,6 +1342,10 @@ var Context = class Context {
|
|
|
881
1342
|
markup: true
|
|
882
1343
|
};
|
|
883
1344
|
onBoundary;
|
|
1345
|
+
/** The `#try` blocks of the parents of this context, from the outside in. */
|
|
1346
|
+
outer = [];
|
|
1347
|
+
/** The `#try` blocks of this context that are rendering their bodies now. */
|
|
1348
|
+
catchers = [];
|
|
884
1349
|
/** The scope that renders the next component, which becomes its owner. */
|
|
885
1350
|
owner;
|
|
886
1351
|
/**
|
|
@@ -894,6 +1359,8 @@ var Context = class Context {
|
|
|
894
1359
|
rpcPrefix = "/_brumate";
|
|
895
1360
|
/** The ID of the build, for forms that post to server functions. See `RenderOptions`. */
|
|
896
1361
|
build;
|
|
1362
|
+
/** True in development, where a memo that failed or a `#catch` sends its error to the browser. */
|
|
1363
|
+
development = false;
|
|
897
1364
|
/** Results of server functions that a form posted to this page, for `$action`. */
|
|
898
1365
|
actions = /* @__PURE__ */ new Map();
|
|
899
1366
|
/** The params of the route of the page, for `$route`. */
|
|
@@ -908,6 +1375,14 @@ var Context = class Context {
|
|
|
908
1375
|
if (!event) throw new Error("getEvent() works while a page renders with a request, such as in a route");
|
|
909
1376
|
return event;
|
|
910
1377
|
}
|
|
1378
|
+
/** Starts an entry of the trace of the request, in development. */
|
|
1379
|
+
traced(kind, label) {
|
|
1380
|
+
return this.root.event?.traced(kind, label);
|
|
1381
|
+
}
|
|
1382
|
+
/** Marks the request of the page as one that depends on the user, so the page is not cached for everyone. */
|
|
1383
|
+
personal() {
|
|
1384
|
+
if (this.root.event) this.root.event.personal = true;
|
|
1385
|
+
}
|
|
911
1386
|
/** Runs code of the render with its event and its call results, such as a memo's compute. */
|
|
912
1387
|
run(callback) {
|
|
913
1388
|
return withEvent(this.root.event, callback, this.root.calls);
|
|
@@ -977,6 +1452,10 @@ var Context = class Context {
|
|
|
977
1452
|
rpc() {
|
|
978
1453
|
return this.root.rpcPrefix;
|
|
979
1454
|
}
|
|
1455
|
+
/** True when the render is in development. */
|
|
1456
|
+
isDev() {
|
|
1457
|
+
return this.root.development;
|
|
1458
|
+
}
|
|
980
1459
|
/** Returns the ID of the build, when the render has one. */
|
|
981
1460
|
buildId() {
|
|
982
1461
|
return this.root.build;
|
|
@@ -1003,7 +1482,7 @@ var Context = class Context {
|
|
|
1003
1482
|
root.owner = void 0;
|
|
1004
1483
|
}
|
|
1005
1484
|
}
|
|
1006
|
-
const inserted = root.inserted
|
|
1485
|
+
const inserted = findLastInserted(root.inserted, up);
|
|
1007
1486
|
if (inserted) {
|
|
1008
1487
|
up = inserted.at;
|
|
1009
1488
|
record.t = inserted.at;
|
|
@@ -1049,12 +1528,18 @@ var Context = class Context {
|
|
|
1049
1528
|
* keep `from`, the scope of the markup that wrote them, for their values,
|
|
1050
1529
|
* and find their contexts from `at`.
|
|
1051
1530
|
*/
|
|
1052
|
-
async children(from, at, renderBody) {
|
|
1531
|
+
async children(from, at, renderBody, tag) {
|
|
1532
|
+
const { inserted } = this.root;
|
|
1533
|
+
const outer = findLastInserted(inserted, at);
|
|
1053
1534
|
const entry = {
|
|
1054
1535
|
from,
|
|
1055
|
-
at
|
|
1536
|
+
at: outer ? outer.at : at,
|
|
1537
|
+
tag: tag ?? outer?.tag
|
|
1056
1538
|
};
|
|
1057
|
-
|
|
1539
|
+
if (outer) {
|
|
1540
|
+
const passing = this.find(at);
|
|
1541
|
+
if (passing) passing.record.f = outer.at;
|
|
1542
|
+
}
|
|
1058
1543
|
inserted.push(entry);
|
|
1059
1544
|
try {
|
|
1060
1545
|
return await renderBody();
|
|
@@ -1062,6 +1547,10 @@ var Context = class Context {
|
|
|
1062
1547
|
inserted.splice(inserted.indexOf(entry), 1);
|
|
1063
1548
|
}
|
|
1064
1549
|
}
|
|
1550
|
+
/** The tag of the element where the children that render now are inserted, for spacers. */
|
|
1551
|
+
spacerTag() {
|
|
1552
|
+
return this.root.inserted.at(-1)?.tag ?? "div";
|
|
1553
|
+
}
|
|
1065
1554
|
/**
|
|
1066
1555
|
* The ID that `$id()` makes: the scope's ID and the position of the call.
|
|
1067
1556
|
* A dot in a scope ID inside a `#loading` body becomes `_`, so the ID also
|
|
@@ -1084,9 +1573,9 @@ var Context = class Context {
|
|
|
1084
1573
|
record.v[context.key] = value;
|
|
1085
1574
|
}
|
|
1086
1575
|
/**
|
|
1087
|
-
* Reads a context from the nearest scope that provides it
|
|
1088
|
-
*
|
|
1089
|
-
*
|
|
1576
|
+
* Reads a context from the nearest scope above `scope` that provides it.
|
|
1577
|
+
* With `slot`, records which slot holds it, so the client can update it
|
|
1578
|
+
* when the provided value changes.
|
|
1090
1579
|
*/
|
|
1091
1580
|
consume(context, scope, slot) {
|
|
1092
1581
|
if (slot !== void 0) {
|
|
@@ -1094,7 +1583,7 @@ var Context = class Context {
|
|
|
1094
1583
|
record.x ??= {};
|
|
1095
1584
|
record.x[context.key] = slot;
|
|
1096
1585
|
}
|
|
1097
|
-
for (let id = scope; id !== void 0;) {
|
|
1586
|
+
for (let id = this.find(scope)?.parent; id !== void 0;) {
|
|
1098
1587
|
const node = this.find(id);
|
|
1099
1588
|
if (node?.values?.has(context.key)) return node.values.get(context.key);
|
|
1100
1589
|
id = node?.parent;
|
|
@@ -1192,19 +1681,81 @@ var Context = class Context {
|
|
|
1192
1681
|
}
|
|
1193
1682
|
/** The records of the scopes of this render, by ID, in the order the render made them. */
|
|
1194
1683
|
get state() {
|
|
1195
|
-
|
|
1684
|
+
const state = /* @__PURE__ */ new Map();
|
|
1685
|
+
for (const entry of this.scopes) state.set(entry.id, entry.record);
|
|
1686
|
+
return state;
|
|
1196
1687
|
}
|
|
1197
1688
|
/**
|
|
1198
1689
|
* The list of each list item scope whose list is a slot of an enclosing
|
|
1199
1690
|
* scope, as `[scope, slot]`. The items of a list share one array.
|
|
1200
1691
|
*/
|
|
1201
1692
|
get sources() {
|
|
1202
|
-
|
|
1693
|
+
const sources = /* @__PURE__ */ new Map();
|
|
1694
|
+
for (const entry of this.scopes) if (entry.source) sources.set(entry.id, entry.source);
|
|
1695
|
+
return sources;
|
|
1696
|
+
}
|
|
1697
|
+
/** The scope that `unbind` collects the promise props of its component in. */
|
|
1698
|
+
sink(scope) {
|
|
1699
|
+
return this.entry(scope);
|
|
1203
1700
|
}
|
|
1204
1701
|
slots(scope, values, names) {
|
|
1205
1702
|
const entry = this.entry(scope);
|
|
1206
1703
|
entry.record.s = values;
|
|
1207
1704
|
if (names) entry.names = names;
|
|
1705
|
+
const forwarded = this.forwards?.get(scope);
|
|
1706
|
+
if (forwarded) {
|
|
1707
|
+
this.forwards.delete(scope);
|
|
1708
|
+
for (const [slot, value] of forwarded) values[slot] = value;
|
|
1709
|
+
}
|
|
1710
|
+
let wrapped;
|
|
1711
|
+
for (let slot = 0; slot < values.length; slot++) {
|
|
1712
|
+
const value = values[slot];
|
|
1713
|
+
if (value instanceof Promise && entry.props?.includes(value) && values.indexOf(value) === slot) {
|
|
1714
|
+
wrapped ??= [...values];
|
|
1715
|
+
wrapped[slot] = new PropPromise(this.isDev() ? value : value.catch((error) => {
|
|
1716
|
+
const safe = new Error(error instanceof ServerError ? error.message : "The page could not compute a value");
|
|
1717
|
+
safe.stack = "";
|
|
1718
|
+
throw safe;
|
|
1719
|
+
}));
|
|
1720
|
+
}
|
|
1721
|
+
}
|
|
1722
|
+
entry.props = void 0;
|
|
1723
|
+
if (wrapped) entry.record.s = wrapped;
|
|
1724
|
+
}
|
|
1725
|
+
/** Elements that bound props of components forwarded to the slots of scopes that have no slots yet. */
|
|
1726
|
+
forwards;
|
|
1727
|
+
/**
|
|
1728
|
+
* Writes the element that a component forwards to a slot of a scope above it, and on through
|
|
1729
|
+
* the props that scope binds in turn. The parent records its slots after its children render,
|
|
1730
|
+
* so a write for a scope that has none waits for them.
|
|
1731
|
+
*/
|
|
1732
|
+
forward(target, value) {
|
|
1733
|
+
const record = this.ownRecord(target.scope);
|
|
1734
|
+
if (!record?.s) {
|
|
1735
|
+
const waiting = (this.forwards ??= /* @__PURE__ */ new Map()).get(target.scope) ?? /* @__PURE__ */ new Map();
|
|
1736
|
+
waiting.set(target.slot, value);
|
|
1737
|
+
this.forwards.set(target.scope, waiting);
|
|
1738
|
+
return;
|
|
1739
|
+
}
|
|
1740
|
+
record.s[target.slot] = value;
|
|
1741
|
+
const next = record.b?.[target.slot];
|
|
1742
|
+
if (isSlotReference(next)) this.forward(next, value);
|
|
1743
|
+
}
|
|
1744
|
+
/**
|
|
1745
|
+
* Records the props that a parent bound with `$bind`, among the props that
|
|
1746
|
+
* the component writes: `slots` has the slot of each, by its name. Its
|
|
1747
|
+
* writes in the browser go to the parent's slots.
|
|
1748
|
+
*/
|
|
1749
|
+
bindings(scope, props, slots) {
|
|
1750
|
+
for (const [name, slot] of Object.entries(slots)) {
|
|
1751
|
+
const value = props[name];
|
|
1752
|
+
if (isBinding(value)) {
|
|
1753
|
+
const record = this.entry(scope).record;
|
|
1754
|
+
(record.b ??= {})[slot] = value.target;
|
|
1755
|
+
const written = record.s?.[slot];
|
|
1756
|
+
if (written instanceof ElementReference && isSlotReference(value.target)) this.forward(value.target, written);
|
|
1757
|
+
}
|
|
1758
|
+
}
|
|
1208
1759
|
}
|
|
1209
1760
|
/**
|
|
1210
1761
|
* Records the item of a list that can change on the client. `source` is
|
|
@@ -1225,14 +1776,45 @@ var Context = class Context {
|
|
|
1225
1776
|
if (links[anchor] === child) delete links[anchor];
|
|
1226
1777
|
});
|
|
1227
1778
|
}
|
|
1779
|
+
/**
|
|
1780
|
+
* A `ref` that the rest props of a component hold is a binding of a signal above. The element
|
|
1781
|
+
* that spreads them goes to that signal, as when the component names `ref` itself.
|
|
1782
|
+
*/
|
|
1783
|
+
restRef(attributes, scope, anchor, tag) {
|
|
1784
|
+
const value = attributes.ref;
|
|
1785
|
+
if (typeof tag !== "function" && isBinding(value) && isSlotReference(value.target)) this.forward(value.target, new ElementReference(scope, anchor));
|
|
1786
|
+
return attributes;
|
|
1787
|
+
}
|
|
1228
1788
|
/** Returns the reference that a `ref` signal holds on the server. */
|
|
1229
1789
|
element(scope, anchor) {
|
|
1230
1790
|
return new ElementReference(scope, anchor);
|
|
1231
1791
|
}
|
|
1232
|
-
/**
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1792
|
+
/**
|
|
1793
|
+
* Marks a function as a client function, so it serializes as a reference.
|
|
1794
|
+
* `args` are the arguments of a handler that `$handler` made, which go
|
|
1795
|
+
* with the reference. Each call makes a new reference, so a function that
|
|
1796
|
+
* `$handler` marks gets a copy for its arguments.
|
|
1797
|
+
*/
|
|
1798
|
+
fn(value, ref, scope, args) {
|
|
1799
|
+
if (typeof value !== "function") return value;
|
|
1800
|
+
if (args === void 0 && /#t\d/.test(ref)) {
|
|
1801
|
+
const render = value;
|
|
1802
|
+
function template(...rest) {
|
|
1803
|
+
return new Children(scope, async () => {
|
|
1804
|
+
const html = await render(...rest);
|
|
1805
|
+
return isRaw(html) ? rawHTML(html) : insertValue(html);
|
|
1806
|
+
});
|
|
1807
|
+
}
|
|
1808
|
+
functionReferences.set(template, new FunctionReference(ref, scope));
|
|
1809
|
+
return template;
|
|
1810
|
+
}
|
|
1811
|
+
if (args === void 0) {
|
|
1812
|
+
functionReferences.set(value, new FunctionReference(ref, scope));
|
|
1813
|
+
return value;
|
|
1814
|
+
}
|
|
1815
|
+
const bound = Object.assign((...rest) => value(...args, ...rest), value);
|
|
1816
|
+
functionReferences.set(bound, new FunctionReference(ref, scope, args));
|
|
1817
|
+
return bound;
|
|
1236
1818
|
}
|
|
1237
1819
|
/** Returns a component's stylesheet the first time the page renders the component. */
|
|
1238
1820
|
style(id, css) {
|
|
@@ -1302,6 +1884,49 @@ var Context = class Context {
|
|
|
1302
1884
|
}
|
|
1303
1885
|
/** True when the bodies of `#defer` blocks render in place, for a page that renders in order. */
|
|
1304
1886
|
inOrder = false;
|
|
1887
|
+
/** The `#reveal` blocks that are open in this context, the innermost last. */
|
|
1888
|
+
reveals = [];
|
|
1889
|
+
/** Starts a `#reveal` block: the `#loading` bodies until `revealEnd` show in its order. */
|
|
1890
|
+
revealStart(order, collapsed) {
|
|
1891
|
+
const group = new RevealGroup(order, collapsed);
|
|
1892
|
+
this.reveals.push(group);
|
|
1893
|
+
this.undo.push(() => group.close());
|
|
1894
|
+
}
|
|
1895
|
+
/** Ends the `#reveal` block that `revealStart` started. */
|
|
1896
|
+
revealEnd() {
|
|
1897
|
+
this.reveals.pop()?.close();
|
|
1898
|
+
}
|
|
1899
|
+
/** The group of the `#reveal` block around the next body, when the stream orders it. */
|
|
1900
|
+
get reveal() {
|
|
1901
|
+
return this.root.target ? void 0 : this.reveals.at(-1);
|
|
1902
|
+
}
|
|
1903
|
+
/** True when a `#loading` body that is ready can render in place, as its `#reveal` allows. */
|
|
1904
|
+
mayShow() {
|
|
1905
|
+
return this.reveal?.mayShow() ?? true;
|
|
1906
|
+
}
|
|
1907
|
+
/** Starts the fallback of a `#loading` body, which `collapsed` hides in a template. */
|
|
1908
|
+
fallbackStart(id) {
|
|
1909
|
+
const group = this.reveal;
|
|
1910
|
+
if (!group?.hides()) return "";
|
|
1911
|
+
group.hidden.add(id);
|
|
1912
|
+
return `<template b-f="${id}">`;
|
|
1913
|
+
}
|
|
1914
|
+
/** Ends the fallback that `fallbackStart` started. */
|
|
1915
|
+
fallbackEnd(id) {
|
|
1916
|
+
return this.reveal?.hidden.has(id) ? "</template>" : "";
|
|
1917
|
+
}
|
|
1918
|
+
/**
|
|
1919
|
+
* Starts a `#try` body. A `#loading` body inside it that fails renders the `#catch` body with
|
|
1920
|
+
* `draw`, after the page is sent. The returned function ends the `#try` body.
|
|
1921
|
+
*/
|
|
1922
|
+
catcher(key, draw) {
|
|
1923
|
+
const entry = {
|
|
1924
|
+
key,
|
|
1925
|
+
render: draw
|
|
1926
|
+
};
|
|
1927
|
+
this.catchers.push(entry);
|
|
1928
|
+
return () => removeLast(this.catchers, entry);
|
|
1929
|
+
}
|
|
1305
1930
|
/** Returns the ID of a new `#loading` boundary. */
|
|
1306
1931
|
boundary() {
|
|
1307
1932
|
return spaceId(this.space, this.space.boundary++);
|
|
@@ -1339,13 +1964,26 @@ var Context = class Context {
|
|
|
1339
1964
|
register(id, renderBody, inTarget, around = false) {
|
|
1340
1965
|
const child = new Context(this.root, void 0, 0, `${id}.`);
|
|
1341
1966
|
child.inTarget = inTarget;
|
|
1967
|
+
const catchers = [...this.outer, ...this.catchers];
|
|
1968
|
+
child.outer = catchers;
|
|
1969
|
+
const group = this.reveal;
|
|
1970
|
+
group?.add(id);
|
|
1971
|
+
const end = around ? void 0 : this.traced("body", `#loading ${id}`);
|
|
1342
1972
|
const boundary = {
|
|
1343
1973
|
id,
|
|
1344
|
-
render: renderBody(child).then((html) =>
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1974
|
+
render: renderBody(child).then((html) => {
|
|
1975
|
+
end?.();
|
|
1976
|
+
return {
|
|
1977
|
+
html,
|
|
1978
|
+
ctx: child
|
|
1979
|
+
};
|
|
1980
|
+
}, (error) => {
|
|
1981
|
+
end?.(true);
|
|
1982
|
+
throw error;
|
|
1983
|
+
}),
|
|
1984
|
+
around,
|
|
1985
|
+
group,
|
|
1986
|
+
catchers
|
|
1349
1987
|
};
|
|
1350
1988
|
boundary.render.catch(() => {});
|
|
1351
1989
|
const root = this.root;
|
|
@@ -1377,11 +2015,12 @@ var NotReady = class extends Error {
|
|
|
1377
2015
|
}
|
|
1378
2016
|
};
|
|
1379
2017
|
/** Declares a memo. Its value is computed when it is first read. */
|
|
1380
|
-
function memo(compute, ctx) {
|
|
2018
|
+
function memo(compute, ctx, name) {
|
|
1381
2019
|
return {
|
|
1382
2020
|
compute,
|
|
1383
2021
|
ctx,
|
|
1384
|
-
state: "idle"
|
|
2022
|
+
state: "idle",
|
|
2023
|
+
name
|
|
1385
2024
|
};
|
|
1386
2025
|
}
|
|
1387
2026
|
/**
|
|
@@ -1405,7 +2044,8 @@ function read(node) {
|
|
|
1405
2044
|
}
|
|
1406
2045
|
if (value !== null && typeof value === "object" && (typeof value.then === "function" || isAsyncIterable(value))) {
|
|
1407
2046
|
node.state = "pending";
|
|
1408
|
-
|
|
2047
|
+
const end = node.ctx?.traced("memo", node.name ?? "memo");
|
|
2048
|
+
node.load = Promise.resolve(value).then(firstValue).finally(() => end?.()).then((result) => {
|
|
1409
2049
|
node.state = "done";
|
|
1410
2050
|
node.value = result;
|
|
1411
2051
|
}, (error) => {
|
|
@@ -1453,18 +2093,32 @@ function ready(node) {
|
|
|
1453
2093
|
}
|
|
1454
2094
|
/**
|
|
1455
2095
|
* The value of a memo for the page state: its value when it is ready, or
|
|
1456
|
-
* a promise of it while it loads. A memo that fails gives a
|
|
1457
|
-
*
|
|
1458
|
-
* browser
|
|
2096
|
+
* a promise of it while it loads. A memo that fails gives a `MemoError`
|
|
2097
|
+
* either way, so the page renders, the stream goes on, and a read in the
|
|
2098
|
+
* browser throws the error as a memo that failed there.
|
|
1459
2099
|
*/
|
|
1460
2100
|
function stateValue(node) {
|
|
1461
2101
|
try {
|
|
1462
2102
|
return read(node);
|
|
1463
2103
|
} catch (error) {
|
|
1464
|
-
|
|
2104
|
+
if (error instanceof NotReady) return wait(node).catch((failure) => heldError(failure, node.ctx));
|
|
2105
|
+
return heldError(error, node.ctx);
|
|
1465
2106
|
}
|
|
1466
2107
|
}
|
|
1467
2108
|
/**
|
|
2109
|
+
* The error of a memo for the page state. In development it is the error as seroval
|
|
2110
|
+
* writes it: its name, message, own properties, `cause` and the `errors` of an `AggregateError`,
|
|
2111
|
+
* and no stack (the serial options leave stacks out). In production it is the message of
|
|
2112
|
+
* a `ServerError`, which the app chose to show, or else a generic message, and the error is
|
|
2113
|
+
* logged, as for a server function that fails.
|
|
2114
|
+
*/
|
|
2115
|
+
function heldError(error, ctx) {
|
|
2116
|
+
let sent;
|
|
2117
|
+
if (ctx?.isDev()) sent = error instanceof Error ? error : new Error(String(error));
|
|
2118
|
+
else sent = safeError(error, "The page could not compute a value");
|
|
2119
|
+
return Object.assign(new MemoError(sent), { [Symbol.for("brumate.held")]: true });
|
|
2120
|
+
}
|
|
2121
|
+
/**
|
|
1468
2122
|
* Starts every memo of a run of declarations that the render waits for,
|
|
1469
2123
|
* so they load at the same time. Returns a promise that settles when all
|
|
1470
2124
|
* of them have, or undefined when none is loading. A memo that fails
|
|
@@ -1500,8 +2154,8 @@ const LAZY = Symbol.for("brumate.lazy");
|
|
|
1500
2154
|
* them, so they read the contexts that the component provides. `from` is the
|
|
1501
2155
|
* scope of the markup that wrote them.
|
|
1502
2156
|
*/
|
|
1503
|
-
function children(from, renderBody) {
|
|
1504
|
-
return new Children(from, renderBody);
|
|
2157
|
+
function children(from, renderBody, ref) {
|
|
2158
|
+
return new Children(from, renderBody, ref);
|
|
1505
2159
|
}
|
|
1506
2160
|
/** The symbol of raw HTML. See `html.ts`. */
|
|
1507
2161
|
const RAW = Symbol.for("brumate.raw");
|
|
@@ -1515,14 +2169,32 @@ var Children = class {
|
|
|
1515
2169
|
[LAZY];
|
|
1516
2170
|
/** The HTML of the first render, under the symbol of raw HTML. */
|
|
1517
2171
|
[RAW];
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
2172
|
+
/**
|
|
2173
|
+
* The export that renders the children in the browser, which the page state sends in place of
|
|
2174
|
+
* their HTML. Each insert in the browser then renders them with new scopes.
|
|
2175
|
+
*/
|
|
2176
|
+
[CHILDREN_REF];
|
|
2177
|
+
constructor(from, renderBody, ref) {
|
|
2178
|
+
if (ref !== void 0) this[CHILDREN_REF] = new ChildrenReference(ref, from);
|
|
2179
|
+
this[LAZY] = async (ctx, at, tag, anchor) => {
|
|
2180
|
+
const reference = this[CHILDREN_REF];
|
|
2181
|
+
if (reference && reference.at === void 0 && anchor !== void 0) {
|
|
2182
|
+
reference.at = at;
|
|
2183
|
+
reference.anchor = anchor;
|
|
2184
|
+
}
|
|
2185
|
+
const html = await (at === void 0 ? renderBody(ctx) : ctx.children(from, at, () => renderBody(ctx), tag));
|
|
2186
|
+
if (ref === void 0) this[RAW] ??= html;
|
|
1522
2187
|
return html;
|
|
1523
2188
|
};
|
|
1524
2189
|
}
|
|
1525
2190
|
};
|
|
2191
|
+
/**
|
|
2192
|
+
* The tag of the spacers of a windowed list in children: a row in a table body, an item in a
|
|
2193
|
+
* list, as the element where the children are inserted says, or else a `div`.
|
|
2194
|
+
*/
|
|
2195
|
+
function spacerTag(ctx) {
|
|
2196
|
+
return ctx.spacerTag();
|
|
2197
|
+
}
|
|
1526
2198
|
/** Makes markup that renders where it is inserted, such as the children of a layout. */
|
|
1527
2199
|
function lazy(renderAt) {
|
|
1528
2200
|
return { [LAZY]: renderAt };
|
|
@@ -1532,7 +2204,12 @@ function isLazy(value) {
|
|
|
1532
2204
|
}
|
|
1533
2205
|
/** Renders the attributes of a form or button that posts to a server function. */
|
|
1534
2206
|
function action(ctx, name, id, method, result) {
|
|
1535
|
-
|
|
2207
|
+
let key;
|
|
2208
|
+
if (idempotentIds.has(id)) {
|
|
2209
|
+
key = crypto.randomUUID();
|
|
2210
|
+
ctx.personal();
|
|
2211
|
+
}
|
|
2212
|
+
return actionAttributes(ctx.rpc(), name, id, method, result, ctx.buildId(), key);
|
|
1536
2213
|
}
|
|
1537
2214
|
/**
|
|
1538
2215
|
* The result of a server function that a form posted to this page, for
|
|
@@ -1542,15 +2219,21 @@ function actionResult(ctx, fn) {
|
|
|
1542
2219
|
return ctx.actionResult(fn);
|
|
1543
2220
|
}
|
|
1544
2221
|
/**
|
|
1545
|
-
* Renders a value inserted in markup. `ctx` and `
|
|
1546
|
-
* inserted, for markup that renders there.
|
|
2222
|
+
* Renders a value inserted in markup. `ctx`, `scope` and `anchor` are where it
|
|
2223
|
+
* is inserted, for markup that renders there.
|
|
1547
2224
|
*/
|
|
1548
|
-
function insert(value, ctx, scope) {
|
|
1549
|
-
if (value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function") return Promise.resolve(value).then((resolved) => insert(resolved, ctx, scope));
|
|
1550
|
-
if (isLazy(value) && ctx) return value[LAZY](ctx, scope);
|
|
2225
|
+
function insert(value, ctx, scope, tag, anchor) {
|
|
2226
|
+
if (value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function") return Promise.resolve(value).then((resolved) => insert(resolved, ctx, scope, tag, anchor));
|
|
2227
|
+
if (isLazy(value) && ctx) return value[LAZY](ctx, scope, tag, anchor);
|
|
1551
2228
|
if (Array.isArray(value)) {
|
|
1552
|
-
const parts =
|
|
1553
|
-
|
|
2229
|
+
const parts = [];
|
|
2230
|
+
let allStrings = true;
|
|
2231
|
+
for (const item of value) {
|
|
2232
|
+
const part = insert(item, ctx, scope, tag);
|
|
2233
|
+
if (typeof part !== "string") allStrings = false;
|
|
2234
|
+
parts.push(part);
|
|
2235
|
+
}
|
|
2236
|
+
return allStrings ? parts.join("") : Promise.all(parts).then((all) => all.join(""));
|
|
1554
2237
|
}
|
|
1555
2238
|
return insertValue(value);
|
|
1556
2239
|
}
|
|
@@ -1558,30 +2241,48 @@ function insert(value, ctx, scope) {
|
|
|
1558
2241
|
* Renders a child component. With `scope` and `anchor`, records the child's
|
|
1559
2242
|
* scope so the parent can update its props on the client.
|
|
1560
2243
|
*/
|
|
1561
|
-
function component(Child, props, ctx, scope, anchor) {
|
|
2244
|
+
function component(Child, props, ctx, scope, anchor, paragraph) {
|
|
1562
2245
|
if (ctx.past()) return Promise.resolve("");
|
|
1563
2246
|
if (scope !== void 0 && anchor !== void 0) ctx.link(scope, anchor, ctx.peek());
|
|
1564
2247
|
if (scope !== void 0) ctx.own(scope);
|
|
1565
2248
|
const given = props?.children;
|
|
1566
|
-
if (!(given instanceof Children)) return Child(props, ctx);
|
|
2249
|
+
if (!(given instanceof Children) || given[CHILDREN_REF]) return checkParagraph(Child(props, ctx), ctx, paragraph);
|
|
1567
2250
|
const root = ctx.peek();
|
|
1568
|
-
return Child(props, ctx).then(async (html) => {
|
|
2251
|
+
return checkParagraph(Child(props, ctx).then(async (html) => {
|
|
1569
2252
|
if (given[RAW] === void 0) await given[LAZY](ctx, root);
|
|
1570
2253
|
return html;
|
|
2254
|
+
}), ctx, paragraph);
|
|
2255
|
+
}
|
|
2256
|
+
/**
|
|
2257
|
+
* In development, throws when a component inside a `<p>` starts with an element that closes the
|
|
2258
|
+
* `<p>`. `paragraph` names the component and where it is, and only the compiler sets it. The
|
|
2259
|
+
* browser splits the markers of the blocks of the page there, so it is an error before that.
|
|
2260
|
+
*/
|
|
2261
|
+
function checkParagraph(rendered, ctx, paragraph) {
|
|
2262
|
+
if (paragraph === void 0 || !ctx.isDev()) return rendered;
|
|
2263
|
+
return rendered.then((html) => {
|
|
2264
|
+
const tag = typeof html === "string" ? firstTag(html) : void 0;
|
|
2265
|
+
if (tag !== void 0 && closesParagraph(tag)) throw new Error(`${paragraph} renders <${tag}>, which the HTML parser does not keep inside a <p>: it closes the <p> and splits the markers of the page [BRM185]. Move the component out of the <p>, or make it render a <span>, as with as="span"`);
|
|
2266
|
+
return html;
|
|
1571
2267
|
});
|
|
1572
2268
|
}
|
|
1573
2269
|
/** Renders a dynamic tag, which can be an element name or a component. */
|
|
1574
|
-
function dynamic(tag, attributes, content, ctx, scope) {
|
|
2270
|
+
function dynamic(tag, attributes, content, ctx, scope, ref) {
|
|
1575
2271
|
if (typeof tag === "function") {
|
|
1576
|
-
|
|
1577
|
-
const props = typeof entries === "string" && scope !== void 0 ? {
|
|
2272
|
+
if (ref !== void 0) attributes = {
|
|
1578
2273
|
...attributes,
|
|
1579
|
-
|
|
1580
|
-
}
|
|
2274
|
+
ref
|
|
2275
|
+
};
|
|
2276
|
+
const { "b-b": bound, "b-on": entries, ...passed } = attributes;
|
|
2277
|
+
addEntryHandlers(passed, entries, scope, (reference) => {
|
|
2278
|
+
const handler = Object.assign(() => {}, reference.modifiers ? { [MODIFIERS]: reference.modifiers } : {});
|
|
2279
|
+
functionReferences.set(handler, reference);
|
|
2280
|
+
return handler;
|
|
2281
|
+
});
|
|
1581
2282
|
return component(tag, content ? {
|
|
1582
|
-
...
|
|
2283
|
+
...passed,
|
|
1583
2284
|
children: content
|
|
1584
|
-
} :
|
|
2285
|
+
} : passed, ctx, scope, bound === void 0 ? void 0 : Number(ownValue("b-b", bound).split(":")[1]));
|
|
1585
2286
|
}
|
|
1586
2287
|
const on = [];
|
|
1587
2288
|
const open = `<${tag}${spread(attributes, on)}${onAttribute(on, "")}>`;
|
|
@@ -1594,7 +2295,12 @@ function holds(value, target, seen = /* @__PURE__ */ new Set()) {
|
|
|
1594
2295
|
if (value === target) return true;
|
|
1595
2296
|
if (typeof value !== "object" || value === null || seen.has(value)) return false;
|
|
1596
2297
|
seen.add(value);
|
|
1597
|
-
|
|
2298
|
+
let items = [];
|
|
2299
|
+
if (value instanceof Map) items = [...value.keys(), ...value.values()];
|
|
2300
|
+
else if (value instanceof Set) items = [...value];
|
|
2301
|
+
else if (Array.isArray(value) || Object.getPrototypeOf(value) === Object.prototype) items = Object.values(value);
|
|
2302
|
+
for (const item of items) if (holds(item, target, seen)) return true;
|
|
2303
|
+
return false;
|
|
1598
2304
|
}
|
|
1599
2305
|
/**
|
|
1600
2306
|
* The error of a value in the state of a page that cannot be sent to the
|
|
@@ -1605,7 +2311,11 @@ function unsendable(error, ctx) {
|
|
|
1605
2311
|
const target = secret ?? error.value;
|
|
1606
2312
|
if (target === void 0) return error instanceof Error ? error : new Error(String(error));
|
|
1607
2313
|
for (const { record, names } of ctx.scopes) {
|
|
1608
|
-
|
|
2314
|
+
let index = -1;
|
|
2315
|
+
for (const [slot, value] of (record.s ?? []).entries()) if (holds(value, target)) {
|
|
2316
|
+
index = slot;
|
|
2317
|
+
break;
|
|
2318
|
+
}
|
|
1609
2319
|
if (index === -1) continue;
|
|
1610
2320
|
let owner = record;
|
|
1611
2321
|
while (owner && owner.m === void 0 && owner.p !== void 0) owner = ctx.ownRecord(owner.p);
|
|
@@ -1653,6 +2363,11 @@ const PACKED_FIELDS = /* @__PURE__ */ new Set([
|
|
|
1653
2363
|
"i",
|
|
1654
2364
|
"c"
|
|
1655
2365
|
]);
|
|
2366
|
+
/** True when a record has a field that `PackedState` has no place for. */
|
|
2367
|
+
function hasUnpackedField(record) {
|
|
2368
|
+
for (const field of Object.keys(record)) if (!PACKED_FIELDS.has(field)) return true;
|
|
2369
|
+
return false;
|
|
2370
|
+
}
|
|
1656
2371
|
/** A group of `PackedState` while `packState` collects it. */
|
|
1657
2372
|
/** How many of the last groups `packState` compares a record with, before it looks up its name. */
|
|
1658
2373
|
const RECENT_GROUPS = 4;
|
|
@@ -1665,7 +2380,9 @@ function splitId(id) {
|
|
|
1665
2380
|
/** The records of a state as a map, for a state written as an object, such as in tests. */
|
|
1666
2381
|
function toStateMap(state) {
|
|
1667
2382
|
if (state instanceof Map) return state;
|
|
1668
|
-
|
|
2383
|
+
const map = /* @__PURE__ */ new Map();
|
|
2384
|
+
for (const [key, record] of Object.entries(state)) map.set(parseId(key), record);
|
|
2385
|
+
return map;
|
|
1669
2386
|
}
|
|
1670
2387
|
/**
|
|
1671
2388
|
* Visits the scopes of a state in the order of the keys of an object: number
|
|
@@ -1678,7 +2395,9 @@ function visitOrdered(entries, visit) {
|
|
|
1678
2395
|
let last = -Infinity;
|
|
1679
2396
|
for (const entry of entries) if (typeof entry.id === "number") {
|
|
1680
2397
|
if (entry.id < last) {
|
|
1681
|
-
|
|
2398
|
+
const numeric = [];
|
|
2399
|
+
for (const item of entries) if (typeof item.id === "number") numeric.push(item);
|
|
2400
|
+
numbers = numeric.toSorted((a, b) => a.id - b.id);
|
|
1682
2401
|
break;
|
|
1683
2402
|
}
|
|
1684
2403
|
last = entry.id;
|
|
@@ -1698,8 +2417,8 @@ function groupSource(record, group) {
|
|
|
1698
2417
|
const source = entries[0].source;
|
|
1699
2418
|
if (!source || !(group.flags & 3)) return;
|
|
1700
2419
|
const value = record(source[0])?.s?.[source[1]];
|
|
1701
|
-
const list =
|
|
1702
|
-
if (!list || list.length < entries.length) return;
|
|
2420
|
+
const list = value instanceof Set ? Array.from(value) : value;
|
|
2421
|
+
if (!Array.isArray(list) || list.length < entries.length) return;
|
|
1703
2422
|
for (let n = 0; n < entries.length; n++) {
|
|
1704
2423
|
const entry = entries[n];
|
|
1705
2424
|
if (entry.source !== source || !Object.is(list[n], entry.record.i)) return;
|
|
@@ -1714,17 +2433,19 @@ function groupSource(record, group) {
|
|
|
1714
2433
|
*/
|
|
1715
2434
|
function packState(input, sources) {
|
|
1716
2435
|
const state = toStateMap(input);
|
|
1717
|
-
|
|
2436
|
+
const entries = [];
|
|
2437
|
+
for (const [id, record] of state) {
|
|
1718
2438
|
const [prefix, n] = splitId(id);
|
|
1719
|
-
|
|
2439
|
+
entries.push({
|
|
1720
2440
|
id,
|
|
1721
2441
|
prefix,
|
|
1722
2442
|
n,
|
|
1723
2443
|
record,
|
|
1724
2444
|
ctx: void 0,
|
|
1725
2445
|
source: sources?.get(id)
|
|
1726
|
-
};
|
|
1727
|
-
}
|
|
2446
|
+
});
|
|
2447
|
+
}
|
|
2448
|
+
return packEntries(entries, (id) => state.get(id));
|
|
1728
2449
|
}
|
|
1729
2450
|
/** Packs the scopes of a render. `lookup` finds the record of a scope in the same state. */
|
|
1730
2451
|
function packEntries(scopes, lookup) {
|
|
@@ -1738,7 +2459,7 @@ function packEntries(scopes, lookup) {
|
|
|
1738
2459
|
const [ownerPrefix, owner] = splitId(record.o);
|
|
1739
2460
|
base = ownerPrefix === prefix ? n - owner : void 0;
|
|
1740
2461
|
}
|
|
1741
|
-
if (record.k === void 0 || base === void 0 || record.p !== void 0 && record.o !== void 0 ||
|
|
2462
|
+
if (record.k === void 0 || base === void 0 || record.p !== void 0 && record.o !== void 0 || hasUnpackedField(record)) {
|
|
1742
2463
|
result[id] = record;
|
|
1743
2464
|
return;
|
|
1744
2465
|
}
|
|
@@ -1747,7 +2468,11 @@ function packEntries(scopes, lookup) {
|
|
|
1747
2468
|
if ("i" in record) flags |= slots.length > 0 && Object.is(record.i, slots[0]) ? 1 : 2;
|
|
1748
2469
|
if (record.c) flags |= 4;
|
|
1749
2470
|
if (record.m !== void 0) flags |= 16;
|
|
1750
|
-
let group
|
|
2471
|
+
let group;
|
|
2472
|
+
for (const item of recent) if (item.k === record.k && item.base === base && item.flags === flags && item.count === slots.length && item.m === record.m && item.prefix === prefix) {
|
|
2473
|
+
group = item;
|
|
2474
|
+
break;
|
|
2475
|
+
}
|
|
1751
2476
|
if (!group) {
|
|
1752
2477
|
const name = `${prefix}:${record.k}:${base}:${flags}:${slots.length}:${record.m ?? ""}`;
|
|
1753
2478
|
group = groups.get(name);
|
|
@@ -1816,19 +2541,19 @@ function packEntries(scopes, lookup) {
|
|
|
1816
2541
|
function serializeState(state, refs, onRecord, onError, onDone, sources, last = false) {
|
|
1817
2542
|
const packed = state instanceof Context ? packEntries(state.scopes, (id) => state.ownRecord(id)) : packState(state, sources);
|
|
1818
2543
|
let leaked = false;
|
|
1819
|
-
|
|
2544
|
+
function send(code, initial) {
|
|
1820
2545
|
const error = leaked ? void 0 : secretError(code);
|
|
1821
2546
|
if (error) {
|
|
1822
2547
|
leaked = true;
|
|
1823
2548
|
onError(error);
|
|
1824
2549
|
} else if (!leaked) onRecord(code, initial);
|
|
1825
|
-
}
|
|
2550
|
+
}
|
|
1826
2551
|
if (last) {
|
|
1827
2552
|
let code;
|
|
1828
2553
|
try {
|
|
1829
2554
|
code = crossSerialize(packed, {
|
|
1830
2555
|
plugins: syncPlugins,
|
|
1831
|
-
|
|
2556
|
+
...serialOptions(),
|
|
1832
2557
|
refs,
|
|
1833
2558
|
assignSharedRefsOnly: true
|
|
1834
2559
|
});
|
|
@@ -1843,7 +2568,7 @@ function serializeState(state, refs, onRecord, onError, onDone, sources, last =
|
|
|
1843
2568
|
}
|
|
1844
2569
|
crossSerializeStream(packed, {
|
|
1845
2570
|
plugins,
|
|
1846
|
-
|
|
2571
|
+
...serialOptions(),
|
|
1847
2572
|
refs,
|
|
1848
2573
|
onSerialize: send,
|
|
1849
2574
|
onError,
|
|
@@ -1883,10 +2608,39 @@ function stateScript(code, scopes = false, attributes = {}) {
|
|
|
1883
2608
|
if (attributes.route !== void 0) extra += ` b-route="${escapeAttribute(attributes.route)}"`;
|
|
1884
2609
|
if (attributes.params !== void 0) extra += ` b-params="${escapeAttribute(JSON.stringify(attributes.params))}"`;
|
|
1885
2610
|
if (attributes.build !== void 0) extra += ` b-build="${escapeAttribute(attributes.build)}"`;
|
|
2611
|
+
if (attributes.fail !== void 0) extra += ` b-fail="${attributes.fail}"`;
|
|
2612
|
+
if (attributes.catches !== void 0) extra += ` b-catch="${attributes.catches}"`;
|
|
1886
2613
|
return `<script${extra}>${attributes.define ? RECORD : ""}$bR(($R,$b)=>(${code}))<\/script>`;
|
|
1887
2614
|
}
|
|
1888
2615
|
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)}`;
|
|
2616
|
+
const SHOW_FALLBACK = `function $bF(i){var t=document.querySelector('template[b-f="'+i+'"]');t&&t.replaceWith(t.content)}`;
|
|
1889
2617
|
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()}`;
|
|
2618
|
+
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()}`;
|
|
2619
|
+
/**
|
|
2620
|
+
* The record that tells the browser a `#loading` body failed. Its code is the error, and the
|
|
2621
|
+
* browser hands it to the nearest `#try` around the boundary.
|
|
2622
|
+
*/
|
|
2623
|
+
function failScript(error, refs, boundary, root, nonce) {
|
|
2624
|
+
let code;
|
|
2625
|
+
try {
|
|
2626
|
+
code = crossSerialize(error, {
|
|
2627
|
+
plugins: syncPlugins,
|
|
2628
|
+
...serialOptions(),
|
|
2629
|
+
refs
|
|
2630
|
+
});
|
|
2631
|
+
} catch {
|
|
2632
|
+
code = crossSerialize(new Error(String(error)), {
|
|
2633
|
+
plugins: syncPlugins,
|
|
2634
|
+
...serialOptions(),
|
|
2635
|
+
refs
|
|
2636
|
+
});
|
|
2637
|
+
}
|
|
2638
|
+
return stateScript(code, false, {
|
|
2639
|
+
root,
|
|
2640
|
+
nonce,
|
|
2641
|
+
fail: boundary
|
|
2642
|
+
});
|
|
2643
|
+
}
|
|
1890
2644
|
/** The `pending` of a render that has nothing left to send. */
|
|
1891
2645
|
const NOTHING_PENDING = { [Symbol.asyncIterator]: () => ({ next: () => Promise.resolve({
|
|
1892
2646
|
done: true,
|
|
@@ -1898,10 +2652,10 @@ function createQueue() {
|
|
|
1898
2652
|
let wake;
|
|
1899
2653
|
let closed = false;
|
|
1900
2654
|
let failure;
|
|
1901
|
-
|
|
2655
|
+
function notify() {
|
|
1902
2656
|
wake?.();
|
|
1903
2657
|
wake = void 0;
|
|
1904
|
-
}
|
|
2658
|
+
}
|
|
1905
2659
|
return {
|
|
1906
2660
|
push(item) {
|
|
1907
2661
|
items.push(item);
|
|
@@ -1938,6 +2692,7 @@ async function render(Root, props, options = {}) {
|
|
|
1938
2692
|
if (options.actions) ctx.actions = options.actions;
|
|
1939
2693
|
if (options.params) ctx.params = options.params;
|
|
1940
2694
|
ctx.build = options.build;
|
|
2695
|
+
ctx.development = options.dev === true;
|
|
1941
2696
|
if (options.defer) ctx.target = { ...options.defer };
|
|
1942
2697
|
ctx.inOrder = !options.defer && rendersInOrder(options.inOrder ?? "bots", options.request ?? options.event?.request);
|
|
1943
2698
|
const event = options.event ?? (options.request ? new RequestEvent(options.request, {
|
|
@@ -1951,7 +2706,9 @@ async function render(Root, props, options = {}) {
|
|
|
1951
2706
|
ctx.send();
|
|
1952
2707
|
const html = beforeBodyEnd(rendered, ctx.portals.join(""));
|
|
1953
2708
|
let queue;
|
|
1954
|
-
|
|
2709
|
+
function pending() {
|
|
2710
|
+
return queue ??= createQueue();
|
|
2711
|
+
}
|
|
1955
2712
|
const refs = /* @__PURE__ */ new Map();
|
|
1956
2713
|
const { nonce } = options;
|
|
1957
2714
|
const root = options.defer ? `d${options.defer.boundary}` : options.base;
|
|
@@ -1959,12 +2716,19 @@ async function render(Root, props, options = {}) {
|
|
|
1959
2716
|
let open = 0;
|
|
1960
2717
|
let swap = false;
|
|
1961
2718
|
let headSwap = false;
|
|
1962
|
-
|
|
2719
|
+
function finish() {
|
|
1963
2720
|
open--;
|
|
1964
2721
|
if (open === 0) queue?.close();
|
|
1965
|
-
}
|
|
2722
|
+
}
|
|
1966
2723
|
let boundaries = 0;
|
|
1967
|
-
const
|
|
2724
|
+
const swapScript = options.dev ? SWAP_DEV : SWAP;
|
|
2725
|
+
let fallbackDefined = false;
|
|
2726
|
+
function showFallback() {
|
|
2727
|
+
if (fallbackDefined) return "";
|
|
2728
|
+
fallbackDefined = true;
|
|
2729
|
+
return `${SHOW_FALLBACK};`;
|
|
2730
|
+
}
|
|
2731
|
+
function serialize(target, onScopes, route, onError = (error) => pending().fail(unsendable(error, target)), last = false) {
|
|
1968
2732
|
open++;
|
|
1969
2733
|
serializeState(target, refs, (code, initial) => {
|
|
1970
2734
|
if (initial) {
|
|
@@ -1983,9 +2747,27 @@ async function render(Root, props, options = {}) {
|
|
|
1983
2747
|
nonce
|
|
1984
2748
|
}));
|
|
1985
2749
|
}, onError, finish, void 0, last);
|
|
1986
|
-
}
|
|
2750
|
+
}
|
|
2751
|
+
async function renderCatch(boundary, error) {
|
|
2752
|
+
const entry = boundary.catchers.at(-1);
|
|
2753
|
+
if (!entry) return;
|
|
2754
|
+
const child = new Context(ctx, void 0, 0, `${boundary.id}c.`);
|
|
2755
|
+
child.outer = boundary.catchers.slice(0, -1);
|
|
2756
|
+
try {
|
|
2757
|
+
return {
|
|
2758
|
+
html: await entry.render(child, error),
|
|
2759
|
+
ctx: child,
|
|
2760
|
+
key: entry.key
|
|
2761
|
+
};
|
|
2762
|
+
} catch (failure) {
|
|
2763
|
+
console.error(failure);
|
|
2764
|
+
return;
|
|
2765
|
+
}
|
|
2766
|
+
}
|
|
1987
2767
|
const inOrder = ctx.inOrder ? [] : void 0;
|
|
1988
|
-
|
|
2768
|
+
function stopped() {
|
|
2769
|
+
return event?.signal.aborted === true;
|
|
2770
|
+
}
|
|
1989
2771
|
event?.signal.addEventListener("abort", () => queue?.close(), { once: true });
|
|
1990
2772
|
ctx.watch((boundary) => {
|
|
1991
2773
|
if (inOrder) {
|
|
@@ -1994,29 +2776,61 @@ async function render(Root, props, options = {}) {
|
|
|
1994
2776
|
}
|
|
1995
2777
|
boundaries++;
|
|
1996
2778
|
open++;
|
|
2779
|
+
function skip(after) {
|
|
2780
|
+
if (after) pending().push(`${scriptTag}${showFallback()}${after}<\/script>`);
|
|
2781
|
+
finish();
|
|
2782
|
+
}
|
|
2783
|
+
function turn(send) {
|
|
2784
|
+
if (boundary.group) boundary.group.ready(boundary.id, send);
|
|
2785
|
+
else send("");
|
|
2786
|
+
}
|
|
1997
2787
|
boundary.render.then((result) => {
|
|
1998
2788
|
if (boundary.cancelled || boundary.around || stopped()) {
|
|
1999
|
-
|
|
2789
|
+
turn(skip);
|
|
2000
2790
|
return;
|
|
2001
2791
|
}
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
head =
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
2792
|
+
turn((after) => {
|
|
2793
|
+
serialize(result.ctx, (script) => {
|
|
2794
|
+
const id = scriptJSON(boundary.id);
|
|
2795
|
+
let call = `${swap ? "" : swapScript}$bS(${id})`;
|
|
2796
|
+
swap = true;
|
|
2797
|
+
if (after) call += `;${showFallback()}${after}`;
|
|
2798
|
+
const late = result.ctx.lateHead();
|
|
2799
|
+
let head = "";
|
|
2800
|
+
if (late.html || late.title !== void 0) {
|
|
2801
|
+
head = `<template b-h="${boundary.id}">${late.html}</template>`;
|
|
2802
|
+
const title = late.title === void 0 ? "" : `,${scriptJSON(late.title)}`;
|
|
2803
|
+
call += `;${headSwap ? "" : HEAD}$bH(${id}${title})`;
|
|
2804
|
+
headSwap = true;
|
|
2805
|
+
}
|
|
2806
|
+
pending().push(`<template b-l="${boundary.id}">${result.html}</template>${head}${result.ctx.portals.join("")}${scriptTag}${call}<\/script>${script}`);
|
|
2807
|
+
});
|
|
2808
|
+
finish();
|
|
2015
2809
|
});
|
|
2016
|
-
finish();
|
|
2017
2810
|
}, (error) => {
|
|
2018
|
-
|
|
2019
|
-
|
|
2811
|
+
if (boundary.cancelled || boundary.around || stopped()) {
|
|
2812
|
+
console.error(error);
|
|
2813
|
+
turn(skip);
|
|
2814
|
+
return;
|
|
2815
|
+
}
|
|
2816
|
+
turn((after) => {
|
|
2817
|
+
if (ctx.isDev()) console.error(error);
|
|
2818
|
+
renderCatch(boundary, error).then((result) => {
|
|
2819
|
+
if (!result) {
|
|
2820
|
+
pending().push(failScript(caught(error, ctx), refs, boundary.id, root, nonce));
|
|
2821
|
+
skip(after);
|
|
2822
|
+
return;
|
|
2823
|
+
}
|
|
2824
|
+
serialize(result.ctx, (script) => {
|
|
2825
|
+
pending().push(`<template b-c="${result.key}">${result.html}</template>${result.ctx.portals.join("")}${stateScript("0", false, {
|
|
2826
|
+
root,
|
|
2827
|
+
nonce,
|
|
2828
|
+
catches: result.key
|
|
2829
|
+
})}${script}`);
|
|
2830
|
+
});
|
|
2831
|
+
skip(after);
|
|
2832
|
+
});
|
|
2833
|
+
});
|
|
2020
2834
|
});
|
|
2021
2835
|
});
|
|
2022
2836
|
if (options.defer) return {
|
|
@@ -2041,13 +2855,28 @@ async function render(Root, props, options = {}) {
|
|
|
2041
2855
|
if (inOrder) {
|
|
2042
2856
|
const bodies = /* @__PURE__ */ new Map();
|
|
2043
2857
|
const portals = [];
|
|
2858
|
+
const catches = [];
|
|
2044
2859
|
for (let index = 0; index < inOrder.length; index++) {
|
|
2045
2860
|
const boundary = inOrder[index];
|
|
2046
2861
|
let result;
|
|
2047
2862
|
try {
|
|
2048
2863
|
result = await boundary.render;
|
|
2049
2864
|
} catch (error) {
|
|
2050
|
-
|
|
2865
|
+
if (boundary.cancelled || boundary.around) continue;
|
|
2866
|
+
if (ctx.isDev()) console.error(error);
|
|
2867
|
+
const replacement = await renderCatch(boundary, error);
|
|
2868
|
+
if (!replacement) {
|
|
2869
|
+
console.error(error);
|
|
2870
|
+
continue;
|
|
2871
|
+
}
|
|
2872
|
+
catches.push([replacement.key, replacement.html]);
|
|
2873
|
+
portals.push(...replacement.ctx.portals);
|
|
2874
|
+
serialize(replacement.ctx, (script) => {
|
|
2875
|
+
state += script;
|
|
2876
|
+
}, void 0, (failed) => {
|
|
2877
|
+
failure = failed;
|
|
2878
|
+
});
|
|
2879
|
+
if (failure !== void 0) throw unsendable(failure, replacement.ctx);
|
|
2051
2880
|
continue;
|
|
2052
2881
|
}
|
|
2053
2882
|
if (boundary.cancelled || boundary.around) continue;
|
|
@@ -2061,7 +2890,9 @@ async function render(Root, props, options = {}) {
|
|
|
2061
2890
|
}, index === inOrder.length - 1);
|
|
2062
2891
|
if (failure !== void 0) throw unsendable(failure, result.ctx);
|
|
2063
2892
|
}
|
|
2064
|
-
|
|
2893
|
+
let shell = rendered;
|
|
2894
|
+
for (const [key, catchHTML] of catches) shell = replaceBlock(shell, key, catchHTML);
|
|
2895
|
+
page = beforeBodyEnd(inlineBodies(shell, bodies), [...ctx.portals, ...portals].join(""));
|
|
2065
2896
|
}
|
|
2066
2897
|
return {
|
|
2067
2898
|
html: page,
|
|
@@ -2083,6 +2914,26 @@ function rendersInOrder(option, request) {
|
|
|
2083
2914
|
if (typeof option === "function") return option(request);
|
|
2084
2915
|
return BOTS.test(request.headers.get("user-agent") ?? "");
|
|
2085
2916
|
}
|
|
2917
|
+
/**
|
|
2918
|
+
* Replaces what a block holds, between its markers, with other markup. `key` is the scope and
|
|
2919
|
+
* the anchor in the start marker. A page without the block stays as it is.
|
|
2920
|
+
*/
|
|
2921
|
+
function replaceBlock(html, key, inner) {
|
|
2922
|
+
const open = `<!--b${key}-->`;
|
|
2923
|
+
const start = html.indexOf(open);
|
|
2924
|
+
if (start === -1) return html;
|
|
2925
|
+
const comments = /<!--([^>]*?)-->/g;
|
|
2926
|
+
comments.lastIndex = start + open.length;
|
|
2927
|
+
let depth = 0;
|
|
2928
|
+
for (let found = comments.exec(html); found; found = comments.exec(html)) {
|
|
2929
|
+
const data = found[1];
|
|
2930
|
+
if (data[0] === "/") {
|
|
2931
|
+
if (depth === 0) return html.slice(0, start + open.length) + inner + html.slice(found.index);
|
|
2932
|
+
depth--;
|
|
2933
|
+
} else if (/^[btilP]-?\d/.test(data)) depth++;
|
|
2934
|
+
}
|
|
2935
|
+
return html;
|
|
2936
|
+
}
|
|
2086
2937
|
const BOUNDARY_MARKER = /<!--(l[\d.]+|\/l)-->/g;
|
|
2087
2938
|
/**
|
|
2088
2939
|
* Puts the bodies of boundaries in place of their fallbacks, with the bodies
|
|
@@ -2116,6 +2967,25 @@ function inlineBodies(html, bodies) {
|
|
|
2116
2967
|
return result + html.slice(position);
|
|
2117
2968
|
}
|
|
2118
2969
|
const HTML = /<html[\s>]/i;
|
|
2970
|
+
const HTML_TAG = /^<html((?:"[^"]*"|'[^']*'|[^>"'])*)>/i;
|
|
2971
|
+
const ATTRIBUTE_NAME = /([^\s"'<>/=]+)(?:=(?:"[^"]*"|'[^']*'|[^\s"'>]+))?/g;
|
|
2972
|
+
/**
|
|
2973
|
+
* Adds `b-html` to the `<html>` tag, with the names of the attributes that the page sent, so
|
|
2974
|
+
* client navigation can tell them from those that a script sets.
|
|
2975
|
+
*/
|
|
2976
|
+
function nameHtmlAttributes(page) {
|
|
2977
|
+
const tag = HTML_TAG.exec(page);
|
|
2978
|
+
if (!tag) return page;
|
|
2979
|
+
const names = [];
|
|
2980
|
+
const attributes = tag[1].replace(ATTRIBUTE_NAME, (text, name) => {
|
|
2981
|
+
if (name.toLowerCase() === "b-html") return "";
|
|
2982
|
+
names.push(name);
|
|
2983
|
+
return text;
|
|
2984
|
+
});
|
|
2985
|
+
if (attributes === tag[1] && names.length === 0) return page;
|
|
2986
|
+
const list = names.length > 0 ? ` b-html="${escapeAttribute(names.join(" "))}"` : "";
|
|
2987
|
+
return `${page.slice(0, 5)}${attributes.trimEnd()}${list}>${page.slice(tag[0].length)}`;
|
|
2988
|
+
}
|
|
2119
2989
|
/**
|
|
2120
2990
|
* Inserts markup before `</body>`, or at the end if there is none. `index`
|
|
2121
2991
|
* is where `</body>` is, when the caller found it already.
|
|
@@ -2136,7 +3006,7 @@ function firstRender(html, componentHead, state, options) {
|
|
|
2136
3006
|
const match = HTML.exec(html);
|
|
2137
3007
|
if (!match) return (typeof options.start === "function" ? options.start(head) : options.start ?? "") + html + tail + (options.end ?? "");
|
|
2138
3008
|
const headContent = html.slice(0, match.index) + head;
|
|
2139
|
-
let page = html.slice(match.index);
|
|
3009
|
+
let page = nameHtmlAttributes(html.slice(match.index));
|
|
2140
3010
|
const lower = page.toLowerCase();
|
|
2141
3011
|
const headEnd = lower.indexOf("</head>");
|
|
2142
3012
|
let bodyEnd = lower.lastIndexOf("</body>");
|
|
@@ -2214,6 +3084,36 @@ function errorAnswer(error, fallback) {
|
|
|
2214
3084
|
status: 500
|
|
2215
3085
|
};
|
|
2216
3086
|
}
|
|
3087
|
+
/** Errors that `safeError` logged, so a failure read in two places logs once. */
|
|
3088
|
+
const logged = /* @__PURE__ */ new WeakSet();
|
|
3089
|
+
/**
|
|
3090
|
+
* The error that the page state may carry in production: a plain `Error` with the message of a
|
|
3091
|
+
* `ServerError`, or `fallback`, and no stack, which holds paths of the server. Any other error is
|
|
3092
|
+
* logged once. A thrown value that is not an object is logged each time.
|
|
3093
|
+
*/
|
|
3094
|
+
function safeError(error, fallback) {
|
|
3095
|
+
let message = fallback;
|
|
3096
|
+
if (error instanceof ServerError) message = error.message;
|
|
3097
|
+
else if (typeof error !== "object" || error === null) console.error(error);
|
|
3098
|
+
else if (!logged.has(error)) {
|
|
3099
|
+
logged.add(error);
|
|
3100
|
+
console.error(error);
|
|
3101
|
+
}
|
|
3102
|
+
const safe = new Error(message);
|
|
3103
|
+
safe.stack = "";
|
|
3104
|
+
return safe;
|
|
3105
|
+
}
|
|
3106
|
+
/**
|
|
3107
|
+
* The error that a `#catch` body gets on the server, which the page state carries to the
|
|
3108
|
+
* browser. In development it is the error itself, for debugging. In production it is a plain
|
|
3109
|
+
* `Error` with the message of a `ServerError`, or a generic message, and the real error is
|
|
3110
|
+
* logged, as for a server function that fails. The body renders with this value too, so the
|
|
3111
|
+
* HTML cannot print what the state does not carry.
|
|
3112
|
+
*/
|
|
3113
|
+
function caught(error, ctx) {
|
|
3114
|
+
if (ctx.isDev()) return error;
|
|
3115
|
+
return safeError(error, "The page could not render this part");
|
|
3116
|
+
}
|
|
2217
3117
|
/** True for a request that a `<form>` sent, without client code. */
|
|
2218
3118
|
function isFormPost(request) {
|
|
2219
3119
|
const type = request.headers.get("content-type") ?? "";
|
|
@@ -2327,12 +3227,12 @@ async function handleForm(invoke, event) {
|
|
|
2327
3227
|
async function readArgs(request) {
|
|
2328
3228
|
if (!request.headers.has("x-brumate-args")) return fromJSON(await request.json(), {
|
|
2329
3229
|
plugins,
|
|
2330
|
-
|
|
3230
|
+
...serialOptions()
|
|
2331
3231
|
});
|
|
2332
3232
|
const form = await request.formData();
|
|
2333
3233
|
return fromJSON(JSON.parse(String(form.get("args"))), {
|
|
2334
3234
|
plugins: callPlugins(void 0, form),
|
|
2335
|
-
|
|
3235
|
+
...serialOptions()
|
|
2336
3236
|
});
|
|
2337
3237
|
}
|
|
2338
3238
|
/**
|
|
@@ -2405,7 +3305,9 @@ async function handleRequest(functions, request, prefix = "/_brumate", options =
|
|
|
2405
3305
|
id,
|
|
2406
3306
|
args
|
|
2407
3307
|
};
|
|
2408
|
-
|
|
3308
|
+
function invoke() {
|
|
3309
|
+
return withEvent(event, () => fn(...args));
|
|
3310
|
+
}
|
|
2409
3311
|
return runEntry(options.middleware, event, () => runEntry(options.fileMiddleware?.[id], event, () => posted ? handleForm(invoke, event) : answerCall(functions, event, async () => invoke())));
|
|
2410
3312
|
}
|
|
2411
3313
|
/**
|
|
@@ -2420,7 +3322,8 @@ async function answerCall(functions, event, run) {
|
|
|
2420
3322
|
const result = await run();
|
|
2421
3323
|
const { refreshed } = event;
|
|
2422
3324
|
if (refreshed?.size) {
|
|
2423
|
-
const ids =
|
|
3325
|
+
const ids = [];
|
|
3326
|
+
for (const key of Object.keys(functions)) if (refreshed.has(unwrap(functions[key]))) ids.push(key);
|
|
2424
3327
|
if (ids.length > 0) headers.set("x-brumate-refresh", ids.join(","));
|
|
2425
3328
|
}
|
|
2426
3329
|
headers.set("content-type", STREAM_TYPE);
|
|
@@ -2445,19 +3348,85 @@ function callFailure(error, headers) {
|
|
|
2445
3348
|
headers
|
|
2446
3349
|
});
|
|
2447
3350
|
}
|
|
3351
|
+
/** The key of a page in the store: its URL, and the base of a client navigation, by build. */
|
|
3352
|
+
function pageKey(url, request, build) {
|
|
3353
|
+
const base = request.headers.get("x-brumate-base") ?? "";
|
|
3354
|
+
return `brumate:page:${build ?? ""}:${base}:${url.pathname}${url.search}`;
|
|
3355
|
+
}
|
|
3356
|
+
/** The page that the store keeps for a key, when it is still fresh. */
|
|
3357
|
+
async function keptPage(key) {
|
|
3358
|
+
const text = await cacheStore().get(key);
|
|
3359
|
+
if (!text) return;
|
|
3360
|
+
const page = JSON.parse(text);
|
|
3361
|
+
const tags = Object.keys(page.tags);
|
|
3362
|
+
const versions = await tagVersions(tags);
|
|
3363
|
+
if (page.expires <= Date.now()) return;
|
|
3364
|
+
for (const tag of tags) if (versions[tag] !== page.tags[tag]) return;
|
|
3365
|
+
const headers = new Headers(page.headers);
|
|
3366
|
+
const maxAge = Number(/max-age=(\d+)/.exec(headers.get("cache-control") ?? "")?.[1] ?? 0);
|
|
3367
|
+
headers.set("age", String(Math.max(0, Math.floor(maxAge - (page.expires - Date.now()) / 1e3))));
|
|
3368
|
+
headers.set("x-brumate-cache", "hit");
|
|
3369
|
+
return new Response(page.body, {
|
|
3370
|
+
status: page.status,
|
|
3371
|
+
headers
|
|
3372
|
+
});
|
|
3373
|
+
}
|
|
3374
|
+
/** Keeps a public page in the store until its `max-age` ends. */
|
|
3375
|
+
async function keepPage(key, response, event) {
|
|
3376
|
+
const maxAge = Number(/max-age=(\d+)/.exec(response.headers.get("cache-control") ?? "")?.[1] ?? 0);
|
|
3377
|
+
if (maxAge <= 0) return;
|
|
3378
|
+
const missing = [];
|
|
3379
|
+
for (const [tag, version] of event.cacheTags) if (version === void 0) missing.push(tag);
|
|
3380
|
+
const versions = await tagVersions(missing);
|
|
3381
|
+
const kept = [];
|
|
3382
|
+
for (const [name, value] of response.headers) if (name !== "set-cookie") kept.push([name, value]);
|
|
3383
|
+
const body = await response.clone().text();
|
|
3384
|
+
const tags = {};
|
|
3385
|
+
for (const [tag, version] of event.cacheTags) tags[tag] = version ?? versions[tag];
|
|
3386
|
+
const page = {
|
|
3387
|
+
status: response.status,
|
|
3388
|
+
headers: kept,
|
|
3389
|
+
body,
|
|
3390
|
+
expires: Date.now() + maxAge * 1e3,
|
|
3391
|
+
tags
|
|
3392
|
+
};
|
|
3393
|
+
await cacheStore().set(key, JSON.stringify(page), maxAge);
|
|
3394
|
+
}
|
|
3395
|
+
/** The `cache` of the page of a view: the nearest one along its `children`. */
|
|
3396
|
+
function pageCache(view) {
|
|
3397
|
+
const inner = view.slots.children;
|
|
3398
|
+
return (inner && pageCache(inner)) ?? view.cache;
|
|
3399
|
+
}
|
|
3400
|
+
/**
|
|
3401
|
+
* The `cache-control` of a page with `cache`. It is public only when the
|
|
3402
|
+
* request did not read or set anything of the user, and the page is a
|
|
3403
|
+
* success without cookies.
|
|
3404
|
+
*/
|
|
3405
|
+
function cacheControl(cache, event, response) {
|
|
3406
|
+
if (event?.personal || response.status !== 200 || response.headers.getSetCookie().length > 0) return "private, no-cache";
|
|
3407
|
+
const parts = ["public", `max-age=${Math.max(0, Math.floor(cache.maxAge))}`];
|
|
3408
|
+
if (cache.staleWhileRevalidate !== void 0) parts.push(`stale-while-revalidate=${Math.max(0, Math.floor(cache.staleWhileRevalidate))}`);
|
|
3409
|
+
return parts.join(", ");
|
|
3410
|
+
}
|
|
3411
|
+
const warnedPrivate = /* @__PURE__ */ new Set();
|
|
2448
3412
|
/** Imports every module of a matched route before it renders. */
|
|
2449
3413
|
async function resolveView(view) {
|
|
3414
|
+
const names = Object.keys(view.slots);
|
|
3415
|
+
const pending = [];
|
|
3416
|
+
for (const slot of Object.values(view.slots)) pending.push(resolveView(slot));
|
|
2450
3417
|
const [module, loading, ...slots] = await Promise.all([
|
|
2451
3418
|
view.load(),
|
|
2452
3419
|
view.loading?.(),
|
|
2453
|
-
...
|
|
3420
|
+
...pending
|
|
2454
3421
|
]);
|
|
2455
|
-
const
|
|
3422
|
+
const resolved = {};
|
|
3423
|
+
for (const [index, name] of names.entries()) resolved[name] = slots[index];
|
|
2456
3424
|
return {
|
|
2457
3425
|
key: view.key,
|
|
2458
3426
|
component: module.default,
|
|
2459
3427
|
loading: loading?.default,
|
|
2460
|
-
|
|
3428
|
+
cache: module.cache,
|
|
3429
|
+
slots: resolved
|
|
2461
3430
|
};
|
|
2462
3431
|
}
|
|
2463
3432
|
/**
|
|
@@ -2475,6 +3444,13 @@ async function renderView(view, props, ctx, scope) {
|
|
|
2475
3444
|
* A component that renders a route, with its slots rendering where the
|
|
2476
3445
|
* layout inserts them. `props` go to every view, such as `params`.
|
|
2477
3446
|
*/
|
|
3447
|
+
/** The component IDs of a view and of the views in its slots. */
|
|
3448
|
+
function viewIds(view) {
|
|
3449
|
+
const id = view.component.brumateId;
|
|
3450
|
+
const ids = id === void 0 ? [] : [id];
|
|
3451
|
+
for (const slot of Object.values(view.slots)) ids.push(...viewIds(slot));
|
|
3452
|
+
return ids;
|
|
3453
|
+
}
|
|
2478
3454
|
function viewComponent(view, props) {
|
|
2479
3455
|
return (_props, ctx) => {
|
|
2480
3456
|
const own = { ...props };
|
|
@@ -2525,10 +3501,25 @@ async function renderPage(view, props, request, options, extra) {
|
|
|
2525
3501
|
const base = Number(request.headers.get("x-brumate-base"));
|
|
2526
3502
|
const defer = deferTarget(request);
|
|
2527
3503
|
if (defer) return renderDeferred(view, props, request, options, defer, base);
|
|
2528
|
-
const
|
|
2529
|
-
|
|
3504
|
+
const event = options.event;
|
|
3505
|
+
if (options.dev && event) {
|
|
3506
|
+
event.trace = [];
|
|
3507
|
+
event.traceStart = performance.now();
|
|
3508
|
+
}
|
|
3509
|
+
const path = new URL(request.url).pathname;
|
|
3510
|
+
const endRender = event?.traced("render", path) ?? (() => {});
|
|
3511
|
+
let hints = [];
|
|
3512
|
+
if (!request.headers.has("x-brumate-base")) {
|
|
3513
|
+
const wanted = [...options.hints ?? []];
|
|
3514
|
+
for (const id of viewIds(view)) wanted.push(...options.bundleHints?.[id] ?? []);
|
|
3515
|
+
hints = [...new Set(wanted)];
|
|
3516
|
+
}
|
|
3517
|
+
const nonce = options.nonce === void 0 ? "" : ` nonce="${escapeAttribute(options.nonce)}"`;
|
|
3518
|
+
const links = [];
|
|
3519
|
+
if (!nonce) for (const url of hints) links.push(`<${url}>; rel=modulepreload`);
|
|
2530
3520
|
if (links.length > 0) options.earlyHints?.(links);
|
|
2531
|
-
|
|
3521
|
+
let preload = "";
|
|
3522
|
+
for (const url of hints) preload += `<link rel="modulepreload"${nonce} href="${escapeAttribute(url)}">`;
|
|
2532
3523
|
const parts = await render(viewComponent(view, props), {}, {
|
|
2533
3524
|
...options,
|
|
2534
3525
|
request,
|
|
@@ -2537,18 +3528,48 @@ async function renderPage(view, props, request, options, extra) {
|
|
|
2537
3528
|
params: props.params,
|
|
2538
3529
|
base: Number.isSafeInteger(base) && base > 0 ? base : void 0
|
|
2539
3530
|
});
|
|
3531
|
+
endRender();
|
|
3532
|
+
const endStream = event?.traced("stream", "the rest of the page") ?? (() => {});
|
|
2540
3533
|
const headers = new Headers(parts.headers);
|
|
2541
3534
|
headers.set("content-type", "text/html; charset=utf-8");
|
|
2542
3535
|
headers.append("vary", "x-brumate-defer");
|
|
2543
3536
|
headers.append("vary", "x-brumate-base");
|
|
2544
3537
|
for (const link of links) headers.append("link", link);
|
|
2545
|
-
|
|
3538
|
+
let html = streamParts(parts, {
|
|
2546
3539
|
...options,
|
|
2547
3540
|
head: preload + (options.head ?? "")
|
|
2548
|
-
})
|
|
3541
|
+
});
|
|
3542
|
+
if (event?.trace) {
|
|
3543
|
+
const trace = event.trace;
|
|
3544
|
+
html = html.pipeThrough(new TransformStream({ flush(controller) {
|
|
3545
|
+
endStream();
|
|
3546
|
+
const json = JSON.stringify({
|
|
3547
|
+
route: path,
|
|
3548
|
+
entries: trace
|
|
3549
|
+
}).replace(/</g, "\\u003c");
|
|
3550
|
+
controller.enqueue(`<script type="application/json" b-trace>${json}<\/script>`);
|
|
3551
|
+
} }));
|
|
3552
|
+
}
|
|
3553
|
+
const body = html.pipeThrough(new TextEncoderStream());
|
|
3554
|
+
const cache = request.method === "GET" || request.method === "HEAD" ? pageCache(view) : void 0;
|
|
3555
|
+
if (!cache) return respond(body, {
|
|
2549
3556
|
status: extra.status ?? parts.status,
|
|
2550
3557
|
headers
|
|
2551
3558
|
});
|
|
3559
|
+
const response = respond(await new Response(body).arrayBuffer(), {
|
|
3560
|
+
status: extra.status ?? parts.status,
|
|
3561
|
+
headers
|
|
3562
|
+
});
|
|
3563
|
+
const control = cacheControl(cache, options.event, response);
|
|
3564
|
+
if (options.dev) {
|
|
3565
|
+
response.headers.set("cache-control", "no-cache");
|
|
3566
|
+
response.headers.set("x-brumate-cache", control);
|
|
3567
|
+
if (control.startsWith("private") && !warnedPrivate.has(view.key)) {
|
|
3568
|
+
warnedPrivate.add(view.key);
|
|
3569
|
+
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.`);
|
|
3570
|
+
}
|
|
3571
|
+
} else response.headers.set("cache-control", control);
|
|
3572
|
+
return response;
|
|
2552
3573
|
}
|
|
2553
3574
|
/**
|
|
2554
3575
|
* The `#defer` block that a request asks for, from `x-brumate-defer:
|
|
@@ -2634,6 +3655,7 @@ async function runMiddleware(loaders, request, event, answer) {
|
|
|
2634
3655
|
* middleware. A `redirect` while the page renders answers with a redirect.
|
|
2635
3656
|
*/
|
|
2636
3657
|
async function handleRoute(tree, request, options = {}) {
|
|
3658
|
+
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
3659
|
const url = new URL(request.url);
|
|
2638
3660
|
const match = matchRoute(tree, url.pathname);
|
|
2639
3661
|
const event = options.event ?? new RequestEvent(request, {
|
|
@@ -2661,13 +3683,70 @@ async function requestKind(request, match) {
|
|
|
2661
3683
|
}
|
|
2662
3684
|
return "page";
|
|
2663
3685
|
}
|
|
3686
|
+
/**
|
|
3687
|
+
* The `#defer` blocks of a prerendered page that the server renders in the
|
|
3688
|
+
* response: those with the `load` or `idle` trigger. A `visible` block is
|
|
3689
|
+
* far down the page, so it waits for the browser to ask for it.
|
|
3690
|
+
*/
|
|
3691
|
+
const HOLE = /<template b-b="([^"]+)" b-defer="(?:load|idle):([^:"]+):([^"]*)"/g;
|
|
3692
|
+
/**
|
|
3693
|
+
* Answers with a prerendered page, then with the body of each of its
|
|
3694
|
+
* `#defer` blocks as it is ready, as a `#loading` body streams. Each body
|
|
3695
|
+
* renders in a request of its own, as when the browser asks for it, so
|
|
3696
|
+
* middleware runs for it. The loader leaves the marked blocks alone, and a
|
|
3697
|
+
* block whose body fails keeps its fallback.
|
|
3698
|
+
*/
|
|
3699
|
+
function fillHoles(tree, request, shell, options) {
|
|
3700
|
+
const holes = [...shell.matchAll(HOLE)];
|
|
3701
|
+
const headers = new Headers({ "content-type": "text/html; charset=utf-8" });
|
|
3702
|
+
if (holes.length === 0) return new Response(request.method === "HEAD" ? null : shell, { headers });
|
|
3703
|
+
headers.set("cache-control", "private, no-cache");
|
|
3704
|
+
headers.append("vary", "x-brumate-defer");
|
|
3705
|
+
headers.append("vary", "x-brumate-base");
|
|
3706
|
+
const marked = shell.replace(HOLE, (template) => `${template} b-hole`);
|
|
3707
|
+
async function loadBody([, at, boundary, base]) {
|
|
3708
|
+
const asked = new Headers(request.headers);
|
|
3709
|
+
asked.set("x-brumate-defer", `${boundary} ${at}`);
|
|
3710
|
+
asked.set("x-brumate-base", base);
|
|
3711
|
+
try {
|
|
3712
|
+
const answer = await handleRoute(tree, new Request(request.url, { headers: asked }), {
|
|
3713
|
+
...options,
|
|
3714
|
+
shell: void 0,
|
|
3715
|
+
event: void 0
|
|
3716
|
+
});
|
|
3717
|
+
return answer?.ok && answer.headers.get("x-brumate-defer") === boundary ? await answer.text() : "";
|
|
3718
|
+
} catch (error) {
|
|
3719
|
+
console.error(error);
|
|
3720
|
+
return "";
|
|
3721
|
+
}
|
|
3722
|
+
}
|
|
3723
|
+
const bodies = [];
|
|
3724
|
+
for (const hole of holes) bodies.push(loadBody(hole));
|
|
3725
|
+
const body = new ReadableStream({ async start(controller) {
|
|
3726
|
+
controller.enqueue(marked);
|
|
3727
|
+
const pending = /* @__PURE__ */ new Map();
|
|
3728
|
+
for (const [index, promise] of bodies.entries()) pending.set(index, promise.then((html) => ({
|
|
3729
|
+
html,
|
|
3730
|
+
index
|
|
3731
|
+
})));
|
|
3732
|
+
while (pending.size > 0) {
|
|
3733
|
+
const { html, index } = await Promise.race(pending.values());
|
|
3734
|
+
pending.delete(index);
|
|
3735
|
+
if (html) controller.enqueue(html);
|
|
3736
|
+
}
|
|
3737
|
+
controller.close();
|
|
3738
|
+
} }).pipeThrough(new TextEncoderStream());
|
|
3739
|
+
return new Response(request.method === "HEAD" ? null : body, { headers });
|
|
3740
|
+
}
|
|
2664
3741
|
/** A response with more headers, such as cookies that middleware set. */
|
|
2665
3742
|
function withHeaders(answer, headers) {
|
|
2666
3743
|
const sent = new Set(answer.headers.getSetCookie());
|
|
2667
|
-
const cookies =
|
|
3744
|
+
const cookies = [];
|
|
3745
|
+
for (const cookie of headers.getSetCookie()) if (!sent.has(cookie)) cookies.push(cookie);
|
|
2668
3746
|
if (cookies.length === 0) return answer;
|
|
2669
3747
|
const result = respond(answer.body, answer);
|
|
2670
3748
|
for (const cookie of cookies) result.headers.append("set-cookie", cookie);
|
|
3749
|
+
if (/^\s*public\b/.test(result.headers.get("cache-control") ?? "")) result.headers.set("cache-control", "private, no-cache");
|
|
2671
3750
|
return result;
|
|
2672
3751
|
}
|
|
2673
3752
|
async function routeAnswer(tree, match, url, options) {
|
|
@@ -2695,7 +3774,8 @@ async function answerRoute(match, request, url, options) {
|
|
|
2695
3774
|
const handler = endpoint[request.method] ?? (request.method === "HEAD" ? endpoint.GET : void 0);
|
|
2696
3775
|
if (handler) return withEvent(options.event, () => handler(request, match.params));
|
|
2697
3776
|
if (match.view.load === missingPage || request.method !== "GET") {
|
|
2698
|
-
const allow =
|
|
3777
|
+
const allow = [];
|
|
3778
|
+
for (const name of Object.keys(endpoint)) if (/^[A-Z]+$/.test(name)) allow.push(name);
|
|
2699
3779
|
return new Response("Method not allowed", {
|
|
2700
3780
|
status: 405,
|
|
2701
3781
|
headers: { allow: allow.join(", ") }
|
|
@@ -2715,8 +3795,15 @@ async function renderRoute(match, request, url, options) {
|
|
|
2715
3795
|
if ("answer" in outcome) return outcome.answer;
|
|
2716
3796
|
actions = outcome.actions;
|
|
2717
3797
|
}
|
|
3798
|
+
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;
|
|
3799
|
+
if (key && !event.personal) {
|
|
3800
|
+
const kept = await keptPage(key);
|
|
3801
|
+
if (kept) return kept;
|
|
3802
|
+
}
|
|
2718
3803
|
try {
|
|
2719
|
-
|
|
3804
|
+
const response = await renderPage(await resolveView(match.view), { params: match.params }, request, options, { actions });
|
|
3805
|
+
if (key && /^\s*public\b/.test(response.headers.get("cache-control") ?? "")) await keepPage(key, response, event);
|
|
3806
|
+
return response;
|
|
2720
3807
|
} catch (error) {
|
|
2721
3808
|
if (isRedirect(error)) return new Response(null, {
|
|
2722
3809
|
status: error.status,
|
|
@@ -2735,28 +3822,30 @@ async function renderRoute(match, request, url, options) {
|
|
|
2735
3822
|
* function belongs to and the modifiers of its wrappers. A function that
|
|
2736
3823
|
* refers to nothing in the browser is left out.
|
|
2737
3824
|
*/
|
|
2738
|
-
function spread(attributes, on) {
|
|
2739
|
-
const entries = on && attributes["b-on"];
|
|
3825
|
+
function spread(attributes, on, names) {
|
|
3826
|
+
const entries = on && ownValue("b-on", attributes["b-on"]);
|
|
2740
3827
|
if (typeof entries === "string") {
|
|
2741
3828
|
on.unshift(entries);
|
|
2742
3829
|
const { "b-on": _, ...rest } = attributes;
|
|
2743
|
-
return spread(rest, on);
|
|
3830
|
+
return spread(rest, on, names);
|
|
2744
3831
|
}
|
|
2745
3832
|
for (const [name, value] of Object.entries(attributes)) {
|
|
2746
|
-
const
|
|
2747
|
-
|
|
2748
|
-
const
|
|
2749
|
-
|
|
3833
|
+
const parts = on && /^on[A-Z]/.test(name) && typeof value === "function" ? value[PARTS] ?? [value] : [];
|
|
3834
|
+
for (const part of parts) {
|
|
3835
|
+
const reference = functionReferences.get(part);
|
|
3836
|
+
if (reference) {
|
|
3837
|
+
const modifiers = part[MODIFIERS];
|
|
3838
|
+
on.push(handlerEntry(name, reference.ref, reference.scope, modifiers, reference.args));
|
|
3839
|
+
}
|
|
3840
|
+
}
|
|
3841
|
+
if (on && (name === "value" || name === "checked") && isBinding(value)) {
|
|
3842
|
+
const setter = typeof value.set === "function" ? functionReferences.get(value.set) : void 0;
|
|
3843
|
+
on.push(bindEntry(name, value.ref, setter));
|
|
2750
3844
|
}
|
|
2751
3845
|
}
|
|
2752
|
-
return spread$1(attributes);
|
|
2753
|
-
}
|
|
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)}"` : "";
|
|
3846
|
+
return spread$1(attributes, names);
|
|
2758
3847
|
}
|
|
2759
3848
|
//#endregion
|
|
2760
|
-
export {
|
|
3849
|
+
export { isRedirect as $, waitAll as A, parseForm as B, spacerTag as C, streamParts as D, stateValue as E, rateLimit as F, revalidate as G, matchRoute as H, parseSubmission as I, RequestEvent as J, setCacheStore as K, ValidationError as L, RateLimitError as M, clientAddress as N, streamState as O, configureRateLimit as P, getEvent as Q, fieldErrors as R, settled as S, stateScript as T, cached as U, safeParse as V, memoryStore as W, dedupe as X, ServerError as Y, defineMiddleware as Z, packState as _, binding as a, render as b, component as c, handleRoute as d, redirect as et, inlineBodies as f, memo as g, lazy as h, actionResult as i, idempotent as j, wait as k, dynamic as l, isCrossSite as m, NotReady as n, caught as o, insert as p, storageStore as q, action as r, children as s, Context as t, withEvent as tt, handleRequest as u, read as v, spread as w, renderToStream as x, ready as y, parse as z };
|
|
2761
3850
|
|
|
2762
|
-
//# sourceMappingURL=server-
|
|
3851
|
+
//# sourceMappingURL=server-DjyOVJtJ.js.map
|