open-webui/static/pyscript/core-CPpjJT4b.js.map
2024-05-16 17:49:28 -10:00

1 line
300 KiB
Plaintext

{"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> & 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<string,any>} 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<string,any>} 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<globalThis> | ProxyHandler<Worker>}\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<T, V>}\n */\nexport const obj = (t, v) => ({t, v});\n\n/**\n * @template V\n * @param {V} value\n * @returns {Ctx<V>}\n */\nexport const bound = value => Context.bind(value);\n\n/**\n * @template V, T\n * @param {V} value\n * @returns {V extends Ctx<T> ? ReturnType<V> : 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<V>} Arr\n */\n\n/**\n * @template T, V\n * @typedef {import(\"./utils.js\").Obj<T, V>} Obj\n */\n\n/**\n * @template V\n * @typedef {import(\"./utils.js\").TypeOf<V>} TypeOf\n */\n\n/**\n * @template W, T, V\n * @typedef {W extends Function ? W : W extends Arr<V> ? W[0] : W extends Obj<T, V> ? 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<V> : Obj<T, V>}\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<V>} */ ([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<string, any>} */ (wrap));\n }\n return revive(type, /** @type {ValueOf<W, T, V>} */ (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<V> : Obj<TypeOf<V>, 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<object>} [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<H>} [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<globalThis>} proxy\n * @property {ProxyHandler<Window>} 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<Worker> | 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<r.length;e++)n[e]=r[e];return\\\"ok\\\"}))})}else{const e=(e,t)=>({[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<e.length;n++)t[n]=e.charCodeAt(n)}if(C(i,0),l)throw l}}))}return!!t.set(s,o)}}))}return X.get(e)};Q.transfer=(...e)=>(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<r;n++)t+=arguments[n]+e[n];return t}(...e))},string(e){for(const t of e.split(/[\\\\r\\\\n]+/))if(t.trim().length){/^(\\\\s+)/.test(t)&&(e=e.replace(new RegExp(\\\"^\\\"+RegExp.$1,\\\"gm\\\"),\\\"\\\"));break}return e}},Ne=new WeakMap,Ie=e=>{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<n.length;r++){const s=n[r];if(\\\"function\\\"==typeof s&&\\\"copy\\\"in s){It=!1;let o=e.get(s)?.deref();if(!o)try{o=pe(s.copy(),t),e.set(s,new WeakRef(o))}catch(e){console.error(e)}o&&(n[r]=o),It=!0}}},{call:r}=Function,s=r.bind(r,r.apply);Object.defineProperties(Function.prototype,{apply:{value(e,t){return It&&n(t),s(this,e,t)}},call:{value(e,...t){return It&&n(t),s(this,e,t)}}})};var Dt={type:\\\"pyodide\\\",module:(e=\\\"0.25.1\\\")=>`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&&gt.set(n,o)}for(const t of[\\\"main\\\",\\\"worker\\\"]){const n=e?.js_modules?.[t];n&&gt.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 '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n \"'\": '&#39;',\n '\"': '&quot;'\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 '&amp;': '&',\n '&#38;': '&',\n '&lt;': '<',\n '&#60;': '<',\n '&gt;': '>',\n '&#62;': '>',\n '&apos;': \"'\",\n '&#39;': \"'\",\n '&quot;': '\"',\n '&#34;': '\"'\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<string, object>} */\nexport const registry = new Map();\n\n/** @type {Map<string, object>} */\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 <script type=\"${name}\"> for an always safe content parsing:\\n`,\n value,\n );\n }\n\n const url = URL.createObjectURL(new Blob([dedent(value)], { type: 'text/plain' }));\n // TODO: should we really clean up this? debugging non-existent resources\n // at distance might be very problematic if the url is revoked.\n // setTimeout(URL.revokeObjectURL, 5000, url);\n return url;\n }\n return value;\n }\n // validate ambiguous cases with src and not empty/commented content\n if (src && !hasCommentsOnly(element.textContent))\n throw new SyntaxError(INVALID_CONTENT);\n};\n/* c8 ignore stop */\n","import fetch from '@webreflection/fetch';\nimport { $ } from 'basic-devtools';\n\nimport $xworker from './worker/class.js';\nimport workerURL from './worker/url.js';\nimport { getRuntime, getRuntimeID } from './loader.js';\nimport { registry } from './interpreters.js';\nimport { JSModules, all, dispatch, resolve, defineProperty, nodeInfo, registerJSModules } from './utils.js';\n\nconst getRoot = (script) => {\n let parent = script;\n while (parent.parentNode) parent = parent.parentNode;\n return parent;\n};\n\nexport const queryTarget = (script, idOrSelector) => {\n const root = getRoot(script);\n return root.getElementById(idOrSelector) || $(idOrSelector, root);\n};\n\nconst targets = new WeakMap();\nconst targetDescriptor = {\n get() {\n let target = targets.get(this);\n if (!target) {\n target = document.createElement(`${this.type}-script`);\n targets.set(this, target);\n handle(this);\n }\n return target;\n },\n set(target) {\n if (typeof target === 'string')\n targets.set(this, queryTarget(this, target));\n else {\n targets.set(this, target);\n handle(this);\n }\n },\n};\n\nconst handled = new WeakMap();\n\nexport const interpreters = new Map();\n\nconst execute = async (currentScript, source, XWorker, isAsync) => {\n const { type } = currentScript;\n const module = registry.get(type);\n /* c8 ignore start */\n if (module.experimental)\n console.warn(`The ${type} interpreter is experimental`);\n const [interpreter, content] = await all([\n handled.get(currentScript).interpreter,\n source,\n ]);\n try {\n // temporarily override inherited document.currentScript in a non writable way\n // but it deletes it right after to preserve native behavior (as it's sync: no trouble)\n defineProperty(document, 'currentScript', {\n configurable: true,\n get: () => currentScript,\n });\n registerJSModules(type, module, interpreter, JSModules);\n module.registerJSModule(interpreter, 'polyscript', {\n XWorker,\n currentScript,\n js_modules: JSModules,\n });\n dispatch(currentScript, type, 'ready');\n const result = module[isAsync ? 'runAsync' : 'run'](interpreter, content);\n const done = dispatch.bind(null, currentScript, type, 'done');\n if (isAsync) result.then(done);\n else done();\n return result;\n } finally {\n delete document.currentScript;\n }\n /* c8 ignore stop */\n};\n\nconst getValue = (ref, prefix) => {\n const value = ref?.value;\n return value ? prefix + value : '';\n};\n\nexport const getDetails = (type, id, name, version, config, configURL, runtime = type) => {\n if (!interpreters.has(id)) {\n const details = {\n interpreter: getRuntime(name, config, configURL),\n queue: resolve(),\n XWorker: $xworker(type, version),\n };\n interpreters.set(id, details);\n // enable sane defaults when single interpreter *of kind* is used in the page\n // this allows `xxx-*` attributes to refer to such interpreter without `env` around\n /* c8 ignore start *//* this is tested very well in PyScript */\n if (!interpreters.has(type)) interpreters.set(type, details);\n if (!interpreters.has(runtime)) interpreters.set(runtime, details);\n /* c8 ignore stopt */\n }\n return interpreters.get(id);\n};\n\n/**\n * @param {HTMLScriptElement} script a special type of <script>\n */\nexport const handle = async (script) => {\n // known node, move its companion target after\n // vDOM or other use cases where the script is a tracked element\n if (handled.has(script)) {\n const { target } = script;\n if (target) {\n // if the script is in the head just append target to the body\n if (script.closest('head')) document.body.append(target);\n // in any other case preserve the script position\n else script.after(target);\n }\n }\n // new script to handle ... allow newly created scripts to work\n // just exactly like any other script would\n else {\n // allow a shared config among scripts, beside interpreter,\n // and/or source code with different config or interpreter\n const {\n attributes: { async: isAsync, config, env, target, version },\n src,\n type,\n } = script;\n\n const versionValue = version?.value;\n const name = getRuntimeID(type, versionValue);\n let configValue = getValue(config, '|');\n const id = getValue(env, '') || `${name}${configValue}`;\n configValue = configValue.slice(1);\n\n /* c8 ignore start */\n const url = workerURL(script);\n if (url) {\n const XWorker = $xworker(type, versionValue);\n const xworker = new XWorker(url, {\n ...nodeInfo(script, type),\n async: !!isAsync,\n config: configValue\n });\n handled.set(\n defineProperty(script, 'xworker', { value: xworker }),\n { xworker }\n );\n return;\n }\n /* c8 ignore stop */\n\n const targetValue = getValue(target, '');\n const details = getDetails(type, id, name, versionValue, configValue);\n\n handled.set(\n defineProperty(script, 'target', targetDescriptor),\n details,\n );\n\n if (targetValue) targets.set(script, queryTarget(script, targetValue));\n\n // start fetching external resources ASAP\n const source = src ? fetch(src).text() : script.textContent;\n details.queue = details.queue.then(() =>\n execute(script, source, details.XWorker, !!isAsync),\n );\n }\n};\n","import { $x } from 'basic-devtools';\n\nimport { interpreters } from './script-handler.js';\nimport { all, create } from './utils.js';\nimport { registry, prefixes } from './interpreters.js';\n\n/* c8 ignore start */\nexport const env = new Proxy(create(null), {\n get: (_, name) => new Promise(queueMicrotask).then(\n () => awaitInterpreter(name)\n ),\n});\n\n// attributes are tested via integration / e2e\n// ensure both interpreter and its queue are awaited then returns the interpreter\nconst awaitInterpreter = async (key) => {\n if (interpreters.has(key)) {\n const { interpreter, queue } = interpreters.get(key);\n return (await all([interpreter, queue]))[0];\n }\n\n const available = interpreters.size\n ? `Available interpreters are: ${[...interpreters.keys()]\n .map((r) => `\"${r}\"`)\n .join(', ')}.`\n : 'There are no interpreters in this page.';\n\n throw new Error(`The interpreter \"${key}\" was not found. ${available}`);\n};\n\nexport const listener = async (event) => {\n const { type, currentTarget } = event;\n if (!prefixes.length) return;\n for (let { name, value, ownerElement: el } of $x(\n `./@*[${prefixes.map((p) => `name()=\"${p}${type}\"`).join(' or ')}]`,\n currentTarget,\n )) {\n name = name.slice(0, -(type.length + 1));\n const interpreter = await awaitInterpreter(\n el.getAttribute(`${name}-env`) || name,\n );\n const handler = registry.get(name);\n handler.runEvent(interpreter, value, event);\n }\n};\n\n/**\n * Look for known prefixes and add related listeners.\n * @param {Document | Element} root\n */\nexport const addAllListeners = (root) => {\n if (!prefixes.length) return;\n for (let { name, ownerElement: el } of $x(\n `.//@*[${prefixes\n .map((p) => `starts-with(name(),\"${p}\")`)\n .join(' or ')}]`,\n root,\n )) {\n const i = name.lastIndexOf('-');\n const type = name.slice(i + 1);\n if (type !== 'env') {\n el.addEventListener(type, listener);\n // automatically disable form controls that are not disabled already\n if ('disabled' in el && !el.disabled) {\n el.disabled = true;\n // set these to enable once the interpreter is known (registered + loaded)\n env[name.slice(0, i)].then(() => {\n el.disabled = false;\n });\n }\n }\n }\n};\n/* c8 ignore stop */\n","import xworker from './worker/class.js';\nimport Hook from './worker/hook.js';\n\nconst XWorker = xworker();\n\nexport { Hook, XWorker };\n","import '@ungap/with-resolvers';\nimport { $$ } from 'basic-devtools';\n\nimport { JSModules, assign, create, createOverload, createResolved, dedent, defineProperty, nodeInfo, registerJSModules } from './utils.js';\nimport { getDetails } from './script-handler.js';\nimport { registry as defaultRegistry, prefixes, configs } from './interpreters.js';\nimport { getRuntimeID } from './loader.js';\nimport { addAllListeners } from './listeners.js';\nimport { Hook, XWorker as XW } from './xworker.js';\nimport { polluteJS, js as jsHooks, code as codeHooks } from './hooks.js';\nimport workerURL from './worker/url.js';\n\nexport const CUSTOM_SELECTORS = [];\n\nexport const customObserver = new Map();\n\n/**\n * @typedef {Object} Runtime custom configuration\n * @prop {object} interpreter the bootstrapped interpreter\n * @prop {(url:string, options?: object) => Worker} XWorker an XWorker constructor that defaults to same interpreter on the Worker.\n * @prop {object} config a cloned config used to bootstrap the interpreter\n * @prop {(code:string) => any} run an utility to run code within the interpreter\n * @prop {(code:string) => Promise<any>} runAsync an utility to run code asynchronously within the interpreter\n * @prop {(path:string, data:ArrayBuffer) => void} writeFile an utility to write a file in the virtual FS, if available\n */\n\nconst types = new Map();\nconst waitList = new Map();\n\n// REQUIRES INTEGRATION TEST\n/* c8 ignore start */\n/**\n * @param {Element} node any DOM element registered via define.\n */\nexport const handleCustomType = async (node) => {\n for (const selector of CUSTOM_SELECTORS) {\n if (node.matches(selector)) {\n const type = types.get(selector);\n const details = registry.get(type);\n const { resolve } = waitList.get(type);\n const { options, known } = details;\n\n if (known.has(node)) return;\n known.add(node);\n\n for (const [selector, callback] of customObserver) {\n if (node.matches(selector)) await callback(node);\n }\n\n const {\n interpreter: runtime,\n configURL,\n config,\n version,\n env,\n onerror,\n hooks,\n } = options;\n\n let error;\n try {\n const worker = workerURL(node);\n if (worker) {\n const xworker = XW.call(new Hook(null, hooks), worker, {\n ...nodeInfo(node, type),\n version,\n configURL,\n type: runtime,\n custom: type,\n config: node.getAttribute('config') || config || {},\n async: node.hasAttribute('async')\n });\n defineProperty(node, 'xworker', { value: xworker });\n resolve({ type, xworker });\n return;\n }\n }\n // let the custom type handle errors via its `io`\n catch (workerError) {\n error = workerError;\n }\n\n const name = getRuntimeID(runtime, version);\n const id = env || `${name}${config ? `|${config}` : ''}`;\n const { interpreter: engine, XWorker: Worker } = getDetails(\n type,\n id,\n name,\n version,\n config,\n configURL,\n runtime\n );\n\n const interpreter = await engine;\n\n const module = create(defaultRegistry.get(runtime));\n\n const hook = new Hook(interpreter, hooks);\n\n const XWorker = function XWorker(...args) {\n return Worker.apply(hook, args);\n };\n\n const resolved = {\n ...createResolved(\n module,\n type,\n structuredClone(configs.get(name)),\n interpreter,\n ),\n XWorker,\n };\n\n registerJSModules(runtime, module, interpreter, JSModules);\n module.registerJSModule(interpreter, 'polyscript', {\n XWorker,\n config: resolved.config,\n currentScript: type.startsWith('_') ? null : node,\n js_modules: JSModules,\n });\n\n // patch methods accordingly to hooks (and only if needed)\n for (const suffix of ['Run', 'RunAsync']) {\n let before = '';\n let after = '';\n\n for (const key of codeHooks) {\n const value = hooks?.main?.[key];\n if (value && key.endsWith(suffix)) {\n if (key.startsWith('codeBefore'))\n before = dedent(value());\n else\n after = dedent(value());\n }\n }\n\n if (before || after) {\n createOverload(\n module,\n `r${suffix.slice(1)}`,\n before,\n after,\n );\n }\n\n let beforeCB, afterCB;\n // ignore onReady and onWorker\n for (let i = 2; i < jsHooks.length; i++) {\n const key = jsHooks[i];\n const value = hooks?.main?.[key];\n if (value && key.endsWith(suffix)) {\n if (key.startsWith('onBefore'))\n beforeCB = value;\n else\n afterCB = value;\n }\n }\n polluteJS(module, resolved, node, suffix.endsWith('Async'), beforeCB, afterCB);\n }\n\n details.queue = details.queue.then(() => {\n resolve(resolved);\n if (error) onerror?.(error, node);\n return hooks?.main?.onReady?.(resolved, node);\n });\n }\n }\n};\n\n/**\n * @type {Map<string, {options:object, known:WeakSet<Element>}>}\n */\nconst registry = new Map();\n\n/**\n * @typedef {Object} CustomOptions custom configuration\n * @prop {'pyodide' | 'micropython' | 'ruby-wasm-wasi' | 'wasmoon'} interpreter the interpreter to use\n * @prop {string} [version] the optional interpreter version to use\n * @prop {string} [config] the optional config to use within such interpreter\n */\n\nlet dontBotherCount = 0;\n\n/**\n * Allows custom types and components on the page to receive interpreters to execute any code\n * @param {string} type the unique `<script type=\"...\">` identifier\n * @param {CustomOptions} options the custom type configuration\n */\nexport const define = (type, options) => {\n // allow no-type to be bootstrapped out of the box\n let dontBother = type == null;\n\n if (dontBother)\n type = `_ps${dontBotherCount++}`;\n else if (defaultRegistry.has(type) || registry.has(type))\n throw new Error(`<script type=\"${type}\"> already registered`);\n\n if (!defaultRegistry.has(options?.interpreter))\n throw new Error('Unspecified interpreter');\n\n // allows reaching out the interpreter helpers on events\n defaultRegistry.set(type, defaultRegistry.get(options.interpreter));\n\n // allows selector -> registry by type\n const selectors = [`script[type=\"${type}\"]`];\n\n // ensure a Promise can resolve once a custom type has been bootstrapped\n whenDefined(type);\n\n if (dontBother) {\n // add a script then cleanup everything once that's ready\n const { hooks } = options;\n const onReady = hooks?.main?.onReady;\n options = {\n ...options,\n hooks: {\n ...hooks,\n main: {\n ...hooks?.main,\n onReady(resolved, node) {\n CUSTOM_SELECTORS.splice(CUSTOM_SELECTORS.indexOf(type), 1);\n defaultRegistry.delete(type);\n registry.delete(type);\n waitList.delete(type);\n node.remove();\n onReady?.(resolved);\n }\n }\n },\n };\n document.head.append(\n assign(document.createElement('script'), { type })\n );\n }\n else {\n selectors.push(`${type}-script`);\n prefixes.push(`${type}-`);\n }\n\n for (const selector of selectors) types.set(selector, type);\n CUSTOM_SELECTORS.push(...selectors);\n\n // ensure always same env for this custom type\n registry.set(type, {\n options: assign({ env: type }, options),\n known: new WeakSet(),\n queue: Promise.resolve(),\n });\n\n if (!dontBother) addAllListeners(document);\n $$(selectors.join(',')).forEach(handleCustomType);\n};\n\n/**\n * Resolves whenever a defined custom type is bootstrapped on the page\n * @param {string} type the unique `<script type=\"...\">` identifier\n * @returns {Promise<object>}\n */\nexport const whenDefined = (type) => {\n if (!waitList.has(type)) waitList.set(type, Promise.withResolvers());\n return waitList.get(type).promise;\n};\n/* c8 ignore stop */\n","import stickyModule from 'sticky-module';\nimport { $$ } from 'basic-devtools';\n\nimport { handle } from './script-handler.js';\nimport { assign } from './utils.js';\nimport { selectors, prefixes } from './interpreters.js';\nimport { CUSTOM_SELECTORS, handleCustomType } from './custom.js';\nimport { listener, addAllListeners } from './listeners.js';\n\nimport { customObserver as $customObserver, define as $define, whenDefined as $whenDefined } from './custom.js';\nimport { env as $env } from './listeners.js';\nimport { Hook as $Hook, XWorker as $XWorker } from './xworker.js';\n\n// avoid multiple initialization of the same library\nconst [\n {\n customObserver,\n define,\n whenDefined,\n env,\n Hook,\n XWorker\n },\n alreadyLive\n] = stickyModule(\n 'polyscript',\n {\n customObserver: $customObserver,\n define: $define,\n whenDefined: $whenDefined,\n env: $env,\n Hook: $Hook,\n XWorker: $XWorker\n }\n);\n\nexport { customObserver, define, whenDefined, env, Hook, XWorker };\nexport * from './errors.js';\n\n\nif (!alreadyLive) {\n const mo = new MutationObserver((records) => {\n const selector = selectors.join(',');\n for (const { type, target, attributeName, addedNodes } of records) {\n // attributes are tested via integration / e2e\n /* c8 ignore start */\n if (type === 'attributes') {\n const i = attributeName.lastIndexOf('-') + 1;\n if (i) {\n const prefix = attributeName.slice(0, i);\n for (const p of prefixes) {\n if (prefix === p) {\n const type = attributeName.slice(i);\n if (type !== 'env') {\n const method = target.hasAttribute(attributeName)\n ? 'add'\n : 'remove';\n target[`${method}EventListener`](type, listener);\n }\n break;\n }\n }\n }\n continue;\n }\n for (const node of addedNodes) {\n if (node.nodeType === 1) {\n addAllListeners(node);\n if (selector && node.matches(selector)) handle(node);\n else bootstrap(selector, node, true);\n }\n }\n /* c8 ignore stop */\n }\n });\n\n /* c8 ignore start */\n const bootstrap = (selector, node, shouldHandle) => {\n if (selector) $$(selector, node).forEach(handle);\n selector = CUSTOM_SELECTORS.join(',');\n if (selector) {\n if (shouldHandle) handleCustomType(node);\n $$(selector, node).forEach(handleCustomType);\n }\n };\n /* c8 ignore stop */\n\n const observe = (root) => {\n mo.observe(root, { childList: true, subtree: true, attributes: true });\n return root;\n };\n\n const { attachShadow } = Element.prototype;\n assign(Element.prototype, {\n attachShadow(init) {\n return observe(attachShadow.call(this, init));\n },\n });\n\n // give 3rd party a chance to apply changes before this happens\n queueMicrotask(() => {\n addAllListeners(observe(document));\n bootstrap(selectors.join(','), document, false);\n });\n\n}\n","export default new Map([\n [\"py\", \"pyodide\"],\n [\"mpy\", \"micropython\"],\n]);\n","import TYPES from \"./types.js\";\n\nconst waitForIt = [];\n\nfor (const [TYPE] of TYPES) {\n const selectors = [`script[type=\"${TYPE}\"]`, `${TYPE}-script`];\n for (const element of document.querySelectorAll(selectors.join(\",\"))) {\n const { promise, resolve } = Promise.withResolvers();\n waitForIt.push(promise);\n element.addEventListener(`${TYPE}:done`, resolve, { once: true });\n }\n}\n\n// wait for all the things then cleanup\nPromise.all(waitForIt).then(() => {\n dispatchEvent(new Event(\"py:all-done\"));\n});\n","// ⚠️ This file is an artifact: DO NOT MODIFY\nexport default {\n [\"deprecations-manager\"]: () => import(/* webpackIgnore: true */ \"./plugins/deprecations-manager.js\"),\n error: () => import(/* webpackIgnore: true */ \"./plugins/error.js\"),\n [\"py-editor\"]: () => import(/* webpackIgnore: true */ \"./plugins/py-editor.js\"),\n [\"py-terminal\"]: () => import(/* webpackIgnore: true */ \"./plugins/py-terminal.js\"),\n};\n","import { assign } from \"polyscript/exports\";\n\nconst CLOSEBUTTON =\n \"<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='currentColor' width='12px'><path d='M.293.293a1 1 0 011.414 0L8 6.586 14.293.293a1 1 0 111.414 1.414L9.414 8l6.293 6.293a1 1 0 01-1.414 1.414L8 9.414l-6.293 6.293a1 1 0 01-1.414-1.414L6.586 8 .293 1.707a1 1 0 010-1.414z'/></svg>\";\n\n/**\n * These error codes are used to identify the type of error that occurred.\n * @see https://pyscript.github.io/docs/latest/reference/exceptions.html?highlight=errors\n */\nexport const ErrorCode = {\n GENERIC: \"PY0000\", // Use this only for development then change to a more specific error code\n CONFLICTING_CODE: \"PY0409\",\n BAD_CONFIG: \"PY1000\",\n MICROPIP_INSTALL_ERROR: \"PY1001\",\n BAD_PLUGIN_FILE_EXTENSION: \"PY2000\",\n NO_DEFAULT_EXPORT: \"PY2001\",\n TOP_LEVEL_AWAIT: \"PY9000\",\n // Currently these are created depending on error code received from fetching\n FETCH_ERROR: \"PY0001\",\n FETCH_NAME_ERROR: \"PY0002\",\n FETCH_UNAUTHORIZED_ERROR: \"PY0401\",\n FETCH_FORBIDDEN_ERROR: \"PY0403\",\n FETCH_NOT_FOUND_ERROR: \"PY0404\",\n FETCH_SERVER_ERROR: \"PY0500\",\n FETCH_UNAVAILABLE_ERROR: \"PY0503\",\n};\n\n/**\n * Keys of the ErrorCode object\n * @typedef {keyof ErrorCode} ErrorCodes\n * */\n\nexport class UserError extends Error {\n /**\n * @param {ErrorCodes} errorCode\n * @param {string} message\n * @param {string} messageType\n * */\n constructor(errorCode, message = \"\", messageType = \"text\") {\n super(`(${errorCode}): ${message}`);\n this.errorCode = errorCode;\n this.messageType = messageType;\n this.name = \"UserError\";\n }\n}\n\nexport class FetchError extends UserError {\n /**\n * @param {ErrorCodes} errorCode\n * @param {string} message\n * */\n constructor(errorCode, message) {\n super(errorCode, message);\n this.name = \"FetchError\";\n }\n}\n\nexport class InstallError extends UserError {\n /**\n * @param {ErrorCodes} errorCode\n * @param {string} message\n * */\n constructor(errorCode, message) {\n super(errorCode, message);\n this.name = \"InstallError\";\n }\n}\n\n/**\n * Internal function for creating alert banners on the page\n * @param {string} message The message to be displayed to the user\n * @param {string} level The alert level of the message. Can be any string; 'error' or 'warning' cause matching messages to be emitted to the console\n * @param {string} [messageType=\"text\"] If set to \"html\", the message content will be assigned to the banner's innerHTML directly, instead of its textContent\n * @param {any} [logMessage=true] An additional flag for whether the message should be sent to the console log.\n */\nexport function _createAlertBanner(\n message,\n level,\n messageType = \"text\",\n logMessage = true,\n) {\n switch (`log-${level}-${logMessage}`) {\n case \"log-error-true\":\n console.error(message);\n break;\n case \"log-warning-true\":\n console.warn(message);\n break;\n }\n\n const content = messageType === \"html\" ? \"innerHTML\" : \"textContent\";\n const banner = assign(document.createElement(\"div\"), {\n className: `alert-banner py-${level}`,\n [content]: message,\n });\n\n if (level === \"warning\") {\n const closeButton = assign(document.createElement(\"button\"), {\n id: \"alert-close-button\",\n innerHTML: CLOSEBUTTON,\n });\n\n banner.appendChild(closeButton).addEventListener(\"click\", () => {\n banner.remove();\n });\n }\n\n document.body.prepend(banner);\n}\n","import { FetchError, ErrorCode } from \"./exceptions.js\";\n\n/**\n * @param {Response} response\n * @returns\n */\nexport const getText = (response) => response.text();\n\n/**\n * This is a fetch wrapper that handles any non 200 responses and throws a\n * FetchError with the right ErrorCode. This is useful because our FetchError\n * will automatically create an alert banner.\n *\n * @param {string} url - URL to fetch\n * @param {Request} [options] - options to pass to fetch\n * @returns {Promise<Response>}\n */\nexport async function robustFetch(url, options) {\n let response;\n\n // Note: We need to wrap fetch into a try/catch block because fetch\n // throws a TypeError if the URL is invalid such as http://blah.blah\n try {\n response = await fetch(url, options);\n } catch (err) {\n const error = err;\n let errMsg;\n if (url.startsWith(\"http\")) {\n errMsg =\n `Fetching from URL ${url} failed with error ` +\n `'${error.message}'. Are your filename and path correct?`;\n } else {\n errMsg = `Polyscript: Access to local files\n (using [[fetch]] configurations in &lt;py-config&gt;)\n is not available when directly opening a HTML file;\n you must use a webserver to serve the additional files.\n See <a style=\"text-decoration: underline;\" href=\"https://github.com/pyscript/pyscript/issues/257#issuecomment-1119595062\">this reference</a>\n on starting a simple webserver with Python.\n `;\n }\n throw new FetchError(ErrorCode.FETCH_ERROR, errMsg);\n }\n\n // Note that response.ok is true for 200-299 responses\n if (!response.ok) {\n const errorMsg = `Fetching from URL ${url} failed with error ${response.status} (${response.statusText}). Are your filename and path correct?`;\n switch (response.status) {\n case 404:\n throw new FetchError(ErrorCode.FETCH_NOT_FOUND_ERROR, errorMsg);\n case 401:\n throw new FetchError(\n ErrorCode.FETCH_UNAUTHORIZED_ERROR,\n errorMsg,\n );\n case 403:\n throw new FetchError(ErrorCode.FETCH_FORBIDDEN_ERROR, errorMsg);\n case 500:\n throw new FetchError(ErrorCode.FETCH_SERVER_ERROR, errorMsg);\n case 503:\n throw new FetchError(\n ErrorCode.FETCH_UNAVAILABLE_ERROR,\n errorMsg,\n );\n default:\n throw new FetchError(ErrorCode.FETCH_ERROR, errorMsg);\n }\n }\n return response;\n}\n","/**\n * This file parses a generic <py-config> or config attribute\n * to use as base config for all py-script elements, importing\n * also a queue of plugins *before* the interpreter (if any) resolves.\n */\nimport { $$ } from \"basic-devtools\";\n\nimport TYPES from \"./types.js\";\nimport allPlugins from \"./plugins.js\";\nimport { robustFetch as fetch, getText } from \"./fetch.js\";\nimport { ErrorCode } from \"./exceptions.js\";\n\nconst { BAD_CONFIG, CONFLICTING_CODE } = ErrorCode;\n\nconst badURL = (url, expected = \"\") => {\n let message = `(${BAD_CONFIG}): Invalid URL: ${url}`;\n if (expected) message += `\\nexpected ${expected} content`;\n throw new Error(message);\n};\n\n/**\n * Given a string, returns its trimmed content as text,\n * fetching it from a file if the content is a URL.\n * @param {string} config either JSON, TOML, or a file to fetch\n * @param {string?} type the optional type to enforce\n * @returns {{json: boolean, toml: boolean, text: string}}\n */\nconst configDetails = async (config, type) => {\n let text = config?.trim();\n // we only support an object as root config\n let url = \"\",\n toml = false,\n json = /^{/.test(text) && /}$/.test(text);\n // handle files by extension (relaxing urls parts after)\n if (!json && /\\.(\\w+)(?:\\?\\S*)?$/.test(text)) {\n const ext = RegExp.$1;\n if (ext === \"json\" && type !== \"toml\") json = true;\n else if (ext === \"toml\" && type !== \"json\") toml = true;\n else badURL(text, type);\n url = text;\n text = (await fetch(url).then(getText)).trim();\n }\n return { json, toml: toml || (!json && !!text), text, url };\n};\n\nconst conflictError = (reason) => new Error(`(${CONFLICTING_CODE}): ${reason}`);\n\nconst syntaxError = (type, url, { message }) => {\n let str = `(${BAD_CONFIG}): Invalid ${type}`;\n if (url) str += ` @ ${url}`;\n return new SyntaxError(`${str}\\n${message}`);\n};\n\nconst configs = new Map();\n\nfor (const [TYPE] of TYPES) {\n /** @type {Promise<[...any]>} A Promise wrapping any plugins which should be loaded. */\n let plugins;\n\n /** @type {any} The PyScript configuration parsed from the JSON or TOML object*. May be any of the return types of JSON.parse() or toml-j0.4's parse() ( {number | string | boolean | null | object | Array} ) */\n let parsed;\n\n /** @type {Error | undefined} The error thrown when parsing the PyScript config, if any.*/\n let error;\n\n /** @type {string | undefined} The `configURL` field to normalize all config operations as opposite of guessing it once resolved */\n let configURL;\n\n let config,\n type,\n pyElement,\n pyConfigs = $$(`${TYPE}-config`),\n attrConfigs = $$(\n [\n `script[type=\"${TYPE}\"][config]:not([worker])`,\n `${TYPE}-script[config]:not([worker])`,\n ].join(\",\"),\n );\n\n // throw an error if there are multiple <py-config> or <mpy-config>\n if (pyConfigs.length > 1) {\n error = conflictError(`Too many ${TYPE}-config`);\n } else {\n // throw an error if there are <x-config> and config=\"x\" attributes\n if (pyConfigs.length && attrConfigs.length) {\n error = conflictError(\n `Ambiguous ${TYPE}-config VS config attribute`,\n );\n } else if (pyConfigs.length) {\n [pyElement] = pyConfigs;\n config = pyElement.getAttribute(\"src\") || pyElement.textContent;\n type = pyElement.getAttribute(\"type\");\n } else if (attrConfigs.length) {\n [pyElement, ...attrConfigs] = attrConfigs;\n config = pyElement.getAttribute(\"config\");\n // throw an error if dirrent scripts use different configs\n if (\n attrConfigs.some((el) => el.getAttribute(\"config\") !== config)\n ) {\n error = conflictError(\n \"Unable to use different configs on main\",\n );\n }\n }\n }\n\n // catch possible fetch errors\n if (!error && config) {\n try {\n const { json, toml, text, url } = await configDetails(config, type);\n if (url) configURL = new URL(url, location.href).href;\n config = text;\n if (json || type === \"json\") {\n try {\n parsed = JSON.parse(text);\n } catch (e) {\n error = syntaxError(\"JSON\", url, e);\n }\n } else if (toml || type === \"toml\") {\n try {\n const { parse } = await import(\n /* webpackIgnore: true */ \"./3rd-party/toml.js\"\n );\n parsed = parse(text);\n } catch (e) {\n error = syntaxError(\"TOML\", url, e);\n }\n }\n } catch (e) {\n error = e;\n }\n }\n\n // parse all plugins and optionally ignore only\n // those flagged as \"undesired\" via `!` prefix\n const toBeAwaited = [];\n for (const [key, value] of Object.entries(allPlugins)) {\n if (error) {\n if (key === \"error\") {\n // show on page the config is broken, meaning that\n // it was not possible to disable error plugin neither\n // as that part wasn't correctly parsed anyway\n value().then(({ notify }) => notify(error.message));\n }\n } else if (!parsed?.plugins?.includes(`!${key}`)) {\n toBeAwaited.push(value().then(({ default: p }) => p));\n }\n }\n\n // assign plugins as Promise.all only if needed\n plugins = Promise.all(toBeAwaited);\n\n configs.set(TYPE, { config: parsed, configURL, plugins, error });\n}\n\nexport default configs;\n","export default {\n // allow pyterminal checks to bootstrap\n is_pyterminal: () => false,\n\n /**\n * 'Sleep' for the given number of seconds. Used to implement Python's time.sleep in Worker threads.\n * @param {number} seconds The number of seconds to sleep.\n */\n sleep(seconds) {\n return new Promise(($) => setTimeout($, seconds * 1000));\n },\n};\n","import { defineProperty } from \"polyscript/exports\";\n\n// helper for all script[type=\"py\"] out there\nconst before = (script) => {\n defineProperty(document, \"currentScript\", {\n configurable: true,\n get: () => script,\n });\n};\n\nconst after = () => {\n delete document.currentScript;\n};\n\n// common life-cycle handlers for any node\nexport default async (main, wrap, element, hook) => {\n const isAsync = hook.endsWith(\"Async\");\n const isBefore = hook.startsWith(\"onBefore\");\n // make it possible to reach the current target node via Python\n // or clean up for other scripts executing around this one\n (isBefore ? before : after)(element);\n for (const fn of main(hook)) {\n if (isAsync) await fn(wrap, element);\n else fn(wrap, element);\n }\n};\n","const any = () => true;\nconst error = message => {\n throw new TypeError(message);\n};\n\nconst validator = (type, Class) => {\n const checks = [];\n if (type) {\n for (const t of type.split(/\\s*\\|\\s*/)) {\n if (t === 'object')\n checks.push(v => v !== null && typeof v === t);\n else if (t === 'null')\n checks.push(v => v === null);\n else\n checks.push(v => typeof v === t);\n }\n }\n if (Class) {\n for (const C of [].concat(Class))\n checks.push(o => o instanceof C);\n }\n switch (checks.length) {\n case 0: return any;\n case 1: return checks[0];\n default: return v => checks.some(f => f(v));\n }\n};\n\nconst failure = (type, Class, kind, onerror = error) => value => {\n const message = [`Invalid ${typeof value} ${kind}: expected `];\n if (type) {\n message.push(type);\n if (Class) message.push(' or ');\n }\n if (Class) {\n message.push('an instanceof ');\n message.push([].concat(Class).map(({name}) => name).join(' | '));\n }\n onerror(message.join(''), value);\n};\n\nconst checkFail = (options, kind = 'value') => {\n const type = options?.typeof;\n const Class = options?.instanceof;\n return [\n validator(type, Class),\n failure(type, Class, kind, options?.onerror)\n ];\n};\n\nconst createSet = Set => options => {\n const [check, fail] = checkFail(options);\n return class TypedSet extends Set {\n add(value) {\n return check(value) ? super.add(value) : fail(value);\n }\n };\n};\n\nexport const typedSet = createSet(Set);\nexport const typedWeakSet = createSet(WeakSet);\n\nconst createMap = Map => ([keyOptions, valueOptions]) => {\n const [checkKey, failKey] = checkFail(keyOptions, 'key');\n const [checkValue, failValue] = checkFail(valueOptions);\n return class TypedMap extends Map {\n set(key, value) {\n if (!checkKey(key)) failKey(key);\n if (!checkValue(value)) failValue(value);\n return super.set(key, value);\n }\n };\n};\n\nexport const typedMap = createMap(Map);\nexport const typedWeakMap = createMap(WeakMap);\n","/**\n * Create through Python the pyscript module through\n * the artifact generated at build time.\n * This the returned value is a string that must be used\n * either before a worker execute code or when the module\n * is registered on the main thread.\n */\n\nimport pyscript from \"./stdlib/pyscript.js\";\n\nclass Ignore extends Array {\n #add = false;\n #paths;\n #array;\n constructor(array, ...paths) {\n super();\n this.#array = array;\n this.#paths = paths;\n }\n push(...values) {\n if (this.#add) super.push(...values);\n return this.#array.push(...values);\n }\n path(path) {\n for (const _path of this.#paths) {\n // bails out at the first `true` value\n if ((this.#add = path.startsWith(_path))) break;\n }\n }\n}\n\nconst { entries } = Object;\n\nconst python = [\n \"import os as _os\",\n \"from pathlib import Path as _Path\",\n \"_path = None\",\n];\n\nconst ignore = new Ignore(python, \"./pyweb\");\n\nconst write = (base, literal) => {\n for (const [key, value] of entries(literal)) {\n ignore.path(`${base}/${key}`);\n ignore.push(`_path = _Path(\"${base}/${key}\")`);\n if (typeof value === \"string\") {\n const code = JSON.stringify(value);\n ignore.push(`_path.write_text(${code},encoding=\"utf-8\")`);\n } else {\n // @see https://github.com/pyscript/pyscript/pull/1813#issuecomment-1781502909\n ignore.push(`if not _os.path.exists(\"${base}/${key}\"):`);\n ignore.push(\" _path.mkdir(parents=True, exist_ok=True)\");\n write(`${base}/${key}`, value);\n }\n }\n};\n\nwrite(\".\", pyscript);\n\n// in order to fix js.document in the Worker case\n// we need to bootstrap pyscript module ASAP\npython.push(\"import pyscript as _pyscript\");\n\npython.push(\n ...[\"_Path\", \"_path\", \"_os\", \"_pyscript\"].map((ref) => `del ${ref}`),\n);\npython.push(\"\\n\");\n\nexport const stdlib = python.join(\"\\n\");\nexport const optional = ignore.join(\"\\n\");\n","// ⚠️ This file is an artifact: DO NOT MODIFY\nexport default {\n \"pyscript\": {\n \"__init__.py\": \"# Some notes about the naming conventions and the relationship between various\\n# similar-but-different names.\\n#\\n# import pyscript\\n# this package contains the main user-facing API offered by pyscript. All\\n# the names which are supposed be used by end users should be made\\n# available in pyscript/__init__.py (i.e., this file)\\n#\\n# import _pyscript\\n# this is an internal module implemented in JS. It is used internally by\\n# the pyscript package, end users should not use it directly. For its\\n# implementation, grep for `interpreter.registerJsModule(\\\"_pyscript\\\",\\n# ...)` in core.js\\n#\\n# import js\\n# this is the JS globalThis, as exported by pyodide and/or micropython's\\n# FFIs. As such, it contains different things in the main thread or in a\\n# worker.\\n#\\n# import pyscript.magic_js\\n# this submodule abstracts away some of the differences between the main\\n# thread and the worker. In particular, it defines `window` and `document`\\n# in such a way that these names work in both cases: in the main thread,\\n# they are the \\\"real\\\" objects, in the worker they are proxies which work\\n# thanks to coincident.\\n#\\n# from pyscript import window, document\\n# these are just the window and document objects as defined by\\n# pyscript.magic_js. This is the blessed way to access them from pyscript,\\n# as it works transparently in both the main thread and worker cases.\\n\\nfrom pyscript.display import HTML, display\\nfrom pyscript.fetch import fetch\\nfrom pyscript.magic_js import (\\n RUNNING_IN_WORKER,\\n PyWorker,\\n config,\\n current_target,\\n document,\\n js_modules,\\n sync,\\n window,\\n)\\nfrom pyscript.websocket import WebSocket\\n\\ntry:\\n from pyscript.event_handling import when\\nexcept:\\n # TODO: should we remove this? Or at the very least, we should capture\\n # the traceback otherwise it's very hard to debug\\n from pyscript.util import NotSupported\\n\\n when = NotSupported(\\n \\\"pyscript.when\\\", \\\"pyscript.when currently not available with this interpreter\\\"\\n )\\n\",\n \"display.py\": \"import base64\\nimport html\\nimport io\\nimport re\\n\\nfrom pyscript.magic_js import current_target, document, window\\n\\n_MIME_METHODS = {\\n \\\"savefig\\\": \\\"image/png\\\",\\n \\\"_repr_javascript_\\\": \\\"application/javascript\\\",\\n \\\"_repr_json_\\\": \\\"application/json\\\",\\n \\\"_repr_latex\\\": \\\"text/latex\\\",\\n \\\"_repr_png_\\\": \\\"image/png\\\",\\n \\\"_repr_jpeg_\\\": \\\"image/jpeg\\\",\\n \\\"_repr_pdf_\\\": \\\"application/pdf\\\",\\n \\\"_repr_svg_\\\": \\\"image/svg+xml\\\",\\n \\\"_repr_markdown_\\\": \\\"text/markdown\\\",\\n \\\"_repr_html_\\\": \\\"text/html\\\",\\n \\\"__repr__\\\": \\\"text/plain\\\",\\n}\\n\\n\\ndef _render_image(mime, value, meta):\\n # If the image value is using bytes we should convert it to base64\\n # otherwise it will return raw bytes and the browser will not be able to\\n # render it.\\n if isinstance(value, bytes):\\n value = base64.b64encode(value).decode(\\\"utf-8\\\")\\n\\n # This is the pattern of base64 strings\\n base64_pattern = re.compile(\\n r\\\"^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$\\\"\\n )\\n # If value doesn't match the base64 pattern we should encode it to base64\\n if len(value) > 0 and not base64_pattern.match(value):\\n value = base64.b64encode(value.encode(\\\"utf-8\\\")).decode(\\\"utf-8\\\")\\n\\n data = f\\\"data:{mime};charset=utf-8;base64,{value}\\\"\\n attrs = \\\" \\\".join(['{k}=\\\"{v}\\\"' for k, v in meta.items()])\\n return f'<img src=\\\"{data}\\\" {attrs}></img>'\\n\\n\\ndef _identity(value, meta):\\n return value\\n\\n\\n_MIME_RENDERERS = {\\n \\\"text/plain\\\": html.escape,\\n \\\"text/html\\\": _identity,\\n \\\"image/png\\\": lambda value, meta: _render_image(\\\"image/png\\\", value, meta),\\n \\\"image/jpeg\\\": lambda value, meta: _render_image(\\\"image/jpeg\\\", value, meta),\\n \\\"image/svg+xml\\\": _identity,\\n \\\"application/json\\\": _identity,\\n \\\"application/javascript\\\": lambda value, meta: f\\\"<script>{value}<\\\\\\\\/script>\\\",\\n}\\n\\n\\nclass HTML:\\n \\\"\\\"\\\"\\n Wrap a string so that display() can render it as plain HTML\\n \\\"\\\"\\\"\\n\\n def __init__(self, html):\\n self._html = html\\n\\n def _repr_html_(self):\\n return self._html\\n\\n\\ndef _eval_formatter(obj, print_method):\\n \\\"\\\"\\\"\\n Evaluates a formatter method.\\n \\\"\\\"\\\"\\n if print_method == \\\"__repr__\\\":\\n return repr(obj)\\n elif hasattr(obj, print_method):\\n if print_method == \\\"savefig\\\":\\n buf = io.BytesIO()\\n obj.savefig(buf, format=\\\"png\\\")\\n buf.seek(0)\\n return base64.b64encode(buf.read()).decode(\\\"utf-8\\\")\\n return getattr(obj, print_method)()\\n elif print_method == \\\"_repr_mimebundle_\\\":\\n return {}, {}\\n return None\\n\\n\\ndef _format_mime(obj):\\n \\\"\\\"\\\"\\n Formats object using _repr_x_ methods.\\n \\\"\\\"\\\"\\n if isinstance(obj, str):\\n return html.escape(obj), \\\"text/plain\\\"\\n\\n mimebundle = _eval_formatter(obj, \\\"_repr_mimebundle_\\\")\\n if isinstance(mimebundle, tuple):\\n format_dict, _ = mimebundle\\n else:\\n format_dict = mimebundle\\n\\n output, not_available = None, []\\n for method, mime_type in _MIME_METHODS.items():\\n if mime_type in format_dict:\\n output = format_dict[mime_type]\\n else:\\n output = _eval_formatter(obj, method)\\n\\n if output is None:\\n continue\\n elif mime_type not in _MIME_RENDERERS:\\n not_available.append(mime_type)\\n continue\\n break\\n if output is None:\\n if not_available:\\n window.console.warn(\\n f\\\"Rendered object requested unavailable MIME renderers: {not_available}\\\"\\n )\\n output = repr(output)\\n mime_type = \\\"text/plain\\\"\\n elif isinstance(output, tuple):\\n output, meta = output\\n else:\\n meta = {}\\n return _MIME_RENDERERS[mime_type](output, meta), mime_type\\n\\n\\ndef _write(element, value, append=False):\\n html, mime_type = _format_mime(value)\\n if html == \\\"\\\\\\\\n\\\":\\n return\\n\\n if append:\\n out_element = document.createElement(\\\"div\\\")\\n element.append(out_element)\\n else:\\n out_element = element.lastElementChild\\n if out_element is None:\\n out_element = element\\n\\n if mime_type in (\\\"application/javascript\\\", \\\"text/html\\\"):\\n script_element = document.createRange().createContextualFragment(html)\\n out_element.append(script_element)\\n else:\\n out_element.innerHTML = html\\n\\n\\ndef display(*values, target=None, append=True):\\n if target is None:\\n target = current_target()\\n elif not isinstance(target, str):\\n raise TypeError(f\\\"target must be str or None, not {target.__class__.__name__}\\\")\\n elif target == \\\"\\\":\\n raise ValueError(\\\"Cannot have an empty target\\\")\\n elif target.startswith(\\\"#\\\"):\\n # note: here target is str and not None!\\n # align with @when behavior\\n target = target[1:]\\n\\n element = document.getElementById(target)\\n\\n # If target cannot be found on the page, a ValueError is raised\\n if element is None:\\n raise ValueError(\\n f\\\"Invalid selector with id={target}. Cannot be found in the page.\\\"\\n )\\n\\n # if element is a <script type=\\\"py\\\">, it has a 'target' attribute which\\n # points to the visual element holding the displayed values. In that case,\\n # use that.\\n if element.tagName == \\\"SCRIPT\\\" and hasattr(element, \\\"target\\\"):\\n element = element.target\\n\\n for v in values:\\n if not append:\\n element.replaceChildren()\\n _write(element, v, append=append)\\n\",\n \"event_handling.py\": \"import inspect\\n\\ntry:\\n from pyodide.ffi.wrappers import add_event_listener\\n\\nexcept ImportError:\\n\\n def add_event_listener(el, event_type, func):\\n el.addEventListener(event_type, func)\\n\\n\\nfrom pyscript.magic_js import document\\n\\n\\ndef when(event_type=None, selector=None):\\n \\\"\\\"\\\"\\n Decorates a function and passes py-* events to the decorated function\\n The events might or not be an argument of the decorated function\\n \\\"\\\"\\\"\\n\\n def decorator(func):\\n if isinstance(selector, str):\\n elements = document.querySelectorAll(selector)\\n else:\\n # TODO: This is a hack that will be removed when pyscript becomes a package\\n # and we can better manage the imports without circular dependencies\\n from pyweb import pydom\\n\\n if isinstance(selector, pydom.Element):\\n elements = [selector._js]\\n elif isinstance(selector, pydom.ElementCollection):\\n elements = [el._js for el in selector]\\n else:\\n raise ValueError(\\n f\\\"Invalid selector: {selector}. Selector must\\\"\\n \\\" be a string, a pydom.Element or a pydom.ElementCollection.\\\"\\n )\\n try:\\n sig = inspect.signature(func)\\n # Function doesn't receive events\\n if not sig.parameters:\\n\\n def wrapper(*args, **kwargs):\\n func()\\n\\n else:\\n wrapper = func\\n\\n except AttributeError:\\n # TODO: this is currently an quick hack to get micropython working but we need\\n # to actually properly replace inspect.signature with something else\\n def wrapper(*args, **kwargs):\\n try:\\n return func(*args, **kwargs)\\n except TypeError as e:\\n if \\\"takes 0 positional arguments\\\" in str(e):\\n return func()\\n\\n raise\\n\\n for el in elements:\\n add_event_listener(el, event_type, wrapper)\\n\\n return func\\n\\n return decorator\\n\",\n \"fetch.py\": \"import json\\n\\nimport js\\nfrom pyscript.util import as_bytearray\\n\\n\\n### wrap the response to grant Pythonic results\\nclass _Response:\\n def __init__(self, response):\\n self._response = response\\n\\n # grant access to response.ok and other fields\\n def __getattr__(self, attr):\\n return getattr(self._response, attr)\\n\\n # exposed methods with Pythonic results\\n async def arrayBuffer(self):\\n buffer = await self._response.arrayBuffer()\\n # works in Pyodide\\n if hasattr(buffer, \\\"to_py\\\"):\\n return buffer.to_py()\\n # shims in MicroPython\\n return memoryview(as_bytearray(buffer))\\n\\n async def blob(self):\\n return await self._response.blob()\\n\\n async def bytearray(self):\\n buffer = await self._response.arrayBuffer()\\n return as_bytearray(buffer)\\n\\n async def json(self):\\n return json.loads(await self.text())\\n\\n async def text(self):\\n return await self._response.text()\\n\\n\\n### allow direct await to _Response methods\\nclass _DirectResponse:\\n @staticmethod\\n def setup(promise, response):\\n promise._response = _Response(response)\\n return promise._response\\n\\n def __init__(self, promise):\\n self._promise = promise\\n promise._response = None\\n promise.arrayBuffer = self.arrayBuffer\\n promise.blob = self.blob\\n promise.bytearray = self.bytearray\\n promise.json = self.json\\n promise.text = self.text\\n\\n async def _response(self):\\n if not self._promise._response:\\n await self._promise\\n return self._promise._response\\n\\n async def arrayBuffer(self):\\n response = await self._response()\\n return await response.arrayBuffer()\\n\\n async def blob(self):\\n response = await self._response()\\n return await response.blob()\\n\\n async def bytearray(self):\\n response = await self._response()\\n return await response.bytearray()\\n\\n async def json(self):\\n response = await self._response()\\n return await response.json()\\n\\n async def text(self):\\n response = await self._response()\\n return await response.text()\\n\\n\\ndef fetch(url, **kw):\\n # workaround Pyodide / MicroPython dict <-> js conversion\\n options = js.JSON.parse(json.dumps(kw))\\n awaited = lambda response, *args: _DirectResponse.setup(promise, response)\\n promise = js.fetch(url, options).then(awaited)\\n _DirectResponse(promise)\\n return promise\\n\",\n \"ffi.py\": \"try:\\n import js\\n from pyodide.ffi import create_proxy as _cp\\n from pyodide.ffi import to_js as _py_tjs\\n\\n from_entries = js.Object.fromEntries\\n\\n def _tjs(value, **kw):\\n if not hasattr(kw, \\\"dict_converter\\\"):\\n kw[\\\"dict_converter\\\"] = from_entries\\n return _py_tjs(value, **kw)\\n\\nexcept:\\n from jsffi import create_proxy as _cp\\n from jsffi import to_js as _tjs\\n\\ncreate_proxy = _cp\\nto_js = _tjs\\n\",\n \"magic_js.py\": \"import json\\nimport sys\\n\\nimport js as globalThis\\nfrom polyscript import config as _config\\nfrom polyscript import js_modules\\nfrom pyscript.util import NotSupported\\n\\nRUNNING_IN_WORKER = not hasattr(globalThis, \\\"document\\\")\\n\\nconfig = json.loads(globalThis.JSON.stringify(_config))\\n\\n\\n# allow `from pyscript.js_modules.xxx import yyy`\\nclass JSModule:\\n def __init__(self, name):\\n self.name = name\\n\\n def __getattr__(self, field):\\n # avoid pyodide looking for non existent fields\\n if not field.startswith(\\\"_\\\"):\\n return getattr(getattr(js_modules, self.name), field)\\n\\n\\n# generate N modules in the system that will proxy the real value\\nfor name in globalThis.Reflect.ownKeys(js_modules):\\n sys.modules[f\\\"pyscript.js_modules.{name}\\\"] = JSModule(name)\\nsys.modules[\\\"pyscript.js_modules\\\"] = js_modules\\n\\nif RUNNING_IN_WORKER:\\n import polyscript\\n\\n PyWorker = NotSupported(\\n \\\"pyscript.PyWorker\\\",\\n \\\"pyscript.PyWorker works only when running in the main thread\\\",\\n )\\n\\n try:\\n globalThis.SharedArrayBuffer.new(4)\\n import js\\n\\n window = polyscript.xworker.window\\n document = window.document\\n js.document = document\\n except:\\n globalThis.console.debug(\\\"SharedArrayBuffer is not available\\\")\\n # in this scenario none of the utilities would work\\n # as expected so we better export these as NotSupported\\n window = NotSupported(\\n \\\"pyscript.window\\\",\\n \\\"pyscript.window in workers works only via SharedArrayBuffer\\\",\\n )\\n document = NotSupported(\\n \\\"pyscript.document\\\",\\n \\\"pyscript.document in workers works only via SharedArrayBuffer\\\",\\n )\\n\\n sync = polyscript.xworker.sync\\n\\n # in workers the display does not have a default ID\\n # but there is a sync utility from xworker\\n def current_target():\\n return polyscript.target\\n\\nelse:\\n import _pyscript\\n from _pyscript import PyWorker\\n\\n window = globalThis\\n document = globalThis.document\\n sync = NotSupported(\\n \\\"pyscript.sync\\\", \\\"pyscript.sync works only when running in a worker\\\"\\n )\\n\\n # in MAIN the current element target exist, just use it\\n def current_target():\\n return _pyscript.target\\n\",\n \"util.py\": \"import js\\n\\n\\ndef as_bytearray(buffer):\\n ui8a = js.Uint8Array.new(buffer)\\n size = ui8a.length\\n ba = bytearray(size)\\n for i in range(0, size):\\n ba[i] = ui8a[i]\\n return ba\\n\\n\\nclass NotSupported:\\n \\\"\\\"\\\"\\n Small helper that raises exceptions if you try to get/set any attribute on\\n it.\\n \\\"\\\"\\\"\\n\\n def __init__(self, name, error):\\n object.__setattr__(self, \\\"name\\\", name)\\n object.__setattr__(self, \\\"error\\\", error)\\n\\n def __repr__(self):\\n return f\\\"<NotSupported {self.name} [{self.error}]>\\\"\\n\\n def __getattr__(self, attr):\\n raise AttributeError(self.error)\\n\\n def __setattr__(self, attr, value):\\n raise AttributeError(self.error)\\n\\n def __call__(self, *args):\\n raise TypeError(self.error)\\n\",\n \"websocket.py\": \"import js\\nfrom pyscript.util import as_bytearray\\n\\ncode = \\\"code\\\"\\nprotocols = \\\"protocols\\\"\\nreason = \\\"reason\\\"\\n\\n\\nclass EventMessage:\\n def __init__(self, event):\\n self._event = event\\n\\n def __getattr__(self, attr):\\n value = getattr(self._event, attr)\\n\\n if attr == \\\"data\\\" and not isinstance(value, str):\\n if hasattr(value, \\\"to_py\\\"):\\n return value.to_py()\\n # shims in MicroPython\\n return memoryview(as_bytearray(value))\\n\\n return value\\n\\n\\nclass WebSocket(object):\\n CONNECTING = 0\\n OPEN = 1\\n CLOSING = 2\\n CLOSED = 3\\n\\n def __init__(self, **kw):\\n url = kw[\\\"url\\\"]\\n if protocols in kw:\\n socket = js.WebSocket.new(url, kw[protocols])\\n else:\\n socket = js.WebSocket.new(url)\\n object.__setattr__(self, \\\"_ws\\\", socket)\\n\\n for t in [\\\"onclose\\\", \\\"onerror\\\", \\\"onmessage\\\", \\\"onopen\\\"]:\\n if t in kw:\\n socket[t] = kw[t]\\n\\n def __getattr__(self, attr):\\n return getattr(self._ws, attr)\\n\\n def __setattr__(self, attr, value):\\n if attr == \\\"onmessage\\\":\\n self._ws[attr] = lambda e: value(EventMessage(e))\\n else:\\n self._ws[attr] = value\\n\\n def close(self, **kw):\\n if code in kw and reason in kw:\\n self._ws.close(kw[code], kw[reason])\\n elif code in kw:\\n self._ws.close(kw[code])\\n else:\\n self._ws.close()\\n\\n def send(self, data):\\n if isinstance(data, str):\\n self._ws.send(data)\\n else:\\n buffer = js.Uint8Array.new(len(data))\\n for pos, b in enumerate(data):\\n buffer[pos] = b\\n self._ws.send(buffer)\\n\"\n },\n \"pyweb\": {\n \"__init__.py\": \"from .pydom import dom as pydom\\n\",\n \"media.py\": \"from pyodide.ffi import to_js\\nfrom pyscript import window\\n\\n\\nclass Device:\\n \\\"\\\"\\\"Device represents a media input or output device, such as a microphone,\\n camera, or headset.\\n \\\"\\\"\\\"\\n\\n def __init__(self, device):\\n self._js = device\\n\\n @property\\n def id(self):\\n return self._js.deviceId\\n\\n @property\\n def group(self):\\n return self._js.groupId\\n\\n @property\\n def kind(self):\\n return self._js.kind\\n\\n @property\\n def label(self):\\n return self._js.label\\n\\n def __getitem__(self, key):\\n return getattr(self, key)\\n\\n @classmethod\\n async def load(cls, audio=False, video=True):\\n \\\"\\\"\\\"Load the device stream.\\\"\\\"\\\"\\n options = window.Object.new()\\n options.audio = audio\\n if isinstance(video, bool):\\n options.video = video\\n else:\\n # TODO: Think this can be simplified but need to check it on the pyodide side\\n\\n # TODO: this is pyodide specific. shouldn't be!\\n options.video = window.Object.new()\\n for k in video:\\n setattr(\\n options.video,\\n k,\\n to_js(video[k], dict_converter=window.Object.fromEntries),\\n )\\n\\n stream = await window.navigator.mediaDevices.getUserMedia(options)\\n return stream\\n\\n async def get_stream(self):\\n key = self.kind.replace(\\\"input\\\", \\\"\\\").replace(\\\"output\\\", \\\"\\\")\\n options = {key: {\\\"deviceId\\\": {\\\"exact\\\": self.id}}}\\n\\n return await self.load(**options)\\n\\n\\nasync def list_devices() -> list[dict]:\\n \\\"\\\"\\\"\\n Return the list of the currently available media input and output devices,\\n such as microphones, cameras, headsets, and so forth.\\n\\n Output:\\n\\n list(dict) - list of dictionaries representing the available media devices.\\n Each dictionary has the following keys:\\n * deviceId: a string that is an identifier for the represented device\\n that is persisted across sessions. It is un-guessable by other\\n applications and unique to the origin of the calling application.\\n It is reset when the user clears cookies (for Private Browsing, a\\n different identifier is used that is not persisted across sessions).\\n\\n * groupId: a string that is a group identifier. Two devices have the same\\n group identifier if they belong to the same physical device — for\\n example a monitor with both a built-in camera and a microphone.\\n\\n * kind: an enumerated value that is either \\\"videoinput\\\", \\\"audioinput\\\"\\n or \\\"audiooutput\\\".\\n\\n * label: a string describing this device (for example \\\"External USB\\n Webcam\\\").\\n\\n Note: the returned list will omit any devices that are blocked by the document\\n Permission Policy: microphone, camera, speaker-selection (for output devices),\\n and so on. Access to particular non-default devices is also gated by the\\n Permissions API, and the list will omit devices for which the user has not\\n granted explicit permission.\\n \\\"\\\"\\\"\\n # https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices\\n return [\\n Device(obj) for obj in await window.navigator.mediaDevices.enumerateDevices()\\n ]\\n\",\n \"pydom.py\": \"try:\\n from typing import Any\\nexcept ImportError:\\n Any = \\\"Any\\\"\\n\\ntry:\\n import warnings\\nexcept ImportError:\\n # TODO: For now it probably means we are in MicroPython. We should figure\\n # out the \\\"right\\\" way to handle this. For now we just ignore the warning\\n # and logging to console\\n class warnings:\\n @staticmethod\\n def warn(*args, **kwargs):\\n print(\\\"WARNING: \\\", *args, **kwargs)\\n\\n\\ntry:\\n from functools import cached_property\\nexcept ImportError:\\n # TODO: same comment about micropython as above\\n cached_property = property\\n\\ntry:\\n from pyodide.ffi import JsProxy\\nexcept ImportError:\\n # TODO: same comment about micropython as above\\n def JsProxy(obj):\\n return obj\\n\\n\\nfrom pyscript import display, document, window\\n\\nalert = window.alert\\n\\n\\nclass BaseElement:\\n def __init__(self, js_element):\\n self._js = js_element\\n self._parent = None\\n self.style = StyleProxy(self)\\n self._proxies = {}\\n\\n def __eq__(self, obj):\\n \\\"\\\"\\\"Check if the element is the same as the other element by comparing\\n the underlying JS element\\\"\\\"\\\"\\n return isinstance(obj, BaseElement) and obj._js == self._js\\n\\n @property\\n def parent(self):\\n if self._parent:\\n return self._parent\\n\\n if self._js.parentElement:\\n self._parent = self.__class__(self._js.parentElement)\\n\\n return self._parent\\n\\n @property\\n def __class(self):\\n return self.__class__ if self.__class__ != PyDom else Element\\n\\n def create(self, type_, is_child=True, classes=None, html=None, label=None):\\n js_el = document.createElement(type_)\\n element = self.__class(js_el)\\n\\n if classes:\\n for class_ in classes:\\n element.add_class(class_)\\n\\n if html is not None:\\n element.html = html\\n\\n if label is not None:\\n element.label = label\\n\\n if is_child:\\n self.append(element)\\n\\n return element\\n\\n def find(self, selector):\\n \\\"\\\"\\\"Return an ElementCollection representing all the child elements that\\n match the specified selector.\\n\\n Args:\\n selector (str): A string containing a selector expression\\n\\n Returns:\\n ElementCollection: A collection of elements matching the selector\\n \\\"\\\"\\\"\\n elements = self._js.querySelectorAll(selector)\\n if not elements:\\n return None\\n return ElementCollection([Element(el) for el in elements])\\n\\n\\nclass Element(BaseElement):\\n @property\\n def children(self):\\n return [self.__class__(el) for el in self._js.children]\\n\\n def append(self, child):\\n # TODO: this is Pyodide specific for now!!!!!!\\n # if we get passed a JSProxy Element directly we just map it to the\\n # higher level Python element\\n if isinstance(child, JsProxy):\\n return self.append(Element(child))\\n\\n elif isinstance(child, Element):\\n self._js.appendChild(child._js)\\n\\n return child\\n\\n elif isinstance(child, ElementCollection):\\n for el in child:\\n self.append(el)\\n\\n # -------- Pythonic Interface to Element -------- #\\n @property\\n def html(self):\\n return self._js.innerHTML\\n\\n @html.setter\\n def html(self, value):\\n self._js.innerHTML = value\\n\\n @property\\n def text(self):\\n return self._js.textContent\\n\\n @text.setter\\n def text(self, value):\\n self._js.textContent = value\\n\\n @property\\n def content(self):\\n # TODO: This breaks with with standard template elements. Define how to best\\n # handle this specifica use case. Just not support for now?\\n if self._js.tagName == \\\"TEMPLATE\\\":\\n warnings.warn(\\n \\\"Content attribute not supported for template elements.\\\", stacklevel=2\\n )\\n return None\\n return self._js.innerHTML\\n\\n @content.setter\\n def content(self, value):\\n # TODO: (same comment as above)\\n if self._js.tagName == \\\"TEMPLATE\\\":\\n warnings.warn(\\n \\\"Content attribute not supported for template elements.\\\", stacklevel=2\\n )\\n return\\n\\n display(value, target=self.id)\\n\\n @property\\n def id(self):\\n return self._js.id\\n\\n @id.setter\\n def id(self, value):\\n self._js.id = value\\n\\n @property\\n def options(self):\\n if \\\"options\\\" in self._proxies:\\n return self._proxies[\\\"options\\\"]\\n\\n if not self._js.tagName.lower() in {\\\"select\\\", \\\"datalist\\\", \\\"optgroup\\\"}:\\n raise AttributeError(\\n f\\\"Element {self._js.tagName} has no options attribute.\\\"\\n )\\n self._proxies[\\\"options\\\"] = OptionsProxy(self)\\n return self._proxies[\\\"options\\\"]\\n\\n @property\\n def value(self):\\n return self._js.value\\n\\n @value.setter\\n def value(self, value):\\n # in order to avoid confusion to the user, we don't allow setting the\\n # value of elements that don't have a value attribute\\n if not hasattr(self._js, \\\"value\\\"):\\n raise AttributeError(\\n f\\\"Element {self._js.tagName} has no value attribute. If you want to \\\"\\n \\\"force a value attribute, set it directly using the `_js.value = <value>` \\\"\\n \\\"javascript API attribute instead.\\\"\\n )\\n self._js.value = value\\n\\n @property\\n def selected(self):\\n return self._js.selected\\n\\n @selected.setter\\n def selected(self, value):\\n # in order to avoid confusion to the user, we don't allow setting the\\n # value of elements that don't have a value attribute\\n if not hasattr(self._js, \\\"selected\\\"):\\n raise AttributeError(\\n f\\\"Element {self._js.tagName} has no value attribute. If you want to \\\"\\n \\\"force a value attribute, set it directly using the `_js.value = <value>` \\\"\\n \\\"javascript API attribute instead.\\\"\\n )\\n self._js.selected = value\\n\\n def clone(self, new_id=None):\\n clone = Element(self._js.cloneNode(True))\\n clone.id = new_id\\n\\n return clone\\n\\n def remove_class(self, classname):\\n classList = self._js.classList\\n if isinstance(classname, list):\\n classList.remove(*classname)\\n else:\\n classList.remove(classname)\\n return self\\n\\n def add_class(self, classname):\\n classList = self._js.classList\\n if isinstance(classname, list):\\n classList.add(*classname)\\n else:\\n self._js.classList.add(classname)\\n return self\\n\\n @property\\n def classes(self):\\n classes = self._js.classList.values()\\n return [x for x in classes]\\n\\n def show_me(self):\\n self._js.scrollIntoView()\\n\\n def snap(\\n self,\\n to: BaseElement | str = None,\\n width: int | None = None,\\n height: int | None = None,\\n ):\\n \\\"\\\"\\\"\\n Captures a snapshot of a video element. (Only available for video elements)\\n\\n Inputs:\\n\\n * to: element where to save the snapshot of the video frame to\\n * width: width of the image\\n * height: height of the image\\n\\n Output:\\n (Element) canvas element where the video frame snapshot was drawn into\\n \\\"\\\"\\\"\\n if self._js.tagName != \\\"VIDEO\\\":\\n raise AttributeError(\\\"Snap method is only available for video Elements\\\")\\n\\n if to is None:\\n canvas = self.create(\\\"canvas\\\")\\n if width is None:\\n width = self._js.width\\n if height is None:\\n height = self._js.height\\n canvas._js.width = width\\n canvas._js.height = height\\n\\n elif isistance(to, Element):\\n if to._js.tagName != \\\"CANVAS\\\":\\n raise TypeError(\\\"Element to snap to must a canvas.\\\")\\n canvas = to\\n elif getattr(to, \\\"tagName\\\", \\\"\\\") == \\\"CANVAS\\\":\\n canvas = Element(to)\\n elif isinstance(to, str):\\n canvas = pydom[to][0]\\n if canvas._js.tagName != \\\"CANVAS\\\":\\n raise TypeError(\\\"Element to snap to must a be canvas.\\\")\\n\\n canvas.draw(self, width, height)\\n\\n return canvas\\n\\n def download(self, filename: str = \\\"snapped.png\\\") -> None:\\n \\\"\\\"\\\"Download the current element (only available for canvas elements) with the filename\\n provided in input.\\n\\n Inputs:\\n * filename (str): name of the file being downloaded\\n\\n Output:\\n None\\n \\\"\\\"\\\"\\n if self._js.tagName != \\\"CANVAS\\\":\\n raise AttributeError(\\n \\\"The download method is only available for canvas Elements\\\"\\n )\\n\\n link = self.create(\\\"a\\\")\\n link._js.download = filename\\n link._js.href = self._js.toDataURL()\\n link._js.click()\\n\\n def draw(self, what, width, height):\\n \\\"\\\"\\\"Draw `what` on the current element (only available for canvas elements).\\n\\n Inputs:\\n\\n * what (canvas image source): An element to draw into the context. The specification permits any canvas\\n image source, specifically, an HTMLImageElement, an SVGImageElement, an HTMLVideoElement,\\n an HTMLCanvasElement, an ImageBitmap, an OffscreenCanvas, or a VideoFrame.\\n \\\"\\\"\\\"\\n if self._js.tagName != \\\"CANVAS\\\":\\n raise AttributeError(\\n \\\"The draw method is only available for canvas Elements\\\"\\n )\\n\\n if isinstance(what, Element):\\n what = what._js\\n\\n # https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage\\n self._js.getContext(\\\"2d\\\").drawImage(what, 0, 0, width, height)\\n\\n\\nclass OptionsProxy:\\n \\\"\\\"\\\"This class represents the options of a select element. It\\n allows to access to add and remove options by using the `add` and `remove` methods.\\n \\\"\\\"\\\"\\n\\n def __init__(self, element: Element) -> None:\\n self._element = element\\n if self._element._js.tagName.lower() != \\\"select\\\":\\n raise AttributeError(\\n f\\\"Element {self._element._js.tagName} has no options attribute.\\\"\\n )\\n\\n def add(\\n self,\\n value: Any = None,\\n html: str = None,\\n text: str = None,\\n before: Element | int = None,\\n **kws,\\n ) -> None:\\n \\\"\\\"\\\"Add a new option to the select element\\\"\\\"\\\"\\n # create the option element and set the attributes\\n option = document.createElement(\\\"option\\\")\\n if value is not None:\\n kws[\\\"value\\\"] = value\\n if html is not None:\\n option.innerHTML = html\\n if text is not None:\\n kws[\\\"text\\\"] = text\\n\\n for key, value in kws.items():\\n option.setAttribute(key, value)\\n\\n if before:\\n if isinstance(before, Element):\\n before = before._js\\n\\n self._element._js.add(option, before)\\n\\n def remove(self, item: int) -> None:\\n \\\"\\\"\\\"Remove the option at the specified index\\\"\\\"\\\"\\n self._element._js.remove(item)\\n\\n def clear(self) -> None:\\n \\\"\\\"\\\"Remove all the options\\\"\\\"\\\"\\n for i in range(len(self)):\\n self.remove(0)\\n\\n @property\\n def options(self):\\n \\\"\\\"\\\"Return the list of options\\\"\\\"\\\"\\n return [Element(opt) for opt in self._element._js.options]\\n\\n @property\\n def selected(self):\\n \\\"\\\"\\\"Return the selected option\\\"\\\"\\\"\\n return self.options[self._element._js.selectedIndex]\\n\\n def __iter__(self):\\n yield from self.options\\n\\n def __len__(self):\\n return len(self.options)\\n\\n def __repr__(self):\\n return f\\\"{self.__class__.__name__} (length: {len(self)}) {self.options}\\\"\\n\\n def __getitem__(self, key):\\n return self.options[key]\\n\\n\\nclass StyleProxy: # (dict):\\n def __init__(self, element: Element) -> None:\\n self._element = element\\n\\n @cached_property\\n def _style(self):\\n return self._element._js.style\\n\\n def __getitem__(self, key):\\n return self._style.getPropertyValue(key)\\n\\n def __setitem__(self, key, value):\\n self._style.setProperty(key, value)\\n\\n def remove(self, key):\\n self._style.removeProperty(key)\\n\\n def set(self, **kws):\\n for k, v in kws.items():\\n self._element._js.style.setProperty(k, v)\\n\\n # CSS Properties\\n # Reference: https://github.com/microsoft/TypeScript/blob/main/src/lib/dom.generated.d.ts#L3799C1-L5005C2\\n # Following prperties automatically generated from the above reference using\\n # tools/codegen_css_proxy.py\\n @property\\n def visible(self):\\n return self._element._js.style.visibility\\n\\n @visible.setter\\n def visible(self, value):\\n self._element._js.style.visibility = value\\n\\n\\nclass StyleCollection:\\n def __init__(self, collection: \\\"ElementCollection\\\") -> None:\\n self._collection = collection\\n\\n def __get__(self, obj, objtype=None):\\n return obj._get_attribute(\\\"style\\\")\\n\\n def __getitem__(self, key):\\n return self._collection._get_attribute(\\\"style\\\")[key]\\n\\n def __setitem__(self, key, value):\\n for element in self._collection._elements:\\n element.style[key] = value\\n\\n def remove(self, key):\\n for element in self._collection._elements:\\n element.style.remove(key)\\n\\n\\nclass ElementCollection:\\n def __init__(self, elements: [Element]) -> None:\\n self._elements = elements\\n self.style = StyleCollection(self)\\n\\n def __getitem__(self, key):\\n # If it's an integer we use it to access the elements in the collection\\n if isinstance(key, int):\\n return self._elements[key]\\n # If it's a slice we use it to support slice operations over the elements\\n # in the collection\\n elif isinstance(key, slice):\\n return ElementCollection(self._elements[key])\\n\\n # If it's anything else (basically a string) we use it as a selector\\n # TODO: Write tests!\\n elements = self._element.querySelectorAll(key)\\n return ElementCollection([Element(el) for el in elements])\\n\\n def __len__(self):\\n return len(self._elements)\\n\\n def __eq__(self, obj):\\n \\\"\\\"\\\"Check if the element is the same as the other element by comparing\\n the underlying JS element\\\"\\\"\\\"\\n return isinstance(obj, ElementCollection) and obj._elements == self._elements\\n\\n def _get_attribute(self, attr, index=None):\\n if index is None:\\n return [getattr(el, attr) for el in self._elements]\\n\\n # As JQuery, when getting an attr, only return it for the first element\\n return getattr(self._elements[index], attr)\\n\\n def _set_attribute(self, attr, value):\\n for el in self._elements:\\n setattr(el, attr, value)\\n\\n @property\\n def html(self):\\n return self._get_attribute(\\\"html\\\")\\n\\n @html.setter\\n def html(self, value):\\n self._set_attribute(\\\"html\\\", value)\\n\\n @property\\n def value(self):\\n return self._get_attribute(\\\"value\\\")\\n\\n @value.setter\\n def value(self, value):\\n self._set_attribute(\\\"value\\\", value)\\n\\n @property\\n def children(self):\\n return self._elements\\n\\n def __iter__(self):\\n yield from self._elements\\n\\n def __repr__(self):\\n return f\\\"{self.__class__.__name__} (length: {len(self._elements)}) {self._elements}\\\"\\n\\n\\nclass DomScope:\\n def __getattr__(self, __name: str):\\n element = document[f\\\"#{__name}\\\"]\\n if element:\\n return element[0]\\n\\n\\nclass PyDom(BaseElement):\\n # Add objects we want to expose to the DOM namespace since this class instance is being\\n # remapped as \\\"the module\\\" itself\\n BaseElement = BaseElement\\n Element = Element\\n ElementCollection = ElementCollection\\n\\n def __init__(self):\\n # PyDom is a special case of BaseElement where we don't want to create a new JS element\\n # and it really doesn't have a need for styleproxy or parent to to call to __init__\\n # (which actually fails in MP for some reason)\\n self._js = document\\n self._parent = None\\n self._proxies = {}\\n self.ids = DomScope()\\n self.body = Element(document.body)\\n self.head = Element(document.head)\\n\\n def create(self, type_, classes=None, html=None):\\n return super().create(type_, is_child=False, classes=classes, html=html)\\n\\n def __getitem__(self, key):\\n elements = self._js.querySelectorAll(key)\\n if not elements:\\n return None\\n return ElementCollection([Element(el) for el in elements])\\n\\n\\ndom = PyDom()\\n\"\n }\n};\n","import { typedSet } from \"type-checked-collections\";\nimport { dedent } from \"polyscript/exports\";\nimport toJSONCallback from \"to-json-callback\";\n\nimport { stdlib, optional } from \"./stdlib.js\";\n\nexport const main = (name) => hooks.main[name];\nexport const worker = (name) => hooks.worker[name];\n\nconst code = (hooks, branch, key, lib) => {\n hooks[key] = () => {\n const arr = lib ? [lib] : [];\n arr.push(...branch(key));\n return arr.map(dedent).join(\"\\n\");\n };\n};\n\nexport const codeFor = (branch, type) => {\n const pylib = type === \"mpy\" ? stdlib.replace(optional, \"\") : stdlib;\n const hooks = {};\n code(hooks, branch, `codeBeforeRun`, pylib);\n code(hooks, branch, `codeBeforeRunAsync`, pylib);\n code(hooks, branch, `codeAfterRun`);\n code(hooks, branch, `codeAfterRunAsync`);\n return hooks;\n};\n\nexport const createFunction = (self, name) => {\n const cbs = [...worker(name)];\n if (cbs.length) {\n const cb = toJSONCallback(\n self[`_${name}`] ||\n (name.endsWith(\"Async\")\n ? async (wrap, xworker, ...cbs) => {\n for (const cb of cbs) await cb(wrap, xworker);\n }\n : (wrap, xworker, ...cbs) => {\n for (const cb of cbs) cb(wrap, xworker);\n }),\n );\n const a = cbs.map(toJSONCallback).join(\", \");\n return Function(`return(w,x)=>(${cb})(w,x,...[${a}])`)();\n }\n};\n\nconst SetFunction = typedSet({ typeof: \"function\" });\nconst SetString = typedSet({ typeof: \"string\" });\n\nconst inputFailure = `\n import builtins\n def input(prompt=\"\"):\n raise Exception(\"\\\\n \".join([\n \"input() doesn't work when PyScript runs in the main thread.\",\n \"Consider using the worker attribute: https://pyscript.github.io/docs/2023.11.2/user-guide/workers/\"\n ]))\n\n builtins.input = input\n del builtins\n del input\n`;\n\nexport const hooks = {\n main: {\n /** @type {Set<function>} */\n onWorker: new SetFunction(),\n /** @type {Set<function>} */\n onReady: new SetFunction(),\n /** @type {Set<function>} */\n onBeforeRun: new SetFunction(),\n /** @type {Set<function>} */\n onBeforeRunAsync: new SetFunction(),\n /** @type {Set<function>} */\n onAfterRun: new SetFunction(),\n /** @type {Set<function>} */\n onAfterRunAsync: new SetFunction(),\n /** @type {Set<string>} */\n codeBeforeRun: new SetString([inputFailure]),\n /** @type {Set<string>} */\n codeBeforeRunAsync: new SetString(),\n /** @type {Set<string>} */\n codeAfterRun: new SetString(),\n /** @type {Set<string>} */\n codeAfterRunAsync: new SetString(),\n },\n worker: {\n /** @type {Set<function>} */\n onReady: new SetFunction(),\n /** @type {Set<function>} */\n onBeforeRun: new SetFunction(),\n /** @type {Set<function>} */\n onBeforeRunAsync: new SetFunction(),\n /** @type {Set<function>} */\n onAfterRun: new SetFunction(),\n /** @type {Set<function>} */\n onAfterRunAsync: new SetFunction(),\n /** @type {Set<string>} */\n codeBeforeRun: new SetString(),\n /** @type {Set<string>} */\n codeBeforeRunAsync: new SetString(),\n /** @type {Set<string>} */\n codeAfterRun: new SetString(),\n /** @type {Set<string>} */\n codeAfterRunAsync: new SetString(),\n },\n};\n","/*! (c) PyScript Development Team */\n\nimport stickyModule from \"sticky-module\";\nimport \"@ungap/with-resolvers\";\n\nimport {\n INVALID_CONTENT,\n Hook,\n XWorker,\n assign,\n dedent,\n define,\n defineProperty,\n dispatch,\n queryTarget,\n unescape,\n whenDefined,\n} from \"polyscript/exports\";\n\nimport \"./all-done.js\";\nimport TYPES from \"./types.js\";\nimport configs from \"./config.js\";\nimport sync from \"./sync.js\";\nimport bootstrapNodeAndPlugins from \"./plugins-helper.js\";\nimport { ErrorCode } from \"./exceptions.js\";\nimport { robustFetch as fetch, getText } from \"./fetch.js\";\nimport { hooks, main, worker, codeFor, createFunction } from \"./hooks.js\";\n\nimport { stdlib, optional } from \"./stdlib.js\";\nexport { stdlib, optional };\n\n// generic helper to disambiguate between custom element and script\nconst isScript = ({ tagName }) => tagName === \"SCRIPT\";\n\n// Used to create either Pyodide or MicroPython workers\n// with the PyScript module available within the code\nconst [PyWorker, MPWorker] = [...TYPES.entries()].map(\n ([TYPE, interpreter]) =>\n /**\n * A `Worker` facade able to bootstrap on the worker thread only a PyScript module.\n * @param {string} file the python file to run ina worker.\n * @param {{config?: string | object, async?: boolean}} [options] optional configuration for the worker.\n * @returns {Promise<Worker & {sync: object}>}\n */\n async function PyScriptWorker(file, options) {\n await configs.get(TYPE).plugins;\n const xworker = XWorker.call(\n new Hook(null, hooked.get(TYPE)),\n file,\n {\n ...options,\n type: interpreter,\n },\n );\n assign(xworker.sync, sync);\n return xworker.ready;\n },\n);\n\n// avoid multiple initialization of the same library\nconst [\n {\n PyWorker: exportedPyWorker,\n MPWorker: exportedMPWorker,\n hooks: exportedHooks,\n config: exportedConfig,\n whenDefined: exportedWhenDefined,\n },\n alreadyLive,\n] = stickyModule(\"@pyscript/core\", {\n PyWorker,\n MPWorker,\n hooks,\n config: {},\n whenDefined,\n});\n\nexport {\n TYPES,\n exportedPyWorker as PyWorker,\n exportedMPWorker as MPWorker,\n exportedHooks as hooks,\n exportedConfig as config,\n exportedWhenDefined as whenDefined,\n};\n\nexport const offline_interpreter = (config) =>\n config?.interpreter && new URL(config.interpreter, location.href).href;\n\nconst hooked = new Map();\n\nfor (const [TYPE, interpreter] of TYPES) {\n // avoid any dance if the module already landed\n if (alreadyLive) break;\n\n const dispatchDone = (element, isAsync, result) => {\n if (isAsync) result.then(() => dispatch(element, TYPE, \"done\"));\n else dispatch(element, TYPE, \"done\");\n };\n\n const { config, configURL, plugins, error } = configs.get(TYPE);\n\n // create a unique identifier when/if needed\n let id = 0;\n const getID = (prefix = TYPE) => `${prefix}-${id++}`;\n\n /**\n * Given a generic DOM Element, tries to fetch the 'src' attribute, if present.\n * It either throws an error if the 'src' can't be fetched or it returns a fallback\n * content as source.\n */\n const fetchSource = async (tag, io, asText) => {\n if (tag.hasAttribute(\"src\")) {\n try {\n return await fetch(tag.getAttribute(\"src\")).then(getText);\n } catch (error) {\n io.stderr(error);\n }\n }\n\n if (asText) return dedent(tag.textContent);\n\n const code = dedent(unescape(tag.innerHTML));\n console.warn(\n `Deprecated: use <script type=\"${TYPE}\"> for an always safe content parsing:\\n`,\n code,\n );\n return code;\n };\n\n // register once any interpreter\n let alreadyRegistered = false;\n\n // allows lazy element features on code evaluation\n let currentElement;\n\n const registerModule = ({ XWorker, interpreter, io }) => {\n // avoid multiple registration of the same interpreter\n if (alreadyRegistered) return;\n alreadyRegistered = true;\n\n // automatically use the pyscript stderr (when/if defined)\n // this defaults to console.error\n function PyWorker(...args) {\n const worker = XWorker(...args);\n worker.onerror = ({ error }) => io.stderr(error);\n return worker;\n }\n\n // enrich the Python env with some JS utility for main\n interpreter.registerJsModule(\"_pyscript\", {\n PyWorker,\n get target() {\n return isScript(currentElement)\n ? currentElement.target.id\n : currentElement.id;\n },\n });\n };\n\n // define the module as both `<script type=\"py\">` and `<py-script>`\n // but only if the config didn't throw an error\n if (!error) {\n // ensure plugins are bootstrapped already before custom type definition\n // NOTE: we cannot top-level await in here as plugins import other utilities\n // from core.js itself so that custom definition should not be blocking.\n plugins.then(() => {\n // possible early errors sent by polyscript\n const errors = new Map();\n\n // specific main and worker hooks\n const hooks = {\n main: {\n ...codeFor(main, TYPE),\n async onReady(wrap, element) {\n registerModule(wrap);\n\n // allows plugins to do whatever they want with the element\n // before regular stuff happens in here\n for (const callback of main(\"onReady\"))\n await callback(wrap, element);\n\n // now that all possible plugins are configured,\n // bail out if polyscript encountered an error\n if (errors.has(element)) {\n let { message } = errors.get(element);\n errors.delete(element);\n const clone = message === INVALID_CONTENT;\n message = `(${ErrorCode.CONFLICTING_CODE}) ${message} for `;\n message += element.cloneNode(clone).outerHTML;\n wrap.io.stderr(message);\n return;\n }\n\n if (isScript(element)) {\n const {\n attributes: { async: isAsync, target },\n } = element;\n const hasTarget = !!target?.value;\n const show = hasTarget\n ? queryTarget(element, target.value)\n : document.createElement(\"script-py\");\n\n if (!hasTarget) {\n const { head, body } = document;\n if (head.contains(element)) body.append(show);\n else element.after(show);\n }\n if (!show.id) show.id = getID();\n\n // allows the code to retrieve the target element via\n // document.currentScript.target if needed\n defineProperty(element, \"target\", { value: show });\n\n // notify before the code runs\n dispatch(element, TYPE, \"ready\");\n dispatchDone(\n element,\n isAsync,\n wrap[`run${isAsync ? \"Async\" : \"\"}`](\n await fetchSource(element, wrap.io, true),\n ),\n );\n } else {\n // resolve PyScriptElement to allow connectedCallback\n element._wrap.resolve(wrap);\n }\n console.debug(\"[pyscript/main] PyScript Ready\");\n },\n onWorker(_, xworker) {\n assign(xworker.sync, sync);\n for (const callback of main(\"onWorker\"))\n callback(_, xworker);\n },\n onBeforeRun(wrap, element) {\n currentElement = element;\n bootstrapNodeAndPlugins(\n main,\n wrap,\n element,\n \"onBeforeRun\",\n );\n },\n onBeforeRunAsync(wrap, element) {\n currentElement = element;\n return bootstrapNodeAndPlugins(\n main,\n wrap,\n element,\n \"onBeforeRunAsync\",\n );\n },\n onAfterRun(wrap, element) {\n bootstrapNodeAndPlugins(\n main,\n wrap,\n element,\n \"onAfterRun\",\n );\n },\n onAfterRunAsync(wrap, element) {\n return bootstrapNodeAndPlugins(\n main,\n wrap,\n element,\n \"onAfterRunAsync\",\n );\n },\n },\n worker: {\n ...codeFor(worker, TYPE),\n // these are lazy getters that returns a composition\n // of the current hooks or undefined, if no hook is present\n get onReady() {\n return createFunction(this, \"onReady\", true);\n },\n get onBeforeRun() {\n return createFunction(this, \"onBeforeRun\", false);\n },\n get onBeforeRunAsync() {\n return createFunction(this, \"onBeforeRunAsync\", true);\n },\n get onAfterRun() {\n return createFunction(this, \"onAfterRun\", false);\n },\n get onAfterRunAsync() {\n return createFunction(this, \"onAfterRunAsync\", true);\n },\n },\n };\n\n hooked.set(TYPE, hooks);\n\n define(TYPE, {\n config,\n configURL,\n interpreter,\n hooks,\n env: `${TYPE}-script`,\n version: offline_interpreter(config),\n onerror(error, element) {\n errors.set(element, error);\n },\n });\n\n customElements.define(\n `${TYPE}-script`,\n class extends HTMLElement {\n constructor() {\n assign(super(), {\n _wrap: Promise.withResolvers(),\n srcCode: \"\",\n executed: false,\n });\n }\n get id() {\n return super.id || (super.id = getID());\n }\n set id(value) {\n super.id = value;\n }\n async connectedCallback() {\n if (!this.executed) {\n this.executed = true;\n const isAsync = this.hasAttribute(\"async\");\n const { io, run, runAsync } = await this._wrap\n .promise;\n this.srcCode = await fetchSource(\n this,\n io,\n !this.childElementCount,\n );\n this.replaceChildren();\n this.style.display = \"block\";\n dispatch(this, TYPE, \"ready\");\n dispatchDone(\n this,\n isAsync,\n (isAsync ? runAsync : run)(this.srcCode),\n );\n }\n }\n },\n );\n });\n }\n\n // export the used config without allowing leaks through it\n exportedConfig[TYPE] = structuredClone(config);\n}\n"],"names":["stickyModule","name","value","global","globalThis","symbol","Symbol","for","known","Object","defineProperty","Promise","withResolvers","a","b","c","this","resolve","reject","promise","$$","css","root","document","querySelectorAll","$x","path","xpath","XPathEvaluator","createExpression","evaluate","XPathResult","ORDERED_NODE_SNAPSHOT_TYPE","result","i","snapshotLength","push","snapshotItem","d","getOwnPropertyDescriptors","Response","prototype","isFunction","handler","get","p","k","hasOwnProperty","then","r","args","bypass","bind","direct","fetch$1","input","init","Proxy","fetch","env","self","deserialize","serialized","$","_","as","out","index","set","unpair","has","type","arr","object","key","Date","source","flags","RegExp","map","Map","Set","add","message","BigInt","deserializer","EMPTY","toString","keys","typeOf","asString","call","slice","includes","shouldSkip","TYPE","serialize","json","lossy","strict","pair","entry","TypeError","valueOf","toJSON","entries","toISOString","serializer","parse","$parse","stringify","$stringify","JSON","options","str","any","CHANNEL","MAIN","THREAD","ARRAY","FUNCTION","NULL","NUMBER","OBJECT","STRING","SYMBOL","UNDEFINED","APPLY","CONSTRUCT","DEFINE_PROPERTY","DELETE_PROPERTY","GET","GET_OWN_PROPERTY_DESCRIPTOR","GET_PROTOTYPE_OF","HAS","IS_EXTENSIBLE","OWN_KEYS","PREVENT_EXTENSION","SET","SET_PROTOTYPE_OF","DELETE","isArray","Array","SharedArrayBuffer","window","notify","wait","waitAsync","Atomics","postPatched","buffer","onmessage","w","Worker","postMessage","ArrayBuffer","ids","WeakMap","resolvers","listener","event","details","data","stopImmediatePropagation","id","sb","rest","addEventListener","buff","delete","length","Int32Array","Uint16Array","BYTES_PER_ELEMENT","I32_BYTES","UI16_BYTES","buffers","WeakSet","context","syncResult","fn","uid","coincident","transform","interrupt","sendMessage","post","transfer","delay","decoder","TextDecoder","waitFor","isAsync","waitInterrupt","seppuku","action","startsWith","at","pop","deadlock","setTimeout","console","warn","clearTimeout","bytes","decode","actions","callback","Error","size","results","async","error","ui16a","charCodeAt","reviver","unbound","invoke","Context","target","t","v","unwrap","wrap","revive","resolver","registry","FinalizationRegistry","onGarbageCollected","held","debug","String","nullHandler","create","hold","return","token","register","deleteProperty","getOwnPropertyDescriptor","getPrototypeOf","isExtensible","ownKeys","preventExtensions","setPrototypeOf","Reflect","assign","TypedArray","Int8Array","augment","descriptor","how","asEntry","tv","symbols","keyFor","filter","s","o","main","patch","eventsHandler","EventTarget","concat","thread","values","__thread__","sid","asValue","retained","deref","cb","Event","currentTarget","method","handleEvent","WeakRef","createGCHook","trapsHandler","thisArg","apply","proto","trap","proxy","toLowerCase","__proxy__","__main__","proxies","argument","bound","proxyHandler","fromEntry","TRAP","ctx","Worker$1","$coincident","util","url","re","place","q","f","URL","href","dedent","string","l","arguments","content","line","split","trim","test","replace","$1","es","unes","cape","m","io","stdio","localIO","buffered","stderr","stdout","log","engine","interpreter","EOL","maybeUI8","Uint8Array","splice","tpl","unescape","un","defineProperties","all","absoluteURL","base","location","nodeInfo","node","tag","tagName","dispatch","what","worker","CE","CustomEvent","dispatchEvent","bubbles","detail","createResolved","module","config","run","code","runAsync","runEvent","dropLine0","createOverload","before","after","js_modules","jsModules","JSModules","field","modules","registerJSModules","registerJSModule","importJS","import","esm","importCSS","onload","onerror","querySelector","head","append","createElement","rel","isCSS","pathname","RUNNING_IN_WORKER","writeFile","FS","PATH","PATH_FS","absPath","dirPath","dirname","mkdirTree","canOwn","tree","join","current","branch","mkdir","cwd","joinPaths","parts","res","part","fetchBuffer","config_fetch","arrayBuffer","fetchPaths","files","to_file","from","undefined","endsWith","flatMap","to_folder","file","filename","lastIndexOf","calculateFetchPaths","fillName","dest","parseTemplate","src","SyntaxError","fetchFiles","config_files","targets","sourceDest","calculateFilesPaths","fetchJSModules","promises","loader","lazy_py_modules","packages","pyimport","registerJsModule","getFormat","runPython","runPythonAsync","globals","mip","TextEncoder","encode","micropython","version","loadMicroPython","linebuffer","py_imports","importPackages","PyProxy","toJs","_module","fs","format","extractDir","blob","Blob","BlobReader","Uint8ArrayWriter","ZipReader","zipReader","getEntries","directory","getData","close","TMP","mpyPackageManager","mpyPackage","install","toJsOptions","dict_converter","fromEntries","overrideFunction","overrideMethod","overridden","applyOverride","onGC","destroy","patchArgs","copy","Function","pyodide","loadPyodide","experimental_create_proxy","indexURL","ffi","unpackArchive","loadPackage","micropip","keep_going","jsType","ruby_wasm_wasi","experimental","DefaultRubyVM","WebAssembly","compile","vm","eval","evalAsync","wasmoon","LuaFactory","LuaLibraries","createEngine","getTable","Base","setField","doStringSync","doString","cmodule","writeFileShim","shelter","output","captureR","webr","WebR","Shelter","evalRVoid","configs","selectors","prefixes","baseURL","text","getConfigURLAndType","configURL","parseString","getRuntime","absolute","getRuntimeID","toJSONCallback","beforeRun","afterRun","js","resolved","polluteJS","ref","patched","Hook$1","constructor","hooks","onWorker","jsHooks","codeHooks","xworker","createObjectURL","isHook","Hook","bootstrap","sync","ready","writable","configurable","isError","INVALID_CONTENT","workerURL","element","attributes","childElementCount","innerHTML","localName","textContent","queryTarget","script","idOrSelector","parent","parentNode","getRoot","getElementById","targetDescriptor","handle","handled","interpreters","getValue","prefix","getDetails","runtime","queue","XWorker","$xworker","closest","body","versionValue","configValue","targetValue","currentScript","done","execute","queueMicrotask","awaitInterpreter","available","ownerElement","el","getAttribute","addAllListeners","disabled","CUSTOM_SELECTORS","customObserver","types","waitList","handleCustomType","selector","matches","XW","custom","hasAttribute","workerError","defaultRegistry","hook","structuredClone","suffix","beforeCB","afterCB","onReady","dontBotherCount","whenDefined","define","alreadyLive","$customObserver","dontBother","indexOf","remove","forEach","$whenDefined","$env","$Hook","$XWorker","mo","MutationObserver","records","attributeName","addedNodes","nodeType","shouldHandle","observe","childList","subtree","attachShadow","Element","TYPES","waitForIt","once","allPlugins","ErrorCode","GENERIC","CONFLICTING_CODE","BAD_CONFIG","MICROPIP_INSTALL_ERROR","BAD_PLUGIN_FILE_EXTENSION","NO_DEFAULT_EXPORT","TOP_LEVEL_AWAIT","FETCH_ERROR","FETCH_NAME_ERROR","FETCH_UNAUTHORIZED_ERROR","FETCH_FORBIDDEN_ERROR","FETCH_NOT_FOUND_ERROR","FETCH_SERVER_ERROR","FETCH_UNAVAILABLE_ERROR","UserError","errorCode","messageType","super","FetchError","getText","response","robustFetch","err","errMsg","ok","errorMsg","status","statusText","configDetails","toml","ext","expected","badURL","conflictError","reason","syntaxError","plugins","parsed","pyElement","pyConfigs","attrConfigs","some","e","toBeAwaited","default","is_pyterminal","sleep","seconds","bootstrapNodeAndPlugins","validator","Class","checks","C","failure","kind","typedSet","check","fail","typeof","instanceof","checkFail","createSet","python","ignore","paths","array","_path","write","literal","pyscript","pyweb","stdlib","optional","lib","codeFor","pylib","createFunction","cbs","SetFunction","SetString","onBeforeRun","onBeforeRunAsync","onAfterRun","onAfterRunAsync","codeBeforeRun","codeBeforeRunAsync","codeAfterRun","codeAfterRunAsync","isScript","PyWorker","MPWorker","hooked","exportedPyWorker","exportedMPWorker","exportedHooks","exportedConfig","exportedWhenDefined","offline_interpreter","dispatchDone","getID","fetchSource","asText","currentElement","alreadyRegistered","registerModule","errors","clone","cloneNode","outerHTML","hasTarget","show","contains","_wrap","customElements","HTMLElement","srcCode","executed","connectedCallback","replaceChildren","style","display"],"mappings":"AASA,MAAMA,EAAe,CAACC,EAAMC,EAAOC,EAASC,cAC1C,MAAMC,EAASC,OAAOC,IAAIN,GACpBO,EAAQH,KAAUF,EACxB,MAAO,CACLK,EACEL,EAAOE,GACPI,OAAOC,eAAeP,EAAQE,EAAQ,CAAEH,UAASG,GACnDG,EACD,ECjBHG,QAAQC,gBAAkBD,QAAQC,cAAgB,WAChD,IAAIC,EAAGC,EAAGC,EAAI,IAAIC,MAAK,SAAUC,EAASC,GACxCL,EAAII,EACJH,EAAII,CACR,IACE,MAAO,CAACD,QAASJ,EAAGK,OAAQJ,EAAGK,QAASJ,EAC1C,GCAA,MAQMK,EAAK,CAACC,EAAKC,EAAOC,WAAa,IAAID,EAAKE,iBAAiBH,IAQzDI,EAAK,CAACC,EAAMJ,EAAOC,YACvB,MACMI,GADa,IAAKC,gBAAgBC,iBAAiBH,GAChCI,SAASR,EAAMS,YAAYC,4BAC9CC,EAAS,GACf,IAAK,IAAIC,EAAI,GAAGC,eAACA,GAAkBR,EAAOO,EAAIC,EAAgBD,IAC5DD,EAAOG,KAAKT,EAAMU,aAAaH,IACjC,OAAOD,CAAM,ECnBTK,EAAI7B,OAAO8B,0BAA0BC,SAASC,WAE9CC,EAAaxC,GAA0B,mBAAVA,EAQ7ByC,EAAU,CACZC,IAAK,CAACC,EAAGC,IAAMR,EAAES,eAAeD,GAPrB,EAACD,EAAGC,GAAKF,MAAK1C,WAAY0C,IAAQF,EAAWxC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,KAAKouB,SAEvC,CACJ,GAER,IAKTpB,GAAejoB,GAAQ+f,gBAAgB5P,EAC3C","x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,61]}