@valbuild/server 0.154.1 → 0.154.3

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.
Files changed (58) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/browser/dist/valbuild-server-browser.cjs.dev.js +6 -3
  3. package/browser/dist/valbuild-server-browser.cjs.prod.js +6 -3
  4. package/browser/dist/valbuild-server-browser.esm.js +6 -3
  5. package/dist/{ValRouterCore-cfb35067.cjs.prod.js → ValOpsMemory-18337353.cjs.prod.js} +23 -2013
  6. package/dist/{ValRouterCore-361673dc.cjs.dev.js → ValOpsMemory-45ba05ad.cjs.dev.js} +23 -2013
  7. package/dist/{ValRouterCore-be314bc7.esm.js → ValOpsMemory-972616ae.esm.js} +14 -1992
  8. package/dist/ValPatchStore-2f92eced.cjs.prod.js +1128 -0
  9. package/dist/ValPatchStore-df8cdbe7.cjs.dev.js +1128 -0
  10. package/dist/ValPatchStore-e23070df.esm.js +1119 -0
  11. package/dist/ValRouterCore-5b747abb.cjs.prod.js +612 -0
  12. package/dist/ValRouterCore-73eb843d.esm.js +608 -0
  13. package/dist/ValRouterCore-86757d56.cjs.dev.js +612 -0
  14. package/dist/createPrettierFormatter-05ad7480.cjs.prod.js +692 -0
  15. package/dist/createPrettierFormatter-1edca494.esm.js +673 -0
  16. package/dist/createPrettierFormatter-851fcf99.cjs.dev.js +692 -0
  17. package/dist/createValRuntime-472df6e8.cjs.prod.js +47 -0
  18. package/dist/createValRuntime-5cebf459.cjs.dev.js +47 -0
  19. package/dist/createValRuntime-c77ee010.esm.js +45 -0
  20. package/dist/declarations/src/ValOpsMemory.d.ts +3 -73
  21. package/dist/declarations/src/ValPatchStore.d.ts +92 -0
  22. package/dist/declarations/src/ValRouter.d.ts +1 -11
  23. package/dist/declarations/src/createPrettierFormatter.d.ts +18 -3
  24. package/dist/declarations/src/createValRuntime.d.ts +12 -0
  25. package/dist/declarations/src/draftReads.d.ts +11 -3
  26. package/dist/declarations/src/index.d.ts +4 -2
  27. package/dist/declarations/src/internal/index.d.ts +28 -6
  28. package/dist/declarations/src/proposal.d.ts +13 -25
  29. package/dist/declarations/src/proposalJsonEntries.d.ts +30 -0
  30. package/dist/declarations/src/serverMode.d.ts +31 -0
  31. package/dist/{draftReads-0dcddf72.cjs.prod.js → draftReads-3f7dcda5.cjs.prod.js} +10 -2
  32. package/dist/{draftReads-df44e629.cjs.dev.js → draftReads-a300a02f.cjs.dev.js} +10 -2
  33. package/dist/{draftReads-1f29aedd.esm.js → draftReads-bca0d49c.esm.js} +10 -2
  34. package/dist/{inTabFetch-7c8a5628.esm.js → inTabFetch-0c997998.esm.js} +2 -1
  35. package/dist/{inTabFetch-56226d62.cjs.prod.js → inTabFetch-c2efa1bd.cjs.prod.js} +5 -4
  36. package/dist/{inTabFetch-5d0314a3.cjs.dev.js → inTabFetch-db6d6425.cjs.dev.js} +5 -4
  37. package/dist/jsonValuesPatch-13acc674.esm.js +276 -0
  38. package/dist/jsonValuesPatch-88bc661d.cjs.dev.js +281 -0
  39. package/dist/jsonValuesPatch-92798812.cjs.prod.js +281 -0
  40. package/dist/proposalJsonEntries-0669f027.esm.js +480 -0
  41. package/dist/proposalJsonEntries-26f397bd.cjs.dev.js +500 -0
  42. package/dist/proposalJsonEntries-9e537244.cjs.prod.js +500 -0
  43. package/dist/{publishKit-707230bc.cjs.prod.js → publishKit-38d46a51.cjs.dev.js} +20 -22
  44. package/dist/{publishKit-5a8c9a0d.cjs.dev.js → publishKit-7aca03bb.cjs.prod.js} +20 -22
  45. package/dist/{publishKit-b850045b.esm.js → publishKit-ac0af189.esm.js} +8 -9
  46. package/dist/{ValRouter-9505c550.cjs.dev.js → valRuntime-2a3cc887.cjs.prod.js} +158 -6038
  47. package/dist/{ValRouter-31f89baf.cjs.prod.js → valRuntime-70ee2dc2.cjs.dev.js} +158 -6038
  48. package/dist/{ValRouter-b7dc784d.esm.js → valRuntime-e4d26702.esm.js} +107 -5937
  49. package/dist/valbuild-server.cjs.dev.js +5146 -352
  50. package/dist/valbuild-server.cjs.prod.js +5146 -352
  51. package/dist/valbuild-server.esm.js +4902 -132
  52. package/internal/browser/dist/valbuild-server-internal-browser.cjs.dev.js +7 -4
  53. package/internal/browser/dist/valbuild-server-internal-browser.cjs.prod.js +7 -4
  54. package/internal/browser/dist/valbuild-server-internal-browser.esm.js +7 -4
  55. package/internal/dist/valbuild-server-internal.cjs.dev.js +47 -31
  56. package/internal/dist/valbuild-server-internal.cjs.prod.js +47 -31
  57. package/internal/dist/valbuild-server-internal.esm.js +38 -22
  58. package/package.json +4 -4
