@solidjs/web 2.0.0-rc.0 → 2.0.0-rc.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/server.dev.js +4472 -0
- package/dist/server.js +1363 -224
- package/dist/{server.cjs → server.observe.js} +1563 -424
- package/dist/{dev.cjs → web.dev.js} +708 -365
- package/dist/web.js +460 -144
- package/dist/{dev.js → web.observe.js} +511 -213
- package/frames/dist/client.dev.js +464 -72
- package/frames/dist/client.js +364 -71
- package/frames/dist/{client.dev.cjs → client.observe.js} +487 -134
- package/frames/dist/server.dev.js +1713 -0
- package/frames/dist/server.js +553 -2495
- package/frames/dist/server.observe.js +1713 -0
- package/frames/package.json +2 -25
- package/package.json +214 -254
- package/performance-tracks/dist/performance-tracks.dev.js +678 -0
- package/performance-tracks/dist/performance-tracks.js +6 -0
- package/performance-tracks/dist/performance-tracks.observe.js +666 -0
- package/performance-tracks/package.json +7 -0
- package/performance-tracks/types/index.d.ts +67 -0
- package/serialization/decode/package.json +2 -15
- package/serialization/dist/decode.js +101 -12
- package/serialization/dist/serialization.js +112 -20
- package/serialization/package.json +2 -15
- package/serialization/types/index.d.ts +76 -157
- package/serialization/types/serializer-decode.d.ts +149 -112
- package/serialization/types/serializer.d.ts +101 -0
- package/server-functions/dist/client.dev.js +1364 -0
- package/server-functions/dist/client.js +745 -85
- package/server-functions/dist/client.observe.js +1343 -0
- package/server-functions/dist/server.dev.js +2203 -175
- package/server-functions/dist/server.js +2111 -176
- package/server-functions/dist/server.observe.js +3043 -0
- package/server-functions/package.json +2 -35
- package/server-functions/rich-args/package.json +2 -15
- package/storage/package.json +2 -15
- package/types/client.d.ts +193 -288
- package/types/constants.d.ts +20 -0
- package/types/cookies.d.ts +32 -84
- package/types/diagnostics.d.ts +56 -0
- package/types/frames/client.d.ts +1 -1
- package/types/frames/frame-client.d.ts +323 -259
- package/types/frames/frame-container-plugin.d.ts +72 -0
- package/types/frames/frame-sink.d.ts +101 -158
- package/types/frames/frame-transport.d.ts +192 -190
- package/types/frames/serializer-decode.d.ts +219 -0
- package/types/frames/serializer.d.ts +76 -157
- package/types/frames/server.d.ts +1 -1
- package/types/head.d.ts +19 -0
- package/types/index.d.ts +62 -76
- package/types/index.server.d.ts +174 -0
- package/types/jsx.d.ts +33 -26
- package/types/observe.d.ts +358 -0
- package/types/reconcile.d.ts +1 -0
- package/types/render.d.ts +9 -0
- package/types/response.d.ts +75 -150
- package/types/serializer-decode.d.ts +149 -112
- package/types/serializer.d.ts +76 -157
- package/types/server-functions/client.d.ts +202 -174
- package/types/server-functions/flash.d.ts +28 -30
- package/types/server-functions/registry.d.ts +102 -0
- package/types/server-functions/rich-args.d.ts +1 -10
- package/types/server-functions/server.d.ts +518 -454
- package/types/server-functions/shared.d.ts +366 -425
- package/types/server-mock.d.ts +110 -13
- package/types/server-observe.d.ts +77 -0
- package/types/server.d.ts +425 -425
- package/types/trace.d.ts +127 -0
- package/LICENSE +0 -21
- package/dist/web.cjs +0 -2007
- package/frames/dist/client.cjs +0 -1916
- package/frames/dist/server.cjs +0 -3667
- package/serialization/dist/decode.cjs +0 -110
- package/serialization/dist/serialization.cjs +0 -232
- package/serialization/types-cjs/index.d.cts +0 -182
- package/serialization/types-cjs/package.json +0 -3
- package/serialization/types-cjs/serializer-decode.d.cts +0 -182
- package/server-functions/dist/client.cjs +0 -646
- package/server-functions/dist/rich-args.cjs +0 -11
- package/server-functions/dist/server.cjs +0 -1077
- package/server-functions/dist/server.dev.cjs +0 -1077
- package/storage/dist/storage.cjs +0 -12
- package/storage/types-cjs/index.d.cts +0 -28
- package/storage/types-cjs/package.json +0 -3
- package/types/core.d.ts +0 -6
- package/types-cjs/client.d.cts +0 -337
- package/types-cjs/cookies.d.cts +0 -93
- package/types-cjs/core.d.cts +0 -6
- package/types-cjs/frames/client.d.cts +0 -36
- package/types-cjs/frames/frame-client.d.cts +0 -338
- package/types-cjs/frames/frame-sink.d.cts +0 -194
- package/types-cjs/frames/frame-transport.d.cts +0 -222
- package/types-cjs/frames/serializer.d.cts +0 -182
- package/types-cjs/frames/server.d.cts +0 -52
- package/types-cjs/index.d.cts +0 -230
- package/types-cjs/jsx-properties.d.cts +0 -93
- package/types-cjs/jsx.d.cts +0 -4150
- package/types-cjs/package.json +0 -3
- package/types-cjs/response.d.cts +0 -174
- package/types-cjs/serializer-decode.d.cts +0 -182
- package/types-cjs/serializer.d.cts +0 -182
- package/types-cjs/server-functions/client.d.cts +0 -201
- package/types-cjs/server-functions/flash.d.cts +0 -38
- package/types-cjs/server-functions/rich-args.d.cts +0 -10
- package/types-cjs/server-functions/server.d.cts +0 -588
- package/types-cjs/server-functions/shared.d.cts +0 -523
- package/types-cjs/server-mock.d.cts +0 -277
- package/types-cjs/server.d.cts +0 -523
|
@@ -1,4 +1,15 @@
|
|
|
1
1
|
import { sharedConfig } from 'solid-js';
|
|
2
|
+
import { reportServerError } from 'solid-js/internal';
|
|
3
|
+
|
|
4
|
+
const COMPOSED_BODY_FRAMING = /*#__PURE__*/new Set(["content-length", "content-encoding", "transfer-encoding"]);
|
|
5
|
+
function isHttpNavigationTarget(target) {
|
|
6
|
+
try {
|
|
7
|
+
const protocol = new URL(target, "http://base.invalid").protocol;
|
|
8
|
+
return protocol === "http:" || protocol === "https:";
|
|
9
|
+
} catch {
|
|
10
|
+
return false;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
2
13
|
|
|
3
14
|
const ENVELOPE = Symbol.for("solid.ResponseEnvelope");
|
|
4
15
|
function isResponseEnvelope(value) {
|
|
@@ -9,6 +20,232 @@ function isSafeError(value) {
|
|
|
9
20
|
return !!(value && (typeof value === "object" || typeof value === "function") && value[SAFE_ERROR]);
|
|
10
21
|
}
|
|
11
22
|
const REVALIDATE_HEADER = "X-Revalidate";
|
|
23
|
+
const RESPONSE_HEADER_VALUE_LIMIT = 4096;
|
|
24
|
+
const NULL_BODY_STATUSES = new Set([204, 205, 304]);
|
|
25
|
+
|
|
26
|
+
const TRACEPARENT = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;
|
|
27
|
+
const ZERO_TRACE = "00000000000000000000000000000000";
|
|
28
|
+
const ZERO_SPAN = "0000000000000000";
|
|
29
|
+
function parseTraceparent(value) {
|
|
30
|
+
if (!value) return undefined;
|
|
31
|
+
const m = TRACEPARENT.exec(value.trim());
|
|
32
|
+
if (!m) return undefined;
|
|
33
|
+
const [, version, traceId, parentId, flags, rest] = m;
|
|
34
|
+
if (version === "ff") return undefined;
|
|
35
|
+
if (version === "00" && rest !== undefined) return undefined;
|
|
36
|
+
if (traceId === ZERO_TRACE || parentId === ZERO_SPAN) return undefined;
|
|
37
|
+
return {
|
|
38
|
+
traceId,
|
|
39
|
+
parentId,
|
|
40
|
+
sampled: (parseInt(flags, 16) & 1) === 1
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
function randomHex(bytes) {
|
|
44
|
+
const buffer = new Uint8Array(bytes);
|
|
45
|
+
crypto.getRandomValues(buffer);
|
|
46
|
+
let out = "";
|
|
47
|
+
for (let i = 0; i < buffer.length; i++) out += (buffer[i] < 16 ? "0" : "") + buffer[i].toString(16);
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
function randomTraceId() {
|
|
51
|
+
let id = randomHex(16);
|
|
52
|
+
while (id === ZERO_TRACE) id = randomHex(16);
|
|
53
|
+
return id;
|
|
54
|
+
}
|
|
55
|
+
function randomSpanId() {
|
|
56
|
+
let id = randomHex(8);
|
|
57
|
+
while (id === ZERO_SPAN) id = randomHex(8);
|
|
58
|
+
return id;
|
|
59
|
+
}
|
|
60
|
+
function formatTraceparent(context) {
|
|
61
|
+
return `00-${context.traceId}-${context.spanId}-${context.sampled === true ? "01" : "00"}`;
|
|
62
|
+
}
|
|
63
|
+
const RECORDS_KEY = Symbol.for("@solidjs/web/trace/records");
|
|
64
|
+
function records$1() {
|
|
65
|
+
const g = globalThis;
|
|
66
|
+
return g[RECORDS_KEY] || (g[RECORDS_KEY] = new WeakMap());
|
|
67
|
+
}
|
|
68
|
+
function traceFor(key, request) {
|
|
69
|
+
const store = records$1();
|
|
70
|
+
let record = store.get(key);
|
|
71
|
+
if (record) return record;
|
|
72
|
+
const headers = request ? request.headers : undefined;
|
|
73
|
+
const incoming = headers ? parseTraceparent(headers.get("traceparent")) : undefined;
|
|
74
|
+
const context = {
|
|
75
|
+
traceId: incoming ? incoming.traceId : randomTraceId(),
|
|
76
|
+
spanId: randomSpanId(),
|
|
77
|
+
entries: {}
|
|
78
|
+
};
|
|
79
|
+
if (incoming) {
|
|
80
|
+
context.parentId = incoming.parentId;
|
|
81
|
+
context.sampled = incoming.sampled;
|
|
82
|
+
}
|
|
83
|
+
if (headers) {
|
|
84
|
+
const state = headers.get("tracestate");
|
|
85
|
+
if (state) context.state = state;
|
|
86
|
+
const baggage = headers.get("baggage");
|
|
87
|
+
if (baggage) context.baggage = baggage;
|
|
88
|
+
}
|
|
89
|
+
let answered = false;
|
|
90
|
+
context.entries.traceparent = formatTraceparent(context);
|
|
91
|
+
record = {
|
|
92
|
+
context,
|
|
93
|
+
emit: incoming !== undefined && incoming.sampled || answered,
|
|
94
|
+
timing: []
|
|
95
|
+
};
|
|
96
|
+
store.set(key, record);
|
|
97
|
+
return record;
|
|
98
|
+
}
|
|
99
|
+
function traceForEvent(event) {
|
|
100
|
+
return traceFor(event.request || event, event.request);
|
|
101
|
+
}
|
|
102
|
+
const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
103
|
+
function splitServerTiming(value) {
|
|
104
|
+
const entries = [];
|
|
105
|
+
let start = 0;
|
|
106
|
+
let quoted = false;
|
|
107
|
+
for (let i = 0; i < value.length; i++) {
|
|
108
|
+
const c = value[i];
|
|
109
|
+
if (quoted) {
|
|
110
|
+
if (c === "\\") i++;else if (c === '"') quoted = false;
|
|
111
|
+
} else if (c === '"') quoted = true;else if (c === ",") {
|
|
112
|
+
entries.push(value.slice(start, i));
|
|
113
|
+
start = i + 1;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
entries.push(value.slice(start));
|
|
117
|
+
return entries;
|
|
118
|
+
}
|
|
119
|
+
function metricName(entry) {
|
|
120
|
+
return entry.split(";")[0].trim().toLowerCase();
|
|
121
|
+
}
|
|
122
|
+
function namesOnServerTiming(headers) {
|
|
123
|
+
const names = new Set();
|
|
124
|
+
const existing = headers.get("server-timing");
|
|
125
|
+
if (existing) {
|
|
126
|
+
for (const entry of splitServerTiming(existing)) {
|
|
127
|
+
const name = metricName(entry);
|
|
128
|
+
if (name) names.add(name);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return names;
|
|
132
|
+
}
|
|
133
|
+
function quoteDesc(value) {
|
|
134
|
+
return value.replace(/[\x00-\x1f\x7f]/g, "").replace(/[^\x20-\x7e]/g, "?").replace(/[\\"]/g, m => "\\" + m);
|
|
135
|
+
}
|
|
136
|
+
function shellMs(record) {
|
|
137
|
+
return record.render !== undefined ? record.render.shellMs : undefined;
|
|
138
|
+
}
|
|
139
|
+
function hasServerTiming(record) {
|
|
140
|
+
return record.emit || record.timing.length > 0 || shellMs(record) !== undefined;
|
|
141
|
+
}
|
|
142
|
+
function appendTraceServerTiming(headers, record) {
|
|
143
|
+
if (record.emit) {
|
|
144
|
+
const entries = record.context.entries;
|
|
145
|
+
let present;
|
|
146
|
+
for (const name in entries) {
|
|
147
|
+
if (!TOKEN.test(name)) continue;
|
|
148
|
+
if (!present) present = namesOnServerTiming(headers);
|
|
149
|
+
if (present.has(name.toLowerCase())) continue;
|
|
150
|
+
headers.append("Server-Timing", `${name};desc="${quoteDesc(entries[name])}"`);
|
|
151
|
+
present.add(name.toLowerCase());
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
const shell = shellMs(record);
|
|
155
|
+
if (shell !== undefined) headers.append("Server-Timing", formatMetric("solid-shell", shell));
|
|
156
|
+
for (const work of record.timing) headers.append("Server-Timing", metricOf(work));
|
|
157
|
+
}
|
|
158
|
+
function metricOf(work) {
|
|
159
|
+
if (work.type === "invocation") return formatMetric("solid-invocation", work.event.durationMs, work.event.id);
|
|
160
|
+
const boundary = work.event;
|
|
161
|
+
return formatMetric("solid-boundary", boundary.durationMs, boundary.ownerPath !== undefined ? boundary.ownerPath.join(" > ") : boundary.id);
|
|
162
|
+
}
|
|
163
|
+
function formatMetric(name, dur, desc) {
|
|
164
|
+
let out = `${name};dur=${Math.round(dur * 10) / 10}`;
|
|
165
|
+
if (desc) out += `;desc="${quoteDesc(desc)}"`;
|
|
166
|
+
return out;
|
|
167
|
+
}
|
|
168
|
+
function mergeServerTiming(target, value) {
|
|
169
|
+
const present = namesOnServerTiming(target);
|
|
170
|
+
for (const entry of splitServerTiming(value)) {
|
|
171
|
+
const trimmed = entry.trim();
|
|
172
|
+
const name = metricName(trimmed);
|
|
173
|
+
if (!name || present.has(name)) continue;
|
|
174
|
+
target.append("Server-Timing", trimmed);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function records() {
|
|
179
|
+
return undefined;
|
|
180
|
+
}
|
|
181
|
+
function settledPromise(value) {
|
|
182
|
+
if (value instanceof Promise) return value;
|
|
183
|
+
try {
|
|
184
|
+
if (Object.prototype.toString.call(value) === "[object Promise]") return Promise.prototype.then.call(value, v => v);
|
|
185
|
+
} catch {}
|
|
186
|
+
return undefined;
|
|
187
|
+
}
|
|
188
|
+
function isDeferredBody(value) {
|
|
189
|
+
if (value === null || typeof value !== "object" && typeof value !== "function") return false;
|
|
190
|
+
if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) return true;
|
|
191
|
+
const v = value;
|
|
192
|
+
if (typeof v[Symbol.asyncIterator] === "function") return true;
|
|
193
|
+
return typeof v[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function timesServerWork(type) {
|
|
197
|
+
const channel = records();
|
|
198
|
+
if (channel === undefined) return false;
|
|
199
|
+
return channel.observed(type);
|
|
200
|
+
}
|
|
201
|
+
function deliver(context, at, boundary, outcome, value) {
|
|
202
|
+
const record = {
|
|
203
|
+
id: context.id,
|
|
204
|
+
direct: context.direct,
|
|
205
|
+
at,
|
|
206
|
+
durationMs: performance.now() - at,
|
|
207
|
+
outcome
|
|
208
|
+
};
|
|
209
|
+
if (boundary !== undefined) record.boundary = boundary;
|
|
210
|
+
if (outcome === "ok" && isDeferredBody(value)) record.deferred = true;
|
|
211
|
+
traceForEvent(context.event).timing.push({
|
|
212
|
+
type: "invocation",
|
|
213
|
+
event: record
|
|
214
|
+
});
|
|
215
|
+
const channel = records();
|
|
216
|
+
if (!channel.observed("invocation")) return;
|
|
217
|
+
const live = {
|
|
218
|
+
event: context.event,
|
|
219
|
+
args: context.args
|
|
220
|
+
};
|
|
221
|
+
if (context.request !== undefined) live.request = context.request;
|
|
222
|
+
if (outcome === "ok") live.result = value;else live.error = value;
|
|
223
|
+
channel.emit("invocation", record, live);
|
|
224
|
+
}
|
|
225
|
+
function observeInvocation(context, execute) {
|
|
226
|
+
if (!timesServerWork("invocation")) return execute();
|
|
227
|
+
const at = performance.now();
|
|
228
|
+
const boundary = context.direct ? sharedConfig.context?._currentBoundaryId ?? undefined : undefined;
|
|
229
|
+
let result;
|
|
230
|
+
try {
|
|
231
|
+
result = execute();
|
|
232
|
+
} catch (error) {
|
|
233
|
+
deliver(context, at, boundary, "error", error);
|
|
234
|
+
throw error;
|
|
235
|
+
}
|
|
236
|
+
const promised = settledPromise(result);
|
|
237
|
+
if (promised !== undefined) {
|
|
238
|
+
return promised.then(value => {
|
|
239
|
+
deliver(context, at, boundary, "ok", value);
|
|
240
|
+
return value;
|
|
241
|
+
}, error => {
|
|
242
|
+
deliver(context, at, boundary, "error", error);
|
|
243
|
+
throw error;
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
deliver(context, at, boundary, "ok", result);
|
|
247
|
+
return result;
|
|
248
|
+
}
|
|
12
249
|
|
|
13
250
|
const SERVER_FUNCTION_METADATA = Symbol.for("solid.ServerFunctionMetadata");
|
|
14
251
|
function getServerFunctionMetadata(fn) {
|
|
@@ -26,6 +263,33 @@ function withMeta(fn, meta) {
|
|
|
26
263
|
Object.assign(metadata, meta);
|
|
27
264
|
return fn;
|
|
28
265
|
}
|
|
266
|
+
const SERVER_FUNCTION_INVOKE = Symbol.for("solid.ServerFunctionInvoke");
|
|
267
|
+
const INVOKE_OPTION_REDIRECTS = {
|
|
268
|
+
headers: "Session-dynamic headers belong to the prepareRequest hook, declaration metadata to " + "withMeta(fn, meta), and data belongs in the arguments, where it is serialized, typed, " + "and part of the cache key.",
|
|
269
|
+
method: "The method is declaration-scoped: declare the function with GET(fn).",
|
|
270
|
+
body: "The arguments are the body: pass them in the args array.",
|
|
271
|
+
timeout: "Compose timeouts through `signal` with AbortSignal.timeout(ms) (and AbortSignal.any to " + "combine it with a caller signal)."
|
|
272
|
+
};
|
|
273
|
+
function invoke(fn, options, ...args) {
|
|
274
|
+
const channel = typeof fn === "function" && fn[SERVER_FUNCTION_INVOKE];
|
|
275
|
+
if (!channel) {
|
|
276
|
+
throw new Error(isServerFunction(fn) ? "invoke: this wrapper does not forward the invocation channel " + "(SERVER_FUNCTION_INVOKE). Wrappers that share calls (caches, channels) opt in " + "deliberately — a caller's signal cannot own a wire other callers share. Invoke " + "the underlying reference directly, or use the wrapper's own per-call idioms." : "invoke expects a server function reference (or a wrapper that forwards its " + "invocation channel). Per-call options apply at the transport; for a data " + "layer's calls, use its per-call options instead.");
|
|
277
|
+
}
|
|
278
|
+
if (options === null || typeof options !== "object") {
|
|
279
|
+
throw new Error("invoke's second argument is the invocation options bag: invoke(fn, { signal }, ...args)");
|
|
280
|
+
}
|
|
281
|
+
const picked = {};
|
|
282
|
+
for (const key in options) {
|
|
283
|
+
if (key !== "signal" && key !== "keepalive" && key !== "priority") {
|
|
284
|
+
throw new Error(`\`${key}\` is not an invocation option. ` + (INVOKE_OPTION_REDIRECTS[key] || "Options here are strictly invocation-scoped (they vary between calls of the " + "same function): signal, keepalive, priority."));
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
if (options.signal !== undefined) picked.signal = options.signal;
|
|
288
|
+
if (options.keepalive !== undefined) picked.keepalive = options.keepalive;
|
|
289
|
+
if (options.priority !== undefined) picked.priority = options.priority;
|
|
290
|
+
return channel(args, picked);
|
|
291
|
+
}
|
|
292
|
+
const LIVE_SOURCE = Symbol.for("solid.LiveSource");
|
|
29
293
|
const SERVER_FUNCTION_RPC = Symbol.for("solid.ServerFunctionRPC");
|
|
30
294
|
function provideServerFunctionRPC(rpc) {
|
|
31
295
|
globalThis[SERVER_FUNCTION_RPC] || (globalThis[SERVER_FUNCTION_RPC] = rpc);
|
|
@@ -61,6 +325,7 @@ function serializeCookie(name, value, options = {}) {
|
|
|
61
325
|
if (options.expires) cookie += `; Expires=${options.expires.toUTCString()}`;
|
|
62
326
|
if (options.httpOnly) cookie += "; HttpOnly";
|
|
63
327
|
if (options.secure) cookie += "; Secure";
|
|
328
|
+
if (options.partitioned) cookie += "; Partitioned";
|
|
64
329
|
if (options.sameSite) {
|
|
65
330
|
const sameSite = options.sameSite.toLowerCase();
|
|
66
331
|
cookie += `; SameSite=${sameSite === "none" ? "None" : sameSite === "strict" ? "Strict" : "Lax"}`;
|
|
@@ -85,11 +350,141 @@ function configureServerFunctionsCodec(codec) {
|
|
|
85
350
|
function getServerFunctionsCodec() {
|
|
86
351
|
return codecConfig.codec;
|
|
87
352
|
}
|
|
88
|
-
|
|
353
|
+
const UNNAMED_FLIGHT_SOURCE = "true";
|
|
354
|
+
const flightConfig = {
|
|
355
|
+
consumers: new Map()
|
|
356
|
+
};
|
|
357
|
+
function assertFlightSource(source) {
|
|
358
|
+
if (source === UNNAMED_FLIGHT_SOURCE || source === "" || source.includes(",")) {
|
|
359
|
+
throw new TypeError(`Invalid flight data source id "${source}": ids ride the ` + `${SINGLE_FLIGHT_HEADER} header as a comma-separated list, and "true" is ` + `reserved for the unnamed registration (the bare consumer/hook signatures).`);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
function subscribeFlightData(sourceOrConsumer, maybeConsumer) {
|
|
363
|
+
const named = typeof sourceOrConsumer === "string";
|
|
364
|
+
if (named) assertFlightSource(sourceOrConsumer);
|
|
365
|
+
const source = named ? sourceOrConsumer : UNNAMED_FLIGHT_SOURCE;
|
|
366
|
+
const consumer = named ? maybeConsumer : sourceOrConsumer;
|
|
367
|
+
flightConfig.consumers.set(source, consumer);
|
|
89
368
|
return () => {
|
|
369
|
+
if (flightConfig.consumers.get(source) === consumer) flightConfig.consumers.delete(source);
|
|
90
370
|
};
|
|
91
371
|
}
|
|
92
|
-
|
|
372
|
+
function frameAddress(id, args) {
|
|
373
|
+
return args && args.length ? id + ":" + hashArguments(args) : id;
|
|
374
|
+
}
|
|
375
|
+
function hashArguments(args) {
|
|
376
|
+
let hash = 0;
|
|
377
|
+
const text = stableString(args);
|
|
378
|
+
for (let i = 0; i < text.length; i++) {
|
|
379
|
+
hash = (hash << 5) - hash + text.charCodeAt(i);
|
|
380
|
+
hash |= 0;
|
|
381
|
+
}
|
|
382
|
+
return (hash >>> 0).toString(36);
|
|
383
|
+
}
|
|
384
|
+
function stableString(value, seen) {
|
|
385
|
+
if (value === null || typeof value !== "object") {
|
|
386
|
+
return typeof value === "bigint" ? value + "n" : String(value);
|
|
387
|
+
}
|
|
388
|
+
if (value instanceof Date) return "Date:" + value.getTime();
|
|
389
|
+
seen || (seen = new Set());
|
|
390
|
+
if (seen.has(value)) return "~";
|
|
391
|
+
seen.add(value);
|
|
392
|
+
if (value instanceof Map) {
|
|
393
|
+
const entries = [];
|
|
394
|
+
for (const [k, v] of value) {
|
|
395
|
+
entries.push(stableString(k, seen) + "=>" + stableString(v, seen));
|
|
396
|
+
}
|
|
397
|
+
return "Map{" + entries.sort().join(",") + "}";
|
|
398
|
+
}
|
|
399
|
+
if (value instanceof Set) {
|
|
400
|
+
const members = [];
|
|
401
|
+
for (const v of value) members.push(stableString(v, seen));
|
|
402
|
+
return "Set{" + members.sort().join(",") + "}";
|
|
403
|
+
}
|
|
404
|
+
if (Array.isArray(value)) {
|
|
405
|
+
let out = "[";
|
|
406
|
+
for (let i = 0; i < value.length; i++) out += (i ? "," : "") + stableString(value[i], seen);
|
|
407
|
+
return out + "]";
|
|
408
|
+
}
|
|
409
|
+
const keys = Object.keys(value).sort();
|
|
410
|
+
let out = "{";
|
|
411
|
+
for (let i = 0; i < keys.length; i++) {
|
|
412
|
+
out += (i ? "," : "") + keys[i] + ":" + stableString(value[keys[i]], seen);
|
|
413
|
+
}
|
|
414
|
+
return out + "}";
|
|
415
|
+
}
|
|
416
|
+
function serverFunctionAddress(endpoint, id) {
|
|
417
|
+
const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
|
|
418
|
+
return `${mount}/${encodeURIComponent(id)}`;
|
|
419
|
+
}
|
|
420
|
+
function serverFunctionDataAddress(endpoint, id) {
|
|
421
|
+
const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
|
|
422
|
+
return `${mount}/data/${encodeURIComponent(id)}`;
|
|
423
|
+
}
|
|
424
|
+
function serverFunctionLiveAddress(endpoint, id) {
|
|
425
|
+
const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
|
|
426
|
+
return `${mount}/live/${encodeURIComponent(id)}`;
|
|
427
|
+
}
|
|
428
|
+
function parseServerFunctionAddress(pathname, endpoint) {
|
|
429
|
+
const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
|
|
430
|
+
if (!pathname.startsWith(mount)) return null;
|
|
431
|
+
const rest = pathname.slice(mount.length);
|
|
432
|
+
if (!rest.startsWith("/")) return null;
|
|
433
|
+
let segment = rest.slice(1);
|
|
434
|
+
let data = false;
|
|
435
|
+
let live = false;
|
|
436
|
+
if (segment.startsWith("data/")) {
|
|
437
|
+
segment = segment.slice(5);
|
|
438
|
+
data = true;
|
|
439
|
+
} else if (segment.startsWith("live/")) {
|
|
440
|
+
segment = segment.slice(5);
|
|
441
|
+
live = true;
|
|
442
|
+
}
|
|
443
|
+
if (!segment || segment.includes("/")) return null;
|
|
444
|
+
try {
|
|
445
|
+
return {
|
|
446
|
+
id: decodeURIComponent(segment),
|
|
447
|
+
data,
|
|
448
|
+
live
|
|
449
|
+
};
|
|
450
|
+
} catch {
|
|
451
|
+
return null;
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
const MAX_GET_URL_LENGTH = 2000;
|
|
455
|
+
function urlTargetId(target, helper) {
|
|
456
|
+
if (typeof target === "string") return target;
|
|
457
|
+
if (isServerFunction(target) && typeof target.id === "string") return target.id;
|
|
458
|
+
throw new Error(`${helper} expects a server function reference (or its id).`);
|
|
459
|
+
}
|
|
460
|
+
function serverFunctionActionUrlFor(endpoint, target, boundArgs) {
|
|
461
|
+
const address = serverFunctionAddress(endpoint, urlTargetId(target, "serverFunctionActionUrl"));
|
|
462
|
+
if (!boundArgs.length) return address;
|
|
463
|
+
if (!isJSONSafe(boundArgs)) {
|
|
464
|
+
throw new Error("Bound arguments in an action url must be JSON-safe: the server reads them the way it " + "reads a form post's, and that convention has no codec. Pass the value through the " + "function's body, or call the reference instead of rendering a url for it.");
|
|
465
|
+
}
|
|
466
|
+
return `${address}?args=${encodeURIComponent(JSON.stringify(boundArgs))}`;
|
|
467
|
+
}
|
|
468
|
+
function serverFunctionUrlFor(endpoint, fn, args) {
|
|
469
|
+
if (!isServerFunction(fn) || typeof fn.id !== "string") {
|
|
470
|
+
throw new Error("serverFunctionUrl expects a server function reference.");
|
|
471
|
+
}
|
|
472
|
+
const metadata = getServerFunctionMetadata(fn);
|
|
473
|
+
if (!metadata || metadata.method !== "GET") {
|
|
474
|
+
throw new Error(`serverFunctionUrl: "${fn.id}" is not a declared read. A call over the default ` + "transport is a POST — its arguments travel in the body, so no url describes it. " + "Declare the function with GET(fn) for a cacheable read that has a url, or start " + 'the call itself: invoke(fn, { priority: "low" }, ...args).');
|
|
475
|
+
}
|
|
476
|
+
const address = metadata.live ? serverFunctionLiveAddress(endpoint, fn.id) : serverFunctionDataAddress(endpoint, fn.id);
|
|
477
|
+
if (!args.length) return address;
|
|
478
|
+
if (!isJSONSafe(args)) {
|
|
479
|
+
throw new Error("Arguments in a server function url must be JSON-safe: the transport encodes anything " + "else through the codec asynchronously, and a url rendered as a value cannot wait for " + "it. Pass JSON-safe arguments, or call the reference instead of rendering a url for it.");
|
|
480
|
+
}
|
|
481
|
+
const url = `${address}?args=${encodeURIComponent(JSON.stringify(args))}`;
|
|
482
|
+
const length = new URL(url, globalThis.location?.href || "http://localhost").href.length;
|
|
483
|
+
if (length > MAX_GET_URL_LENGTH) {
|
|
484
|
+
throw new Error(`serverFunctionUrl: the url for "${fn.id}" with these arguments is ${length} characters; ` + `past ${MAX_GET_URL_LENGTH} the call dispatches over POST (a cache miss rather than a ` + "414), so no url describes it. Shorten the arguments, or call the reference instead.");
|
|
485
|
+
}
|
|
486
|
+
return url;
|
|
487
|
+
}
|
|
93
488
|
const ERROR_HEADER = "X-Server-Function-Error";
|
|
94
489
|
const ERROR_HEADER_MARKER = "=?1?";
|
|
95
490
|
const NEEDS_ENCODING = /[^\x20-\x7e\xa0-\xff]/;
|
|
@@ -115,8 +510,30 @@ function decodeErrorHeaderValue(value) {
|
|
|
115
510
|
return value;
|
|
116
511
|
}
|
|
117
512
|
}
|
|
118
|
-
const INSTANCE_HEADER = "X-Server-Function-Instance";
|
|
119
513
|
const BODY_FORMAT_HEADER = "X-Server-Function-Format";
|
|
514
|
+
const LAST_EVENT_ID_HEADER = "Last-Event-ID";
|
|
515
|
+
const UNKNOWN_HEADER = "X-Server-Function-Unknown";
|
|
516
|
+
const REDIRECT_HEADER = "X-Server-Function-Redirect";
|
|
517
|
+
function decodeRedirectHeaderValue(value) {
|
|
518
|
+
if (typeof value !== "string") return undefined;
|
|
519
|
+
const at = value.indexOf(" ");
|
|
520
|
+
if (at < 0) return undefined;
|
|
521
|
+
const status = Number(value.slice(0, at));
|
|
522
|
+
const url = value.slice(at + 1);
|
|
523
|
+
if (!Number.isInteger(status) || !url) return undefined;
|
|
524
|
+
if (status !== 301 && status !== 302 && status !== 303 && status !== 307 && status !== 308) return undefined;
|
|
525
|
+
let parsed;
|
|
526
|
+
try {
|
|
527
|
+
parsed = new URL(url);
|
|
528
|
+
} catch {
|
|
529
|
+
return undefined;
|
|
530
|
+
}
|
|
531
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return undefined;
|
|
532
|
+
return {
|
|
533
|
+
status,
|
|
534
|
+
url
|
|
535
|
+
};
|
|
536
|
+
}
|
|
120
537
|
const SINGLE_FLIGHT_HEADER = "X-Single-Flight";
|
|
121
538
|
const FILE_FORM_KEY = "__server_function_file__";
|
|
122
539
|
const BodyFormat = {
|
|
@@ -128,9 +545,10 @@ const BodyFormat = {
|
|
|
128
545
|
File: "5",
|
|
129
546
|
ArrayBuffer: "6",
|
|
130
547
|
Uint8Array: "7",
|
|
131
|
-
Json: "8"
|
|
548
|
+
Json: "8",
|
|
549
|
+
Void: "9"
|
|
132
550
|
};
|
|
133
|
-
const JSON_SAFE_DEPTH_LIMIT =
|
|
551
|
+
const JSON_SAFE_DEPTH_LIMIT = 4096;
|
|
134
552
|
const EXIT = {};
|
|
135
553
|
function isJSONSafe(value) {
|
|
136
554
|
const stack = [value];
|
|
@@ -145,7 +563,7 @@ function isJSONSafe(value) {
|
|
|
145
563
|
const t = typeof v;
|
|
146
564
|
if (t === "string" || t === "boolean") continue;
|
|
147
565
|
if (t === "number") {
|
|
148
|
-
if (!Number.isFinite(v)) return false;
|
|
566
|
+
if (!Number.isFinite(v) || Object.is(v, -0)) return false;
|
|
149
567
|
continue;
|
|
150
568
|
}
|
|
151
569
|
if (t !== "object") return false;
|
|
@@ -157,7 +575,12 @@ function isJSONSafe(value) {
|
|
|
157
575
|
} else {
|
|
158
576
|
const proto = Object.getPrototypeOf(v);
|
|
159
577
|
if (proto !== Object.prototype && proto !== null) return false;
|
|
160
|
-
|
|
578
|
+
if (Symbol.asyncIterator in v || Symbol.iterator in v) return false;
|
|
579
|
+
for (const k in v) {
|
|
580
|
+
const descriptor = Object.getOwnPropertyDescriptor(v, k);
|
|
581
|
+
if (descriptor === undefined || !("value" in descriptor)) return false;
|
|
582
|
+
stack.push(descriptor.value);
|
|
583
|
+
}
|
|
161
584
|
}
|
|
162
585
|
}
|
|
163
586
|
return true;
|
|
@@ -223,34 +646,33 @@ function getHeadersAndBody(body) {
|
|
|
223
646
|
return undefined;
|
|
224
647
|
}
|
|
225
648
|
}
|
|
226
|
-
async function extractBody(source, codecOptions) {
|
|
649
|
+
async function extractBody(source, codecOptions, wire) {
|
|
227
650
|
const contentType = source.headers.get("content-type");
|
|
228
651
|
const format = source.headers.get(BODY_FORMAT_HEADER);
|
|
229
|
-
const clone = source.clone();
|
|
230
652
|
switch (true) {
|
|
231
653
|
case format === BodyFormat.Serialized:
|
|
232
|
-
return await deserializeStream(
|
|
654
|
+
return await deserializeStream(source, codecOptions);
|
|
233
655
|
case format === BodyFormat.Json:
|
|
234
|
-
return JSON.parse(await
|
|
656
|
+
return JSON.parse(await source.text());
|
|
235
657
|
case format === BodyFormat.String:
|
|
236
|
-
return await
|
|
658
|
+
return await source.text();
|
|
237
659
|
case format === BodyFormat.File:
|
|
238
660
|
{
|
|
239
|
-
const formData = await
|
|
661
|
+
const formData = await source.formData();
|
|
240
662
|
return formData.get(FILE_FORM_KEY);
|
|
241
663
|
}
|
|
242
664
|
case format === BodyFormat.FormData:
|
|
243
665
|
case contentType && contentType.startsWith("multipart/form-data"):
|
|
244
|
-
return await
|
|
666
|
+
return await source.formData();
|
|
245
667
|
case format === BodyFormat.URLSearchParams:
|
|
246
668
|
case contentType && contentType.startsWith("application/x-www-form-urlencoded"):
|
|
247
|
-
return new URLSearchParams(await
|
|
669
|
+
return new URLSearchParams(await source.text());
|
|
248
670
|
case format === BodyFormat.Blob:
|
|
249
|
-
return await
|
|
671
|
+
return await source.blob();
|
|
250
672
|
case format === BodyFormat.ArrayBuffer:
|
|
251
|
-
return await
|
|
673
|
+
return await source.arrayBuffer();
|
|
252
674
|
case format === BodyFormat.Uint8Array:
|
|
253
|
-
return new Uint8Array(await
|
|
675
|
+
return new Uint8Array(await source.arrayBuffer());
|
|
254
676
|
}
|
|
255
677
|
return undefined;
|
|
256
678
|
}
|
|
@@ -266,18 +688,34 @@ function createChunk(data) {
|
|
|
266
688
|
class ChunkReader {
|
|
267
689
|
constructor(stream) {
|
|
268
690
|
this.reader = stream.getReader();
|
|
269
|
-
this.
|
|
691
|
+
this.store = new Uint8Array(0);
|
|
692
|
+
this.buffer = this.store;
|
|
270
693
|
this.done = false;
|
|
271
694
|
}
|
|
272
695
|
async readChunk() {
|
|
273
696
|
const chunk = await this.reader.read();
|
|
274
|
-
if (
|
|
275
|
-
const newBuffer = new Uint8Array(this.buffer.length + chunk.value.length);
|
|
276
|
-
newBuffer.set(this.buffer);
|
|
277
|
-
newBuffer.set(chunk.value, this.buffer.length);
|
|
278
|
-
this.buffer = newBuffer;
|
|
279
|
-
} else {
|
|
697
|
+
if (chunk.done) {
|
|
280
698
|
this.done = true;
|
|
699
|
+
return;
|
|
700
|
+
}
|
|
701
|
+
const incoming = chunk.value;
|
|
702
|
+
const store = this.store;
|
|
703
|
+
const start = this.buffer.byteOffset;
|
|
704
|
+
const end = start + this.buffer.length;
|
|
705
|
+
const needed = this.buffer.length + incoming.length;
|
|
706
|
+
if (end + incoming.length <= store.length) {
|
|
707
|
+
store.set(incoming, end);
|
|
708
|
+
this.buffer = store.subarray(start, end + incoming.length);
|
|
709
|
+
} else if (needed <= store.length) {
|
|
710
|
+
store.copyWithin(0, start, end);
|
|
711
|
+
store.set(incoming, this.buffer.length);
|
|
712
|
+
this.buffer = store.subarray(0, needed);
|
|
713
|
+
} else {
|
|
714
|
+
const grown = new Uint8Array(Math.max(needed, store.length * 2));
|
|
715
|
+
grown.set(this.buffer);
|
|
716
|
+
grown.set(incoming, this.buffer.length);
|
|
717
|
+
this.store = grown;
|
|
718
|
+
this.buffer = grown.subarray(0, needed);
|
|
281
719
|
}
|
|
282
720
|
}
|
|
283
721
|
async next() {
|
|
@@ -318,6 +756,52 @@ class ChunkReader {
|
|
|
318
756
|
interpret(result.value);
|
|
319
757
|
}
|
|
320
758
|
}
|
|
759
|
+
cancel(reason) {
|
|
760
|
+
return this.reader.cancel(reason);
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
function createEventChunk(data, id) {
|
|
764
|
+
let event = id !== undefined && !id.includes("\0") ? `id: ${id}\n` : "";
|
|
765
|
+
for (const line of data.split(/\r\n|\r|\n/)) event += `data: ${line}\n`;
|
|
766
|
+
return new TextEncoder().encode(event + "\n");
|
|
767
|
+
}
|
|
768
|
+
const EVENT_STREAM_HEARTBEAT = new TextEncoder().encode(":\n\n");
|
|
769
|
+
function positionDigest(value) {
|
|
770
|
+
if (value === undefined || !isJSONSafe(value)) return undefined;
|
|
771
|
+
const text = JSON.stringify(value);
|
|
772
|
+
if (typeof text !== "string") return undefined;
|
|
773
|
+
return textDigest(text);
|
|
774
|
+
}
|
|
775
|
+
function textDigest(text) {
|
|
776
|
+
let a = 0x811c9dc5;
|
|
777
|
+
let b = 0x050c5d1f;
|
|
778
|
+
for (let i = 0; i < text.length; i++) {
|
|
779
|
+
const code = text.charCodeAt(i);
|
|
780
|
+
a = Math.imul(a ^ code, 0x01000193);
|
|
781
|
+
b = Math.imul(b ^ code, 0x01000193);
|
|
782
|
+
}
|
|
783
|
+
return (a >>> 0).toString(16).padStart(8, "0") + (b >>> 0).toString(16).padStart(8, "0");
|
|
784
|
+
}
|
|
785
|
+
const ERROR_TRAILER_PREFIX = "!";
|
|
786
|
+
function encodeErrorTrailer(error) {
|
|
787
|
+
const shaped = error instanceof Error ? error : new Error(String(error));
|
|
788
|
+
return ERROR_TRAILER_PREFIX + JSON.stringify(shaped.name && shaped.name !== "Error" ? {
|
|
789
|
+
name: shaped.name,
|
|
790
|
+
message: shaped.message
|
|
791
|
+
} : {
|
|
792
|
+
message: shaped.message
|
|
793
|
+
});
|
|
794
|
+
}
|
|
795
|
+
function errorFromTrailer(payload) {
|
|
796
|
+
let shape;
|
|
797
|
+
try {
|
|
798
|
+
shape = JSON.parse(payload.slice(1));
|
|
799
|
+
} catch {
|
|
800
|
+
shape = null;
|
|
801
|
+
}
|
|
802
|
+
const error = new Error(shape && typeof shape.message === "string" ? shape.message : "Server function result could not be delivered.");
|
|
803
|
+
if (shape && typeof shape.name === "string") error.name = shape.name;
|
|
804
|
+
return error;
|
|
321
805
|
}
|
|
322
806
|
function serializeStream(value, codecOptions) {
|
|
323
807
|
return new ReadableStream({
|
|
@@ -340,21 +824,31 @@ function serializeStream(value, codecOptions) {
|
|
|
340
824
|
}
|
|
341
825
|
});
|
|
342
826
|
}
|
|
343
|
-
async function deserializeStream(source, codecOptions) {
|
|
827
|
+
async function deserializeStream(source, codecOptions, wire) {
|
|
344
828
|
if (!source.body) {
|
|
345
829
|
throw new Error("missing body");
|
|
346
830
|
}
|
|
347
831
|
const reader = new ChunkReader(source.body);
|
|
348
832
|
const result = await reader.next();
|
|
349
833
|
if (!result.done) {
|
|
834
|
+
if (result.value.startsWith(ERROR_TRAILER_PREFIX)) {
|
|
835
|
+
throw errorFromTrailer(result.value);
|
|
836
|
+
}
|
|
350
837
|
const {
|
|
351
838
|
createJSONDeserializer
|
|
352
839
|
} = await import('@solidjs/web/serialization/decode');
|
|
353
840
|
const deserializeChunk = createJSONDeserializer(codecOptions);
|
|
354
841
|
function interpretChunk(chunk) {
|
|
842
|
+
if (chunk.startsWith(ERROR_TRAILER_PREFIX)) {
|
|
843
|
+
throw errorFromTrailer(chunk);
|
|
844
|
+
}
|
|
355
845
|
return deserializeChunk(JSON.parse(chunk));
|
|
356
846
|
}
|
|
357
|
-
|
|
847
|
+
const end = error => {
|
|
848
|
+
const sweep = () => deserializeChunk.abort(error);
|
|
849
|
+
sweep();
|
|
850
|
+
};
|
|
851
|
+
reader.drain(interpretChunk).then(() => end(new Error("Server function stream ended unexpectedly.")), error => end(error));
|
|
358
852
|
return interpretChunk(result.value);
|
|
359
853
|
}
|
|
360
854
|
return undefined;
|
|
@@ -364,7 +858,7 @@ async function deserializeString(text, codecOptions) {
|
|
|
364
858
|
}
|
|
365
859
|
async function decodeResponse(response, codecOptions) {
|
|
366
860
|
if (!response.body) return undefined;
|
|
367
|
-
return await extractBody(response, codecOptions === undefined ? codecConfig.codec : codecOptions);
|
|
861
|
+
return await extractBody(response.clone(), codecOptions === undefined ? codecConfig.codec : codecOptions);
|
|
368
862
|
}
|
|
369
863
|
async function decodeResponsePayload(response, codecOptions) {
|
|
370
864
|
const decoded = await decodeResponse(response, codecOptions);
|
|
@@ -379,20 +873,37 @@ async function decodeResponsePayload(response, codecOptions) {
|
|
|
379
873
|
};
|
|
380
874
|
}
|
|
381
875
|
|
|
876
|
+
typeof setImmediate === "function" ? setImmediate : fn => setTimeout(fn, 0);
|
|
382
877
|
const RequestContext = Symbol.for("solid.RequestContext");
|
|
383
878
|
function getRequestEvent() {
|
|
384
879
|
return globalThis[RequestContext] ? globalThis[RequestContext].getStore() || sharedConfig.context && sharedConfig.context.event || console.warn("RequestEvent is missing. This is most likely due to accessing `getRequestEvent` non-managed async scope in a partially polyfilled environment. Try moving it above all `await` calls.") : undefined;
|
|
385
880
|
}
|
|
881
|
+
function peekRequestEvent() {
|
|
882
|
+
const store = globalThis[RequestContext];
|
|
883
|
+
return store ? store.getStore() : undefined;
|
|
884
|
+
}
|
|
885
|
+
function traceForStub(stub, event) {
|
|
886
|
+
if (!event) {
|
|
887
|
+
event = peekRequestEvent();
|
|
888
|
+
if (!event || event.response !== stub) return undefined;
|
|
889
|
+
}
|
|
890
|
+
return traceForEvent(event);
|
|
891
|
+
}
|
|
386
892
|
function reportLostHeaderWrite(method, name) {
|
|
387
|
-
const message = `Response header write dropped: headers.${method}(${JSON.stringify(String(name))}) ` + "ran after the response head was sent. Write headers before the shell flushes " + "(or before the handler returns).";
|
|
893
|
+
const message = `[LATE_HEADER_WRITE] Response header write dropped: headers.${method}(${JSON.stringify(String(name))}) ` + "ran after the response head was sent. Write headers before the shell flushes " + "(or before the handler returns).";
|
|
388
894
|
console.error(message);
|
|
389
895
|
}
|
|
390
896
|
function commitResponseStub(stub, {
|
|
391
|
-
allowLateLocation = false
|
|
897
|
+
allowLateLocation = false,
|
|
898
|
+
event
|
|
392
899
|
} = {}) {
|
|
393
900
|
if (!stub || stub.committed) return stub;
|
|
394
|
-
stub.committed = true;
|
|
395
901
|
const headers = stub.headers;
|
|
902
|
+
if (headers && typeof headers.append === "function") {
|
|
903
|
+
const trace = traceForStub(stub, event);
|
|
904
|
+
if (trace) appendTraceServerTiming(headers, trace);
|
|
905
|
+
}
|
|
906
|
+
stub.committed = true;
|
|
396
907
|
if (!headers || typeof headers.set !== "function") return stub;
|
|
397
908
|
for (const method of ["set", "append", "delete"]) {
|
|
398
909
|
const original = headers[method].bind(headers);
|
|
@@ -414,7 +925,8 @@ function copyInitHeaders(init) {
|
|
|
414
925
|
for (const cookie of init.getSetCookie()) headers.append("Set-Cookie", cookie);
|
|
415
926
|
return headers;
|
|
416
927
|
}
|
|
417
|
-
const STUB_GAP_FILL_EXCLUDED = /*#__PURE__*/new Set([ERROR_HEADER, BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, REVALIDATE_HEADER, "Location"
|
|
928
|
+
const STUB_GAP_FILL_EXCLUDED = /*#__PURE__*/new Set([ERROR_HEADER, BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, REVALIDATE_HEADER, REDIRECT_HEADER, "Location",
|
|
929
|
+
...COMPOSED_BODY_FRAMING].map(header => header.toLowerCase()));
|
|
418
930
|
function fillsStubGap(key, headers, response) {
|
|
419
931
|
if (key === "set-cookie" || STUB_GAP_FILL_EXCLUDED.has(key)) return false;
|
|
420
932
|
if (response.body === null && (key === "content-type" || key === "content-length")) return false;
|
|
@@ -422,34 +934,106 @@ function fillsStubGap(key, headers, response) {
|
|
|
422
934
|
}
|
|
423
935
|
function commitEventResponse(response, event = getRequestEvent()) {
|
|
424
936
|
const stub = event && event.response;
|
|
425
|
-
if (!stub || !stub.headers || stub.committed)
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
stub.headers.forEach((value, key) => {
|
|
430
|
-
if (fillsStubGap(key, response.headers, response)) hasGaps = true;
|
|
431
|
-
});
|
|
432
|
-
if (!cookies.length && !hasGaps) return response;
|
|
433
|
-
try {
|
|
434
|
-
for (const cookie of cookies) response.headers.append("Set-Cookie", cookie);
|
|
435
|
-
stub.headers.forEach((value, key) => {
|
|
436
|
-
if (fillsStubGap(key, response.headers, response)) response.headers.set(key, value);
|
|
437
|
-
});
|
|
438
|
-
return response;
|
|
439
|
-
} catch {
|
|
937
|
+
if (!stub || !stub.headers || stub.committed) {
|
|
938
|
+
if (!event || stub) return response;
|
|
939
|
+
const trace = traceForEvent(event);
|
|
940
|
+
if (!hasServerTiming(trace)) return response;
|
|
440
941
|
const headers = copyInitHeaders(response.headers);
|
|
441
|
-
|
|
442
|
-
stub.headers.forEach((value, key) => {
|
|
443
|
-
if (fillsStubGap(key, headers, response)) headers.set(key, value);
|
|
444
|
-
});
|
|
942
|
+
appendTraceServerTiming(headers, trace);
|
|
445
943
|
return new Response(response.body, {
|
|
446
944
|
status: response.status,
|
|
447
945
|
statusText: response.statusText,
|
|
448
946
|
headers
|
|
449
947
|
});
|
|
450
948
|
}
|
|
949
|
+
const cookies = stub.headers.getSetCookie ? stub.headers.getSetCookie() : [];
|
|
950
|
+
commitResponseStub(stub, {
|
|
951
|
+
event
|
|
952
|
+
});
|
|
953
|
+
let hasGaps = false;
|
|
954
|
+
stub.headers.forEach((value, key) => {
|
|
955
|
+
if (fillsStubGap(key, response.headers, response)) hasGaps = true;
|
|
956
|
+
});
|
|
957
|
+
const timing = stub.headers.get("server-timing");
|
|
958
|
+
const mergesTiming = timing !== null && response.headers.has("server-timing");
|
|
959
|
+
if (!cookies.length && !hasGaps && !mergesTiming) return response;
|
|
960
|
+
const headers = copyInitHeaders(response.headers);
|
|
961
|
+
for (const cookie of cookies) headers.append("Set-Cookie", cookie);
|
|
962
|
+
stub.headers.forEach((value, key) => {
|
|
963
|
+
if (fillsStubGap(key, headers, response)) headers.set(key, value);
|
|
964
|
+
});
|
|
965
|
+
if (mergesTiming) mergeServerTiming(headers, timing);
|
|
966
|
+
return new Response(response.body, {
|
|
967
|
+
status: response.status,
|
|
968
|
+
statusText: response.statusText,
|
|
969
|
+
headers
|
|
970
|
+
});
|
|
451
971
|
}
|
|
452
972
|
|
|
973
|
+
let configuredSecret;
|
|
974
|
+
function setFlashSecret(secret) {
|
|
975
|
+
configuredSecret = secret;
|
|
976
|
+
}
|
|
977
|
+
function resolveSecret() {
|
|
978
|
+
return configuredSecret !== undefined ? configuredSecret : globalThis.__SOLID_SECRET__;
|
|
979
|
+
}
|
|
980
|
+
const FLASH_KEY_DOMAIN = "solid.flash.v1\0";
|
|
981
|
+
const FLASH_KEY_ITERATIONS = 100_000;
|
|
982
|
+
let cachedSecret;
|
|
983
|
+
let cachedKey;
|
|
984
|
+
function resolveFlashKey() {
|
|
985
|
+
const secret = resolveSecret();
|
|
986
|
+
if (typeof secret !== "string" || secret.length === 0) return null;
|
|
987
|
+
if (secret !== cachedSecret) {
|
|
988
|
+
cachedSecret = secret;
|
|
989
|
+
const encoder = new TextEncoder();
|
|
990
|
+
cachedKey = crypto.subtle.importKey("raw", encoder.encode(secret), "PBKDF2", false, ["deriveKey"]).then(material => crypto.subtle.deriveKey({
|
|
991
|
+
name: "PBKDF2",
|
|
992
|
+
salt: encoder.encode(FLASH_KEY_DOMAIN),
|
|
993
|
+
iterations: FLASH_KEY_ITERATIONS,
|
|
994
|
+
hash: "SHA-256"
|
|
995
|
+
}, material, {
|
|
996
|
+
name: "AES-GCM",
|
|
997
|
+
length: 256
|
|
998
|
+
}, false, ["encrypt", "decrypt"]));
|
|
999
|
+
}
|
|
1000
|
+
return cachedKey;
|
|
1001
|
+
}
|
|
1002
|
+
const FLASH_FORMAT_VERSION = "1.";
|
|
1003
|
+
const IV_BYTES = 12;
|
|
1004
|
+
const GCM_TAG_BYTES = 16;
|
|
1005
|
+
function toBase64url(bytes) {
|
|
1006
|
+
let binary = "";
|
|
1007
|
+
for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
|
|
1008
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
1009
|
+
}
|
|
1010
|
+
function fromBase64url(text) {
|
|
1011
|
+
const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/"));
|
|
1012
|
+
const bytes = new Uint8Array(binary.length);
|
|
1013
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
1014
|
+
return bytes;
|
|
1015
|
+
}
|
|
1016
|
+
async function encryptFlashValue(key, json) {
|
|
1017
|
+
const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
|
|
1018
|
+
const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
|
|
1019
|
+
name: "AES-GCM",
|
|
1020
|
+
iv
|
|
1021
|
+
}, key, new TextEncoder().encode(json)));
|
|
1022
|
+
const packed = new Uint8Array(IV_BYTES + ciphertext.length);
|
|
1023
|
+
packed.set(iv);
|
|
1024
|
+
packed.set(ciphertext, IV_BYTES);
|
|
1025
|
+
return FLASH_FORMAT_VERSION + toBase64url(packed);
|
|
1026
|
+
}
|
|
1027
|
+
async function decryptFlashValue(key, value) {
|
|
1028
|
+
if (!value.startsWith(FLASH_FORMAT_VERSION)) return;
|
|
1029
|
+
const packed = fromBase64url(value.slice(FLASH_FORMAT_VERSION.length));
|
|
1030
|
+
if (packed.length <= IV_BYTES + GCM_TAG_BYTES) return;
|
|
1031
|
+
const plain = await crypto.subtle.decrypt({
|
|
1032
|
+
name: "AES-GCM",
|
|
1033
|
+
iv: packed.subarray(0, IV_BYTES)
|
|
1034
|
+
}, key, packed.subarray(IV_BYTES));
|
|
1035
|
+
return new TextDecoder().decode(plain);
|
|
1036
|
+
}
|
|
453
1037
|
function encodeInputValue(value) {
|
|
454
1038
|
if (value instanceof FormData) return {
|
|
455
1039
|
$f: [...value.entries()].filter(([, v]) => typeof v === "string")
|
|
@@ -470,7 +1054,11 @@ function decodeInputValue(value) {
|
|
|
470
1054
|
}
|
|
471
1055
|
return value;
|
|
472
1056
|
}
|
|
473
|
-
function encodeFlashCookie(url, result, input, thrown) {
|
|
1057
|
+
async function encodeFlashCookie(url, result, input, thrown) {
|
|
1058
|
+
const key = resolveFlashKey();
|
|
1059
|
+
if (!key) {
|
|
1060
|
+
return null;
|
|
1061
|
+
}
|
|
474
1062
|
const isError = result instanceof Error;
|
|
475
1063
|
const payload = {
|
|
476
1064
|
url,
|
|
@@ -479,26 +1067,62 @@ function encodeFlashCookie(url, result, input, thrown) {
|
|
|
479
1067
|
thrown: !!thrown,
|
|
480
1068
|
input: input.map(encodeInputValue)
|
|
481
1069
|
};
|
|
482
|
-
|
|
1070
|
+
if (fitsCookie(payload)) return flashCookie(payload, await key);
|
|
1071
|
+
payload.truncated = true;
|
|
1072
|
+
payload.input = [];
|
|
1073
|
+
if (!fitsCookie(payload)) {
|
|
1074
|
+
if (typeof payload.result === "string") {
|
|
1075
|
+
let prefix = payload.result;
|
|
1076
|
+
while (prefix.length > 0 && !fitsCookie({
|
|
1077
|
+
...payload,
|
|
1078
|
+
result: prefix
|
|
1079
|
+
})) {
|
|
1080
|
+
prefix = prefix.slice(0, prefix.length >> 1);
|
|
1081
|
+
}
|
|
1082
|
+
payload.result = prefix.length > 0 ? prefix : true;
|
|
1083
|
+
} else {
|
|
1084
|
+
payload.result = true;
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
if (!fitsCookie(payload)) return null;
|
|
1088
|
+
return flashCookie(payload, await key);
|
|
1089
|
+
}
|
|
1090
|
+
const FLASH_MAX_AGE_SECONDS = 60;
|
|
1091
|
+
async function flashCookie(payload, key) {
|
|
1092
|
+
return serializeCookie(FLASH_COOKIE, await encryptFlashValue(key, JSON.stringify(payload)), {
|
|
483
1093
|
secure: true,
|
|
484
|
-
httpOnly: true
|
|
1094
|
+
httpOnly: true,
|
|
1095
|
+
sameSite: "lax",
|
|
1096
|
+
maxAge: FLASH_MAX_AGE_SECONDS
|
|
485
1097
|
});
|
|
486
1098
|
}
|
|
487
|
-
|
|
1099
|
+
const COOKIE_PAIR_BUDGET = 4000;
|
|
1100
|
+
function fitsCookie(payload) {
|
|
1101
|
+
const plaintextBytes = new TextEncoder().encode(JSON.stringify(payload)).length;
|
|
1102
|
+
const packedBytes = IV_BYTES + plaintextBytes + GCM_TAG_BYTES;
|
|
1103
|
+
const valueLength = FLASH_FORMAT_VERSION.length + Math.ceil(packedBytes * 4 / 3);
|
|
1104
|
+
return FLASH_COOKIE.length + 1 + valueLength <= COOKIE_PAIR_BUDGET;
|
|
1105
|
+
}
|
|
1106
|
+
async function decodeFlashCookie(cookieHeader) {
|
|
488
1107
|
const match = parseCookieHeader(cookieHeader)[FLASH_COOKIE];
|
|
489
1108
|
if (!match) return;
|
|
490
1109
|
try {
|
|
491
|
-
const
|
|
492
|
-
if (!
|
|
1110
|
+
const key = resolveFlashKey();
|
|
1111
|
+
if (!key) return;
|
|
1112
|
+
const json = await decryptFlashValue(await key, match);
|
|
1113
|
+
if (json === undefined) return;
|
|
1114
|
+
const payload = JSON.parse(json);
|
|
1115
|
+
if (!payload || typeof payload !== "object" || !("result" in payload)) return;
|
|
493
1116
|
const result = payload.error ? new Error(payload.result) : payload.result;
|
|
494
|
-
|
|
1117
|
+
const submission = {
|
|
495
1118
|
input: Array.isArray(payload.input) ? payload.input.map(decodeInputValue) : [],
|
|
496
1119
|
url: payload.url,
|
|
497
1120
|
result: payload.thrown ? undefined : result,
|
|
498
1121
|
error: payload.thrown ? result : undefined
|
|
499
1122
|
};
|
|
1123
|
+
if (payload.truncated) submission.truncated = true;
|
|
1124
|
+
return submission;
|
|
500
1125
|
} catch (error) {
|
|
501
|
-
console.error(error);
|
|
502
1126
|
}
|
|
503
1127
|
}
|
|
504
1128
|
|
|
@@ -510,7 +1134,11 @@ const config = {
|
|
|
510
1134
|
transformFlightResult: undefined,
|
|
511
1135
|
transformDirectResult: undefined,
|
|
512
1136
|
handleNoJS: undefined,
|
|
513
|
-
endpoint: "/_server"
|
|
1137
|
+
endpoint: "/_server",
|
|
1138
|
+
csrf: true,
|
|
1139
|
+
bodySizeLimit: 1_048_576,
|
|
1140
|
+
maxArguments: 1000,
|
|
1141
|
+
chaosReconnectEvery: 0
|
|
514
1142
|
};
|
|
515
1143
|
function configureServerFunctionsServer({
|
|
516
1144
|
provideEvent,
|
|
@@ -521,7 +1149,12 @@ function configureServerFunctionsServer({
|
|
|
521
1149
|
transformDirectResult,
|
|
522
1150
|
handleNoJS,
|
|
523
1151
|
endpoint,
|
|
524
|
-
|
|
1152
|
+
csrf,
|
|
1153
|
+
codec,
|
|
1154
|
+
bodySizeLimit,
|
|
1155
|
+
maxArguments,
|
|
1156
|
+
secret,
|
|
1157
|
+
chaosReconnectEvery
|
|
525
1158
|
} = {}) {
|
|
526
1159
|
if (provideEvent !== undefined) config.provideEvent = provideEvent;
|
|
527
1160
|
if (wrapInvocation !== undefined) config.wrapInvocation = wrapInvocation;
|
|
@@ -531,7 +1164,24 @@ function configureServerFunctionsServer({
|
|
|
531
1164
|
if (transformDirectResult !== undefined) config.transformDirectResult = transformDirectResult;
|
|
532
1165
|
if (handleNoJS !== undefined) config.handleNoJS = handleNoJS;
|
|
533
1166
|
if (endpoint !== undefined) config.endpoint = endpoint;
|
|
1167
|
+
if (csrf !== undefined) config.csrf = csrf;
|
|
534
1168
|
if (codec !== undefined) configureServerFunctionsCodec(codec);
|
|
1169
|
+
if (bodySizeLimit !== undefined) config.bodySizeLimit = bodySizeLimit;
|
|
1170
|
+
if (maxArguments !== undefined) config.maxArguments = maxArguments;
|
|
1171
|
+
if (secret !== undefined) setFlashSecret(secret);
|
|
1172
|
+
if (chaosReconnectEvery !== undefined) config.chaosReconnectEvery = chaosReconnectEvery;
|
|
1173
|
+
}
|
|
1174
|
+
const flightSources = new Map();
|
|
1175
|
+
function registerFlightDataSource(source, hook) {
|
|
1176
|
+
assertFlightSource(source);
|
|
1177
|
+
flightSources.set(source, hook);
|
|
1178
|
+
return () => {
|
|
1179
|
+
if (flightSources.get(source) === hook) flightSources.delete(source);
|
|
1180
|
+
};
|
|
1181
|
+
}
|
|
1182
|
+
function resolveWrapInvocation(hook) {
|
|
1183
|
+
if (hook === undefined || typeof hook === "function") return hook;
|
|
1184
|
+
throw new Error(`Invalid wrapInvocation: expected a function, received ${hook === null ? "null" : typeof hook}. A hook that is not callable cannot wrap the call - configure a function, or leave ` + `wrapInvocation undefined.`);
|
|
535
1185
|
}
|
|
536
1186
|
function provideEvent(event, fn) {
|
|
537
1187
|
if (config.provideEvent) return config.provideEvent(event, fn);
|
|
@@ -539,8 +1189,193 @@ function provideEvent(event, fn) {
|
|
|
539
1189
|
if (ctx) return ctx.run(event, fn);
|
|
540
1190
|
throw new Error("No request event provider. Configure one with configureServerFunctionsServer({ provideEvent }).");
|
|
541
1191
|
}
|
|
542
|
-
const
|
|
543
|
-
const
|
|
1192
|
+
const PROVIDE_EVENT_TWICE = "provideEvent invoked the server function callback more than once: a second invocation " + "would commit the call's side effects twice. The hook must call fn exactly once and return " + "its result.";
|
|
1193
|
+
const PROVIDE_EVENT_NEVER = "provideEvent returned without invoking the server function callback: the call would have " + "answered as a void success without running the function. The hook must call fn exactly once " + "and return its result.";
|
|
1194
|
+
function provideEventOnce(provide, event, run) {
|
|
1195
|
+
let invocations = 0;
|
|
1196
|
+
const settle = () => {
|
|
1197
|
+
if (invocations !== 1) throw new Error(invocations === 0 ? PROVIDE_EVENT_NEVER : PROVIDE_EVENT_TWICE);
|
|
1198
|
+
};
|
|
1199
|
+
const result = provide(event, () => {
|
|
1200
|
+
if (++invocations > 1) throw new Error(PROVIDE_EVENT_TWICE);
|
|
1201
|
+
return run();
|
|
1202
|
+
});
|
|
1203
|
+
const promised = nativePromise(result);
|
|
1204
|
+
if (promised) {
|
|
1205
|
+
return promised.then(value => {
|
|
1206
|
+
settle();
|
|
1207
|
+
return value;
|
|
1208
|
+
});
|
|
1209
|
+
}
|
|
1210
|
+
settle();
|
|
1211
|
+
return result;
|
|
1212
|
+
}
|
|
1213
|
+
function scopeDeferredResult(value, scope) {
|
|
1214
|
+
const bound = bindDeferredBody(value, scope);
|
|
1215
|
+
if (bound !== value || value === null || typeof value !== "object") return bound;
|
|
1216
|
+
return scopeDeferredContents(value, scope);
|
|
1217
|
+
}
|
|
1218
|
+
class ScopeFrame {
|
|
1219
|
+
constructor(value, next, keys, descriptors) {
|
|
1220
|
+
this.value = value;
|
|
1221
|
+
this.next = next;
|
|
1222
|
+
this.keys = keys;
|
|
1223
|
+
this.descriptors = descriptors;
|
|
1224
|
+
this.i = 0;
|
|
1225
|
+
this.changed = false;
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
function enterScopeCarrier(value, state) {
|
|
1229
|
+
if (value === null || typeof value !== "object" && typeof value !== "function") return value;
|
|
1230
|
+
if (state.seen.has(value)) {
|
|
1231
|
+
state.cyclic.add(value);
|
|
1232
|
+
return state.seen.get(value);
|
|
1233
|
+
}
|
|
1234
|
+
const bound = bindDeferredBody(value, state.scope);
|
|
1235
|
+
if (bound !== value) {
|
|
1236
|
+
state.seen.set(value, bound);
|
|
1237
|
+
return bound;
|
|
1238
|
+
}
|
|
1239
|
+
if (typeof value !== "object") return value;
|
|
1240
|
+
if (Array.isArray(value)) {
|
|
1241
|
+
if (Object.isFrozen(value)) {
|
|
1242
|
+
state.seen.set(value, value);
|
|
1243
|
+
return value;
|
|
1244
|
+
}
|
|
1245
|
+
const next = value.slice();
|
|
1246
|
+
state.seen.set(value, next);
|
|
1247
|
+
return new ScopeFrame(value, next, null, null);
|
|
1248
|
+
}
|
|
1249
|
+
const prototype = Object.getPrototypeOf(value);
|
|
1250
|
+
if (prototype !== Object.prototype && prototype !== null || Object.isFrozen(value)) {
|
|
1251
|
+
state.seen.set(value, value);
|
|
1252
|
+
return value;
|
|
1253
|
+
}
|
|
1254
|
+
const descriptors = Object.getOwnPropertyDescriptors(value);
|
|
1255
|
+
const next = Object.create(prototype, descriptors);
|
|
1256
|
+
state.seen.set(value, next);
|
|
1257
|
+
return new ScopeFrame(value, next, Object.keys(value), descriptors);
|
|
1258
|
+
}
|
|
1259
|
+
function scopeDeferredContents(root, scope) {
|
|
1260
|
+
const state = {
|
|
1261
|
+
seen: new Map(),
|
|
1262
|
+
cyclic: new Set(),
|
|
1263
|
+
scope
|
|
1264
|
+
};
|
|
1265
|
+
const entered = enterScopeCarrier(root, state);
|
|
1266
|
+
if (!(entered instanceof ScopeFrame)) return entered;
|
|
1267
|
+
const stack = [entered];
|
|
1268
|
+
let delivered = NOTHING;
|
|
1269
|
+
for (;;) {
|
|
1270
|
+
const top = stack[stack.length - 1];
|
|
1271
|
+
const length = top.keys ? top.keys.length : top.value.length;
|
|
1272
|
+
let pushed = null;
|
|
1273
|
+
while (top.i < length) {
|
|
1274
|
+
const i = top.i;
|
|
1275
|
+
let original;
|
|
1276
|
+
let writable = true;
|
|
1277
|
+
if (top.keys) {
|
|
1278
|
+
const descriptor = top.descriptors[top.keys[i]];
|
|
1279
|
+
writable = "value" in descriptor && descriptor.writable === true;
|
|
1280
|
+
original = writable ? descriptor.value : undefined;
|
|
1281
|
+
} else {
|
|
1282
|
+
original = top.value[i];
|
|
1283
|
+
}
|
|
1284
|
+
if (!writable) {
|
|
1285
|
+
top.i++;
|
|
1286
|
+
continue;
|
|
1287
|
+
}
|
|
1288
|
+
let bound;
|
|
1289
|
+
if (delivered !== NOTHING) {
|
|
1290
|
+
bound = delivered;
|
|
1291
|
+
delivered = NOTHING;
|
|
1292
|
+
} else {
|
|
1293
|
+
bound = enterScopeCarrier(original, state);
|
|
1294
|
+
if (bound instanceof ScopeFrame) {
|
|
1295
|
+
pushed = bound;
|
|
1296
|
+
break;
|
|
1297
|
+
}
|
|
1298
|
+
}
|
|
1299
|
+
if (bound !== original) {
|
|
1300
|
+
if (top.keys) top.next[top.keys[i]] = bound;else top.next[i] = bound;
|
|
1301
|
+
top.changed = true;
|
|
1302
|
+
}
|
|
1303
|
+
top.i++;
|
|
1304
|
+
}
|
|
1305
|
+
if (pushed !== null) {
|
|
1306
|
+
stack.push(pushed);
|
|
1307
|
+
continue;
|
|
1308
|
+
}
|
|
1309
|
+
stack.pop();
|
|
1310
|
+
let out;
|
|
1311
|
+
if (top.changed || state.cyclic.has(top.value)) {
|
|
1312
|
+
out = top.next;
|
|
1313
|
+
} else {
|
|
1314
|
+
state.seen.set(top.value, top.value);
|
|
1315
|
+
out = top.value;
|
|
1316
|
+
}
|
|
1317
|
+
if (stack.length === 0) return out;
|
|
1318
|
+
delivered = out;
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
function bindDeferredBody(value, scope) {
|
|
1322
|
+
if (value === null || typeof value !== "object" && typeof value !== "function") return value;
|
|
1323
|
+
const promised = scope(() => nativePromise(value));
|
|
1324
|
+
if (promised) {
|
|
1325
|
+
return promised.then(result => scope(() => scopeDeferredResult(result, scope)));
|
|
1326
|
+
}
|
|
1327
|
+
if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) {
|
|
1328
|
+
let reader;
|
|
1329
|
+
return new ReadableStream({
|
|
1330
|
+
async pull(controller) {
|
|
1331
|
+
try {
|
|
1332
|
+
const step = await scope(() => {
|
|
1333
|
+
if (!reader) reader = value.getReader();
|
|
1334
|
+
return reader.read();
|
|
1335
|
+
});
|
|
1336
|
+
if (step.done) controller.close();else controller.enqueue(step.value);
|
|
1337
|
+
} catch (error) {
|
|
1338
|
+
controller.error(error);
|
|
1339
|
+
}
|
|
1340
|
+
},
|
|
1341
|
+
cancel(reason) {
|
|
1342
|
+
return scope(() => reader ? reader.cancel(reason) : value.cancel(reason));
|
|
1343
|
+
}
|
|
1344
|
+
}, {
|
|
1345
|
+
highWaterMark: 0
|
|
1346
|
+
});
|
|
1347
|
+
}
|
|
1348
|
+
const scopedIterator = symbol => ({
|
|
1349
|
+
[symbol]() {
|
|
1350
|
+
const iterator = scope(() => value[symbol]());
|
|
1351
|
+
return new Proxy(iterator, {
|
|
1352
|
+
get(target, property) {
|
|
1353
|
+
const member = Reflect.get(target, property, target);
|
|
1354
|
+
return typeof member === "function" && (property === "next" || property === "return" || property === "throw") ? (...args) => scope(() => member.apply(target, args)) : member;
|
|
1355
|
+
}
|
|
1356
|
+
});
|
|
1357
|
+
}
|
|
1358
|
+
});
|
|
1359
|
+
if (typeof value[Symbol.asyncIterator] === "function") {
|
|
1360
|
+
return scopedIterator(Symbol.asyncIterator);
|
|
1361
|
+
}
|
|
1362
|
+
if (typeof value[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value)) {
|
|
1363
|
+
return scopedIterator(Symbol.iterator);
|
|
1364
|
+
}
|
|
1365
|
+
return value;
|
|
1366
|
+
}
|
|
1367
|
+
function processState(key, create) {
|
|
1368
|
+
const slot = Symbol.for(key);
|
|
1369
|
+
return globalThis[slot] || (globalThis[slot] = create());
|
|
1370
|
+
}
|
|
1371
|
+
const REGISTRATIONS = processState("solid.ServerFunctionRegistrations", () => new Map());
|
|
1372
|
+
const METHODS = processState("solid.ServerFunctionMethods", () => new Map());
|
|
1373
|
+
const REFERENCE_BINDINGS = processState("solid.ServerFunctionReferenceBindings", () => new WeakMap());
|
|
1374
|
+
const CARRIED = processState("solid.ServerFunctionCarriedGrants", () => new Set());
|
|
1375
|
+
function declaresRead(id) {
|
|
1376
|
+
const granted = METHODS.get(id);
|
|
1377
|
+
return granted !== undefined && granted === REGISTRATIONS.get(id);
|
|
1378
|
+
}
|
|
544
1379
|
const INVOCATIONS = new WeakMap();
|
|
545
1380
|
let rpcProvided = false;
|
|
546
1381
|
function provideRPC() {
|
|
@@ -553,6 +1388,15 @@ function provideRPC() {
|
|
|
553
1388
|
}
|
|
554
1389
|
function registerServerFunction(id, callback) {
|
|
555
1390
|
provideRPC();
|
|
1391
|
+
if (REGISTRATIONS.get(id) !== callback) {
|
|
1392
|
+
if (DEV && declaresRead(id)) {
|
|
1393
|
+
METHODS.set(id, callback);
|
|
1394
|
+
CARRIED.add(id);
|
|
1395
|
+
} else {
|
|
1396
|
+
METHODS.delete(id);
|
|
1397
|
+
CARRIED.delete(id);
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
556
1400
|
REGISTRATIONS.set(id, callback);
|
|
557
1401
|
return callback;
|
|
558
1402
|
}
|
|
@@ -564,6 +1408,9 @@ function getServerFunction(id) {
|
|
|
564
1408
|
throw new Error("invalid server function: " + id);
|
|
565
1409
|
}
|
|
566
1410
|
function registerServerReference(id, fn, name) {
|
|
1411
|
+
if (typeof fn !== "function") {
|
|
1412
|
+
throw new Error(`Server function${name ? ` \`${name}\`` : ""} (${id}) is not a function: a module-level ` + `"use server" export must evaluate to a server function (got ${fn === null ? "null" : typeof fn}). Move non-function exports out of the directive module.`);
|
|
1413
|
+
}
|
|
567
1414
|
registerServerFunction(id, fn);
|
|
568
1415
|
return {
|
|
569
1416
|
id,
|
|
@@ -571,6 +1418,33 @@ function registerServerReference(id, fn, name) {
|
|
|
571
1418
|
name
|
|
572
1419
|
};
|
|
573
1420
|
}
|
|
1421
|
+
function inProcessInvoker(call) {
|
|
1422
|
+
return (args, options) => {
|
|
1423
|
+
const signal = options && options.signal;
|
|
1424
|
+
if (!signal) return call(...args);
|
|
1425
|
+
if (signal.aborted) return Promise.reject(signal.reason);
|
|
1426
|
+
return new Promise((resolve, reject) => {
|
|
1427
|
+
const onAbort = () => reject(signal.reason);
|
|
1428
|
+
signal.addEventListener("abort", onAbort, {
|
|
1429
|
+
once: true
|
|
1430
|
+
});
|
|
1431
|
+
let result;
|
|
1432
|
+
try {
|
|
1433
|
+
result = call(...args);
|
|
1434
|
+
} catch (error) {
|
|
1435
|
+
signal.removeEventListener("abort", onAbort);
|
|
1436
|
+
return reject(error);
|
|
1437
|
+
}
|
|
1438
|
+
Promise.resolve(result).then(value => {
|
|
1439
|
+
signal.removeEventListener("abort", onAbort);
|
|
1440
|
+
resolve(value);
|
|
1441
|
+
}, error => {
|
|
1442
|
+
signal.removeEventListener("abort", onAbort);
|
|
1443
|
+
reject(error);
|
|
1444
|
+
});
|
|
1445
|
+
});
|
|
1446
|
+
};
|
|
1447
|
+
}
|
|
574
1448
|
function createServerReference({
|
|
575
1449
|
id,
|
|
576
1450
|
fn,
|
|
@@ -581,58 +1455,128 @@ function createServerReference({
|
|
|
581
1455
|
const metadata = name === undefined ? {} : {
|
|
582
1456
|
name
|
|
583
1457
|
};
|
|
584
|
-
|
|
1458
|
+
const invokeChannel = inProcessInvoker((...args) => proxy(...args));
|
|
1459
|
+
const proxy = new Proxy(fn, {
|
|
585
1460
|
get(target, prop) {
|
|
586
1461
|
if (prop === "id") return id;
|
|
587
1462
|
if (prop === "url") {
|
|
588
|
-
return
|
|
1463
|
+
return serverFunctionAddress(config.endpoint, id);
|
|
589
1464
|
}
|
|
590
1465
|
if (prop === SERVER_FUNCTION_METADATA) return metadata;
|
|
1466
|
+
if (prop === SERVER_FUNCTION_INVOKE) return invokeChannel;
|
|
591
1467
|
return target[prop];
|
|
592
1468
|
},
|
|
593
1469
|
apply(target, thisArg, args) {
|
|
594
1470
|
const ogEvt = getRequestEvent();
|
|
595
1471
|
if (!ogEvt) throw new Error("Cannot call server function outside of a request");
|
|
596
1472
|
const evt = {
|
|
597
|
-
...ogEvt
|
|
1473
|
+
...ogEvt,
|
|
1474
|
+
locals: {
|
|
1475
|
+
...ogEvt.locals
|
|
1476
|
+
}
|
|
598
1477
|
};
|
|
599
1478
|
INVOCATIONS.set(evt, {
|
|
600
|
-
id
|
|
1479
|
+
id,
|
|
1480
|
+
live: false
|
|
601
1481
|
});
|
|
602
1482
|
evt.serverOnly = true;
|
|
603
|
-
const
|
|
1483
|
+
const scope = run => provideEvent(evt, run);
|
|
1484
|
+
const wrap = resolveWrapInvocation(config.wrapInvocation);
|
|
1485
|
+
let result = provideEventOnce(provideEvent, evt, () => {
|
|
604
1486
|
const run = () => fn.apply(thisArg, args);
|
|
605
|
-
return
|
|
1487
|
+
return observeInvocation({
|
|
1488
|
+
id,
|
|
1489
|
+
direct: true,
|
|
1490
|
+
event: evt,
|
|
1491
|
+
args
|
|
1492
|
+
}, () => reportDirectFailure(() => wrap ? wrap(run, {
|
|
606
1493
|
id,
|
|
607
1494
|
args,
|
|
608
1495
|
event: evt,
|
|
609
1496
|
direct: true
|
|
610
|
-
}) : run();
|
|
1497
|
+
}) : run(), id));
|
|
611
1498
|
});
|
|
1499
|
+
result = scopeDeferredResult(result, scope);
|
|
612
1500
|
const transform = config.transformDirectResult;
|
|
613
1501
|
if (transform && result && typeof result.then === "function") {
|
|
614
|
-
return result.then(value => transform(value, {
|
|
1502
|
+
return result.then(value => scopeDeferredResult(transform(value, {
|
|
615
1503
|
id,
|
|
616
1504
|
args,
|
|
617
1505
|
event: evt
|
|
618
|
-
}));
|
|
1506
|
+
}), scope));
|
|
619
1507
|
}
|
|
620
|
-
return transform ? transform(result, {
|
|
1508
|
+
return transform ? scopeDeferredResult(transform(result, {
|
|
621
1509
|
id,
|
|
622
1510
|
args,
|
|
623
1511
|
event: evt
|
|
624
|
-
}) : result;
|
|
1512
|
+
}), scope) : result;
|
|
625
1513
|
}
|
|
626
1514
|
});
|
|
1515
|
+
REFERENCE_BINDINGS.set(proxy, fn);
|
|
1516
|
+
return proxy;
|
|
627
1517
|
}
|
|
628
1518
|
function GET(fn) {
|
|
629
1519
|
if (!isServerFunction(fn) || typeof fn.id !== "string") {
|
|
630
1520
|
throw new Error("GET expects a server function reference");
|
|
631
1521
|
}
|
|
632
|
-
|
|
633
|
-
|
|
1522
|
+
const id = fn.id;
|
|
1523
|
+
const binding = REFERENCE_BINDINGS.has(fn) ? REFERENCE_BINDINGS.get(fn) : REGISTRATIONS.get(id);
|
|
1524
|
+
const existing = METHODS.get(id);
|
|
1525
|
+
if (existing !== undefined && existing !== binding) {
|
|
1526
|
+
if (CARRIED.has(id)) return fn;
|
|
1527
|
+
if (DEV) {
|
|
1528
|
+
throw new Error(`GET() would rebind the existing grant for server function "${id}" to a different ` + `function. A GET declaration is made about a function, not an id - two references ` + `sharing one id cannot both hold it. Give the functions distinct ids, or drop the ` + `stale declaration.`);
|
|
1529
|
+
}
|
|
1530
|
+
METHODS.delete(id);
|
|
1531
|
+
return fn;
|
|
1532
|
+
}
|
|
1533
|
+
METHODS.set(id, binding);
|
|
1534
|
+
CARRIED.delete(id);
|
|
1535
|
+
const reference = withMeta(fn, {
|
|
634
1536
|
method: "GET"
|
|
635
1537
|
});
|
|
1538
|
+
guardDeclaredMethod(getServerFunctionMetadata(reference), id);
|
|
1539
|
+
return reference;
|
|
1540
|
+
}
|
|
1541
|
+
function guardDeclaredMethod(metadata, id) {
|
|
1542
|
+
let declared = metadata.method;
|
|
1543
|
+
Object.defineProperty(metadata, "method", {
|
|
1544
|
+
configurable: true,
|
|
1545
|
+
enumerable: true,
|
|
1546
|
+
get: () => declared,
|
|
1547
|
+
set(next) {
|
|
1548
|
+
if (next === declared) return;
|
|
1549
|
+
if (DEV) {
|
|
1550
|
+
throw new Error(`withMeta({ method }) cannot change the GET() declaration of server function ` + `"${id}". The method is declaration-scoped: it was granted about the function ` + `by GET(fn), and a metadata write cannot re-shape the wire grant.`);
|
|
1551
|
+
}
|
|
1552
|
+
METHODS.delete(id);
|
|
1553
|
+
declared = next;
|
|
1554
|
+
}
|
|
1555
|
+
});
|
|
1556
|
+
}
|
|
1557
|
+
function live(fn) {
|
|
1558
|
+
if (!isServerFunction(fn) || typeof fn.id !== "string") {
|
|
1559
|
+
throw new Error("live expects a server function reference");
|
|
1560
|
+
}
|
|
1561
|
+
const metadata = {
|
|
1562
|
+
...getServerFunctionMetadata(fn),
|
|
1563
|
+
live: true
|
|
1564
|
+
};
|
|
1565
|
+
const wrapped = async (...args) => brandLive(await fn(...args));
|
|
1566
|
+
wrapped[SERVER_FUNCTION_METADATA] = metadata;
|
|
1567
|
+
wrapped[SERVER_FUNCTION_INVOKE] = inProcessInvoker(wrapped);
|
|
1568
|
+
wrapped.id = fn.id;
|
|
1569
|
+
Object.defineProperty(wrapped, "url", {
|
|
1570
|
+
get: () => fn.url,
|
|
1571
|
+
configurable: true
|
|
1572
|
+
});
|
|
1573
|
+
return wrapped;
|
|
1574
|
+
}
|
|
1575
|
+
function brandLive(answer) {
|
|
1576
|
+
if (typeof answer === "function" || answer !== null && typeof answer === "object" && answer[Symbol.asyncIterator]) {
|
|
1577
|
+
answer[LIVE_SOURCE] = true;
|
|
1578
|
+
}
|
|
1579
|
+
return answer;
|
|
636
1580
|
}
|
|
637
1581
|
function getServerFunctionInvocation() {
|
|
638
1582
|
return getEventServerFunctionInvocation(getRequestEvent());
|
|
@@ -640,53 +1584,179 @@ function getServerFunctionInvocation() {
|
|
|
640
1584
|
function getEventServerFunctionInvocation(event) {
|
|
641
1585
|
return event && INVOCATIONS.get(event);
|
|
642
1586
|
}
|
|
643
|
-
function
|
|
644
|
-
|
|
645
|
-
if (reference) {
|
|
646
|
-
return reference.split("#")[0];
|
|
647
|
-
}
|
|
648
|
-
return url.searchParams.get("id");
|
|
1587
|
+
function resolveAddress(url) {
|
|
1588
|
+
return parseServerFunctionAddress(url.pathname, config.endpoint);
|
|
649
1589
|
}
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
1590
|
+
const DECODE_DEPTH_LIMIT = 64;
|
|
1591
|
+
function assertDecodeDepth(value) {
|
|
1592
|
+
let level = [value];
|
|
1593
|
+
for (let depth = 0; level.length > 0; depth++) {
|
|
1594
|
+
if (depth > DECODE_DEPTH_LIMIT) {
|
|
1595
|
+
throw new TypeError("Server function arguments exceed the decode depth limit");
|
|
1596
|
+
}
|
|
1597
|
+
const next = [];
|
|
1598
|
+
for (const node of level) {
|
|
1599
|
+
if (node === null || typeof node !== "object") continue;
|
|
1600
|
+
if (Array.isArray(node)) {
|
|
1601
|
+
for (const child of node) next.push(child);
|
|
1602
|
+
} else {
|
|
1603
|
+
for (const key of Object.keys(node)) next.push(node[key]);
|
|
659
1604
|
}
|
|
660
1605
|
}
|
|
1606
|
+
level = next;
|
|
661
1607
|
}
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
1608
|
+
}
|
|
1609
|
+
const UNSAFE_ARGUMENT_KEYS = ["__proto__", "constructor", "prototype"];
|
|
1610
|
+
function stripUnsafeArgumentKeys(value) {
|
|
1611
|
+
const stack = [value];
|
|
1612
|
+
const seen = new Set();
|
|
1613
|
+
while (stack.length) {
|
|
1614
|
+
const v = stack.pop();
|
|
1615
|
+
if (v === null || typeof v !== "object" || seen.has(v)) continue;
|
|
1616
|
+
seen.add(v);
|
|
1617
|
+
for (const key of UNSAFE_ARGUMENT_KEYS) {
|
|
1618
|
+
delete v[key];
|
|
1619
|
+
}
|
|
1620
|
+
for (const key of Object.keys(v)) stack.push(v[key]);
|
|
1621
|
+
if (v instanceof Map) {
|
|
1622
|
+
for (const [k, entry] of v) stack.push(k, entry);
|
|
1623
|
+
} else if (v instanceof Set) {
|
|
1624
|
+
for (const member of v) stack.push(member);
|
|
666
1625
|
}
|
|
667
|
-
parsed.push(decoded);
|
|
668
1626
|
}
|
|
669
|
-
return
|
|
1627
|
+
return value;
|
|
670
1628
|
}
|
|
671
|
-
async function
|
|
1629
|
+
async function bufferBodyWithin(request, limit) {
|
|
1630
|
+
const reader = request.body.getReader();
|
|
1631
|
+
const signal = request.signal;
|
|
1632
|
+
const chunks = [];
|
|
1633
|
+
let total = 0;
|
|
1634
|
+
const onAbort = () => {
|
|
1635
|
+
reader.cancel(signal.reason).catch(() => {});
|
|
1636
|
+
};
|
|
1637
|
+
if (signal.aborted) onAbort();else signal.addEventListener("abort", onAbort, {
|
|
1638
|
+
once: true
|
|
1639
|
+
});
|
|
1640
|
+
try {
|
|
1641
|
+
for (;;) {
|
|
1642
|
+
const {
|
|
1643
|
+
done,
|
|
1644
|
+
value
|
|
1645
|
+
} = await reader.read();
|
|
1646
|
+
if (signal.aborted) throw signal.reason;
|
|
1647
|
+
if (done) break;
|
|
1648
|
+
total += value.byteLength;
|
|
1649
|
+
if (total > limit) {
|
|
1650
|
+
reader.cancel().catch(() => {});
|
|
1651
|
+
return null;
|
|
1652
|
+
}
|
|
1653
|
+
chunks.push(value);
|
|
1654
|
+
}
|
|
1655
|
+
} catch (error) {
|
|
1656
|
+
reader.cancel(error).catch(() => {});
|
|
1657
|
+
throw error;
|
|
1658
|
+
} finally {
|
|
1659
|
+
signal.removeEventListener("abort", onAbort);
|
|
1660
|
+
reader.releaseLock();
|
|
1661
|
+
}
|
|
1662
|
+
const body = new Uint8Array(total);
|
|
1663
|
+
let offset = 0;
|
|
1664
|
+
for (const chunk of chunks) {
|
|
1665
|
+
body.set(chunk, offset);
|
|
1666
|
+
offset += chunk.byteLength;
|
|
1667
|
+
}
|
|
1668
|
+
return body;
|
|
1669
|
+
}
|
|
1670
|
+
function withBufferedBody(request, body) {
|
|
1671
|
+
return new Request(request.url, {
|
|
1672
|
+
method: request.method,
|
|
1673
|
+
headers: request.headers,
|
|
1674
|
+
signal: request.signal,
|
|
1675
|
+
body
|
|
1676
|
+
});
|
|
1677
|
+
}
|
|
1678
|
+
const KNOWN_BODY_FORMATS = new Set(Object.values(BodyFormat));
|
|
1679
|
+
const FORMAT_SKEW = Symbol("solid.serverFunction.formatSkew");
|
|
1680
|
+
function unknownFormatError(tag) {
|
|
1681
|
+
const error = new TypeError(`Server function body carries an unrecognized ${BODY_FORMAT_HEADER} tag ("${tag}"): the ` + "caller encodes a newer wire format than this build can decode (version skew), or an " + "intermediary duplicated the header. The body was refused rather than reinterpreted.");
|
|
1682
|
+
error[FORMAT_SKEW] = true;
|
|
1683
|
+
return error;
|
|
1684
|
+
}
|
|
1685
|
+
async function parseArguments(request, url, scripted, codec) {
|
|
1686
|
+
const parsed = [];
|
|
1687
|
+
const bodyFormat = request.method === "POST" ? request.headers.get(BODY_FORMAT_HEADER) : null;
|
|
1688
|
+
const args = url.searchParams.get("args");
|
|
1689
|
+
if (args && (!scripted || request.method === "GET" || bodyFormat !== BodyFormat.Serialized)) {
|
|
1690
|
+
let result;
|
|
1691
|
+
if (args.startsWith(";0x")) {
|
|
1692
|
+
result = await deserializeString(args, codec);
|
|
1693
|
+
} else {
|
|
1694
|
+
result = JSON.parse(args);
|
|
1695
|
+
assertDecodeDepth(result);
|
|
1696
|
+
}
|
|
1697
|
+
if (!Array.isArray(result)) {
|
|
1698
|
+
throw new TypeError("Server function arguments must encode an array");
|
|
1699
|
+
}
|
|
1700
|
+
stripUnsafeArgumentKeys(result);
|
|
1701
|
+
for (const arg of result) {
|
|
1702
|
+
parsed.push(arg);
|
|
1703
|
+
}
|
|
1704
|
+
} else if (!args && url.search && (request.method === "GET" || request.method === "HEAD")) {
|
|
1705
|
+
parsed.push(url.searchParams);
|
|
1706
|
+
}
|
|
1707
|
+
if (request.method === "POST" && request.body !== null) {
|
|
1708
|
+
if (bodyFormat !== null && !KNOWN_BODY_FORMATS.has(bodyFormat)) {
|
|
1709
|
+
throw unknownFormatError(bodyFormat);
|
|
1710
|
+
}
|
|
1711
|
+
const body = request.clone();
|
|
1712
|
+
const decoded = await extractBody(body, codec);
|
|
1713
|
+
if (bodyFormat === BodyFormat.Serialized || bodyFormat === BodyFormat.Json) {
|
|
1714
|
+
if (bodyFormat === BodyFormat.Json) assertDecodeDepth(decoded);
|
|
1715
|
+
if (!Array.isArray(decoded)) {
|
|
1716
|
+
throw new TypeError("Server function arguments must encode an array");
|
|
1717
|
+
}
|
|
1718
|
+
return stripUnsafeArgumentKeys(decoded);
|
|
1719
|
+
}
|
|
1720
|
+
if (decoded === undefined) {
|
|
1721
|
+
if (bodyFormat === null && (await body.arrayBuffer()).byteLength === 0) {
|
|
1722
|
+
return parsed;
|
|
1723
|
+
}
|
|
1724
|
+
throw new TypeError("Server function body carries no usable encoding");
|
|
1725
|
+
}
|
|
1726
|
+
parsed.push(decoded);
|
|
1727
|
+
}
|
|
1728
|
+
return parsed;
|
|
1729
|
+
}
|
|
1730
|
+
async function foldFlightData(hooks, event, headers, outcome, context = {}) {
|
|
672
1731
|
if (outcome.value instanceof Response && outcome.value.body) return outcome.value;
|
|
673
1732
|
digestOutcome(event, outcome);
|
|
674
|
-
const
|
|
675
|
-
|
|
676
|
-
|
|
1733
|
+
const folded = [];
|
|
1734
|
+
for (const [source, hook] of hooks) {
|
|
1735
|
+
try {
|
|
1736
|
+
const slice = await hook(event, outcome);
|
|
1737
|
+
if (slice !== undefined) folded.push([source, slice]);
|
|
1738
|
+
} catch (error) {
|
|
1739
|
+
console.error(`Error collecting flight data for source "${source}"`, error);
|
|
1740
|
+
}
|
|
1741
|
+
}
|
|
1742
|
+
if (folded.length === 0) return outcome.value;
|
|
1743
|
+
const data = Object.fromEntries(folded);
|
|
1744
|
+
headers.set(SINGLE_FLIGHT_HEADER, folded.map(([source]) => source).join(","));
|
|
677
1745
|
if (context.transformFlightResult) {
|
|
678
1746
|
const transformed = await context.transformFlightResult(event, {
|
|
679
1747
|
value: outcome.value,
|
|
680
1748
|
data
|
|
681
1749
|
}, context);
|
|
682
1750
|
if (transformed !== undefined) {
|
|
683
|
-
|
|
1751
|
+
const owned = ownResponse(transformed);
|
|
1752
|
+
for (const cookie of headers.getSetCookie()) owned.headers.append("Set-Cookie", cookie);
|
|
684
1753
|
headers.forEach((value, key) => {
|
|
685
|
-
if (key !== "set-cookie" && !
|
|
686
|
-
|
|
1754
|
+
if (key !== "set-cookie" && !owned.headers.has(key)) {
|
|
1755
|
+
owned.headers.set(key, value);
|
|
687
1756
|
}
|
|
688
1757
|
});
|
|
689
|
-
|
|
1758
|
+
owned.headers.set(SINGLE_FLIGHT_HEADER, headers.get(SINGLE_FLIGHT_HEADER));
|
|
1759
|
+
return owned;
|
|
690
1760
|
}
|
|
691
1761
|
}
|
|
692
1762
|
return outcome.value === undefined ? {
|
|
@@ -753,7 +1823,7 @@ function foldSetCookies(headers, setCookies) {
|
|
|
753
1823
|
}
|
|
754
1824
|
function mergeResponseHeaders(target, source) {
|
|
755
1825
|
source.forEach((value, key) => {
|
|
756
|
-
if (key !== "set-cookie") target.append(key, value);
|
|
1826
|
+
if (key !== "set-cookie" && !COMPOSED_BODY_FRAMING.has(key)) target.append(key, value);
|
|
757
1827
|
});
|
|
758
1828
|
if (source.getSetCookie) {
|
|
759
1829
|
for (const cookie of source.getSetCookie()) target.append("Set-Cookie", cookie);
|
|
@@ -762,10 +1832,52 @@ function mergeResponseHeaders(target, source) {
|
|
|
762
1832
|
}
|
|
763
1833
|
}
|
|
764
1834
|
const validRedirectStatuses = new Set([301, 302, 303, 307, 308]);
|
|
1835
|
+
function maskRedirect(headers, response, requestUrl) {
|
|
1836
|
+
const target = response.headers && response.headers.get("Location");
|
|
1837
|
+
if (target) {
|
|
1838
|
+
headers.set(REDIRECT_HEADER, `${response.status} ${new URL(target, requestUrl)}`);
|
|
1839
|
+
}
|
|
1840
|
+
headers.delete("Location");
|
|
1841
|
+
}
|
|
1842
|
+
const BOUNDED_COMPOSED_HEADERS = [REDIRECT_HEADER, "Location", REVALIDATE_HEADER];
|
|
1843
|
+
function enforceComposedHeaderInvariants(response) {
|
|
1844
|
+
for (const name of BOUNDED_COMPOSED_HEADERS) {
|
|
1845
|
+
const value = response.headers.get(name);
|
|
1846
|
+
if (value === null) continue;
|
|
1847
|
+
if (value.length > RESPONSE_HEADER_VALUE_LIMIT) {
|
|
1848
|
+
return refuseComposedHeader(response, name, `${name} response header refused at ${value.length} characters`, DEV ? `The ${name} response header is ${value.length} characters; past ` + `${RESPONSE_HEADER_VALUE_LIMIT} it would overflow receivers (an 8 KiB proxy ` + `buffer holds the whole header block) and the response dies at the socket after ` + `the mutation committed. Refused rather than trimmed: a cut redirect target is a ` + `different address, a dropped revalidate key is a silently stale cache. The ` + `redirect()/reload() helpers enforce this bound with the full reasoning at the ` + `call site.` : null);
|
|
1849
|
+
}
|
|
1850
|
+
if (name === REVALIDATE_HEADER) continue;
|
|
1851
|
+
const target = name === REDIRECT_HEADER ? value.slice(value.indexOf(" ") + 1) : value;
|
|
1852
|
+
if (!isHttpNavigationTarget(target)) {
|
|
1853
|
+
return refuseComposedHeader(response, name, `${name} response header refused: non-http(s) navigation target`, DEV ? `The ${name} response header carries a navigation target with a non-http(s) ` + `scheme ("${target.slice(0, 64)}"). A javascript: target is same-origin script ` + `execution in any integration that navigates to it, so only http(s) and ` + `relative targets leave this transport. If the target came from request data ` + `(?next= and friends), validate it against your own origin before redirecting.` : null);
|
|
1854
|
+
}
|
|
1855
|
+
}
|
|
1856
|
+
return response;
|
|
1857
|
+
}
|
|
1858
|
+
function refuseComposedHeader(response, name, headerMessage, body) {
|
|
1859
|
+
if (response.body) {
|
|
1860
|
+
try {
|
|
1861
|
+
const cancelled = response.body.cancel();
|
|
1862
|
+
if (cancelled && typeof cancelled.then === "function") cancelled.then(undefined, () => {});
|
|
1863
|
+
} catch {}
|
|
1864
|
+
}
|
|
1865
|
+
const headers = new Headers();
|
|
1866
|
+
headers.set(ERROR_HEADER, boundedErrorHeaderValue(DEV ? headerMessage : GENERIC_SERVER_ERROR_MESSAGE));
|
|
1867
|
+
return new Response(body, {
|
|
1868
|
+
status: 500,
|
|
1869
|
+
headers
|
|
1870
|
+
});
|
|
1871
|
+
}
|
|
1872
|
+
function warnScripted304(functionId) {
|
|
1873
|
+
if (DEV) {
|
|
1874
|
+
console.warn(`Server function "${functionId}" answered a scripted call with 304 Not Modified. ` + `The client transport sends no conditional headers, so nothing was asked to be ` + `revalidated: the call resolves to undefined, not "unchanged". For conditional ` + `reads, declare the function GET and set ETag/Cache-Control response headers - ` + `the browser owns that exchange and replays its cached answer on a 304.`);
|
|
1875
|
+
}
|
|
1876
|
+
}
|
|
765
1877
|
function createNoJSHandler({
|
|
766
1878
|
base = ""
|
|
767
1879
|
} = {}) {
|
|
768
|
-
return function handleNoJS(result, request, args, thrown) {
|
|
1880
|
+
return async function handleNoJS(result, request, args, thrown) {
|
|
769
1881
|
const url = new URL(request.url);
|
|
770
1882
|
let back = new URL(base || "/", url.origin).toString();
|
|
771
1883
|
try {
|
|
@@ -790,8 +1902,9 @@ function createNoJSHandler({
|
|
|
790
1902
|
Location: back
|
|
791
1903
|
});
|
|
792
1904
|
}
|
|
793
|
-
if (result && !(result instanceof Response)) {
|
|
794
|
-
|
|
1905
|
+
if (result !== undefined && !(result instanceof Response)) {
|
|
1906
|
+
const flash = await encodeFlashCookie(url.pathname, result, args, thrown);
|
|
1907
|
+
if (flash !== null) headers.append("Set-Cookie", flash);
|
|
795
1908
|
}
|
|
796
1909
|
return new Response(null, {
|
|
797
1910
|
status,
|
|
@@ -805,14 +1918,477 @@ function isFormPost(request) {
|
|
|
805
1918
|
const type = request.headers.get("content-type") || "";
|
|
806
1919
|
return type.startsWith("application/x-www-form-urlencoded") || type.startsWith("multipart/form-data");
|
|
807
1920
|
}
|
|
808
|
-
function
|
|
1921
|
+
function guardFailures(value, state) {
|
|
1922
|
+
if (!state) state = {
|
|
1923
|
+
seen: new WeakMap(),
|
|
1924
|
+
cyclic: new WeakSet()
|
|
1925
|
+
};
|
|
1926
|
+
const entered = enterGuard(value, state);
|
|
1927
|
+
if (!(entered instanceof Frame)) return entered;
|
|
1928
|
+
const stack = [entered];
|
|
1929
|
+
let delivered = NOTHING;
|
|
1930
|
+
for (;;) {
|
|
1931
|
+
const top = stack[stack.length - 1];
|
|
1932
|
+
const items = top.items;
|
|
1933
|
+
let pushed = null;
|
|
1934
|
+
while (top.i < items.length) {
|
|
1935
|
+
const i = top.i;
|
|
1936
|
+
let original;
|
|
1937
|
+
if (top.kind === OBJECT) {
|
|
1938
|
+
const descriptor = top.descriptors[items[i]];
|
|
1939
|
+
if ("value" in descriptor) {
|
|
1940
|
+
original = descriptor.value;
|
|
1941
|
+
} else if (typeof descriptor.get === "function") {
|
|
1942
|
+
if (top.accessorRead !== i) {
|
|
1943
|
+
try {
|
|
1944
|
+
top.accessorValue = descriptor.get.call(top.value);
|
|
1945
|
+
} catch (error) {
|
|
1946
|
+
throw wireServerFunctionError(error, "channel");
|
|
1947
|
+
}
|
|
1948
|
+
top.accessorRead = i;
|
|
1949
|
+
}
|
|
1950
|
+
original = top.accessorValue;
|
|
1951
|
+
} else {
|
|
1952
|
+
top.i++;
|
|
1953
|
+
continue;
|
|
1954
|
+
}
|
|
1955
|
+
} else {
|
|
1956
|
+
original = items[i];
|
|
1957
|
+
}
|
|
1958
|
+
let guarded;
|
|
1959
|
+
if (delivered !== NOTHING) {
|
|
1960
|
+
guarded = delivered;
|
|
1961
|
+
delivered = NOTHING;
|
|
1962
|
+
} else {
|
|
1963
|
+
guarded = enterGuard(original, state);
|
|
1964
|
+
if (guarded instanceof Frame) {
|
|
1965
|
+
pushed = guarded;
|
|
1966
|
+
break;
|
|
1967
|
+
}
|
|
1968
|
+
}
|
|
1969
|
+
if (top.kind === ARRAY) {
|
|
1970
|
+
if (guarded !== original) {
|
|
1971
|
+
top.next[i] = guarded;
|
|
1972
|
+
top.changed = true;
|
|
1973
|
+
}
|
|
1974
|
+
} else if (top.kind === MAP) {
|
|
1975
|
+
if ((i & 1) === 0) top.pendingKey = guarded;else top.next.set(top.pendingKey, guarded);
|
|
1976
|
+
if (guarded !== original) top.changed = true;
|
|
1977
|
+
} else if (top.kind === SET) {
|
|
1978
|
+
top.next.add(guarded);
|
|
1979
|
+
if (guarded !== original) top.changed = true;
|
|
1980
|
+
} else if (guarded !== original || top.accessorRead === i) {
|
|
1981
|
+
Object.defineProperty(top.next, items[i], {
|
|
1982
|
+
value: guarded,
|
|
1983
|
+
writable: true,
|
|
1984
|
+
configurable: true,
|
|
1985
|
+
enumerable: top.descriptors[items[i]].enumerable
|
|
1986
|
+
});
|
|
1987
|
+
top.changed = true;
|
|
1988
|
+
}
|
|
1989
|
+
top.i++;
|
|
1990
|
+
}
|
|
1991
|
+
if (pushed !== null) {
|
|
1992
|
+
stack.push(pushed);
|
|
1993
|
+
continue;
|
|
1994
|
+
}
|
|
1995
|
+
stack.pop();
|
|
1996
|
+
const out = keepGuarded(top.value, top.next, top.changed, state);
|
|
1997
|
+
if (stack.length === 0) return out;
|
|
1998
|
+
delivered = out;
|
|
1999
|
+
}
|
|
2000
|
+
}
|
|
2001
|
+
const NOTHING = Symbol();
|
|
2002
|
+
const ARRAY = 0;
|
|
2003
|
+
const MAP = 1;
|
|
2004
|
+
const SET = 2;
|
|
2005
|
+
const OBJECT = 3;
|
|
2006
|
+
class Frame {
|
|
2007
|
+
constructor(kind, value, next, items, descriptors) {
|
|
2008
|
+
this.kind = kind;
|
|
2009
|
+
this.value = value;
|
|
2010
|
+
this.next = next;
|
|
2011
|
+
this.items = items;
|
|
2012
|
+
this.descriptors = descriptors;
|
|
2013
|
+
this.i = 0;
|
|
2014
|
+
this.changed = false;
|
|
2015
|
+
this.accessorRead = -1;
|
|
2016
|
+
this.accessorValue = undefined;
|
|
2017
|
+
this.pendingKey = undefined;
|
|
2018
|
+
}
|
|
2019
|
+
}
|
|
2020
|
+
function guardOperation(state, run) {
|
|
2021
|
+
return state.scope ? state.scope(run) : run();
|
|
2022
|
+
}
|
|
2023
|
+
function enterGuard(value, state) {
|
|
2024
|
+
if (value === null || typeof value !== "object") return value;
|
|
2025
|
+
if (state.seen.has(value)) {
|
|
2026
|
+
state.cyclic.add(value);
|
|
2027
|
+
return state.seen.get(value);
|
|
2028
|
+
}
|
|
2029
|
+
if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) {
|
|
2030
|
+
let reader;
|
|
2031
|
+
const gate = state.gate;
|
|
2032
|
+
let finished = false;
|
|
2033
|
+
const close = () => {
|
|
2034
|
+
if (finished) return;
|
|
2035
|
+
finished = true;
|
|
2036
|
+
try {
|
|
2037
|
+
const cancelled = guardOperation(state, () => reader ? reader.cancel() : value.cancel());
|
|
2038
|
+
if (cancelled && typeof cancelled.then === "function") cancelled.then(undefined, () => {});
|
|
2039
|
+
} catch {}
|
|
2040
|
+
};
|
|
2041
|
+
const guardedStream = new ReadableStream({
|
|
2042
|
+
async pull(controller) {
|
|
2043
|
+
try {
|
|
2044
|
+
if (gate && !finished && !gate.wantsMore()) await gate.awaitDemand();
|
|
2045
|
+
if (finished) {
|
|
2046
|
+
controller.close();
|
|
2047
|
+
return;
|
|
2048
|
+
}
|
|
2049
|
+
if (!reader) reader = guardOperation(state, () => value.getReader());
|
|
2050
|
+
const {
|
|
2051
|
+
done,
|
|
2052
|
+
value: chunk
|
|
2053
|
+
} = await guardOperation(state, () => reader.read());
|
|
2054
|
+
done ? controller.close() : controller.enqueue(guardOperation(state, () => guardFailures(chunk, state)));
|
|
2055
|
+
} catch (error) {
|
|
2056
|
+
controller.error(guardOperation(state, () => wireServerFunctionError(error, "channel")));
|
|
2057
|
+
}
|
|
2058
|
+
},
|
|
2059
|
+
cancel(reason) {
|
|
2060
|
+
finished = true;
|
|
2061
|
+
return guardOperation(state, () => reader ? reader.cancel(reason) : value.cancel(reason));
|
|
2062
|
+
}
|
|
2063
|
+
});
|
|
2064
|
+
if (gate) gate.onOpen(close);
|
|
2065
|
+
state.seen.set(value, guardedStream);
|
|
2066
|
+
return guardedStream;
|
|
2067
|
+
}
|
|
2068
|
+
if (typeof value.then === "function") {
|
|
2069
|
+
const guardedPromise = Promise.resolve(value).then(resolved => guardOperation(state, () => guardFailures(resolved, state)), error => {
|
|
2070
|
+
throw guardOperation(state, () => wireServerFunctionError(error, "channel"));
|
|
2071
|
+
});
|
|
2072
|
+
guardedPromise.catch(() => {});
|
|
2073
|
+
state.seen.set(value, guardedPromise);
|
|
2074
|
+
return guardedPromise;
|
|
2075
|
+
}
|
|
2076
|
+
if (typeof value[Symbol.asyncIterator] === "function") {
|
|
2077
|
+
const source = value;
|
|
2078
|
+
const gate = state.gate;
|
|
2079
|
+
const guardedIterable = {
|
|
2080
|
+
[Symbol.asyncIterator]() {
|
|
2081
|
+
const iterator = guardOperation(state, () => source[Symbol.asyncIterator]());
|
|
2082
|
+
let finished = false;
|
|
2083
|
+
const close = () => {
|
|
2084
|
+
if (finished) return;
|
|
2085
|
+
finished = true;
|
|
2086
|
+
try {
|
|
2087
|
+
const returned = iterator.return && guardOperation(state, () => iterator.return());
|
|
2088
|
+
if (returned && typeof returned.then === "function") returned.then(undefined, () => {});
|
|
2089
|
+
} catch {}
|
|
2090
|
+
};
|
|
2091
|
+
if (gate) gate.onOpen(close);
|
|
2092
|
+
const step = () => finished ? Promise.resolve({
|
|
2093
|
+
done: true,
|
|
2094
|
+
value: undefined
|
|
2095
|
+
}) : guardOperation(state, () => iterator.next()).then(step => {
|
|
2096
|
+
if (step.done) {
|
|
2097
|
+
finished = true;
|
|
2098
|
+
return step;
|
|
2099
|
+
}
|
|
2100
|
+
return {
|
|
2101
|
+
done: false,
|
|
2102
|
+
value: guardOperation(state, () => guardFailures(step.value, state))
|
|
2103
|
+
};
|
|
2104
|
+
}, error => {
|
|
2105
|
+
throw guardOperation(state, () => wireServerFunctionError(error, "channel"));
|
|
2106
|
+
});
|
|
2107
|
+
return {
|
|
2108
|
+
next: () => finished || !gate || gate.wantsMore() ? step() : gate.awaitDemand().then(step),
|
|
2109
|
+
return: () => {
|
|
2110
|
+
close();
|
|
2111
|
+
return Promise.resolve({
|
|
2112
|
+
done: true,
|
|
2113
|
+
value: undefined
|
|
2114
|
+
});
|
|
2115
|
+
}
|
|
2116
|
+
};
|
|
2117
|
+
}
|
|
2118
|
+
};
|
|
2119
|
+
state.seen.set(value, guardedIterable);
|
|
2120
|
+
return guardedIterable;
|
|
2121
|
+
}
|
|
2122
|
+
if (state.scope && typeof value[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value)) {
|
|
2123
|
+
const scopedIterable = scopeDeferredResult(value, state.scope);
|
|
2124
|
+
state.seen.set(value, scopedIterable);
|
|
2125
|
+
return scopedIterable;
|
|
2126
|
+
}
|
|
2127
|
+
if (Array.isArray(value)) {
|
|
2128
|
+
const next = value.slice();
|
|
2129
|
+
state.seen.set(value, next);
|
|
2130
|
+
return new Frame(ARRAY, value, next, value, null);
|
|
2131
|
+
}
|
|
2132
|
+
if (value instanceof Map) {
|
|
2133
|
+
const next = new Map();
|
|
2134
|
+
state.seen.set(value, next);
|
|
2135
|
+
const items = [];
|
|
2136
|
+
for (const entry of value) items.push(entry[0], entry[1]);
|
|
2137
|
+
return new Frame(MAP, value, next, items, null);
|
|
2138
|
+
}
|
|
2139
|
+
if (value instanceof Set) {
|
|
2140
|
+
const next = new Set();
|
|
2141
|
+
state.seen.set(value, next);
|
|
2142
|
+
return new Frame(SET, value, next, [...value], null);
|
|
2143
|
+
}
|
|
2144
|
+
const prototype = Object.getPrototypeOf(value);
|
|
2145
|
+
if (prototype !== Object.prototype && prototype !== null && !(value instanceof Error)) {
|
|
2146
|
+
state.seen.set(value, value);
|
|
2147
|
+
return value;
|
|
2148
|
+
}
|
|
2149
|
+
const descriptors = Object.getOwnPropertyDescriptors(value);
|
|
2150
|
+
for (const key of Object.keys(descriptors)) {
|
|
2151
|
+
descriptors[key].configurable = true;
|
|
2152
|
+
if ("value" in descriptors[key]) descriptors[key].writable = true;
|
|
2153
|
+
}
|
|
2154
|
+
const next = Object.create(prototype, descriptors);
|
|
2155
|
+
state.seen.set(value, next);
|
|
2156
|
+
const children = !(value instanceof Error) ? Object.keys(value) : Object.getOwnPropertyNames(value).filter(key => {
|
|
2157
|
+
const descriptor = descriptors[key];
|
|
2158
|
+
return descriptor.enumerable || "value" in descriptor;
|
|
2159
|
+
});
|
|
2160
|
+
return new Frame(OBJECT, value, next, children, descriptors);
|
|
2161
|
+
}
|
|
2162
|
+
function keepGuarded(value, next, changed, state) {
|
|
2163
|
+
if (changed || state.cyclic.has(value)) return next;
|
|
2164
|
+
state.seen.set(value, value);
|
|
2165
|
+
return value;
|
|
2166
|
+
}
|
|
2167
|
+
function serializeResponseStream(value, codecOptions, signal, scope, live) {
|
|
2168
|
+
let closed = false;
|
|
2169
|
+
const frame = live ? payload => {
|
|
2170
|
+
const id = live.pending;
|
|
2171
|
+
live.pending = undefined;
|
|
2172
|
+
return createEventChunk(payload, id);
|
|
2173
|
+
} : createChunk;
|
|
2174
|
+
let stopLive = null;
|
|
2175
|
+
const stopHeartbeat = () => {
|
|
2176
|
+
if (stopLive !== null) {
|
|
2177
|
+
stopLive();
|
|
2178
|
+
stopLive = null;
|
|
2179
|
+
}
|
|
2180
|
+
};
|
|
2181
|
+
let streamController = null;
|
|
2182
|
+
let demandWaiters = null;
|
|
2183
|
+
const wantsMore = () => streamController !== null && streamController.desiredSize > 0;
|
|
2184
|
+
const awaitDemand = () => new Promise(resolve => (demandWaiters ??= []).push(resolve));
|
|
2185
|
+
const supplyDemand = () => {
|
|
2186
|
+
const resolvers = demandWaiters;
|
|
2187
|
+
demandWaiters = null;
|
|
2188
|
+
if (resolvers) for (const resolve of resolvers) resolve();
|
|
2189
|
+
};
|
|
2190
|
+
const sourceClosers = new Set();
|
|
2191
|
+
const gate = {
|
|
2192
|
+
wantsMore,
|
|
2193
|
+
awaitDemand,
|
|
2194
|
+
onOpen(close) {
|
|
2195
|
+
if (closed) close();else sourceClosers.add(close);
|
|
2196
|
+
}
|
|
2197
|
+
};
|
|
2198
|
+
const guardState = {
|
|
2199
|
+
seen: new WeakMap(),
|
|
2200
|
+
cyclic: new WeakSet(),
|
|
2201
|
+
gate,
|
|
2202
|
+
scope
|
|
2203
|
+
};
|
|
2204
|
+
value = guardOperation(guardState, () => guardFailures(value, guardState));
|
|
2205
|
+
let cancelSerialize = null;
|
|
2206
|
+
let onAbort = null;
|
|
2207
|
+
const finishSource = () => {
|
|
2208
|
+
for (const close of sourceClosers) close();
|
|
2209
|
+
sourceClosers.clear();
|
|
2210
|
+
supplyDemand();
|
|
2211
|
+
};
|
|
2212
|
+
const teardown = () => {
|
|
2213
|
+
if (closed) return;
|
|
2214
|
+
closed = true;
|
|
2215
|
+
stopHeartbeat();
|
|
2216
|
+
if (onAbort) signal.removeEventListener("abort", onAbort);
|
|
2217
|
+
if (cancelSerialize) cancelSerialize();
|
|
2218
|
+
finishSource();
|
|
2219
|
+
};
|
|
2220
|
+
return new ReadableStream({
|
|
2221
|
+
async start(controller) {
|
|
2222
|
+
streamController = controller;
|
|
2223
|
+
if (live) stopLive = armLiveBody(controller, teardown);
|
|
2224
|
+
if (signal) {
|
|
2225
|
+
if (signal.aborted) {
|
|
2226
|
+
teardown();
|
|
2227
|
+
controller.close();
|
|
2228
|
+
return;
|
|
2229
|
+
}
|
|
2230
|
+
onAbort = () => {
|
|
2231
|
+
const alreadyClosed = closed;
|
|
2232
|
+
teardown();
|
|
2233
|
+
if (!alreadyClosed) {
|
|
2234
|
+
try {
|
|
2235
|
+
controller.error(signal.reason || new Error("The operation was aborted."));
|
|
2236
|
+
} catch {}
|
|
2237
|
+
}
|
|
2238
|
+
};
|
|
2239
|
+
signal.addEventListener("abort", onAbort);
|
|
2240
|
+
}
|
|
2241
|
+
const {
|
|
2242
|
+
serializeJSON
|
|
2243
|
+
} = await import('@solidjs/web/serialization');
|
|
2244
|
+
if (closed) {
|
|
2245
|
+
try {
|
|
2246
|
+
controller.close();
|
|
2247
|
+
} catch {}
|
|
2248
|
+
return;
|
|
2249
|
+
}
|
|
2250
|
+
cancelSerialize = serializeJSON(value, {
|
|
2251
|
+
...codecOptions,
|
|
2252
|
+
onParse(node) {
|
|
2253
|
+
if (!closed) controller.enqueue(frame(JSON.stringify(node)));
|
|
2254
|
+
},
|
|
2255
|
+
onDone() {
|
|
2256
|
+
if (closed) return;
|
|
2257
|
+
closed = true;
|
|
2258
|
+
stopHeartbeat();
|
|
2259
|
+
if (onAbort) signal.removeEventListener("abort", onAbort);
|
|
2260
|
+
finishSource();
|
|
2261
|
+
controller.close();
|
|
2262
|
+
},
|
|
2263
|
+
onError(error) {
|
|
2264
|
+
if (closed) return;
|
|
2265
|
+
closed = true;
|
|
2266
|
+
stopHeartbeat();
|
|
2267
|
+
if (onAbort) signal.removeEventListener("abort", onAbort);
|
|
2268
|
+
finishSource();
|
|
2269
|
+
try {
|
|
2270
|
+
const delivered = wireServerFunctionError(DEV && error instanceof Error ? new Error(`Server function result could not be encoded: ${error.message}`) : error, "channel");
|
|
2271
|
+
controller.enqueue(frame(encodeErrorTrailer(delivered)));
|
|
2272
|
+
controller.close();
|
|
2273
|
+
} catch {
|
|
2274
|
+
try {
|
|
2275
|
+
controller.error(error);
|
|
2276
|
+
} catch {}
|
|
2277
|
+
}
|
|
2278
|
+
}
|
|
2279
|
+
});
|
|
2280
|
+
},
|
|
2281
|
+
pull() {
|
|
2282
|
+
supplyDemand();
|
|
2283
|
+
},
|
|
2284
|
+
cancel() {
|
|
2285
|
+
teardown();
|
|
2286
|
+
}
|
|
2287
|
+
});
|
|
2288
|
+
}
|
|
2289
|
+
function serializedResponse(value, headers, codec, signal, scope) {
|
|
809
2290
|
headers.set(BODY_FORMAT_HEADER, BodyFormat.Serialized);
|
|
810
2291
|
headers.set("Content-Type", "text/plain");
|
|
811
|
-
return new Response(
|
|
2292
|
+
return new Response(serializeResponseStream(value, codec, signal, scope), {
|
|
812
2293
|
headers
|
|
813
2294
|
});
|
|
814
2295
|
}
|
|
815
|
-
|
|
2296
|
+
const LIVE_HEARTBEAT_INTERVAL = 20000;
|
|
2297
|
+
function armLiveBody(controller, teardown) {
|
|
2298
|
+
let stopped = false;
|
|
2299
|
+
const heartbeat = setInterval(() => {
|
|
2300
|
+
if (stopped) return;
|
|
2301
|
+
try {
|
|
2302
|
+
controller.enqueue(EVENT_STREAM_HEARTBEAT);
|
|
2303
|
+
} catch {}
|
|
2304
|
+
}, LIVE_HEARTBEAT_INTERVAL);
|
|
2305
|
+
if (typeof heartbeat === "object" && heartbeat && typeof heartbeat.unref === "function") heartbeat.unref();
|
|
2306
|
+
let chaos = null;
|
|
2307
|
+
if (DEV && config.chaosReconnectEvery > 0) {
|
|
2308
|
+
chaos = setTimeout(() => {
|
|
2309
|
+
if (stopped) return;
|
|
2310
|
+
teardown();
|
|
2311
|
+
try {
|
|
2312
|
+
controller.error(new Error("Live response ended by the chaos knob."));
|
|
2313
|
+
} catch {}
|
|
2314
|
+
}, config.chaosReconnectEvery);
|
|
2315
|
+
if (typeof chaos === "object" && chaos && typeof chaos.unref === "function") chaos.unref();
|
|
2316
|
+
}
|
|
2317
|
+
return () => {
|
|
2318
|
+
if (stopped) return;
|
|
2319
|
+
stopped = true;
|
|
2320
|
+
clearInterval(heartbeat);
|
|
2321
|
+
if (chaos !== null) clearTimeout(chaos);
|
|
2322
|
+
};
|
|
2323
|
+
}
|
|
2324
|
+
function liveSource(value, lastEventId, position, scope) {
|
|
2325
|
+
const digestOf = v => scope ? scope(() => positionDigest(v)) : positionDigest(v);
|
|
2326
|
+
if (value === null || typeof value !== "object" || typeof value[Symbol.asyncIterator] !== "function") {
|
|
2327
|
+
const digest = digestOf(value);
|
|
2328
|
+
if (digest !== undefined && digest === lastEventId) return async function* () {}();
|
|
2329
|
+
position.pending = digest;
|
|
2330
|
+
return value;
|
|
2331
|
+
}
|
|
2332
|
+
const source = value;
|
|
2333
|
+
return {
|
|
2334
|
+
[Symbol.asyncIterator]() {
|
|
2335
|
+
const iterator = source[Symbol.asyncIterator]();
|
|
2336
|
+
let first = true;
|
|
2337
|
+
const step = () => iterator.next().then(result => {
|
|
2338
|
+
if (result.done) return result;
|
|
2339
|
+
const digest = digestOf(result.value);
|
|
2340
|
+
if (first) {
|
|
2341
|
+
first = false;
|
|
2342
|
+
if (digest !== undefined && digest === lastEventId) return step();
|
|
2343
|
+
}
|
|
2344
|
+
position.pending = digest;
|
|
2345
|
+
return result;
|
|
2346
|
+
});
|
|
2347
|
+
return {
|
|
2348
|
+
next: step,
|
|
2349
|
+
return: v => iterator.return ? iterator.return(v) : Promise.resolve({
|
|
2350
|
+
done: true,
|
|
2351
|
+
value: v
|
|
2352
|
+
}),
|
|
2353
|
+
throw: e => iterator.throw ? iterator.throw(e) : Promise.reject(e)
|
|
2354
|
+
};
|
|
2355
|
+
}
|
|
2356
|
+
};
|
|
2357
|
+
}
|
|
2358
|
+
function encodeLiveResult(value, headers, status, codec, request, scope) {
|
|
2359
|
+
if (NULL_BODY_STATUSES.has(status) || value === undefined || getHeadersAndBody(value)) {
|
|
2360
|
+
return encodeResult(value, headers, status, codec, request.signal, scope);
|
|
2361
|
+
}
|
|
2362
|
+
const position = {
|
|
2363
|
+
pending: undefined
|
|
2364
|
+
};
|
|
2365
|
+
const source = liveSource(value, request.headers.get(LAST_EVENT_ID_HEADER), position, scope);
|
|
2366
|
+
headers.set(BODY_FORMAT_HEADER, BodyFormat.Serialized);
|
|
2367
|
+
headers.set("Content-Type", "text/event-stream");
|
|
2368
|
+
headers.set("Cache-Control", "no-store");
|
|
2369
|
+
headers.set("X-Accel-Buffering", "no");
|
|
2370
|
+
try {
|
|
2371
|
+
return new Response(serializeResponseStream(source, codec, request.signal, scope, position), {
|
|
2372
|
+
status,
|
|
2373
|
+
headers
|
|
2374
|
+
});
|
|
2375
|
+
} catch (error) {
|
|
2376
|
+
throw DEV && error instanceof Error ? new Error(`Server function result could not be encoded: ${error.message}`) : error;
|
|
2377
|
+
}
|
|
2378
|
+
}
|
|
2379
|
+
function encodeResult(value, headers, status, codec, signal, scope) {
|
|
2380
|
+
if (NULL_BODY_STATUSES.has(status)) {
|
|
2381
|
+
if (value === undefined || value === null) {
|
|
2382
|
+
headers.set(BODY_FORMAT_HEADER, BodyFormat.Void);
|
|
2383
|
+
return new Response(null, {
|
|
2384
|
+
status,
|
|
2385
|
+
headers
|
|
2386
|
+
});
|
|
2387
|
+
}
|
|
2388
|
+
const error = new Error(`Server function answered status ${status}, which forbids a response body, with a value. ` + `Return respond(undefined, { status: ${status} }) for a bodiless answer, or drop the ` + `status to send the value.`);
|
|
2389
|
+
headers.set(ERROR_HEADER, encodeErrorHeaderValue(error.message));
|
|
2390
|
+
return encodeResult(error, headers, 500, codec, signal, scope);
|
|
2391
|
+
}
|
|
816
2392
|
const direct = getHeadersAndBody(value);
|
|
817
2393
|
if (direct) {
|
|
818
2394
|
for (const [key, val] of Object.entries(direct.headers || {})) {
|
|
@@ -824,80 +2400,374 @@ function encodeResult(value, headers, status, codec) {
|
|
|
824
2400
|
});
|
|
825
2401
|
}
|
|
826
2402
|
if (value === undefined) {
|
|
2403
|
+
headers.set(BODY_FORMAT_HEADER, BodyFormat.Void);
|
|
827
2404
|
return new Response(null, {
|
|
828
2405
|
status,
|
|
829
2406
|
headers
|
|
830
2407
|
});
|
|
831
2408
|
}
|
|
832
2409
|
try {
|
|
833
|
-
|
|
2410
|
+
const jsonSafe = scope ? scope(() => isJSONSafe(value)) : isJSONSafe(value);
|
|
2411
|
+
if (jsonSafe) {
|
|
834
2412
|
headers.set(BODY_FORMAT_HEADER, BodyFormat.Json);
|
|
835
2413
|
headers.set("Content-Type", "application/json");
|
|
836
|
-
|
|
2414
|
+
const body = scope ? scope(() => JSON.stringify(value)) : JSON.stringify(value);
|
|
2415
|
+
return new Response(body, {
|
|
837
2416
|
status,
|
|
838
2417
|
headers
|
|
839
2418
|
});
|
|
840
2419
|
}
|
|
841
2420
|
} catch {
|
|
842
2421
|
}
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
status,
|
|
846
|
-
|
|
847
|
-
|
|
2422
|
+
try {
|
|
2423
|
+
const response = serializedResponse(value, headers, codec, signal, scope);
|
|
2424
|
+
return status === 200 ? response : new Response(response.body, {
|
|
2425
|
+
status,
|
|
2426
|
+
headers
|
|
2427
|
+
});
|
|
2428
|
+
} catch (error) {
|
|
2429
|
+
throw DEV && error instanceof Error ? new Error(`Server function result could not be encoded: ${error.message}`) : error;
|
|
2430
|
+
}
|
|
2431
|
+
}
|
|
2432
|
+
const ERROR_HEADER_VALUE_LIMIT = 1024;
|
|
2433
|
+
function boundedErrorHeaderValue(message) {
|
|
2434
|
+
let label = message.length > 256 ? message.slice(0, 256) : message;
|
|
2435
|
+
let encoded = encodeErrorHeaderValue(label);
|
|
2436
|
+
while (encoded.length > ERROR_HEADER_VALUE_LIMIT && label.length > 1) {
|
|
2437
|
+
label = label.slice(0, Math.ceil(label.length / 2));
|
|
2438
|
+
encoded = encodeErrorHeaderValue(label);
|
|
2439
|
+
}
|
|
2440
|
+
return encoded;
|
|
848
2441
|
}
|
|
849
2442
|
const GENERIC_SERVER_ERROR_MESSAGE = "Internal Server Error";
|
|
850
2443
|
let DEV = false === true;
|
|
851
2444
|
function setServerFunctionsDev(dev) {
|
|
852
2445
|
DEV = !!dev;
|
|
853
2446
|
}
|
|
2447
|
+
const REQUEST_ERROR_HOOKS = new WeakMap();
|
|
2448
|
+
function siteFor(handling, event, direct) {
|
|
2449
|
+
const invocation = event ? INVOCATIONS.get(event) : undefined;
|
|
2450
|
+
const site = {
|
|
2451
|
+
kind: "server-function",
|
|
2452
|
+
handling,
|
|
2453
|
+
direct
|
|
2454
|
+
};
|
|
2455
|
+
if (invocation) site.functionId = invocation.id;
|
|
2456
|
+
if (event) site.event = event;
|
|
2457
|
+
return site;
|
|
2458
|
+
}
|
|
2459
|
+
function wireServerFunctionError(value, handling, event = currentEvent()) {
|
|
2460
|
+
const report = reportServerError(value, siteFor(handling, event, false), null, event ? REQUEST_ERROR_HOOKS.get(event) : undefined);
|
|
2461
|
+
return report.mapped ? report.value : sanitizeServerError(value);
|
|
2462
|
+
}
|
|
2463
|
+
function currentEvent() {
|
|
2464
|
+
const store = globalThis[RequestContext];
|
|
2465
|
+
return store ? store.getStore() : undefined;
|
|
2466
|
+
}
|
|
2467
|
+
function reportDirectFailure(run, id) {
|
|
2468
|
+
const report = error => {
|
|
2469
|
+
reportServerError(error, {
|
|
2470
|
+
kind: "server-function",
|
|
2471
|
+
handling: "thrown",
|
|
2472
|
+
functionId: id,
|
|
2473
|
+
direct: true
|
|
2474
|
+
}, null);
|
|
2475
|
+
throw error;
|
|
2476
|
+
};
|
|
2477
|
+
let result;
|
|
2478
|
+
try {
|
|
2479
|
+
result = run();
|
|
2480
|
+
} catch (error) {
|
|
2481
|
+
report(error);
|
|
2482
|
+
}
|
|
2483
|
+
return result && typeof result.then === "function" ? result.then(undefined, report) : result;
|
|
2484
|
+
}
|
|
854
2485
|
function sanitizeServerError(value) {
|
|
855
2486
|
if (DEV) return value;
|
|
856
2487
|
if (isSafeError(value)) return value;
|
|
857
|
-
|
|
2488
|
+
const wire = new Error(GENERIC_SERVER_ERROR_MESSAGE);
|
|
2489
|
+
return wire;
|
|
2490
|
+
}
|
|
2491
|
+
function serverFunctionUrl(fn, ...args) {
|
|
2492
|
+
return serverFunctionUrlFor(config.endpoint, fn, args);
|
|
2493
|
+
}
|
|
2494
|
+
function serverFunctionActionUrl(fn, ...boundArgs) {
|
|
2495
|
+
return serverFunctionActionUrlFor(config.endpoint, fn, boundArgs);
|
|
2496
|
+
}
|
|
2497
|
+
function parseServerFunctionActionUrl(url) {
|
|
2498
|
+
const parsed = parseServerFunctionAddress(new URL(url, "http://localhost").pathname, config.endpoint);
|
|
2499
|
+
return parsed && parsed.id;
|
|
2500
|
+
}
|
|
2501
|
+
async function matchesOrigin(origin, request, matcher) {
|
|
2502
|
+
if (matcher === undefined) return origin === new URL(request.url).origin;
|
|
2503
|
+
if (typeof matcher === "function") return (await matcher(origin, request)) === true;
|
|
2504
|
+
return Array.isArray(matcher) ? matcher.includes(origin) : origin === matcher;
|
|
2505
|
+
}
|
|
2506
|
+
async function allowsServerFunctionRequest(request, options) {
|
|
2507
|
+
const fetchSite = request.headers.get("Sec-Fetch-Site");
|
|
2508
|
+
if (fetchSite === "same-origin") return true;
|
|
2509
|
+
if (fetchSite === "none") return false;
|
|
2510
|
+
const origin = request.headers.get("Origin");
|
|
2511
|
+
if (fetchSite === "same-site" || fetchSite === "cross-site") {
|
|
2512
|
+
if (origin === null || options.origin === undefined) return false;
|
|
2513
|
+
return (await matchesOrigin(origin, request, options.origin)) ? origin : false;
|
|
2514
|
+
}
|
|
2515
|
+
if (origin !== null) {
|
|
2516
|
+
if (!(await matchesOrigin(origin, request, options.origin))) return false;
|
|
2517
|
+
return origin === new URL(request.url).origin ? true : origin;
|
|
2518
|
+
}
|
|
2519
|
+
const referer = request.headers.get("Referer");
|
|
2520
|
+
if (referer !== null) {
|
|
2521
|
+
try {
|
|
2522
|
+
return matchesOrigin(new URL(referer).origin, request, options.origin);
|
|
2523
|
+
} catch {
|
|
2524
|
+
return false;
|
|
2525
|
+
}
|
|
2526
|
+
}
|
|
2527
|
+
return options.allowRequestsWithoutOriginCheck === true;
|
|
2528
|
+
}
|
|
2529
|
+
const CSRF_VARY = ["Sec-Fetch-Site", "Origin", "Referer"];
|
|
2530
|
+
function appendVary(headers, names) {
|
|
2531
|
+
const current = headers.get("Vary");
|
|
2532
|
+
if (current === "*") return;
|
|
2533
|
+
const values = current ? current.split(",").map(value => value.trim()) : [];
|
|
2534
|
+
const seen = new Set(values.map(value => value.toLowerCase()));
|
|
2535
|
+
for (const name of names) {
|
|
2536
|
+
if (!seen.has(name.toLowerCase())) values.push(name);
|
|
2537
|
+
}
|
|
2538
|
+
headers.set("Vary", values.join(", "));
|
|
2539
|
+
}
|
|
2540
|
+
function withHeaders(response, write) {
|
|
2541
|
+
try {
|
|
2542
|
+
write(response.headers);
|
|
2543
|
+
return response;
|
|
2544
|
+
} catch {
|
|
2545
|
+
const headers = new Headers(response.headers);
|
|
2546
|
+
write(headers);
|
|
2547
|
+
return new Response(response.body, {
|
|
2548
|
+
status: response.status,
|
|
2549
|
+
statusText: response.statusText,
|
|
2550
|
+
headers
|
|
2551
|
+
});
|
|
2552
|
+
}
|
|
2553
|
+
}
|
|
2554
|
+
function withCSRFVary(response) {
|
|
2555
|
+
return withHeaders(response, headers => appendVary(headers, CSRF_VARY));
|
|
2556
|
+
}
|
|
2557
|
+
const TRANSPORT_REQUEST_HEADERS = ["Content-Type", BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER].join(", ");
|
|
2558
|
+
const PREFLIGHT_MAX_AGE = "600";
|
|
2559
|
+
const CORS_SAFELISTED_RESPONSE_HEADERS = new Set(["cache-control", "content-language", "content-length", "content-type", "expires", "last-modified", "pragma"]);
|
|
2560
|
+
function withCORS(response, cors) {
|
|
2561
|
+
if (cors === null) return response;
|
|
2562
|
+
return withHeaders(response, headers => {
|
|
2563
|
+
headers.set("Access-Control-Allow-Origin", cors.origin);
|
|
2564
|
+
if (cors.credentials) headers.set("Access-Control-Allow-Credentials", "true");
|
|
2565
|
+
const exposed = [];
|
|
2566
|
+
for (const name of headers.keys()) {
|
|
2567
|
+
if (CORS_SAFELISTED_RESPONSE_HEADERS.has(name) || name === "set-cookie" || name === "vary" || name.startsWith("access-control-")) {
|
|
2568
|
+
continue;
|
|
2569
|
+
}
|
|
2570
|
+
exposed.push(name);
|
|
2571
|
+
}
|
|
2572
|
+
if (exposed.length > 0) headers.set("Access-Control-Expose-Headers", exposed.join(", "));
|
|
2573
|
+
appendVary(headers, ["Origin"]);
|
|
2574
|
+
});
|
|
2575
|
+
}
|
|
2576
|
+
function preflightResponse(request) {
|
|
2577
|
+
const requested = request.headers.get("Access-Control-Request-Headers");
|
|
2578
|
+
const response = new Response(null, {
|
|
2579
|
+
status: 204,
|
|
2580
|
+
headers: {
|
|
2581
|
+
"Access-Control-Allow-Methods": "POST, GET, HEAD",
|
|
2582
|
+
"Access-Control-Allow-Headers": requested !== null && requested.trim() !== "" ? requested : TRANSPORT_REQUEST_HEADERS,
|
|
2583
|
+
"Access-Control-Max-Age": PREFLIGHT_MAX_AGE,
|
|
2584
|
+
"Cache-Control": "no-store"
|
|
2585
|
+
}
|
|
2586
|
+
});
|
|
2587
|
+
appendVary(response.headers, ["Access-Control-Request-Method", "Access-Control-Request-Headers"]);
|
|
2588
|
+
return response;
|
|
2589
|
+
}
|
|
2590
|
+
function forbiddenResponse() {
|
|
2591
|
+
return withCSRFVary(new Response(DEV ? "Forbidden" : null, {
|
|
2592
|
+
status: 403,
|
|
2593
|
+
headers: {
|
|
2594
|
+
"Cache-Control": "no-store"
|
|
2595
|
+
}
|
|
2596
|
+
}));
|
|
2597
|
+
}
|
|
2598
|
+
function nativePromise(value) {
|
|
2599
|
+
if (value instanceof Promise) return value;
|
|
2600
|
+
try {
|
|
2601
|
+
if (Object.prototype.toString.call(value) === "[object Promise]") return Promise.prototype.then.call(value, value => value);
|
|
2602
|
+
} catch {}
|
|
858
2603
|
}
|
|
859
2604
|
async function handleServerFunctionRequest(request, options = {}) {
|
|
860
|
-
const codec =
|
|
2605
|
+
const codec = {
|
|
2606
|
+
...(options.codec !== undefined ? options.codec : getServerFunctionsCodec())
|
|
2607
|
+
};
|
|
2608
|
+
codec.serializeErrorStacks ??= DEV;
|
|
861
2609
|
const url = new URL(request.url);
|
|
862
|
-
const
|
|
863
|
-
const
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
2610
|
+
const method = request.method;
|
|
2611
|
+
const address = resolveAddress(url);
|
|
2612
|
+
const functionId = address && address.id;
|
|
2613
|
+
const declaredRead = (method === "GET" || method === "HEAD") && functionId !== null && declaresRead(functionId);
|
|
2614
|
+
const csrf = options.csrf !== undefined ? options.csrf : config.csrf;
|
|
2615
|
+
const protectsRequest = csrf !== false && (!declaredRead || CARRIED.has(functionId) || typeof csrf === "object" && csrf.protectDeclaredReads === true);
|
|
2616
|
+
const csrfOptions = csrf === true ? {} : csrf;
|
|
2617
|
+
let verdict = true;
|
|
2618
|
+
let readVariesByOrigin = false;
|
|
2619
|
+
if (protectsRequest) {
|
|
2620
|
+
verdict = await allowsServerFunctionRequest(request, csrfOptions);
|
|
2621
|
+
} else if (csrfOptions !== false && csrfOptions.origin !== undefined) {
|
|
2622
|
+
readVariesByOrigin = true;
|
|
2623
|
+
const admitted = await allowsServerFunctionRequest(request, csrfOptions);
|
|
2624
|
+
if (typeof admitted === "string") verdict = admitted;
|
|
2625
|
+
}
|
|
2626
|
+
const cors = typeof verdict === "string" ? {
|
|
2627
|
+
origin: verdict,
|
|
2628
|
+
credentials: csrfOptions.allowCredentials === true
|
|
2629
|
+
} : null;
|
|
2630
|
+
const finish = response => {
|
|
2631
|
+
const finalized = withCORS(finalizeTransportResponse(response, method), cors);
|
|
2632
|
+
return readVariesByOrigin && cors === null ? withHeaders(finalized, headers => appendVary(headers, ["Origin"])) : finalized;
|
|
2633
|
+
};
|
|
2634
|
+
if (cors !== null && method === "OPTIONS" && request.headers.has("Access-Control-Request-Method")) {
|
|
2635
|
+
return finish(preflightResponse(request));
|
|
868
2636
|
}
|
|
869
2637
|
let serverFunction;
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
2638
|
+
if (functionId) {
|
|
2639
|
+
try {
|
|
2640
|
+
serverFunction = getServerFunction(functionId);
|
|
2641
|
+
} catch {
|
|
2642
|
+
return finish(new Response(DEV ? `Unknown server function: ${functionId}` : null, {
|
|
2643
|
+
status: 404,
|
|
2644
|
+
headers: {
|
|
2645
|
+
[UNKNOWN_HEADER]: "true"
|
|
2646
|
+
}
|
|
2647
|
+
}));
|
|
2648
|
+
}
|
|
2649
|
+
}
|
|
2650
|
+
if (verdict === false) {
|
|
2651
|
+
return finish(forbiddenResponse());
|
|
2652
|
+
}
|
|
2653
|
+
if (!functionId) {
|
|
2654
|
+
const response = new Response(DEV ? "Server function not found" : null, {
|
|
874
2655
|
status: 404
|
|
875
2656
|
});
|
|
2657
|
+
return finish(protectsRequest ? withCSRFVary(response) : response);
|
|
876
2658
|
}
|
|
877
|
-
|
|
878
|
-
|
|
2659
|
+
const scripted = address.data || address.live;
|
|
2660
|
+
const live = address.live;
|
|
2661
|
+
if (method !== "POST" && !declaredRead) {
|
|
2662
|
+
const response = new Response(DEV ? `Method not allowed for server function: ${functionId}` : null, {
|
|
879
2663
|
status: 405,
|
|
880
2664
|
headers: {
|
|
881
|
-
Allow: "POST"
|
|
2665
|
+
Allow: declaresRead(functionId) ? "POST, GET, HEAD" : "POST"
|
|
882
2666
|
}
|
|
883
2667
|
});
|
|
2668
|
+
return finish(protectsRequest ? withCSRFVary(response) : response);
|
|
884
2669
|
}
|
|
885
|
-
const
|
|
886
|
-
|
|
887
|
-
|
|
2670
|
+
const bodySizeLimit = options.bodySizeLimit !== undefined ? options.bodySizeLimit : config.bodySizeLimit;
|
|
2671
|
+
const argsEncoding = url.searchParams.get("args");
|
|
2672
|
+
if (argsEncoding !== null && argsEncoding.length > bodySizeLimit) {
|
|
2673
|
+
const response = new Response(DEV ? "Server function arguments exceed the configured bodySizeLimit" : null, {
|
|
2674
|
+
status: 413
|
|
2675
|
+
});
|
|
2676
|
+
return finish(protectsRequest ? withCSRFVary(response) : response);
|
|
2677
|
+
}
|
|
2678
|
+
if (method === "POST" && request.body !== null && bodySizeLimit !== Infinity) {
|
|
2679
|
+
const raw = request.headers.get("content-length");
|
|
2680
|
+
const declared = raw !== null && /^\d+$/.test(raw) ? Number(raw) : NaN;
|
|
2681
|
+
if (declared > bodySizeLimit) {
|
|
2682
|
+
const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
|
|
2683
|
+
status: 413
|
|
2684
|
+
});
|
|
2685
|
+
return finish(protectsRequest ? withCSRFVary(response) : response);
|
|
2686
|
+
}
|
|
2687
|
+
let buffered;
|
|
2688
|
+
try {
|
|
2689
|
+
buffered = await bufferBodyWithin(request, bodySizeLimit);
|
|
2690
|
+
} catch {
|
|
2691
|
+
const response = new Response(DEV ? "Malformed server function arguments" : null, {
|
|
2692
|
+
status: 400
|
|
2693
|
+
});
|
|
2694
|
+
return finish(protectsRequest ? withCSRFVary(response) : response);
|
|
2695
|
+
}
|
|
2696
|
+
if (buffered === null) {
|
|
2697
|
+
const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
|
|
2698
|
+
status: 413
|
|
2699
|
+
});
|
|
2700
|
+
return finish(protectsRequest ? withCSRFVary(response) : response);
|
|
2701
|
+
}
|
|
2702
|
+
request = withBufferedBody(request, buffered);
|
|
2703
|
+
}
|
|
2704
|
+
let event;
|
|
2705
|
+
try {
|
|
2706
|
+
event = options.createEvent ? options.createEvent(request) : {
|
|
2707
|
+
request,
|
|
2708
|
+
locals: {}
|
|
2709
|
+
};
|
|
2710
|
+
const promised = nativePromise(event);
|
|
2711
|
+
if (promised) event = await promised;
|
|
2712
|
+
} catch (error) {
|
|
2713
|
+
const safe = sanitizeServerError(error);
|
|
2714
|
+
const message = safe instanceof Error ? safe.message : String(safe);
|
|
2715
|
+
const headers = new Headers();
|
|
2716
|
+
headers.set(ERROR_HEADER, boundedErrorHeaderValue(message));
|
|
2717
|
+
const response = scripted ? encodeResult(safe, headers, 500, codec, request.signal) : new Response(DEV ? message : null, {
|
|
2718
|
+
status: 500
|
|
2719
|
+
});
|
|
2720
|
+
return finish(protectsRequest ? withCSRFVary(response) : response);
|
|
2721
|
+
}
|
|
2722
|
+
const refuseCommitted = raw => {
|
|
2723
|
+
const response = commitEventResponse(raw, event);
|
|
2724
|
+
return finish(protectsRequest ? withCSRFVary(response) : response);
|
|
888
2725
|
};
|
|
889
2726
|
const provide = options.provideEvent || provideEvent;
|
|
2727
|
+
const scope = run => provide(event, run);
|
|
2728
|
+
if (options.onError !== undefined) REQUEST_ERROR_HOOKS.set(event, options.onError);
|
|
890
2729
|
const flightHook = options.collectFlightData !== undefined ? options.collectFlightData : config.collectFlightData;
|
|
891
2730
|
const transformResult = options.transformResult !== undefined ? options.transformResult : config.transformResult;
|
|
892
|
-
const wrapInvocation = options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation;
|
|
2731
|
+
const wrapInvocation = resolveWrapInvocation(options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation);
|
|
893
2732
|
const transformFlightResult = options.transformFlightResult !== undefined ? options.transformFlightResult : config.transformFlightResult;
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
2733
|
+
let handleNoJS = options.handleNoJS !== undefined ? options.handleNoJS : config.handleNoJS;
|
|
2734
|
+
if (handleNoJS === undefined && !scripted && isFormPost(request)) {
|
|
2735
|
+
const fetchMode = request.headers.get("Sec-Fetch-Mode");
|
|
2736
|
+
if (fetchMode === null || fetchMode === "navigate") {
|
|
2737
|
+
handleNoJS = defaultNoJSHandler || (defaultNoJSHandler = createNoJSHandler());
|
|
2738
|
+
} else {
|
|
2739
|
+
const response = new Response(DEV ? "The bare server-function address answers form navigations with the " + "no-JS redirect convention. Scripted callers use the data address " + `(…/data/${functionId}) or send the ${BODY_FORMAT_HEADER} tag.` : null, {
|
|
2740
|
+
status: 400
|
|
2741
|
+
});
|
|
2742
|
+
return refuseCommitted(response);
|
|
2743
|
+
}
|
|
2744
|
+
}
|
|
2745
|
+
const flightHeader = scripted && method === "POST" ? request.headers.get(SINGLE_FLIGHT_HEADER) : null;
|
|
2746
|
+
const flightHooks = flightHeader ? [...new Set(flightHeader.split(","))].flatMap(source => {
|
|
2747
|
+
const hook = source === "true" ? flightHook : flightSources.get(source);
|
|
2748
|
+
return hook ? [[source, hook]] : [];
|
|
2749
|
+
}) : [];
|
|
2750
|
+
const collectsFlight = flightHooks.length > 0;
|
|
2751
|
+
let parsed;
|
|
2752
|
+
try {
|
|
2753
|
+
parsed = await parseArguments(request, url, scripted, codec);
|
|
2754
|
+
} catch (error) {
|
|
2755
|
+
const skewed = error !== null && typeof error === "object" && error[FORMAT_SKEW] === true;
|
|
2756
|
+
const response = new Response(DEV ? skewed ? error.message : "Malformed server function arguments" : null, {
|
|
2757
|
+
status: 400
|
|
2758
|
+
});
|
|
2759
|
+
return refuseCommitted(response);
|
|
2760
|
+
}
|
|
2761
|
+
const maxArguments = options.maxArguments !== undefined ? options.maxArguments : config.maxArguments;
|
|
2762
|
+
if (parsed.length > maxArguments) {
|
|
2763
|
+
const response = new Response(DEV ? "Server function call exceeds the configured maxArguments" : null, {
|
|
2764
|
+
status: 400
|
|
2765
|
+
});
|
|
2766
|
+
return refuseCommitted(response);
|
|
2767
|
+
}
|
|
897
2768
|
const flightContext = {
|
|
898
2769
|
id: functionId,
|
|
899
2770
|
args: parsed,
|
|
900
|
-
instance,
|
|
901
2771
|
request,
|
|
902
2772
|
collectsFlight,
|
|
903
2773
|
codec,
|
|
@@ -906,19 +2776,27 @@ async function handleServerFunctionRequest(request, options = {}) {
|
|
|
906
2776
|
const headers = new Headers();
|
|
907
2777
|
const dispatch = async () => {
|
|
908
2778
|
try {
|
|
909
|
-
|
|
2779
|
+
const invokeOnce = async () => {
|
|
910
2780
|
INVOCATIONS.set(event, {
|
|
911
|
-
id: functionId
|
|
2781
|
+
id: functionId,
|
|
2782
|
+
live: !!live
|
|
912
2783
|
});
|
|
913
2784
|
const run = () => serverFunction(...parsed);
|
|
914
|
-
return
|
|
2785
|
+
return observeInvocation({
|
|
2786
|
+
id: functionId,
|
|
2787
|
+
direct: false,
|
|
2788
|
+
event,
|
|
2789
|
+
request,
|
|
2790
|
+
args: parsed
|
|
2791
|
+
}, () => wrapInvocation ? wrapInvocation(run, {
|
|
915
2792
|
id: functionId,
|
|
916
2793
|
args: parsed,
|
|
917
2794
|
event,
|
|
918
2795
|
request,
|
|
919
2796
|
direct: false
|
|
920
|
-
}) : run();
|
|
921
|
-
}
|
|
2797
|
+
}) : run());
|
|
2798
|
+
};
|
|
2799
|
+
let result = await provideEventOnce(provide, event, invokeOnce);
|
|
922
2800
|
if (transformResult) {
|
|
923
2801
|
result = await transformResult(event, result, flightContext);
|
|
924
2802
|
}
|
|
@@ -929,25 +2807,29 @@ async function handleServerFunctionRequest(request, options = {}) {
|
|
|
929
2807
|
response,
|
|
930
2808
|
value
|
|
931
2809
|
} = result;
|
|
932
|
-
if (!
|
|
2810
|
+
if (!scripted && !handleNoJS && response && response.body) {
|
|
933
2811
|
return response;
|
|
934
2812
|
}
|
|
935
2813
|
if (response && response.headers) {
|
|
936
2814
|
mergeResponseHeaders(headers, response.headers);
|
|
937
2815
|
}
|
|
938
|
-
if (response && response.status && (
|
|
2816
|
+
if (response && response.status && (!scripted || !validRedirectStatuses.has(response.status))) {
|
|
939
2817
|
status = response.status;
|
|
2818
|
+
} else if (response && response.status) {
|
|
2819
|
+
maskRedirect(headers, response, request.url);
|
|
940
2820
|
}
|
|
941
2821
|
metadata = response;
|
|
942
2822
|
result = value;
|
|
943
2823
|
} else if (result instanceof Response) {
|
|
944
2824
|
if (result.headers && result.headers.has("X-Content-Raw")) return result;
|
|
945
|
-
if (
|
|
2825
|
+
if (scripted) {
|
|
946
2826
|
if (result.headers) {
|
|
947
2827
|
mergeResponseHeaders(headers, result.headers);
|
|
948
2828
|
}
|
|
949
|
-
if (result.status && (result.status
|
|
2829
|
+
if (result.status && !validRedirectStatuses.has(result.status)) {
|
|
950
2830
|
status = result.status;
|
|
2831
|
+
} else if (result.status) {
|
|
2832
|
+
maskRedirect(headers, result, request.url);
|
|
951
2833
|
}
|
|
952
2834
|
metadata = result;
|
|
953
2835
|
if (result.body == null) {
|
|
@@ -956,7 +2838,7 @@ async function handleServerFunctionRequest(request, options = {}) {
|
|
|
956
2838
|
}
|
|
957
2839
|
}
|
|
958
2840
|
if (collectsFlight) {
|
|
959
|
-
result = await foldFlightData(
|
|
2841
|
+
result = await foldFlightData(flightHooks, event, headers, {
|
|
960
2842
|
id: functionId,
|
|
961
2843
|
value: result,
|
|
962
2844
|
response: metadata,
|
|
@@ -965,20 +2847,41 @@ async function handleServerFunctionRequest(request, options = {}) {
|
|
|
965
2847
|
}, flightContext);
|
|
966
2848
|
if (result instanceof Response && result.headers.has("X-Content-Raw")) return result;
|
|
967
2849
|
}
|
|
968
|
-
if (!
|
|
969
|
-
if (handleNoJS)
|
|
2850
|
+
if (!scripted) {
|
|
2851
|
+
if (handleNoJS) {
|
|
2852
|
+
return handleNoJS(result == null && metadata !== undefined ? metadata : result, request, parsed);
|
|
2853
|
+
}
|
|
970
2854
|
if (result instanceof Response) return result;
|
|
971
|
-
return encodeResult(result, headers,
|
|
2855
|
+
return encodeResult(result, headers, status, codec, request.signal, scope);
|
|
972
2856
|
}
|
|
973
|
-
|
|
2857
|
+
if (status === 304) warnScripted304(functionId);
|
|
2858
|
+
if (live) return encodeLiveResult(result, headers, status, codec, request, scope);
|
|
2859
|
+
return encodeResult(result, headers, status, codec, request.signal, scope);
|
|
974
2860
|
} catch (x) {
|
|
975
|
-
|
|
976
|
-
|
|
2861
|
+
const respondThrown = value => {
|
|
2862
|
+
const safe = wireServerFunctionError(value, "thrown", event);
|
|
2863
|
+
if (!scripted) {
|
|
2864
|
+
if (handleNoJS) return handleNoJS(safe, request, parsed, true);
|
|
2865
|
+
const message = safe instanceof Error ? safe.message : String(safe);
|
|
2866
|
+
return new Response(DEV ? message : null, {
|
|
2867
|
+
status: 500
|
|
2868
|
+
});
|
|
2869
|
+
}
|
|
2870
|
+
const error = safe instanceof Error ? safe.message : typeof safe === "string" ? safe : "true";
|
|
2871
|
+
headers.set(ERROR_HEADER, boundedErrorHeaderValue(error));
|
|
2872
|
+
return encodeResult(safe, headers, 500, codec, request.signal, scope);
|
|
2873
|
+
};
|
|
2874
|
+
if (transformResult) {
|
|
2875
|
+
try {
|
|
977
2876
|
x = await transformResult(event, x, {
|
|
978
2877
|
...flightContext,
|
|
979
2878
|
thrown: true
|
|
980
2879
|
});
|
|
2880
|
+
} catch (hookError) {
|
|
2881
|
+
return respondThrown(hookError);
|
|
981
2882
|
}
|
|
2883
|
+
}
|
|
2884
|
+
if (x instanceof Response || isResponseEnvelope(x)) {
|
|
982
2885
|
let status = 200;
|
|
983
2886
|
let metadata;
|
|
984
2887
|
if (isResponseEnvelope(x)) {
|
|
@@ -989,8 +2892,10 @@ async function handleServerFunctionRequest(request, options = {}) {
|
|
|
989
2892
|
if (response && response.headers) {
|
|
990
2893
|
mergeResponseHeaders(headers, response.headers);
|
|
991
2894
|
}
|
|
992
|
-
if (response && response.status && (!
|
|
2895
|
+
if (response && response.status && (!scripted || !validRedirectStatuses.has(response.status))) {
|
|
993
2896
|
status = response.status;
|
|
2897
|
+
} else if (response && response.status) {
|
|
2898
|
+
maskRedirect(headers, response, request.url);
|
|
994
2899
|
}
|
|
995
2900
|
metadata = response;
|
|
996
2901
|
x = value;
|
|
@@ -998,8 +2903,10 @@ async function handleServerFunctionRequest(request, options = {}) {
|
|
|
998
2903
|
if (x.headers) {
|
|
999
2904
|
mergeResponseHeaders(headers, x.headers);
|
|
1000
2905
|
}
|
|
1001
|
-
if (x.status && (!
|
|
2906
|
+
if (x.status && (!scripted || !validRedirectStatuses.has(x.status))) {
|
|
1002
2907
|
status = x.status;
|
|
2908
|
+
} else if (x.status) {
|
|
2909
|
+
maskRedirect(headers, x, request.url);
|
|
1003
2910
|
}
|
|
1004
2911
|
metadata = x;
|
|
1005
2912
|
if (x.body == null) {
|
|
@@ -1007,7 +2914,7 @@ async function handleServerFunctionRequest(request, options = {}) {
|
|
|
1007
2914
|
}
|
|
1008
2915
|
}
|
|
1009
2916
|
if (collectsFlight) {
|
|
1010
|
-
x = await foldFlightData(
|
|
2917
|
+
x = await foldFlightData(flightHooks, event, headers, {
|
|
1011
2918
|
id: functionId,
|
|
1012
2919
|
value: x,
|
|
1013
2920
|
response: metadata,
|
|
@@ -1015,31 +2922,59 @@ async function handleServerFunctionRequest(request, options = {}) {
|
|
|
1015
2922
|
thrown: true
|
|
1016
2923
|
}, flightContext);
|
|
1017
2924
|
if (x instanceof Response && x.headers.has("X-Content-Raw")) {
|
|
2925
|
+
x = ownResponse(x);
|
|
1018
2926
|
x.headers.set(ERROR_HEADER, "true");
|
|
1019
2927
|
return x;
|
|
1020
2928
|
}
|
|
1021
2929
|
}
|
|
1022
2930
|
headers.set(ERROR_HEADER, "true");
|
|
1023
|
-
if (!
|
|
2931
|
+
if (!scripted) {
|
|
1024
2932
|
if (handleNoJS) return handleNoJS(x ?? metadata, request, parsed, true);
|
|
1025
2933
|
if (x instanceof Response) return x;
|
|
1026
2934
|
}
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
const safe = sanitizeServerError(x);
|
|
1030
|
-
if (!instance) {
|
|
1031
|
-
if (handleNoJS) return handleNoJS(safe, request, parsed, true);
|
|
1032
|
-
const message = safe instanceof Error ? safe.message : String(safe);
|
|
1033
|
-
return new Response(DEV ? message : null, {
|
|
1034
|
-
status: 500
|
|
1035
|
-
});
|
|
2935
|
+
if (scripted && status === 304) warnScripted304(functionId);
|
|
2936
|
+
return encodeResult(x, headers, status, codec, request.signal, scope);
|
|
1036
2937
|
}
|
|
1037
|
-
|
|
1038
|
-
headers.set(ERROR_HEADER, encodeErrorHeaderValue(error));
|
|
1039
|
-
return encodeResult(safe, headers, 200, codec);
|
|
2938
|
+
return respondThrown(x);
|
|
1040
2939
|
}
|
|
1041
2940
|
};
|
|
1042
|
-
|
|
2941
|
+
const response = commitEventResponse(enforceComposedHeaderInvariants(ownResponse(await dispatch())), event);
|
|
2942
|
+
return finish(protectsRequest ? withCSRFVary(response) : response);
|
|
2943
|
+
}
|
|
2944
|
+
function ownResponse(response) {
|
|
2945
|
+
try {
|
|
2946
|
+
return new Response(response.body, response);
|
|
2947
|
+
} catch {
|
|
2948
|
+
return response;
|
|
2949
|
+
}
|
|
2950
|
+
}
|
|
2951
|
+
function finalizeTransportResponse(response, method) {
|
|
2952
|
+
const stripBody = method === "HEAD" && response.body !== null;
|
|
2953
|
+
const defaultsCache = !response.headers.has("Cache-Control") && response.status !== 304;
|
|
2954
|
+
if (stripBody || defaultsCache) {
|
|
2955
|
+
try {
|
|
2956
|
+
if (defaultsCache) {
|
|
2957
|
+
response.headers.set("Cache-Control", "no-store");
|
|
2958
|
+
}
|
|
2959
|
+
if (!stripBody) return response;
|
|
2960
|
+
response.body.cancel().catch(() => {});
|
|
2961
|
+
return new Response(null, {
|
|
2962
|
+
status: response.status,
|
|
2963
|
+
statusText: response.statusText,
|
|
2964
|
+
headers: response.headers
|
|
2965
|
+
});
|
|
2966
|
+
} catch {
|
|
2967
|
+
const headers = new Headers(response.headers);
|
|
2968
|
+
if (defaultsCache && !headers.has("Cache-Control")) headers.set("Cache-Control", "no-store");
|
|
2969
|
+
if (stripBody) response.body.cancel().catch(() => {});
|
|
2970
|
+
return new Response(stripBody ? null : response.body, {
|
|
2971
|
+
status: response.status,
|
|
2972
|
+
statusText: response.statusText,
|
|
2973
|
+
headers
|
|
2974
|
+
});
|
|
2975
|
+
}
|
|
2976
|
+
}
|
|
2977
|
+
return response;
|
|
1043
2978
|
}
|
|
1044
2979
|
|
|
1045
|
-
export { ERROR_HEADER, FLASH_COOKIE,
|
|
2980
|
+
export { ChunkReader, ERROR_HEADER, FLASH_COOKIE, GENERIC_SERVER_ERROR_MESSAGE, GET, REDIRECT_HEADER, SERVER_FUNCTION_INVOKE, SINGLE_FLIGHT_HEADER, UNKNOWN_HEADER, armLiveBody, clearFlashCookie, configureServerFunctionsServer, createChunk, createEventChunk, createNoJSHandler, createServerReference, decodeErrorHeaderValue, decodeFlashCookie, decodeRedirectHeaderValue, decodeResponse, decodeResponsePayload, encodeErrorHeaderValue, encodeFlashCookie, foldSetCookies, frameAddress, getEventServerFunctionInvocation, getServerFunction, getServerFunctionInvocation, getServerFunctionMetadata, guardFailures, handleServerFunctionRequest, hasFlashCookie, invoke, isServerFunction, live, parseServerFunctionActionUrl, registerFlightDataSource, registerServerFunction, registerServerReference, sanitizeServerError, serializeResponseStream, serializeStream, serverFunctionActionUrl, serverFunctionUrl, setServerFunctionsDev, subscribeFlightData, textDigest, withMeta };
|