diff --git "a/index.js" "b/index.js" deleted file mode 100644--- "a/index.js" +++ /dev/null @@ -1,3839 +0,0 @@ -import { D as DEV, a as assets, b as base, c as app_dir, r as relative, o as override, d as reset } from "./chunks/environment.js"; -import { json, text, error } from "@sveltejs/kit"; -import { HttpError, SvelteKitError, Redirect, ActionFailure } from "@sveltejs/kit/internal"; -import { with_request_store, merge_tracing, try_get_request_store } from "@sveltejs/kit/internal/server"; -import * as devalue from "devalue"; -import { m as make_trackable, d as disable_search, a as decode_params, S as SCHEME, r as readable, w as writable, v as validate_layout_server_exports, b as validate_layout_exports, c as validate_page_server_exports, e as validate_page_exports, n as normalize_path, f as resolve, g as decode_pathname, h as validate_server_exports } from "./chunks/exports.js"; -import { b as base64_encode, t as text_decoder, a as text_encoder, g as get_relative_path } from "./chunks/utils.js"; -import { p as public_env, r as read_implementation, o as options, s as set_private_env, a as set_public_env, g as get_hooks, b as set_read_implementation } from "./chunks/internal.js"; -import { c as create_remote_cache_key, p as parse_remote_arg, s as stringify, T as TRAILING_SLASH_PARAM, I as INVALIDATED_PARAM } from "./chunks/shared.js"; -import { parse, serialize } from "cookie"; -import * as set_cookie_parser from "set-cookie-parser"; -function with_resolvers() { - let resolve2; - let reject; - const promise = new Promise((res, rej) => { - resolve2 = res; - reject = rej; - }); - return { promise, resolve: resolve2, reject }; -} -const NULL_BODY_STATUS = [101, 103, 204, 205, 304]; -const IN_WEBCONTAINER = !!globalThis.process?.versions?.webcontainer; -const SVELTE_KIT_ASSETS = "/_svelte_kit_assets"; -const ENDPOINT_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]; -const PAGE_METHODS = ["GET", "POST", "HEAD"]; -function negotiate(accept, types) { - const parts = []; - accept.split(",").forEach((str, i) => { - const match = /([^/ \t]+)\/([^; \t]+)[ \t]*(?:;[ \t]*q=([0-9.]+))?/.exec(str); - if (match) { - const [, type, subtype, q = "1"] = match; - parts.push({ type, subtype, q: +q, i }); - } - }); - parts.sort((a, b) => { - if (a.q !== b.q) { - return b.q - a.q; - } - if (a.subtype === "*" !== (b.subtype === "*")) { - return a.subtype === "*" ? 1 : -1; - } - if (a.type === "*" !== (b.type === "*")) { - return a.type === "*" ? 1 : -1; - } - return a.i - b.i; - }); - let accepted; - let min_priority = Infinity; - for (const mimetype of types) { - const [type, subtype] = mimetype.split("/"); - const priority = parts.findIndex( - (part) => (part.type === type || part.type === "*") && (part.subtype === subtype || part.subtype === "*") - ); - if (priority !== -1 && priority < min_priority) { - accepted = mimetype; - min_priority = priority; - } - } - return accepted; -} -function is_content_type(request, ...types) { - const type = request.headers.get("content-type")?.split(";", 1)[0].trim() ?? ""; - return types.includes(type.toLowerCase()); -} -function is_form_content_type(request) { - return is_content_type( - request, - "application/x-www-form-urlencoded", - "multipart/form-data", - "text/plain" - ); -} -function coalesce_to_error(err) { - return err instanceof Error || err && /** @type {any} */ - err.name && /** @type {any} */ - err.message ? ( - /** @type {Error} */ - err - ) : new Error(JSON.stringify(err)); -} -function normalize_error(error2) { - return ( - /** @type {import('../exports/internal/index.js').Redirect | HttpError | SvelteKitError | Error} */ - error2 - ); -} -function get_status(error2) { - return error2 instanceof HttpError || error2 instanceof SvelteKitError ? error2.status : 500; -} -function get_message(error2) { - return error2 instanceof SvelteKitError ? error2.text : "Internal Error"; -} -const escape_html_attr_dict = { - "&": "&", - '"': """ - // Svelte also escapes < because the escape function could be called inside a `noscript` there - // https://github.com/sveltejs/svelte/security/advisories/GHSA-8266-84wp-wv5c - // However, that doesn't apply in SvelteKit -}; -const escape_html_dict = { - "&": "&", - "<": "<" -}; -const surrogates = ( - // high surrogate without paired low surrogate - "[\\ud800-\\udbff](?![\\udc00-\\udfff])|[\\ud800-\\udbff][\\udc00-\\udfff]|[\\udc00-\\udfff]" -); -const escape_html_attr_regex = new RegExp( - `[${Object.keys(escape_html_attr_dict).join("")}]|` + surrogates, - "g" -); -const escape_html_regex = new RegExp( - `[${Object.keys(escape_html_dict).join("")}]|` + surrogates, - "g" -); -function escape_html(str, is_attr) { - const dict = is_attr ? escape_html_attr_dict : escape_html_dict; - const escaped_str = str.replace(is_attr ? escape_html_attr_regex : escape_html_regex, (match) => { - if (match.length === 2) { - return match; - } - return dict[match] ?? `&#${match.charCodeAt(0)};`; - }); - return escaped_str; -} -function method_not_allowed(mod, method) { - return text(`${method} method not allowed`, { - status: 405, - headers: { - // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405 - // "The server must generate an Allow header field in a 405 status code response" - allow: allowed_methods(mod).join(", ") - } - }); -} -function allowed_methods(mod) { - const allowed = ENDPOINT_METHODS.filter((method) => method in mod); - if ("GET" in mod && !("HEAD" in mod)) { - allowed.push("HEAD"); - } - return allowed; -} -function get_global_name(options2) { - return `__sveltekit_${options2.version_hash}`; -} -function static_error_page(options2, status, message) { - let page = options2.templates.error({ status, message: escape_html(message) }); - return text(page, { - headers: { "content-type": "text/html; charset=utf-8" }, - status - }); -} -async function handle_fatal_error(event, state, options2, error2) { - error2 = error2 instanceof HttpError ? error2 : coalesce_to_error(error2); - const status = get_status(error2); - const body2 = await handle_error_and_jsonify(event, state, options2, error2); - const type = negotiate(event.request.headers.get("accept") || "text/html", [ - "application/json", - "text/html" - ]); - if (event.isDataRequest || type === "application/json") { - return json(body2, { - status - }); - } - return static_error_page(options2, status, body2.message); -} -async function handle_error_and_jsonify(event, state, options2, error2) { - if (error2 instanceof HttpError) { - return { message: "Unknown Error", ...error2.body }; - } - const status = get_status(error2); - const message = get_message(error2); - return await with_request_store( - { event, state }, - () => options2.hooks.handleError({ error: error2, event, status, message }) - ) ?? { message }; -} -function redirect_response(status, location) { - const response = new Response(void 0, { - status, - headers: { location } - }); - return response; -} -function clarify_devalue_error(event, error2) { - if (error2.path) { - return `Data returned from \`load\` while rendering ${event.route.id} is not serializable: ${error2.message} (${error2.path}). If you need to serialize/deserialize custom types, use transport hooks: https://svelte.dev/docs/kit/hooks#Universal-hooks-transport.`; - } - if (error2.path === "") { - return `Data returned from \`load\` while rendering ${event.route.id} is not a plain object`; - } - return error2.message; -} -function serialize_uses(node) { - const uses = {}; - if (node.uses && node.uses.dependencies.size > 0) { - uses.dependencies = Array.from(node.uses.dependencies); - } - if (node.uses && node.uses.search_params.size > 0) { - uses.search_params = Array.from(node.uses.search_params); - } - if (node.uses && node.uses.params.size > 0) { - uses.params = Array.from(node.uses.params); - } - if (node.uses?.parent) uses.parent = 1; - if (node.uses?.route) uses.route = 1; - if (node.uses?.url) uses.url = 1; - return uses; -} -function has_prerendered_path(manifest, pathname) { - return manifest._.prerendered_routes.has(pathname) || pathname.at(-1) === "/" && manifest._.prerendered_routes.has(pathname.slice(0, -1)); -} -function format_server_error(status, error2, event) { - const formatted_text = ` -\x1B[1;31m[${status}] ${event.request.method} ${event.url.pathname}\x1B[0m`; - if (status === 404) { - return formatted_text; - } - return `${formatted_text} -${error2.stack}`; -} -function get_node_type(node_id) { - const parts = node_id?.split("/"); - const filename = parts?.at(-1); - if (!filename) return "unknown"; - const dot_parts = filename.split("."); - return dot_parts.slice(0, -1).join("."); -} -async function render_endpoint(event, event_state, mod, state) { - const method = ( - /** @type {import('types').HttpMethod} */ - event.request.method - ); - let handler = mod[method] || mod.fallback; - if (method === "HEAD" && !mod.HEAD && mod.GET) { - handler = mod.GET; - } - if (!handler) { - return method_not_allowed(mod, method); - } - const prerender = mod.prerender ?? state.prerender_default; - if (prerender && (mod.POST || mod.PATCH || mod.PUT || mod.DELETE)) { - throw new Error("Cannot prerender endpoints that have mutative methods"); - } - if (state.prerendering && !state.prerendering.inside_reroute && !prerender) { - if (state.depth > 0) { - throw new Error(`${event.route.id} is not prerenderable`); - } else { - return new Response(void 0, { status: 204 }); - } - } - event_state.is_endpoint_request = true; - try { - const response = await with_request_store( - { event, state: event_state }, - () => handler( - /** @type {import('@sveltejs/kit').RequestEvent>} */ - event - ) - ); - if (!(response instanceof Response)) { - throw new Error( - `Invalid response from route ${event.url.pathname}: handler should return a Response object` - ); - } - if (state.prerendering && (!state.prerendering.inside_reroute || prerender)) { - const cloned = new Response(response.clone().body, { - status: response.status, - statusText: response.statusText, - headers: new Headers(response.headers) - }); - cloned.headers.set("x-sveltekit-prerender", String(prerender)); - if (state.prerendering.inside_reroute && prerender) { - cloned.headers.set( - "x-sveltekit-routeid", - encodeURI( - /** @type {string} */ - event.route.id - ) - ); - state.prerendering.dependencies.set(event.url.pathname, { response: cloned, body: null }); - } else { - return cloned; - } - } - return response; - } catch (e) { - if (e instanceof Redirect) { - return new Response(void 0, { - status: e.status, - headers: { location: e.location } - }); - } - throw e; - } -} -function is_endpoint_request(event) { - const { method, headers: headers2 } = event.request; - if (ENDPOINT_METHODS.includes(method) && !PAGE_METHODS.includes(method)) { - return true; - } - if (method === "POST" && headers2.get("x-sveltekit-action") === "true") return false; - const accept = event.request.headers.get("accept") ?? "*/*"; - return negotiate(accept, ["*", "text/html"]) !== "text/html"; -} -function compact(arr) { - return arr.filter( - /** @returns {val is NonNullable} */ - (val) => val != null - ); -} -const DATA_SUFFIX = "/__data.json"; -const HTML_DATA_SUFFIX = ".html__data.json"; -function has_data_suffix(pathname) { - return pathname.endsWith(DATA_SUFFIX) || pathname.endsWith(HTML_DATA_SUFFIX); -} -function add_data_suffix(pathname) { - if (pathname.endsWith(".html")) return pathname.replace(/\.html$/, HTML_DATA_SUFFIX); - return pathname.replace(/\/$/, "") + DATA_SUFFIX; -} -function strip_data_suffix(pathname) { - if (pathname.endsWith(HTML_DATA_SUFFIX)) { - return pathname.slice(0, -HTML_DATA_SUFFIX.length) + ".html"; - } - return pathname.slice(0, -DATA_SUFFIX.length); -} -const ROUTE_SUFFIX = "/__route.js"; -function has_resolution_suffix(pathname) { - return pathname.endsWith(ROUTE_SUFFIX); -} -function add_resolution_suffix(pathname) { - return pathname.replace(/\/$/, "") + ROUTE_SUFFIX; -} -function strip_resolution_suffix(pathname) { - return pathname.slice(0, -ROUTE_SUFFIX.length); -} -const noop_span = { - spanContext() { - return noop_span_context; - }, - setAttribute() { - return this; - }, - setAttributes() { - return this; - }, - addEvent() { - return this; - }, - setStatus() { - return this; - }, - updateName() { - return this; - }, - end() { - return this; - }, - isRecording() { - return false; - }, - recordException() { - return this; - }, - addLink() { - return this; - }, - addLinks() { - return this; - } -}; -const noop_span_context = { - traceId: "", - spanId: "", - traceFlags: 0 -}; -async function record_span({ name, attributes, fn }) { - { - return fn(noop_span); - } -} -function is_action_json_request(event) { - const accept = negotiate(event.request.headers.get("accept") ?? "*/*", [ - "application/json", - "text/html" - ]); - return accept === "application/json" && event.request.method === "POST"; -} -async function handle_action_json_request(event, event_state, options2, server) { - const actions = server?.actions; - if (!actions) { - const no_actions_error = new SvelteKitError( - 405, - "Method Not Allowed", - `POST method not allowed. No form actions exist for ${"this page"}` - ); - return action_json( - { - type: "error", - error: await handle_error_and_jsonify(event, event_state, options2, no_actions_error) - }, - { - status: no_actions_error.status, - headers: { - // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405 - // "The server must generate an Allow header field in a 405 status code response" - allow: "GET" - } - } - ); - } - check_named_default_separate(actions); - try { - const data = await call_action(event, event_state, actions); - if (DEV) ; - if (data instanceof ActionFailure) { - return action_json({ - type: "failure", - status: data.status, - // @ts-expect-error we assign a string to what is supposed to be an object. That's ok - // because we don't use the object outside, and this way we have better code navigation - // through knowing where the related interface is used. - data: stringify_action_response( - data.data, - /** @type {string} */ - event.route.id, - options2.hooks.transport - ) - }); - } else { - return action_json({ - type: "success", - status: data ? 200 : 204, - // @ts-expect-error see comment above - data: stringify_action_response( - data, - /** @type {string} */ - event.route.id, - options2.hooks.transport - ) - }); - } - } catch (e) { - const err = normalize_error(e); - if (err instanceof Redirect) { - return action_json_redirect(err); - } - return action_json( - { - type: "error", - error: await handle_error_and_jsonify( - event, - event_state, - options2, - check_incorrect_fail_use(err) - ) - }, - { - status: get_status(err) - } - ); - } -} -function check_incorrect_fail_use(error2) { - return error2 instanceof ActionFailure ? new Error('Cannot "throw fail()". Use "return fail()"') : error2; -} -function action_json_redirect(redirect) { - return action_json({ - type: "redirect", - status: redirect.status, - location: redirect.location - }); -} -function action_json(data, init2) { - return json(data, init2); -} -function is_action_request(event) { - return event.request.method === "POST"; -} -async function handle_action_request(event, event_state, server) { - const actions = server?.actions; - if (!actions) { - event.setHeaders({ - // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405 - // "The server must generate an Allow header field in a 405 status code response" - allow: "GET" - }); - return { - type: "error", - error: new SvelteKitError( - 405, - "Method Not Allowed", - `POST method not allowed. No form actions exist for ${"this page"}` - ) - }; - } - check_named_default_separate(actions); - try { - const data = await call_action(event, event_state, actions); - if (DEV) ; - if (data instanceof ActionFailure) { - return { - type: "failure", - status: data.status, - data: data.data - }; - } else { - return { - type: "success", - status: 200, - // @ts-expect-error this will be removed upon serialization, so `undefined` is the same as omission - data - }; - } - } catch (e) { - const err = normalize_error(e); - if (err instanceof Redirect) { - return { - type: "redirect", - status: err.status, - location: err.location - }; - } - return { - type: "error", - error: check_incorrect_fail_use(err) - }; - } -} -function check_named_default_separate(actions) { - if (actions.default && Object.keys(actions).length > 1) { - throw new Error( - "When using named actions, the default action cannot be used. See the docs for more info: https://svelte.dev/docs/kit/form-actions#named-actions" - ); - } -} -async function call_action(event, event_state, actions) { - const url = new URL(event.request.url); - let name = "default"; - for (const param of url.searchParams) { - if (param[0].startsWith("/")) { - name = param[0].slice(1); - if (name === "default") { - throw new Error('Cannot use reserved action name "default"'); - } - break; - } - } - const action = actions[name]; - if (!action) { - throw new SvelteKitError(404, "Not Found", `No action with name '${name}' found`); - } - if (!is_form_content_type(event.request)) { - throw new SvelteKitError( - 415, - "Unsupported Media Type", - `Form actions expect form-encoded data — received ${event.request.headers.get( - "content-type" - )}` - ); - } - return record_span({ - name: "sveltekit.form_action", - attributes: { - "http.route": event.route.id || "unknown" - }, - fn: async (current2) => { - const traced_event = merge_tracing(event, current2); - const result = await with_request_store( - { event: traced_event, state: event_state }, - () => action(traced_event) - ); - if (result instanceof ActionFailure) { - current2.setAttributes({ - "sveltekit.form_action.result.type": "failure", - "sveltekit.form_action.result.status": result.status - }); - } - return result; - } - }); -} -function validate_action_return(data) { - if (data instanceof Redirect) { - throw new Error("Cannot `return redirect(...)` — use `redirect(...)` instead"); - } - if (data instanceof HttpError) { - throw new Error("Cannot `return error(...)` — use `error(...)` or `return fail(...)` instead"); - } -} -function uneval_action_response(data, route_id, transport) { - const replacer = (thing) => { - for (const key2 in transport) { - const encoded = transport[key2].encode(thing); - if (encoded) { - return `app.decode('${key2}', ${devalue.uneval(encoded, replacer)})`; - } - } - }; - return try_serialize(data, (value) => devalue.uneval(value, replacer), route_id); -} -function stringify_action_response(data, route_id, transport) { - const encoders = Object.fromEntries( - Object.entries(transport).map(([key2, value]) => [key2, value.encode]) - ); - return try_serialize(data, (value) => devalue.stringify(value, encoders), route_id); -} -function try_serialize(data, fn, route_id) { - try { - return fn(data); - } catch (e) { - const error2 = ( - /** @type {any} */ - e - ); - if (data instanceof Response) { - throw new Error( - `Data returned from action inside ${route_id} is not serializable. Form actions need to return plain objects or fail(). E.g. return { success: true } or return fail(400, { message: "invalid" });` - ); - } - if ("path" in error2) { - let message = `Data returned from action inside ${route_id} is not serializable: ${error2.message}`; - if (error2.path !== "") message += ` (data.${error2.path})`; - throw new Error(message); - } - throw error2; - } -} -function create_async_iterator() { - let resolved = -1; - let returned = -1; - const deferred = []; - return { - iterate: (transform = (x) => x) => { - return { - [Symbol.asyncIterator]() { - return { - next: async () => { - const next = deferred[++returned]; - if (!next) return { value: null, done: true }; - const value = await next.promise; - return { value: transform(value), done: false }; - } - }; - } - }; - }, - add: (promise) => { - deferred.push(with_resolvers()); - void promise.then((value) => { - deferred[++resolved].resolve(value); - }); - } - }; -} -function server_data_serializer(event, event_state, options2) { - let promise_id = 1; - let max_nodes = -1; - const iterator = create_async_iterator(); - const global = get_global_name(options2); - function get_replacer(index) { - return function replacer(thing) { - if (typeof thing?.then === "function") { - const id = promise_id++; - const promise = thing.then( - /** @param {any} data */ - (data) => ({ data }) - ).catch( - /** @param {any} error */ - async (error2) => ({ - error: await handle_error_and_jsonify(event, event_state, options2, error2) - }) - ).then( - /** - * @param {{data: any; error: any}} result - */ - async ({ data, error: error2 }) => { - let str; - try { - str = devalue.uneval(error2 ? [, error2] : [data], replacer); - } catch { - error2 = await handle_error_and_jsonify( - event, - event_state, - options2, - new Error(`Failed to serialize promise while rendering ${event.route.id}`) - ); - data = void 0; - str = devalue.uneval([, error2], replacer); - } - return { - index, - str: `${global}.resolve(${id}, ${str.includes("app.decode") ? `(app) => ${str}` : `() => ${str}`})` - }; - } - ); - iterator.add(promise); - return `${global}.defer(${id})`; - } else { - for (const key2 in options2.hooks.transport) { - const encoded = options2.hooks.transport[key2].encode(thing); - if (encoded) { - return `app.decode('${key2}', ${devalue.uneval(encoded, replacer)})`; - } - } - } - }; - } - const strings = ( - /** @type {string[]} */ - [] - ); - return { - set_max_nodes(i) { - max_nodes = i; - }, - add_node(i, node) { - try { - if (!node) { - strings[i] = "null"; - return; - } - const payload = { type: "data", data: node.data, uses: serialize_uses(node) }; - if (node.slash) payload.slash = node.slash; - strings[i] = devalue.uneval(payload, get_replacer(i)); - } catch (e) { - e.path = e.path.slice(1); - throw new Error(clarify_devalue_error( - event, - /** @type {any} */ - e - )); - } - }, - get_data(csp) { - const open = ``; - const close = `<\/script> -`; - return { - data: `[${compact(max_nodes > -1 ? strings.slice(0, max_nodes) : strings).join(",")}]`, - chunks: promise_id > 1 ? iterator.iterate(({ index, str }) => { - if (max_nodes > -1 && index >= max_nodes) { - return ""; - } - return open + str + close; - }) : null - }; - } - }; -} -function server_data_serializer_json(event, event_state, options2) { - let promise_id = 1; - const iterator = create_async_iterator(); - const reducers = { - ...Object.fromEntries( - Object.entries(options2.hooks.transport).map(([key2, value]) => [key2, value.encode]) - ), - /** @param {any} thing */ - Promise: (thing) => { - if (typeof thing?.then !== "function") { - return; - } - const id = promise_id++; - let key2 = "data"; - const promise = thing.catch( - /** @param {any} e */ - async (e) => { - key2 = "error"; - return handle_error_and_jsonify( - event, - event_state, - options2, - /** @type {any} */ - e - ); - } - ).then( - /** @param {any} value */ - async (value) => { - let str; - try { - str = devalue.stringify(value, reducers); - } catch { - const error2 = await handle_error_and_jsonify( - event, - event_state, - options2, - new Error(`Failed to serialize promise while rendering ${event.route.id}`) - ); - key2 = "error"; - str = devalue.stringify(error2, reducers); - } - return `{"type":"chunk","id":${id},"${key2}":${str}} -`; - } - ); - iterator.add(promise); - return id; - } - }; - const strings = ( - /** @type {string[]} */ - [] - ); - return { - add_node(i, node) { - try { - if (!node) { - strings[i] = "null"; - return; - } - if (node.type === "error" || node.type === "skip") { - strings[i] = JSON.stringify(node); - return; - } - strings[i] = `{"type":"data","data":${devalue.stringify(node.data, reducers)},"uses":${JSON.stringify( - serialize_uses(node) - )}${node.slash ? `,"slash":${JSON.stringify(node.slash)}` : ""}}`; - } catch (e) { - e.path = "data" + e.path; - throw new Error(clarify_devalue_error( - event, - /** @type {any} */ - e - )); - } - }, - get_data() { - return { - data: `{"type":"data","nodes":[${strings.join(",")}]} -`, - chunks: promise_id > 1 ? iterator.iterate() : null - }; - } - }; -} -async function load_server_data({ event, event_state, state, node, parent }) { - if (!node?.server) return null; - let is_tracking = true; - const uses = { - dependencies: /* @__PURE__ */ new Set(), - params: /* @__PURE__ */ new Set(), - parent: false, - route: false, - url: false, - search_params: /* @__PURE__ */ new Set() - }; - const load = node.server.load; - const slash = node.server.trailingSlash; - if (!load) { - return { type: "data", data: null, uses, slash }; - } - const url = make_trackable( - event.url, - () => { - if (is_tracking) { - uses.url = true; - } - }, - (param) => { - if (is_tracking) { - uses.search_params.add(param); - } - } - ); - if (state.prerendering) { - disable_search(url); - } - const result = await record_span({ - name: "sveltekit.load", - attributes: { - "sveltekit.load.node_id": node.server_id || "unknown", - "sveltekit.load.node_type": get_node_type(node.server_id), - "http.route": event.route.id || "unknown" - }, - fn: async (current2) => { - const traced_event = merge_tracing(event, current2); - const result2 = await with_request_store( - { event: traced_event, state: event_state }, - () => load.call(null, { - ...traced_event, - fetch: (info, init2) => { - new URL(info instanceof Request ? info.url : info, event.url); - return event.fetch(info, init2); - }, - /** @param {string[]} deps */ - depends: (...deps) => { - for (const dep of deps) { - const { href } = new URL(dep, event.url); - uses.dependencies.add(href); - } - }, - params: new Proxy(event.params, { - get: (target, key2) => { - if (is_tracking) { - uses.params.add(key2); - } - return target[ - /** @type {string} */ - key2 - ]; - } - }), - parent: async () => { - if (is_tracking) { - uses.parent = true; - } - return parent(); - }, - route: new Proxy(event.route, { - get: (target, key2) => { - if (is_tracking) { - uses.route = true; - } - return target[ - /** @type {'id'} */ - key2 - ]; - } - }), - url, - untrack(fn) { - is_tracking = false; - try { - return fn(); - } finally { - is_tracking = true; - } - } - }) - ); - return result2; - } - }); - return { - type: "data", - data: result ?? null, - uses, - slash - }; -} -async function load_data({ - event, - event_state, - fetched, - node, - parent, - server_data_promise, - state, - resolve_opts, - csr -}) { - const server_data_node = await server_data_promise; - const load = node?.universal?.load; - if (!load) { - return server_data_node?.data ?? null; - } - const result = await record_span({ - name: "sveltekit.load", - attributes: { - "sveltekit.load.node_id": node.universal_id || "unknown", - "sveltekit.load.node_type": get_node_type(node.universal_id), - "http.route": event.route.id || "unknown" - }, - fn: async (current2) => { - const traced_event = merge_tracing(event, current2); - return await with_request_store( - { event: traced_event, state: event_state }, - () => load.call(null, { - url: event.url, - params: event.params, - data: server_data_node?.data ?? null, - route: event.route, - fetch: create_universal_fetch(event, state, fetched, csr, resolve_opts), - setHeaders: event.setHeaders, - depends: () => { - }, - parent, - untrack: (fn) => fn(), - tracing: traced_event.tracing - }) - ); - } - }); - return result ?? null; -} -function create_universal_fetch(event, state, fetched, csr, resolve_opts) { - const universal_fetch = async (input, init2) => { - const cloned_body = input instanceof Request && input.body ? input.clone().body : null; - const cloned_headers = input instanceof Request && [...input.headers].length ? new Headers(input.headers) : init2?.headers; - let response = await event.fetch(input, init2); - const url = new URL(input instanceof Request ? input.url : input, event.url); - const same_origin = url.origin === event.url.origin; - let dependency; - if (same_origin) { - if (state.prerendering) { - dependency = { response, body: null }; - state.prerendering.dependencies.set(url.pathname, dependency); - } - } else if (url.protocol === "https:" || url.protocol === "http:") { - const mode = input instanceof Request ? input.mode : init2?.mode ?? "cors"; - if (mode === "no-cors") { - response = new Response("", { - status: response.status, - statusText: response.statusText, - headers: response.headers - }); - } else { - const acao = response.headers.get("access-control-allow-origin"); - if (!acao || acao !== event.url.origin && acao !== "*") { - throw new Error( - `CORS error: ${acao ? "Incorrect" : "No"} 'Access-Control-Allow-Origin' header is present on the requested resource` - ); - } - } - } - let teed_body; - const proxy = new Proxy(response, { - get(response2, key2, _receiver) { - async function push_fetched(body2, is_b64) { - const status_number = Number(response2.status); - if (isNaN(status_number)) { - throw new Error( - `response.status is not a number. value: "${response2.status}" type: ${typeof response2.status}` - ); - } - fetched.push({ - url: same_origin ? url.href.slice(event.url.origin.length) : url.href, - method: event.request.method, - request_body: ( - /** @type {string | ArrayBufferView | undefined} */ - input instanceof Request && cloned_body ? await stream_to_string(cloned_body) : init2?.body - ), - request_headers: cloned_headers, - response_body: body2, - response: response2, - is_b64 - }); - } - if (key2 === "body") { - if (response2.body === null) { - return null; - } - if (teed_body) { - return teed_body; - } - const [a, b] = response2.body.tee(); - void (async () => { - let result = new Uint8Array(); - for await (const chunk of a) { - const combined = new Uint8Array(result.length + chunk.length); - combined.set(result, 0); - combined.set(chunk, result.length); - result = combined; - } - if (dependency) { - dependency.body = new Uint8Array(result); - } - void push_fetched(base64_encode(result), true); - })(); - return teed_body = b; - } - if (key2 === "arrayBuffer") { - return async () => { - const buffer = await response2.arrayBuffer(); - const bytes = new Uint8Array(buffer); - if (dependency) { - dependency.body = bytes; - } - if (buffer instanceof ArrayBuffer) { - await push_fetched(base64_encode(bytes), true); - } - return buffer; - }; - } - async function text2() { - const body2 = await response2.text(); - if (body2 === "" && NULL_BODY_STATUS.includes(response2.status)) { - await push_fetched(void 0, false); - return void 0; - } - if (!body2 || typeof body2 === "string") { - await push_fetched(body2, false); - } - if (dependency) { - dependency.body = body2; - } - return body2; - } - if (key2 === "text") { - return text2; - } - if (key2 === "json") { - return async () => { - const body2 = await text2(); - return body2 ? JSON.parse(body2) : void 0; - }; - } - return Reflect.get(response2, key2, response2); - } - }); - if (csr) { - const get = response.headers.get; - response.headers.get = (key2) => { - const lower = key2.toLowerCase(); - const value = get.call(response.headers, lower); - if (value && !lower.startsWith("x-sveltekit-")) { - const included = resolve_opts.filterSerializedResponseHeaders(lower, value); - if (!included) { - throw new Error( - `Failed to get response header "${lower}" — it must be included by the \`filterSerializedResponseHeaders\` option: https://svelte.dev/docs/kit/hooks#Server-hooks-handle (at ${event.route.id})` - ); - } - } - return value; - }; - } - return proxy; - }; - return (input, init2) => { - const response = universal_fetch(input, init2); - response.catch(() => { - }); - return response; - }; -} -async function stream_to_string(stream) { - let result = ""; - const reader = stream.getReader(); - while (true) { - const { done, value } = await reader.read(); - if (done) { - break; - } - result += text_decoder.decode(value); - } - return result; -} -function hash(...values) { - let hash2 = 5381; - for (const value of values) { - if (typeof value === "string") { - let i = value.length; - while (i) hash2 = hash2 * 33 ^ value.charCodeAt(--i); - } else if (ArrayBuffer.isView(value)) { - const buffer = new Uint8Array(value.buffer, value.byteOffset, value.byteLength); - let i = buffer.length; - while (i) hash2 = hash2 * 33 ^ buffer[--i]; - } else { - throw new TypeError("value must be a string or TypedArray"); - } - } - return (hash2 >>> 0).toString(36); -} -const replacements = { - "<": "\\u003C", - "\u2028": "\\u2028", - "\u2029": "\\u2029" -}; -const pattern = new RegExp(`[${Object.keys(replacements).join("")}]`, "g"); -function serialize_data(fetched, filter, prerendering = false) { - const headers2 = {}; - let cache_control = null; - let age = null; - let varyAny = false; - for (const [key2, value] of fetched.response.headers) { - if (filter(key2, value)) { - headers2[key2] = value; - } - if (key2 === "cache-control") cache_control = value; - else if (key2 === "age") age = value; - else if (key2 === "vary" && value.trim() === "*") varyAny = true; - } - const payload = { - status: fetched.response.status, - statusText: fetched.response.statusText, - headers: headers2, - body: fetched.response_body - }; - const safe_payload = JSON.stringify(payload).replace(pattern, (match) => replacements[match]); - const attrs = [ - 'type="application/json"', - "data-sveltekit-fetched", - `data-url="${escape_html(fetched.url, true)}"` - ]; - if (fetched.is_b64) { - attrs.push("data-b64"); - } - if (fetched.request_headers || fetched.request_body) { - const values = []; - if (fetched.request_headers) { - values.push([...new Headers(fetched.request_headers)].join(",")); - } - if (fetched.request_body) { - values.push(fetched.request_body); - } - attrs.push(`data-hash="${hash(...values)}"`); - } - if (!prerendering && fetched.method === "GET" && cache_control && !varyAny) { - const match = /s-maxage=(\d+)/g.exec(cache_control) ?? /max-age=(\d+)/g.exec(cache_control); - if (match) { - const ttl = +match[1] - +(age ?? "0"); - attrs.push(`data-ttl="${ttl}"`); - } - } - return `