import { D as DevalueError, i as is_primitive, g as get_type, a as is_plain_object, e as enumerable_symbols, s as stringify_key, b as stringify_string, w as with_request_store, t as text_decoder, c as base64_decode, r as root, d as decode_pathname, f as browser, n as normalize_path, h as disable_search, j as decode_params, v as validate_layout_server_exports, k as validate_layout_exports, l as validate_page_server_exports, m as validate_page_exports, u as uneval, o as text_encoder$1, p as resolve, q as make_trackable, x as get_relative_path, y as base64_encode, z as writable, A as readable } from './chunks/exports-yY1xCm4l.js'; import { t as text_encoder } from './chunks/utils-FiC4zhrQ.js'; /** @import { StandardSchemaV1 } from '@standard-schema/spec' */ class HttpError { /** * @param {number} status * @param {{message: string} extends App.Error ? (App.Error | string | undefined) : App.Error} body */ constructor(status, body) { this.status = status; if (typeof body === 'string') { this.body = { message: body }; } else if (body) { this.body = body; } else { this.body = { message: `Error: ${status}` }; } } toString() { return JSON.stringify(this.body); } } class Redirect { /** * @param {300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308} status * @param {string} location */ constructor(status, location) { this.status = status; this.location = location; } } /** * An error that was thrown from within the SvelteKit runtime that is not fatal and doesn't result in a 500, such as a 404. * `SvelteKitError` goes through `handleError`. * @extends Error */ class SvelteKitError extends Error { /** * @param {number} status * @param {string} text * @param {string} message */ constructor(status, text, message) { super(message); this.status = status; this.text = text; } } /** * @template [T=undefined] */ class ActionFailure { /** * @param {number} status * @param {T} data */ constructor(status, data) { this.status = status; this.data = data; } } /** @import { StandardSchemaV1 } from '@standard-schema/spec' */ // TODO 3.0: remove these types as they are not used anymore (we can't remove them yet because that would be a breaking change) /** * @template {number} TNumber * @template {any[]} [TArray=[]] * @typedef {TNumber extends TArray['length'] ? TArray[number] : LessThan} LessThan */ /** * @template {number} TStart * @template {number} TEnd * @typedef {Exclude, LessThan>} NumericRange */ // Keep the status codes as `number` because restricting to certain numbers makes it unnecessarily hard to use compared to the benefits // (we have runtime errors already to check for invalid codes). Also see https://github.com/sveltejs/kit/issues/11780 // we have to repeat the JSDoc because the display for function overloads is broken // see https://github.com/microsoft/TypeScript/issues/55056 /** * Throws an error with a HTTP status code and an optional message. * When called during request handling, this will cause SvelteKit to * return an error response without invoking `handleError`. * Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it. * @param {number} status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599. * @param {App.Error} body An object that conforms to the App.Error type. If a string is passed, it will be used as the message property. * @overload * @param {number} status * @param {App.Error} body * @return {never} * @throws {HttpError} This error instructs SvelteKit to initiate HTTP error handling. * @throws {Error} If the provided status is invalid (not between 400 and 599). */ /** * Throws an error with a HTTP status code and an optional message. * When called during request handling, this will cause SvelteKit to * return an error response without invoking `handleError`. * Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it. * @param {number} status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599. * @param {{ message: string } extends App.Error ? App.Error | string | undefined : never} [body] An object that conforms to the App.Error type. If a string is passed, it will be used as the message property. * @overload * @param {number} status * @param {{ message: string } extends App.Error ? App.Error | string | undefined : never} [body] * @return {never} * @throws {HttpError} This error instructs SvelteKit to initiate HTTP error handling. * @throws {Error} If the provided status is invalid (not between 400 and 599). */ /** * Throws an error with a HTTP status code and an optional message. * When called during request handling, this will cause SvelteKit to * return an error response without invoking `handleError`. * Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it. * @param {number} status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599. * @param {{ message: string } extends App.Error ? App.Error | string | undefined : never} body An object that conforms to the App.Error type. If a string is passed, it will be used as the message property. * @return {never} * @throws {HttpError} This error instructs SvelteKit to initiate HTTP error handling. * @throws {Error} If the provided status is invalid (not between 400 and 599). */ function error(status, body) { if ((isNaN(status) || status < 400 || status > 599)) { throw new Error(`HTTP error status codes must be between 400 and 599 — ${status} is invalid`); } throw new HttpError(status, body); } /** * Create a JSON `Response` object from the supplied data. * @param {any} data The value that will be serialized as JSON. * @param {ResponseInit} [init] Options such as `status` and `headers` that will be added to the response. `Content-Type: application/json` and `Content-Length` headers will be added automatically. */ function json(data, init) { // TODO deprecate this in favour of `Response.json` when it's // more widely supported const body = JSON.stringify(data); // we can't just do `text(JSON.stringify(data), init)` because // it will set a default `content-type` header. duplicated code // means less duplicated work const headers = new Headers(init?.headers); if (!headers.has('content-length')) { headers.set('content-length', text_encoder.encode(body).byteLength.toString()); } if (!headers.has('content-type')) { headers.set('content-type', 'application/json'); } return new Response(body, { ...init, headers }); } /** * Create a `Response` object from the supplied body. * @param {string} body The value that will be used as-is. * @param {ResponseInit} [init] Options such as `status` and `headers` that will be added to the response. A `Content-Length` header will be added automatically. */ function text(body, init) { const headers = new Headers(init?.headers); if (!headers.has('content-length')) { const encoded = text_encoder.encode(body); headers.set('content-length', encoded.byteLength.toString()); return new Response(encoded, { ...init, headers }); } return new Response(body, { ...init, headers }); } /** * @template {{ tracing: { enabled: boolean, root: import('@opentelemetry/api').Span, current: import('@opentelemetry/api').Span } }} T * @param {T} event_like * @param {import('@opentelemetry/api').Span} current * @returns {T} */ function merge_tracing(event_like, current) { return { ...event_like, tracing: { ...event_like.tracing, current } }; } let base = ""; let assets = base; const app_dir = "_app"; const relative = true; const initial = { base, assets }; function override(paths) { base = paths.base; assets = paths.assets; } function reset() { base = initial.base; assets = initial.assets; } /** * Base64 Encodes an arraybuffer * @param {ArrayBuffer} arraybuffer * @returns {string} */ function encode64(arraybuffer) { const dv = new DataView(arraybuffer); let binaryString = ""; for (let i = 0; i < arraybuffer.byteLength; i++) { binaryString += String.fromCharCode(dv.getUint8(i)); } return binaryToAscii(binaryString); } /** * Decodes a base64 string into an arraybuffer * @param {string} string * @returns {ArrayBuffer} */ function decode64(string) { const binaryString = asciiToBinary(string); const arraybuffer = new ArrayBuffer(binaryString.length); const dv = new DataView(arraybuffer); for (let i = 0; i < arraybuffer.byteLength; i++) { dv.setUint8(i, binaryString.charCodeAt(i)); } return arraybuffer; } const KEY_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /** * Substitute for atob since it's deprecated in node. * Does not do any input validation. * * @see https://github.com/jsdom/abab/blob/master/lib/atob.js * * @param {string} data * @returns {string} */ function asciiToBinary(data) { if (data.length % 4 === 0) { data = data.replace(/==?$/, ""); } let output = ""; let buffer = 0; let accumulatedBits = 0; for (let i = 0; i < data.length; i++) { buffer <<= 6; buffer |= KEY_STRING.indexOf(data[i]); accumulatedBits += 6; if (accumulatedBits === 24) { output += String.fromCharCode((buffer & 0xff0000) >> 16); output += String.fromCharCode((buffer & 0xff00) >> 8); output += String.fromCharCode(buffer & 0xff); buffer = accumulatedBits = 0; } } if (accumulatedBits === 12) { buffer >>= 4; output += String.fromCharCode(buffer); } else if (accumulatedBits === 18) { buffer >>= 2; output += String.fromCharCode((buffer & 0xff00) >> 8); output += String.fromCharCode(buffer & 0xff); } return output; } /** * Substitute for btoa since it's deprecated in node. * Does not do any input validation. * * @see https://github.com/jsdom/abab/blob/master/lib/btoa.js * * @param {string} str * @returns {string} */ function binaryToAscii(str) { let out = ""; for (let i = 0; i < str.length; i += 3) { /** @type {[number, number, number, number]} */ const groupsOfSix = [undefined, undefined, undefined, undefined]; groupsOfSix[0] = str.charCodeAt(i) >> 2; groupsOfSix[1] = (str.charCodeAt(i) & 0x03) << 4; if (str.length > i + 1) { groupsOfSix[1] |= str.charCodeAt(i + 1) >> 4; groupsOfSix[2] = (str.charCodeAt(i + 1) & 0x0f) << 2; } if (str.length > i + 2) { groupsOfSix[2] |= str.charCodeAt(i + 2) >> 6; groupsOfSix[3] = str.charCodeAt(i + 2) & 0x3f; } for (let j = 0; j < groupsOfSix.length; j++) { if (typeof groupsOfSix[j] === "undefined") { out += "="; } else { out += KEY_STRING[groupsOfSix[j]]; } } } return out; } const UNDEFINED = -1; const HOLE = -2; const NAN = -3; const POSITIVE_INFINITY = -4; const NEGATIVE_INFINITY = -5; const NEGATIVE_ZERO = -6; /** * Revive a value serialized with `devalue.stringify` * @param {string} serialized * @param {Record any>} [revivers] */ function parse(serialized, revivers) { return unflatten(JSON.parse(serialized), revivers); } /** * Revive a value flattened with `devalue.stringify` * @param {number | any[]} parsed * @param {Record any>} [revivers] */ function unflatten(parsed, revivers) { if (typeof parsed === 'number') return hydrate(parsed, true); if (!Array.isArray(parsed) || parsed.length === 0) { throw new Error('Invalid input'); } const values = /** @type {any[]} */ (parsed); const hydrated = Array(values.length); /** * A set of values currently being hydrated with custom revivers, * used to detect invalid cyclical dependencies * @type {Set | null} */ let hydrating = null; /** * @param {number} index * @returns {any} */ function hydrate(index, standalone = false) { if (index === UNDEFINED) return undefined; if (index === NAN) return NaN; if (index === POSITIVE_INFINITY) return Infinity; if (index === NEGATIVE_INFINITY) return -Infinity; if (index === NEGATIVE_ZERO) return -0; if (standalone || typeof index !== 'number') { throw new Error(`Invalid input`); } if (index in hydrated) return hydrated[index]; const value = values[index]; if (!value || typeof value !== 'object') { hydrated[index] = value; } else if (Array.isArray(value)) { if (typeof value[0] === 'string') { const type = value[0]; const reviver = revivers && Object.hasOwn(revivers, type) ? revivers[type] : undefined; if (reviver) { let i = value[1]; if (typeof i !== 'number') { // if it's not a number, it was serialized by a builtin reviver // so we need to munge it into the format expected by a custom reviver i = values.push(value[1]) - 1; } hydrating ??= new Set(); if (hydrating.has(i)) { throw new Error('Invalid circular reference'); } hydrating.add(i); hydrated[index] = reviver(hydrate(i)); hydrating.delete(i); return hydrated[index]; } switch (type) { case 'Date': hydrated[index] = new Date(value[1]); break; case 'Set': const set = new Set(); hydrated[index] = set; for (let i = 1; i < value.length; i += 1) { set.add(hydrate(value[i])); } break; case 'Map': const map = new Map(); hydrated[index] = map; for (let i = 1; i < value.length; i += 2) { map.set(hydrate(value[i]), hydrate(value[i + 1])); } break; case 'RegExp': hydrated[index] = new RegExp(value[1], value[2]); break; case 'Object': hydrated[index] = Object(value[1]); break; case 'BigInt': hydrated[index] = BigInt(value[1]); break; case 'null': const obj = Object.create(null); hydrated[index] = obj; for (let i = 1; i < value.length; i += 2) { obj[value[i]] = hydrate(value[i + 1]); } break; case 'Int8Array': case 'Uint8Array': case 'Uint8ClampedArray': case 'Int16Array': case 'Uint16Array': case 'Int32Array': case 'Uint32Array': case 'Float32Array': case 'Float64Array': case 'BigInt64Array': case 'BigUint64Array': { if (values[value[1]][0] !== 'ArrayBuffer') { // without this, if we receive malformed input we could // end up trying to hydrate in a circle or allocate // huge amounts of memory when we call `new TypedArrayConstructor(buffer)` throw new Error('Invalid data'); } const TypedArrayConstructor = globalThis[type]; const buffer = hydrate(value[1]); const typedArray = new TypedArrayConstructor(buffer); hydrated[index] = value[2] !== undefined ? typedArray.subarray(value[2], value[3]) : typedArray; break; } case 'ArrayBuffer': { const base64 = value[1]; if (typeof base64 !== 'string') { throw new Error('Invalid ArrayBuffer encoding'); } const arraybuffer = decode64(base64); hydrated[index] = arraybuffer; break; } case 'Temporal.Duration': case 'Temporal.Instant': case 'Temporal.PlainDate': case 'Temporal.PlainTime': case 'Temporal.PlainDateTime': case 'Temporal.PlainMonthDay': case 'Temporal.PlainYearMonth': case 'Temporal.ZonedDateTime': { const temporalName = type.slice(9); // @ts-expect-error TS doesn't know about Temporal yet hydrated[index] = Temporal[temporalName].from(value[1]); break; } case 'URL': { const url = new URL(value[1]); hydrated[index] = url; break; } case 'URLSearchParams': { const url = new URLSearchParams(value[1]); hydrated[index] = url; break; } default: throw new Error(`Unknown type ${type}`); } } else { const array = new Array(value.length); hydrated[index] = array; for (let i = 0; i < value.length; i += 1) { const n = value[i]; if (n === HOLE) continue; array[i] = hydrate(n); } } } else { /** @type {Record} */ const object = {}; hydrated[index] = object; for (const key in value) { if (key === '__proto__') { throw new Error('Cannot parse an object with a `__proto__` property'); } const n = value[key]; object[key] = hydrate(n); } } return hydrated[index]; } return hydrate(0); } /** * Turn a value into a JSON string that can be parsed with `devalue.parse` * @param {any} value * @param {Record any>} [reducers] */ function stringify$1(value, reducers) { /** @type {any[]} */ const stringified = []; /** @type {Map} */ const indexes = new Map(); /** @type {Array<{ key: string, fn: (value: any) => any }>} */ const custom = []; if (reducers) { for (const key of Object.getOwnPropertyNames(reducers)) { custom.push({ key, fn: reducers[key] }); } } /** @type {string[]} */ const keys = []; let p = 0; /** @param {any} thing */ function flatten(thing) { if (thing === undefined) return UNDEFINED; if (Number.isNaN(thing)) return NAN; if (thing === Infinity) return POSITIVE_INFINITY; if (thing === -Infinity) return NEGATIVE_INFINITY; if (thing === 0 && 1 / thing < 0) return NEGATIVE_ZERO; if (indexes.has(thing)) return indexes.get(thing); const index = p++; indexes.set(thing, index); for (const { key, fn } of custom) { const value = fn(thing); if (value) { stringified[index] = `["${key}",${flatten(value)}]`; return index; } } if (typeof thing === 'function') { throw new DevalueError(`Cannot stringify a function`, keys, thing, value); } let str = ''; if (is_primitive(thing)) { str = stringify_primitive(thing); } else { const type = get_type(thing); switch (type) { case 'Number': case 'String': case 'Boolean': str = `["Object",${stringify_primitive(thing)}]`; break; case 'BigInt': str = `["BigInt",${thing}]`; break; case 'Date': const valid = !isNaN(thing.getDate()); str = `["Date","${valid ? thing.toISOString() : ''}"]`; break; case 'URL': str = `["URL",${stringify_string(thing.toString())}]`; break; case 'URLSearchParams': str = `["URLSearchParams",${stringify_string(thing.toString())}]`; break; case 'RegExp': const { source, flags } = thing; str = flags ? `["RegExp",${stringify_string(source)},"${flags}"]` : `["RegExp",${stringify_string(source)}]`; break; case 'Array': str = '['; for (let i = 0; i < thing.length; i += 1) { if (i > 0) str += ','; if (i in thing) { keys.push(`[${i}]`); str += flatten(thing[i]); keys.pop(); } else { str += HOLE; } } str += ']'; break; case 'Set': str = '["Set"'; for (const value of thing) { str += `,${flatten(value)}`; } str += ']'; break; case 'Map': str = '["Map"'; for (const [key, value] of thing) { keys.push( `.get(${is_primitive(key) ? stringify_primitive(key) : '...'})` ); str += `,${flatten(key)},${flatten(value)}`; keys.pop(); } str += ']'; break; case 'Int8Array': case 'Uint8Array': case 'Uint8ClampedArray': case 'Int16Array': case 'Uint16Array': case 'Int32Array': case 'Uint32Array': case 'Float32Array': case 'Float64Array': case 'BigInt64Array': case 'BigUint64Array': { /** @type {import("./types.js").TypedArray} */ const typedArray = thing; str = '["' + type + '",' + flatten(typedArray.buffer); const a = thing.byteOffset; const b = a + thing.byteLength; // handle subarrays if (a > 0 || b !== typedArray.buffer.byteLength) { const m = +/(\d+)/.exec(type)[1] / 8; str += `,${a / m},${b / m}`; } str += ']'; break; } case 'ArrayBuffer': { /** @type {ArrayBuffer} */ const arraybuffer = thing; const base64 = encode64(arraybuffer); str = `["ArrayBuffer","${base64}"]`; break; } case 'Temporal.Duration': case 'Temporal.Instant': case 'Temporal.PlainDate': case 'Temporal.PlainTime': case 'Temporal.PlainDateTime': case 'Temporal.PlainMonthDay': case 'Temporal.PlainYearMonth': case 'Temporal.ZonedDateTime': str = `["${type}",${stringify_string(thing.toString())}]`; break; default: if (!is_plain_object(thing)) { throw new DevalueError( `Cannot stringify arbitrary non-POJOs`, keys, thing, value ); } if (enumerable_symbols(thing).length > 0) { throw new DevalueError( `Cannot stringify POJOs with symbolic keys`, keys, thing, value ); } if (Object.getPrototypeOf(thing) === null) { str = '["null"'; for (const key in thing) { keys.push(stringify_key(key)); str += `,${stringify_string(key)},${flatten(thing[key])}`; keys.pop(); } str += ']'; } else { str = '{'; let started = false; for (const key in thing) { if (started) str += ','; started = true; keys.push(stringify_key(key)); str += `${stringify_string(key)}:${flatten(thing[key])}`; keys.pop(); } str += '}'; } } } stringified[index] = str; return index; } const index = flatten(value); // special case — value is represented as a negative index if (index < 0) return `${index}`; return `[${stringified.join(',')}]`; } /** * @param {any} thing * @returns {string} */ function stringify_primitive(thing) { const type = typeof thing; if (type === 'string') return stringify_string(thing); if (thing instanceof String) return stringify_string(thing.toString()); if (thing === void 0) return UNDEFINED.toString(); if (thing === 0 && 1 / thing < 0) return NEGATIVE_ZERO.toString(); if (type === 'bigint') return `["BigInt","${thing}"]`; return String(thing); } const SVELTE_KIT_ASSETS = "/_svelte_kit_assets"; const ENDPOINT_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]; const PAGE_METHODS = ["GET", "POST", "HEAD"]; function set_nested_value(object, path_string, value) { if (path_string.startsWith("n:")) { path_string = path_string.slice(2); value = value === "" ? void 0 : parseFloat(value); } else if (path_string.startsWith("b:")) { path_string = path_string.slice(2); value = value === "on"; } deep_set(object, split_path(path_string), value); } function convert_formdata(data) { const result = {}; for (let key of data.keys()) { const is_array = key.endsWith("[]"); let values = data.getAll(key); if (is_array) key = key.slice(0, -2); if (values.length > 1 && !is_array) { throw new Error(`Form cannot contain duplicated keys — "${key}" has ${values.length} values`); } values = values.filter( (entry) => typeof entry === "string" || entry.name !== "" || entry.size > 0 ); if (key.startsWith("n:")) { key = key.slice(2); values = values.map((v) => v === "" ? void 0 : parseFloat( /** @type {string} */ v )); } else if (key.startsWith("b:")) { key = key.slice(2); values = values.map((v) => v === "on"); } set_nested_value(result, key, is_array ? values : values[0]); } return result; } const BINARY_FORM_CONTENT_TYPE = "application/x-sveltekit-formdata"; const BINARY_FORM_VERSION = 0; const HEADER_BYTES = 1 + 4 + 2; async function deserialize_binary_form(request) { if (request.headers.get("content-type") !== BINARY_FORM_CONTENT_TYPE) { const form_data = await request.formData(); return { data: convert_formdata(form_data), meta: {}, form_data }; } if (!request.body) { throw deserialize_error("no body"); } const content_length = parseInt(request.headers.get("content-length") ?? ""); if (Number.isNaN(content_length)) { throw deserialize_error("invalid Content-Length header"); } const reader = request.body.getReader(); const chunks = []; function get_chunk(index) { if (index in chunks) return chunks[index]; let i = chunks.length; while (i <= index) { chunks[i] = reader.read().then((chunk) => chunk.value); i++; } return chunks[index]; } async function get_buffer(offset, length) { let start_chunk; let chunk_start = 0; let chunk_index; for (chunk_index = 0; ; chunk_index++) { const chunk = await get_chunk(chunk_index); if (!chunk) return null; const chunk_end = chunk_start + chunk.byteLength; if (offset >= chunk_start && offset < chunk_end) { start_chunk = chunk; break; } chunk_start = chunk_end; } if (offset + length <= chunk_start + start_chunk.byteLength) { return start_chunk.subarray(offset - chunk_start, offset + length - chunk_start); } const chunks2 = [start_chunk.subarray(offset - chunk_start)]; let cursor = start_chunk.byteLength - offset + chunk_start; while (cursor < length) { chunk_index++; let chunk = await get_chunk(chunk_index); if (!chunk) return null; if (chunk.byteLength > length - cursor) { chunk = chunk.subarray(0, length - cursor); } chunks2.push(chunk); cursor += chunk.byteLength; } const buffer = new Uint8Array(length); cursor = 0; for (const chunk of chunks2) { buffer.set(chunk, cursor); cursor += chunk.byteLength; } return buffer; } const header = await get_buffer(0, HEADER_BYTES); if (!header) throw deserialize_error("too short"); if (header[0] !== BINARY_FORM_VERSION) { throw deserialize_error(`got version ${header[0]}, expected version ${BINARY_FORM_VERSION}`); } const header_view = new DataView(header.buffer, header.byteOffset, header.byteLength); const data_length = header_view.getUint32(1, true); if (HEADER_BYTES + data_length > content_length) { throw deserialize_error("data overflow"); } const file_offsets_length = header_view.getUint16(5, true); if (HEADER_BYTES + data_length + file_offsets_length > content_length) { throw deserialize_error("file offset table overflow"); } const data_buffer = await get_buffer(HEADER_BYTES, data_length); if (!data_buffer) throw deserialize_error("data too short"); let file_offsets; let files_start_offset; if (file_offsets_length > 0) { const file_offsets_buffer = await get_buffer(HEADER_BYTES + data_length, file_offsets_length); if (!file_offsets_buffer) throw deserialize_error("file offset table too short"); file_offsets = /** @type {Array} */ JSON.parse(text_decoder.decode(file_offsets_buffer)); files_start_offset = HEADER_BYTES + data_length + file_offsets_length; } const [data, meta] = parse(text_decoder.decode(data_buffer), { File: ([name, type, size, last_modified, index]) => { if (files_start_offset + file_offsets[index] + size > content_length) { throw deserialize_error("file data overflow"); } return new Proxy( new LazyFile( name, type, size, last_modified, get_chunk, files_start_offset + file_offsets[index] ), { getPrototypeOf() { return File.prototype; } } ); } }); void (async () => { let has_more = true; while (has_more) { const chunk = await get_chunk(chunks.length); has_more = !!chunk; } })(); return { data, meta, form_data: null }; } function deserialize_error(message) { return new SvelteKitError(400, "Bad Request", `Could not deserialize binary form: ${message}`); } class LazyFile { /** @type {(index: number) => Promise | undefined>} */ #get_chunk; /** @type {number} */ #offset; /** * @param {string} name * @param {string} type * @param {number} size * @param {number} last_modified * @param {(index: number) => Promise | undefined>} get_chunk * @param {number} offset */ constructor(name, type, size, last_modified, get_chunk, offset) { this.name = name; this.type = type; this.size = size; this.lastModified = last_modified; this.webkitRelativePath = ""; this.#get_chunk = get_chunk; this.#offset = offset; this.arrayBuffer = this.arrayBuffer.bind(this); this.bytes = this.bytes.bind(this); this.slice = this.slice.bind(this); this.stream = this.stream.bind(this); this.text = this.text.bind(this); } /** @type {ArrayBuffer | undefined} */ #buffer; async arrayBuffer() { this.#buffer ??= await new Response(this.stream()).arrayBuffer(); return this.#buffer; } async bytes() { return new Uint8Array(await this.arrayBuffer()); } /** * @param {number=} start * @param {number=} end * @param {string=} contentType */ slice(start = 0, end = this.size, contentType = this.type) { if (start < 0) { start = Math.max(this.size + start, 0); } else { start = Math.min(start, this.size); } if (end < 0) { end = Math.max(this.size + end, 0); } else { end = Math.min(end, this.size); } const size = Math.max(end - start, 0); const file = new LazyFile( this.name, contentType, size, this.lastModified, this.#get_chunk, this.#offset + start ); return file; } stream() { let cursor = 0; let chunk_index = 0; return new ReadableStream({ start: async (controller) => { let chunk_start = 0; let start_chunk = null; for (chunk_index = 0; ; chunk_index++) { const chunk = await this.#get_chunk(chunk_index); if (!chunk) return null; const chunk_end = chunk_start + chunk.byteLength; if (this.#offset >= chunk_start && this.#offset < chunk_end) { start_chunk = chunk; break; } chunk_start = chunk_end; } if (this.#offset + this.size <= chunk_start + start_chunk.byteLength) { controller.enqueue( start_chunk.subarray(this.#offset - chunk_start, this.#offset + this.size - chunk_start) ); controller.close(); } else { controller.enqueue(start_chunk.subarray(this.#offset - chunk_start)); cursor = start_chunk.byteLength - this.#offset + chunk_start; } }, pull: async (controller) => { chunk_index++; let chunk = await this.#get_chunk(chunk_index); if (!chunk) { controller.error("incomplete file data"); controller.close(); return; } if (chunk.byteLength > this.size - cursor) { chunk = chunk.subarray(0, this.size - cursor); } controller.enqueue(chunk); cursor += chunk.byteLength; if (cursor >= this.size) { controller.close(); } } }); } async text() { return text_decoder.decode(await this.arrayBuffer()); } } const path_regex = /^[a-zA-Z_$]\w*(\.[a-zA-Z_$]\w*|\[\d+\])*$/; function split_path(path) { if (!path_regex.test(path)) { throw new Error(`Invalid path ${path}`); } return path.split(/\.|\[|\]/).filter(Boolean); } function check_prototype_pollution(key) { if (key === "__proto__" || key === "constructor" || key === "prototype") { throw new Error( `Invalid key "${key}"` ); } } function deep_set(object, keys, value) { let current = object; for (let i = 0; i < keys.length - 1; i += 1) { const key = keys[i]; check_prototype_pollution(key); const is_array = /^\d+$/.test(keys[i + 1]); const exists = Object.hasOwn(current, key); const inner = current[key]; if (exists && is_array !== Array.isArray(inner)) { throw new Error(`Invalid array key ${keys[i + 1]}`); } if (!exists) { current[key] = is_array ? [] : {}; } current = current[key]; } const final_key = keys[keys.length - 1]; check_prototype_pollution(final_key); current[final_key] = value; } 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", BINARY_FORM_CONTENT_TYPE ); } 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(error) { return ( /** @type {import('../exports/internal/index.js').Redirect | HttpError | SvelteKitError | Error} */ error ); } function get_status(error) { return error instanceof HttpError || error instanceof SvelteKitError ? error.status : 500; } function get_message(error) { return error instanceof SvelteKitError ? error.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(options) { return `__sveltekit_${options.version_hash}`; } function static_error_page(options, status, message) { let page = options.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, options, error) { error = error instanceof HttpError ? error : coalesce_to_error(error); const status = get_status(error); const body = await handle_error_and_jsonify(event, state, options, error); const type = negotiate(event.request.headers.get("accept") || "text/html", [ "application/json", "text/html" ]); if (event.isDataRequest || type === "application/json") { return json(body, { status }); } return static_error_page(options, status, body.message); } async function handle_error_and_jsonify(event, state, options, error) { if (error instanceof HttpError) { return { message: "Unknown Error", ...error.body }; } const status = get_status(error); const message = get_message(error); return await with_request_store( { event, state }, () => options.hooks.handleError({ error, 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, error) { if (error.path) { return `Data returned from \`load\` while rendering ${event.route.id} is not serializable: ${error.message} (${error.path}). If you need to serialize/deserialize custom types, use transport hooks: https://svelte.dev/docs/kit/hooks#Universal-hooks-transport.`; } if (error.path === "") { return `Data returned from \`load\` while rendering ${event.route.id} is not a plain object`; } return error.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, error, 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} ${error.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("."); } const INVALIDATED_PARAM = "x-sveltekit-invalidated"; const TRAILING_SLASH_PARAM = "x-sveltekit-trailing-slash"; function stringify(data, transport) { const encoders = Object.fromEntries(Object.entries(transport).map(([k, v]) => [k, v.encode])); return stringify$1(data, encoders); } function parse_remote_arg(string, transport) { if (!string) return void 0; const json_string = text_decoder.decode( // no need to add back `=` characters, atob can handle it base64_decode(string.replaceAll("-", "+").replaceAll("_", "/")) ); const decoders = Object.fromEntries(Object.entries(transport).map(([k, v]) => [k, v.decode])); return parse(json_string, decoders); } function create_remote_key(id, payload) { return id + "/" + payload; } let public_env = {}; function set_private_env(environment) { } function set_public_env(environment) { public_env = environment; } let read_implementation = null; function set_read_implementation(fn) { read_implementation = fn; } const options = { app_template_contains_nonce: false, async: false, csp: { "mode": "auto", "directives": { "upgrade-insecure-requests": false, "block-all-mixed-content": false }, "reportOnly": { "upgrade-insecure-requests": false, "block-all-mixed-content": false } }, csrf_check_origin: true, csrf_trusted_origins: [], embedded: false, env_public_prefix: "PUBLIC_", env_private_prefix: "", hash_routing: false, hooks: null, // added lazily, via `get_hooks` preload_strategy: "modulepreload", root, service_worker: false, service_worker_options: void 0, templates: { app: ({ head, body, assets, nonce, env }) => '\n\n \n \n \n \n ' + head + '\n \n \n
' + body + "
\n \n\n", error: ({ status, message }) => '\n\n \n \n ' + message + `
` + status + '\n
\n

' + message + "

\n
\n
\n \n\n" }, version_hash: "1hqd1fi" }; async function get_hooks() { let handle; let handleFetch; let handleError; let handleValidationError; let init; let reroute; let transport; return { handle, handleFetch, handleError, handleValidationError, init, reroute, transport }; } var cookie = {}; /*! * cookie * Copyright(c) 2012-2014 Roman Shtylman * Copyright(c) 2015 Douglas Christopher Wilson * MIT Licensed */ var hasRequiredCookie; function requireCookie () { if (hasRequiredCookie) return cookie; hasRequiredCookie = 1; /** * Module exports. * @public */ cookie.parse = parse; cookie.serialize = serialize; /** * Module variables. * @private */ var __toString = Object.prototype.toString; /** * RegExp to match field-content in RFC 7230 sec 3.2 * * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] * field-vchar = VCHAR / obs-text * obs-text = %x80-FF */ var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; /** * Parse a cookie header. * * Parse the given cookie header string into an object * The object has the various cookies as keys(names) => values * * @param {string} str * @param {object} [options] * @return {object} * @public */ function parse(str, options) { if (typeof str !== 'string') { throw new TypeError('argument str must be a string'); } var obj = {}; var opt = options || {}; var dec = opt.decode || decode; var index = 0; while (index < str.length) { var eqIdx = str.indexOf('=', index); // no more cookie pairs if (eqIdx === -1) { break } var endIdx = str.indexOf(';', index); if (endIdx === -1) { endIdx = str.length; } else if (endIdx < eqIdx) { // backtrack on prior semicolon index = str.lastIndexOf(';', eqIdx - 1) + 1; continue } var key = str.slice(index, eqIdx).trim(); // only assign once if (undefined === obj[key]) { var val = str.slice(eqIdx + 1, endIdx).trim(); // quoted values if (val.charCodeAt(0) === 0x22) { val = val.slice(1, -1); } obj[key] = tryDecode(val, dec); } index = endIdx + 1; } return obj; } /** * Serialize data into a cookie header. * * Serialize the a name value pair into a cookie string suitable for * http headers. An optional options object specified cookie parameters. * * serialize('foo', 'bar', { httpOnly: true }) * => "foo=bar; httpOnly" * * @param {string} name * @param {string} val * @param {object} [options] * @return {string} * @public */ function serialize(name, val, options) { var opt = options || {}; var enc = opt.encode || encode; if (typeof enc !== 'function') { throw new TypeError('option encode is invalid'); } if (!fieldContentRegExp.test(name)) { throw new TypeError('argument name is invalid'); } var value = enc(val); if (value && !fieldContentRegExp.test(value)) { throw new TypeError('argument val is invalid'); } var str = name + '=' + value; if (null != opt.maxAge) { var maxAge = opt.maxAge - 0; if (isNaN(maxAge) || !isFinite(maxAge)) { throw new TypeError('option maxAge is invalid') } str += '; Max-Age=' + Math.floor(maxAge); } if (opt.domain) { if (!fieldContentRegExp.test(opt.domain)) { throw new TypeError('option domain is invalid'); } str += '; Domain=' + opt.domain; } if (opt.path) { if (!fieldContentRegExp.test(opt.path)) { throw new TypeError('option path is invalid'); } str += '; Path=' + opt.path; } if (opt.expires) { var expires = opt.expires; if (!isDate(expires) || isNaN(expires.valueOf())) { throw new TypeError('option expires is invalid'); } str += '; Expires=' + expires.toUTCString(); } if (opt.httpOnly) { str += '; HttpOnly'; } if (opt.secure) { str += '; Secure'; } if (opt.partitioned) { str += '; Partitioned'; } if (opt.priority) { var priority = typeof opt.priority === 'string' ? opt.priority.toLowerCase() : opt.priority; switch (priority) { case 'low': str += '; Priority=Low'; break case 'medium': str += '; Priority=Medium'; break case 'high': str += '; Priority=High'; break default: throw new TypeError('option priority is invalid') } } if (opt.sameSite) { var sameSite = typeof opt.sameSite === 'string' ? opt.sameSite.toLowerCase() : opt.sameSite; switch (sameSite) { case true: str += '; SameSite=Strict'; break; case 'lax': str += '; SameSite=Lax'; break; case 'strict': str += '; SameSite=Strict'; break; case 'none': str += '; SameSite=None'; break; default: throw new TypeError('option sameSite is invalid'); } } return str; } /** * URL-decode string value. Optimized to skip native call when no %. * * @param {string} str * @returns {string} */ function decode (str) { return str.indexOf('%') !== -1 ? decodeURIComponent(str) : str } /** * URL-encode value. * * @param {string} val * @returns {string} */ function encode (val) { return encodeURIComponent(val) } /** * Determine if value is a Date. * * @param {*} val * @private */ function isDate (val) { return __toString.call(val) === '[object Date]' || val instanceof Date } /** * Try decoding a string using a decoding function. * * @param {string} str * @param {function} decode * @private */ function tryDecode(str, decode) { try { return decode(str); } catch (e) { return str; } } return cookie; } var cookieExports = requireCookie(); var defaultParseOptions = { decodeValues: true, map: false, silent: false, split: "auto", // auto = split strings but not arrays }; function isForbiddenKey(key) { return typeof key !== "string" || key in {}; } function createNullObj() { return Object.create(null); } function isNonEmptyString(str) { return typeof str === "string" && !!str.trim(); } function parseString(setCookieValue, options) { var parts = setCookieValue.split(";").filter(isNonEmptyString); var nameValuePairStr = parts.shift(); var parsed = parseNameValuePair(nameValuePairStr); var name = parsed.name; var value = parsed.value; options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions; if (isForbiddenKey(name)) { return null; } try { value = options.decodeValues ? decodeURIComponent(value) : value; // decode cookie value } catch (e) { console.error( "set-cookie-parser: failed to decode cookie value. Set options.decodeValues=false to disable decoding.", e ); } var cookie = createNullObj(); cookie.name = name; cookie.value = value; parts.forEach(function (part) { var sides = part.split("="); var key = sides.shift().trimLeft().toLowerCase(); if (isForbiddenKey(key)) { return; } var value = sides.join("="); if (key === "expires") { cookie.expires = new Date(value); } else if (key === "max-age") { var n = parseInt(value, 10); if (!Number.isNaN(n)) cookie.maxAge = n; } else if (key === "secure") { cookie.secure = true; } else if (key === "httponly") { cookie.httpOnly = true; } else if (key === "samesite") { cookie.sameSite = value; } else if (key === "partitioned") { cookie.partitioned = true; } else if (key) { cookie[key] = value; } }); return cookie; } function parseNameValuePair(nameValuePairStr) { // Parses name-value-pair according to rfc6265bis draft var name = ""; var value = ""; var nameValueArr = nameValuePairStr.split("="); if (nameValueArr.length > 1) { name = nameValueArr.shift(); value = nameValueArr.join("="); // everything after the first =, joined by a "=" if there was more than one part } else { value = nameValuePairStr; } return { name: name, value: value }; } function parseSetCookie(input, options) { options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions; if (!input) { if (!options.map) { return []; } else { return createNullObj(); } } if (input.headers) { if (typeof input.headers.getSetCookie === "function") { // for fetch responses - they combine headers of the same type in the headers array, // but getSetCookie returns an uncombined array input = input.headers.getSetCookie(); } else if (input.headers["set-cookie"]) { // fast-path for node.js (which automatically normalizes header names to lower-case) input = input.headers["set-cookie"]; } else { // slow-path for other environments - see #25 var sch = input.headers[ Object.keys(input.headers).find(function (key) { return key.toLowerCase() === "set-cookie"; }) ]; // warn if called on a request-like object with a cookie header rather than a set-cookie header - see #34, 36 if (!sch && input.headers.cookie && !options.silent) { console.warn( "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning." ); } input = sch; } } var split = options.split; var isArray = Array.isArray(input); if (split === "auto") { split = !isArray; } if (!isArray) { input = [input]; } input = input.filter(isNonEmptyString); if (split) { input = input.map(splitCookiesString).flat(); } if (!options.map) { return input .map(function (str) { return parseString(str, options); }) .filter(Boolean); } else { var cookies = createNullObj(); return input.reduce(function (cookies, str) { var cookie = parseString(str, options); if (cookie && !isForbiddenKey(cookie.name)) { cookies[cookie.name] = cookie; } return cookies; }, cookies); } } /* Set-Cookie header field-values are sometimes comma joined in one string. This splits them without choking on commas that are within a single set-cookie field-value, such as in the Expires portion. This is uncommon, but explicitly allowed - see https://tools.ietf.org/html/rfc2616#section-4.2 Node.js does this for every header *except* set-cookie - see https://github.com/nodejs/node/blob/d5e363b77ebaf1caf67cd7528224b651c86815c1/lib/_http_incoming.js#L128 React Native's fetch does this for *every* header, including set-cookie. Based on: https://github.com/google/j2objc/commit/16820fdbc8f76ca0c33472810ce0cb03d20efe25 Credits to: https://github.com/tomball for original and https://github.com/chrusart for JavaScript implementation */ function splitCookiesString(cookiesString) { if (Array.isArray(cookiesString)) { return cookiesString; } if (typeof cookiesString !== "string") { return []; } var cookiesStrings = []; var pos = 0; var start; var ch; var lastComma; var nextStart; var cookiesSeparatorFound; function skipWhitespace() { while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) { pos += 1; } return pos < cookiesString.length; } function notSpecialChar() { ch = cookiesString.charAt(pos); return ch !== "=" && ch !== ";" && ch !== ","; } while (pos < cookiesString.length) { start = pos; cookiesSeparatorFound = false; while (skipWhitespace()) { ch = cookiesString.charAt(pos); if (ch === ",") { // ',' is a cookie separator if we have later first '=', not ';' or ',' lastComma = pos; pos += 1; skipWhitespace(); nextStart = pos; while (pos < cookiesString.length && notSpecialChar()) { pos += 1; } // currently special character if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") { // we found cookies separator cookiesSeparatorFound = true; // pos is inside the next cookie, so back up and return it. pos = nextStart; cookiesStrings.push(cookiesString.substring(start, lastComma)); start = pos; } else { // in param ',' or param separator ';', // we continue from that comma pos = lastComma + 1; } } else { pos += 1; } } if (!cookiesSeparatorFound || pos >= cookiesString.length) { cookiesStrings.push(cookiesString.substring(start, cookiesString.length)); } } return cookiesStrings; } // named export for CJS parseSetCookie.parseSetCookie = parseSetCookie; // for backwards compatibility parseSetCookie.parse = parseSetCookie; parseSetCookie.parseString = parseString; parseSetCookie.splitCookiesString = splitCookiesString; 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; 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 (browser) ; 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 (browser) ; 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 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}', ${uneval(encoded, replacer)})`; } } }; return try_serialize(data, (value) => 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) => stringify$1(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 = 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 = 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}', ${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] = 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 = stringify$1(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 = stringify$1(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":${stringify$1(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; }; } const value = Reflect.get(response2, key2, response2); if (value instanceof Function) { return Object.defineProperties( /** * @this {any} */ function() { return Reflect.apply(value, this === receiver ? response2 : this, arguments); }, { name: { value: value.name }, length: { value: value.length } } ); } return value; } }); 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 `