import { c as create_ssr_component, s as setContext, v as validate_component, m as missing_component, n as noop, a as safe_not_equal } from './chunks/ssr-7369fb3e.js';
let base = "";
let assets = base;
const initial = { base, assets };
function reset() {
base = initial.base;
assets = initial.assets;
}
let public_env = {};
function set_private_env(environment) {
}
function set_public_env(environment) {
public_env = environment;
}
function afterUpdate() {
}
const Root = create_ssr_component(($$result, $$props, $$bindings, slots) => {
let { stores } = $$props;
let { page } = $$props;
let { constructors } = $$props;
let { components = [] } = $$props;
let { form } = $$props;
let { data_0 = null } = $$props;
let { data_1 = null } = $$props;
{
setContext("__svelte__", stores);
}
afterUpdate(stores.page.notify);
if ($$props.stores === void 0 && $$bindings.stores && stores !== void 0)
$$bindings.stores(stores);
if ($$props.page === void 0 && $$bindings.page && page !== void 0)
$$bindings.page(page);
if ($$props.constructors === void 0 && $$bindings.constructors && constructors !== void 0)
$$bindings.constructors(constructors);
if ($$props.components === void 0 && $$bindings.components && components !== void 0)
$$bindings.components(components);
if ($$props.form === void 0 && $$bindings.form && form !== void 0)
$$bindings.form(form);
if ($$props.data_0 === void 0 && $$bindings.data_0 && data_0 !== void 0)
$$bindings.data_0(data_0);
if ($$props.data_1 === void 0 && $$bindings.data_1 && data_1 !== void 0)
$$bindings.data_1(data_1);
let $$settled;
let $$rendered;
do {
$$settled = true;
{
stores.page.set(page);
}
$$rendered = ` ${constructors[1] ? `${validate_component(constructors[0] || missing_component, "svelte:component").$$render(
$$result,
{ data: data_0, this: components[0] },
{
this: ($$value) => {
components[0] = $$value;
$$settled = false;
}
},
{
default: () => {
return `${validate_component(constructors[1] || missing_component, "svelte:component").$$render(
$$result,
{ data: data_1, form, this: components[1] },
{
this: ($$value) => {
components[1] = $$value;
$$settled = false;
}
},
{}
)}`;
}
}
)}` : `${validate_component(constructors[0] || missing_component, "svelte:component").$$render(
$$result,
{ data: data_0, form, this: components[0] },
{
this: ($$value) => {
components[0] = $$value;
$$settled = false;
}
},
{}
)}`} ${``}`;
} while (!$$settled);
return $$rendered;
});
const options = {
app_template_contains_nonce: 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,
track_server_fetches: false,
embedded: false,
env_public_prefix: "PUBLIC_",
env_private_prefix: "",
hooks: null,
// added lazily, via `get_hooks`
preload_strategy: "modulepreload",
root: Root,
service_worker: false,
templates: {
app: ({ head, body, assets: assets2, 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: "rrbcpm"
};
function get_hooks() {
return {};
}
/** @type {Record} */
const escaped = {
'<': '\\u003C',
'\\': '\\\\',
'\b': '\\b',
'\f': '\\f',
'\n': '\\n',
'\r': '\\r',
'\t': '\\t',
'\u2028': '\\u2028',
'\u2029': '\\u2029'
};
class DevalueError extends Error {
/**
* @param {string} message
* @param {string[]} keys
*/
constructor(message, keys) {
super(message);
this.name = 'DevalueError';
this.path = keys.join('');
}
}
/** @param {any} thing */
function is_primitive(thing) {
return Object(thing) !== thing;
}
const object_proto_names = /* @__PURE__ */ Object.getOwnPropertyNames(
Object.prototype
)
.sort()
.join('\0');
/** @param {any} thing */
function is_plain_object(thing) {
const proto = Object.getPrototypeOf(thing);
return (
proto === Object.prototype ||
proto === null ||
Object.getOwnPropertyNames(proto).sort().join('\0') === object_proto_names
);
}
/** @param {any} thing */
function get_type(thing) {
return Object.prototype.toString.call(thing).slice(8, -1);
}
/** @param {string} char */
function get_escaped_char(char) {
switch (char) {
case '"':
return '\\"';
case '<':
return '\\u003C';
case '\\':
return '\\\\';
case '\n':
return '\\n';
case '\r':
return '\\r';
case '\t':
return '\\t';
case '\b':
return '\\b';
case '\f':
return '\\f';
case '\u2028':
return '\\u2028';
case '\u2029':
return '\\u2029';
default:
return char < ' '
? `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`
: '';
}
}
/** @param {string} str */
function stringify_string(str) {
let result = '';
let last_pos = 0;
const len = str.length;
for (let i = 0; i < len; i += 1) {
const char = str[i];
const replacement = get_escaped_char(char);
if (replacement) {
result += str.slice(last_pos, i) + replacement;
last_pos = i + 1;
}
}
return `"${last_pos === 0 ? str : result + str.slice(last_pos)}"`;
}
const chars$1 = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
const unsafe_chars = /[<\b\f\n\r\t\0\u2028\u2029]/g;
const reserved =
/^(?:do|if|in|for|int|let|new|try|var|byte|case|char|else|enum|goto|long|this|void|with|await|break|catch|class|const|final|float|short|super|throw|while|yield|delete|double|export|import|native|return|switch|throws|typeof|boolean|default|extends|finally|package|private|abstract|continue|debugger|function|volatile|interface|protected|transient|implements|instanceof|synchronized)$/;
/**
* Turn a value into the JavaScript that creates an equivalent value
* @param {any} value
* @param {(value: any) => string | void} [replacer]
*/
function uneval(value, replacer) {
const counts = new Map();
/** @type {string[]} */
const keys = [];
const custom = new Map();
/** @param {any} thing */
function walk(thing) {
if (typeof thing === 'function') {
throw new DevalueError(`Cannot stringify a function`, keys);
}
if (!is_primitive(thing)) {
if (counts.has(thing)) {
counts.set(thing, counts.get(thing) + 1);
return;
}
counts.set(thing, 1);
if (replacer) {
const str = replacer(thing);
if (typeof str === 'string') {
custom.set(thing, str);
return;
}
}
const type = get_type(thing);
switch (type) {
case 'Number':
case 'BigInt':
case 'String':
case 'Boolean':
case 'Date':
case 'RegExp':
return;
case 'Array':
/** @type {any[]} */ (thing).forEach((value, i) => {
keys.push(`[${i}]`);
walk(value);
keys.pop();
});
break;
case 'Set':
Array.from(thing).forEach(walk);
break;
case 'Map':
for (const [key, value] of thing) {
keys.push(
`.get(${is_primitive(key) ? stringify_primitive$1(key) : '...'})`
);
walk(value);
keys.pop();
}
break;
default:
if (!is_plain_object(thing)) {
throw new DevalueError(
`Cannot stringify arbitrary non-POJOs`,
keys
);
}
if (Object.getOwnPropertySymbols(thing).length > 0) {
throw new DevalueError(
`Cannot stringify POJOs with symbolic keys`,
keys
);
}
for (const key in thing) {
keys.push(`.${key}`);
walk(thing[key]);
keys.pop();
}
}
}
}
walk(value);
const names = new Map();
Array.from(counts)
.filter((entry) => entry[1] > 1)
.sort((a, b) => b[1] - a[1])
.forEach((entry, i) => {
names.set(entry[0], get_name(i));
});
/**
* @param {any} thing
* @returns {string}
*/
function stringify(thing) {
if (names.has(thing)) {
return names.get(thing);
}
if (is_primitive(thing)) {
return stringify_primitive$1(thing);
}
if (custom.has(thing)) {
return custom.get(thing);
}
const type = get_type(thing);
switch (type) {
case 'Number':
case 'String':
case 'Boolean':
return `Object(${stringify(thing.valueOf())})`;
case 'RegExp':
return `new RegExp(${stringify_string(thing.source)}, "${
thing.flags
}")`;
case 'Date':
return `new Date(${thing.getTime()})`;
case 'Array':
const members = /** @type {any[]} */ (thing).map((v, i) =>
i in thing ? stringify(v) : ''
);
const tail = thing.length === 0 || thing.length - 1 in thing ? '' : ',';
return `[${members.join(',')}${tail}]`;
case 'Set':
case 'Map':
return `new ${type}([${Array.from(thing).map(stringify).join(',')}])`;
default:
const obj = `{${Object.keys(thing)
.map((key) => `${safe_key(key)}:${stringify(thing[key])}`)
.join(',')}}`;
const proto = Object.getPrototypeOf(thing);
if (proto === null) {
return Object.keys(thing).length > 0
? `Object.assign(Object.create(null),${obj})`
: `Object.create(null)`;
}
return obj;
}
}
const str = stringify(value);
if (names.size) {
/** @type {string[]} */
const params = [];
/** @type {string[]} */
const statements = [];
/** @type {string[]} */
const values = [];
names.forEach((name, thing) => {
params.push(name);
if (custom.has(thing)) {
values.push(/** @type {string} */ (custom.get(thing)));
return;
}
if (is_primitive(thing)) {
values.push(stringify_primitive$1(thing));
return;
}
const type = get_type(thing);
switch (type) {
case 'Number':
case 'String':
case 'Boolean':
values.push(`Object(${stringify(thing.valueOf())})`);
break;
case 'RegExp':
values.push(thing.toString());
break;
case 'Date':
values.push(`new Date(${thing.getTime()})`);
break;
case 'Array':
values.push(`Array(${thing.length})`);
/** @type {any[]} */ (thing).forEach((v, i) => {
statements.push(`${name}[${i}]=${stringify(v)}`);
});
break;
case 'Set':
values.push(`new Set`);
statements.push(
`${name}.${Array.from(thing)
.map((v) => `add(${stringify(v)})`)
.join('.')}`
);
break;
case 'Map':
values.push(`new Map`);
statements.push(
`${name}.${Array.from(thing)
.map(([k, v]) => `set(${stringify(k)}, ${stringify(v)})`)
.join('.')}`
);
break;
default:
values.push(
Object.getPrototypeOf(thing) === null ? 'Object.create(null)' : '{}'
);
Object.keys(thing).forEach((key) => {
statements.push(
`${name}${safe_prop(key)}=${stringify(thing[key])}`
);
});
}
});
statements.push(`return ${str}`);
return `(function(${params.join(',')}){${statements.join(
';'
)}}(${values.join(',')}))`;
} else {
return str;
}
}
/** @param {number} num */
function get_name(num) {
let name = '';
do {
name = chars$1[num % chars$1.length] + name;
num = ~~(num / chars$1.length) - 1;
} while (num >= 0);
return reserved.test(name) ? `${name}0` : name;
}
/** @param {string} c */
function escape_unsafe_char(c) {
return escaped[c] || c;
}
/** @param {string} str */
function escape_unsafe_chars(str) {
return str.replace(unsafe_chars, escape_unsafe_char);
}
/** @param {string} key */
function safe_key(key) {
return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key)
? key
: escape_unsafe_chars(JSON.stringify(key));
}
/** @param {string} key */
function safe_prop(key) {
return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key)
? `.${key}`
: `[${escape_unsafe_chars(JSON.stringify(key))}]`;
}
/** @param {any} thing */
function stringify_primitive$1(thing) {
if (typeof thing === 'string') return stringify_string(thing);
if (thing === void 0) return 'void 0';
if (thing === 0 && 1 / thing < 0) return '-0';
const str = String(thing);
if (typeof thing === 'number') return str.replace(/^(-)?0\./, '$1.');
if (typeof thing === 'bigint') return thing + 'n';
return str;
}
const UNDEFINED = -1;
const HOLE = -2;
const NAN = -3;
const POSITIVE_INFINITY = -4;
const NEGATIVE_INFINITY = -5;
const NEGATIVE_ZERO = -6;
/**
* Turn a value into a JSON string that can be parsed with `devalue.parse`
* @param {any} value
* @param {Record any>} [reducers]
*/
function stringify(value, reducers) {
/** @type {any[]} */
const stringified = [];
/** @type {Map} */
const indexes = new Map();
/** @type {Array<{ key: string, fn: (value: any) => any }>} */
const custom = [];
for (const key in reducers) {
custom.push({ key, fn: reducers[key] });
}
/** @type {string[]} */
const keys = [];
let p = 0;
/** @param {any} thing */
function flatten(thing) {
if (typeof thing === 'function') {
throw new DevalueError(`Cannot stringify a function`, keys);
}
if (indexes.has(thing)) return indexes.get(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;
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;
}
}
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':
str = `["Date","${thing.toISOString()}"]`;
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)}`;
}
str += ']';
break;
default:
if (!is_plain_object(thing)) {
throw new DevalueError(
`Cannot stringify arbitrary non-POJOs`,
keys
);
}
if (Object.getOwnPropertySymbols(thing).length > 0) {
throw new DevalueError(
`Cannot stringify POJOs with symbolic keys`,
keys
);
}
if (Object.getPrototypeOf(thing) === null) {
str = '["null"';
for (const key in thing) {
keys.push(`.${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(`.${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);
}
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.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} str
* @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 setCookie = {exports: {}};
var hasRequiredSetCookie;
function requireSetCookie () {
if (hasRequiredSetCookie) return setCookie.exports;
hasRequiredSetCookie = 1;
var defaultParseOptions = {
decodeValues: true,
map: false,
silent: false,
};
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;
try {
value = options.decodeValues ? decodeURIComponent(value) : value; // decode cookie value
} catch (e) {
console.error(
"set-cookie-parser encountered an error while decoding a cookie with value '" +
value +
"'. Set options.decodeValues to false to disable this feature.",
e
);
}
var cookie = {
name: name,
value: value,
};
parts.forEach(function (part) {
var sides = part.split("=");
var key = sides.shift().trimLeft().toLowerCase();
var value = sides.join("=");
if (key === "expires") {
cookie.expires = new Date(value);
} else if (key === "max-age") {
cookie.maxAge = parseInt(value, 10);
} else if (key === "secure") {
cookie.secure = true;
} else if (key === "httponly") {
cookie.httpOnly = true;
} else if (key === "samesite") {
cookie.sameSite = value;
} else {
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 parse(input, options) {
options = options
? Object.assign({}, defaultParseOptions, options)
: defaultParseOptions;
if (!input) {
if (!options.map) {
return [];
} else {
return {};
}
}
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;
}
}
if (!Array.isArray(input)) {
input = [input];
}
options = options
? Object.assign({}, defaultParseOptions, options)
: defaultParseOptions;
if (!options.map) {
return input.filter(isNonEmptyString).map(function (str) {
return parseString(str, options);
});
} else {
var cookies = {};
return input.filter(isNonEmptyString).reduce(function (cookies, str) {
var cookie = parseString(str, options);
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;
}
setCookie.exports = parse;
setCookie.exports.parse = parse;
setCookie.exports.parseString = parseString;
setCookie.exports.splitCookiesString = splitCookiesString;
return setCookie.exports;
}
var setCookieExports = requireSetCookie();
const DEV = false;
const SVELTE_KIT_ASSETS = "/_svelte_kit_assets";
const ENDPOINT_METHODS = /* @__PURE__ */ new Set([
"GET",
"POST",
"PUT",
"PATCH",
"DELETE",
"OPTIONS",
"HEAD"
]);
const PAGE_METHODS = /* @__PURE__ */ new Set(["GET", "POST", "HEAD"]);
function negotiate(accept, types) {
const parts = [];
accept.split(",").forEach((str, i) => {
const match = /([^/]+)\/([^;]+)(?:;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"
);
}
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;
}
}
class ActionFailure {
/**
* @param {number} status
* @param {T} [data]
*/
constructor(status, data) {
this.status = status;
this.data = data;
}
}
function exec(match, params, matchers) {
const result = {};
const values = match.slice(1);
let buffered = 0;
for (let i = 0; i < params.length; i += 1) {
const param = params[i];
let value = values[i - buffered];
if (param.chained && param.rest && buffered) {
value = values.slice(i - buffered, i + 1).filter((s2) => s2).join("/");
buffered = 0;
}
if (value === void 0) {
if (param.rest)
result[param.name] = "";
continue;
}
if (!param.matcher || matchers[param.matcher](value)) {
result[param.name] = value;
const next_param = params[i + 1];
const next_value = values[i + 1];
if (next_param && !next_param.rest && next_param.optional && next_value && param.chained) {
buffered = 0;
}
continue;
}
if (param.optional && param.chained) {
buffered++;
continue;
}
return;
}
if (buffered)
return;
return result;
}
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`);
}
return new HttpError(status, body);
}
function json(data, init2) {
const body = JSON.stringify(data);
const headers = new Headers(init2?.headers);
if (!headers.has("content-length")) {
headers.set("content-length", encoder$3.encode(body).byteLength.toString());
}
if (!headers.has("content-type")) {
headers.set("content-type", "application/json");
}
return new Response(body, {
...init2,
headers
});
}
const encoder$3 = new TextEncoder();
function text(body, init2) {
const headers = new Headers(init2?.headers);
if (!headers.has("content-length")) {
const encoded = encoder$3.encode(body);
headers.set("content-length", encoded.byteLength.toString());
return new Response(encoded, {
...init2,
headers
});
}
return new Response(body, {
...init2,
headers
});
}
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('../runtime/control.js').Redirect | import('../runtime/control.js').HttpError | Error} */
error2
);
}
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 = Array.from(ENDPOINT_METHODS).filter((method) => method in mod);
if ("GET" in mod || "HEAD" in mod)
allowed.push("HEAD");
return allowed;
}
function static_error_page(options2, status, message) {
let page = options2.templates.error({ status, message });
return text(page, {
headers: { "content-type": "text/html; charset=utf-8" },
status
});
}
async function handle_fatal_error(event, options2, error2) {
error2 = error2 instanceof HttpError ? error2 : coalesce_to_error(error2);
const status = error2 instanceof HttpError ? error2.status : 500;
const body = await handle_error_and_jsonify(event, options2, error2);
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(options2, status, body.message);
}
async function handle_error_and_jsonify(event, options2, error2) {
if (error2 instanceof HttpError) {
return error2.body;
} else {
return await options2.hooks.handleError({ error: error2, event }) ?? {
message: event.route.id != null ? "Internal Error" : "Not Found"
};
}
}
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} (data${error2.path})`;
}
if (error2.path === "") {
return `Data returned from \`load\` while rendering ${event.route.id} is not a plain object`;
}
return error2.message;
}
function stringify_uses(node) {
const uses = [];
if (node.uses && node.uses.dependencies.size > 0) {
uses.push(`"dependencies":${JSON.stringify(Array.from(node.uses.dependencies))}`);
}
if (node.uses && node.uses.params.size > 0) {
uses.push(`"params":${JSON.stringify(Array.from(node.uses.params))}`);
}
if (node.uses?.parent)
uses.push('"parent":1');
if (node.uses?.route)
uses.push('"route":1');
if (node.uses?.url)
uses.push('"url":1');
return `"uses":{${uses.join(",")}}`;
}
async function render_endpoint(event, mod, state) {
const method = (
/** @type {import('types').HttpMethod} */
event.request.method
);
let handler = mod[method] || mod.fallback;
if (method === "HEAD" && mod.GET && !mod.HEAD) {
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 && !prerender) {
if (state.depth > 0) {
throw new Error(`${event.route.id} is not prerenderable`);
} else {
return new Response(void 0, { status: 204 });
}
}
try {
let response = await 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) {
response = new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: new Headers(response.headers)
});
response.headers.set("x-sveltekit-prerender", String(prerender));
}
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 } = event.request;
if (ENDPOINT_METHODS.has(method) && !PAGE_METHODS.has(method)) {
return true;
}
if (method === "POST" && headers.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
);
}
function normalize_path(path, trailing_slash) {
if (path === "/" || trailing_slash === "ignore")
return path;
if (trailing_slash === "never") {
return path.endsWith("/") ? path.slice(0, -1) : path;
} else if (trailing_slash === "always" && !path.endsWith("/")) {
return path + "/";
}
return path;
}
function decode_pathname(pathname) {
return pathname.split("%25").map(decodeURI).join("%25");
}
function decode_params(params) {
for (const key2 in params) {
params[key2] = decodeURIComponent(params[key2]);
}
return params;
}
const tracked_url_properties = (
/** @type {const} */
[
"href",
"pathname",
"search",
"searchParams",
"toString",
"toJSON"
]
);
function make_trackable(url, callback) {
const tracked = new URL(url);
for (const property of tracked_url_properties) {
Object.defineProperty(tracked, property, {
get() {
callback();
return url[property];
},
enumerable: true,
configurable: true
});
}
{
tracked[Symbol.for("nodejs.util.inspect.custom")] = (depth, opts, inspect) => {
return inspect(url, opts);
};
}
disable_hash(tracked);
return tracked;
}
function disable_hash(url) {
allow_nodejs_console_log(url);
Object.defineProperty(url, "hash", {
get() {
throw new Error(
"Cannot access event.url.hash. Consider using `$page.url.hash` inside a component instead"
);
}
});
}
function disable_search(url) {
allow_nodejs_console_log(url);
for (const property of ["search", "searchParams"]) {
Object.defineProperty(url, property, {
get() {
throw new Error(`Cannot access url.${property} on a page with prerendering enabled`);
}
});
}
}
function allow_nodejs_console_log(url) {
{
url[Symbol.for("nodejs.util.inspect.custom")] = (depth, opts, inspect) => {
return inspect(new URL(url), opts);
};
}
}
const DATA_SUFFIX = "/__data.json";
function has_data_suffix(pathname) {
return pathname.endsWith(DATA_SUFFIX);
}
function add_data_suffix(pathname) {
return pathname.replace(/\/$/, "") + DATA_SUFFIX;
}
function strip_data_suffix(pathname) {
return pathname.slice(0, -DATA_SUFFIX.length);
}
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, options2, server) {
const actions = server?.actions;
if (!actions) {
const no_actions_error = error(405, "POST method not allowed. No actions exist for this page");
return action_json(
{
type: "error",
error: await handle_error_and_jsonify(event, 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, actions);
if (false)
;
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
)
});
} 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
)
});
}
} 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, options2, check_incorrect_fail_use(err))
},
{
status: err instanceof HttpError ? err.status : 500
}
);
}
}
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, 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: error(405, "POST method not allowed. No actions exist for this page")
};
}
check_named_default_separate(actions);
try {
const data = await call_action(event, actions);
if (false)
;
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://kit.svelte.dev/docs/form-actions#named-actions"
);
}
}
async function call_action(event, 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 Error(`No action with name '${name}' found`);
}
if (!is_form_content_type(event.request)) {
throw new Error(
`Actions expect form-encoded data (received ${event.request.headers.get("content-type")})`
);
}
return action(event);
}
function uneval_action_response(data, route_id) {
return try_deserialize(data, uneval, route_id);
}
function stringify_action_response(data, route_id) {
return try_deserialize(data, stringify, route_id);
}
function try_deserialize(data, fn, route_id) {
try {
return fn(data);
} catch (e) {
const error2 = (
/** @type {any} */
e
);
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;
}
}
async function unwrap_promises(object) {
for (const key2 in object) {
if (typeof object[key2]?.then === "function") {
return Object.fromEntries(
await Promise.all(Object.entries(object).map(async ([key3, value]) => [key3, await value]))
);
}
}
return object;
}
const INVALIDATED_PARAM = "x-sveltekit-invalidated";
const TRAILING_SLASH_PARAM = "x-sveltekit-trailing-slash";
async function load_server_data({
event,
state,
node,
parent,
// TODO 2.0: Remove this
track_server_fetches
}) {
if (!node?.server)
return null;
const uses = {
dependencies: /* @__PURE__ */ new Set(),
params: /* @__PURE__ */ new Set(),
parent: false,
route: false,
url: false
};
const url = make_trackable(event.url, () => {
uses.url = true;
});
if (state.prerendering) {
disable_search(url);
}
const result = await node.server.load?.call(null, {
...event,
fetch: (info, init2) => {
const url2 = new URL(info instanceof Request ? info.url : info, event.url);
if (track_server_fetches) {
uses.dependencies.add(url2.href);
}
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) => {
uses.params.add(key2);
return target[
/** @type {string} */
key2
];
}
}),
parent: async () => {
uses.parent = true;
return parent();
},
route: new Proxy(event.route, {
get: (target, key2) => {
uses.route = true;
return target[
/** @type {'id'} */
key2
];
}
}),
url
});
const data = result ? await unwrap_promises(result) : null;
return {
type: "data",
data,
uses,
slash: node.server.trailingSlash
};
}
async function load_data({
event,
fetched,
node,
parent,
server_data_promise,
state,
resolve_opts,
csr
}) {
const server_data_node = await server_data_promise;
if (!node?.universal?.load) {
return server_data_node?.data ?? null;
}
const result = await node.universal.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
});
const data = result ? await unwrap_promises(result) : null;
return data;
}
function create_universal_fetch(event, state, fetched, csr, resolve_opts) {
return 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 {
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`
);
}
}
}
const proxy = new Proxy(response, {
get(response2, key2, _receiver) {
async function text2() {
const body = await response2.text();
if (!body || typeof body === "string") {
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: body,
response: response2
});
}
if (dependency) {
dependency.body = body;
}
return body;
}
if (key2 === "arrayBuffer") {
return async () => {
const buffer = await response2.arrayBuffer();
if (dependency) {
dependency.body = new Uint8Array(buffer);
}
return buffer;
};
}
if (key2 === "text") {
return text2;
}
if (key2 === "json") {
return async () => {
return JSON.parse(await text2());
};
}
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://kit.svelte.dev/docs/hooks#server-hooks-handle (at ${event.route.id})`
);
}
}
return value;
};
}
return proxy;
};
}
async function stream_to_string(stream) {
let result = "";
const reader = stream.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
result += decoder.decode(value);
}
return result;
}
const subscriber_queue = [];
function readable(value, start) {
return {
subscribe: writable(value, start).subscribe
};
}
function writable(value, start = noop) {
let stop;
const subscribers = /* @__PURE__ */ new Set();
function set(new_value) {
if (safe_not_equal(value, new_value)) {
value = new_value;
if (stop) {
const run_queue = !subscriber_queue.length;
for (const subscriber of subscribers) {
subscriber[1]();
subscriber_queue.push(subscriber, value);
}
if (run_queue) {
for (let i = 0; i < subscriber_queue.length; i += 2) {
subscriber_queue[i][0](subscriber_queue[i + 1]);
}
subscriber_queue.length = 0;
}
}
}
}
function update(fn) {
set(fn(value));
}
function subscribe(run, invalidate = noop) {
const subscriber = [run, invalidate];
subscribers.add(subscriber);
if (subscribers.size === 1) {
stop = start(set, update) || noop;
}
run(value);
return () => {
subscribers.delete(subscriber);
if (subscribers.size === 0 && stop) {
stop();
stop = null;
}
};
}
return { set, update, subscribe };
}
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 escape_html_attr_dict = {
"&": "&",
'"': """
};
const escape_html_attr_regex = new RegExp(
// special characters
`[${Object.keys(escape_html_attr_dict).join("")}]|[\\ud800-\\udbff](?![\\udc00-\\udfff])|[\\ud800-\\udbff][\\udc00-\\udfff]|[\\udc00-\\udfff]`,
"g"
);
function escape_html_attr(str) {
const escaped_str = str.replace(escape_html_attr_regex, (match) => {
if (match.length === 2) {
return match;
}
return escape_html_attr_dict[match] ?? `${match.charCodeAt(0)};`;
});
return `"${escaped_str}"`;
}
const replacements = {
"<": "\\u003C",
"\u2028": "\\u2028",
"\u2029": "\\u2029"
};
const pattern = new RegExp(`[${Object.keys(replacements).join("")}]`, "g");
function serialize_data(fetched, filter, prerendering = false) {
const headers = {};
let cache_control = null;
let age = null;
let varyAny = false;
for (const [key2, value] of fetched.response.headers) {
if (filter(key2, value)) {
headers[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,
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_attr(fetched.url)}`
];
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 `