{"version":3,"file":"core-CPpjJT4b.js","sources":["../node_modules/sticky-module/esm/index.js","../node_modules/@ungap/with-resolvers/index.js","../node_modules/basic-devtools/esm/index.js","../node_modules/@webreflection/fetch/esm/index.js","../node_modules/@ungap/structured-clone/esm/types.js","../node_modules/@ungap/structured-clone/esm/deserialize.js","../node_modules/@ungap/structured-clone/esm/serialize.js","../node_modules/@ungap/structured-clone/esm/json.js","../node_modules/coincident/esm/channel.js","../node_modules/proxy-target/esm/types.js","../node_modules/proxy-target/esm/traps.js","../node_modules/coincident/esm/shared/traps.js","../node_modules/coincident/esm/bridge.js","../node_modules/coincident/esm/index.js","../node_modules/proxy-target/esm/utils.js","../node_modules/proxy-target/esm/array.js","../node_modules/gc-hook/esm/index.js","../node_modules/coincident/esm/shared/utils.js","../node_modules/coincident/esm/shared/main.js","../node_modules/coincident/esm/window/main.js","../node_modules/coincident/esm/window/thread.js","../node_modules/coincident/esm/shared/thread.js","../node_modules/coincident/esm/shared/worker.js","../node_modules/coincident/esm/window.js","../node_modules/polyscript/esm/worker/xworker.js","../node_modules/codedent/esm/index.js","../node_modules/plain-tag/esm/index.js","../node_modules/html-escaper/esm/index.js","../node_modules/polyscript/esm/interpreter/_io.js","../node_modules/polyscript/esm/utils.js","../node_modules/polyscript/esm/interpreter/_utils.js","../node_modules/polyscript/esm/interpreter/_python.js","../node_modules/polyscript/esm/python/mip.js","../node_modules/polyscript/esm/interpreter/micropython.js","../node_modules/polyscript/esm/zip.js","../node_modules/polyscript/esm/interpreter/pyodide.js","../node_modules/polyscript/esm/interpreter/ruby-wasm-wasi.js","../node_modules/polyscript/esm/interpreter/wasmoon.js","../node_modules/polyscript/esm/interpreter/webr.js","../node_modules/polyscript/esm/interpreters.js","../node_modules/polyscript/esm/toml.js","../node_modules/polyscript/esm/loader.js","../node_modules/to-json-callback/esm/index.js","../node_modules/polyscript/esm/hooks.js","../node_modules/polyscript/esm/worker/hook.js","../node_modules/polyscript/esm/worker/class.js","../node_modules/polyscript/esm/errors.js","../node_modules/polyscript/esm/worker/url.js","../node_modules/polyscript/esm/script-handler.js","../node_modules/polyscript/esm/listeners.js","../node_modules/polyscript/esm/xworker.js","../node_modules/polyscript/esm/custom.js","../node_modules/polyscript/esm/index.js","../src/types.js","../src/all-done.js","../src/plugins.js","../src/exceptions.js","../src/fetch.js","../src/config.js","../src/sync.js","../src/plugins-helper.js","../node_modules/type-checked-collections/esm/index.js","../src/stdlib.js","../src/stdlib/pyscript.js","../src/hooks.js","../src/core.js"],"sourcesContent":["/**\n * Allow leaking a module globally to help avoid conflicting exports\n * if the module might have been re-bundled in other projects.\n * @template T\n * @param {string} name the module name to save or retrieve\n * @param {T} value the module as value to save if not known\n * @param {globalThis} [global=globalThis] the reference where modules are saved where `globalThis` is the default\n * @returns {[T, boolean]} the passed `value` or the previous one as first entry, a boolean indicating if it was known or not\n */\nconst stickyModule = (name, value, global = globalThis) => {\n const symbol = Symbol.for(name);\n const known = symbol in global;\n return [\n known ?\n global[symbol] :\n Object.defineProperty(global, symbol, { value })[symbol],\n known\n ];\n};\n\nexport default stickyModule;\n","Promise.withResolvers || (Promise.withResolvers = function withResolvers() {\n var a, b, c = new this(function (resolve, reject) {\n a = resolve;\n b = reject;\n });\n return {resolve: a, reject: b, promise: c};\n});\n","/**\n * Given a CSS selector, returns the first matching node, if any.\n * @param {string} css the CSS selector to query\n * @param {Document | DocumentFragment | Element} [root] the optional parent node to query\n * @returns {Element?} the found element, if any\n */\nconst $ = (css, root = document) => root.querySelector(css);\n\n/**\n * Given a CSS selector, returns a list of all matching nodes.\n * @param {string} css the CSS selector to query\n * @param {Document | DocumentFragment | Element} [root] the optional parent node to query\n * @returns {Element[]} a list of found nodes\n */\nconst $$ = (css, root = document) => [...root.querySelectorAll(css)];\n\n/**\n * Given a XPath selector, returns a list of all matching nodes.\n * @param {string} path the XPath selector to evaluate\n * @param {Document | DocumentFragment | Element} [root] the optional parent node to query\n * @returns {Node[]} a list of found nodes (elements, attributes, text, comments)\n */\nconst $x = (path, root = document) => {\n const expression = (new XPathEvaluator).createExpression(path);\n const xpath = expression.evaluate(root, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE);\n const result = [];\n for (let i = 0, {snapshotLength} = xpath; i < snapshotLength; i++)\n result.push(xpath.snapshotItem(i));\n return result;\n};\n\nexport {$, $$, $x};\n","// a bit terser code than I usually write but it's 10 LOC within 80 cols\n// if you are struggling to follow the code you can replace 1-char\n// references around with the following one, hoping that helps :-)\n\n// d => descriptors\n// k => key\n// p => promise\n// r => response\n\nconst d = Object.getOwnPropertyDescriptors(Response.prototype);\n\nconst isFunction = value => typeof value === 'function';\n\nconst bypass = (p, k, { get, value }) => get || !isFunction(value) ?\n p.then(r => r[k]) :\n (...args) => p.then(r => r[k](...args));\n\nconst direct = (p, value) => isFunction(value) ? value.bind(p) : value;\n\nconst handler = {\n get: (p, k) => d.hasOwnProperty(k) ? bypass(p, k, d[k]) : direct(p, p[k])\n};\n\n/**\n * @param {RequestInfo | URL} input\n * @param {...RequestInit} init\n * @returns {Promise & Response}\n */\nexport default (input, ...init) => new Proxy(fetch(input, ...init), handler);\n","export const VOID = -1;\nexport const PRIMITIVE = 0;\nexport const ARRAY = 1;\nexport const OBJECT = 2;\nexport const DATE = 3;\nexport const REGEXP = 4;\nexport const MAP = 5;\nexport const SET = 6;\nexport const ERROR = 7;\nexport const BIGINT = 8;\n// export const SYMBOL = 9;\n","import {\n VOID, PRIMITIVE,\n ARRAY, OBJECT,\n DATE, REGEXP, MAP, SET,\n ERROR, BIGINT\n} from './types.js';\n\nconst env = typeof self === 'object' ? self : globalThis;\n\nconst deserializer = ($, _) => {\n const as = (out, index) => {\n $.set(index, out);\n return out;\n };\n\n const unpair = index => {\n if ($.has(index))\n return $.get(index);\n\n const [type, value] = _[index];\n switch (type) {\n case PRIMITIVE:\n case VOID:\n return as(value, index);\n case ARRAY: {\n const arr = as([], index);\n for (const index of value)\n arr.push(unpair(index));\n return arr;\n }\n case OBJECT: {\n const object = as({}, index);\n for (const [key, index] of value)\n object[unpair(key)] = unpair(index);\n return object;\n }\n case DATE:\n return as(new Date(value), index);\n case REGEXP: {\n const {source, flags} = value;\n return as(new RegExp(source, flags), index);\n }\n case MAP: {\n const map = as(new Map, index);\n for (const [key, index] of value)\n map.set(unpair(key), unpair(index));\n return map;\n }\n case SET: {\n const set = as(new Set, index);\n for (const index of value)\n set.add(unpair(index));\n return set;\n }\n case ERROR: {\n const {name, message} = value;\n return as(new env[name](message), index);\n }\n case BIGINT:\n return as(BigInt(value), index);\n case 'BigInt':\n return as(Object(BigInt(value)), index);\n }\n return as(new env[type](value), index);\n };\n\n return unpair;\n};\n\n/**\n * @typedef {Array} Record a type representation\n */\n\n/**\n * Returns a deserialized value from a serialized array of Records.\n * @param {Record[]} serialized a previously serialized value.\n * @returns {any}\n */\nexport const deserialize = serialized => deserializer(new Map, serialized)(0);\n","import {\n VOID, PRIMITIVE,\n ARRAY, OBJECT,\n DATE, REGEXP, MAP, SET,\n ERROR, BIGINT\n} from './types.js';\n\nconst EMPTY = '';\n\nconst {toString} = {};\nconst {keys} = Object;\n\nconst typeOf = value => {\n const type = typeof value;\n if (type !== 'object' || !value)\n return [PRIMITIVE, type];\n\n const asString = toString.call(value).slice(8, -1);\n switch (asString) {\n case 'Array':\n return [ARRAY, EMPTY];\n case 'Object':\n return [OBJECT, EMPTY];\n case 'Date':\n return [DATE, EMPTY];\n case 'RegExp':\n return [REGEXP, EMPTY];\n case 'Map':\n return [MAP, EMPTY];\n case 'Set':\n return [SET, EMPTY];\n }\n\n if (asString.includes('Array'))\n return [ARRAY, asString];\n\n if (asString.includes('Error'))\n return [ERROR, asString];\n\n return [OBJECT, asString];\n};\n\nconst shouldSkip = ([TYPE, type]) => (\n TYPE === PRIMITIVE &&\n (type === 'function' || type === 'symbol')\n);\n\nconst serializer = (strict, json, $, _) => {\n\n const as = (out, value) => {\n const index = _.push(out) - 1;\n $.set(value, index);\n return index;\n };\n\n const pair = value => {\n if ($.has(value))\n return $.get(value);\n\n let [TYPE, type] = typeOf(value);\n switch (TYPE) {\n case PRIMITIVE: {\n let entry = value;\n switch (type) {\n case 'bigint':\n TYPE = BIGINT;\n entry = value.toString();\n break;\n case 'function':\n case 'symbol':\n if (strict)\n throw new TypeError('unable to serialize ' + type);\n entry = null;\n break;\n case 'undefined':\n return as([VOID], value);\n }\n return as([TYPE, entry], value);\n }\n case ARRAY: {\n if (type)\n return as([type, [...value]], value);\n \n const arr = [];\n const index = as([TYPE, arr], value);\n for (const entry of value)\n arr.push(pair(entry));\n return index;\n }\n case OBJECT: {\n if (type) {\n switch (type) {\n case 'BigInt':\n return as([type, value.toString()], value);\n case 'Boolean':\n case 'Number':\n case 'String':\n return as([type, value.valueOf()], value);\n }\n }\n\n if (json && ('toJSON' in value))\n return pair(value.toJSON());\n\n const entries = [];\n const index = as([TYPE, entries], value);\n for (const key of keys(value)) {\n if (strict || !shouldSkip(typeOf(value[key])))\n entries.push([pair(key), pair(value[key])]);\n }\n return index;\n }\n case DATE:\n return as([TYPE, value.toISOString()], value);\n case REGEXP: {\n const {source, flags} = value;\n return as([TYPE, {source, flags}], value);\n }\n case MAP: {\n const entries = [];\n const index = as([TYPE, entries], value);\n for (const [key, entry] of value) {\n if (strict || !(shouldSkip(typeOf(key)) || shouldSkip(typeOf(entry))))\n entries.push([pair(key), pair(entry)]);\n }\n return index;\n }\n case SET: {\n const entries = [];\n const index = as([TYPE, entries], value);\n for (const entry of value) {\n if (strict || !shouldSkip(typeOf(entry)))\n entries.push(pair(entry));\n }\n return index;\n }\n }\n\n const {message} = value;\n return as([TYPE, {name: type, message}], value);\n };\n\n return pair;\n};\n\n/**\n * @typedef {Array} Record a type representation\n */\n\n/**\n * Returns an array of serialized Records.\n * @param {any} value a serializable value.\n * @param {{json?: boolean, lossy?: boolean}?} options an object with a `lossy` or `json` property that,\n * if `true`, will not throw errors on incompatible types, and behave more\n * like JSON stringify would behave. Symbol and Function will be discarded.\n * @returns {Record[]}\n */\n export const serialize = (value, {json, lossy} = {}) => {\n const _ = [];\n return serializer(!(json || lossy), !!json, new Map, _)(value), _;\n};\n","/*! (c) Andrea Giammarchi - ISC */\n\nimport {deserialize} from './deserialize.js';\nimport {serialize} from './serialize.js';\n\nconst {parse: $parse, stringify: $stringify} = JSON;\nconst options = {json: true, lossy: true};\n\n/**\n * Revive a previously stringified structured clone.\n * @param {string} str previously stringified data as string.\n * @returns {any} whatever was previously stringified as clone.\n */\nexport const parse = str => deserialize($parse(str));\n\n/**\n * Represent a structured clone value as string.\n * @param {any} any some clone-able value to stringify.\n * @returns {string} the value stringified.\n */\nexport const stringify = any => $stringify(serialize(any, options));\n","// ⚠️ AUTOMATICALLY GENERATED - DO NOT CHANGE\nexport const CHANNEL = '64e10b34-2bf7-4616-9668-f99de5aa046e';\n\nexport const MAIN = 'M' + CHANNEL;\nexport const THREAD = 'T' + CHANNEL;\n","export const ARRAY = 'array';\nexport const BIGINT = 'bigint';\nexport const BOOLEAN = 'boolean';\nexport const FUNCTION = 'function';\nexport const NULL = 'null';\nexport const NUMBER = 'number';\nexport const OBJECT = 'object';\nexport const STRING = 'string';\nexport const SYMBOL = 'symbol';\nexport const UNDEFINED = 'undefined';\n","export const APPLY = 'apply';\nexport const CONSTRUCT = 'construct';\nexport const DEFINE_PROPERTY = 'defineProperty';\nexport const DELETE_PROPERTY = 'deleteProperty';\nexport const GET = 'get';\nexport const GET_OWN_PROPERTY_DESCRIPTOR = 'getOwnPropertyDescriptor';\nexport const GET_PROTOTYPE_OF = 'getPrototypeOf';\nexport const HAS = 'has';\nexport const IS_EXTENSIBLE = 'isExtensible';\nexport const OWN_KEYS = 'ownKeys';\nexport const PREVENT_EXTENSION = 'preventExtensions';\nexport const SET = 'set';\nexport const SET_PROTOTYPE_OF = 'setPrototypeOf';\n","export * from 'proxy-target/traps';\nexport const DELETE = 'delete';\n","// The goal of this file is to normalize SAB\n// at least in main -> worker() use cases.\n// This still cannot possibly solve the sync\n// worker -> main() use case if SharedArrayBuffer\n// is not available or usable.\n\nimport {CHANNEL} from './channel.js';\n\nconst {isArray} = Array;\n\nlet {SharedArrayBuffer, window} = globalThis;\nlet {notify, wait, waitAsync} = Atomics;\nlet postPatched = null;\n\n// This is needed for some version of Firefox\nif (!waitAsync) {\n waitAsync = buffer => ({\n value: new Promise(onmessage => {\n // encodeURIComponent('onmessage=({data:b})=>(Atomics.wait(b,0),postMessage(0))')\n let w = new Worker('data:application/javascript,onmessage%3D(%7Bdata%3Ab%7D)%3D%3E(Atomics.wait(b%2C0)%2CpostMessage(0))');\n w.onmessage = onmessage;\n w.postMessage(buffer);\n })\n });\n}\n\n// Monkey-patch SharedArrayBuffer if needed\ntry {\n new SharedArrayBuffer(4);\n}\ncatch (_) {\n SharedArrayBuffer = ArrayBuffer;\n\n const ids = new WeakMap;\n // patch only main -> worker():async use case\n if (window) {\n const resolvers = new Map;\n const {prototype: {postMessage}} = Worker;\n\n const listener = event => {\n const details = event.data?.[CHANNEL];\n if (!isArray(details)) {\n event.stopImmediatePropagation();\n const { id, sb } = details;\n resolvers.get(id)(sb);\n }\n };\n\n postPatched = function (data, ...rest) {\n const details = data?.[CHANNEL];\n if (isArray(details)) {\n const [id, sb] = details;\n ids.set(sb, id);\n this.addEventListener('message', listener);\n }\n return postMessage.call(this, data, ...rest);\n };\n\n waitAsync = sb => ({\n value: new Promise(resolve => {\n resolvers.set(ids.get(sb), resolve);\n }).then(buff => {\n resolvers.delete(ids.get(sb));\n ids.delete(sb);\n for (let i = 0; i < buff.length; i++) sb[i] = buff[i];\n return 'ok';\n })\n });\n }\n else {\n const as = (id, sb) => ({[CHANNEL]: { id, sb }});\n\n notify = sb => {\n postMessage(as(ids.get(sb), sb));\n };\n\n addEventListener('message', event => {\n const details = event.data?.[CHANNEL];\n if (isArray(details)) {\n const [id, sb] = details;\n ids.set(sb, id);\n }\n });\n }\n}\n\nexport {SharedArrayBuffer, isArray, notify, postPatched, wait, waitAsync};\n","/*! (c) Andrea Giammarchi - ISC */\n\nimport {FUNCTION} from 'proxy-target/types';\n\nimport {CHANNEL} from './channel.js';\nimport {GET, HAS, SET} from './shared/traps.js';\n\nimport {SharedArrayBuffer, isArray, notify, postPatched, wait, waitAsync} from './bridge.js';\n\n// just minifier friendly for Blob Workers' cases\nconst {Int32Array, Map, Uint16Array} = globalThis;\n\n// common constants / utilities for repeated operations\nconst {BYTES_PER_ELEMENT: I32_BYTES} = Int32Array;\nconst {BYTES_PER_ELEMENT: UI16_BYTES} = Uint16Array;\n\nconst waitInterrupt = (sb, delay, handler) => {\n while (wait(sb, 0, 0, delay) === 'timed-out')\n handler();\n};\n\n// retain buffers to transfer\nconst buffers = new WeakSet;\n\n// retain either main threads or workers global context\nconst context = new WeakMap;\n\nconst syncResult = {value: {then: fn => fn()}};\n\n// used to generate a unique `id` per each worker `postMessage` \"transaction\"\nlet uid = 0;\n\n/**\n * @typedef {Object} Interrupt used to sanity-check interrupts while waiting synchronously.\n * @prop {function} [handler] a callback invoked every `delay` milliseconds.\n * @prop {number} [delay=42] define `handler` invokes in terms of milliseconds.\n */\n\n/**\n * Create once a `Proxy` able to orchestrate synchronous `postMessage` out of the box.\n * @param {globalThis | Worker} self the context in which code should run\n * @param {{parse: (serialized: string) => any, stringify: (serializable: any) => string, transform?: (value:any) => any, interrupt?: () => void | Interrupt}} [JSON] an optional `JSON` like interface to `parse` or `stringify` content with extra `transform` ability.\n * @returns {ProxyHandler | ProxyHandler}\n */\nconst coincident = (self, {parse = JSON.parse, stringify = JSON.stringify, transform, interrupt} = JSON) => {\n // create a Proxy once for the given context (globalThis or Worker instance)\n if (!context.has(self)) {\n // ensure no SAB gets a chance to pass through this call\n const sendMessage = postPatched || self.postMessage;\n // ensure the CHANNEL and data are posted correctly\n const post = (transfer, ...args) => sendMessage.call(self, {[CHANNEL]: args}, {transfer});\n\n const handler = typeof interrupt === FUNCTION ? interrupt : interrupt?.handler;\n const delay = interrupt?.delay || 42;\n const decoder = new TextDecoder('utf-16');\n\n // automatically uses sync wait (worker -> main)\n // or fallback to async wait (main -> worker)\n const waitFor = (isAsync, sb) => isAsync ?\n waitAsync(sb, 0) :\n ((handler ? waitInterrupt(sb, delay, handler) : wait(sb, 0)), syncResult);\n\n // prevent Harakiri https://github.com/WebReflection/coincident/issues/18\n let seppuku = false;\n\n context.set(self, new Proxy(new Map, {\n // there is very little point in checking prop in proxy for this very specific case\n // and I don't want to orchestrate a whole roundtrip neither, as stuff would fail\n // regardless if from Worker we access non existent Main callback, and vice-versa.\n // This is here mostly to guarantee that if such check is performed, at least the\n // get trap goes through and then it's up to developers guarantee they are accessing\n // stuff that actually exists elsewhere.\n [HAS]: (_, action) => typeof action === 'string' && !action.startsWith('_'),\n\n // worker related: get any utility that should be available on the main thread\n [GET]: (_, action) => action === 'then' ? null : ((...args) => {\n // transaction id\n const id = uid++;\n\n // first contact: just ask for how big the buffer should be\n // the value would be stored at index [1] while [0] is just control\n let sb = new Int32Array(new SharedArrayBuffer(I32_BYTES * 2));\n\n // if a transfer list has been passed, drop it from args\n let transfer = [];\n if (buffers.has(args.at(-1) || transfer))\n buffers.delete(transfer = args.pop());\n\n // ask for invoke with arguments and wait for it\n post(transfer, id, sb, action, transform ? args.map(transform) : args);\n\n // helps deciding how to wait for results\n const isAsync = self !== globalThis;\n\n // warn users about possible deadlock still allowing them\n // to explicitly `proxy.invoke().then(...)` without blocking\n let deadlock = 0;\n if (seppuku && isAsync)\n deadlock = setTimeout(console.warn, 1000, `💀🔒 - Possible deadlock if proxy.${action}(...args) is awaited`);\n\n return waitFor(isAsync, sb).value.then(() => {\n clearTimeout(deadlock);\n\n // commit transaction using the returned / needed buffer length\n const length = sb[1];\n\n // filter undefined results\n if (!length) return;\n\n // calculate the needed ui16 bytes length to store the result string\n const bytes = UI16_BYTES * length;\n\n // round up to the next amount of bytes divided by 4 to allow i32 operations\n sb = new Int32Array(new SharedArrayBuffer(bytes + (bytes % I32_BYTES)));\n\n // ask for results and wait for it\n post([], id, sb);\n return waitFor(isAsync, sb).value.then(() => parse(\n decoder.decode(new Uint16Array(sb.buffer).slice(0, length)))\n );\n });\n }),\n\n // main thread related: react to any utility a worker is asking for\n [SET](actions, action, callback) {\n const type = typeof callback;\n if (type !== FUNCTION)\n throw new Error(`Unable to assign ${action} as ${type}`);\n // lazy event listener and logic handling, triggered once by setters actions\n if (!actions.size) {\n // maps results by `id` as they are asked for\n const results = new Map;\n // add the event listener once (first defined setter, all others work the same)\n self.addEventListener('message', async (event) => {\n // grub the very same library CHANNEL; ignore otherwise\n const details = event.data?.[CHANNEL];\n if (isArray(details)) {\n // if early enough, avoid leaking data to other listeners\n event.stopImmediatePropagation();\n const [id, sb, ...rest] = details;\n let error;\n // action available: it must be defined/known on the main thread\n if (rest.length) {\n const [action, args] = rest;\n if (actions.has(action)) {\n seppuku = true;\n try {\n // await for result either sync or async and serialize it\n const result = await actions.get(action)(...args);\n if (result !== void 0) {\n const serialized = stringify(transform ? transform(result) : result);\n // store the result for \"the very next\" event listener call\n results.set(id, serialized);\n // communicate the required SharedArrayBuffer length out of the\n // resulting serialized string\n sb[1] = serialized.length;\n }\n }\n catch (_) {\n error = _;\n }\n finally {\n seppuku = false;\n }\n }\n // unknown action should be notified as missing on the main thread\n else {\n error = new Error(`Unsupported action: ${action}`);\n }\n // unlock the wait lock later on\n sb[0] = 1;\n }\n // no action means: get results out of the well known `id`\n // wait lock automatically unlocked here as no `0` value would\n // possibly ever land at index `0`\n else {\n const result = results.get(id);\n results.delete(id);\n // populate the SharedArrayBuffer with utf-16 chars code\n for (let ui16a = new Uint16Array(sb.buffer), i = 0; i < result.length; i++)\n ui16a[i] = result.charCodeAt(i);\n }\n // release te worker waiting either the length or the result\n notify(sb, 0);\n if (error) throw error;\n }\n });\n }\n // store this action callback allowing the setter in the process\n return !!actions.set(action, callback);\n }\n }));\n }\n return context.get(self);\n};\n\ncoincident.transfer = (...args) => (buffers.add(args), args);\n\nexport default coincident;\n","import { BIGINT, BOOLEAN, FUNCTION, NULL, NUMBER, OBJECT, STRING, SYMBOL, UNDEFINED } from './types.js';\n\nconst { isArray } = Array;\n\nexport { isArray };\n\nexport const invoke = value => /** @type {Function} */ (value)();\n\n/**\n * @template Value\n * @param {string} type\n * @param {Value} value\n * @returns {Value}\n */\nexport const reviver = (type, value) => value;\n\n/**\n * @template V\n * @typedef {[V]} Arr\n */\n\n/**\n * @template V\n * @typedef {() => V} Ctx\n */\n\n/**\n * @template T, V\n * @typedef {{t:T, v:V}} Obj\n */\n\n/**\n * @template V\n * @typedef {V extends bigint ? BIGINT : V extends boolean ? BOOLEAN : V extends null ? NULL : V extends number ? NUMBER : V extends string ? STRING : V extends symbol ? SYMBOL : V extends undefined ? UNDEFINED : V extends object ? OBJECT : never} TypeOf\n */\n\n/**\n * @template T, V\n * @param {T} t\n * @param {V} v\n * @returns {Obj}\n */\nexport const obj = (t, v) => ({t, v});\n\n/**\n * @template V\n * @param {V} value\n * @returns {Ctx}\n */\nexport const bound = value => Context.bind(value);\n\n/**\n * @template V, T\n * @param {V} value\n * @returns {V extends Ctx ? ReturnType : V}\n */\nexport const unbound = value => (\n typeof value === FUNCTION ? invoke(value) : value\n);\n\n// This is needed to unlock *both* apply and construct\n// traps otherwise one of these might fail.\n// The 'use strict' directive is needed to allow\n// also primitive types to be bound.\nfunction Context() {\n 'use strict';\n return this;\n}\n\n// TODO: is this really needed in here?\n// const { hasOwn } = Object;\n// const isConstructable = value => hasOwn(value, 'prototype');\n// const isFunction = value => typeof value === FUNCTION;\n","import { ARRAY, FUNCTION, NULL, OBJECT } from './types.js';\nimport { isArray, reviver, obj } from './utils.js';\n\nexport { bound, unbound } from './utils.js';\n\n/**\n * @template V\n * @typedef {import(\"./utils.js\").Arr} Arr\n */\n\n/**\n * @template T, V\n * @typedef {import(\"./utils.js\").Obj} Obj\n */\n\n/**\n * @template V\n * @typedef {import(\"./utils.js\").TypeOf} TypeOf\n */\n\n/**\n * @template W, T, V\n * @typedef {W extends Function ? W : W extends Arr ? W[0] : W extends Obj ? W[\"v\"] : never} ValueOf\n */\n\n/**\n * @template {string} T\n * @template V\n * @param {T} type\n * @param {V} value\n * @returns {T extends typeof ARRAY ? Arr : Obj}\n */\nexport const target = (type, value) =>\n// @see https://github.com/microsoft/TypeScript/issues/33014\n// @ts-ignore\n(\n type === ARRAY ?\n (/** @type {Arr} */ ([value])) :\n obj(type, value)\n);\n\n/**\n * @template W, T, V\n * @param {W} wrap\n * @param {typeof reviver} [revive]\n * @returns\n */\nexport const unwrap = (wrap, revive = reviver) => {\n /** @type {string} */\n let type = typeof wrap, value = wrap;\n if (type === OBJECT) {\n if (isArray(wrap)) {\n type = ARRAY;\n value = wrap.at(0);\n }\n else\n ({ t: type, v: value } = /** @type {Obj} */ (wrap));\n }\n return revive(type, /** @type {ValueOf} */ (value));\n};\n\nconst resolver = (type, value) => (\n type === FUNCTION ? value : target(type, value)\n);\n\n/**\n * @template V\n * @param {V} value\n * @param {Function} [resolve]\n * @returns {V extends Function ? V : V extends Array ? Arr : Obj, V>}\n */\nexport const wrap = (value, resolve = resolver) => {\n const type = value === null ? NULL : typeof value;\n return resolve(type === OBJECT && isArray(value) ? ARRAY : type, value);\n};\n","// (c) Andrea Giammarchi - ISC\n\nconst registry = new FinalizationRegistry(\n ([onGarbageCollected, held, debug]) => {\n if (debug) console.debug(`Held value ${String(held)} not relevant anymore`);\n onGarbageCollected(held);\n }\n);\n\nconst nullHandler = Object.create(null);\n\n/**\n * @template {unknown} H\n * @typedef {Object} GCHookOptions\n * @prop {boolean} [debug=false] if `true`, logs values once these can get collected.\n * @prop {ProxyHandler} [handler] optional proxy handler to use instead of the default one.\n * @prop {H} [return=H] if specified, overrides the returned proxy with its value.\n * @prop {unknown} [token=H] it's the held value by default, but it can be any other token except the returned value itself.\n */\n\n/**\n * @template {unknown} H\n * @param {H} hold the reference to hold behind the scene and passed along the callback once it triggers.\n * @param {(held:H) => void} onGarbageCollected the callback that will receive the held value once its wrapper or indirect reference is no longer needed.\n * @param {GCHookOptions} [options] an optional configuration object to change some default behavior.\n */\nexport const create = (\n hold,\n onGarbageCollected,\n { debug, handler, return: r, token = hold } = nullHandler\n) => {\n // if no reference to return is defined,\n // create a proxy for the held one and register that instead.\n /** @type {H} */\n const target = r || new Proxy(hold, handler || nullHandler);\n const args = [target, [onGarbageCollected, hold, !!debug]];\n if (token !== false) args.push(token);\n // register the target reference in a way that\n // the `onGarbageCollected(held)` callback will eventually notify.\n registry.register(...args);\n return target;\n};\n\n/**\n * If previously registered as either `token` or `hold` value, allow explicit removal of the entry in the registry.\n * @param {unknown} token the token used during registration. If no `token` was passed, this can be the same `hold` reference.\n * @returns {boolean} `true` if successfully unregistered.\n */\nexport const drop = token => registry.unregister(token);\n","import { target as tv, wrap } from 'proxy-target/array';\n\nimport {\n ARRAY,\n OBJECT,\n FUNCTION,\n BOOLEAN,\n NUMBER,\n STRING,\n UNDEFINED,\n BIGINT,\n SYMBOL,\n NULL,\n} from 'proxy-target/types';\n\nconst {\n defineProperty,\n deleteProperty,\n getOwnPropertyDescriptor,\n getPrototypeOf,\n isExtensible,\n ownKeys,\n preventExtensions,\n set,\n setPrototypeOf\n} = Reflect;\n\nconst { assign, create } = Object;\n\nexport const TypedArray = getPrototypeOf(Int8Array);\n\nexport {\n assign,\n create,\n defineProperty,\n deleteProperty,\n getOwnPropertyDescriptor,\n getPrototypeOf,\n isExtensible,\n ownKeys,\n preventExtensions,\n set,\n setPrototypeOf\n};\n\nexport const augment = (descriptor, how) => {\n const {get, set, value} = descriptor;\n if (get) descriptor.get = how(get);\n if (set) descriptor.set = how(set);\n if (value) descriptor.value = how(value);\n return descriptor;\n};\n\nexport const asEntry = transform => value => wrap(value, (type, value) => {\n switch (type) {\n case NULL:\n return tv(NULL, value);\n case OBJECT:\n if (value === globalThis)\n return tv(type, null);\n case ARRAY:\n case FUNCTION:\n return transform(type, value);\n case BOOLEAN:\n case NUMBER:\n case STRING:\n case UNDEFINED:\n case BIGINT:\n return tv(type, value);\n case SYMBOL: {\n // handle known symbols\n if (symbols.has(value))\n return tv(type, symbols.get(value));\n // handle `Symbol.for('...')` cases\n let key = Symbol.keyFor(value);\n if (key)\n return tv(type, `.${key}`);\n }\n }\n throw new TypeError(`Unable to handle this ${type}: ${String(value)}`);\n});\n\nconst symbols = new Map(\n ownKeys(Symbol)\n .filter(s => typeof Symbol[s] === SYMBOL)\n .map(s => [Symbol[s], s])\n);\n\nexport const symbol = value => {\n if (value.startsWith('.'))\n return Symbol.for(value.slice(1));\n for (const [symbol, name] of symbols) {\n if (name === value)\n return symbol;\n }\n};\n\nexport const transform = o => o;\n","import { target as tv, unwrap } from 'proxy-target/array';\nimport { create as createGCHook } from 'gc-hook';\n\nimport {\n ARRAY,\n OBJECT,\n FUNCTION,\n NUMBER,\n STRING,\n SYMBOL,\n UNDEFINED,\n} from 'proxy-target/types';\n\nimport {\n TypedArray,\n defineProperty,\n deleteProperty,\n getOwnPropertyDescriptor,\n getPrototypeOf,\n isExtensible,\n ownKeys,\n preventExtensions,\n set,\n setPrototypeOf,\n\n assign,\n create,\n augment,\n asEntry,\n symbol,\n transform\n} from './utils.js';\n\nimport {\n APPLY,\n CONSTRUCT,\n DEFINE_PROPERTY,\n DELETE_PROPERTY,\n GET,\n GET_OWN_PROPERTY_DESCRIPTOR,\n GET_PROTOTYPE_OF,\n HAS,\n IS_EXTENSIBLE,\n OWN_KEYS,\n PREVENT_EXTENSION,\n SET,\n SET_PROTOTYPE_OF,\n DELETE\n} from './traps.js';\n\nexport default (name, patch) => {\n const eventsHandler = patch && new WeakMap;\n\n // patch once main UI tread\n if (patch) {\n const { addEventListener } = EventTarget.prototype;\n // this should never be on the way as it's extremely light and fast\n // but it's necessary to allow \"preventDefault\" or other event invokes at distance\n defineProperty(EventTarget.prototype, 'addEventListener', {\n value(type, listener, ...options) {\n if (options.at(0)?.invoke) {\n if (!eventsHandler.has(this))\n eventsHandler.set(this, new Map);\n eventsHandler.get(this).set(type, [].concat(options[0].invoke));\n delete options[0].invoke;\n }\n return addEventListener.call(this, type, listener, ...options);\n }\n });\n }\n\n const handleEvent = patch && (event => {\n const {currentTarget, target, type} = event;\n for (const method of eventsHandler.get(currentTarget || target)?.get(type) || [])\n event[method]();\n });\n\n return function (thread, MAIN, THREAD, ...args) {\n let id = 0, $ = this?.transform || transform;\n const ids = new Map;\n const values = new Map;\n\n const {[THREAD]: __thread__} = thread;\n\n const global = args.length ? assign(create(globalThis), ...args) : globalThis;\n\n const result = asEntry((type, value) => {\n if (!ids.has(value)) {\n let sid;\n // a bit apocalyptic scenario but if this main runs forever\n // and the id does a whole int32 roundtrip we might have still\n // some reference dangling around\n while (values.has(sid = id++));\n ids.set(value, sid);\n values.set(sid, type === FUNCTION ? value : $(value));\n }\n return tv(type, ids.get(value));\n });\n\n const onGarbageCollected = value => {\n __thread__(DELETE, tv(STRING, value));\n };\n\n const asValue = (type, value) => {\n switch (type) {\n case OBJECT:\n if (value == null) return global;\n case ARRAY:\n if (typeof value === NUMBER) return values.get(value);\n if (!(value instanceof TypedArray)) {\n for (const key in value)\n value[key] = target(value[key]);\n }\n return value;\n case FUNCTION:\n if (typeof value === STRING) {\n const retained = values.get(value)?.deref();\n if (retained) return retained;\n const cb = function (...args) {\n if (patch && args.at(0) instanceof Event) handleEvent(...args);\n return __thread__(\n APPLY,\n tv(FUNCTION, value),\n result(this),\n args.map(result)\n );\n };\n values.set(value, new WeakRef(cb));\n return createGCHook(value, onGarbageCollected, {\n return: cb,\n token: false,\n });\n }\n return values.get(value);\n case SYMBOL:\n return symbol(value);\n }\n return value;\n };\n\n const target = entry => unwrap(entry, asValue);\n\n const trapsHandler = {\n [APPLY]: (target, thisArg, args) => result(target.apply(thisArg, args)),\n [CONSTRUCT]: (target, args) => result(new target(...args)),\n [DEFINE_PROPERTY]: (target, name, descriptor) => result(defineProperty(target, name, descriptor)),\n [DELETE_PROPERTY]: (target, name) => result(deleteProperty(target, name)),\n [GET_PROTOTYPE_OF]: target => result(getPrototypeOf(target)),\n [GET]: (target, name) => result(target[name]),\n [GET_OWN_PROPERTY_DESCRIPTOR]: (target, name) => {\n const descriptor = getOwnPropertyDescriptor(target, name);\n return descriptor ? tv(OBJECT, augment(descriptor, result)) : tv(UNDEFINED, descriptor);\n },\n [HAS]: (target, name) => result(name in target),\n [IS_EXTENSIBLE]: target => result(isExtensible(target)),\n [OWN_KEYS]: target => tv(ARRAY, ownKeys(target).map(result)),\n [PREVENT_EXTENSION]: target => result(preventExtensions(target)),\n [SET]: (target, name, value) => result(set(target, name, value)),\n [SET_PROTOTYPE_OF]: (target, proto) => result(setPrototypeOf(target, proto)),\n [DELETE](id) {\n ids.delete(values.get(id));\n values.delete(id);\n }\n };\n\n thread[MAIN] = (trap, entry, ...args) => {\n switch (trap) {\n case APPLY:\n args[0] = target(args[0]);\n args[1] = args[1].map(target);\n break;\n case CONSTRUCT:\n args[0] = args[0].map(target);\n break;\n case DEFINE_PROPERTY: {\n const [name, descriptor] = args;\n args[0] = target(name);\n const {get, set, value} = descriptor;\n if (get) descriptor.get = target(get);\n if (set) descriptor.set = target(set);\n if (value) descriptor.value = target(value);\n break;\n }\n default:\n args = args.map(target);\n break;\n }\n return trapsHandler[trap](target(entry), ...args);\n };\n\n return {\n proxy: thread,\n [name.toLowerCase()]: global,\n [`is${name}Proxy`]: () => false\n };\n };\n};\n","import main from '../shared/main.js';\n\nexport default main('Window', true);\n","import thread from '../shared/thread.js';\n\nexport default thread('Window');\n","import { target as tv, unwrap, bound, unbound } from 'proxy-target/array';\nimport { create as createGCHook } from 'gc-hook';\n\nimport {\n ARRAY,\n OBJECT,\n FUNCTION,\n NUMBER,\n STRING,\n SYMBOL,\n} from 'proxy-target/types';\n\nimport {\n TypedArray,\n augment,\n asEntry,\n symbol,\n transform,\n} from './utils.js';\n\nimport {\n APPLY,\n CONSTRUCT,\n DEFINE_PROPERTY,\n DELETE_PROPERTY,\n GET,\n GET_OWN_PROPERTY_DESCRIPTOR,\n GET_PROTOTYPE_OF,\n HAS,\n IS_EXTENSIBLE,\n OWN_KEYS,\n PREVENT_EXTENSION,\n SET,\n SET_PROTOTYPE_OF,\n DELETE\n} from './traps.js';\n\nexport default name => {\n let id = 0;\n const ids = new Map;\n const values = new Map;\n\n const __proxy__ = Symbol();\n\n return function (main, MAIN, THREAD) {\n const $ = this?.transform || transform;\n const { [MAIN]: __main__ } = main;\n\n const proxies = new Map;\n\n const onGarbageCollected = value => {\n proxies.delete(value);\n __main__(DELETE, argument(value));\n };\n\n const argument = asEntry(\n (type, value) => {\n if (__proxy__ in value)\n return unbound(value[__proxy__]);\n if (type === FUNCTION) {\n value = $(value);\n if (!values.has(value)) {\n let sid;\n // a bit apocalyptic scenario but if this thread runs forever\n // and the id does a whole int32 roundtrip we might have still\n // some reference dangling around\n while (values.has(sid = String(id++)));\n ids.set(value, sid);\n values.set(sid, value);\n }\n return tv(type, ids.get(value));\n }\n if (!(value instanceof TypedArray)) {\n value = $(value);\n for(const key in value)\n value[key] = argument(value[key]);\n }\n return tv(type, value);\n }\n );\n\n const register = (entry, type, value) => {\n const retained = proxies.get(value)?.deref();\n if (retained) return retained;\n const target = type === FUNCTION ? bound(entry) : entry;\n const proxy = new Proxy(target, proxyHandler);\n proxies.set(value, new WeakRef(proxy));\n return createGCHook(value, onGarbageCollected, {\n return: proxy,\n token: false,\n });\n };\n\n const fromEntry = entry => unwrap(entry, (type, value) => {\n switch (type) {\n case OBJECT:\n if (value === null) return globalThis;\n case ARRAY:\n return typeof value === NUMBER ? register(entry, type, value) : value;\n case FUNCTION:\n return typeof value === STRING ? values.get(value) : register(entry, type, value);\n case SYMBOL:\n return symbol(value);\n }\n return value;\n });\n\n const result = (TRAP, target, ...args) => fromEntry(__main__(TRAP, unbound(target), ...args));\n\n const proxyHandler = {\n [APPLY]: (target, thisArg, args) => result(APPLY, target, argument(thisArg), args.map(argument)),\n [CONSTRUCT]: (target, args) => result(CONSTRUCT, target, args.map(argument)),\n [DEFINE_PROPERTY]: (target, name, descriptor) => {\n const { get, set, value } = descriptor;\n if (typeof get === FUNCTION) descriptor.get = argument(get);\n if (typeof set === FUNCTION) descriptor.set = argument(set);\n if (typeof value === FUNCTION) descriptor.value = argument(value);\n return result(DEFINE_PROPERTY, target, argument(name), descriptor);\n },\n [DELETE_PROPERTY]: (target, name) => result(DELETE_PROPERTY, target, argument(name)),\n [GET_PROTOTYPE_OF]: target => result(GET_PROTOTYPE_OF, target),\n [GET]: (target, name) => name === __proxy__ ? target : result(GET, target, argument(name)),\n [GET_OWN_PROPERTY_DESCRIPTOR]: (target, name) => {\n const descriptor = result(GET_OWN_PROPERTY_DESCRIPTOR, target, argument(name));\n return descriptor && augment(descriptor, fromEntry);\n },\n [HAS]: (target, name) => name === __proxy__ || result(HAS, target, argument(name)),\n [IS_EXTENSIBLE]: target => result(IS_EXTENSIBLE, target),\n [OWN_KEYS]: target => result(OWN_KEYS, target).map(fromEntry),\n [PREVENT_EXTENSION]: target => result(PREVENT_EXTENSION, target),\n [SET]: (target, name, value) => result(SET, target, argument(name), argument(value)),\n [SET_PROTOTYPE_OF]: (target, proto) => result(SET_PROTOTYPE_OF, target, argument(proto)),\n };\n\n main[THREAD] = (trap, entry, ctx, args) => {\n switch (trap) {\n case APPLY:\n return fromEntry(entry).apply(fromEntry(ctx), args.map(fromEntry));\n case DELETE: {\n const id = fromEntry(entry);\n ids.delete(values.get(id));\n values.delete(id);\n }\n }\n };\n\n const global = new Proxy(tv(OBJECT, null), proxyHandler);\n\n return {\n [name.toLowerCase()]: global,\n [`is${name}Proxy`]: value => typeof value === OBJECT && !!value && __proxy__ in value,\n proxy: main\n };\n };\n};\n","import {FUNCTION} from 'proxy-target/types';\nexport default typeof Worker === FUNCTION ? Worker : class {};\n","import {MAIN, THREAD} from './channel.js';\nimport $coincident from './index.js';\nimport main from './window/main.js';\nimport thread from './window/thread.js';\nimport Worker from './shared/worker.js';\n\nconst proxies = new WeakMap;\n\n/**\n * @typedef {object} Coincident\n * @property {ProxyHandler} proxy\n * @property {ProxyHandler} window\n * @property {(value: any) => boolean} isWindowProxy\n */\n\n/**\n * Create once a `Proxy` able to orchestrate synchronous `postMessage` out of the box.\n * In workers, returns a `{proxy, window, isWindowProxy}` namespace to reach main globals synchronously.\n * @param {Worker | globalThis} self the context in which code should run\n * @returns {ProxyHandler | Coincident}\n */\nconst coincident = (self, ...args) => {\n const proxy = $coincident(self, ...args);\n if (!proxies.has(proxy)) {\n const util = self instanceof Worker ? main : thread;\n proxies.set(proxy, util.call(args.at(0), proxy, MAIN, THREAD));\n }\n return proxies.get(proxy);\n}\n\ncoincident.transfer = $coincident.transfer;\n\nexport default coincident;\n","/* c8 ignore start */\nconst {url} = import.meta;\nconst re = /import\\((['\"])([^)]+?\\.js)\\1\\)/g;\nconst place = (_,q,f) => `import(${q}${new URL(f,url).href}${q})`;\nexport default () => new Worker(URL.createObjectURL(new Blob([\"const e=\\\"object\\\"==typeof self?self:globalThis,t=t=>((t,n)=>{const r=(e,n)=>(t.set(n,e),e),s=o=>{if(t.has(o))return t.get(o);const[a,i]=n[o];switch(a){case 0:case-1:return r(i,o);case 1:{const e=r([],o);for(const t of i)e.push(s(t));return e}case 2:{const e=r({},o);for(const[t,n]of i)e[s(t)]=s(n);return e}case 3:return r(new Date(i),o);case 4:{const{source:e,flags:t}=i;return r(new RegExp(e,t),o)}case 5:{const e=r(new Map,o);for(const[t,n]of i)e.set(s(t),s(n));return e}case 6:{const e=r(new Set,o);for(const t of i)e.add(s(t));return e}case 7:{const{name:t,message:n}=i;return r(new e[t](n),o)}case 8:return r(BigInt(i),o);case\\\"BigInt\\\":return r(Object(BigInt(i)),o)}return r(new e[a](i),o)};return s})(new Map,t)(0),n=\\\"\\\",{toString:r}={},{keys:s}=Object,o=e=>{const t=typeof e;if(\\\"object\\\"!==t||!e)return[0,t];const s=r.call(e).slice(8,-1);switch(s){case\\\"Array\\\":return[1,n];case\\\"Object\\\":return[2,n];case\\\"Date\\\":return[3,n];case\\\"RegExp\\\":return[4,n];case\\\"Map\\\":return[5,n];case\\\"Set\\\":return[6,n]}return s.includes(\\\"Array\\\")?[1,s]:s.includes(\\\"Error\\\")?[7,s]:[2,s]},a=([e,t])=>0===e&&(\\\"function\\\"===t||\\\"symbol\\\"===t),i=(e,{json:t,lossy:n}={})=>{const r=[];return((e,t,n,r)=>{const i=(e,t)=>{const s=r.push(e)-1;return n.set(t,s),s},c=r=>{if(n.has(r))return n.get(r);let[l,p]=o(r);switch(l){case 0:{let t=r;switch(p){case\\\"bigint\\\":l=8,t=r.toString();break;case\\\"function\\\":case\\\"symbol\\\":if(e)throw new TypeError(\\\"unable to serialize \\\"+p);t=null;break;case\\\"undefined\\\":return i([-1],r)}return i([l,t],r)}case 1:{if(p)return i([p,[...r]],r);const e=[],t=i([l,e],r);for(const t of r)e.push(c(t));return t}case 2:{if(p)switch(p){case\\\"BigInt\\\":return i([p,r.toString()],r);case\\\"Boolean\\\":case\\\"Number\\\":case\\\"String\\\":return i([p,r.valueOf()],r)}if(t&&\\\"toJSON\\\"in r)return c(r.toJSON());const n=[],u=i([l,n],r);for(const t of s(r))!e&&a(o(r[t]))||n.push([c(t),c(r[t])]);return u}case 3:return i([l,r.toISOString()],r);case 4:{const{source:e,flags:t}=r;return i([l,{source:e,flags:t}],r)}case 5:{const t=[],n=i([l,t],r);for(const[n,s]of r)(e||!a(o(n))&&!a(o(s)))&&t.push([c(n),c(s)]);return n}case 6:{const t=[],n=i([l,t],r);for(const n of r)!e&&a(o(n))||t.push(c(n));return n}}const{message:u}=r;return i([l,{name:p,message:u}],r)};return c})(!(t||n),!!t,new Map,r)(e),r},{parse:c,stringify:l}=JSON,p={json:!0,lossy:!0};var u=Object.freeze({__proto__:null,parse:e=>t(c(e)),stringify:e=>l(i(e,p))});const f=\\\"64e10b34-2bf7-4616-9668-f99de5aa046e\\\",d=\\\"M\\\"+f,h=\\\"T\\\"+f,g=\\\"array\\\",y=\\\"function\\\",w=\\\"null\\\",m=\\\"number\\\",_=\\\"object\\\",b=\\\"string\\\",E=\\\"symbol\\\",v=\\\"undefined\\\",k=\\\"apply\\\",x=\\\"construct\\\",T=\\\"defineProperty\\\",S=\\\"deleteProperty\\\",A=\\\"get\\\",j=\\\"getOwnPropertyDescriptor\\\",O=\\\"getPrototypeOf\\\",R=\\\"has\\\",P=\\\"isExtensible\\\",$=\\\"ownKeys\\\",M=\\\"preventExtensions\\\",N=\\\"set\\\",I=\\\"setPrototypeOf\\\",F=\\\"delete\\\",{isArray:W}=Array;let{SharedArrayBuffer:H,window:D}=globalThis,{notify:C,wait:L,waitAsync:U}=Atomics,B=null;U||(U=e=>({value:new Promise((t=>{let n=new Worker(\\\"data:application/javascript,onmessage%3D(%7Bdata%3Ab%7D)%3D%3E(Atomics.wait(b%2C0)%2CpostMessage(0))\\\");n.onmessage=t,n.postMessage(e)}))}));try{new H(4)}catch(e){H=ArrayBuffer;const t=new WeakMap;if(D){const e=new Map,{prototype:{postMessage:n}}=Worker,r=t=>{const n=t.data?.[f];if(!W(n)){t.stopImmediatePropagation();const{id:r,sb:s}=n;e.get(r)(s)}};B=function(e,...s){const o=e?.[f];if(W(o)){const[e,n]=o;t.set(n,e),this.addEventListener(\\\"message\\\",r)}return n.call(this,e,...s)},U=n=>({value:new Promise((r=>{e.set(t.get(n),r)})).then((r=>{e.delete(t.get(n)),t.delete(n);for(let e=0;e({[f]:{id:e,sb:t}});C=n=>{postMessage(e(t.get(n),n))},addEventListener(\\\"message\\\",(e=>{const n=e.data?.[f];if(W(n)){const[e,r]=n;t.set(r,e)}}))}}\\n/*! (c) Andrea Giammarchi - ISC */const{Int32Array:J,Map:q,Uint16Array:z}=globalThis,{BYTES_PER_ELEMENT:G}=J,{BYTES_PER_ELEMENT:K}=z,Y=new WeakSet,X=new WeakMap,V={value:{then:e=>e()}};let Z=0;const Q=(e,{parse:t=JSON.parse,stringify:n=JSON.stringify,transform:r,interrupt:s}=JSON)=>{if(!X.has(e)){const o=B||e.postMessage,a=(t,...n)=>o.call(e,{[f]:n},{transfer:t}),i=typeof s===y?s:s?.handler,c=s?.delay||42,l=new TextDecoder(\\\"utf-16\\\"),p=(e,t)=>e?U(t,0):(i?((e,t,n)=>{for(;\\\"timed-out\\\"===L(e,0,0,t);)n()})(t,c,i):L(t,0),V);let u=!1;X.set(e,new Proxy(new q,{[R]:(e,t)=>\\\"string\\\"==typeof t&&!t.startsWith(\\\"_\\\"),[A]:(n,s)=>\\\"then\\\"===s?null:(...n)=>{const o=Z++;let i=new J(new H(2*G)),c=[];Y.has(n.at(-1)||c)&&Y.delete(c=n.pop()),a(c,o,i,s,r?n.map(r):n);const f=e!==globalThis;let d=0;return u&&f&&(d=setTimeout(console.warn,1e3,`💀🔒 - Possible deadlock if proxy.${s}(...args) is awaited`)),p(f,i).value.then((()=>{clearTimeout(d);const e=i[1];if(!e)return;const n=K*e;return i=new J(new H(n+n%G)),a([],o,i),p(f,i).value.then((()=>t(l.decode(new z(i.buffer).slice(0,e)))))}))},[N](t,s,o){const a=typeof o;if(a!==y)throw new Error(`Unable to assign ${s} as ${a}`);if(!t.size){const s=new q;e.addEventListener(\\\"message\\\",(async e=>{const o=e.data?.[f];if(W(o)){e.stopImmediatePropagation();const[a,i,...c]=o;let l;if(c.length){const[e,o]=c;if(t.has(e)){u=!0;try{const c=await t.get(e)(...o);if(void 0!==c){const e=n(r?r(c):c);s.set(a,e),i[1]=e.length}}catch(e){l=e}finally{u=!1}}else l=new Error(`Unsupported action: ${e}`);i[0]=1}else{const e=s.get(a);s.delete(a);for(let t=new z(i.buffer),n=0;n(Y.add(e),e);const{isArray:ee}=Array,te=(e,t)=>t,ne=e=>typeof e===y?(e=>e())(e):e;function re(){return this}const se=(e,t)=>e===g?[t]:{t:e,v:t},oe=(e,t=te)=>{let n=typeof e,r=e;return n===_&&(ee(e)?(n=g,r=e.at(0)):({t:n,v:r}=e)),t(n,r)},ae=(e,t)=>e===y?t:se(e,t),ie=(e,t=ae)=>{const n=null===e?w:typeof e;return t(n===_&&ee(e)?g:n,e)},ce=new FinalizationRegistry((([e,t,n])=>{n&&console.debug(`Held value ${String(t)} not relevant anymore`),e(t)})),le=Object.create(null),pe=(e,t,{debug:n,handler:r,return:s,token:o=e}=le)=>{const a=s||new Proxy(e,r||le),i=[a,[t,e,!!n]];return!1!==o&&i.push(o),ce.register(...i),a},{defineProperty:ue,deleteProperty:fe,getOwnPropertyDescriptor:de,getPrototypeOf:he,isExtensible:ge,ownKeys:ye,preventExtensions:we,set:me,setPrototypeOf:_e}=Reflect,{assign:be,create:Ee}=Object,ve=he(Int8Array),ke=(e,t)=>{const{get:n,set:r,value:s}=e;return n&&(e.get=t(n)),r&&(e.set=t(r)),s&&(e.value=t(s)),e},xe=e=>t=>ie(t,((t,n)=>{switch(t){case w:return se(w,n);case _:if(n===globalThis)return se(t,null);case g:case y:return e(t,n);case\\\"boolean\\\":case m:case b:case v:case\\\"bigint\\\":return se(t,n);case E:{if(Te.has(n))return se(t,Te.get(n));let e=Symbol.keyFor(n);if(e)return se(t,`.${e}`)}}throw new TypeError(`Unable to handle this ${t}: ${String(n)}`)})),Te=new Map(ye(Symbol).filter((e=>typeof Symbol[e]===E)).map((e=>[Symbol[e],e]))),Se=e=>{if(e.startsWith(\\\".\\\"))return Symbol.for(e.slice(1));for(const[t,n]of Te)if(n===e)return t},Ae=e=>e;var je=((e,t)=>{const n=new WeakMap;{const{addEventListener:e}=EventTarget.prototype;ue(EventTarget.prototype,\\\"addEventListener\\\",{value(t,r,...s){return s.at(0)?.invoke&&(n.has(this)||n.set(this,new Map),n.get(this).set(t,[].concat(s[0].invoke)),delete s[0].invoke),e.call(this,t,r,...s)}})}return function(t,r,s,...o){let a=0,i=this?.transform||Ae;const c=new Map,l=new Map,{[s]:p}=t,u=o.length?be(Ee(globalThis),...o):globalThis,f=xe(((e,t)=>{if(!c.has(t)){let n;for(;l.has(n=a++););c.set(t,n),l.set(n,e===y?t:i(t))}return se(e,c.get(t))})),d=e=>{p(F,se(b,e))},h=(e,t)=>{switch(e){case _:if(null==t)return u;case g:if(typeof t===m)return l.get(t);if(!(t instanceof ve))for(const e in t)t[e]=w(t[e]);return t;case y:if(typeof t===b){const e=l.get(t)?.deref();if(e)return e;const r=function(...e){return e.at(0)instanceof Event&&(e=>{const{currentTarget:t,target:r,type:s}=e;for(const o of n.get(t||r)?.get(s)||[])e[o]()})(...e),p(k,se(y,t),f(this),e.map(f))};return l.set(t,new WeakRef(r)),pe(t,d,{return:r,token:!1})}return l.get(t);case E:return Se(t)}return t},w=e=>oe(e,h),W={[k]:(e,t,n)=>f(e.apply(t,n)),[x]:(e,t)=>f(new e(...t)),[T]:(e,t,n)=>f(ue(e,t,n)),[S]:(e,t)=>f(fe(e,t)),[O]:e=>f(he(e)),[A]:(e,t)=>f(e[t]),[j]:(e,t)=>{const n=de(e,t);return n?se(_,ke(n,f)):se(v,n)},[R]:(e,t)=>f(t in e),[P]:e=>f(ge(e)),[$]:e=>se(g,ye(e).map(f)),[M]:e=>f(we(e)),[N]:(e,t,n)=>f(me(e,t,n)),[I]:(e,t)=>f(_e(e,t)),[F](e){c.delete(l.get(e)),l.delete(e)}};return t[r]=(e,t,...n)=>{switch(e){case k:n[0]=w(n[0]),n[1]=n[1].map(w);break;case x:n[0]=n[0].map(w);break;case T:{const[e,t]=n;n[0]=w(e);const{get:r,set:s,value:o}=t;r&&(t.get=w(r)),s&&(t.set=w(s)),o&&(t.value=w(o));break}default:n=n.map(w)}return W[e](w(t),...n)},{proxy:t,[e.toLowerCase()]:u,[`is${e}Proxy`]:()=>!1}}})(\\\"Window\\\"),Oe=(e=>{let t=0;const n=new Map,r=new Map,s=Symbol();return function(o,a,i){const c=this?.transform||Ae,{[a]:l}=o,p=new Map,u=e=>{p.delete(e),l(F,f(e))},f=xe(((e,o)=>{if(s in o)return ne(o[s]);if(e===y){if(o=c(o),!r.has(o)){let e;for(;r.has(e=String(t++)););n.set(o,e),r.set(e,o)}return se(e,n.get(o))}if(!(o instanceof ve)){o=c(o);for(const e in o)o[e]=f(o[e])}return se(e,o)})),d=(e,t,n)=>{const r=p.get(n)?.deref();if(r)return r;const s=t===y?(e=>re.bind(e))(e):e,o=new Proxy(s,v);return p.set(n,new WeakRef(o)),pe(n,u,{return:o,token:!1})},h=e=>oe(e,((t,n)=>{switch(t){case _:if(null===n)return globalThis;case g:return typeof n===m?d(e,t,n):n;case y:return typeof n===b?r.get(n):d(e,t,n);case E:return Se(n)}return n})),w=(e,t,...n)=>h(l(e,ne(t),...n)),v={[k]:(e,t,n)=>w(k,e,f(t),n.map(f)),[x]:(e,t)=>w(x,e,t.map(f)),[T]:(e,t,n)=>{const{get:r,set:s,value:o}=n;return typeof r===y&&(n.get=f(r)),typeof s===y&&(n.set=f(s)),typeof o===y&&(n.value=f(o)),w(T,e,f(t),n)},[S]:(e,t)=>w(S,e,f(t)),[O]:e=>w(O,e),[A]:(e,t)=>t===s?e:w(A,e,f(t)),[j]:(e,t)=>{const n=w(j,e,f(t));return n&&ke(n,h)},[R]:(e,t)=>t===s||w(R,e,f(t)),[P]:e=>w(P,e),[$]:e=>w($,e).map(h),[M]:e=>w(M,e),[N]:(e,t,n)=>w(N,e,f(t),f(n)),[I]:(e,t)=>w(I,e,f(t))};o[i]=(e,t,s,o)=>{switch(e){case k:return h(t).apply(h(s),o.map(h));case F:{const e=h(t);n.delete(r.get(e)),r.delete(e)}}};const W=new Proxy(se(_,null),v);return{[e.toLowerCase()]:W,[`is${e}Proxy`]:e=>typeof e===_&&!!e&&s in e,proxy:o}}})(\\\"Window\\\"),Re=typeof Worker===y?Worker:class{};const Pe=new WeakMap,$e=(e,...t)=>{const n=Q(e,...t);if(!Pe.has(n)){const r=e instanceof Re?je:Oe;Pe.set(n,r.call(t.at(0),n,d,h))}return Pe.get(n)};$e.transfer=Q.transfer;const Me={object(...e){return this.string(function(e){for(var t=e[0],n=1,r=arguments.length;n{const t=e||console,n={buffered:We,stderr:(t.stderr||console.error).bind(t),stdout:(t.stdout||console.log).bind(t)};return{stderr:(...e)=>n.stderr(...e),stdout:(...e)=>n.stdout(...e),async get(e){const t=await e;return Ne.set(t,n),t}}},Fe=new TextDecoder,We=(e,t=10)=>{const n=[];return r=>{if(r instanceof Uint8Array)for(const s of r)s===t?e(Fe.decode(new Uint8Array(n.splice(0)))):n.push(s);else e(r)}},He=(e,...t)=>Me[typeof e](e,...t),{isArray:De}=Array,{assign:Ce,create:Le,defineProperties:Ue,defineProperty:Be,entries:Je}=Object,{all:qe,resolve:ze}=new Proxy(Promise,{get:(e,t)=>e[t].bind(e)}),Ge=(e,t=location.href)=>new URL(e,t.replace(/^blob:/,\\\"\\\")).href,Ke=(e,t,n,r=!1,s=CustomEvent)=>{e.dispatchEvent(new s(`${t}:${n}`,{bubbles:!0,detail:{worker:r}}))},Ye=e=>Function(`'use strict';return (${e})`)(),Xe=e=>e.replace(/^(?:\\\\n|\\\\r\\\\n)/,\\\"\\\"),Ve=Symbol.for(\\\"polyscript.js_modules\\\"),Ze=new Map;Be(globalThis,Ve,{value:Ze}),new Proxy(Ze,{get:(e,t)=>e.get(t),has:(e,t)=>e.has(t),ownKeys:e=>[...e.keys()]});const Qe=(e,t)=>!t.startsWith(\\\"_\\\"),et=(e,t)=>new Proxy(e,{has:Qe,get:(e,n)=>e[t][n]}),tt=(e,t)=>import(e).then((e=>{Ze.set(t,{...e})})),nt=e=>new Promise(((t,n)=>{document.querySelector(`link[href=\\\"${e}\\\"]`)&&t(),document.head.append(Ce(document.createElement(\\\"link\\\"),{rel:\\\"stylesheet\\\",href:e,onload:t,onerror:n}))})),rt=e=>/\\\\.css/i.test(new URL(e).pathname);Promise.withResolvers||(Promise.withResolvers=function(){var e,t,n=new this((function(n,r){e=n,t=r}));return{resolve:e,reject:t,promise:n}});const st=Object.getOwnPropertyDescriptors(Response.prototype),ot=e=>\\\"function\\\"==typeof e,at={get:(e,t)=>st.hasOwnProperty(t)?((e,t,{get:n,value:r})=>n||!ot(r)?e.then((e=>e[t])):(...n)=>e.then((e=>e[t](...n))))(e,t,st[t]):((e,t)=>ot(t)?t.bind(e):t)(e,e[t])};var it=(e,...t)=>new Proxy(fetch(e,...t),at);const ct=!globalThis.window,lt=({FS:e,PATH:t,PATH_FS:n},r,s)=>{const o=n.resolve(r),a=t.dirname(o);return e.mkdirTree?e.mkdirTree(a):ut(e,a),e.writeFile(o,new Uint8Array(s),{canOwn:!0})},pt=e=>{const t=e.split(\\\"/\\\");return t.pop(),t.join(\\\"/\\\")},ut=(e,t)=>{const n=[];for(const r of t.split(\\\"/\\\"))\\\".\\\"!==r&&\\\"..\\\"!==r&&(n.push(r),r&&e.mkdir(n.join(\\\"/\\\")))},ft=(e,t)=>{const n=[];for(const e of t.split(\\\"/\\\"))switch(e){case\\\"\\\":case\\\".\\\":break;case\\\"..\\\":n.pop();break;default:n.push(e)}return[e.cwd()].concat(n).join(\\\"/\\\").replace(/^\\\\/+/,\\\"/\\\")},dt=e=>{const t=e.map((e=>e.trim().replace(/(^[/]*|[/]*$)/g,\\\"\\\"))).filter((e=>\\\"\\\"!==e&&\\\".\\\"!==e)).join(\\\"/\\\");return e[0].startsWith(\\\"/\\\")?`/${t}`:t},ht=(e,t)=>it(Ge(t,gt.get(e))).arrayBuffer(),gt=new WeakMap,yt=(e,t,n)=>qe((e=>{for(const{files:t,to_file:n,from:r=\\\"\\\"}of e){if(void 0!==t&&void 0!==n)throw new Error(\\\"Cannot use 'to_file' and 'files' parameters together!\\\");if(void 0===t&&void 0===n&&r.endsWith(\\\"/\\\"))throw new Error(`Couldn't determine the filename from the path ${r}, please supply 'to_file' parameter.`)}return e.flatMap((({from:e=\\\"\\\",to_folder:t=\\\".\\\",to_file:n,files:r})=>{if(De(r))return r.map((n=>({url:dt([e,n]),path:dt([t,n])})));const s=n||e.slice(1+e.lastIndexOf(\\\"/\\\"));return[{url:e,path:dt([t,s])}]}))})(n).map((({url:r,path:s})=>ht(n,r).then((n=>e.writeFile(t,s,n)))))),wt=(e,t)=>t.endsWith(\\\"/\\\")?`${t}${e.split(\\\"/\\\").pop()}`:t,mt=(e,t)=>e.replace(/\\\\{.+?\\\\}/g,(e=>{if(!t.has(e))throw new SyntaxError(`Invalid template: ${e}`);return t.get(e)})),_t=(e,t,n)=>qe((e=>{const t=new Map,n=new Set,r=[];for(const[s,o]of Je(e))if(/^\\\\{.+\\\\}$/.test(s)){if(t.has(s))throw new SyntaxError(`Duplicated template: ${s}`);t.set(s,mt(o,t))}else{const e=mt(s,t),a=wt(e,mt(o||\\\"./\\\",t));if(n.has(a))throw new SyntaxError(`Duplicated destination: ${a}`);n.add(a),r.push({url:e,path:a})}return r})(n).map((({url:r,path:s})=>ht(n,r).then((n=>e.writeFile(t,s,n,r)))))),bt=({main:e,worker:t})=>{const n=[];if(t&&ct)for(let[e,r]of Je(t))e=Ge(e,gt.get(t)),n.push(tt(e,r));if(e&&!ct)for(let[t,r]of Je(e))t=Ge(t,gt.get(e)),rt(t)?nt(t):n.push(tt(t,r));return qe(n)},Et=(e,t)=>e.has(t),vt=e=>[...e.keys()];var kt=(e,t,n)=>{let r=globalThis[Ve],s=\\\"\\\";if(n){s=gt.get(n);for(let[e,t]of Je(n)){let n=r.get(t);n&&!De(n)||(r.set(t,n||(n=[])),n.push(e))}}return((e,t,n,r)=>new Proxy(e,{has:Et,ownKeys:vt,get:(e,s)=>{let o=e.get(s);if(De(o)){let a=o;o=null;for(let e of a)e=Ge(e,r),rt(e)?n.importCSS(e):(n.importJS(e,s),o=t[Ve].get(s));e.set(s,o)}return o}}))(r,e,t,s)};const xt=new WeakMap,Tt=(e,t,n)=>{\\\"polyscript\\\"===t&&(n.lazy_py_modules=async(...t)=>(await xt.get(e)(t),t.map((t=>e.pyimport(t))))),e.registerJsModule(t,n)},St=(e,t)=>{if(e.endsWith(\\\"/*\\\")){if(/\\\\.(zip|tar(?:\\\\.gz)?)$/.test(t))return RegExp.$1;throw new Error(`Unsupported archive ${t}`)}return\\\"\\\"},At=(e,t,...n)=>{try{return e.runPython(He(t),...n)}catch(t){Ne.get(e).stderr(t)}},jt=async(e,t,...n)=>{try{return await e.runPythonAsync(He(t),...n)}catch(t){Ne.get(e).stderr(t)}},Ot=async(e,t,n)=>{const[r,...s]=t.split(\\\".\\\");let o,a=e.globals.get(r);for(const e of s)[o,a]=[a,a[e]];try{await a.call(o,n)}catch(t){Ne.get(e).stderr(t)}};var Rt=(new TextEncoder).encode('from uio import StringIO\\\\nimport sys\\\\n\\\\nclass Response:\\\\n def __init__(self, f):\\\\n self.raw = f\\\\n self.encoding = \\\"utf-8\\\"\\\\n self._cached = None\\\\n\\\\n def close(self):\\\\n if self.raw:\\\\n self.raw.close()\\\\n self.raw = None\\\\n self._cached = None\\\\n\\\\n @property\\\\n def content(self):\\\\n if self._cached is None:\\\\n try:\\\\n self._cached = self.raw.read()\\\\n finally:\\\\n self.raw.close()\\\\n self.raw = None\\\\n return self._cached\\\\n\\\\n @property\\\\n def text(self):\\\\n return str(self.content, self.encoding)\\\\n\\\\n def json(self):\\\\n import ujson\\\\n\\\\n return ujson.loads(self.content)\\\\n\\\\n\\\\n# TODO try to support streaming xhr requests, a-la pyodide-http\\\\nHEADERS_TO_IGNORE = (\\\"user-agent\\\",)\\\\n\\\\n\\\\ntry:\\\\n import js\\\\nexcept Exception as err:\\\\n raise OSError(\\\"This version of urequests can only be used in the browser\\\")\\\\n\\\\n# TODO try to support streaming xhr requests, a-la pyodide-http\\\\n\\\\nHEADERS_TO_IGNORE = (\\\"user-agent\\\",)\\\\n\\\\n\\\\ndef request(\\\\n method,\\\\n url,\\\\n data=None,\\\\n json=None,\\\\n headers={},\\\\n stream=None,\\\\n auth=None,\\\\n timeout=None,\\\\n parse_headers=True,\\\\n):\\\\n from js import XMLHttpRequest\\\\n\\\\n xhr = XMLHttpRequest.new()\\\\n xhr.withCredentials = False\\\\n\\\\n if auth is not None:\\\\n import ubinascii\\\\n\\\\n username, password = auth\\\\n xhr.open(method, url, False, username, password)\\\\n else:\\\\n xhr.open(method, url, False)\\\\n\\\\n for name, value in headers.items():\\\\n if name.lower() not in HEADERS_TO_IGNORE:\\\\n xhr.setRequestHeader(name, value)\\\\n\\\\n if timeout:\\\\n xhr.timeout = int(timeout * 1000)\\\\n\\\\n if json is not None:\\\\n assert data is None\\\\n import ujson\\\\n\\\\n data = ujson.dumps(json)\\\\n # s.write(b\\\"Content-Type: application/json\\\\\\\\r\\\\\\\\n\\\")\\\\n xhr.setRequestHeader(\\\"Content-Type\\\", \\\"application/json\\\")\\\\n\\\\n xhr.send(data)\\\\n\\\\n # Emulates the construction process in the original urequests\\\\n resp = Response(StringIO(xhr.responseText))\\\\n resp.status_code = xhr.status\\\\n resp.reason = xhr.statusText\\\\n resp.headers = xhr.getAllResponseHeaders()\\\\n\\\\n return resp\\\\n\\\\n\\\\n# Other methods - head, post, put, patch, delete - are not used by\\\\n# mip and therefore not included\\\\n\\\\n\\\\ndef get(url, **kw):\\\\n return request(\\\"GET\\\", url, **kw)\\\\n\\\\n\\\\n# Content below this line is from the Micropython MIP package and is covered\\\\n# by the applicable MIT license:\\\\n# \\\\n# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\\\\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, \\\\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\\\\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER \\\\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING \\\\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER \\\\n# DEALINGS IN THE SOFTWARE.\\\\n\\\\n# MicroPython package installer\\\\n# MIT license; Copyright (c) 2022 Jim Mussared\\\\n\\\\n\\\\n_PACKAGE_INDEX = const(\\\"https://micropython.org/pi/v2\\\")\\\\n_CHUNK_SIZE = 128\\\\n\\\\n\\\\n# This implements os.makedirs(os.dirname(path))\\\\ndef _ensure_path_exists(path):\\\\n import os\\\\n\\\\n split = path.split(\\\"/\\\")\\\\n\\\\n # Handle paths starting with \\\"/\\\".\\\\n if not split[0]:\\\\n split.pop(0)\\\\n split[0] = \\\"/\\\" + split[0]\\\\n\\\\n prefix = \\\"\\\"\\\\n for i in range(len(split) - 1):\\\\n prefix += split[i]\\\\n try:\\\\n os.stat(prefix)\\\\n except:\\\\n os.mkdir(prefix)\\\\n prefix += \\\"/\\\"\\\\n\\\\n\\\\n# Copy from src (stream) to dest (function-taking-bytes)\\\\ndef _chunk(src, dest):\\\\n buf = memoryview(bytearray(_CHUNK_SIZE))\\\\n while True:\\\\n n = src.readinto(buf)\\\\n if n == 0:\\\\n break\\\\n dest(buf if n == _CHUNK_SIZE else buf[:n])\\\\n\\\\n\\\\n# Check if the specified path exists and matches the hash.\\\\ndef _check_exists(path, short_hash):\\\\n import os\\\\n\\\\n try:\\\\n import binascii\\\\n import hashlib\\\\n\\\\n with open(path, \\\"rb\\\") as f:\\\\n hs256 = hashlib.sha256()\\\\n _chunk(f, hs256.update)\\\\n existing_hash = str(binascii.hexlify(hs256.digest())[: len(short_hash)], \\\"utf-8\\\")\\\\n return existing_hash == short_hash\\\\n except:\\\\n return False\\\\n\\\\n\\\\ndef _rewrite_url(url, branch=None):\\\\n if not branch:\\\\n branch = \\\"HEAD\\\"\\\\n if url.startswith(\\\"github:\\\"):\\\\n url = url[7:].split(\\\"/\\\")\\\\n url = (\\\\n \\\"https://raw.githubusercontent.com/\\\"\\\\n + url[0]\\\\n + \\\"/\\\"\\\\n + url[1]\\\\n + \\\"/\\\"\\\\n + branch\\\\n + \\\"/\\\"\\\\n + \\\"/\\\".join(url[2:])\\\\n )\\\\n return url\\\\n\\\\n\\\\ndef _download_file(url, dest):\\\\n response = get(url)\\\\n try:\\\\n if response.status_code != 200:\\\\n print(\\\"Error\\\", response.status_code, \\\"requesting\\\", url)\\\\n return False\\\\n\\\\n print(\\\"Copying:\\\", dest)\\\\n _ensure_path_exists(dest)\\\\n with open(dest, \\\"wb\\\") as f:\\\\n _chunk(response.raw, f.write)\\\\n\\\\n return True\\\\n finally:\\\\n response.close()\\\\n\\\\n\\\\ndef _install_json(package_json_url, index, target, version, mpy):\\\\n response = get(_rewrite_url(package_json_url, version))\\\\n try:\\\\n if response.status_code != 200:\\\\n print(\\\"Package not found:\\\", package_json_url)\\\\n return False\\\\n\\\\n package_json = response.json()\\\\n finally:\\\\n response.close()\\\\n for target_path, short_hash in package_json.get(\\\"hashes\\\", ()):\\\\n fs_target_path = target + \\\"/\\\" + target_path\\\\n if _check_exists(fs_target_path, short_hash):\\\\n print(\\\"Exists:\\\", fs_target_path)\\\\n else:\\\\n file_url = \\\"{}/file/{}/{}\\\".format(index, short_hash[:2], short_hash)\\\\n if not _download_file(file_url, fs_target_path):\\\\n print(\\\"File not found: {} {}\\\".format(target_path, short_hash))\\\\n return False\\\\n for target_path, url in package_json.get(\\\"urls\\\", ()):\\\\n fs_target_path = target + \\\"/\\\" + target_path\\\\n if not _download_file(_rewrite_url(url, version), fs_target_path):\\\\n print(\\\"File not found: {} {}\\\".format(target_path, url))\\\\n return False\\\\n for dep, dep_version in package_json.get(\\\"deps\\\", ()):\\\\n if not _install_package(dep, index, target, dep_version, mpy):\\\\n return False\\\\n return True\\\\n\\\\n\\\\ndef _install_package(package, index, target, version, mpy):\\\\n if (\\\\n package.startswith(\\\"http://\\\")\\\\n or package.startswith(\\\"https://\\\")\\\\n or package.startswith(\\\"github:\\\")\\\\n ):\\\\n if package.endswith(\\\".py\\\") or package.endswith(\\\".mpy\\\"):\\\\n print(\\\"Downloading {} to {}\\\".format(package, target))\\\\n return _download_file(\\\\n _rewrite_url(package, version), target + \\\"/\\\" + package.rsplit(\\\"/\\\")[-1]\\\\n )\\\\n else:\\\\n if not package.endswith(\\\".json\\\"):\\\\n if not package.endswith(\\\"/\\\"):\\\\n package += \\\"/\\\"\\\\n package += \\\"package.json\\\"\\\\n print(\\\"Installing {} to {}\\\".format(package, target))\\\\n else:\\\\n if not version:\\\\n version = \\\"latest\\\"\\\\n print(\\\"Installing {} ({}) from {} to {}\\\".format(package, version, index, target))\\\\n\\\\n mpy_version = (\\\\n sys.implementation._mpy & 0xFF if mpy and hasattr(sys.implementation, \\\"_mpy\\\") else \\\"py\\\"\\\\n )\\\\n\\\\n package = \\\"{}/package/{}/{}/{}.json\\\".format(index, mpy_version, package, version)\\\\n\\\\n return _install_json(package, index, target, version, mpy)\\\\n\\\\n\\\\ndef install(package, index=None, target=None, version=None, mpy=True):\\\\n if not target:\\\\n for p in sys.path:\\\\n if p.endswith(\\\"/lib\\\"):\\\\n target = p\\\\n break\\\\n else:\\\\n print(\\\"Unable to find lib dir in sys.path\\\")\\\\n return\\\\n\\\\n if not index:\\\\n index = _PACKAGE_INDEX\\\\n\\\\n if _install_package(package, index.rstrip(\\\"/\\\"), target, version, mpy):\\\\n print(\\\"Done\\\")\\\\n else:\\\\n print(\\\"Package may be partially installed\\\")\\\\n');const Pt=(e,t)=>{try{e.mkdir(t)}catch(e){}};var $t={type:\\\"micropython\\\",module:(e=\\\"1.22.0-356\\\")=>`https://cdn.jsdelivr.net/npm/@micropython/micropython-webassembly-pyscript@${e}/micropython.mjs`,async engine({loadMicroPython:e},t,n){const{stderr:r,stdout:s,get:o}=Ie({stderr:We(console.error),stdout:We(console.log)});n=n.replace(/\\\\.m?js$/,\\\".wasm\\\");const a=await o(e({linebuffer:!1,stderr:r,stdout:s,url:n})),i=Mt.bind(a);return xt.set(a,i),t.files&&await _t(this,a,t.files),t.fetch&&await yt(this,a,t.fetch),t.js_modules&&await bt(t.js_modules),this.writeFile(a,\\\"./mip.py\\\",Rt),t.packages&&await i(t.packages),a},registerJSModule:Tt,run:At,runAsync:jt,runEvent:Ot,transform:(e,t)=>e.PyProxy.toJs(t),writeFile:(e,t,n,r)=>{const{FS:s,_module:{PATH:o,PATH_FS:a}}=e,i={FS:s,PATH:o,PATH_FS:a},c=St(t,r);if(c){const r=t.slice(0,-1);switch(\\\"./\\\"!==r&&s.mkdir(r),c){case\\\"zip\\\":{const e=new Blob([n],{type:\\\"application/zip\\\"});return import(\\\"./zip-D2yvzXKD.js\\\").then((async({BlobReader:t,Uint8ArrayWriter:n,ZipReader:a})=>{const i=new a(new t(e));for(const e of await i.getEntries()){const{directory:t,filename:a}=e,i=r+a;if(t)Pt(s,i);else{Pt(s,o.dirname(i));const t=await e.getData(new n);s.writeFile(i,t,{canOwn:!0})}}i.close()}))}case\\\"tar.gz\\\":{const t=\\\"./_.tar.gz\\\";return lt(i,t,n),void e.runPython(`\\\\n import os, gzip, tarfile\\\\n tar = tarfile.TarFile(fileobj=gzip.GzipFile(fileobj=open(\\\"${t}\\\", \\\"rb\\\")))\\\\n for f in tar:\\\\n name = f\\\"${r}{f.name}\\\"\\\\n if f.type == tarfile.DIRTYPE:\\\\n if f.name != \\\"./\\\":\\\\n os.mkdir(name.strip(\\\"/\\\"))\\\\n else:\\\\n dir = os.path.dirname(name)\\\\n if not os.path.exists(dir):\\\\n os.mkdir(dir)\\\\n source = tar.extractfile(f)\\\\n with open(name, \\\"wb\\\") as dest:\\\\n dest.write(source.read())\\\\n dest.close()\\\\n tar.close()\\\\n os.remove(\\\"${t}\\\")\\\\n `)}}}return lt(i,t,n)}};async function Mt(e){const t=this.pyimport(\\\"mip\\\");for(const n of e)t.install(n)}const Nt={dict_converter:Object.fromEntries};let It=!1;const Ft=e=>(...t)=>{try{return It=!0,e(...t)}finally{It=!1}};let Wt=!1;const Ht=()=>{if(Wt)return;Wt=!0;const e=new WeakMap,t=e=>e.destroy(),n=n=>{for(let r=0;r`https://cdn.jsdelivr.net/pyodide/v${e}/full/pyodide.mjs`,async engine({loadPyodide:e},t,n){ct||\\\"auto\\\"!==t.experimental_create_proxy||Ht();const{stderr:r,stdout:s,get:o}=Ie(),a=n.slice(0,n.lastIndexOf(\\\"/\\\")),i=await o(e({stderr:r,stdout:s,indexURL:a})),c=Ct.bind(i);return xt.set(i,c),t.files&&await _t(this,i,t.files),t.fetch&&await yt(this,i,t.fetch),t.js_modules&&await bt(t.js_modules),t.packages&&await c(t.packages),i},registerJSModule:Tt,run:Ft(At),runAsync:Ft(jt),runEvent:Ft(Ot),transform:({ffi:{PyProxy:e}},t)=>t instanceof e?t.toJs(Nt):t,writeFile:(e,t,n,r)=>{const s=St(t,r);if(s)return e.unpackArchive(n,s,{extractDir:t.slice(0,-1)});const{FS:o,PATH:a,_module:{PATH_FS:i}}=e;return lt({FS:o,PATH:a,PATH_FS:i},t,n)}};async function Ct(e){await this.loadPackage(\\\"micropip\\\");const t=this.pyimport(\\\"micropip\\\");await t.install(e,{keep_going:!0}),t.destroy()}const Lt=\\\"ruby-wasm-wasi\\\",Ut=Lt.replace(/\\\\W+/g,\\\"_\\\");var Bt={type:Lt,experimental:!0,module:(e=\\\"2.6.0\\\")=>`https://cdn.jsdelivr.net/npm/@ruby/3.2-wasm-wasi@${e}/dist/browser/+esm`,async engine({DefaultRubyVM:e},t,n){n=n.replace(/\\\\/browser\\\\/\\\\+esm$/,\\\"/ruby.wasm\\\");const r=await it(n).arrayBuffer(),s=await WebAssembly.compile(r),{vm:o}=await e(s);return t.files&&await _t(this,o,t.files),t.fetch&&await yt(this,o,t.fetch),t.js_modules&&await bt(t.js_modules),o},registerJSModule(e,t,n){t=t.replace(/\\\\W+/g,\\\"__\\\");const r=`__module_${Ut}_${t}`;globalThis[r]=n,this.run(e,`require \\\"js\\\";$${t}=JS.global[:${r}]`),delete globalThis[r]},run:(e,t,...n)=>e.eval(He(t),...n),runAsync:(e,t,...n)=>e.evalAsync(He(t),...n),async runEvent(e,t,n){if(/^xworker\\\\.(on\\\\w+)$/.test(t)){const{$1:t}=RegExp,r=`__module_${Ut}_event`;globalThis[r]=n,this.run(e,`require \\\"js\\\";$xworker.call(\\\"${t}\\\",JS.global[:${r}])`),delete globalThis[r]}else{const r=this.run(e,`method(:${t})`);await r.call(t,e.wrap(n))}},transform:(e,t)=>t,writeFile:()=>{throw new Error(`writeFile is not supported in ${Lt}`)}};var Jt={type:\\\"wasmoon\\\",module:(e=\\\"1.16.0\\\")=>`https://cdn.jsdelivr.net/npm/wasmoon@${e}/+esm`,async engine({LuaFactory:e,LuaLibraries:t},n){const{stderr:r,stdout:s,get:o}=Ie(),a=await o((new e).createEngine());return a.global.getTable(t.Base,(e=>{a.global.setField(e,\\\"print\\\",s),a.global.setField(e,\\\"printErr\\\",r)})),n.files&&await _t(this,a,n.files),n.fetch&&await yt(this,a,n.fetch),n.js_modules&&await bt(n.js_modules),a},registerJSModule:(e,t,n)=>{e.global.set(t,n)},run:(e,t,...n)=>{try{return e.doStringSync(He(t),...n)}catch(t){Ne.get(e).stderr(t)}},runAsync:async(e,t,...n)=>{try{return await e.doString(He(t),...n)}catch(t){Ne.get(e).stderr(t)}},runEvent:async(e,t,n)=>{const[r,...s]=t.split(\\\".\\\");let o,a=e.global.get(r);for(const e of s)[o,a]=[a,a[e]];try{await a.call(o,n)}catch(t){Ne.get(e).stderr(t)}},transform:(e,t)=>t,writeFile:({cmodule:{module:{FS:e}}},t,n)=>((e,t,n)=>(ut(e,pt(t)),t=ft(e,t),e.writeFile(t,new Uint8Array(n),{canOwn:!0})))(e,t,n)};const qt=new WeakMap,zt=async(e,t)=>{const{shelter:n,destroy:r,io:s}=qt.get(e),{output:o,result:a}=await n.captureR(He(t));for(const{type:e,data:t}of o)s[e](t);return pe(a,r,{token:!1})};var Gt={type:\\\"webr\\\",experimental:!0,module:(e=\\\"0.3.3\\\")=>`https://cdn.jsdelivr.net/npm/webr@${e}/dist/webr.mjs`,async engine(e,t){const{get:n}=Ie(),r=new e.WebR;await n(r.init().then((()=>r)));const s=await new r.Shelter;return qt.set(r,{module:e,shelter:s,destroy:s.destroy.bind(s),io:Ne.get(r)}),t.files&&await _t(this,r,t.files),t.fetch&&await yt(this,r,t.fetch),t.js_modules&&await bt(t.js_modules),r},registerJSModule(e,t){console.warn(`Experimental interpreter: module ${t} is not supported (yet)`)},run:zt,runAsync:zt,async runEvent(e,t,n){await e.evalRVoid(`${t}(event)`,{env:{event:{type:[n.type]}}})},transform:(e,t)=>(console.log(\\\"transforming\\\",t),t),writeFile:()=>{}};const Kt=new Map,Yt=new Map,Xt=new Proxy(new Map,{get(e,t){if(!e.has(t)){const[n,...r]=t.split(\\\"@\\\"),s=Kt.get(n),o=/^(?:\\\\.?\\\\.?\\\\/|https?:\\\\/\\\\/)/i.test(r)?r.join(\\\"@\\\"):s.module(...r);e.set(t,{url:o,module:import(o),engine:s.engine.bind(s)})}const{url:n,module:r,engine:s}=e.get(t);return(e,o)=>r.then((r=>{Yt.set(t,e);for(const t of[\\\"files\\\",\\\"fetch\\\"]){const n=e?.[t];n&>.set(n,o)}for(const t of[\\\"main\\\",\\\"worker\\\"]){const n=e?.js_modules?.[t];n&>.set(n,o)}return s(r,e,n)}))}}),Vt=e=>{for(const t of[].concat(e.type))Kt.set(t,e)};for(const e of[$t,Dt,Bt,Jt,Gt])Vt(e);const Zt=async e=>(await import(\\\"./toml-DiUM0_qs.js\\\")).parse(e),Qt=e=>{try{return JSON.parse(e)}catch(t){return Zt(e)}},en=(e,t,n,r={})=>{if(t){const[e,s]=((e,t=\\\"./config.txt\\\")=>{let n=typeof e;return\\\"string\\\"===n&&/\\\\.(json|toml|txt)$/.test(e)?n=RegExp.$1:e=t,[Ge(e),n]})(t,n);\\\"json\\\"===s?r=it(e).json():\\\"toml\\\"===s?r=it(e).text().then(Zt):\\\"string\\\"===s?r=Qt(t):\\\"object\\\"===s&&t?r=t:\\\"txt\\\"===s&&\\\"string\\\"==typeof r&&(r=Qt(r)),t=e}return ze(r).then((n=>Xt[e](n,t)))},tn=\\\"BeforeRun\\\",nn=\\\"AfterRun\\\",rn=[`code${tn}`,`code${tn}Async`,`code${nn}`,`code${nn}Async`],sn=[\\\"onWorker\\\",\\\"onReady\\\",`on${tn}`,`on${tn}Async`,`on${nn}`,`on${nn}Async`];function on(e,t){const{run:n,runAsync:r}=Kt.get(this.type);return{...e,run:n.bind(this,t),runAsync:r.bind(this,t)}}const an=(e,t,n,r,s,o)=>{if(s||o){const a=on.bind(e,t),i=r?\\\"runAsync\\\":\\\"run\\\",c=e[i];e[i]=r?async function(e,t,...r){s&&await s.call(this,a(e),n);const i=await c.call(this,e,t,...r);return o&&await o.call(this,a(e),n),i}:function(e,t,...r){s&&s.call(this,a(e),n);const i=c.call(this,e,t,...r);return o&&o.call(this,a(e),n),i}}};let cn,ln,pn;const un=(e,t)=>{addEventListener(e,t||(async t=>{try{await cn,ln(`xworker.on${e}`,t)}catch(e){postMessage(e)}}),!!t&&{once:!0})},{parse:fn,stringify:dn}=u,{proxy:hn,window:gn,isWindowProxy:yn}=$e(self,{parse:fn,stringify:dn,transform:e=>pn?pn(e):e}),wn={sync:hn,window:gn,isWindowProxy:yn,onmessage:console.info,onerror:console.error,onmessageerror:console.warn,postMessage:postMessage.bind(self)};un(\\\"message\\\",(({data:{options:e,config:t,configURL:n,code:r,hooks:s}})=>{cn=(async()=>{try{const{id:o,tag:a,type:i,custom:c,version:l,config:p,async:u}=e,f=((e,t=\\\"\\\")=>`${e}@${t}`.replace(/@$/,\\\"\\\"))(i,l),d=await en(f,t,n,p),{js_modules:h,sync_main_only:g}=Yt.get(f),y=h?.main;let w=!g;try{new SharedArrayBuffer(4),w=!0}catch(e){if(w)throw new Error([\\\"Unable to use SharedArrayBuffer due insecure environment.\\\",\\\"Please read requirements in MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer#security_requirements\\\"].join(\\\"\\\\n\\\"))}const m=Le(Kt.get(i)),_=((e,t,n,r)=>({type:t,config:n,interpreter:r,io:Ne.get(r),run:(t,...n)=>e.run(r,t,...n),runAsync:(t,...n)=>e.runAsync(r,t,...n),runEvent:(...t)=>e.runEvent(r,...t)}))(m,c||i,p,d);let b=\\\"run\\\";if(u&&(b+=\\\"Async\\\"),s){let e,t,n=\\\"\\\",r=\\\"\\\";for(const e of rn){const t=s[e];if(t){const s=e.endsWith(\\\"Async\\\");(s&&u||!s&&!u)&&(e.startsWith(\\\"codeBefore\\\")?n=t:r=t)}}(n||r)&&((e,t,n,r)=>{const s=e[t].bind(e);e[t]=\\\"run\\\"===t?(e,t,...o)=>{n&&s(e,n,...o);const a=s(e,Xe(t),...o);return r&&s(e,r,...o),a}:async(e,t,...o)=>{n&&await s(e,n,...o);const a=await s(e,Xe(t),...o);return r&&await s(e,r,...o),a}})(m,b,n,r);for(const n of sn.slice(2)){const r=s[n];if(r){const s=n.endsWith(\\\"Async\\\");if(s&&u||!s&&!u){const s=Ye(r);n.startsWith(\\\"onBefore\\\")?e=s:t=s}}}an(m,_,wn,u,e,t)}let E,v,k,x=null,T=\\\"\\\";w&&(({CustomEvent:E,document:v}=gn),x=o&&v.getElementById(o)||null,k=e=>Ke(x,c||i,e,!0,E));const S=kt(gn,hn,y);return((e,t,n,r)=>{if(\\\"pyodide\\\"===e)return;const s=\\\"polyscript.js_modules\\\";for(const e of Reflect.ownKeys(r))t.registerJSModule(n,`${s}.${e}`,et(r,e));t.registerJSModule(n,s,r)})(i,m,d,S),m.registerJSModule(d,\\\"polyscript\\\",{xworker:wn,currentScript:x,config:_.config,js_modules:S,get target(){return!T&&x&&(\\\"SCRIPT\\\"===a?x.after(Ce(v.createElement(`script-${c||i}`),{id:T=`${o}-target`})):(T=o,x.replaceChildren(),x.style.display=\\\"block\\\")),T}}),ln=m.runEvent.bind(m,d),pn=m.transform.bind(m,d),x&&k(\\\"ready\\\"),s?.onReady&&Ye(s?.onReady).call(m,on.call(m,_,d),wn),await m[b](d,r),x&&k(\\\"done\\\"),postMessage(\\\"polyscript:done\\\"),d}catch(e){postMessage(e)}})(),un(\\\"error\\\"),un(\\\"message\\\"),un(\\\"messageerror\\\")}));\\n\".replace(re,place)],{type:'application/javascript'})),{type:'module'})\n/* c8 ignore stop */\n","import content from 'plain-tag';\n\nconst dedent = {\n object(...args) {\n return this.string(content(...args));\n },\n string(content) {\n for (const line of content.split(/[\\r\\n]+/)) {\n // skip initial empty lines\n if (line.trim().length) {\n // trap indentation at the very first line of code\n if (/^(\\s+)/.test(line))\n content = content.replace(new RegExp('^' + RegExp.$1, 'gm'), '');\n // no indentation? all good: get out of here!\n break;\n }\n }\n return content;\n }\n};\n\n/**\n * Usable both as template literal tag or just as callback for strings, removes all spaces found\n * at the very first line of code encountered while sanitizing, keeping everything else around.\n * @param {string | TemplateStringsArray} tpl either code as string or as template, when used as tag\n * @param {...any} values the template interpolations, when used as tag\n * @returns {string} code without undesired indentation\n */\nconst codedent = (tpl, ...values) => dedent[typeof tpl](tpl, ...values);\n\nexport default codedent;\n","export default function (t) {\n for (var s = t[0], i = 1, l = arguments.length; i < l; i++)\n s += arguments[i] + t[i];\n return s;\n};\n","/**\n * Copyright (C) 2017-present by Andrea Giammarchi - @WebReflection\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n\nconst {replace} = '';\n\n// escape\nconst es = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34);/g;\nconst ca = /[&<>'\"]/g;\n\nconst esca = {\n '&': '&',\n '<': '<',\n '>': '>',\n \"'\": ''',\n '\"': '"'\n};\nconst pe = m => esca[m];\n\n/**\n * Safely escape HTML entities such as `&`, `<`, `>`, `\"`, and `'`.\n * @param {string} es the input to safely escape\n * @returns {string} the escaped input, and it **throws** an error if\n * the input type is unexpected, except for boolean and numbers,\n * converted as string.\n */\nexport const escape = es => replace.call(es, ca, pe);\n\n\n// unescape\nconst unes = {\n '&': '&',\n '&': '&',\n '<': '<',\n '<': '<',\n '>': '>',\n '>': '>',\n ''': \"'\",\n ''': \"'\",\n '"': '\"',\n '"': '\"'\n};\nconst cape = m => unes[m];\n\n/**\n * Safely unescape previously escaped entities such as `&`, `<`, `>`, `\"`,\n * and `'`.\n * @param {string} un a previously escaped string\n * @returns {string} the unescaped input, and it **throws** an error if\n * the input type is unexpected, except for boolean and numbers,\n * converted as string.\n */\nexport const unescape = un => replace.call(un, es, cape);\n","// REQUIRES INTEGRATION TEST\n/* c8 ignore start */\nexport const io = new WeakMap();\nexport const stdio = (init) => {\n const context = init || console;\n const localIO = {\n // allow plugins or other io manipulating logic to reuse\n // the buffered utility exposed in here (see py-editor)\n buffered,\n stderr: (context.stderr || console.error).bind(context),\n stdout: (context.stdout || console.log).bind(context),\n };\n return {\n stderr: (...args) => localIO.stderr(...args),\n stdout: (...args) => localIO.stdout(...args),\n async get(engine) {\n const interpreter = await engine;\n io.set(interpreter, localIO);\n return interpreter;\n },\n };\n};\n\nconst decoder = new TextDecoder();\nexport const buffered = (callback, EOL = 10) => {\n const buffer = [];\n return (maybeUI8) => {\n if (maybeUI8 instanceof Uint8Array) {\n for (const c of maybeUI8) {\n if (c === EOL)\n callback(decoder.decode(new Uint8Array(buffer.splice(0))));\n else\n buffer.push(c);\n }\n }\n // if io.stderr(error) is passed instead\n // or any io.stdout(\"thing\") this should\n // still work as expected\n else {\n callback(maybeUI8);\n }\n };\n};\n/* c8 ignore stop */\n","import $dedent from 'codedent';\nimport { unescape as $unescape } from 'html-escaper';\nimport { io } from './interpreter/_io.js';\n\n/** @type {(tpl: string | TemplateStringsArray, ...values:any[]) => string} */\nconst dedent = $dedent;\n\n/** @type {(value:string) => string} */\nconst unescape = $unescape;\n\nconst { isArray } = Array;\n\nconst { assign, create, defineProperties, defineProperty, entries } = Object;\n\nconst { all, resolve } = new Proxy(Promise, {\n get: ($, name) => $[name].bind($),\n});\n\nconst absoluteURL = (path, base = location.href) =>\n new URL(path, base.replace(/^blob:/, '')).href;\n\n/* c8 ignore start */\nlet id = 0;\nconst nodeInfo = (node, type) => ({\n id: node.id || (node.id = `${type}-w${id++}`),\n tag: node.tagName\n});\n\n/**\n * Notify the main thread about element \"readiness\".\n * @param {HTMLScriptElement | HTMLElement} target the script or custom-type element\n * @param {string} type the custom/type as event prefix\n * @param {string} what the kind of event to dispatch, i.e. `ready` or `done`\n * @param {boolean} [worker = false] `true` if dispatched form a worker, `false` by default if in main\n * @param {globalThis.CustomEvent} [CustomEvent = globalThis.CustomEvent] the `CustomEvent` to use\n */\nconst dispatch = (target, type, what, worker = false, CE = CustomEvent) => {\n target.dispatchEvent(\n new CE(`${type}:${what}`, {\n bubbles: true,\n detail: { worker },\n })\n );\n};\n\nexport const createFunction = value => Function(`'use strict';return (${value})`)();\n\nexport const createResolved = (module, type, config, interpreter) => ({\n type,\n config,\n interpreter,\n io: io.get(interpreter),\n run: (code, ...args) => module.run(interpreter, code, ...args),\n runAsync: (code, ...args) => module.runAsync(interpreter, code, ...args),\n runEvent: (...args) => module.runEvent(interpreter, ...args),\n});\n\nconst dropLine0 = code => code.replace(/^(?:\\n|\\r\\n)/, '');\n\nexport const createOverload = (module, name, before, after) => {\n const method = module[name].bind(module);\n module[name] = name === 'run' ?\n // patch the sync method\n (interpreter, code, ...args) => {\n if (before) method(interpreter, before, ...args);\n const result = method(interpreter, dropLine0(code), ...args);\n if (after) method(interpreter, after, ...args);\n return result;\n } :\n // patch the async one\n async (interpreter, code, ...args) => {\n if (before) await method(interpreter, before, ...args);\n const result = await method(interpreter, dropLine0(code), ...args);\n if (after) await method(interpreter, after, ...args);\n return result;\n };\n};\n\nexport const js_modules = Symbol.for('polyscript.js_modules');\n\nconst jsModules = new Map;\ndefineProperty(globalThis, js_modules, { value: jsModules });\n\nexport const JSModules = new Proxy(jsModules, {\n get: (map, name) => map.get(name),\n has: (map, name) => map.has(name),\n ownKeys: map => [...map.keys()],\n});\n\nconst has = (_, field) => !field.startsWith('_');\n\nconst proxy = (modules, name) => new Proxy(\n modules,\n { has, get: (modules, field) => modules[name][field] }\n);\n\nexport const registerJSModules = (type, module, interpreter, modules) => {\n // Pyodide resolves JS modules magically\n if (type === 'pyodide') return;\n\n // other runtimes need this pretty ugly dance (it works though)\n const jsModules = 'polyscript.js_modules';\n for (const name of Reflect.ownKeys(modules))\n module.registerJSModule(interpreter, `${jsModules}.${name}`, proxy(modules, name));\n module.registerJSModule(interpreter, jsModules, modules);\n};\n\nexport const importJS = (source, name) => import(source).then(esm => {\n jsModules.set(name, { ...esm });\n});\n\nexport const importCSS = href => new Promise((onload, onerror) => {\n if (document.querySelector(`link[href=\"${href}\"]`)) onload();\n document.head.append(\n assign(\n document.createElement('link'),\n { rel: 'stylesheet', href, onload, onerror },\n )\n )\n});\n\nexport const isCSS = source => /\\.css/i.test(new URL(source).pathname);\n/* c8 ignore stop */\n\nexport {\n dedent, unescape,\n dispatch,\n isArray,\n assign,\n create,\n defineProperties,\n defineProperty,\n entries,\n all,\n resolve,\n absoluteURL,\n nodeInfo,\n};\n","import '@ungap/with-resolvers';\nimport fetch from '@webreflection/fetch';\n\nimport { absoluteURL, all, entries, importCSS, importJS, isArray, isCSS } from '../utils.js';\n\nexport const RUNNING_IN_WORKER = !globalThis.window;\n\n// REQUIRES INTEGRATION TEST\n/* c8 ignore start */\n\n// This should be the only helper needed for all Emscripten based FS exports\nexport const writeFile = ({ FS, PATH, PATH_FS }, path, buffer) => {\n const absPath = PATH_FS.resolve(path);\n const dirPath = PATH.dirname(absPath);\n if (FS.mkdirTree) FS.mkdirTree(dirPath);\n else mkdirTree(FS, dirPath);\n return FS.writeFile(absPath, new Uint8Array(buffer), {\n canOwn: true,\n });\n};\n\n// This is instead a fallback for Lua or others\nexport const writeFileShim = (FS, path, buffer) => {\n mkdirTree(FS, dirname(path));\n path = resolve(FS, path);\n return FS.writeFile(path, new Uint8Array(buffer), { canOwn: true });\n};\n\nconst dirname = (path) => {\n const tree = path.split('/');\n tree.pop();\n return tree.join('/');\n};\n\nconst mkdirTree = (FS, path) => {\n const current = [];\n for (const branch of path.split('/')) {\n if (branch === '.' || branch === '..') continue;\n current.push(branch);\n if (branch) FS.mkdir(current.join('/'));\n }\n};\n\nconst resolve = (FS, path) => {\n const tree = [];\n for (const branch of path.split('/')) {\n switch (branch) {\n case '':\n break;\n case '.':\n break;\n case '..':\n tree.pop();\n break;\n default:\n tree.push(branch);\n }\n }\n return [FS.cwd()].concat(tree).join('/').replace(/^\\/+/, '/');\n};\n\nconst calculateFetchPaths = (config_fetch) => {\n for (const { files, to_file, from = '' } of config_fetch) {\n if (files !== undefined && to_file !== undefined)\n throw new Error(\n 'Cannot use \\'to_file\\' and \\'files\\' parameters together!',\n );\n if (files === undefined && to_file === undefined && from.endsWith('/'))\n throw new Error(\n `Couldn't determine the filename from the path ${from}, please supply 'to_file' parameter.`,\n );\n }\n return config_fetch.flatMap(\n ({ from = '', to_folder = '.', to_file, files }) => {\n if (isArray(files))\n return files.map((file) => ({\n url: joinPaths([from, file]),\n path: joinPaths([to_folder, file]),\n }));\n const filename = to_file || from.slice(1 + from.lastIndexOf('/'));\n return [{ url: from, path: joinPaths([to_folder, filename]) }];\n },\n );\n};\n\nconst joinPaths = (parts) => {\n const res = parts\n .map((part) => part.trim().replace(/(^[/]*|[/]*$)/g, ''))\n .filter((p) => p !== '' && p !== '.')\n .join('/');\n\n return parts[0].startsWith('/') ? `/${res}` : res;\n};\n\nconst fetchBuffer = (config_fetch, url) =>\n fetch(absoluteURL(url, base.get(config_fetch))).arrayBuffer();\n\nexport const base = new WeakMap();\n\nexport const fetchPaths = (module, interpreter, config_fetch) =>\n all(\n calculateFetchPaths(config_fetch).map(({ url, path }) =>\n fetchBuffer(config_fetch, url)\n .then((buffer) => module.writeFile(interpreter, path, buffer)),\n ),\n );\n\n const fillName = (source, dest) => dest.endsWith('/') ?\n `${dest}${source.split('/').pop()}` : dest;\n\nconst parseTemplate = (src, map) => src.replace(\n /\\{.+?\\}/g,\n k => {\n if (!map.has(k))\n throw new SyntaxError(`Invalid template: ${k}`);\n return map.get(k);\n }\n);\n\nconst calculateFilesPaths = files => {\n const map = new Map;\n const targets = new Set;\n const sourceDest = [];\n for (const [source, dest] of entries(files)) {\n if (/^\\{.+\\}$/.test(source)) {\n if (map.has(source))\n throw new SyntaxError(`Duplicated template: ${source}`);\n map.set(source, parseTemplate(dest, map));\n }\n else {\n const url = parseTemplate(source, map);\n const path = fillName(url, parseTemplate(dest || './', map));\n if (targets.has(path))\n throw new SyntaxError(`Duplicated destination: ${path}`);\n targets.add(path);\n sourceDest.push({ url, path });\n }\n }\n return sourceDest;\n};\n\nexport const fetchFiles = (module, interpreter, config_files) =>\n all(\n calculateFilesPaths(config_files).map(({ url, path }) =>\n fetchBuffer(config_files, url)\n .then((buffer) => module.writeFile(\n interpreter,\n path,\n buffer,\n url,\n )),\n ),\n );\n\nexport const fetchJSModules = ({ main, worker }) => {\n const promises = [];\n if (worker && RUNNING_IN_WORKER) {\n for (let [source, name] of entries(worker)) {\n source = absoluteURL(source, base.get(worker));\n promises.push(importJS(source, name));\n }\n }\n if (main && !RUNNING_IN_WORKER) {\n for (let [source, name] of entries(main)) {\n source = absoluteURL(source, base.get(main));\n if (isCSS(source)) importCSS(source);\n else promises.push(importJS(source, name));\n }\n }\n return all(promises);\n};\n/* c8 ignore stop */\n","import { dedent } from '../utils.js';\nimport { io } from './_io.js';\n\nexport const loader = new WeakMap();\n\n// REQUIRES INTEGRATION TEST\n/* c8 ignore start */\nexport const registerJSModule = (interpreter, name, value) => {\n if (name === 'polyscript') {\n value.lazy_py_modules = async (...packages) => {\n await loader.get(interpreter)(packages);\n return packages.map(name => interpreter.pyimport(name));\n };\n }\n interpreter.registerJsModule(name, value);\n};\n\nexport const getFormat = (path, url) => {\n if (path.endsWith('/*')) {\n if (/\\.(zip|tar(?:\\.gz)?)$/.test(url))\n return RegExp.$1;\n throw new Error(`Unsupported archive ${url}`);\n }\n return '';\n};\n\nexport const run = (interpreter, code, ...args) => {\n try {\n return interpreter.runPython(dedent(code), ...args);\n }\n catch (error) {\n io.get(interpreter).stderr(error);\n }\n};\n\nexport const runAsync = async (interpreter, code, ...args) => {\n try {\n return await interpreter.runPythonAsync(dedent(code), ...args);\n }\n catch (error) {\n io.get(interpreter).stderr(error);\n }\n};\n\nexport const runEvent = async (interpreter, code, event) => {\n // allows method(event) as well as namespace.method(event)\n // it does not allow fancy brackets names for now\n const [name, ...keys] = code.split('.');\n let target = interpreter.globals.get(name);\n let context;\n for (const key of keys) [context, target] = [target, target[key]];\n try {\n await target.call(context, event);\n }\n catch (error) {\n io.get(interpreter).stderr(error);\n }\n};\n/* c8 ignore stop */\n","// ⚠️ DO NOT MODIFY - SOURCE FILE: \"../../python/mip.py\"\nexport default new TextEncoder().encode(\"from uio import StringIO\\nimport sys\\n\\nclass Response:\\n def __init__(self, f):\\n self.raw = f\\n self.encoding = \\\"utf-8\\\"\\n self._cached = None\\n\\n def close(self):\\n if self.raw:\\n self.raw.close()\\n self.raw = None\\n self._cached = None\\n\\n @property\\n def content(self):\\n if self._cached is None:\\n try:\\n self._cached = self.raw.read()\\n finally:\\n self.raw.close()\\n self.raw = None\\n return self._cached\\n\\n @property\\n def text(self):\\n return str(self.content, self.encoding)\\n\\n def json(self):\\n import ujson\\n\\n return ujson.loads(self.content)\\n\\n\\n# TODO try to support streaming xhr requests, a-la pyodide-http\\nHEADERS_TO_IGNORE = (\\\"user-agent\\\",)\\n\\n\\ntry:\\n import js\\nexcept Exception as err:\\n raise OSError(\\\"This version of urequests can only be used in the browser\\\")\\n\\n# TODO try to support streaming xhr requests, a-la pyodide-http\\n\\nHEADERS_TO_IGNORE = (\\\"user-agent\\\",)\\n\\n\\ndef request(\\n method,\\n url,\\n data=None,\\n json=None,\\n headers={},\\n stream=None,\\n auth=None,\\n timeout=None,\\n parse_headers=True,\\n):\\n from js import XMLHttpRequest\\n\\n xhr = XMLHttpRequest.new()\\n xhr.withCredentials = False\\n\\n if auth is not None:\\n import ubinascii\\n\\n username, password = auth\\n xhr.open(method, url, False, username, password)\\n else:\\n xhr.open(method, url, False)\\n\\n for name, value in headers.items():\\n if name.lower() not in HEADERS_TO_IGNORE:\\n xhr.setRequestHeader(name, value)\\n\\n if timeout:\\n xhr.timeout = int(timeout * 1000)\\n\\n if json is not None:\\n assert data is None\\n import ujson\\n\\n data = ujson.dumps(json)\\n # s.write(b\\\"Content-Type: application/json\\\\r\\\\n\\\")\\n xhr.setRequestHeader(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\n xhr.send(data)\\n\\n # Emulates the construction process in the original urequests\\n resp = Response(StringIO(xhr.responseText))\\n resp.status_code = xhr.status\\n resp.reason = xhr.statusText\\n resp.headers = xhr.getAllResponseHeaders()\\n\\n return resp\\n\\n\\n# Other methods - head, post, put, patch, delete - are not used by\\n# mip and therefore not included\\n\\n\\ndef get(url, **kw):\\n return request(\\\"GET\\\", url, **kw)\\n\\n\\n# Content below this line is from the Micropython MIP package and is covered\\n# by the applicable MIT license:\\n# \\n# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, \\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER \\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING \\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER \\n# DEALINGS IN THE SOFTWARE.\\n\\n# MicroPython package installer\\n# MIT license; Copyright (c) 2022 Jim Mussared\\n\\n\\n_PACKAGE_INDEX = const(\\\"https://micropython.org/pi/v2\\\")\\n_CHUNK_SIZE = 128\\n\\n\\n# This implements os.makedirs(os.dirname(path))\\ndef _ensure_path_exists(path):\\n import os\\n\\n split = path.split(\\\"/\\\")\\n\\n # Handle paths starting with \\\"/\\\".\\n if not split[0]:\\n split.pop(0)\\n split[0] = \\\"/\\\" + split[0]\\n\\n prefix = \\\"\\\"\\n for i in range(len(split) - 1):\\n prefix += split[i]\\n try:\\n os.stat(prefix)\\n except:\\n os.mkdir(prefix)\\n prefix += \\\"/\\\"\\n\\n\\n# Copy from src (stream) to dest (function-taking-bytes)\\ndef _chunk(src, dest):\\n buf = memoryview(bytearray(_CHUNK_SIZE))\\n while True:\\n n = src.readinto(buf)\\n if n == 0:\\n break\\n dest(buf if n == _CHUNK_SIZE else buf[:n])\\n\\n\\n# Check if the specified path exists and matches the hash.\\ndef _check_exists(path, short_hash):\\n import os\\n\\n try:\\n import binascii\\n import hashlib\\n\\n with open(path, \\\"rb\\\") as f:\\n hs256 = hashlib.sha256()\\n _chunk(f, hs256.update)\\n existing_hash = str(binascii.hexlify(hs256.digest())[: len(short_hash)], \\\"utf-8\\\")\\n return existing_hash == short_hash\\n except:\\n return False\\n\\n\\ndef _rewrite_url(url, branch=None):\\n if not branch:\\n branch = \\\"HEAD\\\"\\n if url.startswith(\\\"github:\\\"):\\n url = url[7:].split(\\\"/\\\")\\n url = (\\n \\\"https://raw.githubusercontent.com/\\\"\\n + url[0]\\n + \\\"/\\\"\\n + url[1]\\n + \\\"/\\\"\\n + branch\\n + \\\"/\\\"\\n + \\\"/\\\".join(url[2:])\\n )\\n return url\\n\\n\\ndef _download_file(url, dest):\\n response = get(url)\\n try:\\n if response.status_code != 200:\\n print(\\\"Error\\\", response.status_code, \\\"requesting\\\", url)\\n return False\\n\\n print(\\\"Copying:\\\", dest)\\n _ensure_path_exists(dest)\\n with open(dest, \\\"wb\\\") as f:\\n _chunk(response.raw, f.write)\\n\\n return True\\n finally:\\n response.close()\\n\\n\\ndef _install_json(package_json_url, index, target, version, mpy):\\n response = get(_rewrite_url(package_json_url, version))\\n try:\\n if response.status_code != 200:\\n print(\\\"Package not found:\\\", package_json_url)\\n return False\\n\\n package_json = response.json()\\n finally:\\n response.close()\\n for target_path, short_hash in package_json.get(\\\"hashes\\\", ()):\\n fs_target_path = target + \\\"/\\\" + target_path\\n if _check_exists(fs_target_path, short_hash):\\n print(\\\"Exists:\\\", fs_target_path)\\n else:\\n file_url = \\\"{}/file/{}/{}\\\".format(index, short_hash[:2], short_hash)\\n if not _download_file(file_url, fs_target_path):\\n print(\\\"File not found: {} {}\\\".format(target_path, short_hash))\\n return False\\n for target_path, url in package_json.get(\\\"urls\\\", ()):\\n fs_target_path = target + \\\"/\\\" + target_path\\n if not _download_file(_rewrite_url(url, version), fs_target_path):\\n print(\\\"File not found: {} {}\\\".format(target_path, url))\\n return False\\n for dep, dep_version in package_json.get(\\\"deps\\\", ()):\\n if not _install_package(dep, index, target, dep_version, mpy):\\n return False\\n return True\\n\\n\\ndef _install_package(package, index, target, version, mpy):\\n if (\\n package.startswith(\\\"http://\\\")\\n or package.startswith(\\\"https://\\\")\\n or package.startswith(\\\"github:\\\")\\n ):\\n if package.endswith(\\\".py\\\") or package.endswith(\\\".mpy\\\"):\\n print(\\\"Downloading {} to {}\\\".format(package, target))\\n return _download_file(\\n _rewrite_url(package, version), target + \\\"/\\\" + package.rsplit(\\\"/\\\")[-1]\\n )\\n else:\\n if not package.endswith(\\\".json\\\"):\\n if not package.endswith(\\\"/\\\"):\\n package += \\\"/\\\"\\n package += \\\"package.json\\\"\\n print(\\\"Installing {} to {}\\\".format(package, target))\\n else:\\n if not version:\\n version = \\\"latest\\\"\\n print(\\\"Installing {} ({}) from {} to {}\\\".format(package, version, index, target))\\n\\n mpy_version = (\\n sys.implementation._mpy & 0xFF if mpy and hasattr(sys.implementation, \\\"_mpy\\\") else \\\"py\\\"\\n )\\n\\n package = \\\"{}/package/{}/{}/{}.json\\\".format(index, mpy_version, package, version)\\n\\n return _install_json(package, index, target, version, mpy)\\n\\n\\ndef install(package, index=None, target=None, version=None, mpy=True):\\n if not target:\\n for p in sys.path:\\n if p.endswith(\\\"/lib\\\"):\\n target = p\\n break\\n else:\\n print(\\\"Unable to find lib dir in sys.path\\\")\\n return\\n\\n if not index:\\n index = _PACKAGE_INDEX\\n\\n if _install_package(package, index.rstrip(\\\"/\\\"), target, version, mpy):\\n print(\\\"Done\\\")\\n else:\\n print(\\\"Package may be partially installed\\\")\\n\");","// import fetch from '@webreflection/fetch';\nimport { fetchFiles, fetchJSModules, fetchPaths, writeFile } from './_utils.js';\nimport { getFormat, loader, registerJSModule, run, runAsync, runEvent } from './_python.js';\nimport { stdio, buffered } from './_io.js';\nimport mip from '../python/mip.js';\nimport zip from '../zip.js';\n\nconst type = 'micropython';\n\n// REQUIRES INTEGRATION TEST\n/* c8 ignore start */\nconst mkdir = (FS, path) => {\n try {\n FS.mkdir(path);\n }\n // eslint-disable-next-line no-unused-vars\n catch (_) {\n // ignore as there's no path.exists here\n }\n};\n\nexport default {\n type,\n module: (version = '1.22.0-356') =>\n `https://cdn.jsdelivr.net/npm/@micropython/micropython-webassembly-pyscript@${version}/micropython.mjs`,\n async engine({ loadMicroPython }, config, url) {\n const { stderr, stdout, get } = stdio({\n stderr: buffered(console.error),\n stdout: buffered(console.log),\n });\n url = url.replace(/\\.m?js$/, '.wasm');\n const interpreter = await get(loadMicroPython({ linebuffer: false, stderr, stdout, url }));\n const py_imports = importPackages.bind(interpreter);\n loader.set(interpreter, py_imports);\n if (config.files) await fetchFiles(this, interpreter, config.files);\n if (config.fetch) await fetchPaths(this, interpreter, config.fetch);\n if (config.js_modules) await fetchJSModules(config.js_modules);\n\n // Install Micropython Package\n this.writeFile(interpreter, './mip.py', mip);\n if (config.packages) await py_imports(config.packages);\n return interpreter;\n },\n registerJSModule,\n run,\n runAsync,\n runEvent,\n transform: (interpreter, value) => interpreter.PyProxy.toJs(value),\n writeFile: (interpreter, path, buffer, url) => {\n const { FS, _module: { PATH, PATH_FS } } = interpreter;\n const fs = { FS, PATH, PATH_FS };\n const format = getFormat(path, url);\n if (format) {\n const extractDir = path.slice(0, -1);\n if (extractDir !== './') FS.mkdir(extractDir);\n switch (format) {\n case 'zip': {\n const blob = new Blob([buffer], { type: 'application/zip' });\n return zip().then(async ({ BlobReader, Uint8ArrayWriter, ZipReader }) => {\n const zipFileReader = new BlobReader(blob);\n const zipReader = new ZipReader(zipFileReader);\n for (const entry of await zipReader.getEntries()) {\n const { directory, filename } = entry;\n const name = extractDir + filename;\n if (directory) mkdir(FS, name);\n else {\n mkdir(FS, PATH.dirname(name));\n const buffer = await entry.getData(new Uint8ArrayWriter);\n FS.writeFile(name, buffer, {\n canOwn: true,\n });\n }\n }\n zipReader.close();\n });\n }\n case 'tar.gz': {\n const TMP = './_.tar.gz';\n writeFile(fs, TMP, buffer);\n interpreter.runPython(`\n import os, gzip, tarfile\n tar = tarfile.TarFile(fileobj=gzip.GzipFile(fileobj=open(\"${TMP}\", \"rb\")))\n for f in tar:\n name = f\"${extractDir}{f.name}\"\n if f.type == tarfile.DIRTYPE:\n if f.name != \"./\":\n os.mkdir(name.strip(\"/\"))\n else:\n dir = os.path.dirname(name)\n if not os.path.exists(dir):\n os.mkdir(dir)\n source = tar.extractfile(f)\n with open(name, \"wb\") as dest:\n dest.write(source.read())\n dest.close()\n tar.close()\n os.remove(\"${TMP}\")\n `);\n return;\n }\n }\n }\n return writeFile(fs, path, buffer);\n },\n};\n\nasync function importPackages(packages) {\n const mpyPackageManager = this.pyimport('mip');\n for (const mpyPackage of packages)\n mpyPackageManager.install(mpyPackage);\n}\n/* c8 ignore stop */\n","/* c8 ignore start */\nexport default () => import(/* webpackIgnore: true */'./3rd-party/zip.js');\n/* c8 ignore stop */\n","import { create } from 'gc-hook';\n\nimport { RUNNING_IN_WORKER, fetchFiles, fetchJSModules, fetchPaths, writeFile } from './_utils.js';\nimport { getFormat, loader, registerJSModule, run, runAsync, runEvent } from './_python.js';\nimport { stdio } from './_io.js';\n\nconst type = 'pyodide';\nconst toJsOptions = { dict_converter: Object.fromEntries };\n\n/* c8 ignore start */\nlet overrideFunction = false;\nconst overrideMethod = method => (...args) => {\n try {\n overrideFunction = true;\n return method(...args);\n }\n finally {\n overrideFunction = false;\n }\n};\n\nlet overridden = false;\nconst applyOverride = () => {\n if (overridden) return;\n overridden = true;\n\n const proxies = new WeakMap;\n const onGC = value => value.destroy();\n const patchArgs = args => {\n for (let i = 0; i < args.length; i++) {\n const value = args[i];\n if (\n typeof value === 'function' &&\n 'copy' in value\n ) {\n // avoid seppuku / Harakiri + speed up\n overrideFunction = false;\n // reuse copied value if known already\n let proxy = proxies.get(value)?.deref();\n if (!proxy) {\n try {\n // observe the copy and return a Proxy reference\n proxy = create(value.copy(), onGC);\n proxies.set(value, new WeakRef(proxy));\n }\n catch (error) {\n console.error(error);\n }\n }\n if (proxy) args[i] = proxy;\n overrideFunction = true;\n }\n }\n };\n\n // trap apply to make call possible after the patch\n const { call } = Function;\n const apply = call.bind(call, call.apply);\n // the patch\n Object.defineProperties(Function.prototype, {\n apply: {\n value(context, args) {\n if (overrideFunction) patchArgs(args);\n return apply(this, context, args);\n }\n },\n call: {\n value(context, ...args) {\n if (overrideFunction) patchArgs(args);\n return apply(this, context, args);\n }\n }\n });\n};\n/* c8 ignore stop */\n\n// REQUIRES INTEGRATION TEST\n/* c8 ignore start */\nexport default {\n type,\n module: (version = '0.25.1') =>\n `https://cdn.jsdelivr.net/pyodide/v${version}/full/pyodide.mjs`,\n async engine({ loadPyodide }, config, url) {\n // apply override ASAP then load foreign code\n if (!RUNNING_IN_WORKER && config.experimental_create_proxy === 'auto')\n applyOverride();\n const { stderr, stdout, get } = stdio();\n const indexURL = url.slice(0, url.lastIndexOf('/'));\n const interpreter = await get(\n loadPyodide({ stderr, stdout, indexURL }),\n );\n const py_imports = importPackages.bind(interpreter);\n loader.set(interpreter, py_imports);\n if (config.files) await fetchFiles(this, interpreter, config.files);\n if (config.fetch) await fetchPaths(this, interpreter, config.fetch);\n if (config.js_modules) await fetchJSModules(config.js_modules);\n if (config.packages) await py_imports(config.packages);\n return interpreter;\n },\n registerJSModule,\n run: overrideMethod(run),\n runAsync: overrideMethod(runAsync),\n runEvent: overrideMethod(runEvent),\n transform: ({ ffi: { PyProxy } }, value) => (\n value instanceof PyProxy ?\n value.toJs(toJsOptions) :\n value\n ),\n writeFile: (interpreter, path, buffer, url) => {\n const format = getFormat(path, url);\n if (format) {\n return interpreter.unpackArchive(buffer, format, {\n extractDir: path.slice(0, -1)\n });\n }\n const { FS, PATH, _module: { PATH_FS } } = interpreter;\n return writeFile({ FS, PATH, PATH_FS }, path, buffer);\n },\n};\n\n// exposed utility to import packages via polyscript.lazy_py_modules\nasync function importPackages(packages) {\n await this.loadPackage('micropip');\n const micropip = this.pyimport('micropip');\n await micropip.install(packages, { keep_going: true });\n micropip.destroy();\n}\n/* c8 ignore stop */\n","import fetch from '@webreflection/fetch';\n\nimport { dedent } from '../utils.js';\nimport { fetchFiles, fetchJSModules, fetchPaths } from './_utils.js';\n\nconst type = 'ruby-wasm-wasi';\nconst jsType = type.replace(/\\W+/g, '_');\n\n// MISSING:\n// * there is no VFS apparently or I couldn't reach any\n// * I've no idea how to override the stderr and stdout\n// * I've no idea how to import packages\n\n// REQUIRES INTEGRATION TEST\n/* c8 ignore start */\nexport default {\n type,\n experimental: true,\n module: (version = '2.6.0') =>\n `https://cdn.jsdelivr.net/npm/@ruby/3.2-wasm-wasi@${version}/dist/browser/+esm`,\n async engine({ DefaultRubyVM }, config, url) {\n url = url.replace(/\\/browser\\/\\+esm$/, '/ruby.wasm');\n const buffer = await fetch(url).arrayBuffer();\n const module = await WebAssembly.compile(buffer);\n const { vm: interpreter } = await DefaultRubyVM(module);\n if (config.files) await fetchFiles(this, interpreter, config.files);\n if (config.fetch) await fetchPaths(this, interpreter, config.fetch);\n if (config.js_modules) await fetchJSModules(config.js_modules);\n return interpreter;\n },\n // Fallback to globally defined module fields (i.e. $xworker)\n registerJSModule(interpreter, name, value) {\n name = name.replace(/\\W+/g, '__');\n const id = `__module_${jsType}_${name}`;\n globalThis[id] = value;\n this.run(interpreter, `require \"js\";$${name}=JS.global[:${id}]`);\n delete globalThis[id];\n },\n run: (interpreter, code, ...args) => interpreter.eval(dedent(code), ...args),\n runAsync: (interpreter, code, ...args) => interpreter.evalAsync(dedent(code), ...args),\n async runEvent(interpreter, code, event) {\n // patch common xworker.onmessage/onerror cases\n if (/^xworker\\.(on\\w+)$/.test(code)) {\n const { $1: name } = RegExp;\n const id = `__module_${jsType}_event`;\n globalThis[id] = event;\n this.run(\n interpreter,\n `require \"js\";$xworker.call(\"${name}\",JS.global[:${id}])`,\n );\n delete globalThis[id];\n } else {\n // Experimental: allows only events by fully qualified method name\n const method = this.run(interpreter, `method(:${code})`);\n await method.call(code, interpreter.wrap(event));\n }\n },\n transform: (_, value) => value,\n writeFile: () => {\n throw new Error(`writeFile is not supported in ${type}`);\n },\n};\n/* c8 ignore stop */\n","import { dedent } from '../utils.js';\nimport { fetchFiles, fetchJSModules, fetchPaths, writeFileShim } from './_utils.js';\nimport { io, stdio } from './_io.js';\n\nconst type = 'wasmoon';\n\n// MISSING:\n// * I've no idea how to import packages\n\n// REQUIRES INTEGRATION TEST\n/* c8 ignore start */\nexport default {\n type,\n module: (version = '1.16.0') =>\n `https://cdn.jsdelivr.net/npm/wasmoon@${version}/+esm`,\n async engine({ LuaFactory, LuaLibraries }, config) {\n const { stderr, stdout, get } = stdio();\n const interpreter = await get(new LuaFactory().createEngine());\n interpreter.global.getTable(LuaLibraries.Base, (index) => {\n interpreter.global.setField(index, 'print', stdout);\n interpreter.global.setField(index, 'printErr', stderr);\n });\n if (config.files) await fetchFiles(this, interpreter, config.files);\n if (config.fetch) await fetchPaths(this, interpreter, config.fetch);\n if (config.js_modules) await fetchJSModules(config.js_modules);\n return interpreter;\n },\n // Fallback to globally defined module fields\n registerJSModule: (interpreter, name, value) => {\n interpreter.global.set(name, value);\n },\n run: (interpreter, code, ...args) => {\n try {\n return interpreter.doStringSync(dedent(code), ...args);\n }\n catch (error) {\n io.get(interpreter).stderr(error);\n }\n },\n runAsync: async (interpreter, code, ...args) => {\n try {\n return await interpreter.doString(dedent(code), ...args);\n }\n catch (error) {\n io.get(interpreter).stderr(error);\n }\n },\n runEvent: async (interpreter, code, event) => {\n // allows method(event) as well as namespace.method(event)\n // it does not allow fancy brackets names for now\n const [name, ...keys] = code.split('.');\n let target = interpreter.global.get(name);\n let context;\n for (const key of keys) [context, target] = [target, target[key]];\n try {\n await target.call(context, event);\n }\n catch (error) {\n io.get(interpreter).stderr(error);\n }\n },\n transform: (_, value) => value,\n writeFile: (\n {\n cmodule: {\n module: { FS },\n },\n },\n path,\n buffer,\n ) => writeFileShim(FS, path, buffer),\n};\n/* c8 ignore stop */\n","import { create } from 'gc-hook';\nimport { dedent } from '../utils.js';\nimport { fetchFiles, fetchJSModules, fetchPaths } from './_utils.js';\nimport { io, stdio } from './_io.js';\n\nconst type = 'webr';\nconst r = new WeakMap();\n\n// REQUIRES INTEGRATION TEST\n/* c8 ignore start */\nconst run = async (interpreter, code) => {\n const { shelter, destroy, io } = r.get(interpreter);\n const { output, result } = await shelter.captureR(dedent(code));\n for (const { type, data } of output) io[type](data);\n // this is a double proxy but it's OK as the consumer\n // of the result here needs to invoke explicitly a conversion\n // or trust the `(await p.toJs()).values` returns what's expected.\n return create(result, destroy, { token: false });\n};\n\nexport default {\n type,\n experimental: true,\n module: (version = '0.3.3') =>\n `https://cdn.jsdelivr.net/npm/webr@${version}/dist/webr.mjs`,\n async engine(module, config) {\n const { get } = stdio();\n const interpreter = new module.WebR();\n await get(interpreter.init().then(() => interpreter));\n const shelter = await new interpreter.Shelter();\n r.set(interpreter, {\n module,\n shelter,\n destroy: shelter.destroy.bind(shelter),\n io: io.get(interpreter),\n });\n if (config.files) await fetchFiles(this, interpreter, config.files);\n if (config.fetch) await fetchPaths(this, interpreter, config.fetch);\n if (config.js_modules) await fetchJSModules(config.js_modules);\n return interpreter;\n },\n // Fallback to globally defined module fields (i.e. $xworker)\n registerJSModule(_, name) {\n console.warn(`Experimental interpreter: module ${name} is not supported (yet)`);\n // TODO: as complex JS objects / modules are not allowed\n // it's not clear how we can bind anything or import a module\n // in a context that doesn't understand methods from JS\n // https://docs.r-wasm.org/webr/latest/convert-js-to-r.html#constructing-r-objects-from-javascript-objects\n },\n run,\n runAsync: run,\n async runEvent(interpreter, code, event) {\n // TODO: WebR cannot convert exoteric objects or any literal\n // to an easy to reason about data/frame ... that convertion\n // is reserved for the future:\n // https://docs.r-wasm.org/webr/latest/convert-js-to-r.html#constructing-r-objects-from-javascript-objects\n await interpreter.evalRVoid(`${code}(event)`, {\n env: { event: { type: [ event.type ] } }\n });\n },\n transform: (_, value) => {\n console.log('transforming', value);\n return value;\n },\n writeFile: () => {\n // MAYBE ???\n },\n};\n/* c8 ignore stop */\n","// ⚠️ Part of this file is automatically generated\n// The :RUNTIMES comment is a delimiter and no code should be written/changed after\n// See rollup/build_interpreters.cjs to know more\n\nimport { base } from './interpreter/_utils.js';\n\n/** @type {Map} */\nexport const registry = new Map();\n\n/** @type {Map} */\nexport const configs = new Map();\n\n/** @type {string[]} */\nexport const selectors = [];\n\n/** @type {string[]} */\nexport const prefixes = [];\n\n/* c8 ignore start */\nexport const interpreter = new Proxy(new Map(), {\n get(map, id) {\n if (!map.has(id)) {\n const [type, ...rest] = id.split('@');\n const interpreter = registry.get(type);\n const url = /^(?:\\.?\\.?\\/|https?:\\/\\/)/i.test(rest) \n ? rest.join('@')\n : interpreter.module(...rest);\n map.set(id, {\n url,\n module: import(/* webpackIgnore: true */url),\n engine: interpreter.engine.bind(interpreter),\n });\n }\n const { url, module, engine } = map.get(id);\n return (config, baseURL) =>\n module.then((module) => {\n configs.set(id, config);\n for (const entry of ['files', 'fetch']) {\n const value = config?.[entry];\n if (value) base.set(value, baseURL);\n }\n for (const entry of ['main', 'worker']) {\n const value = config?.js_modules?.[entry];\n if (value) base.set(value, baseURL);\n }\n return engine(module, config, url);\n });\n },\n});\n/* c8 ignore stop */\n\nconst register = (interpreter) => {\n for (const type of [].concat(interpreter.type)) {\n registry.set(type, interpreter);\n selectors.push(`script[type=\"${type}\"]`);\n prefixes.push(`${type}-`);\n }\n};\n\n//:RUNTIMES\nimport micropython from './interpreter/micropython.js';\nimport pyodide from './interpreter/pyodide.js';\nimport ruby_wasm_wasi from './interpreter/ruby-wasm-wasi.js';\nimport wasmoon from './interpreter/wasmoon.js';\nimport webr from './interpreter/webr.js';\nfor (const interpreter of [micropython, pyodide, ruby_wasm_wasi, wasmoon, webr])\n register(interpreter);\n","/**\n * @param {string} text TOML text to parse\n * @returns {object} the resulting JS object\n */\nexport const parse = async (text) => (\n await import(/* webpackIgnore: true */'./3rd-party/toml.js')\n).parse(text);\n","import fetch from '@webreflection/fetch';\n\nimport { interpreter } from './interpreters.js';\nimport { absoluteURL, resolve } from './utils.js';\nimport { parse } from './toml.js';\n\n// REQUIRES INTEGRATION TEST\n/* c8 ignore start */\nexport const getConfigURLAndType = (config, configURL = './config.txt') => {\n let type = typeof config;\n if (type === 'string' && /\\.(json|toml|txt)$/.test(config))\n type = RegExp.$1;\n else\n config = configURL;\n return [absoluteURL(config), type];\n};\n\nconst parseString = config => {\n try {\n return JSON.parse(config);\n }\n // eslint-disable-next-line no-unused-vars\n catch (_) {\n return parse(config);\n }\n};\n/* c8 ignore stop */\n\n/**\n * Parse a generic config if it came from an attribute either as URL\n * or as a serialized string. In XWorker case, accepts a pre-defined\n * options to use as it is to avoid needing at all a fetch operation.\n * In latter case, config will be suffixed as `config.txt`.\n * @param {string} id the interpreter name @ version identifier\n * @param {string | object} config optional config file to parse\n * @param {string} [configURL] optional config URL if config is not string\n * @param {object} [options] optional options used to bootstrap XWorker\n * @returns\n */\nexport const getRuntime = (id, config, configURL, options = {}) => {\n if (config) {\n // REQUIRES INTEGRATION TEST\n /* c8 ignore start */\n const [absolute, type] = getConfigURLAndType(config, configURL);\n if (type === 'json') {\n options = fetch(absolute).json();\n } else if (type === 'toml') {\n options = fetch(absolute).text().then(parse);\n } else if (type === 'string') {\n options = parseString(config);\n } else if (type === 'object' && config) {\n options = config;\n } else if (type === 'txt' && typeof options === 'string') {\n options = parseString(options);\n }\n config = absolute;\n /* c8 ignore stop */\n }\n return resolve(options).then(options => interpreter[id](options, config));\n};\n\n/**\n * @param {string} type the interpreter type\n * @param {string} [version] the optional interpreter version\n * @returns\n */\nexport const getRuntimeID = (type, version = '') =>\n `${type}@${version}`.replace(/@$/, '');\n","export default function (callback = this) {\n return String(callback).replace(\n /^(async\\s*)?(\\bfunction\\b)?(.*?)\\(/,\n (_, isAsync, fn, name) => (\n name && !fn ?\n `${isAsync || \"\"}function ${name}(` :\n _\n ),\n );\n};\n","import { registry } from './interpreters.js';\n\nconst beforeRun = 'BeforeRun';\nconst afterRun = 'AfterRun';\n\nexport const code = [\n `code${beforeRun}`,\n `code${beforeRun}Async`,\n `code${afterRun}`,\n `code${afterRun}Async`,\n];\n\nexport const js = [\n 'onWorker',\n 'onReady',\n `on${beforeRun}`,\n `on${beforeRun}Async`,\n `on${afterRun}`,\n `on${afterRun}Async`,\n];\n\n/* c8 ignore start */\n// create a copy of the resolved wrapper with the original\n// run and runAsync so that, if used within onBeforeRun/Async\n// or onAfterRun/Async polluted entries won't matter and just\n// the native utilities will be available without seppuku.\n// The same applies if called within `onReady` worker hook.\nexport function patch(resolved, interpreter) {\n const { run, runAsync } = registry.get(this.type);\n return {\n ...resolved,\n run: run.bind(this, interpreter),\n runAsync: runAsync.bind(this, interpreter)\n };\n}\n\n/**\n * Created the wrapper to pass along hooked callbacks.\n * @param {object} module the details module\n * @param {object} ref the node or reference to pass as second argument\n * @param {boolean} isAsync if run should be async\n * @param {function?} before callback to run before\n * @param {function?} after callback to run after\n * @returns {object}\n */\nexport const polluteJS = (module, resolved, ref, isAsync, before, after) => {\n if (before || after) {\n const patched = patch.bind(module, resolved);\n const name = isAsync ? 'runAsync' : 'run';\n const method = module[name];\n module[name] = isAsync ?\n async function (interpreter, code, ...args) {\n if (before) await before.call(this, patched(interpreter), ref);\n const result = await method.call(\n this,\n interpreter,\n code,\n ...args\n );\n if (after) await after.call(this, patched(interpreter), ref);\n return result;\n } :\n function (interpreter, code, ...args) {\n if (before) before.call(this, patched(interpreter), ref);\n const result = method.call(this, interpreter, code, ...args);\n if (after) after.call(this, patched(interpreter), ref);\n return result;\n }\n ;\n }\n};\n/* c8 ignore stop */\n","import toJSONCallback from 'to-json-callback';\n\nimport { dedent } from '../utils.js';\nimport { js as jsHooks, code as codeHooks } from '../hooks.js';\n\n// REQUIRES INTEGRATION TEST\n/* c8 ignore start */\nexport default class Hook {\n constructor(interpreter, hooks = {}) {\n const { main, worker } = hooks;\n this.interpreter = interpreter;\n this.onWorker = main?.onWorker;\n // ignore onWorker as that's main only\n for (const key of jsHooks.slice(1))\n this[key] = worker?.[key];\n for (const key of codeHooks)\n this[key] = worker?.[key];\n }\n toJSON() {\n const hooks = {};\n // ignore onWorker as that's main only\n for (const key of jsHooks.slice(1)) {\n if (this[key]) hooks[key] = toJSONCallback(this[key]);\n }\n // code related: exclude `onReady` callback\n for (const key of codeHooks) {\n if (this[key]) hooks[key] = dedent(this[key]());\n }\n return hooks;\n }\n}\n/* c8 ignore stop */\n","import * as JSON from '@ungap/structured-clone/json';\nimport fetch from '@webreflection/fetch';\nimport coincident from 'coincident/window';\nimport xworker from './xworker.js';\nimport { getConfigURLAndType } from '../loader.js';\nimport { assign, create, defineProperties, importCSS, importJS } from '../utils.js';\nimport Hook from './hook.js';\n\n/**\n * @typedef {Object} WorkerOptions custom configuration\n * @prop {string} type the interpreter type to use\n * @prop {string} [version] the optional interpreter version to use\n * @prop {string | object} [config] the optional config to use within such interpreter\n * @prop {string} [configURL] the optional configURL used to resolve config entries\n */\n\nexport default (...args) =>\n /**\n * A XWorker is a Worker facade able to bootstrap a channel with any desired interpreter.\n * @param {string} url the remote file to evaluate on bootstrap\n * @param {WorkerOptions} [options] optional arguments to define the interpreter to use\n * @returns {Worker}\n */\n function XWorker(url, options) {\n const worker = xworker();\n const { postMessage } = worker;\n const isHook = this instanceof Hook;\n\n if (args.length) {\n const [type, version] = args;\n options = assign({}, options || { type, version });\n if (!options.type) options.type = type;\n }\n\n // provide a base url to fetch or load config files from a Worker\n // because there's no location at all in the Worker as it's embedded.\n // fallback to a generic, ignored, config.txt file to still provide a URL.\n const [ config ] = getConfigURLAndType(options.config, options.configURL);\n\n const bootstrap = fetch(url)\n .text()\n .then(code => {\n const hooks = isHook ? this.toJSON() : void 0;\n postMessage.call(worker, { options, config, code, hooks });\n });\n\n const sync = assign(\n coincident(worker, JSON).proxy,\n { importJS, importCSS },\n );\n\n const resolver = Promise.withResolvers();\n\n defineProperties(worker, {\n sync: { value: sync },\n ready: { value: resolver.promise },\n postMessage: {\n value: (data, ...rest) =>\n bootstrap.then(() =>\n postMessage.call(worker, data, ...rest),\n ),\n },\n onerror: {\n writable: true,\n configurable: true,\n value: console.error\n }\n });\n\n worker.addEventListener('message', event => {\n const { data } = event;\n const isError = data instanceof Error;\n if (isError || data === 'polyscript:done') {\n event.stopImmediatePropagation();\n if (isError) {\n resolver.reject(data);\n worker.onerror(create(event, {\n type: { value: 'error' },\n error: { value: data }\n }));\n }\n else resolver.resolve(worker);\n }\n });\n\n if (isHook) this.onWorker?.(this.interpreter, worker);\n\n return worker;\n };\n","export const INVALID_CONTENT = 'Invalid content';\nexport const INVALID_SRC_ATTR = 'Invalid worker attribute';\nexport const INVALID_WORKER_ATTR = 'Invalid worker attribute';\n","import { INVALID_CONTENT, INVALID_SRC_ATTR, INVALID_WORKER_ATTR } from '../errors.js';\n\nimport { dedent, unescape } from '../utils.js';\n\nconst hasCommentsOnly = text => !text\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, '')\n .replace(/^\\s*(?:\\/\\/|#).*/gm, '')\n .trim()\n;\n\n/* c8 ignore start */ // tested via integration\nexport default element => {\n const { src, worker } = element.attributes;\n if (worker) {\n let { value } = worker;\n // throw on worker values as ambiguous\n // @see https://github.com/pyscript/polyscript/issues/43\n if (value) throw new SyntaxError(INVALID_WORKER_ATTR);\n value = src?.value;\n if (!value) {\n // throw on empty src attributes\n if (src) throw new SyntaxError(INVALID_SRC_ATTR);\n if (!element.childElementCount)\n value = element.textContent;\n else {\n const { innerHTML, localName, type } = element;\n const name = type || localName.replace(/-script$/, '');\n value = unescape(innerHTML);\n console.warn(\n `Deprecated: use