diff --git a/docs/index.js b/docs/index.js index b8dc71d..bafa093 100644 --- a/docs/index.js +++ b/docs/index.js @@ -1,2 +1,2 @@ -const e=(e,t=document)=>[...t.querySelectorAll(e)],t=(e,t=document)=>{const n=(new XPathEvaluator).createExpression(e).evaluate(t,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE),r=[];for(let e=0,{snapshotLength:t}=n;e"function"==typeof e,s={get:(e,t)=>n.hasOwnProperty(t)?((e,t,{get:n,value:s})=>n||!r(s)?e.then((e=>e[t])):(...n)=>e.then((e=>e[t](...n))))(e,t,n[t]):((e,t)=>r(t)?t.bind(e):t)(e,e[t])};var o=(e,...t)=>new Proxy(fetch(e,...t),s);const a=new Proxy(new Map,{get:(e,t)=>(e.has(t)||e.set(t,Promise.withResolvers()),e.get(t))}),i=new Set(["__dict__","constructor","get","has","includes","next","set","then"]),c=new Proxy(Object.freeze({}),{get:(e,t)=>"string"!=typeof t||i.has(t)?void 0:a[t].promise.then((e=>e.sync))}),l="object"==typeof self?self:globalThis,u=e=>((e,t)=>{const n=(t,n)=>(e.set(n,t),t),r=s=>{if(e.has(s))return e.get(s);const[o,a]=t[s];switch(o){case 0:case-1:return n(a,s);case 1:{const e=n([],s);for(const t of a)e.push(r(t));return e}case 2:{const e=n({},s);for(const[t,n]of a)e[r(t)]=r(n);return e}case 3:return n(new Date(a),s);case 4:{const{source:e,flags:t}=a;return n(new RegExp(e,t),s)}case 5:{const e=n(new Map,s);for(const[t,n]of a)e.set(r(t),r(n));return e}case 6:{const e=n(new Set,s);for(const t of a)e.add(r(t));return e}case 7:{const{name:e,message:t}=a;return n(new l[e](t),s)}case 8:return n(BigInt(a),s);case"BigInt":return n(Object(BigInt(a)),s)}return n(new l[o](a),s)};return r})(new Map,e)(0),p="",{toString:f}={},{keys:d}=Object,h=e=>{const t=typeof e;if("object"!==t||!e)return[0,t];const n=f.call(e).slice(8,-1);switch(n){case"Array":return[1,p];case"Object":return[2,p];case"Date":return[3,p];case"RegExp":return[4,p];case"Map":return[5,p];case"Set":return[6,p]}return n.includes("Array")?[1,n]:n.includes("Error")?[7,n]:[2,n]},y=([e,t])=>0===e&&("function"===t||"symbol"===t),g=(e,{json:t,lossy:n}={})=>{const r=[];return((e,t,n,r)=>{const s=(e,t)=>{const s=r.push(e)-1;return n.set(t,s),s},o=r=>{if(n.has(r))return n.get(r);let[a,i]=h(r);switch(a){case 0:{let t=r;switch(i){case"bigint":a=8,t=r.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+i);t=null;break;case"undefined":return s([-1],r)}return s([a,t],r)}case 1:{if(i)return s([i,[...r]],r);const e=[],t=s([a,e],r);for(const t of r)e.push(o(t));return t}case 2:{if(i)switch(i){case"BigInt":return s([i,r.toString()],r);case"Boolean":case"Number":case"String":return s([i,r.valueOf()],r)}if(t&&"toJSON"in r)return o(r.toJSON());const n=[],c=s([a,n],r);for(const t of d(r))!e&&y(h(r[t]))||n.push([o(t),o(r[t])]);return c}case 3:return s([a,r.toISOString()],r);case 4:{const{source:e,flags:t}=r;return s([a,{source:e,flags:t}],r)}case 5:{const t=[],n=s([a,t],r);for(const[n,s]of r)(e||!y(h(n))&&!y(h(s)))&&t.push([o(n),o(s)]);return n}case 6:{const t=[],n=s([a,t],r);for(const n of r)!e&&y(h(n))||t.push(o(n));return n}}const{message:c}=r;return s([a,{name:i,message:c}],r)};return o})(!(t||n),!!t,new Map,r)(e),r},{parse:w,stringify:m}=JSON,_={json:!0,lossy:!0};var A=Object.freeze({__proto__:null,parse:e=>u(w(e)),stringify:e=>m(g(e,_))});const b="ownKeys",v="destruct",E="destroy",k="c70de905-a212-4eca-80aa-dad8bd4e677b",j="="+k,x="-"+k,{ArrayBuffer:S,Atomics:$,Promise:B}=globalThis,{isArray:P}=Array,{create:R,getPrototypeOf:T,values:M}=Object,O=T(Int32Array),F=R($),C=()=>B.withResolvers();let D=0;const W=new Map,I=(e,t)=>class extends e{constructor(e,...n){super(e,...n),e instanceof t&&W.set(this,[D++,0,C()])}},L=new WeakSet,N=e=>(L.add(e),e),U=(e,t)=>{const{data:n}=e,r=P(n)&&(n.at(0)===t||0===n.at(1)&&!t);return r&&(e.stopImmediatePropagation(),e.preventDefault()),r},H=e=>null!==e&&"object"==typeof e&&!L.has(e),J=new WeakMap,q=(e,t,n)=>{if(W.has(e))t.set(e,W.get(e)[0]);else if(!(e instanceof O||e instanceof S))for(const r of M(e))H(r)&&!n.has(r)&&(n.add(r),q(r,t,n))},z=(...e)=>({value:new B((t=>{let n=new Worker("data:application/javascript,onmessage%3De%3D%3EpostMessage(!Atomics.wait(...e.data))");n.onmessage=()=>t("ok"),n.postMessage(e)}))}),K=(e,t,n)=>{for(const[n,r]of t)J.set(n,[r,e.currentTarget]);(({currentTarget:e,type:t,origin:n,lastEventId:r,source:s,ports:o},a)=>{e.dispatchEvent(new MessageEvent(t,{data:a,origin:n,lastEventId:r,source:s,ports:o}))})(e,n)};let{BigInt64Array:G,Int32Array:X,SharedArrayBuffer:Y,Worker:Z}=globalThis,V=e=>e,Q=!1;const ee=e=>({...e,type:"module"});try{new Y(4),Z=class extends Z{constructor(e,t){super(e,ee(t))}},F.waitAsync||(F.waitAsync=z)}catch(e){const t=crypto.randomUUID(),n=new Map,r=(e,t,n,...r)=>{e.addEventListener(t,n,...r)},s=({serviceWorker:e},s,o)=>{let a,i=!0;r(e,"message",(e=>{if(U(e,t)){const[r,s,o]=e.data,i=[s,o].join(","),c=e=>{n.delete(i),a.postMessage([t,s,o,e])},l=n.get(i);if(l)c(l);else{const{promise:e,resolve:t}=C();n.set(i,t),e.then(c)}}})),e.getRegistration(s).then((t=>t??e.register(s))).then((function t(n){i=i&&!!e.controller,a=n.installing||n.waiting||n.active,"activated"===a.state?i?o():location.reload():r(a,"statechange",(()=>t(n)),{once:!0})}))};V=N,Q=!0,F.notify=(e,r)=>{const[s,o]=(e=>J.get(e))(e),a=[s,r].join(","),i=n.get(a);return i?i(e):n.set(a,e),o.postMessage([t,1,e,s,r]),0},F.waitAsync=(e,...t)=>{const[n,r]=((e,t)=>{const n=W.get(e),[r,s,{promise:o}]=n;return n[1]=t,[r,o]})(e,...t);return{value:r}},Y=class extends S{},G=I(G,Y),X=I(X,Y);let o=null;Z=class extends Z{constructor(e,n){let a=n?.serviceWorker||"";if(a){if(a=new URL(a,location.href).href,n={...n,serviceWorker:a},!o){const{promise:e,resolve:t}=C();s(navigator,a,t),o=e}o.then((()=>super.postMessage([t,3])))}super(e,ee(n)),super.postMessage([t,0,n]),r(this,"message",(e=>{if(U(e,t)){const[t,n,...r]=e.data;switch(n){case 1:((e,t,n)=>{for(const[r,[s,o,{resolve:a}]]of W)if(t===s&&n===o){for(let t=0;t{const n=new Map;return H(t)&&q(t,n,new Set),n.size?[e,2,n,t]:t})(t,e),...n)}}}const{BYTES_PER_ELEMENT:te}=Int32Array,{BYTES_PER_ELEMENT:ne}=Uint16Array,{notify:re}=F,se=new TextDecoder("utf-16"),oe=new WeakSet,ae=(...e)=>(oe.add(e),e);let ie="";let ce=0;const le=([e,t,n,r,s,o,a,i,c],l)=>(...u)=>{let p=""!==ie,f=0;p&&"="!==ie[0]&&"-"!==ie[0]&&(f=((e,t)=>setTimeout(console.warn,3e3,`💀🔒 - proxy.${e}() in proxy.${t}()`))(l,ie));const d=ce++;let h=[];oe.has(u.at(-1)||h)&&oe.delete(h=u.pop());const y=n(i?u.map(i):u);let g=t(2*te);return a([e,2,l,d,g,y,r],{transfer:h}),c(g,0).value.then((()=>{p&&clearTimeout(f);const n=g[1];if(!n)return;const r=ne*n;return g=t(r+r%te),a([e,1,d,g]),c(g,0).value.then((()=>{const e=new Uint16Array(g.buffer),t=o?e.subarray(0,n):e.slice(0,n);return s(se.decode(t))}))}))};var ue=({parse:e,stringify:t,transform:n}=JSON)=>{const r=((e,t)=>async(n,r,[s,o,a,i,c])=>{c&&(ie=s);try{const s=await n(...i);if(void 0!==s){const n=e(t?t(s):s);r.set(o,n),a[1]=n.length}}finally{c&&(ie=""),a[0]=1,re(a,0)}})(t,n);return{Worker:class extends Z{constructor(t,s){const o=crypto.randomUUID(),a=new Map,i=new Map;super(t,s),this.proxy=((e,t)=>new Proxy(t,{get:(t,n)=>{let r;return"then"!==n&&(r=t.get(n),r||(r=le(e,n),t.set(n,r))),r},set:(e,t,n)=>"then"!==t&&!!e.set(t,n)}))([o,e=>new X(new Y(e)),V,!1,e,Q,(...e)=>this.postMessage(...e),n,F.waitAsync],a),this.postMessage(V([o,0,s])),this.addEventListener("message",(e=>{if(U(e,o)){const[t,n,...s]=e.data;switch(n){case 2:((e,t,n,r)=>{const[s]=r,o=n.get(s);if(!o)throw new Error(`Unknown proxy.${s}()`);e(o,t,r)})(r,i,a,s);break;case 1:((e,[t,n])=>{const r=e.get(t);e.delete(t);for(let e=new Uint16Array(n.buffer),t=0,{length:s}=r;t[e,t])));const{[b]:Ae}=Reflect,be=new Map(Ae(Symbol).filter((e=>typeof Symbol[e]===we)).map((e=>[Symbol[e],e]))),ve=e=>be.get(e)||`.${Symbol.keyFor(e)||""}`,Ee=new FinalizationRegistry((([e,t,n])=>{n&&console.debug(`%c${String(t)}`,"font-weight:bold","collected"),e(t)})),ke=Object.create(null),je=(e,t,{debug:n,handler:r,return:s,token:o=e}=ke)=>{const a=s||new Proxy(e,r||ke),i=[a,[t,e,!!n]];return!1!==o&&i.push(o),Ee.register(...i),a},{addEventListener:xe}=EventTarget.prototype,Se=new WeakMap;Reflect.defineProperty(EventTarget.prototype,"addEventListener",{value(e,t,...n){const r=n.at(0)?.invoke;if(r){let t=Se.get(this);t||(t=new Map,Se.set(this,t)),t.set(e,[].concat(r)),delete n[0].invoke}return xe.call(this,e,t,...n)}});const{isArray:$e}=Array;var Be=(e,t)=>{const{clear:n,drop:r,get:s,hold:o}=(()=>{const e=new Map,t=new Map;let n=0;return{clear:()=>{e.clear(),t.clear()},drop:n=>{const[r,s]=typeof n===he?[t,e]:[e,t],o=r.has(n);return o&&(s.delete(r.get(n)),r.delete(n)),o},get:e=>t.get(e),hold:r=>{if(!e.has(r)){let s;for(;t.has(s=n++););e.set(r,s),t.set(s,r)}return e.get(r)}}})(),a=new Map,i=e=>{a.delete(e),t(v,e)},c=e=>{const t=typeof e;switch(t){case ye:return null===e?[_e[de],e]:e===globalThis?[_e[ye],null]:$e(e)?[_e[pe],o(e)]:[_e[ye],e instanceof O?e:o(e)];case fe:return[_e[fe],o(e)];case we:return[_e[we],ve(e)];default:return[_e[t],e]}},l=([e,n])=>{switch(e){case _e[ye]:if(null===n)return globalThis;if(typeof n===he)return s(n);if(!(n instanceof O))for(const e in n)n[e]=l(n[e]);return n;case _e[pe]:return typeof n===he?s(n):n.map(l);case _e[fe]:switch(typeof n){case he:return s(n);case ge:{let e=a.get(n)?.deref();return e||(e=je(n,i,{token:!1,return:function(...e){return e.length&&e[0]instanceof Event&&(e=>{const{currentTarget:t,target:n,type:r}=e,s=Se.get(t||n)?.get(r);if(s)for(const t of s)e[t]()})(e[0]),t("apply",n,c(this),e.map(c)).then(l)}}),a.set(n,new WeakRef(e))),e}}case _e[we]:return(e=>{if(e.startsWith("."))return Symbol.for(e.slice(1));for(const[t,n]of be)if(n===e)return t})(n);default:return n}},u=(e,t,n)=>c(e(t,...n.map(l))),p=t=>import(e(t)),f=new Set;return(e,t,...o)=>{if(e===E)n();else if(e===v)f.has(t)||r(t);else{const n=Reflect[e],r=null==t?globalThis:s(t);switch(e){case"defineProperty":{const[e,t]=o.map(l);return c(n(r,e,t))}case"getOwnPropertyDescriptor":{const e=n(r,...o.map(l));if(e){const{get:t,set:n,value:r}=e;t&&(e.get=c(t)),n&&(e.set=c(n)),r&&(e.value=c(r))}return[_e[e?ye:me],e]}case b:return[_e[pe],n(r).map(c)];case"get":if(null==t){const e="import"===o[0][1]?c(p):u(n,r,o);return f.add(e[1]),e}default:return u(n,r,o)}}}};const{url:Pe}=import.meta,Re=/import\((['"])([^)]+?\.js)\1\)/g,Te=(e,t,n)=>`import(${t}${new URL(n,Pe).href}${t})`,{Worker:Me}=(e=>{const t=e?.import,n=ue(e);class r extends n.Worker{constructor(e,n){const{proxy:r}=super(e,n);r[j]=Be(n?.import||t||(e=>new URL(e,location.href)),r[x])}terminate(){this.proxy[j](E),super.terminate()}}return{...n,Worker:r}})(A);const Oe=new WeakMap,Fe=e=>{const t=e||console,n={buffered:De,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 Oe.set(t,n),t}}},Ce=new TextDecoder,De=(e,t=10)=>{const n=[];return r=>{if(r instanceof Uint8Array)for(const s of r)s===t?e(Ce.decode(new Uint8Array(n.splice(0)))):n.push(s);else e(r)}},We=new Map,Ie=e=>We.get(e),Le=(e,t)=>{try{return Function("require",t)(Ie)}catch(t){Oe.get(e).stderr(t)}};var Ne={type:"dummy",module:()=>"data:application/javascript,",engine:e=>Fe().get(e),registerJSModule(e,t,n){We.set(t,n)},run:Le,runAsync:Le,runEvent:async(e,t,n)=>{try{await Function("require","e",`return ${t}(e)`)(Ie,n)}catch(t){Oe.get(e).stderr(t)}},transform:(e,t)=>t,writeFile(){}};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{assign:Ue}=Object,He="entries",Je="readonly",qe="readwrite",ze={durability:"default",prefix:"IDBMap"},Ke=({target:{result:e}})=>e;class Ge extends EventTarget{#e;#t;#n;async#r(e,t){const n=(await this.#e).transaction(He,t,this.#t);return new Promise(((t,r)=>Ue(e(n.objectStore(He)),{onsuccess:t,onerror:r})))}constructor(e,{durability:t=ze.durability,prefix:n=ze.prefix}=ze){super(),this.#n=n,this.#t={durability:t},this.#e=new Promise(((t,n)=>{Ue(indexedDB.open(`${this.#n}/${e}`),{onupgradeneeded({target:{result:e,transaction:n}}){e.objectStoreNames.length||e.createObjectStore(He),n.oncomplete=()=>t(e)},onsuccess(e){t(Ke(e))},onerror(e){n(e),this.dispatchEvent(e)}})})).then((e=>{const t=this.dispatchEvent.bind(this);for(const n in e)n.startsWith("on")&&(e[n]=t);return e}))}dispatchEvent(e){const{type:t,message:n,isTrusted:r}=e;return super.dispatchEvent(r?Ue(new Event(t),{message:n}):e)}async close(){(await this.#e).close()}get size(){return this.#r((e=>e.count()),Je).then(Ke)}async clear(){await this.#r((e=>e.clear()),qe)}async delete(e){await this.#r((t=>t.delete(e)),qe)}async entries(){const e=await this.keys();return Promise.all(e.map((e=>this.get(e).then((t=>[e,t])))))}async forEach(e,t=this){for(const[n,r]of await this.entries())await e.call(t,r,n,this)}async get(e){return await this.#r((t=>t.get(e)),Je).then(Ke)}async has(e){return void 0!==await this.#r((t=>t.getKey(e)),Je).then(Ke)}async keys(){return await this.#r((e=>e.getAllKeys()),Je).then(Ke)}async set(e,t){return await this.#r((n=>n.put(t,e)),qe),this}async values(){const e=await this.keys();return Promise.all(e.map((e=>this.get(e))))}get[Symbol.toStringTag](){return this.#n}}class Xe extends Map{#s;#o;constructor(...e){super(),this.#s=new Ge(...e),this.#o=this.#s.entries().then((e=>{for(const[t,n]of e)super.set(t,n)}))}async close(){await this.#o,await this.#s.close()}async sync(){await this.#o}clear(){return this.#o=this.#o.then((()=>this.#s.clear())),super.clear()}delete(e){return this.#o=this.#o.then((()=>this.#s.delete(e))),super.delete(e)}set(e,t){return this.#o=this.#o.then((()=>this.#s.set(e,t))),super.set(e,t)}}const Ye={object(...e){return this.string(function(e){for(var t=e[0],n=1,r=arguments.length;n",">":">","'":"'","'":"'",""":'"',""":'"'},et=e=>Qe[e],tt=(e,...t)=>Ye[typeof e](e,...t),nt=e=>Ze.call(e,Ve,et),{isArray:rt}=Array,{assign:st,create:ot,defineProperties:at,defineProperty:it,entries:ct}=Object,{all:lt,resolve:ut}=new Proxy(Promise,{get:(e,t)=>e[t].bind(e)}),pt=(e,t=location.href)=>new URL(e,t.replace(/^blob:/,"")).href;let ft=0;const dt=(e,t)=>({id:e.id||(e.id=`${t}-w${ft++}`),tag:e.tagName}),ht=(e,t,n,r=!1,s=CustomEvent)=>{e.dispatchEvent(new s(`${t}:${n}`,{bubbles:!0,detail:{worker:r}}))},yt=(e,t,n,r)=>({type:t,config:n,interpreter:r,io:Oe.get(r),run:(t,...n)=>e.run(r,t,...n),runAsync:(t,...n)=>e.runAsync(r,t,...n),runEvent:(...t)=>e.runEvent(r,...t)}),gt=e=>e.replace(/^(?:\n|\r\n)/,""),wt=(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,gt(t),...o);return r&&s(e,r,...o),a}:async(e,t,...o)=>{n&&await s(e,n,...o);const a=await s(e,gt(t),...o);return r&&await s(e,r,...o),a}},mt=Symbol.for("polyscript.js_modules"),_t=new Map;it(globalThis,mt,{value:_t});const At=new Proxy(_t,{get:(e,t)=>e.get(t),has:(e,t)=>e.has(t),ownKeys:e=>[...e.keys()]}),bt=(e,t)=>!t.startsWith("_"),vt=(e,t)=>new Proxy(e,{has:bt,get:(e,n)=>e[t][n]}),Et=(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}`,vt(r,e));t.registerJSModule(n,s,r)},kt=(e,t)=>import(e).then((e=>{_t.set(t,{...e})})),jt=e=>new Promise(((t,n)=>{document.querySelector(`link[rel="stylesheet"][href="${e}"]`)?t():document.head.append(st(document.createElement("link"),{rel:"stylesheet",href:e,onload:t,onerror:n}))})),xt=e=>/\.css$/i.test(new URL(e).pathname),St=e=>/^(?:false|0|no)$/i.test(e.getAttribute("async")),$t=!globalThis.window,Bt=({FS:e,PATH:t,PATH_FS:n},r,s)=>{const o=n.resolve(r),a=t.dirname(o);return e.mkdirTree?e.mkdirTree(a):Rt(e,a),e.writeFile(o,new Uint8Array(s),{canOwn:!0})},Pt=e=>{const t=e.split("/");return t.pop(),t.join("/")},Rt=(e,t)=>{const n=[];for(const r of t.split("/"))"."!==r&&".."!==r&&(n.push(r),r&&e.mkdir(n.join("/")))},Tt=(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(/^\/+/,"/")},Mt=e=>{const t=e.map((e=>e.trim().replace(/(^[/]*|[/]*$)/g,""))).filter((e=>""!==e&&"."!==e)).join("/");return e[0].startsWith("/")?`/${t}`:t},Ot=(e,t)=>o(pt(e,t)).arrayBuffer(),Ft=(e,t,n,r)=>lt((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(rt(r))return r.map((n=>({url:Mt([e,n]),path:Mt([t,n])})));const s=n||e.slice(1+e.lastIndexOf("/"));return[{url:e,path:Mt([t,s])}]}))})(n).map((({url:n,path:s})=>Ot(n,r).then((n=>e.writeFile(t,s,n)))))),Ct=(e,t)=>t.endsWith("/")?`${t}${e.split("/").pop()}`:t,Dt=(e,t)=>e.replace(/\{.+?\}/g,(e=>{if(!t.has(e))throw new SyntaxError(`Invalid template: ${e}`);return t.get(e)})),Wt=(e,t,n,r)=>lt((e=>{const t=new Map,n=new Set,r=[];for(const[s,o]of ct(e))if(/^\{.+\}$/.test(s)){if(t.has(s))throw new SyntaxError(`Duplicated template: ${s}`);t.set(s,Dt(o,t))}else{const e=Dt(s,t),a=Ct(e,Dt(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:n,path:s})=>Ot(n,r).then((r=>e.writeFile(t,s,r,n)))))),It=({main:e,worker:t},n)=>{const r=[];if(t&&$t)for(let[e,s]of ct(t))e=pt(e,n),r.push(kt(e,s));if(e&&!$t)for(let[t,s]of ct(e))t=pt(t,n),xt(t)?jt(t):r.push(kt(t,s));return lt(r)},Lt=e=>t=>{dispatchEvent(new CustomEvent(`${e}:progress`,{detail:t}))},Nt=new WeakMap,Ut=async(e,t,n,r,s)=>{r.files&&(t("Loading files"),await Wt(e,n,r.files,s),t("Loaded files")),r.fetch&&(t("Loading fetch"),await Ft(e,n,r.fetch,s),t("Loaded fetch")),r.js_modules&&(t("Loading JS modules"),await It(r.js_modules,s),t("Loaded JS modules"))},Ht=(e,t,n)=>{"polyscript"===t&&(n.lazy_py_modules=async(...t)=>(await Nt.get(e)(t),t.map((t=>e.pyimport(t)))),n.storage=async e=>{const t=new Xe(e);return await t.sync(),t},n.JSON=A),e.registerJsModule(t,n)},Jt=(e,t)=>{if(e.endsWith("/*")){if(/\.(zip|whl|tgz|tar(?:\.gz)?)$/.test(t))return RegExp.$1;throw new Error(`Unsupported archive ${t}`)}return""},qt=(e,t,...n)=>{try{return e.runPython(tt(t),...n)}catch(t){Oe.get(e).stderr(t)}},zt=async(e,t,...n)=>{try{return await e.runPythonAsync(tt(t),...n)}catch(t){Oe.get(e).stderr(t)}},Kt=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){Oe.get(e).stderr(t)}};var Gt=(new TextEncoder).encode("_F='github:'\n_E='user-agent'\n_D=True\n_C=False\n_B='/'\n_A=None\nfrom uio import StringIO\nimport sys\nclass Response:\n\tdef __init__(A,f):A.raw=f;A.encoding='utf-8';A._cached=_A\n\tdef close(A):\n\t\tif A.raw:A.raw.close();A.raw=_A\n\t\tA._cached=_A\n\t@property\n\tdef content(self):\n\t\tA=self\n\t\tif A._cached is _A:\n\t\t\ttry:A._cached=A.raw.read()\n\t\t\tfinally:A.raw.close();A.raw=_A\n\t\treturn A._cached\n\t@property\n\tdef text(self):return str(self.content,self.encoding)\n\tdef json(A):import ujson;return ujson.loads(A.content)\nHEADERS_TO_IGNORE=_E,\ntry:import js\nexcept Exception as err:raise OSError('This version of urequests can only be used in the browser')\nHEADERS_TO_IGNORE=_E,\ndef request(method,url,data=_A,json=_A,headers={},stream=_A,auth=_A,timeout=_A,parse_headers=_D):\n\tE=timeout;D=method;C=data;from js import XMLHttpRequest as G;A=G.new();A.withCredentials=_C\n\tif auth is not _A:import ubinascii;H,I=auth;A.open(D,url,_C,H,I)\n\telse:A.open(D,url,_C)\n\tfor(F,J)in headers.items():\n\t\tif F.lower()not in HEADERS_TO_IGNORE:A.setRequestHeader(F,J)\n\tif E:A.timeout=int(E*1000)\n\tif json is not _A:assert C is _A;import ujson;C=ujson.dumps(json);A.setRequestHeader('Content-Type','application/json')\n\tA.send(C);B=Response(StringIO(A.responseText));B.status_code=A.status;B.reason=A.statusText;B.headers=A.getAllResponseHeaders();return B\ndef get(url,**A):return request('GET',url,**A)\n_PACKAGE_INDEX=const('https://micropython.org/pi/v2')\n_CHUNK_SIZE=128\ndef _ensure_path_exists(path):\n\timport os;A=path.split(_B)\n\tif not A[0]:A.pop(0);A[0]=_B+A[0]\n\tB=''\n\tfor C in range(len(A)-1):\n\t\tB+=A[C]\n\t\ttry:os.stat(B)\n\t\texcept:os.mkdir(B)\n\t\tB+=_B\ndef _chunk(src,dest):\n\tA=memoryview(bytearray(_CHUNK_SIZE))\n\twhile _D:\n\t\tB=src.readinto(A)\n\t\tif B==0:break\n\t\tdest(A if B==_CHUNK_SIZE else A[:B])\ndef _check_exists(path,short_hash):\n\tA=short_hash;import os\n\ttry:\n\t\timport binascii as C,hashlib as D\n\t\twith open(path,'rb')as E:B=D.sha256();_chunk(E,B.update);F=str(C.hexlify(B.digest())[:len(A)],'utf-8');return F==A\n\texcept:return _C\ndef _rewrite_url(url,branch=_A):\n\tB=branch;A=url\n\tif not B:B='HEAD'\n\tif A.startswith(_F):A=A[7:].split(_B);A='https://raw.githubusercontent.com/'+A[0]+_B+A[1]+_B+B+_B+_B.join(A[2:])\n\treturn A\ndef _download_file(url,dest):\n\tB=dest;A=get(url)\n\ttry:\n\t\tif A.status_code!=200:print('Error',A.status_code,'requesting',url);return _C\n\t\tprint('Copying:',B);_ensure_path_exists(B)\n\t\twith open(B,'wb')as C:_chunk(A.raw,C.write)\n\t\treturn _D\n\tfinally:A.close()\ndef _install_json(package_json_url,index,target,version,mpy):\n\tK='File not found: {} {}';I=version;H=index;G=package_json_url;D=target;E=get(_rewrite_url(G,I))\n\ttry:\n\t\tif E.status_code!=200:print('Package not found:',G);return _C\n\t\tF=E.json()\n\tfinally:E.close()\n\tfor(A,C)in F.get('hashes',()):\n\t\tB=D+_B+A\n\t\tif _check_exists(B,C):print('Exists:',B)\n\t\telse:\n\t\t\tL='{}/file/{}/{}'.format(H,C[:2],C)\n\t\t\tif not _download_file(L,B):print(K.format(A,C));return _C\n\tfor(A,J)in F.get('urls',()):\n\t\tB=D+_B+A\n\t\tif not _download_file(_rewrite_url(J,I),B):print(K.format(A,J));return _C\n\tfor(M,N)in F.get('deps',()):\n\t\tif not _install_package(M,H,D,N,mpy):return _C\n\treturn _D\ndef _install_package(package,index,target,version,mpy):\n\tD=index;C=target;B=version;A=package\n\tif A.startswith('http://')or A.startswith('https://')or A.startswith(_F):\n\t\tif A.endswith('.py')or A.endswith('.mpy'):print('Downloading {} to {}'.format(A,C));return _download_file(_rewrite_url(A,B),C+_B+A.rsplit(_B)[-1])\n\t\telse:\n\t\t\tif not A.endswith('.json'):\n\t\t\t\tif not A.endswith(_B):A+=_B\n\t\t\t\tA+='package.json'\n\t\t\tprint('Installing {} to {}'.format(A,C))\n\telse:\n\t\tif not B:B='latest'\n\t\tprint('Installing {} ({}) from {} to {}'.format(A,B,D,C));E=sys.implementation._mpy&255 if mpy and hasattr(sys.implementation,'_mpy')else'py';A='{}/package/{}/{}/{}.json'.format(D,'py',A,B)\n\treturn _install_json(A,D,C,B,mpy)\ndef install(package,index=_A,target=_A,version=_A,mpy=_D):\n\tB=target;A=index\n\tif not B:\n\t\tfor C in sys.path:\n\t\t\tif C.endswith('/lib'):B=C;break\n\t\telse:print('Unable to find lib dir in sys.path');return\n\tif not A:A=_PACKAGE_INDEX\n\tif _install_package(package,A.rstrip(_B),B,version,mpy):print('Done')\n\telse:print('Package may be partially installed')");const Xt=async e=>(await import("./toml-DiUM0_qs.js")).parse(e),Yt=(e,t)=>{try{e.mkdir(t)}catch(e){}},Zt=Lt("mpy");var Vt={type:"micropython",module:(e="1.24.0")=>`https://cdn.jsdelivr.net/npm/@micropython/micropython-webassembly-pyscript@${e}/micropython.mjs`,async engine({loadMicroPython:e},t,n,r){const{stderr:s,stdout:o,get:a}=Fe({stderr:De(console.error),stdout:De(console.log)});n=n.replace(/\.m?js$/,".wasm"),Zt("Loading MicroPython");const i=await a(e({linebuffer:!1,stderr:s,stdout:o,url:n})),c=Qt.bind(this,i,r);return Nt.set(i,c),await Ut(this,Zt,i,t,r),this.writeFile(i,"./mip.py",Gt),t.packages&&(Zt("Loading packages"),await c(t.packages),Zt("Loaded packages")),Zt("Loaded MicroPython"),i},registerJSModule:Ht,run:qt,runAsync:zt,runEvent:Kt,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=Jt(t,r);if(c){const r=t.slice(0,-1);switch("./"!==r&&s.mkdir(r),c){case"whl":case"zip":{const e=new Blob([n],{type:"application/zip"});return import("./zip-Bf48tRr5.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)Yt(s,i);else{Yt(s,o.dirname(i));const t=await e.getData(new n);s.writeFile(i,t,{canOwn:!0})}}i.close()}))}case"tgz":case"tar.gz":{const t="./_.tar.gz";return Bt(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 Bt(i,t,n)}};async function Qt(e,t,n){let r;for(const s of n)if(s.endsWith(".whl")){const n=pt(s,t),r=await o(n).arrayBuffer();await this.writeFile(e,"./*",r,n)}else r||(r=e.pyimport("mip")),r.install(s)}const en={dict_converter:Object.fromEntries},{stringify:tn}=JSON;let nn=!1;const rn=e=>(...t)=>{try{return nn=!0,e(...t)}finally{nn=!1}};let sn=!1;const on=()=>{if(sn)return;sn=!0;const e=new WeakMap,t=e=>e.destroy(),n=n=>{for(let r=0;r`https://cdn.jsdelivr.net/pyodide/v${e}/full/pyodide.mjs`,async engine({loadPyodide:e},t,n,r){$t||"auto"!==t.experimental_create_proxy||on(),an("Loading Pyodide");let{packages:s}=t;an("Loading Storage");const o=n.slice(0,n.lastIndexOf("/")),a=new Xe(o),i={indexURL:o},c="never"!==t.packages_cache;if(await a.sync(),c){if(s){s=s.slice(0).sort();const e=tn(s);if(a.has(e)){const t=new Blob([a.get(e)],{type:"application/json"});i.lockFileURL=URL.createObjectURL(t),i.packages=s.map((e=>e.split("==")[0])),s=null}}}else a.clear();an("Loaded Storage");const{stderr:l,stdout:u,get:p}=Fe(),f=await p(e({stderr:l,stdout:u,...i})),d=un.bind(f);return Nt.set(f,d),await Ut(this,an,f,t,r),s&&await d(s,a,c),await a.close(),i.lockFileURL&&URL.revokeObjectURL(i.lockFileURL),an("Loaded Pyodide"),f},registerJSModule:Ht,run:rn(qt),runAsync:rn(zt),runEvent:rn(Kt),transform:(e,t)=>ln.call(e,t),writeFile:(e,t,n,r)=>{const s=Jt(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 Bt({FS:o,PATH:a,PATH_FS:i},t,n)}};function ln(e){const{ffi:{PyProxy:t}}=this;if(e&&"object"==typeof e){if(e instanceof t)return e.toJs(en);if(e instanceof Map)return new Map([...e.entries()]);if(rt(e))return e.map(ln,this)}return e}async function un(e,t,n=!1){const{log:r}=console,s=(e,...t)=>{r(e,...t),console.log=r,an(e),console.log=s};console.log=s,await this.loadPackage("micropip");const o=this.pyimport("micropip");if(await o.install(e,{keep_going:!0}),console.log=r,n&&t instanceof Xe){const n=o.freeze();t.set(tn(e),n)}o.destroy()}const pn="ruby-wasm-wasi",fn=pn.replace(/\W+/g,"_");var dn={type:pn,experimental:!0,module:(e="2.6.2")=>`https://cdn.jsdelivr.net/npm/@ruby/3.2-wasm-wasi@${e}/dist/browser/+esm`,async engine({DefaultRubyVM:e},t,n,r){n=n.replace(/\/browser\/\+esm$/,"/ruby.wasm");const s=await o(n).arrayBuffer(),a=await WebAssembly.compile(s),{vm:i}=await e(a);return t.files&&await Wt(this,i,t.files,r),t.fetch&&await Ft(this,i,t.fetch,r),t.js_modules&&await It(t.js_modules,r),i},registerJSModule(e,t,n){t=t.replace(/\W+/g,"__");const r=`__module_${fn}_${t}`;globalThis[r]=n,this.run(e,`require "js";$${t}=JS.global[:${r}]`),delete globalThis[r]},run:(e,t,...n)=>e.eval(tt(t),...n),runAsync:(e,t,...n)=>e.evalAsync(tt(t),...n),async runEvent(e,t,n){if(/^xworker\.(on\w+)$/.test(t)){const{$1:t}=RegExp,r=`__module_${fn}_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 ${pn}`)}};var hn={type:"wasmoon",module:(e="1.16.0")=>`https://cdn.jsdelivr.net/npm/wasmoon@${e}/+esm`,async engine({LuaFactory:e,LuaLibraries:t},n,r,s){const{stderr:o,stdout:a,get:i}=Fe(),c=await i((new e).createEngine());return c.global.getTable(t.Base,(e=>{c.global.setField(e,"print",a),c.global.setField(e,"printErr",o)})),n.files&&await Wt(this,c,n.files,s),n.fetch&&await Ft(this,c,n.fetch,s),n.js_modules&&await It(n.js_modules,s),c},registerJSModule:(e,t,n)=>{e.global.set(t,n)},run:(e,t,...n)=>{try{return e.doStringSync(tt(t),...n)}catch(t){Oe.get(e).stderr(t)}},runAsync:async(e,t,...n)=>{try{return await e.doString(tt(t),...n)}catch(t){Oe.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){Oe.get(e).stderr(t)}},transform:(e,t)=>t,writeFile:({cmodule:{module:{FS:e}}},t,n)=>((e,t,n)=>(Rt(e,Pt(t)),t=Tt(e,t),e.writeFile(t,new Uint8Array(n),{canOwn:!0})))(e,t,n)};const yn=new WeakMap,gn=async(e,t)=>{const{shelter:n,destroy:r,io:s}=yn.get(e),{output:o,result:a}=await n.captureR(tt(t));for(const{type:e,data:t}of o)s[e](t);return je(a,r,{token:!1})};var wn={type:"webr",experimental:!0,module:(e="0.4.2")=>`https://cdn.jsdelivr.net/npm/webr@${e}/dist/webr.mjs`,async engine(e,t,n,r){const{get:s}=Fe(),o=new e.WebR;await s(o.init().then((()=>o)));const a=await new o.Shelter;return yn.set(o,{module:e,shelter:a,destroy:a.destroy.bind(a),io:Oe.get(o)}),t.files&&await Wt(this,o,t.files,r),t.fetch&&await Ft(this,o,t.fetch,r),t.js_modules&&await It(t.js_modules,r),o},registerJSModule(e,t){console.warn(`Experimental interpreter: module ${t} is not supported (yet)`)},run:gn,runAsync:gn,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 mn=new Map,_n=new Map,An=[],bn=[],vn=new Proxy(new Map,{get(e,t){if(!e.has(t)){const[n,...r]=t.split("@"),s=mn.get(n),o=/^(?:\.?\.?\/|[a-z0-9-]+:\/\/)/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=>(_n.set(t,e),s(r,e,n,o))))}}),En=e=>{for(const t of[].concat(e.type))mn.set(t,e),An.push(`script[type="${t}"]`),bn.push(`${t}-`)};for(const e of[Ne,Vt,cn,dn,hn,wn])En(e);const{parse:kn}=JSON,jn=(e,t="./config.txt")=>{let n=typeof e;return"string"===n&&/\.(json|toml|txt)$/.test(e)?n=RegExp.$1:e=t,[pt(e),n]},xn=(e,t,n={})=>{const[r,s]=jn(e,t);return"json"===s?n=o(r).json():"toml"===s?n=o(r).text().then(Xt):"string"===s?n=Sn(e):"object"===s&&e?n=e:"txt"===s&&"string"==typeof n&&(n=Sn(n)),[n,e=r]},Sn=e=>{try{return kn(e)}catch(t){return Xt(e)}},$n=(e,t,n,r={})=>(t&&([r,t]=xn(t,n,r)),ut(r).then((n=>vn[e](n,t)))),Bn=(e,t="")=>`${e}@${t}`.replace(/@$/,"");function Pn(e=this){return String(e).replace(/^(async\s*)?(\bfunction\b)?(.*?)\(/,((e,t,n,r)=>r&&!n?`${t||""}function ${r}(`:e))}const Rn="BeforeRun",Tn="AfterRun",Mn=[`code${Rn}`,`code${Rn}Async`,`code${Tn}`,`code${Tn}Async`],On=["onWorker","onReady",`on${Rn}`,`on${Rn}Async`,`on${Tn}`,`on${Tn}Async`];function Fn(e,t){const{run:n,runAsync:r}=mn.get(this.type);return{...e,run:n.bind(this,t),runAsync:r.bind(this,t)}}const Cn=(e,t,n,r,s,o)=>{if(s||o){const a=Fn.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 Dn=class{constructor(e,t={}){const{main:n,worker:r}=t;this.interpreter=e,this.onWorker=n?.onWorker;for(const e of On.slice(1))this[e]=r?.[e];for(const e of Mn)this[e]=r?.[e]}toJSON(){const e={};for(const t of On.slice(1))this[t]&&(e[t]=Pn(this[t]));for(const t of Mn)this[t]&&(e[t]=tt(this[t]()));return e}};var Wn=(...e)=>function(t,n){if(e.length){const[t,r]=e;(n=st({},n||{type:t,version:r})).type||(n.type=t)}const[r]=jn(n.config,n.configURL),s=((...e)=>new Me(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,u]=o(r);switch(l){case 0:{let t=r;switch(u){case"bigint":l=8,t=r.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+u);t=null;break;case"undefined":return i([-1],r)}return i([l,t],r)}case 1:{if(u)return i([u,[...r]],r);const e=[],t=i([l,e],r);for(const t of r)e.push(c(t));return t}case 2:{if(u)switch(u){case"BigInt":return i([u,r.toString()],r);case"Boolean":case"Number":case"String":return i([u,r.valueOf()],r)}if(t&&"toJSON"in r)return c(r.toJSON());const n=[],p=i([l,n],r);for(const t of s(r))!e&&a(o(r[t]))||n.push([c(t),c(r[t])]);return p}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:p}=r;return i([l,{name:u,message:p}],r)};return c})(!(t||n),!!t,new Map,r)(e),r},{parse:c,stringify:l}=JSON,u={json:!0,lossy:!0};var p=Object.freeze({__proto__:null,parse:e=>t(c(e)),stringify:e=>l(i(e,u))});const f="apply",d="construct",y="defineProperty",h="deleteProperty",g="get",w="getOwnPropertyDescriptor",m="getPrototypeOf",_="has",A="isExtensible",b="ownKeys",E="preventExtensions",v="set",k="setPrototypeOf";var j=Object.freeze({__proto__:null,APPLY:f,CONSTRUCT:d,DEFINE_PROPERTY:y,DELETE_PROPERTY:h,GET:g,GET_OWN_PROPERTY_DESCRIPTOR:w,GET_PROTOTYPE_OF:m,HAS:_,IS_EXTENSIBLE:A,OWN_KEYS:b,PREVENT_EXTENSION:E,SET:v,SET_PROTOTYPE_OF:k});const x="destruct",S="c70de905-a212-4eca-80aa-dad8bd4e677b",$="="+S,P="-"+S,{ArrayBuffer:B,Atomics:T,Promise:R}=globalThis,{isArray:O}=Array,{create:F,getPrototypeOf:M,values:C}=Object,D=M(Int32Array),I=F(T),L=({currentTarget:e,type:t,origin:n,lastEventId:r,source:s,ports:o},a)=>e.dispatchEvent(new MessageEvent(t,{data:a,origin:n,lastEventId:r,source:s,ports:o})),W=()=>R.withResolvers();let H=0;const N=new Map,J=(e,t)=>class extends e{constructor(e,...n){super(e,...n),e instanceof t&&N.set(this,[H++,0,W()])}},U=new WeakSet,q=e=>(U.add(e),e),z=(e,t)=>{const{data:n}=e,r=O(n)&&(n.at(0)===t||0===n.at(1)&&!t);return r&&(e.stopImmediatePropagation(),e.preventDefault()),r},K=e=>null!==e&&"object"==typeof e&&!U.has(e),G=new WeakMap,Y=(e,t,n)=>{if(N.has(e))t.set(e,N.get(e)[0]);else if(!(e instanceof D||e instanceof B))for(const r of C(e))K(r)&&!n.has(r)&&(n.add(r),Y(r,t,n))},X=(...e)=>({value:new R((t=>{let n=new Worker("data:application/javascript,onmessage%3De%3D%3EpostMessage(!Atomics.wait(...e.data))");n.onmessage=()=>t("ok"),n.postMessage(e)}))}),Z=(e,t)=>{const n=N.get(e),[r,s,{promise:o}]=n;return n[1]=t,[r,o]};let{BigInt64Array:V,Int32Array:Q,SharedArrayBuffer:ee,addEventListener:te,postMessage:ne}=globalThis,re=!0,se=e=>e,oe=!1;const ae=W();try{new ee(4),I.waitAsync||(I.waitAsync=X),ae.resolve()}catch(e){const t=ne,n=te,r=[];let s="",o="";ee=class extends B{},V=J(V,ee),Q=J(Q,ee),se=q,oe=!0,I.notify=(e,n)=>{const[r]=(e=>G.get(e))(e);return t([s,1,e,r,n]),0},I.waitAsync=(...e)=>{const[t,n]=Z(...e);return{value:n}},I.wait=(e,t,...n)=>{const[r]=Z(e,t,...n),a=new XMLHttpRequest;a.responseType="json",a.open("POST",`${o}?sabayon`,!1),a.setRequestHeader("Content-Type","application/json"),a.send(`["${s}",${r},${t}]`);const{response:i}=a;N.delete(e);for(let t=0;t{if(z(e,s)){const[t,n,...r]=e.data;switch(n){case 0:s=t,o=r.at(0)?.serviceWorker||"",o||(I.wait=null,ae.resolve());break;case 1:((e,t,n)=>{for(const[r,[s,o,{resolve:a}]]of N)if(t===s&&n===o){for(let t=0;t{for(const[n,r]of t)G.set(n,[r,e.currentTarget]);L(e,n)})(e,...r);break;case 3:ae.resolve()}}else if(re){const{currentTarget:t,type:n,origin:s,lastEventId:o,source:a,ports:i}=e;r.push([{currentTarget:t,type:n,origin:s,lastEventId:o,source:a,ports:i},e.data])}})),te=(e,...t)=>{if(n(e,...t),r.length)for(const e of r.splice(0))L(...e)},ne=(e,...n)=>t(((e,t)=>{const n=new Map;return K(t)&&Y(t,n,new Set),n.size?[e,2,n,t]:t})(s,e),...n)}await ae.promise,re=!1;const{BYTES_PER_ELEMENT:ie}=Int32Array,{BYTES_PER_ELEMENT:ce}=Uint16Array,{notify:le}=I,ue=new TextDecoder("utf-16"),pe=new WeakSet,fe=(...e)=>(pe.add(e),e);let de="";const ye=(e,t,n,r)=>{const[s]=r,o=n.get(s);if(!o)throw new Error(`Unknown proxy.${s}()`);e(o,t,r)};let he=0;const ge=([e,t,n,r,s,o,a,i,c],l)=>(...u)=>{let p=""!==de,f=0;p&&"="!==de[0]&&"-"!==de[0]&&(f=((e,t)=>setTimeout(console.warn,3e3,`💀🔒 - proxy.${e}() in proxy.${t}()`))(l,de));const d=he++;let y=[];pe.has(u.at(-1)||y)&&pe.delete(y=u.pop());const h=n(i?u.map(i):u);let g=t(2*ie);return a([e,2,l,d,g,h,r],{transfer:y}),c(g,0).value.then((()=>{p&&clearTimeout(f);const n=g[1];if(!n)return;const r=ce*n;return g=t(r+r%ie),a([e,1,d,g]),c(g,0).value.then((()=>{const e=new Uint16Array(g.buffer),t=o?e.subarray(0,n):e.slice(0,n);return s(ue.decode(t))}))}))},we=(e,t)=>new Proxy(t,{get:(t,n)=>{let r;return"then"!==n&&(r=t.get(n),r||(r=ge(e,n),t.set(n,r))),r},set:(e,t,n)=>"then"!==t&&!!e.set(t,n)}),{wait:me,waitAsync:_e}=I;var Ae=({parse:e,stringify:t,transform:n,interrupt:r}=JSON)=>{const s=((e,t)=>async(n,r,[s,o,a,i,c])=>{c&&(de=s);try{const s=await n(...i);if(void 0!==s){const n=e(t?t(s):s);r.set(o,n),a[1]=n.length}}finally{c&&(de=""),a[0]=1,le(a,0)}})(t,n),o=W(),a=new Map,i=new Map;let c="",l=me;if(me&&r){const{handler:e,timeout:t=42}=r;l=(n,r,s)=>{for(;"timed-out"===(s=me(n,r,0,t));)e();return s}}return te("message",(t=>{if(z(t,c)){const[r,u,...p]=t.data;switch(u){case 0:{const t=!!me;c=r,o.resolve({polyfill:oe,sync:t,transfer:fe,proxy:we([c,e=>new Q(new ee(e)),se,t,e,oe,ne,n,t?(...e)=>({value:{then:t=>t(l(...e))}}):_e],a)});break}case 2:a.size?ye(s,i,a,p):setTimeout(ye,0,s,i,a,p);break;case 1:((e,[t,n])=>{const r=e.get(t);e.delete(t);for(let e=new Uint16Array(n.buffer),t=0,{length:s}=r;t{n&&console.debug(`Held value ${String(t)} not relevant anymore`),e(t)})),Be=Object.create(null),{Object:Te,Proxy:Re,Reflect:Oe}=globalThis,{isArray:Fe}=Array,{ownKeys:Me}=Oe,{create:Ce,hasOwn:De,values:Ie}=Te,Le=(e,t)=>t===be?e[0]:t===Ee?e():t===je?e.$:e,We=(e,t,n,r)=>{const s={type:{value:t}},o=De(e,"valueOf");for(const a of Ie(j)){let i=r(e[a]||Oe[a]);if(o&&a===g){const{valueOf:r}=e,{value:s}=i;i={value(e,o,...a){return o===n?r.call(this,Le(e,t)):s.call(this,e,o,...a)}}}s[a]=i}return Ce(e,s)},He=(e,t,n,r=e)=>{if(r===e)switch(typeof e){case je:case Se:r||(r=!1);case Ee:break;default:r=!1,t===e&&(t=Te(e))}const s=new Re(t,n),{destruct:o}=n;return o?((e,t,{debug:n,handler:r,return:s,token:o=e}=Be)=>{const a=s||new Proxy(e,r||Be),i=[a,[t,e,!!n]];return!1!==o&&i.push(o),Pe.register(...i),a})(e,o,{token:r,return:s}):s},Ne=e=>t=>{const n=typeof t;return n===je?t?e.get(t)?.[0]??(e=>Fe(e)?be:je)(t):ve:n},Je=e=>t=>{let n=typeof t;switch(n){case je:if(!t){n=ve;break}case Ee:const r=e.get(t);r&&([n,t]=r)}return[n,t]},Ue=e=>((e=>{Pe.unregister(e)})(e),e);var qe=e=>{const t=new WeakMap,n=Symbol(),r={},s=(e,n,r)=>(t.set(e,[n,r]),e),o={proxy:r,release:Ue,pair:Je(t),typeOf:Ne(t),isProxy:e=>t.has(e),valueOf:e=>e[n]??e.valueOf()};for(const t of Me(e)){if(De(o,t))continue;const a=e[t];switch(t){case be:{const e=We(a,t,n,(e=>({value([t],...n){return e.call(this,t,...n)}})));r[t]=(t,...n)=>s(He(t,[t],e,...n),be,t);break}case Ee:{const e=We(a,t,n,(e=>({value(t,...n){return e.call(this,t(),...n)}})));r[t]=(t,...n)=>{return s(He(t,(r=t,$e.bind(r)),e,...n),Ee,t);var r};break}case je:{const e=We(a,t,n,(e=>({value({$:t},...n){return e.call(this,t,...n)}})));r[t]=(t,...n)=>s(He(t,{$:t},e,...n),je,t);break}default:{const e=We(a,t,n,(e=>({value:e})));r[t]=(n,...r)=>s(He(n,n,e,...r),t,n);break}}}return o};const{clear:ze,drop:Ke,get:Ge,hold:Ye}=(()=>{const e=new Map,t=new Map;let n=0;return{clear:()=>{e.clear(),t.clear()},drop:n=>{const[r,s]=typeof n===ke?[t,e]:[e,t],o=r.has(n);return o&&(s.delete(r.get(n)),r.delete(n)),o},get:e=>t.get(e),hold:r=>{if(!e.has(r)){let s;for(;t.has(s=n++););e.set(r,s),t.set(s,r)}return e.get(r)}}})();var Xe=Object.fromEntries([be,"bigint","boolean",Ee,ve,ke,je,"string",xe,Se].map(((e,t)=>[e,t])));const{[b]:Ze}=Reflect,Ve=new Map(Ze(Symbol).filter((e=>typeof Symbol[e]===xe)).map((e=>[Symbol[e],e]))),Qe=e=>Ve.get(e)||`.${Symbol.keyFor(e)||""}`,{isArray:et}=Array,{[f]:tt}=Reflect;var nt=(e,t)=>{const n=new Map,r=(e,t)=>{let r=n.get(e)?.deref();return r||n.set(e,new WeakRef(r=t(e))),r},s=([e,t])=>{switch(e){case Xe[je]:return null==t?globalThis:typeof t===ke?r(t,l.object):t;case Xe[be]:return typeof t===ke?r(t,l.array):t;case Xe[Ee]:return typeof t===ke?r(t,l.function):Ge(parseInt(t));case Xe[xe]:return(e=>{if(e.startsWith("."))return Symbol.for(e.slice(1));for(const[t,n]of Ve)if(n===e)return t})(t);default:return t}},o=e=>{let[n,r]=p(e);switch(n){case je:if(r==globalThis||null==r)r=null;else if(typeof r===je&&!(r instanceof D))if(r=t(r),et(r))r=r.map(o);else for(const e in r)r[e]=o(r[e]);return[Xe[je],r];case be:return[Xe[be],typeof r===ke?r:t(r).map(o)];case Ee:return[Xe[Ee],typeof r===Ee?String(Ye(t(r))):r];case xe:return[Xe[xe],Qe(e)];default:return[Xe[n],r]}},a=(...t)=>s(e(...t)),i={[y]:(e,t,n)=>a(y,e,o(t),o(n)),[h]:(e,t)=>a(h,e,o(t)),[g]:(e,t)=>a(g,e,o(t)),[m]:e=>a(m,e),[w]:(e,t)=>{const n=a(w,e,o(t));if(n){const{get:e,set:t,value:r}=n;e&&(n.get=s(e)),t&&(n.set=s(t)),r&&(n.value=s(r))}return n},[_]:(e,t)=>a(_,e,o(t)),[A]:e=>a(A,e),[b]:e=>a(b,e).map(s),[E]:e=>a(E,e),[v]:(e,t,n)=>a(v,e,o(t),o(n)),[k]:(e,t)=>a(k,e,o(t)),[x](t){n.delete(t),e(x,t)}},c={[je]:i,[be]:i,[Ee]:{...i,[f]:(e,...t)=>a(f,e,...t.map(o)),[d]:(e,...t)=>a(d,e,...t.map(o))}},{proxy:l,isProxy:u,pair:p}=qe(c);return{isProxy:u,global:l.object(null),method:async(e,t,...n)=>{const r=parseInt(t);switch(e){case f:{const[e,t]=n;return o(await tt(Ge(r),s(e),t.map(s)))}case x:Ke(r)}}}};const{assign:rt}=Object,st="entries",ot="readonly",at="readwrite",it={durability:"default",prefix:"IDBMap"},ct=({target:{result:e}})=>e;class lt extends EventTarget{#e;#t;#n;async#r(e,t){const n=(await this.#e).transaction(st,t,this.#t);return new Promise(((t,r)=>rt(e(n.objectStore(st)),{onsuccess:t,onerror:r})))}constructor(e,{durability:t=it.durability,prefix:n=it.prefix}=it){super(),this.#n=n,this.#t={durability:t},this.#e=new Promise(((t,n)=>{rt(indexedDB.open(`${this.#n}/${e}`),{onupgradeneeded({target:{result:e,transaction:n}}){e.objectStoreNames.length||e.createObjectStore(st),n.oncomplete=()=>t(e)},onsuccess(e){t(ct(e))},onerror(e){n(e),this.dispatchEvent(e)}})})).then((e=>{const t=this.dispatchEvent.bind(this);for(const n in e)n.startsWith("on")&&(e[n]=t);return e}))}dispatchEvent(e){const{type:t,message:n,isTrusted:r}=e;return super.dispatchEvent(r?rt(new Event(t),{message:n}):e)}async close(){(await this.#e).close()}get size(){return this.#r((e=>e.count()),ot).then(ct)}async clear(){await this.#r((e=>e.clear()),at)}async delete(e){await this.#r((t=>t.delete(e)),at)}async entries(){const e=await this.keys();return Promise.all(e.map((e=>this.get(e).then((t=>[e,t])))))}async forEach(e,t=this){for(const[n,r]of await this.entries())await e.call(t,r,n,this)}async get(e){return await this.#r((t=>t.get(e)),ot).then(ct)}async has(e){return void 0!==await this.#r((t=>t.getKey(e)),ot).then(ct)}async keys(){return await this.#r((e=>e.getAllKeys()),ot).then(ct)}async set(e,t){return await this.#r((n=>n.put(t,e)),at),this}async values(){const e=await this.keys();return Promise.all(e.map((e=>this.get(e))))}get[Symbol.toStringTag](){return this.#n}}class ut extends Map{#s;#o;constructor(...e){super(),this.#s=new lt(...e),this.#o=this.#s.entries().then((e=>{for(const[t,n]of e)super.set(t,n)}))}async close(){await this.#o,await this.#s.close()}async sync(){await this.#o}clear(){return this.#o=this.#o.then((()=>this.#s.clear())),super.clear()}delete(e){return this.#o=this.#o.then((()=>this.#s.delete(e))),super.delete(e)}set(e,t){return this.#o=this.#o.then((()=>this.#s.set(e,t))),super.set(e,t)}}const pt={object(...e){return this.string(function(e){for(var t=e[0],n=1,r=arguments.length;n{const t=e||console,n={buffered:ht,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 ft.set(t,n),t}}},yt=new TextDecoder,ht=(e,t=10)=>{const n=[];return r=>{if(r instanceof Uint8Array)for(const s of r)s===t?e(yt.decode(new Uint8Array(n.splice(0)))):n.push(s);else e(r)}},gt=(e,...t)=>pt[typeof e](e,...t),{isArray:wt}=Array,{assign:mt,create:_t,defineProperties:At,defineProperty:bt,entries:Et}=Object,{all:vt,resolve:kt}=new Proxy(Promise,{get:(e,t)=>e[t].bind(e)}),jt=(e,t=location.href)=>new URL(e,t.replace(/^blob:/,"")).href,xt=(e,t,n,r=!1,s=CustomEvent)=>{e.dispatchEvent(new s(`${t}:${n}`,{bubbles:!0,detail:{worker:r}}))},St=e=>Function(`\'use strict\';return (${e})`)(),$t=e=>e.replace(/^(?:\\n|\\r\\n)/,""),Pt=Symbol.for("polyscript.js_modules"),Bt=new Map;bt(globalThis,Pt,{value:Bt}),new Proxy(Bt,{get:(e,t)=>e.get(t),has:(e,t)=>e.has(t),ownKeys:e=>[...e.keys()]});const Tt=(e,t)=>!t.startsWith("_"),Rt=(e,t)=>new Proxy(e,{has:Tt,get:(e,n)=>e[t][n]}),Ot=(e,t)=>import(e).then((e=>{Bt.set(t,{...e})})),Ft=e=>new Promise(((t,n)=>{document.querySelector(`link[rel="stylesheet"][href="${e}"]`)?t():document.head.append(mt(document.createElement("link"),{rel:"stylesheet",href:e,onload:t,onerror:n}))})),Mt=e=>/\\.css$/i.test(new URL(e).pathname),Ct=(e,t)=>e.has(t),Dt=e=>[...e.keys()];var It=(e,t,n,r)=>{const s=globalThis[Pt];if(n)for(let[e,t]of Et(n)){let n=s.get(t);n&&!wt(n)||(s.set(t,n||(n=[])),n.push(e))}return((e,t,n,r)=>new Proxy(e,{has:Ct,ownKeys:Dt,get:(e,s)=>{let o=e.get(s);if(wt(o)){let a=o;o=null;for(let e of a)e=jt(e,r),Mt(e)?n.importCSS(e):(n.importJS(e,s),o=t[Pt].get(s));e.set(s,o)}return o}}))(s,e,t,r)};const Lt=new Map,Wt=e=>Lt.get(e),Ht=(e,t)=>{try{return Function("require",t)(Wt)}catch(t){ft.get(e).stderr(t)}};var Nt={type:"dummy",module:()=>"data:application/javascript,",engine:e=>dt().get(e),registerJSModule(e,t,n){Lt.set(t,n)},run:Ht,runAsync:Ht,runEvent:async(e,t,n)=>{try{await Function("require","e",`return ${t}(e)`)(Wt,n)}catch(t){ft.get(e).stderr(t)}},transform:(e,t)=>t,writeFile(){}};const Jt=Object.getOwnPropertyDescriptors(Response.prototype),Ut=e=>"function"==typeof e,qt={get:(e,t)=>Jt.hasOwnProperty(t)?((e,t,{get:n,value:r})=>n||!Ut(r)?e.then((e=>e[t])):(...n)=>e.then((e=>e[t](...n))))(e,t,Jt[t]):((e,t)=>Ut(t)?t.bind(e):t)(e,e[t])};var zt=(e,...t)=>new Proxy(fetch(e,...t),qt);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 Kt=!globalThis.window,Gt=({FS:e,PATH:t,PATH_FS:n},r,s)=>{const o=n.resolve(r),a=t.dirname(o);return e.mkdirTree?e.mkdirTree(a):Xt(e,a),e.writeFile(o,new Uint8Array(s),{canOwn:!0})},Yt=e=>{const t=e.split("/");return t.pop(),t.join("/")},Xt=(e,t)=>{const n=[];for(const r of t.split("/"))"."!==r&&".."!==r&&(n.push(r),r&&e.mkdir(n.join("/")))},Zt=(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(/^\\/+/,"/")},Vt=e=>{const t=e.map((e=>e.trim().replace(/(^[/]*|[/]*$)/g,""))).filter((e=>""!==e&&"."!==e)).join("/");return e[0].startsWith("/")?`/${t}`:t},Qt=(e,t)=>zt(jt(e,t)).arrayBuffer(),en=(e,t,n,r)=>vt((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(wt(r))return r.map((n=>({url:Vt([e,n]),path:Vt([t,n])})));const s=n||e.slice(1+e.lastIndexOf("/"));return[{url:e,path:Vt([t,s])}]}))})(n).map((({url:n,path:s})=>Qt(n,r).then((n=>e.writeFile(t,s,n)))))),tn=(e,t)=>t.endsWith("/")?`${t}${e.split("/").pop()}`:t,nn=(e,t)=>e.replace(/\\{.+?\\}/g,(e=>{if(!t.has(e))throw new SyntaxError(`Invalid template: ${e}`);return t.get(e)})),rn=(e,t,n,r)=>vt((e=>{const t=new Map,n=new Set,r=[];for(const[s,o]of Et(e))if(/^\\{.+\\}$/.test(s)){if(t.has(s))throw new SyntaxError(`Duplicated template: ${s}`);t.set(s,nn(o,t))}else{const e=nn(s,t),a=tn(e,nn(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:n,path:s})=>Qt(n,r).then((r=>e.writeFile(t,s,r,n)))))),sn=({main:e,worker:t},n)=>{const r=[];if(t&&Kt)for(let[e,s]of Et(t))e=jt(e,n),r.push(Ot(e,s));if(e&&!Kt)for(let[t,s]of Et(e))t=jt(t,n),Mt(t)?Ft(t):r.push(Ot(t,s));return vt(r)},on=e=>t=>{dispatchEvent(new CustomEvent(`${e}:progress`,{detail:t}))},an=new WeakMap,cn=async(e,t,n,r,s)=>{r.files&&(t("Loading files"),await rn(e,n,r.files,s),t("Loaded files")),r.fetch&&(t("Loading fetch"),await en(e,n,r.fetch,s),t("Loaded fetch")),r.js_modules&&(t("Loading JS modules"),await sn(r.js_modules,s),t("Loaded JS modules"))},ln=(e,t,n)=>{"polyscript"===t&&(n.lazy_py_modules=async(...t)=>(await an.get(e)(t),t.map((t=>e.pyimport(t)))),n.storage=async e=>{const t=new ut(e);return await t.sync(),t},n.JSON=p),e.registerJsModule(t,n)},un=(e,t)=>{if(e.endsWith("/*")){if(/\\.(zip|whl|tgz|tar(?:\\.gz)?)$/.test(t))return RegExp.$1;throw new Error(`Unsupported archive ${t}`)}return""},pn=(e,t,...n)=>{try{return e.runPython(gt(t),...n)}catch(t){ft.get(e).stderr(t)}},fn=async(e,t,...n)=>{try{return await e.runPythonAsync(gt(t),...n)}catch(t){ft.get(e).stderr(t)}},dn=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){ft.get(e).stderr(t)}};var yn=(new TextEncoder).encode("_F=\'github:\'\\n_E=\'user-agent\'\\n_D=True\\n_C=False\\n_B=\'/\'\\n_A=None\\nfrom uio import StringIO\\nimport sys\\nclass Response:\\n\\tdef __init__(A,f):A.raw=f;A.encoding=\'utf-8\';A._cached=_A\\n\\tdef close(A):\\n\\t\\tif A.raw:A.raw.close();A.raw=_A\\n\\t\\tA._cached=_A\\n\\t@property\\n\\tdef content(self):\\n\\t\\tA=self\\n\\t\\tif A._cached is _A:\\n\\t\\t\\ttry:A._cached=A.raw.read()\\n\\t\\t\\tfinally:A.raw.close();A.raw=_A\\n\\t\\treturn A._cached\\n\\t@property\\n\\tdef text(self):return str(self.content,self.encoding)\\n\\tdef json(A):import ujson;return ujson.loads(A.content)\\nHEADERS_TO_IGNORE=_E,\\ntry:import js\\nexcept Exception as err:raise OSError(\'This version of urequests can only be used in the browser\')\\nHEADERS_TO_IGNORE=_E,\\ndef request(method,url,data=_A,json=_A,headers={},stream=_A,auth=_A,timeout=_A,parse_headers=_D):\\n\\tE=timeout;D=method;C=data;from js import XMLHttpRequest as G;A=G.new();A.withCredentials=_C\\n\\tif auth is not _A:import ubinascii;H,I=auth;A.open(D,url,_C,H,I)\\n\\telse:A.open(D,url,_C)\\n\\tfor(F,J)in headers.items():\\n\\t\\tif F.lower()not in HEADERS_TO_IGNORE:A.setRequestHeader(F,J)\\n\\tif E:A.timeout=int(E*1000)\\n\\tif json is not _A:assert C is _A;import ujson;C=ujson.dumps(json);A.setRequestHeader(\'Content-Type\',\'application/json\')\\n\\tA.send(C);B=Response(StringIO(A.responseText));B.status_code=A.status;B.reason=A.statusText;B.headers=A.getAllResponseHeaders();return B\\ndef get(url,**A):return request(\'GET\',url,**A)\\n_PACKAGE_INDEX=const(\'https://micropython.org/pi/v2\')\\n_CHUNK_SIZE=128\\ndef _ensure_path_exists(path):\\n\\timport os;A=path.split(_B)\\n\\tif not A[0]:A.pop(0);A[0]=_B+A[0]\\n\\tB=\'\'\\n\\tfor C in range(len(A)-1):\\n\\t\\tB+=A[C]\\n\\t\\ttry:os.stat(B)\\n\\t\\texcept:os.mkdir(B)\\n\\t\\tB+=_B\\ndef _chunk(src,dest):\\n\\tA=memoryview(bytearray(_CHUNK_SIZE))\\n\\twhile _D:\\n\\t\\tB=src.readinto(A)\\n\\t\\tif B==0:break\\n\\t\\tdest(A if B==_CHUNK_SIZE else A[:B])\\ndef _check_exists(path,short_hash):\\n\\tA=short_hash;import os\\n\\ttry:\\n\\t\\timport binascii as C,hashlib as D\\n\\t\\twith open(path,\'rb\')as E:B=D.sha256();_chunk(E,B.update);F=str(C.hexlify(B.digest())[:len(A)],\'utf-8\');return F==A\\n\\texcept:return _C\\ndef _rewrite_url(url,branch=_A):\\n\\tB=branch;A=url\\n\\tif not B:B=\'HEAD\'\\n\\tif A.startswith(_F):A=A[7:].split(_B);A=\'https://raw.githubusercontent.com/\'+A[0]+_B+A[1]+_B+B+_B+_B.join(A[2:])\\n\\treturn A\\ndef _download_file(url,dest):\\n\\tB=dest;A=get(url)\\n\\ttry:\\n\\t\\tif A.status_code!=200:print(\'Error\',A.status_code,\'requesting\',url);return _C\\n\\t\\tprint(\'Copying:\',B);_ensure_path_exists(B)\\n\\t\\twith open(B,\'wb\')as C:_chunk(A.raw,C.write)\\n\\t\\treturn _D\\n\\tfinally:A.close()\\ndef _install_json(package_json_url,index,target,version,mpy):\\n\\tK=\'File not found: {} {}\';I=version;H=index;G=package_json_url;D=target;E=get(_rewrite_url(G,I))\\n\\ttry:\\n\\t\\tif E.status_code!=200:print(\'Package not found:\',G);return _C\\n\\t\\tF=E.json()\\n\\tfinally:E.close()\\n\\tfor(A,C)in F.get(\'hashes\',()):\\n\\t\\tB=D+_B+A\\n\\t\\tif _check_exists(B,C):print(\'Exists:\',B)\\n\\t\\telse:\\n\\t\\t\\tL=\'{}/file/{}/{}\'.format(H,C[:2],C)\\n\\t\\t\\tif not _download_file(L,B):print(K.format(A,C));return _C\\n\\tfor(A,J)in F.get(\'urls\',()):\\n\\t\\tB=D+_B+A\\n\\t\\tif not _download_file(_rewrite_url(J,I),B):print(K.format(A,J));return _C\\n\\tfor(M,N)in F.get(\'deps\',()):\\n\\t\\tif not _install_package(M,H,D,N,mpy):return _C\\n\\treturn _D\\ndef _install_package(package,index,target,version,mpy):\\n\\tD=index;C=target;B=version;A=package\\n\\tif A.startswith(\'http://\')or A.startswith(\'https://\')or A.startswith(_F):\\n\\t\\tif A.endswith(\'.py\')or A.endswith(\'.mpy\'):print(\'Downloading {} to {}\'.format(A,C));return _download_file(_rewrite_url(A,B),C+_B+A.rsplit(_B)[-1])\\n\\t\\telse:\\n\\t\\t\\tif not A.endswith(\'.json\'):\\n\\t\\t\\t\\tif not A.endswith(_B):A+=_B\\n\\t\\t\\t\\tA+=\'package.json\'\\n\\t\\t\\tprint(\'Installing {} to {}\'.format(A,C))\\n\\telse:\\n\\t\\tif not B:B=\'latest\'\\n\\t\\tprint(\'Installing {} ({}) from {} to {}\'.format(A,B,D,C));E=sys.implementation._mpy&255 if mpy and hasattr(sys.implementation,\'_mpy\')else\'py\';A=\'{}/package/{}/{}/{}.json\'.format(D,\'py\',A,B)\\n\\treturn _install_json(A,D,C,B,mpy)\\ndef install(package,index=_A,target=_A,version=_A,mpy=_D):\\n\\tB=target;A=index\\n\\tif not B:\\n\\t\\tfor C in sys.path:\\n\\t\\t\\tif C.endswith(\'/lib\'):B=C;break\\n\\t\\telse:print(\'Unable to find lib dir in sys.path\');return\\n\\tif not A:A=_PACKAGE_INDEX\\n\\tif _install_package(package,A.rstrip(_B),B,version,mpy):print(\'Done\')\\n\\telse:print(\'Package may be partially installed\')");const hn=async e=>(await import("./toml-DiUM0_qs.js")).parse(e),gn=(e,t)=>{try{e.mkdir(t)}catch(e){}},wn=on("mpy");var mn={type:"micropython",module:(e="1.24.0")=>`https://cdn.jsdelivr.net/npm/@micropython/micropython-webassembly-pyscript@${e}/micropython.mjs`,async engine({loadMicroPython:e},t,n,r){const{stderr:s,stdout:o,get:a}=dt({stderr:ht(console.error),stdout:ht(console.log)});n=n.replace(/\\.m?js$/,".wasm"),wn("Loading MicroPython");const i=await a(e({linebuffer:!1,stderr:s,stdout:o,url:n})),c=_n.bind(this,i,r);return an.set(i,c),await cn(this,wn,i,t,r),this.writeFile(i,"./mip.py",yn),t.packages&&(wn("Loading packages"),await c(t.packages),wn("Loaded packages")),wn("Loaded MicroPython"),i},registerJSModule:ln,run:pn,runAsync:fn,runEvent:dn,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=un(t,r);if(c){const r=t.slice(0,-1);switch("./"!==r&&s.mkdir(r),c){case"whl":case"zip":{const e=new Blob([n],{type:"application/zip"});return import("./zip-Bf48tRr5.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)gn(s,i);else{gn(s,o.dirname(i));const t=await e.getData(new n);s.writeFile(i,t,{canOwn:!0})}}i.close()}))}case"tgz":case"tar.gz":{const t="./_.tar.gz";return Gt(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 Gt(i,t,n)}};async function _n(e,t,n){let r;for(const s of n)if(s.endsWith(".whl")){const n=jt(s,t),r=await zt(n).arrayBuffer();await this.writeFile(e,"./*",r,n)}else r||(r=e.pyimport("mip")),r.install(s)}const An=new FinalizationRegistry((([e,t,n])=>{n&&console.debug(`%c${String(t)}`,"font-weight:bold","collected"),e(t)})),bn=Object.create(null),En=(e,t,{debug:n,handler:r,return:s,token:o=e}=bn)=>{const a=s||new Proxy(e,r||bn),i=[a,[t,e,!!n]];return!1!==o&&i.push(o),An.register(...i),a},vn={dict_converter:Object.fromEntries},{stringify:kn}=JSON;let jn=!1;const xn=e=>(...t)=>{try{return jn=!0,e(...t)}finally{jn=!1}};let Sn=!1;const $n=()=>{if(Sn)return;Sn=!0;const e=new WeakMap,t=e=>e.destroy(),n=n=>{for(let r=0;r`https://cdn.jsdelivr.net/pyodide/v${e}/full/pyodide.mjs`,async engine({loadPyodide:e},t,n,r){Kt||"auto"!==t.experimental_create_proxy||$n(),Pn("Loading Pyodide");let{packages:s}=t;Pn("Loading Storage");const o=n.slice(0,n.lastIndexOf("/")),a=new ut(o),i={indexURL:o},c="never"!==t.packages_cache;if(await a.sync(),c){if(s){s=s.slice(0).sort();const e=kn(s);if(a.has(e)){const t=new Blob([a.get(e)],{type:"application/json"});i.lockFileURL=URL.createObjectURL(t),i.packages=s.map((e=>e.split("==")[0])),s=null}}}else a.clear();Pn("Loaded Storage");const{stderr:l,stdout:u,get:p}=dt(),f=await p(e({stderr:l,stdout:u,...i})),d=Rn.bind(f);return an.set(f,d),await cn(this,Pn,f,t,r),s&&await d(s,a,c),await a.close(),i.lockFileURL&&URL.revokeObjectURL(i.lockFileURL),Pn("Loaded Pyodide"),f},registerJSModule:ln,run:xn(pn),runAsync:xn(fn),runEvent:xn(dn),transform:(e,t)=>Tn.call(e,t),writeFile:(e,t,n,r)=>{const s=un(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 Gt({FS:o,PATH:a,PATH_FS:i},t,n)}};function Tn(e){const{ffi:{PyProxy:t}}=this;if(e&&"object"==typeof e){if(e instanceof t)return e.toJs(vn);if(e instanceof Map)return new Map([...e.entries()]);if(wt(e))return e.map(Tn,this)}return e}async function Rn(e,t,n=!1){const{log:r}=console,s=(e,...t)=>{r(e,...t),console.log=r,Pn(e),console.log=s};console.log=s,await this.loadPackage("micropip");const o=this.pyimport("micropip");if(await o.install(e,{keep_going:!0}),console.log=r,n&&t instanceof ut){const n=o.freeze();t.set(kn(e),n)}o.destroy()}const On="ruby-wasm-wasi",Fn=On.replace(/\\W+/g,"_");var Mn={type:On,experimental:!0,module:(e="2.6.2")=>`https://cdn.jsdelivr.net/npm/@ruby/3.2-wasm-wasi@${e}/dist/browser/+esm`,async engine({DefaultRubyVM:e},t,n,r){n=n.replace(/\\/browser\\/\\+esm$/,"/ruby.wasm");const s=await zt(n).arrayBuffer(),o=await WebAssembly.compile(s),{vm:a}=await e(o);return t.files&&await rn(this,a,t.files,r),t.fetch&&await en(this,a,t.fetch,r),t.js_modules&&await sn(t.js_modules,r),a},registerJSModule(e,t,n){t=t.replace(/\\W+/g,"__");const r=`__module_${Fn}_${t}`;globalThis[r]=n,this.run(e,`require "js";$${t}=JS.global[:${r}]`),delete globalThis[r]},run:(e,t,...n)=>e.eval(gt(t),...n),runAsync:(e,t,...n)=>e.evalAsync(gt(t),...n),async runEvent(e,t,n){if(/^xworker\\.(on\\w+)$/.test(t)){const{$1:t}=RegExp,r=`__module_${Fn}_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 ${On}`)}};var Cn={type:"wasmoon",module:(e="1.16.0")=>`https://cdn.jsdelivr.net/npm/wasmoon@${e}/+esm`,async engine({LuaFactory:e,LuaLibraries:t},n,r,s){const{stderr:o,stdout:a,get:i}=dt(),c=await i((new e).createEngine());return c.global.getTable(t.Base,(e=>{c.global.setField(e,"print",a),c.global.setField(e,"printErr",o)})),n.files&&await rn(this,c,n.files,s),n.fetch&&await en(this,c,n.fetch,s),n.js_modules&&await sn(n.js_modules,s),c},registerJSModule:(e,t,n)=>{e.global.set(t,n)},run:(e,t,...n)=>{try{return e.doStringSync(gt(t),...n)}catch(t){ft.get(e).stderr(t)}},runAsync:async(e,t,...n)=>{try{return await e.doString(gt(t),...n)}catch(t){ft.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){ft.get(e).stderr(t)}},transform:(e,t)=>t,writeFile:({cmodule:{module:{FS:e}}},t,n)=>((e,t,n)=>(Xt(e,Yt(t)),t=Zt(e,t),e.writeFile(t,new Uint8Array(n),{canOwn:!0})))(e,t,n)};const Dn=new WeakMap,In=async(e,t)=>{const{shelter:n,destroy:r,io:s}=Dn.get(e),{output:o,result:a}=await n.captureR(gt(t));for(const{type:e,data:t}of o)s[e](t);return En(a,r,{token:!1})};var Ln={type:"webr",experimental:!0,module:(e="0.4.2")=>`https://cdn.jsdelivr.net/npm/webr@${e}/dist/webr.mjs`,async engine(e,t,n,r){const{get:s}=dt(),o=new e.WebR;await s(o.init().then((()=>o)));const a=await new o.Shelter;return Dn.set(o,{module:e,shelter:a,destroy:a.destroy.bind(a),io:ft.get(o)}),t.files&&await rn(this,o,t.files,r),t.fetch&&await en(this,o,t.fetch,r),t.js_modules&&await sn(t.js_modules,r),o},registerJSModule(e,t){console.warn(`Experimental interpreter: module ${t} is not supported (yet)`)},run:In,runAsync:In,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 Wn=new Map,Hn=new Map,Nn=new Proxy(new Map,{get(e,t){if(!e.has(t)){const[n,...r]=t.split("@"),s=Wn.get(n),o=/^(?:\\.?\\.?\\/|[a-z0-9-]+:\\/\\/)/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=>(Hn.set(t,e),s(r,e,n,o))))}}),Jn=e=>{for(const t of[].concat(e.type))Wn.set(t,e)};for(const e of[Nt,mn,Bn,Mn,Cn,Ln])Jn(e);const{parse:Un}=JSON,qn=(e,t,n={})=>{const[r,s]=((e,t="./config.txt")=>{let n=typeof e;return"string"===n&&/\\.(json|toml|txt)$/.test(e)?n=RegExp.$1:e=t,[jt(e),n]})(e,t);return"json"===s?n=zt(r).json():"toml"===s?n=zt(r).text().then(hn):"string"===s?n=zn(e):"object"===s&&e?n=e:"txt"===s&&"string"==typeof n&&(n=zn(n)),[n,e=r]},zn=e=>{try{return Un(e)}catch(t){return hn(e)}},Kn="BeforeRun",Gn="AfterRun",Yn=[`code${Kn}`,`code${Kn}Async`,`code${Gn}`,`code${Gn}Async`],Xn=["onWorker","onReady",`on${Kn}`,`on${Kn}Async`,`on${Gn}`,`on${Gn}Async`];function Zn(e,t){const{run:n,runAsync:r}=Wn.get(this.type);return{...e,run:n.bind(this,t),runAsync:r.bind(this,t)}}const Vn=(e,t,n,r,s,o)=>{if(s||o){const a=Zn.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 Qn,er,tr;const nr=(e,t)=>{addEventListener(e,t||(async t=>{try{await Qn,er(`xworker.on${e}`,t)}catch(e){postMessage(e)}}),!!t&&{once:!0})},{parse:rr,stringify:sr}=p,{proxy:or,sync:ar,polyfill:ir,window:cr,isWindowProxy:lr}=await(async e=>{const t=await Ae(e),{isProxy:n,global:r,method:s}=nt(t.proxy[$],e?.transform||(e=>e));return t.proxy[P]=s,{...t,window:r,isWindowProxy:n}})({parse:rr,stringify:sr,transform:e=>tr?tr(e):e}),ur={polyfill:ir,sync:or,window:ar?cr:null,isWindowProxy:lr,onmessage:console.info,onerror:console.error,onmessageerror:console.warn,postMessage:postMessage.bind(self)};nr("message",(({data:{options:e,config:t,configURL:n,code:r,hooks:s}})=>{Qn=(async()=>{try{const{id:o,tag:a,type:i,custom:c,version:l,config:u,async:p}=e,f=((e,t="")=>`${e}@${t}`.replace(/@$/,""))(i,l),d=await((e,t,n,r={})=>(t&&([r,t]=qn(t,n,r)),kt(r).then((n=>Nn[e](n,t)))))(f,t,n,u),{js_modules:y}=Hn.get(f),h=y?.main,g=_t(Wn.get(i)),w=((e,t,n,r)=>({type:t,config:n,interpreter:r,io:ft.get(r),run:(t,...n)=>e.run(r,t,...n),runAsync:(t,...n)=>e.runAsync(r,t,...n),runEvent:(...t)=>e.runEvent(r,...t)}))(g,c||i,u||{},d);let m="run";if(p&&(m+="Async"),s){let e,t,n="",r="";for(const e of Yn){const t=s[e];if(t){const s=e.endsWith("Async");(s&&p||!s&&!p)&&(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,$t(t),...o);return r&&s(e,r,...o),a}:async(e,t,...o)=>{n&&await s(e,n,...o);const a=await s(e,$t(t),...o);return r&&await s(e,r,...o),a}})(g,m,n,r);for(const n of Xn.slice(2)){const r=s[n];if(r){const s=n.endsWith("Async");if(s&&p||!s&&!p){const s=St(r);n.startsWith("onBefore")?e=s:t=s}}}Vn(g,w,ur,p,e,t)}let _,A,b,E=null,v="";ar&&(({CustomEvent:_,document:A}=cr),E=o&&A.getElementById(o)||null,b=e=>xt(E,c||i,e,!0,_));const k=It(cr,or,h,t);if(((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}`,Rt(r,e));t.registerJSModule(n,s,r)})(i,g,d,k),g.registerJSModule(d,"polyscript",{xworker:ur,currentScript:E,config:w.config,js_modules:k,get target(){return!v&&E&&("SCRIPT"===a?E.after(mt(cr.document.createElement(`script-${c||i}`),{id:v=`${o}-target`})):(v=o,E.replaceChildren(),E.style.display="block")),v}}),er=g.runEvent.bind(g,d),tr=g.transform.bind(g,d),E&&b("ready"),s?.onReady&&St(s?.onReady).call(g,Zn.call(g,w,d),ur),await g[m](d,r),["micropython","pyodide"].includes(g.type)){const e="polyscript",t=`__${e}_workers__`,n="__export__";d.runPython([`import js as ${t}`,`${t}.${t} = "${n}" in locals() and ${n} or []`,`del ${t}`].join("\\n"));const r=[...globalThis[t]];delete globalThis[t],r.length&&d.runPython([`from ${e} import xworker as ${t}`,...r.map((e=>`${t}.sync.${e} = ${e}`)),`del ${t}`].join("\\n"))}return E&&b("done"),postMessage("polyscript:done"),d}catch(e){postMessage(e)}})(),nr("error"),nr("message"),nr("messageerror"),ar&&addEventListener("py:progress",(({type:e,detail:t})=>{cr.dispatchEvent(new cr.CustomEvent(e,{detail:t}))}))}));\n'.replace(Re,Te)],{type:"application/javascript"})),...e))({serviceWorker:n?.serviceWorker||n?.service_worker}),{postMessage:a}=s,i=this instanceof Dn,c=st(s.proxy,{importJS:kt,importCSS:jt}),l=Promise.withResolvers();let u=o(t).text().then((e=>{const t=i?this.toJSON():void 0;a.call(s,{options:n,config:r,code:e,hooks:t})})).then((()=>{u={then:e=>e()}}));return at(s,{sync:{value:c},ready:{value:l.promise},postMessage:{value:(e,...t)=>u.then((()=>a.call(s,e,...t)))},onerror:{writable:!0,configurable:!0,value:console.error}}),s.addEventListener("message",(e=>{const{data:t}=e,n=t instanceof Error;(n||"polyscript:done"===t)&&(e.stopImmediatePropagation(),n?(l.reject(t),s.onerror(ot(e,{type:{value:"error"},error:{value:t}}))):l.resolve(s))})),i&&this.onWorker?.(this.interpreter,s),s};const In="Invalid content",Ln="Invalid worker attribute",Nn="Invalid worker attribute";var Un=e=>{const{src:t,worker:n}=e.attributes;if(n){let{value:r}=n;if(r)throw new SyntaxError(Nn);if(r=t?.value,!r){if(t)throw new SyntaxError(Ln);if(e.childElementCount){const{innerHTML:t,localName:n,type:s}=e,o=s||n.replace(/-script$/,"");r=nt(t),console.warn(`Deprecated: use + + + + + diff --git a/test/integration/pyodide.js b/test/integration/pyodide.js index 9035d24..9c55c6c 100644 --- a/test/integration/pyodide.js +++ b/test/integration/pyodide.js @@ -33,4 +33,9 @@ export default (playwright, baseURL) => { test('Pyodide transform', python.error(playwright, baseURL)); test('Pyodide events ready', python.disabledUntilReady(playwright, baseURL)); + + test('Pyodide index_urls', async ({ page }) => { + await page.goto(`${baseURL}/index_urls.html`); + await page.waitForSelector('html.test_foo'); + }); };