UNPKG

@kaifronsdal/transcript-viewer

Version:

A web-based viewer for AI conversation transcripts with rollback support

1,939 lines (1,721 loc) 150 kB
import { r as render, s as set, L as LEGACY_PROPS, g as get, f as flushSync, d as define_property, m as mutable_source, i as init_operations, a as get_first_child, C as COMMENT_NODE, H as HYDRATION_START, b as get_next_sibling, c as HYDRATION_ERROR, e as HYDRATION_END, h as hydration_failed, j as clear_text_content, k as array_from, l as component_root, n as is_passive_event, o as set_active_reaction, p as set_active_effect, q as is_array, t as active_effect, u as active_reaction, v as create_text, w as branch, x as push, y as setContext, z as pop, A as push$1, B as component_context, D as pop$1, E as BROWSER } from './chunks/index-CeukPVPf.js'; import { json, text } from '@sveltejs/kit'; import { HttpError, Redirect, SvelteKitError, ActionFailure } from '@sveltejs/kit/internal'; import { d as decode_pathname, a as decode_params, n as normalize_path, b as disable_search, v as validate_layout_server_exports, c as validate_layout_exports, e as validate_page_server_exports, f as validate_page_exports, r as resolve, m as make_trackable } from './chunks/exports-Cv9LZeD1.js'; import { r as readable, w as writable } from './chunks/index2-uppKP1uk.js'; let base = ""; let assets = base; const app_dir = "_app"; const initial = { base, assets }; function override(paths) { base = paths.base; assets = paths.assets; } function reset() { base = initial.base; assets = initial.assets; } let public_env = {}; let safe_public_env = {}; function set_public_env(environment) { public_env = environment; } function set_safe_public_env(environment) { safe_public_env = environment; } function hydration_mismatch(location) { { console.warn(`https://svelte.dev/e/hydration_mismatch`); } } let hydrating = false; function set_hydrating(value) { hydrating = value; } let hydrate_node; function set_hydrate_node(node) { if (node === null) { hydration_mismatch(); throw HYDRATION_ERROR; } return hydrate_node = node; } function hydrate_next() { return set_hydrate_node( /** @type {TemplateNode} */ get_next_sibling(hydrate_node) ); } const all_registered_events = /* @__PURE__ */ new Set(); const root_event_handles = /* @__PURE__ */ new Set(); function handle_event_propagation(event) { var handler_element = this; var owner_document = ( /** @type {Node} */ handler_element.ownerDocument ); var event_name = event.type; var path = event.composedPath?.() || []; var current_target = ( /** @type {null | Element} */ path[0] || event.target ); var path_idx = 0; var handled_at = event.__root; if (handled_at) { var at_idx = path.indexOf(handled_at); if (at_idx !== -1 && (handler_element === document || handler_element === /** @type {any} */ window)) { event.__root = handler_element; return; } var handler_idx = path.indexOf(handler_element); if (handler_idx === -1) { return; } if (at_idx <= handler_idx) { path_idx = at_idx; } } current_target = /** @type {Element} */ path[path_idx] || event.target; if (current_target === handler_element) return; define_property(event, "currentTarget", { configurable: true, get() { return current_target || owner_document; } }); var previous_reaction = active_reaction; var previous_effect = active_effect; set_active_reaction(null); set_active_effect(null); try { var throw_error; var other_errors = []; while (current_target !== null) { var parent_element = current_target.assignedSlot || current_target.parentNode || /** @type {any} */ current_target.host || null; try { var delegated = current_target["__" + event_name]; if (delegated != null && (!/** @type {any} */ current_target.disabled || // DOM could've been updated already by the time this is reached, so we check this as well // -> the target could not have been disabled because it emits the event in the first place event.target === current_target)) { if (is_array(delegated)) { var [fn, ...data] = delegated; fn.apply(current_target, [event, ...data]); } else { delegated.call(current_target, event); } } } catch (error) { if (throw_error) { other_errors.push(error); } else { throw_error = error; } } if (event.cancelBubble || parent_element === handler_element || parent_element === null) { break; } current_target = parent_element; } if (throw_error) { for (let error of other_errors) { queueMicrotask(() => { throw error; }); } throw throw_error; } } finally { event.__root = handler_element; delete event.currentTarget; set_active_reaction(previous_reaction); set_active_effect(previous_effect); } } function assign_nodes(start, end) { var effect = ( /** @type {Effect} */ active_effect ); if (effect.nodes_start === null) { effect.nodes_start = start; effect.nodes_end = end; } } function mount(component, options2) { return _mount(component, options2); } function hydrate(component, options2) { init_operations(); options2.intro = options2.intro ?? false; const target = options2.target; const was_hydrating = hydrating; const previous_hydrate_node = hydrate_node; try { var anchor = ( /** @type {TemplateNode} */ get_first_child(target) ); while (anchor && (anchor.nodeType !== COMMENT_NODE || /** @type {Comment} */ anchor.data !== HYDRATION_START)) { anchor = /** @type {TemplateNode} */ get_next_sibling(anchor); } if (!anchor) { throw HYDRATION_ERROR; } set_hydrating(true); set_hydrate_node( /** @type {Comment} */ anchor ); hydrate_next(); const instance = _mount(component, { ...options2, anchor }); if (hydrate_node === null || hydrate_node.nodeType !== COMMENT_NODE || /** @type {Comment} */ hydrate_node.data !== HYDRATION_END) { hydration_mismatch(); throw HYDRATION_ERROR; } set_hydrating(false); return ( /** @type {Exports} */ instance ); } catch (error) { if (error === HYDRATION_ERROR) { if (options2.recover === false) { hydration_failed(); } init_operations(); clear_text_content(target); set_hydrating(false); return mount(component, options2); } throw error; } finally { set_hydrating(was_hydrating); set_hydrate_node(previous_hydrate_node); } } const document_listeners = /* @__PURE__ */ new Map(); function _mount(Component, { target, anchor, props = {}, events, context, intro = true }) { init_operations(); var registered_events = /* @__PURE__ */ new Set(); var event_handle = (events2) => { for (var i = 0; i < events2.length; i++) { var event_name = events2[i]; if (registered_events.has(event_name)) continue; registered_events.add(event_name); var passive = is_passive_event(event_name); target.addEventListener(event_name, handle_event_propagation, { passive }); var n = document_listeners.get(event_name); if (n === void 0) { document.addEventListener(event_name, handle_event_propagation, { passive }); document_listeners.set(event_name, 1); } else { document_listeners.set(event_name, n + 1); } } }; event_handle(array_from(all_registered_events)); root_event_handles.add(event_handle); var component = void 0; var unmount2 = component_root(() => { var anchor_node = anchor ?? target.appendChild(create_text()); branch(() => { if (context) { push$1({}); var ctx = ( /** @type {ComponentContext} */ component_context ); ctx.c = context; } if (events) { props.$$events = events; } if (hydrating) { assign_nodes( /** @type {TemplateNode} */ anchor_node, null ); } component = Component(anchor_node, props) || {}; if (hydrating) { active_effect.nodes_end = hydrate_node; } if (context) { pop$1(); } }); return () => { for (var event_name of registered_events) { target.removeEventListener(event_name, handle_event_propagation); var n = ( /** @type {number} */ document_listeners.get(event_name) ); if (--n === 0) { document.removeEventListener(event_name, handle_event_propagation); document_listeners.delete(event_name); } else { document_listeners.set(event_name, n); } } root_event_handles.delete(event_handle); if (anchor_node !== anchor) { anchor_node.parentNode?.removeChild(anchor_node); } }; }); mounted_components.set(component, unmount2); return component; } let mounted_components = /* @__PURE__ */ new WeakMap(); function unmount(component, options2) { const fn = mounted_components.get(component); if (fn) { mounted_components.delete(component); return fn(options2); } return Promise.resolve(); } function asClassComponent$1(component) { return class extends Svelte4Component { /** @param {any} options */ constructor(options2) { super({ component, ...options2 }); } }; } class Svelte4Component { /** @type {any} */ #events; /** @type {Record<string, any>} */ #instance; /** * @param {ComponentConstructorOptions & { * component: any; * }} options */ constructor(options2) { var sources = /* @__PURE__ */ new Map(); var add_source = (key, value) => { var s = mutable_source(value, false, false); sources.set(key, s); return s; }; const props = new Proxy( { ...options2.props || {}, $$events: {} }, { get(target, prop) { return get(sources.get(prop) ?? add_source(prop, Reflect.get(target, prop))); }, has(target, prop) { if (prop === LEGACY_PROPS) return true; get(sources.get(prop) ?? add_source(prop, Reflect.get(target, prop))); return Reflect.has(target, prop); }, set(target, prop, value) { set(sources.get(prop) ?? add_source(prop, value), value); return Reflect.set(target, prop, value); } } ); this.#instance = (options2.hydrate ? hydrate : mount)(options2.component, { target: options2.target, anchor: options2.anchor, props, context: options2.context, intro: options2.intro ?? false, recover: options2.recover }); if (!options2?.props?.$$host || options2.sync === false) { flushSync(); } this.#events = props.$$events; for (const key of Object.keys(this.#instance)) { if (key === "$set" || key === "$destroy" || key === "$on") continue; define_property(this, key, { get() { return this.#instance[key]; }, /** @param {any} value */ set(value) { this.#instance[key] = value; }, enumerable: true }); } this.#instance.$set = /** @param {Record<string, any>} next */ (next) => { Object.assign(props, next); }; this.#instance.$destroy = () => { unmount(this.#instance); }; } /** @param {Record<string, any>} props */ $set(props) { this.#instance.$set(props); } /** * @param {string} event * @param {(...args: any[]) => any} callback * @returns {any} */ $on(event, callback) { this.#events[event] = this.#events[event] || []; const cb = (...args) => callback.call(this, ...args); this.#events[event].push(cb); return () => { this.#events[event] = this.#events[event].filter( /** @param {any} fn */ (fn) => fn !== cb ); }; } $destroy() { this.#instance.$destroy(); } } let read_implementation = null; function set_read_implementation(fn) { read_implementation = fn; } function asClassComponent(component) { const component_constructor = asClassComponent$1(component); const _render = (props, { context } = {}) => { const result = render(component, { props, context }); return { css: { code: "", map: null }, head: result.head, html: result.body }; }; component_constructor.render = _render; return component_constructor; } function Root($$payload, $$props) { push(); let { stores, page, constructors, components = [], form, data_0 = null, data_1 = null } = $$props; { setContext("__svelte__", stores); } { stores.page.set(page); } const Pyramid_1 = constructors[1]; if (constructors[1]) { $$payload.out += "<!--[-->"; const Pyramid_0 = constructors[0]; $$payload.out += `<!---->`; Pyramid_0($$payload, { data: data_0, form, children: ($$payload2) => { $$payload2.out += `<!---->`; Pyramid_1($$payload2, { data: data_1, form }); $$payload2.out += `<!---->`; }, $$slots: { default: true } }); $$payload.out += `<!---->`; } else { $$payload.out += "<!--[!-->"; const Pyramid_0 = constructors[0]; $$payload.out += `<!---->`; Pyramid_0($$payload, { data: data_0, form }); $$payload.out += `<!---->`; } $$payload.out += `<!--]--> `; { $$payload.out += "<!--[!-->"; } $$payload.out += `<!--]-->`; pop(); } const root = asClassComponent(Root); 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, 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, templates: { app: ({ head, body, assets: assets2, nonce, env }) => '<!doctype html>\n<html lang="en">\n <head>\n <meta charset="utf-8" />\n <title>Petri Transcript Viewer</title>\n <link rel="icon" type="image/x-icon" href="' + assets2 + '/favicon.ico" />\n <link rel="icon" type="image/png" sizes="16x16" href="' + assets2 + '/favicon-16x16.png" />\n <link rel="icon" type="image/png" sizes="32x32" href="' + assets2 + '/favicon.png" />\n <link rel="icon" type="image/png" sizes="96x96" href="' + assets2 + '/favicon-96x96.png" />\n <link rel="apple-touch-icon" sizes="180x180" href="' + assets2 + '/apple-touch-icon.png" />\n <meta name="viewport" content="width=device-width, initial-scale=1" />\n ' + head + '\n </head>\n <body data-sveltekit-preload-data="hover">\n <div style="display: contents">' + body + "</div>\n </body>\n</html>\n", error: ({ status, message }) => '<!doctype html>\n<html lang="en">\n <head>\n <meta charset="utf-8" />\n <title>' + message + `</title> <style> body { --bg: white; --fg: #222; --divider: #ccc; background: var(--bg); color: var(--fg); font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; } .error { display: flex; align-items: center; max-width: 32rem; margin: 0 1rem; } .status { font-weight: 200; font-size: 3rem; line-height: 1; position: relative; top: -0.05rem; } .message { border-left: 1px solid var(--divider); padding: 0 0 0 1rem; margin: 0 0 0 1rem; min-height: 2.5rem; display: flex; align-items: center; } .message h1 { font-weight: 400; font-size: 1em; margin: 0; } @media (prefers-color-scheme: dark) { body { --bg: #222; --fg: #ddd; --divider: #666; } } </style> </head> <body> <div class="error"> <span class="status">` + status + '</span>\n <div class="message">\n <h1>' + message + "</h1>\n </div>\n </div>\n </body>\n</html>\n" }, version_hash: "wb0av3" }; async function get_hooks() { let handle; let handleFetch; let handleError; let init; ({ handle, handleFetch, handleError, init } = await import('./chunks/hooks.server-UzO6P2GS.js')); let reroute; let transport; return { handle, handleFetch, handleError, init, reroute, transport }; } /** @type {Record<string, string>} */ 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)}"`; } /** @param {Record<string | symbol, any>} object */ function enumerable_symbols(object) { return Object.getOwnPropertySymbols(object).filter( (symbol) => Object.getOwnPropertyDescriptor(object, symbol).enumerable ); } const is_identifier = /^[a-zA-Z_$][a-zA-Z_$0-9]*$/; /** @param {string} key */ function stringify_key(key) { return is_identifier.test(key) ? '.' + key : '[' + JSON.stringify(key) + ']'; } 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; case "Int8Array": case "Uint8Array": case "Uint8ClampedArray": case "Int16Array": case "Uint16Array": case "Int32Array": case "Uint32Array": case "Float32Array": case "Float64Array": case "BigInt64Array": case "BigUint64Array": return; case "ArrayBuffer": return; default: if (!is_plain_object(thing)) { throw new DevalueError( `Cannot stringify arbitrary non-POJOs`, keys ); } if (enumerable_symbols(thing).length > 0) { throw new DevalueError( `Cannot stringify POJOs with symbolic keys`, keys ); } for (const key in thing) { keys.push(stringify_key(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(',')}])`; 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; return `new ${type}([${typedArray.toString()}])`; } case "ArrayBuffer": { const ui8 = new Uint8Array(thing); return `new Uint8Array([${ui8.toString()}]).buffer`; } 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; } /** * 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); } const KEY_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /** * 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; /** * Turn a value into a JSON string that can be parsed with `devalue.parse` * @param {any} value * @param {Record<string, (value: any) => any>} [reducers] */ function stringify(value, reducers) { /** @type {any[]} */ const stringified = []; /** @type {Map<any, number>} */ 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 (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': const valid = !isNaN(thing.getDate()); str = `["Date","${valid ? 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)}`; 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; const base64 = encode64(typedArray.buffer); str = '["' + type + '","' + base64 + '"]'; break; } case "ArrayBuffer": { /** @type {ArrayBuffer} */ const arraybuffer = thing; const base64 = encode64(arraybuffer); str = `["ArrayBuffer","${base64}"]`; break; } default: if (!is_plain_object(thing)) { throw new DevalueError( `Cannot stringify arbitrary non-POJOs`, keys ); } if (enumerable_symbols(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(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); } 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 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 if (key === "partitioned") { cookie.partitioned = true; } 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]; } 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 = /*@__PURE__*/ requireSetCookie(); const SVELTE_KIT_ASSETS = "/_svelte_kit_assets"; const ENDPOINT_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]; const PAGE_METHODS = ["GET", "POST", "HEAD"]; function negotiate(accept, types) { const parts = []; accept.split(",").forEach((str, i) => { const match = /([^/ \t]+)\/([^; \t]+)[ \t]*(?:;[ \t]*q=([0-9.]+))?/.exec(str); if (match) { const [, type, subtype, q = "1"] = match; parts.push({ type, subtype, q: +q, i }); } }); parts.sort((a, b) => { if (a.q !== b.q) { return b.q - a.q; } if (a.subtype === "*" !== (b.subtype === "*")) { return a.subtype === "*" ? 1 : -1; } if (a.type === "*" !== (b.type === "*")) { return a.type === "*" ? 1 : -1; } return a.i - b.i; }); let accepted; let min_priority = Infinity; for (const mimetype of types) { const [type, subtype] = mimetype.split("/"); const priority = parts.findIndex( (part) => (part.type === type || part.type === "*") && (part.subtype === subtype || part.subtype === "*") ); if (priority !== -1 && priority < min_priority) { accepted = mimetype; min_priority = priority; } } return accepted; } function is_content_type(request, ...types) { const type = request.headers.get("content-type")?.split(";", 1)[0].trim() ?? ""; return types.includes(type.toLowerCase()); } function is_form_content_type(request) { return is_content_type( request, "application/x-www-form-urlencoded", "multipart/form-data", "text/plain" ); } let request_event = null; let als; import('node:async_hooks').then((hooks) => als = new hooks.AsyncLocalStorage()).catch(() => { }); function with_event(event, fn) { try { request_event = event; return als ? als.run(event, fn) : fn(); } finally { request_event = null; } } 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 = { "&": "&amp;", '"': "&quot;" // 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 = { "&": "&amp;", "<": "&lt;" }; 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 (