@pyscript/core 0.4.56 → 0.5.0-rc2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{codemirror-BZEh__gm.js → codemirror-ZWX__zRS.js} +2 -2
- package/dist/{codemirror-BZEh__gm.js.map → codemirror-ZWX__zRS.js.map} +1 -1
- package/dist/{codemirror_commands-leH8shna.js → codemirror_commands-BvofQ4B2.js} +2 -2
- package/dist/{codemirror_commands-leH8shna.js.map → codemirror_commands-BvofQ4B2.js.map} +1 -1
- package/dist/{codemirror_lang-python-DuOzopOD.js → codemirror_lang-python-CAjFAwEr.js} +2 -2
- package/dist/{codemirror_lang-python-DuOzopOD.js.map → codemirror_lang-python-CAjFAwEr.js.map} +1 -1
- package/dist/{codemirror_language-Dakzaxks.js → codemirror_language-BzugrQDC.js} +2 -2
- package/dist/{codemirror_language-Dakzaxks.js.map → codemirror_language-BzugrQDC.js.map} +1 -1
- package/dist/{codemirror_view-Bm5_2vT5.js → codemirror_view-DrrFKRyn.js} +2 -2
- package/dist/codemirror_view-DrrFKRyn.js.map +1 -0
- package/dist/core-sVxLb9Ur.js +2 -0
- package/dist/core-sVxLb9Ur.js.map +1 -0
- package/dist/core.js +1 -1
- package/dist/{deprecations-manager-BYGF73-y.js → deprecations-manager-C1bCFFAJ.js} +2 -2
- package/dist/{deprecations-manager-BYGF73-y.js.map → deprecations-manager-C1bCFFAJ.js.map} +1 -1
- package/dist/{error-DgYfWJQg.js → error-BE-P8gi6.js} +2 -2
- package/dist/{error-DgYfWJQg.js.map → error-BE-P8gi6.js.map} +1 -1
- package/dist/{index-DA5aljNV.js → index-YJCpGJSa.js} +2 -2
- package/dist/{index-DA5aljNV.js.map → index-YJCpGJSa.js.map} +1 -1
- package/dist/{mpy-DiqSc6w9.js → mpy-awU48RT6.js} +2 -2
- package/dist/{mpy-DiqSc6w9.js.map → mpy-awU48RT6.js.map} +1 -1
- package/dist/{py-DEubHlb_.js → py-DQxM9K2E.js} +2 -2
- package/dist/{py-DEubHlb_.js.map → py-DQxM9K2E.js.map} +1 -1
- package/dist/{py-editor-DHmqLMO5.js → py-editor-CUd-CQKV.js} +2 -2
- package/dist/{py-editor-DHmqLMO5.js.map → py-editor-CUd-CQKV.js.map} +1 -1
- package/dist/{py-terminal-E6BBcU6N.js → py-terminal-CgSL5otC.js} +2 -2
- package/dist/{py-terminal-E6BBcU6N.js.map → py-terminal-CgSL5otC.js.map} +1 -1
- package/package.json +6 -6
- package/src/stdlib/pyscript/magic_js.py +5 -12
- package/src/stdlib/pyscript/web/__init__.py +7 -4
- package/src/stdlib/pyscript/web/elements.py +134 -114
- package/src/stdlib/pyscript.js +3 -3
- package/dist/codemirror_view-Bm5_2vT5.js.map +0 -1
- package/dist/core-DKrwnOQh.js +0 -3
- package/dist/core-DKrwnOQh.js.map +0 -1
- package/dist.zip +0 -0
@@ -0,0 +1,2 @@
|
|
1
|
+
const e=(e,n,t=globalThis)=>{const r=Symbol.for(e),s=r in t;return[s?t[r]:Object.defineProperty(t,r,{value:n})[r],s]};Promise.withResolvers||(Promise.withResolvers=function(){var e,n,t=new this((function(t,r){e=t,n=r}));return{resolve:e,reject:n,promise:t}});const n=(e,n=document)=>[...n.querySelectorAll(e)],t=(e,n=document)=>{const t=(new XPathEvaluator).createExpression(e).evaluate(n,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE),r=[];for(let e=0,{snapshotLength:n}=t;e<n;e++)r.push(t.snapshotItem(e));return r},r=Object.getOwnPropertyDescriptors(Response.prototype),s=e=>"function"==typeof e,o={get:(e,n)=>r.hasOwnProperty(n)?((e,n,{get:t,value:r})=>t||!s(r)?e.then((e=>e[n])):(...t)=>e.then((e=>e[n](...t))))(e,n,r[n]):((e,n)=>s(n)?n.bind(e):n)(e,e[n])};var a=(e,...n)=>new Proxy(fetch(e,...n),o);const i=new Proxy(new Map,{get:(e,n)=>(e.has(n)||e.set(n,Promise.withResolvers()),e.get(n))}),l=new Set(["__dict__","constructor","get","has","includes","next","set","then"]),c=new Proxy(Object.freeze({}),{get:(e,n)=>"string"!=typeof n||l.has(n)?void 0:i[n].promise.then((e=>e.sync))}),p="object"==typeof self?self:globalThis,d=e=>((e,n)=>{const t=(n,t)=>(e.set(t,n),n),r=s=>{if(e.has(s))return e.get(s);const[o,a]=n[s];switch(o){case 0:case-1:return t(a,s);case 1:{const e=t([],s);for(const n of a)e.push(r(n));return e}case 2:{const e=t({},s);for(const[n,t]of a)e[r(n)]=r(t);return e}case 3:return t(new Date(a),s);case 4:{const{source:e,flags:n}=a;return t(new RegExp(e,n),s)}case 5:{const e=t(new Map,s);for(const[n,t]of a)e.set(r(n),r(t));return e}case 6:{const e=t(new Set,s);for(const n of a)e.add(r(n));return e}case 7:{const{name:e,message:n}=a;return t(new p[e](n),s)}case 8:return t(BigInt(a),s);case"BigInt":return t(Object(BigInt(a)),s)}return t(new p[o](a),s)};return r})(new Map,e)(0),f="",{toString:u}={},{keys:m}=Object,h=e=>{const n=typeof e;if("object"!==n||!e)return[0,n];const t=u.call(e).slice(8,-1);switch(t){case"Array":return[1,f];case"Object":return[2,f];case"Date":return[3,f];case"RegExp":return[4,f];case"Map":return[5,f];case"Set":return[6,f]}return t.includes("Array")?[1,t]:t.includes("Error")?[7,t]:[2,t]},y=([e,n])=>0===e&&("function"===n||"symbol"===n),g=(e,{json:n,lossy:t}={})=>{const r=[];return((e,n,t,r)=>{const s=(e,n)=>{const s=r.push(e)-1;return t.set(n,s),s},o=r=>{if(t.has(r))return t.get(r);let[a,i]=h(r);switch(a){case 0:{let n=r;switch(i){case"bigint":a=8,n=r.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+i);n=null;break;case"undefined":return s([-1],r)}return s([a,n],r)}case 1:{if(i)return s([i,[...r]],r);const e=[],n=s([a,e],r);for(const n of r)e.push(o(n));return n}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(n&&"toJSON"in r)return o(r.toJSON());const t=[],l=s([a,t],r);for(const n of m(r))!e&&y(h(r[n]))||t.push([o(n),o(r[n])]);return l}case 3:return s([a,r.toISOString()],r);case 4:{const{source:e,flags:n}=r;return s([a,{source:e,flags:n}],r)}case 5:{const n=[],t=s([a,n],r);for(const[t,s]of r)(e||!y(h(t))&&!y(h(s)))&&n.push([o(t),o(s)]);return t}case 6:{const n=[],t=s([a,n],r);for(const t of r)!e&&y(h(t))||n.push(o(t));return t}}const{message:l}=r;return s([a,{name:i,message:l}],r)};return o})(!(n||t),!!n,new Map,r)(e),r},{parse:_,stringify:w}=JSON,b={json:!0,lossy:!0};var v=Object.freeze({__proto__:null,parse:e=>d(_(e)),stringify:e=>w(g(e,b))});const E="array",M="function",O="null",k="number",P="object",T="string",R="symbol",S="undefined";let D=0;const x=new Map,j=new Map,A=e=>j.get(e),N=e=>{if(!x.has(e)){let n;for(;j.has(n=D++););x.set(e,n),j.set(n,e)}return x.get(e)},{ArrayBuffer:C,Atomics:W,Promise:I}=globalThis,{isArray:L}=Array,{create:$,getPrototypeOf:H,values:U}=Object,z=H(Int32Array),F=$(W),B=()=>I.withResolvers();let q=0;const J=new Map,G=(e,n)=>class extends e{constructor(e,...t){super(e,...t),e instanceof n&&J.set(this,[q++,0,B()])}},Y=new WeakSet,K=e=>(Y.add(e),e),V=(e,n)=>{const{data:t}=e,r=L(t)&&(t.at(0)===n||0===t.at(1)&&!n);return r&&(e.stopImmediatePropagation(),e.preventDefault()),r},X=e=>null!==e&&"object"==typeof e&&!Y.has(e),Z=new WeakMap,Q=(e,n,t)=>{if(J.has(e))n.set(e,J.get(e)[0]);else if(!(e instanceof z||e instanceof C))for(const r of U(e))X(r)&&!t.has(r)&&(t.add(r),Q(r,n,t))},ee=(...e)=>({value:new I((n=>{let t=new Worker("data:application/javascript,onmessage%3De%3D%3EpostMessage(!Atomics.wait(...e.data))");t.onmessage=()=>n("ok"),t.postMessage(e)}))}),ne=(e,n,t)=>{for(const[t,r]of n)Z.set(t,[r,e.currentTarget]);(({currentTarget:e,type:n,origin:t,lastEventId:r,source:s,ports:o},a)=>{e.dispatchEvent(new MessageEvent(n,{data:a,origin:t,lastEventId:r,source:s,ports:o}))})(e,t)};let{BigInt64Array:te,Int32Array:re,SharedArrayBuffer:se,Worker:oe}=globalThis,ae=e=>e,ie=!1;const le=e=>({...e,type:"module"});try{new se(4),oe=class extends oe{constructor(e,n){super(e,le(n))}},F.waitAsync||(F.waitAsync=ee)}catch(e){const n=crypto.randomUUID(),t=new Map,r=(e,n,t,...r)=>{e.addEventListener(n,t,...r)},s=({serviceWorker:e},s,o)=>{let a;r(e,"message",(e=>{if(V(e,n)){const[r,s,o]=e.data,i=[s,o].join(","),l=e=>{t.delete(i),a.postMessage([n,s,o,e])},c=t.get(i);if(c)l(c);else{const{promise:e,resolve:n}=B();t.set(i,n),e.then(l)}}})),e.getRegistration(s).then((n=>n??e.register(s))).then((function e(n){a=n.installing||n.waiting||n.active,"activated"===a.state?o():r(a,"statechange",(()=>e(n)),{once:!0})}))};ae=K,ie=!0,F.notify=(e,r)=>{const[s,o]=(e=>Z.get(e))(e),a=[s,r].join(","),i=t.get(a);return i?i(e):t.set(a,e),o.postMessage([n,1,e,s,r]),0},F.waitAsync=(e,...n)=>{const[t,r]=((e,n)=>{const t=J.get(e),[r,s,{promise:o}]=t;return t[1]=n,[r,o]})(e,...n);return{value:r}},se=class extends C{},te=G(te,se),re=G(re,se);let o=null;oe=class extends oe{constructor(e,t){let a=t?.serviceWorker||"";if(a){if(a=new URL(a,location.href).href,t={...t,serviceWorker:a},!o){const{promise:e,resolve:n}=B();s(navigator,a,n),o=e}o.then((()=>super.postMessage([n,3])))}super(e,le(t)),super.postMessage([n,0,t]),r(this,"message",(e=>{if(V(e,n)){const[n,t,...r]=e.data;switch(t){case 1:((e,n,t)=>{for(const[r,[s,o,{resolve:a}]]of J)if(n===s&&t===o){for(let n=0;n<e.length;n++)r[n]=e[n];J.delete(r),a("ok");break}})(...r);break;case 2:ne(e,...r)}}}))}postMessage(e,...t){return super.postMessage(((e,n)=>{const t=new Map;return X(n)&&Q(n,t,new Set),t.size?[e,2,t,n]:n})(n,e),...t)}}}const{BYTES_PER_ELEMENT:ce}=Int32Array,{BYTES_PER_ELEMENT:pe}=Uint16Array,{notify:de}=F,fe=new TextDecoder("utf-16"),ue=new WeakSet,me=(...e)=>(ue.add(e),e);let he="";let ye=0;const ge=([e,n,t,r,s,o,a,i,l,c],p)=>(...d)=>{let f=""!==he,u=0;f&&(u=((e,n)=>setTimeout(console.warn,1e3,`💀🔒 - proxy.${e}() in proxy.${n}()`))(p,he));const m=ye++,h=[];ue.has(d.at(-1)||h)&&ue.delete(h=d.pop());const y=r(l?d.map(l):d);let g=new n(new t(2*ce));return i([e,2,p,m,g,y,s],{transfer:h}),c(g,0).value.then((()=>{f&&clearTimeout(u);const r=g[1];if(!r)return;const s=pe*r;return g=new n(new t(s+s%ce)),i([e,1,m,g]),c(g,0).value.then((()=>{const e=new Uint16Array(g.buffer),n=a?e.subarray(0,r):e.slice(0,r);return o(fe.decode(n))}))}))};var _e=({parse:e,stringify:n,transform:t}=JSON)=>{const r=((e,n)=>async(t,r,[s,o,a,i,l])=>{l&&(he=s);try{const s=await t(...i);if(void 0!==s){const t=e(n?n(s):s);r.set(o,t),a[1]=t.length}}finally{l&&(he=""),a[0]=1,de(a,0)}})(n,t),s=crypto.randomUUID();return{Worker:class extends oe{constructor(n,o){const a=new Map,i=new Map;super(n,o),this.proxy=((e,n)=>new Proxy(n,{get:(n,t)=>{let r;return"then"!==t&&(r=n.get(t),r||(r=ge(e,t),n.set(t,r))),r},set:(e,n,t)=>"then"!==n&&!!e.set(n,t)}))([s,re,se,ae,!1,e,ie,(...e)=>this.postMessage(...e),t,F.waitAsync],a),this.postMessage(ae([s,0,o])),this.addEventListener("message",(e=>{if(V(e,s)){const[n,t,...s]=e.data;switch(t){case 2:((e,n,t,r)=>{const[s]=r,o=t.get(s);if(!o)throw new Error(`Unknown proxy.${s}()`);e(o,n,r)})(r,i,a,s);break;case 1:((e,[n,t])=>{const r=e.get(n);e.delete(n);for(let e=new Uint16Array(t.buffer),n=0,{length:s}=r;n<s;n++)e[n]=r.charCodeAt(n);de(t,0)})(i,s)}}}))}},polyfill:ie,transfer:me}},we=Object.fromEntries([E,"bigint","boolean",M,O,k,P,T,R,S].map(((e,n)=>[e,n])));const be="ownKeys",ve="destruct",{[be]:Ee}=Reflect,Me=new Map(Ee(Symbol).filter((e=>typeof Symbol[e]===R)).map((e=>[Symbol[e],e]))),Oe=e=>Me.get(e)||`.${Symbol.keyFor(e)||""}`,ke="3753967f-73c7-40f1-9973-3c5e60d13535",Pe="M"+ke,Te="W"+ke,Re=new FinalizationRegistry((([e,n,t])=>{t&&console.debug(`Held value ${String(n)} not relevant anymore`),e(n)})),Se=Object.create(null),De=(e,n,{debug:t,handler:r,return:s,token:o=e}=Se)=>{const a=s||new Proxy(e,r||Se),i=[a,[n,e,!!t]];return!1!==o&&i.push(o),Re.register(...i),a},{addEventListener:xe}=EventTarget.prototype,je=new WeakMap;Reflect.defineProperty(EventTarget.prototype,"addEventListener",{value(e,n,...t){const r=t.at(0)?.invoke;if(r){let n=je.get(this);n||je.set(this,n=new Map),n.set(e,[].concat(r)),delete t[0].invoke}return xe.call(this,e,n,...t)}});const{isArray:Ae}=Array;const{url:Ne}=import.meta,Ce=/import\((['"])([^)]+?\.js)\1\)/g,We=(e,n,t)=>`import(${n}${new URL(t,Ne).href}${n})`,{Worker:Ie}=(e=>{const n=_e(e),t=e=>{const n=typeof e;switch(n){case P:return null===e?[we[O],e]:e===globalThis?[we[P],null]:Ae(e)?[we[E],N(e)]:[we[P],e instanceof z?e:N(e)];case M:return[we[M],N(e)];case R:return[we[R],Oe(e)];default:return[we[n],e]}};class r extends n.Worker{constructor(e,n){const{proxy:r}=super(e,n),{[Te]:s}=r,o=new Map,a=e=>{o.delete(e),s(ve,e)},i=([e,n])=>{switch(e){case we[P]:if(null===n)return globalThis;if(typeof n===k)return A(n);if(!(n instanceof z))for(const e in n)n[e]=i(n[e]);return n;case we[E]:return typeof n===k?A(n):n.map(i);case we[M]:switch(typeof n){case k:return A(n);case T:{let e=o.get(n)?.deref();return e||(e=De(n,a,{token:!1,return:function(...e){return e.length&&e[0]instanceof Event&&(e=>{const{currentTarget:n,target:t,type:r}=e,s=je.get(n||t)?.get(r);if(s)for(const n of s)e[n]()})(e[0]),s("apply",n,t(this),e.map(t)).then(i)}}),o.set(n,new WeakRef(e))),e}}case we[R]:return(e=>{if(e.startsWith("."))return Symbol.for(e.slice(1));for(const[n,t]of Me)if(t===e)return n})(n);default:return n}};r[Pe]=(e,n,...r)=>{if(e===ve)(e=>{const[n,t]=typeof e===k?[j,x]:[x,j],r=n.has(e);r&&(t.delete(n.get(e)),n.delete(e))})(n);else{const s=Reflect[e],o=null==n?globalThis:A(n);switch(e){case"defineProperty":{const[e,n]=r.map(i);return t(s(o,e,n))}case"getOwnPropertyDescriptor":{const e=s(o,...r.map(i));if(e){const{get:n,set:r,value:s}=e;n&&(e.get=t(n)),r&&(e.set=t(r)),s&&(e.value=t(s))}return[we[e?P:S],e]}case be:return[we[E],s(o).map(t)];default:return((e,n,r)=>t(e(n,...r.map(i))))(s,o,r)}}}}}return{...n,Worker:r}})(v);const Le={object(...e){return this.string(function(e){for(var n=e[0],t=1,r=arguments.length;t<r;t++)n+=arguments[t]+e[t];return n}(...e))},string(e){for(const n of e.split(/[\r\n]+/))if(n.trim().length){/^(\s+)/.test(n)&&(e=e.replace(new RegExp("^"+RegExp.$1,"gm"),""));break}return e}},{replace:$e}="",He=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34);/g,Ue={"&":"&","&":"&","<":"<","<":"<",">":">",">":">","'":"'","'":"'",""":'"',""":'"'},ze=e=>Ue[e],Fe=new WeakMap,Be=e=>{const n=e||console,t={buffered:Je,stderr:(n.stderr||console.error).bind(n),stdout:(n.stdout||console.log).bind(n)};return{stderr:(...e)=>t.stderr(...e),stdout:(...e)=>t.stdout(...e),async get(e){const n=await e;return Fe.set(n,t),n}}},qe=new TextDecoder,Je=(e,n=10)=>{const t=[];return r=>{if(r instanceof Uint8Array)for(const s of r)s===n?e(qe.decode(new Uint8Array(t.splice(0)))):t.push(s);else e(r)}},Ge=(e,...n)=>Le[typeof e](e,...n),Ye=e=>$e.call(e,He,ze),{isArray:Ke}=Array,{assign:Ve,create:Xe,defineProperties:Ze,defineProperty:Qe,entries:en}=Object,{all:nn,resolve:tn}=new Proxy(Promise,{get:(e,n)=>e[n].bind(e)}),rn=(e,n=location.href)=>new URL(e,n.replace(/^blob:/,"")).href;let sn=0;const on=(e,n)=>({id:e.id||(e.id=`${n}-w${sn++}`),tag:e.tagName}),an=(e,n,t,r=!1,s=CustomEvent)=>{e.dispatchEvent(new s(`${n}:${t}`,{bubbles:!0,detail:{worker:r}}))},ln=(e,n,t,r)=>({type:n,config:t,interpreter:r,io:Fe.get(r),run:(n,...t)=>e.run(r,n,...t),runAsync:(n,...t)=>e.runAsync(r,n,...t),runEvent:(...n)=>e.runEvent(r,...n)}),cn=e=>e.replace(/^(?:\n|\r\n)/,""),pn=(e,n,t,r)=>{const s=e[n].bind(e);e[n]="run"===n?(e,n,...o)=>{t&&s(e,t,...o);const a=s(e,cn(n),...o);return r&&s(e,r,...o),a}:async(e,n,...o)=>{t&&await s(e,t,...o);const a=await s(e,cn(n),...o);return r&&await s(e,r,...o),a}},dn=Symbol.for("polyscript.js_modules"),fn=new Map;Qe(globalThis,dn,{value:fn});const un=new Proxy(fn,{get:(e,n)=>e.get(n),has:(e,n)=>e.has(n),ownKeys:e=>[...e.keys()]}),mn=(e,n)=>!n.startsWith("_"),hn=(e,n)=>new Proxy(e,{has:mn,get:(e,t)=>e[n][t]}),yn=(e,n,t,r)=>{if("pyodide"===e)return;const s="polyscript.js_modules";for(const e of Reflect.ownKeys(r))n.registerJSModule(t,`${s}.${e}`,hn(r,e));n.registerJSModule(t,s,r)},gn=(e,n)=>import(e).then((e=>{fn.set(n,{...e})})),_n=e=>new Promise(((n,t)=>{document.querySelector(`link[rel="stylesheet"][href="${e}"]`)?n():document.head.append(Ve(document.createElement("link"),{rel:"stylesheet",href:e,onload:n,onerror:t}))})),wn=e=>/\.css$/i.test(new URL(e).pathname),bn=!globalThis.window,vn=({FS:e,PATH:n,PATH_FS:t},r,s)=>{const o=t.resolve(r),a=n.dirname(o);return e.mkdirTree?e.mkdirTree(a):Mn(e,a),e.writeFile(o,new Uint8Array(s),{canOwn:!0})},En=e=>{const n=e.split("/");return n.pop(),n.join("/")},Mn=(e,n)=>{const t=[];for(const r of n.split("/"))"."!==r&&".."!==r&&(t.push(r),r&&e.mkdir(t.join("/")))},On=(e,n)=>{const t=[];for(const e of n.split("/"))switch(e){case"":case".":break;case"..":t.pop();break;default:t.push(e)}return[e.cwd()].concat(t).join("/").replace(/^\/+/,"/")},kn=e=>{const n=e.map((e=>e.trim().replace(/(^[/]*|[/]*$)/g,""))).filter((e=>""!==e&&"."!==e)).join("/");return e[0].startsWith("/")?`/${n}`:n},Pn=(e,n)=>a(rn(e,n)).arrayBuffer(),Tn=(e,n,t,r)=>nn((e=>{for(const{files:n,to_file:t,from:r=""}of e){if(void 0!==n&&void 0!==t)throw new Error("Cannot use 'to_file' and 'files' parameters together!");if(void 0===n&&void 0===t&&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:n=".",to_file:t,files:r})=>{if(Ke(r))return r.map((t=>({url:kn([e,t]),path:kn([n,t])})));const s=t||e.slice(1+e.lastIndexOf("/"));return[{url:e,path:kn([n,s])}]}))})(t).map((({url:t,path:s})=>Pn(t,r).then((t=>e.writeFile(n,s,t)))))),Rn=(e,n)=>n.endsWith("/")?`${n}${e.split("/").pop()}`:n,Sn=(e,n)=>e.replace(/\{.+?\}/g,(e=>{if(!n.has(e))throw new SyntaxError(`Invalid template: ${e}`);return n.get(e)})),Dn=(e,n,t,r)=>nn((e=>{const n=new Map,t=new Set,r=[];for(const[s,o]of en(e))if(/^\{.+\}$/.test(s)){if(n.has(s))throw new SyntaxError(`Duplicated template: ${s}`);n.set(s,Sn(o,n))}else{const e=Sn(s,n),a=Rn(e,Sn(o||"./",n));if(t.has(a))throw new SyntaxError(`Duplicated destination: ${a}`);t.add(a),r.push({url:e,path:a})}return r})(t).map((({url:t,path:s})=>Pn(t,r).then((r=>e.writeFile(n,s,r,t)))))),xn=({main:e,worker:n},t)=>{const r=[];if(n&&bn)for(let[e,s]of en(n))e=rn(e,t),r.push(gn(e,s));if(e&&!bn)for(let[n,s]of en(e))n=rn(n,t),wn(n)?_n(n):r.push(gn(n,s));return nn(r)},{assign:jn}=Object,An="entries",Nn="readonly",Cn="readwrite",Wn={durability:"default",prefix:"IDBMap"},In=({target:{result:e}})=>e;class Ln extends EventTarget{#e;#n;#t;async#r(e,n){const t=(await this.#e).transaction(An,n,this.#n);return new Promise(((n,r)=>jn(e(t.objectStore(An)),{onsuccess:n,onerror:r})))}constructor(e,{durability:n=Wn.durability,prefix:t=Wn.prefix}=Wn){super(),this.#t=t,this.#n={durability:n},this.#e=new Promise(((n,t)=>{jn(indexedDB.open(`${this.#t}/${e}`),{onupgradeneeded({target:{result:e,transaction:t}}){e.objectStoreNames.length||e.createObjectStore(An),t.oncomplete=()=>n(e)},onsuccess(e){n(In(e))},onerror(e){t(e),this.dispatchEvent(e)}})})).then((e=>{const n=this.dispatchEvent.bind(this);for(const t in e)t.startsWith("on")&&(e[t]=n);return e}))}dispatchEvent(e){const{type:n,message:t,isTrusted:r}=e;return super.dispatchEvent(r?jn(new Event(n),{message:t}):e)}async close(){(await this.#e).close()}get size(){return this.#r((e=>e.count()),Nn).then(In)}async clear(){await this.#r((e=>e.clear()),Cn)}async delete(e){await this.#r((n=>n.delete(e)),Cn)}async entries(){const e=await this.keys();return Promise.all(e.map((e=>this.get(e).then((n=>[e,n])))))}async forEach(e,n=this){for(const[t,r]of await this.entries())await e.call(n,r,t,this)}async get(e){return await this.#r((n=>n.get(e)),Nn).then(In)}async has(e){return void 0!==await this.#r((n=>n.getKey(e)),Nn).then(In)}async keys(){return await this.#r((e=>e.getAllKeys()),Nn).then(In)}async set(e,n){return await this.#r((t=>t.put(n,e)),Cn),this}async values(){const e=await this.keys();return Promise.all(e.map((e=>this.get(e))))}get[Symbol.toStringTag](){return this.#t}}class $n extends Map{#s;#o;constructor(...e){super(),this.#s=new Ln(...e),this.#o=this.#s.entries().then((e=>{for(const[n,t]of e)super.set(n,t)}))}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,n){return this.#o=this.#o.then((()=>this.#s.set(e,n))),super.set(e,n)}}const Hn=new WeakMap,Un=(e,n,t)=>{"polyscript"===n&&(t.lazy_py_modules=async(...n)=>(await Hn.get(e)(n),n.map((n=>e.pyimport(n)))),t.storage=async e=>{const n=new $n(e);return await n.sync(),n},t.JSON=v),e.registerJsModule(n,t)},zn=(e,n)=>{if(e.endsWith("/*")){if(/\.(zip|whl|tgz|tar(?:\.gz)?)$/.test(n))return RegExp.$1;throw new Error(`Unsupported archive ${n}`)}return""},Fn=(e,n,...t)=>{try{return e.runPython(Ge(n),...t)}catch(n){Fe.get(e).stderr(n)}},Bn=async(e,n,...t)=>{try{return await e.runPythonAsync(Ge(n),...t)}catch(n){Fe.get(e).stderr(n)}},qn=async(e,n,t)=>{const[r,...s]=n.split(".");let o,a=e.globals.get(r);for(const e of s)[o,a]=[a,a[e]];try{await a.call(o,t)}catch(n){Fe.get(e).stderr(n)}};var Jn=(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 # WARNING: mpy_version fails miserably with 1.22.0-380\n package = "{}/package/{}/{}/{}.json".format(index, "py", 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 Gn=async e=>(await import("./toml-DiUM0_qs.js")).parse(e),Yn=(e,n)=>{try{e.mkdir(n)}catch(e){}};var Kn={type:"micropython",module:(e="1.24.0-preview-114")=>`https://cdn.jsdelivr.net/npm/@micropython/micropython-webassembly-pyscript@${e}/micropython.mjs`,async engine({loadMicroPython:e},n,t,r){const{stderr:s,stdout:o,get:a}=Be({stderr:Je(console.error),stdout:Je(console.log)});t=t.replace(/\.m?js$/,".wasm");const i=await a(e({linebuffer:!1,stderr:s,stdout:o,url:t})),l=Vn.bind(this,i,r);return Hn.set(i,l),n.files&&await Dn(this,i,n.files,r),n.fetch&&await Tn(this,i,n.fetch,r),n.js_modules&&await xn(n.js_modules,r),this.writeFile(i,"./mip.py",Jn),n.packages&&await l(n.packages),i},registerJSModule:Un,run:Fn,runAsync:Bn,runEvent:qn,transform:(e,n)=>e.PyProxy.toJs(n),writeFile:(e,n,t,r)=>{const{FS:s,_module:{PATH:o,PATH_FS:a}}=e,i={FS:s,PATH:o,PATH_FS:a},l=zn(n,r);if(l){const r=n.slice(0,-1);switch("./"!==r&&s.mkdir(r),l){case"whl":case"zip":{const e=new Blob([t],{type:"application/zip"});return import("./zip-CGWtiqjJ.js").then((async({BlobReader:n,Uint8ArrayWriter:t,ZipReader:a})=>{const i=new a(new n(e));for(const e of await i.getEntries()){const{directory:n,filename:a}=e,i=r+a;if(n)Yn(s,i);else{Yn(s,o.dirname(i));const n=await e.getData(new t);s.writeFile(i,n,{canOwn:!0})}}i.close()}))}case"tgz":case"tar.gz":{const n="./_.tar.gz";return vn(i,n,t),void e.runPython(`\n import os, gzip, tarfile\n tar = tarfile.TarFile(fileobj=gzip.GzipFile(fileobj=open("${n}", "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("${n}")\n `)}}}return vn(i,n,t)}};async function Vn(e,n,t){let r;for(const s of t)if(s.endsWith(".whl")){const t=rn(s,n),r=await a(t).arrayBuffer();await this.writeFile(e,"./*",r,t)}else r||(r=e.pyimport("mip")),r.install(s)}const Xn={dict_converter:Object.fromEntries};let Zn=!1;const Qn=e=>(...n)=>{try{return Zn=!0,e(...n)}finally{Zn=!1}};let et=!1;const nt=()=>{if(et)return;et=!0;const e=new WeakMap,n=e=>e.destroy(),t=t=>{for(let r=0;r<t.length;r++){const s=t[r];if("function"==typeof s&&"copy"in s){Zn=!1;let o=e.get(s)?.deref();if(!o)try{o=De(s.copy(),n),e.set(s,new WeakRef(o))}catch(e){console.error(e)}o&&(t[r]=o),Zn=!0}}},{call:r}=Function,s=r.bind(r,r.apply);Object.defineProperties(Function.prototype,{apply:{value(e,n){return Zn&&t(n),s(this,e,n)}},call:{value(e,...n){return Zn&&t(n),s(this,e,n)}}})};var tt={type:"pyodide",module:(e="0.26.1")=>`https://cdn.jsdelivr.net/pyodide/v${e}/full/pyodide.mjs`,async engine({loadPyodide:e},n,t,r){bn||"auto"!==n.experimental_create_proxy||nt();const{stderr:s,stdout:o,get:a}=Be(),i=t.slice(0,t.lastIndexOf("/")),l=await a(e({stderr:s,stdout:o,indexURL:i})),c=rt.bind(l);return Hn.set(l,c),n.files&&await Dn(this,l,n.files,r),n.fetch&&await Tn(this,l,n.fetch,r),n.js_modules&&await xn(n.js_modules,r),n.packages&&await c(n.packages),l},registerJSModule:Un,run:Qn(Fn),runAsync:Qn(Bn),runEvent:Qn(qn),transform:({ffi:{PyProxy:e}},n)=>n instanceof e?n.toJs(Xn):n,writeFile:(e,n,t,r)=>{const s=zn(n,r);if(s)return e.unpackArchive(t,s,{extractDir:n.slice(0,-1)});const{FS:o,PATH:a,_module:{PATH_FS:i}}=e;return vn({FS:o,PATH:a,PATH_FS:i},n,t)}};async function rt(e){await this.loadPackage("micropip");const n=this.pyimport("micropip");await n.install(e,{keep_going:!0}),n.destroy()}const st="ruby-wasm-wasi",ot=st.replace(/\W+/g,"_");var at={type:st,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},n,t,r){t=t.replace(/\/browser\/\+esm$/,"/ruby.wasm");const s=await a(t).arrayBuffer(),o=await WebAssembly.compile(s),{vm:i}=await e(o);return n.files&&await Dn(this,i,n.files,r),n.fetch&&await Tn(this,i,n.fetch,r),n.js_modules&&await xn(n.js_modules,r),i},registerJSModule(e,n,t){n=n.replace(/\W+/g,"__");const r=`__module_${ot}_${n}`;globalThis[r]=t,this.run(e,`require "js";$${n}=JS.global[:${r}]`),delete globalThis[r]},run:(e,n,...t)=>e.eval(Ge(n),...t),runAsync:(e,n,...t)=>e.evalAsync(Ge(n),...t),async runEvent(e,n,t){if(/^xworker\.(on\w+)$/.test(n)){const{$1:n}=RegExp,r=`__module_${ot}_event`;globalThis[r]=t,this.run(e,`require "js";$xworker.call("${n}",JS.global[:${r}])`),delete globalThis[r]}else{const r=this.run(e,`method(:${n})`);await r.call(n,e.wrap(t))}},transform:(e,n)=>n,writeFile:()=>{throw new Error(`writeFile is not supported in ${st}`)}};var it={type:"wasmoon",module:(e="1.16.0")=>`https://cdn.jsdelivr.net/npm/wasmoon@${e}/+esm`,async engine({LuaFactory:e,LuaLibraries:n},t,r,s){const{stderr:o,stdout:a,get:i}=Be(),l=await i((new e).createEngine());return l.global.getTable(n.Base,(e=>{l.global.setField(e,"print",a),l.global.setField(e,"printErr",o)})),t.files&&await Dn(this,l,t.files,s),t.fetch&&await Tn(this,l,t.fetch,s),t.js_modules&&await xn(t.js_modules,s),l},registerJSModule:(e,n,t)=>{e.global.set(n,t)},run:(e,n,...t)=>{try{return e.doStringSync(Ge(n),...t)}catch(n){Fe.get(e).stderr(n)}},runAsync:async(e,n,...t)=>{try{return await e.doString(Ge(n),...t)}catch(n){Fe.get(e).stderr(n)}},runEvent:async(e,n,t)=>{const[r,...s]=n.split(".");let o,a=e.global.get(r);for(const e of s)[o,a]=[a,a[e]];try{await a.call(o,t)}catch(n){Fe.get(e).stderr(n)}},transform:(e,n)=>n,writeFile:({cmodule:{module:{FS:e}}},n,t)=>((e,n,t)=>(Mn(e,En(n)),n=On(e,n),e.writeFile(n,new Uint8Array(t),{canOwn:!0})))(e,n,t)};const lt=new WeakMap,ct=async(e,n)=>{const{shelter:t,destroy:r,io:s}=lt.get(e),{output:o,result:a}=await t.captureR(Ge(n));for(const{type:e,data:n}of o)s[e](n);return De(a,r,{token:!1})};var pt={type:"webr",experimental:!0,module:(e="0.4.0")=>`https://cdn.jsdelivr.net/npm/webr@${e}/dist/webr.mjs`,async engine(e,n,t,r){const{get:s}=Be(),o=new e.WebR;await s(o.init().then((()=>o)));const a=await new o.Shelter;return lt.set(o,{module:e,shelter:a,destroy:a.destroy.bind(a),io:Fe.get(o)}),n.files&&await Dn(this,o,n.files,r),n.fetch&&await Tn(this,o,n.fetch,r),n.js_modules&&await xn(n.js_modules,r),o},registerJSModule(e,n){console.warn(`Experimental interpreter: module ${n} is not supported (yet)`)},run:ct,runAsync:ct,async runEvent(e,n,t){await e.evalRVoid(`${n}(event)`,{env:{event:{type:[t.type]}}})},transform:(e,n)=>(console.log("transforming",n),n),writeFile:()=>{}};const dt=new Map,ft=new Map,ut=[],mt=[],ht=new Proxy(new Map,{get(e,n){if(!e.has(n)){const[t,...r]=n.split("@"),s=dt.get(t),o=/^(?:\.?\.?\/|https?:\/\/)/i.test(r)?r.join("@"):s.module(...r);e.set(n,{url:o,module:import(o),engine:s.engine.bind(s)})}const{url:t,module:r,engine:s}=e.get(n);return(e,o)=>r.then((r=>(ft.set(n,e),s(r,e,t,o))))}}),yt=e=>{for(const n of[].concat(e.type))dt.set(n,e),ut.push(`script[type="${n}"]`),mt.push(`${n}-`)};for(const e of[Kn,tt,at,it,pt])yt(e);const{parse:gt}=JSON,_t=(e,n="./config.txt")=>{let t=typeof e;return"string"===t&&/\.(json|toml|txt)$/.test(e)?t=RegExp.$1:e=n,[rn(e),t]},wt=e=>{try{return gt(e)}catch(n){return Gn(e)}},bt=(e,n,t,r={})=>{if(n){const[e,s]=_t(n,t);"json"===s?r=a(e).json():"toml"===s?r=a(e).text().then(Gn):"string"===s?r=wt(n):"object"===s&&n?r=n:"txt"===s&&"string"==typeof r&&(r=wt(r)),n=e}return tn(r).then((t=>ht[e](t,n)))},vt=(e,n="")=>`${e}@${n}`.replace(/@$/,"");function Et(e=this){return String(e).replace(/^(async\s*)?(\bfunction\b)?(.*?)\(/,((e,n,t,r)=>r&&!t?`${n||""}function ${r}(`:e))}const Mt="BeforeRun",Ot="AfterRun",kt=[`code${Mt}`,`code${Mt}Async`,`code${Ot}`,`code${Ot}Async`],Pt=["onWorker","onReady",`on${Mt}`,`on${Mt}Async`,`on${Ot}`,`on${Ot}Async`];function Tt(e,n){const{run:t,runAsync:r}=dt.get(this.type);return{...e,run:t.bind(this,n),runAsync:r.bind(this,n)}}const Rt=(e,n,t,r,s,o)=>{if(s||o){const a=Tt.bind(e,n),i=r?"runAsync":"run",l=e[i];e[i]=r?async function(e,n,...r){s&&await s.call(this,a(e),t);const i=await l.call(this,e,n,...r);return o&&await o.call(this,a(e),t),i}:function(e,n,...r){s&&s.call(this,a(e),t);const i=l.call(this,e,n,...r);return o&&o.call(this,a(e),t),i}}};let St=class{constructor(e,n={}){const{main:t,worker:r}=n;this.interpreter=e,this.onWorker=t?.onWorker;for(const e of Pt.slice(1))this[e]=r?.[e];for(const e of kt)this[e]=r?.[e]}toJSON(){const e={};for(const n of Pt.slice(1))this[n]&&(e[n]=Et(this[n]));for(const n of kt)this[n]&&(e[n]=Ge(this[n]()));return e}};const Dt=e=>e?.serviceWorker||e?.service_worker;var xt=(...e)=>function(n,t){if(e.length){const[n,r]=e;(t=Ve({},t||{type:n,version:r})).type||(t.type=n)}const[r,s]=_t(t.config,t.configURL);let o=Dt(t);o||"object"!==s||(o=Dt(t.config));const i=((...e)=>new Ie(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="array",h="function",d="null",y="number",g="object",w="symbol",m="undefined",_="apply",b="construct",E="defineProperty",v="deleteProperty",T="get",x="getOwnPropertyDescriptor",k="getPrototypeOf",S="has",O="isExtensible",A="ownKeys",R="preventExtensions",j="set",P="setPrototypeOf";var $=Object.freeze({__proto__:null,APPLY:_,CONSTRUCT:b,DEFINE_PROPERTY:E,DELETE_PROPERTY:v,GET:T,GET_OWN_PROPERTY_DESCRIPTOR:x,GET_PROTOTYPE_OF:k,HAS:S,IS_EXTENSIBLE:O,OWN_KEYS:A,PREVENT_EXTENSION:R,SET:j,SET_PROTOTYPE_OF:P});function I(){return this}const N=new FinalizationRegistry((([e,t,n])=>{n&&console.debug(`Held value ${String(t)} not relevant anymore`),e(t)})),M=Object.create(null),F=(e,t,{debug:n,handler:r,return:s,token:o=e}=M)=>{const a=s||new Proxy(e,r||M),i=[a,[t,e,!!n]];return!1!==o&&i.push(o),N.register(...i),a},{Object:W,Proxy:H,Reflect:D}=globalThis,{isArray:C}=Array,{ownKeys:L}=D,{create:B,hasOwn:U,values:q}=W,J=(e,t)=>t===f?e[0]:t===h?e():t===g?e.$:e,z=(e,t,n,r)=>{const s={type:{value:t}},o=U(e,"valueOf");for(const a of q($)){let i=r(e[a]||D[a]);if(o&&a===T){const{valueOf:r}=e,{value:s}=i;i={value(e,o,...a){return o===n?r.call(this,J(e,t)):s.call(this,e,o,...a)}}}s[a]=i}return B(e,s)},G=(e,t,n,r=e)=>{if(r===e)switch(typeof e){case g:case m:r||(r=!1);case h:break;default:r=!1,t===e&&(t=W(e))}const s=new H(t,n),{destruct:o}=n;return o?F(e,o,{token:r,return:s}):s},Y=e=>t=>{const n=typeof t;return n===g?t?e.get(t)?.[0]??(e=>C(e)?f:g)(t):d:n},K=e=>t=>{let n=typeof t;switch(n){case g:if(!t){n=d;break}case h:const r=e.get(t);r&&([n,t]=r)}return[n,t]},X=e=>((e=>{N.unregister(e)})(e),e);var V=e=>{const t=new WeakMap,n=Symbol(),r={},s=(e,n,r)=>(t.set(e,[n,r]),e),o={proxy:r,release:X,pair:K(t),typeOf:Y(t),isProxy:e=>t.has(e),valueOf:e=>e[n]??e.valueOf()};for(const t of L(e)){if(U(o,t))continue;const a=e[t];switch(t){case f:{const e=z(a,t,n,(e=>({value([t],...n){return e.call(this,t,...n)}})));r[t]=(t,...n)=>s(G(t,[t],e,...n),f,t);break}case h:{const e=z(a,t,n,(e=>({value(t,...n){return e.call(this,t(),...n)}})));r[t]=(t,...n)=>{return s(G(t,(r=t,I.bind(r)),e,...n),h,t);var r};break}case g:{const e=z(a,t,n,(e=>({value({$:t},...n){return e.call(this,t,...n)}})));r[t]=(t,...n)=>s(G(t,{$:t},e,...n),g,t);break}default:{const e=z(a,t,n,(e=>({value:e})));r[t]=(n,...r)=>s(G(n,n,e,...r),t,n);break}}}return o};let Z=0;const Q=new Map,ee=new Map,te=e=>ee.get(e),ne=e=>{if(!Q.has(e)){let t;for(;ee.has(t=Z++););Q.set(e,t),ee.set(t,e)}return Q.get(e)},{ArrayBuffer:re,Atomics:se,Promise:oe}=globalThis,{isArray:ae}=Array,{create:ie,getPrototypeOf:ce,values:le}=Object,ue=ce(Int32Array),pe=ie(se),fe=({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})),he=()=>oe.withResolvers();let de=0;const ye=new Map,ge=(e,t)=>class extends e{constructor(e,...n){super(e,...n),e instanceof t&&ye.set(this,[de++,0,he()])}},we=new WeakSet,me=e=>(we.add(e),e),_e=(e,t)=>{const{data:n}=e,r=ae(n)&&(n.at(0)===t||0===n.at(1)&&!t);return r&&(e.stopImmediatePropagation(),e.preventDefault()),r},be=e=>null!==e&&"object"==typeof e&&!we.has(e),Ee=new WeakMap,ve=(e,t,n)=>{if(ye.has(e))t.set(e,ye.get(e)[0]);else if(!(e instanceof ue||e instanceof re))for(const r of le(e))be(r)&&!n.has(r)&&(n.add(r),ve(r,t,n))},Te=(...e)=>({value:new oe((t=>{let n=new Worker("data:application/javascript,onmessage%3De%3D%3EpostMessage(!Atomics.wait(...e.data))");n.onmessage=()=>t("ok"),n.postMessage(e)}))}),xe=(e,t)=>{const n=ye.get(e),[r,s,{promise:o}]=n;return n[1]=t,[r,o]};let{BigInt64Array:ke,Int32Array:Se,SharedArrayBuffer:Oe,addEventListener:Ae,postMessage:Re}=globalThis,je=!0,Pe=e=>e,$e=!1;const Ie=he();try{new Oe(4),pe.waitAsync||(pe.waitAsync=Te),Ie.resolve()}catch(e){const t=Re,n=Ae,r=[];let s="",o="";Oe=class extends re{},ke=ge(ke,Oe),Se=ge(Se,Oe),Pe=me,$e=!0,pe.notify=(e,n)=>{const[r]=(e=>Ee.get(e))(e);return t([s,1,e,r,n]),0},pe.waitAsync=(...e)=>{const[t,n]=xe(...e);return{value:n}},pe.wait=(e,t,...n)=>{const[r]=xe(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;ye.delete(e);for(let t=0;t<i.length;t++)e[t]=i[t];return"ok"},n("message",(e=>{if(_e(e,s)){const[t,n,...r]=e.data;switch(n){case 0:s=t,o=r.at(0)?.serviceWorker||"",o||(pe.wait=null,Ie.resolve());break;case 1:((e,t,n)=>{for(const[r,[s,o,{resolve:a}]]of ye)if(t===s&&n===o){for(let t=0;t<e.length;t++)r[t]=e[t];ye.delete(r),a("ok");break}})(...r);break;case 2:((e,t,n)=>{for(const[n,r]of t)Ee.set(n,[r,e.currentTarget]);fe(e,n)})(e,...r);break;case 3:Ie.resolve()}}else if(je){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])}})),Ae=(e,...t)=>{if(n(e,...t),r.length)for(const e of r.splice(0))fe(...e)},Re=(e,...n)=>t(((e,t)=>{const n=new Map;return be(t)&&ve(t,n,new Set),n.size?[e,2,n,t]:t})(s,e),...n)}await Ie.promise,je=!1;const{BYTES_PER_ELEMENT:Ne}=Int32Array,{BYTES_PER_ELEMENT:Me}=Uint16Array,{notify:Fe}=pe,We=new TextDecoder("utf-16"),He=new WeakSet,De=(...e)=>(He.add(e),e);let Ce="";const Le=(e,t,n,r)=>{const[s]=r,o=n.get(s);if(!o)throw new Error(`Unknown proxy.${s}()`);e(o,t,r)};let Be=0;const Ue=([e,t,n,r,s,o,a,i,c,l],u)=>(...p)=>{let f=""!==Ce,h=0;f&&(h=((e,t)=>setTimeout(console.warn,1e3,`💀🔒 - proxy.${e}() in proxy.${t}()`))(u,Ce));const d=Be++,y=[];He.has(p.at(-1)||y)&&He.delete(y=p.pop());const g=r(c?p.map(c):p);let w=new t(new n(2*Ne));return i([e,2,u,d,w,g,s],{transfer:y}),l(w,0).value.then((()=>{f&&clearTimeout(h);const r=w[1];if(!r)return;const s=Me*r;return w=new t(new n(s+s%Ne)),i([e,1,d,w]),l(w,0).value.then((()=>{const e=new Uint16Array(w.buffer),t=a?e.subarray(0,r):e.slice(0,r);return o(We.decode(t))}))}))},qe=(e,t)=>new Proxy(t,{get:(t,n)=>{let r;return"then"!==n&&(r=t.get(n),r||(r=Ue(e,n),t.set(n,r))),r},set:(e,t,n)=>"then"!==t&&!!e.set(t,n)}),{wait:Je,waitAsync:ze}=pe;var Ge=({parse:e,stringify:t,transform:n,interrupt:r}=JSON)=>{const s=((e,t)=>async(n,r,[s,o,a,i,c])=>{c&&(Ce=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&&(Ce=""),a[0]=1,Fe(a,0)}})(t,n),o=he(),a=new Map,i=new Map;let c="",l=Je;if(Je&&r){const{handler:e,timeout:t=42}=r;l=(n,r,s)=>{for(;"timed-out"===(s=Je(n,r,0,t));)e();return s}}return Ae("message",(t=>{if(_e(t,c)){const[r,u,...p]=t.data;switch(u){case 0:{const t=!!Je;c=r,o.resolve({polyfill:$e,sync:t,transfer:De,proxy:qe([c,Se,Oe,Pe,t,e,$e,Re,n,t?(...e)=>({value:{then:t=>t(l(...e))}}):ze],a)});break}case 2:a.size?Le(s,i,a,p):setTimeout(Le,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<s;t++)e[t]=r.charCodeAt(t);Fe(n,0)})(i,p)}}})),o.promise},Ye=Object.fromEntries([f,"bigint","boolean",h,d,y,g,"string",w,m].map(((e,t)=>[e,t])));const Ke="destruct",{[A]:Xe}=Reflect,Ve=new Map(Xe(Symbol).filter((e=>typeof Symbol[e]===w)).map((e=>[Symbol[e],e]))),Ze=e=>Ve.get(e)||`.${Symbol.keyFor(e)||""}`,Qe="3753967f-73c7-40f1-9973-3c5e60d13535",et="M"+Qe,tt="W"+Qe,{[_]:nt}=Reflect;const rt={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}},st=new WeakMap,ot=e=>{const t=e||console,n={buffered:it,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 st.set(t,n),t}}},at=new TextDecoder,it=(e,t=10)=>{const n=[];return r=>{if(r instanceof Uint8Array)for(const s of r)s===t?e(at.decode(new Uint8Array(n.splice(0)))):n.push(s);else e(r)}},ct=(e,...t)=>rt[typeof e](e,...t),{isArray:lt}=Array,{assign:ut,create:pt,defineProperties:ft,defineProperty:ht,entries:dt}=Object,{all:yt,resolve:gt}=new Proxy(Promise,{get:(e,t)=>e[t].bind(e)}),wt=(e,t=location.href)=>new URL(e,t.replace(/^blob:/,"")).href,mt=(e,t,n,r=!1,s=CustomEvent)=>{e.dispatchEvent(new s(`${t}:${n}`,{bubbles:!0,detail:{worker:r}}))},_t=e=>Function(`\'use strict\';return (${e})`)(),bt=e=>e.replace(/^(?:\\n|\\r\\n)/,""),Et=Symbol.for("polyscript.js_modules"),vt=new Map;ht(globalThis,Et,{value:vt}),new Proxy(vt,{get:(e,t)=>e.get(t),has:(e,t)=>e.has(t),ownKeys:e=>[...e.keys()]});const Tt=(e,t)=>!t.startsWith("_"),xt=(e,t)=>new Proxy(e,{has:Tt,get:(e,n)=>e[t][n]}),kt=(e,t)=>import(e).then((e=>{vt.set(t,{...e})})),St=e=>new Promise(((t,n)=>{document.querySelector(`link[rel="stylesheet"][href="${e}"]`)?t():document.head.append(ut(document.createElement("link"),{rel:"stylesheet",href:e,onload:t,onerror:n}))})),Ot=e=>/\\.css$/i.test(new URL(e).pathname),At=(e,t)=>e.has(t),Rt=e=>[...e.keys()];var jt=(e,t,n,r)=>{const s=globalThis[Et];if(n)for(let[e,t]of dt(n)){let n=s.get(t);n&&!lt(n)||(s.set(t,n||(n=[])),n.push(e))}return((e,t,n,r)=>new Proxy(e,{has:At,ownKeys:Rt,get:(e,s)=>{let o=e.get(s);if(lt(o)){let a=o;o=null;for(let e of a)e=wt(e,r),Ot(e)?n.importCSS(e):(n.importJS(e,s),o=t[Et].get(s));e.set(s,o)}return o}}))(s,e,t,r)};const Pt=Object.getOwnPropertyDescriptors(Response.prototype),$t=e=>"function"==typeof e,It={get:(e,t)=>Pt.hasOwnProperty(t)?((e,t,{get:n,value:r})=>n||!$t(r)?e.then((e=>e[t])):(...n)=>e.then((e=>e[t](...n))))(e,t,Pt[t]):((e,t)=>$t(t)?t.bind(e):t)(e,e[t])};var Nt=(e,...t)=>new Proxy(fetch(e,...t),It);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 Mt=!globalThis.window,Ft=({FS:e,PATH:t,PATH_FS:n},r,s)=>{const o=n.resolve(r),a=t.dirname(o);return e.mkdirTree?e.mkdirTree(a):Ht(e,a),e.writeFile(o,new Uint8Array(s),{canOwn:!0})},Wt=e=>{const t=e.split("/");return t.pop(),t.join("/")},Ht=(e,t)=>{const n=[];for(const r of t.split("/"))"."!==r&&".."!==r&&(n.push(r),r&&e.mkdir(n.join("/")))},Dt=(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(/^\\/+/,"/")},Ct=e=>{const t=e.map((e=>e.trim().replace(/(^[/]*|[/]*$)/g,""))).filter((e=>""!==e&&"."!==e)).join("/");return e[0].startsWith("/")?`/${t}`:t},Lt=(e,t)=>Nt(wt(e,t)).arrayBuffer(),Bt=(e,t,n,r)=>yt((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(lt(r))return r.map((n=>({url:Ct([e,n]),path:Ct([t,n])})));const s=n||e.slice(1+e.lastIndexOf("/"));return[{url:e,path:Ct([t,s])}]}))})(n).map((({url:n,path:s})=>Lt(n,r).then((n=>e.writeFile(t,s,n)))))),Ut=(e,t)=>t.endsWith("/")?`${t}${e.split("/").pop()}`:t,qt=(e,t)=>e.replace(/\\{.+?\\}/g,(e=>{if(!t.has(e))throw new SyntaxError(`Invalid template: ${e}`);return t.get(e)})),Jt=(e,t,n,r)=>yt((e=>{const t=new Map,n=new Set,r=[];for(const[s,o]of dt(e))if(/^\\{.+\\}$/.test(s)){if(t.has(s))throw new SyntaxError(`Duplicated template: ${s}`);t.set(s,qt(o,t))}else{const e=qt(s,t),a=Ut(e,qt(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})=>Lt(n,r).then((r=>e.writeFile(t,s,r,n)))))),zt=({main:e,worker:t},n)=>{const r=[];if(t&&Mt)for(let[e,s]of dt(t))e=wt(e,n),r.push(kt(e,s));if(e&&!Mt)for(let[t,s]of dt(e))t=wt(t,n),Ot(t)?St(t):r.push(kt(t,s));return yt(r)},{assign:Gt}=Object,Yt="entries",Kt="readonly",Xt="readwrite",Vt={durability:"default",prefix:"IDBMap"},Zt=({target:{result:e}})=>e;class Qt extends EventTarget{#e;#t;#n;async#r(e,t){const n=(await this.#e).transaction(Yt,t,this.#t);return new Promise(((t,r)=>Gt(e(n.objectStore(Yt)),{onsuccess:t,onerror:r})))}constructor(e,{durability:t=Vt.durability,prefix:n=Vt.prefix}=Vt){super(),this.#n=n,this.#t={durability:t},this.#e=new Promise(((t,n)=>{Gt(indexedDB.open(`${this.#n}/${e}`),{onupgradeneeded({target:{result:e,transaction:n}}){e.objectStoreNames.length||e.createObjectStore(Yt),n.oncomplete=()=>t(e)},onsuccess(e){t(Zt(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?Gt(new Event(t),{message:n}):e)}async close(){(await this.#e).close()}get size(){return this.#r((e=>e.count()),Kt).then(Zt)}async clear(){await this.#r((e=>e.clear()),Xt)}async delete(e){await this.#r((t=>t.delete(e)),Xt)}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)),Kt).then(Zt)}async has(e){return void 0!==await this.#r((t=>t.getKey(e)),Kt).then(Zt)}async keys(){return await this.#r((e=>e.getAllKeys()),Kt).then(Zt)}async set(e,t){return await this.#r((n=>n.put(t,e)),Xt),this}async values(){const e=await this.keys();return Promise.all(e.map((e=>this.get(e))))}get[Symbol.toStringTag](){return this.#n}}class en extends Map{#s;#o;constructor(...e){super(),this.#s=new Qt(...e),this.#o=this.#s.entries().then((e=>{for(const[t,n]of e)super.set(t,n)}))}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 tn=new WeakMap,nn=(e,t,n)=>{"polyscript"===t&&(n.lazy_py_modules=async(...t)=>(await tn.get(e)(t),t.map((t=>e.pyimport(t)))),n.storage=async e=>{const t=new en(e);return await t.sync(),t},n.JSON=p),e.registerJsModule(t,n)},rn=(e,t)=>{if(e.endsWith("/*")){if(/\\.(zip|whl|tgz|tar(?:\\.gz)?)$/.test(t))return RegExp.$1;throw new Error(`Unsupported archive ${t}`)}return""},sn=(e,t,...n)=>{try{return e.runPython(ct(t),...n)}catch(t){st.get(e).stderr(t)}},on=async(e,t,...n)=>{try{return await e.runPythonAsync(ct(t),...n)}catch(t){st.get(e).stderr(t)}},an=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){st.get(e).stderr(t)}};var cn=(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 # WARNING: mpy_version fails miserably with 1.22.0-380\\n package = "{}/package/{}/{}/{}.json".format(index, "py", 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 ln=async e=>(await import("./toml-DiUM0_qs.js")).parse(e),un=(e,t)=>{try{e.mkdir(t)}catch(e){}};var pn={type:"micropython",module:(e="1.24.0-preview-114")=>`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}=ot({stderr:it(console.error),stdout:it(console.log)});n=n.replace(/\\.m?js$/,".wasm");const i=await a(e({linebuffer:!1,stderr:s,stdout:o,url:n})),c=fn.bind(this,i,r);return tn.set(i,c),t.files&&await Jt(this,i,t.files,r),t.fetch&&await Bt(this,i,t.fetch,r),t.js_modules&&await zt(t.js_modules,r),this.writeFile(i,"./mip.py",cn),t.packages&&await c(t.packages),i},registerJSModule:nn,run:sn,runAsync:on,runEvent:an,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=rn(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-gl8b5xR3.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)un(s,i);else{un(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 Ft(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 Ft(i,t,n)}};async function fn(e,t,n){let r;for(const s of n)if(s.endsWith(".whl")){const n=wt(s,t),r=await Nt(n).arrayBuffer();await this.writeFile(e,"./*",r,n)}else r||(r=e.pyimport("mip")),r.install(s)}const hn={dict_converter:Object.fromEntries};let dn=!1;const yn=e=>(...t)=>{try{return dn=!0,e(...t)}finally{dn=!1}};let gn=!1;const wn=()=>{if(gn)return;gn=!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){dn=!1;let o=e.get(s)?.deref();if(!o)try{o=F(s.copy(),t),e.set(s,new WeakRef(o))}catch(e){console.error(e)}o&&(n[r]=o),dn=!0}}},{call:r}=Function,s=r.bind(r,r.apply);Object.defineProperties(Function.prototype,{apply:{value(e,t){return dn&&n(t),s(this,e,t)}},call:{value(e,...t){return dn&&n(t),s(this,e,t)}}})};var mn={type:"pyodide",module:(e="0.26.1")=>`https://cdn.jsdelivr.net/pyodide/v${e}/full/pyodide.mjs`,async engine({loadPyodide:e},t,n,r){Mt||"auto"!==t.experimental_create_proxy||wn();const{stderr:s,stdout:o,get:a}=ot(),i=n.slice(0,n.lastIndexOf("/")),c=await a(e({stderr:s,stdout:o,indexURL:i})),l=_n.bind(c);return tn.set(c,l),t.files&&await Jt(this,c,t.files,r),t.fetch&&await Bt(this,c,t.fetch,r),t.js_modules&&await zt(t.js_modules,r),t.packages&&await l(t.packages),c},registerJSModule:nn,run:yn(sn),runAsync:yn(on),runEvent:yn(an),transform:({ffi:{PyProxy:e}},t)=>t instanceof e?t.toJs(hn):t,writeFile:(e,t,n,r)=>{const s=rn(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 Ft({FS:o,PATH:a,PATH_FS:i},t,n)}};async function _n(e){await this.loadPackage("micropip");const t=this.pyimport("micropip");await t.install(e,{keep_going:!0}),t.destroy()}const bn="ruby-wasm-wasi",En=bn.replace(/\\W+/g,"_");var vn={type:bn,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 Nt(n).arrayBuffer(),o=await WebAssembly.compile(s),{vm:a}=await e(o);return t.files&&await Jt(this,a,t.files,r),t.fetch&&await Bt(this,a,t.fetch,r),t.js_modules&&await zt(t.js_modules,r),a},registerJSModule(e,t,n){t=t.replace(/\\W+/g,"__");const r=`__module_${En}_${t}`;globalThis[r]=n,this.run(e,`require "js";$${t}=JS.global[:${r}]`),delete globalThis[r]},run:(e,t,...n)=>e.eval(ct(t),...n),runAsync:(e,t,...n)=>e.evalAsync(ct(t),...n),async runEvent(e,t,n){if(/^xworker\\.(on\\w+)$/.test(t)){const{$1:t}=RegExp,r=`__module_${En}_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 ${bn}`)}};var Tn={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}=ot(),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 Jt(this,c,n.files,s),n.fetch&&await Bt(this,c,n.fetch,s),n.js_modules&&await zt(n.js_modules,s),c},registerJSModule:(e,t,n)=>{e.global.set(t,n)},run:(e,t,...n)=>{try{return e.doStringSync(ct(t),...n)}catch(t){st.get(e).stderr(t)}},runAsync:async(e,t,...n)=>{try{return await e.doString(ct(t),...n)}catch(t){st.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){st.get(e).stderr(t)}},transform:(e,t)=>t,writeFile:({cmodule:{module:{FS:e}}},t,n)=>((e,t,n)=>(Ht(e,Wt(t)),t=Dt(e,t),e.writeFile(t,new Uint8Array(n),{canOwn:!0})))(e,t,n)};const xn=new WeakMap,kn=async(e,t)=>{const{shelter:n,destroy:r,io:s}=xn.get(e),{output:o,result:a}=await n.captureR(ct(t));for(const{type:e,data:t}of o)s[e](t);return F(a,r,{token:!1})};var Sn={type:"webr",experimental:!0,module:(e="0.4.0")=>`https://cdn.jsdelivr.net/npm/webr@${e}/dist/webr.mjs`,async engine(e,t,n,r){const{get:s}=ot(),o=new e.WebR;await s(o.init().then((()=>o)));const a=await new o.Shelter;return xn.set(o,{module:e,shelter:a,destroy:a.destroy.bind(a),io:st.get(o)}),t.files&&await Jt(this,o,t.files,r),t.fetch&&await Bt(this,o,t.fetch,r),t.js_modules&&await zt(t.js_modules,r),o},registerJSModule(e,t){console.warn(`Experimental interpreter: module ${t} is not supported (yet)`)},run:kn,runAsync:kn,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 On=new Map,An=new Map,Rn=new Proxy(new Map,{get(e,t){if(!e.has(t)){const[n,...r]=t.split("@"),s=On.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=>(An.set(t,e),s(r,e,n,o))))}}),jn=e=>{for(const t of[].concat(e.type))On.set(t,e)};for(const e of[pn,mn,vn,Tn,Sn])jn(e);const{parse:Pn}=JSON,$n=e=>{try{return Pn(e)}catch(t){return ln(e)}},In=(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,[wt(e),n]})(t,n);"json"===s?r=Nt(e).json():"toml"===s?r=Nt(e).text().then(ln):"string"===s?r=$n(t):"object"===s&&t?r=t:"txt"===s&&"string"==typeof r&&(r=$n(r)),t=e}return gt(r).then((n=>Rn[e](n,t)))},Nn="BeforeRun",Mn="AfterRun",Fn=[`code${Nn}`,`code${Nn}Async`,`code${Mn}`,`code${Mn}Async`],Wn=["onWorker","onReady",`on${Nn}`,`on${Nn}Async`,`on${Mn}`,`on${Mn}Async`];function Hn(e,t){const{run:n,runAsync:r}=On.get(this.type);return{...e,run:n.bind(this,t),runAsync:r.bind(this,t)}}const Dn=(e,t,n,r,s,o)=>{if(s||o){const a=Hn.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,Bn;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:qn,stringify:Jn}=p,{proxy:zn,sync:Gn,polyfill:Yn,window:Kn,isWindowProxy:Xn}=await(async e=>{const t=await Ge(e),n=e?.transform||(e=>e),{[et]:r}=t.proxy,s=new Map,o=(e,t)=>{let n=s.get(e)?.deref();return n||s.set(e,new WeakRef(n=t(e))),n},a=([e,t])=>{switch(e){case Ye[g]:return null==t?globalThis:typeof t===y?o(t,p.object):t;case Ye[f]:return typeof t===y?o(t,p.array):t;case Ye[h]:return typeof t===y?o(t,p.function):te(parseInt(t));case Ye[w]: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}},i=e=>{let[t,r]=m(e);switch(t){case g:if(r==globalThis||null==r)r=null;else if(typeof r===g&&!(r instanceof ue)){r=n(r);for(const e in r)r[e]=i(r[e])}return[Ye[g],r];case f:return[Ye[f],typeof r===y?r:n(r).map(i)];case h:return[Ye[h],typeof r===h?String(ne(n(r))):r];case w:return[Ye[w],Ze(e)];default:return[Ye[t],r]}},c=(...e)=>a(r(...e)),l={[E]:(e,t,n)=>c(E,e,i(t),i(n)),[v]:(e,t)=>c(v,e,i(t)),[T]:(e,t)=>c(T,e,i(t)),[k]:e=>c(k,e),[x]:(e,t)=>{const n=c(x,e,i(t));if(n){const{get:e,set:t,value:r}=n;e&&(n.get=a(e)),t&&(n.set=a(t)),r&&(n.value=a(r))}return n},[S]:(e,t)=>c(S,e,i(t)),[O]:e=>c(O,e),[A]:e=>c(A,e).map(a),[R]:e=>c(R,e),[j]:(e,t,n)=>c(j,e,i(t),i(n)),[P]:(e,t)=>c(P,e,i(t)),[Ke](e){s.delete(e),r(Ke,e)}},u={object:l,array:l,function:{...l,[_]:(e,...t)=>c(_,e,...t.map(i)),[b]:(e,...t)=>c(b,e,...t.map(i))}},{proxy:p,isProxy:d,pair:m}=V(u),$=p.object(null);return t.proxy[tt]=(e,t,...n)=>{const r=parseInt(t);switch(e){case _:{const[e,t]=n;return i(nt(te(r),a(e),t.map(a)))}case Ke:(e=>{const[t,n]=typeof e===y?[ee,Q]:[Q,ee],r=t.has(e);r&&(n.delete(t.get(e)),t.delete(e))})(r)}},{...t,window:$,isWindowProxy:d}})({parse:qn,stringify:Jn,transform:e=>Bn?Bn(e):e}),Vn={polyfill:Yn,sync:zn,window:Gn?Kn:null,isWindowProxy:Xn,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:u,async:p}=e,f=((e,t="")=>`${e}@${t}`.replace(/@$/,""))(i,l),h=await In(f,t,n,u),{js_modules:d}=An.get(f),y=d?.main,g=pt(On.get(i)),w=((e,t,n,r)=>({type:t,config:n,interpreter:r,io:st.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||{},h);let m="run";if(p&&(m+="Async"),s){let e,t,n="",r="";for(const e of Fn){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,bt(t),...o);return r&&s(e,r,...o),a}:async(e,t,...o)=>{n&&await s(e,n,...o);const a=await s(e,bt(t),...o);return r&&await s(e,r,...o),a}})(g,m,n,r);for(const n of Wn.slice(2)){const r=s[n];if(r){const s=n.endsWith("Async");if(s&&p||!s&&!p){const s=_t(r);n.startsWith("onBefore")?e=s:t=s}}}Dn(g,w,Vn,p,e,t)}let _,b,E,v=null,T="";Gn&&(({CustomEvent:_,document:b}=Kn),v=o&&b.getElementById(o)||null,E=e=>mt(v,c||i,e,!0,_));const x=jt(Kn,zn,y,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}`,xt(r,e));t.registerJSModule(n,s,r)})(i,g,h,x),g.registerJSModule(h,"polyscript",{xworker:Vn,currentScript:v,config:w.config,js_modules:x,get target(){return!T&&v&&("SCRIPT"===a?v.after(ut(b.createElement(`script-${c||i}`),{id:T=`${o}-target`})):(T=o,v.replaceChildren(),v.style.display="block")),T}}),Ln=g.runEvent.bind(g,h),Bn=g.transform.bind(g,h),v&&E("ready"),s?.onReady&&_t(s?.onReady).call(g,Hn.call(g,w,h),Vn),await g[m](h,r),["micropython","pyodide"].includes(g.type)){const e="polyscript",t=`__${e}_workers__`,n="__export__";h.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&&h.runPython([`from ${e} import xworker as ${t}`,...r.map((e=>`${t}.sync.${e} = ${e}`)),`del ${t}`].join("\\n"))}return v&&E("done"),postMessage("polyscript:done"),h}catch(e){postMessage(e)}})(),Un("error"),Un("message"),Un("messageerror")}));\n'.replace(Ce,We)],{type:"application/javascript"})),...e))({serviceWorker:o}),{postMessage:l}=i,c=this instanceof St,p=Ve(i.proxy,{importJS:gn,importCSS:_n}),d=Promise.withResolvers();let f=a(n).text().then((e=>{const n=c?this.toJSON():void 0;l.call(i,{options:t,config:r,code:e,hooks:n})})).then((()=>{f={then:e=>e()}}));return Ze(i,{sync:{value:p},ready:{value:d.promise},postMessage:{value:(e,...n)=>f.then((()=>l.call(i,e,...n)))},onerror:{writable:!0,configurable:!0,value:console.error}}),i.addEventListener("message",(e=>{const{data:n}=e,t=n instanceof Error;(t||"polyscript:done"===n)&&(e.stopImmediatePropagation(),t?(d.reject(n),i.onerror(Xe(e,{type:{value:"error"},error:{value:n}}))):d.resolve(i))})),c&&this.onWorker?.(this.interpreter,i),i};const jt="Invalid content";var At=e=>{const{src:n,worker:t}=e.attributes;if(t){let{value:r}=t;if(r)throw new SyntaxError("Invalid worker attribute");if(r=n?.value,!r){if(n)throw new SyntaxError("Invalid worker attribute");if(e.childElementCount){const{innerHTML:n,localName:t,type:s}=e,o=s||t.replace(/-script$/,"");r=Ye(n),console.warn(`Deprecated: use <script type="${o}"> for an always safe content parsing:\n`,r)}else r=e.textContent;return URL.createObjectURL(new Blob([Ge(r)],{type:"text/plain"}))}return r}if(n&&e.textContent.replace(/\/\*[\s\S]*?\*\//g,"").replace(/^\s*(?:\/\/|#).*/gm,"").trim())throw new SyntaxError(jt)};const Nt=(e,n)=>{const t=(e=>{let n=e;for(;n.parentNode;)n=n.parentNode;return n})(e);return t.getElementById(n)||((e,n=document)=>n.querySelector(e))(n,t)},Ct=new WeakMap,Wt={get(){let e=Ct.get(this);return e||(e=document.createElement(`${this.type}-script`),Ct.set(this,e),Ut(this)),e},set(e){"string"==typeof e?Ct.set(this,Nt(this,e)):(Ct.set(this,e),Ut(this))}},It=new WeakMap,Lt=new Map,$t=(e,n)=>{const t=e?.value;return t?n+t:""},Ht=(e,n,t,r,s,o,a=e)=>{if(!Lt.has(n)){const i={interpreter:bt(t,s,o),queue:tn(),XWorker:xt(e,r)};Lt.set(n,i),Lt.has(e)||Lt.set(e,i),Lt.has(a)||Lt.set(a,i)}return Lt.get(n)},Ut=async e=>{if(It.has(e)){const{target:n}=e;n&&(e.closest("head")?document.body.append(n):e.after(n))}else{const{attributes:{async:n,config:t,env:r,name:s,target:o,version:l},src:p,type:d}=e,f=l?.value,u=vt(d,f);let m=$t(t,"|");const h=$t(r,"")||`${u}${m}`;m=m.slice(1);const y=At(e);if(y){const t=new(xt(d,f))(y,{...on(e,d),async:!!n,config:m});It.set(Qe(e,"xworker",{value:t}),{xworker:t});const r=s?.value;return void(r&&i[r].resolve(t.ready))}const g=$t(o,""),_=Ht(d,h,u,f,m);It.set(Qe(e,"target",Wt),_),g&&Ct.set(e,Nt(e,g));const w=p?a(p).text():e.textContent;_.queue=_.queue.then((()=>(async(e,n,t,r)=>{const{type:s}=e,o=dt.get(s);o.experimental&&console.warn(`The ${s} interpreter is experimental`);const[a,i]=await nn([It.get(e).interpreter,n]);try{Qe(document,"currentScript",{configurable:!0,get:()=>e}),yn(s,o,a,un),o.registerJSModule(a,"polyscript",{XWorker:t,currentScript:e,js_modules:un,workers:c}),an(e,s,"ready");const n=o[r?"runAsync":"run"](a,i),l=an.bind(null,e,s,"done");return r?n.then(l):l(),n}finally{delete document.currentScript}})(e,w,_.XWorker,!!n)))}},zt=new Proxy(Xe(null),{get:(e,n)=>new Promise(queueMicrotask).then((()=>Ft(n)))}),Ft=async e=>{if(Lt.has(e)){const{interpreter:n,queue:t}=Lt.get(e);return(await nn([n,t]))[0]}const n=Lt.size?`Available interpreters are: ${[...Lt.keys()].map((e=>`"${e}"`)).join(", ")}.`:"There are no interpreters in this page.";throw new Error(`The interpreter "${e}" was not found. ${n}`)},Bt=async e=>{const{type:n,currentTarget:r}=e;if(mt.length)for(let{name:s,value:o,ownerElement:a}of t(`./@*[${mt.map((e=>`name()="${e}${n}"`)).join(" or ")}]`,r)){s=s.slice(0,-(n.length+1));const t=await Ft(a.getAttribute(`${s}-env`)||s);dt.get(s).runEvent(t,o,e)}},qt=e=>{if(mt.length)for(let{name:n,ownerElement:r}of t(`.//@*[${mt.map((e=>`starts-with(name(),"${e}")`)).join(" or ")}]`,e)){const e=n.lastIndexOf("-"),t=n.slice(e+1);"env"!==t&&(r.addEventListener(t,Bt),"disabled"in r&&!r.disabled&&(r.disabled=!0,zt[n.slice(0,e)].then((()=>{r.disabled=!1}))))}},Jt=xt(),Gt=[],Yt=new Map,Kt=new Map,Vt=new Map,Xt=async e=>{for(const n of Gt)if(e.matches(n)){const t=Kt.get(n),r=Zt.get(t),{resolve:s}=Vt.get(t),{options:o,known:a}=r;if(a.has(e))return;a.add(e);for(const[n,t]of Yt)e.matches(n)&&await t(e);const{interpreter:l,configURL:p,config:d,version:f,env:u,onerror:m,hooks:h}=o;let y;try{const n=At(e);if(n){const r=Jt.call(new St(null,h),n,{...on(e,t),version:f,configURL:p,type:l,custom:t,config:e.getAttribute("config")||d||{},async:e.hasAttribute("async")});Qe(e,"xworker",{value:r}),s({type:t,xworker:r});const o=e.getAttribute("name");return void(o&&i[o].resolve(r.ready))}}catch(e){y=e}const g=vt(l,f),_=u||`${g}${d?`|${d}`:""}`,{interpreter:w,XWorker:b}=Ht(t,_,g,f,d,p,l),v=await w,E=Xe(dt.get(l)),M=new St(v,h),O=function(...e){return b.apply(M,e)},k={...ln(E,t,structuredClone(ft.get(g)),v),XWorker:O};yn(l,E,v,un),E.registerJSModule(v,"polyscript",{XWorker:O,config:k.config,currentScript:t.startsWith("_")?null:e,js_modules:un,workers:c});for(const n of["Run","RunAsync"]){let t,r,s="",o="";for(const e of kt){const t=h?.main?.[e];t&&e.endsWith(n)&&(e.startsWith("codeBefore")?s=Ge(t()):o=Ge(t()))}(s||o)&&pn(E,`r${n.slice(1)}`,s,o);for(let e=2;e<Pt.length;e++){const s=Pt[e],o=h?.main?.[s];o&&s.endsWith(n)&&(s.startsWith("onBefore")?t=o:r=o)}Rt(E,k,e,n.endsWith("Async"),t,r)}r.queue=r.queue.then((()=>(s(k),y&&m?.(y,e),h?.main?.onReady?.(k,e))))}},Zt=new Map;let Qt=0;const er=e=>(Vt.has(e)||Vt.set(e,Promise.withResolvers()),Vt.get(e).promise),[{customObserver:nr,define:tr,whenDefined:rr,env:sr,Hook:or,XWorker:ar},ir]=e("polyscript",{customObserver:Yt,define:(e,t)=>{let r=null==e;if(r)e="_ps"+Qt++;else if(dt.has(e)||Zt.has(e))throw new Error(`<script type="${e}"> already registered`);if(!dt.has(t?.interpreter))throw new Error("Unspecified interpreter");dt.set(e,dt.get(t.interpreter));const s=[`script[type="${e}"]`];if(er(e),r){const{hooks:n}=t,r=n?.main?.onReady;t={...t,hooks:{...n,main:{...n?.main,onReady(n,t){Gt.splice(Gt.indexOf(e),1),dt.delete(e),Zt.delete(e),Vt.delete(e),t.remove(),r?.(n)}}}},document.head.append(Ve(document.createElement("script"),{type:e}))}else s.push(`${e}-script`),mt.push(`${e}-`);for(const n of s)Kt.set(n,e);Gt.push(...s),Zt.set(e,{options:Ve({env:e},t),known:new WeakSet,queue:Promise.resolve()}),r||qt(document),n(s.join(",")).forEach(Xt)},whenDefined:er,env:zt,Hook:St,XWorker:Jt});if(!ir){const e=new MutationObserver((e=>{const n=ut.join(",");for(const{type:r,target:s,attributeName:o,addedNodes:a}of e)if("attributes"!==r)for(const e of a)1===e.nodeType&&(qt(e),n&&e.matches(n)?Ut(e):t(n,e,!0));else{const e=o.lastIndexOf("-")+1;if(e){const n=o.slice(0,e);for(const t of mt)if(n===t){const n=o.slice(e);if("env"!==n){const e=s.hasAttribute(o)?"add":"remove";s[`${e}EventListener`](n,Bt)}break}}}})),t=(e,t,r)=>{e&&n(e,t).forEach(Ut),(e=Gt.join(","))&&(r&&Xt(t),n(e,t).forEach(Xt))},r=n=>(e.observe(n,{childList:!0,subtree:!0,attributes:!0}),n),{attachShadow:s}=Element.prototype;Ve(Element.prototype,{attachShadow(e){return r(s.call(this,e))}}),queueMicrotask((()=>{qt(r(document)),t(ut.join(","),document,!1)}))}var lr=new Map([["py","pyodide"],["mpy","micropython"]]);const cr=[];for(const[e]of lr){const n=[`script[type="${e}"]`,`${e}-script`];for(const t of document.querySelectorAll(n.join(","))){const{promise:n,resolve:r}=Promise.withResolvers();cr.push(n),t.addEventListener(`${e}:done`,r,{once:!0})}}Promise.all(cr).then((()=>{dispatchEvent(new Event("py:all-done"))}));var pr={"deprecations-manager":()=>import("./deprecations-manager-C1bCFFAJ.js"),error:()=>import("./error-BE-P8gi6.js"),"py-editor":()=>import("./py-editor-CUd-CQKV.js"),"py-terminal":()=>import("./py-terminal-CgSL5otC.js")};const dr={GENERIC:"PY0000",CONFLICTING_CODE:"PY0409",BAD_CONFIG:"PY1000",MICROPIP_INSTALL_ERROR:"PY1001",BAD_PLUGIN_FILE_EXTENSION:"PY2000",NO_DEFAULT_EXPORT:"PY2001",TOP_LEVEL_AWAIT:"PY9000",FETCH_ERROR:"PY0001",FETCH_NAME_ERROR:"PY0002",FETCH_UNAUTHORIZED_ERROR:"PY0401",FETCH_FORBIDDEN_ERROR:"PY0403",FETCH_NOT_FOUND_ERROR:"PY0404",FETCH_SERVER_ERROR:"PY0500",FETCH_UNAVAILABLE_ERROR:"PY0503"};class fr extends Error{constructor(e,n="",t="text"){super(`(${e}): ${n}`),this.errorCode=e,this.messageType=t,this.name="UserError"}}class ur extends fr{constructor(e,n){super(e,n),this.name="FetchError"}}const mr=e=>e.text();async function hr(e,n){let t;try{t=await fetch(e,n)}catch(n){const t=n;let r;throw r=e.startsWith("http")?`Fetching from URL ${e} failed with error '${t.message}'. Are your filename and path correct?`:'Polyscript: Access to local files\n (using [[fetch]] configurations in <py-config>)\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 ',new ur(dr.FETCH_ERROR,r)}if(!t.ok){const n=`Fetching from URL ${e} failed with error ${t.status} (${t.statusText}). Are your filename and path correct?`;switch(t.status){case 404:throw new ur(dr.FETCH_NOT_FOUND_ERROR,n);case 401:throw new ur(dr.FETCH_UNAUTHORIZED_ERROR,n);case 403:throw new ur(dr.FETCH_FORBIDDEN_ERROR,n);case 500:throw new ur(dr.FETCH_SERVER_ERROR,n);case 503:throw new ur(dr.FETCH_UNAVAILABLE_ERROR,n);default:throw new ur(dr.FETCH_ERROR,n)}}return t}const{BAD_CONFIG:yr,CONFLICTING_CODE:gr}=dr,_r=async(e,n)=>{let t=e?.trim(),r="",s=!1,o=/^{/.test(t)&&/}$/.test(t);if(!o&&/\.(\w+)(?:\?\S*)?$/.test(t)){const e=RegExp.$1;"json"===e&&"toml"!==n?o=!0:"toml"===e&&"json"!==n?s=!0:((e,n="")=>{let t=`(${yr}): Invalid URL: ${e}`;throw n&&(t+=`\nexpected ${n} content`),new Error(t)})(t,n),r=t,t=(await hr(r).then(mr)).trim()}return{json:o,toml:s||!o&&!!t,text:t,url:r}},wr=e=>new Error(`(${gr}): ${e}`),br=(e,n=location.href)=>new URL(e,n).href,vr=(e,n,{message:t})=>{let r=`(${yr}): Invalid ${e}`;return n&&(r+=` @ ${n}`),new SyntaxError(`${r}\n${t}`)},Er=new Map;for(const[e]of lr){let t,r,s,o,a,i,l,c=n(`${e}-config`),p=n([`script[type="${e}"][config]:not([worker])`,`${e}-script[config]:not([worker])`].join(","));if(c.length>1?s=wr(`Too many ${e}-config`):c.length&&p.length?s=wr(`Ambiguous ${e}-config VS config attribute`):c.length?([l]=c,a=l.getAttribute("src")||l.textContent,i=l.getAttribute("type")):p.length&&([l,...p]=p,a=l.getAttribute("config"),p.some((e=>e.getAttribute("config")!==a))&&(s=wr("Unable to use different configs on main"))),!s&&a)try{const{json:e,toml:n,text:t,url:l}=await _r(a,i);if(l&&(o=br(l)),a=t,e||"json"===i)try{r=JSON.parse(t)}catch(e){s=vr("JSON",l,e)}else if(n||"toml"===i)try{const{parse:e}=await import("./toml-CvAfdf9_.js");r=e(t)}catch(e){s=vr("TOML",l,e)}}catch(e){s=e}const d=[];for(const[e,n]of Object.entries(pr))s?"error"===e&&n().then((({notify:e})=>e(s.message))):r?.plugins?.includes(`!${e}`)||d.push(n().then((({default:e})=>e)));t=Promise.all(d),Er.set(e,{config:r,configURL:o,plugins:t,error:s})}var Mr={is_pyterminal:()=>!1,sleep:e=>new Promise((n=>setTimeout(n,1e3*e)))};const Or=e=>{Qe(document,"currentScript",{configurable:!0,get:()=>e})},kr=()=>{delete document.currentScript};var Pr=async(e,n,t,r)=>{const s=r.endsWith("Async");(r.startsWith("onBefore")?Or:kr)(t);for(const o of e(r))s?await o(n,t):o(n,t)};const Tr=()=>!0,Rr=e=>{throw new TypeError(e)},Sr=(e,n)=>{const t=[];if(e)for(const n of e.split(/\s*\|\s*/))"object"===n?t.push((e=>null!==e&&typeof e===n)):"null"===n?t.push((e=>null===e)):t.push((e=>typeof e===n));if(n)for(const e of[].concat(n))t.push((n=>n instanceof e));switch(t.length){case 0:return Tr;case 1:return t[0];default:return e=>t.some((n=>n(e)))}},Dr=(e,n,t,r=Rr)=>s=>{const o=[`Invalid ${typeof s} ${t}: expected `];e&&(o.push(e),n&&o.push(" or ")),n&&(o.push("an instanceof "),o.push([].concat(n).map((({name:e})=>e)).join(" | "))),r(o.join(""),s)},xr=(e=>n=>{const[t,r]=((e,n="value")=>{const t=e?.typeof,r=e?.instanceof;return[Sr(t,r),Dr(t,r,n,e?.onerror)]})(n);return class extends e{add(e){return t(e)?super.add(e):r(e)}}})(Set);const{entries:jr}=Object,Ar=["import os as _os","from pathlib import Path as _Path","_path = None"],Nr=new class extends Array{#a=!1;#i;#l;constructor(e,...n){super(),this.#l=e,this.#i=n}push(...e){return this.#a&&super.push(...e),this.#l.push(...e)}path(e){for(const n of this.#i)if(this.#a=e.startsWith(n))break}}(Ar,"-"),Cr=(e,n)=>{for(const[t,r]of jr(n))if(Nr.path(`${e}/${t}`),Nr.push(`_path = _Path("${e}/${t}")`),"string"==typeof r){const e=JSON.stringify(r);Nr.push(`_path.write_text(${e},encoding="utf-8")`)}else Nr.push(`if not _os.path.exists("${e}/${t}"):`),Nr.push(" _path.mkdir(parents=True, exist_ok=True)"),Cr(`${e}/${t}`,r)};Cr(".",{pyscript:{"__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 polyscript import lazy_py_modules as py_import\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_import,\n js_modules,\n sync,\n window,\n)\nfrom pyscript.storage import Storage, storage\nfrom pyscript.websocket import WebSocket\n\nif not RUNNING_IN_WORKER:\n from pyscript.workers import create_named_worker, workers\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',"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',"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\n from pyscript.web.elements import Element, ElementCollection\n\n if isinstance(selector, str):\n elements = document.querySelectorAll(selector)\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 elif isinstance(selector, Element):\n elements = [selector._dom_element]\n elif isinstance(selector, ElementCollection):\n elements = [el._dom_element for el in selector]\n else:\n if isinstance(selector, list):\n elements = selector\n else:\n elements = [selector]\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 very ugly hack to get micropython working because inspect.signature\n # doesn\'t exist, but we need to actually properly replace inspect.signature.\n # It may be actually better to not try any magic for now and raise the error\n def wrapper(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except TypeError as e:\n if "takes" in str(e) and "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',"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',"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',"flatted.py":"# https://www.npmjs.com/package/flatted\n\nimport json as _json\n\n\nclass _Known:\n def __init__(self):\n self.key = []\n self.value = []\n\n\nclass _String:\n def __init__(self, value):\n self.value = value\n\n\ndef _array_keys(value):\n keys = []\n i = 0\n for _ in value:\n keys.append(i)\n i += 1\n return keys\n\n\ndef _object_keys(value):\n keys = []\n for key in value:\n keys.append(key)\n return keys\n\n\ndef _is_array(value):\n return isinstance(value, list) or isinstance(value, tuple)\n\n\ndef _is_object(value):\n return isinstance(value, dict)\n\n\ndef _is_string(value):\n return isinstance(value, str)\n\n\ndef _index(known, input, value):\n input.append(value)\n index = str(len(input) - 1)\n known.key.append(value)\n known.value.append(index)\n return index\n\n\ndef _loop(keys, input, known, output):\n for key in keys:\n value = output[key]\n if isinstance(value, _String):\n _ref(key, input[int(value.value)], input, known, output)\n\n return output\n\n\ndef _ref(key, value, input, known, output):\n if _is_array(value) and not value in known:\n known.append(value)\n value = _loop(_array_keys(value), input, known, value)\n elif _is_object(value) and not value in known:\n known.append(value)\n value = _loop(_object_keys(value), input, known, value)\n\n output[key] = value\n\n\ndef _relate(known, input, value):\n if _is_string(value) or _is_array(value) or _is_object(value):\n try:\n return known.value[known.key.index(value)]\n except:\n return _index(known, input, value)\n\n return value\n\n\ndef _transform(known, input, value):\n if _is_array(value):\n output = []\n for val in value:\n output.append(_relate(known, input, val))\n return output\n\n if _is_object(value):\n obj = {}\n for key in value:\n obj[key] = _relate(known, input, value[key])\n return obj\n\n return value\n\n\ndef _wrap(value):\n if _is_string(value):\n return _String(value)\n\n if _is_array(value):\n i = 0\n for val in value:\n value[i] = _wrap(val)\n i += 1\n\n elif _is_object(value):\n for key in value:\n value[key] = _wrap(value[key])\n\n return value\n\n\ndef parse(value, *args, **kwargs):\n json = _json.loads(value, *args, **kwargs)\n wrapped = []\n for value in json:\n wrapped.append(_wrap(value))\n\n input = []\n for value in wrapped:\n if isinstance(value, _String):\n input.append(value.value)\n else:\n input.append(value)\n\n value = input[0]\n\n if _is_array(value):\n return _loop(_array_keys(value), input, [value], value)\n\n if _is_object(value):\n return _loop(_object_keys(value), input, [value], value)\n\n return value\n\n\ndef stringify(value, *args, **kwargs):\n known = _Known()\n input = []\n output = []\n i = int(_index(known, input, value))\n while i < len(input):\n output.append(_transform(known, input, input[i]))\n i += 1\n return _json.dumps(output, *args, **kwargs)\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 import js\n\n window = polyscript.xworker.window\n document = window.document\n js.document = document\n # this is the same as js_import on main and it lands modules on main\n js_import = window.Function(\n "return (...urls) => Promise.all(urls.map((url) => import(url)))"\n )()\n except:\n message = "Unable to use `window` or `document` -> https://docs.pyscript.net/latest/faq/#sharedarraybuffer"\n globalThis.console.warn(message)\n window = NotSupported("pyscript.window", message)\n document = NotSupported("pyscript.document", message)\n js_import = None\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, js_import\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',"storage.py":'from polyscript import storage as _storage\nfrom pyscript.flatted import parse as _parse\nfrom pyscript.flatted import stringify as _stringify\n\n\n# convert a Python value into an IndexedDB compatible entry\ndef _to_idb(value):\n if value is None:\n return _stringify(["null", 0])\n if isinstance(value, (bool, float, int, str, list, dict, tuple)):\n return _stringify(["generic", value])\n if isinstance(value, bytearray):\n return _stringify(["bytearray", [v for v in value]])\n if isinstance(value, memoryview):\n return _stringify(["memoryview", [v for v in value]])\n raise TypeError(f"Unexpected value: {value}")\n\n\n# convert an IndexedDB compatible entry into a Python value\ndef _from_idb(value):\n (\n kind,\n result,\n ) = _parse(value)\n if kind == "null":\n return None\n if kind == "generic":\n return result\n if kind == "bytearray":\n return bytearray(result)\n if kind == "memoryview":\n return memoryview(bytearray(result))\n return value\n\n\nclass Storage(dict):\n def __init__(self, store):\n super().__init__({k: _from_idb(v) for k, v in store.entries()})\n self.__store__ = store\n\n def __delitem__(self, attr):\n self.__store__.delete(attr)\n super().__delitem__(attr)\n\n def __setitem__(self, attr, value):\n self.__store__.set(attr, _to_idb(value))\n super().__setitem__(attr, value)\n\n def clear(self):\n self.__store__.clear()\n super().clear()\n\n async def sync(self):\n await self.__store__.sync()\n\n\nasync def storage(name="", storage_class=Storage):\n if not name:\n raise ValueError("The storage name must be defined")\n return storage_class(await _storage(f"@pyscript/{name}"))\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',web:{"__init__.py":"from pyscript import document\nfrom pyscript.web.elements import Element, ElementCollection\n\n\nclass DOM:\n def __init__(self):\n self.body = Element.from_dom_element(document.body)\n self.head = Element.from_dom_element(document.head)\n\n def __getitem__(self, selector):\n return self.find(selector)\n\n def find(self, selector):\n return ElementCollection(\n [\n Element.from_dom_element(dom_element)\n for dom_element in document.querySelectorAll(selector)\n ]\n )\n\n\ndom = DOM()\n","elements.py":'# noinspection PyPep8Naming\nimport inspect\nimport sys\n\ntry:\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\nfrom pyscript import document\n\n#: A flag to show if MicroPython is the current Python interpreter.\nis_micropython = "MicroPython" in sys.version\n\n\ndef getmembers_static(cls):\n """Cross-interpreter implementation of inspect.getmembers_static."""\n\n if is_micropython: # pragma: no cover\n return [(name, getattr(cls, name)) for name, _ in inspect.getmembers(cls)]\n\n return inspect.getmembers_static(cls)\n\n\nclass DOMProperty:\n """A descriptor representing a DOM property on an `Element` instance.\n\n This maps a property on an `Element` instance, to the property with the specified\n name on the element\'s underlying DOM element.\n """\n\n def __init__(self, name: str, allow_nones: bool = False):\n self.name = name\n self.allow_nones = allow_nones\n\n def __get__(self, obj, objtype=None):\n return getattr(obj._dom_element, self.name)\n\n def __set__(self, obj, value):\n if not self.allow_nones and value is None:\n return\n setattr(obj._dom_element, self.name, value)\n\n\nclass Element:\n tag = "div"\n\n # These are attribute that all elements have (this list is a subset of the official\n # one - we are just trying to capture the most used ones).\n accesskey = DOMProperty("accesskey")\n autofocus = DOMProperty("autofocus")\n autocapitalize = DOMProperty("autocapitalize")\n className = DOMProperty("className")\n contenteditable = DOMProperty("contenteditable")\n draggable = DOMProperty("draggable")\n enterkeyhint = DOMProperty("enterkeyhint")\n hidden = DOMProperty("hidden")\n innerHTML = DOMProperty("innerHTML")\n id = DOMProperty("id")\n lang = DOMProperty("lang")\n nonce = DOMProperty("nonce")\n part = DOMProperty("part")\n popover = DOMProperty("popover")\n slot = DOMProperty("slot")\n spellcheck = DOMProperty("spellcheck")\n tabindex = DOMProperty("tabindex")\n tagName = DOMProperty("tagName")\n textContent = DOMProperty("textContent")\n title = DOMProperty("title")\n translate = DOMProperty("translate")\n virtualkeyboardpolicy = DOMProperty("virtualkeyboardpolicy")\n\n @classmethod\n def from_dom_element(cls, dom_element):\n """Create an instance of the appropriate subclass of `Element` for a DOM\n element.\n\n If the DOM element was created via an `Element` (i.e. by us) it will have a data\n attribute named `data-pyscript-type` that contains the name of the subclass\n that created it. Hence, if the `data-pyscript-type` attribute *is* present we\n look up the subclass by name and create an instance of that. Otherwise, we make\n a \'best-guess\' and look up the `Element` subclass by the DOM element\'s tag name\n (this is NOT fool-proof as many subclasses might use a `<div>`, but close enough\n for jazz).\n """\n\n # We use "getAttribute" here instead of `js_element.dataset.pyscriptType` as the\n # latter throws an `AttributeError` if the value isn\'t set. This way we just get\n # `None` which seems cleaner.\n cls_name = dom_element.getAttribute("data-pyscript-type")\n if cls_name:\n element_cls = ELEMENT_CLASSES_BY_NAME.get(cls_name.lower())\n\n else:\n element_cls = ELEMENT_CLASSES_BY_TAG.get(dom_element.tagName.lower())\n\n # For any unknown elements (custom tags etc.) create an instance of this\n # class (\'Element\').\n if not element_cls:\n element_cls = cls\n\n return element_cls(dom_element=dom_element)\n\n def __init__(self, dom_element=None, classes=None, style=None, **kwargs):\n """Create a new, or wrap an existing DOM element.\n\n If `dom_element` is None we are being called to *create* a new element.\n Otherwise, we are being called to *wrap* an existing DOM element.\n """\n self._dom_element = dom_element or document.createElement(self.tag)\n\n # Tag the DOM element with our class name.\n #\n # Using the `dataset` attribute is how you programmatically add `data-xxx`\n # attributes to a DOM element. In this case it will set an attribute that\n # appears in the DOM as `data-pyscript-type`.\n self._dom_element.dataset.pyscriptType = type(self).__name__\n\n self._parent = None\n self._classes = Classes(self)\n self._style = Style(self)\n\n # Set any specified classes, styles, and DOM properties.\n self.update(classes=classes, style=style, **kwargs)\n\n def update(self, classes=None, style=None, **kwargs):\n """Update the element with the specified classes, styles, and DOM properties."""\n\n if classes:\n self.classes.add(classes)\n\n if isinstance(style, dict):\n self.style.set(**style)\n\n elif style is not None:\n raise ValueError(\n f"Style should be a dictionary, received {style} "\n f"(type {type(style)}) instead."\n )\n\n self._set_dom_properties(**kwargs)\n\n def _set_dom_properties(self, **kwargs):\n """Set the specified DOM properties.\n\n Args:\n **kwargs: The properties to set\n """\n # Harvest all DOM properties from the instance\'s class.\n dom_properties = {\n attribute_name: attribute_value\n for attribute_name, attribute_value in getmembers_static(self.__class__)\n if isinstance(attribute_value, DOMProperty)\n }\n\n for name, value in kwargs.items():\n if name not in dom_properties:\n raise ValueError(f"\'{name}\' is not a DOM property.")\n\n try:\n setattr(self, name, value)\n except Exception as e:\n print(f"Error setting {name} to {value}: {e}")\n raise\n\n def __eq__(self, obj):\n """Check for equality by comparing the underlying DOM element."""\n return isinstance(obj, Element) and obj._dom_element == self._dom_element\n\n @property\n def children(self):\n return ElementCollection(\n [Element.from_dom_element(el) for el in self._dom_element.children]\n )\n\n @property\n def classes(self):\n return self._classes\n\n @property\n def parent(self):\n if self._parent:\n return self._parent\n\n if self._dom_element.parentElement:\n self._parent = Element.from_dom_element(self._dom_element.parentElement)\n\n return self._parent\n\n @property\n def style(self):\n return self._style\n\n def append(self, child):\n if isinstance(child, Element):\n self._dom_element.appendChild(child._dom_element)\n\n elif isinstance(child, ElementCollection):\n for el in child:\n self._dom_element.appendChild(el._dom_element)\n\n else:\n # In this case we know it\'s not an Element or an ElementCollection, so we\n # guess that it\'s either a DOM element or NodeList returned via the ffi.\n try:\n # First, we try to see if it\'s an element by accessing the \'tagName\'\n # attribute.\n child.tagName\n self._dom_element.appendChild(child)\n\n except AttributeError:\n try:\n # Ok, it\'s not an element, so let\'s see if it\'s a NodeList by\n # accessing the \'length\' attribute.\n child.length\n for element_ in child:\n self._dom_element.appendChild(element_)\n\n except AttributeError:\n # Nope! This is not an element or a NodeList.\n raise TypeError(\n f\'Element "{child}" is a proxy object, "\'\n f"but not a valid element or a NodeList."\n )\n\n def clone(self, clone_id=None):\n """Make a clone of the element (clones the underlying DOM object too)."""\n clone = Element.from_dom_element(self._dom_element.cloneNode(True))\n clone.id = clone_id\n return clone\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 return ElementCollection(\n [\n Element.from_dom_element(dom_element)\n for dom_element in self._dom_element.querySelectorAll(selector)\n ]\n )\n\n def show_me(self):\n """Scroll the element into view."""\n self._dom_element.scrollIntoView()\n\n\nclass Classes:\n """A set-like interface to an element\'s `classList`."""\n\n def __init__(self, element: Element):\n self._element = element\n self._class_list = self._element._dom_element.classList\n\n def __contains__(self, item):\n return item in self._class_list\n\n def __eq__(self, other):\n # We allow comparison with either another `Classes` instance...\n if isinstance(other, Classes):\n compare_with = list(other._class_list)\n\n # ...or iterables of strings.\n else:\n # TODO: Check MP for existence of better iterable test.\n try:\n compare_with = iter(other)\n\n except TypeError:\n return False\n\n return set(self._class_list) == set(compare_with)\n\n def __iter__(self):\n return iter(self._class_list)\n\n def __len__(self):\n return self._class_list.length\n\n def __repr__(self):\n return f"Classes({\', \'.join(self._class_list)})"\n\n def __str__(self):\n return " ".join(self._class_list)\n\n def add(self, *class_names):\n for class_name in class_names:\n if isinstance(class_name, list):\n for item in class_name:\n self.add(item)\n\n else:\n self._class_list.add(class_name)\n\n def contains(self, class_name):\n return class_name in self\n\n def remove(self, *class_names):\n for class_name in class_names:\n if isinstance(class_name, list):\n for item in class_name:\n self.remove(item)\n\n else:\n self._class_list.remove(class_name)\n\n def replace(self, old_class, new_class):\n self.remove(old_class)\n self.add(new_class)\n\n def toggle(self, *class_names):\n for class_name in class_names:\n if class_name in self:\n self.remove(class_name)\n\n else:\n self.add(class_name)\n\n\nclass HasOptions:\n """Mix-in for elements that have an options attribute.\n\n The elements that support options are: <datalist>, <optgroup>, and <select>.\n """\n\n @property\n def options(self):\n if not hasattr(self, "_options"):\n self._options = Options(self)\n\n return self._options\n\n\nclass Options:\n """This class represents the <option>s of a <datalist>, <optgroup> or <select>\n element.\n\n It allows to access to add and remove <option>s by using the `add` and `remove`\n methods.\n """\n\n def __init__(self, element: Element) -> None:\n self._element = element\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\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._dom_element\n\n self._element._dom_element.add(option, before)\n\n def remove(self, item: int) -> None:\n """Remove the option at the specified index"""\n self._element._dom_element.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 [\n Element.from_dom_element(opt) for opt in self._element._dom_element.options\n ]\n\n @property\n def selected(self):\n """Return the selected option"""\n return self.options[self._element._dom_element.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 Style:\n """A dict-like interface to an element\'s css style."""\n\n def __init__(self, element: Element) -> None:\n self._element = element\n self._style = self._element._dom_element.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, **kwargs):\n for key, value in kwargs.items():\n self._element._dom_element.style.setProperty(key, value)\n\n # CSS Properties\n # Reference: https://github.com/microsoft/TypeScript/blob/main/src/lib/dom.generated.d.ts#L3799C1-L5005C2\n # Following properties automatically generated from the above reference using\n # tools/codegen_css_proxy.py\n @property\n def visible(self):\n return self._element._dom_element.style.visibility\n\n @visible.setter\n def visible(self, value):\n self._element._dom_element.style.visibility = value\n\n\nclass ContainerElement(Element):\n """Base class for elements that can contain other elements."""\n\n def __init__(\n self, *args, children=None, dom_element=None, style=None, classes=None, **kwargs\n ):\n super().__init__(\n dom_element=dom_element, style=style, classes=classes, **kwargs\n )\n\n for child in list(args) + (children or []):\n if isinstance(child, Element) or isinstance(child, ElementCollection):\n self.append(child)\n\n else:\n self.innerHTML += child\n\n\n# IMPORTANT: For all HTML components defined below, we are not mapping all possible\n# attributes, just the global and the most common ones. If you need to access a\n# specific attribute, you can always use the `_dom_element.<attribute>`\nclass a(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a"""\n\n tag = "a"\n\n download = DOMProperty("download")\n href = DOMProperty("href")\n referrerpolicy = DOMProperty("referrerpolicy")\n rel = DOMProperty("rel")\n target = DOMProperty("target")\n type = DOMProperty("type")\n\n\nclass abbr(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/abbr"""\n\n tag = "abbr"\n\n\nclass address(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/address"""\n\n tag = "address"\n\n\nclass area(Element):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/area"""\n\n tag = "area"\n\n alt = DOMProperty("alt")\n coords = DOMProperty("coords")\n download = DOMProperty("download")\n href = DOMProperty("href")\n ping = DOMProperty("ping")\n referrerpolicy = DOMProperty("referrerpolicy")\n rel = DOMProperty("rel")\n shape = DOMProperty("shape")\n target = DOMProperty("target")\n\n\nclass article(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/article"""\n\n tag = "article"\n\n\nclass aside(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/aside"""\n\n tag = "aside"\n\n\nclass audio(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio"""\n\n tag = "audio"\n\n autoplay = DOMProperty("autoplay")\n controls = DOMProperty("controls")\n controlslist = DOMProperty("controlslist")\n crossorigin = DOMProperty("crossorigin")\n disableremoteplayback = DOMProperty("disableremoteplayback")\n loop = DOMProperty("loop")\n muted = DOMProperty("muted")\n preload = DOMProperty("preload")\n src = DOMProperty("src")\n\n\nclass b(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/b"""\n\n tag = "b"\n\n\nclass base(Element):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base"""\n\n tag = "base"\n\n href = DOMProperty("href")\n target = DOMProperty("target")\n\n\nclass blockquote(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blockquote"""\n\n tag = "blockquote"\n\n cite = DOMProperty("cite")\n\n\nclass body(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/body"""\n\n tag = "body"\n\n\nclass br(Element):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/br"""\n\n tag = "br"\n\n\nclass button(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button"""\n\n tag = "button"\n\n autofocus = DOMProperty("autofocus")\n disabled = DOMProperty("disabled")\n form = DOMProperty("form")\n formaction = DOMProperty("formaction")\n formenctype = DOMProperty("formenctype")\n formmethod = DOMProperty("formmethod")\n formnovalidate = DOMProperty("formnovalidate")\n formtarget = DOMProperty("formtarget")\n name = DOMProperty("name")\n type = DOMProperty("type")\n value = DOMProperty("value")\n\n\nclass canvas(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas"""\n\n tag = "canvas"\n\n height = DOMProperty("height")\n width = DOMProperty("width")\n\n def download(self, filename: str = "snapped.png") -> None:\n """Download the current element with the filename provided in input.\n\n Inputs:\n * filename (str): name of the file being downloaded\n\n Output:\n None\n """\n download_link = a(download=filename, href=self._dom_element.toDataURL())\n\n # Adding the link to the DOM is recommended for browser compatibility to make\n # sure that the click works.\n self.append(download_link)\n\n download_link._dom_element.click()\n\n def draw(self, what, width=None, height=None):\n """Draw `what` on the current element\n\n Inputs:\n\n * what (canvas image source): An element to draw into the context. The\n specification permits any canvas image source, specifically, an\n HTMLImageElement, an SVGImageElement, an HTMLVideoElement,\n an HTMLCanvasElement, an ImageBitmap, an OffscreenCanvas, or a\n VideoFrame.\n """\n if isinstance(what, Element):\n what = what._dom_element\n\n # https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage\n ctx = self._dom_element.getContext("2d")\n if width or height:\n ctx.drawImage(what, 0, 0, width, height)\n\n else:\n ctx.drawImage(what, 0, 0)\n\n\nclass caption(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/caption"""\n\n tag = "caption"\n\n\nclass cite(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/cite"""\n\n tag = "cite"\n\n\nclass code(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/code"""\n\n tag = "code"\n\n\nclass col(Element):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/col"""\n\n tag = "col"\n\n span = DOMProperty("span")\n\n\nclass colgroup(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/colgroup"""\n\n tag = "colgroup"\n\n\nclass data(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/data"""\n\n tag = "data"\n\n value = DOMProperty("value")\n\n\nclass datalist(ContainerElement, HasOptions):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist"""\n\n tag = "datalist"\n\n\nclass dd(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dd"""\n\n tag = "dd"\n\n\nclass del_(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/del"""\n\n tag = "del"\n\n cite = DOMProperty("cite")\n datetime = DOMProperty("datetime")\n\n\nclass details(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details"""\n\n tag = "details"\n\n open = DOMProperty("open")\n\n\nclass dialog(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog"""\n\n tag = "dialog"\n\n open = DOMProperty("open")\n\n\nclass div(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div"""\n\n tag = "div"\n\n\nclass dl(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dl"""\n\n tag = "dl"\n\n value = DOMProperty("value")\n\n\nclass dt(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dt"""\n\n tag = "dt"\n\n\nclass em(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/em"""\n\n tag = "em"\n\n\nclass embed(Element):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/embed"""\n\n tag = "embed"\n\n height = DOMProperty("height")\n src = DOMProperty("src")\n type = DOMProperty("type")\n width = DOMProperty("width")\n\n\nclass fieldset(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/fieldset"""\n\n tag = "fieldset"\n\n disabled = DOMProperty("disabled")\n form = DOMProperty("form")\n name = DOMProperty("name")\n\n\nclass figcaption(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/figcaption"""\n\n tag = "figcaption"\n\n\nclass figure(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/figure"""\n\n tag = "figure"\n\n\nclass footer(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/footer"""\n\n tag = "footer"\n\n\nclass form(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form"""\n\n tag = "form"\n\n accept_charset = DOMProperty("accept-charset")\n action = DOMProperty("action")\n autocapitalize = DOMProperty("autocapitalize")\n autocomplete = DOMProperty("autocomplete")\n enctype = DOMProperty("enctype")\n name = DOMProperty("name")\n method = DOMProperty("method")\n nonvalidate = DOMProperty("nonvalidate")\n rel = DOMProperty("rel")\n target = DOMProperty("target")\n\n\nclass h1(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/h1"""\n\n tag = "h1"\n\n\nclass h2(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/h2"""\n\n tag = "h2"\n\n\nclass h3(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/h3"""\n\n tag = "h3"\n\n\nclass h4(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/h4"""\n\n tag = "h4"\n\n\nclass h5(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/h5"""\n\n tag = "h5"\n\n\nclass h6(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/h6"""\n\n tag = "h6"\n\n\nclass head(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head"""\n\n tag = "head"\n\n\nclass header(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/header"""\n\n tag = "header"\n\n\nclass hgroup(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/hgroup"""\n\n tag = "hgroup"\n\n\nclass hr(Element):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/hr"""\n\n tag = "hr"\n\n align = DOMProperty("align")\n color = DOMProperty("color")\n noshade = DOMProperty("noshade")\n size = DOMProperty("size")\n width = DOMProperty("width")\n\n\nclass html(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/html"""\n\n tag = "html"\n\n\nclass i(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/i"""\n\n tag = "i"\n\n\nclass iframe(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe"""\n\n tag = "iframe"\n\n allow = DOMProperty("allow")\n allowfullscreen = DOMProperty("allowfullscreen")\n height = DOMProperty("height")\n loading = DOMProperty("loading")\n name = DOMProperty("name")\n referrerpolicy = DOMProperty("referrerpolicy")\n sandbox = DOMProperty("sandbox")\n src = DOMProperty("src")\n srcdoc = DOMProperty("srcdoc")\n width = DOMProperty("width")\n\n\nclass img(Element):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img"""\n\n tag = "img"\n\n alt = DOMProperty("alt")\n crossorigin = DOMProperty("crossorigin")\n decoding = DOMProperty("decoding")\n fetchpriority = DOMProperty("fetchpriority")\n height = DOMProperty("height")\n ismap = DOMProperty("ismap")\n loading = DOMProperty("loading")\n referrerpolicy = DOMProperty("referrerpolicy")\n sizes = DOMProperty("sizes")\n src = DOMProperty("src")\n width = DOMProperty("width")\n\n\n# NOTE: Input is a reserved keyword in Python, so we use input_ instead\nclass input_(Element):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input"""\n\n tag = "input"\n\n accept = DOMProperty("accept")\n alt = DOMProperty("alt")\n autofocus = DOMProperty("autofocus")\n capture = DOMProperty("capture")\n checked = DOMProperty("checked")\n dirname = DOMProperty("dirname")\n disabled = DOMProperty("disabled")\n form = DOMProperty("form")\n formaction = DOMProperty("formaction")\n formenctype = DOMProperty("formenctype")\n formmethod = DOMProperty("formmethod")\n formnovalidate = DOMProperty("formnovalidate")\n formtarget = DOMProperty("formtarget")\n height = DOMProperty("height")\n list = DOMProperty("list")\n max = DOMProperty("max")\n maxlength = DOMProperty("maxlength")\n min = DOMProperty("min")\n minlength = DOMProperty("minlength")\n multiple = DOMProperty("multiple")\n name = DOMProperty("name")\n pattern = DOMProperty("pattern")\n placeholder = DOMProperty("placeholder")\n popovertarget = DOMProperty("popovertarget")\n popovertargetaction = DOMProperty("popovertargetaction")\n readonly = DOMProperty("readonly")\n required = DOMProperty("required")\n size = DOMProperty("size")\n src = DOMProperty("src")\n step = DOMProperty("step")\n type = DOMProperty("type")\n value = DOMProperty("value")\n width = DOMProperty("width")\n\n\nclass ins(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ins"""\n\n tag = "ins"\n\n cite = DOMProperty("cite")\n datetime = DOMProperty("datetime")\n\n\nclass kbd(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/kbd"""\n\n tag = "kbd"\n\n\nclass label(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label"""\n\n tag = "label"\n\n for_ = DOMProperty("for")\n\n\nclass legend(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/legend"""\n\n tag = "legend"\n\n\nclass li(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/li"""\n\n tag = "li"\n\n value = DOMProperty("value")\n\n\nclass link(Element):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link"""\n\n tag = "link"\n\n as_ = DOMProperty("as")\n crossorigin = DOMProperty("crossorigin")\n disabled = DOMProperty("disabled")\n fetchpriority = DOMProperty("fetchpriority")\n href = DOMProperty("href")\n imagesizes = DOMProperty("imagesizes")\n imagesrcset = DOMProperty("imagesrcset")\n integrity = DOMProperty("integrity")\n media = DOMProperty("media")\n rel = DOMProperty("rel")\n referrerpolicy = DOMProperty("referrerpolicy")\n sizes = DOMProperty("sizes")\n title = DOMProperty("title")\n type = DOMProperty("type")\n\n\nclass main(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/main"""\n\n tag = "main"\n\n\nclass map_(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/map"""\n\n tag = "map"\n\n name = DOMProperty("name")\n\n\nclass mark(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/mark"""\n\n tag = "mark"\n\n\nclass menu(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/menu"""\n\n tag = "menu"\n\n\nclass meta(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta"""\n\n tag = "meta"\n\n charset = DOMProperty("charset")\n content = DOMProperty("content")\n http_equiv = DOMProperty("http-equiv")\n name = DOMProperty("name")\n\n\nclass meter(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meter"""\n\n tag = "meter"\n\n form = DOMProperty("form")\n high = DOMProperty("high")\n low = DOMProperty("low")\n max = DOMProperty("max")\n min = DOMProperty("min")\n optimum = DOMProperty("optimum")\n value = DOMProperty("value")\n\n\nclass nav(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/nav"""\n\n tag = "nav"\n\n\nclass object_(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object"""\n\n tag = "object"\n\n data = DOMProperty("data")\n form = DOMProperty("form")\n height = DOMProperty("height")\n name = DOMProperty("name")\n type = DOMProperty("type")\n usemap = DOMProperty("usemap")\n width = DOMProperty("width")\n\n\nclass ol(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol"""\n\n tag = "ol"\n\n reversed = DOMProperty("reversed")\n start = DOMProperty("start")\n type = DOMProperty("type")\n\n\nclass optgroup(ContainerElement, HasOptions):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/optgroup"""\n\n tag = "optgroup"\n\n disabled = DOMProperty("disabled")\n label = DOMProperty("label")\n\n\nclass option(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option"""\n\n tag = "option"\n\n disabled = DOMProperty("value")\n label = DOMProperty("label")\n selected = DOMProperty("selected")\n value = DOMProperty("value")\n\n\nclass output(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/output"""\n\n tag = "output"\n\n for_ = DOMProperty("for")\n form = DOMProperty("form")\n name = DOMProperty("name")\n\n\nclass p(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/p"""\n\n tag = "p"\n\n\nclass param(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/p"""\n\n tag = "p"\n\n\nclass picture(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture"""\n\n tag = "picture"\n\n\nclass pre(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre"""\n\n tag = "pre"\n\n\nclass progress(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/progress"""\n\n tag = "progress"\n\n max = DOMProperty("max")\n value = DOMProperty("value")\n\n\nclass q(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/q"""\n\n tag = "q"\n\n cite = DOMProperty("cite")\n\n\nclass s(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/s"""\n\n tag = "s"\n\n\nclass script(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script"""\n\n tag = "script"\n\n # Let\'s add async manually since it\'s a reserved keyword in Python\n async_ = DOMProperty("async")\n blocking = DOMProperty("blocking")\n crossorigin = DOMProperty("crossorigin")\n defer = DOMProperty("defer")\n fetchpriority = DOMProperty("fetchpriority")\n integrity = DOMProperty("integrity")\n nomodule = DOMProperty("nomodule")\n nonce = DOMProperty("nonce")\n referrerpolicy = DOMProperty("referrerpolicy")\n src = DOMProperty("src")\n type = DOMProperty("type")\n\n\nclass section(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/section"""\n\n tag = "section"\n\n\nclass select(ContainerElement, HasOptions):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select"""\n\n tag = "select"\n\n value = DOMProperty("value")\n\n\nclass small(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/small"""\n\n tag = "small"\n\n\nclass source(Element):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/source"""\n\n tag = "source"\n\n media = DOMProperty("media")\n sizes = DOMProperty("sizes")\n src = DOMProperty("src")\n srcset = DOMProperty("srcset")\n type = DOMProperty("type")\n\n\nclass span(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/span"""\n\n tag = "span"\n\n\nclass strong(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/strong"""\n\n tag = "strong"\n\n\nclass style(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style"""\n\n tag = "style"\n\n blocking = DOMProperty("blocking")\n media = DOMProperty("media")\n nonce = DOMProperty("nonce")\n title = DOMProperty("title")\n\n\nclass sub(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/sub"""\n\n tag = "sub"\n\n\nclass summary(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/summary"""\n\n tag = "summary"\n\n\nclass sup(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/sup"""\n\n tag = "sup"\n\n\nclass table(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table"""\n\n tag = "table"\n\n\nclass tbody(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tbody"""\n\n tag = "tbody"\n\n\nclass td(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td"""\n\n tag = "td"\n\n colspan = DOMProperty("colspan")\n headers = DOMProperty("headers")\n rowspan = DOMProperty("rowspan")\n\n\nclass template(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template"""\n\n tag = "template"\n\n shadowrootmode = DOMProperty("shadowrootmode")\n\n\nclass textarea(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea"""\n\n tag = "textarea"\n\n autocapitalize = DOMProperty("autocapitalize")\n autocomplete = DOMProperty("autocomplete")\n autofocus = DOMProperty("autofocus")\n cols = DOMProperty("cols")\n dirname = DOMProperty("dirname")\n disabled = DOMProperty("disabled")\n form = DOMProperty("form")\n maxlength = DOMProperty("maxlength")\n minlength = DOMProperty("minlength")\n name = DOMProperty("name")\n placeholder = DOMProperty("placeholder")\n readonly = DOMProperty("readonly")\n required = DOMProperty("required")\n rows = DOMProperty("rows")\n spellcheck = DOMProperty("spellcheck")\n value = DOMProperty("value")\n wrap = DOMProperty("wrap")\n\n\nclass tfoot(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tfoot"""\n\n tag = "tfoot"\n\n\nclass th(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/th"""\n\n tag = "th"\n\n\nclass thead(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/thead"""\n\n tag = "thead"\n\n\nclass time(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/time"""\n\n tag = "time"\n\n datetime = DOMProperty("datetime")\n\n\nclass title(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/title"""\n\n tag = "title"\n\n\nclass tr(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tr"""\n\n tag = "tr"\n\n abbr = DOMProperty("abbr")\n colspan = DOMProperty("colspan")\n headers = DOMProperty("headers")\n rowspan = DOMProperty("rowspan")\n scope = DOMProperty("scope")\n\n\nclass track(Element):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/track"""\n\n tag = "track"\n\n default = DOMProperty("default")\n kind = DOMProperty("kind")\n label = DOMProperty("label")\n src = DOMProperty("src")\n srclang = DOMProperty("srclang")\n\n\nclass u(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/u"""\n\n tag = "u"\n\n\nclass ul(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul"""\n\n tag = "ul"\n\n\nclass var(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/var"""\n\n tag = "var"\n\n\nclass video(ContainerElement):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video"""\n\n tag = "video"\n\n autoplay = DOMProperty("autoplay")\n controls = DOMProperty("controls")\n crossorigin = DOMProperty("crossorigin")\n disablepictureinpicture = DOMProperty("disablepictureinpicture")\n disableremoteplayback = DOMProperty("disableremoteplayback")\n height = DOMProperty("height")\n loop = DOMProperty("loop")\n muted = DOMProperty("muted")\n playsinline = DOMProperty("playsinline")\n poster = DOMProperty("poster")\n preload = DOMProperty("preload")\n src = DOMProperty("src")\n width = DOMProperty("width")\n videoHeight = DOMProperty("videoHeight")\n videoWidth = DOMProperty("videoWidth")\n\n def snap(\n self,\n to: Element | str = None,\n width: int | None = None,\n height: int | None = None,\n ):\n """\n Capture a snapshot (i.e. a single frame) of a video to a canvas.\n\n Inputs:\n\n * to: the canvas to save the video frame to (if None, one is created).\n * width: width of the snapshot (defaults to the video width).\n * height: height of the snapshot (defaults to the video height).\n\n Output:\n (Element) canvas element where the video frame snapshot was drawn into\n """\n width = width if width is not None else self.videoWidth\n height = height if height is not None else self.videoHeight\n\n if to is None:\n to = canvas(width=width, height=height)\n\n elif isinstance(to, Element):\n if to.tag != "canvas":\n raise TypeError("Element to snap to must be a canvas.")\n\n elif getattr(to, "tagName", "") == "CANVAS":\n to = canvas(dom_element=to)\n\n # If \'to\' is a string, then assume it is a query selector.\n elif isinstance(to, str):\n nodelist = document.querySelectorAll(to) # NOQA\n if nodelist.length == 0:\n raise TypeError("No element with selector {to} to snap to.")\n\n if nodelist[0].tagName != "CANVAS":\n raise TypeError("Element to snap to must be a canvas.")\n\n to = canvas(dom_element=nodelist[0])\n\n to.draw(self, width, height)\n\n return to\n\n\nclass wbr(Element):\n """Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/wbr"""\n\n tag = "wbr"\n\n\n# Custom Elements\nclass grid(ContainerElement):\n tag = "div"\n\n def __init__(self, layout, content=None, gap=None, **kwargs):\n super().__init__(content, **kwargs)\n self.style["display"] = "grid"\n self.style["grid-template-columns"] = layout\n\n # TODO: This should be a property\n if gap is not None:\n self.style["gap"] = gap\n\n\nclass ClassesCollection:\n def __init__(self, collection: "ElementCollection") -> None:\n self._collection = collection\n\n def __contains__(self, class_name):\n for element in self._collection:\n if class_name in element.classes:\n return True\n\n return False\n\n def __eq__(self, other):\n return (\n isinstance(other, ClassesCollection)\n and self._collection == other._collection\n )\n\n def __iter__(self):\n for class_name in self._all_class_names():\n yield class_name\n\n def __len__(self):\n return len(self._all_class_names())\n\n def __repr__(self):\n return f"ClassesCollection({repr(self._collection)})"\n\n def __str__(self):\n return " ".join(self._all_class_names())\n\n def add(self, *class_names):\n for element in self._collection:\n element.classes.add(*class_names)\n\n def contains(self, class_name):\n return class_name in self\n\n def remove(self, *class_names):\n for element in self._collection:\n element.classes.remove(*class_names)\n\n def replace(self, old_class, new_class):\n for element in self._collection:\n element.classes.replace(old_class, new_class)\n\n def toggle(self, *class_names):\n for element in self._collection:\n element.classes.toggle(*class_names)\n\n def _all_class_names(self):\n all_class_names = set()\n for element in self._collection:\n for class_name in element.classes:\n all_class_names.add(class_name)\n\n return all_class_names\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 __repr__(self):\n return f"StyleCollection({repr(self._collection)})"\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._classes = ClassesCollection(self)\n self._style = StyleCollection(self)\n\n def __eq__(self, obj):\n """Check for equality by comparing the underlying DOM elements."""\n return isinstance(obj, ElementCollection) and obj._elements == self._elements\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\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 query selector.\n return self.find(key)\n\n def __iter__(self):\n yield from self._elements\n\n def __len__(self):\n return len(self._elements)\n\n def __repr__(self):\n return (\n f"{self.__class__.__name__} (length: {len(self._elements)}) "\n f"{self._elements}"\n )\n\n def __getattr__(self, item):\n return self._get_attribute(item)\n\n def __setattr__(self, key, value):\n # This class overrides `__setattr__` to delegate "public" attributes to the\n # elements in the collection, but we don\'t use the usual Python pattern where we\n # set attributes on the collection itself via `self.__dict__` as it is not yet\n # supported in our build of MicroPython. Instead, we handle it here.\n if key.startswith("_"):\n super().__setattr__(key, value)\n\n else:\n self._set_attribute(key, value)\n\n @property\n def children(self):\n return self._elements\n\n @property\n def classes(self):\n return self._classes\n\n @property\n def style(self):\n return self._style\n\n def find(self, selector):\n elements = []\n for element in self._elements:\n elements.extend(element.find(selector))\n\n return ElementCollection(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\n# fmt: off\nELEMENT_CLASSES = [\n # We put grid first because it is really just a <div> but we want the div class to\n # be used if wrapping existing js elements that we have not tagged with a\n # `data-pyscript-type` attribute (last one is the winner when it comes to this\n # list).\n grid,\n # The rest in alphabetical order.\n a, abbr, address, area, article, aside, audio,\n b, base, blockquote, body, br, button,\n canvas, caption, cite, code, col, colgroup,\n data, datalist, dd, del_, details, dialog, div, dl, dt,\n em, embed,\n fieldset, figcaption, figure, footer, form,\n h1, h2, h3, h4, h5, h6, head, header, hgroup, hr, html,\n i, iframe, img, input_, ins,\n kbd,\n label, legend, li, link,\n main, map_, mark, menu, meta, meter,\n nav,\n object_, ol, optgroup, option, output,\n p, param, picture, pre, progress,\n q,\n s, script, section, select, small, source, span, strong, style, sub, summary, sup,\n table, tbody, td, template, textarea, tfoot, th, thead, time, title, tr, track,\n u, ul,\n var, video,\n wbr,\n]\n# fmt: on\n\n\n# Lookup tables to get an element class by its name or tag.\nELEMENT_CLASSES_BY_NAME = {cls.__name__: cls for cls in ELEMENT_CLASSES}\nELEMENT_CLASSES_BY_TAG = {cls.tag: cls for cls in ELEMENT_CLASSES}\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',"workers.py":'import js as _js\nfrom polyscript import workers as _workers\n\n_get = _js.Reflect.get\n\n\ndef _set(script, name, value=""):\n script.setAttribute(name, value)\n\n\n# this solves an inconsistency between Pyodide and MicroPython\n# @see https://github.com/pyscript/pyscript/issues/2106\nclass _ReadOnlyProxy:\n def __getitem__(self, name):\n return _get(_workers, name)\n\n def __getattr__(self, name):\n return _get(_workers, name)\n\n\nworkers = _ReadOnlyProxy()\n\n\nasync def create_named_worker(src="", name="", config=None, type="py"):\n from json import dumps\n\n if not src:\n raise ValueError("Named workers require src")\n\n if not name:\n raise ValueError("Named workers require a name")\n\n s = _js.document.createElement("script")\n s.type = type\n s.src = src\n _set(s, "worker")\n _set(s, "name", name)\n\n if config:\n _set(s, "config", isinstance(config, str) and config or dumps(config))\n\n _js.document.body.append(s)\n return await workers[name]\n'}}),Ar.push("import pyscript as _pyscript"),Ar.push(...["_Path","_path","_os","_pyscript"].map((e=>`del ${e}`))),Ar.push("\n");const Wr=Ar.join("\n"),Ir=Nr.join("\n"),Lr=e=>Jr.main[e],$r=e=>Jr.worker[e],Hr=(e,n,t,r)=>{e[t]=()=>{const e=r?[r]:[];return e.push(...n(t)),e.map(Ge).join("\n")}},Ur=(e,n)=>{const t="mpy"===n?Wr.replace(Ir,""):Wr,r={};return Hr(r,e,"codeBeforeRun",t),Hr(r,e,"codeBeforeRunAsync",t),Hr(r,e,"codeAfterRun"),Hr(r,e,"codeAfterRunAsync"),r},zr=(e,n)=>{const t=[...$r(n)];if(t.length){const r=Et(e[`_${n}`]||(n.endsWith("Async")?async(e,n,...t)=>{for(const r of t)await r(e,n)}:(e,n,...t)=>{for(const r of t)r(e,n)})),s=t.map(Et).join(", ");return Function(`return(w,x)=>(${r})(w,x,...[${s}])`)()}},Fr=xr({typeof:"function"}),Br=xr({typeof:"string"}),qr='\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',Jr={main:{onWorker:new Fr,onReady:new Fr,onBeforeRun:new Fr,onBeforeRunAsync:new Fr,onAfterRun:new Fr,onAfterRunAsync:new Fr,codeBeforeRun:new Br([qr]),codeBeforeRunAsync:new Br,codeAfterRun:new Br,codeAfterRunAsync:new Br},worker:{onReady:new Fr,onBeforeRun:new Fr,onBeforeRunAsync:new Fr,onAfterRun:new Fr,onAfterRunAsync:new Fr,codeBeforeRun:new Br,codeBeforeRunAsync:new Br,codeAfterRun:new Br,codeAfterRunAsync:new Br}},Gr=({tagName:e})=>"SCRIPT"===e,[Yr,Kr]=[...lr.entries()].map((([e,n])=>async function(t,r){await Er.get(e).plugins;const s=ar.call(new or(null,rs.get(e)),t,{...r,type:n});return Ve(s.sync,Mr),s.ready})),[{PyWorker:Vr,MPWorker:Xr,hooks:Zr,config:Qr,whenDefined:es},ns]=e("@pyscript/core",{PyWorker:Yr,MPWorker:Kr,hooks:Jr,config:{},whenDefined:rr}),ts=e=>e?.interpreter&&br(e.interpreter),rs=new Map;for(const[e,n]of lr){if(ns)break;const t=(n,t,r)=>{t?r.then((()=>an(n,e,"done"))):an(n,e,"done")},{config:r,configURL:s,plugins:o,error:a}=Er.get(e);let i=0;const l=(n=e)=>`${n}-${i++}`,c=async(n,t,r)=>{if(n.hasAttribute("src"))try{return await hr(n.getAttribute("src")).then(mr)}catch(e){t.stderr(e)}if(r)return Ge(n.textContent);const s=Ge(Ye(n.innerHTML));return console.warn(`Deprecated: use <script type="${e}"> for an always safe content parsing:\n`,s),s};let p,d=!1;const f=({XWorker:e,interpreter:n,io:t})=>{d||(d=!0,n.registerJsModule("_pyscript",{PyWorker:function(...n){const r=e(...n);return r.onerror=({error:e})=>t.stderr(e),r},js_import:(...e)=>Promise.all(e.map((e=>import(e)))),get target(){return Gr(p)?p.target.id:p.id}}))};a||o.then((()=>{const o=new Map,a={main:{...Ur(Lr,e),async onReady(n,r){f(n);for(const e of Lr("onReady"))await e(n,r);if(o.has(r)){let{message:e}=o.get(r);o.delete(r);const t=e===jt;return e=`(${dr.CONFLICTING_CODE}) ${e} for `,e+=r.cloneNode(t).outerHTML,void n.io.stderr(e)}if(Gr(r)){const{attributes:{async:s,target:o}}=r,a=!!o?.value,i=a?Nt(r,o.value):document.createElement("script-py");if(!a){const{head:e,body:n}=document;e.contains(r)?n.append(i):r.after(i)}i.id||(i.id=l()),Qe(r,"target",{value:i}),an(r,e,"ready"),t(r,s,n["run"+(s?"Async":"")](await c(r,n.io,!0)))}else r._wrap.resolve(n);console.debug("[pyscript/main] PyScript Ready")},onWorker(e,n){Ve(n.sync,Mr);for(const t of Lr("onWorker"))t(e,n)},onBeforeRun(e,n){p=n,Pr(Lr,e,n,"onBeforeRun")},onBeforeRunAsync:(e,n)=>(p=n,Pr(Lr,e,n,"onBeforeRunAsync")),onAfterRun(e,n){Pr(Lr,e,n,"onAfterRun")},onAfterRunAsync:(e,n)=>Pr(Lr,e,n,"onAfterRunAsync")},worker:{...Ur($r,e),get onReady(){return zr(this,"onReady")},get onBeforeRun(){return zr(this,"onBeforeRun")},get onBeforeRunAsync(){return zr(this,"onBeforeRunAsync")},get onAfterRun(){return zr(this,"onAfterRun")},get onAfterRunAsync(){return zr(this,"onAfterRunAsync")}}};rs.set(e,a),tr(e,{config:r,configURL:s,interpreter:n,hooks:a,env:`${e}-script`,version:ts(r),onerror(e,n){o.set(n,e)}}),customElements.define(`${e}-script`,class extends HTMLElement{constructor(){Ve(super(),{_wrap:Promise.withResolvers(),srcCode:"",executed:!1})}get id(){return super.id||(super.id=l())}set id(e){super.id=e}async connectedCallback(){if(!this.executed){this.executed=!0;const n=this.hasAttribute("async"),{io:r,run:s,runAsync:o}=await this._wrap.promise;this.srcCode=await c(this,r,!this.childElementCount),this.replaceChildren(),this.style.display="block",an(this,e,"ready"),t(this,n,(n?o:s)(this.srcCode))}}})})),Qr[e]=structuredClone(r)}export{or as H,lr as T,ar as X,Ge as a,Ir as b,nr as c,Ze as d,Zr as e,Vr as f,Xr as g,Qr as h,qr as i,es as j,ts as o,br as r,Wr as s};
|
2
|
+
//# sourceMappingURL=core-sVxLb9Ur.js.map
|