brumate 0.1.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{boot-DN1ZU8Hg.d.ts → boot-C25Sa6vq.d.ts} +27 -2
- package/dist/cli.js +2 -2
- package/dist/client-BD6XT-s5.js +1968 -0
- package/dist/client-BD6XT-s5.js.map +1 -0
- package/dist/{client-DwJInP_a.d.ts → client-D0CqSxoO.d.ts} +211 -30
- package/dist/{client-routes-DakuM32C.js → client-routes-JTbGtukf.js} +28 -15
- package/dist/client-routes-JTbGtukf.js.map +1 -0
- package/dist/context-CTiSzQRc.js +27 -0
- package/dist/context-CTiSzQRc.js.map +1 -0
- package/dist/context-btHuB01Z.d.ts +42 -0
- package/dist/{cookies-Av5WFmcf.js → cookies-BzllthiF.js} +2 -1
- package/dist/cookies-BzllthiF.js.map +1 -0
- package/dist/defer-BbD7JQhj.js +56 -0
- package/dist/defer-BbD7JQhj.js.map +1 -0
- package/dist/devtools-CQgD7NPB.js +623 -0
- package/dist/devtools-CQgD7NPB.js.map +1 -0
- package/dist/devtools-panel-BVB-W5q4.js +1930 -0
- package/dist/devtools-panel-BVB-W5q4.js.map +1 -0
- package/dist/events-CSs7OwIC.js +85 -0
- package/dist/events-CSs7OwIC.js.map +1 -0
- package/dist/{files-DdT84mPy.js → files-BXSSrQgc.js} +34 -6
- package/dist/files-BXSSrQgc.js.map +1 -0
- package/dist/forms-Bg-CwGqX.js +406 -0
- package/dist/forms-Bg-CwGqX.js.map +1 -0
- package/dist/forms-Cl21hkHt.d.ts +281 -0
- package/dist/highlight.d.ts +17 -0
- package/dist/highlight.js +269 -0
- package/dist/highlight.js.map +1 -0
- package/dist/html-Bq1rFxX_.d.ts +92 -0
- package/dist/html-mNTKzaDD.js +241 -0
- package/dist/html-mNTKzaDD.js.map +1 -0
- package/dist/index.d.ts +123 -30
- package/dist/index.js +14 -6
- package/dist/index.js.map +1 -1
- package/dist/{inspect-BPchdWbU.js → inspect-BHpOw1LF.js} +1400 -121
- package/dist/inspect-BHpOw1LF.js.map +1 -0
- package/dist/{loader-Dc9OwY5I.js → loader-Dos_3NP0.js} +47 -11
- package/dist/loader-Dos_3NP0.js.map +1 -0
- package/dist/{navigate-CzLjnoPH.js → navigate-O78d_zGN.js} +115 -13
- package/dist/navigate-O78d_zGN.js.map +1 -0
- package/dist/produce-D0V0ICkz.d.ts +114 -0
- package/dist/produce-Doc91GkX.js +274 -0
- package/dist/produce-Doc91GkX.js.map +1 -0
- package/dist/routes-BZNt7DSZ.d.ts +38 -0
- package/dist/{rpc-9fSqL_YK.js → rpc-ygMRPmN4.js} +39 -23
- package/dist/rpc-ygMRPmN4.js.map +1 -0
- package/dist/runtime/batch.d.ts +23 -0
- package/dist/runtime/batch.js +69 -0
- package/dist/runtime/batch.js.map +1 -0
- package/dist/runtime/client.d.ts +5 -5
- package/dist/runtime/client.js +5 -1345
- package/dist/runtime/context.d.ts +2 -2
- package/dist/runtime/context.js +1 -1
- package/dist/runtime/devtools.d.ts +191 -5
- package/dist/runtime/devtools.js +1 -1
- package/dist/runtime/env.d.ts +44 -0
- package/dist/runtime/env.js +61 -0
- package/dist/runtime/env.js.map +1 -0
- package/dist/runtime/events.d.ts +42 -0
- package/dist/runtime/events.js +1 -0
- 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/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.d.ts +2 -21
- package/dist/runtime/routes.js +31 -1
- package/dist/runtime/routes.js.map +1 -1
- package/dist/runtime/server.d.ts +7 -5
- package/dist/runtime/server.js +6 -7
- package/dist/runtime/signals.d.ts +60 -3
- package/dist/runtime/signals.js +40 -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 +46 -5
- package/dist/runtime/testing.js +240 -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/secrets-BxagsJxJ.js +23 -0
- package/dist/secrets-BxagsJxJ.js.map +1 -0
- package/dist/server-CxVDYE_V.js +3417 -0
- package/dist/server-CxVDYE_V.js.map +1 -0
- package/dist/server-DuFYRXrd.d.ts +1460 -0
- package/dist/skew-FRmAy9iy.js +49 -0
- package/dist/skew-FRmAy9iy.js.map +1 -0
- package/dist/standard-schema-BNY82yX3.d.ts +63 -0
- package/dist/{static-loader-BcFh4ebX.d.ts → static-loader-Drpr0AzI.d.ts} +2 -2
- package/dist/static-loader-nZssh66R.js +333 -0
- package/dist/static-loader-nZssh66R.js.map +1 -0
- package/dist/stream-DCYZO4IF.js +424 -0
- package/dist/stream-DCYZO4IF.js.map +1 -0
- package/dist/values-B8C7CLvG.d.ts +63 -0
- package/dist/vite.d.ts +49 -1
- package/dist/vite.js +598 -68
- package/dist/vite.js.map +1 -1
- package/forms/forms.brm.ts +141 -0
- package/package.json +45 -3
- package/types.d.ts +9 -1
- package/dist/client-routes-DakuM32C.js.map +0 -1
- package/dist/context-BG8KCF3v.js +0 -15
- package/dist/context-BG8KCF3v.js.map +0 -1
- package/dist/context-aeo9esY9.d.ts +0 -16
- package/dist/cookies-Av5WFmcf.js.map +0 -1
- package/dist/devtools-BKjnHrnv.js +0 -113
- package/dist/devtools-BKjnHrnv.js.map +0 -1
- package/dist/devtools-panel-AWOn0VK2.js +0 -434
- package/dist/devtools-panel-AWOn0VK2.js.map +0 -1
- package/dist/files-DdT84mPy.js.map +0 -1
- package/dist/html-DEeoepg3.js +0 -152
- package/dist/html-DEeoepg3.js.map +0 -1
- package/dist/html-Du8jY2Cc.d.ts +0 -53
- package/dist/inspect-BPchdWbU.js.map +0 -1
- package/dist/loader-Dc9OwY5I.js.map +0 -1
- package/dist/navigate-CzLjnoPH.js.map +0 -1
- package/dist/produce-BRGHP7e0.js +0 -126
- package/dist/produce-BRGHP7e0.js.map +0 -1
- package/dist/produce-CtZ32UGG.d.ts +0 -60
- package/dist/rpc-9fSqL_YK.js.map +0 -1
- package/dist/runtime/client.js.map +0 -1
- package/dist/server-BxqjLUnV.d.ts +0 -753
- package/dist/server-DZsgnPKS.js +0 -1615
- package/dist/server-DZsgnPKS.js.map +0 -1
- package/dist/shared-CWYOd0H3.js +0 -40
- package/dist/shared-CWYOd0H3.js.map +0 -1
- package/dist/static-loader-ClNkHZGn.js +0 -185
- package/dist/static-loader-ClNkHZGn.js.map +0 -1
- package/dist/stream-bgNCMcaA.js +0 -280
- package/dist/stream-bgNCMcaA.js.map +0 -1
|
@@ -0,0 +1,3417 @@
|
|
|
1
|
+
import { n as MODIFIERS } from "./events-CSs7OwIC.js";
|
|
2
|
+
import { _ as rawHTML, d as handlerEntry, f as insertValue, h as onAttribute, l as escape, n as actionAttributes, o as bindEntry, p as isRaw, t as VOID_ELEMENTS, u as escapeAttribute, v as spread$1, y as styleElement } from "./html-mNTKzaDD.js";
|
|
3
|
+
import { n as deleteCookie, o as setCookie, r as getCookies } from "./cookies-BzllthiF.js";
|
|
4
|
+
import { a as plugins, c as functionReferences, i as callPlugins, o as serialOptions, r as toChunkStream, s as syncPlugins, t as STREAM_TYPE } from "./stream-DCYZO4IF.js";
|
|
5
|
+
import { a as SlotReference, d as parseId, i as FunctionReference, n as Binding, o as isAsyncIterable, r as ElementReference, s as isBinding } from "./produce-Doc91GkX.js";
|
|
6
|
+
import { n as serverSecrets } from "./secrets-BxagsJxJ.js";
|
|
7
|
+
import "./context-CTiSzQRc.js";
|
|
8
|
+
import { a as applyIntent, d as formValues, f as formatPath, m as groupIssues, p as getAt, r as INTENT, v as parseIntent, y as parsePath } from "./forms-Bg-CwGqX.js";
|
|
9
|
+
import { crossSerialize, crossSerializeStream, fromJSON, toJSON } from "seroval";
|
|
10
|
+
//#region src/runtime/request.ts
|
|
11
|
+
function noTrace() {}
|
|
12
|
+
/** Ends an entry of the trace when a value settles, if it is a promise, or at once. */
|
|
13
|
+
function traceValue(value, end) {
|
|
14
|
+
const thenable = value;
|
|
15
|
+
if (thenable && typeof thenable.then === "function") thenable.then(() => end(), () => end(true));
|
|
16
|
+
else end();
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
19
|
+
/** The headers that tell who the user is. */
|
|
20
|
+
const PERSONAL = /* @__PURE__ */ new Set(["cookie", "authorization"]);
|
|
21
|
+
/**
|
|
22
|
+
* Calls `read` when code reads the headers that tell who the user is, by
|
|
23
|
+
* name or by going through all the headers.
|
|
24
|
+
*/
|
|
25
|
+
function watchPersonal(headers, read) {
|
|
26
|
+
const get = headers.get.bind(headers);
|
|
27
|
+
const has = headers.has.bind(headers);
|
|
28
|
+
Object.assign(headers, {
|
|
29
|
+
get: (name) => {
|
|
30
|
+
if (PERSONAL.has(name.toLowerCase())) read();
|
|
31
|
+
return get(name);
|
|
32
|
+
},
|
|
33
|
+
has: (name) => {
|
|
34
|
+
if (PERSONAL.has(name.toLowerCase())) read();
|
|
35
|
+
return has(name);
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
for (const method of [
|
|
39
|
+
"entries",
|
|
40
|
+
"forEach",
|
|
41
|
+
"values",
|
|
42
|
+
Symbol.iterator
|
|
43
|
+
]) {
|
|
44
|
+
const all = headers[method].bind(headers);
|
|
45
|
+
Object.defineProperty(headers, method, {
|
|
46
|
+
value: (...args) => {
|
|
47
|
+
read();
|
|
48
|
+
return all(...args);
|
|
49
|
+
},
|
|
50
|
+
configurable: true
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
var RequestEvent = class {
|
|
55
|
+
request;
|
|
56
|
+
/** What the request is for. */
|
|
57
|
+
kind;
|
|
58
|
+
/** For a call, and a page that a form posted to, the server function and its arguments. */
|
|
59
|
+
call;
|
|
60
|
+
/** Values for this request, which middleware writes and the rest of the request reads. */
|
|
61
|
+
locals = {};
|
|
62
|
+
/** The address of the client as the server saw it, when the server passed it. */
|
|
63
|
+
address;
|
|
64
|
+
/** True while the build prerenders the page. */
|
|
65
|
+
prerender;
|
|
66
|
+
/**
|
|
67
|
+
* The pattern of the route files that matched the path, such as
|
|
68
|
+
* `/todos/[id]`. `handleRoute` sets it. Undefined for a path that no route
|
|
69
|
+
* matches.
|
|
70
|
+
*/
|
|
71
|
+
route;
|
|
72
|
+
/** Headers to add to the response, such as `cache-control`. */
|
|
73
|
+
headers = new Headers();
|
|
74
|
+
/** The status that `setStatus` set. */
|
|
75
|
+
status;
|
|
76
|
+
/** Server functions that `refresh` named, whose memos the client loads again. */
|
|
77
|
+
refreshed;
|
|
78
|
+
/** Cookies that this request set, or deleted with undefined, so later reads see them. */
|
|
79
|
+
cookies;
|
|
80
|
+
/**
|
|
81
|
+
* True once the request read its cookies or its `authorization` header, or
|
|
82
|
+
* set a cookie, such as for a session. The answer then depends on the user,
|
|
83
|
+
* so a page with `cache` is not cached for everyone.
|
|
84
|
+
*/
|
|
85
|
+
personal = false;
|
|
86
|
+
/**
|
|
87
|
+
* In development, what the render of the page did and when, in
|
|
88
|
+
* milliseconds from its start, for the Server tab of the devtools.
|
|
89
|
+
*/
|
|
90
|
+
trace;
|
|
91
|
+
/** When the trace started, by `performance.now()`. */
|
|
92
|
+
traceStart = 0;
|
|
93
|
+
/** Starts an entry of the trace, when there is one, and returns what ends it. */
|
|
94
|
+
traced(kind, label) {
|
|
95
|
+
const trace = this.trace;
|
|
96
|
+
if (!trace) return noTrace;
|
|
97
|
+
const entry = {
|
|
98
|
+
kind,
|
|
99
|
+
label,
|
|
100
|
+
start: performance.now() - this.traceStart
|
|
101
|
+
};
|
|
102
|
+
trace.push(entry);
|
|
103
|
+
return (failed) => {
|
|
104
|
+
entry.end = performance.now() - this.traceStart;
|
|
105
|
+
if (failed) entry.failed = true;
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* The tags of the `cached` functions that the request called, with the
|
|
110
|
+
* version that each had then, so `revalidate` drops the page that it renders.
|
|
111
|
+
*/
|
|
112
|
+
cacheTags = /* @__PURE__ */ new Map();
|
|
113
|
+
controller = new AbortController();
|
|
114
|
+
/**
|
|
115
|
+
* Aborts when the request no longer needs an answer: the request's own
|
|
116
|
+
* signal aborts, or the reader of the response went away, such as a
|
|
117
|
+
* browser that left the page while it streamed. Pass it on, such as to
|
|
118
|
+
* `fetch(url, { signal })`, so work that nobody waits for stops.
|
|
119
|
+
*/
|
|
120
|
+
signal = this.controller.signal;
|
|
121
|
+
keepGoing;
|
|
122
|
+
constructor(request, options = {}) {
|
|
123
|
+
this.request = request;
|
|
124
|
+
this.kind = options.kind ?? "page";
|
|
125
|
+
this.keepGoing = options.waitUntil;
|
|
126
|
+
this.address = options.address;
|
|
127
|
+
this.prerender = options.prerender ?? false;
|
|
128
|
+
watchPersonal(request.headers, () => {
|
|
129
|
+
this.personal = true;
|
|
130
|
+
});
|
|
131
|
+
const outer = request.signal;
|
|
132
|
+
if (outer?.aborted) this.controller.abort(outer.reason);
|
|
133
|
+
else outer?.addEventListener("abort", () => this.abort(outer.reason), { once: true });
|
|
134
|
+
}
|
|
135
|
+
/** Aborts `signal`, such as when the response's reader went away. The server calls it. */
|
|
136
|
+
abort(reason) {
|
|
137
|
+
if (!this.signal.aborted) this.controller.abort(reason);
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Keeps work going after the response ends, such as a log line or
|
|
141
|
+
* analytics. On a host that stops a function when its response ends, the
|
|
142
|
+
* server passes the promise to the host, through the `waitUntil` option.
|
|
143
|
+
* Elsewhere the promise runs on its own, and its error is logged.
|
|
144
|
+
*/
|
|
145
|
+
waitUntil(promise) {
|
|
146
|
+
if (this.keepGoing) this.keepGoing(promise);
|
|
147
|
+
else promise.catch((error) => console.error(error));
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Sets the status of the page response, such as 404 for a page that shows
|
|
151
|
+
* that nothing was found. It works while the first render of a page runs.
|
|
152
|
+
* Markup that streams later, such as a `#loading` body, cannot change it,
|
|
153
|
+
* because the response has started by then.
|
|
154
|
+
*/
|
|
155
|
+
setStatus(status) {
|
|
156
|
+
this.status = status;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Asks the client to load again the memos that call a server function, such
|
|
160
|
+
* as a list after a server function adds to it. The compiler gives those
|
|
161
|
+
* memos client code, so they can load.
|
|
162
|
+
*/
|
|
163
|
+
refresh(fn) {
|
|
164
|
+
this.refreshed ??= /* @__PURE__ */ new Set();
|
|
165
|
+
this.refreshed.add(unwrap(fn));
|
|
166
|
+
}
|
|
167
|
+
/** The cookies of the request, with the ones that this request set or deleted. */
|
|
168
|
+
getCookies() {
|
|
169
|
+
return getCookies(this);
|
|
170
|
+
}
|
|
171
|
+
/** A cookie of the request, or the value that this request set. */
|
|
172
|
+
getCookie(name) {
|
|
173
|
+
return getCookies(this)[name];
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Sets a cookie on the response. It is `HttpOnly`, `SameSite=Lax` and on
|
|
177
|
+
* the path `/` unless the options say otherwise, and `Secure` on HTTPS.
|
|
178
|
+
* Markup that streams later, such as a `#loading` body, cannot set cookies,
|
|
179
|
+
* because the response has started.
|
|
180
|
+
*/
|
|
181
|
+
setCookie(name, value, options = {}) {
|
|
182
|
+
setCookie(this, name, value, options);
|
|
183
|
+
}
|
|
184
|
+
/** Deletes a cookie. Pass the `path` and `domain` that it was set with, if they were not the defaults. */
|
|
185
|
+
deleteCookie(name, options = {}) {
|
|
186
|
+
deleteCookie(this, name, options);
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
/**
|
|
190
|
+
* The event of the code that runs now. The runtime sets it while it calls a
|
|
191
|
+
* server function, middleware, an endpoint or a memo, and clears it as soon
|
|
192
|
+
* as the call returns, which is at its first `await`. One request at a time
|
|
193
|
+
* runs until an `await`, so it is never the event of another request.
|
|
194
|
+
*/
|
|
195
|
+
let current;
|
|
196
|
+
/** The results of server function calls of the render that runs now, by function and arguments. */
|
|
197
|
+
let currentCalls;
|
|
198
|
+
globalThis[Symbol.for("brumate.inRequest")] = () => current !== void 0 || currentCalls !== void 0;
|
|
199
|
+
/**
|
|
200
|
+
* Runs a callback with an event, so `getEvent()` in its code before its first
|
|
201
|
+
* `await` returns it. Returns what the callback returns, such as its promise.
|
|
202
|
+
* `calls`, while a page renders, lets calls with the same arguments share a result.
|
|
203
|
+
*/
|
|
204
|
+
function withEvent(event, callback, calls) {
|
|
205
|
+
const outer = current;
|
|
206
|
+
const outerCalls = currentCalls;
|
|
207
|
+
current = event;
|
|
208
|
+
currentCalls = calls;
|
|
209
|
+
try {
|
|
210
|
+
return callback();
|
|
211
|
+
} finally {
|
|
212
|
+
current = outer;
|
|
213
|
+
currentCalls = outerCalls;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
/** The event of the request being handled, or undefined, without throwing as `getEvent` does. */
|
|
217
|
+
function currentEvent() {
|
|
218
|
+
return current;
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* Returns the event of the request that the server handles: in a server
|
|
222
|
+
* function, middleware or an endpoint, or while a component renders.
|
|
223
|
+
*
|
|
224
|
+
* Call it before the first `await` of the function, and keep it in a
|
|
225
|
+
* variable. After an `await`, other requests may have run, so it throws.
|
|
226
|
+
*
|
|
227
|
+
* ```ts
|
|
228
|
+
* async function save(todo: Todo) {
|
|
229
|
+
* 'use server';
|
|
230
|
+
* const event = getEvent();
|
|
231
|
+
* await db.save(todo);
|
|
232
|
+
* event.setCookie('saved', todo.id);
|
|
233
|
+
* }
|
|
234
|
+
* ```
|
|
235
|
+
*/
|
|
236
|
+
function getEvent() {
|
|
237
|
+
if (!current) throw new Error("getEvent() works in server functions, middleware and endpoints before their first await, and while a component renders. Call it at the start of the function, keep the event in a variable, and pass it to helpers");
|
|
238
|
+
return current;
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Types the middleware of the entry file, `src/middleware.ts`, which the
|
|
242
|
+
* Vite plugin runs for every request:
|
|
243
|
+
*
|
|
244
|
+
* ```ts
|
|
245
|
+
* export default defineMiddleware(async (event, next) => {
|
|
246
|
+
* event.locals.user = await readUser(event);
|
|
247
|
+
* return next();
|
|
248
|
+
* });
|
|
249
|
+
* ```
|
|
250
|
+
*/
|
|
251
|
+
function defineMiddleware(middleware) {
|
|
252
|
+
return middleware;
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Runs the middleware of the entry, when there is one, around an answer.
|
|
256
|
+
* `getEvent()` works in the middleware before its first `await`.
|
|
257
|
+
*/
|
|
258
|
+
function runEntry(middleware, event, answer) {
|
|
259
|
+
if (!middleware) return answer();
|
|
260
|
+
return Promise.resolve(withEvent(event, () => middleware(event, answer)));
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* Wraps a server function, so its calls while a page renders share a result
|
|
264
|
+
* when their arguments are the same. Calls from the browser, which are
|
|
265
|
+
* requests of their own, always run, so a function that changes something
|
|
266
|
+
* runs each time.
|
|
267
|
+
*/
|
|
268
|
+
/** Marks the functions that `idempotent` made. A symbol of the registry. */
|
|
269
|
+
const IDEMPOTENT = Symbol.for("brumate.idempotent");
|
|
270
|
+
/** The IDs of the server functions that `idempotent` made, which `dedupe` records. */
|
|
271
|
+
const idempotentIds = /* @__PURE__ */ new Set();
|
|
272
|
+
/** The ID of each function that `idempotent` made, once the server registered it. */
|
|
273
|
+
const idempotentId = /* @__PURE__ */ new WeakMap();
|
|
274
|
+
function dedupe(fn, id) {
|
|
275
|
+
if (IDEMPOTENT in fn) {
|
|
276
|
+
idempotentIds.add(id);
|
|
277
|
+
idempotentId.set(fn, id);
|
|
278
|
+
}
|
|
279
|
+
const wrapper = ((...args) => {
|
|
280
|
+
const cache = currentCalls;
|
|
281
|
+
if (!cache) return fn(...args);
|
|
282
|
+
let key;
|
|
283
|
+
try {
|
|
284
|
+
key = `${id} ${JSON.stringify(toJSON(args, {
|
|
285
|
+
plugins: syncPlugins,
|
|
286
|
+
...serialOptions()
|
|
287
|
+
}))}`;
|
|
288
|
+
} catch {
|
|
289
|
+
return fn(...args);
|
|
290
|
+
}
|
|
291
|
+
if (!cache.has(key)) cache.set(key, traceValue(fn(...args), current?.traced("call", id) ?? noTrace));
|
|
292
|
+
return cache.get(key);
|
|
293
|
+
});
|
|
294
|
+
Object.defineProperty(wrapper, ORIGINAL, { value: fn });
|
|
295
|
+
return wrapper;
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* The function that `dedupe` wrapped, on its wrapper. A symbol of the
|
|
299
|
+
* registry, so two copies of the runtime agree on it.
|
|
300
|
+
*/
|
|
301
|
+
const ORIGINAL = Symbol.for("brumate.original");
|
|
302
|
+
/**
|
|
303
|
+
* The server function itself, for a wrapper that `dedupe` made. `refresh`
|
|
304
|
+
* and `$action` compare server functions, and the registry holds them unwrapped.
|
|
305
|
+
*/
|
|
306
|
+
function unwrap(fn) {
|
|
307
|
+
return fn?.[ORIGINAL] ?? fn;
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* An error whose message reaches the client. A server function call that
|
|
311
|
+
* throws it rejects with the message, and the response has its status.
|
|
312
|
+
* Other errors reach the client as a generic message, so server details stay
|
|
313
|
+
* on the server.
|
|
314
|
+
*/
|
|
315
|
+
var ServerError = class extends Error {
|
|
316
|
+
status;
|
|
317
|
+
constructor(message, options = {}) {
|
|
318
|
+
super(message);
|
|
319
|
+
this.name = "ServerError";
|
|
320
|
+
this.status = options.status ?? 400;
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
/** Thrown by `redirect`. */
|
|
324
|
+
var Redirect = class extends Error {
|
|
325
|
+
location;
|
|
326
|
+
status;
|
|
327
|
+
constructor(location, status) {
|
|
328
|
+
super(`Redirect to ${location}`);
|
|
329
|
+
this.name = "Redirect";
|
|
330
|
+
this.location = location;
|
|
331
|
+
this.status = status;
|
|
332
|
+
}
|
|
333
|
+
};
|
|
334
|
+
/**
|
|
335
|
+
* Stops a server function and sends the browser to another page. While a
|
|
336
|
+
* page renders, the error reaches the caller of `render`, which can
|
|
337
|
+
* answer with a redirect.
|
|
338
|
+
*/
|
|
339
|
+
function redirect(location, status = 303) {
|
|
340
|
+
throw new Redirect(location, status);
|
|
341
|
+
}
|
|
342
|
+
function isRedirect(error) {
|
|
343
|
+
return error instanceof Redirect;
|
|
344
|
+
}
|
|
345
|
+
//#endregion
|
|
346
|
+
//#region src/runtime/cache.ts
|
|
347
|
+
/** Tags live longer than any result, so a result never outlives the version of its tag. */
|
|
348
|
+
const TAG_AGE = 31536e3;
|
|
349
|
+
/**
|
|
350
|
+
* A store in the memory of the server, the default. Each process has its
|
|
351
|
+
* own, and it keeps at most `size` values, dropping the oldest first.
|
|
352
|
+
*/
|
|
353
|
+
function memoryStore(size = 1e3) {
|
|
354
|
+
const values = /* @__PURE__ */ new Map();
|
|
355
|
+
return {
|
|
356
|
+
memory: true,
|
|
357
|
+
get(key) {
|
|
358
|
+
const item = values.get(key);
|
|
359
|
+
if (!item) return;
|
|
360
|
+
if (item.expires <= Date.now()) {
|
|
361
|
+
values.delete(key);
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
return item.value;
|
|
365
|
+
},
|
|
366
|
+
set(key, value, maxAge) {
|
|
367
|
+
values.delete(key);
|
|
368
|
+
values.set(key, {
|
|
369
|
+
value,
|
|
370
|
+
expires: Date.now() + maxAge * 1e3
|
|
371
|
+
});
|
|
372
|
+
for (const oldest of values.keys()) {
|
|
373
|
+
if (values.size <= size) break;
|
|
374
|
+
values.delete(oldest);
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
let store = memoryStore();
|
|
380
|
+
/**
|
|
381
|
+
* Sets the store of `cached`, such as one that keeps results in Redis for
|
|
382
|
+
* every process of the app. Set it before the first request.
|
|
383
|
+
*/
|
|
384
|
+
function setCacheStore(next) {
|
|
385
|
+
store = next;
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* A store of `cached` from an unstorage storage, such as Nitro's
|
|
389
|
+
* `useStorage('cache')`. It reads and writes the values as they are, since
|
|
390
|
+
* `getItem` would parse text that looks like JSON.
|
|
391
|
+
*/
|
|
392
|
+
function storageStore(storage) {
|
|
393
|
+
return {
|
|
394
|
+
get: async (key) => {
|
|
395
|
+
const value = await (storage.getItemRaw ?? storage.getItem).call(storage, key);
|
|
396
|
+
if (value instanceof Uint8Array) return new TextDecoder().decode(value);
|
|
397
|
+
return typeof value === "string" ? value : void 0;
|
|
398
|
+
},
|
|
399
|
+
set: (key, value, maxAge) => (storage.setItemRaw ?? storage.setItem).call(storage, key, value, { ttl: maxAge })
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
/** Calls that are running, by key, so calls with the same arguments share one run. */
|
|
403
|
+
const running$1 = /* @__PURE__ */ new Map();
|
|
404
|
+
let unnamed = 0;
|
|
405
|
+
/** The text of a value, as the store keeps it. */
|
|
406
|
+
function write(value) {
|
|
407
|
+
return toJSON(value, {
|
|
408
|
+
plugins: syncPlugins,
|
|
409
|
+
...serialOptions()
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
/**
|
|
413
|
+
* Makes a function that keeps its results for `maxAge` seconds, by its
|
|
414
|
+
* arguments, and returns a kept result in place of running again. Use it for
|
|
415
|
+
* data that every user sees the same, such as a list of products.
|
|
416
|
+
*
|
|
417
|
+
* - The function runs without the request: `getEvent()` throws in it, so a
|
|
418
|
+
* result never holds one user's data. Pass what it needs as arguments.
|
|
419
|
+
* - Arguments and results are values that brumate can send, such as plain
|
|
420
|
+
* objects, arrays, dates and maps.
|
|
421
|
+
* - Calls with the same arguments while one runs share that run.
|
|
422
|
+
* - `revalidate(tag)` drops the results of a tag.
|
|
423
|
+
*/
|
|
424
|
+
function cached(fn, options) {
|
|
425
|
+
const id = options.name ?? `#${unnamed++}`;
|
|
426
|
+
return async (...args) => {
|
|
427
|
+
if (options.name === void 0 && !("memory" in store)) throw new Error("Give cached a name, such as cached(fn, { name: \"products\", maxAge: 60 }), so every process finds its results in the store");
|
|
428
|
+
const key = `brumate:cache:${id}:${JSON.stringify(write(args))}`;
|
|
429
|
+
const tags = typeof options.tags === "function" ? options.tags(...args) : options.tags ?? [];
|
|
430
|
+
const event = currentEvent();
|
|
431
|
+
for (const tag of tags) if (!event?.cacheTags.has(tag)) event?.cacheTags.set(tag, void 0);
|
|
432
|
+
const versions = await tagVersions(tags);
|
|
433
|
+
for (const tag of tags) if (event?.cacheTags.get(tag) === void 0) event?.cacheTags.set(tag, versions[tag]);
|
|
434
|
+
const kept = await store.get(key);
|
|
435
|
+
if (kept) {
|
|
436
|
+
const entry = JSON.parse(kept);
|
|
437
|
+
if (entry.expires > Date.now() && tags.every((tag) => entry.tags[tag] === versions[tag])) return fromJSON(entry.value, { plugins: syncPlugins });
|
|
438
|
+
}
|
|
439
|
+
let run = running$1.get(key);
|
|
440
|
+
if (!run) {
|
|
441
|
+
const started = (async () => {
|
|
442
|
+
const value = await withEvent(void 0, () => fn(...args));
|
|
443
|
+
const entry = {
|
|
444
|
+
value: write(value),
|
|
445
|
+
expires: Date.now() + options.maxAge * 1e3,
|
|
446
|
+
tags: versions
|
|
447
|
+
};
|
|
448
|
+
await store.set(key, JSON.stringify(entry), options.maxAge);
|
|
449
|
+
return value;
|
|
450
|
+
})();
|
|
451
|
+
run = started;
|
|
452
|
+
running$1.set(key, started);
|
|
453
|
+
started.then(() => running$1.delete(key), () => running$1.delete(key));
|
|
454
|
+
}
|
|
455
|
+
return fromJSON(write(await run), { plugins: syncPlugins });
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
/** The store of `cached`, which the page cache of the server shares. */
|
|
459
|
+
function cacheStore() {
|
|
460
|
+
return store;
|
|
461
|
+
}
|
|
462
|
+
/** The versions of tags. A tag that was never revalidated has version `0`. */
|
|
463
|
+
async function tagVersions(tags) {
|
|
464
|
+
const versions = {};
|
|
465
|
+
await Promise.all([...tags].map(async (tag) => {
|
|
466
|
+
versions[tag] = await store.get(`brumate:tag:${tag}`) ?? "0";
|
|
467
|
+
}));
|
|
468
|
+
return versions;
|
|
469
|
+
}
|
|
470
|
+
let revalidations = 0;
|
|
471
|
+
/**
|
|
472
|
+
* Drops the results of `cached` functions with these tags, such as after a
|
|
473
|
+
* server function changes the data. The next call runs the function again.
|
|
474
|
+
* To show the new data on the page, call `refresh` too.
|
|
475
|
+
*/
|
|
476
|
+
async function revalidate(...tags) {
|
|
477
|
+
const version = `${Date.now()}.${revalidations++}`;
|
|
478
|
+
await Promise.all(tags.map((tag) => store.set(`brumate:tag:${tag}`, version, TAG_AGE)));
|
|
479
|
+
}
|
|
480
|
+
//#endregion
|
|
481
|
+
//#region src/runtime/router.ts
|
|
482
|
+
function key(path, file, params) {
|
|
483
|
+
return `${path}/${file} ${JSON.stringify(params)}`;
|
|
484
|
+
}
|
|
485
|
+
/** Puts a view in the children slot of a layout, with its other slots. */
|
|
486
|
+
function wrap(view, wrapper) {
|
|
487
|
+
return wrapper ? {
|
|
488
|
+
load: wrapper.layout,
|
|
489
|
+
key: wrapper.key,
|
|
490
|
+
slots: {
|
|
491
|
+
...wrapper.slots,
|
|
492
|
+
children: view
|
|
493
|
+
}
|
|
494
|
+
} : view;
|
|
495
|
+
}
|
|
496
|
+
/** The layout of a folder, or undefined when it has none. */
|
|
497
|
+
function wrapperOf(node, segments, index, params, path) {
|
|
498
|
+
return node.layout ? {
|
|
499
|
+
layout: node.layout,
|
|
500
|
+
key: key(path, "_layout", params),
|
|
501
|
+
slots: namedSlots(node, segments, index, params, path)
|
|
502
|
+
} : void 0;
|
|
503
|
+
}
|
|
504
|
+
/** The `_error.brm` of a folder, inside its layout. */
|
|
505
|
+
function errorIn(error, wrapper, params, path) {
|
|
506
|
+
return wrap({
|
|
507
|
+
load: error,
|
|
508
|
+
key: key(path, ERROR_VIEW, params),
|
|
509
|
+
slots: {}
|
|
510
|
+
}, wrapper);
|
|
511
|
+
}
|
|
512
|
+
/** The slots of a layout other than `children`, each matched against the same path. */
|
|
513
|
+
function namedSlots(node, segments, index, params, path) {
|
|
514
|
+
const slots = {};
|
|
515
|
+
for (const [name, slot] of Object.entries(node.slots ?? {})) {
|
|
516
|
+
const match = matchNode(slot, segments, index, params, `${path}/@${name}`);
|
|
517
|
+
if (match) slots[name] = match.view;
|
|
518
|
+
else if (slot.fallback) slots[name] = {
|
|
519
|
+
load: slot.fallback,
|
|
520
|
+
key: key(`${path}/@${name}`, "_default", params),
|
|
521
|
+
slots: {}
|
|
522
|
+
};
|
|
523
|
+
}
|
|
524
|
+
return slots;
|
|
525
|
+
}
|
|
526
|
+
/** The view of an `_error.brm`. Its component gets the error as a prop. */
|
|
527
|
+
const ERROR_VIEW = "_error";
|
|
528
|
+
/**
|
|
529
|
+
* Matches the segments from `index` on. `path` is the folders of `node` in
|
|
530
|
+
* the route files, such as `/todos/[id]`.
|
|
531
|
+
*/
|
|
532
|
+
function matchNode(node, segments, index, params, path = "") {
|
|
533
|
+
let inner;
|
|
534
|
+
if (index === segments.length) {
|
|
535
|
+
if (node.page || node.endpoint) inner = {
|
|
536
|
+
view: {
|
|
537
|
+
load: node.page ?? missingPage,
|
|
538
|
+
key: key(path, "index", params),
|
|
539
|
+
slots: {}
|
|
540
|
+
},
|
|
541
|
+
params,
|
|
542
|
+
route: path || "/",
|
|
543
|
+
endpoint: node.endpoint,
|
|
544
|
+
middleware: [],
|
|
545
|
+
errors: []
|
|
546
|
+
};
|
|
547
|
+
} else {
|
|
548
|
+
const first = segments[index];
|
|
549
|
+
const fixed = node.static?.[first];
|
|
550
|
+
inner = fixed && matchNode(fixed, segments, index + 1, params, `${path}/${first}`);
|
|
551
|
+
if (!inner && node.dynamic) {
|
|
552
|
+
const { name } = node.dynamic;
|
|
553
|
+
inner = matchNode(node.dynamic.node, segments, index + 1, {
|
|
554
|
+
...params,
|
|
555
|
+
[name]: first
|
|
556
|
+
}, `${path}/[${name}]`);
|
|
557
|
+
}
|
|
558
|
+
if (!inner && node.rest) {
|
|
559
|
+
const { name } = node.rest;
|
|
560
|
+
inner = matchNode(node.rest.node, segments, segments.length, {
|
|
561
|
+
...params,
|
|
562
|
+
[name]: segments.slice(index).join("/")
|
|
563
|
+
}, `${path}/[...${name}]`);
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
if (!inner) return;
|
|
567
|
+
const content = node.loading ? {
|
|
568
|
+
...inner.view,
|
|
569
|
+
loading: node.loading
|
|
570
|
+
} : inner.view;
|
|
571
|
+
const wrapper = wrapperOf(node, segments, index, params, path);
|
|
572
|
+
const errors = wrapper ? inner.errors.map((view) => wrap(view, wrapper)) : inner.errors;
|
|
573
|
+
if (node.error) errors.push(errorIn(node.error, wrapper, params, path));
|
|
574
|
+
return {
|
|
575
|
+
view: wrap(content, wrapper),
|
|
576
|
+
params: inner.params,
|
|
577
|
+
route: inner.route,
|
|
578
|
+
endpoint: inner.endpoint,
|
|
579
|
+
middleware: node.middleware ? [node.middleware, ...inner.middleware] : inner.middleware,
|
|
580
|
+
errors
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
/** An endpoint without a page: a GET that it does not answer has no page either. */
|
|
584
|
+
const missingPage = () => {
|
|
585
|
+
throw new Error("This path has an endpoint and no page");
|
|
586
|
+
};
|
|
587
|
+
/** Finds the route for a path. A path with a malformed escape, such as `/%E0`, matches none. */
|
|
588
|
+
function matchRoute(tree, pathname) {
|
|
589
|
+
let segments;
|
|
590
|
+
try {
|
|
591
|
+
segments = pathname.split("/").filter(Boolean).map((segment) => decodeURIComponent(segment));
|
|
592
|
+
} catch {
|
|
593
|
+
return;
|
|
594
|
+
}
|
|
595
|
+
return matchNode(tree, segments, 0, {});
|
|
596
|
+
}
|
|
597
|
+
/**
|
|
598
|
+
* The views for a path that no route matches: the `_error.brm` of the
|
|
599
|
+
* root, inside the root layout, and the root middleware.
|
|
600
|
+
*/
|
|
601
|
+
function notFound(tree) {
|
|
602
|
+
return {
|
|
603
|
+
errors: tree.error ? [errorIn(tree.error, wrapperOf(tree, [], 0, {}, ""), {}, "")] : [],
|
|
604
|
+
middleware: tree.middleware ? [tree.middleware] : []
|
|
605
|
+
};
|
|
606
|
+
}
|
|
607
|
+
//#endregion
|
|
608
|
+
//#region src/runtime/validate.ts
|
|
609
|
+
/**
|
|
610
|
+
* The error that `parse` throws when the value does not match. It answers
|
|
611
|
+
* with status 400 and its message, as any `ServerError` does. Its `issues`
|
|
612
|
+
* stay on the server.
|
|
613
|
+
*/
|
|
614
|
+
var ValidationError = class extends ServerError {
|
|
615
|
+
issues;
|
|
616
|
+
constructor(issues) {
|
|
617
|
+
super(summary(issues), { status: 400 });
|
|
618
|
+
this.name = "ValidationError";
|
|
619
|
+
this.issues = issues;
|
|
620
|
+
}
|
|
621
|
+
};
|
|
622
|
+
/** The longest message that `parse` sends, so a long input in a message stays short. */
|
|
623
|
+
const MAX_MESSAGE = 300;
|
|
624
|
+
/** The message of a `ValidationError`: the first issue with its path, and how many others there are. */
|
|
625
|
+
function summary(issues) {
|
|
626
|
+
const first = issues[0];
|
|
627
|
+
if (!first) return "Invalid input";
|
|
628
|
+
const path = first.path?.join(".");
|
|
629
|
+
let message = path ? `${path}: ${first.message}` : first.message;
|
|
630
|
+
if (message.length > MAX_MESSAGE) message = `${message.slice(0, MAX_MESSAGE)}…`;
|
|
631
|
+
const more = issues.length - 1;
|
|
632
|
+
return more > 0 ? `${message} (${more} more ${more === 1 ? "issue" : "issues"})` : message;
|
|
633
|
+
}
|
|
634
|
+
/**
|
|
635
|
+
* Copies an issue as plain data. A `{ key }` segment becomes its key, and a
|
|
636
|
+
* symbol becomes its text, such as `Symbol(id)`. Other fields of the issue,
|
|
637
|
+
* which some libraries add, are left out, so the input is not sent back.
|
|
638
|
+
*/
|
|
639
|
+
function plainIssue(issue) {
|
|
640
|
+
const plain = { message: String(issue.message) };
|
|
641
|
+
if (issue.path && issue.path.length > 0) plain.path = issue.path.map((segment) => {
|
|
642
|
+
const key = typeof segment === "object" && segment !== null ? segment.key : segment;
|
|
643
|
+
return typeof key === "number" ? key : String(key);
|
|
644
|
+
});
|
|
645
|
+
return plain;
|
|
646
|
+
}
|
|
647
|
+
/**
|
|
648
|
+
* Validates a value with a Standard Schema. Returns `{ value }` with the
|
|
649
|
+
* output of the schema, or `{ issues }` as plain data. It does not throw for
|
|
650
|
+
* a value that does not match.
|
|
651
|
+
*/
|
|
652
|
+
async function safeParse(schema, value) {
|
|
653
|
+
const props = schema["~standard"];
|
|
654
|
+
if (props?.version !== 1 || typeof props.validate !== "function") throw new TypeError("The schema is not a Standard Schema of version 1");
|
|
655
|
+
const result = await props.validate(value);
|
|
656
|
+
if (result.issues) return { issues: result.issues.map(plainIssue) };
|
|
657
|
+
return { value: result.value };
|
|
658
|
+
}
|
|
659
|
+
/**
|
|
660
|
+
* Validates a value with a Standard Schema, and returns the output of the
|
|
661
|
+
* schema. A value that does not match throws a `ValidationError`, which
|
|
662
|
+
* answers with status 400 and a message built from the first issue.
|
|
663
|
+
*
|
|
664
|
+
* ```ts
|
|
665
|
+
* async function save(input: unknown) {
|
|
666
|
+
* 'use server';
|
|
667
|
+
* const todo = await parse(Todo, input);
|
|
668
|
+
* await db.todos.save(todo);
|
|
669
|
+
* }
|
|
670
|
+
* ```
|
|
671
|
+
*/
|
|
672
|
+
async function parse(schema, value) {
|
|
673
|
+
const result = await safeParse(schema, value);
|
|
674
|
+
if (result.issues) throw new ValidationError(result.issues);
|
|
675
|
+
return result.value;
|
|
676
|
+
}
|
|
677
|
+
/**
|
|
678
|
+
* Validates the data of a form with a Standard Schema. The entries become a
|
|
679
|
+
* plain object first. Returns `{ value }` or `{ issues }`, and does not throw
|
|
680
|
+
* for data that does not match, so a function of `$action` can return the
|
|
681
|
+
* issues for the page to show.
|
|
682
|
+
*
|
|
683
|
+
* ```ts
|
|
684
|
+
* async function signUp(form: FormData) {
|
|
685
|
+
* 'use server';
|
|
686
|
+
* const result = await parseForm(SignUp, form);
|
|
687
|
+
* if (result.issues) {
|
|
688
|
+
* return { errors: fieldErrors(result.issues) };
|
|
689
|
+
* }
|
|
690
|
+
* }
|
|
691
|
+
* ```
|
|
692
|
+
*/
|
|
693
|
+
async function parseForm(schema, form) {
|
|
694
|
+
const values = formValues(form);
|
|
695
|
+
if (values.issues) return { issues: values.issues };
|
|
696
|
+
return safeParse(schema, values.value);
|
|
697
|
+
}
|
|
698
|
+
/**
|
|
699
|
+
* The messages of issues by field, for a page to show next to each field.
|
|
700
|
+
* The key is the path joined with dots, such as `address.city`. Issues
|
|
701
|
+
* without a path, and a path of `__proto__`, are under the key `''`. The
|
|
702
|
+
* result is plain data, so a server function can return it.
|
|
703
|
+
*/
|
|
704
|
+
function fieldErrors(issues) {
|
|
705
|
+
const errors = {};
|
|
706
|
+
for (const issue of issues) {
|
|
707
|
+
let key = plainIssue(issue).path?.join(".") ?? "";
|
|
708
|
+
if (key === "__proto__") key = "";
|
|
709
|
+
(Object.hasOwn(errors, key) ? errors[key] : errors[key] = []).push(String(issue.message));
|
|
710
|
+
}
|
|
711
|
+
return errors;
|
|
712
|
+
}
|
|
713
|
+
//#endregion
|
|
714
|
+
//#region src/runtime/submission.ts
|
|
715
|
+
/** True for a file, so it is not sent back. */
|
|
716
|
+
const isBlob = (value) => typeof Blob !== "undefined" && value instanceof Blob;
|
|
717
|
+
/** The values to send back: without files and hidden fields. */
|
|
718
|
+
function echo(value, hidden, path = []) {
|
|
719
|
+
if (path.length > 0 && hidden.has(formatPath(path))) return;
|
|
720
|
+
if (isBlob(value)) return;
|
|
721
|
+
if (Array.isArray(value)) return value.map((item, index) => echo(item, hidden, [...path, index]));
|
|
722
|
+
if (typeof value === "object" && value !== null) {
|
|
723
|
+
const copy = {};
|
|
724
|
+
for (const [key, item] of Object.entries(value)) {
|
|
725
|
+
const next = echo(item, hidden, [...path, key]);
|
|
726
|
+
if (next !== void 0) copy[key] = next;
|
|
727
|
+
}
|
|
728
|
+
return copy;
|
|
729
|
+
}
|
|
730
|
+
return value;
|
|
731
|
+
}
|
|
732
|
+
/** A new ID for a reply, which the keys of the items of a changed list start with. */
|
|
733
|
+
function replyId() {
|
|
734
|
+
return Math.random().toString(36).slice(2, 10);
|
|
735
|
+
}
|
|
736
|
+
/**
|
|
737
|
+
* Reads the data of a form that `createForm` shows. It turns the entries
|
|
738
|
+
* into an object, as `parseForm` does, applies the intent of the button
|
|
739
|
+
* that was pressed, and validates the values with a Standard Schema when
|
|
740
|
+
* the button was not an intent. It does not throw for data that does not
|
|
741
|
+
* match. `reply()` gives what the function returns, for `createForm` to show.
|
|
742
|
+
*
|
|
743
|
+
* ```ts
|
|
744
|
+
* async function save(form: FormData) {
|
|
745
|
+
* 'use server';
|
|
746
|
+
* const submission = await parseSubmission(Order, form);
|
|
747
|
+
* if (submission.status !== 'success') {
|
|
748
|
+
* return submission.reply();
|
|
749
|
+
* }
|
|
750
|
+
* await db.orders.save(submission.value);
|
|
751
|
+
* return submission.reply({ reset: true });
|
|
752
|
+
* }
|
|
753
|
+
* ```
|
|
754
|
+
*/
|
|
755
|
+
async function parseSubmission(schema, form, options = {}) {
|
|
756
|
+
const hidden = new Set(options.hide);
|
|
757
|
+
const id = replyId();
|
|
758
|
+
const make = (status, payload, issues, list) => ({
|
|
759
|
+
payload,
|
|
760
|
+
reply(reply = {}) {
|
|
761
|
+
const grouped = groupIssues(issues);
|
|
762
|
+
const errors = { ...grouped.errors };
|
|
763
|
+
for (const [name, messages] of Object.entries(reply.fieldErrors ?? {})) errors[name] = [...Object.hasOwn(errors, name) ? errors[name] : [], ...messages];
|
|
764
|
+
const keys = {};
|
|
765
|
+
const items = list === void 0 ? void 0 : getAt(payload, parsePath(list));
|
|
766
|
+
if (list !== void 0 && Array.isArray(items)) keys[list] = items.map((_, index) => `${id}-${index}`);
|
|
767
|
+
const result = {
|
|
768
|
+
status,
|
|
769
|
+
value: reply.reset ? void 0 : echo(payload, hidden),
|
|
770
|
+
errors: reply.reset ? {} : errors,
|
|
771
|
+
formErrors: [...grouped.formErrors, ...reply.formErrors ?? []],
|
|
772
|
+
keys: reply.reset ? {} : keys,
|
|
773
|
+
id
|
|
774
|
+
};
|
|
775
|
+
if (reply.reset) result.reset = true;
|
|
776
|
+
return result;
|
|
777
|
+
}
|
|
778
|
+
});
|
|
779
|
+
const raw = form.get(INTENT);
|
|
780
|
+
const values = formValues(form, (name) => name === INTENT);
|
|
781
|
+
if (values.issues) return {
|
|
782
|
+
status: "error",
|
|
783
|
+
issues: values.issues,
|
|
784
|
+
...make("error", void 0, values.issues)
|
|
785
|
+
};
|
|
786
|
+
let payload = values.value;
|
|
787
|
+
if (raw === null) {
|
|
788
|
+
const result = await safeParse(schema, payload);
|
|
789
|
+
if (result.issues) return {
|
|
790
|
+
status: "error",
|
|
791
|
+
issues: result.issues,
|
|
792
|
+
...make("error", payload, result.issues)
|
|
793
|
+
};
|
|
794
|
+
return {
|
|
795
|
+
status: "success",
|
|
796
|
+
value: result.value,
|
|
797
|
+
...make("success", payload, [])
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
const intent = typeof raw === "string" ? parseIntent(raw) : void 0;
|
|
801
|
+
const applied = intent && applyIntent(payload, intent);
|
|
802
|
+
if (!intent || !applied) {
|
|
803
|
+
const issues = [{ message: "The form asked for a change that it cannot make" }];
|
|
804
|
+
return {
|
|
805
|
+
status: "error",
|
|
806
|
+
intent,
|
|
807
|
+
issues,
|
|
808
|
+
...make("error", payload, issues)
|
|
809
|
+
};
|
|
810
|
+
}
|
|
811
|
+
payload = applied.value ?? void 0;
|
|
812
|
+
if (intent.type === "validate") {
|
|
813
|
+
const result = await safeParse(schema, payload);
|
|
814
|
+
const name = intent.name;
|
|
815
|
+
const issues = (result.issues ?? []).filter((issue) => {
|
|
816
|
+
const path = issue.path ? formatPath(issue.path) : "";
|
|
817
|
+
return path === name || path.startsWith(`${name}.`) || path.startsWith(`${name}[`);
|
|
818
|
+
});
|
|
819
|
+
return {
|
|
820
|
+
status: "intent",
|
|
821
|
+
intent,
|
|
822
|
+
...make("intent", payload, issues)
|
|
823
|
+
};
|
|
824
|
+
}
|
|
825
|
+
return {
|
|
826
|
+
status: "intent",
|
|
827
|
+
intent,
|
|
828
|
+
...make("intent", payload, [], applied.list)
|
|
829
|
+
};
|
|
830
|
+
}
|
|
831
|
+
//#endregion
|
|
832
|
+
//#region src/runtime/rate-limit.ts
|
|
833
|
+
/**
|
|
834
|
+
* The error of a request over its limit. Its status is 429, and
|
|
835
|
+
* `retryAfter` is how many seconds to wait. In the browser, the call rejects
|
|
836
|
+
* with it, and `retryAfter` comes from the `Retry-After` header.
|
|
837
|
+
*/
|
|
838
|
+
var RateLimitError = class extends ServerError {
|
|
839
|
+
retryAfter;
|
|
840
|
+
constructor(retryAfter) {
|
|
841
|
+
super(`Too many requests. Try again in ${retryAfter} ${retryAfter === 1 ? "second" : "seconds"}`, { status: 429 });
|
|
842
|
+
this.name = "RateLimitError";
|
|
843
|
+
this.retryAfter = retryAfter;
|
|
844
|
+
}
|
|
845
|
+
};
|
|
846
|
+
const UNITS = {
|
|
847
|
+
ms: 1,
|
|
848
|
+
s: 1e3,
|
|
849
|
+
m: 6e4,
|
|
850
|
+
h: 36e5,
|
|
851
|
+
d: 864e5
|
|
852
|
+
};
|
|
853
|
+
/** The length of a window in milliseconds. */
|
|
854
|
+
function windowMs(window) {
|
|
855
|
+
if (typeof window === "number") return window;
|
|
856
|
+
const match = /^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/.exec(window);
|
|
857
|
+
if (!match) throw new TypeError(`The window "${window}" is not a length such as "10s", "1m" or "1h"`);
|
|
858
|
+
return Number(match[1]) * UNITS[match[2]];
|
|
859
|
+
}
|
|
860
|
+
/** Counts in memory, per process. Expired keys go when they are read, and in a sweep now and then. */
|
|
861
|
+
function createMemoryStore(now = Date.now) {
|
|
862
|
+
const counts = /* @__PURE__ */ new Map();
|
|
863
|
+
let sweeps = 0;
|
|
864
|
+
const sweep = () => {
|
|
865
|
+
if (++sweeps % 1e3 !== 0) return;
|
|
866
|
+
const time = now();
|
|
867
|
+
for (const [key, entry] of counts) if (entry.expires <= time) counts.delete(key);
|
|
868
|
+
};
|
|
869
|
+
return {
|
|
870
|
+
increment(key, ttl) {
|
|
871
|
+
sweep();
|
|
872
|
+
const time = now();
|
|
873
|
+
const entry = counts.get(key);
|
|
874
|
+
if (!entry || entry.expires <= time) {
|
|
875
|
+
counts.set(key, {
|
|
876
|
+
count: 1,
|
|
877
|
+
expires: time + ttl
|
|
878
|
+
});
|
|
879
|
+
return 1;
|
|
880
|
+
}
|
|
881
|
+
entry.count++;
|
|
882
|
+
return entry.count;
|
|
883
|
+
},
|
|
884
|
+
get(key) {
|
|
885
|
+
const entry = counts.get(key);
|
|
886
|
+
return entry && entry.expires > now() ? entry.count : void 0;
|
|
887
|
+
}
|
|
888
|
+
};
|
|
889
|
+
}
|
|
890
|
+
const config = {};
|
|
891
|
+
let memory;
|
|
892
|
+
let warned = false;
|
|
893
|
+
/** The clock, which tests replace. */
|
|
894
|
+
let clock = Date.now;
|
|
895
|
+
/** Sets the defaults of every limit: the store, the trusted proxies, and whether limits count. */
|
|
896
|
+
function configureRateLimit(options) {
|
|
897
|
+
for (const range of options.proxies ?? []) parseRange(range);
|
|
898
|
+
Object.assign(config, options);
|
|
899
|
+
}
|
|
900
|
+
/** True in development and in tests, from `NODE_ENV`. A runtime without it is production. */
|
|
901
|
+
function isDevelopment() {
|
|
902
|
+
const mode = globalThis.process?.env?.NODE_ENV;
|
|
903
|
+
return mode === "development" || mode === "test";
|
|
904
|
+
}
|
|
905
|
+
/**
|
|
906
|
+
* What a limit counts per: the server function, the pattern of the route,
|
|
907
|
+
* such as `/api/[id]`, or one count for every path that no route matches.
|
|
908
|
+
*/
|
|
909
|
+
function targetOf(event) {
|
|
910
|
+
return event.call?.id ?? event.route ?? "(no route)";
|
|
911
|
+
}
|
|
912
|
+
/**
|
|
913
|
+
* The key of a request: the key of the app, or the address of the client.
|
|
914
|
+
* Without either, callers would share one count, and one client could use
|
|
915
|
+
* up the limit of all. So it throws in production. In development it warns
|
|
916
|
+
* once and returns undefined, and the limit does not count.
|
|
917
|
+
*/
|
|
918
|
+
async function keyOf(event, options) {
|
|
919
|
+
const key = await options.key?.(event, event.call?.args ?? []) ?? clientAddress(event);
|
|
920
|
+
if (key !== void 0) return key;
|
|
921
|
+
const message = `rateLimit: the request to "${targetOf(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.`;
|
|
922
|
+
if (!isDevelopment()) throw new Error(message);
|
|
923
|
+
if (!warned) {
|
|
924
|
+
warned = true;
|
|
925
|
+
console.warn(`${message} Until then, the limit does not count in development.`);
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
/**
|
|
929
|
+
* Counts a request, and throws a `RateLimitError` when its key has made
|
|
930
|
+
* more than `max` requests in the window.
|
|
931
|
+
*/
|
|
932
|
+
async function check(event, options) {
|
|
933
|
+
if (event.prerender || !(options.enabled ?? config.enabled ?? true)) return;
|
|
934
|
+
const key = await keyOf(event, options);
|
|
935
|
+
if (key === void 0) return;
|
|
936
|
+
const name = `${key} ${targetOf(event)}`;
|
|
937
|
+
const store = options.store ?? config.store ?? (memory ??= createMemoryStore(clock));
|
|
938
|
+
const window = windowMs(options.window);
|
|
939
|
+
const now = clock();
|
|
940
|
+
const bucket = Math.floor(now / window);
|
|
941
|
+
const elapsed = now - bucket * window;
|
|
942
|
+
const [current, previous = 0] = await Promise.all([store.increment(`${name} ${bucket}`, window * 2), store.get(`${name} ${bucket - 1}`)]);
|
|
943
|
+
if (current + previous * (1 - elapsed / window) <= options.max) return;
|
|
944
|
+
const room = options.max - current - 1;
|
|
945
|
+
const wait = room >= 0 && previous > 0 ? window * (1 - room / previous) - elapsed : window - elapsed + (current > options.max - 1 ? window * (1 - (options.max - 1) / current) : 0);
|
|
946
|
+
const retryAfter = Math.max(1, Math.ceil(wait / 1e3));
|
|
947
|
+
event.headers.set("retry-after", String(retryAfter));
|
|
948
|
+
throw new RateLimitError(retryAfter);
|
|
949
|
+
}
|
|
950
|
+
/**
|
|
951
|
+
* Limits how often a key, such as the user or the address of the client,
|
|
952
|
+
* can call a server function. Call it first thing in the function, before
|
|
953
|
+
* its first `await`, as `getEvent()`:
|
|
954
|
+
*
|
|
955
|
+
* ```ts
|
|
956
|
+
* async function signIn(email: string, password: string) {
|
|
957
|
+
* 'use server';
|
|
958
|
+
* await rateLimit({ ...rateLimit.strict, key: () => email.toLowerCase() });
|
|
959
|
+
* // …
|
|
960
|
+
* }
|
|
961
|
+
* ```
|
|
962
|
+
*
|
|
963
|
+
* The fourth call in 10 seconds for one email rejects with a
|
|
964
|
+
* `RateLimitError`, with status 429 and `Retry-After`, and the rest of the
|
|
965
|
+
* function does not run. Without a `key`, the limit counts by the address
|
|
966
|
+
* of the client, which the server passes to its handler as `address`. In
|
|
967
|
+
* production, a limit with neither throws. `rateLimit.middleware(options)`
|
|
968
|
+
* limits every request under a folder of routes, or of the whole app from
|
|
969
|
+
* the entry.
|
|
970
|
+
*/
|
|
971
|
+
const rateLimit = Object.assign((options) => {
|
|
972
|
+
return check(options.event ?? getEvent(), options);
|
|
973
|
+
}, {
|
|
974
|
+
middleware: (options) => async (target, next) => {
|
|
975
|
+
const event = target instanceof RequestEvent ? target : options.event ?? getEvent();
|
|
976
|
+
try {
|
|
977
|
+
await check(event, options);
|
|
978
|
+
} catch (error) {
|
|
979
|
+
if (error instanceof RateLimitError) return new Response(error.message, {
|
|
980
|
+
status: 429,
|
|
981
|
+
headers: {
|
|
982
|
+
"retry-after": String(error.retryAfter),
|
|
983
|
+
"content-type": "text/plain"
|
|
984
|
+
}
|
|
985
|
+
});
|
|
986
|
+
throw error;
|
|
987
|
+
}
|
|
988
|
+
return next();
|
|
989
|
+
},
|
|
990
|
+
strict: {
|
|
991
|
+
max: 3,
|
|
992
|
+
window: "10s"
|
|
993
|
+
}
|
|
994
|
+
});
|
|
995
|
+
/** The 16 bytes of an address, or undefined for text that is not one. */
|
|
996
|
+
function parseAddress(text) {
|
|
997
|
+
const value = text.trim().replace(/^\[|\]$/g, "");
|
|
998
|
+
if (value.includes(":")) return parseIPv6(value);
|
|
999
|
+
const parts = value.split(".");
|
|
1000
|
+
if (parts.length !== 4 || !parts.every((part) => /^\d{1,3}$/.test(part) && Number(part) < 256)) return;
|
|
1001
|
+
const bytes = /* @__PURE__ */ new Uint8Array(16);
|
|
1002
|
+
bytes[10] = 255;
|
|
1003
|
+
bytes[11] = 255;
|
|
1004
|
+
parts.forEach((part, index) => {
|
|
1005
|
+
bytes[12 + index] = Number(part);
|
|
1006
|
+
});
|
|
1007
|
+
return bytes;
|
|
1008
|
+
}
|
|
1009
|
+
function parseIPv6(value) {
|
|
1010
|
+
const tail = /^(.*:)(\d+\.\d+\.\d+\.\d+)$/.exec(value);
|
|
1011
|
+
let text = value;
|
|
1012
|
+
if (tail) {
|
|
1013
|
+
const v4 = parseAddress(tail[2]);
|
|
1014
|
+
if (!v4) return;
|
|
1015
|
+
text = `${tail[1]}${(v4[12] << 8 | v4[13]).toString(16)}:${(v4[14] << 8 | v4[15]).toString(16)}`;
|
|
1016
|
+
}
|
|
1017
|
+
const halves = text.split("::");
|
|
1018
|
+
if (halves.length > 2) return;
|
|
1019
|
+
const head = halves[0] ? halves[0].split(":") : [];
|
|
1020
|
+
const rest = halves[1] ? halves[1].split(":") : [];
|
|
1021
|
+
const missing = 8 - head.length - rest.length;
|
|
1022
|
+
if (missing < 0 || halves.length === 1 && missing !== 0) return;
|
|
1023
|
+
const groups = [
|
|
1024
|
+
...head,
|
|
1025
|
+
...Array(missing).fill("0"),
|
|
1026
|
+
...rest
|
|
1027
|
+
];
|
|
1028
|
+
const bytes = /* @__PURE__ */ new Uint8Array(16);
|
|
1029
|
+
for (const [index, group] of groups.entries()) {
|
|
1030
|
+
if (!/^[\da-f]{1,4}$/i.test(group)) return;
|
|
1031
|
+
const number = Number.parseInt(group, 16);
|
|
1032
|
+
bytes[index * 2] = number >> 8;
|
|
1033
|
+
bytes[index * 2 + 1] = number & 255;
|
|
1034
|
+
}
|
|
1035
|
+
return bytes;
|
|
1036
|
+
}
|
|
1037
|
+
function isIPv4(bytes) {
|
|
1038
|
+
return bytes.slice(0, 10).every((byte) => byte === 0) && bytes[10] === 255 && bytes[11] === 255;
|
|
1039
|
+
}
|
|
1040
|
+
/**
|
|
1041
|
+
* Reads a range: an address, or a CIDR such as `10.0.0.0/8` or `fd00::/8`.
|
|
1042
|
+
* Throws for anything else, such as `10.0.0.0/` or `10.0.0.0/33`, since a
|
|
1043
|
+
* range that matched every address would trust any `X-Forwarded-For`.
|
|
1044
|
+
*/
|
|
1045
|
+
function parseRange(range) {
|
|
1046
|
+
const [text, length, ...extra] = range.split("/");
|
|
1047
|
+
const base = parseAddress(text);
|
|
1048
|
+
const v4 = base !== void 0 && isIPv4(base);
|
|
1049
|
+
if (!base || extra.length > 0 || length !== void 0 && (!/^\d{1,3}$/.test(length) || Number(length) > (v4 ? 32 : 128))) throw new TypeError(`The proxy range "${range}" is not an address, or an address and a prefix length such as "10.0.0.0/8"`);
|
|
1050
|
+
return {
|
|
1051
|
+
base,
|
|
1052
|
+
bits: length === void 0 ? 128 : Number(length) + (v4 ? 96 : 0)
|
|
1053
|
+
};
|
|
1054
|
+
}
|
|
1055
|
+
function inParsedRange(address, { base, bits }) {
|
|
1056
|
+
if (isIPv4(base) !== isIPv4(address)) return false;
|
|
1057
|
+
for (let bit = 0; bit < bits; bit++) {
|
|
1058
|
+
const mask = 128 >> bit % 8;
|
|
1059
|
+
if (((address[bit >> 3] ^ base[bit >> 3]) & mask) !== 0) return false;
|
|
1060
|
+
}
|
|
1061
|
+
return true;
|
|
1062
|
+
}
|
|
1063
|
+
/** The text of an address. An IPv6 address counts by its /64, since one client often holds a whole subnet. */
|
|
1064
|
+
function formatAddress(bytes) {
|
|
1065
|
+
if (isIPv4(bytes)) return bytes.slice(12).join(".");
|
|
1066
|
+
const groups = [];
|
|
1067
|
+
for (let index = 0; index < 8; index++) groups.push(index < 4 ? (bytes[index * 2] << 8 | bytes[index * 2 + 1]).toString(16) : "0");
|
|
1068
|
+
return groups.join(":");
|
|
1069
|
+
}
|
|
1070
|
+
/**
|
|
1071
|
+
* The address of the client of a request. It is the address that the server
|
|
1072
|
+
* saw, which the handler of the server passes as `address`. When that
|
|
1073
|
+
* address is one of the proxies that `configureRateLimit({ proxies })`
|
|
1074
|
+
* names, it comes from `X-Forwarded-For`: the header is read from the right,
|
|
1075
|
+
* past the trusted proxies, because a client can write anything at its
|
|
1076
|
+
* left. An IPv6 address counts by its /64.
|
|
1077
|
+
*
|
|
1078
|
+
* Undefined when the server passed no address, whatever the headers say,
|
|
1079
|
+
* since nothing then shows that the header comes from a proxy. Undefined too
|
|
1080
|
+
* when the first hop past the proxies is not an address.
|
|
1081
|
+
*/
|
|
1082
|
+
function clientAddress(event, proxies = config.proxies ?? []) {
|
|
1083
|
+
const seen = event.address === void 0 ? void 0 : parseAddress(event.address);
|
|
1084
|
+
if (!seen) return;
|
|
1085
|
+
const ranges = proxies.map(parseRange);
|
|
1086
|
+
const trusted = (address) => ranges.some((range) => inParsedRange(address, range));
|
|
1087
|
+
if (!trusted(seen)) return formatAddress(seen);
|
|
1088
|
+
const hops = (event.request.headers.get("x-forwarded-for") ?? "").split(",").filter((hop) => hop.trim() !== "");
|
|
1089
|
+
let client = seen;
|
|
1090
|
+
for (let index = hops.length - 1; index >= 0; index--) {
|
|
1091
|
+
const address = parseAddress(hops[index]);
|
|
1092
|
+
if (!address) return;
|
|
1093
|
+
client = address;
|
|
1094
|
+
if (!trusted(address)) break;
|
|
1095
|
+
}
|
|
1096
|
+
return formatAddress(client);
|
|
1097
|
+
}
|
|
1098
|
+
//#endregion
|
|
1099
|
+
//#region src/runtime/idempotent.ts
|
|
1100
|
+
/** Runs that are going on, by key, so a second post while the first runs waits for it. */
|
|
1101
|
+
const running = /* @__PURE__ */ new Map();
|
|
1102
|
+
/**
|
|
1103
|
+
* Makes a server function that runs once for each form that the server
|
|
1104
|
+
* renders for it. A second post of the same form, such as a double click
|
|
1105
|
+
* before the page loaded or a post again after a reload, gets the result of
|
|
1106
|
+
* the first, or the same redirect, without running the function again.
|
|
1107
|
+
*
|
|
1108
|
+
* - It works for the exported functions of a `'use server'` file, used as the
|
|
1109
|
+
* `action` of a form.
|
|
1110
|
+
* - The key is in the URL of the form, so a page with such a form is not
|
|
1111
|
+
* cached for everyone. Each render has a new key.
|
|
1112
|
+
* - With scripts, the form gets a new key after each answer, so a post that
|
|
1113
|
+
* the user means again runs again.
|
|
1114
|
+
* - A call without a key, such as from a handler, runs as usual.
|
|
1115
|
+
*/
|
|
1116
|
+
function idempotent(fn, options = {}) {
|
|
1117
|
+
const maxAge = options.maxAge ?? 600;
|
|
1118
|
+
const wrapper = ((...args) => {
|
|
1119
|
+
const event = currentEvent();
|
|
1120
|
+
const key = event && new URL(event.request.url).searchParams.get("__key");
|
|
1121
|
+
const id = idempotentId.get(wrapper);
|
|
1122
|
+
if (!event || !key || !id || !/^[\w-]{8,64}$/.test(key)) return fn(...args);
|
|
1123
|
+
const storeKey = `brumate:once:${id}:${key}`;
|
|
1124
|
+
let run = running.get(storeKey);
|
|
1125
|
+
if (!run) {
|
|
1126
|
+
run = (async () => {
|
|
1127
|
+
const kept = await cacheStore().get(storeKey);
|
|
1128
|
+
if (kept) return fromJSON(JSON.parse(kept), { plugins: syncPlugins });
|
|
1129
|
+
let outcome;
|
|
1130
|
+
try {
|
|
1131
|
+
outcome = { result: await withEvent(event, () => fn(...args)) };
|
|
1132
|
+
} catch (error) {
|
|
1133
|
+
if (!isRedirect(error)) throw error;
|
|
1134
|
+
outcome = { redirect: {
|
|
1135
|
+
location: error.location,
|
|
1136
|
+
status: error.status
|
|
1137
|
+
} };
|
|
1138
|
+
}
|
|
1139
|
+
const text = JSON.stringify(toJSON(outcome, {
|
|
1140
|
+
plugins: syncPlugins,
|
|
1141
|
+
...serialOptions()
|
|
1142
|
+
}));
|
|
1143
|
+
await cacheStore().set(storeKey, text, maxAge);
|
|
1144
|
+
return outcome;
|
|
1145
|
+
})();
|
|
1146
|
+
running.set(storeKey, run);
|
|
1147
|
+
run.then(() => running.delete(storeKey), () => running.delete(storeKey));
|
|
1148
|
+
}
|
|
1149
|
+
return run.then((outcome) => {
|
|
1150
|
+
if ("redirect" in outcome) redirect(outcome.redirect.location, outcome.redirect.status);
|
|
1151
|
+
return outcome.result;
|
|
1152
|
+
});
|
|
1153
|
+
});
|
|
1154
|
+
Object.defineProperty(wrapper, IDEMPOTENT, { value: true });
|
|
1155
|
+
return wrapper;
|
|
1156
|
+
}
|
|
1157
|
+
//#endregion
|
|
1158
|
+
//#region src/runtime/server.ts
|
|
1159
|
+
/** What `$bind(name)` passes a child: the value of the name, and the scope and slot it writes. */
|
|
1160
|
+
function binding(value, scope, slot, set) {
|
|
1161
|
+
return new Binding(value, new SlotReference(scope, slot), set);
|
|
1162
|
+
}
|
|
1163
|
+
/**
|
|
1164
|
+
* The `#loading` bodies of a `#reveal` block, in the order of the markup.
|
|
1165
|
+
* When a body is ready, the stream asks the group, which sends the bodies
|
|
1166
|
+
* that its order lets show. The data of every body still loads at once.
|
|
1167
|
+
*/
|
|
1168
|
+
var RevealGroup = class {
|
|
1169
|
+
order;
|
|
1170
|
+
collapsed;
|
|
1171
|
+
/** The bodies that stream, each with how to send it once it is ready. */
|
|
1172
|
+
members = [];
|
|
1173
|
+
/** The fallbacks that `collapsed` hides until the body before them shows. */
|
|
1174
|
+
hidden = /* @__PURE__ */ new Set();
|
|
1175
|
+
closed = false;
|
|
1176
|
+
constructor(order, collapsed) {
|
|
1177
|
+
this.order = order;
|
|
1178
|
+
this.collapsed = collapsed;
|
|
1179
|
+
}
|
|
1180
|
+
/** True when a body that is ready can render in place, before the bodies that stream. */
|
|
1181
|
+
mayShow() {
|
|
1182
|
+
return this.order === "natural" || this.order === "sequential" && this.members.length === 0;
|
|
1183
|
+
}
|
|
1184
|
+
/** True when the fallback of the next body that streams waits, for `collapsed`. */
|
|
1185
|
+
hides() {
|
|
1186
|
+
return this.collapsed && this.members.length > 0;
|
|
1187
|
+
}
|
|
1188
|
+
add(id) {
|
|
1189
|
+
this.members.push({ id });
|
|
1190
|
+
}
|
|
1191
|
+
/** The body is ready, or failed with nothing to send. `send` writes it, and runs `after` with it. */
|
|
1192
|
+
ready(id, send) {
|
|
1193
|
+
const member = this.members.find((item) => item.id === id);
|
|
1194
|
+
if (member) {
|
|
1195
|
+
member.send = send;
|
|
1196
|
+
this.flush();
|
|
1197
|
+
} else send("");
|
|
1198
|
+
}
|
|
1199
|
+
/** The block ended, so the group knows its last body. */
|
|
1200
|
+
close() {
|
|
1201
|
+
this.closed = true;
|
|
1202
|
+
this.flush();
|
|
1203
|
+
}
|
|
1204
|
+
flush() {
|
|
1205
|
+
const { members } = this;
|
|
1206
|
+
const sendAt = (index) => {
|
|
1207
|
+
const member = members[index];
|
|
1208
|
+
member.sent = true;
|
|
1209
|
+
const next = members[index + 1];
|
|
1210
|
+
member.send(next && this.hidden.has(next.id) ? `$bF(${scriptJSON(next.id)})` : "");
|
|
1211
|
+
};
|
|
1212
|
+
if (this.order === "natural") members.forEach((member, index) => member.send && !member.sent && sendAt(index));
|
|
1213
|
+
else if (this.order === "sequential") {
|
|
1214
|
+
for (let index = 0; index < members.length && members[index].send; index++) if (!members[index].sent) sendAt(index);
|
|
1215
|
+
} else if (this.closed && this.order === "backwards") {
|
|
1216
|
+
for (let index = members.length - 1; index >= 0 && members[index].send; index--) if (!members[index].sent) sendAt(index);
|
|
1217
|
+
} else if (this.closed && members.every((member) => member.send)) members.forEach((member, index) => !member.sent && sendAt(index));
|
|
1218
|
+
}
|
|
1219
|
+
};
|
|
1220
|
+
/** True if a boundary holds `target`, whose ID starts with the boundary's ID and a dot. */
|
|
1221
|
+
function holdsBoundary(id, target) {
|
|
1222
|
+
return typeof target === "string" && target.startsWith(`${id}.`);
|
|
1223
|
+
}
|
|
1224
|
+
function spaceId(space, n) {
|
|
1225
|
+
return space.prefix ? `${space.prefix}${n}` : n;
|
|
1226
|
+
}
|
|
1227
|
+
/**
|
|
1228
|
+
* True for an ID that a render made after `mark`: a scope of the same space
|
|
1229
|
+
* from its counter on, or a scope inside a block or boundary from then on.
|
|
1230
|
+
*/
|
|
1231
|
+
function madeAfter(mark, id) {
|
|
1232
|
+
const text = String(id);
|
|
1233
|
+
if (!text.startsWith(mark.prefix)) return false;
|
|
1234
|
+
const rest = text.slice(mark.prefix.length);
|
|
1235
|
+
const dot = rest.indexOf(".");
|
|
1236
|
+
return dot === -1 ? Number(rest) >= mark.scope : Number(rest.slice(0, dot)) >= mark.boundary;
|
|
1237
|
+
}
|
|
1238
|
+
/**
|
|
1239
|
+
* Tracks the scopes of one render. A `#loading` body renders in a child
|
|
1240
|
+
* context, so its scopes are written with its markup.
|
|
1241
|
+
*/
|
|
1242
|
+
var Context = class Context {
|
|
1243
|
+
/**
|
|
1244
|
+
* The scopes of this render, in the order it made them, with their
|
|
1245
|
+
* records. A record that this render adds to a scope of another render,
|
|
1246
|
+
* such as a link from a `#loading` body to a scope of the page, is here
|
|
1247
|
+
* too, as a scope of its own.
|
|
1248
|
+
*/
|
|
1249
|
+
scopes = [];
|
|
1250
|
+
/**
|
|
1251
|
+
* Every ID space of the page, across the renders of `#loading` bodies, on
|
|
1252
|
+
* the root context. A scope is found by its ID in the entries of its space.
|
|
1253
|
+
* The spaces are put in a map by prefix only when a scope is looked up
|
|
1254
|
+
* outside the blocks that are open, since a render makes many and looks
|
|
1255
|
+
* up few, and each string key costs a hash.
|
|
1256
|
+
*/
|
|
1257
|
+
made = [];
|
|
1258
|
+
byPrefix;
|
|
1259
|
+
indexed = 0;
|
|
1260
|
+
/** The records that this render adds to scopes of other renders, by ID. */
|
|
1261
|
+
partials;
|
|
1262
|
+
/** The scope that the render used last, since it uses one a few times in a row. */
|
|
1263
|
+
last;
|
|
1264
|
+
root;
|
|
1265
|
+
/** The ID spaces of the blocks that the render is in, from the outside in. */
|
|
1266
|
+
spaces;
|
|
1267
|
+
baseId;
|
|
1268
|
+
/** The `#defer` body to render, in the request for it. The rest of the page renders no body. */
|
|
1269
|
+
target;
|
|
1270
|
+
/** True in the context of the target body and the bodies inside it. */
|
|
1271
|
+
inTarget = false;
|
|
1272
|
+
boundaries = [];
|
|
1273
|
+
styles = /* @__PURE__ */ new Set();
|
|
1274
|
+
/** Markup of `#portal` blocks, written at the end of the page. */
|
|
1275
|
+
portals = [];
|
|
1276
|
+
/** Markup of `#head` blocks. */
|
|
1277
|
+
heads = [];
|
|
1278
|
+
pageTitle;
|
|
1279
|
+
/** The titles that this render set, and whether they all came from a `<title>` in `#head`. */
|
|
1280
|
+
titles = {
|
|
1281
|
+
count: 0,
|
|
1282
|
+
markup: true
|
|
1283
|
+
};
|
|
1284
|
+
onBoundary;
|
|
1285
|
+
/** The scope that renders the next component, which becomes its owner. */
|
|
1286
|
+
owner;
|
|
1287
|
+
/**
|
|
1288
|
+
* Children that render where they are inserted: the scope of the markup
|
|
1289
|
+
* that wrote them, and the scope where they are, for their contexts.
|
|
1290
|
+
*/
|
|
1291
|
+
inserted = [];
|
|
1292
|
+
/** Takes back what this context added to the page, from the newest, for `restore`. */
|
|
1293
|
+
undo = [];
|
|
1294
|
+
/** The URL prefix of server function calls. */
|
|
1295
|
+
rpcPrefix = "/_brumate";
|
|
1296
|
+
/** The ID of the build, for forms that post to server functions. See `RenderOptions`. */
|
|
1297
|
+
build;
|
|
1298
|
+
/** Results of server functions that a form posted to this page, for `$action`. */
|
|
1299
|
+
actions = /* @__PURE__ */ new Map();
|
|
1300
|
+
/** The params of the route of the page, for `$route`. */
|
|
1301
|
+
params = {};
|
|
1302
|
+
/** The request of the page, when it renders with one. */
|
|
1303
|
+
event;
|
|
1304
|
+
/** Results of server function calls in this render, so the same call runs once. */
|
|
1305
|
+
calls = /* @__PURE__ */ new Map();
|
|
1306
|
+
/** The event of the page, for `getEvent()` in a component, which the compiler rewrites to this. */
|
|
1307
|
+
getEvent() {
|
|
1308
|
+
const event = this.root.event;
|
|
1309
|
+
if (!event) throw new Error("getEvent() works while a page renders with a request, such as in a route");
|
|
1310
|
+
return event;
|
|
1311
|
+
}
|
|
1312
|
+
/** Starts an entry of the trace of the request, in development. */
|
|
1313
|
+
traced(kind, label) {
|
|
1314
|
+
return this.root.event?.traced(kind, label);
|
|
1315
|
+
}
|
|
1316
|
+
/** Marks the request of the page as one that depends on the user, so the page is not cached for everyone. */
|
|
1317
|
+
personal() {
|
|
1318
|
+
if (this.root.event) this.root.event.personal = true;
|
|
1319
|
+
}
|
|
1320
|
+
/** Runs code of the render with its event and its call results, such as a memo's compute. */
|
|
1321
|
+
run(callback) {
|
|
1322
|
+
return withEvent(this.root.event, callback, this.root.calls);
|
|
1323
|
+
}
|
|
1324
|
+
/** The result of a server function that a form posted to this page. */
|
|
1325
|
+
actionResult(fn) {
|
|
1326
|
+
return this.root.actions.get(unwrap(fn));
|
|
1327
|
+
}
|
|
1328
|
+
/** `prefix` is the boundary ID and a dot, for the context of a `#loading` body. */
|
|
1329
|
+
constructor(root, rpc, base = 0, prefix = "") {
|
|
1330
|
+
this.root = root ?? this;
|
|
1331
|
+
if (rpc) this.rpcPrefix = rpc;
|
|
1332
|
+
const first = prefix ? 0 : base;
|
|
1333
|
+
this.spaces = [{
|
|
1334
|
+
prefix,
|
|
1335
|
+
scope: first,
|
|
1336
|
+
boundary: first,
|
|
1337
|
+
first,
|
|
1338
|
+
entries: []
|
|
1339
|
+
}];
|
|
1340
|
+
this.root.made.push(this.spaces[0]);
|
|
1341
|
+
this.baseId = base;
|
|
1342
|
+
}
|
|
1343
|
+
/** The base of the render, which the browser sends back to ask for a `#defer` body. */
|
|
1344
|
+
base() {
|
|
1345
|
+
return this.root.baseId;
|
|
1346
|
+
}
|
|
1347
|
+
/** True in a request for a `#defer` body, outside the body, once the body has started. */
|
|
1348
|
+
past() {
|
|
1349
|
+
return this.root.target?.status === "found" && !this.inTarget;
|
|
1350
|
+
}
|
|
1351
|
+
/**
|
|
1352
|
+
* A number above every scope and boundary ID of the page so far, so a
|
|
1353
|
+
* later render can start there. The IDs inside boundaries start with one.
|
|
1354
|
+
*/
|
|
1355
|
+
next() {
|
|
1356
|
+
const space = this.root.spaces[0];
|
|
1357
|
+
return Math.max(space.scope, space.boundary);
|
|
1358
|
+
}
|
|
1359
|
+
/** The space that the next IDs come from. */
|
|
1360
|
+
get space() {
|
|
1361
|
+
return this.spaces.at(-1);
|
|
1362
|
+
}
|
|
1363
|
+
/**
|
|
1364
|
+
* Starts a block whose shape depends on data, such as an `#if` or a
|
|
1365
|
+
* `#for`. The scopes of its bodies are numbered after one ID that the
|
|
1366
|
+
* block takes, until `leave`. A `#loading` body that renders in place
|
|
1367
|
+
* passes the ID of its boundary, so its scopes get the IDs that they
|
|
1368
|
+
* would get in a stream.
|
|
1369
|
+
*/
|
|
1370
|
+
enter(id = spaceId(this.space, this.space.boundary++)) {
|
|
1371
|
+
const space = {
|
|
1372
|
+
prefix: `${id}.`,
|
|
1373
|
+
scope: 0,
|
|
1374
|
+
boundary: 0,
|
|
1375
|
+
first: 0,
|
|
1376
|
+
entries: []
|
|
1377
|
+
};
|
|
1378
|
+
this.spaces.push(space);
|
|
1379
|
+
this.root.made.push(space);
|
|
1380
|
+
}
|
|
1381
|
+
/** Ends the block that `enter` started. */
|
|
1382
|
+
leave() {
|
|
1383
|
+
this.spaces.pop();
|
|
1384
|
+
}
|
|
1385
|
+
/** Returns the URL prefix of server function calls. */
|
|
1386
|
+
rpc() {
|
|
1387
|
+
return this.root.rpcPrefix;
|
|
1388
|
+
}
|
|
1389
|
+
/** Returns the ID of the build, when the render has one. */
|
|
1390
|
+
buildId() {
|
|
1391
|
+
return this.root.build;
|
|
1392
|
+
}
|
|
1393
|
+
/**
|
|
1394
|
+
* Returns a new scope ID. `kind` is the scope's ID in the compiled
|
|
1395
|
+
* component, `parent` is the scope that contains it, and `module` is the
|
|
1396
|
+
* component ID of a component's root scope.
|
|
1397
|
+
*/
|
|
1398
|
+
scope(kind, parent, module) {
|
|
1399
|
+
const root = this.root;
|
|
1400
|
+
const space = this.space;
|
|
1401
|
+
const n = space.scope++;
|
|
1402
|
+
const id = space.prefix ? `${space.prefix}${n}` : n;
|
|
1403
|
+
const record = {};
|
|
1404
|
+
record.k = kind;
|
|
1405
|
+
if (parent !== void 0) record.p = parent;
|
|
1406
|
+
let up = parent;
|
|
1407
|
+
if (module !== void 0) {
|
|
1408
|
+
record.m = module;
|
|
1409
|
+
if (root.owner !== void 0) {
|
|
1410
|
+
record.o = root.owner;
|
|
1411
|
+
up = root.owner;
|
|
1412
|
+
root.owner = void 0;
|
|
1413
|
+
}
|
|
1414
|
+
}
|
|
1415
|
+
const inserted = root.inserted.findLast((entry) => entry.from === up);
|
|
1416
|
+
if (inserted) {
|
|
1417
|
+
up = inserted.at;
|
|
1418
|
+
record.t = inserted.at;
|
|
1419
|
+
}
|
|
1420
|
+
const entry = {
|
|
1421
|
+
id,
|
|
1422
|
+
prefix: space.prefix,
|
|
1423
|
+
n,
|
|
1424
|
+
record,
|
|
1425
|
+
ctx: this,
|
|
1426
|
+
parent: up,
|
|
1427
|
+
space
|
|
1428
|
+
};
|
|
1429
|
+
this.scopes.push(entry);
|
|
1430
|
+
space.entries.push(entry);
|
|
1431
|
+
this.last = entry;
|
|
1432
|
+
return id;
|
|
1433
|
+
}
|
|
1434
|
+
/** The scope of the page with an ID, from any render. */
|
|
1435
|
+
find(id) {
|
|
1436
|
+
const root = this.root;
|
|
1437
|
+
if (typeof id === "number") {
|
|
1438
|
+
const page = root.made[0];
|
|
1439
|
+
return page.entries[id - page.first];
|
|
1440
|
+
}
|
|
1441
|
+
const dot = id.lastIndexOf(".");
|
|
1442
|
+
let n = 0;
|
|
1443
|
+
for (let i = dot + 1; i < id.length; i++) n = n * 10 + id.charCodeAt(i) - 48;
|
|
1444
|
+
for (let i = this.spaces.length - 1; i >= 0; i--) {
|
|
1445
|
+
const space = this.spaces[i];
|
|
1446
|
+
if (space.prefix.length === dot + 1 && id.startsWith(space.prefix)) return space.entries[n - space.first];
|
|
1447
|
+
}
|
|
1448
|
+
const byPrefix = root.byPrefix ??= /* @__PURE__ */ new Map();
|
|
1449
|
+
for (; root.indexed < root.made.length; root.indexed++) {
|
|
1450
|
+
const space = root.made[root.indexed];
|
|
1451
|
+
byPrefix.set(space.prefix, space);
|
|
1452
|
+
}
|
|
1453
|
+
const space = byPrefix.get(id.slice(0, dot + 1));
|
|
1454
|
+
return space?.entries[n - space.first];
|
|
1455
|
+
}
|
|
1456
|
+
/**
|
|
1457
|
+
* Renders children where a component inserts them, at `at`. Their scopes
|
|
1458
|
+
* keep `from`, the scope of the markup that wrote them, for their values,
|
|
1459
|
+
* and find their contexts from `at`.
|
|
1460
|
+
*/
|
|
1461
|
+
async children(from, at, renderBody) {
|
|
1462
|
+
const entry = {
|
|
1463
|
+
from,
|
|
1464
|
+
at
|
|
1465
|
+
};
|
|
1466
|
+
const { inserted } = this.root;
|
|
1467
|
+
inserted.push(entry);
|
|
1468
|
+
try {
|
|
1469
|
+
return await renderBody();
|
|
1470
|
+
} finally {
|
|
1471
|
+
inserted.splice(inserted.indexOf(entry), 1);
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1474
|
+
/**
|
|
1475
|
+
* The ID that `$id()` makes: the scope's ID and the position of the call.
|
|
1476
|
+
* A dot in a scope ID inside a `#loading` body becomes `_`, so the ID also
|
|
1477
|
+
* works as a CSS selector, such as `#b5_1-0`.
|
|
1478
|
+
*/
|
|
1479
|
+
id(scope, index) {
|
|
1480
|
+
return `b${String(scope).replace(/\./g, "_")}-${index}`;
|
|
1481
|
+
}
|
|
1482
|
+
/** Sets the owner of the next component's root scope. */
|
|
1483
|
+
own(scope) {
|
|
1484
|
+
this.root.owner = scope;
|
|
1485
|
+
}
|
|
1486
|
+
/** Provides a value of a context to the scopes inside `scope`. */
|
|
1487
|
+
provide(context, value, scope) {
|
|
1488
|
+
const node = this.find(scope);
|
|
1489
|
+
node.values ??= /* @__PURE__ */ new Map();
|
|
1490
|
+
node.values.set(context.key, value);
|
|
1491
|
+
const record = this.record(scope);
|
|
1492
|
+
record.v ??= {};
|
|
1493
|
+
record.v[context.key] = value;
|
|
1494
|
+
}
|
|
1495
|
+
/**
|
|
1496
|
+
* Reads a context from the nearest scope that provides it, starting at
|
|
1497
|
+
* `scope`. With `slot`, records which slot holds it, so the client can
|
|
1498
|
+
* update it when the provided value changes.
|
|
1499
|
+
*/
|
|
1500
|
+
consume(context, scope, slot) {
|
|
1501
|
+
if (slot !== void 0) {
|
|
1502
|
+
const record = this.record(scope);
|
|
1503
|
+
record.x ??= {};
|
|
1504
|
+
record.x[context.key] = slot;
|
|
1505
|
+
}
|
|
1506
|
+
for (let id = scope; id !== void 0;) {
|
|
1507
|
+
const node = this.find(id);
|
|
1508
|
+
if (node?.values?.has(context.key)) return node.values.get(context.key);
|
|
1509
|
+
id = node?.parent;
|
|
1510
|
+
}
|
|
1511
|
+
if (context.key === "brumate.route") {
|
|
1512
|
+
const url = new URL(this.root.event?.request.url ?? "http://localhost/");
|
|
1513
|
+
return {
|
|
1514
|
+
url,
|
|
1515
|
+
search: url.searchParams,
|
|
1516
|
+
params: this.root.params
|
|
1517
|
+
};
|
|
1518
|
+
}
|
|
1519
|
+
return context.defaultValue;
|
|
1520
|
+
}
|
|
1521
|
+
/** The ID that the next call to `scope()` returns. */
|
|
1522
|
+
peek() {
|
|
1523
|
+
return spaceId(this.space, this.space.scope);
|
|
1524
|
+
}
|
|
1525
|
+
/** Marks the render so far, such as before a `#try` body, for `restore`. */
|
|
1526
|
+
mark() {
|
|
1527
|
+
const { prefix, scope, boundary } = this.space;
|
|
1528
|
+
return {
|
|
1529
|
+
prefix,
|
|
1530
|
+
scope,
|
|
1531
|
+
boundary,
|
|
1532
|
+
depth: this.spaces.length,
|
|
1533
|
+
undo: this.undo.length,
|
|
1534
|
+
owner: this.root.owner
|
|
1535
|
+
};
|
|
1536
|
+
}
|
|
1537
|
+
/**
|
|
1538
|
+
* Takes back what the render added to the page since `mark`, such as a
|
|
1539
|
+
* `#try` body that threw, whose markup is not sent: its scopes, the
|
|
1540
|
+
* stylesheets it counted as sent, its `#portal` and `#head` markup, its
|
|
1541
|
+
* title, its `#loading` bodies, and its links to child components.
|
|
1542
|
+
*/
|
|
1543
|
+
restore(mark) {
|
|
1544
|
+
this.drop(mark);
|
|
1545
|
+
this.spaces.length = mark.depth;
|
|
1546
|
+
for (const undo of this.undo.splice(mark.undo).toReversed()) undo();
|
|
1547
|
+
this.root.owner = mark.owner;
|
|
1548
|
+
}
|
|
1549
|
+
/**
|
|
1550
|
+
* Forgets the scopes of this render from `from` on, such as those of a
|
|
1551
|
+
* `#try` body that threw, so the client does not resume markup that was
|
|
1552
|
+
* never sent. `#loading` bodies render in contexts of their own, so their
|
|
1553
|
+
* scopes stay.
|
|
1554
|
+
*/
|
|
1555
|
+
drop(mark) {
|
|
1556
|
+
this.last = void 0;
|
|
1557
|
+
const { scopes } = this;
|
|
1558
|
+
let kept = 0;
|
|
1559
|
+
for (const entry of scopes) {
|
|
1560
|
+
if (!madeAfter(mark, entry.id)) {
|
|
1561
|
+
scopes[kept++] = entry;
|
|
1562
|
+
continue;
|
|
1563
|
+
}
|
|
1564
|
+
const { space } = entry;
|
|
1565
|
+
if (space?.entries[entry.n - space.first] === entry) space.entries[entry.n - space.first] = void 0;
|
|
1566
|
+
this.partials?.delete(entry.id);
|
|
1567
|
+
}
|
|
1568
|
+
scopes.length = kept;
|
|
1569
|
+
}
|
|
1570
|
+
/** The scope of this render with an ID, or the record that this render adds to another's. */
|
|
1571
|
+
entry(scope) {
|
|
1572
|
+
const last = this.last;
|
|
1573
|
+
if (last && last.id === scope) return last;
|
|
1574
|
+
let entry = this.find(scope);
|
|
1575
|
+
if (entry?.ctx !== this) {
|
|
1576
|
+
this.partials ??= /* @__PURE__ */ new Map();
|
|
1577
|
+
entry = this.partials.get(scope);
|
|
1578
|
+
if (!entry) {
|
|
1579
|
+
const [prefix, n] = splitId(scope);
|
|
1580
|
+
entry = {
|
|
1581
|
+
id: scope,
|
|
1582
|
+
prefix,
|
|
1583
|
+
n,
|
|
1584
|
+
record: {},
|
|
1585
|
+
ctx: this
|
|
1586
|
+
};
|
|
1587
|
+
this.partials.set(scope, entry);
|
|
1588
|
+
this.scopes.push(entry);
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
1591
|
+
this.last = entry;
|
|
1592
|
+
return entry;
|
|
1593
|
+
}
|
|
1594
|
+
record(scope) {
|
|
1595
|
+
return this.entry(scope).record;
|
|
1596
|
+
}
|
|
1597
|
+
/** The record of a scope in the state of this render, if it is there. */
|
|
1598
|
+
ownRecord(scope) {
|
|
1599
|
+
const entry = this.find(scope);
|
|
1600
|
+
return entry?.ctx === this ? entry.record : this.partials?.get(scope)?.record;
|
|
1601
|
+
}
|
|
1602
|
+
/** The records of the scopes of this render, by ID, in the order the render made them. */
|
|
1603
|
+
get state() {
|
|
1604
|
+
return new Map(this.scopes.map((entry) => [entry.id, entry.record]));
|
|
1605
|
+
}
|
|
1606
|
+
/**
|
|
1607
|
+
* The list of each list item scope whose list is a slot of an enclosing
|
|
1608
|
+
* scope, as `[scope, slot]`. The items of a list share one array.
|
|
1609
|
+
*/
|
|
1610
|
+
get sources() {
|
|
1611
|
+
return new Map(this.scopes.flatMap((entry) => entry.source ? [[entry.id, entry.source]] : []));
|
|
1612
|
+
}
|
|
1613
|
+
slots(scope, values, names) {
|
|
1614
|
+
const entry = this.entry(scope);
|
|
1615
|
+
entry.record.s = values;
|
|
1616
|
+
if (names) entry.names = names;
|
|
1617
|
+
}
|
|
1618
|
+
/**
|
|
1619
|
+
* Records the props that a parent bound with `$bind`, among the props that
|
|
1620
|
+
* the component writes: `slots` has the slot of each, by its name. Its
|
|
1621
|
+
* writes in the browser go to the parent's slots.
|
|
1622
|
+
*/
|
|
1623
|
+
bindings(scope, props, slots) {
|
|
1624
|
+
for (const [name, slot] of Object.entries(slots)) {
|
|
1625
|
+
const value = props[name];
|
|
1626
|
+
if (isBinding(value)) (this.entry(scope).record.b ??= {})[slot] = value.target;
|
|
1627
|
+
}
|
|
1628
|
+
}
|
|
1629
|
+
/**
|
|
1630
|
+
* Records the item of a list that can change on the client. `source` is
|
|
1631
|
+
* the scope and slot that hold the list, when the compiler found one, so
|
|
1632
|
+
* the client can take the item from there.
|
|
1633
|
+
*/
|
|
1634
|
+
item(scope, value, source) {
|
|
1635
|
+
const entry = this.entry(scope);
|
|
1636
|
+
entry.record.i = value;
|
|
1637
|
+
if (source) entry.source = source;
|
|
1638
|
+
}
|
|
1639
|
+
/** Records the scope of a child component at an anchor of its parent. */
|
|
1640
|
+
link(scope, anchor, child) {
|
|
1641
|
+
const record = this.record(scope);
|
|
1642
|
+
const links = record.c ??= {};
|
|
1643
|
+
links[anchor] = child;
|
|
1644
|
+
this.undo.push(() => {
|
|
1645
|
+
if (links[anchor] === child) delete links[anchor];
|
|
1646
|
+
});
|
|
1647
|
+
}
|
|
1648
|
+
/** Returns the reference that a `ref` signal holds on the server. */
|
|
1649
|
+
element(scope, anchor) {
|
|
1650
|
+
return new ElementReference(scope, anchor);
|
|
1651
|
+
}
|
|
1652
|
+
/**
|
|
1653
|
+
* Marks a function as a client function, so it serializes as a reference.
|
|
1654
|
+
* `args` are the arguments of a handler that `$handler` made, which go
|
|
1655
|
+
* with the reference. Each call makes a new reference, so a function that
|
|
1656
|
+
* `$handler` marks gets a copy for its arguments.
|
|
1657
|
+
*/
|
|
1658
|
+
fn(value, ref, scope, args) {
|
|
1659
|
+
if (typeof value !== "function") return value;
|
|
1660
|
+
if (args === void 0) {
|
|
1661
|
+
functionReferences.set(value, new FunctionReference(ref, scope));
|
|
1662
|
+
return value;
|
|
1663
|
+
}
|
|
1664
|
+
const bound = Object.assign((...rest) => value(...args, ...rest), value);
|
|
1665
|
+
functionReferences.set(bound, new FunctionReference(ref, scope, args));
|
|
1666
|
+
return bound;
|
|
1667
|
+
}
|
|
1668
|
+
/** Returns a component's stylesheet the first time the page renders the component. */
|
|
1669
|
+
style(id, css) {
|
|
1670
|
+
const styles = this.root.styles;
|
|
1671
|
+
if (styles.has(id)) return "";
|
|
1672
|
+
styles.add(id);
|
|
1673
|
+
this.undo.push(() => styles.delete(id));
|
|
1674
|
+
return styleElement(id, css);
|
|
1675
|
+
}
|
|
1676
|
+
/** Adds the markup of a `#head` block. */
|
|
1677
|
+
head(html) {
|
|
1678
|
+
const heads = (this.root.sent ? this : this.root).heads;
|
|
1679
|
+
heads.push(html);
|
|
1680
|
+
this.undo.push(() => removeLast(heads, html));
|
|
1681
|
+
}
|
|
1682
|
+
/**
|
|
1683
|
+
* Sets the title of the page. The last call wins. `markup` is true for a
|
|
1684
|
+
* `<title>` in `#head`, which is in the head already.
|
|
1685
|
+
*/
|
|
1686
|
+
title(value, markup = false) {
|
|
1687
|
+
const target = this.root.sent ? this : this.root;
|
|
1688
|
+
const previous = target.pageTitle;
|
|
1689
|
+
const titles = { ...target.titles };
|
|
1690
|
+
const title = value === null || value === void 0 ? "" : String(value);
|
|
1691
|
+
target.pageTitle = title;
|
|
1692
|
+
target.titles = {
|
|
1693
|
+
count: titles.count + 1,
|
|
1694
|
+
markup: titles.markup && markup
|
|
1695
|
+
};
|
|
1696
|
+
this.undo.push(() => {
|
|
1697
|
+
if (target.pageTitle === title) {
|
|
1698
|
+
target.pageTitle = previous;
|
|
1699
|
+
target.titles = titles;
|
|
1700
|
+
}
|
|
1701
|
+
});
|
|
1702
|
+
}
|
|
1703
|
+
/** True once the first render is done, and its head is about to be sent. */
|
|
1704
|
+
sent = false;
|
|
1705
|
+
/** Marks the first render as done. Head markup after it streams with its `#loading` body. */
|
|
1706
|
+
send() {
|
|
1707
|
+
this.root.sent = true;
|
|
1708
|
+
}
|
|
1709
|
+
/**
|
|
1710
|
+
* The head markup and the title that a `#loading` body set, after the
|
|
1711
|
+
* head was sent. The title is undefined if the body set none.
|
|
1712
|
+
*/
|
|
1713
|
+
lateHead() {
|
|
1714
|
+
return {
|
|
1715
|
+
html: this.heads.join(""),
|
|
1716
|
+
title: this.pageTitle
|
|
1717
|
+
};
|
|
1718
|
+
}
|
|
1719
|
+
/** The markup for the document's head: the title and the `#head` blocks. */
|
|
1720
|
+
headHTML() {
|
|
1721
|
+
const { count, markup } = this.root.titles;
|
|
1722
|
+
return (this.root.pageTitle === void 0 || count === 1 && markup ? "" : `<title>${escape(this.root.pageTitle)}</title>`) + this.root.heads.join("");
|
|
1723
|
+
}
|
|
1724
|
+
/** Adds the markup of a `#portal` block, which goes after the rest of the page. */
|
|
1725
|
+
portal(html) {
|
|
1726
|
+
this.portals.push(html);
|
|
1727
|
+
this.undo.push(() => removeLast(this.portals, html));
|
|
1728
|
+
}
|
|
1729
|
+
/** Adds the head markup and the title of a body that renders in place, to the head of the page. */
|
|
1730
|
+
adoptHead(late) {
|
|
1731
|
+
if (late.html) this.root.heads.push(late.html);
|
|
1732
|
+
if (late.title !== void 0) this.root.pageTitle = late.title;
|
|
1733
|
+
}
|
|
1734
|
+
/** True when the bodies of `#defer` blocks render in place, for a page that renders in order. */
|
|
1735
|
+
inOrder = false;
|
|
1736
|
+
/** The `#reveal` blocks that are open in this context, the innermost last. */
|
|
1737
|
+
reveals = [];
|
|
1738
|
+
/** Starts a `#reveal` block: the `#loading` bodies until `revealEnd` show in its order. */
|
|
1739
|
+
revealStart(order, collapsed) {
|
|
1740
|
+
const group = new RevealGroup(order, collapsed);
|
|
1741
|
+
this.reveals.push(group);
|
|
1742
|
+
this.undo.push(() => group.close());
|
|
1743
|
+
}
|
|
1744
|
+
/** Ends the `#reveal` block that `revealStart` started. */
|
|
1745
|
+
revealEnd() {
|
|
1746
|
+
this.reveals.pop()?.close();
|
|
1747
|
+
}
|
|
1748
|
+
/** The group of the `#reveal` block around the next body, when the stream orders it. */
|
|
1749
|
+
get reveal() {
|
|
1750
|
+
return this.root.target ? void 0 : this.reveals.at(-1);
|
|
1751
|
+
}
|
|
1752
|
+
/** True when a `#loading` body that is ready can render in place, as its `#reveal` allows. */
|
|
1753
|
+
mayShow() {
|
|
1754
|
+
return this.reveal?.mayShow() ?? true;
|
|
1755
|
+
}
|
|
1756
|
+
/** Starts the fallback of a `#loading` body, which `collapsed` hides in a template. */
|
|
1757
|
+
fallbackStart(id) {
|
|
1758
|
+
const group = this.reveal;
|
|
1759
|
+
if (!group?.hides()) return "";
|
|
1760
|
+
group.hidden.add(id);
|
|
1761
|
+
return `<template b-f="${id}">`;
|
|
1762
|
+
}
|
|
1763
|
+
/** Ends the fallback that `fallbackStart` started. */
|
|
1764
|
+
fallbackEnd(id) {
|
|
1765
|
+
return this.reveal?.hidden.has(id) ? "</template>" : "";
|
|
1766
|
+
}
|
|
1767
|
+
/** Returns the ID of a new `#loading` boundary. */
|
|
1768
|
+
boundary() {
|
|
1769
|
+
return spaceId(this.space, this.space.boundary++);
|
|
1770
|
+
}
|
|
1771
|
+
/** Renders a `#loading` body after the rest of the page, in its own context and ID space. */
|
|
1772
|
+
defer(id, renderBody) {
|
|
1773
|
+
const target = this.root.target;
|
|
1774
|
+
if (!target || this.inTarget) this.register(id, renderBody, this.inTarget);
|
|
1775
|
+
else if (holdsBoundary(id, target.boundary)) this.register(id, renderBody, false, true);
|
|
1776
|
+
}
|
|
1777
|
+
/**
|
|
1778
|
+
* Renders the body of a `#defer` block, in the request for it. `at` is
|
|
1779
|
+
* the scope and the anchor of the block. A page renders only the
|
|
1780
|
+
* fallback, so it does nothing then.
|
|
1781
|
+
*/
|
|
1782
|
+
deferBlock(id, at, renderBody) {
|
|
1783
|
+
const target = this.root.target;
|
|
1784
|
+
if (!target && this.root.inOrder) {
|
|
1785
|
+
this.register(id, renderBody, false);
|
|
1786
|
+
return;
|
|
1787
|
+
}
|
|
1788
|
+
if (!target || this.inTarget) return;
|
|
1789
|
+
if (holdsBoundary(id, target.boundary)) {
|
|
1790
|
+
this.register(id, renderBody, false, true);
|
|
1791
|
+
return;
|
|
1792
|
+
}
|
|
1793
|
+
if (id !== target.boundary) return;
|
|
1794
|
+
if (at !== target.at) {
|
|
1795
|
+
target.status = "moved";
|
|
1796
|
+
return;
|
|
1797
|
+
}
|
|
1798
|
+
target.status = "found";
|
|
1799
|
+
this.register(id, renderBody, true);
|
|
1800
|
+
}
|
|
1801
|
+
register(id, renderBody, inTarget, around = false) {
|
|
1802
|
+
const child = new Context(this.root, void 0, 0, `${id}.`);
|
|
1803
|
+
child.inTarget = inTarget;
|
|
1804
|
+
const group = this.reveal;
|
|
1805
|
+
group?.add(id);
|
|
1806
|
+
const end = around ? void 0 : this.traced("body", `#loading ${id}`);
|
|
1807
|
+
const boundary = {
|
|
1808
|
+
id,
|
|
1809
|
+
render: renderBody(child).then((html) => {
|
|
1810
|
+
end?.();
|
|
1811
|
+
return {
|
|
1812
|
+
html,
|
|
1813
|
+
ctx: child
|
|
1814
|
+
};
|
|
1815
|
+
}, (error) => {
|
|
1816
|
+
end?.(true);
|
|
1817
|
+
throw error;
|
|
1818
|
+
}),
|
|
1819
|
+
around,
|
|
1820
|
+
group
|
|
1821
|
+
};
|
|
1822
|
+
boundary.render.catch(() => {});
|
|
1823
|
+
const root = this.root;
|
|
1824
|
+
if (root.onBoundary) root.onBoundary(boundary);
|
|
1825
|
+
else root.boundaries.push(boundary);
|
|
1826
|
+
this.undo.push(() => {
|
|
1827
|
+
boundary.cancelled = true;
|
|
1828
|
+
removeLast(root.boundaries, boundary);
|
|
1829
|
+
});
|
|
1830
|
+
}
|
|
1831
|
+
/** Receives every boundary, including those registered before this call. */
|
|
1832
|
+
watch(onBoundary) {
|
|
1833
|
+
this.onBoundary = onBoundary;
|
|
1834
|
+
for (const boundary of this.boundaries.splice(0)) onBoundary(boundary);
|
|
1835
|
+
}
|
|
1836
|
+
};
|
|
1837
|
+
/** Removes the last copy of a value from a list. */
|
|
1838
|
+
function removeLast(list, value) {
|
|
1839
|
+
const index = list.lastIndexOf(value);
|
|
1840
|
+
if (index !== -1) list.splice(index, 1);
|
|
1841
|
+
}
|
|
1842
|
+
/** Thrown when code reads a memo whose value is still loading. It carries the load. */
|
|
1843
|
+
var NotReady = class extends Error {
|
|
1844
|
+
source;
|
|
1845
|
+
constructor(source) {
|
|
1846
|
+
super("The value is still loading");
|
|
1847
|
+
this.name = "NotReady";
|
|
1848
|
+
this.source = source;
|
|
1849
|
+
}
|
|
1850
|
+
};
|
|
1851
|
+
/** Declares a memo. Its value is computed when it is first read. */
|
|
1852
|
+
function memo(compute, ctx, name) {
|
|
1853
|
+
return {
|
|
1854
|
+
compute,
|
|
1855
|
+
ctx,
|
|
1856
|
+
state: "idle",
|
|
1857
|
+
name
|
|
1858
|
+
};
|
|
1859
|
+
}
|
|
1860
|
+
/**
|
|
1861
|
+
* Reads a memo. A value that is still loading throws `NotReady` with its
|
|
1862
|
+
* load, and a memo that read such a value stays unread, so it computes
|
|
1863
|
+
* again when it is read after the load settles.
|
|
1864
|
+
*/
|
|
1865
|
+
function read(node) {
|
|
1866
|
+
if (node.state === "done") return node.value;
|
|
1867
|
+
if (node.state === "failed") throw node.error;
|
|
1868
|
+
if (node.state === "pending") throw new NotReady(node.load);
|
|
1869
|
+
let value;
|
|
1870
|
+
try {
|
|
1871
|
+
value = node.ctx ? node.ctx.run(node.compute) : node.compute();
|
|
1872
|
+
} catch (error) {
|
|
1873
|
+
if (!(error instanceof NotReady)) {
|
|
1874
|
+
node.state = "failed";
|
|
1875
|
+
node.error = error;
|
|
1876
|
+
}
|
|
1877
|
+
throw error;
|
|
1878
|
+
}
|
|
1879
|
+
if (value !== null && typeof value === "object" && (typeof value.then === "function" || isAsyncIterable(value))) {
|
|
1880
|
+
node.state = "pending";
|
|
1881
|
+
const end = node.ctx?.traced("memo", node.name ?? "memo");
|
|
1882
|
+
node.load = Promise.resolve(value).then(firstValue).finally(() => end?.()).then((result) => {
|
|
1883
|
+
node.state = "done";
|
|
1884
|
+
node.value = result;
|
|
1885
|
+
}, (error) => {
|
|
1886
|
+
node.state = "failed";
|
|
1887
|
+
node.error = error;
|
|
1888
|
+
});
|
|
1889
|
+
throw new NotReady(node.load);
|
|
1890
|
+
}
|
|
1891
|
+
node.state = "done";
|
|
1892
|
+
node.value = value;
|
|
1893
|
+
return value;
|
|
1894
|
+
}
|
|
1895
|
+
/**
|
|
1896
|
+
* The first value of an async iterable, such as a server function that
|
|
1897
|
+
* streams. A page renders once, so the server stops reading after it. Other
|
|
1898
|
+
* values are themselves.
|
|
1899
|
+
*/
|
|
1900
|
+
async function firstValue(value) {
|
|
1901
|
+
if (!isAsyncIterable(value)) return value;
|
|
1902
|
+
const iterator = value[Symbol.asyncIterator]();
|
|
1903
|
+
const first = await iterator.next();
|
|
1904
|
+
await iterator.return?.();
|
|
1905
|
+
return first.value;
|
|
1906
|
+
}
|
|
1907
|
+
/** Waits for the value of a memo, through every load it reads. */
|
|
1908
|
+
async function wait(node) {
|
|
1909
|
+
for (;;) try {
|
|
1910
|
+
return read(node);
|
|
1911
|
+
} catch (error) {
|
|
1912
|
+
if (!(error instanceof NotReady)) throw error;
|
|
1913
|
+
await error.source.catch(() => {});
|
|
1914
|
+
}
|
|
1915
|
+
}
|
|
1916
|
+
/**
|
|
1917
|
+
* The value of a memo when it is ready, or a promise of it while it loads.
|
|
1918
|
+
* The render then awaits only a memo that is loading.
|
|
1919
|
+
*/
|
|
1920
|
+
function ready(node) {
|
|
1921
|
+
try {
|
|
1922
|
+
return read(node);
|
|
1923
|
+
} catch (error) {
|
|
1924
|
+
if (error instanceof NotReady) return wait(node);
|
|
1925
|
+
throw error;
|
|
1926
|
+
}
|
|
1927
|
+
}
|
|
1928
|
+
/**
|
|
1929
|
+
* The value of a memo for the page state: its value when it is ready, or
|
|
1930
|
+
* a promise of it while it loads. A memo that fails gives a rejected
|
|
1931
|
+
* promise either way, so the page renders and the failure reaches the
|
|
1932
|
+
* browser as the load that failed.
|
|
1933
|
+
*/
|
|
1934
|
+
function stateValue(node) {
|
|
1935
|
+
try {
|
|
1936
|
+
return read(node);
|
|
1937
|
+
} catch (error) {
|
|
1938
|
+
return error instanceof NotReady ? wait(node) : Promise.reject(error);
|
|
1939
|
+
}
|
|
1940
|
+
}
|
|
1941
|
+
/**
|
|
1942
|
+
* Starts every memo of a run of declarations that the render waits for,
|
|
1943
|
+
* so they load at the same time. Returns a promise that settles when all
|
|
1944
|
+
* of them have, or undefined when none is loading. A memo that fails
|
|
1945
|
+
* throws here, or rejects the promise.
|
|
1946
|
+
*/
|
|
1947
|
+
function waitAll(nodes) {
|
|
1948
|
+
const loads = [];
|
|
1949
|
+
for (const node of nodes) {
|
|
1950
|
+
const value = ready(node);
|
|
1951
|
+
if (value instanceof Promise) loads.push(value);
|
|
1952
|
+
}
|
|
1953
|
+
return loads.length === 0 ? void 0 : Promise.all(loads);
|
|
1954
|
+
}
|
|
1955
|
+
/**
|
|
1956
|
+
* True when every memo has its value, so a `#loading` body that reads them
|
|
1957
|
+
* can render in place. A memo that is not computed yet computes here, so
|
|
1958
|
+
* the loads of the memos that are not ready start now, and the body that
|
|
1959
|
+
* streams later finds them loading. A memo that failed counts as not ready:
|
|
1960
|
+
* the body streams, and throws where it reads the memo.
|
|
1961
|
+
*/
|
|
1962
|
+
function settled(nodes) {
|
|
1963
|
+
let result = true;
|
|
1964
|
+
for (const node of nodes) try {
|
|
1965
|
+
read(node);
|
|
1966
|
+
} catch {
|
|
1967
|
+
result = false;
|
|
1968
|
+
}
|
|
1969
|
+
return result;
|
|
1970
|
+
}
|
|
1971
|
+
const LAZY = Symbol.for("brumate.lazy");
|
|
1972
|
+
/**
|
|
1973
|
+
* The children of a component, which render where the component inserts
|
|
1974
|
+
* them, so they read the contexts that the component provides. `from` is the
|
|
1975
|
+
* scope of the markup that wrote them.
|
|
1976
|
+
*/
|
|
1977
|
+
function children(from, renderBody) {
|
|
1978
|
+
return new Children(from, renderBody);
|
|
1979
|
+
}
|
|
1980
|
+
/** The symbol of raw HTML. See `html.ts`. */
|
|
1981
|
+
const RAW = Symbol.for("brumate.raw");
|
|
1982
|
+
/**
|
|
1983
|
+
* Children of a component. The first render keeps its HTML as raw HTML, so
|
|
1984
|
+
* the page state sends it for the browser to insert, such as when a block
|
|
1985
|
+
* that holds the children opens. A class, since the serializer tests only
|
|
1986
|
+
* class instances.
|
|
1987
|
+
*/
|
|
1988
|
+
var Children = class {
|
|
1989
|
+
[LAZY];
|
|
1990
|
+
/** The HTML of the first render, under the symbol of raw HTML. */
|
|
1991
|
+
[RAW];
|
|
1992
|
+
constructor(from, renderBody) {
|
|
1993
|
+
this[LAZY] = async (ctx, at) => {
|
|
1994
|
+
const html = await (at === void 0 ? renderBody(ctx) : ctx.children(from, at, () => renderBody(ctx)));
|
|
1995
|
+
this[RAW] ??= html;
|
|
1996
|
+
return html;
|
|
1997
|
+
};
|
|
1998
|
+
}
|
|
1999
|
+
};
|
|
2000
|
+
/** Makes markup that renders where it is inserted, such as the children of a layout. */
|
|
2001
|
+
function lazy(renderAt) {
|
|
2002
|
+
return { [LAZY]: renderAt };
|
|
2003
|
+
}
|
|
2004
|
+
function isLazy(value) {
|
|
2005
|
+
return typeof value === "object" && value !== null && LAZY in value;
|
|
2006
|
+
}
|
|
2007
|
+
/** Renders the attributes of a form or button that posts to a server function. */
|
|
2008
|
+
function action(ctx, name, id, method, result) {
|
|
2009
|
+
let key;
|
|
2010
|
+
if (idempotentIds.has(id)) {
|
|
2011
|
+
key = crypto.randomUUID();
|
|
2012
|
+
ctx.personal();
|
|
2013
|
+
}
|
|
2014
|
+
return actionAttributes(ctx.rpc(), name, id, method, result, ctx.buildId(), key);
|
|
2015
|
+
}
|
|
2016
|
+
/**
|
|
2017
|
+
* The result of a server function that a form posted to this page, for
|
|
2018
|
+
* `$action`, or undefined when the page was not rendered for a post.
|
|
2019
|
+
*/
|
|
2020
|
+
function actionResult(ctx, fn) {
|
|
2021
|
+
return ctx.actionResult(fn);
|
|
2022
|
+
}
|
|
2023
|
+
/**
|
|
2024
|
+
* Renders a value inserted in markup. `ctx` and `scope` are where it is
|
|
2025
|
+
* inserted, for markup that renders there.
|
|
2026
|
+
*/
|
|
2027
|
+
function insert(value, ctx, scope) {
|
|
2028
|
+
if (value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function") return Promise.resolve(value).then((resolved) => insert(resolved, ctx, scope));
|
|
2029
|
+
if (isLazy(value) && ctx) return value[LAZY](ctx, scope);
|
|
2030
|
+
if (Array.isArray(value)) {
|
|
2031
|
+
const parts = value.map((item) => insert(item, ctx, scope));
|
|
2032
|
+
return parts.every((part) => typeof part === "string") ? parts.join("") : Promise.all(parts).then((all) => all.join(""));
|
|
2033
|
+
}
|
|
2034
|
+
return insertValue(value);
|
|
2035
|
+
}
|
|
2036
|
+
/**
|
|
2037
|
+
* Renders a child component. With `scope` and `anchor`, records the child's
|
|
2038
|
+
* scope so the parent can update its props on the client.
|
|
2039
|
+
*/
|
|
2040
|
+
function component(Child, props, ctx, scope, anchor) {
|
|
2041
|
+
if (ctx.past()) return Promise.resolve("");
|
|
2042
|
+
if (scope !== void 0 && anchor !== void 0) ctx.link(scope, anchor, ctx.peek());
|
|
2043
|
+
if (scope !== void 0) ctx.own(scope);
|
|
2044
|
+
const given = props?.children;
|
|
2045
|
+
if (!(given instanceof Children)) return Child(props, ctx);
|
|
2046
|
+
const root = ctx.peek();
|
|
2047
|
+
return Child(props, ctx).then(async (html) => {
|
|
2048
|
+
if (given[RAW] === void 0) await given[LAZY](ctx, root);
|
|
2049
|
+
return html;
|
|
2050
|
+
});
|
|
2051
|
+
}
|
|
2052
|
+
/** Renders a dynamic tag, which can be an element name or a component. */
|
|
2053
|
+
function dynamic(tag, attributes, content, ctx, scope) {
|
|
2054
|
+
if (typeof tag === "function") {
|
|
2055
|
+
const entries = attributes["b-on"];
|
|
2056
|
+
const props = typeof entries === "string" && scope !== void 0 ? {
|
|
2057
|
+
...attributes,
|
|
2058
|
+
"b-on": entries.split(" ").map((entry) => entry.includes("@") ? entry : `${entry}@${scope}`).join(" ")
|
|
2059
|
+
} : attributes;
|
|
2060
|
+
return component(tag, content ? {
|
|
2061
|
+
...props,
|
|
2062
|
+
children: content
|
|
2063
|
+
} : props, ctx, scope);
|
|
2064
|
+
}
|
|
2065
|
+
const on = [];
|
|
2066
|
+
const open = `<${tag}${spread(attributes, on)}${onAttribute(on, "")}>`;
|
|
2067
|
+
if (VOID_ELEMENTS.has(tag)) return open;
|
|
2068
|
+
if (isLazy(content)) return Promise.resolve(content[LAZY](ctx, scope)).then((html) => `${open}${html}</${tag}>`);
|
|
2069
|
+
return `${open}${content && isRaw(content) ? rawHTML(content) : ""}</${tag}>`;
|
|
2070
|
+
}
|
|
2071
|
+
/** True when `value` is `target`, or holds it in plain objects, arrays, maps or sets. */
|
|
2072
|
+
function holds(value, target, seen = /* @__PURE__ */ new Set()) {
|
|
2073
|
+
if (value === target) return true;
|
|
2074
|
+
if (typeof value !== "object" || value === null || seen.has(value)) return false;
|
|
2075
|
+
seen.add(value);
|
|
2076
|
+
let items = [];
|
|
2077
|
+
if (value instanceof Map) items = [...value.keys(), ...value.values()];
|
|
2078
|
+
else if (value instanceof Set) items = [...value];
|
|
2079
|
+
else if (Array.isArray(value) || Object.getPrototypeOf(value) === Object.prototype) items = Object.values(value);
|
|
2080
|
+
return items.some((item) => holds(item, target, seen));
|
|
2081
|
+
}
|
|
2082
|
+
/**
|
|
2083
|
+
* The error of a value in the state of a page that cannot be sent to the
|
|
2084
|
+
* browser, which names the value and its component.
|
|
2085
|
+
*/
|
|
2086
|
+
function unsendable(error, ctx) {
|
|
2087
|
+
const secret = secretErrors.get(error);
|
|
2088
|
+
const target = secret ?? error.value;
|
|
2089
|
+
if (target === void 0) return error instanceof Error ? error : new Error(String(error));
|
|
2090
|
+
for (const { record, names } of ctx.scopes) {
|
|
2091
|
+
const index = (record.s ?? []).findIndex((value) => holds(value, target));
|
|
2092
|
+
if (index === -1) continue;
|
|
2093
|
+
let owner = record;
|
|
2094
|
+
while (owner && owner.m === void 0 && owner.p !== void 0) owner = ctx.ownRecord(owner.p);
|
|
2095
|
+
const name = names?.[index] ?? `slot ${index}`;
|
|
2096
|
+
if (secret !== void 0) return /* @__PURE__ */ new Error(`The value of "${name}" in ${owner?.m ?? "a component"} is the value of a server environment variable, and code that runs in the browser reads it. Read the variable in a server function, and send the browser only what it needs.`);
|
|
2097
|
+
const kind = target?.constructor?.name ?? typeof target;
|
|
2098
|
+
return new Error(`The value of "${name}" in ${owner?.m ?? "a component"} holds a ${kind}, which cannot be sent to the browser, and code that runs in the browser reads it. Use it in a server function, or create it in the browser, such as in $client.`, { cause: error });
|
|
2099
|
+
}
|
|
2100
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
2101
|
+
}
|
|
2102
|
+
/** The secret that each error of `secretError` found. The error does not hold it, so a log does not show it. */
|
|
2103
|
+
const secretErrors = /* @__PURE__ */ new WeakMap();
|
|
2104
|
+
/** The code of each secret as seroval writes a string: in double quotes, escaped. */
|
|
2105
|
+
const secretCode = /* @__PURE__ */ new Map();
|
|
2106
|
+
/**
|
|
2107
|
+
* An error for a record of the page state that holds the value of a server
|
|
2108
|
+
* environment variable as a string, or undefined. A record holds a string
|
|
2109
|
+
* as its code in quotes, so this is one search of the code per secret.
|
|
2110
|
+
*/
|
|
2111
|
+
function secretError(code) {
|
|
2112
|
+
for (const secret of serverSecrets()) {
|
|
2113
|
+
let literal = secretCode.get(secret);
|
|
2114
|
+
if (literal === void 0) {
|
|
2115
|
+
literal = crossSerialize(secret);
|
|
2116
|
+
secretCode.set(secret, literal);
|
|
2117
|
+
}
|
|
2118
|
+
if (code.includes(literal)) {
|
|
2119
|
+
const error = /* @__PURE__ */ new Error("The page state holds the value of a server environment variable, which is not sent to the browser");
|
|
2120
|
+
secretErrors.set(error, secret);
|
|
2121
|
+
return error;
|
|
2122
|
+
}
|
|
2123
|
+
}
|
|
2124
|
+
}
|
|
2125
|
+
/** JSON that is safe in a `<script>`, with each `<` escaped. */
|
|
2126
|
+
function scriptJSON(value) {
|
|
2127
|
+
return JSON.stringify(value).replace(/</g, "\\u003c");
|
|
2128
|
+
}
|
|
2129
|
+
/** The fields that a record in a group of `PackedState` can have. */
|
|
2130
|
+
const PACKED_FIELDS = /* @__PURE__ */ new Set([
|
|
2131
|
+
"k",
|
|
2132
|
+
"p",
|
|
2133
|
+
"o",
|
|
2134
|
+
"m",
|
|
2135
|
+
"s",
|
|
2136
|
+
"i",
|
|
2137
|
+
"c"
|
|
2138
|
+
]);
|
|
2139
|
+
/** A group of `PackedState` while `packState` collects it. */
|
|
2140
|
+
/** How many of the last groups `packState` compares a record with, before it looks up its name. */
|
|
2141
|
+
const RECENT_GROUPS = 4;
|
|
2142
|
+
/** The prefix of an ID and its number after it, such as `['', 3]` or `['5.', 1]`. */
|
|
2143
|
+
function splitId(id) {
|
|
2144
|
+
if (typeof id === "number") return ["", id];
|
|
2145
|
+
const dot = id.lastIndexOf(".");
|
|
2146
|
+
return [id.slice(0, dot + 1), Number(id.slice(dot + 1))];
|
|
2147
|
+
}
|
|
2148
|
+
/** The records of a state as a map, for a state written as an object, such as in tests. */
|
|
2149
|
+
function toStateMap(state) {
|
|
2150
|
+
if (state instanceof Map) return state;
|
|
2151
|
+
return new Map(Object.entries(state).map(([key, record]) => [parseId(key), record]));
|
|
2152
|
+
}
|
|
2153
|
+
/**
|
|
2154
|
+
* Visits the scopes of a state in the order of the keys of an object: number
|
|
2155
|
+
* IDs ascending, then string IDs in the order they were made. A render makes
|
|
2156
|
+
* its number IDs in order, so the scopes are only copied to sort them when
|
|
2157
|
+
* they are not.
|
|
2158
|
+
*/
|
|
2159
|
+
function visitOrdered(entries, visit) {
|
|
2160
|
+
let numbers = entries;
|
|
2161
|
+
let last = -Infinity;
|
|
2162
|
+
for (const entry of entries) if (typeof entry.id === "number") {
|
|
2163
|
+
if (entry.id < last) {
|
|
2164
|
+
numbers = entries.filter((item) => typeof item.id === "number").toSorted((a, b) => a.id - b.id);
|
|
2165
|
+
break;
|
|
2166
|
+
}
|
|
2167
|
+
last = entry.id;
|
|
2168
|
+
}
|
|
2169
|
+
for (const entry of numbers) if (typeof entry.id === "number") visit(entry);
|
|
2170
|
+
for (const entry of entries) if (typeof entry.id !== "number") visit(entry);
|
|
2171
|
+
}
|
|
2172
|
+
/**
|
|
2173
|
+
* The list that the client can take the items of a group from: the items
|
|
2174
|
+
* are list items with the same source, the source's record is in `state`,
|
|
2175
|
+
* and the item of the scope at each position of the group is the value at
|
|
2176
|
+
* that position of the list. The client reads the same list, so it gets the
|
|
2177
|
+
* same values. Otherwise the items are written.
|
|
2178
|
+
*/
|
|
2179
|
+
function groupSource(record, group) {
|
|
2180
|
+
const { entries } = group;
|
|
2181
|
+
const source = entries[0].source;
|
|
2182
|
+
if (!source || !(group.flags & 3)) return;
|
|
2183
|
+
const value = record(source[0])?.s?.[source[1]];
|
|
2184
|
+
const list = value instanceof Set ? Array.from(value) : value;
|
|
2185
|
+
if (!Array.isArray(list) || list.length < entries.length) return;
|
|
2186
|
+
for (let n = 0; n < entries.length; n++) {
|
|
2187
|
+
const entry = entries[n];
|
|
2188
|
+
if (entry.source !== source || !Object.is(list[n], entry.record.i)) return;
|
|
2189
|
+
}
|
|
2190
|
+
return source;
|
|
2191
|
+
}
|
|
2192
|
+
/**
|
|
2193
|
+
* Writes the records of scopes with the same kind, parent and shape, such as
|
|
2194
|
+
* the items of a list, in groups. Each one then costs its slots and the gap
|
|
2195
|
+
* to the ID before it. The items of a list whose list is in `sources` and in
|
|
2196
|
+
* the state are not written. See `PackedState`.
|
|
2197
|
+
*/
|
|
2198
|
+
function packState(input, sources) {
|
|
2199
|
+
const state = toStateMap(input);
|
|
2200
|
+
return packEntries(Array.from(state, ([id, record]) => {
|
|
2201
|
+
const [prefix, n] = splitId(id);
|
|
2202
|
+
return {
|
|
2203
|
+
id,
|
|
2204
|
+
prefix,
|
|
2205
|
+
n,
|
|
2206
|
+
record,
|
|
2207
|
+
ctx: void 0,
|
|
2208
|
+
source: sources?.get(id)
|
|
2209
|
+
};
|
|
2210
|
+
}), (id) => state.get(id));
|
|
2211
|
+
}
|
|
2212
|
+
/** Packs the scopes of a render. `lookup` finds the record of a scope in the same state. */
|
|
2213
|
+
function packEntries(scopes, lookup) {
|
|
2214
|
+
const result = {};
|
|
2215
|
+
const groups = /* @__PURE__ */ new Map();
|
|
2216
|
+
const recent = [];
|
|
2217
|
+
visitOrdered(scopes, (entry) => {
|
|
2218
|
+
const { id, record, prefix, n } = entry;
|
|
2219
|
+
let base = record.p;
|
|
2220
|
+
if (base === void 0 && record.o !== void 0) {
|
|
2221
|
+
const [ownerPrefix, owner] = splitId(record.o);
|
|
2222
|
+
base = ownerPrefix === prefix ? n - owner : void 0;
|
|
2223
|
+
}
|
|
2224
|
+
if (record.k === void 0 || base === void 0 || record.p !== void 0 && record.o !== void 0 || !Object.keys(record).every((field) => PACKED_FIELDS.has(field))) {
|
|
2225
|
+
result[id] = record;
|
|
2226
|
+
return;
|
|
2227
|
+
}
|
|
2228
|
+
const slots = record.s ?? [];
|
|
2229
|
+
let flags = record.p === void 0 ? 8 : 0;
|
|
2230
|
+
if ("i" in record) flags |= slots.length > 0 && Object.is(record.i, slots[0]) ? 1 : 2;
|
|
2231
|
+
if (record.c) flags |= 4;
|
|
2232
|
+
if (record.m !== void 0) flags |= 16;
|
|
2233
|
+
let group = recent.find((item) => item.k === record.k && item.base === base && item.flags === flags && item.count === slots.length && item.m === record.m && item.prefix === prefix);
|
|
2234
|
+
if (!group) {
|
|
2235
|
+
const name = `${prefix}:${record.k}:${base}:${flags}:${slots.length}:${record.m ?? ""}`;
|
|
2236
|
+
group = groups.get(name);
|
|
2237
|
+
if (!group) {
|
|
2238
|
+
group = {
|
|
2239
|
+
k: record.k,
|
|
2240
|
+
base,
|
|
2241
|
+
flags,
|
|
2242
|
+
count: slots.length,
|
|
2243
|
+
m: record.m,
|
|
2244
|
+
prefix,
|
|
2245
|
+
entries: []
|
|
2246
|
+
};
|
|
2247
|
+
groups.set(name, group);
|
|
2248
|
+
}
|
|
2249
|
+
recent.unshift(group);
|
|
2250
|
+
if (recent.length > RECENT_GROUPS) recent.pop();
|
|
2251
|
+
}
|
|
2252
|
+
group.entries.push(entry);
|
|
2253
|
+
});
|
|
2254
|
+
const packed = [];
|
|
2255
|
+
for (const group of groups.values()) {
|
|
2256
|
+
const { entries } = group;
|
|
2257
|
+
if (entries.length === 1) {
|
|
2258
|
+
result[entries[0].id] = entries[0].record;
|
|
2259
|
+
continue;
|
|
2260
|
+
}
|
|
2261
|
+
const source = groupSource(lookup, group);
|
|
2262
|
+
let flags = source ? group.flags | 32 : group.flags;
|
|
2263
|
+
if (group.prefix) flags |= 64;
|
|
2264
|
+
const values = [
|
|
2265
|
+
group.k,
|
|
2266
|
+
group.base,
|
|
2267
|
+
flags,
|
|
2268
|
+
group.count
|
|
2269
|
+
];
|
|
2270
|
+
if (group.m !== void 0) values.push(group.m);
|
|
2271
|
+
if (source) values.push(source[0], source[1]);
|
|
2272
|
+
if (group.prefix) values.push(group.prefix);
|
|
2273
|
+
const from = source && flags & 1 ? 1 : 0;
|
|
2274
|
+
const item = !source && flags & 2;
|
|
2275
|
+
let last = flags & 72 ? 0 : group.base;
|
|
2276
|
+
for (const { n: number, record: scope } of entries) {
|
|
2277
|
+
values.push(number - last);
|
|
2278
|
+
const slots = scope.s ?? [];
|
|
2279
|
+
for (let n = from; n < slots.length; n++) values.push(slots[n]);
|
|
2280
|
+
if (item) values.push(scope.i);
|
|
2281
|
+
if (flags & 4) values.push(scope.c);
|
|
2282
|
+
last = number;
|
|
2283
|
+
}
|
|
2284
|
+
packed.push(values);
|
|
2285
|
+
}
|
|
2286
|
+
if (packed.length > 0) result.g = packed;
|
|
2287
|
+
return result;
|
|
2288
|
+
}
|
|
2289
|
+
/**
|
|
2290
|
+
* Serializes the page state as seroval cross-reference code, one record at
|
|
2291
|
+
* a time. The first record holds the state, and each later record settles a
|
|
2292
|
+
* promise in it. Records that share `refs` can refer to each other's values.
|
|
2293
|
+
*
|
|
2294
|
+
* With `last`, no later record of the render reads this one, so a state
|
|
2295
|
+
* without promises is one record that assigns only the references that it
|
|
2296
|
+
* uses twice. That record is smaller, and faster to write. A state with a
|
|
2297
|
+
* promise makes `crossSerialize` throw, and then it streams as usual.
|
|
2298
|
+
*/
|
|
2299
|
+
function serializeState(state, refs, onRecord, onError, onDone, sources, last = false) {
|
|
2300
|
+
const packed = state instanceof Context ? packEntries(state.scopes, (id) => state.ownRecord(id)) : packState(state, sources);
|
|
2301
|
+
let leaked = false;
|
|
2302
|
+
const send = (code, initial) => {
|
|
2303
|
+
const error = leaked ? void 0 : secretError(code);
|
|
2304
|
+
if (error) {
|
|
2305
|
+
leaked = true;
|
|
2306
|
+
onError(error);
|
|
2307
|
+
} else if (!leaked) onRecord(code, initial);
|
|
2308
|
+
};
|
|
2309
|
+
if (last) {
|
|
2310
|
+
let code;
|
|
2311
|
+
try {
|
|
2312
|
+
code = crossSerialize(packed, {
|
|
2313
|
+
plugins: syncPlugins,
|
|
2314
|
+
...serialOptions(),
|
|
2315
|
+
refs,
|
|
2316
|
+
assignSharedRefsOnly: true
|
|
2317
|
+
});
|
|
2318
|
+
} catch {
|
|
2319
|
+
refs.clear();
|
|
2320
|
+
}
|
|
2321
|
+
if (code !== void 0) {
|
|
2322
|
+
send(code, true);
|
|
2323
|
+
onDone();
|
|
2324
|
+
return;
|
|
2325
|
+
}
|
|
2326
|
+
}
|
|
2327
|
+
crossSerializeStream(packed, {
|
|
2328
|
+
plugins,
|
|
2329
|
+
...serialOptions(),
|
|
2330
|
+
refs,
|
|
2331
|
+
onSerialize: send,
|
|
2332
|
+
onError,
|
|
2333
|
+
onDone
|
|
2334
|
+
});
|
|
2335
|
+
}
|
|
2336
|
+
/**
|
|
2337
|
+
* Serializes the page state as the code of state records. `onRecord`
|
|
2338
|
+
* receives each record as soon as it is ready. The promise resolves when
|
|
2339
|
+
* every promise in the state has settled.
|
|
2340
|
+
*/
|
|
2341
|
+
function streamState(state, onRecord) {
|
|
2342
|
+
return new Promise((resolve, reject) => {
|
|
2343
|
+
serializeState(state, /* @__PURE__ */ new Map(), onRecord, reject, resolve);
|
|
2344
|
+
});
|
|
2345
|
+
}
|
|
2346
|
+
/**
|
|
2347
|
+
* Defines `$bR`, which hands the code of a state record and its script to
|
|
2348
|
+
* the core, through `self.$brm`. The core runs the code when it starts, or
|
|
2349
|
+
* at once when it has started. The first record of each render defines it.
|
|
2350
|
+
*/
|
|
2351
|
+
const RECORD = "function $bR(f){(self.$brm=self.$brm||[]).push([document.currentScript,f])}";
|
|
2352
|
+
/**
|
|
2353
|
+
* Returns the script of a state record. `scopes` marks a record with scopes,
|
|
2354
|
+
* as opposed to one that settles a promise. The record is code that seroval
|
|
2355
|
+
* wrote, as a function of the references of its render, `$R`, and of the
|
|
2356
|
+
* functions that make brumate's values, `$b`. seroval escapes every `<` in
|
|
2357
|
+
* the strings in it.
|
|
2358
|
+
*/
|
|
2359
|
+
function stateScript(code, scopes = false, attributes = {}) {
|
|
2360
|
+
if (code.includes("</") || code.includes("<!")) throw new Error("A state record would end its script");
|
|
2361
|
+
let extra = attributes.nonce === void 0 ? "" : ` nonce="${escapeAttribute(attributes.nonce)}"`;
|
|
2362
|
+
extra += " b-state";
|
|
2363
|
+
if (scopes) extra += " b-scopes";
|
|
2364
|
+
if (attributes.next !== void 0) extra += ` b-next="${attributes.next}"`;
|
|
2365
|
+
if (attributes.root) extra += ` b-root="${attributes.root}"`;
|
|
2366
|
+
if (attributes.route !== void 0) extra += ` b-route="${escapeAttribute(attributes.route)}"`;
|
|
2367
|
+
if (attributes.params !== void 0) extra += ` b-params="${escapeAttribute(JSON.stringify(attributes.params))}"`;
|
|
2368
|
+
if (attributes.build !== void 0) extra += ` b-build="${escapeAttribute(attributes.build)}"`;
|
|
2369
|
+
return `<script${extra}>${attributes.define ? RECORD : ""}$bR(($R,$b)=>(${code}))<\/script>`;
|
|
2370
|
+
}
|
|
2371
|
+
const HEAD = `function $bH(i,t){var e=document.querySelector('template[b-h="'+i+'"]'),h=document.head;e&&(h.append(e.content),e.remove());t!=null&&(h.querySelector('title:not([b-t])')||h.prepend(document.createElement('title')),document.title=t)}`;
|
|
2372
|
+
const SHOW_FALLBACK = `function $bF(i){var t=document.querySelector('template[b-f="'+i+'"]');t&&t.replaceWith(t.content)}`;
|
|
2373
|
+
const SWAP = `function $bS(i){var t=document.querySelector('template[b-l="'+i+'"]'),w=document.createTreeWalker(document.body,128),s,n,d=0;while(n=w.nextNode())if(n.data==='l'+i){s=n;break}if(!s||!t)return;var p=s.parentNode;for(n=s.nextSibling;n;){if(n.nodeType===8){if(n.data==='/l'){if(!d)break;d--}else if(/^l\\d/.test(n.data))d++}var x=n.nextSibling;p.removeChild(n);n=x}p.insertBefore(t.content,s);p.removeChild(s);n&&p.removeChild(n);t.remove()}`;
|
|
2374
|
+
const SWAP_DEV = `function $bS(i){var t=document.querySelector('template[b-l="'+i+'"]'),w=document.createTreeWalker(document.body,128),s,n,d=0;while(n=w.nextNode())if(n.data==='l'+i){s=n;break}if(!s||!t)return;var p=s.parentNode,f=[];for(n=s.nextSibling;n;){if(n.nodeType===8){if(n.data==='/l'){if(!d)break;d--}else if(/^l\\d/.test(n.data))d++}var x=n.nextSibling;f.push(p.removeChild(n));n=x}(self.$bD||(self.$bD={}))[i]={f:f,b:[].slice.call(t.content.childNodes)};p.insertBefore(t.content,s);p.removeChild(s);n&&p.removeChild(n);t.remove()}`;
|
|
2375
|
+
/** The `pending` of a render that has nothing left to send. */
|
|
2376
|
+
const NOTHING_PENDING = { [Symbol.asyncIterator]: () => ({ next: () => Promise.resolve({
|
|
2377
|
+
done: true,
|
|
2378
|
+
value: void 0
|
|
2379
|
+
}) }) };
|
|
2380
|
+
/** An async iterable that a producer pushes into. */
|
|
2381
|
+
function createQueue() {
|
|
2382
|
+
const items = [];
|
|
2383
|
+
let wake;
|
|
2384
|
+
let closed = false;
|
|
2385
|
+
let failure;
|
|
2386
|
+
const notify = () => {
|
|
2387
|
+
wake?.();
|
|
2388
|
+
wake = void 0;
|
|
2389
|
+
};
|
|
2390
|
+
return {
|
|
2391
|
+
push(item) {
|
|
2392
|
+
items.push(item);
|
|
2393
|
+
notify();
|
|
2394
|
+
},
|
|
2395
|
+
close() {
|
|
2396
|
+
closed = true;
|
|
2397
|
+
notify();
|
|
2398
|
+
},
|
|
2399
|
+
fail(error) {
|
|
2400
|
+
failure = { error };
|
|
2401
|
+
notify();
|
|
2402
|
+
},
|
|
2403
|
+
iterable: { async *[Symbol.asyncIterator]() {
|
|
2404
|
+
for (;;) if (items.length > 0) yield items.shift();
|
|
2405
|
+
else if (failure) throw failure.error;
|
|
2406
|
+
else if (closed) return;
|
|
2407
|
+
else await new Promise((resolve) => {
|
|
2408
|
+
wake = resolve;
|
|
2409
|
+
});
|
|
2410
|
+
} }
|
|
2411
|
+
};
|
|
2412
|
+
}
|
|
2413
|
+
/**
|
|
2414
|
+
* Renders the parts of a page. It returns as soon as the markup is rendered.
|
|
2415
|
+
* `#loading` bodies and promises in the state do not hold it up: they come
|
|
2416
|
+
* later, from `pending`. `renderToStream` puts the parts together. Use this
|
|
2417
|
+
* directly to send the response headers that server functions set before
|
|
2418
|
+
* the stream starts.
|
|
2419
|
+
*/
|
|
2420
|
+
async function render(Root, props, options = {}) {
|
|
2421
|
+
const scriptTag = options.nonce === void 0 ? "<script>" : `<script nonce="${escapeAttribute(options.nonce)}">`;
|
|
2422
|
+
const ctx = new Context(void 0, options.rpc, options.base);
|
|
2423
|
+
if (options.actions) ctx.actions = options.actions;
|
|
2424
|
+
if (options.params) ctx.params = options.params;
|
|
2425
|
+
ctx.build = options.build;
|
|
2426
|
+
if (options.defer) ctx.target = { ...options.defer };
|
|
2427
|
+
ctx.inOrder = !options.defer && rendersInOrder(options.inOrder ?? "bots", options.request ?? options.event?.request);
|
|
2428
|
+
const event = options.event ?? (options.request ? new RequestEvent(options.request, {
|
|
2429
|
+
kind: options.defer ? "defer" : "page",
|
|
2430
|
+
waitUntil: options.waitUntil,
|
|
2431
|
+
address: options.address,
|
|
2432
|
+
prerender: options.prerender
|
|
2433
|
+
}) : void 0);
|
|
2434
|
+
ctx.event = event;
|
|
2435
|
+
const rendered = await ctx.run(() => Root(props, ctx));
|
|
2436
|
+
ctx.send();
|
|
2437
|
+
const html = beforeBodyEnd(rendered, ctx.portals.join(""));
|
|
2438
|
+
let queue;
|
|
2439
|
+
const pending = () => queue ??= createQueue();
|
|
2440
|
+
const refs = /* @__PURE__ */ new Map();
|
|
2441
|
+
const { nonce } = options;
|
|
2442
|
+
const root = options.defer ? `d${options.defer.boundary}` : options.base;
|
|
2443
|
+
let first = true;
|
|
2444
|
+
let open = 0;
|
|
2445
|
+
let swap = false;
|
|
2446
|
+
let headSwap = false;
|
|
2447
|
+
const finish = () => {
|
|
2448
|
+
open--;
|
|
2449
|
+
if (open === 0) queue?.close();
|
|
2450
|
+
};
|
|
2451
|
+
let boundaries = 0;
|
|
2452
|
+
const swapScript = options.dev ? SWAP_DEV : SWAP;
|
|
2453
|
+
let fallbackDefined = false;
|
|
2454
|
+
const showFallback = () => {
|
|
2455
|
+
if (fallbackDefined) return "";
|
|
2456
|
+
fallbackDefined = true;
|
|
2457
|
+
return `${SHOW_FALLBACK};`;
|
|
2458
|
+
};
|
|
2459
|
+
const serialize = (target, onScopes, route, onError = (error) => pending().fail(unsendable(error, target)), last = false) => {
|
|
2460
|
+
open++;
|
|
2461
|
+
serializeState(target, refs, (code, initial) => {
|
|
2462
|
+
if (initial) {
|
|
2463
|
+
onScopes(stateScript(code, true, {
|
|
2464
|
+
next: ctx.next(),
|
|
2465
|
+
route,
|
|
2466
|
+
root,
|
|
2467
|
+
nonce,
|
|
2468
|
+
define: first,
|
|
2469
|
+
params: route === void 0 ? void 0 : options.params,
|
|
2470
|
+
build: first ? options.build : void 0
|
|
2471
|
+
}));
|
|
2472
|
+
first = false;
|
|
2473
|
+
} else pending().push(stateScript(code, false, {
|
|
2474
|
+
root,
|
|
2475
|
+
nonce
|
|
2476
|
+
}));
|
|
2477
|
+
}, onError, finish, void 0, last);
|
|
2478
|
+
};
|
|
2479
|
+
const inOrder = ctx.inOrder ? [] : void 0;
|
|
2480
|
+
const stopped = () => event?.signal.aborted === true;
|
|
2481
|
+
event?.signal.addEventListener("abort", () => queue?.close(), { once: true });
|
|
2482
|
+
ctx.watch((boundary) => {
|
|
2483
|
+
if (inOrder) {
|
|
2484
|
+
inOrder.push(boundary);
|
|
2485
|
+
return;
|
|
2486
|
+
}
|
|
2487
|
+
boundaries++;
|
|
2488
|
+
open++;
|
|
2489
|
+
const skip = (after) => {
|
|
2490
|
+
if (after) pending().push(`${scriptTag}${showFallback()}${after}<\/script>`);
|
|
2491
|
+
finish();
|
|
2492
|
+
};
|
|
2493
|
+
const turn = (send) => {
|
|
2494
|
+
if (boundary.group) boundary.group.ready(boundary.id, send);
|
|
2495
|
+
else send("");
|
|
2496
|
+
};
|
|
2497
|
+
boundary.render.then((result) => {
|
|
2498
|
+
if (boundary.cancelled || boundary.around || stopped()) {
|
|
2499
|
+
turn(skip);
|
|
2500
|
+
return;
|
|
2501
|
+
}
|
|
2502
|
+
turn((after) => {
|
|
2503
|
+
serialize(result.ctx, (script) => {
|
|
2504
|
+
const id = scriptJSON(boundary.id);
|
|
2505
|
+
let call = `${swap ? "" : swapScript}$bS(${id})`;
|
|
2506
|
+
swap = true;
|
|
2507
|
+
if (after) call += `;${showFallback()}${after}`;
|
|
2508
|
+
const late = result.ctx.lateHead();
|
|
2509
|
+
let head = "";
|
|
2510
|
+
if (late.html || late.title !== void 0) {
|
|
2511
|
+
head = `<template b-h="${boundary.id}">${late.html}</template>`;
|
|
2512
|
+
const title = late.title === void 0 ? "" : `,${scriptJSON(late.title)}`;
|
|
2513
|
+
call += `;${headSwap ? "" : HEAD}$bH(${id}${title})`;
|
|
2514
|
+
headSwap = true;
|
|
2515
|
+
}
|
|
2516
|
+
pending().push(`<template b-l="${boundary.id}">${result.html}</template>${head}${result.ctx.portals.join("")}${scriptTag}${call}<\/script>${script}`);
|
|
2517
|
+
});
|
|
2518
|
+
finish();
|
|
2519
|
+
});
|
|
2520
|
+
}, (error) => {
|
|
2521
|
+
console.error(error);
|
|
2522
|
+
turn(skip);
|
|
2523
|
+
});
|
|
2524
|
+
});
|
|
2525
|
+
if (options.defer) return {
|
|
2526
|
+
html: "",
|
|
2527
|
+
state: "",
|
|
2528
|
+
pending: queue === void 0 && open === 0 ? NOTHING_PENDING : pending().iterable,
|
|
2529
|
+
headers: event?.headers ?? new Headers(),
|
|
2530
|
+
status: event?.status ?? 200,
|
|
2531
|
+
next: () => ctx.next(),
|
|
2532
|
+
head: "",
|
|
2533
|
+
defer: ctx.target.status ?? "missing"
|
|
2534
|
+
};
|
|
2535
|
+
let state = "";
|
|
2536
|
+
let failure;
|
|
2537
|
+
serialize(ctx, (script) => {
|
|
2538
|
+
state = script;
|
|
2539
|
+
}, options.route, (error) => {
|
|
2540
|
+
failure = error;
|
|
2541
|
+
}, boundaries === 0 && (inOrder === void 0 || inOrder.length === 0));
|
|
2542
|
+
if (failure !== void 0) throw unsendable(failure, ctx);
|
|
2543
|
+
let page = html;
|
|
2544
|
+
if (inOrder) {
|
|
2545
|
+
const bodies = /* @__PURE__ */ new Map();
|
|
2546
|
+
const portals = [];
|
|
2547
|
+
for (let index = 0; index < inOrder.length; index++) {
|
|
2548
|
+
const boundary = inOrder[index];
|
|
2549
|
+
let result;
|
|
2550
|
+
try {
|
|
2551
|
+
result = await boundary.render;
|
|
2552
|
+
} catch (error) {
|
|
2553
|
+
console.error(error);
|
|
2554
|
+
continue;
|
|
2555
|
+
}
|
|
2556
|
+
if (boundary.cancelled || boundary.around) continue;
|
|
2557
|
+
bodies.set(String(boundary.id), result.html);
|
|
2558
|
+
portals.push(...result.ctx.portals);
|
|
2559
|
+
ctx.adoptHead(result.ctx.lateHead());
|
|
2560
|
+
serialize(result.ctx, (script) => {
|
|
2561
|
+
state += script;
|
|
2562
|
+
}, void 0, (error) => {
|
|
2563
|
+
failure = error;
|
|
2564
|
+
}, index === inOrder.length - 1);
|
|
2565
|
+
if (failure !== void 0) throw unsendable(failure, result.ctx);
|
|
2566
|
+
}
|
|
2567
|
+
page = beforeBodyEnd(inlineBodies(rendered, bodies), [...ctx.portals, ...portals].join(""));
|
|
2568
|
+
}
|
|
2569
|
+
return {
|
|
2570
|
+
html: page,
|
|
2571
|
+
state,
|
|
2572
|
+
pending: queue === void 0 && open === 0 ? NOTHING_PENDING : pending().iterable,
|
|
2573
|
+
headers: event?.headers ?? new Headers(),
|
|
2574
|
+
status: event?.status ?? 200,
|
|
2575
|
+
next: () => ctx.next(),
|
|
2576
|
+
head: ctx.headHTML(),
|
|
2577
|
+
event
|
|
2578
|
+
};
|
|
2579
|
+
}
|
|
2580
|
+
/** Crawlers and link previews, which read the page without running its scripts. */
|
|
2581
|
+
const BOTS = /bot\b|bot\/|crawl|spider|slurp|bingpreview|facebookexternalhit|embedly|quora link preview|outbrain|pinterest|vkshare|w3c_validator|whatsapp|lighthouse|google-inspectiontool|headlesschrome/i;
|
|
2582
|
+
/** True if a render with these options writes its bodies in place. */
|
|
2583
|
+
function rendersInOrder(option, request) {
|
|
2584
|
+
if (typeof option === "boolean") return option;
|
|
2585
|
+
if (!request) return false;
|
|
2586
|
+
if (typeof option === "function") return option(request);
|
|
2587
|
+
return BOTS.test(request.headers.get("user-agent") ?? "");
|
|
2588
|
+
}
|
|
2589
|
+
const BOUNDARY_MARKER = /<!--(l[\d.]+|\/l)-->/g;
|
|
2590
|
+
/**
|
|
2591
|
+
* Puts the bodies of boundaries in place of their fallbacks, with the bodies
|
|
2592
|
+
* inside them, as the swap script would in the browser. A `#defer` block
|
|
2593
|
+
* loses its `<template>` too, so the browser does not ask for a body that
|
|
2594
|
+
* is there. A boundary without a body keeps its fallback.
|
|
2595
|
+
*/
|
|
2596
|
+
function inlineBodies(html, bodies) {
|
|
2597
|
+
let result = "";
|
|
2598
|
+
let position = 0;
|
|
2599
|
+
BOUNDARY_MARKER.lastIndex = 0;
|
|
2600
|
+
for (let match = BOUNDARY_MARKER.exec(html); match; match = BOUNDARY_MARKER.exec(html)) {
|
|
2601
|
+
if (match[1] === "/l") continue;
|
|
2602
|
+
const id = match[1].slice(1);
|
|
2603
|
+
let depth = 0;
|
|
2604
|
+
let end = -1;
|
|
2605
|
+
for (let inner = BOUNDARY_MARKER.exec(html); inner; inner = BOUNDARY_MARKER.exec(html)) if (inner[1] !== "/l") depth++;
|
|
2606
|
+
else if (depth === 0) {
|
|
2607
|
+
end = inner.index + inner[0].length;
|
|
2608
|
+
break;
|
|
2609
|
+
} else depth--;
|
|
2610
|
+
if (end === -1) break;
|
|
2611
|
+
const body = bodies.get(id);
|
|
2612
|
+
if (body === void 0) continue;
|
|
2613
|
+
let before = html.slice(position, match.index);
|
|
2614
|
+
before = before.replace(new RegExp(`<template b-b="[^"]*" b-defer="[^":]*:${id.replace(/\./g, "\\.")}:[^"]*"></template>$`), "");
|
|
2615
|
+
result += before + inlineBodies(body, bodies);
|
|
2616
|
+
position = end;
|
|
2617
|
+
BOUNDARY_MARKER.lastIndex = end;
|
|
2618
|
+
}
|
|
2619
|
+
return result + html.slice(position);
|
|
2620
|
+
}
|
|
2621
|
+
const HTML = /<html[\s>]/i;
|
|
2622
|
+
/**
|
|
2623
|
+
* Inserts markup before `</body>`, or at the end if there is none. `index`
|
|
2624
|
+
* is where `</body>` is, when the caller found it already.
|
|
2625
|
+
*/
|
|
2626
|
+
function beforeBodyEnd(html, content, index = content ? html.toLowerCase().lastIndexOf("</body>") : -1) {
|
|
2627
|
+
if (!content) return html;
|
|
2628
|
+
return index === -1 ? html + content : html.slice(0, index) + content + html.slice(index);
|
|
2629
|
+
}
|
|
2630
|
+
/**
|
|
2631
|
+
* Builds the first chunk of a page: the whole rendered document, with the
|
|
2632
|
+
* page state and the scripts. A component that renders `<html>` gets the
|
|
2633
|
+
* doctype, its head before `</head>`, and the state and scripts before
|
|
2634
|
+
* `</body>`. Markup that resolves later is written after it.
|
|
2635
|
+
*/
|
|
2636
|
+
function firstRender(html, componentHead, state, options) {
|
|
2637
|
+
const head = (options.head ?? "") + componentHead;
|
|
2638
|
+
const tail = state + (options.scripts ?? "");
|
|
2639
|
+
const match = HTML.exec(html);
|
|
2640
|
+
if (!match) return (typeof options.start === "function" ? options.start(head) : options.start ?? "") + html + tail + (options.end ?? "");
|
|
2641
|
+
const headContent = html.slice(0, match.index) + head;
|
|
2642
|
+
let page = html.slice(match.index);
|
|
2643
|
+
const lower = page.toLowerCase();
|
|
2644
|
+
const headEnd = lower.indexOf("</head>");
|
|
2645
|
+
let bodyEnd = lower.lastIndexOf("</body>");
|
|
2646
|
+
let at = headEnd;
|
|
2647
|
+
let inserted = headContent;
|
|
2648
|
+
if (headEnd === -1 && headContent) {
|
|
2649
|
+
const bodyStart = lower.search(/<body[\s>]/);
|
|
2650
|
+
at = bodyStart === -1 ? page.indexOf(">") + 1 : bodyStart;
|
|
2651
|
+
inserted = `<head>${headContent}</head>`;
|
|
2652
|
+
}
|
|
2653
|
+
if (at !== -1 && inserted) {
|
|
2654
|
+
page = page.slice(0, at) + inserted + page.slice(at);
|
|
2655
|
+
const own = inserted.toLowerCase();
|
|
2656
|
+
if (bodyEnd >= at) bodyEnd += own.length;
|
|
2657
|
+
else if (own.includes("</body>")) bodyEnd = at + own.lastIndexOf("</body>");
|
|
2658
|
+
}
|
|
2659
|
+
return `<!doctype html>${beforeBodyEnd(page, tail, bodyEnd)}`;
|
|
2660
|
+
}
|
|
2661
|
+
/**
|
|
2662
|
+
* Renders a component as a stream. The first chunk is the whole first
|
|
2663
|
+
* render, sent as soon as it is ready. Each `#loading` body and each state
|
|
2664
|
+
* record that settles a promise follows it as it resolves. A component that
|
|
2665
|
+
* renders `<html>` gets the doctype and its head.
|
|
2666
|
+
*/
|
|
2667
|
+
function renderToStream(Root, props, options = {}) {
|
|
2668
|
+
return partsStream(() => render(Root, props, options), options);
|
|
2669
|
+
}
|
|
2670
|
+
/** Streams the parts of a page from `render`: the first render whole, then what resolves later. */
|
|
2671
|
+
function streamParts(parts, options = {}) {
|
|
2672
|
+
return partsStream(() => parts, options);
|
|
2673
|
+
}
|
|
2674
|
+
/** A stream of the parts of a page. An error while it gets or writes them fails the stream. */
|
|
2675
|
+
function partsStream(getParts, options) {
|
|
2676
|
+
let parts;
|
|
2677
|
+
let cancelled = false;
|
|
2678
|
+
return new ReadableStream({
|
|
2679
|
+
async start(controller) {
|
|
2680
|
+
try {
|
|
2681
|
+
parts = await getParts();
|
|
2682
|
+
if (cancelled) {
|
|
2683
|
+
parts.event?.abort();
|
|
2684
|
+
return;
|
|
2685
|
+
}
|
|
2686
|
+
await writeParts(parts, options, controller, () => cancelled);
|
|
2687
|
+
} catch (error) {
|
|
2688
|
+
if (!cancelled) controller.error(error);
|
|
2689
|
+
}
|
|
2690
|
+
},
|
|
2691
|
+
cancel(reason) {
|
|
2692
|
+
cancelled = true;
|
|
2693
|
+
parts?.event?.abort(reason);
|
|
2694
|
+
}
|
|
2695
|
+
});
|
|
2696
|
+
}
|
|
2697
|
+
async function writeParts(parts, options, controller, cancelled = () => false) {
|
|
2698
|
+
controller.enqueue(firstRender(parts.html, parts.head, parts.state, options));
|
|
2699
|
+
if (parts.pending !== NOTHING_PENDING) for await (const chunk of parts.pending) {
|
|
2700
|
+
if (cancelled()) return;
|
|
2701
|
+
controller.enqueue(chunk);
|
|
2702
|
+
}
|
|
2703
|
+
if (!cancelled()) controller.close();
|
|
2704
|
+
}
|
|
2705
|
+
/**
|
|
2706
|
+
* The message and status that answer an error. A `ServerError` sends its
|
|
2707
|
+
* own. Any other error is logged, and sends `fallback` with status 500.
|
|
2708
|
+
*/
|
|
2709
|
+
function errorAnswer(error, fallback) {
|
|
2710
|
+
if (error instanceof ServerError) return {
|
|
2711
|
+
message: error.message,
|
|
2712
|
+
status: error.status
|
|
2713
|
+
};
|
|
2714
|
+
console.error(error);
|
|
2715
|
+
return {
|
|
2716
|
+
message: fallback,
|
|
2717
|
+
status: 500
|
|
2718
|
+
};
|
|
2719
|
+
}
|
|
2720
|
+
/** True for a request that a `<form>` sent, without client code. */
|
|
2721
|
+
function isFormPost(request) {
|
|
2722
|
+
const type = request.headers.get("content-type") ?? "";
|
|
2723
|
+
return type.startsWith("application/x-www-form-urlencoded") || type.startsWith("multipart/form-data");
|
|
2724
|
+
}
|
|
2725
|
+
/** The answer to a call or a form post from a page of another site. See `isCrossSite`. */
|
|
2726
|
+
function crossSiteAnswer() {
|
|
2727
|
+
return new Response("Calls from other sites are not allowed", { status: 403 });
|
|
2728
|
+
}
|
|
2729
|
+
/** The answer to a call or a form post to a server function that does not exist. */
|
|
2730
|
+
function unknownAnswer(id) {
|
|
2731
|
+
return new Response(`Unknown server function "${id}"`, { status: 404 });
|
|
2732
|
+
}
|
|
2733
|
+
/**
|
|
2734
|
+
* A response with `init`. A DOM environment such as happy-dom drops
|
|
2735
|
+
* `set-cookie` from the headers that a response is made with, but keeps the
|
|
2736
|
+
* ones added after, so a page in `brumate/testing` keeps its cookies.
|
|
2737
|
+
*/
|
|
2738
|
+
function respond(body, init) {
|
|
2739
|
+
const result = new Response(body, init);
|
|
2740
|
+
if (result.headers.getSetCookie().length === 0) for (const cookie of init.headers.getSetCookie()) result.headers.append("set-cookie", cookie);
|
|
2741
|
+
return result;
|
|
2742
|
+
}
|
|
2743
|
+
/**
|
|
2744
|
+
* True when a request names a build other than the server's, so its page is
|
|
2745
|
+
* from before a deploy. Calls send the build in `x-brumate-build`, and forms
|
|
2746
|
+
* without scripts in `__build` of their URL.
|
|
2747
|
+
*/
|
|
2748
|
+
function isSkewed(request, build) {
|
|
2749
|
+
const sent = request.headers.get("x-brumate-build") ?? new URL(request.url).searchParams.get("__build");
|
|
2750
|
+
return build !== void 0 && sent !== null && sent !== build;
|
|
2751
|
+
}
|
|
2752
|
+
/**
|
|
2753
|
+
* The answer to a form without scripts, from a page of another build, that
|
|
2754
|
+
* posts to a function that is gone. It goes back to its page, which loads
|
|
2755
|
+
* with the new build, or to `/` when the page is on another site.
|
|
2756
|
+
*/
|
|
2757
|
+
function backAnswer(request) {
|
|
2758
|
+
let location = "/";
|
|
2759
|
+
const referer = request.headers.get("referer");
|
|
2760
|
+
if (referer) try {
|
|
2761
|
+
const page = new URL(referer);
|
|
2762
|
+
if (page.origin === new URL(request.url).origin) location = `${page.pathname}${page.search}`;
|
|
2763
|
+
} catch {}
|
|
2764
|
+
return new Response(null, {
|
|
2765
|
+
status: 303,
|
|
2766
|
+
headers: { location }
|
|
2767
|
+
});
|
|
2768
|
+
}
|
|
2769
|
+
/** The answer to a request from a page of another build that the server cannot serve. */
|
|
2770
|
+
function skewAnswer(build) {
|
|
2771
|
+
return new Response(JSON.stringify({ error: "The site changed. Load the page again" }), {
|
|
2772
|
+
status: 409,
|
|
2773
|
+
headers: {
|
|
2774
|
+
"content-type": "application/json",
|
|
2775
|
+
"x-brumate-build": build
|
|
2776
|
+
}
|
|
2777
|
+
});
|
|
2778
|
+
}
|
|
2779
|
+
/**
|
|
2780
|
+
* Calls a server function with the data of a form that the browser sent.
|
|
2781
|
+
* Returns its result, or the response that answers the post instead: a
|
|
2782
|
+
* `redirect` in the function sends the browser there, and an error answers
|
|
2783
|
+
* with a short text page, because there is no page to report it in. The
|
|
2784
|
+
* response has `headers`. With `base`, the location of a redirect is
|
|
2785
|
+
* resolved against it.
|
|
2786
|
+
*/
|
|
2787
|
+
async function callWithForm(invoke, headers, base) {
|
|
2788
|
+
try {
|
|
2789
|
+
return { result: await invoke() };
|
|
2790
|
+
} catch (error) {
|
|
2791
|
+
return { answer: formFailure(error, headers, base) };
|
|
2792
|
+
}
|
|
2793
|
+
}
|
|
2794
|
+
/** The answer to a form post whose server function threw, or whose data could not be read. */
|
|
2795
|
+
function formFailure(error, headers, base) {
|
|
2796
|
+
if (error instanceof Redirect) {
|
|
2797
|
+
headers.set("location", base ? new URL(error.location, base).href : error.location);
|
|
2798
|
+
return respond(null, {
|
|
2799
|
+
status: error.status,
|
|
2800
|
+
headers
|
|
2801
|
+
});
|
|
2802
|
+
}
|
|
2803
|
+
const { message, status } = errorAnswer(error, "The server function failed");
|
|
2804
|
+
headers.set("content-type", "text/plain; charset=utf-8");
|
|
2805
|
+
return respond(message, {
|
|
2806
|
+
status,
|
|
2807
|
+
headers
|
|
2808
|
+
});
|
|
2809
|
+
}
|
|
2810
|
+
/**
|
|
2811
|
+
* Calls a server function with the data of a form that the browser sent, and
|
|
2812
|
+
* sends the browser back to the page with a redirect. The response has the
|
|
2813
|
+
* headers of the event, such as cookies that the function set.
|
|
2814
|
+
*/
|
|
2815
|
+
async function handleForm(invoke, event) {
|
|
2816
|
+
const { headers } = event;
|
|
2817
|
+
const outcome = await callWithForm(invoke, headers);
|
|
2818
|
+
if ("answer" in outcome) return outcome.answer;
|
|
2819
|
+
headers.set("location", event.request.headers.get("referer") ?? "/");
|
|
2820
|
+
return respond(null, {
|
|
2821
|
+
status: 303,
|
|
2822
|
+
headers
|
|
2823
|
+
});
|
|
2824
|
+
}
|
|
2825
|
+
/**
|
|
2826
|
+
* The arguments of a call. They come as seroval JSON, or as multipart form
|
|
2827
|
+
* data when they hold files: the JSON in `args`, and each file in
|
|
2828
|
+
* `file<index>`, whose index stands in the JSON.
|
|
2829
|
+
*/
|
|
2830
|
+
async function readArgs(request) {
|
|
2831
|
+
if (!request.headers.has("x-brumate-args")) return fromJSON(await request.json(), {
|
|
2832
|
+
plugins,
|
|
2833
|
+
...serialOptions()
|
|
2834
|
+
});
|
|
2835
|
+
const form = await request.formData();
|
|
2836
|
+
return fromJSON(JSON.parse(String(form.get("args"))), {
|
|
2837
|
+
plugins: callPlugins(void 0, form),
|
|
2838
|
+
...serialOptions()
|
|
2839
|
+
});
|
|
2840
|
+
}
|
|
2841
|
+
/**
|
|
2842
|
+
* True when a request comes from a page of another site. Server function
|
|
2843
|
+
* calls and form posts send the cookies of the user, so another site must
|
|
2844
|
+
* not be able to make them.
|
|
2845
|
+
*
|
|
2846
|
+
* The browser sends `Origin` with every call and post. Without it, an older
|
|
2847
|
+
* browser's `Sec-Fetch-Site` decides. A request with neither does not come
|
|
2848
|
+
* from a page in a browser, so it is allowed.
|
|
2849
|
+
*/
|
|
2850
|
+
function isCrossSite(request, options = {}) {
|
|
2851
|
+
const origin = request.headers.get("origin");
|
|
2852
|
+
if (origin === null) {
|
|
2853
|
+
const site = request.headers.get("sec-fetch-site");
|
|
2854
|
+
return site === "cross-site" || site === "same-site";
|
|
2855
|
+
}
|
|
2856
|
+
if (origin === "null") return true;
|
|
2857
|
+
if (options.origins?.includes(origin)) return false;
|
|
2858
|
+
let host;
|
|
2859
|
+
try {
|
|
2860
|
+
host = new URL(origin).host;
|
|
2861
|
+
} catch {
|
|
2862
|
+
return true;
|
|
2863
|
+
}
|
|
2864
|
+
return ![
|
|
2865
|
+
new URL(request.url).host,
|
|
2866
|
+
request.headers.get("host"),
|
|
2867
|
+
request.headers.get("x-forwarded-host")
|
|
2868
|
+
].includes(host);
|
|
2869
|
+
}
|
|
2870
|
+
/**
|
|
2871
|
+
* Answers a server function call from `brumate/client`. Returns undefined
|
|
2872
|
+
* when the request is not a call, so other handlers can answer it. Server
|
|
2873
|
+
* functions read the request with `getEvent()`. A call from a page of
|
|
2874
|
+
* another site answers 403. See `isCrossSite`.
|
|
2875
|
+
*/
|
|
2876
|
+
async function handleRequest(functions, request, prefix = "/_brumate", options = {}) {
|
|
2877
|
+
const url = new URL(request.url);
|
|
2878
|
+
if (request.method !== "POST" || !url.pathname.startsWith(`${prefix}/`)) return;
|
|
2879
|
+
if (isCrossSite(request, options)) return crossSiteAnswer();
|
|
2880
|
+
const id = decodeURIComponent(url.pathname.slice(prefix.length + 1));
|
|
2881
|
+
if (id === "") {
|
|
2882
|
+
const headers = options.build === void 0 ? {} : { "x-brumate-build": options.build };
|
|
2883
|
+
return new Response(null, {
|
|
2884
|
+
status: 204,
|
|
2885
|
+
headers
|
|
2886
|
+
});
|
|
2887
|
+
}
|
|
2888
|
+
const form = isFormPost(request) && !request.headers.has("x-brumate-args");
|
|
2889
|
+
const posted = form && !request.headers.has("x-brumate-result");
|
|
2890
|
+
const fn = functions[id];
|
|
2891
|
+
if (!fn) {
|
|
2892
|
+
if (!isSkewed(request, options.build)) return unknownAnswer(id);
|
|
2893
|
+
return posted ? backAnswer(request) : skewAnswer(options.build);
|
|
2894
|
+
}
|
|
2895
|
+
const event = new RequestEvent(request, {
|
|
2896
|
+
kind: "call",
|
|
2897
|
+
waitUntil: options.waitUntil,
|
|
2898
|
+
address: options.address,
|
|
2899
|
+
prerender: options.prerender
|
|
2900
|
+
});
|
|
2901
|
+
let args;
|
|
2902
|
+
try {
|
|
2903
|
+
args = form ? [await request.formData()] : await readArgs(request);
|
|
2904
|
+
} catch (error) {
|
|
2905
|
+
return posted ? formFailure(error, event.headers) : callFailure(error, event.headers);
|
|
2906
|
+
}
|
|
2907
|
+
event.call = {
|
|
2908
|
+
id,
|
|
2909
|
+
args
|
|
2910
|
+
};
|
|
2911
|
+
const invoke = () => withEvent(event, () => fn(...args));
|
|
2912
|
+
return runEntry(options.middleware, event, () => runEntry(options.fileMiddleware?.[id], event, () => posted ? handleForm(invoke, event) : answerCall(functions, event, async () => invoke())));
|
|
2913
|
+
}
|
|
2914
|
+
/**
|
|
2915
|
+
* Answers a server function call with its result as a stream of seroval
|
|
2916
|
+
* chunks, so promises and async iterables in it stream as they settle. A
|
|
2917
|
+
* redirect is sent as a header, so the client can follow it. An error
|
|
2918
|
+
* answers with a message that the client throws.
|
|
2919
|
+
*/
|
|
2920
|
+
async function answerCall(functions, event, run) {
|
|
2921
|
+
const { headers } = event;
|
|
2922
|
+
try {
|
|
2923
|
+
const result = await run();
|
|
2924
|
+
const { refreshed } = event;
|
|
2925
|
+
if (refreshed?.size) {
|
|
2926
|
+
const ids = Object.keys(functions).filter((key) => refreshed.has(unwrap(functions[key])));
|
|
2927
|
+
if (ids.length > 0) headers.set("x-brumate-refresh", ids.join(","));
|
|
2928
|
+
}
|
|
2929
|
+
headers.set("content-type", STREAM_TYPE);
|
|
2930
|
+
return respond(toChunkStream(result, (reason) => event.abort(reason)), { headers });
|
|
2931
|
+
} catch (error) {
|
|
2932
|
+
return callFailure(error, headers);
|
|
2933
|
+
}
|
|
2934
|
+
}
|
|
2935
|
+
/** The answer to a call whose server function threw, or whose arguments could not be read. */
|
|
2936
|
+
function callFailure(error, headers) {
|
|
2937
|
+
if (error instanceof Redirect) {
|
|
2938
|
+
headers.set("x-brumate-redirect", error.location);
|
|
2939
|
+
return respond(null, {
|
|
2940
|
+
status: 204,
|
|
2941
|
+
headers
|
|
2942
|
+
});
|
|
2943
|
+
}
|
|
2944
|
+
const { message, status } = errorAnswer(error, "The server function failed");
|
|
2945
|
+
headers.set("content-type", "application/json");
|
|
2946
|
+
return respond(JSON.stringify({ error: message }), {
|
|
2947
|
+
status,
|
|
2948
|
+
headers
|
|
2949
|
+
});
|
|
2950
|
+
}
|
|
2951
|
+
/** The key of a page in the store: its URL, and the base of a client navigation, by build. */
|
|
2952
|
+
function pageKey(url, request, build) {
|
|
2953
|
+
const base = request.headers.get("x-brumate-base") ?? "";
|
|
2954
|
+
return `brumate:page:${build ?? ""}:${base}:${url.pathname}${url.search}`;
|
|
2955
|
+
}
|
|
2956
|
+
/** The page that the store keeps for a key, when it is still fresh. */
|
|
2957
|
+
async function keptPage(key) {
|
|
2958
|
+
const text = await cacheStore().get(key);
|
|
2959
|
+
if (!text) return;
|
|
2960
|
+
const page = JSON.parse(text);
|
|
2961
|
+
const tags = Object.keys(page.tags);
|
|
2962
|
+
const versions = await tagVersions(tags);
|
|
2963
|
+
if (page.expires <= Date.now() || tags.some((tag) => versions[tag] !== page.tags[tag])) return;
|
|
2964
|
+
const headers = new Headers(page.headers);
|
|
2965
|
+
const maxAge = Number(/max-age=(\d+)/.exec(headers.get("cache-control") ?? "")?.[1] ?? 0);
|
|
2966
|
+
headers.set("age", String(Math.max(0, Math.floor(maxAge - (page.expires - Date.now()) / 1e3))));
|
|
2967
|
+
headers.set("x-brumate-cache", "hit");
|
|
2968
|
+
return new Response(page.body, {
|
|
2969
|
+
status: page.status,
|
|
2970
|
+
headers
|
|
2971
|
+
});
|
|
2972
|
+
}
|
|
2973
|
+
/** Keeps a public page in the store until its `max-age` ends. */
|
|
2974
|
+
async function keepPage(key, response, event) {
|
|
2975
|
+
const maxAge = Number(/max-age=(\d+)/.exec(response.headers.get("cache-control") ?? "")?.[1] ?? 0);
|
|
2976
|
+
if (maxAge <= 0) return;
|
|
2977
|
+
const versions = await tagVersions([...event.cacheTags].filter(([, version]) => version === void 0).map(([tag]) => tag));
|
|
2978
|
+
const page = {
|
|
2979
|
+
status: response.status,
|
|
2980
|
+
headers: [...response.headers].filter(([name]) => name !== "set-cookie"),
|
|
2981
|
+
body: await response.clone().text(),
|
|
2982
|
+
expires: Date.now() + maxAge * 1e3,
|
|
2983
|
+
tags: Object.fromEntries([...event.cacheTags].map(([tag, version]) => [tag, version ?? versions[tag]]))
|
|
2984
|
+
};
|
|
2985
|
+
await cacheStore().set(key, JSON.stringify(page), maxAge);
|
|
2986
|
+
}
|
|
2987
|
+
/** The `cache` of the page of a view: the nearest one along its `children`. */
|
|
2988
|
+
function pageCache(view) {
|
|
2989
|
+
const inner = view.slots.children;
|
|
2990
|
+
return (inner && pageCache(inner)) ?? view.cache;
|
|
2991
|
+
}
|
|
2992
|
+
/**
|
|
2993
|
+
* The `cache-control` of a page with `cache`. It is public only when the
|
|
2994
|
+
* request did not read or set anything of the user, and the page is a
|
|
2995
|
+
* success without cookies.
|
|
2996
|
+
*/
|
|
2997
|
+
function cacheControl(cache, event, response) {
|
|
2998
|
+
if (event?.personal || response.status !== 200 || response.headers.getSetCookie().length > 0) return "private, no-cache";
|
|
2999
|
+
const parts = ["public", `max-age=${Math.max(0, Math.floor(cache.maxAge))}`];
|
|
3000
|
+
if (cache.staleWhileRevalidate !== void 0) parts.push(`stale-while-revalidate=${Math.max(0, Math.floor(cache.staleWhileRevalidate))}`);
|
|
3001
|
+
return parts.join(", ");
|
|
3002
|
+
}
|
|
3003
|
+
const warnedPrivate = /* @__PURE__ */ new Set();
|
|
3004
|
+
/** Imports every module of a matched route before it renders. */
|
|
3005
|
+
async function resolveView(view) {
|
|
3006
|
+
const [module, loading, ...slots] = await Promise.all([
|
|
3007
|
+
view.load(),
|
|
3008
|
+
view.loading?.(),
|
|
3009
|
+
...Object.values(view.slots).map(resolveView)
|
|
3010
|
+
]);
|
|
3011
|
+
const names = Object.keys(view.slots);
|
|
3012
|
+
return {
|
|
3013
|
+
key: view.key,
|
|
3014
|
+
component: module.default,
|
|
3015
|
+
loading: loading?.default,
|
|
3016
|
+
cache: module.cache,
|
|
3017
|
+
slots: Object.fromEntries(names.map((name, index) => [name, slots[index]]))
|
|
3018
|
+
};
|
|
3019
|
+
}
|
|
3020
|
+
/**
|
|
3021
|
+
* Renders a view where its layout inserts it. A view with a loading file
|
|
3022
|
+
* streams in after the rest of the page, as a `#loading` body does.
|
|
3023
|
+
*/
|
|
3024
|
+
async function renderView(view, props, ctx, scope) {
|
|
3025
|
+
if (!view.loading) return component(viewComponent(view, props), {}, ctx, scope);
|
|
3026
|
+
const id = ctx.boundary();
|
|
3027
|
+
const fallback = await component(view.loading, props, ctx, scope);
|
|
3028
|
+
ctx.defer(id, (child) => component(viewComponent(view, props), {}, child, scope));
|
|
3029
|
+
return `<!--l${id}-->${fallback}<!--/l-->`;
|
|
3030
|
+
}
|
|
3031
|
+
/**
|
|
3032
|
+
* A component that renders a route, with its slots rendering where the
|
|
3033
|
+
* layout inserts them. `props` go to every view, such as `params`.
|
|
3034
|
+
*/
|
|
3035
|
+
function viewComponent(view, props) {
|
|
3036
|
+
return (_props, ctx) => {
|
|
3037
|
+
const own = { ...props };
|
|
3038
|
+
for (const [name, slot] of Object.entries(view.slots)) own[name] = lazy(async (at, scope) => {
|
|
3039
|
+
const root = at.peek();
|
|
3040
|
+
const html = await renderView(slot, props, at, scope);
|
|
3041
|
+
return `<!--R${scope ?? -1}:${name}:${root}:${encodeURIComponent(slot.key)}-->${html}<!--/R-->`;
|
|
3042
|
+
});
|
|
3043
|
+
return view.component(own, ctx);
|
|
3044
|
+
};
|
|
3045
|
+
}
|
|
3046
|
+
/**
|
|
3047
|
+
* Runs the server function that a form without scripts posted to a page, as
|
|
3048
|
+
* `?__action=<id>`. Returns its result for `$action`, or the response that
|
|
3049
|
+
* answers the post instead of the page: a redirect, or an error.
|
|
3050
|
+
* `handleRoute` adds the cookies of the event to that response, and no other
|
|
3051
|
+
* headers of the event.
|
|
3052
|
+
*/
|
|
3053
|
+
async function runAction(fn, event) {
|
|
3054
|
+
const { request } = event;
|
|
3055
|
+
const args = event.call.args;
|
|
3056
|
+
const outcome = await callWithForm(() => withEvent(event, () => fn(...args)), new Headers(), request.url);
|
|
3057
|
+
return "answer" in outcome ? outcome : { actions: /* @__PURE__ */ new Map([[fn, outcome.result]]) };
|
|
3058
|
+
}
|
|
3059
|
+
/**
|
|
3060
|
+
* Reads the server function that a form without scripts posted to a page,
|
|
3061
|
+
* as `?__action=<id>`, into `event.call`, before any middleware runs.
|
|
3062
|
+
* Returns the response that answers the post instead of the page: a post
|
|
3063
|
+
* from another site, an unknown function, or a form that cannot be read.
|
|
3064
|
+
*/
|
|
3065
|
+
async function readAction(url, event, options) {
|
|
3066
|
+
const { request } = event;
|
|
3067
|
+
const id = url.searchParams.get("__action");
|
|
3068
|
+
if (request.method !== "POST" || id === null) return;
|
|
3069
|
+
if (isCrossSite(request, options)) return crossSiteAnswer();
|
|
3070
|
+
if (!options.functions?.[id]) return isSkewed(request, options.build) ? backAnswer(request) : unknownAnswer(id);
|
|
3071
|
+
try {
|
|
3072
|
+
event.call = {
|
|
3073
|
+
id,
|
|
3074
|
+
args: [await request.formData()]
|
|
3075
|
+
};
|
|
3076
|
+
} catch (error) {
|
|
3077
|
+
return formFailure(error, new Headers(), request.url);
|
|
3078
|
+
}
|
|
3079
|
+
}
|
|
3080
|
+
/** Renders the page of a route tree, streamed, with the results of a form for `$action`. */
|
|
3081
|
+
async function renderPage(view, props, request, options, extra) {
|
|
3082
|
+
const base = Number(request.headers.get("x-brumate-base"));
|
|
3083
|
+
const defer = deferTarget(request);
|
|
3084
|
+
if (defer) return renderDeferred(view, props, request, options, defer, base);
|
|
3085
|
+
const event = options.event;
|
|
3086
|
+
if (options.dev && event) {
|
|
3087
|
+
event.trace = [];
|
|
3088
|
+
event.traceStart = performance.now();
|
|
3089
|
+
}
|
|
3090
|
+
const path = new URL(request.url).pathname;
|
|
3091
|
+
const endRender = event?.traced("render", path) ?? (() => {});
|
|
3092
|
+
const hints = request.headers.has("x-brumate-base") ? [] : options.hints ?? [];
|
|
3093
|
+
const nonce = options.nonce === void 0 ? "" : ` nonce="${escapeAttribute(options.nonce)}"`;
|
|
3094
|
+
const links = nonce ? [] : hints.map((url) => `<${url}>; rel=modulepreload`);
|
|
3095
|
+
if (links.length > 0) options.earlyHints?.(links);
|
|
3096
|
+
const preload = hints.map((url) => `<link rel="modulepreload"${nonce} href="${escapeAttribute(url)}">`).join("");
|
|
3097
|
+
const parts = await render(viewComponent(view, props), {}, {
|
|
3098
|
+
...options,
|
|
3099
|
+
request,
|
|
3100
|
+
actions: extra.actions,
|
|
3101
|
+
route: view.key,
|
|
3102
|
+
params: props.params,
|
|
3103
|
+
base: Number.isSafeInteger(base) && base > 0 ? base : void 0
|
|
3104
|
+
});
|
|
3105
|
+
endRender();
|
|
3106
|
+
const endStream = event?.traced("stream", "the rest of the page") ?? (() => {});
|
|
3107
|
+
const headers = new Headers(parts.headers);
|
|
3108
|
+
headers.set("content-type", "text/html; charset=utf-8");
|
|
3109
|
+
headers.append("vary", "x-brumate-defer");
|
|
3110
|
+
headers.append("vary", "x-brumate-base");
|
|
3111
|
+
for (const link of links) headers.append("link", link);
|
|
3112
|
+
let html = streamParts(parts, {
|
|
3113
|
+
...options,
|
|
3114
|
+
head: preload + (options.head ?? "")
|
|
3115
|
+
});
|
|
3116
|
+
if (event?.trace) {
|
|
3117
|
+
const trace = event.trace;
|
|
3118
|
+
html = html.pipeThrough(new TransformStream({ flush(controller) {
|
|
3119
|
+
endStream();
|
|
3120
|
+
const json = JSON.stringify({
|
|
3121
|
+
route: path,
|
|
3122
|
+
entries: trace
|
|
3123
|
+
}).replace(/</g, "\\u003c");
|
|
3124
|
+
controller.enqueue(`<script type="application/json" b-trace>${json}<\/script>`);
|
|
3125
|
+
} }));
|
|
3126
|
+
}
|
|
3127
|
+
const body = html.pipeThrough(new TextEncoderStream());
|
|
3128
|
+
const cache = request.method === "GET" || request.method === "HEAD" ? pageCache(view) : void 0;
|
|
3129
|
+
if (!cache) return respond(body, {
|
|
3130
|
+
status: extra.status ?? parts.status,
|
|
3131
|
+
headers
|
|
3132
|
+
});
|
|
3133
|
+
const response = respond(await new Response(body).arrayBuffer(), {
|
|
3134
|
+
status: extra.status ?? parts.status,
|
|
3135
|
+
headers
|
|
3136
|
+
});
|
|
3137
|
+
const control = cacheControl(cache, options.event, response);
|
|
3138
|
+
if (options.dev) {
|
|
3139
|
+
response.headers.set("cache-control", "no-cache");
|
|
3140
|
+
response.headers.set("x-brumate-cache", control);
|
|
3141
|
+
if (control.startsWith("private") && !warnedPrivate.has(view.key)) {
|
|
3142
|
+
warnedPrivate.add(view.key);
|
|
3143
|
+
console.warn(`The page ${new URL(request.url).pathname} exports cache, but it read cookies or the authorization header, or set a cookie, so it is not cached for everyone. Move what reads the user into #defer.`);
|
|
3144
|
+
}
|
|
3145
|
+
} else response.headers.set("cache-control", control);
|
|
3146
|
+
return response;
|
|
3147
|
+
}
|
|
3148
|
+
/**
|
|
3149
|
+
* The `#defer` block that a request asks for, from `x-brumate-defer:
|
|
3150
|
+
* <boundary> <scope>:<anchor>`, which the browser sends when the block's
|
|
3151
|
+
* trigger fires.
|
|
3152
|
+
*/
|
|
3153
|
+
function deferTarget(request) {
|
|
3154
|
+
const match = /^([\d.]+) (-?[\d.]+:\d+)$/.exec(request.headers.get("x-brumate-defer") ?? "");
|
|
3155
|
+
return match ? {
|
|
3156
|
+
boundary: parseId(match[1]),
|
|
3157
|
+
at: match[2]
|
|
3158
|
+
} : void 0;
|
|
3159
|
+
}
|
|
3160
|
+
/**
|
|
3161
|
+
* Renders the route again and answers with the body of one `#defer` block:
|
|
3162
|
+
* its markup in a `<template b-l>`, the script that swaps it in, and its
|
|
3163
|
+
* state. The page renders with the base it had, so its IDs come out the
|
|
3164
|
+
* same. When the block is not where the browser has it, such as after the
|
|
3165
|
+
* data of the page changed, the answer is 409 and the fallback stays.
|
|
3166
|
+
*/
|
|
3167
|
+
async function renderDeferred(view, props, request, options, defer, base) {
|
|
3168
|
+
const parts = await render(viewComponent(view, props), {}, {
|
|
3169
|
+
...options,
|
|
3170
|
+
request,
|
|
3171
|
+
route: view.key,
|
|
3172
|
+
params: props.params,
|
|
3173
|
+
base: Number.isSafeInteger(base) && base > 0 ? base : void 0,
|
|
3174
|
+
defer
|
|
3175
|
+
});
|
|
3176
|
+
const headers = new Headers(parts.headers);
|
|
3177
|
+
headers.append("vary", "x-brumate-defer");
|
|
3178
|
+
if (parts.defer !== "found") return respond(null, {
|
|
3179
|
+
status: parts.defer === "moved" ? 409 : 404,
|
|
3180
|
+
headers
|
|
3181
|
+
});
|
|
3182
|
+
headers.set("content-type", "text/html; charset=utf-8");
|
|
3183
|
+
headers.set("x-brumate-defer", String(defer.boundary));
|
|
3184
|
+
return respond(new ReadableStream({ async start(controller) {
|
|
3185
|
+
try {
|
|
3186
|
+
if (parts.pending !== NOTHING_PENDING) for await (const chunk of parts.pending) controller.enqueue(chunk);
|
|
3187
|
+
controller.close();
|
|
3188
|
+
} catch (error) {
|
|
3189
|
+
controller.error(error);
|
|
3190
|
+
}
|
|
3191
|
+
} }).pipeThrough(new TextEncoderStream()), {
|
|
3192
|
+
status: parts.status,
|
|
3193
|
+
headers
|
|
3194
|
+
});
|
|
3195
|
+
}
|
|
3196
|
+
/**
|
|
3197
|
+
* Renders the first `_error.brm` that renders, from the innermost. Its
|
|
3198
|
+
* component gets `error`, with the message and the status.
|
|
3199
|
+
*/
|
|
3200
|
+
async function renderError(views, error, params, request, options) {
|
|
3201
|
+
for (const view of views) try {
|
|
3202
|
+
return await renderPage(await resolveView(view), {
|
|
3203
|
+
params,
|
|
3204
|
+
error
|
|
3205
|
+
}, request, options, { status: error.status });
|
|
3206
|
+
} catch (failure) {
|
|
3207
|
+
console.error(failure);
|
|
3208
|
+
}
|
|
3209
|
+
}
|
|
3210
|
+
/** Runs the middleware of the folders on the path, from the outside in, around the answer. */
|
|
3211
|
+
async function runMiddleware(loaders, request, event, answer) {
|
|
3212
|
+
const [first, ...rest] = loaders;
|
|
3213
|
+
if (!first) return answer();
|
|
3214
|
+
const { middleware } = await first();
|
|
3215
|
+
return withEvent(event, () => middleware(request, () => runMiddleware(rest, request, event, answer)));
|
|
3216
|
+
}
|
|
3217
|
+
/**
|
|
3218
|
+
* Answers a request with the route that matches its path, streamed:
|
|
3219
|
+
*
|
|
3220
|
+
* - The `_middleware.ts` of each folder on the path runs first, from the outside in.
|
|
3221
|
+
* - An endpoint at the path answers the methods that it exports.
|
|
3222
|
+
* - A form without scripts that posts to the page with `?__action=<id>`
|
|
3223
|
+
* runs that server function first, and the page renders with its result
|
|
3224
|
+
* for `$action`.
|
|
3225
|
+
* - A route that throws renders the nearest `_error.brm`, and a path that
|
|
3226
|
+
* no route matches renders the `_error.brm` of the root with status 404.
|
|
3227
|
+
*
|
|
3228
|
+
* Returns undefined when no route matches and the root has no error file or
|
|
3229
|
+
* middleware. A `redirect` while the page renders answers with a redirect.
|
|
3230
|
+
*/
|
|
3231
|
+
async function handleRoute(tree, request, options = {}) {
|
|
3232
|
+
if (options.shell !== void 0 && (request.method === "GET" || request.method === "HEAD") && !deferTarget(request) && !request.headers.has("x-brumate-base")) return fillHoles(tree, request, options.shell, options);
|
|
3233
|
+
const url = new URL(request.url);
|
|
3234
|
+
const match = matchRoute(tree, url.pathname);
|
|
3235
|
+
const event = options.event ?? new RequestEvent(request, {
|
|
3236
|
+
kind: await requestKind(request, match),
|
|
3237
|
+
waitUntil: options.waitUntil,
|
|
3238
|
+
address: options.address,
|
|
3239
|
+
prerender: options.prerender
|
|
3240
|
+
});
|
|
3241
|
+
event.route = match?.route;
|
|
3242
|
+
const answer = await routeAnswer(tree, match, url, {
|
|
3243
|
+
...options,
|
|
3244
|
+
event
|
|
3245
|
+
});
|
|
3246
|
+
return answer && withHeaders(answer, event.headers);
|
|
3247
|
+
}
|
|
3248
|
+
/**
|
|
3249
|
+
* What a request to a route is for: the body of a `#defer` block, an
|
|
3250
|
+
* endpoint when the folder has one that answers the method, or a page. A
|
|
3251
|
+
* path that no route matches is a page, the 404 page.
|
|
3252
|
+
*/
|
|
3253
|
+
async function requestKind(request, match) {
|
|
3254
|
+
if (deferTarget(request)) return "defer";
|
|
3255
|
+
if (match?.endpoint) {
|
|
3256
|
+
if ((await match.endpoint())[request.method === "HEAD" ? "GET" : request.method] || request.method !== "GET") return "endpoint";
|
|
3257
|
+
}
|
|
3258
|
+
return "page";
|
|
3259
|
+
}
|
|
3260
|
+
/**
|
|
3261
|
+
* The `#defer` blocks of a prerendered page that the server renders in the
|
|
3262
|
+
* response: those with the `load` or `idle` trigger. A `visible` block is
|
|
3263
|
+
* far down the page, so it waits for the browser to ask for it.
|
|
3264
|
+
*/
|
|
3265
|
+
const HOLE = /<template b-b="([^"]+)" b-defer="(?:load|idle):([^:"]+):([^"]*)"/g;
|
|
3266
|
+
/**
|
|
3267
|
+
* Answers with a prerendered page, then with the body of each of its
|
|
3268
|
+
* `#defer` blocks as it is ready, as a `#loading` body streams. Each body
|
|
3269
|
+
* renders in a request of its own, as when the browser asks for it, so
|
|
3270
|
+
* middleware runs for it. The loader leaves the marked blocks alone, and a
|
|
3271
|
+
* block whose body fails keeps its fallback.
|
|
3272
|
+
*/
|
|
3273
|
+
function fillHoles(tree, request, shell, options) {
|
|
3274
|
+
const holes = [...shell.matchAll(HOLE)];
|
|
3275
|
+
const headers = new Headers({ "content-type": "text/html; charset=utf-8" });
|
|
3276
|
+
if (holes.length === 0) return new Response(request.method === "HEAD" ? null : shell, { headers });
|
|
3277
|
+
headers.set("cache-control", "private, no-cache");
|
|
3278
|
+
headers.append("vary", "x-brumate-defer");
|
|
3279
|
+
headers.append("vary", "x-brumate-base");
|
|
3280
|
+
const marked = shell.replace(HOLE, (template) => `${template} b-hole`);
|
|
3281
|
+
const bodies = holes.map(async ([, at, boundary, base]) => {
|
|
3282
|
+
const asked = new Headers(request.headers);
|
|
3283
|
+
asked.set("x-brumate-defer", `${boundary} ${at}`);
|
|
3284
|
+
asked.set("x-brumate-base", base);
|
|
3285
|
+
try {
|
|
3286
|
+
const answer = await handleRoute(tree, new Request(request.url, { headers: asked }), {
|
|
3287
|
+
...options,
|
|
3288
|
+
shell: void 0,
|
|
3289
|
+
event: void 0
|
|
3290
|
+
});
|
|
3291
|
+
return answer?.ok && answer.headers.get("x-brumate-defer") === boundary ? await answer.text() : "";
|
|
3292
|
+
} catch (error) {
|
|
3293
|
+
console.error(error);
|
|
3294
|
+
return "";
|
|
3295
|
+
}
|
|
3296
|
+
});
|
|
3297
|
+
const body = new ReadableStream({ async start(controller) {
|
|
3298
|
+
controller.enqueue(marked);
|
|
3299
|
+
const pending = new Map(bodies.map((body, index) => [index, body.then((html) => ({
|
|
3300
|
+
html,
|
|
3301
|
+
index
|
|
3302
|
+
}))]));
|
|
3303
|
+
while (pending.size > 0) {
|
|
3304
|
+
const { html, index } = await Promise.race(pending.values());
|
|
3305
|
+
pending.delete(index);
|
|
3306
|
+
if (html) controller.enqueue(html);
|
|
3307
|
+
}
|
|
3308
|
+
controller.close();
|
|
3309
|
+
} }).pipeThrough(new TextEncoderStream());
|
|
3310
|
+
return new Response(request.method === "HEAD" ? null : body, { headers });
|
|
3311
|
+
}
|
|
3312
|
+
/** A response with more headers, such as cookies that middleware set. */
|
|
3313
|
+
function withHeaders(answer, headers) {
|
|
3314
|
+
const sent = new Set(answer.headers.getSetCookie());
|
|
3315
|
+
const cookies = headers.getSetCookie().filter((cookie) => !sent.has(cookie));
|
|
3316
|
+
if (cookies.length === 0) return answer;
|
|
3317
|
+
const result = respond(answer.body, answer);
|
|
3318
|
+
for (const cookie of cookies) result.headers.append("set-cookie", cookie);
|
|
3319
|
+
if (/^\s*public\b/.test(result.headers.get("cache-control") ?? "")) result.headers.set("cache-control", "private, no-cache");
|
|
3320
|
+
return result;
|
|
3321
|
+
}
|
|
3322
|
+
async function routeAnswer(tree, match, url, options) {
|
|
3323
|
+
const event = options.event;
|
|
3324
|
+
const { request } = event;
|
|
3325
|
+
if (deferTarget(request) && isSkewed(request, options.build)) return skewAnswer(options.build);
|
|
3326
|
+
if (!match) {
|
|
3327
|
+
const missing = notFound(tree);
|
|
3328
|
+
if (missing.errors.length === 0 && missing.middleware.length === 0 && !options.middleware) return;
|
|
3329
|
+
return runEntry(options.middleware, event, () => runMiddleware(missing.middleware, request, event, async () => {
|
|
3330
|
+
return await renderError(missing.errors, {
|
|
3331
|
+
message: "Not found",
|
|
3332
|
+
status: 404
|
|
3333
|
+
}, {}, request, options) ?? new Response("Not found", { status: 404 });
|
|
3334
|
+
}));
|
|
3335
|
+
}
|
|
3336
|
+
const refused = await readAction(url, event, options);
|
|
3337
|
+
if (refused) return refused;
|
|
3338
|
+
return runEntry(options.middleware, event, () => runMiddleware(match.middleware, request, event, () => answerRoute(match, request, url, options)));
|
|
3339
|
+
}
|
|
3340
|
+
/** Answers a request that a route matches, after its middleware. `url` is the URL of the request. */
|
|
3341
|
+
async function answerRoute(match, request, url, options) {
|
|
3342
|
+
if (match.endpoint) {
|
|
3343
|
+
const endpoint = await match.endpoint();
|
|
3344
|
+
const handler = endpoint[request.method] ?? (request.method === "HEAD" ? endpoint.GET : void 0);
|
|
3345
|
+
if (handler) return withEvent(options.event, () => handler(request, match.params));
|
|
3346
|
+
if (match.view.load === missingPage || request.method !== "GET") {
|
|
3347
|
+
const allow = Object.keys(endpoint).filter((name) => /^[A-Z]+$/.test(name));
|
|
3348
|
+
return new Response("Method not allowed", {
|
|
3349
|
+
status: 405,
|
|
3350
|
+
headers: { allow: allow.join(", ") }
|
|
3351
|
+
});
|
|
3352
|
+
}
|
|
3353
|
+
}
|
|
3354
|
+
const event = options.event;
|
|
3355
|
+
const call = event.call;
|
|
3356
|
+
return runEntry(call && options.fileMiddleware?.[call.id], event, () => renderRoute(match, request, url, options));
|
|
3357
|
+
}
|
|
3358
|
+
/** Runs the server function that a form posted to the page, if any, and renders the page. */
|
|
3359
|
+
async function renderRoute(match, request, url, options) {
|
|
3360
|
+
let actions;
|
|
3361
|
+
const event = options.event;
|
|
3362
|
+
if (event.call) {
|
|
3363
|
+
const outcome = await runAction(options.functions[event.call.id], event);
|
|
3364
|
+
if ("answer" in outcome) return outcome.answer;
|
|
3365
|
+
actions = outcome.actions;
|
|
3366
|
+
}
|
|
3367
|
+
const key = !event.call && !options.dev && options.pageCache !== false && event.kind === "page" && (request.method === "GET" || request.method === "HEAD") ? pageKey(url, request, options.build) : void 0;
|
|
3368
|
+
if (key && !event.personal) {
|
|
3369
|
+
const kept = await keptPage(key);
|
|
3370
|
+
if (kept) return kept;
|
|
3371
|
+
}
|
|
3372
|
+
try {
|
|
3373
|
+
const response = await renderPage(await resolveView(match.view), { params: match.params }, request, options, { actions });
|
|
3374
|
+
if (key && /^\s*public\b/.test(response.headers.get("cache-control") ?? "")) await keepPage(key, response, event);
|
|
3375
|
+
return response;
|
|
3376
|
+
} catch (error) {
|
|
3377
|
+
if (isRedirect(error)) return new Response(null, {
|
|
3378
|
+
status: error.status,
|
|
3379
|
+
headers: { location: new URL(error.location, url).href }
|
|
3380
|
+
});
|
|
3381
|
+
if (options.dev && !(error instanceof ServerError)) throw error;
|
|
3382
|
+
const page = await renderError(match.errors, errorAnswer(error, "Something went wrong"), match.params, request, options);
|
|
3383
|
+
if (page) return page;
|
|
3384
|
+
throw error;
|
|
3385
|
+
}
|
|
3386
|
+
}
|
|
3387
|
+
/**
|
|
3388
|
+
* Renders an object of attributes. A handler in it, such as an `onClick`
|
|
3389
|
+
* that a component passes on with `...rest`, goes into `on` as a `b-on`
|
|
3390
|
+
* entry: the client function that it refers to, with the scope that the
|
|
3391
|
+
* function belongs to and the modifiers of its wrappers. A function that
|
|
3392
|
+
* refers to nothing in the browser is left out.
|
|
3393
|
+
*/
|
|
3394
|
+
function spread(attributes, on) {
|
|
3395
|
+
const entries = on && attributes["b-on"];
|
|
3396
|
+
if (typeof entries === "string") {
|
|
3397
|
+
on.unshift(entries);
|
|
3398
|
+
const { "b-on": _, ...rest } = attributes;
|
|
3399
|
+
return spread(rest, on);
|
|
3400
|
+
}
|
|
3401
|
+
for (const [name, value] of Object.entries(attributes)) {
|
|
3402
|
+
const reference = on && /^on[A-Z]/.test(name) && typeof value === "function" ? functionReferences.get(value) : void 0;
|
|
3403
|
+
if (reference) {
|
|
3404
|
+
const modifiers = value[MODIFIERS];
|
|
3405
|
+
on.push(handlerEntry(name, reference.ref, reference.scope, modifiers, reference.args));
|
|
3406
|
+
}
|
|
3407
|
+
if (on && (name === "value" || name === "checked") && isBinding(value)) {
|
|
3408
|
+
const setter = typeof value.set === "function" ? functionReferences.get(value.set) : void 0;
|
|
3409
|
+
on.push(bindEntry(name, value.ref, setter));
|
|
3410
|
+
}
|
|
3411
|
+
}
|
|
3412
|
+
return spread$1(attributes);
|
|
3413
|
+
}
|
|
3414
|
+
//#endregion
|
|
3415
|
+
export { withEvent as $, RateLimitError as A, matchRoute as B, stateScript as C, wait as D, streamState as E, ValidationError as F, storageStore as G, memoryStore as H, fieldErrors as I, dedupe as J, RequestEvent as K, parse as L, configureRateLimit as M, rateLimit as N, waitAll as O, parseSubmission as P, redirect as Q, parseForm as R, spread as S, streamParts as T, revalidate as U, cached as V, setCacheStore as W, getEvent as X, defineMiddleware as Y, isRedirect as Z, read as _, binding as a, renderToStream as b, dynamic as c, inlineBodies as d, insert as f, packState as g, memo as h, actionResult as i, clientAddress as j, idempotent as k, handleRequest as l, lazy as m, NotReady as n, children as o, isCrossSite as p, ServerError as q, action as r, component as s, Context as t, handleRoute as u, ready as v, stateValue as w, settled as x, render as y, safeParse as z };
|
|
3416
|
+
|
|
3417
|
+
//# sourceMappingURL=server-CxVDYE_V.js.map
|