@barqjs/start 0.0.0-stage → 0.2.0-next.1
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/LICENSE +21 -0
- package/README.md +817 -2
- package/dist/client-BsyxVCyu.js +1554 -0
- package/dist/client-BsyxVCyu.js.map +1 -0
- package/dist/client-DidH0F2e.d.ts +450 -0
- package/dist/client-DidH0F2e.d.ts.map +1 -0
- package/dist/client.d.ts +25 -0
- package/dist/client.js +4 -0
- package/dist/env-Bhk_aIkx.d.ts +47 -0
- package/dist/env-Bhk_aIkx.d.ts.map +1 -0
- package/dist/env.d.ts +2 -0
- package/dist/env.js +43 -0
- package/dist/env.js.map +1 -0
- package/dist/index-B4o7eyCr.d.ts +925 -0
- package/dist/index-B4o7eyCr.d.ts.map +1 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +6 -0
- package/dist/middleware-B-tI8QHQ.d.ts +574 -0
- package/dist/middleware-B-tI8QHQ.d.ts.map +1 -0
- package/dist/middleware.d.ts +2 -0
- package/dist/middleware.js +281 -0
- package/dist/middleware.js.map +1 -0
- package/dist/prerender.d.ts +118 -0
- package/dist/prerender.d.ts.map +1 -0
- package/dist/prerender.js +289 -0
- package/dist/prerender.js.map +1 -0
- package/dist/protocol.d.ts +56 -0
- package/dist/protocol.d.ts.map +1 -0
- package/dist/protocol.js +25 -0
- package/dist/protocol.js.map +1 -0
- package/dist/serve.d.ts +144 -0
- package/dist/serve.d.ts.map +1 -0
- package/dist/serve.js +221 -0
- package/dist/serve.js.map +1 -0
- package/dist/server-DG6jb_NA.js +1253 -0
- package/dist/server-DG6jb_NA.js.map +1 -0
- package/dist/server.d.ts +159 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +1 -0
- package/dist/src-odXG7kLA.js +1151 -0
- package/dist/src-odXG7kLA.js.map +1 -0
- package/dist/static-fn-CXjJi-It.js +122 -0
- package/dist/static-fn-CXjJi-It.js.map +1 -0
- package/package.json +106 -4
- package/src/client.ts +698 -0
- package/src/context.ts +699 -0
- package/src/cookies.ts +229 -0
- package/src/env.ts +86 -0
- package/src/fn-error.ts +121 -0
- package/src/frames-client.ts +1220 -0
- package/src/frames-server.ts +464 -0
- package/src/frames.ts +285 -0
- package/src/index.ts +740 -0
- package/src/live-client.ts +50 -0
- package/src/live-server.ts +292 -0
- package/src/middleware.ts +994 -0
- package/src/prerender.ts +477 -0
- package/src/protocol.ts +61 -0
- package/src/rate-limit.ts +202 -0
- package/src/serve.ts +153 -0
- package/src/server.ts +1026 -0
- package/src/session.ts +449 -0
- package/src/start-instance.ts +147 -0
- package/src/static-fn.ts +181 -0
- package/src/static.ts +302 -0
- package/src/stubs.ts +32 -0
- package/src/timing.ts +29 -0
- package/src/wire-types.ts +138 -0
|
@@ -0,0 +1,1253 @@
|
|
|
1
|
+
import { block, childScope, getOwner, isDev, isSafeError, runWithOwner, untrack } from "@barqjs/core";
|
|
2
|
+
import { SSR_HTML_BRAND, commitEventResponse, commitResponseStub, createRequestEvent, isNavigable, setHeadSink } from "@barqjs/web/internal";
|
|
3
|
+
import { SharedSources, diagnosticsEnabled, emitDiagnostic, setHydratable, shareSources, unshareSources } from "@barqjs/core/internal";
|
|
4
|
+
import { decodeWire, encodeWire, registerSerializationAdapters, serializationAdapters } from "@barqjs/server/codec";
|
|
5
|
+
import { provideRequestEvent, withoutRequestEvent } from "@barqjs/server/storage";
|
|
6
|
+
import { createBodyTooLargeError, limitBodyStream } from "srvx/body-limit";
|
|
7
|
+
import { B as invalidatedFrames, K as setRequestMiddlewareContext, X as takeSendContext, b as collectRequestCss, s as serverTiming, v as applyResponseDraft, w as draftedStatus, x as createResponseDraft } from "./src-odXG7kLA.js";
|
|
8
|
+
import { A as FRAME, B as installFrames, E as startOptions, F as RPC_FRAME, H as regionMarkup, J as UNKNOWN_HEADER, L as bindEntries, N as FRAME_CLOSE, P as RPC_FLIGHT, R as frameAddress, U as slotClose, V as isFrame, W as slotOpen, a as PAYLOAD_PARAM, c as RPC_CONTROL, d as RPC_STREAM, f as RPC_THROWN, i as LIVE_SUFFIX, j as FRAMES_HEADER, k as FLIGHT_TYPE, l as RPC_PREFIX, n as BUNDLED_BUILD, r as DATA_SUFFIX, s as RPC_CONTEXT, t as BUILD_HEADER, u as RPC_RESPONSE, x as isServerFn, z as frameOpen } from "./client-BsyxVCyu.js";
|
|
9
|
+
import { NOT_FOUND, REDIRECT, isInputError, runRequestMiddleware } from "./middleware.js";
|
|
10
|
+
import { SlotValue, esc, html, renderFrame, setServerComponent } from "@barqjs/server";
|
|
11
|
+
// src/frames-server.ts
|
|
12
|
+
/**
|
|
13
|
+
* How a frame crosses inside the page's own seed: by address, as a reference
|
|
14
|
+
* the browser resolves to the region already on the page. Registered when a
|
|
15
|
+
* frame is made and the registry does not hold it, so an application that has
|
|
16
|
+
* none sends the bytes it always did.
|
|
17
|
+
*/
|
|
18
|
+
const FRAME_ADAPTER = {
|
|
19
|
+
key: "barq.frame",
|
|
20
|
+
test: isFrame,
|
|
21
|
+
toSerializable: (frame) => ({
|
|
22
|
+
id: frame[FRAME].id,
|
|
23
|
+
address: frame[FRAME].address
|
|
24
|
+
}),
|
|
25
|
+
fromSerializable: (ref) => ref
|
|
26
|
+
};
|
|
27
|
+
function registerFrameAdapter() {
|
|
28
|
+
if (serializationAdapters().some((adapter) => adapter.key === FRAME_ADAPTER.key)) return;
|
|
29
|
+
registerSerializationAdapters([FRAME_ADAPTER]);
|
|
30
|
+
}
|
|
31
|
+
/** The server function's component result, as a frame. */
|
|
32
|
+
function serverFrame(id, data, component) {
|
|
33
|
+
registerFrameAdapter();
|
|
34
|
+
const args = data === void 0 ? void 0 : encodeWire(data);
|
|
35
|
+
const address = frameAddress(id, encodeWire(data ?? null));
|
|
36
|
+
const state = {
|
|
37
|
+
id,
|
|
38
|
+
address,
|
|
39
|
+
args,
|
|
40
|
+
component,
|
|
41
|
+
markup: (options) => renderMarkup(state, options)
|
|
42
|
+
};
|
|
43
|
+
const render = (props) => documentFrame(address, args, component, props, state.live === true);
|
|
44
|
+
return Object.assign(render, { [FRAME]: state });
|
|
45
|
+
}
|
|
46
|
+
/** A value read from a slot argument: a Cell is called, anything else is the value. */
|
|
47
|
+
function valueOf(argument) {
|
|
48
|
+
return typeof argument === "function" ? untrack(argument) : argument;
|
|
49
|
+
}
|
|
50
|
+
/** What a slot call returns that is never one of its properties: the markup's own names. */
|
|
51
|
+
const NOT_A_PROPERTY = /* @__PURE__ */ new Set([
|
|
52
|
+
"t",
|
|
53
|
+
"then",
|
|
54
|
+
"toString",
|
|
55
|
+
"toJSON",
|
|
56
|
+
"valueOf",
|
|
57
|
+
"constructor"
|
|
58
|
+
]);
|
|
59
|
+
/**
|
|
60
|
+
* The props a server component is rendered with: every name is a slot.
|
|
61
|
+
*
|
|
62
|
+
* A slot call is placed as markup, `<props.comment … />`, or read as data,
|
|
63
|
+
* `props.row(args).done`, which makes it a binding slot. Which one is known
|
|
64
|
+
* only once the component uses what the call returned, so the call answers
|
|
65
|
+
* both: its markup when it is placed, a stand-in for each property read.
|
|
66
|
+
*
|
|
67
|
+
* `fills` are the page's own props, when the frame is written into the page:
|
|
68
|
+
* each slot then holds what the browser would put there, for the first paint,
|
|
69
|
+
* and a binding slot's stand-ins hold the fill's first values.
|
|
70
|
+
*/
|
|
71
|
+
var Slots = class {
|
|
72
|
+
fills;
|
|
73
|
+
records = [];
|
|
74
|
+
props;
|
|
75
|
+
constructor(fills) {
|
|
76
|
+
this.fills = fills;
|
|
77
|
+
this.props = new Proxy({}, { get: (_, name) => typeof name === "string" ? this.slot(name) : void 0 });
|
|
78
|
+
}
|
|
79
|
+
slot(name) {
|
|
80
|
+
if (name === "children") {
|
|
81
|
+
const at = this.reserve();
|
|
82
|
+
this.records[at] = {
|
|
83
|
+
at,
|
|
84
|
+
name,
|
|
85
|
+
key: ""
|
|
86
|
+
};
|
|
87
|
+
return html(this.markup(at, this.fill(name, at, {}, void 0)));
|
|
88
|
+
}
|
|
89
|
+
return (args) => this.call(name, args);
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Taken before the region renders, so an occurrence inside it numbers after
|
|
93
|
+
* this one, in document order.
|
|
94
|
+
*/
|
|
95
|
+
reserve() {
|
|
96
|
+
this.records.push(null);
|
|
97
|
+
return this.records.length - 1;
|
|
98
|
+
}
|
|
99
|
+
call(name, args) {
|
|
100
|
+
const at = this.reserve();
|
|
101
|
+
const values = {};
|
|
102
|
+
let explicit = "";
|
|
103
|
+
for (const [key, argument] of Object.entries(args ?? {})) {
|
|
104
|
+
if (key === "children") continue;
|
|
105
|
+
if (key === "$key") explicit = String(valueOf(argument));
|
|
106
|
+
else values[key] = valueOf(argument);
|
|
107
|
+
}
|
|
108
|
+
const children = args?.children;
|
|
109
|
+
const region = children === void 0 ? void 0 : esc(children);
|
|
110
|
+
const record = {
|
|
111
|
+
at,
|
|
112
|
+
name,
|
|
113
|
+
key: explicit,
|
|
114
|
+
...args === void 0 ? {} : { args: encodeWire(values) },
|
|
115
|
+
...region === void 0 ? {} : {
|
|
116
|
+
region,
|
|
117
|
+
hasRegion: true
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
this.records[at] = record;
|
|
121
|
+
const filled = this.fill(name, at, values, region);
|
|
122
|
+
let markup = null;
|
|
123
|
+
const placed = () => {
|
|
124
|
+
if (record.bind === true) throw readTwice(name);
|
|
125
|
+
markup ??= this.markup(at, filled);
|
|
126
|
+
return markup;
|
|
127
|
+
};
|
|
128
|
+
const standIns = /* @__PURE__ */ new Map();
|
|
129
|
+
const read = (key) => {
|
|
130
|
+
if (markup !== null) throw readTwice(name);
|
|
131
|
+
record.bind = true;
|
|
132
|
+
let standIn = standIns.get(key);
|
|
133
|
+
if (standIn === void 0) {
|
|
134
|
+
const result = filled?.result;
|
|
135
|
+
const known = typeof result === "object" && result !== null;
|
|
136
|
+
const value = known ? runWithOwner(filled.scope, () => untrack(() => result[key])) : void 0;
|
|
137
|
+
standIn = new SlotValue(at, key, this.fills !== null && known, value);
|
|
138
|
+
standIns.set(key, standIn);
|
|
139
|
+
}
|
|
140
|
+
return standIn;
|
|
141
|
+
};
|
|
142
|
+
return new Proxy({}, {
|
|
143
|
+
get: (_, key) => {
|
|
144
|
+
if (key === SSR_HTML_BRAND) return record.bind !== true;
|
|
145
|
+
if (key === "t") return placed();
|
|
146
|
+
if (key === "toString") return placed;
|
|
147
|
+
if (typeof key === "symbol" || NOT_A_PROPERTY.has(key)) return void 0;
|
|
148
|
+
return read(key);
|
|
149
|
+
},
|
|
150
|
+
ownKeys: () => {
|
|
151
|
+
throw new Error(`[barq] A server component spread what \`props.${name}()\` returned. A binding slot's properties are placed one position at a time, so the markup shows what the browser fills: name each one, as in \`<li hidden={row.hidden}>\`.`);
|
|
152
|
+
}
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
markup(at, filled) {
|
|
156
|
+
const content = filled === null ? "" : runWithOwner(filled.scope, () => esc(filled.result));
|
|
157
|
+
return `<!--${slotOpen(at)}-->${content}<!--${slotClose(at)}-->`;
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* The page's fill for a slot, run once for the first paint: its content for
|
|
161
|
+
* a slot that is placed, its values for one read as data. Nothing over the
|
|
162
|
+
* wire, where the browser fills every slot itself.
|
|
163
|
+
*/
|
|
164
|
+
fill(name, at, values, region) {
|
|
165
|
+
if (this.fills === null) return null;
|
|
166
|
+
const given = this.fills[name];
|
|
167
|
+
const scope = childScope(getOwner(), "branch");
|
|
168
|
+
setHydratable(scope, true);
|
|
169
|
+
setServerComponent(scope, false);
|
|
170
|
+
if (name === "children") return {
|
|
171
|
+
result: given,
|
|
172
|
+
scope
|
|
173
|
+
};
|
|
174
|
+
const props = {};
|
|
175
|
+
for (const [key, value] of Object.entries(values)) props[key] = () => value;
|
|
176
|
+
if (region !== void 0) props.children = block(() => html(regionMarkup(String(at), region)));
|
|
177
|
+
const result = runWithOwner(scope, () => {
|
|
178
|
+
const fill = valueOf(given);
|
|
179
|
+
return typeof fill === "function" ? fill(props) : fill;
|
|
180
|
+
});
|
|
181
|
+
return result === void 0 ? null : {
|
|
182
|
+
result,
|
|
183
|
+
scope
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* The records the markup still carries, keyed: a boundary resumed during the
|
|
188
|
+
* render built its slots again, so only the occurrences in the final markup
|
|
189
|
+
* count, and a positional key is taken in that markup's order. `inline`
|
|
190
|
+
* drops each region, which the page already carries inside the slot.
|
|
191
|
+
*/
|
|
192
|
+
final(markup, inline) {
|
|
193
|
+
const present = /* @__PURE__ */ new Set();
|
|
194
|
+
for (const found of markup.matchAll(/<!--s:(\d+)-->/g)) present.add(Number(found[1]));
|
|
195
|
+
for (const found of markup.matchAll(/ _b-[^\s=>]+="([^"]*)"/g)) for (const entry of bindEntries(found[1])) present.add(entry.at);
|
|
196
|
+
for (const found of markup.matchAll(/<!--_b:(\d+):/g)) present.add(Number(found[1]));
|
|
197
|
+
const ordinal = /* @__PURE__ */ new Map();
|
|
198
|
+
const out = [];
|
|
199
|
+
for (const record of this.records) {
|
|
200
|
+
if (record === null || !present.has(record.at)) continue;
|
|
201
|
+
const count = ordinal.get(record.name) ?? 0;
|
|
202
|
+
ordinal.set(record.name, count + 1);
|
|
203
|
+
out.push({
|
|
204
|
+
at: record.at,
|
|
205
|
+
name: record.name,
|
|
206
|
+
key: record.key === "" ? `${record.name}:${count}` : `$${record.key}`,
|
|
207
|
+
...record.args === void 0 ? {} : { args: record.args },
|
|
208
|
+
...record.bind === true ? { bind: true } : {
|
|
209
|
+
...record.hasRegion === true ? { hasRegion: true } : {},
|
|
210
|
+
...inline || record.region === void 0 ? {} : { region: record.region }
|
|
211
|
+
}
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
return out;
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
function readTwice(name) {
|
|
218
|
+
return /* @__PURE__ */ new Error(`[barq] A server component both placed \`props.${name}()\` as markup and read it as data. A slot call is one or the other: place it, \`<props.` + name + " />`, for the browser's content, or read its properties, for a binding slot.");
|
|
219
|
+
}
|
|
220
|
+
/** Render a server component: what renders under it may read binding slots. */
|
|
221
|
+
function asServerComponent(render) {
|
|
222
|
+
const scope = childScope(getOwner(), "branch");
|
|
223
|
+
setServerComponent(scope, true);
|
|
224
|
+
return runWithOwner(scope, render);
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* The frame written into the page, where a route renders it.
|
|
228
|
+
*
|
|
229
|
+
* What the component declares for the head goes to the page's head as any
|
|
230
|
+
* component's does, and is recorded too, so the browser takes those tags over
|
|
231
|
+
* with the frame and drops them with it.
|
|
232
|
+
*/
|
|
233
|
+
function documentFrame(address, args, component, fills, live) {
|
|
234
|
+
const slots = new Slots(fills);
|
|
235
|
+
const head = [];
|
|
236
|
+
let outer = null;
|
|
237
|
+
outer = setHeadSink({
|
|
238
|
+
add: (tags) => {
|
|
239
|
+
head.push(...tags);
|
|
240
|
+
outer?.add(tags);
|
|
241
|
+
},
|
|
242
|
+
module: (url) => outer?.module?.(url)
|
|
243
|
+
});
|
|
244
|
+
const scope = childScope(getOwner(), "branch");
|
|
245
|
+
setHydratable(scope, false);
|
|
246
|
+
setServerComponent(scope, true);
|
|
247
|
+
let region;
|
|
248
|
+
try {
|
|
249
|
+
region = runWithOwner(scope, () => esc(component(slots.props)));
|
|
250
|
+
} finally {
|
|
251
|
+
setHeadSink(outer);
|
|
252
|
+
}
|
|
253
|
+
const payload = {
|
|
254
|
+
v: 1,
|
|
255
|
+
args,
|
|
256
|
+
...live ? { live: true } : {},
|
|
257
|
+
slots: slots.final(region, true),
|
|
258
|
+
head
|
|
259
|
+
};
|
|
260
|
+
return html(frameOpen(address, payload) + region + FRAME_CLOSE);
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* The answer to a call from the browser: the region rendered on its own, its
|
|
264
|
+
* slots empty. Its head carries what the region declared, the stylesheets and
|
|
265
|
+
* chunks its `lazy()` modules need, and the rules `@barqjs/css` registered
|
|
266
|
+
* while it rendered.
|
|
267
|
+
*/
|
|
268
|
+
async function frameResponse(frame) {
|
|
269
|
+
const answer = new Response(await frameMarkup(frame));
|
|
270
|
+
answer.headers.set("content-type", "text/html; charset=utf-8");
|
|
271
|
+
answer.headers.set("cache-control", "no-store");
|
|
272
|
+
answer.headers.set("x-barq-rpc", RPC_FRAME);
|
|
273
|
+
return answer;
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* A frame's markup over the wire: the region rendered on its own, its slots
|
|
277
|
+
* empty. Rendered by the frame itself, so by the copy of this module that made
|
|
278
|
+
* it: a host serving a built server through its own `serveBarq` answers the
|
|
279
|
+
* call from another copy, whose renderer is not the one the component was
|
|
280
|
+
* compiled against.
|
|
281
|
+
*/
|
|
282
|
+
function frameMarkup(frame, options = {}) {
|
|
283
|
+
return frame[FRAME].markup(options);
|
|
284
|
+
}
|
|
285
|
+
async function renderMarkup(frame, options) {
|
|
286
|
+
const { address, args, component } = frame;
|
|
287
|
+
const slots = new Slots(null);
|
|
288
|
+
const rendered = await renderFrame(() => asServerComponent(() => component(slots.props)), {
|
|
289
|
+
renderId: `f${address.slice(address.lastIndexOf("#") + 1)}-`,
|
|
290
|
+
session: options.session
|
|
291
|
+
});
|
|
292
|
+
const head = [...rendered.head];
|
|
293
|
+
const css = collectRequestCss();
|
|
294
|
+
if (css !== "") head.push({
|
|
295
|
+
tag: "style",
|
|
296
|
+
props: { "data-frame-css": address },
|
|
297
|
+
children: css
|
|
298
|
+
});
|
|
299
|
+
const payload = {
|
|
300
|
+
v: 1,
|
|
301
|
+
args,
|
|
302
|
+
...frame.live === true ? { live: true } : {},
|
|
303
|
+
slots: slots.final(rendered.html, false),
|
|
304
|
+
head
|
|
305
|
+
};
|
|
306
|
+
return frameOpen(address, payload) + rendered.html + FRAME_CLOSE;
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* The frames a request says its page has mounted. Untrusted input like any
|
|
310
|
+
* other: each one is asked for through its own function, validator and
|
|
311
|
+
* middleware included, and a malformed list is no list.
|
|
312
|
+
*/
|
|
313
|
+
function mountedFrames(header) {
|
|
314
|
+
if (header === null || header === "") return [];
|
|
315
|
+
let parsed;
|
|
316
|
+
try {
|
|
317
|
+
parsed = JSON.parse(header);
|
|
318
|
+
} catch {
|
|
319
|
+
return [];
|
|
320
|
+
}
|
|
321
|
+
if (!Array.isArray(parsed)) return [];
|
|
322
|
+
const out = [];
|
|
323
|
+
for (const entry of parsed.slice(0, 32)) {
|
|
324
|
+
if (typeof entry !== "object" || entry === null) continue;
|
|
325
|
+
const { id, args } = entry;
|
|
326
|
+
if (typeof id === "string") out.push({
|
|
327
|
+
id,
|
|
328
|
+
args
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
return out;
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* A mutation's answer with the regions it changed: its value in a script, then
|
|
335
|
+
* each changed frame's markup, as the page applies them. `ask` calls a mounted
|
|
336
|
+
* frame's server function again with the arguments the page sent.
|
|
337
|
+
*/
|
|
338
|
+
async function flightResponse(value, mounted, invalidated, ask) {
|
|
339
|
+
const seen = /* @__PURE__ */ new Set();
|
|
340
|
+
let regions = "";
|
|
341
|
+
for (const frame of mounted) {
|
|
342
|
+
if (!invalidated.has(frame.id)) continue;
|
|
343
|
+
const answered = await ask(frame);
|
|
344
|
+
if (!isFrame(answered)) continue;
|
|
345
|
+
const { address } = answered[FRAME];
|
|
346
|
+
if (seen.has(address)) continue;
|
|
347
|
+
seen.add(address);
|
|
348
|
+
regions += await frameMarkup(answered);
|
|
349
|
+
}
|
|
350
|
+
const script = `<script type="${FLIGHT_TYPE}">${JSON.stringify(encodeWire(value)).replaceAll("<", "\\u003c")}<\/script>`;
|
|
351
|
+
const answer = new Response(script + regions);
|
|
352
|
+
answer.headers.set("content-type", "text/html; charset=utf-8");
|
|
353
|
+
answer.headers.set("cache-control", "no-store");
|
|
354
|
+
answer.headers.set("x-barq-rpc", RPC_FLIGHT);
|
|
355
|
+
return answer;
|
|
356
|
+
}
|
|
357
|
+
// src/live-server.ts
|
|
358
|
+
/**
|
|
359
|
+
* The server half of `live`: a call at the live address answered as server-sent
|
|
360
|
+
* events, for as long as the answer stands.
|
|
361
|
+
*
|
|
362
|
+
* A frame is rendered again each time an async source it reads moves, and each
|
|
363
|
+
* new rendering that differs from the last goes out as one event carrying the
|
|
364
|
+
* frame's markup. Any other answer goes out a value per event. An answer whose
|
|
365
|
+
* every source has ended says so with a `complete` event; a body that ends
|
|
366
|
+
* without one is a connection that died, which the page's loop reconnects.
|
|
367
|
+
*
|
|
368
|
+
* Each event's id is the digest of what it carried. A reconnect names the last
|
|
369
|
+
* one it applied in `Last-Event-ID`, and an answer that still matches it is not
|
|
370
|
+
* sent again.
|
|
371
|
+
*/
|
|
372
|
+
/** The `x-barq-rpc` value a live answer carries. */
|
|
373
|
+
const RPC_LIVE = "live";
|
|
374
|
+
/** How often an idle connection says it is still there, against proxies that time one out. */
|
|
375
|
+
const HEARTBEAT_MS = 2e4;
|
|
376
|
+
function digest(text) {
|
|
377
|
+
let hash = 0x811c9dc5;
|
|
378
|
+
for (let at = 0; at < text.length; at++) {
|
|
379
|
+
hash ^= text.charCodeAt(at);
|
|
380
|
+
hash = Math.imul(hash, 16777619);
|
|
381
|
+
}
|
|
382
|
+
return (hash >>> 0).toString(36);
|
|
383
|
+
}
|
|
384
|
+
function isIterable$1(value) {
|
|
385
|
+
return typeof value === "object" && value !== null && typeof value[Symbol.asyncIterator] === "function";
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* One event: its kind, an id, and data that is JSON and so carries no line
|
|
389
|
+
* break of its own. A frame's markup is `frame`, a value the default kind.
|
|
390
|
+
*/
|
|
391
|
+
function event(kind, id, data) {
|
|
392
|
+
return `${kind === "frame" ? "event: frame\n" : ""}id: ${id}\ndata: ${data}\n\n`;
|
|
393
|
+
}
|
|
394
|
+
/**
|
|
395
|
+
* Drive a live answer: each rendering of a frame, or each value of an
|
|
396
|
+
* iterable, through `emit` until it ends, then `finish(complete)`. Returns
|
|
397
|
+
* what stops it early.
|
|
398
|
+
*/
|
|
399
|
+
function produce(result, emit, finish) {
|
|
400
|
+
let ended = false;
|
|
401
|
+
const stops = [];
|
|
402
|
+
const end = (complete) => {
|
|
403
|
+
if (ended) return;
|
|
404
|
+
ended = true;
|
|
405
|
+
for (const stop of stops) stop();
|
|
406
|
+
finish(complete);
|
|
407
|
+
};
|
|
408
|
+
const frames = async (frame) => {
|
|
409
|
+
const shared = new SharedSources();
|
|
410
|
+
stops.push(() => shared.close());
|
|
411
|
+
let rendering = false;
|
|
412
|
+
let again = false;
|
|
413
|
+
const render = async () => {
|
|
414
|
+
if (rendering) {
|
|
415
|
+
again = true;
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
rendering = true;
|
|
419
|
+
try {
|
|
420
|
+
for (;;) {
|
|
421
|
+
again = false;
|
|
422
|
+
const session = Symbol("live-frame");
|
|
423
|
+
shared.begin();
|
|
424
|
+
shareSources(session, shared);
|
|
425
|
+
let markup;
|
|
426
|
+
try {
|
|
427
|
+
markup = await frameMarkup(frame, { session });
|
|
428
|
+
} finally {
|
|
429
|
+
unshareSources(session);
|
|
430
|
+
}
|
|
431
|
+
shared.sweep();
|
|
432
|
+
if (ended) return;
|
|
433
|
+
emit(JSON.stringify(markup), "frame");
|
|
434
|
+
if (!again) break;
|
|
435
|
+
}
|
|
436
|
+
} catch (error) {
|
|
437
|
+
console.error("[barq] A live frame failed to render, so its connection ends and the page reconnects. The error:", error);
|
|
438
|
+
end(false);
|
|
439
|
+
return;
|
|
440
|
+
} finally {
|
|
441
|
+
rendering = false;
|
|
442
|
+
}
|
|
443
|
+
if (shared.settled) end(true);
|
|
444
|
+
};
|
|
445
|
+
shared.onChange(() => void render());
|
|
446
|
+
await render();
|
|
447
|
+
};
|
|
448
|
+
const values = async (source) => {
|
|
449
|
+
const iterator = source[Symbol.asyncIterator]();
|
|
450
|
+
stops.push(() => void iterator.return?.());
|
|
451
|
+
try {
|
|
452
|
+
for (;;) {
|
|
453
|
+
const step = await iterator.next();
|
|
454
|
+
if (ended) return;
|
|
455
|
+
if (step.done === true) break;
|
|
456
|
+
emit(JSON.stringify(encodeWire(step.value)), "message");
|
|
457
|
+
}
|
|
458
|
+
end(true);
|
|
459
|
+
} catch (error) {
|
|
460
|
+
console.error("[barq] A live answer failed while streaming, so its connection ends and the page reconnects. The error:", error);
|
|
461
|
+
end(false);
|
|
462
|
+
}
|
|
463
|
+
};
|
|
464
|
+
if (isFrame(result)) frames(result);
|
|
465
|
+
else if (isIterable$1(result)) values(result);
|
|
466
|
+
else {
|
|
467
|
+
emit(JSON.stringify(encodeWire(result)), "message");
|
|
468
|
+
end(true);
|
|
469
|
+
}
|
|
470
|
+
return () => {
|
|
471
|
+
if (ended) return;
|
|
472
|
+
ended = true;
|
|
473
|
+
for (const stop of stops) stop();
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
/**
|
|
477
|
+
* One server-sent event stream. `attach` is handed the connection when the
|
|
478
|
+
* stream starts and answers with what to run when it ends, either way.
|
|
479
|
+
*/
|
|
480
|
+
function connection(request, attach) {
|
|
481
|
+
const encoder = new TextEncoder();
|
|
482
|
+
let controller = null;
|
|
483
|
+
let ended = false;
|
|
484
|
+
const stops = [];
|
|
485
|
+
const end = (complete) => {
|
|
486
|
+
if (ended) return;
|
|
487
|
+
ended = true;
|
|
488
|
+
for (const stop of stops) stop();
|
|
489
|
+
if (controller === null) return;
|
|
490
|
+
try {
|
|
491
|
+
if (complete) controller.enqueue(encoder.encode("event: complete\ndata: \n\n"));
|
|
492
|
+
controller.close();
|
|
493
|
+
} catch {}
|
|
494
|
+
};
|
|
495
|
+
const send = (text) => {
|
|
496
|
+
if (ended || controller === null) return;
|
|
497
|
+
try {
|
|
498
|
+
controller.enqueue(encoder.encode(text));
|
|
499
|
+
} catch {
|
|
500
|
+
end(false);
|
|
501
|
+
}
|
|
502
|
+
};
|
|
503
|
+
let sentId = request.headers.get("last-event-id");
|
|
504
|
+
const emit = (data, kind) => {
|
|
505
|
+
const id = digest(data);
|
|
506
|
+
if (id === sentId) return;
|
|
507
|
+
sentId = id;
|
|
508
|
+
send(event(kind, id, data));
|
|
509
|
+
};
|
|
510
|
+
const body = new ReadableStream({
|
|
511
|
+
start(given) {
|
|
512
|
+
controller = given;
|
|
513
|
+
const heartbeat = setInterval(() => send(": still here\n\n"), HEARTBEAT_MS);
|
|
514
|
+
heartbeat.unref?.();
|
|
515
|
+
stops.push(() => clearInterval(heartbeat));
|
|
516
|
+
const abort = () => end(false);
|
|
517
|
+
request.signal.addEventListener("abort", abort, { once: true });
|
|
518
|
+
stops.push(() => request.signal.removeEventListener("abort", abort));
|
|
519
|
+
stops.push(attach({
|
|
520
|
+
emit,
|
|
521
|
+
end
|
|
522
|
+
}));
|
|
523
|
+
},
|
|
524
|
+
cancel() {
|
|
525
|
+
end(false);
|
|
526
|
+
}
|
|
527
|
+
});
|
|
528
|
+
const answer = new Response(body);
|
|
529
|
+
answer.headers.set("content-type", "text/event-stream; charset=utf-8");
|
|
530
|
+
answer.headers.set("cache-control", "no-store");
|
|
531
|
+
answer.headers.set("x-accel-buffering", "no");
|
|
532
|
+
answer.headers.set("x-barq-rpc", RPC_LIVE);
|
|
533
|
+
return answer;
|
|
534
|
+
}
|
|
535
|
+
/** The answer to a call at the live address. */
|
|
536
|
+
function liveResponse(result, request) {
|
|
537
|
+
return connection(request, (to) => produce(result, to.emit, to.end));
|
|
538
|
+
}
|
|
539
|
+
/** The running shared answers, by function and arguments. */
|
|
540
|
+
const BROADCASTS = /* @__PURE__ */ new Map();
|
|
541
|
+
/**
|
|
542
|
+
* A joiner's own answer, closed without reading it. Only an answer that is
|
|
543
|
+
* already an iterator, a generator object, holds anything: an iterable nobody
|
|
544
|
+
* has asked for an iterator has started nothing, and asking would start it.
|
|
545
|
+
*/
|
|
546
|
+
function closeUnread(result) {
|
|
547
|
+
const iterator = result;
|
|
548
|
+
if (typeof iterator?.return !== "function") return;
|
|
549
|
+
try {
|
|
550
|
+
const closing = iterator.return();
|
|
551
|
+
if (closing instanceof Promise) closing.catch(() => {});
|
|
552
|
+
} catch {}
|
|
553
|
+
}
|
|
554
|
+
/**
|
|
555
|
+
* The answer to a live call to a `broadcast` function: one rendering per
|
|
556
|
+
* `key`, every connection asking the same thing a reader of it. The first call
|
|
557
|
+
* starts it, outside its own request, and each later one joins it with the
|
|
558
|
+
* latest event and closes its own answer unread. It stops when its last
|
|
559
|
+
* connection goes.
|
|
560
|
+
*/
|
|
561
|
+
function broadcastResponse(key, result, request) {
|
|
562
|
+
let shared = BROADCASTS.get(key);
|
|
563
|
+
if (shared !== void 0 && !shared.ended) closeUnread(result);
|
|
564
|
+
else {
|
|
565
|
+
const started = {
|
|
566
|
+
connections: /* @__PURE__ */ new Set(),
|
|
567
|
+
latest: null,
|
|
568
|
+
ended: false,
|
|
569
|
+
stop: () => {}
|
|
570
|
+
};
|
|
571
|
+
BROADCASTS.set(key, started);
|
|
572
|
+
started.stop = withoutRequestEvent(() => produce(result, (data, kind) => {
|
|
573
|
+
started.latest = {
|
|
574
|
+
data,
|
|
575
|
+
kind
|
|
576
|
+
};
|
|
577
|
+
for (const each of started.connections) each.emit(data, kind);
|
|
578
|
+
}, (complete) => {
|
|
579
|
+
started.ended = true;
|
|
580
|
+
if (BROADCASTS.get(key) === started) BROADCASTS.delete(key);
|
|
581
|
+
for (const each of started.connections) each.end(complete);
|
|
582
|
+
}));
|
|
583
|
+
shared = started;
|
|
584
|
+
}
|
|
585
|
+
const joined = shared;
|
|
586
|
+
return connection(request, (to) => {
|
|
587
|
+
joined.connections.add(to);
|
|
588
|
+
if (joined.latest !== null) to.emit(joined.latest.data, joined.latest.kind);
|
|
589
|
+
if (joined.ended) to.end(true);
|
|
590
|
+
return () => {
|
|
591
|
+
joined.connections.delete(to);
|
|
592
|
+
if (joined.connections.size > 0 || joined.ended) return;
|
|
593
|
+
joined.ended = true;
|
|
594
|
+
if (BROADCASTS.get(key) === joined) BROADCASTS.delete(key);
|
|
595
|
+
joined.stop();
|
|
596
|
+
};
|
|
597
|
+
});
|
|
598
|
+
}
|
|
599
|
+
// src/server.ts
|
|
600
|
+
/**
|
|
601
|
+
* The request handler: one URL shape, one lookup, and the checks that run
|
|
602
|
+
* before a handler body does.
|
|
603
|
+
*
|
|
604
|
+
* Every default here is the strict one, because the survey found the same four
|
|
605
|
+
* failures composing across shipping frameworks — an unvalidated, CSRF-unchecked,
|
|
606
|
+
* publicly-mounted endpoint reached by an id enumerable from the client bundle.
|
|
607
|
+
* Each is cheap to close and expensive to retrofit.
|
|
608
|
+
*/
|
|
609
|
+
installFrames(serverFrame);
|
|
610
|
+
/**
|
|
611
|
+
* ONE registry per process, whichever copy of this module asks.
|
|
612
|
+
*
|
|
613
|
+
* A build compiles this module INTO its server bundle, and a host that serves
|
|
614
|
+
* that bundle through its own `serveBarq` has imported a second copy. Kept in
|
|
615
|
+
* a module variable, each copy had a registry of its own: the bundle mounted
|
|
616
|
+
* every function into one and the host answered 404 out of the other.
|
|
617
|
+
*/
|
|
618
|
+
const MOUNTED = globalThis[Symbol.for("barq.start.server-fns")] ??= {
|
|
619
|
+
registry: /* @__PURE__ */ new Map(),
|
|
620
|
+
manifest: null
|
|
621
|
+
};
|
|
622
|
+
const REGISTRY = MOUNTED.registry;
|
|
623
|
+
/**
|
|
624
|
+
* Say how the build's manifest is mounted, so a call can ask for it.
|
|
625
|
+
*
|
|
626
|
+
* The server entry imports the manifest when it first renders a page, which is
|
|
627
|
+
* late for a function called before any page has been asked for: a server that
|
|
628
|
+
* has just started and a browser tab that was already open. The id it names
|
|
629
|
+
* was in no registry yet, and the answer was a 404 for a function that exists.
|
|
630
|
+
*/
|
|
631
|
+
function mountOnDemand(manifest) {
|
|
632
|
+
MOUNTED.manifest = manifest;
|
|
633
|
+
}
|
|
634
|
+
/**
|
|
635
|
+
* Mount a server function. The compiler emits one call per EXPORTED server
|
|
636
|
+
* function in a module compiled for the server.
|
|
637
|
+
*
|
|
638
|
+
* Export-ness is what decides reachability, which is SvelteKit's rule and the
|
|
639
|
+
* only genuine notion of an internal server function in the survey: a
|
|
640
|
+
* non-exported one is never registered, so it has no id and no endpoint, and is
|
|
641
|
+
* still callable from its siblings.
|
|
642
|
+
*/
|
|
643
|
+
function mount(id, fn) {
|
|
644
|
+
if (!isServerFn(fn)) throw new TypeError(`[barq] \`mount(${JSON.stringify(id)}, fn)\` was given something that is not a server function, so there is nothing to answer calls with. Pass a function built with \`createServerFn().handler(...)\`.`);
|
|
645
|
+
if (id === "") throw new TypeError("[barq] `mount(id, fn)` was given an empty `id`, so no request could reach the function. Pass a non-empty string that is unique in the application.");
|
|
646
|
+
fn.meta.id = id;
|
|
647
|
+
REGISTRY.set(id, fn);
|
|
648
|
+
}
|
|
649
|
+
/** The mounted surface, for the build to record and a reviewer to read. */
|
|
650
|
+
function mounted() {
|
|
651
|
+
return [...REGISTRY.keys()].toSorted();
|
|
652
|
+
}
|
|
653
|
+
/**
|
|
654
|
+
* The function mounted at an id, or `undefined`.
|
|
655
|
+
*
|
|
656
|
+
* Exported for the BUILD's chain check, which has to ask each reachable id what
|
|
657
|
+
* middleware it actually carries. It reads the registry inside whichever bundle
|
|
658
|
+
* it is called from, which is why the check runs through the server entry
|
|
659
|
+
* rather than from the Vite plugin: `resolve.noExternal` compiles `@barqjs/*`
|
|
660
|
+
* INTO the ssr bundle, so a plugin importing this module would be asking a
|
|
661
|
+
* second, empty registry.
|
|
662
|
+
*/
|
|
663
|
+
function mountedFn(id) {
|
|
664
|
+
return REGISTRY.get(id);
|
|
665
|
+
}
|
|
666
|
+
/** Test seam. Not for application use. */
|
|
667
|
+
function unmountAll() {
|
|
668
|
+
REGISTRY.clear();
|
|
669
|
+
MOUNTED.manifest = null;
|
|
670
|
+
}
|
|
671
|
+
/**
|
|
672
|
+
* Is this request allowed to invoke a server function?
|
|
673
|
+
*
|
|
674
|
+
* `Origin` first, then `Sec-Fetch-Site` when `Origin` is absent. That fallback
|
|
675
|
+
* is Waku's post-CVE shape and it is the strictest default found: `Origin` is
|
|
676
|
+
* legitimately absent on some same-origin requests and on non-browser clients,
|
|
677
|
+
* while `Sec-Fetch-Site` is sent by every modern browser and cannot be forged
|
|
678
|
+
* from script. Next.js warns and PROCEEDS on a missing `Origin`; this refuses.
|
|
679
|
+
*/
|
|
680
|
+
function originAllowed(request, options) {
|
|
681
|
+
const origin = request.headers.get("origin");
|
|
682
|
+
if (origin !== null) {
|
|
683
|
+
if (origin === "null") return false;
|
|
684
|
+
if (origin === new URL(request.url).origin) return true;
|
|
685
|
+
return options?.allowedOrigins?.includes(origin) ?? false;
|
|
686
|
+
}
|
|
687
|
+
const site = request.headers.get("sec-fetch-site");
|
|
688
|
+
if (site === null) return false;
|
|
689
|
+
return site === "same-origin" || site === "none";
|
|
690
|
+
}
|
|
691
|
+
/** Methods that cannot change state, so CSRF does not apply to them. */
|
|
692
|
+
const SAFE_METHODS = /* @__PURE__ */ new Set([
|
|
693
|
+
"GET",
|
|
694
|
+
"HEAD",
|
|
695
|
+
"OPTIONS"
|
|
696
|
+
]);
|
|
697
|
+
/**
|
|
698
|
+
* Is this a request a BROWSER made from another origin?
|
|
699
|
+
*
|
|
700
|
+
* A DIFFERENT QUESTION FROM `originAllowed`, and the difference is the whole
|
|
701
|
+
* design. `originAllowed` guards `/_barq/fn/*`, which only ever exists to be
|
|
702
|
+
* called by this application's own pages — so a request with no origin signal at
|
|
703
|
+
* all is refused there, because there is no legitimate caller that omits one.
|
|
704
|
+
*
|
|
705
|
+
* A route handler is the opposite: an API route exists so that something OTHER
|
|
706
|
+
* than a browser can call it. A Stripe webhook, a GitHub delivery, a cron
|
|
707
|
+
* hitting it with curl — none of them send `Origin` or `Sec-Fetch-Site`, and
|
|
708
|
+
* refusing on their absence would refuse the main reason API routes exist.
|
|
709
|
+
*
|
|
710
|
+
* So this answers the narrower question, and the narrower question is the one
|
|
711
|
+
* CSRF actually asks. A cross-site forgery is by definition made BY A BROWSER
|
|
712
|
+
* with the victim's cookies attached, and a browser making a cross-origin
|
|
713
|
+
* state-changing request always says so — `Origin` on any cross-origin POST
|
|
714
|
+
* since forever, `Sec-Fetch-Site` on everything in every current browser. So:
|
|
715
|
+
* refuse when a signal is present and says cross-origin; allow when there is no
|
|
716
|
+
* signal, because then it is not a browser and cannot be a forgery.
|
|
717
|
+
*
|
|
718
|
+
* `null` origin — a sandboxed iframe, a `data:` URL — is refused rather than
|
|
719
|
+
* read as absent, which is a bypass that has shipped.
|
|
720
|
+
*/
|
|
721
|
+
function crossOriginRefused(request, allowedOrigins) {
|
|
722
|
+
if (SAFE_METHODS.has(request.method.toUpperCase())) return false;
|
|
723
|
+
const origin = request.headers.get("origin");
|
|
724
|
+
if (origin !== null) {
|
|
725
|
+
if (origin === "null") return true;
|
|
726
|
+
if (origin === new URL(request.url).origin) return false;
|
|
727
|
+
return !(allowedOrigins?.includes(origin) ?? false);
|
|
728
|
+
}
|
|
729
|
+
const site = request.headers.get("sec-fetch-site");
|
|
730
|
+
if (site === null) return false;
|
|
731
|
+
return site !== "same-origin" && site !== "none";
|
|
732
|
+
}
|
|
733
|
+
/** The labelled 404: the client reports it as skew rather than as a failed call. */
|
|
734
|
+
function unknownFunction() {
|
|
735
|
+
return new Response("not found", {
|
|
736
|
+
status: 404,
|
|
737
|
+
headers: { [UNKNOWN_HEADER]: "true" }
|
|
738
|
+
});
|
|
739
|
+
}
|
|
740
|
+
/**
|
|
741
|
+
* Handle one server-function request, or return null if the URL is not one.
|
|
742
|
+
*
|
|
743
|
+
* Returning null rather than a 404 is what lets this compose as middleware in
|
|
744
|
+
* front of a page handler.
|
|
745
|
+
*/
|
|
746
|
+
async function handleServerFn(request, options) {
|
|
747
|
+
const url = new URL(request.url);
|
|
748
|
+
if (!url.pathname.startsWith("/_barq/fn/")) return null;
|
|
749
|
+
const method = request.method;
|
|
750
|
+
if (method !== "POST" && method !== "GET") return new Response("method not allowed", {
|
|
751
|
+
status: 405,
|
|
752
|
+
headers: { allow: "GET, POST" }
|
|
753
|
+
});
|
|
754
|
+
if (!originAllowed(request, options)) return new Response("forbidden", { status: 403 });
|
|
755
|
+
const path = url.pathname.slice(RPC_PREFIX.length);
|
|
756
|
+
const isLive = path.endsWith(LIVE_SUFFIX);
|
|
757
|
+
const isData = isLive || path.endsWith(".data");
|
|
758
|
+
let id;
|
|
759
|
+
try {
|
|
760
|
+
id = decodeURIComponent(isLive ? path.slice(0, -LIVE_SUFFIX.length) : isData ? path.slice(0, -DATA_SUFFIX.length) : path);
|
|
761
|
+
} catch {
|
|
762
|
+
return new Response("bad request", { status: 400 });
|
|
763
|
+
}
|
|
764
|
+
let fn = REGISTRY.get(id);
|
|
765
|
+
if (fn === void 0 && MOUNTED.manifest !== null) {
|
|
766
|
+
await MOUNTED.manifest();
|
|
767
|
+
fn = REGISTRY.get(id);
|
|
768
|
+
}
|
|
769
|
+
if (fn === void 0) return unknownFunction();
|
|
770
|
+
if (options?.reachable?.(id) === false) return unknownFunction();
|
|
771
|
+
const build = options?.buildId ?? BUNDLED_BUILD;
|
|
772
|
+
const callerBuild = request.headers.get(BUILD_HEADER);
|
|
773
|
+
if (build !== void 0 && callerBuild !== null && callerBuild !== build) return new Response(`call from build ${JSON.stringify(callerBuild)} refused`, {
|
|
774
|
+
status: 409,
|
|
775
|
+
headers: {
|
|
776
|
+
[UNKNOWN_HEADER]: "true",
|
|
777
|
+
[BUILD_HEADER]: build,
|
|
778
|
+
"cache-control": "no-store"
|
|
779
|
+
}
|
|
780
|
+
});
|
|
781
|
+
const expected = fn.meta.method ?? "POST";
|
|
782
|
+
if (method !== expected) return new Response("method not allowed", {
|
|
783
|
+
status: 405,
|
|
784
|
+
headers: { allow: expected }
|
|
785
|
+
});
|
|
786
|
+
if (method === "GET") {
|
|
787
|
+
if (!isData) return new Response("not found", { status: 404 });
|
|
788
|
+
if (request.headers.get("x-barq-fn") === null) return new Response("forbidden", { status: 403 });
|
|
789
|
+
}
|
|
790
|
+
const bodyLimit = options?.maxBodySize ?? DEFAULT_BODY_LIMIT;
|
|
791
|
+
const target = fn;
|
|
792
|
+
const draft = createResponseDraft();
|
|
793
|
+
/**
|
|
794
|
+
* The call itself: read the body, run the function, build the answer. The
|
|
795
|
+
* innermost step of the request middleware chain, so a global middleware
|
|
796
|
+
* that refuses does so before a byte of the payload has been parsed.
|
|
797
|
+
*/
|
|
798
|
+
const respond = async () => {
|
|
799
|
+
let input;
|
|
800
|
+
let clientContext;
|
|
801
|
+
let encoded;
|
|
802
|
+
if (isData && (method === "GET" || !isFormBody(request))) try {
|
|
803
|
+
if (method === "POST") encoded = await capped(request, bodyLimit).text();
|
|
804
|
+
else encoded = url.searchParams.get("payload") ?? "";
|
|
805
|
+
const body = method === "GET" ? queryPayload(url, bodyLimit) : JSON.parse(encoded);
|
|
806
|
+
input = body?.input === void 0 ? void 0 : decodeWire(body.input);
|
|
807
|
+
clientContext = body?.context === void 0 ? void 0 : { ...decodeWire(body.context) };
|
|
808
|
+
} catch (error) {
|
|
809
|
+
return unreadable(error);
|
|
810
|
+
}
|
|
811
|
+
else try {
|
|
812
|
+
input = await capped(request, options?.maxFormSize ?? bodyLimit).formData();
|
|
813
|
+
} catch (error) {
|
|
814
|
+
return unreadable(error);
|
|
815
|
+
}
|
|
816
|
+
try {
|
|
817
|
+
const result = await (input instanceof FormData ? target(input) : target({ data: input }, clientContext));
|
|
818
|
+
const sendContext = takeSendContext();
|
|
819
|
+
if (isLive) {
|
|
820
|
+
if (result instanceof Response) return applyResponseDraft(result, draft);
|
|
821
|
+
if (target.meta.broadcast === true && encoded !== void 0) return applyResponseDraft(broadcastResponse(`${id}\0${method}\0${encoded}`, result, request), draft);
|
|
822
|
+
return applyResponseDraft(liveResponse(result, request), draft);
|
|
823
|
+
}
|
|
824
|
+
if (result instanceof Response) {
|
|
825
|
+
if (isData) draft.headers.set(RPC_CONTROL, RPC_RESPONSE);
|
|
826
|
+
return applyResponseDraft(result, draft);
|
|
827
|
+
}
|
|
828
|
+
if (isFrame(result)) {
|
|
829
|
+
if (isData) return applyResponseDraft(await frameResponse(result), draft);
|
|
830
|
+
return applyResponseDraft(seeOther(request), draft);
|
|
831
|
+
}
|
|
832
|
+
if (isIterable(result)) {
|
|
833
|
+
if (isData) return applyResponseDraft(streamed(result, sendContext, id, revealerOf(options)), draft);
|
|
834
|
+
result[Symbol.asyncIterator]().return?.();
|
|
835
|
+
return applyResponseDraft(seeOther(request), draft);
|
|
836
|
+
}
|
|
837
|
+
if (isData) {
|
|
838
|
+
const answer = draftedStatus(draft, 200);
|
|
839
|
+
const mountedHere = mountedFrames(request.headers.get(FRAMES_HEADER));
|
|
840
|
+
const changed = invalidatedFrames();
|
|
841
|
+
if (mountedHere.length > 0 && changed.size > 0) {
|
|
842
|
+
const flight = await flightResponse(Object.keys(sendContext).length === 0 ? result : {
|
|
843
|
+
result,
|
|
844
|
+
context: sendContext
|
|
845
|
+
}, mountedHere, changed, async (frame) => {
|
|
846
|
+
const asked = REGISTRY.get(frame.id);
|
|
847
|
+
if (asked === void 0 || options?.reachable?.(frame.id) === false) return void 0;
|
|
848
|
+
try {
|
|
849
|
+
return await asked({ data: frame.args === void 0 ? void 0 : decodeWire(frame.args) });
|
|
850
|
+
} catch (error) {
|
|
851
|
+
console.error(`[barq] The frame of ${JSON.stringify(frame.id)} could not be rendered again for the mutation ${JSON.stringify(id)}, so its answer leaves it out. The error:`, error);
|
|
852
|
+
return;
|
|
853
|
+
}
|
|
854
|
+
});
|
|
855
|
+
if (Object.keys(sendContext).length > 0) flight.headers.set(RPC_CONTEXT, "1");
|
|
856
|
+
return applyResponseDraft(new Response(flight.body, {
|
|
857
|
+
...answer,
|
|
858
|
+
headers: flight.headers
|
|
859
|
+
}), draft);
|
|
860
|
+
}
|
|
861
|
+
if (Object.keys(sendContext).length === 0) return applyResponseDraft(Response.json(encodeWire(result), answer), draft);
|
|
862
|
+
return applyResponseDraft(Response.json(encodeWire({
|
|
863
|
+
result,
|
|
864
|
+
context: sendContext
|
|
865
|
+
}), {
|
|
866
|
+
...answer,
|
|
867
|
+
headers: { [RPC_CONTEXT]: "1" }
|
|
868
|
+
}), draft);
|
|
869
|
+
}
|
|
870
|
+
return applyResponseDraft(seeOther(request), draft);
|
|
871
|
+
} catch (error) {
|
|
872
|
+
if (error instanceof Response) return thrownAnswer(error, isData, draft);
|
|
873
|
+
const control = controlOf(error);
|
|
874
|
+
if (control !== null) return applyResponseDraft(controlResponse(control, isData, error.headers), draft);
|
|
875
|
+
if (isInputError(error)) return applyResponseDraft(isData ? Response.json(inputAnswer(error), { status: 400 }) : new Response("invalid input", { status: 400 }), draft);
|
|
876
|
+
return applyResponseDraft(failed(id, error, isData, options, "threw"), draft);
|
|
877
|
+
}
|
|
878
|
+
};
|
|
879
|
+
const context = {};
|
|
880
|
+
const timing = isDev ? serverTiming() : void 0;
|
|
881
|
+
const event = createRequestEvent(request, { response: draft });
|
|
882
|
+
try {
|
|
883
|
+
const response = await provideRequestEvent(event, () => {
|
|
884
|
+
setRequestMiddlewareContext(context);
|
|
885
|
+
return runRequestMiddleware(startOptions().requestMiddleware ?? [], {
|
|
886
|
+
request,
|
|
887
|
+
pathname: url.pathname,
|
|
888
|
+
handlerType: "serverFn",
|
|
889
|
+
context
|
|
890
|
+
}, respond);
|
|
891
|
+
});
|
|
892
|
+
if (timing !== void 0) {
|
|
893
|
+
timing.phase("barq-fn", id);
|
|
894
|
+
draft.headers.append("server-timing", timing.header());
|
|
895
|
+
}
|
|
896
|
+
return commitEventResponse(response, event);
|
|
897
|
+
} catch (error) {
|
|
898
|
+
if (error instanceof Response) return commitEventResponse(thrownAnswer(error, isData, draft), event);
|
|
899
|
+
return commitEventResponse(failed(id, error, isData, options, "middleware"), event);
|
|
900
|
+
} finally {
|
|
901
|
+
commitResponseStub(draft, { event });
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
/**
|
|
905
|
+
* The 400 a refused input answers with: the refusal and each issue with the
|
|
906
|
+
* path to the field it is about.
|
|
907
|
+
*/
|
|
908
|
+
function inputAnswer(error) {
|
|
909
|
+
const issues = error.issues ?? [];
|
|
910
|
+
return {
|
|
911
|
+
error: "invalid input",
|
|
912
|
+
message: error.message,
|
|
913
|
+
issues: issues.map((issue) => {
|
|
914
|
+
const { message, path } = issue ?? {};
|
|
915
|
+
const keys = Array.isArray(path) ? path.map((segment) => {
|
|
916
|
+
const key = typeof segment === "object" && segment !== null && "key" in segment ? segment.key : segment;
|
|
917
|
+
return typeof key === "number" ? key : String(key);
|
|
918
|
+
}) : [];
|
|
919
|
+
return keys.length === 0 ? { message: String(message) } : {
|
|
920
|
+
message: String(message),
|
|
921
|
+
path: keys
|
|
922
|
+
};
|
|
923
|
+
})
|
|
924
|
+
};
|
|
925
|
+
}
|
|
926
|
+
/**
|
|
927
|
+
* What a failed call may tell its caller: everything the development server
|
|
928
|
+
* asks for, and in production only an error the application branded with
|
|
929
|
+
* `markSafeError`, by its name and message.
|
|
930
|
+
*/
|
|
931
|
+
function revealerOf(options) {
|
|
932
|
+
const reveal = options?.revealError;
|
|
933
|
+
return (error) => {
|
|
934
|
+
if (reveal !== void 0) return reveal(error);
|
|
935
|
+
if (!(error instanceof Error) || !isSafeError(error)) return void 0;
|
|
936
|
+
return {
|
|
937
|
+
name: error.name,
|
|
938
|
+
message: error.message
|
|
939
|
+
};
|
|
940
|
+
};
|
|
941
|
+
}
|
|
942
|
+
/**
|
|
943
|
+
* A call that failed on the server: logged there, reported on the diagnostics
|
|
944
|
+
* channel, and answered 500. The caller learns what was thrown only when the
|
|
945
|
+
* development server asked for it.
|
|
946
|
+
*/
|
|
947
|
+
function failed(id, error, isData, options, where) {
|
|
948
|
+
const thrown = revealerOf(options)(error);
|
|
949
|
+
const happened = where === "threw" ? `The server function ${JSON.stringify(id)} threw` : `A request middleware threw before the server function ${JSON.stringify(id)} ran`;
|
|
950
|
+
if (diagnosticsEnabled()) reportFailure(id, error, happened);
|
|
951
|
+
console.error(`[barq] ${happened}, so the call answered 500${thrown === void 0 ? " without the error's text" : ""}. The error:`, error);
|
|
952
|
+
if (thrown === void 0) return new Response("internal server error", { status: 500 });
|
|
953
|
+
return isData ? Response.json({
|
|
954
|
+
error: "internal server error",
|
|
955
|
+
thrown
|
|
956
|
+
}, { status: 500 }) : new Response(`internal server error\n\n${thrown.stack ?? `${thrown.name}: ${thrown.message}`}`, { status: 500 });
|
|
957
|
+
}
|
|
958
|
+
function reportFailure(id, error, happened) {
|
|
959
|
+
const text = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
|
|
960
|
+
emitDiagnostic({
|
|
961
|
+
code: "SERVER_FUNCTION_FAILED",
|
|
962
|
+
kind: "ssr",
|
|
963
|
+
severity: "error",
|
|
964
|
+
message: `${happened}: \`${text}\`. The caller received a 500. Fix the throw at the top of the stack, or throw a \`Response\`, \`redirect()\` or \`notFound()\` to answer the caller on purpose.`,
|
|
965
|
+
data: {
|
|
966
|
+
id,
|
|
967
|
+
error
|
|
968
|
+
}
|
|
969
|
+
}, null);
|
|
970
|
+
}
|
|
971
|
+
/**
|
|
972
|
+
* A `Response` the chain or the handler threw, as the answer. The data
|
|
973
|
+
* channel's client rejects the call with it, so the header says it was thrown
|
|
974
|
+
* rather than returned; a browser following a form needs no telling.
|
|
975
|
+
*/
|
|
976
|
+
function thrownAnswer(error, isData, draft) {
|
|
977
|
+
if (isData) draft.headers.set(RPC_CONTROL, RPC_THROWN);
|
|
978
|
+
return applyResponseDraft(error, draft);
|
|
979
|
+
}
|
|
980
|
+
/**
|
|
981
|
+
* Read a thrown value as a control answer, by BRAND rather than by class.
|
|
982
|
+
*
|
|
983
|
+
* The classes are `@barqjs/router`'s and this package cannot import them; see
|
|
984
|
+
* {@link REDIRECT}. A brand check is also what lets the same code recognise a
|
|
985
|
+
* redirect the router threw and one `@barqjs/start/client` rebuilt off the
|
|
986
|
+
* wire, which matters when a server function calls another one.
|
|
987
|
+
*/
|
|
988
|
+
function controlOf(error) {
|
|
989
|
+
if (typeof error !== "object" || error === null) return null;
|
|
990
|
+
const branded = error;
|
|
991
|
+
if (branded[REDIRECT] === true) {
|
|
992
|
+
if (typeof branded.to !== "string") return null;
|
|
993
|
+
const status = typeof branded.status === "number" ? branded.status : 302;
|
|
994
|
+
const options = describedNavigation(branded.options);
|
|
995
|
+
return {
|
|
996
|
+
kind: "redirect",
|
|
997
|
+
to: branded.to,
|
|
998
|
+
status,
|
|
999
|
+
...options === void 0 ? {} : { options: encodeWire(options) }
|
|
1000
|
+
};
|
|
1001
|
+
}
|
|
1002
|
+
if (branded[NOT_FOUND] === true) {
|
|
1003
|
+
const message = error.message;
|
|
1004
|
+
return {
|
|
1005
|
+
kind: "not-found",
|
|
1006
|
+
message: typeof message === "string" ? message : "not found",
|
|
1007
|
+
...branded.data === void 0 ? {} : { data: encodeWire(branded.data) },
|
|
1008
|
+
...typeof branded.routeId === "string" ? { routeId: branded.routeId } : {}
|
|
1009
|
+
};
|
|
1010
|
+
}
|
|
1011
|
+
return null;
|
|
1012
|
+
}
|
|
1013
|
+
/** The parts of a navigation that are values, and so can be sent. */
|
|
1014
|
+
const NAVIGATION = [
|
|
1015
|
+
"to",
|
|
1016
|
+
"from",
|
|
1017
|
+
"params",
|
|
1018
|
+
"search",
|
|
1019
|
+
"hash",
|
|
1020
|
+
"replace",
|
|
1021
|
+
"reloadDocument",
|
|
1022
|
+
"href"
|
|
1023
|
+
];
|
|
1024
|
+
/**
|
|
1025
|
+
* The navigation an options-form redirect described, as far as it can cross.
|
|
1026
|
+
*
|
|
1027
|
+
* A function among them cannot: `search: (current) => ...` is asked about a
|
|
1028
|
+
* location only the browser has. A redirect holding one is sent as its resolved
|
|
1029
|
+
* target alone, which is what every redirect was sent as before this existed.
|
|
1030
|
+
* `statusCode` and `headers` are the answer rather than the navigation, and
|
|
1031
|
+
* travel as the status and on the response.
|
|
1032
|
+
*/
|
|
1033
|
+
function describedNavigation(described) {
|
|
1034
|
+
if (typeof described !== "object" || described === null) return void 0;
|
|
1035
|
+
const given = described;
|
|
1036
|
+
const out = {};
|
|
1037
|
+
for (const name of NAVIGATION) {
|
|
1038
|
+
const value = given[name];
|
|
1039
|
+
if (value === void 0) continue;
|
|
1040
|
+
if (typeof value === "function") return void 0;
|
|
1041
|
+
out[name] = value;
|
|
1042
|
+
}
|
|
1043
|
+
if (typeof given.statusCode === "number") out.statusCode = given.statusCode;
|
|
1044
|
+
return out;
|
|
1045
|
+
}
|
|
1046
|
+
/**
|
|
1047
|
+
* A control answer, on whichever channel asked.
|
|
1048
|
+
*
|
|
1049
|
+
* THE TWO CHANNELS DIVERGE HERE ON PURPOSE, because their clients are different
|
|
1050
|
+
* programs. The form channel's client is a BROWSER following the response
|
|
1051
|
+
* itself, so a redirect has to be a real 3xx with a `Location`. The data
|
|
1052
|
+
* channel's client is `clientRpc`, and a real 3xx there would be FOLLOWED by
|
|
1053
|
+
* `fetch` — the caller would receive the target page's HTML instead of a
|
|
1054
|
+
* navigation. So the data channel answers 200 and describes the redirect in the
|
|
1055
|
+
* body, and the client re-throws it for the router to act on. That is a soft
|
|
1056
|
+
* navigation rather than a document load, which is both correct and faster;
|
|
1057
|
+
* TanStack returns the raw 3xx and the fetch follows it.
|
|
1058
|
+
*
|
|
1059
|
+
* `not-found` is a 404 on both, because 404 is the honest status and no client
|
|
1060
|
+
* follows one.
|
|
1061
|
+
*
|
|
1062
|
+
* `extra` is the thrown value's own `headers`, which are the response's on
|
|
1063
|
+
* either channel: a redirect that signs a visitor out carries the cookie that
|
|
1064
|
+
* does it.
|
|
1065
|
+
*/
|
|
1066
|
+
function controlResponse(control, isData, extra) {
|
|
1067
|
+
const headers = answerHeaders(extra);
|
|
1068
|
+
if (control.kind === "not-found") {
|
|
1069
|
+
if (!isData) return new Response(control.message, {
|
|
1070
|
+
status: 404,
|
|
1071
|
+
headers
|
|
1072
|
+
});
|
|
1073
|
+
headers.set(RPC_CONTROL, control.kind);
|
|
1074
|
+
return Response.json(control, {
|
|
1075
|
+
status: 404,
|
|
1076
|
+
headers
|
|
1077
|
+
});
|
|
1078
|
+
}
|
|
1079
|
+
if (!isNavigable(control.to)) {
|
|
1080
|
+
reportRefusedRedirect(control.to);
|
|
1081
|
+
return new Response("bad redirect", { status: 500 });
|
|
1082
|
+
}
|
|
1083
|
+
if (isData) {
|
|
1084
|
+
headers.set(RPC_CONTROL, control.kind);
|
|
1085
|
+
return Response.json(control, {
|
|
1086
|
+
status: 200,
|
|
1087
|
+
headers
|
|
1088
|
+
});
|
|
1089
|
+
}
|
|
1090
|
+
const status = control.status === 302 ? 303 : control.status;
|
|
1091
|
+
headers.set("location", control.to);
|
|
1092
|
+
return new Response(null, {
|
|
1093
|
+
status,
|
|
1094
|
+
headers
|
|
1095
|
+
});
|
|
1096
|
+
}
|
|
1097
|
+
/** A thrown answer's `headers`, or none when it carried nothing a response can take. */
|
|
1098
|
+
function answerHeaders(extra) {
|
|
1099
|
+
if (extra === void 0 || extra === null) return new Headers();
|
|
1100
|
+
try {
|
|
1101
|
+
return new Headers(extra);
|
|
1102
|
+
} catch {
|
|
1103
|
+
return new Headers();
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
function reportRefusedRedirect(to) {
|
|
1107
|
+
console.error(`[barq] A server function threw \`redirect(${JSON.stringify(to)})\`, which is not a path or an \`http(s)\` URL, so the redirect was refused and the call answered 500. Validate the value passed to \`redirect()\` before using it, especially when it comes from the request.`);
|
|
1108
|
+
}
|
|
1109
|
+
function isIterable(value) {
|
|
1110
|
+
return typeof value === "object" && value !== null && typeof value[Symbol.asyncIterator] === "function";
|
|
1111
|
+
}
|
|
1112
|
+
/**
|
|
1113
|
+
* An answer that arrives over time: one JSON line for each value yielded.
|
|
1114
|
+
*
|
|
1115
|
+
* Produced from `start`, so the function keeps running inside the request it
|
|
1116
|
+
* was called for: a `pull` is made from wherever the body is read, where there
|
|
1117
|
+
* is no request. It waits to be asked all the same, so a reader that falls
|
|
1118
|
+
* behind holds the function at its next `yield` rather than filling memory.
|
|
1119
|
+
*
|
|
1120
|
+
* A failure after the first value cannot become a status, so it is one last
|
|
1121
|
+
* line that says so and nothing else: a handler's message can name a table, a
|
|
1122
|
+
* column or a path.
|
|
1123
|
+
*/
|
|
1124
|
+
function streamed(values, sendContext, id, reveal) {
|
|
1125
|
+
const encoder = new TextEncoder();
|
|
1126
|
+
const line = (payload) => encoder.encode(`${JSON.stringify(payload)}\n`);
|
|
1127
|
+
const source = values[Symbol.asyncIterator]();
|
|
1128
|
+
let wanted = null;
|
|
1129
|
+
let cancelled = false;
|
|
1130
|
+
const produce = async (controller) => {
|
|
1131
|
+
try {
|
|
1132
|
+
if (Object.keys(sendContext).length > 0) controller.enqueue(line({ c: encodeWire(sendContext) }));
|
|
1133
|
+
for (;;) {
|
|
1134
|
+
if ((controller.desiredSize ?? 1) <= 0) await new Promise((resolve) => {
|
|
1135
|
+
wanted = resolve;
|
|
1136
|
+
});
|
|
1137
|
+
if (cancelled) return;
|
|
1138
|
+
const next = await source.next();
|
|
1139
|
+
if (cancelled || next.done === true) break;
|
|
1140
|
+
controller.enqueue(line({ v: encodeWire(next.value) }));
|
|
1141
|
+
}
|
|
1142
|
+
if (!cancelled) controller.close();
|
|
1143
|
+
} catch (error) {
|
|
1144
|
+
if (cancelled) return;
|
|
1145
|
+
const thrown = reveal(error);
|
|
1146
|
+
const happened = `The server function ${JSON.stringify(id)} threw while streaming its result`;
|
|
1147
|
+
if (diagnosticsEnabled()) reportFailure(id, error, happened);
|
|
1148
|
+
console.error(`[barq] ${happened}, so the stream ended early and the caller receives a \`ServerFnError\`. The error:`, error);
|
|
1149
|
+
controller.enqueue(line(thrown === void 0 ? { e: 1 } : {
|
|
1150
|
+
e: 1,
|
|
1151
|
+
t: thrown
|
|
1152
|
+
}));
|
|
1153
|
+
controller.close();
|
|
1154
|
+
}
|
|
1155
|
+
};
|
|
1156
|
+
const body = new ReadableStream({
|
|
1157
|
+
start(controller) {
|
|
1158
|
+
produce(controller);
|
|
1159
|
+
},
|
|
1160
|
+
pull() {
|
|
1161
|
+
const waiting = wanted;
|
|
1162
|
+
wanted = null;
|
|
1163
|
+
waiting?.();
|
|
1164
|
+
},
|
|
1165
|
+
cancel() {
|
|
1166
|
+
cancelled = true;
|
|
1167
|
+
const waiting = wanted;
|
|
1168
|
+
wanted = null;
|
|
1169
|
+
waiting?.();
|
|
1170
|
+
source.return?.();
|
|
1171
|
+
}
|
|
1172
|
+
});
|
|
1173
|
+
return new Response(body, { headers: {
|
|
1174
|
+
"content-type": "application/x-ndjson; charset=utf-8",
|
|
1175
|
+
"cache-control": "no-store",
|
|
1176
|
+
[RPC_CONTROL]: RPC_STREAM
|
|
1177
|
+
} });
|
|
1178
|
+
}
|
|
1179
|
+
const DEFAULT_BODY_LIMIT = 1048576;
|
|
1180
|
+
/**
|
|
1181
|
+
* The request's body behind a cap, as something that can still be parsed.
|
|
1182
|
+
*
|
|
1183
|
+
* The declared length is only the early exit. A chunked request declares none
|
|
1184
|
+
* and a header can understate, so the stream is counted as it is read and
|
|
1185
|
+
* errors the moment it passes the limit, with the rest left unread.
|
|
1186
|
+
*
|
|
1187
|
+
* A `Response` carrying the content type, because that is what parses a
|
|
1188
|
+
* multipart body: the boundary is in the header, and srvx's own
|
|
1189
|
+
* `limitRequestBody` drops it and so cannot read a form.
|
|
1190
|
+
*/
|
|
1191
|
+
function capped(request, limit) {
|
|
1192
|
+
if (Number(request.headers.get("content-length")) > limit) throw createBodyTooLargeError(limit);
|
|
1193
|
+
const type = request.headers.get("content-type");
|
|
1194
|
+
return new Response(request.body === null ? null : limitBodyStream(request.body, limit), type === null ? void 0 : { headers: { "content-type": type } });
|
|
1195
|
+
}
|
|
1196
|
+
/**
|
|
1197
|
+
* A GET call's payload: the body a POST would have sent, in `?payload=`.
|
|
1198
|
+
*
|
|
1199
|
+
* Held to the body limit, since a URL is a body a caller chose the size of,
|
|
1200
|
+
* and refused as a 413 the way an oversized body is.
|
|
1201
|
+
*/
|
|
1202
|
+
function queryPayload(url, limit) {
|
|
1203
|
+
const payload = url.searchParams.get(PAYLOAD_PARAM);
|
|
1204
|
+
if (payload === null) return {};
|
|
1205
|
+
if (payload.length > limit) throw createBodyTooLargeError(limit);
|
|
1206
|
+
return JSON.parse(payload);
|
|
1207
|
+
}
|
|
1208
|
+
/**
|
|
1209
|
+
* What a body that could not be read is answered with.
|
|
1210
|
+
*
|
|
1211
|
+
* By the error's code and not by who threw it: a server in front that enforces
|
|
1212
|
+
* `maxRequestBodySize` fails the read with the same error, and that caller is
|
|
1213
|
+
* owed the same 413.
|
|
1214
|
+
*/
|
|
1215
|
+
function unreadable(error) {
|
|
1216
|
+
return error?.code === "ERR_BODY_TOO_LARGE" ? new Response("payload too large", { status: 413 }) : new Response("bad request", { status: 400 });
|
|
1217
|
+
}
|
|
1218
|
+
/**
|
|
1219
|
+
* Whether the body is a form rather than a value. The enhanced path posts
|
|
1220
|
+
* `FormData` to the data channel so that a handler sees the SAME input type
|
|
1221
|
+
* whether or not JS ran.
|
|
1222
|
+
*/
|
|
1223
|
+
function isFormBody(request) {
|
|
1224
|
+
const type = request.headers.get("content-type") ?? "";
|
|
1225
|
+
return type.includes("multipart/form-data") || type.includes("application/x-www-form-urlencoded");
|
|
1226
|
+
}
|
|
1227
|
+
/**
|
|
1228
|
+
* Back where the form was. 303 and not 302, so the browser re-issues as GET and
|
|
1229
|
+
* a reload does not repost — the POST/redirect/GET the no-JS path exists for.
|
|
1230
|
+
*
|
|
1231
|
+
* `Referer` is used only as a destination and never as a decision. SvelteKit's
|
|
1232
|
+
* docs make the distinction for the same reason: values derived from the
|
|
1233
|
+
* request are fine to navigate to and never fine to authorize with.
|
|
1234
|
+
*/
|
|
1235
|
+
function seeOther(request) {
|
|
1236
|
+
const referer = request.headers.get("referer");
|
|
1237
|
+
const origin = new URL(request.url).origin;
|
|
1238
|
+
let location = "/";
|
|
1239
|
+
if (referer !== null) try {
|
|
1240
|
+
const target = new URL(referer);
|
|
1241
|
+
if (target.origin === origin) {
|
|
1242
|
+
const path = target.pathname + target.search;
|
|
1243
|
+
location = path.startsWith("//") ? origin + path : path;
|
|
1244
|
+
}
|
|
1245
|
+
} catch {}
|
|
1246
|
+
return new Response(null, {
|
|
1247
|
+
status: 303,
|
|
1248
|
+
headers: { location }
|
|
1249
|
+
});
|
|
1250
|
+
}
|
|
1251
|
+
export { mounted as a, unmountAll as c, mountOnDemand as i, handleServerFn as n, mountedFn as o, mount as r, originAllowed as s, crossOriginRefused as t };
|
|
1252
|
+
|
|
1253
|
+
//# sourceMappingURL=server-DG6jb_NA.js.map
|