@solidjs/web 2.0.0-rc.2 → 2.0.0-rc.21
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 +5165 -0
- package/dist/server.js +1876 -374
- package/dist/{server.cjs → server.observe.js} +2070 -577
- package/dist/{dev.cjs → web.dev.js} +955 -567
- package/dist/web.js +646 -350
- package/dist/{dev.js → web.observe.js} +699 -421
- package/frames/dist/assets.js +92 -0
- package/frames/dist/client.dev.js +1296 -1198
- package/frames/dist/client.js +1128 -1191
- package/frames/dist/client.observe.js +2041 -0
- package/frames/dist/regions.js +171 -0
- package/frames/dist/server.dev.js +2545 -0
- package/frames/dist/server.js +1683 -3004
- package/frames/dist/server.observe.js +2544 -0
- package/frames/dist/trace.js +45 -0
- package/frames/dist/wire.js +594 -0
- package/frames/package.json +2 -25
- package/package.json +244 -256
- package/performance-tracks/dist/performance-tracks.dev.js +679 -0
- package/performance-tracks/dist/performance-tracks.js +6 -0
- package/performance-tracks/dist/performance-tracks.observe.js +667 -0
- package/performance-tracks/package.json +7 -0
- package/performance-tracks/types/index.d.ts +69 -0
- package/serialization/decode/package.json +2 -15
- package/serialization/dist/decode.js +121 -25
- package/serialization/dist/serialization.js +282 -88
- package/serialization/package.json +2 -15
- package/serialization/types/index.d.ts +115 -153
- package/serialization/types/serializer-decode.d.ts +173 -114
- package/serialization/types/serializer.d.ts +144 -0
- package/server-functions/dist/client.dev.js +1462 -0
- package/server-functions/dist/client.js +667 -165
- package/server-functions/dist/client.observe.js +1441 -0
- package/server-functions/dist/rich-args.js +102 -1
- package/server-functions/dist/server.dev.js +2802 -299
- package/server-functions/dist/server.js +2724 -314
- package/server-functions/dist/server.observe.js +3680 -0
- package/server-functions/package.json +2 -35
- package/server-functions/rich-args/package.json +2 -15
- package/skills/server-components/SKILL.md +117 -0
- package/storage/package.json +2 -15
- package/types/client.d.ts +342 -288
- package/types/constants.d.ts +22 -0
- package/types/cookies.d.ts +32 -84
- package/types/diagnostics.d.ts +80 -0
- package/types/frames/assets-tier.d.ts +78 -0
- package/types/frames/client.d.ts +40 -1
- package/types/frames/frame-client.d.ts +443 -280
- package/types/frames/frame-container-plugin.d.ts +64 -0
- package/types/frames/frame-morph.d.ts +29 -0
- package/types/frames/frame-sink.d.ts +141 -161
- package/types/frames/frame-transport.d.ts +263 -184
- package/types/frames/regions-tier.d.ts +60 -0
- package/types/frames/serializer-decode.d.ts +241 -0
- package/types/frames/serializer.d.ts +115 -153
- package/types/frames/server.d.ts +2 -2
- package/types/frames/trace-tier.d.ts +2 -0
- package/types/frames/tree-rewrite.d.ts +39 -0
- package/types/frames/wire-tier.d.ts +169 -0
- package/types/head.d.ts +20 -0
- package/types/index.d.ts +98 -81
- package/types/index.server.d.ts +159 -0
- package/types/jsx.d.ts +49 -44
- package/types/observe.d.ts +535 -0
- package/types/reconcile.d.ts +1 -0
- package/types/render.d.ts +11 -0
- package/types/request-error-hook.d.ts +5 -0
- package/types/response.d.ts +95 -147
- package/types/serializer-decode.d.ts +173 -114
- package/types/serializer.d.ts +115 -153
- package/types/server-functions/argument-codec.d.ts +30 -0
- package/types/server-functions/client.d.ts +237 -223
- package/types/server-functions/flash.d.ts +28 -30
- package/types/server-functions/registry.d.ts +105 -0
- package/types/server-functions/rich-args.d.ts +1 -10
- package/types/server-functions/server.d.ts +538 -531
- package/types/server-functions/shared.d.ts +398 -425
- package/types/server-functions/uploads.d.ts +53 -0
- package/types/server-mock.d.ts +154 -20
- package/types/server-observe.d.ts +86 -0
- package/types/server.d.ts +601 -422
- package/types/trace.d.ts +127 -0
- package/LICENSE +0 -21
- package/dist/web.cjs +0 -2033
- package/frames/dist/client.cjs +0 -2002
- package/frames/dist/client.dev.cjs +0 -2022
- package/frames/dist/server.cjs +0 -3877
- package/serialization/dist/decode.cjs +0 -139
- package/serialization/dist/serialization.cjs +0 -261
- 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 -834
- package/server-functions/dist/rich-args.cjs +0 -11
- package/server-functions/dist/server.cjs +0 -1242
- package/server-functions/dist/server.dev.cjs +0 -1242
- 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 -9
- package/types-cjs/client.d.cts +0 -337
- package/types-cjs/cookies.d.cts +0 -93
- package/types-cjs/core.d.cts +0 -9
- package/types-cjs/frames/client.d.cts +0 -36
- package/types-cjs/frames/frame-client.d.cts +0 -356
- 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 -244
- package/types-cjs/jsx-properties.d.cts +0 -93
- package/types-cjs/jsx.d.cts +0 -4159
- 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 -262
- 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 -681
- package/types-cjs/server-functions/shared.d.cts +0 -523
- package/types-cjs/server-mock.d.cts +0 -286
- package/types-cjs/server.d.cts +0 -544
|
@@ -1,4 +1,15 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { getOwner } from 'solid-js';
|
|
2
|
+
import { sharedConfig, 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,239 @@ 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 REQUEST_ERROR_HOOK = Symbol.for("solid-js/server/request-error-hook");
|
|
27
|
+
function hooks() {
|
|
28
|
+
const g = globalThis;
|
|
29
|
+
return g[REQUEST_ERROR_HOOK] || (g[REQUEST_ERROR_HOOK] = new WeakMap());
|
|
30
|
+
}
|
|
31
|
+
function requestErrorHook(event) {
|
|
32
|
+
return event === undefined ? undefined : hooks().get(event);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const TRACEPARENT = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;
|
|
36
|
+
const ZERO_TRACE = "00000000000000000000000000000000";
|
|
37
|
+
const ZERO_SPAN = "0000000000000000";
|
|
38
|
+
function parseTraceparent(value) {
|
|
39
|
+
if (!value) return undefined;
|
|
40
|
+
const m = TRACEPARENT.exec(value.trim());
|
|
41
|
+
if (!m) return undefined;
|
|
42
|
+
const [, version, traceId, parentId, flags, rest] = m;
|
|
43
|
+
if (version === "ff") return undefined;
|
|
44
|
+
if (version === "00" && rest !== undefined) return undefined;
|
|
45
|
+
if (traceId === ZERO_TRACE || parentId === ZERO_SPAN) return undefined;
|
|
46
|
+
return {
|
|
47
|
+
traceId,
|
|
48
|
+
parentId,
|
|
49
|
+
sampled: (parseInt(flags, 16) & 1) === 1
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
function randomHex(bytes) {
|
|
53
|
+
let out = "";
|
|
54
|
+
for (let i = 0; i < bytes; i += 4) out += (Math.random() * 0x100000000 >>> 0).toString(16).padStart(8, "0");
|
|
55
|
+
return out.length === bytes * 2 ? out : out.slice(0, bytes * 2);
|
|
56
|
+
}
|
|
57
|
+
function randomTraceId() {
|
|
58
|
+
let id = randomHex(16);
|
|
59
|
+
while (id === ZERO_TRACE) id = randomHex(16);
|
|
60
|
+
return id;
|
|
61
|
+
}
|
|
62
|
+
function randomSpanId() {
|
|
63
|
+
let id = randomHex(8);
|
|
64
|
+
while (id === ZERO_SPAN) id = randomHex(8);
|
|
65
|
+
return id;
|
|
66
|
+
}
|
|
67
|
+
function formatTraceparent(context) {
|
|
68
|
+
return `00-${context.traceId}-${context.spanId}-${context.sampled === true ? "01" : "00"}`;
|
|
69
|
+
}
|
|
70
|
+
const RECORDS_KEY = Symbol.for("@solidjs/web/trace/records");
|
|
71
|
+
function records$1() {
|
|
72
|
+
const g = globalThis;
|
|
73
|
+
return g[RECORDS_KEY] || (g[RECORDS_KEY] = new WeakMap());
|
|
74
|
+
}
|
|
75
|
+
function traceFor(key, request) {
|
|
76
|
+
const store = records$1();
|
|
77
|
+
let record = store.get(key);
|
|
78
|
+
if (record) return record;
|
|
79
|
+
const headers = request ? request.headers : undefined;
|
|
80
|
+
const incoming = headers ? parseTraceparent(headers.get("traceparent")) : undefined;
|
|
81
|
+
const context = {
|
|
82
|
+
traceId: incoming ? incoming.traceId : randomTraceId(),
|
|
83
|
+
spanId: randomSpanId(),
|
|
84
|
+
entries: {}
|
|
85
|
+
};
|
|
86
|
+
if (incoming) {
|
|
87
|
+
context.parentId = incoming.parentId;
|
|
88
|
+
context.sampled = incoming.sampled;
|
|
89
|
+
}
|
|
90
|
+
if (headers) {
|
|
91
|
+
const state = headers.get("tracestate");
|
|
92
|
+
if (state) context.state = state;
|
|
93
|
+
const baggage = headers.get("baggage");
|
|
94
|
+
if (baggage) context.baggage = baggage;
|
|
95
|
+
}
|
|
96
|
+
let answered = false;
|
|
97
|
+
context.entries.traceparent = formatTraceparent(context);
|
|
98
|
+
record = {
|
|
99
|
+
context,
|
|
100
|
+
emit: incoming !== undefined && incoming.sampled || answered,
|
|
101
|
+
timing: []
|
|
102
|
+
};
|
|
103
|
+
store.set(key, record);
|
|
104
|
+
return record;
|
|
105
|
+
}
|
|
106
|
+
function traceForEvent(event) {
|
|
107
|
+
return traceFor(event.request || event, event.request);
|
|
108
|
+
}
|
|
109
|
+
const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
110
|
+
function splitServerTiming(value) {
|
|
111
|
+
const entries = [];
|
|
112
|
+
let start = 0;
|
|
113
|
+
let quoted = false;
|
|
114
|
+
for (let i = 0; i < value.length; i++) {
|
|
115
|
+
const c = value[i];
|
|
116
|
+
if (quoted) {
|
|
117
|
+
if (c === "\\") i++;else if (c === '"') quoted = false;
|
|
118
|
+
} else if (c === '"') quoted = true;else if (c === ",") {
|
|
119
|
+
entries.push(value.slice(start, i));
|
|
120
|
+
start = i + 1;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
entries.push(value.slice(start));
|
|
124
|
+
return entries;
|
|
125
|
+
}
|
|
126
|
+
function metricName(entry) {
|
|
127
|
+
return entry.split(";")[0].trim().toLowerCase();
|
|
128
|
+
}
|
|
129
|
+
function namesOnServerTiming(headers) {
|
|
130
|
+
const names = new Set();
|
|
131
|
+
const existing = headers.get("server-timing");
|
|
132
|
+
if (existing) {
|
|
133
|
+
for (const entry of splitServerTiming(existing)) {
|
|
134
|
+
const name = metricName(entry);
|
|
135
|
+
if (name) names.add(name);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return names;
|
|
139
|
+
}
|
|
140
|
+
function quoteDesc(value) {
|
|
141
|
+
return value.replace(/[\x00-\x1f\x7f]/g, "").replace(/[^\x20-\x7e]/g, "?").replace(/[\\"]/g, m => "\\" + m);
|
|
142
|
+
}
|
|
143
|
+
function shellMs(record) {
|
|
144
|
+
return record.render !== undefined ? record.render.shellMs : undefined;
|
|
145
|
+
}
|
|
146
|
+
function hasServerTiming(record) {
|
|
147
|
+
return record.emit || record.timing.length > 0 || shellMs(record) !== undefined;
|
|
148
|
+
}
|
|
149
|
+
function appendTraceServerTiming(headers, record) {
|
|
150
|
+
if (record.emit) {
|
|
151
|
+
const entries = record.context.entries;
|
|
152
|
+
let present;
|
|
153
|
+
for (const name in entries) {
|
|
154
|
+
if (!TOKEN.test(name)) continue;
|
|
155
|
+
if (!present) present = namesOnServerTiming(headers);
|
|
156
|
+
if (present.has(name.toLowerCase())) continue;
|
|
157
|
+
headers.append("Server-Timing", `${name};desc="${quoteDesc(entries[name])}"`);
|
|
158
|
+
present.add(name.toLowerCase());
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
const shell = shellMs(record);
|
|
162
|
+
if (shell !== undefined) headers.append("Server-Timing", formatMetric("solid-shell", shell));
|
|
163
|
+
for (const work of record.timing) headers.append("Server-Timing", metricOf(work));
|
|
164
|
+
}
|
|
165
|
+
function metricOf(work) {
|
|
166
|
+
if (work.type === "invocation") return formatMetric("solid-invocation", work.event.durationMs, work.event.id);
|
|
167
|
+
const boundary = work.event;
|
|
168
|
+
return formatMetric("solid-boundary", boundary.durationMs, boundary.ownerPath !== undefined ? boundary.ownerPath.join(" > ") : boundary.id);
|
|
169
|
+
}
|
|
170
|
+
function formatMetric(name, dur, desc) {
|
|
171
|
+
let out = `${name};dur=${Math.round(dur * 10) / 10}`;
|
|
172
|
+
if (desc) out += `;desc="${quoteDesc(desc)}"`;
|
|
173
|
+
return out;
|
|
174
|
+
}
|
|
175
|
+
function mergeServerTiming(target, value) {
|
|
176
|
+
const present = namesOnServerTiming(target);
|
|
177
|
+
for (const entry of splitServerTiming(value)) {
|
|
178
|
+
const trimmed = entry.trim();
|
|
179
|
+
const name = metricName(trimmed);
|
|
180
|
+
if (!name || present.has(name)) continue;
|
|
181
|
+
target.append("Server-Timing", trimmed);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function records() {
|
|
186
|
+
return undefined;
|
|
187
|
+
}
|
|
188
|
+
function settledPromise(value) {
|
|
189
|
+
if (value instanceof Promise) return value;
|
|
190
|
+
try {
|
|
191
|
+
if (Object.prototype.toString.call(value) === "[object Promise]") return Promise.prototype.then.call(value, v => v);
|
|
192
|
+
} catch {}
|
|
193
|
+
return undefined;
|
|
194
|
+
}
|
|
195
|
+
function isDeferredBody(value) {
|
|
196
|
+
if (value === null || typeof value !== "object" && typeof value !== "function") return false;
|
|
197
|
+
if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) return true;
|
|
198
|
+
const v = value;
|
|
199
|
+
if (typeof v[Symbol.asyncIterator] === "function") return true;
|
|
200
|
+
return typeof v[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function timesServerWork(type) {
|
|
204
|
+
const channel = records();
|
|
205
|
+
if (channel === undefined) return false;
|
|
206
|
+
return channel.observed(type);
|
|
207
|
+
}
|
|
208
|
+
function deliver(context, at, boundary, outcome, value) {
|
|
209
|
+
const record = {
|
|
210
|
+
id: context.id,
|
|
211
|
+
direct: context.direct,
|
|
212
|
+
at,
|
|
213
|
+
durationMs: performance.now() - at,
|
|
214
|
+
outcome
|
|
215
|
+
};
|
|
216
|
+
if (boundary !== undefined) record.boundary = boundary;
|
|
217
|
+
if (outcome === "ok" && isDeferredBody(value)) record.deferred = true;
|
|
218
|
+
traceForEvent(context.event).timing.push({
|
|
219
|
+
type: "invocation",
|
|
220
|
+
event: record
|
|
221
|
+
});
|
|
222
|
+
const channel = records();
|
|
223
|
+
if (!channel.observed("invocation")) return;
|
|
224
|
+
const live = {
|
|
225
|
+
event: context.event,
|
|
226
|
+
args: context.args
|
|
227
|
+
};
|
|
228
|
+
if (context.request !== undefined) live.request = context.request;
|
|
229
|
+
if (outcome === "ok") live.result = value;else live.error = value;
|
|
230
|
+
channel.emit("invocation", record, live);
|
|
231
|
+
}
|
|
232
|
+
function observeInvocation(context, execute) {
|
|
233
|
+
if (!timesServerWork("invocation")) return execute();
|
|
234
|
+
const at = performance.now();
|
|
235
|
+
const boundary = context.direct ? sharedConfig.context?._currentBoundaryId ?? undefined : undefined;
|
|
236
|
+
let result;
|
|
237
|
+
try {
|
|
238
|
+
result = execute();
|
|
239
|
+
} catch (error) {
|
|
240
|
+
deliver(context, at, boundary, "error", error);
|
|
241
|
+
throw error;
|
|
242
|
+
}
|
|
243
|
+
const promised = settledPromise(result);
|
|
244
|
+
if (promised !== undefined) {
|
|
245
|
+
return promised.then(value => {
|
|
246
|
+
deliver(context, at, boundary, "ok", value);
|
|
247
|
+
return value;
|
|
248
|
+
}, error => {
|
|
249
|
+
deliver(context, at, boundary, "error", error);
|
|
250
|
+
throw error;
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
deliver(context, at, boundary, "ok", result);
|
|
254
|
+
return result;
|
|
255
|
+
}
|
|
12
256
|
|
|
13
257
|
const SERVER_FUNCTION_METADATA = Symbol.for("solid.ServerFunctionMetadata");
|
|
14
258
|
function getServerFunctionMetadata(fn) {
|
|
@@ -26,6 +270,32 @@ function withMeta(fn, meta) {
|
|
|
26
270
|
Object.assign(metadata, meta);
|
|
27
271
|
return fn;
|
|
28
272
|
}
|
|
273
|
+
const SERVER_FUNCTION_INVOKE = Symbol.for("solid.ServerFunctionInvoke");
|
|
274
|
+
const INVOKE_OPTION_REDIRECTS = {
|
|
275
|
+
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.",
|
|
276
|
+
method: "The method is declaration-scoped: declare the function with GET(fn).",
|
|
277
|
+
body: "The arguments are the body: pass them in the args array.",
|
|
278
|
+
timeout: "Compose timeouts through `signal` with AbortSignal.timeout(ms) (and AbortSignal.any to " + "combine it with a caller signal)."
|
|
279
|
+
};
|
|
280
|
+
function invoke(fn, options, ...args) {
|
|
281
|
+
const channel = typeof fn === "function" && fn[SERVER_FUNCTION_INVOKE];
|
|
282
|
+
if (!channel) {
|
|
283
|
+
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.");
|
|
284
|
+
}
|
|
285
|
+
if (options === null || typeof options !== "object") {
|
|
286
|
+
throw new Error("invoke's second argument is the invocation options bag: invoke(fn, { signal }, ...args)");
|
|
287
|
+
}
|
|
288
|
+
const picked = {};
|
|
289
|
+
for (const key in options) {
|
|
290
|
+
if (key !== "signal" && key !== "keepalive" && key !== "priority") {
|
|
291
|
+
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."));
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
if (options.signal !== undefined) picked.signal = options.signal;
|
|
295
|
+
if (options.keepalive !== undefined) picked.keepalive = options.keepalive;
|
|
296
|
+
if (options.priority !== undefined) picked.priority = options.priority;
|
|
297
|
+
return channel(args, picked);
|
|
298
|
+
}
|
|
29
299
|
const LIVE_SOURCE = Symbol.for("solid.LiveSource");
|
|
30
300
|
const SERVER_FUNCTION_RPC = Symbol.for("solid.ServerFunctionRPC");
|
|
31
301
|
function provideServerFunctionRPC(rpc) {
|
|
@@ -62,6 +332,7 @@ function serializeCookie(name, value, options = {}) {
|
|
|
62
332
|
if (options.expires) cookie += `; Expires=${options.expires.toUTCString()}`;
|
|
63
333
|
if (options.httpOnly) cookie += "; HttpOnly";
|
|
64
334
|
if (options.secure) cookie += "; Secure";
|
|
335
|
+
if (options.partitioned) cookie += "; Partitioned";
|
|
65
336
|
if (options.sameSite) {
|
|
66
337
|
const sameSite = options.sameSite.toLowerCase();
|
|
67
338
|
cookie += `; SameSite=${sameSite === "none" ? "None" : sameSite === "strict" ? "Strict" : "Lax"}`;
|
|
@@ -69,7 +340,7 @@ function serializeCookie(name, value, options = {}) {
|
|
|
69
340
|
return cookie;
|
|
70
341
|
}
|
|
71
342
|
const FLASH_COOKIE = "flash";
|
|
72
|
-
const FLASH_MATCHER =
|
|
343
|
+
const FLASH_MATCHER = /(?:^|;\s*)flash=([^;]+)/;
|
|
73
344
|
function hasFlashCookie(cookieHeader) {
|
|
74
345
|
return !!cookieHeader && FLASH_MATCHER.test(cookieHeader);
|
|
75
346
|
}
|
|
@@ -86,11 +357,141 @@ function configureServerFunctionsCodec(codec) {
|
|
|
86
357
|
function getServerFunctionsCodec() {
|
|
87
358
|
return codecConfig.codec;
|
|
88
359
|
}
|
|
89
|
-
|
|
360
|
+
const UNNAMED_FLIGHT_SOURCE = "true";
|
|
361
|
+
const flightConfig = {
|
|
362
|
+
consumers: new Map()
|
|
363
|
+
};
|
|
364
|
+
function assertFlightSource(source) {
|
|
365
|
+
if (source === UNNAMED_FLIGHT_SOURCE || source === "" || source.includes(",")) {
|
|
366
|
+
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).`);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
function subscribeFlightData(sourceOrConsumer, maybeConsumer) {
|
|
370
|
+
const named = typeof sourceOrConsumer === "string";
|
|
371
|
+
if (named) assertFlightSource(sourceOrConsumer);
|
|
372
|
+
const source = named ? sourceOrConsumer : UNNAMED_FLIGHT_SOURCE;
|
|
373
|
+
const consumer = named ? maybeConsumer : sourceOrConsumer;
|
|
374
|
+
flightConfig.consumers.set(source, consumer);
|
|
90
375
|
return () => {
|
|
376
|
+
if (flightConfig.consumers.get(source) === consumer) flightConfig.consumers.delete(source);
|
|
91
377
|
};
|
|
92
378
|
}
|
|
93
|
-
|
|
379
|
+
function frameAddress(id, args) {
|
|
380
|
+
return args && args.length ? id + ":" + hashArguments(args) : id;
|
|
381
|
+
}
|
|
382
|
+
function hashArguments(args) {
|
|
383
|
+
let hash = 0;
|
|
384
|
+
const text = stableString(args);
|
|
385
|
+
for (let i = 0; i < text.length; i++) {
|
|
386
|
+
hash = (hash << 5) - hash + text.charCodeAt(i);
|
|
387
|
+
hash |= 0;
|
|
388
|
+
}
|
|
389
|
+
return (hash >>> 0).toString(36);
|
|
390
|
+
}
|
|
391
|
+
function stableString(value, seen) {
|
|
392
|
+
if (value === null || typeof value !== "object") {
|
|
393
|
+
return typeof value === "bigint" ? value + "n" : String(value);
|
|
394
|
+
}
|
|
395
|
+
if (value instanceof Date) return "Date:" + value.getTime();
|
|
396
|
+
seen || (seen = new Set());
|
|
397
|
+
if (seen.has(value)) return "~";
|
|
398
|
+
seen.add(value);
|
|
399
|
+
if (value instanceof Map) {
|
|
400
|
+
const entries = [];
|
|
401
|
+
for (const [k, v] of value) {
|
|
402
|
+
entries.push(stableString(k, seen) + "=>" + stableString(v, seen));
|
|
403
|
+
}
|
|
404
|
+
return "Map{" + entries.sort().join(",") + "}";
|
|
405
|
+
}
|
|
406
|
+
if (value instanceof Set) {
|
|
407
|
+
const members = [];
|
|
408
|
+
for (const v of value) members.push(stableString(v, seen));
|
|
409
|
+
return "Set{" + members.sort().join(",") + "}";
|
|
410
|
+
}
|
|
411
|
+
if (Array.isArray(value)) {
|
|
412
|
+
let out = "[";
|
|
413
|
+
for (let i = 0; i < value.length; i++) out += (i ? "," : "") + stableString(value[i], seen);
|
|
414
|
+
return out + "]";
|
|
415
|
+
}
|
|
416
|
+
const keys = Object.keys(value).sort();
|
|
417
|
+
let out = "{";
|
|
418
|
+
for (let i = 0; i < keys.length; i++) {
|
|
419
|
+
out += (i ? "," : "") + keys[i] + ":" + stableString(value[keys[i]], seen);
|
|
420
|
+
}
|
|
421
|
+
return out + "}";
|
|
422
|
+
}
|
|
423
|
+
function serverFunctionAddress(endpoint, id) {
|
|
424
|
+
const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
|
|
425
|
+
return `${mount}/${encodeURIComponent(id)}`;
|
|
426
|
+
}
|
|
427
|
+
function serverFunctionDataAddress(endpoint, id) {
|
|
428
|
+
const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
|
|
429
|
+
return `${mount}/data/${encodeURIComponent(id)}`;
|
|
430
|
+
}
|
|
431
|
+
function serverFunctionLiveAddress(endpoint, id) {
|
|
432
|
+
const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
|
|
433
|
+
return `${mount}/live/${encodeURIComponent(id)}`;
|
|
434
|
+
}
|
|
435
|
+
function parseServerFunctionAddress(pathname, endpoint) {
|
|
436
|
+
const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
|
|
437
|
+
if (!pathname.startsWith(mount)) return null;
|
|
438
|
+
const rest = pathname.slice(mount.length);
|
|
439
|
+
if (!rest.startsWith("/")) return null;
|
|
440
|
+
let segment = rest.slice(1);
|
|
441
|
+
let data = false;
|
|
442
|
+
let live = false;
|
|
443
|
+
if (segment.startsWith("data/")) {
|
|
444
|
+
segment = segment.slice(5);
|
|
445
|
+
data = true;
|
|
446
|
+
} else if (segment.startsWith("live/")) {
|
|
447
|
+
segment = segment.slice(5);
|
|
448
|
+
live = true;
|
|
449
|
+
}
|
|
450
|
+
if (!segment || segment.includes("/")) return null;
|
|
451
|
+
try {
|
|
452
|
+
return {
|
|
453
|
+
id: decodeURIComponent(segment),
|
|
454
|
+
data,
|
|
455
|
+
live
|
|
456
|
+
};
|
|
457
|
+
} catch {
|
|
458
|
+
return null;
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
const MAX_GET_URL_LENGTH = 2000;
|
|
462
|
+
function urlTargetId(target, helper) {
|
|
463
|
+
if (typeof target === "string") return target;
|
|
464
|
+
if (isServerFunction(target) && typeof target.id === "string") return target.id;
|
|
465
|
+
throw new Error(`${helper} expects a server function reference (or its id).`);
|
|
466
|
+
}
|
|
467
|
+
function serverFunctionActionUrlFor(endpoint, target, boundArgs) {
|
|
468
|
+
const address = serverFunctionAddress(endpoint, urlTargetId(target, "serverFunctionActionUrl"));
|
|
469
|
+
if (!boundArgs.length) return address;
|
|
470
|
+
if (!isJSONSafe(boundArgs)) {
|
|
471
|
+
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.");
|
|
472
|
+
}
|
|
473
|
+
return `${address}?args=${encodeURIComponent(JSON.stringify(boundArgs))}`;
|
|
474
|
+
}
|
|
475
|
+
function serverFunctionUrlFor(endpoint, fn, args) {
|
|
476
|
+
if (!isServerFunction(fn) || typeof fn.id !== "string") {
|
|
477
|
+
throw new Error("serverFunctionUrl expects a server function reference.");
|
|
478
|
+
}
|
|
479
|
+
const metadata = getServerFunctionMetadata(fn);
|
|
480
|
+
if (!metadata || metadata.method !== "GET") {
|
|
481
|
+
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).');
|
|
482
|
+
}
|
|
483
|
+
const address = metadata.live ? serverFunctionLiveAddress(endpoint, fn.id) : serverFunctionDataAddress(endpoint, fn.id);
|
|
484
|
+
if (!args.length) return address;
|
|
485
|
+
if (!isJSONSafe(args)) {
|
|
486
|
+
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.");
|
|
487
|
+
}
|
|
488
|
+
const url = `${address}?args=${encodeURIComponent(JSON.stringify(args))}`;
|
|
489
|
+
const length = new URL(url, globalThis.location?.href || "http://localhost").href.length;
|
|
490
|
+
if (length > MAX_GET_URL_LENGTH) {
|
|
491
|
+
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.");
|
|
492
|
+
}
|
|
493
|
+
return url;
|
|
494
|
+
}
|
|
94
495
|
const ERROR_HEADER = "X-Server-Function-Error";
|
|
95
496
|
const ERROR_HEADER_MARKER = "=?1?";
|
|
96
497
|
const NEEDS_ENCODING = /[^\x20-\x7e\xa0-\xff]/;
|
|
@@ -116,8 +517,31 @@ function decodeErrorHeaderValue(value) {
|
|
|
116
517
|
return value;
|
|
117
518
|
}
|
|
118
519
|
}
|
|
119
|
-
const INSTANCE_HEADER = "X-Server-Function-Instance";
|
|
120
520
|
const BODY_FORMAT_HEADER = "X-Server-Function-Format";
|
|
521
|
+
const LAST_EVENT_ID_HEADER = "Last-Event-ID";
|
|
522
|
+
const UNKNOWN_HEADER = "X-Server-Function-Unknown";
|
|
523
|
+
const BUILD_HEADER = "X-Server-Function-Build";
|
|
524
|
+
const REDIRECT_HEADER = "X-Server-Function-Redirect";
|
|
525
|
+
function decodeRedirectHeaderValue(value) {
|
|
526
|
+
if (typeof value !== "string") return undefined;
|
|
527
|
+
const at = value.indexOf(" ");
|
|
528
|
+
if (at < 0) return undefined;
|
|
529
|
+
const status = Number(value.slice(0, at));
|
|
530
|
+
const url = value.slice(at + 1);
|
|
531
|
+
if (!Number.isInteger(status) || !url) return undefined;
|
|
532
|
+
if (status !== 301 && status !== 302 && status !== 303 && status !== 307 && status !== 308) return undefined;
|
|
533
|
+
let parsed;
|
|
534
|
+
try {
|
|
535
|
+
parsed = new URL(url);
|
|
536
|
+
} catch {
|
|
537
|
+
return undefined;
|
|
538
|
+
}
|
|
539
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return undefined;
|
|
540
|
+
return {
|
|
541
|
+
status,
|
|
542
|
+
url
|
|
543
|
+
};
|
|
544
|
+
}
|
|
121
545
|
const SINGLE_FLIGHT_HEADER = "X-Single-Flight";
|
|
122
546
|
const FILE_FORM_KEY = "__server_function_file__";
|
|
123
547
|
const BodyFormat = {
|
|
@@ -129,7 +553,8 @@ const BodyFormat = {
|
|
|
129
553
|
File: "5",
|
|
130
554
|
ArrayBuffer: "6",
|
|
131
555
|
Uint8Array: "7",
|
|
132
|
-
Json: "8"
|
|
556
|
+
Json: "8",
|
|
557
|
+
Void: "9"
|
|
133
558
|
};
|
|
134
559
|
const JSON_SAFE_DEPTH_LIMIT = 4096;
|
|
135
560
|
const EXIT = {};
|
|
@@ -146,7 +571,7 @@ function isJSONSafe(value) {
|
|
|
146
571
|
const t = typeof v;
|
|
147
572
|
if (t === "string" || t === "boolean") continue;
|
|
148
573
|
if (t === "number") {
|
|
149
|
-
if (!Number.isFinite(v)) return false;
|
|
574
|
+
if (!Number.isFinite(v) || Object.is(v, -0)) return false;
|
|
150
575
|
continue;
|
|
151
576
|
}
|
|
152
577
|
if (t !== "object") return false;
|
|
@@ -159,7 +584,11 @@ function isJSONSafe(value) {
|
|
|
159
584
|
const proto = Object.getPrototypeOf(v);
|
|
160
585
|
if (proto !== Object.prototype && proto !== null) return false;
|
|
161
586
|
if (Symbol.asyncIterator in v || Symbol.iterator in v) return false;
|
|
162
|
-
for (const k in v)
|
|
587
|
+
for (const k in v) {
|
|
588
|
+
const descriptor = Object.getOwnPropertyDescriptor(v, k);
|
|
589
|
+
if (descriptor === undefined || !("value" in descriptor)) return false;
|
|
590
|
+
stack.push(descriptor.value);
|
|
591
|
+
}
|
|
163
592
|
}
|
|
164
593
|
}
|
|
165
594
|
return true;
|
|
@@ -225,127 +654,262 @@ function getHeadersAndBody(body) {
|
|
|
225
654
|
return undefined;
|
|
226
655
|
}
|
|
227
656
|
}
|
|
228
|
-
async function extractBody(source, codecOptions) {
|
|
657
|
+
async function extractBody(source, codecOptions, wire) {
|
|
229
658
|
const contentType = source.headers.get("content-type");
|
|
230
659
|
const format = source.headers.get(BODY_FORMAT_HEADER);
|
|
231
|
-
const clone = source.clone();
|
|
232
660
|
switch (true) {
|
|
233
661
|
case format === BodyFormat.Serialized:
|
|
234
|
-
return await deserializeStream(
|
|
662
|
+
return await deserializeStream(source, codecOptions, wire);
|
|
235
663
|
case format === BodyFormat.Json:
|
|
236
|
-
return JSON.parse(await
|
|
664
|
+
return JSON.parse(await source.text());
|
|
237
665
|
case format === BodyFormat.String:
|
|
238
|
-
return await
|
|
666
|
+
return await source.text();
|
|
239
667
|
case format === BodyFormat.File:
|
|
240
668
|
{
|
|
241
|
-
const formData = await
|
|
669
|
+
const formData = await source.formData();
|
|
242
670
|
return formData.get(FILE_FORM_KEY);
|
|
243
671
|
}
|
|
244
672
|
case format === BodyFormat.FormData:
|
|
245
673
|
case contentType && contentType.startsWith("multipart/form-data"):
|
|
246
|
-
return await
|
|
674
|
+
return await source.formData();
|
|
247
675
|
case format === BodyFormat.URLSearchParams:
|
|
248
676
|
case contentType && contentType.startsWith("application/x-www-form-urlencoded"):
|
|
249
|
-
return new URLSearchParams(await
|
|
677
|
+
return new URLSearchParams(await source.text());
|
|
250
678
|
case format === BodyFormat.Blob:
|
|
251
|
-
return await
|
|
679
|
+
return await source.blob();
|
|
252
680
|
case format === BodyFormat.ArrayBuffer:
|
|
253
|
-
return await
|
|
681
|
+
return await source.arrayBuffer();
|
|
254
682
|
case format === BodyFormat.Uint8Array:
|
|
255
|
-
return new Uint8Array(await
|
|
683
|
+
return new Uint8Array(await source.arrayBuffer());
|
|
256
684
|
}
|
|
257
685
|
return undefined;
|
|
258
686
|
}
|
|
259
687
|
function createChunk(data) {
|
|
260
|
-
const
|
|
261
|
-
const encodeData = encoder.encode(data);
|
|
688
|
+
const encodeData = CHUNK_ENCODER.encode(data);
|
|
262
689
|
const bytes = encodeData.length;
|
|
690
|
+
if (bytes > MAX_CHUNK_BYTES) {
|
|
691
|
+
throw new RangeError("Server function chunk is too large to frame.");
|
|
692
|
+
}
|
|
263
693
|
const chunk = new Uint8Array(12 + bytes);
|
|
264
|
-
chunk.set(
|
|
694
|
+
chunk.set(CHUNK_ENCODER.encode(`;0x${bytes.toString(16).padStart(8, "0")};`));
|
|
265
695
|
chunk.set(encodeData, 12);
|
|
266
696
|
return chunk;
|
|
267
697
|
}
|
|
698
|
+
const CHUNK_ENCODER = /* @__PURE__ */new TextEncoder();
|
|
699
|
+
const CHUNK_DECODER = /* @__PURE__ */new TextDecoder("utf-8", {
|
|
700
|
+
fatal: true
|
|
701
|
+
});
|
|
702
|
+
const MAX_CHUNK_BYTES = 0xffffffff;
|
|
703
|
+
const RETAINED_STORE_BYTES = 64 * 1024;
|
|
704
|
+
const DONE = {
|
|
705
|
+
done: true,
|
|
706
|
+
value: undefined
|
|
707
|
+
};
|
|
708
|
+
function malformedStream() {
|
|
709
|
+
return new Error("Malformed server function stream.");
|
|
710
|
+
}
|
|
268
711
|
class ChunkReader {
|
|
269
712
|
constructor(stream) {
|
|
270
713
|
this.reader = stream.getReader();
|
|
271
|
-
this.
|
|
714
|
+
this.store = new Uint8Array(0);
|
|
715
|
+
this.buffer = this.store;
|
|
272
716
|
this.done = false;
|
|
717
|
+
this.cancelled = false;
|
|
273
718
|
}
|
|
274
719
|
async readChunk() {
|
|
275
720
|
const chunk = await this.reader.read();
|
|
276
|
-
if (
|
|
277
|
-
const newBuffer = new Uint8Array(this.buffer.length + chunk.value.length);
|
|
278
|
-
newBuffer.set(this.buffer);
|
|
279
|
-
newBuffer.set(chunk.value, this.buffer.length);
|
|
280
|
-
this.buffer = newBuffer;
|
|
281
|
-
} else {
|
|
721
|
+
if (chunk.done) {
|
|
282
722
|
this.done = true;
|
|
723
|
+
return this.cancelled;
|
|
283
724
|
}
|
|
725
|
+
const incoming = chunk.value;
|
|
726
|
+
const store = this.store;
|
|
727
|
+
const start = this.buffer.byteOffset;
|
|
728
|
+
const end = start + this.buffer.length;
|
|
729
|
+
const needed = this.buffer.length + incoming.length;
|
|
730
|
+
if (end + incoming.length <= store.length) {
|
|
731
|
+
store.set(incoming, end);
|
|
732
|
+
this.buffer = store.subarray(start, end + incoming.length);
|
|
733
|
+
} else if (needed <= store.length) {
|
|
734
|
+
store.copyWithin(0, start, end);
|
|
735
|
+
store.set(incoming, this.buffer.length);
|
|
736
|
+
this.buffer = store.subarray(0, needed);
|
|
737
|
+
} else {
|
|
738
|
+
const grown = new Uint8Array(Math.max(needed, store.length * 2));
|
|
739
|
+
grown.set(this.buffer);
|
|
740
|
+
grown.set(incoming, this.buffer.length);
|
|
741
|
+
this.store = grown;
|
|
742
|
+
this.buffer = grown.subarray(0, needed);
|
|
743
|
+
}
|
|
744
|
+
return this.cancelled;
|
|
284
745
|
}
|
|
285
746
|
async next() {
|
|
747
|
+
if (this.cancelled) return DONE;
|
|
286
748
|
while (this.buffer.length < 12) {
|
|
287
749
|
if (this.done) {
|
|
288
|
-
if (this.buffer.length === 0) return
|
|
289
|
-
|
|
290
|
-
value: undefined
|
|
291
|
-
};
|
|
292
|
-
throw new Error("Malformed server function stream.");
|
|
750
|
+
if (this.buffer.length === 0) return DONE;
|
|
751
|
+
throw malformedStream();
|
|
293
752
|
}
|
|
294
|
-
await this.readChunk();
|
|
295
|
-
}
|
|
296
|
-
const decoder = new TextDecoder();
|
|
297
|
-
const bytes = Number.parseInt(decoder.decode(this.buffer.subarray(1, 11)), 16);
|
|
298
|
-
if (Number.isNaN(bytes)) {
|
|
299
|
-
throw new Error("Malformed server function stream.");
|
|
753
|
+
if (await this.readChunk()) return DONE;
|
|
300
754
|
}
|
|
755
|
+
const header = String.fromCharCode(...this.buffer.subarray(0, 12));
|
|
756
|
+
if (!/^;0x[\dA-Fa-f]{8};$/.test(header)) throw malformedStream();
|
|
757
|
+
const bytes = parseInt(header.slice(3, 11), 16);
|
|
301
758
|
while (bytes > this.buffer.length - 12) {
|
|
302
759
|
if (this.done) {
|
|
303
|
-
throw
|
|
760
|
+
throw malformedStream();
|
|
304
761
|
}
|
|
305
|
-
await this.readChunk();
|
|
762
|
+
if (await this.readChunk()) return DONE;
|
|
763
|
+
}
|
|
764
|
+
let partial;
|
|
765
|
+
try {
|
|
766
|
+
partial = CHUNK_DECODER.decode(this.buffer.subarray(12, 12 + bytes));
|
|
767
|
+
} catch {
|
|
768
|
+
throw malformedStream();
|
|
306
769
|
}
|
|
307
|
-
const partial = decoder.decode(this.buffer.subarray(12, 12 + bytes));
|
|
308
770
|
this.buffer = this.buffer.subarray(12 + bytes);
|
|
771
|
+
if (this.store.length > RETAINED_STORE_BYTES && this.buffer.length <= RETAINED_STORE_BYTES) {
|
|
772
|
+
this.store = this.buffer = this.buffer.slice();
|
|
773
|
+
}
|
|
309
774
|
return {
|
|
310
775
|
done: false,
|
|
311
776
|
value: partial
|
|
312
777
|
};
|
|
313
778
|
}
|
|
314
779
|
async drain(interpret) {
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
780
|
+
try {
|
|
781
|
+
while (true) {
|
|
782
|
+
const result = await this.next();
|
|
783
|
+
if (result.done) {
|
|
784
|
+
break;
|
|
785
|
+
}
|
|
786
|
+
interpret(result.value);
|
|
319
787
|
}
|
|
320
|
-
|
|
788
|
+
} catch (error) {
|
|
789
|
+
this.cancel(error).catch(() => {});
|
|
790
|
+
throw error;
|
|
321
791
|
}
|
|
322
792
|
}
|
|
793
|
+
cancel(reason) {
|
|
794
|
+
this.cancelled = true;
|
|
795
|
+
return this.reader.cancel(reason);
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
function createEventChunk(data, id) {
|
|
799
|
+
let event = id !== undefined && !id.includes("\0") ? `id: ${id}\n` : "";
|
|
800
|
+
for (const line of data.split(/\r\n|\r|\n/)) event += `data: ${line}\n`;
|
|
801
|
+
return CHUNK_ENCODER.encode(event + "\n");
|
|
802
|
+
}
|
|
803
|
+
const EVENT_STREAM_HEARTBEAT = /* @__PURE__ */new TextEncoder().encode(":\n\n");
|
|
804
|
+
function isEventStream(source) {
|
|
805
|
+
const contentType = source.headers.get("content-type");
|
|
806
|
+
return !!contentType && contentType.startsWith("text/event-stream");
|
|
807
|
+
}
|
|
808
|
+
function positionDigest(value) {
|
|
809
|
+
if (value === undefined || !isJSONSafe(value)) return undefined;
|
|
810
|
+
const text = JSON.stringify(value);
|
|
811
|
+
if (typeof text !== "string") return undefined;
|
|
812
|
+
return textDigest(text);
|
|
813
|
+
}
|
|
814
|
+
function textDigest(text) {
|
|
815
|
+
let a = 0x811c9dc5;
|
|
816
|
+
let b = 0x050c5d1f;
|
|
817
|
+
for (let i = 0; i < text.length; i++) {
|
|
818
|
+
const code = text.charCodeAt(i);
|
|
819
|
+
a = Math.imul(a ^ code, 0x01000193);
|
|
820
|
+
b = Math.imul(b ^ code, 0x01000193);
|
|
821
|
+
}
|
|
822
|
+
return (a >>> 0).toString(16).padStart(8, "0") + (b >>> 0).toString(16).padStart(8, "0");
|
|
823
|
+
}
|
|
824
|
+
const ERROR_TRAILER_PREFIX = "!";
|
|
825
|
+
function encodeErrorTrailer(error) {
|
|
826
|
+
const shaped = error instanceof Error ? error : new Error(String(error));
|
|
827
|
+
return ERROR_TRAILER_PREFIX + JSON.stringify(shaped.name && shaped.name !== "Error" ? {
|
|
828
|
+
name: shaped.name,
|
|
829
|
+
message: shaped.message
|
|
830
|
+
} : {
|
|
831
|
+
message: shaped.message
|
|
832
|
+
});
|
|
833
|
+
}
|
|
834
|
+
function errorFromTrailer(payload) {
|
|
835
|
+
let shape;
|
|
836
|
+
try {
|
|
837
|
+
shape = JSON.parse(payload.slice(1));
|
|
838
|
+
} catch {
|
|
839
|
+
shape = null;
|
|
840
|
+
}
|
|
841
|
+
const error = new Error(shape && typeof shape.message === "string" ? shape.message : "Server function result could not be delivered.");
|
|
842
|
+
if (shape && typeof shape.name === "string") error.name = shape.name;
|
|
843
|
+
return error;
|
|
844
|
+
}
|
|
845
|
+
function serializeStream(value, codecOptions) {
|
|
846
|
+
return new ReadableStream({
|
|
847
|
+
async start(controller) {
|
|
848
|
+
const {
|
|
849
|
+
serializeJSON
|
|
850
|
+
} = await import('@solidjs/web/serialization');
|
|
851
|
+
serializeJSON(value, {
|
|
852
|
+
...codecOptions,
|
|
853
|
+
onParse(node) {
|
|
854
|
+
controller.enqueue(createChunk(JSON.stringify(node)));
|
|
855
|
+
},
|
|
856
|
+
onDone() {
|
|
857
|
+
controller.close();
|
|
858
|
+
},
|
|
859
|
+
onError(error) {
|
|
860
|
+
controller.error(error);
|
|
861
|
+
}
|
|
862
|
+
});
|
|
863
|
+
}
|
|
864
|
+
});
|
|
323
865
|
}
|
|
324
|
-
async function deserializeStream(source, codecOptions) {
|
|
866
|
+
async function deserializeStream(source, codecOptions, wire) {
|
|
325
867
|
if (!source.body) {
|
|
326
868
|
throw new Error("missing body");
|
|
327
869
|
}
|
|
328
|
-
const reader = new ChunkReader(source.body);
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
870
|
+
const reader = wire && isEventStream(source) ? wire.open(source.body) : new ChunkReader(source.body);
|
|
871
|
+
try {
|
|
872
|
+
const result = await reader.next();
|
|
873
|
+
if (!result.done) {
|
|
874
|
+
if (result.value.startsWith(ERROR_TRAILER_PREFIX)) {
|
|
875
|
+
throw errorFromTrailer(result.value);
|
|
876
|
+
}
|
|
877
|
+
const {
|
|
878
|
+
createJSONDeserializer
|
|
879
|
+
} = await import('@solidjs/web/serialization/decode');
|
|
880
|
+
const deserializeChunk = createJSONDeserializer(codecOptions);
|
|
881
|
+
function interpretChunk(chunk) {
|
|
882
|
+
if (chunk.startsWith(ERROR_TRAILER_PREFIX)) {
|
|
883
|
+
throw errorFromTrailer(chunk);
|
|
884
|
+
}
|
|
885
|
+
return deserializeChunk(JSON.parse(chunk));
|
|
886
|
+
}
|
|
887
|
+
const connection = wire && wire.connection;
|
|
888
|
+
let endConnection;
|
|
889
|
+
if (connection) connection.ended = new Promise(resolve => endConnection = resolve);
|
|
890
|
+
const end = error => {
|
|
891
|
+
const sweep = () => deserializeChunk.abort(error);
|
|
892
|
+
if (connection) {
|
|
893
|
+
const close = () => deserializeChunk.close();
|
|
894
|
+
endConnection({
|
|
895
|
+
open: deserializeChunk.open(),
|
|
896
|
+
error,
|
|
897
|
+
sweep,
|
|
898
|
+
close
|
|
899
|
+
});
|
|
900
|
+
} else sweep();
|
|
901
|
+
};
|
|
902
|
+
reader.drain(interpretChunk).then(() => end(new Error("Server function stream ended unexpectedly.")), error => end(error));
|
|
903
|
+
return interpretChunk(result.value);
|
|
337
904
|
}
|
|
338
|
-
|
|
339
|
-
|
|
905
|
+
} catch (error) {
|
|
906
|
+
reader.cancel(error).catch(() => {});
|
|
907
|
+
throw error;
|
|
340
908
|
}
|
|
341
|
-
return undefined;
|
|
342
|
-
}
|
|
343
|
-
async function deserializeString(text, codecOptions) {
|
|
344
|
-
return await deserializeStream(new Response(text), codecOptions);
|
|
345
909
|
}
|
|
346
910
|
async function decodeResponse(response, codecOptions) {
|
|
347
911
|
if (!response.body) return undefined;
|
|
348
|
-
return await extractBody(response, codecOptions === undefined ? codecConfig.codec : codecOptions);
|
|
912
|
+
return await extractBody(response.clone(), codecOptions === undefined ? codecConfig.codec : codecOptions);
|
|
349
913
|
}
|
|
350
914
|
async function decodeResponsePayload(response, codecOptions) {
|
|
351
915
|
const decoded = await decodeResponse(response, codecOptions);
|
|
@@ -363,18 +927,48 @@ async function decodeResponsePayload(response, codecOptions) {
|
|
|
363
927
|
typeof setImmediate === "function" ? setImmediate : fn => setTimeout(fn, 0);
|
|
364
928
|
const RequestContext = Symbol.for("solid.RequestContext");
|
|
365
929
|
function getRequestEvent() {
|
|
366
|
-
|
|
930
|
+
const store = globalThis[RequestContext];
|
|
931
|
+
if (!store) return undefined;
|
|
932
|
+
const event = store.getStore();
|
|
933
|
+
if (event) return event;
|
|
934
|
+
const ctx = renderContextOf(getOwner());
|
|
935
|
+
return ctx && ctx.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.");
|
|
936
|
+
}
|
|
937
|
+
const RENDER_ROOTS = Symbol.for("@solidjs/web/render-roots");
|
|
938
|
+
function renderContextOf(owner) {
|
|
939
|
+
const roots = globalThis[RENDER_ROOTS];
|
|
940
|
+
if (!roots) return undefined;
|
|
941
|
+
for (; owner; owner = owner._parent) {
|
|
942
|
+
const context = roots.get(owner);
|
|
943
|
+
if (context) return context;
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
function peekRequestEvent() {
|
|
947
|
+
const store = globalThis[RequestContext];
|
|
948
|
+
return store ? store.getStore() : undefined;
|
|
949
|
+
}
|
|
950
|
+
function traceForStub(stub, event) {
|
|
951
|
+
if (!event) {
|
|
952
|
+
event = peekRequestEvent();
|
|
953
|
+
if (!event || event.response !== stub) return undefined;
|
|
954
|
+
}
|
|
955
|
+
return traceForEvent(event);
|
|
367
956
|
}
|
|
368
957
|
function reportLostHeaderWrite(method, name) {
|
|
369
|
-
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).";
|
|
958
|
+
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).";
|
|
370
959
|
console.error(message);
|
|
371
960
|
}
|
|
372
961
|
function commitResponseStub(stub, {
|
|
373
|
-
allowLateLocation = false
|
|
962
|
+
allowLateLocation = false,
|
|
963
|
+
event
|
|
374
964
|
} = {}) {
|
|
375
965
|
if (!stub || stub.committed) return stub;
|
|
376
|
-
stub.committed = true;
|
|
377
966
|
const headers = stub.headers;
|
|
967
|
+
if (headers && typeof headers.append === "function") {
|
|
968
|
+
const trace = traceForStub(stub, event);
|
|
969
|
+
if (trace) appendTraceServerTiming(headers, trace);
|
|
970
|
+
}
|
|
971
|
+
stub.committed = true;
|
|
378
972
|
if (!headers || typeof headers.set !== "function") return stub;
|
|
379
973
|
for (const method of ["set", "append", "delete"]) {
|
|
380
974
|
const original = headers[method].bind(headers);
|
|
@@ -396,42 +990,118 @@ function copyInitHeaders(init) {
|
|
|
396
990
|
for (const cookie of init.getSetCookie()) headers.append("Set-Cookie", cookie);
|
|
397
991
|
return headers;
|
|
398
992
|
}
|
|
399
|
-
|
|
993
|
+
let stubGapFillExcluded;
|
|
994
|
+
function isStubGapFillExcluded(key) {
|
|
995
|
+
return (stubGapFillExcluded ||= new Set([ERROR_HEADER, BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, REVALIDATE_HEADER, REDIRECT_HEADER, "Location",
|
|
996
|
+
...COMPOSED_BODY_FRAMING].map(header => header.toLowerCase()))).has(key);
|
|
997
|
+
}
|
|
400
998
|
function fillsStubGap(key, headers, response) {
|
|
401
|
-
if (key === "set-cookie" ||
|
|
999
|
+
if (key === "set-cookie" || isStubGapFillExcluded(key)) return false;
|
|
402
1000
|
if (response.body === null && (key === "content-type" || key === "content-length")) return false;
|
|
403
1001
|
return !headers.has(key);
|
|
404
1002
|
}
|
|
405
1003
|
function commitEventResponse(response, event = getRequestEvent()) {
|
|
406
1004
|
const stub = event && event.response;
|
|
407
|
-
if (!stub || !stub.headers || stub.committed)
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
stub.headers.forEach((value, key) => {
|
|
412
|
-
if (fillsStubGap(key, response.headers, response)) hasGaps = true;
|
|
413
|
-
});
|
|
414
|
-
if (!cookies.length && !hasGaps) return response;
|
|
415
|
-
try {
|
|
416
|
-
for (const cookie of cookies) response.headers.append("Set-Cookie", cookie);
|
|
417
|
-
stub.headers.forEach((value, key) => {
|
|
418
|
-
if (fillsStubGap(key, response.headers, response)) response.headers.set(key, value);
|
|
419
|
-
});
|
|
420
|
-
return response;
|
|
421
|
-
} catch {
|
|
1005
|
+
if (!stub || !stub.headers || stub.committed) {
|
|
1006
|
+
if (!event || stub) return response;
|
|
1007
|
+
const trace = traceForEvent(event);
|
|
1008
|
+
if (!hasServerTiming(trace)) return response;
|
|
422
1009
|
const headers = copyInitHeaders(response.headers);
|
|
423
|
-
|
|
424
|
-
stub.headers.forEach((value, key) => {
|
|
425
|
-
if (fillsStubGap(key, headers, response)) headers.set(key, value);
|
|
426
|
-
});
|
|
1010
|
+
appendTraceServerTiming(headers, trace);
|
|
427
1011
|
return new Response(response.body, {
|
|
428
1012
|
status: response.status,
|
|
429
1013
|
statusText: response.statusText,
|
|
430
1014
|
headers
|
|
431
1015
|
});
|
|
432
1016
|
}
|
|
1017
|
+
const cookies = stub.headers.getSetCookie ? stub.headers.getSetCookie() : [];
|
|
1018
|
+
commitResponseStub(stub, {
|
|
1019
|
+
event
|
|
1020
|
+
});
|
|
1021
|
+
let hasGaps = false;
|
|
1022
|
+
stub.headers.forEach((value, key) => {
|
|
1023
|
+
if (fillsStubGap(key, response.headers, response)) hasGaps = true;
|
|
1024
|
+
});
|
|
1025
|
+
const timing = stub.headers.get("server-timing");
|
|
1026
|
+
const mergesTiming = timing !== null && response.headers.has("server-timing");
|
|
1027
|
+
if (!cookies.length && !hasGaps && !mergesTiming) return response;
|
|
1028
|
+
const headers = copyInitHeaders(response.headers);
|
|
1029
|
+
for (const cookie of cookies) headers.append("Set-Cookie", cookie);
|
|
1030
|
+
stub.headers.forEach((value, key) => {
|
|
1031
|
+
if (fillsStubGap(key, headers, response)) headers.set(key, value);
|
|
1032
|
+
});
|
|
1033
|
+
if (mergesTiming) mergeServerTiming(headers, timing);
|
|
1034
|
+
return new Response(response.body, {
|
|
1035
|
+
status: response.status,
|
|
1036
|
+
statusText: response.statusText,
|
|
1037
|
+
headers
|
|
1038
|
+
});
|
|
433
1039
|
}
|
|
434
1040
|
|
|
1041
|
+
let configuredSecret;
|
|
1042
|
+
function setFlashSecret(secret) {
|
|
1043
|
+
configuredSecret = secret;
|
|
1044
|
+
}
|
|
1045
|
+
function resolveSecret() {
|
|
1046
|
+
return configuredSecret !== undefined ? configuredSecret : globalThis.__SOLID_SECRET__;
|
|
1047
|
+
}
|
|
1048
|
+
const FLASH_KEY_DOMAIN = "solid.flash.v1\0";
|
|
1049
|
+
const FLASH_KEY_ITERATIONS = 100_000;
|
|
1050
|
+
let cachedSecret;
|
|
1051
|
+
let cachedKey;
|
|
1052
|
+
function resolveFlashKey() {
|
|
1053
|
+
const secret = resolveSecret();
|
|
1054
|
+
if (typeof secret !== "string" || secret.length === 0) return null;
|
|
1055
|
+
if (secret !== cachedSecret) {
|
|
1056
|
+
cachedSecret = secret;
|
|
1057
|
+
const encoder = new TextEncoder();
|
|
1058
|
+
cachedKey = crypto.subtle.importKey("raw", encoder.encode(secret), "PBKDF2", false, ["deriveKey"]).then(material => crypto.subtle.deriveKey({
|
|
1059
|
+
name: "PBKDF2",
|
|
1060
|
+
salt: encoder.encode(FLASH_KEY_DOMAIN),
|
|
1061
|
+
iterations: FLASH_KEY_ITERATIONS,
|
|
1062
|
+
hash: "SHA-256"
|
|
1063
|
+
}, material, {
|
|
1064
|
+
name: "AES-GCM",
|
|
1065
|
+
length: 256
|
|
1066
|
+
}, false, ["encrypt", "decrypt"]));
|
|
1067
|
+
}
|
|
1068
|
+
return cachedKey;
|
|
1069
|
+
}
|
|
1070
|
+
const FLASH_FORMAT_VERSION = "1.";
|
|
1071
|
+
const IV_BYTES = 12;
|
|
1072
|
+
const GCM_TAG_BYTES = 16;
|
|
1073
|
+
function toBase64url(bytes) {
|
|
1074
|
+
let binary = "";
|
|
1075
|
+
for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
|
|
1076
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
1077
|
+
}
|
|
1078
|
+
function fromBase64url(text) {
|
|
1079
|
+
const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/"));
|
|
1080
|
+
const bytes = new Uint8Array(binary.length);
|
|
1081
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
1082
|
+
return bytes;
|
|
1083
|
+
}
|
|
1084
|
+
async function encryptFlashValue(key, json) {
|
|
1085
|
+
const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
|
|
1086
|
+
const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
|
|
1087
|
+
name: "AES-GCM",
|
|
1088
|
+
iv
|
|
1089
|
+
}, key, new TextEncoder().encode(json)));
|
|
1090
|
+
const packed = new Uint8Array(IV_BYTES + ciphertext.length);
|
|
1091
|
+
packed.set(iv);
|
|
1092
|
+
packed.set(ciphertext, IV_BYTES);
|
|
1093
|
+
return FLASH_FORMAT_VERSION + toBase64url(packed);
|
|
1094
|
+
}
|
|
1095
|
+
async function decryptFlashValue(key, value) {
|
|
1096
|
+
if (!value.startsWith(FLASH_FORMAT_VERSION)) return;
|
|
1097
|
+
const packed = fromBase64url(value.slice(FLASH_FORMAT_VERSION.length));
|
|
1098
|
+
if (packed.length <= IV_BYTES + GCM_TAG_BYTES) return;
|
|
1099
|
+
const plain = await crypto.subtle.decrypt({
|
|
1100
|
+
name: "AES-GCM",
|
|
1101
|
+
iv: packed.subarray(0, IV_BYTES)
|
|
1102
|
+
}, key, packed.subarray(IV_BYTES));
|
|
1103
|
+
return new TextDecoder().decode(plain);
|
|
1104
|
+
}
|
|
435
1105
|
function encodeInputValue(value) {
|
|
436
1106
|
if (value instanceof FormData) return {
|
|
437
1107
|
$f: [...value.entries()].filter(([, v]) => typeof v === "string")
|
|
@@ -452,7 +1122,11 @@ function decodeInputValue(value) {
|
|
|
452
1122
|
}
|
|
453
1123
|
return value;
|
|
454
1124
|
}
|
|
455
|
-
function encodeFlashCookie(url, result, input, thrown) {
|
|
1125
|
+
async function encodeFlashCookie(url, result, input, thrown) {
|
|
1126
|
+
const key = resolveFlashKey();
|
|
1127
|
+
if (!key) {
|
|
1128
|
+
return null;
|
|
1129
|
+
}
|
|
456
1130
|
const isError = result instanceof Error;
|
|
457
1131
|
const payload = {
|
|
458
1132
|
url,
|
|
@@ -461,29 +1135,167 @@ function encodeFlashCookie(url, result, input, thrown) {
|
|
|
461
1135
|
thrown: !!thrown,
|
|
462
1136
|
input: input.map(encodeInputValue)
|
|
463
1137
|
};
|
|
464
|
-
|
|
1138
|
+
if (fitsCookie(payload)) return flashCookie(payload, await key);
|
|
1139
|
+
payload.truncated = true;
|
|
1140
|
+
payload.input = [];
|
|
1141
|
+
if (!fitsCookie(payload)) {
|
|
1142
|
+
if (typeof payload.result === "string") {
|
|
1143
|
+
let prefix = payload.result;
|
|
1144
|
+
while (prefix.length > 0 && !fitsCookie({
|
|
1145
|
+
...payload,
|
|
1146
|
+
result: prefix
|
|
1147
|
+
})) {
|
|
1148
|
+
prefix = prefix.slice(0, prefix.length >> 1);
|
|
1149
|
+
}
|
|
1150
|
+
payload.result = prefix.length > 0 ? prefix : true;
|
|
1151
|
+
} else {
|
|
1152
|
+
payload.result = true;
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
if (!fitsCookie(payload)) return null;
|
|
1156
|
+
return flashCookie(payload, await key);
|
|
1157
|
+
}
|
|
1158
|
+
const FLASH_MAX_AGE_SECONDS = 60;
|
|
1159
|
+
async function flashCookie(payload, key) {
|
|
1160
|
+
return serializeCookie(FLASH_COOKIE, await encryptFlashValue(key, JSON.stringify(payload)), {
|
|
465
1161
|
secure: true,
|
|
466
|
-
httpOnly: true
|
|
1162
|
+
httpOnly: true,
|
|
1163
|
+
sameSite: "lax",
|
|
1164
|
+
maxAge: FLASH_MAX_AGE_SECONDS
|
|
467
1165
|
});
|
|
468
1166
|
}
|
|
469
|
-
|
|
1167
|
+
const COOKIE_PAIR_BUDGET = 4000;
|
|
1168
|
+
function fitsCookie(payload) {
|
|
1169
|
+
const plaintextBytes = new TextEncoder().encode(JSON.stringify(payload)).length;
|
|
1170
|
+
const packedBytes = IV_BYTES + plaintextBytes + GCM_TAG_BYTES;
|
|
1171
|
+
const valueLength = FLASH_FORMAT_VERSION.length + Math.ceil(packedBytes * 4 / 3);
|
|
1172
|
+
return FLASH_COOKIE.length + 1 + valueLength <= COOKIE_PAIR_BUDGET;
|
|
1173
|
+
}
|
|
1174
|
+
async function decodeFlashCookie(cookieHeader) {
|
|
470
1175
|
const match = parseCookieHeader(cookieHeader)[FLASH_COOKIE];
|
|
471
1176
|
if (!match) return;
|
|
472
1177
|
try {
|
|
473
|
-
const
|
|
474
|
-
if (!
|
|
1178
|
+
const key = resolveFlashKey();
|
|
1179
|
+
if (!key) return;
|
|
1180
|
+
const json = await decryptFlashValue(await key, match);
|
|
1181
|
+
if (json === undefined) return;
|
|
1182
|
+
const payload = JSON.parse(json);
|
|
1183
|
+
if (!payload || typeof payload !== "object" || !("result" in payload)) return;
|
|
475
1184
|
const result = payload.error ? new Error(payload.result) : payload.result;
|
|
476
|
-
|
|
1185
|
+
const submission = {
|
|
477
1186
|
input: Array.isArray(payload.input) ? payload.input.map(decodeInputValue) : [],
|
|
478
1187
|
url: payload.url,
|
|
479
1188
|
result: payload.thrown ? undefined : result,
|
|
480
1189
|
error: payload.thrown ? result : undefined
|
|
481
1190
|
};
|
|
1191
|
+
if (payload.truncated) submission.truncated = true;
|
|
1192
|
+
return submission;
|
|
482
1193
|
} catch (error) {
|
|
483
|
-
console.error(error);
|
|
484
1194
|
}
|
|
485
1195
|
}
|
|
486
1196
|
|
|
1197
|
+
const RESPONSE_TAG = "seroval-plugins/web/Response";
|
|
1198
|
+
const REQUEST_TAG = "seroval-plugins/web/Request";
|
|
1199
|
+
const REFUSED_TAGS = [RESPONSE_TAG, REQUEST_TAG];
|
|
1200
|
+
const RESOLVED_PLUGINS = Symbol.for("solid.codec.resolvedPlugins");
|
|
1201
|
+
const REFUSED_ARGUMENT = Symbol("solid.serverFunction.refusedArgument");
|
|
1202
|
+
function refusedArgumentError(name = "Response or Request") {
|
|
1203
|
+
const error = new TypeError(`Server function arguments cannot carry Response or Request values (got a ${name}). ` + "Pass the data it holds — its body, headers or url — instead.");
|
|
1204
|
+
error[REFUSED_ARGUMENT] = true;
|
|
1205
|
+
return error;
|
|
1206
|
+
}
|
|
1207
|
+
function refusedArgument(error) {
|
|
1208
|
+
for (let depth = 0; depth < 4 && error !== null && typeof error === "object"; depth++) {
|
|
1209
|
+
if (error[REFUSED_ARGUMENT] === true) return error;
|
|
1210
|
+
error = error.cause;
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
const refused = plugin => REFUSED_TAGS.includes(plugin.tag);
|
|
1214
|
+
const reachesRefused = plugin => refused(plugin) || !!plugin.extends && plugin.extends.some(reachesRefused);
|
|
1215
|
+
function filterPlugins(plugins, out, seen) {
|
|
1216
|
+
for (const plugin of plugins) {
|
|
1217
|
+
if (seen.has(plugin)) continue;
|
|
1218
|
+
seen.add(plugin);
|
|
1219
|
+
if (refused(plugin)) continue;
|
|
1220
|
+
const severs = !!plugin.extends && plugin.extends.some(reachesRefused);
|
|
1221
|
+
out.push(severs ? {
|
|
1222
|
+
...plugin,
|
|
1223
|
+
extends: undefined
|
|
1224
|
+
} : plugin);
|
|
1225
|
+
if (plugin.extends) filterPlugins(plugin.extends, out, seen);
|
|
1226
|
+
}
|
|
1227
|
+
return out;
|
|
1228
|
+
}
|
|
1229
|
+
let defaultArgumentPlugins;
|
|
1230
|
+
const customArgumentPlugins = new WeakMap();
|
|
1231
|
+
function argumentDecodeCodec(codec, defaults) {
|
|
1232
|
+
const custom = codec && codec.plugins;
|
|
1233
|
+
let plugins = custom ? customArgumentPlugins.get(custom) : defaultArgumentPlugins;
|
|
1234
|
+
if (!plugins) {
|
|
1235
|
+
plugins = filterPlugins(custom ? [...custom, ...defaults] : defaults, [], new Set());
|
|
1236
|
+
if (custom) customArgumentPlugins.set(custom, plugins);else defaultArgumentPlugins = plugins;
|
|
1237
|
+
}
|
|
1238
|
+
return {
|
|
1239
|
+
...codec,
|
|
1240
|
+
[RESOLVED_PLUGINS]: plugins
|
|
1241
|
+
};
|
|
1242
|
+
}
|
|
1243
|
+
function namesRefusedType(payload) {
|
|
1244
|
+
for (const tag of REFUSED_TAGS) if (payload.includes(`"c":"${tag}"`)) return true;
|
|
1245
|
+
return false;
|
|
1246
|
+
}
|
|
1247
|
+
function withArgumentPlugins(argumentCodec, extra) {
|
|
1248
|
+
return {
|
|
1249
|
+
...argumentCodec,
|
|
1250
|
+
[RESOLVED_PLUGINS]: [...extra, ...argumentCodec[RESOLVED_PLUGINS]]
|
|
1251
|
+
};
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
const UPLOAD_ARGS_PART = "args";
|
|
1255
|
+
const UPLOAD_FILE_PART = "file";
|
|
1256
|
+
const UPLOAD_TAG = "solid/server-function-upload";
|
|
1257
|
+
function isBlob(value) {
|
|
1258
|
+
if (typeof Blob !== "undefined" && value instanceof Blob) return true;
|
|
1259
|
+
return typeof value === "object" && value !== null && typeof value.size === "number" && typeof value.type === "string" && typeof value.arrayBuffer === "function" && typeof value.slice === "function";
|
|
1260
|
+
}
|
|
1261
|
+
function malformed() {
|
|
1262
|
+
return new TypeError("Malformed server function upload");
|
|
1263
|
+
}
|
|
1264
|
+
function createUploadDeserializer(form) {
|
|
1265
|
+
const refuse = () => {
|
|
1266
|
+
throw malformed();
|
|
1267
|
+
};
|
|
1268
|
+
return {
|
|
1269
|
+
tag: UPLOAD_TAG,
|
|
1270
|
+
test: () => false,
|
|
1271
|
+
parse: {
|
|
1272
|
+
sync: refuse,
|
|
1273
|
+
async: refuse,
|
|
1274
|
+
stream: refuse
|
|
1275
|
+
},
|
|
1276
|
+
serialize: refuse,
|
|
1277
|
+
deserialize: (node, ctx) => {
|
|
1278
|
+
const index = ctx.deserialize(node.i);
|
|
1279
|
+
if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0) refuse();
|
|
1280
|
+
const part = form.get(UPLOAD_FILE_PART + index);
|
|
1281
|
+
if (!isBlob(part)) refuse();
|
|
1282
|
+
if (node.t === undefined) return part;
|
|
1283
|
+
const type = ctx.deserialize(node.t);
|
|
1284
|
+
if (typeof type !== "string") refuse();
|
|
1285
|
+
if (node.n === undefined) return new Blob([part], {
|
|
1286
|
+
type
|
|
1287
|
+
});
|
|
1288
|
+
const name = ctx.deserialize(node.n);
|
|
1289
|
+
const lastModified = node.l === undefined ? undefined : ctx.deserialize(node.l);
|
|
1290
|
+
if (typeof name !== "string" || typeof lastModified !== "number") refuse();
|
|
1291
|
+
return new File([part], name, {
|
|
1292
|
+
type,
|
|
1293
|
+
lastModified
|
|
1294
|
+
});
|
|
1295
|
+
}
|
|
1296
|
+
};
|
|
1297
|
+
}
|
|
1298
|
+
|
|
487
1299
|
const config = {
|
|
488
1300
|
provideEvent: undefined,
|
|
489
1301
|
wrapInvocation: undefined,
|
|
@@ -493,7 +1305,11 @@ const config = {
|
|
|
493
1305
|
transformDirectResult: undefined,
|
|
494
1306
|
handleNoJS: undefined,
|
|
495
1307
|
endpoint: "/_server",
|
|
496
|
-
csrf: true
|
|
1308
|
+
csrf: true,
|
|
1309
|
+
bodySizeLimit: 1_048_576,
|
|
1310
|
+
maxArguments: 1000,
|
|
1311
|
+
chaosReconnectEvery: 0,
|
|
1312
|
+
buildId: undefined
|
|
497
1313
|
};
|
|
498
1314
|
function configureServerFunctionsServer({
|
|
499
1315
|
provideEvent,
|
|
@@ -505,7 +1321,12 @@ function configureServerFunctionsServer({
|
|
|
505
1321
|
handleNoJS,
|
|
506
1322
|
endpoint,
|
|
507
1323
|
csrf,
|
|
508
|
-
codec
|
|
1324
|
+
codec,
|
|
1325
|
+
bodySizeLimit,
|
|
1326
|
+
maxArguments,
|
|
1327
|
+
secret,
|
|
1328
|
+
chaosReconnectEvery,
|
|
1329
|
+
buildId
|
|
509
1330
|
} = {}) {
|
|
510
1331
|
if (provideEvent !== undefined) config.provideEvent = provideEvent;
|
|
511
1332
|
if (wrapInvocation !== undefined) config.wrapInvocation = wrapInvocation;
|
|
@@ -517,6 +1338,23 @@ function configureServerFunctionsServer({
|
|
|
517
1338
|
if (endpoint !== undefined) config.endpoint = endpoint;
|
|
518
1339
|
if (csrf !== undefined) config.csrf = csrf;
|
|
519
1340
|
if (codec !== undefined) configureServerFunctionsCodec(codec);
|
|
1341
|
+
if (bodySizeLimit !== undefined) config.bodySizeLimit = bodySizeLimit;
|
|
1342
|
+
if (maxArguments !== undefined) config.maxArguments = maxArguments;
|
|
1343
|
+
if (secret !== undefined) setFlashSecret(secret);
|
|
1344
|
+
if (chaosReconnectEvery !== undefined) config.chaosReconnectEvery = chaosReconnectEvery;
|
|
1345
|
+
if (buildId !== undefined) config.buildId = buildId;
|
|
1346
|
+
}
|
|
1347
|
+
const flightSources = new Map();
|
|
1348
|
+
function registerFlightDataSource(source, hook) {
|
|
1349
|
+
assertFlightSource(source);
|
|
1350
|
+
flightSources.set(source, hook);
|
|
1351
|
+
return () => {
|
|
1352
|
+
if (flightSources.get(source) === hook) flightSources.delete(source);
|
|
1353
|
+
};
|
|
1354
|
+
}
|
|
1355
|
+
function resolveWrapInvocation(hook) {
|
|
1356
|
+
if (hook === undefined || typeof hook === "function") return hook;
|
|
1357
|
+
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.`);
|
|
520
1358
|
}
|
|
521
1359
|
function provideEvent(event, fn) {
|
|
522
1360
|
if (config.provideEvent) return config.provideEvent(event, fn);
|
|
@@ -524,117 +1362,456 @@ function provideEvent(event, fn) {
|
|
|
524
1362
|
if (ctx) return ctx.run(event, fn);
|
|
525
1363
|
throw new Error("No request event provider. Configure one with configureServerFunctionsServer({ provideEvent }).");
|
|
526
1364
|
}
|
|
527
|
-
const
|
|
528
|
-
const
|
|
529
|
-
|
|
530
|
-
let
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
1365
|
+
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.";
|
|
1366
|
+
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.";
|
|
1367
|
+
function provideEventOnce(provide, event, run) {
|
|
1368
|
+
let invocations = 0;
|
|
1369
|
+
const settle = () => {
|
|
1370
|
+
if (invocations !== 1) throw new Error(invocations === 0 ? PROVIDE_EVENT_NEVER : PROVIDE_EVENT_TWICE);
|
|
1371
|
+
};
|
|
1372
|
+
const result = provide(event, () => {
|
|
1373
|
+
if (++invocations > 1) throw new Error(PROVIDE_EVENT_TWICE);
|
|
1374
|
+
return run();
|
|
537
1375
|
});
|
|
1376
|
+
const promised = nativePromise(result);
|
|
1377
|
+
if (promised) {
|
|
1378
|
+
return promised.then(value => {
|
|
1379
|
+
settle();
|
|
1380
|
+
return value;
|
|
1381
|
+
});
|
|
1382
|
+
}
|
|
1383
|
+
settle();
|
|
1384
|
+
return result;
|
|
1385
|
+
}
|
|
1386
|
+
function scopeDeferredResult(value, scope) {
|
|
1387
|
+
const bound = bindDeferredBody(value, scope);
|
|
1388
|
+
if (bound !== value || value === null || typeof value !== "object") return bound;
|
|
1389
|
+
return scopeDeferredContents(value, scope);
|
|
1390
|
+
}
|
|
1391
|
+
class ScopeFrame {
|
|
1392
|
+
constructor(value, prototype, keys, i, first) {
|
|
1393
|
+
this.value = value;
|
|
1394
|
+
this.prototype = prototype;
|
|
1395
|
+
this.next = null;
|
|
1396
|
+
this.keys = keys;
|
|
1397
|
+
this.i = i;
|
|
1398
|
+
this.first = first;
|
|
1399
|
+
this.descriptors = null;
|
|
1400
|
+
this.snapshotted = false;
|
|
1401
|
+
this.changed = false;
|
|
1402
|
+
}
|
|
538
1403
|
}
|
|
539
|
-
function
|
|
540
|
-
|
|
541
|
-
REGISTRATIONS.set(id, callback);
|
|
542
|
-
return callback;
|
|
1404
|
+
function frameShell(frame) {
|
|
1405
|
+
return frame.next ??= frame.keys ? Object.create(frame.prototype, frame.descriptors ?? Object.getOwnPropertyDescriptors(frame.value)) : frame.value.slice();
|
|
543
1406
|
}
|
|
544
|
-
function
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
1407
|
+
function writableValue(descriptor) {
|
|
1408
|
+
return descriptor !== undefined && "value" in descriptor && descriptor.writable === true ? descriptor.value : undefined;
|
|
1409
|
+
}
|
|
1410
|
+
function carrierSlot(frame, key) {
|
|
1411
|
+
return writableValue(frame.descriptors ? frame.descriptors[key] : Object.getOwnPropertyDescriptor(frame.value, key));
|
|
1412
|
+
}
|
|
1413
|
+
function snapshotFrames(stack) {
|
|
1414
|
+
for (let k = stack.length - 1; k >= 0 && !stack[k].snapshotted; k--) {
|
|
1415
|
+
const frame = stack[k];
|
|
1416
|
+
frame.snapshotted = true;
|
|
1417
|
+
if (frame.keys) frame.descriptors = Object.getOwnPropertyDescriptors(frame.value);
|
|
548
1418
|
}
|
|
549
|
-
throw new Error("invalid server function: " + id);
|
|
550
1419
|
}
|
|
551
|
-
function
|
|
552
|
-
|
|
553
|
-
return {
|
|
554
|
-
id,
|
|
555
|
-
fn,
|
|
556
|
-
name
|
|
557
|
-
};
|
|
1420
|
+
function isLeaf(value) {
|
|
1421
|
+
return value === null || typeof value !== "object" && typeof value !== "function";
|
|
558
1422
|
}
|
|
559
|
-
function
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
1423
|
+
function sharedPrototypesInert() {
|
|
1424
|
+
const {
|
|
1425
|
+
toStringTag,
|
|
1426
|
+
asyncIterator,
|
|
1427
|
+
iterator,
|
|
1428
|
+
hasInstance
|
|
1429
|
+
} = Symbol;
|
|
1430
|
+
return !(Object.hasOwn(Promise, hasInstance) || typeof ReadableStream !== "undefined" && Object.hasOwn(ReadableStream, hasInstance) || Object.hasOwn(Object.prototype, toStringTag) || Object.hasOwn(Object.prototype, asyncIterator) || Object.hasOwn(Object.prototype, iterator) || Object.hasOwn(Array.prototype, toStringTag) || Object.hasOwn(Array.prototype, asyncIterator));
|
|
1431
|
+
}
|
|
1432
|
+
function isInertCarrier(value, prototype, isArray) {
|
|
1433
|
+
const {
|
|
1434
|
+
toStringTag,
|
|
1435
|
+
asyncIterator,
|
|
1436
|
+
iterator
|
|
1437
|
+
} = Symbol;
|
|
1438
|
+
return (isArray ? prototype === Array.prototype : prototype === Object.prototype || prototype === null) && !Object.hasOwn(value, toStringTag) && !Object.hasOwn(value, asyncIterator) && (isArray || !Object.hasOwn(value, iterator)) && typeof value[asyncIterator] !== "function" && (isArray || typeof value[iterator] !== "function");
|
|
1439
|
+
}
|
|
1440
|
+
function enterScopeCarrier(value, state) {
|
|
1441
|
+
if (isLeaf(value)) return value;
|
|
1442
|
+
const seen = state.seen.get(value);
|
|
1443
|
+
if (seen !== undefined) {
|
|
1444
|
+
state.cyclic.add(value);
|
|
1445
|
+
return seen instanceof ScopeFrame ? frameShell(seen) : seen;
|
|
1446
|
+
}
|
|
1447
|
+
let isArray = false;
|
|
1448
|
+
let prototype;
|
|
1449
|
+
if (typeof value === "object") {
|
|
1450
|
+
isArray = Array.isArray(value);
|
|
1451
|
+
prototype = Object.getPrototypeOf(value);
|
|
1452
|
+
}
|
|
1453
|
+
if (!state.inert || prototype === undefined || !isInertCarrier(value, prototype, isArray)) {
|
|
1454
|
+
snapshotFrames(state.stack);
|
|
1455
|
+
const bound = bindDeferredBody(value, state.scope);
|
|
1456
|
+
if (bound !== value) {
|
|
1457
|
+
state.seen.set(value, bound);
|
|
1458
|
+
return bound;
|
|
1459
|
+
}
|
|
1460
|
+
if (typeof value !== "object") return value;
|
|
1461
|
+
}
|
|
1462
|
+
if (isArray) {
|
|
1463
|
+
if (Object.isFrozen(value)) {
|
|
1464
|
+
state.seen.set(value, value);
|
|
1465
|
+
return value;
|
|
1466
|
+
}
|
|
1467
|
+
let i = 0;
|
|
1468
|
+
let first;
|
|
1469
|
+
while (i < value.length && isLeaf(first = value[i])) i++;
|
|
1470
|
+
if (i === value.length) {
|
|
1471
|
+
state.seen.set(value, value);
|
|
1472
|
+
return value;
|
|
1473
|
+
}
|
|
1474
|
+
const frame = new ScopeFrame(value, null, null, i, first);
|
|
1475
|
+
state.seen.set(value, frame);
|
|
1476
|
+
return frame;
|
|
1477
|
+
}
|
|
1478
|
+
if (prototype !== Object.prototype && prototype !== null) {
|
|
1479
|
+
state.seen.set(value, value);
|
|
1480
|
+
return value;
|
|
1481
|
+
}
|
|
1482
|
+
const keys = Object.keys(value);
|
|
1483
|
+
let i = 0;
|
|
1484
|
+
let first;
|
|
1485
|
+
while (i < keys.length && isLeaf(first = writableValue(Object.getOwnPropertyDescriptor(value, keys[i])))) i++;
|
|
1486
|
+
if (i === keys.length) {
|
|
1487
|
+
state.seen.set(value, value);
|
|
1488
|
+
return value;
|
|
1489
|
+
}
|
|
1490
|
+
if (Object.isFrozen(value)) {
|
|
1491
|
+
state.seen.set(value, value);
|
|
1492
|
+
return value;
|
|
1493
|
+
}
|
|
1494
|
+
const frame = new ScopeFrame(value, prototype, keys, i, first);
|
|
1495
|
+
state.seen.set(value, frame);
|
|
1496
|
+
return frame;
|
|
1497
|
+
}
|
|
1498
|
+
function scopeDeferredContents(root, scope) {
|
|
1499
|
+
const stack = [];
|
|
1500
|
+
const state = {
|
|
1501
|
+
seen: new Map(),
|
|
1502
|
+
cyclic: new Set(),
|
|
1503
|
+
scope,
|
|
1504
|
+
inert: sharedPrototypesInert(),
|
|
1505
|
+
stack
|
|
1506
|
+
};
|
|
1507
|
+
const entered = enterScopeCarrier(root, state);
|
|
1508
|
+
if (!(entered instanceof ScopeFrame)) return entered;
|
|
1509
|
+
stack.push(entered);
|
|
1510
|
+
let delivered = NOTHING;
|
|
1511
|
+
for (;;) {
|
|
1512
|
+
const top = stack[stack.length - 1];
|
|
1513
|
+
const length = top.keys ? top.keys.length : top.value.length;
|
|
1514
|
+
let pushed = null;
|
|
1515
|
+
while (top.i < length) {
|
|
1516
|
+
const i = top.i;
|
|
1517
|
+
let original;
|
|
1518
|
+
if (top.first !== NOTHING) {
|
|
1519
|
+
original = top.first;
|
|
1520
|
+
top.first = NOTHING;
|
|
1521
|
+
} else {
|
|
1522
|
+
original = top.keys ? carrierSlot(top, top.keys[i]) : top.value[i];
|
|
1523
|
+
}
|
|
1524
|
+
let bound;
|
|
1525
|
+
if (delivered !== NOTHING) {
|
|
1526
|
+
bound = delivered;
|
|
1527
|
+
delivered = NOTHING;
|
|
1528
|
+
} else {
|
|
1529
|
+
bound = enterScopeCarrier(original, state);
|
|
1530
|
+
if (bound instanceof ScopeFrame) {
|
|
1531
|
+
pushed = bound;
|
|
1532
|
+
break;
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1535
|
+
if (bound !== original) {
|
|
1536
|
+
if (top.keys) frameShell(top)[top.keys[i]] = bound;else frameShell(top)[i] = bound;
|
|
1537
|
+
top.changed = true;
|
|
1538
|
+
}
|
|
1539
|
+
top.i++;
|
|
1540
|
+
}
|
|
1541
|
+
if (pushed !== null) {
|
|
1542
|
+
stack.push(pushed);
|
|
1543
|
+
continue;
|
|
1544
|
+
}
|
|
1545
|
+
stack.pop();
|
|
1546
|
+
let out;
|
|
1547
|
+
if (top.changed || state.cyclic.has(top.value)) {
|
|
1548
|
+
out = frameShell(top);
|
|
1549
|
+
state.seen.set(top.value, out);
|
|
1550
|
+
} else {
|
|
1551
|
+
state.seen.set(top.value, top.value);
|
|
1552
|
+
out = top.value;
|
|
1553
|
+
}
|
|
1554
|
+
if (stack.length === 0) return out;
|
|
1555
|
+
delivered = out;
|
|
1556
|
+
}
|
|
1557
|
+
}
|
|
1558
|
+
function bindDeferredBody(value, scope) {
|
|
1559
|
+
if (isLeaf(value)) return value;
|
|
1560
|
+
const promised = scope(() => nativePromise(value));
|
|
1561
|
+
if (promised) {
|
|
1562
|
+
return promised.then(result => scope(() => scopeDeferredResult(result, scope)));
|
|
1563
|
+
}
|
|
1564
|
+
if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) {
|
|
1565
|
+
let reader;
|
|
1566
|
+
return new ReadableStream({
|
|
1567
|
+
async pull(controller) {
|
|
1568
|
+
try {
|
|
1569
|
+
const step = await scope(() => {
|
|
1570
|
+
if (!reader) reader = value.getReader();
|
|
1571
|
+
return reader.read();
|
|
1572
|
+
});
|
|
1573
|
+
if (step.done) controller.close();else controller.enqueue(step.value);
|
|
1574
|
+
} catch (error) {
|
|
1575
|
+
controller.error(error);
|
|
1576
|
+
}
|
|
1577
|
+
},
|
|
1578
|
+
cancel(reason) {
|
|
1579
|
+
return scope(() => reader ? reader.cancel(reason) : value.cancel(reason));
|
|
1580
|
+
}
|
|
1581
|
+
}, {
|
|
1582
|
+
highWaterMark: 0
|
|
1583
|
+
});
|
|
1584
|
+
}
|
|
1585
|
+
const scopedIterator = symbol => ({
|
|
1586
|
+
[symbol]() {
|
|
1587
|
+
const iterator = scope(() => value[symbol]());
|
|
1588
|
+
return new Proxy(iterator, {
|
|
1589
|
+
get(target, property) {
|
|
1590
|
+
const member = Reflect.get(target, property, target);
|
|
1591
|
+
return typeof member === "function" && (property === "next" || property === "return" || property === "throw") ? (...args) => scope(() => member.apply(target, args)) : member;
|
|
1592
|
+
}
|
|
586
1593
|
});
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
1594
|
+
}
|
|
1595
|
+
});
|
|
1596
|
+
if (typeof value[Symbol.asyncIterator] === "function") {
|
|
1597
|
+
return scopedIterator(Symbol.asyncIterator);
|
|
1598
|
+
}
|
|
1599
|
+
if (typeof value[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value)) {
|
|
1600
|
+
return scopedIterator(Symbol.iterator);
|
|
1601
|
+
}
|
|
1602
|
+
return value;
|
|
1603
|
+
}
|
|
1604
|
+
function processState(key, create) {
|
|
1605
|
+
const slot = Symbol.for(key);
|
|
1606
|
+
return globalThis[slot] || (globalThis[slot] = create());
|
|
1607
|
+
}
|
|
1608
|
+
const REGISTRATIONS = processState("solid.ServerFunctionRegistrations", () => new Map());
|
|
1609
|
+
const METHODS = processState("solid.ServerFunctionMethods", () => new Map());
|
|
1610
|
+
const REFERENCE_BINDINGS = processState("solid.ServerFunctionReferenceBindings", () => new WeakMap());
|
|
1611
|
+
const CARRIED = processState("solid.ServerFunctionCarriedGrants", () => new Set());
|
|
1612
|
+
function declaresRead(id) {
|
|
1613
|
+
const granted = METHODS.get(id);
|
|
1614
|
+
return granted !== undefined && granted === REGISTRATIONS.get(id);
|
|
1615
|
+
}
|
|
1616
|
+
const INVOCATIONS = new WeakMap();
|
|
1617
|
+
let rpcProvided = false;
|
|
1618
|
+
function provideRPC() {
|
|
1619
|
+
if (rpcProvided) return;
|
|
1620
|
+
rpcProvided = true;
|
|
1621
|
+
provideServerFunctionRPC({
|
|
1622
|
+
GET,
|
|
1623
|
+
decodeResponse
|
|
1624
|
+
});
|
|
1625
|
+
}
|
|
1626
|
+
function registerServerFunction(id, callback) {
|
|
1627
|
+
provideRPC();
|
|
1628
|
+
if (REGISTRATIONS.get(id) !== callback) {
|
|
1629
|
+
if (DEV && declaresRead(id)) {
|
|
1630
|
+
METHODS.set(id, callback);
|
|
1631
|
+
CARRIED.add(id);
|
|
1632
|
+
} else {
|
|
1633
|
+
METHODS.delete(id);
|
|
1634
|
+
CARRIED.delete(id);
|
|
1635
|
+
}
|
|
1636
|
+
}
|
|
1637
|
+
REGISTRATIONS.set(id, callback);
|
|
1638
|
+
return callback;
|
|
1639
|
+
}
|
|
1640
|
+
function getServerFunction(id) {
|
|
1641
|
+
const fn = REGISTRATIONS.get(id);
|
|
1642
|
+
if (fn) {
|
|
1643
|
+
return fn;
|
|
1644
|
+
}
|
|
1645
|
+
throw new Error("invalid server function: " + id);
|
|
1646
|
+
}
|
|
1647
|
+
function registerServerReference(id, fn, name) {
|
|
1648
|
+
if (typeof fn !== "function") {
|
|
1649
|
+
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.`);
|
|
1650
|
+
}
|
|
1651
|
+
registerServerFunction(id, fn);
|
|
1652
|
+
return {
|
|
1653
|
+
id,
|
|
1654
|
+
fn,
|
|
1655
|
+
name
|
|
1656
|
+
};
|
|
1657
|
+
}
|
|
1658
|
+
function inProcessInvoker(call) {
|
|
1659
|
+
return (args, options) => {
|
|
1660
|
+
const signal = options && options.signal;
|
|
1661
|
+
if (!signal) return call(...args);
|
|
1662
|
+
if (signal.aborted) return Promise.reject(signal.reason);
|
|
1663
|
+
return new Promise((resolve, reject) => {
|
|
1664
|
+
const onAbort = () => reject(signal.reason);
|
|
1665
|
+
signal.addEventListener("abort", onAbort, {
|
|
1666
|
+
once: true
|
|
1667
|
+
});
|
|
1668
|
+
let result;
|
|
1669
|
+
try {
|
|
1670
|
+
result = call(...args);
|
|
1671
|
+
} catch (error) {
|
|
1672
|
+
signal.removeEventListener("abort", onAbort);
|
|
1673
|
+
return reject(error);
|
|
1674
|
+
}
|
|
1675
|
+
Promise.resolve(result).then(value => {
|
|
1676
|
+
signal.removeEventListener("abort", onAbort);
|
|
1677
|
+
resolve(value);
|
|
1678
|
+
}, error => {
|
|
1679
|
+
signal.removeEventListener("abort", onAbort);
|
|
1680
|
+
reject(error);
|
|
1681
|
+
});
|
|
1682
|
+
});
|
|
1683
|
+
};
|
|
1684
|
+
}
|
|
1685
|
+
function createServerReference({
|
|
1686
|
+
id,
|
|
1687
|
+
fn,
|
|
1688
|
+
name
|
|
1689
|
+
}) {
|
|
1690
|
+
if (typeof fn !== "function") throw new Error("Export from a 'use server' module must be a function");
|
|
1691
|
+
provideRPC();
|
|
1692
|
+
const metadata = name === undefined ? {} : {
|
|
1693
|
+
name
|
|
1694
|
+
};
|
|
1695
|
+
const invokeChannel = inProcessInvoker((...args) => proxy(...args));
|
|
1696
|
+
const proxy = new Proxy(fn, {
|
|
1697
|
+
get(target, prop) {
|
|
1698
|
+
if (prop === "id") return id;
|
|
1699
|
+
if (prop === "url") {
|
|
1700
|
+
return serverFunctionAddress(config.endpoint, id);
|
|
1701
|
+
}
|
|
1702
|
+
if (prop === SERVER_FUNCTION_METADATA) return metadata;
|
|
1703
|
+
if (prop === SERVER_FUNCTION_INVOKE) return invokeChannel;
|
|
1704
|
+
return target[prop];
|
|
1705
|
+
},
|
|
1706
|
+
apply(target, thisArg, args) {
|
|
1707
|
+
const ogEvt = getRequestEvent();
|
|
1708
|
+
if (!ogEvt) throw new Error("Cannot call server function outside of a request");
|
|
1709
|
+
const evt = {
|
|
1710
|
+
...ogEvt,
|
|
1711
|
+
locals: {
|
|
1712
|
+
...ogEvt.locals
|
|
1713
|
+
}
|
|
1714
|
+
};
|
|
1715
|
+
INVOCATIONS.set(evt, {
|
|
1716
|
+
id,
|
|
1717
|
+
live: false
|
|
596
1718
|
});
|
|
1719
|
+
evt.serverOnly = true;
|
|
1720
|
+
const scope = run => provideEvent(evt, run);
|
|
1721
|
+
const wrap = resolveWrapInvocation(config.wrapInvocation);
|
|
1722
|
+
const hook = requestErrorHook(ogEvt);
|
|
1723
|
+
let result;
|
|
1724
|
+
try {
|
|
1725
|
+
result = provideEventOnce(provideEvent, evt, () => {
|
|
1726
|
+
const run = () => fn.apply(thisArg, args);
|
|
1727
|
+
return observeInvocation({
|
|
1728
|
+
id,
|
|
1729
|
+
direct: true,
|
|
1730
|
+
event: evt,
|
|
1731
|
+
args
|
|
1732
|
+
}, () => reportDirectFailure(() => wrap ? wrap(run, {
|
|
1733
|
+
id,
|
|
1734
|
+
args,
|
|
1735
|
+
event: evt,
|
|
1736
|
+
direct: true
|
|
1737
|
+
}) : run(), id, hook));
|
|
1738
|
+
});
|
|
1739
|
+
} catch (error) {
|
|
1740
|
+
throw directEnvelopeValue(error, evt);
|
|
1741
|
+
}
|
|
1742
|
+
result = result && typeof result.then === "function" ? result.then(value => directEnvelopeValue(value, evt), error => {
|
|
1743
|
+
throw directEnvelopeValue(error, evt);
|
|
1744
|
+
}) : directEnvelopeValue(result, evt);
|
|
1745
|
+
result = scopeDeferredResult(result, scope);
|
|
597
1746
|
const transform = config.transformDirectResult;
|
|
598
1747
|
if (transform && result && typeof result.then === "function") {
|
|
599
|
-
return result.then(value => transform(value, {
|
|
1748
|
+
return result.then(value => scopeDeferredResult(transform(value, {
|
|
600
1749
|
id,
|
|
601
1750
|
args,
|
|
602
1751
|
event: evt
|
|
603
|
-
}));
|
|
1752
|
+
}), scope));
|
|
604
1753
|
}
|
|
605
|
-
return transform ? transform(result, {
|
|
1754
|
+
return transform ? scopeDeferredResult(transform(result, {
|
|
606
1755
|
id,
|
|
607
1756
|
args,
|
|
608
1757
|
event: evt
|
|
609
|
-
}) : result;
|
|
1758
|
+
}), scope) : result;
|
|
610
1759
|
}
|
|
611
1760
|
});
|
|
1761
|
+
REFERENCE_BINDINGS.set(proxy, fn);
|
|
1762
|
+
return proxy;
|
|
612
1763
|
}
|
|
613
1764
|
function GET(fn) {
|
|
614
1765
|
if (!isServerFunction(fn) || typeof fn.id !== "string") {
|
|
615
1766
|
throw new Error("GET expects a server function reference");
|
|
616
1767
|
}
|
|
617
|
-
|
|
618
|
-
|
|
1768
|
+
const id = fn.id;
|
|
1769
|
+
const binding = REFERENCE_BINDINGS.has(fn) ? REFERENCE_BINDINGS.get(fn) : REGISTRATIONS.get(id);
|
|
1770
|
+
const existing = METHODS.get(id);
|
|
1771
|
+
if (existing !== undefined && existing !== binding) {
|
|
1772
|
+
if (CARRIED.has(id)) return fn;
|
|
1773
|
+
if (DEV) {
|
|
1774
|
+
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.`);
|
|
1775
|
+
}
|
|
1776
|
+
METHODS.delete(id);
|
|
1777
|
+
return fn;
|
|
1778
|
+
}
|
|
1779
|
+
METHODS.set(id, binding);
|
|
1780
|
+
CARRIED.delete(id);
|
|
1781
|
+
const reference = withMeta(fn, {
|
|
619
1782
|
method: "GET"
|
|
620
1783
|
});
|
|
1784
|
+
guardDeclaredMethod(getServerFunctionMetadata(reference), id);
|
|
1785
|
+
return reference;
|
|
1786
|
+
}
|
|
1787
|
+
function guardDeclaredMethod(metadata, id) {
|
|
1788
|
+
let declared = metadata.method;
|
|
1789
|
+
Object.defineProperty(metadata, "method", {
|
|
1790
|
+
configurable: true,
|
|
1791
|
+
enumerable: true,
|
|
1792
|
+
get: () => declared,
|
|
1793
|
+
set(next) {
|
|
1794
|
+
if (next === declared) return;
|
|
1795
|
+
if (DEV) {
|
|
1796
|
+
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.`);
|
|
1797
|
+
}
|
|
1798
|
+
METHODS.delete(id);
|
|
1799
|
+
declared = next;
|
|
1800
|
+
}
|
|
1801
|
+
});
|
|
621
1802
|
}
|
|
622
1803
|
function live(fn) {
|
|
623
1804
|
if (!isServerFunction(fn) || typeof fn.id !== "string") {
|
|
624
1805
|
throw new Error("live expects a server function reference");
|
|
625
1806
|
}
|
|
1807
|
+
if (getServerFunctionMetadata(fn)?.method !== "GET") fn = GET(fn);
|
|
626
1808
|
const metadata = {
|
|
627
1809
|
...getServerFunctionMetadata(fn),
|
|
628
1810
|
live: true
|
|
629
1811
|
};
|
|
630
|
-
const wrapped = async (...args) =>
|
|
631
|
-
const result = await fn(...args);
|
|
632
|
-
if (result !== null && typeof result === "object" && result[Symbol.asyncIterator]) {
|
|
633
|
-
result[LIVE_SOURCE] = true;
|
|
634
|
-
}
|
|
635
|
-
return result;
|
|
636
|
-
};
|
|
1812
|
+
const wrapped = async (...args) => brandLive(await fn(...args));
|
|
637
1813
|
wrapped[SERVER_FUNCTION_METADATA] = metadata;
|
|
1814
|
+
wrapped[SERVER_FUNCTION_INVOKE] = inProcessInvoker(wrapped);
|
|
638
1815
|
wrapped.id = fn.id;
|
|
639
1816
|
Object.defineProperty(wrapped, "url", {
|
|
640
1817
|
get: () => fn.url,
|
|
@@ -642,59 +1819,255 @@ function live(fn) {
|
|
|
642
1819
|
});
|
|
643
1820
|
return wrapped;
|
|
644
1821
|
}
|
|
1822
|
+
function broadcast(fn) {
|
|
1823
|
+
const ref = live(fn);
|
|
1824
|
+
ref[SERVER_FUNCTION_METADATA].broadcast = true;
|
|
1825
|
+
BROADCASTS.add(fn.id);
|
|
1826
|
+
return ref;
|
|
1827
|
+
}
|
|
1828
|
+
function encodedArguments(request, url, argsEncoding, argumentBytes) {
|
|
1829
|
+
if (request.method !== "POST") return argsEncoding || url.search;
|
|
1830
|
+
if (!argumentBytes) return undefined;
|
|
1831
|
+
return (request.headers.get("content-type") || "") + "\0" + (argsEncoding || "") + "\0" + new TextDecoder("latin1").decode(argumentBytes);
|
|
1832
|
+
}
|
|
1833
|
+
const BROADCASTS = new Set();
|
|
1834
|
+
function brandLive(answer) {
|
|
1835
|
+
if (typeof answer === "function" || answer !== null && typeof answer === "object" && answer[Symbol.asyncIterator]) {
|
|
1836
|
+
answer[LIVE_SOURCE] = true;
|
|
1837
|
+
}
|
|
1838
|
+
return answer;
|
|
1839
|
+
}
|
|
645
1840
|
function getServerFunctionInvocation() {
|
|
646
1841
|
return getEventServerFunctionInvocation(getRequestEvent());
|
|
647
1842
|
}
|
|
648
1843
|
function getEventServerFunctionInvocation(event) {
|
|
649
1844
|
return event && INVOCATIONS.get(event);
|
|
650
1845
|
}
|
|
651
|
-
function
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
1846
|
+
function resolveAddress(url) {
|
|
1847
|
+
return parseServerFunctionAddress(url.pathname, config.endpoint);
|
|
1848
|
+
}
|
|
1849
|
+
const DECODE_DEPTH_LIMIT = 64;
|
|
1850
|
+
function assertDecodeDepth(value) {
|
|
1851
|
+
let level = [value];
|
|
1852
|
+
for (let depth = 0; level.length > 0; depth++) {
|
|
1853
|
+
if (depth > DECODE_DEPTH_LIMIT) {
|
|
1854
|
+
throw new TypeError("Server function arguments exceed the decode depth limit");
|
|
1855
|
+
}
|
|
1856
|
+
const next = [];
|
|
1857
|
+
for (const node of level) {
|
|
1858
|
+
if (node === null || typeof node !== "object") continue;
|
|
1859
|
+
if (Array.isArray(node)) {
|
|
1860
|
+
for (const child of node) next.push(child);
|
|
1861
|
+
} else {
|
|
1862
|
+
for (const key of Object.keys(node)) next.push(node[key]);
|
|
1863
|
+
}
|
|
1864
|
+
}
|
|
1865
|
+
level = next;
|
|
655
1866
|
}
|
|
656
|
-
return url.searchParams.get("id");
|
|
657
1867
|
}
|
|
658
|
-
|
|
1868
|
+
const UNSAFE_ARGUMENT_KEYS = ["__proto__", "constructor", "prototype"];
|
|
1869
|
+
function stripUnsafeArgumentKeys(value) {
|
|
1870
|
+
const stack = [value];
|
|
1871
|
+
const seen = new Set();
|
|
1872
|
+
while (stack.length) {
|
|
1873
|
+
const v = stack.pop();
|
|
1874
|
+
if (v === null || typeof v !== "object" || seen.has(v)) continue;
|
|
1875
|
+
seen.add(v);
|
|
1876
|
+
for (const key of UNSAFE_ARGUMENT_KEYS) {
|
|
1877
|
+
delete v[key];
|
|
1878
|
+
}
|
|
1879
|
+
for (const key of Object.keys(v)) stack.push(v[key]);
|
|
1880
|
+
if (v instanceof Map) {
|
|
1881
|
+
for (const [k, entry] of v) stack.push(k, entry);
|
|
1882
|
+
} else if (v instanceof Set) {
|
|
1883
|
+
for (const member of v) stack.push(member);
|
|
1884
|
+
}
|
|
1885
|
+
}
|
|
1886
|
+
return value;
|
|
1887
|
+
}
|
|
1888
|
+
async function bufferBodyWithin(request, limit) {
|
|
1889
|
+
const reader = request.body.getReader();
|
|
1890
|
+
const signal = request.signal;
|
|
1891
|
+
const chunks = [];
|
|
1892
|
+
let total = 0;
|
|
1893
|
+
const onAbort = () => {
|
|
1894
|
+
reader.cancel(signal.reason).catch(() => {});
|
|
1895
|
+
};
|
|
1896
|
+
if (signal.aborted) onAbort();else signal.addEventListener("abort", onAbort, {
|
|
1897
|
+
once: true
|
|
1898
|
+
});
|
|
1899
|
+
try {
|
|
1900
|
+
for (;;) {
|
|
1901
|
+
const {
|
|
1902
|
+
done,
|
|
1903
|
+
value
|
|
1904
|
+
} = await reader.read();
|
|
1905
|
+
if (signal.aborted) throw signal.reason;
|
|
1906
|
+
if (done) break;
|
|
1907
|
+
total += value.byteLength;
|
|
1908
|
+
if (total > limit) {
|
|
1909
|
+
reader.cancel().catch(() => {});
|
|
1910
|
+
return null;
|
|
1911
|
+
}
|
|
1912
|
+
chunks.push(value);
|
|
1913
|
+
}
|
|
1914
|
+
} catch (error) {
|
|
1915
|
+
reader.cancel(error).catch(() => {});
|
|
1916
|
+
throw error;
|
|
1917
|
+
} finally {
|
|
1918
|
+
signal.removeEventListener("abort", onAbort);
|
|
1919
|
+
reader.releaseLock();
|
|
1920
|
+
}
|
|
1921
|
+
const body = new Uint8Array(total);
|
|
1922
|
+
let offset = 0;
|
|
1923
|
+
for (const chunk of chunks) {
|
|
1924
|
+
body.set(chunk, offset);
|
|
1925
|
+
offset += chunk.byteLength;
|
|
1926
|
+
}
|
|
1927
|
+
return body;
|
|
1928
|
+
}
|
|
1929
|
+
function withBufferedBody(request, body) {
|
|
1930
|
+
return new Request(request.url, {
|
|
1931
|
+
method: request.method,
|
|
1932
|
+
headers: request.headers,
|
|
1933
|
+
signal: request.signal,
|
|
1934
|
+
body
|
|
1935
|
+
});
|
|
1936
|
+
}
|
|
1937
|
+
const KNOWN_BODY_FORMATS = new Set(Object.values(BodyFormat));
|
|
1938
|
+
const FORMAT_SKEW = Symbol("solid.serverFunction.formatSkew");
|
|
1939
|
+
function unknownFormatError(tag) {
|
|
1940
|
+
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.");
|
|
1941
|
+
error[FORMAT_SKEW] = true;
|
|
1942
|
+
return error;
|
|
1943
|
+
}
|
|
1944
|
+
async function decodeArguments(decode, payload) {
|
|
1945
|
+
if (payload === null) return await decode(undefined);
|
|
1946
|
+
const refuseNamed = () => {
|
|
1947
|
+
const text = typeof payload === "string" ? payload : new TextDecoder().decode(payload);
|
|
1948
|
+
if (namesRefusedType(text)) throw refusedArgumentError();
|
|
1949
|
+
};
|
|
1950
|
+
const connection = {};
|
|
1951
|
+
let value;
|
|
1952
|
+
try {
|
|
1953
|
+
value = await decode({
|
|
1954
|
+
connection
|
|
1955
|
+
});
|
|
1956
|
+
} catch (error) {
|
|
1957
|
+
if (connection.ended) connection.ended.then(end => end.sweep());
|
|
1958
|
+
refuseNamed();
|
|
1959
|
+
throw error;
|
|
1960
|
+
}
|
|
1961
|
+
if (connection.ended) {
|
|
1962
|
+
const {
|
|
1963
|
+
open,
|
|
1964
|
+
sweep
|
|
1965
|
+
} = await connection.ended;
|
|
1966
|
+
sweep();
|
|
1967
|
+
if (open) refuseNamed();
|
|
1968
|
+
}
|
|
1969
|
+
return value;
|
|
1970
|
+
}
|
|
1971
|
+
let decodeModule;
|
|
1972
|
+
async function loadArgumentCodec(codec) {
|
|
1973
|
+
decodeModule = await import('@solidjs/web/serialization/decode');
|
|
1974
|
+
return argumentDecodeCodec(codec, decodeModule.DEFAULT_WEB_PLUGINS);
|
|
1975
|
+
}
|
|
1976
|
+
const argumentCodecFor = codec => decodeModule ? argumentDecodeCodec(codec, decodeModule.DEFAULT_WEB_PLUGINS) : loadArgumentCodec(codec);
|
|
1977
|
+
async function parseArguments(request, url, scripted, codec, buffered) {
|
|
659
1978
|
const parsed = [];
|
|
660
1979
|
const bodyFormat = request.method === "POST" ? request.headers.get(BODY_FORMAT_HEADER) : null;
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
1980
|
+
const args = url.searchParams.get("args");
|
|
1981
|
+
if (args && (!scripted || request.method === "GET" || bodyFormat !== BodyFormat.Serialized)) {
|
|
1982
|
+
let result;
|
|
1983
|
+
if (args.startsWith(";0x")) {
|
|
1984
|
+
let argumentCodec = argumentCodecFor(codec);
|
|
1985
|
+
if (argumentCodec instanceof Promise) argumentCodec = await argumentCodec;
|
|
1986
|
+
result = await decodeArguments(wire => deserializeStream(new Response(args), argumentCodec, wire), args);
|
|
1987
|
+
} else {
|
|
1988
|
+
result = JSON.parse(args);
|
|
1989
|
+
assertDecodeDepth(result);
|
|
1990
|
+
}
|
|
1991
|
+
if (!Array.isArray(result)) {
|
|
1992
|
+
throw new TypeError("Server function arguments must encode an array");
|
|
668
1993
|
}
|
|
1994
|
+
stripUnsafeArgumentKeys(result);
|
|
1995
|
+
for (const arg of result) {
|
|
1996
|
+
parsed.push(arg);
|
|
1997
|
+
}
|
|
1998
|
+
} else if (!args && url.search && (request.method === "GET" || request.method === "HEAD")) {
|
|
1999
|
+
parsed.push(url.searchParams);
|
|
669
2000
|
}
|
|
670
2001
|
if (request.method === "POST" && request.body !== null) {
|
|
671
|
-
|
|
2002
|
+
if (bodyFormat !== null && !KNOWN_BODY_FORMATS.has(bodyFormat)) {
|
|
2003
|
+
throw unknownFormatError(bodyFormat);
|
|
2004
|
+
}
|
|
2005
|
+
const body = request.clone();
|
|
2006
|
+
let decoded;
|
|
2007
|
+
if (bodyFormat === BodyFormat.Serialized) {
|
|
2008
|
+
let argumentCodec = argumentCodecFor(codec);
|
|
2009
|
+
if (argumentCodec instanceof Promise) argumentCodec = await argumentCodec;
|
|
2010
|
+
if ((request.headers.get("content-type") || "").startsWith("multipart/form-data")) {
|
|
2011
|
+
const form = await body.formData();
|
|
2012
|
+
const encoded = form.get(UPLOAD_ARGS_PART);
|
|
2013
|
+
if (typeof encoded !== "string") {
|
|
2014
|
+
throw new TypeError("Malformed server function upload");
|
|
2015
|
+
}
|
|
2016
|
+
const uploadCodec = withArgumentPlugins(argumentCodec, [createUploadDeserializer(form)]);
|
|
2017
|
+
decoded = await decodeArguments(wire => deserializeStream(new Response(encoded), uploadCodec, wire), encoded);
|
|
2018
|
+
} else {
|
|
2019
|
+
decoded = await decodeArguments(wire => extractBody(body, argumentCodec, wire), buffered);
|
|
2020
|
+
}
|
|
2021
|
+
} else {
|
|
2022
|
+
decoded = await extractBody(body, codec);
|
|
2023
|
+
}
|
|
672
2024
|
if (bodyFormat === BodyFormat.Serialized || bodyFormat === BodyFormat.Json) {
|
|
673
|
-
|
|
2025
|
+
if (bodyFormat === BodyFormat.Json) assertDecodeDepth(decoded);
|
|
2026
|
+
if (!Array.isArray(decoded)) {
|
|
2027
|
+
throw new TypeError("Server function arguments must encode an array");
|
|
2028
|
+
}
|
|
2029
|
+
return stripUnsafeArgumentKeys(decoded);
|
|
2030
|
+
}
|
|
2031
|
+
if (decoded === undefined) {
|
|
2032
|
+
if (bodyFormat === null && (await body.arrayBuffer()).byteLength === 0) {
|
|
2033
|
+
return parsed;
|
|
2034
|
+
}
|
|
2035
|
+
throw new TypeError("Server function body carries no usable encoding");
|
|
674
2036
|
}
|
|
675
2037
|
parsed.push(decoded);
|
|
676
2038
|
}
|
|
677
2039
|
return parsed;
|
|
678
2040
|
}
|
|
679
|
-
async function foldFlightData(
|
|
2041
|
+
async function foldFlightData(hooks, event, headers, outcome, context = {}) {
|
|
680
2042
|
if (outcome.value instanceof Response && outcome.value.body) return outcome.value;
|
|
681
2043
|
digestOutcome(event, outcome);
|
|
682
|
-
const
|
|
683
|
-
|
|
684
|
-
|
|
2044
|
+
const folded = [];
|
|
2045
|
+
for (const [source, hook] of hooks) {
|
|
2046
|
+
try {
|
|
2047
|
+
const slice = await hook(event, outcome);
|
|
2048
|
+
if (slice !== undefined) folded.push([source, slice]);
|
|
2049
|
+
} catch (error) {
|
|
2050
|
+
console.error(`Error collecting flight data for source "${source}"`, error);
|
|
2051
|
+
}
|
|
2052
|
+
}
|
|
2053
|
+
if (folded.length === 0) return outcome.value;
|
|
2054
|
+
const data = Object.fromEntries(folded);
|
|
2055
|
+
headers.set(SINGLE_FLIGHT_HEADER, folded.map(([source]) => source).join(","));
|
|
685
2056
|
if (context.transformFlightResult) {
|
|
686
2057
|
const transformed = await context.transformFlightResult(event, {
|
|
687
2058
|
value: outcome.value,
|
|
688
2059
|
data
|
|
689
2060
|
}, context);
|
|
690
2061
|
if (transformed !== undefined) {
|
|
691
|
-
|
|
2062
|
+
const owned = ownResponse(transformed);
|
|
2063
|
+
for (const cookie of headers.getSetCookie()) owned.headers.append("Set-Cookie", cookie);
|
|
692
2064
|
headers.forEach((value, key) => {
|
|
693
|
-
if (key !== "set-cookie" && !
|
|
694
|
-
|
|
2065
|
+
if (key !== "set-cookie" && !owned.headers.has(key)) {
|
|
2066
|
+
owned.headers.set(key, value);
|
|
695
2067
|
}
|
|
696
2068
|
});
|
|
697
|
-
|
|
2069
|
+
owned.headers.set(SINGLE_FLIGHT_HEADER, headers.get(SINGLE_FLIGHT_HEADER));
|
|
2070
|
+
return owned;
|
|
698
2071
|
}
|
|
699
2072
|
}
|
|
700
2073
|
return outcome.value === undefined ? {
|
|
@@ -761,7 +2134,7 @@ function foldSetCookies(headers, setCookies) {
|
|
|
761
2134
|
}
|
|
762
2135
|
function mergeResponseHeaders(target, source) {
|
|
763
2136
|
source.forEach((value, key) => {
|
|
764
|
-
if (key !== "set-cookie") target.append(key, value);
|
|
2137
|
+
if (key !== "set-cookie" && !COMPOSED_BODY_FRAMING.has(key)) target.append(key, value);
|
|
765
2138
|
});
|
|
766
2139
|
if (source.getSetCookie) {
|
|
767
2140
|
for (const cookie of source.getSetCookie()) target.append("Set-Cookie", cookie);
|
|
@@ -770,10 +2143,52 @@ function mergeResponseHeaders(target, source) {
|
|
|
770
2143
|
}
|
|
771
2144
|
}
|
|
772
2145
|
const validRedirectStatuses = new Set([301, 302, 303, 307, 308]);
|
|
2146
|
+
function maskRedirect(headers, response, requestUrl) {
|
|
2147
|
+
const target = response.headers && response.headers.get("Location");
|
|
2148
|
+
if (target) {
|
|
2149
|
+
headers.set(REDIRECT_HEADER, `${response.status} ${new URL(target, requestUrl)}`);
|
|
2150
|
+
}
|
|
2151
|
+
headers.delete("Location");
|
|
2152
|
+
}
|
|
2153
|
+
const BOUNDED_COMPOSED_HEADERS = [REDIRECT_HEADER, "Location", REVALIDATE_HEADER];
|
|
2154
|
+
function enforceComposedHeaderInvariants(response) {
|
|
2155
|
+
for (const name of BOUNDED_COMPOSED_HEADERS) {
|
|
2156
|
+
const value = response.headers.get(name);
|
|
2157
|
+
if (value === null) continue;
|
|
2158
|
+
if (value.length > RESPONSE_HEADER_VALUE_LIMIT) {
|
|
2159
|
+
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);
|
|
2160
|
+
}
|
|
2161
|
+
if (name === REVALIDATE_HEADER) continue;
|
|
2162
|
+
const target = name === REDIRECT_HEADER ? value.slice(value.indexOf(" ") + 1) : value;
|
|
2163
|
+
if (!isHttpNavigationTarget(target)) {
|
|
2164
|
+
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);
|
|
2165
|
+
}
|
|
2166
|
+
}
|
|
2167
|
+
return response;
|
|
2168
|
+
}
|
|
2169
|
+
function refuseComposedHeader(response, name, headerMessage, body) {
|
|
2170
|
+
if (response.body) {
|
|
2171
|
+
try {
|
|
2172
|
+
const cancelled = response.body.cancel();
|
|
2173
|
+
if (cancelled && typeof cancelled.then === "function") cancelled.then(undefined, () => {});
|
|
2174
|
+
} catch {}
|
|
2175
|
+
}
|
|
2176
|
+
const headers = new Headers();
|
|
2177
|
+
headers.set(ERROR_HEADER, boundedErrorHeaderValue(DEV ? headerMessage : GENERIC_SERVER_ERROR_MESSAGE));
|
|
2178
|
+
return new Response(body, {
|
|
2179
|
+
status: 500,
|
|
2180
|
+
headers
|
|
2181
|
+
});
|
|
2182
|
+
}
|
|
2183
|
+
function warnScripted304(functionId) {
|
|
2184
|
+
if (DEV) {
|
|
2185
|
+
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.`);
|
|
2186
|
+
}
|
|
2187
|
+
}
|
|
773
2188
|
function createNoJSHandler({
|
|
774
2189
|
base = ""
|
|
775
2190
|
} = {}) {
|
|
776
|
-
return function handleNoJS(result, request, args, thrown) {
|
|
2191
|
+
return async function handleNoJS(result, request, args, thrown) {
|
|
777
2192
|
const url = new URL(request.url);
|
|
778
2193
|
let back = new URL(base || "/", url.origin).toString();
|
|
779
2194
|
try {
|
|
@@ -798,8 +2213,9 @@ function createNoJSHandler({
|
|
|
798
2213
|
Location: back
|
|
799
2214
|
});
|
|
800
2215
|
}
|
|
801
|
-
if (result && !(result instanceof Response)) {
|
|
802
|
-
|
|
2216
|
+
if (result !== undefined && !(result instanceof Response)) {
|
|
2217
|
+
const flash = await encodeFlashCookie(url.pathname, result, args, thrown);
|
|
2218
|
+
if (flash !== null) headers.append("Set-Cookie", flash);
|
|
803
2219
|
}
|
|
804
2220
|
return new Response(null, {
|
|
805
2221
|
status,
|
|
@@ -813,44 +2229,309 @@ function isFormPost(request) {
|
|
|
813
2229
|
const type = request.headers.get("content-type") || "";
|
|
814
2230
|
return type.startsWith("application/x-www-form-urlencoded") || type.startsWith("multipart/form-data");
|
|
815
2231
|
}
|
|
816
|
-
function
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
let onAbort = null;
|
|
821
|
-
const teardown = () => {
|
|
822
|
-
if (closed) return;
|
|
823
|
-
closed = true;
|
|
824
|
-
if (onAbort) signal.removeEventListener("abort", onAbort);
|
|
825
|
-
if (cancelSerialize) cancelSerialize();
|
|
826
|
-
if (closeIterator) closeIterator();
|
|
2232
|
+
function guardFailures(value, state) {
|
|
2233
|
+
if (!state) state = {
|
|
2234
|
+
seen: new WeakMap(),
|
|
2235
|
+
cyclic: new WeakSet()
|
|
827
2236
|
};
|
|
828
|
-
|
|
2237
|
+
const entered = enterGuard(value, state);
|
|
2238
|
+
if (!(entered instanceof Frame)) return entered;
|
|
2239
|
+
const stack = [entered];
|
|
2240
|
+
let delivered = NOTHING;
|
|
2241
|
+
for (;;) {
|
|
2242
|
+
const top = stack[stack.length - 1];
|
|
2243
|
+
const items = top.items;
|
|
2244
|
+
let pushed = null;
|
|
2245
|
+
while (top.i < items.length) {
|
|
2246
|
+
const i = top.i;
|
|
2247
|
+
let original;
|
|
2248
|
+
if (top.kind === OBJECT) {
|
|
2249
|
+
const descriptor = top.descriptors[items[i]];
|
|
2250
|
+
if ("value" in descriptor) {
|
|
2251
|
+
original = descriptor.value;
|
|
2252
|
+
} else if (typeof descriptor.get === "function") {
|
|
2253
|
+
if (top.accessorRead !== i) {
|
|
2254
|
+
try {
|
|
2255
|
+
top.accessorValue = descriptor.get.call(top.value);
|
|
2256
|
+
} catch (error) {
|
|
2257
|
+
throw wireServerFunctionError(error, "channel");
|
|
2258
|
+
}
|
|
2259
|
+
top.accessorRead = i;
|
|
2260
|
+
}
|
|
2261
|
+
original = top.accessorValue;
|
|
2262
|
+
} else {
|
|
2263
|
+
top.i++;
|
|
2264
|
+
continue;
|
|
2265
|
+
}
|
|
2266
|
+
} else {
|
|
2267
|
+
original = items[i];
|
|
2268
|
+
}
|
|
2269
|
+
let guarded;
|
|
2270
|
+
if (delivered !== NOTHING) {
|
|
2271
|
+
guarded = delivered;
|
|
2272
|
+
delivered = NOTHING;
|
|
2273
|
+
} else {
|
|
2274
|
+
guarded = enterGuard(original, state);
|
|
2275
|
+
if (guarded instanceof Frame) {
|
|
2276
|
+
pushed = guarded;
|
|
2277
|
+
break;
|
|
2278
|
+
}
|
|
2279
|
+
}
|
|
2280
|
+
if (top.kind === ARRAY) {
|
|
2281
|
+
if (guarded !== original) {
|
|
2282
|
+
top.next[i] = guarded;
|
|
2283
|
+
top.changed = true;
|
|
2284
|
+
}
|
|
2285
|
+
} else if (top.kind === MAP) {
|
|
2286
|
+
if ((i & 1) === 0) top.pendingKey = guarded;else top.next.set(top.pendingKey, guarded);
|
|
2287
|
+
if (guarded !== original) top.changed = true;
|
|
2288
|
+
} else if (top.kind === SET) {
|
|
2289
|
+
top.next.add(guarded);
|
|
2290
|
+
if (guarded !== original) top.changed = true;
|
|
2291
|
+
} else if (guarded !== original || top.accessorRead === i) {
|
|
2292
|
+
Object.defineProperty(top.next, items[i], {
|
|
2293
|
+
value: guarded,
|
|
2294
|
+
writable: true,
|
|
2295
|
+
configurable: true,
|
|
2296
|
+
enumerable: top.descriptors[items[i]].enumerable
|
|
2297
|
+
});
|
|
2298
|
+
top.changed = true;
|
|
2299
|
+
}
|
|
2300
|
+
top.i++;
|
|
2301
|
+
}
|
|
2302
|
+
if (pushed !== null) {
|
|
2303
|
+
stack.push(pushed);
|
|
2304
|
+
continue;
|
|
2305
|
+
}
|
|
2306
|
+
stack.pop();
|
|
2307
|
+
const out = keepGuarded(top.value, top.next, top.changed, state);
|
|
2308
|
+
if (stack.length === 0) return out;
|
|
2309
|
+
delivered = out;
|
|
2310
|
+
}
|
|
2311
|
+
}
|
|
2312
|
+
const NOTHING = Symbol();
|
|
2313
|
+
const ARRAY = 0;
|
|
2314
|
+
const MAP = 1;
|
|
2315
|
+
const SET = 2;
|
|
2316
|
+
const OBJECT = 3;
|
|
2317
|
+
class Frame {
|
|
2318
|
+
constructor(kind, value, next, items, descriptors) {
|
|
2319
|
+
this.kind = kind;
|
|
2320
|
+
this.value = value;
|
|
2321
|
+
this.next = next;
|
|
2322
|
+
this.items = items;
|
|
2323
|
+
this.descriptors = descriptors;
|
|
2324
|
+
this.i = 0;
|
|
2325
|
+
this.changed = false;
|
|
2326
|
+
this.accessorRead = -1;
|
|
2327
|
+
this.accessorValue = undefined;
|
|
2328
|
+
this.pendingKey = undefined;
|
|
2329
|
+
}
|
|
2330
|
+
}
|
|
2331
|
+
function guardOperation(state, run) {
|
|
2332
|
+
return state.scope ? state.scope(run) : run();
|
|
2333
|
+
}
|
|
2334
|
+
function enterGuard(value, state) {
|
|
2335
|
+
if (value === null || typeof value !== "object") return value;
|
|
2336
|
+
if (state.seen.has(value)) {
|
|
2337
|
+
state.cyclic.add(value);
|
|
2338
|
+
return state.seen.get(value);
|
|
2339
|
+
}
|
|
2340
|
+
if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) {
|
|
2341
|
+
let reader;
|
|
2342
|
+
const gate = state.gate;
|
|
2343
|
+
let finished = false;
|
|
2344
|
+
const close = () => {
|
|
2345
|
+
if (finished) return;
|
|
2346
|
+
finished = true;
|
|
2347
|
+
try {
|
|
2348
|
+
const cancelled = guardOperation(state, () => reader ? reader.cancel() : value.cancel());
|
|
2349
|
+
if (cancelled && typeof cancelled.then === "function") cancelled.then(undefined, () => {});
|
|
2350
|
+
} catch {}
|
|
2351
|
+
};
|
|
2352
|
+
const guardedStream = new ReadableStream({
|
|
2353
|
+
async pull(controller) {
|
|
2354
|
+
try {
|
|
2355
|
+
if (gate && !finished && !gate.wantsMore()) await gate.awaitDemand();
|
|
2356
|
+
if (finished) {
|
|
2357
|
+
controller.close();
|
|
2358
|
+
return;
|
|
2359
|
+
}
|
|
2360
|
+
if (!reader) reader = guardOperation(state, () => value.getReader());
|
|
2361
|
+
const {
|
|
2362
|
+
done,
|
|
2363
|
+
value: chunk
|
|
2364
|
+
} = await guardOperation(state, () => reader.read());
|
|
2365
|
+
done ? controller.close() : controller.enqueue(guardOperation(state, () => guardFailures(chunk, state)));
|
|
2366
|
+
} catch (error) {
|
|
2367
|
+
controller.error(guardOperation(state, () => wireServerFunctionError(error, "channel")));
|
|
2368
|
+
}
|
|
2369
|
+
},
|
|
2370
|
+
cancel(reason) {
|
|
2371
|
+
finished = true;
|
|
2372
|
+
return guardOperation(state, () => reader ? reader.cancel(reason) : value.cancel(reason));
|
|
2373
|
+
}
|
|
2374
|
+
});
|
|
2375
|
+
if (gate) gate.onOpen(close);
|
|
2376
|
+
state.seen.set(value, guardedStream);
|
|
2377
|
+
return guardedStream;
|
|
2378
|
+
}
|
|
2379
|
+
if (typeof value.then === "function") {
|
|
2380
|
+
const guardedPromise = Promise.resolve(value).then(resolved => guardOperation(state, () => guardFailures(resolved, state)), error => {
|
|
2381
|
+
throw guardOperation(state, () => wireServerFunctionError(error, "channel"));
|
|
2382
|
+
});
|
|
2383
|
+
guardedPromise.catch(() => {});
|
|
2384
|
+
state.seen.set(value, guardedPromise);
|
|
2385
|
+
return guardedPromise;
|
|
2386
|
+
}
|
|
2387
|
+
if (typeof value[Symbol.asyncIterator] === "function") {
|
|
829
2388
|
const source = value;
|
|
830
|
-
|
|
2389
|
+
const gate = state.gate;
|
|
2390
|
+
const guardedIterable = {
|
|
831
2391
|
[Symbol.asyncIterator]() {
|
|
832
|
-
const
|
|
2392
|
+
const iterator = guardOperation(state, () => source[Symbol.asyncIterator]());
|
|
833
2393
|
let finished = false;
|
|
834
|
-
|
|
2394
|
+
const close = () => {
|
|
835
2395
|
if (finished) return;
|
|
836
2396
|
finished = true;
|
|
837
2397
|
try {
|
|
838
|
-
const returned =
|
|
2398
|
+
const returned = iterator.return && guardOperation(state, () => iterator.return());
|
|
839
2399
|
if (returned && typeof returned.then === "function") returned.then(undefined, () => {});
|
|
840
2400
|
} catch {}
|
|
841
2401
|
};
|
|
842
|
-
if (
|
|
2402
|
+
if (gate) gate.onOpen(close);
|
|
2403
|
+
const step = () => finished ? Promise.resolve({
|
|
2404
|
+
done: true,
|
|
2405
|
+
value: undefined
|
|
2406
|
+
}) : guardOperation(state, () => iterator.next()).then(step => {
|
|
2407
|
+
if (step.done) {
|
|
2408
|
+
finished = true;
|
|
2409
|
+
return step;
|
|
2410
|
+
}
|
|
2411
|
+
return {
|
|
2412
|
+
done: false,
|
|
2413
|
+
value: guardOperation(state, () => guardFailures(step.value, state))
|
|
2414
|
+
};
|
|
2415
|
+
}, error => {
|
|
2416
|
+
throw guardOperation(state, () => wireServerFunctionError(error, "channel"));
|
|
2417
|
+
});
|
|
843
2418
|
return {
|
|
844
|
-
next: () => finished ?
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
2419
|
+
next: () => finished || !gate || gate.wantsMore() ? step() : gate.awaitDemand().then(step),
|
|
2420
|
+
return: () => {
|
|
2421
|
+
close();
|
|
2422
|
+
return Promise.resolve({
|
|
2423
|
+
done: true,
|
|
2424
|
+
value: undefined
|
|
2425
|
+
});
|
|
2426
|
+
}
|
|
848
2427
|
};
|
|
849
2428
|
}
|
|
850
2429
|
};
|
|
2430
|
+
state.seen.set(value, guardedIterable);
|
|
2431
|
+
return guardedIterable;
|
|
2432
|
+
}
|
|
2433
|
+
if (state.scope && typeof value[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value)) {
|
|
2434
|
+
const scopedIterable = scopeDeferredResult(value, state.scope);
|
|
2435
|
+
state.seen.set(value, scopedIterable);
|
|
2436
|
+
return scopedIterable;
|
|
851
2437
|
}
|
|
2438
|
+
if (Array.isArray(value)) {
|
|
2439
|
+
const next = value.slice();
|
|
2440
|
+
state.seen.set(value, next);
|
|
2441
|
+
return new Frame(ARRAY, value, next, value, null);
|
|
2442
|
+
}
|
|
2443
|
+
if (value instanceof Map) {
|
|
2444
|
+
const next = new Map();
|
|
2445
|
+
state.seen.set(value, next);
|
|
2446
|
+
const items = [];
|
|
2447
|
+
for (const entry of value) items.push(entry[0], entry[1]);
|
|
2448
|
+
return new Frame(MAP, value, next, items, null);
|
|
2449
|
+
}
|
|
2450
|
+
if (value instanceof Set) {
|
|
2451
|
+
const next = new Set();
|
|
2452
|
+
state.seen.set(value, next);
|
|
2453
|
+
return new Frame(SET, value, next, [...value], null);
|
|
2454
|
+
}
|
|
2455
|
+
const prototype = Object.getPrototypeOf(value);
|
|
2456
|
+
if (prototype !== Object.prototype && prototype !== null && !(value instanceof Error)) {
|
|
2457
|
+
state.seen.set(value, value);
|
|
2458
|
+
return value;
|
|
2459
|
+
}
|
|
2460
|
+
const descriptors = Object.getOwnPropertyDescriptors(value);
|
|
2461
|
+
for (const key of Object.keys(descriptors)) {
|
|
2462
|
+
descriptors[key].configurable = true;
|
|
2463
|
+
if ("value" in descriptors[key]) descriptors[key].writable = true;
|
|
2464
|
+
}
|
|
2465
|
+
const next = Object.create(prototype, descriptors);
|
|
2466
|
+
state.seen.set(value, next);
|
|
2467
|
+
const children = !(value instanceof Error) ? Object.keys(value) : Object.getOwnPropertyNames(value).filter(key => {
|
|
2468
|
+
const descriptor = descriptors[key];
|
|
2469
|
+
return descriptor.enumerable || "value" in descriptor;
|
|
2470
|
+
});
|
|
2471
|
+
return new Frame(OBJECT, value, next, children, descriptors);
|
|
2472
|
+
}
|
|
2473
|
+
function keepGuarded(value, next, changed, state) {
|
|
2474
|
+
if (changed || state.cyclic.has(value)) return next;
|
|
2475
|
+
state.seen.set(value, value);
|
|
2476
|
+
return value;
|
|
2477
|
+
}
|
|
2478
|
+
function serializeResponseStream(value, codecOptions, signal, scope, live) {
|
|
2479
|
+
let closed = false;
|
|
2480
|
+
const frame = live ? payload => {
|
|
2481
|
+
const id = live.pending;
|
|
2482
|
+
live.pending = undefined;
|
|
2483
|
+
return createEventChunk(payload, id);
|
|
2484
|
+
} : createChunk;
|
|
2485
|
+
let stopLive = null;
|
|
2486
|
+
const stopHeartbeat = () => {
|
|
2487
|
+
if (stopLive !== null) {
|
|
2488
|
+
stopLive();
|
|
2489
|
+
stopLive = null;
|
|
2490
|
+
}
|
|
2491
|
+
};
|
|
2492
|
+
let streamController = null;
|
|
2493
|
+
let demandWaiters = null;
|
|
2494
|
+
const wantsMore = () => streamController !== null && streamController.desiredSize > 0;
|
|
2495
|
+
const awaitDemand = () => new Promise(resolve => (demandWaiters ??= []).push(resolve));
|
|
2496
|
+
const supplyDemand = () => {
|
|
2497
|
+
const resolvers = demandWaiters;
|
|
2498
|
+
demandWaiters = null;
|
|
2499
|
+
if (resolvers) for (const resolve of resolvers) resolve();
|
|
2500
|
+
};
|
|
2501
|
+
const sourceClosers = new Set();
|
|
2502
|
+
const gate = {
|
|
2503
|
+
wantsMore,
|
|
2504
|
+
awaitDemand,
|
|
2505
|
+
onOpen(close) {
|
|
2506
|
+
if (closed) close();else sourceClosers.add(close);
|
|
2507
|
+
}
|
|
2508
|
+
};
|
|
2509
|
+
const guardState = {
|
|
2510
|
+
seen: new WeakMap(),
|
|
2511
|
+
cyclic: new WeakSet(),
|
|
2512
|
+
gate,
|
|
2513
|
+
scope
|
|
2514
|
+
};
|
|
2515
|
+
value = guardOperation(guardState, () => guardFailures(value, guardState));
|
|
2516
|
+
let cancelSerialize = null;
|
|
2517
|
+
let onAbort = null;
|
|
2518
|
+
const finishSource = () => {
|
|
2519
|
+
for (const close of sourceClosers) close();
|
|
2520
|
+
sourceClosers.clear();
|
|
2521
|
+
supplyDemand();
|
|
2522
|
+
};
|
|
2523
|
+
const teardown = () => {
|
|
2524
|
+
if (closed) return;
|
|
2525
|
+
closed = true;
|
|
2526
|
+
stopHeartbeat();
|
|
2527
|
+
if (onAbort) signal.removeEventListener("abort", onAbort);
|
|
2528
|
+
if (cancelSerialize) cancelSerialize();
|
|
2529
|
+
finishSource();
|
|
2530
|
+
};
|
|
852
2531
|
return new ReadableStream({
|
|
853
2532
|
async start(controller) {
|
|
2533
|
+
streamController = controller;
|
|
2534
|
+
if (live && !live.nodes) stopLive = armLiveBody(controller, teardown);
|
|
854
2535
|
if (signal) {
|
|
855
2536
|
if (signal.aborted) {
|
|
856
2537
|
teardown();
|
|
@@ -880,35 +2561,364 @@ function serializeResponseStream(value, codecOptions, signal) {
|
|
|
880
2561
|
cancelSerialize = serializeJSON(value, {
|
|
881
2562
|
...codecOptions,
|
|
882
2563
|
onParse(node) {
|
|
883
|
-
if (
|
|
2564
|
+
if (closed) return;
|
|
2565
|
+
const chunk = frame(JSON.stringify(node));
|
|
2566
|
+
if (live && live.nodes) live.nodes.set(chunk, node);
|
|
2567
|
+
controller.enqueue(chunk);
|
|
884
2568
|
},
|
|
885
2569
|
onDone() {
|
|
886
2570
|
if (closed) return;
|
|
887
2571
|
closed = true;
|
|
2572
|
+
stopHeartbeat();
|
|
888
2573
|
if (onAbort) signal.removeEventListener("abort", onAbort);
|
|
2574
|
+
finishSource();
|
|
889
2575
|
controller.close();
|
|
890
2576
|
},
|
|
891
2577
|
onError(error) {
|
|
892
2578
|
if (closed) return;
|
|
893
2579
|
closed = true;
|
|
2580
|
+
stopHeartbeat();
|
|
894
2581
|
if (onAbort) signal.removeEventListener("abort", onAbort);
|
|
895
|
-
|
|
2582
|
+
finishSource();
|
|
2583
|
+
try {
|
|
2584
|
+
const delivered = wireServerFunctionError(DEV && error instanceof Error ? new Error(`Server function result could not be encoded: ${error.message}`) : error, "channel");
|
|
2585
|
+
controller.enqueue(frame(encodeErrorTrailer(delivered)));
|
|
2586
|
+
controller.close();
|
|
2587
|
+
} catch {
|
|
2588
|
+
try {
|
|
2589
|
+
controller.error(error);
|
|
2590
|
+
} catch {}
|
|
2591
|
+
}
|
|
896
2592
|
}
|
|
897
2593
|
});
|
|
898
2594
|
},
|
|
2595
|
+
pull() {
|
|
2596
|
+
supplyDemand();
|
|
2597
|
+
},
|
|
899
2598
|
cancel() {
|
|
900
2599
|
teardown();
|
|
901
2600
|
}
|
|
902
2601
|
});
|
|
903
2602
|
}
|
|
904
|
-
function serializedResponse(value, headers, codec, signal) {
|
|
2603
|
+
function serializedResponse(value, headers, codec, signal, scope) {
|
|
905
2604
|
headers.set(BODY_FORMAT_HEADER, BodyFormat.Serialized);
|
|
906
2605
|
headers.set("Content-Type", "text/plain");
|
|
907
|
-
return new Response(serializeResponseStream(value, codec, signal), {
|
|
2606
|
+
return new Response(serializeResponseStream(value, codec, signal, scope), {
|
|
908
2607
|
headers
|
|
909
2608
|
});
|
|
910
2609
|
}
|
|
911
|
-
|
|
2610
|
+
const LIVE_HEARTBEAT_INTERVAL = 20000;
|
|
2611
|
+
function armLiveBody(controller, teardown) {
|
|
2612
|
+
let stopped = false;
|
|
2613
|
+
const heartbeat = setInterval(() => {
|
|
2614
|
+
if (stopped) return;
|
|
2615
|
+
try {
|
|
2616
|
+
controller.enqueue(EVENT_STREAM_HEARTBEAT);
|
|
2617
|
+
} catch {}
|
|
2618
|
+
}, LIVE_HEARTBEAT_INTERVAL);
|
|
2619
|
+
if (typeof heartbeat === "object" && heartbeat && typeof heartbeat.unref === "function") heartbeat.unref();
|
|
2620
|
+
let chaos = null;
|
|
2621
|
+
if (DEV && config.chaosReconnectEvery > 0) {
|
|
2622
|
+
chaos = setTimeout(() => {
|
|
2623
|
+
if (stopped) return;
|
|
2624
|
+
teardown();
|
|
2625
|
+
try {
|
|
2626
|
+
controller.error(new Error("Live response ended by the chaos knob."));
|
|
2627
|
+
} catch {}
|
|
2628
|
+
}, config.chaosReconnectEvery);
|
|
2629
|
+
if (typeof chaos === "object" && chaos && typeof chaos.unref === "function") chaos.unref();
|
|
2630
|
+
}
|
|
2631
|
+
return () => {
|
|
2632
|
+
if (stopped) return;
|
|
2633
|
+
stopped = true;
|
|
2634
|
+
clearInterval(heartbeat);
|
|
2635
|
+
if (chaos !== null) clearTimeout(chaos);
|
|
2636
|
+
};
|
|
2637
|
+
}
|
|
2638
|
+
function liveSource(value, lastEventId, position, scope, refs) {
|
|
2639
|
+
const digestOf = v => scope ? scope(() => positionDigest(v)) : positionDigest(v);
|
|
2640
|
+
if (value === null || typeof value !== "object" || typeof value[Symbol.asyncIterator] !== "function") {
|
|
2641
|
+
const digest = digestOf(value);
|
|
2642
|
+
if (digest !== undefined && digest === lastEventId) return async function* () {}();
|
|
2643
|
+
position.pending = digest;
|
|
2644
|
+
return value;
|
|
2645
|
+
}
|
|
2646
|
+
const source = value;
|
|
2647
|
+
return {
|
|
2648
|
+
[Symbol.asyncIterator]() {
|
|
2649
|
+
const iterator = source[Symbol.asyncIterator]();
|
|
2650
|
+
let first = true;
|
|
2651
|
+
const step = () => iterator.next().then(result => {
|
|
2652
|
+
if (result.done) return result;
|
|
2653
|
+
if (refs) refs.turn();
|
|
2654
|
+
const digest = digestOf(result.value);
|
|
2655
|
+
if (refs) position.yields.push({
|
|
2656
|
+
value: result.value,
|
|
2657
|
+
digest
|
|
2658
|
+
});
|
|
2659
|
+
if (first) {
|
|
2660
|
+
first = false;
|
|
2661
|
+
if (digest !== undefined && digest === lastEventId) return step();
|
|
2662
|
+
}
|
|
2663
|
+
position.pending = digest;
|
|
2664
|
+
return result;
|
|
2665
|
+
});
|
|
2666
|
+
return {
|
|
2667
|
+
next: step,
|
|
2668
|
+
return: v => iterator.return ? iterator.return(v) : Promise.resolve({
|
|
2669
|
+
done: true,
|
|
2670
|
+
value: v
|
|
2671
|
+
}),
|
|
2672
|
+
throw: e => iterator.throw ? iterator.throw(e) : Promise.reject(e)
|
|
2673
|
+
};
|
|
2674
|
+
}
|
|
2675
|
+
};
|
|
2676
|
+
}
|
|
2677
|
+
function encodeLiveResult(value, headers, status, codec, request, scope, shareKey) {
|
|
2678
|
+
if (NULL_BODY_STATUSES.has(status) || value === undefined || getHeadersAndBody(value)) {
|
|
2679
|
+
return encodeResult(value, headers, status, codec, request.signal, scope);
|
|
2680
|
+
}
|
|
2681
|
+
if (shareKey !== undefined && value !== null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function") {
|
|
2682
|
+
const shared = sharedSourceResponse(shareKey, value, headers, status, codec, request);
|
|
2683
|
+
if (shared) return shared;
|
|
2684
|
+
}
|
|
2685
|
+
const position = {
|
|
2686
|
+
pending: undefined
|
|
2687
|
+
};
|
|
2688
|
+
const source = liveSource(value, request.headers.get(LAST_EVENT_ID_HEADER), position, scope);
|
|
2689
|
+
headers.set(BODY_FORMAT_HEADER, BodyFormat.Serialized);
|
|
2690
|
+
headers.set("Content-Type", "text/event-stream");
|
|
2691
|
+
headers.set("Cache-Control", "no-store");
|
|
2692
|
+
headers.set("X-Accel-Buffering", "no");
|
|
2693
|
+
try {
|
|
2694
|
+
return new Response(serializeResponseStream(source, codec, request.signal, scope, position), {
|
|
2695
|
+
status,
|
|
2696
|
+
headers
|
|
2697
|
+
});
|
|
2698
|
+
} catch (error) {
|
|
2699
|
+
throw DEV && error instanceof Error ? new Error(`Server function result could not be encoded: ${error.message}`) : error;
|
|
2700
|
+
}
|
|
2701
|
+
}
|
|
2702
|
+
const SHARED_SOURCES = new Map();
|
|
2703
|
+
class GenerationalRefs extends Map {
|
|
2704
|
+
count = 0;
|
|
2705
|
+
touched = new Set();
|
|
2706
|
+
get size() {
|
|
2707
|
+
return this.count;
|
|
2708
|
+
}
|
|
2709
|
+
get(key) {
|
|
2710
|
+
const id = super.get(key);
|
|
2711
|
+
if (id !== undefined) this.touched.add(key);
|
|
2712
|
+
return id;
|
|
2713
|
+
}
|
|
2714
|
+
set(key, value) {
|
|
2715
|
+
if (!super.has(key)) this.count++;
|
|
2716
|
+
this.touched.add(key);
|
|
2717
|
+
return super.set(key, value);
|
|
2718
|
+
}
|
|
2719
|
+
turn() {
|
|
2720
|
+
for (const key of [...super.keys()]) if (!this.touched.has(key)) super.delete(key);
|
|
2721
|
+
this.touched = new Set();
|
|
2722
|
+
}
|
|
2723
|
+
idOf(key) {
|
|
2724
|
+
return super.get(key);
|
|
2725
|
+
}
|
|
2726
|
+
reserve() {
|
|
2727
|
+
return this.count++;
|
|
2728
|
+
}
|
|
2729
|
+
}
|
|
2730
|
+
function sharedSourceResponse(key, value, headers, status, codec, request) {
|
|
2731
|
+
let shared = SHARED_SOURCES.get(key);
|
|
2732
|
+
let snapshot;
|
|
2733
|
+
if (shared && !shared.ended) {
|
|
2734
|
+
snapshot = sharedSnapshot(shared);
|
|
2735
|
+
if (snapshot === null) return undefined;
|
|
2736
|
+
if (value !== shared.source) closeUnread(value);
|
|
2737
|
+
} else shared = startSharedSource(key, value, codec);
|
|
2738
|
+
return tapSharedSource(shared, request, headers, status, snapshot);
|
|
2739
|
+
}
|
|
2740
|
+
function closeUnread(value) {
|
|
2741
|
+
try {
|
|
2742
|
+
const closing = typeof value.return === "function" ? value.return() : typeof value.cancel === "function" ? value.cancel() : undefined;
|
|
2743
|
+
if (closing && typeof closing.then === "function") closing.then(undefined, () => {});
|
|
2744
|
+
} catch {}
|
|
2745
|
+
}
|
|
2746
|
+
function startSharedSource(key, value, codec) {
|
|
2747
|
+
const refs = new GenerationalRefs();
|
|
2748
|
+
const shared = {
|
|
2749
|
+
key,
|
|
2750
|
+
codec,
|
|
2751
|
+
refs,
|
|
2752
|
+
encode: null,
|
|
2753
|
+
head: null,
|
|
2754
|
+
node: null,
|
|
2755
|
+
value: undefined,
|
|
2756
|
+
position: undefined,
|
|
2757
|
+
stream: undefined,
|
|
2758
|
+
source: value,
|
|
2759
|
+
taps: new Set(),
|
|
2760
|
+
ended: false,
|
|
2761
|
+
teardown: new AbortController()
|
|
2762
|
+
};
|
|
2763
|
+
SHARED_SOURCES.set(key, shared);
|
|
2764
|
+
const event = broadcastEvent();
|
|
2765
|
+
const store = globalThis[RequestContext];
|
|
2766
|
+
const scope = run => store ? store.run(event, run) : run();
|
|
2767
|
+
const live = {
|
|
2768
|
+
pending: undefined,
|
|
2769
|
+
yields: [],
|
|
2770
|
+
nodes: new WeakMap()
|
|
2771
|
+
};
|
|
2772
|
+
const body = serializeResponseStream(liveSource(value, undefined, live, scope, refs), {
|
|
2773
|
+
...codec,
|
|
2774
|
+
refs
|
|
2775
|
+
}, shared.teardown.signal, scope, live);
|
|
2776
|
+
pumpSharedSource(shared, body.getReader(), live);
|
|
2777
|
+
return shared;
|
|
2778
|
+
}
|
|
2779
|
+
async function pumpSharedSource(shared, reader, {
|
|
2780
|
+
nodes,
|
|
2781
|
+
yields
|
|
2782
|
+
}) {
|
|
2783
|
+
try {
|
|
2784
|
+
shared.encode = (await import('@solidjs/web/serialization')).serializeJSON;
|
|
2785
|
+
while (true) {
|
|
2786
|
+
const {
|
|
2787
|
+
done,
|
|
2788
|
+
value: chunk
|
|
2789
|
+
} = await reader.read();
|
|
2790
|
+
if (done) break;
|
|
2791
|
+
const node = nodes.get(chunk);
|
|
2792
|
+
if (shared.head === null) shared.head = chunk;else if (node && node.t === 32 && (shared.stream ??= node.i) === node.i) {
|
|
2793
|
+
const {
|
|
2794
|
+
value,
|
|
2795
|
+
digest
|
|
2796
|
+
} = yields.shift();
|
|
2797
|
+
shared.node = node;
|
|
2798
|
+
shared.value = value;
|
|
2799
|
+
shared.position = digest;
|
|
2800
|
+
}
|
|
2801
|
+
for (const tap of shared.taps) tap.write(chunk);
|
|
2802
|
+
}
|
|
2803
|
+
} catch {}
|
|
2804
|
+
shared.ended = true;
|
|
2805
|
+
if (SHARED_SOURCES.get(shared.key) === shared) SHARED_SOURCES.delete(shared.key);
|
|
2806
|
+
for (const tap of [...shared.taps]) tap.end();
|
|
2807
|
+
}
|
|
2808
|
+
function sharedSnapshot(shared) {
|
|
2809
|
+
if (shared.node === null) return undefined;
|
|
2810
|
+
const own = new Map();
|
|
2811
|
+
let root;
|
|
2812
|
+
let done = false;
|
|
2813
|
+
const cancel = shared.encode(shared.value, {
|
|
2814
|
+
...shared.codec,
|
|
2815
|
+
refs: own,
|
|
2816
|
+
onParse(node) {
|
|
2817
|
+
root ??= node;
|
|
2818
|
+
},
|
|
2819
|
+
onDone() {
|
|
2820
|
+
done = true;
|
|
2821
|
+
},
|
|
2822
|
+
onError() {}
|
|
2823
|
+
});
|
|
2824
|
+
if (!done || root === undefined) {
|
|
2825
|
+
cancel();
|
|
2826
|
+
return null;
|
|
2827
|
+
}
|
|
2828
|
+
const ids = new Map();
|
|
2829
|
+
for (const [value, id] of own) ids.set(id, shared.refs.idOf(value) ?? shared.refs.reserve());
|
|
2830
|
+
return createEventChunk(JSON.stringify({
|
|
2831
|
+
...shared.node,
|
|
2832
|
+
f: renumberNode(root, ids)
|
|
2833
|
+
}), shared.position);
|
|
2834
|
+
}
|
|
2835
|
+
function renumberNode(node, ids) {
|
|
2836
|
+
if (Array.isArray(node)) return node.map(item => renumberNode(item, ids));
|
|
2837
|
+
if (node === null || typeof node !== "object") return node;
|
|
2838
|
+
const out = {};
|
|
2839
|
+
for (const key in node) out[key] = key === "i" && typeof node[key] === "number" ? ids.get(node[key]) ?? node[key] : renumberNode(node[key], ids);
|
|
2840
|
+
return out;
|
|
2841
|
+
}
|
|
2842
|
+
function tapSharedSource(shared, request, headers, status, snapshot) {
|
|
2843
|
+
headers.set(BODY_FORMAT_HEADER, BodyFormat.Serialized);
|
|
2844
|
+
headers.set("Content-Type", "text/event-stream");
|
|
2845
|
+
headers.set("Cache-Control", "no-store");
|
|
2846
|
+
headers.set("X-Accel-Buffering", "no");
|
|
2847
|
+
const signal = request.signal;
|
|
2848
|
+
let closed = false;
|
|
2849
|
+
let stopLive = null;
|
|
2850
|
+
let tap = null;
|
|
2851
|
+
const leave = () => {
|
|
2852
|
+
if (closed) return;
|
|
2853
|
+
closed = true;
|
|
2854
|
+
if (stopLive) stopLive();
|
|
2855
|
+
if (signal) signal.removeEventListener("abort", leave);
|
|
2856
|
+
shared.taps.delete(tap);
|
|
2857
|
+
if (!shared.taps.size && !shared.ended) {
|
|
2858
|
+
shared.ended = true;
|
|
2859
|
+
if (SHARED_SOURCES.get(shared.key) === shared) SHARED_SOURCES.delete(shared.key);
|
|
2860
|
+
shared.teardown.abort();
|
|
2861
|
+
}
|
|
2862
|
+
};
|
|
2863
|
+
const body = new ReadableStream({
|
|
2864
|
+
start(controller) {
|
|
2865
|
+
tap = {
|
|
2866
|
+
write(chunk) {
|
|
2867
|
+
if (closed) return;
|
|
2868
|
+
try {
|
|
2869
|
+
controller.enqueue(chunk);
|
|
2870
|
+
} catch {
|
|
2871
|
+
leave();
|
|
2872
|
+
}
|
|
2873
|
+
},
|
|
2874
|
+
end() {
|
|
2875
|
+
leave();
|
|
2876
|
+
try {
|
|
2877
|
+
controller.close();
|
|
2878
|
+
} catch {}
|
|
2879
|
+
}
|
|
2880
|
+
};
|
|
2881
|
+
stopLive = armLiveBody(controller, leave);
|
|
2882
|
+
if (shared.head) controller.enqueue(shared.head);
|
|
2883
|
+
if (snapshot) controller.enqueue(snapshot);
|
|
2884
|
+
if (shared.ended || signal && signal.aborted) return tap.end();
|
|
2885
|
+
shared.taps.add(tap);
|
|
2886
|
+
if (signal) signal.addEventListener("abort", leave);
|
|
2887
|
+
},
|
|
2888
|
+
cancel() {
|
|
2889
|
+
leave();
|
|
2890
|
+
}
|
|
2891
|
+
});
|
|
2892
|
+
return new Response(body, {
|
|
2893
|
+
status,
|
|
2894
|
+
headers
|
|
2895
|
+
});
|
|
2896
|
+
}
|
|
2897
|
+
function broadcastEvent() {
|
|
2898
|
+
const event = {
|
|
2899
|
+
broadcast: true
|
|
2900
|
+
};
|
|
2901
|
+
for (const name of ["request", "locals", "clientAddress", "nativeEvent"]) Object.defineProperty(event, name, {
|
|
2902
|
+
get() {
|
|
2903
|
+
if (DEV) console.warn(`A broadcast server function read the request (\`event.${name}\`) while producing ` + "its answer, which every viewer shares; read per-viewer state before returning it.");
|
|
2904
|
+
return undefined;
|
|
2905
|
+
}
|
|
2906
|
+
});
|
|
2907
|
+
return event;
|
|
2908
|
+
}
|
|
2909
|
+
function encodeResult(value, headers, status, codec, signal, scope) {
|
|
2910
|
+
if (NULL_BODY_STATUSES.has(status)) {
|
|
2911
|
+
if (value === undefined || value === null) {
|
|
2912
|
+
if (status !== 304) headers.set(BODY_FORMAT_HEADER, BodyFormat.Void);
|
|
2913
|
+
return new Response(null, {
|
|
2914
|
+
status,
|
|
2915
|
+
headers
|
|
2916
|
+
});
|
|
2917
|
+
}
|
|
2918
|
+
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.`);
|
|
2919
|
+
headers.set(ERROR_HEADER, encodeErrorHeaderValue(error.message));
|
|
2920
|
+
return encodeResult(error, headers, 500, codec, signal, scope);
|
|
2921
|
+
}
|
|
912
2922
|
const direct = getHeadersAndBody(value);
|
|
913
2923
|
if (direct) {
|
|
914
2924
|
for (const [key, val] of Object.entries(direct.headers || {})) {
|
|
@@ -920,54 +2930,137 @@ function encodeResult(value, headers, status, codec, signal) {
|
|
|
920
2930
|
});
|
|
921
2931
|
}
|
|
922
2932
|
if (value === undefined) {
|
|
2933
|
+
headers.set(BODY_FORMAT_HEADER, BodyFormat.Void);
|
|
923
2934
|
return new Response(null, {
|
|
924
2935
|
status,
|
|
925
2936
|
headers
|
|
926
2937
|
});
|
|
927
2938
|
}
|
|
928
2939
|
try {
|
|
929
|
-
|
|
2940
|
+
const jsonSafe = scope ? scope(() => isJSONSafe(value)) : isJSONSafe(value);
|
|
2941
|
+
if (jsonSafe) {
|
|
930
2942
|
headers.set(BODY_FORMAT_HEADER, BodyFormat.Json);
|
|
931
2943
|
headers.set("Content-Type", "application/json");
|
|
932
|
-
|
|
2944
|
+
const body = scope ? scope(() => JSON.stringify(value)) : JSON.stringify(value);
|
|
2945
|
+
return new Response(body, {
|
|
933
2946
|
status,
|
|
934
2947
|
headers
|
|
935
2948
|
});
|
|
936
2949
|
}
|
|
937
2950
|
} catch {
|
|
938
2951
|
}
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
status,
|
|
942
|
-
|
|
943
|
-
|
|
2952
|
+
try {
|
|
2953
|
+
const response = serializedResponse(value, headers, codec, signal, scope);
|
|
2954
|
+
return status === 200 ? response : new Response(response.body, {
|
|
2955
|
+
status,
|
|
2956
|
+
headers
|
|
2957
|
+
});
|
|
2958
|
+
} catch (error) {
|
|
2959
|
+
throw DEV && error instanceof Error ? new Error(`Server function result could not be encoded: ${error.message}`) : error;
|
|
2960
|
+
}
|
|
2961
|
+
}
|
|
2962
|
+
const ERROR_HEADER_VALUE_LIMIT = 1024;
|
|
2963
|
+
function boundedErrorHeaderValue(message) {
|
|
2964
|
+
let label = message.length > 256 ? message.slice(0, 256) : message;
|
|
2965
|
+
let encoded = encodeErrorHeaderValue(label);
|
|
2966
|
+
while (encoded.length > ERROR_HEADER_VALUE_LIMIT && label.length > 1) {
|
|
2967
|
+
label = label.slice(0, Math.ceil(label.length / 2));
|
|
2968
|
+
encoded = encodeErrorHeaderValue(label);
|
|
2969
|
+
}
|
|
2970
|
+
return encoded;
|
|
944
2971
|
}
|
|
945
2972
|
const GENERIC_SERVER_ERROR_MESSAGE = "Internal Server Error";
|
|
946
2973
|
let DEV = false === true;
|
|
947
2974
|
function setServerFunctionsDev(dev) {
|
|
948
2975
|
DEV = !!dev;
|
|
949
2976
|
}
|
|
2977
|
+
const REQUEST_ERROR_HOOKS = new WeakMap();
|
|
2978
|
+
function siteFor(handling, event, direct) {
|
|
2979
|
+
const invocation = event ? INVOCATIONS.get(event) : undefined;
|
|
2980
|
+
const site = {
|
|
2981
|
+
kind: "server-function",
|
|
2982
|
+
handling,
|
|
2983
|
+
direct
|
|
2984
|
+
};
|
|
2985
|
+
if (invocation) site.functionId = invocation.id;
|
|
2986
|
+
if (event) site.event = event;
|
|
2987
|
+
return site;
|
|
2988
|
+
}
|
|
2989
|
+
function wireServerFunctionError(value, handling, event = currentEvent()) {
|
|
2990
|
+
const report = reportServerError(value, siteFor(handling, event, false), null, event ? REQUEST_ERROR_HOOKS.get(event) : undefined);
|
|
2991
|
+
return report.mapped ? report.value : sanitizeServerError(value);
|
|
2992
|
+
}
|
|
2993
|
+
function currentEvent() {
|
|
2994
|
+
const store = globalThis[RequestContext];
|
|
2995
|
+
return store ? store.getStore() : undefined;
|
|
2996
|
+
}
|
|
2997
|
+
function reportDirectFailure(run, id, hook) {
|
|
2998
|
+
const report = error => {
|
|
2999
|
+
if (error instanceof Response || isResponseEnvelope(error)) throw error;
|
|
3000
|
+
reportServerError(error, {
|
|
3001
|
+
kind: "server-function",
|
|
3002
|
+
handling: "thrown",
|
|
3003
|
+
functionId: id,
|
|
3004
|
+
direct: true
|
|
3005
|
+
}, null, hook);
|
|
3006
|
+
throw error;
|
|
3007
|
+
};
|
|
3008
|
+
let result;
|
|
3009
|
+
try {
|
|
3010
|
+
result = run();
|
|
3011
|
+
} catch (error) {
|
|
3012
|
+
report(error);
|
|
3013
|
+
}
|
|
3014
|
+
return result && typeof result.then === "function" ? result.then(undefined, report) : result;
|
|
3015
|
+
}
|
|
3016
|
+
function directEnvelopeValue(result, event) {
|
|
3017
|
+
if (!isResponseEnvelope(result)) return result;
|
|
3018
|
+
const {
|
|
3019
|
+
response,
|
|
3020
|
+
value
|
|
3021
|
+
} = result;
|
|
3022
|
+
const stub = event.response;
|
|
3023
|
+
if (response && stub && stub.headers && response.headers.getSetCookie) {
|
|
3024
|
+
for (const cookie of response.headers.getSetCookie()) {
|
|
3025
|
+
stub.headers.append("Set-Cookie", cookie);
|
|
3026
|
+
}
|
|
3027
|
+
}
|
|
3028
|
+
return value;
|
|
3029
|
+
}
|
|
950
3030
|
function sanitizeServerError(value) {
|
|
951
3031
|
if (DEV) return value;
|
|
952
3032
|
if (isSafeError(value)) return value;
|
|
953
|
-
|
|
3033
|
+
const wire = new Error(GENERIC_SERVER_ERROR_MESSAGE);
|
|
3034
|
+
return wire;
|
|
3035
|
+
}
|
|
3036
|
+
function serverFunctionUrl(fn, ...args) {
|
|
3037
|
+
return serverFunctionUrlFor(config.endpoint, fn, args);
|
|
954
3038
|
}
|
|
955
|
-
function
|
|
956
|
-
return (
|
|
3039
|
+
function serverFunctionActionUrl(fn, ...boundArgs) {
|
|
3040
|
+
return serverFunctionActionUrlFor(config.endpoint, fn, boundArgs);
|
|
3041
|
+
}
|
|
3042
|
+
function parseServerFunctionActionUrl(url) {
|
|
3043
|
+
const parsed = parseServerFunctionAddress(new URL(url, "http://localhost").pathname, config.endpoint);
|
|
3044
|
+
return parsed && parsed.id;
|
|
957
3045
|
}
|
|
958
3046
|
async function matchesOrigin(origin, request, matcher) {
|
|
959
3047
|
if (matcher === undefined) return origin === new URL(request.url).origin;
|
|
960
|
-
if (typeof matcher === "function") return
|
|
3048
|
+
if (typeof matcher === "function") return (await matcher(origin, request)) === true;
|
|
961
3049
|
return Array.isArray(matcher) ? matcher.includes(origin) : origin === matcher;
|
|
962
3050
|
}
|
|
963
3051
|
async function allowsServerFunctionRequest(request, options) {
|
|
964
3052
|
const fetchSite = request.headers.get("Sec-Fetch-Site");
|
|
965
3053
|
if (fetchSite === "same-origin") return true;
|
|
966
|
-
if (fetchSite === "
|
|
967
|
-
return false;
|
|
968
|
-
}
|
|
3054
|
+
if (fetchSite === "none") return false;
|
|
969
3055
|
const origin = request.headers.get("Origin");
|
|
970
|
-
if (
|
|
3056
|
+
if (fetchSite === "same-site" || fetchSite === "cross-site") {
|
|
3057
|
+
if (origin === null || options.origin === undefined) return false;
|
|
3058
|
+
return (await matchesOrigin(origin, request, options.origin)) ? origin : false;
|
|
3059
|
+
}
|
|
3060
|
+
if (origin !== null) {
|
|
3061
|
+
if (!(await matchesOrigin(origin, request, options.origin))) return false;
|
|
3062
|
+
return origin === new URL(request.url).origin ? true : origin;
|
|
3063
|
+
}
|
|
971
3064
|
const referer = request.headers.get("Referer");
|
|
972
3065
|
if (referer !== null) {
|
|
973
3066
|
try {
|
|
@@ -979,21 +3072,23 @@ async function allowsServerFunctionRequest(request, options) {
|
|
|
979
3072
|
return options.allowRequestsWithoutOriginCheck === true;
|
|
980
3073
|
}
|
|
981
3074
|
const CSRF_VARY = ["Sec-Fetch-Site", "Origin", "Referer"];
|
|
982
|
-
function
|
|
983
|
-
const current =
|
|
984
|
-
if (current === "*") return
|
|
3075
|
+
function appendVary(headers, names) {
|
|
3076
|
+
const current = headers.get("Vary");
|
|
3077
|
+
if (current === "*") return;
|
|
985
3078
|
const values = current ? current.split(",").map(value => value.trim()) : [];
|
|
986
|
-
const
|
|
987
|
-
for (const
|
|
988
|
-
if (!
|
|
3079
|
+
const seen = new Set(values.map(value => value.toLowerCase()));
|
|
3080
|
+
for (const name of names) {
|
|
3081
|
+
if (!seen.has(name.toLowerCase())) values.push(name);
|
|
989
3082
|
}
|
|
990
|
-
|
|
3083
|
+
headers.set("Vary", values.join(", "));
|
|
3084
|
+
}
|
|
3085
|
+
function withHeaders(response, write) {
|
|
991
3086
|
try {
|
|
992
|
-
response.headers
|
|
3087
|
+
write(response.headers);
|
|
993
3088
|
return response;
|
|
994
3089
|
} catch {
|
|
995
3090
|
const headers = new Headers(response.headers);
|
|
996
|
-
headers
|
|
3091
|
+
write(headers);
|
|
997
3092
|
return new Response(response.body, {
|
|
998
3093
|
status: response.status,
|
|
999
3094
|
statusText: response.statusText,
|
|
@@ -1001,6 +3096,42 @@ function withCSRFVary(response) {
|
|
|
1001
3096
|
});
|
|
1002
3097
|
}
|
|
1003
3098
|
}
|
|
3099
|
+
function withCSRFVary(response) {
|
|
3100
|
+
return withHeaders(response, headers => appendVary(headers, CSRF_VARY));
|
|
3101
|
+
}
|
|
3102
|
+
const TRANSPORT_REQUEST_HEADERS = ["Content-Type", BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, BUILD_HEADER].join(", ");
|
|
3103
|
+
const PREFLIGHT_MAX_AGE = "600";
|
|
3104
|
+
const CORS_SAFELISTED_RESPONSE_HEADERS = new Set(["cache-control", "content-language", "content-length", "content-type", "expires", "last-modified", "pragma"]);
|
|
3105
|
+
function withCORS(response, cors) {
|
|
3106
|
+
if (cors === null) return response;
|
|
3107
|
+
return withHeaders(response, headers => {
|
|
3108
|
+
headers.set("Access-Control-Allow-Origin", cors.origin);
|
|
3109
|
+
if (cors.credentials) headers.set("Access-Control-Allow-Credentials", "true");
|
|
3110
|
+
const exposed = [];
|
|
3111
|
+
for (const name of headers.keys()) {
|
|
3112
|
+
if (CORS_SAFELISTED_RESPONSE_HEADERS.has(name) || name === "set-cookie" || name === "vary" || name.startsWith("access-control-")) {
|
|
3113
|
+
continue;
|
|
3114
|
+
}
|
|
3115
|
+
exposed.push(name);
|
|
3116
|
+
}
|
|
3117
|
+
if (exposed.length > 0) headers.set("Access-Control-Expose-Headers", exposed.join(", "));
|
|
3118
|
+
appendVary(headers, ["Origin"]);
|
|
3119
|
+
});
|
|
3120
|
+
}
|
|
3121
|
+
function preflightResponse(request) {
|
|
3122
|
+
const requested = request.headers.get("Access-Control-Request-Headers");
|
|
3123
|
+
const response = new Response(null, {
|
|
3124
|
+
status: 204,
|
|
3125
|
+
headers: {
|
|
3126
|
+
"Access-Control-Allow-Methods": "POST, GET, HEAD",
|
|
3127
|
+
"Access-Control-Allow-Headers": requested !== null && requested.trim() !== "" ? requested : TRANSPORT_REQUEST_HEADERS,
|
|
3128
|
+
"Access-Control-Max-Age": PREFLIGHT_MAX_AGE,
|
|
3129
|
+
"Cache-Control": "no-store"
|
|
3130
|
+
}
|
|
3131
|
+
});
|
|
3132
|
+
appendVary(response.headers, ["Access-Control-Request-Method", "Access-Control-Request-Headers"]);
|
|
3133
|
+
return response;
|
|
3134
|
+
}
|
|
1004
3135
|
function forbiddenResponse() {
|
|
1005
3136
|
return withCSRFVary(new Response(DEV ? "Forbidden" : null, {
|
|
1006
3137
|
status: 403,
|
|
@@ -1009,56 +3140,198 @@ function forbiddenResponse() {
|
|
|
1009
3140
|
}
|
|
1010
3141
|
}));
|
|
1011
3142
|
}
|
|
3143
|
+
function nativePromise(value) {
|
|
3144
|
+
if (value instanceof Promise) return value;
|
|
3145
|
+
try {
|
|
3146
|
+
if (Object.prototype.toString.call(value) === "[object Promise]") return Promise.prototype.then.call(value, value => value);
|
|
3147
|
+
} catch {}
|
|
3148
|
+
}
|
|
1012
3149
|
async function handleServerFunctionRequest(request, options = {}) {
|
|
1013
|
-
const codec =
|
|
3150
|
+
const codec = {
|
|
3151
|
+
...(options.codec !== undefined ? options.codec : getServerFunctionsCodec())
|
|
3152
|
+
};
|
|
3153
|
+
codec.serializeErrorStacks ??= DEV;
|
|
1014
3154
|
const url = new URL(request.url);
|
|
3155
|
+
const method = request.method;
|
|
3156
|
+
const address = resolveAddress(url);
|
|
3157
|
+
const functionId = address && address.id;
|
|
3158
|
+
const declaredRead = (method === "GET" || method === "HEAD") && functionId !== null && declaresRead(functionId);
|
|
1015
3159
|
const csrf = options.csrf !== undefined ? options.csrf : config.csrf;
|
|
1016
|
-
const protectsRequest = csrf !== false;
|
|
1017
|
-
|
|
1018
|
-
|
|
3160
|
+
const protectsRequest = csrf !== false && (!declaredRead || CARRIED.has(functionId) || typeof csrf === "object" && csrf.protectDeclaredReads === true);
|
|
3161
|
+
const csrfOptions = csrf === true ? {} : csrf;
|
|
3162
|
+
let verdict = true;
|
|
3163
|
+
let readVariesByOrigin = false;
|
|
3164
|
+
if (protectsRequest) {
|
|
3165
|
+
verdict = await allowsServerFunctionRequest(request, csrfOptions);
|
|
3166
|
+
} else if (csrfOptions !== false && csrfOptions.origin !== undefined) {
|
|
3167
|
+
readVariesByOrigin = true;
|
|
3168
|
+
const admitted = await allowsServerFunctionRequest(request, csrfOptions);
|
|
3169
|
+
if (typeof admitted === "string") verdict = admitted;
|
|
3170
|
+
}
|
|
3171
|
+
const cors = typeof verdict === "string" ? {
|
|
3172
|
+
origin: verdict,
|
|
3173
|
+
credentials: csrfOptions.allowCredentials === true
|
|
3174
|
+
} : null;
|
|
3175
|
+
const finish = response => {
|
|
3176
|
+
const finalized = withCORS(finalizeTransportResponse(response, method), cors);
|
|
3177
|
+
return readVariesByOrigin && cors === null ? withHeaders(finalized, headers => appendVary(headers, ["Origin"])) : finalized;
|
|
3178
|
+
};
|
|
3179
|
+
if (cors !== null && method === "OPTIONS" && request.headers.has("Access-Control-Request-Method")) {
|
|
3180
|
+
return finish(preflightResponse(request));
|
|
3181
|
+
}
|
|
3182
|
+
let serverFunction;
|
|
3183
|
+
if (functionId) {
|
|
3184
|
+
try {
|
|
3185
|
+
serverFunction = getServerFunction(functionId);
|
|
3186
|
+
} catch {
|
|
3187
|
+
return finish(new Response(DEV ? `Unknown server function: ${functionId}` : null, {
|
|
3188
|
+
status: 404,
|
|
3189
|
+
headers: {
|
|
3190
|
+
[UNKNOWN_HEADER]: "true"
|
|
3191
|
+
}
|
|
3192
|
+
}));
|
|
3193
|
+
}
|
|
3194
|
+
}
|
|
3195
|
+
if (verdict === false) {
|
|
3196
|
+
return finish(forbiddenResponse());
|
|
1019
3197
|
}
|
|
1020
|
-
const instance = request.headers.get(INSTANCE_HEADER);
|
|
1021
|
-
const functionId = resolveFunctionId(request, url);
|
|
1022
3198
|
if (!functionId) {
|
|
1023
3199
|
const response = new Response(DEV ? "Server function not found" : null, {
|
|
1024
3200
|
status: 404
|
|
1025
3201
|
});
|
|
1026
|
-
return protectsRequest ? withCSRFVary(response) : response;
|
|
3202
|
+
return finish(protectsRequest ? withCSRFVary(response) : response);
|
|
1027
3203
|
}
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
3204
|
+
const callerBuild = request.headers.get(BUILD_HEADER);
|
|
3205
|
+
if (config.buildId && callerBuild !== null && callerBuild !== config.buildId) {
|
|
3206
|
+
return finish(new Response(DEV ? `Server function call from build "${callerBuild}" refused by build "${config.buildId}"` : null, {
|
|
3207
|
+
status: 409,
|
|
3208
|
+
headers: {
|
|
3209
|
+
[UNKNOWN_HEADER]: "true",
|
|
3210
|
+
[BUILD_HEADER]: config.buildId,
|
|
3211
|
+
"Cache-Control": "no-store"
|
|
3212
|
+
}
|
|
3213
|
+
}));
|
|
1036
3214
|
}
|
|
1037
|
-
|
|
3215
|
+
const scripted = address.data || address.live;
|
|
3216
|
+
const live = address.live;
|
|
3217
|
+
if (method !== "POST" && !declaredRead) {
|
|
1038
3218
|
const response = new Response(DEV ? `Method not allowed for server function: ${functionId}` : null, {
|
|
1039
3219
|
status: 405,
|
|
1040
3220
|
headers: {
|
|
1041
|
-
Allow: "POST"
|
|
3221
|
+
Allow: declaresRead(functionId) ? "POST, GET, HEAD" : "POST"
|
|
1042
3222
|
}
|
|
1043
3223
|
});
|
|
1044
|
-
return protectsRequest ? withCSRFVary(response) : response;
|
|
3224
|
+
return finish(protectsRequest ? withCSRFVary(response) : response);
|
|
1045
3225
|
}
|
|
1046
|
-
const
|
|
1047
|
-
|
|
1048
|
-
|
|
3226
|
+
const bodySizeLimit = options.bodySizeLimit !== undefined ? options.bodySizeLimit : config.bodySizeLimit;
|
|
3227
|
+
const argsEncoding = url.searchParams.get("args");
|
|
3228
|
+
if (argsEncoding !== null && argsEncoding.length > bodySizeLimit) {
|
|
3229
|
+
const response = new Response(DEV ? "Server function arguments exceed the configured bodySizeLimit" : null, {
|
|
3230
|
+
status: 413
|
|
3231
|
+
});
|
|
3232
|
+
return finish(protectsRequest ? withCSRFVary(response) : response);
|
|
3233
|
+
}
|
|
3234
|
+
let argumentBytes = null;
|
|
3235
|
+
if (method === "POST" && request.body !== null && bodySizeLimit !== Infinity) {
|
|
3236
|
+
const raw = request.headers.get("content-length");
|
|
3237
|
+
const declared = raw !== null && /^\d+$/.test(raw) ? Number(raw) : NaN;
|
|
3238
|
+
if (declared > bodySizeLimit) {
|
|
3239
|
+
const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
|
|
3240
|
+
status: 413
|
|
3241
|
+
});
|
|
3242
|
+
return finish(protectsRequest ? withCSRFVary(response) : response);
|
|
3243
|
+
}
|
|
3244
|
+
let buffered;
|
|
3245
|
+
try {
|
|
3246
|
+
buffered = await bufferBodyWithin(request, bodySizeLimit);
|
|
3247
|
+
} catch {
|
|
3248
|
+
const response = new Response(DEV ? "Malformed server function arguments" : null, {
|
|
3249
|
+
status: 400
|
|
3250
|
+
});
|
|
3251
|
+
return finish(protectsRequest ? withCSRFVary(response) : response);
|
|
3252
|
+
}
|
|
3253
|
+
if (buffered === null) {
|
|
3254
|
+
const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
|
|
3255
|
+
status: 413
|
|
3256
|
+
});
|
|
3257
|
+
return finish(protectsRequest ? withCSRFVary(response) : response);
|
|
3258
|
+
}
|
|
3259
|
+
request = withBufferedBody(request, buffered);
|
|
3260
|
+
argumentBytes = buffered;
|
|
3261
|
+
}
|
|
3262
|
+
let event;
|
|
3263
|
+
try {
|
|
3264
|
+
event = options.createEvent ? options.createEvent(request) : {
|
|
3265
|
+
request,
|
|
3266
|
+
locals: {}
|
|
3267
|
+
};
|
|
3268
|
+
const promised = nativePromise(event);
|
|
3269
|
+
if (promised) event = await promised;
|
|
3270
|
+
} catch (error) {
|
|
3271
|
+
const safe = sanitizeServerError(error);
|
|
3272
|
+
const message = safe instanceof Error ? safe.message : String(safe);
|
|
3273
|
+
const headers = new Headers();
|
|
3274
|
+
headers.set(ERROR_HEADER, boundedErrorHeaderValue(message));
|
|
3275
|
+
const response = scripted ? encodeResult(safe, headers, 500, codec, request.signal) : new Response(DEV ? message : null, {
|
|
3276
|
+
status: 500
|
|
3277
|
+
});
|
|
3278
|
+
return finish(protectsRequest ? withCSRFVary(response) : response);
|
|
3279
|
+
}
|
|
3280
|
+
const commitResponse = raw => {
|
|
3281
|
+
if ((method === "GET" || method === "HEAD") && (sharedCacheMayStore(departingHeader(raw, event, "Cache-Control")) || cdnMayStore(departingHeader(raw, event, "CDN-Cache-Control")))) {
|
|
3282
|
+
withholdTrace(event);
|
|
3283
|
+
}
|
|
3284
|
+
return commitEventResponse(raw, event);
|
|
3285
|
+
};
|
|
3286
|
+
const refuseCommitted = raw => {
|
|
3287
|
+
const response = commitResponse(raw);
|
|
3288
|
+
return finish(protectsRequest ? withCSRFVary(response) : response);
|
|
1049
3289
|
};
|
|
1050
3290
|
const provide = options.provideEvent || provideEvent;
|
|
3291
|
+
const scope = run => provide(event, run);
|
|
3292
|
+
if (options.onError !== undefined) REQUEST_ERROR_HOOKS.set(event, options.onError);
|
|
1051
3293
|
const flightHook = options.collectFlightData !== undefined ? options.collectFlightData : config.collectFlightData;
|
|
1052
3294
|
const transformResult = options.transformResult !== undefined ? options.transformResult : config.transformResult;
|
|
1053
|
-
const wrapInvocation = options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation;
|
|
3295
|
+
const wrapInvocation = resolveWrapInvocation(options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation);
|
|
1054
3296
|
const transformFlightResult = options.transformFlightResult !== undefined ? options.transformFlightResult : config.transformFlightResult;
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
3297
|
+
let handleNoJS = options.handleNoJS !== undefined ? options.handleNoJS : config.handleNoJS;
|
|
3298
|
+
if (handleNoJS === undefined && !scripted && isFormPost(request)) {
|
|
3299
|
+
const fetchMode = request.headers.get("Sec-Fetch-Mode");
|
|
3300
|
+
if (fetchMode === null || fetchMode === "navigate") {
|
|
3301
|
+
handleNoJS = defaultNoJSHandler || (defaultNoJSHandler = createNoJSHandler());
|
|
3302
|
+
} else {
|
|
3303
|
+
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, {
|
|
3304
|
+
status: 400
|
|
3305
|
+
});
|
|
3306
|
+
return refuseCommitted(response);
|
|
3307
|
+
}
|
|
3308
|
+
}
|
|
3309
|
+
const flightHeader = scripted && method === "POST" ? request.headers.get(SINGLE_FLIGHT_HEADER) : null;
|
|
3310
|
+
const flightHooks = flightHeader ? [...new Set(flightHeader.split(","))].flatMap(source => {
|
|
3311
|
+
const hook = source === "true" ? flightHook : flightSources.get(source);
|
|
3312
|
+
return hook ? [[source, hook]] : [];
|
|
3313
|
+
}) : [];
|
|
3314
|
+
const collectsFlight = flightHooks.length > 0;
|
|
3315
|
+
let parsed;
|
|
3316
|
+
try {
|
|
3317
|
+
parsed = await parseArguments(request, url, scripted, codec, argumentBytes);
|
|
3318
|
+
} catch (error) {
|
|
3319
|
+
const named = error !== null && typeof error === "object" && error[FORMAT_SKEW] === true ? error : refusedArgument(error);
|
|
3320
|
+
const response = new Response(DEV ? named ? named.message : "Malformed server function arguments" : null, {
|
|
3321
|
+
status: 400
|
|
3322
|
+
});
|
|
3323
|
+
return refuseCommitted(response);
|
|
3324
|
+
}
|
|
3325
|
+
const maxArguments = options.maxArguments !== undefined ? options.maxArguments : config.maxArguments;
|
|
3326
|
+
if (parsed.length > maxArguments) {
|
|
3327
|
+
const response = new Response(DEV ? "Server function call exceeds the configured maxArguments" : null, {
|
|
3328
|
+
status: 400
|
|
3329
|
+
});
|
|
3330
|
+
return refuseCommitted(response);
|
|
3331
|
+
}
|
|
1058
3332
|
const flightContext = {
|
|
1059
3333
|
id: functionId,
|
|
1060
3334
|
args: parsed,
|
|
1061
|
-
instance,
|
|
1062
3335
|
request,
|
|
1063
3336
|
collectsFlight,
|
|
1064
3337
|
codec,
|
|
@@ -1067,19 +3340,30 @@ async function handleServerFunctionRequest(request, options = {}) {
|
|
|
1067
3340
|
const headers = new Headers();
|
|
1068
3341
|
const dispatch = async () => {
|
|
1069
3342
|
try {
|
|
1070
|
-
|
|
3343
|
+
const invokeOnce = async () => {
|
|
3344
|
+
const shared = !!live && BROADCASTS.has(functionId);
|
|
1071
3345
|
INVOCATIONS.set(event, {
|
|
1072
|
-
id: functionId
|
|
3346
|
+
id: functionId,
|
|
3347
|
+
live: !!live,
|
|
3348
|
+
broadcast: shared || undefined,
|
|
3349
|
+
shareKey: shared ? encodedArguments(request, url, argsEncoding, argumentBytes) : undefined
|
|
1073
3350
|
});
|
|
1074
3351
|
const run = () => serverFunction(...parsed);
|
|
1075
|
-
return
|
|
3352
|
+
return observeInvocation({
|
|
3353
|
+
id: functionId,
|
|
3354
|
+
direct: false,
|
|
3355
|
+
event,
|
|
3356
|
+
request,
|
|
3357
|
+
args: parsed
|
|
3358
|
+
}, () => wrapInvocation ? wrapInvocation(run, {
|
|
1076
3359
|
id: functionId,
|
|
1077
3360
|
args: parsed,
|
|
1078
3361
|
event,
|
|
1079
3362
|
request,
|
|
1080
3363
|
direct: false
|
|
1081
|
-
}) : run();
|
|
1082
|
-
}
|
|
3364
|
+
}) : run());
|
|
3365
|
+
};
|
|
3366
|
+
let result = await provideEventOnce(provide, event, invokeOnce);
|
|
1083
3367
|
if (transformResult) {
|
|
1084
3368
|
result = await transformResult(event, result, flightContext);
|
|
1085
3369
|
}
|
|
@@ -1090,25 +3374,29 @@ async function handleServerFunctionRequest(request, options = {}) {
|
|
|
1090
3374
|
response,
|
|
1091
3375
|
value
|
|
1092
3376
|
} = result;
|
|
1093
|
-
if (!
|
|
3377
|
+
if (!scripted && !handleNoJS && response && response.body && isJSONSafe(value)) {
|
|
1094
3378
|
return response;
|
|
1095
3379
|
}
|
|
1096
3380
|
if (response && response.headers) {
|
|
1097
3381
|
mergeResponseHeaders(headers, response.headers);
|
|
1098
3382
|
}
|
|
1099
|
-
if (response && response.status && (
|
|
3383
|
+
if (response && response.status && (!scripted || !validRedirectStatuses.has(response.status))) {
|
|
1100
3384
|
status = response.status;
|
|
3385
|
+
} else if (response && response.status) {
|
|
3386
|
+
maskRedirect(headers, response, request.url);
|
|
1101
3387
|
}
|
|
1102
3388
|
metadata = response;
|
|
1103
3389
|
result = value;
|
|
1104
3390
|
} else if (result instanceof Response) {
|
|
1105
3391
|
if (result.headers && result.headers.has("X-Content-Raw")) return result;
|
|
1106
|
-
if (
|
|
3392
|
+
if (scripted) {
|
|
1107
3393
|
if (result.headers) {
|
|
1108
3394
|
mergeResponseHeaders(headers, result.headers);
|
|
1109
3395
|
}
|
|
1110
|
-
if (result.status && (result.status
|
|
3396
|
+
if (result.status && !validRedirectStatuses.has(result.status)) {
|
|
1111
3397
|
status = result.status;
|
|
3398
|
+
} else if (result.status) {
|
|
3399
|
+
maskRedirect(headers, result, request.url);
|
|
1112
3400
|
}
|
|
1113
3401
|
metadata = result;
|
|
1114
3402
|
if (result.body == null) {
|
|
@@ -1117,7 +3405,7 @@ async function handleServerFunctionRequest(request, options = {}) {
|
|
|
1117
3405
|
}
|
|
1118
3406
|
}
|
|
1119
3407
|
if (collectsFlight) {
|
|
1120
|
-
result = await foldFlightData(
|
|
3408
|
+
result = await foldFlightData(flightHooks, event, headers, {
|
|
1121
3409
|
id: functionId,
|
|
1122
3410
|
value: result,
|
|
1123
3411
|
response: metadata,
|
|
@@ -1126,20 +3414,45 @@ async function handleServerFunctionRequest(request, options = {}) {
|
|
|
1126
3414
|
}, flightContext);
|
|
1127
3415
|
if (result instanceof Response && result.headers.has("X-Content-Raw")) return result;
|
|
1128
3416
|
}
|
|
1129
|
-
if (!
|
|
1130
|
-
if (handleNoJS)
|
|
3417
|
+
if (!scripted) {
|
|
3418
|
+
if (handleNoJS) {
|
|
3419
|
+
const outcome = result == null && metadata !== undefined ? metadata : result;
|
|
3420
|
+
return withEnvelopeCookies(await handleNoJS(outcome, request, parsed), outcome, metadata);
|
|
3421
|
+
}
|
|
1131
3422
|
if (result instanceof Response) return result;
|
|
1132
|
-
return encodeResult(result, headers,
|
|
3423
|
+
return encodeResult(result, headers, status, codec, request.signal, scope);
|
|
3424
|
+
}
|
|
3425
|
+
if (status === 304) warnScripted304(functionId);
|
|
3426
|
+
if (live) {
|
|
3427
|
+
const invocation = INVOCATIONS.get(event);
|
|
3428
|
+
return encodeLiveResult(result, headers, status, codec, request, scope, invocation && invocation.broadcast && invocation.shareKey !== undefined ? invocation.id + "\0" + invocation.shareKey : undefined);
|
|
1133
3429
|
}
|
|
1134
|
-
return encodeResult(result, headers, status, codec, request.signal);
|
|
3430
|
+
return encodeResult(result, headers, status, codec, request.signal, scope);
|
|
1135
3431
|
} catch (x) {
|
|
1136
|
-
|
|
1137
|
-
|
|
3432
|
+
const respondThrown = value => {
|
|
3433
|
+
const safe = wireServerFunctionError(value, "thrown", event);
|
|
3434
|
+
if (!scripted) {
|
|
3435
|
+
if (handleNoJS) return handleNoJS(safe, request, parsed, true);
|
|
3436
|
+
const message = safe instanceof Error ? safe.message : String(safe);
|
|
3437
|
+
return new Response(DEV ? message : null, {
|
|
3438
|
+
status: 500
|
|
3439
|
+
});
|
|
3440
|
+
}
|
|
3441
|
+
const error = safe instanceof Error ? safe.message : typeof safe === "string" ? safe : "true";
|
|
3442
|
+
headers.set(ERROR_HEADER, boundedErrorHeaderValue(error));
|
|
3443
|
+
return encodeResult(safe, headers, 500, codec, request.signal, scope);
|
|
3444
|
+
};
|
|
3445
|
+
if (transformResult) {
|
|
3446
|
+
try {
|
|
1138
3447
|
x = await transformResult(event, x, {
|
|
1139
3448
|
...flightContext,
|
|
1140
3449
|
thrown: true
|
|
1141
3450
|
});
|
|
3451
|
+
} catch (hookError) {
|
|
3452
|
+
return respondThrown(hookError);
|
|
1142
3453
|
}
|
|
3454
|
+
}
|
|
3455
|
+
if (x instanceof Response || isResponseEnvelope(x)) {
|
|
1143
3456
|
let status = 200;
|
|
1144
3457
|
let metadata;
|
|
1145
3458
|
if (isResponseEnvelope(x)) {
|
|
@@ -1150,8 +3463,10 @@ async function handleServerFunctionRequest(request, options = {}) {
|
|
|
1150
3463
|
if (response && response.headers) {
|
|
1151
3464
|
mergeResponseHeaders(headers, response.headers);
|
|
1152
3465
|
}
|
|
1153
|
-
if (response && response.status && (!
|
|
3466
|
+
if (response && response.status && (!scripted || !validRedirectStatuses.has(response.status))) {
|
|
1154
3467
|
status = response.status;
|
|
3468
|
+
} else if (response && response.status) {
|
|
3469
|
+
maskRedirect(headers, response, request.url);
|
|
1155
3470
|
}
|
|
1156
3471
|
metadata = response;
|
|
1157
3472
|
x = value;
|
|
@@ -1159,8 +3474,10 @@ async function handleServerFunctionRequest(request, options = {}) {
|
|
|
1159
3474
|
if (x.headers) {
|
|
1160
3475
|
mergeResponseHeaders(headers, x.headers);
|
|
1161
3476
|
}
|
|
1162
|
-
if (x.status && (!
|
|
3477
|
+
if (x.status && (!scripted || !validRedirectStatuses.has(x.status))) {
|
|
1163
3478
|
status = x.status;
|
|
3479
|
+
} else if (x.status) {
|
|
3480
|
+
maskRedirect(headers, x, request.url);
|
|
1164
3481
|
}
|
|
1165
3482
|
metadata = x;
|
|
1166
3483
|
if (x.body == null) {
|
|
@@ -1168,7 +3485,7 @@ async function handleServerFunctionRequest(request, options = {}) {
|
|
|
1168
3485
|
}
|
|
1169
3486
|
}
|
|
1170
3487
|
if (collectsFlight) {
|
|
1171
|
-
x = await foldFlightData(
|
|
3488
|
+
x = await foldFlightData(flightHooks, event, headers, {
|
|
1172
3489
|
id: functionId,
|
|
1173
3490
|
value: x,
|
|
1174
3491
|
response: metadata,
|
|
@@ -1176,32 +3493,125 @@ async function handleServerFunctionRequest(request, options = {}) {
|
|
|
1176
3493
|
thrown: true
|
|
1177
3494
|
}, flightContext);
|
|
1178
3495
|
if (x instanceof Response && x.headers.has("X-Content-Raw")) {
|
|
3496
|
+
x = ownResponse(x);
|
|
1179
3497
|
x.headers.set(ERROR_HEADER, "true");
|
|
1180
3498
|
return x;
|
|
1181
3499
|
}
|
|
1182
3500
|
}
|
|
1183
3501
|
headers.set(ERROR_HEADER, "true");
|
|
1184
|
-
if (!
|
|
1185
|
-
if (handleNoJS)
|
|
3502
|
+
if (!scripted) {
|
|
3503
|
+
if (handleNoJS) {
|
|
3504
|
+
const outcome = x ?? metadata;
|
|
3505
|
+
return withEnvelopeCookies(await handleNoJS(outcome, request, parsed, true), outcome, metadata);
|
|
3506
|
+
}
|
|
1186
3507
|
if (x instanceof Response) return x;
|
|
1187
3508
|
}
|
|
1188
|
-
|
|
3509
|
+
if (scripted && status === 304) warnScripted304(functionId);
|
|
3510
|
+
return encodeResult(x, headers, status, codec, request.signal, scope);
|
|
1189
3511
|
}
|
|
1190
|
-
|
|
1191
|
-
if (!instance) {
|
|
1192
|
-
if (handleNoJS) return handleNoJS(safe, request, parsed, true);
|
|
1193
|
-
const message = safe instanceof Error ? safe.message : String(safe);
|
|
1194
|
-
return new Response(DEV ? message : null, {
|
|
1195
|
-
status: 500
|
|
1196
|
-
});
|
|
1197
|
-
}
|
|
1198
|
-
const error = safe instanceof Error ? safe.message : typeof safe === "string" ? safe : "true";
|
|
1199
|
-
headers.set(ERROR_HEADER, encodeErrorHeaderValue(error));
|
|
1200
|
-
return encodeResult(safe, headers, 200, codec, request.signal);
|
|
3512
|
+
return respondThrown(x);
|
|
1201
3513
|
}
|
|
1202
3514
|
};
|
|
1203
|
-
const response =
|
|
1204
|
-
return protectsRequest ? withCSRFVary(response) : response;
|
|
3515
|
+
const response = commitResponse(enforceComposedHeaderInvariants(ownResponse(await dispatch())));
|
|
3516
|
+
return finish(protectsRequest ? withCSRFVary(response) : response);
|
|
3517
|
+
}
|
|
3518
|
+
function departingHeader(response, event, name) {
|
|
3519
|
+
const own = response.headers.get(name);
|
|
3520
|
+
if (own !== null) return own;
|
|
3521
|
+
const stub = event.response;
|
|
3522
|
+
return stub && stub.headers && !stub.committed ? stub.headers.get(name) : null;
|
|
3523
|
+
}
|
|
3524
|
+
function cdnMayStore(cdnCacheControl) {
|
|
3525
|
+
return cdnCacheControl !== null && !forbidsStoring(cdnCacheControl);
|
|
3526
|
+
}
|
|
3527
|
+
function sharedCacheMayStore(cacheControl) {
|
|
3528
|
+
let shared = false;
|
|
3529
|
+
return !!cacheControl && !eachDirective(cacheControl, name => {
|
|
3530
|
+
if (name === "public" || name === "s-maxage") shared = true;
|
|
3531
|
+
}) && shared;
|
|
3532
|
+
}
|
|
3533
|
+
function forbidsStoring(value) {
|
|
3534
|
+
return eachDirective(value, () => {});
|
|
3535
|
+
}
|
|
3536
|
+
function eachDirective(value, visit) {
|
|
3537
|
+
let start = 0;
|
|
3538
|
+
let quoted = false;
|
|
3539
|
+
for (let i = 0; i <= value.length; i++) {
|
|
3540
|
+
const c = value[i];
|
|
3541
|
+
if (quoted) {
|
|
3542
|
+
if (c === "\\") i++;else if (c === '"') quoted = false;
|
|
3543
|
+
continue;
|
|
3544
|
+
}
|
|
3545
|
+
if (c === '"') {
|
|
3546
|
+
quoted = true;
|
|
3547
|
+
continue;
|
|
3548
|
+
}
|
|
3549
|
+
if (c !== "," && i < value.length) continue;
|
|
3550
|
+
const directive = value.slice(start, i);
|
|
3551
|
+
start = i + 1;
|
|
3552
|
+
const eq = directive.indexOf("=");
|
|
3553
|
+
const name = (eq === -1 ? directive : directive.slice(0, eq)).trim().toLowerCase();
|
|
3554
|
+
if (name === "no-store" || name === "private" && eq === -1) return true;
|
|
3555
|
+
visit(name);
|
|
3556
|
+
}
|
|
3557
|
+
return false;
|
|
3558
|
+
}
|
|
3559
|
+
function withholdTrace(event) {
|
|
3560
|
+
if (event.response && event.response.committed) return;
|
|
3561
|
+
traceForEvent(event).emit = false;
|
|
3562
|
+
}
|
|
3563
|
+
function withEnvelopeCookies(response, outcome, metadata) {
|
|
3564
|
+
if (outcome === metadata || !metadata || !metadata.headers || !(response instanceof Response)) {
|
|
3565
|
+
return response;
|
|
3566
|
+
}
|
|
3567
|
+
const cookies = metadata.headers.getSetCookie ? metadata.headers.getSetCookie() : [];
|
|
3568
|
+
if (!cookies.length) return response;
|
|
3569
|
+
const owned = ownResponse(response);
|
|
3570
|
+
if (owned === response) return response;
|
|
3571
|
+
for (const cookie of cookies) owned.headers.append("Set-Cookie", cookie);
|
|
3572
|
+
return owned;
|
|
3573
|
+
}
|
|
3574
|
+
function ownResponse(response) {
|
|
3575
|
+
try {
|
|
3576
|
+
return new Response(response.body, response);
|
|
3577
|
+
} catch {
|
|
3578
|
+
return response;
|
|
3579
|
+
}
|
|
3580
|
+
}
|
|
3581
|
+
function finalizeTransportResponse(response, method) {
|
|
3582
|
+
const stripBody = method === "HEAD" && response.body !== null;
|
|
3583
|
+
const defaultsCache = !response.headers.has("Cache-Control") && response.status !== 304;
|
|
3584
|
+
const defaultsSniff = !response.headers.has("X-Content-Type-Options");
|
|
3585
|
+
if (stripBody || defaultsCache || defaultsSniff) {
|
|
3586
|
+
try {
|
|
3587
|
+
if (defaultsCache) {
|
|
3588
|
+
response.headers.set("Cache-Control", "no-store");
|
|
3589
|
+
}
|
|
3590
|
+
if (defaultsSniff) {
|
|
3591
|
+
response.headers.set("X-Content-Type-Options", "nosniff");
|
|
3592
|
+
}
|
|
3593
|
+
if (!stripBody) return response;
|
|
3594
|
+
response.body.cancel().catch(() => {});
|
|
3595
|
+
return new Response(null, {
|
|
3596
|
+
status: response.status,
|
|
3597
|
+
statusText: response.statusText,
|
|
3598
|
+
headers: response.headers
|
|
3599
|
+
});
|
|
3600
|
+
} catch {
|
|
3601
|
+
const headers = new Headers(response.headers);
|
|
3602
|
+
if (defaultsCache && !headers.has("Cache-Control")) headers.set("Cache-Control", "no-store");
|
|
3603
|
+
if (defaultsSniff && !headers.has("X-Content-Type-Options")) {
|
|
3604
|
+
headers.set("X-Content-Type-Options", "nosniff");
|
|
3605
|
+
}
|
|
3606
|
+
if (stripBody) response.body.cancel().catch(() => {});
|
|
3607
|
+
return new Response(stripBody ? null : response.body, {
|
|
3608
|
+
status: response.status,
|
|
3609
|
+
statusText: response.statusText,
|
|
3610
|
+
headers
|
|
3611
|
+
});
|
|
3612
|
+
}
|
|
3613
|
+
}
|
|
3614
|
+
return response;
|
|
1205
3615
|
}
|
|
1206
3616
|
|
|
1207
|
-
export { ERROR_HEADER, FLASH_COOKIE,
|
|
3617
|
+
export { ChunkReader, ERROR_HEADER, FLASH_COOKIE, GENERIC_SERVER_ERROR_MESSAGE, GET, REDIRECT_HEADER, SERVER_FUNCTION_INVOKE, SINGLE_FLIGHT_HEADER, UNKNOWN_HEADER, armLiveBody, broadcast, 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 };
|