@@ -0,0 +1,608 @@
1
+ import { Internal } from '@valbuild/core';
2
+ import { QUICK_PREVIEW_SERVICE_WORKER_PATH, QUICK_PREVIEW_SERVICE_WORKER_SOURCE, Api } from '@valbuild/shared/internal';
3
+ import { fromError } from 'zod-validation-error';
4
+ import { z } from 'zod';
5
+
6
+ /**
7
+ * What `redirect_to` may be on Val's routes (`/enable`, `/disable`,
8
+ * `/authorize`, `/draft/enable`, ...): a path on the site that was asked,
9
+ * which is made absolute against the request's own origin, or an absolute
10
+ * URL on that same site.
11
+ *
12
+ * A path used to go through as it was, and two things downstream need an
13
+ * absolute URL: `/authorize` reads the origin off it to build the callback,
14
+ * and Next's `NextResponse.redirect` refuses anything else. Both threw, so
15
+ * `/api/val/enable?redirect_to=/` answered 500 in a Next app.
16
+ *
17
+ * `//host/path` is a URL on another host, not a path on this one, and
18
+ * anything that is neither is refused with what is accepted instead. An
19
+ * empty value is not resolved at all: the router leaves it to the route, as
20
+ * it always was (`/logout` reads it as absent).
21
+ */
22
+
23
+ const REDIRECT_TO_ACCEPTS = "redirect_to must be a path on this site starting with / (/page), or an absolute URL on this site (https://this-site.example/page).";
24
+
25
+ /**
26
+ * `siteHosts` are the other names the request knows this site by (`Host`,
27
+ * `X-Forwarded-Host`), for a server behind a proxy whose own URL is internal.
28
+ */
29
+ function resolveRedirectTo(value, requestOrigin, siteHosts = []) {
30
+ if (value.startsWith("/") && !value.startsWith("//")) {
31
+ // A path stays on this origin. `/\host/x` also starts with one slash,
32
+ // and a URL parser reads the backslash as a second one: another host,
33
+ // not a path here.
34
+ const resolved = parsed(value, requestOrigin);
35
+ return resolved !== null && resolved.origin === new URL(requestOrigin).origin ? {
36
+ ok: true,
37
+ href: resolved.href
38
+ } : {
39
+ ok: false,
40
+ message: REDIRECT_TO_ACCEPTS
41
+ };
42
+ }
43
+ // An absolute URL, on this site only. Any URL used to pass, which made
44
+ // `/logout` and `/enable` redirect wherever a link said, and `/authorize`
45
+ // send the sign-in's code to that host: it reads the callback's origin off
46
+ // this. http(s) only: `javascript:` parses as a URL too.
47
+ const url = parsed(value);
48
+ if (url === null || url.protocol !== "https:" && url.protocol !== "http:") {
49
+ return {
50
+ ok: false,
51
+ message: REDIRECT_TO_ACCEPTS
52
+ };
53
+ }
54
+ const hosts = [new URL(requestOrigin).host, ...siteHosts].filter(host => typeof host === "string" && host !== "").map(host => host.toLowerCase());
55
+ return hosts.includes(url.host.toLowerCase()) ? {
56
+ ok: true,
57
+ href: value
58
+ } : {
59
+ ok: false,
60
+ message: REDIRECT_TO_ACCEPTS
61
+ };
62
+ }
63
+
64
+ /**
65
+ * `value` as a URL, or null. Not `URL.canParse`: this runs in the browser
66
+ * too (demo mode), where it is missing before Safari 17 and Chrome 120.
67
+ */
68
+ function parsed(value, base) {
69
+ try {
70
+ return new URL(value, base);
71
+ } catch {
72
+ return null;
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Which requests Val's API answers in fs mode, where there is no session.
78
+ *
79
+ * fs mode reads and writes a working tree and asks nobody who they are: it is
80
+ * a developer's own machine. That holds only while the request really comes
81
+ * from that developer's Studio, and three kinds do not:
82
+ *
83
+ * - **A deployed site.** fs is the mode an app falls into when it has no
84
+ * `VAL_API_KEY` and `VAL_SECRET`, so a site deployed without them served
85
+ * this API, unauthenticated, to the internet.
86
+ * - **Another site's page**, in the developer's browser. A `text/plain` POST
87
+ * needs no preflight, and the router reads its body as JSON, so any page
88
+ * open in another tab could write to the working tree.
89
+ * - **A name that resolves to 127.0.0.1** (DNS rebinding), which makes such a
90
+ * page same-origin with the dev server as far as the browser can tell.
91
+ *
92
+ * The MCP endpoint has refused all three since it was written
93
+ * (`refuseUnsafeRequest` in `@valbuild/mcp`); this is the same rule for the
94
+ * API the Studio uses. Nothing here needs Node: `ValRouterCore` runs in a
95
+ * browser tab too, where no server is registered and nothing is refused.
96
+ */
97
+
98
+ const guards = new WeakMap();
99
+
100
+ /** Say how `server`'s requests are to be checked. Without it, none are. */
101
+ function setRequestGuard(server, guard) {
102
+ guards.set(server, guard);
103
+ }
104
+
105
+ /** `VAL_ALLOWED_HOSTS`: comma separated host names, without a port. */
106
+ function parseAllowedHosts(value) {
107
+ return (value ?? "").split(",").map(host => host.trim().toLowerCase()).filter(host => host !== "");
108
+ }
109
+
110
+ /** The refusal, or `null` when the request may go on to its route. */
111
+ function refuseUnsafeRequest(server, req, apiPath) {
112
+ var _req$method;
113
+ const guard = guards.get(server);
114
+ if (guard === undefined || guard.mode !== "fs") {
115
+ return null;
116
+ }
117
+ // Beacons are not refused: in fs mode one is checked and dropped, nothing
118
+ // is written or forwarded, and a deployed site with analytics on would fill
119
+ // every visitor's console with errors.
120
+ if (apiPath === "/analytics") {
121
+ return null;
122
+ }
123
+ if (guard.production) {
124
+ return refusal("Val is not set up for a deployed site here: without VAL_API_KEY and VAL_SECRET it runs in local filesystem mode, which has no sign-in and is only served by a development server. Set both (and VAL_PROJECT) on this deployment to use Val on it.");
125
+ }
126
+ const host = hostOf(req);
127
+ const forwardedHost = firstOf(req.headers.get("x-forwarded-host"));
128
+ const origin = req.headers.get("origin");
129
+ if (origin !== null) {
130
+ // `null` is the opaque origin (a sandboxed frame, a `file:` page). It
131
+ // cannot be compared with anything, so it is refused.
132
+ const originHost = origin === "null" ? null : hostOfUrl(origin);
133
+ if (originHost === null || originHost !== host && originHost !== forwardedHost) {
134
+ return refusal(`Val refused a request from another site (${origin}). In local filesystem mode the API only answers the Studio on its own address.`);
135
+ }
136
+ }
137
+ // A request with no `Origin` can still come from another site: an `<img>`,
138
+ // a script. Following a link here is not refused: sign-in comes back as
139
+ // one. A link is a GET; a form posted from another site navigates too.
140
+ const followedLink = ((_req$method = req.method) === null || _req$method === void 0 ? void 0 : _req$method.toUpperCase()) === "GET" && req.headers.get("sec-fetch-mode") === "navigate";
141
+ if (req.headers.get("sec-fetch-site") === "cross-site" && !followedLink) {
142
+ return refusal("Val refused a request from another site. In local filesystem mode the API only answers the Studio on its own address.");
143
+ }
144
+ const hostname = host === null ? null : hostnameOf(host);
145
+ if (hostname === null || !isLocalName(hostname, guard.allowedHosts)) {
146
+ return refusal(`Val refused a request addressed to ${host ?? "an unknown host"}. In local filesystem mode the API answers on localhost and on IP addresses, because any other name can be made to point at this machine by the site that owns it. If this is the address you develop on, add its host name to the VAL_ALLOWED_HOSTS environment variable (comma separated) and restart the dev server.`);
147
+ }
148
+ return null;
149
+ }
150
+ function refusal(message) {
151
+ return {
152
+ status: 403,
153
+ json: {
154
+ message
155
+ }
156
+ };
157
+ }
158
+ function firstOf(header) {
159
+ var _header$split$;
160
+ const first = header === null || header === void 0 || (_header$split$ = header.split(",")[0]) === null || _header$split$ === void 0 ? void 0 : _header$split$.trim().toLowerCase();
161
+ return first ? first : null;
162
+ }
163
+ function hostOf(req) {
164
+ const header = firstOf(req.headers.get("host"));
165
+ if (header !== null) {
166
+ return header;
167
+ }
168
+ // No Host header: the URL the framework built the request from.
169
+ return hostOfUrl(req.url);
170
+ }
171
+ function hostOfUrl(url) {
172
+ try {
173
+ return new URL(url).host.toLowerCase();
174
+ } catch {
175
+ return null;
176
+ }
177
+ }
178
+
179
+ /** A host without its port. An IPv6 literal keeps its brackets. */
180
+ function hostnameOf(host) {
181
+ if (host.startsWith("[")) {
182
+ const end = host.indexOf("]");
183
+ return end === -1 ? host : host.slice(0, end + 1);
184
+ }
185
+ const colon = host.indexOf(":");
186
+ return colon === -1 ? host : host.slice(0, colon);
187
+ }
188
+
189
+ /**
190
+ * localhost, an IP address, or a name the developer listed.
191
+ *
192
+ * An IP address is allowed because it cannot be rebound: a page that reaches
193
+ * this server by address is on another origin, and the `Origin` check above
194
+ * has already refused it. A phone on the same network uses one.
195
+ */
196
+ function isLocalName(hostname, allowedHosts) {
197
+ return hostname === "localhost" || hostname.endsWith(".localhost") || /^\d{1,3}(\.\d{1,3}){3}$/.test(hostname) || hostname.startsWith("[") && hostname.endsWith("]") || allowedHosts.includes(hostname);
198
+ }
199
+
200
+ /**
201
+ * Val's API as a web-standard handler: a `Request` in, a converted result out.
202
+ *
203
+ * The request handling itself -- matching a route, parsing it against `Api`,
204
+ * calling the server, checking the answer -- and nothing that needs Node, so it
205
+ * runs in a browser tab as well as on a server. That is what the demo does
206
+ * (`@valbuild/server/browser`): the Studio's own client sends its requests
207
+ * here, in the same tab, instead of over the network.
208
+ *
209
+ * `serveStatic` answers `/static/...`, the Studio's own scripts and styles.
210
+ * `createValApiRouter` passes the embedded bundle; the demo passes nothing,
211
+ * because its page loaded those from the app already.
212
+ */
213
+ function createValRequestHandler(route, valServerPromise, convert, serveStatic) {
214
+ // valServerPromise is created at module-eval time, but only awaited per request.
215
+ // Without this no-op catch, a config error (e.g. proxy mode without a project)
216
+ // rejects with no handler attached, which becomes an unhandledRejection and kills
217
+ // the dev server. The error is still reported per request by the try/catch below.
218
+ valServerPromise.catch(() => {
219
+ // handled below
220
+ });
221
+ return async req => {
222
+ let valServer;
223
+ try {
224
+ valServer = await valServerPromise;
225
+ } catch (err) {
226
+ const error = {
227
+ message: "Val: could not start the Val server",
228
+ details: err instanceof Error ? err.message : String(err)
229
+ };
230
+ Internal.log.error(error.message + ": " + error.details);
231
+ return convert({
232
+ status: 500,
233
+ json: error
234
+ });
235
+ }
236
+ const url = new URL(req.url);
237
+ if (!url.pathname.startsWith(route)) {
238
+ const error = {
239
+ message: "Val: routes are not configured correctly",
240
+ details: `Check you api routes. Expected pathname to start with "${route}", but it was: "${url.pathname}"`
241
+ };
242
+ Internal.log.error(error);
243
+ return convert({
244
+ status: 500,
245
+ json: error
246
+ });
247
+ }
248
+ const path = url.pathname.slice(route.length);
249
+ if (path === QUICK_PREVIEW_SERVICE_WORKER_PATH) {
250
+ /*
251
+ * The quick preview worker (`quickPreview.ts` in
252
+ * `@valbuild/shared`). `Service-Worker-Allowed: /` lets a script at
253
+ * this path control the whole origin, which it needs: it serves the
254
+ * page's `/_app/` files. It serves them only to a page opened as a
255
+ * quick preview, and the bridge stores them only for the site.
256
+ */
257
+ return convert({
258
+ status: 200,
259
+ headers: {
260
+ "Content-Type": "text/javascript; charset=utf-8",
261
+ "Service-Worker-Allowed": "/",
262
+ "Cache-Control": "no-cache"
263
+ },
264
+ body: QUICK_PREVIEW_SERVICE_WORKER_SOURCE
265
+ });
266
+ }
267
+ const groupQueryParams = arr => {
268
+ const map = {};
269
+ for (const [key, value] of arr) {
270
+ const list = map[key] || [];
271
+ list.push(value);
272
+ map[key] = list;
273
+ }
274
+ return map;
275
+ };
276
+ async function getValServerResponse(reqApiRoutePath, req) {
277
+ var _req$method, _anyApi$route, _anyValServer$route;
278
+ const anyApi =
279
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
280
+ Api;
281
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
282
+ const anyValServer = valServer;
283
+ const refused = refuseUnsafeRequest(valServer, req, reqApiRoutePath);
284
+ if (refused !== null) {
285
+ return refused;
286
+ }
287
+ const method = (_req$method = req.method) === null || _req$method === void 0 ? void 0 : _req$method.toUpperCase();
288
+ let route = null;
289
+ let path = undefined;
290
+ // An exact match wins over every prefix match, wherever it sits in
291
+ // `Api`: checked per key, in order, `/validate` took `/validate/fix`
292
+ // because it was declared first.
293
+ const exactRouteDef = Object.keys(Api).find(routeDef => routeDef === reqApiRoutePath);
294
+ for (const routeDef of exactRouteDef ? [exactRouteDef] : Object.keys(Api)) {
295
+ if (routeDef === reqApiRoutePath) {
296
+ route = routeDef;
297
+ break;
298
+ }
299
+ if (reqApiRoutePath.startsWith(routeDef)) {
300
+ var _anyApi$routeDef;
301
+ const reqDefinition = anyApi === null || anyApi === void 0 || (_anyApi$routeDef = anyApi[routeDef]) === null || _anyApi$routeDef === void 0 || (_anyApi$routeDef = _anyApi$routeDef[method]) === null || _anyApi$routeDef === void 0 ? void 0 : _anyApi$routeDef.req;
302
+ if (reqDefinition) {
303
+ route = routeDef;
304
+ if (reqDefinition.path) {
305
+ const subPath = reqApiRoutePath.slice(routeDef.length);
306
+ const pathRes = reqDefinition.path.safeParse(subPath);
307
+ if (!pathRes.success) {
308
+ return zodErrorResult(pathRes.error, `invalid path: '${subPath}' endpoint: '${routeDef}'`);
309
+ } else {
310
+ path = pathRes.data;
311
+ }
312
+ }
313
+ break;
314
+ }
315
+ }
316
+ }
317
+ if (!route) {
318
+ return {
319
+ status: 404,
320
+ json: {
321
+ message: "Route not found. Valid routes are: " + Object.keys(Api),
322
+ details: {
323
+ route,
324
+ method
325
+ }
326
+ }
327
+ };
328
+ }
329
+ const apiEndpoint = anyApi === null || anyApi === void 0 || (_anyApi$route = anyApi[route]) === null || _anyApi$route === void 0 ? void 0 : _anyApi$route[method];
330
+ const reqDefinition = apiEndpoint === null || apiEndpoint === void 0 ? void 0 : apiEndpoint.req;
331
+ if (!reqDefinition) {
332
+ return {
333
+ status: 404,
334
+ json: {
335
+ message: `Requested method ${method} on route ${route} is not valid. Valid methods are: ${Object.keys(anyApi[route]).join(", ")}`,
336
+ details: {
337
+ route,
338
+ method
339
+ }
340
+ }
341
+ };
342
+ }
343
+ const endpointImpl = anyValServer === null || anyValServer === void 0 || (_anyValServer$route = anyValServer[route]) === null || _anyValServer$route === void 0 ? void 0 : _anyValServer$route[method];
344
+ if (!endpointImpl) {
345
+ return {
346
+ status: 500,
347
+ json: {
348
+ message: "Missing server implementation of route with method. This might be caused by a mismatch between Val package versions.",
349
+ details: {
350
+ valid: {
351
+ route: {
352
+ server: Object.keys(anyValServer || {}),
353
+ api: Object.keys(anyApi || {})
354
+ },
355
+ method: {
356
+ server: Object.keys((anyValServer === null || anyValServer === void 0 ? void 0 : anyValServer[route]) || {}),
357
+ api: Object.keys((anyApi === null || anyApi === void 0 ? void 0 : anyApi[route]) || {})
358
+ }
359
+ },
360
+ route,
361
+ method
362
+ }
363
+ }
364
+ };
365
+ }
366
+ let bodyRes;
367
+ try {
368
+ bodyRes = reqDefinition.body ? reqDefinition.body.safeParse(await readJsonBody(req)) : {
369
+ success: true,
370
+ data: {}
371
+ };
372
+ if (!bodyRes.success) {
373
+ return zodErrorResult(bodyRes.error, "invalid body data");
374
+ }
375
+ } catch (e) {
376
+ return {
377
+ status: 400,
378
+ json: {
379
+ message: "Could not parse request body",
380
+ details: {
381
+ error: JSON.stringify(e)
382
+ }
383
+ }
384
+ };
385
+ }
386
+ const cookiesRes = reqDefinition.cookies ? getCookies(req, reqDefinition.cookies) : {
387
+ success: true,
388
+ data: {}
389
+ };
390
+ if (!cookiesRes.success) {
391
+ return zodErrorResult(cookiesRes.error, "invalid cookies");
392
+ }
393
+ const headersRes = reqDefinition.headers ? getHeaders(req, reqDefinition.headers) : {
394
+ success: true,
395
+ data: {}
396
+ };
397
+ if (!headersRes.success) {
398
+ return zodErrorResult(headersRes.error, "invalid headers");
399
+ }
400
+ const actualQueryParams = groupQueryParams(Array.from(url.searchParams.entries()));
401
+ let query = {};
402
+ if (reqDefinition.query) {
403
+ const queryRules = reqDefinition.query;
404
+ const queryRes = z.object(queryRules).safeParse(actualQueryParams);
405
+ if (!queryRes.success) {
406
+ return zodErrorResult(queryRes.error, `invalid query params: (${JSON.stringify(actualQueryParams)})`);
407
+ }
408
+ query = queryRes.data;
409
+ }
410
+ // `redirect_to` is a URL or a path on this site: see `resolveRedirectTo`.
411
+ if ("redirect_to" in query && typeof query.redirect_to === "string" && query.redirect_to !== "") {
412
+ var _req$headers$get;
413
+ // Behind a proxy `url` can be an internal address: the site's own
414
+ // name is then in `Host` or `X-Forwarded-Host`.
415
+ const resolved = resolveRedirectTo(query.redirect_to, url.origin, [req.headers.get("host"), (_req$headers$get = req.headers.get("x-forwarded-host")) === null || _req$headers$get === void 0 || (_req$headers$get = _req$headers$get.split(",")[0]) === null || _req$headers$get === void 0 ? void 0 : _req$headers$get.trim()]);
416
+ if (!resolved.ok) {
417
+ return {
418
+ status: 400,
419
+ json: {
420
+ message: resolved.message
421
+ }
422
+ };
423
+ }
424
+ query = {
425
+ ...query,
426
+ redirect_to: resolved.href
427
+ };
428
+ }
429
+
430
+ /*
431
+ * A throw from an endpoint is Val's to report, not the framework's.
432
+ *
433
+ * Nothing here used to catch, so an endpoint that threw left the router
434
+ * entirely and became whatever the host does with an unhandled error --
435
+ * and on TanStack Start that is h3, which replaces the message with the
436
+ * literal string "HTTPError" and drops the stack. Its `debug` and
437
+ * `silent` options are not reachable from out here: `requestHandler`
438
+ * calls `toResponse(value, event)` with no config, and the default is
439
+ * `{}`. So the body a caller got was
440
+ * `{"status":500,"unhandled":true,"message":"HTTPError"}` -- the same
441
+ * five words for a missing project, a bad cookie secret and a module
442
+ * that failed to link -- with the real cause only on the server's
443
+ * console.
444
+ *
445
+ * That is survivable where the console is readable. It is not in a
446
+ * Cloudflare Dynamic Worker, whose `console` reaches no tail stream: a
447
+ * link error in a lazily imported chunk (`does not provide an export
448
+ * named 'getSerovalPlugins'`) showed up as an unreadable 500 on
449
+ * `/authorize` and nowhere else at all.
450
+ *
451
+ * So every endpoint's throw becomes Val's own 500 envelope, which the
452
+ * Studio already renders and `curl` already prints. The route and method
453
+ * are named because a message rarely says which endpoint it came from.
454
+ *
455
+ * The MESSAGE travels and the STACK does not. The message is the whole
456
+ * diagnostic value -- the line above names the package, the chunk and
457
+ * the export -- while a stack is a walk through somebody's bundle, and
458
+ * `/authorize` and `/enable` are reachable without a session. So the
459
+ * stack goes to the console, where a host that can read one will find
460
+ * it, and the body carries what a caller can act on.
461
+ */
462
+ let res;
463
+ try {
464
+ res = await endpointImpl({
465
+ body: bodyRes.data,
466
+ cookies: cookiesRes.data,
467
+ headers: headersRes.data,
468
+ rawQuery: reqDefinition.rawQuery ? url.search : undefined,
469
+ query,
470
+ path
471
+ });
472
+ } catch (err) {
473
+ const error = err instanceof Error ? err : new Error(String(err));
474
+ Internal.log.error(`${method} ${route} threw: ${error.message}`, error.stack);
475
+ return {
476
+ status: 500,
477
+ json: {
478
+ message: `Val: ${method} ${route} failed: ${error.message}`,
479
+ details: {
480
+ route,
481
+ method,
482
+ error: error.message
483
+ }
484
+ }
485
+ };
486
+ }
487
+ const resDef = apiEndpoint.res;
488
+ if (res.status === 500) {
489
+ var _res$json;
490
+ /*
491
+ * A failure the route declares goes out as declared, as a success
492
+ * does below. DELETE /patches says which change was not discarded and
493
+ * which publish holds it, and collapsed to its message the Studio
494
+ * could only say "Failed to delete patches" -- not why, nor offer to
495
+ * cancel that publish. Anything undeclared is still reduced to its
496
+ * message.
497
+ */
498
+ if (resDef !== null && resDef !== void 0 && resDef.safeParse(res).success) return res;
499
+ return {
500
+ status: 500,
501
+ json: {
502
+ message: ((_res$json = res.json) === null || _res$json === void 0 ? void 0 : _res$json.message) || "Internal Server Error"
503
+ }
504
+ };
505
+ }
506
+ if (resDef) {
507
+ const responseResult = resDef.safeParse(res);
508
+ if (!responseResult.success) {
509
+ return {
510
+ status: 500,
511
+ json: {
512
+ message: "Could not validate response. This is likely a bug in Val server.",
513
+ details: {
514
+ response: res,
515
+ errors: formatZodErrorString(responseResult.error)
516
+ }
517
+ }
518
+ };
519
+ }
520
+ }
521
+ return res;
522
+ }
523
+ if (path.startsWith("/static")) {
524
+ if (!serveStatic) {
525
+ return convert({
526
+ status: 404,
527
+ json: {
528
+ message: "Val: this server does not serve the Studio's own files"
529
+ }
530
+ });
531
+ }
532
+ return convert(await serveStatic(path.slice("/static".length), url.href));
533
+ } else {
534
+ return convert(await getValServerResponse(path, req));
535
+ }
536
+ };
537
+ }
538
+ function formatZodErrorString(error) {
539
+ const errors = fromError(error).toString();
540
+ return errors.length > 640 ? `${errors.slice(0, 640)}...` : errors;
541
+ }
542
+
543
+ /**
544
+ * The request's JSON body, or `undefined` when it has none.
545
+ *
546
+ * `req.json()` THROWS on an empty body, and the router used to call it
547
+ * unconditionally for any route that declares a body — so the moment
548
+ * `DELETE /patches` gained an optional body, every caller that sent none got
549
+ * `400 Could not parse request body`. Declaring the schema `.optional()` did
550
+ * not help: the throw happens before zod is ever consulted. Six e2e tests went
551
+ * red on a helper doing exactly what the route still permits.
552
+ *
553
+ * Told apart by the request rather than by catching, so a body that IS sent and
554
+ * is malformed still fails: absent means no content type and nothing to read,
555
+ * and anything else is parsed and allowed to throw. A route whose schema
556
+ * requires a body is unaffected — it gets `undefined` and zod refuses it, with
557
+ * the same 400 as before, now naming the field.
558
+ */
559
+ async function readJsonBody(req) {
560
+ if (req.headers.get("content-length") === "0") {
561
+ return undefined;
562
+ }
563
+ const text = await req.text();
564
+ if (text.length === 0) {
565
+ return undefined;
566
+ }
567
+ return JSON.parse(text);
568
+ }
569
+ function zodErrorResult(error, message) {
570
+ return {
571
+ status: 400,
572
+ json: {
573
+ message: "Bad Request: " + message,
574
+ details: {
575
+ errors: formatZodErrorString(error)
576
+ }
577
+ }
578
+ };
579
+ }
580
+
581
+ // TODO: is this naive implementation is too naive?
582
+ /** The declared headers, by name; `Headers.get` is case-insensitive. */
583
+ function getHeaders(req, headersDef) {
584
+ const input = {};
585
+ for (const name of Object.keys(headersDef)) {
586
+ var _req$headers;
587
+ const value = (_req$headers = req.headers) === null || _req$headers === void 0 ? void 0 : _req$headers.get(name);
588
+ if (value !== null && value !== undefined) {
589
+ input[name] = value;
590
+ }
591
+ }
592
+ return z.object(headersDef).safeParse(input);
593
+ }
594
+ function getCookies(req, cookiesDef) {
595
+ var _req$headers2;
596
+ const input = {};
597
+ const cookieParts = (_req$headers2 = req.headers) === null || _req$headers2 === void 0 || (_req$headers2 = _req$headers2.get("Cookie")) === null || _req$headers2 === void 0 ? void 0 : _req$headers2.split("; ");
598
+ for (const name of Object.keys(cookiesDef)) {
599
+ const cookie = cookieParts === null || cookieParts === void 0 ? void 0 : cookieParts.find(cookie => cookie.startsWith(`${name}=`));
600
+ const value = cookie ? decodeURIComponent(cookie === null || cookie === void 0 ? void 0 : cookie.split("=")[1]) : undefined;
601
+ if (value) {
602
+ input[name.trim()] = value;
603
+ }
604
+ }
605
+ return z.object(cookiesDef).safeParse(input);
606
+ }
607
+
608
+ export { createValRequestHandler as c, parseAllowedHosts as p, setRequestGuard as s };