-
Notifications
You must be signed in to change notification settings - Fork 418
Expand file tree
/
Copy pathserver-functions-handler.ts
More file actions
364 lines (342 loc) · 9.92 KB
/
server-functions-handler.ts
File metadata and controls
364 lines (342 loc) · 9.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
import { getServerFnById } from "solidstart:server-fn-manifest";
import { parseSetCookie } from "cookie-es";
import { type H3Event, parseCookies } from "h3";
import {
crossSerializeStream,
fromJSON,
getCrossReferenceHeader,
} from "seroval";
import {
CustomEventPlugin,
DOMExceptionPlugin,
EventPlugin,
FormDataPlugin,
HeadersPlugin,
ReadableStreamPlugin,
RequestPlugin,
ResponsePlugin,
URLPlugin,
URLSearchParamsPlugin,
} from "seroval-plugins/web";
import { sharedConfig } from "solid-js";
import { renderToString } from "solid-js/web";
import { provideRequestEvent } from "solid-js/web/storage";
import { getFetchEvent, mergeResponseHeaders } from "./fetchEvent.ts";
import { createPageEvent } from "./handler.ts";
import type { FetchEvent, PageEvent } from "./types.ts";
import { getExpectedRedirectStatus } from "./util.ts";
function createChunk(data: string) {
const encodeData = new TextEncoder().encode(data);
const bytes = encodeData.length;
const baseHex = bytes.toString(16);
const totalHex = "00000000".substring(0, 8 - baseHex.length) + baseHex; // 32-bit
const head = new TextEncoder().encode(`;0x${totalHex};`);
const chunk = new Uint8Array(12 + bytes);
chunk.set(head);
chunk.set(encodeData, 12);
return chunk;
}
function serializeToStream(id: string, value: any) {
return new ReadableStream({
start(controller) {
crossSerializeStream(value, {
scopeId: id,
plugins: [
CustomEventPlugin,
DOMExceptionPlugin,
EventPlugin,
FormDataPlugin,
HeadersPlugin,
ReadableStreamPlugin,
RequestPlugin,
ResponsePlugin,
URLSearchParamsPlugin,
URLPlugin,
],
onSerialize(data: string, initial: boolean) {
controller.enqueue(
createChunk(
initial ? `(${getCrossReferenceHeader(id)},${data})` : data,
),
);
},
onDone() {
controller.close();
},
onError(error: any) {
controller.error(error);
},
});
},
});
}
export async function handleServerFunction(h3Event: H3Event) {
const event = getFetchEvent(h3Event);
const request = event.request;
const serverReference = request.headers.get("X-Server-Id");
const instance = request.headers.get("X-Server-Instance");
const singleFlight = request.headers.has("X-Single-Flight");
const url = new URL(request.url);
let functionId: string | undefined | null;
if (serverReference) {
// invariant(typeof serverReference === "string", "Invalid server function");
[functionId] = serverReference.split("#");
} else {
functionId = url.searchParams.get("id");
if (!functionId) {
return process.env.NODE_ENV === "development"
? new Response("Server function not found", { status: 404 })
: new Response(null, { status: 404 });
}
}
const serverFunction = await getServerFnById(functionId!);
let parsed: any[] = [];
// grab bound arguments from url when no JS
if (!instance || h3Event.method === "GET") {
const args = url.searchParams.get("args");
if (args) {
const json = JSON.parse(args);
(json.t
? (fromJSON(json, {
plugins: [
CustomEventPlugin,
DOMExceptionPlugin,
EventPlugin,
FormDataPlugin,
HeadersPlugin,
ReadableStreamPlugin,
RequestPlugin,
ResponsePlugin,
URLSearchParamsPlugin,
URLPlugin,
],
}) as any)
: json
).forEach((arg: any) => {
parsed.push(arg);
});
}
}
if (h3Event.method === "POST") {
const contentType = request.headers.get("content-type");
if (
contentType?.startsWith("multipart/form-data") ||
contentType?.startsWith("application/x-www-form-urlencoded")
) {
parsed.push(await event.request.formData());
} else if (contentType?.startsWith("application/json")) {
parsed = fromJSON(await event.request.json(), {
plugins: [
CustomEventPlugin,
DOMExceptionPlugin,
EventPlugin,
FormDataPlugin,
HeadersPlugin,
ReadableStreamPlugin,
RequestPlugin,
ResponsePlugin,
URLSearchParamsPlugin,
URLPlugin,
],
});
}
}
try {
let result = await provideRequestEvent(event, async () => {
/* @ts-expect-error */
sharedConfig.context = { event };
event.locals.serverFunctionMeta = {
id: functionId
};
return serverFunction(...parsed);
});
if (singleFlight && instance) {
result = await handleSingleFlight(event, result);
}
// handle responses
if (result instanceof Response) {
if (result.headers && result.headers.has("X-Content-Raw")) return result;
if (instance) {
// forward headers
if (result.headers) mergeResponseHeaders(h3Event, result.headers);
// forward non-redirect statuses
if (result.status && (result.status < 300 || result.status >= 400))
h3Event.res.status = result.status;
if ((result as any).customBody) {
result = await (result as any).customBody();
} else if (result.body == undefined) result = null;
}
}
// handle no JS success case
if (!instance) return handleNoJS(result, request, parsed);
h3Event.res.headers.set("content-type", "text/javascript");
return serializeToStream(instance, result);
} catch (x) {
if (x instanceof Response) {
if (singleFlight && instance) {
x = await handleSingleFlight(event, x);
}
// forward headers
if ((x as any).headers) mergeResponseHeaders(h3Event, (x as any).headers);
// forward non-redirect statuses
if (
(x as any).status &&
(!instance || (x as any).status < 300 || (x as any).status >= 400)
)
h3Event.res.status = (x as any).status;
if ((x as any).customBody) {
x = (x as any).customBody();
} else if ((x as any).body === undefined) x = null;
h3Event.res.headers.set("X-Error", "true");
} else if (instance) {
const error =
x instanceof Error ? x.message : typeof x === "string" ? x : "true";
h3Event.res.headers.set("X-Error", error.replace(/[\r\n]+/g, ""));
} else {
x = handleNoJS(x, request, parsed, true);
}
if (instance) {
h3Event.res.headers.set("content-type", "text/javascript");
return serializeToStream(instance, x);
}
return x;
}
}
function handleNoJS(
result: any,
request: Request,
parsed: any[],
thrown?: boolean,
) {
const url = new URL(request.url);
const isError = result instanceof Error;
let statusCode = 302;
let headers: Headers;
if (result instanceof Response) {
headers = new Headers(result.headers);
if (result.headers.has("Location")) {
headers.set(
`Location`,
new URL(
result.headers.get("Location")!,
url.origin + import.meta.env.SERVER_BASE_URL,
).toString(),
);
statusCode = getExpectedRedirectStatus(result);
}
} else
headers = new Headers({
Location: new URL(request.headers.get("referer")!).toString(),
});
if (result) {
headers.append(
"Set-Cookie",
`flash=${encodeURIComponent(
JSON.stringify({
url: url.pathname + url.search,
result: isError ? result.message : result,
thrown: thrown,
error: isError,
input: [
...parsed.slice(0, -1),
[...parsed[parsed.length - 1].entries()],
],
}),
)}; Secure; HttpOnly;`,
);
}
return new Response(null, {
status: statusCode,
headers,
});
}
let App: any;
function createSingleFlightHeaders(sourceEvent: FetchEvent) {
// cookie handling logic is pretty simplistic so this might be imperfect
// unclear if h3 internals are available on all platforms but we need a way to
// update request headers on the underlying H3 event.
const headers = sourceEvent.request.headers;
const cookies = parseCookies(sourceEvent.nativeEvent);
const SetCookies = sourceEvent.response.headers.getSetCookie();
headers.delete("cookie");
// let useH3Internals = false;
// if (sourceEvent.nativeEvent.node?.req) {
// useH3Internals = true;
// sourceEvent.nativeEvent.node.req.headers.cookie = "";
// }
SetCookies.forEach((cookie) => {
if (!cookie) return;
const { maxAge, expires, name, value } = parseSetCookie(cookie);
if (maxAge != null && maxAge <= 0) {
delete cookies[name];
return;
}
if (expires != null && expires.getTime() <= Date.now()) {
delete cookies[name];
return;
}
cookies[name] = value;
});
Object.entries(cookies).forEach(([key, value]) => {
headers.append("cookie", `${key}=${value}`);
// useH3Internals &&
// (sourceEvent.nativeEvent.node.req.headers.cookie += `${key}=${value};`);
});
return headers;
}
async function handleSingleFlight(
sourceEvent: FetchEvent,
result: any,
): Promise<Response> {
let revalidate: string[];
let url = new URL(sourceEvent.request.headers.get("referer")!).toString();
if (result instanceof Response) {
if (result.headers.has("X-Revalidate"))
revalidate = result.headers.get("X-Revalidate")!.split(",");
if (result.headers.has("Location"))
url = new URL(
result.headers.get("Location")!,
new URL(sourceEvent.request.url).origin +
import.meta.env.SERVER_BASE_URL,
).toString();
}
const event = { ...sourceEvent } as PageEvent;
event.request = new Request(url, {
headers: createSingleFlightHeaders(sourceEvent),
});
return await provideRequestEvent(event, async () => {
await createPageEvent(event);
App || (App = (await import("solid-start:app")).default);
/* @ts-expect-error */
event.router.dataOnly = revalidate || true;
/* @ts-expect-error */
event.router.previousUrl = sourceEvent.request.headers.get("referer");
try {
renderToString(() => {
/* @ts-expect-error */
sharedConfig.context.event = event;
App();
});
} catch (e) {
console.log(e);
}
/* @ts-expect-error */
const body = event.router.data;
if (!body) return result;
let containsKey = false;
for (const key in body) {
if (body[key] === undefined) delete body[key];
else containsKey = true;
}
if (!containsKey) return result;
if (!(result instanceof Response)) {
body["_$value"] = result;
result = new Response(null, { status: 200 });
} else if ((result as any).customBody) {
body["_$value"] = (result as any).customBody();
}
result.customBody = () => body;
result.headers.set("X-Single-Flight", "true");
return result;
});
}