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