@pyscript/core 0.4.54 → 0.4.56

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.
Files changed (50) hide show
  1. package/dist/{codemirror-uEsvwGeX.js → codemirror-BZEh__gm.js} +2 -2
  2. package/dist/{codemirror-uEsvwGeX.js.map → codemirror-BZEh__gm.js.map} +1 -1
  3. package/dist/{codemirror_commands-BjErX5JV.js → codemirror_commands-leH8shna.js} +2 -2
  4. package/dist/{codemirror_commands-BjErX5JV.js.map → codemirror_commands-leH8shna.js.map} +1 -1
  5. package/dist/{codemirror_lang-python-rjOo-iGF.js → codemirror_lang-python-DuOzopOD.js} +2 -2
  6. package/dist/{codemirror_lang-python-rjOo-iGF.js.map → codemirror_lang-python-DuOzopOD.js.map} +1 -1
  7. package/dist/{codemirror_language-oTnz5LmX.js → codemirror_language-Dakzaxks.js} +2 -2
  8. package/dist/{codemirror_language-oTnz5LmX.js.map → codemirror_language-Dakzaxks.js.map} +1 -1
  9. package/dist/codemirror_view-Bm5_2vT5.js +2 -0
  10. package/dist/codemirror_view-Bm5_2vT5.js.map +1 -0
  11. package/dist/core-DKrwnOQh.js +3 -0
  12. package/dist/core-DKrwnOQh.js.map +1 -0
  13. package/dist/core.js +1 -1
  14. package/dist/{deprecations-manager-BxzDUsLg.js → deprecations-manager-BYGF73-y.js} +2 -2
  15. package/dist/{deprecations-manager-BxzDUsLg.js.map → deprecations-manager-BYGF73-y.js.map} +1 -1
  16. package/dist/{error-BiBuvdCh.js → error-DgYfWJQg.js} +2 -2
  17. package/dist/{error-BiBuvdCh.js.map → error-DgYfWJQg.js.map} +1 -1
  18. package/dist/{index-DvH26nkT.js → index-DA5aljNV.js} +2 -2
  19. package/dist/{index-DvH26nkT.js.map → index-DA5aljNV.js.map} +1 -1
  20. package/dist/{mpy-C8arSQdw.js → mpy-DiqSc6w9.js} +2 -2
  21. package/dist/mpy-DiqSc6w9.js.map +1 -0
  22. package/dist/{py-CQbAin00.js → py-DEubHlb_.js} +2 -2
  23. package/dist/{py-CQbAin00.js.map → py-DEubHlb_.js.map} +1 -1
  24. package/dist/{py-editor-Cd7PRgND.js → py-editor-DHmqLMO5.js} +2 -2
  25. package/dist/{py-editor-Cd7PRgND.js.map → py-editor-DHmqLMO5.js.map} +1 -1
  26. package/dist/{py-terminal-DCvjFHnO.js → py-terminal-E6BBcU6N.js} +2 -2
  27. package/dist/{py-terminal-DCvjFHnO.js.map → py-terminal-E6BBcU6N.js.map} +1 -1
  28. package/dist/{zip-BxogYCy6.js → zip-CGWtiqjJ.js} +2 -2
  29. package/dist/zip-CGWtiqjJ.js.map +1 -0
  30. package/package.json +7 -7
  31. package/src/plugins/py-terminal/mpy.js +19 -7
  32. package/src/stdlib/pyscript/event_handling.py +13 -12
  33. package/src/stdlib/pyscript/web/__init__.py +18 -4
  34. package/src/stdlib/pyscript/web/elements.py +898 -723
  35. package/src/stdlib/pyscript.js +3 -14
  36. package/types/core.d.ts +1 -1
  37. package/types/stdlib/pyscript.d.ts +0 -11
  38. package/dist/codemirror_view-CH_aW-qU.js +0 -2
  39. package/dist/codemirror_view-CH_aW-qU.js.map +0 -1
  40. package/dist/core-DsWVYGyA.js +0 -3
  41. package/dist/core-DsWVYGyA.js.map +0 -1
  42. package/dist/mpy-C8arSQdw.js.map +0 -1
  43. package/dist/zip-BxogYCy6.js.map +0 -1
  44. package/src/stdlib/pyscript/web/dom.py +0 -21
  45. package/src/stdlib/pyscript/web/media.py +0 -95
  46. package/src/stdlib/pyweb/__init__.py +0 -2
  47. package/src/stdlib/pyweb/media.py +0 -95
  48. package/src/stdlib/pyweb/pydom.py +0 -569
  49. package/src/stdlib/pyweb/ui/__init__.py +0 -1
  50. package/src/stdlib/pyweb/ui/elements.py +0 -947
@@ -0,0 +1,3 @@
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,f=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),d="",{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,d];case"Object":return[2,d];case"Date":return[3,d];case"RegExp":return[4,d];case"Map":return[5,d];case"Set":return[6,d]}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=>f(_(e)),stringify:e=>w(g(e,b))});const E="64e10b34-2bf7-4616-9668-f99de5aa046e",M="M"+E,k="T"+E,O="array",P="function",T="null",R="number",S="object",D="string",x="symbol",j="undefined",A="apply",N="construct",C="defineProperty",W="deleteProperty",L="get",H="getOwnPropertyDescriptor",$="getPrototypeOf",I="has",U="isExtensible",z="ownKeys",F="preventExtensions",B="set",q="setPrototypeOf",J="delete",{isArray:G}=Array;let{SharedArrayBuffer:Y,window:K}=globalThis,{notify:V,wait:X,waitAsync:Z}=Atomics,Q=null;Z||(Z=e=>({value:new Promise((n=>{let t=new Worker("data:application/javascript,onmessage%3D(%7Bdata%3Ab%7D)%3D%3E(Atomics.wait(b%2C0)%2CpostMessage(0))");t.onmessage=n,t.postMessage(e)}))}));try{new Y(4)}catch(e){Y=ArrayBuffer;const n=new WeakMap;if(K){const e=new Map,{prototype:{postMessage:t}}=Worker,r=n=>{const t=n.data?.[E];if(!G(t)){n.stopImmediatePropagation();const{id:r,sb:s}=t;e.get(r)(s)}};Q=function(e,...s){const o=e?.[E];if(G(o)){const[e,t]=o;n.set(t,e),this.addEventListener("message",r)}return t.call(this,e,...s)},Z=t=>({value:new Promise((r=>{e.set(n.get(t),r)})).then((r=>{e.delete(n.get(t)),n.delete(t);for(let e=0;e<r.length;e++)t[e]=r[e];return"ok"}))})}else{const e=(e,n)=>({[E]:{id:e,sb:n}});V=t=>{postMessage(e(n.get(t),t))},addEventListener("message",(e=>{const t=e.data?.[E];if(G(t)){const[e,r]=t;n.set(r,e)}}))}}
2
+ /*! (c) Andrea Giammarchi - ISC */const{Int32Array:ee,Map:ne,Uint16Array:te}=globalThis,{BYTES_PER_ELEMENT:re}=ee,{BYTES_PER_ELEMENT:se}=te,oe=new WeakSet,ae=new WeakMap,ie={value:{then:e=>e()}};let le=0;const ce=(e,{parse:n=JSON.parse,stringify:t=JSON.stringify,transform:r,interrupt:s}=JSON)=>{if(!ae.has(e)){const o=Q||e.postMessage,a=(n,...t)=>o.call(e,{[E]:t},{transfer:n}),i=typeof s===P?s:s?.handler,l=s?.delay||42,c=new TextDecoder("utf-16"),p=(e,n)=>e?Z(n,0):(i?((e,n,t)=>{for(;"timed-out"===X(e,0,0,n);)t()})(n,l,i):X(n,0),ie);let f=!1;ae.set(e,new Proxy(new ne,{[I]:(e,n)=>"string"==typeof n&&!n.startsWith("_"),[L]:(t,s)=>"then"===s?null:(...t)=>{const o=le++;let i=new ee(new Y(2*re)),l=[];oe.has(t.at(-1)||l)&&oe.delete(l=t.pop()),a(l,o,i,s,r?t.map(r):t);const d=e!==globalThis;let u=0;return f&&d&&(u=setTimeout(console.warn,1e3,`💀🔒 - Possible deadlock if proxy.${s}(...args) is awaited`)),p(d,i).value.then((()=>{clearTimeout(u);const e=i[1];if(!e)return;const t=se*e;return i=new ee(new Y(t+t%re)),a([],o,i),p(d,i).value.then((()=>n(c.decode(new te(i.buffer).slice(0,e)))))}))},[B](n,s,o){const a=typeof o;if(a!==P)throw new Error(`Unable to assign ${s} as ${a}`);if(!n.size){const s=new ne;e.addEventListener("message",(async e=>{const o=e.data?.[E];if(G(o)){e.stopImmediatePropagation();const[a,i,...l]=o;let c;if(l.length){const[e,o]=l;if(n.has(e)){f=!0;try{const l=await n.get(e)(...o);if(void 0!==l){const e=t(r?r(l):l);s.set(a,e),i[1]=e.length}}catch(e){c=e}finally{f=!1}}else c=new Error(`Unsupported action: ${e}`);i[0]=1}else{const e=s.get(a);s.delete(a);for(let n=new te(i.buffer),t=0;t<e.length;t++)n[t]=e.charCodeAt(t)}if(V(i,0),c)throw c}}))}return!!n.set(s,o)}}))}return ae.get(e)};ce.transfer=(...e)=>(oe.add(e),e);const{isArray:pe}=Array,fe=(e,n)=>n,de=e=>typeof e===P?(e=>e())(e):e;function ue(){return this}const me=(e,n)=>e===O?[n]:{t:e,v:n},he=(e,n=fe)=>{let t=typeof e,r=e;return t===S&&(pe(e)?(t=O,r=e.at(0)):({t:t,v:r}=e)),n(t,r)},ye=(e,n)=>e===P?n:me(e,n),ge=(e,n=ye)=>{const t=null===e?T:typeof e;return n(t===S&&pe(e)?O:t,e)},_e=new FinalizationRegistry((([e,n,t])=>{t&&console.debug(`Held value ${String(n)} not relevant anymore`),e(n)})),we=Object.create(null),be=(e,n,{debug:t,handler:r,return:s,token:o=e}=we)=>{const a=s||new Proxy(e,r||we),i=[a,[n,e,!!t]];return!1!==o&&i.push(o),_e.register(...i),a},{defineProperty:ve,deleteProperty:Ee,getOwnPropertyDescriptor:Me,getPrototypeOf:ke,isExtensible:Oe,ownKeys:Pe,preventExtensions:Te,set:Re,setPrototypeOf:Se}=Reflect,{assign:De,create:xe}=Object,je=ke(Int8Array),Ae=(e,n)=>{const{get:t,set:r,value:s}=e;return t&&(e.get=n(t)),r&&(e.set=n(r)),s&&(e.value=n(s)),e},Ne=e=>n=>ge(n,((n,t)=>{switch(n){case T:return me(T,t);case S:if(t===globalThis)return me(n,null);case O:case P:return e(n,t);case"boolean":case R:case D:case j:case"bigint":return me(n,t);case x:{if(Ce.has(t))return me(n,Ce.get(t));let e=Symbol.keyFor(t);if(e)return me(n,`.${e}`)}}throw new TypeError(`Unable to handle this ${n}: ${String(t)}`)})),Ce=new Map(Pe(Symbol).filter((e=>typeof Symbol[e]===x)).map((e=>[Symbol[e],e]))),We=e=>{if(e.startsWith("."))return Symbol.for(e.slice(1));for(const[n,t]of Ce)if(t===e)return n},Le=e=>e;var He=((e,n)=>{const t=new WeakMap;{const{addEventListener:e}=EventTarget.prototype;ve(EventTarget.prototype,"addEventListener",{value(n,r,...s){return s.at(0)?.invoke&&(t.has(this)||t.set(this,new Map),t.get(this).set(n,[].concat(s[0].invoke)),delete s[0].invoke),e.call(this,n,r,...s)}})}return function(n,r,s,...o){let a=0,i=this?.transform||Le;const l=new Map,c=new Map,{[s]:p}=n,f=o.length?De(xe(globalThis),...o):globalThis,d=Ne(((e,n)=>{if(!l.has(n)){let t;for(;c.has(t=a++););l.set(n,t),c.set(t,e===P?n:i(n))}return me(e,l.get(n))})),u=e=>{p(J,me(D,e))},m=(e,n)=>{switch(e){case S:if(null==n)return f;case O:if(typeof n===R)return c.get(n);if(!(n instanceof je))for(const e in n)n[e]=h(n[e]);return n;case P:if(typeof n===D){const e=c.get(n)?.deref();if(e)return e;const r=function(...e){return e.at(0)instanceof Event&&(e=>{const{currentTarget:n,target:r,type:s}=e;for(const o of t.get(n||r)?.get(s)||[])e[o]()})(...e),p(A,me(P,n),d(this),e.map(d))};return c.set(n,new WeakRef(r)),be(n,u,{return:r,token:!1})}return c.get(n);case x:return We(n)}return n},h=e=>he(e,m),y={[A]:(e,n,t)=>d(e.apply(n,t)),[N]:(e,n)=>d(new e(...n)),[C]:(e,n,t)=>d(ve(e,n,t)),[W]:(e,n)=>d(Ee(e,n)),[$]:e=>d(ke(e)),[L]:(e,n)=>d(e[n]),[H]:(e,n)=>{const t=Me(e,n);return t?me(S,Ae(t,d)):me(j,t)},[I]:(e,n)=>d(n in e),[U]:e=>d(Oe(e)),[z]:e=>me(O,Pe(e).map(d)),[F]:e=>d(Te(e)),[B]:(e,n,t)=>d(Re(e,n,t)),[q]:(e,n)=>d(Se(e,n)),[J](e){l.delete(c.get(e)),c.delete(e)}};return n[r]=(e,n,...t)=>{switch(e){case A:t[0]=h(t[0]),t[1]=t[1].map(h);break;case N:t[0]=t[0].map(h);break;case C:{const[e,n]=t;t[0]=h(e);const{get:r,set:s,value:o}=n;r&&(n.get=h(r)),s&&(n.set=h(s)),o&&(n.value=h(o));break}default:t=t.map(h)}return y[e](h(n),...t)},{proxy:n,[e.toLowerCase()]:f,[`is${e}Proxy`]:()=>!1}}})("Window"),$e=(e=>{let n=0;const t=new Map,r=new Map,s=Symbol();return function(o,a,i){const l=this?.transform||Le,{[a]:c}=o,p=new Map,f=e=>{p.delete(e),c(J,d(e))},d=Ne(((e,o)=>{if(s in o)return de(o[s]);if(e===P){if(o=l(o),!r.has(o)){let e;for(;r.has(e=String(n++)););t.set(o,e),r.set(e,o)}return me(e,t.get(o))}if(!(o instanceof je)){o=l(o);for(const e in o)o[e]=d(o[e])}return me(e,o)})),u=(e,n,t)=>{const r=p.get(t)?.deref();if(r)return r;const s=n===P?(e=>ue.bind(e))(e):e,o=new Proxy(s,y);return p.set(t,new WeakRef(o)),be(t,f,{return:o,token:!1})},m=e=>he(e,((n,t)=>{switch(n){case S:if(null===t)return globalThis;case O:return typeof t===R?u(e,n,t):t;case P:return typeof t===D?r.get(t):u(e,n,t);case x:return We(t)}return t})),h=(e,n,...t)=>m(c(e,de(n),...t)),y={[A]:(e,n,t)=>h(A,e,d(n),t.map(d)),[N]:(e,n)=>h(N,e,n.map(d)),[C]:(e,n,t)=>{const{get:r,set:s,value:o}=t;return typeof r===P&&(t.get=d(r)),typeof s===P&&(t.set=d(s)),typeof o===P&&(t.value=d(o)),h(C,e,d(n),t)},[W]:(e,n)=>h(W,e,d(n)),[$]:e=>h($,e),[L]:(e,n)=>n===s?e:h(L,e,d(n)),[H]:(e,n)=>{const t=h(H,e,d(n));return t&&Ae(t,m)},[I]:(e,n)=>n===s||h(I,e,d(n)),[U]:e=>h(U,e),[z]:e=>h(z,e).map(m),[F]:e=>h(F,e),[B]:(e,n,t)=>h(B,e,d(n),d(t)),[q]:(e,n)=>h(q,e,d(n))};o[i]=(e,n,s,o)=>{switch(e){case A:return m(n).apply(m(s),o.map(m));case J:{const e=m(n);t.delete(r.get(e)),r.delete(e)}}};const g=new Proxy(me(S,null),y);return{[e.toLowerCase()]:g,[`is${e}Proxy`]:e=>typeof e===S&&!!e&&s in e,proxy:o}}})("Window"),Ie=typeof Worker===P?Worker:class{};const Ue=new WeakMap,ze=(e,...n)=>{const t=ce(e,...n);if(!Ue.has(t)){const r=e instanceof Ie?He:$e;Ue.set(t,r.call(n.at(0),t,M,k))}return Ue.get(t)};ze.transfer=ce.transfer;const{url:Fe}=import.meta,Be=/import\((['"])([^)]+?\.js)\1\)/g,qe=(e,n,t)=>`import(${n}${new URL(t,Fe).href}${n})`;const Je={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:Ge}="",Ye=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34);/g,Ke={"&amp;":"&","&#38;":"&","&lt;":"<","&#60;":"<","&gt;":">","&#62;":">","&apos;":"'","&#39;":"'","&quot;":'"',"&#34;":'"'},Ve=e=>Ke[e],Xe=new WeakMap,Ze=e=>{const n=e||console,t={buffered:en,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 Xe.set(n,t),n}}},Qe=new TextDecoder,en=(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)}},nn=(e,...n)=>Je[typeof e](e,...n),tn=e=>Ge.call(e,Ye,Ve),{isArray:rn}=Array,{assign:sn,create:on,defineProperties:an,defineProperty:ln,entries:cn}=Object,{all:pn,resolve:fn}=new Proxy(Promise,{get:(e,n)=>e[n].bind(e)}),dn=(e,n=location.href)=>new URL(e,n.replace(/^blob:/,"")).href;let un=0;const mn=(e,n)=>({id:e.id||(e.id=`${n}-w${un++}`),tag:e.tagName}),hn=(e,n,t,r=!1,s=CustomEvent)=>{e.dispatchEvent(new s(`${n}:${t}`,{bubbles:!0,detail:{worker:r}}))},yn=(e,n,t,r)=>({type:n,config:t,interpreter:r,io:Xe.get(r),run:(n,...t)=>e.run(r,n,...t),runAsync:(n,...t)=>e.runAsync(r,n,...t),runEvent:(...n)=>e.runEvent(r,...n)}),gn=e=>e.replace(/^(?:\n|\r\n)/,""),_n=(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,gn(n),...o);return r&&s(e,r,...o),a}:async(e,n,...o)=>{t&&await s(e,t,...o);const a=await s(e,gn(n),...o);return r&&await s(e,r,...o),a}},wn=Symbol.for("polyscript.js_modules"),bn=new Map;ln(globalThis,wn,{value:bn});const vn=new Proxy(bn,{get:(e,n)=>e.get(n),has:(e,n)=>e.has(n),ownKeys:e=>[...e.keys()]}),En=(e,n)=>!n.startsWith("_"),Mn=(e,n)=>new Proxy(e,{has:En,get:(e,t)=>e[n][t]}),kn=(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}`,Mn(r,e));n.registerJSModule(t,s,r)},On=(e,n)=>import(e).then((e=>{bn.set(n,{...e})})),Pn=e=>new Promise(((n,t)=>{document.querySelector(`link[href="${e}"]`)&&n(),document.head.append(sn(document.createElement("link"),{rel:"stylesheet",href:e,onload:n,onerror:t}))})),Tn=e=>/\.css/i.test(new URL(e).pathname),Rn=!globalThis.window,Sn=({FS:e,PATH:n,PATH_FS:t},r,s)=>{const o=t.resolve(r),a=n.dirname(o);return e.mkdirTree?e.mkdirTree(a):xn(e,a),e.writeFile(o,new Uint8Array(s),{canOwn:!0})},Dn=e=>{const n=e.split("/");return n.pop(),n.join("/")},xn=(e,n)=>{const t=[];for(const r of n.split("/"))"."!==r&&".."!==r&&(t.push(r),r&&e.mkdir(t.join("/")))},jn=(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(/^\/+/,"/")},An=e=>{const n=e.map((e=>e.trim().replace(/(^[/]*|[/]*$)/g,""))).filter((e=>""!==e&&"."!==e)).join("/");return e[0].startsWith("/")?`/${n}`:n},Nn=(e,n)=>a(dn(e,n)).arrayBuffer(),Cn=(e,n,t,r)=>pn((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(rn(r))return r.map((t=>({url:An([e,t]),path:An([n,t])})));const s=t||e.slice(1+e.lastIndexOf("/"));return[{url:e,path:An([n,s])}]}))})(t).map((({url:t,path:s})=>Nn(t,r).then((t=>e.writeFile(n,s,t)))))),Wn=(e,n)=>n.endsWith("/")?`${n}${e.split("/").pop()}`:n,Ln=(e,n)=>e.replace(/\{.+?\}/g,(e=>{if(!n.has(e))throw new SyntaxError(`Invalid template: ${e}`);return n.get(e)})),Hn=(e,n,t,r)=>pn((e=>{const n=new Map,t=new Set,r=[];for(const[s,o]of cn(e))if(/^\{.+\}$/.test(s)){if(n.has(s))throw new SyntaxError(`Duplicated template: ${s}`);n.set(s,Ln(o,n))}else{const e=Ln(s,n),a=Wn(e,Ln(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})=>Nn(t,r).then((r=>e.writeFile(n,s,r,t)))))),$n=({main:e,worker:n},t)=>{const r=[];if(n&&Rn)for(let[e,s]of cn(n))e=dn(e,t),r.push(On(e,s));if(e&&!Rn)for(let[n,s]of cn(e))n=dn(n,t),Tn(n)?Pn(n):r.push(On(n,s));return pn(r)},{assign:In}=Object,Un="entries",zn="readonly",Fn="readwrite",Bn={durability:"default",prefix:"IDBMap"},qn=({target:{result:e}})=>e;class Jn extends EventTarget{#e;#n;#t;async#r(e,n){const t=(await this.#e).transaction(Un,n,this.#n);return new Promise(((n,r)=>In(e(t.objectStore(Un)),{onsuccess:n,onerror:r})))}constructor(e,{durability:n=Bn.durability,prefix:t=Bn.prefix}=Bn){super(),this.#t=t,this.#n={durability:n},this.#e=new Promise(((n,t)=>{In(indexedDB.open(`${this.#t}/${e}`),{onupgradeneeded({target:{result:e,transaction:t}}){e.objectStoreNames.length||e.createObjectStore(Un),t.oncomplete=()=>n(e)},onsuccess(e){n(qn(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?In(new Event(n),{message:t}):e)}async close(){(await this.#e).close()}get size(){return this.#r((e=>e.count()),zn).then(qn)}async clear(){await this.#r((e=>e.clear()),Fn)}async delete(e){await this.#r((n=>n.delete(e)),Fn)}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)),zn).then(qn)}async has(e){return void 0!==await this.#r((n=>n.getKey(e)),zn).then(qn)}async keys(){return await this.#r((e=>e.getAllKeys()),zn).then(qn)}async set(e,n){return await this.#r((t=>t.put(n,e)),Fn),this}async values(){const e=await this.keys();return Promise.all(e.map((e=>this.get(e))))}get[Symbol.toStringTag](){return this.#t}}class Gn extends Map{#s;#o;constructor(...e){super(),this.#s=new Jn(...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 Yn=new WeakMap,Kn=(e,n,t)=>{"polyscript"===n&&(t.lazy_py_modules=async(...n)=>(await Yn.get(e)(n),n.map((n=>e.pyimport(n)))),t.storage=async e=>{const n=new Gn(e);return await n.sync(),n},t.JSON=v),e.registerJsModule(n,t)},Vn=(e,n)=>{if(e.endsWith("/*")){if(/\.(zip|whl|tgz|tar(?:\.gz)?)$/.test(n))return RegExp.$1;throw new Error(`Unsupported archive ${n}`)}return""},Xn=(e,n,...t)=>{try{return e.runPython(nn(n),...t)}catch(n){Xe.get(e).stderr(n)}},Zn=async(e,n,...t)=>{try{return await e.runPythonAsync(nn(n),...t)}catch(n){Xe.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){Xe.get(e).stderr(n)}};var et=(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 nt=async e=>(await import("./toml-DiUM0_qs.js")).parse(e),tt=(e,n)=>{try{e.mkdir(n)}catch(e){}};var rt={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}=Ze({stderr:en(console.error),stdout:en(console.log)});t=t.replace(/\.m?js$/,".wasm");const i=await a(e({linebuffer:!1,stderr:s,stdout:o,url:t})),l=st.bind(this,i,r);return Yn.set(i,l),n.files&&await Hn(this,i,n.files,r),n.fetch&&await Cn(this,i,n.fetch,r),n.js_modules&&await $n(n.js_modules,r),this.writeFile(i,"./mip.py",et),n.packages&&await l(n.packages),i},registerJSModule:Kn,run:Xn,runAsync:Zn,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=Vn(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)tt(s,i);else{tt(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 Sn(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 Sn(i,n,t)}};async function st(e,n,t){let r;for(const s of t)if(s.endsWith(".whl")){const t=dn(s,n),r=await a(t).arrayBuffer();await this.writeFile(e,"./*",r,t)}else r||(r=e.pyimport("mip")),r.install(s)}const ot={dict_converter:Object.fromEntries};let at=!1;const it=e=>(...n)=>{try{return at=!0,e(...n)}finally{at=!1}};let lt=!1;const ct=()=>{if(lt)return;lt=!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){at=!1;let o=e.get(s)?.deref();if(!o)try{o=be(s.copy(),n),e.set(s,new WeakRef(o))}catch(e){console.error(e)}o&&(t[r]=o),at=!0}}},{call:r}=Function,s=r.bind(r,r.apply);Object.defineProperties(Function.prototype,{apply:{value(e,n){return at&&t(n),s(this,e,n)}},call:{value(e,...n){return at&&t(n),s(this,e,n)}}})};var pt={type:"pyodide",module:(e="0.26.1")=>`https://cdn.jsdelivr.net/pyodide/v${e}/full/pyodide.mjs`,async engine({loadPyodide:e},n,t,r){Rn||"auto"!==n.experimental_create_proxy||ct();const{stderr:s,stdout:o,get:a}=Ze(),i=t.slice(0,t.lastIndexOf("/")),l=await a(e({stderr:s,stdout:o,indexURL:i})),c=ft.bind(l);return Yn.set(l,c),n.files&&await Hn(this,l,n.files,r),n.fetch&&await Cn(this,l,n.fetch,r),n.js_modules&&await $n(n.js_modules,r),n.packages&&await c(n.packages),l},registerJSModule:Kn,run:it(Xn),runAsync:it(Zn),runEvent:it(Qn),transform:({ffi:{PyProxy:e}},n)=>n instanceof e?n.toJs(ot):n,writeFile:(e,n,t,r)=>{const s=Vn(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 Sn({FS:o,PATH:a,PATH_FS:i},n,t)}};async function ft(e){await this.loadPackage("micropip");const n=this.pyimport("micropip");await n.install(e,{keep_going:!0}),n.destroy()}const dt="ruby-wasm-wasi",ut=dt.replace(/\W+/g,"_");var mt={type:dt,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 Hn(this,i,n.files,r),n.fetch&&await Cn(this,i,n.fetch,r),n.js_modules&&await $n(n.js_modules,r),i},registerJSModule(e,n,t){n=n.replace(/\W+/g,"__");const r=`__module_${ut}_${n}`;globalThis[r]=t,this.run(e,`require "js";$${n}=JS.global[:${r}]`),delete globalThis[r]},run:(e,n,...t)=>e.eval(nn(n),...t),runAsync:(e,n,...t)=>e.evalAsync(nn(n),...t),async runEvent(e,n,t){if(/^xworker\.(on\w+)$/.test(n)){const{$1:n}=RegExp,r=`__module_${ut}_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 ${dt}`)}};var ht={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}=Ze(),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 Hn(this,l,t.files,s),t.fetch&&await Cn(this,l,t.fetch,s),t.js_modules&&await $n(t.js_modules,s),l},registerJSModule:(e,n,t)=>{e.global.set(n,t)},run:(e,n,...t)=>{try{return e.doStringSync(nn(n),...t)}catch(n){Xe.get(e).stderr(n)}},runAsync:async(e,n,...t)=>{try{return await e.doString(nn(n),...t)}catch(n){Xe.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){Xe.get(e).stderr(n)}},transform:(e,n)=>n,writeFile:({cmodule:{module:{FS:e}}},n,t)=>((e,n,t)=>(xn(e,Dn(n)),n=jn(e,n),e.writeFile(n,new Uint8Array(t),{canOwn:!0})))(e,n,t)};const yt=new WeakMap,gt=async(e,n)=>{const{shelter:t,destroy:r,io:s}=yt.get(e),{output:o,result:a}=await t.captureR(nn(n));for(const{type:e,data:n}of o)s[e](n);return be(a,r,{token:!1})};var _t={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}=Ze(),o=new e.WebR;await s(o.init().then((()=>o)));const a=await new o.Shelter;return yt.set(o,{module:e,shelter:a,destroy:a.destroy.bind(a),io:Xe.get(o)}),n.files&&await Hn(this,o,n.files,r),n.fetch&&await Cn(this,o,n.fetch,r),n.js_modules&&await $n(n.js_modules,r),o},registerJSModule(e,n){console.warn(`Experimental interpreter: module ${n} is not supported (yet)`)},run:gt,runAsync:gt,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 wt=new Map,bt=new Map,vt=[],Et=[],Mt=new Proxy(new Map,{get(e,n){if(!e.has(n)){const[t,...r]=n.split("@"),s=wt.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=>(bt.set(n,e),s(r,e,t,o))))}}),kt=e=>{for(const n of[].concat(e.type))wt.set(n,e),vt.push(`script[type="${n}"]`),Et.push(`${n}-`)};for(const e of[rt,pt,mt,ht,_t])kt(e);const{parse:Ot}=JSON,Pt=(e,n="./config.txt")=>{let t=typeof e;return"string"===t&&/\.(json|toml|txt)$/.test(e)?t=RegExp.$1:e=n,[dn(e),t]},Tt=e=>{try{return Ot(e)}catch(n){return nt(e)}},Rt=(e,n,t,r={})=>{if(n){const[e,s]=Pt(n,t);"json"===s?r=a(e).json():"toml"===s?r=a(e).text().then(nt):"string"===s?r=Tt(n):"object"===s&&n?r=n:"txt"===s&&"string"==typeof r&&(r=Tt(r)),n=e}return fn(r).then((t=>Mt[e](t,n)))},St=(e,n="")=>`${e}@${n}`.replace(/@$/,"");function Dt(e=this){return String(e).replace(/^(async\s*)?(\bfunction\b)?(.*?)\(/,((e,n,t,r)=>r&&!t?`${n||""}function ${r}(`:e))}const xt="BeforeRun",jt="AfterRun",At=[`code${xt}`,`code${xt}Async`,`code${jt}`,`code${jt}Async`],Nt=["onWorker","onReady",`on${xt}`,`on${xt}Async`,`on${jt}`,`on${jt}Async`];function Ct(e,n){const{run:t,runAsync:r}=wt.get(this.type);return{...e,run:t.bind(this,n),runAsync:r.bind(this,n)}}const Wt=(e,n,t,r,s,o)=>{if(s||o){const a=Ct.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 Lt=class{constructor(e,n={}){const{main:t,worker:r}=n;this.interpreter=e,this.onWorker=t?.onWorker;for(const e of Nt.slice(1))this[e]=r?.[e];for(const e of At)this[e]=r?.[e]}toJSON(){const e={};for(const n of Nt.slice(1))this[n]&&(e[n]=Dt(this[n]));for(const n of At)this[n]&&(e[n]=nn(this[n]()));return e}};var Ht=(...e)=>function(n,t){const r=new Worker(URL.createObjectURL(new Blob(['const e="object"==typeof self?self:globalThis,t=t=>((t,n)=>{const r=(e,n)=>(t.set(n,e),e),s=o=>{if(t.has(o))return t.get(o);const[a,i]=n[o];switch(a){case 0:case-1:return r(i,o);case 1:{const e=r([],o);for(const t of i)e.push(s(t));return e}case 2:{const e=r({},o);for(const[t,n]of i)e[s(t)]=s(n);return e}case 3:return r(new Date(i),o);case 4:{const{source:e,flags:t}=i;return r(new RegExp(e,t),o)}case 5:{const e=r(new Map,o);for(const[t,n]of i)e.set(s(t),s(n));return e}case 6:{const e=r(new Set,o);for(const t of i)e.add(s(t));return e}case 7:{const{name:t,message:n}=i;return r(new e[t](n),o)}case 8:return r(BigInt(i),o);case"BigInt":return r(Object(BigInt(i)),o)}return r(new e[a](i),o)};return s})(new Map,t)(0),n="",{toString:r}={},{keys:s}=Object,o=e=>{const t=typeof e;if("object"!==t||!e)return[0,t];const s=r.call(e).slice(8,-1);switch(s){case"Array":return[1,n];case"Object":return[2,n];case"Date":return[3,n];case"RegExp":return[4,n];case"Map":return[5,n];case"Set":return[6,n]}return s.includes("Array")?[1,s]:s.includes("Error")?[7,s]:[2,s]},a=([e,t])=>0===e&&("function"===t||"symbol"===t),i=(e,{json:t,lossy:n}={})=>{const r=[];return((e,t,n,r)=>{const i=(e,t)=>{const s=r.push(e)-1;return n.set(t,s),s},c=r=>{if(n.has(r))return n.get(r);let[l,p]=o(r);switch(l){case 0:{let t=r;switch(p){case"bigint":l=8,t=r.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+p);t=null;break;case"undefined":return i([-1],r)}return i([l,t],r)}case 1:{if(p)return i([p,[...r]],r);const e=[],t=i([l,e],r);for(const t of r)e.push(c(t));return t}case 2:{if(p)switch(p){case"BigInt":return i([p,r.toString()],r);case"Boolean":case"Number":case"String":return i([p,r.valueOf()],r)}if(t&&"toJSON"in r)return c(r.toJSON());const n=[],u=i([l,n],r);for(const t of s(r))!e&&a(o(r[t]))||n.push([c(t),c(r[t])]);return u}case 3:return i([l,r.toISOString()],r);case 4:{const{source:e,flags:t}=r;return i([l,{source:e,flags:t}],r)}case 5:{const t=[],n=i([l,t],r);for(const[n,s]of r)(e||!a(o(n))&&!a(o(s)))&&t.push([c(n),c(s)]);return n}case 6:{const t=[],n=i([l,t],r);for(const n of r)!e&&a(o(n))||t.push(c(n));return n}}const{message:u}=r;return i([l,{name:p,message:u}],r)};return c})(!(t||n),!!t,new Map,r)(e),r},{parse:c,stringify:l}=JSON,p={json:!0,lossy:!0};var u=Object.freeze({__proto__:null,parse:e=>t(c(e)),stringify:e=>l(i(e,p))});const f="64e10b34-2bf7-4616-9668-f99de5aa046e",h="M"+f,d="T"+f,g="array",y="function",w="null",m="number",_="object",b="string",E="symbol",v="undefined",k="apply",x="construct",T="defineProperty",S="deleteProperty",A="get",j="getOwnPropertyDescriptor",O="getPrototypeOf",$="has",R="isExtensible",P="ownKeys",N="preventExtensions",M="set",I="setPrototypeOf",F="delete",{isArray:W}=Array;let{SharedArrayBuffer:H,window:D}=globalThis,{notify:C,wait:L,waitAsync:B}=Atomics,U=null;B||(B=e=>({value:new Promise((t=>{let n=new Worker("data:application/javascript,onmessage%3D(%7Bdata%3Ab%7D)%3D%3E(Atomics.wait(b%2C0)%2CpostMessage(0))");n.onmessage=t,n.postMessage(e)}))}));try{new H(4)}catch(e){H=ArrayBuffer;const t=new WeakMap;if(D){const e=new Map,{prototype:{postMessage:n}}=Worker,r=t=>{const n=t.data?.[f];if(!W(n)){t.stopImmediatePropagation();const{id:r,sb:s}=n;e.get(r)(s)}};U=function(e,...s){const o=e?.[f];if(W(o)){const[e,n]=o;t.set(n,e),this.addEventListener("message",r)}return n.call(this,e,...s)},B=n=>({value:new Promise((r=>{e.set(t.get(n),r)})).then((r=>{e.delete(t.get(n)),t.delete(n);for(let e=0;e<r.length;e++)n[e]=r[e];return"ok"}))})}else{const e=(e,t)=>({[f]:{id:e,sb:t}});C=n=>{postMessage(e(t.get(n),n))},addEventListener("message",(e=>{const n=e.data?.[f];if(W(n)){const[e,r]=n;t.set(r,e)}}))}}\n/*! (c) Andrea Giammarchi - ISC */const{Int32Array:q,Map:J,Uint16Array:z}=globalThis,{BYTES_PER_ELEMENT:G}=q,{BYTES_PER_ELEMENT:K}=z,Y=new WeakSet,X=new WeakMap,V={value:{then:e=>e()}};let Z=0;const Q=(e,{parse:t=JSON.parse,stringify:n=JSON.stringify,transform:r,interrupt:s}=JSON)=>{if(!X.has(e)){const o=U||e.postMessage,a=(t,...n)=>o.call(e,{[f]:n},{transfer:t}),i=typeof s===y?s:s?.handler,c=s?.delay||42,l=new TextDecoder("utf-16"),p=(e,t)=>e?B(t,0):(i?((e,t,n)=>{for(;"timed-out"===L(e,0,0,t);)n()})(t,c,i):L(t,0),V);let u=!1;X.set(e,new Proxy(new J,{[$]:(e,t)=>"string"==typeof t&&!t.startsWith("_"),[A]:(n,s)=>"then"===s?null:(...n)=>{const o=Z++;let i=new q(new H(2*G)),c=[];Y.has(n.at(-1)||c)&&Y.delete(c=n.pop()),a(c,o,i,s,r?n.map(r):n);const f=e!==globalThis;let h=0;return u&&f&&(h=setTimeout(console.warn,1e3,`💀🔒 - Possible deadlock if proxy.${s}(...args) is awaited`)),p(f,i).value.then((()=>{clearTimeout(h);const e=i[1];if(!e)return;const n=K*e;return i=new q(new H(n+n%G)),a([],o,i),p(f,i).value.then((()=>t(l.decode(new z(i.buffer).slice(0,e)))))}))},[M](t,s,o){const a=typeof o;if(a!==y)throw new Error(`Unable to assign ${s} as ${a}`);if(!t.size){const s=new J;e.addEventListener("message",(async e=>{const o=e.data?.[f];if(W(o)){e.stopImmediatePropagation();const[a,i,...c]=o;let l;if(c.length){const[e,o]=c;if(t.has(e)){u=!0;try{const c=await t.get(e)(...o);if(void 0!==c){const e=n(r?r(c):c);s.set(a,e),i[1]=e.length}}catch(e){l=e}finally{u=!1}}else l=new Error(`Unsupported action: ${e}`);i[0]=1}else{const e=s.get(a);s.delete(a);for(let t=new z(i.buffer),n=0;n<e.length;n++)t[n]=e.charCodeAt(n)}if(C(i,0),l)throw l}}))}return!!t.set(s,o)}}))}return X.get(e)};Q.transfer=(...e)=>(Y.add(e),e);const{isArray:ee}=Array,te=(e,t)=>t,ne=e=>typeof e===y?(e=>e())(e):e;function re(){return this}const se=(e,t)=>e===g?[t]:{t:e,v:t},oe=(e,t=te)=>{let n=typeof e,r=e;return n===_&&(ee(e)?(n=g,r=e.at(0)):({t:n,v:r}=e)),t(n,r)},ae=(e,t)=>e===y?t:se(e,t),ie=(e,t=ae)=>{const n=null===e?w:typeof e;return t(n===_&&ee(e)?g:n,e)},ce=new FinalizationRegistry((([e,t,n])=>{n&&console.debug(`Held value ${String(t)} not relevant anymore`),e(t)})),le=Object.create(null),pe=(e,t,{debug:n,handler:r,return:s,token:o=e}=le)=>{const a=s||new Proxy(e,r||le),i=[a,[t,e,!!n]];return!1!==o&&i.push(o),ce.register(...i),a},{defineProperty:ue,deleteProperty:fe,getOwnPropertyDescriptor:he,getPrototypeOf:de,isExtensible:ge,ownKeys:ye,preventExtensions:we,set:me,setPrototypeOf:_e}=Reflect,{assign:be,create:Ee}=Object,ve=de(Int8Array),ke=(e,t)=>{const{get:n,set:r,value:s}=e;return n&&(e.get=t(n)),r&&(e.set=t(r)),s&&(e.value=t(s)),e},xe=e=>t=>ie(t,((t,n)=>{switch(t){case w:return se(w,n);case _:if(n===globalThis)return se(t,null);case g:case y:return e(t,n);case"boolean":case m:case b:case v:case"bigint":return se(t,n);case E:{if(Te.has(n))return se(t,Te.get(n));let e=Symbol.keyFor(n);if(e)return se(t,`.${e}`)}}throw new TypeError(`Unable to handle this ${t}: ${String(n)}`)})),Te=new Map(ye(Symbol).filter((e=>typeof Symbol[e]===E)).map((e=>[Symbol[e],e]))),Se=e=>{if(e.startsWith("."))return Symbol.for(e.slice(1));for(const[t,n]of Te)if(n===e)return t},Ae=e=>e;var je=((e,t)=>{const n=new WeakMap;{const{addEventListener:e}=EventTarget.prototype;ue(EventTarget.prototype,"addEventListener",{value(t,r,...s){return s.at(0)?.invoke&&(n.has(this)||n.set(this,new Map),n.get(this).set(t,[].concat(s[0].invoke)),delete s[0].invoke),e.call(this,t,r,...s)}})}return function(t,r,s,...o){let a=0,i=this?.transform||Ae;const c=new Map,l=new Map,{[s]:p}=t,u=o.length?be(Ee(globalThis),...o):globalThis,f=xe(((e,t)=>{if(!c.has(t)){let n;for(;l.has(n=a++););c.set(t,n),l.set(n,e===y?t:i(t))}return se(e,c.get(t))})),h=e=>{p(F,se(b,e))},d=(e,t)=>{switch(e){case _:if(null==t)return u;case g:if(typeof t===m)return l.get(t);if(!(t instanceof ve))for(const e in t)t[e]=w(t[e]);return t;case y:if(typeof t===b){const e=l.get(t)?.deref();if(e)return e;const r=function(...e){return e.at(0)instanceof Event&&(e=>{const{currentTarget:t,target:r,type:s}=e;for(const o of n.get(t||r)?.get(s)||[])e[o]()})(...e),p(k,se(y,t),f(this),e.map(f))};return l.set(t,new WeakRef(r)),pe(t,h,{return:r,token:!1})}return l.get(t);case E:return Se(t)}return t},w=e=>oe(e,d),W={[k]:(e,t,n)=>f(e.apply(t,n)),[x]:(e,t)=>f(new e(...t)),[T]:(e,t,n)=>f(ue(e,t,n)),[S]:(e,t)=>f(fe(e,t)),[O]:e=>f(de(e)),[A]:(e,t)=>f(e[t]),[j]:(e,t)=>{const n=he(e,t);return n?se(_,ke(n,f)):se(v,n)},[$]:(e,t)=>f(t in e),[R]:e=>f(ge(e)),[P]:e=>se(g,ye(e).map(f)),[N]:e=>f(we(e)),[M]:(e,t,n)=>f(me(e,t,n)),[I]:(e,t)=>f(_e(e,t)),[F](e){c.delete(l.get(e)),l.delete(e)}};return t[r]=(e,t,...n)=>{switch(e){case k:n[0]=w(n[0]),n[1]=n[1].map(w);break;case x:n[0]=n[0].map(w);break;case T:{const[e,t]=n;n[0]=w(e);const{get:r,set:s,value:o}=t;r&&(t.get=w(r)),s&&(t.set=w(s)),o&&(t.value=w(o));break}default:n=n.map(w)}return W[e](w(t),...n)},{proxy:t,[e.toLowerCase()]:u,[`is${e}Proxy`]:()=>!1}}})("Window"),Oe=(e=>{let t=0;const n=new Map,r=new Map,s=Symbol();return function(o,a,i){const c=this?.transform||Ae,{[a]:l}=o,p=new Map,u=e=>{p.delete(e),l(F,f(e))},f=xe(((e,o)=>{if(s in o)return ne(o[s]);if(e===y){if(o=c(o),!r.has(o)){let e;for(;r.has(e=String(t++)););n.set(o,e),r.set(e,o)}return se(e,n.get(o))}if(!(o instanceof ve)){o=c(o);for(const e in o)o[e]=f(o[e])}return se(e,o)})),h=(e,t,n)=>{const r=p.get(n)?.deref();if(r)return r;const s=t===y?(e=>re.bind(e))(e):e,o=new Proxy(s,v);return p.set(n,new WeakRef(o)),pe(n,u,{return:o,token:!1})},d=e=>oe(e,((t,n)=>{switch(t){case _:if(null===n)return globalThis;case g:return typeof n===m?h(e,t,n):n;case y:return typeof n===b?r.get(n):h(e,t,n);case E:return Se(n)}return n})),w=(e,t,...n)=>d(l(e,ne(t),...n)),v={[k]:(e,t,n)=>w(k,e,f(t),n.map(f)),[x]:(e,t)=>w(x,e,t.map(f)),[T]:(e,t,n)=>{const{get:r,set:s,value:o}=n;return typeof r===y&&(n.get=f(r)),typeof s===y&&(n.set=f(s)),typeof o===y&&(n.value=f(o)),w(T,e,f(t),n)},[S]:(e,t)=>w(S,e,f(t)),[O]:e=>w(O,e),[A]:(e,t)=>t===s?e:w(A,e,f(t)),[j]:(e,t)=>{const n=w(j,e,f(t));return n&&ke(n,d)},[$]:(e,t)=>t===s||w($,e,f(t)),[R]:e=>w(R,e),[P]:e=>w(P,e).map(d),[N]:e=>w(N,e),[M]:(e,t,n)=>w(M,e,f(t),f(n)),[I]:(e,t)=>w(I,e,f(t))};o[i]=(e,t,s,o)=>{switch(e){case k:return d(t).apply(d(s),o.map(d));case F:{const e=d(t);n.delete(r.get(e)),r.delete(e)}}};const W=new Proxy(se(_,null),v);return{[e.toLowerCase()]:W,[`is${e}Proxy`]:e=>typeof e===_&&!!e&&s in e,proxy:o}}})("Window"),$e=typeof Worker===y?Worker:class{};const Re=new WeakMap,Pe=(e,...t)=>{const n=Q(e,...t);if(!Re.has(n)){const r=e instanceof $e?je:Oe;Re.set(n,r.call(t.at(0),n,h,d))}return Re.get(n)};Pe.transfer=Q.transfer;const Ne={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}},Me=new WeakMap,Ie=e=>{const t=e||console,n={buffered:We,stderr:(t.stderr||console.error).bind(t),stdout:(t.stdout||console.log).bind(t)};return{stderr:(...e)=>n.stderr(...e),stdout:(...e)=>n.stdout(...e),async get(e){const t=await e;return Me.set(t,n),t}}},Fe=new TextDecoder,We=(e,t=10)=>{const n=[];return r=>{if(r instanceof Uint8Array)for(const s of r)s===t?e(Fe.decode(new Uint8Array(n.splice(0)))):n.push(s);else e(r)}},He=(e,...t)=>Ne[typeof e](e,...t),{isArray:De}=Array,{assign:Ce,create:Le,defineProperties:Be,defineProperty:Ue,entries:qe}=Object,{all:Je,resolve:ze}=new Proxy(Promise,{get:(e,t)=>e[t].bind(e)}),Ge=(e,t=location.href)=>new URL(e,t.replace(/^blob:/,"")).href,Ke=(e,t,n,r=!1,s=CustomEvent)=>{e.dispatchEvent(new s(`${t}:${n}`,{bubbles:!0,detail:{worker:r}}))},Ye=e=>Function(`\'use strict\';return (${e})`)(),Xe=e=>e.replace(/^(?:\\n|\\r\\n)/,""),Ve=Symbol.for("polyscript.js_modules"),Ze=new Map;Ue(globalThis,Ve,{value:Ze}),new Proxy(Ze,{get:(e,t)=>e.get(t),has:(e,t)=>e.has(t),ownKeys:e=>[...e.keys()]});const Qe=(e,t)=>!t.startsWith("_"),et=(e,t)=>new Proxy(e,{has:Qe,get:(e,n)=>e[t][n]}),tt=(e,t)=>import(e).then((e=>{Ze.set(t,{...e})})),nt=e=>new Promise(((t,n)=>{document.querySelector(`link[href="${e}"]`)&&t(),document.head.append(Ce(document.createElement("link"),{rel:"stylesheet",href:e,onload:t,onerror:n}))})),rt=e=>/\\.css/i.test(new URL(e).pathname),st=(e,t)=>e.has(t),ot=e=>[...e.keys()];var at=(e,t,n,r)=>{const s=globalThis[Ve];if(n)for(let[e,t]of qe(n)){let n=s.get(t);n&&!De(n)||(s.set(t,n||(n=[])),n.push(e))}return((e,t,n,r)=>new Proxy(e,{has:st,ownKeys:ot,get:(e,s)=>{let o=e.get(s);if(De(o)){let a=o;o=null;for(let e of a)e=Ge(e,r),rt(e)?n.importCSS(e):(n.importJS(e,s),o=t[Ve].get(s));e.set(s,o)}return o}}))(s,e,t,r)};const it=Object.getOwnPropertyDescriptors(Response.prototype),ct=e=>"function"==typeof e,lt={get:(e,t)=>it.hasOwnProperty(t)?((e,t,{get:n,value:r})=>n||!ct(r)?e.then((e=>e[t])):(...n)=>e.then((e=>e[t](...n))))(e,t,it[t]):((e,t)=>ct(t)?t.bind(e):t)(e,e[t])};var pt=(e,...t)=>new Proxy(fetch(e,...t),lt);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 ut=!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):dt(e,a),e.writeFile(o,new Uint8Array(s),{canOwn:!0})},ht=e=>{const t=e.split("/");return t.pop(),t.join("/")},dt=(e,t)=>{const n=[];for(const r of t.split("/"))"."!==r&&".."!==r&&(n.push(r),r&&e.mkdir(n.join("/")))},gt=(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(/^\\/+/,"/")},yt=e=>{const t=e.map((e=>e.trim().replace(/(^[/]*|[/]*$)/g,""))).filter((e=>""!==e&&"."!==e)).join("/");return e[0].startsWith("/")?`/${t}`:t},wt=(e,t)=>pt(Ge(e,t)).arrayBuffer(),mt=(e,t,n,r)=>Je((e=>{for(const{files:t,to_file:n,from:r=""}of e){if(void 0!==t&&void 0!==n)throw new Error("Cannot use \'to_file\' and \'files\' parameters together!");if(void 0===t&&void 0===n&&r.endsWith("/"))throw new Error(`Couldn\'t determine the filename from the path ${r}, please supply \'to_file\' parameter.`)}return e.flatMap((({from:e="",to_folder:t=".",to_file:n,files:r})=>{if(De(r))return r.map((n=>({url:yt([e,n]),path:yt([t,n])})));const s=n||e.slice(1+e.lastIndexOf("/"));return[{url:e,path:yt([t,s])}]}))})(n).map((({url:n,path:s})=>wt(n,r).then((n=>e.writeFile(t,s,n)))))),_t=(e,t)=>t.endsWith("/")?`${t}${e.split("/").pop()}`:t,bt=(e,t)=>e.replace(/\\{.+?\\}/g,(e=>{if(!t.has(e))throw new SyntaxError(`Invalid template: ${e}`);return t.get(e)})),Et=(e,t,n,r)=>Je((e=>{const t=new Map,n=new Set,r=[];for(const[s,o]of qe(e))if(/^\\{.+\\}$/.test(s)){if(t.has(s))throw new SyntaxError(`Duplicated template: ${s}`);t.set(s,bt(o,t))}else{const e=bt(s,t),a=_t(e,bt(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})=>wt(n,r).then((r=>e.writeFile(t,s,r,n)))))),vt=({main:e,worker:t},n)=>{const r=[];if(t&&ut)for(let[e,s]of qe(t))e=Ge(e,n),r.push(tt(e,s));if(e&&!ut)for(let[t,s]of qe(e))t=Ge(t,n),rt(t)?nt(t):r.push(tt(t,s));return Je(r)},{assign:kt}=Object,xt="entries",Tt="readonly",St="readwrite",At={durability:"default",prefix:"IDBMap"},jt=({target:{result:e}})=>e;class Ot extends EventTarget{#e;#t;#n;async#r(e,t){const n=(await this.#e).transaction(xt,t,this.#t);return new Promise(((t,r)=>kt(e(n.objectStore(xt)),{onsuccess:t,onerror:r})))}constructor(e,{durability:t=At.durability,prefix:n=At.prefix}=At){super(),this.#n=n,this.#t={durability:t},this.#e=new Promise(((t,n)=>{kt(indexedDB.open(`${this.#n}/${e}`),{onupgradeneeded({target:{result:e,transaction:n}}){e.objectStoreNames.length||e.createObjectStore(xt),n.oncomplete=()=>t(e)},onsuccess(e){t(jt(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?kt(new Event(t),{message:n}):e)}async close(){(await this.#e).close()}get size(){return this.#r((e=>e.count()),Tt).then(jt)}async clear(){await this.#r((e=>e.clear()),St)}async delete(e){await this.#r((t=>t.delete(e)),St)}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)),Tt).then(jt)}async has(e){return void 0!==await this.#r((t=>t.getKey(e)),Tt).then(jt)}async keys(){return await this.#r((e=>e.getAllKeys()),Tt).then(jt)}async set(e,t){return await this.#r((n=>n.put(t,e)),St),this}async values(){const e=await this.keys();return Promise.all(e.map((e=>this.get(e))))}get[Symbol.toStringTag](){return this.#n}}class $t extends Map{#s;#o;constructor(...e){super(),this.#s=new Ot(...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 Rt=new WeakMap,Pt=(e,t,n)=>{"polyscript"===t&&(n.lazy_py_modules=async(...t)=>(await Rt.get(e)(t),t.map((t=>e.pyimport(t)))),n.storage=async e=>{const t=new $t(e);return await t.sync(),t},n.JSON=u),e.registerJsModule(t,n)},Nt=(e,t)=>{if(e.endsWith("/*")){if(/\\.(zip|whl|tgz|tar(?:\\.gz)?)$/.test(t))return RegExp.$1;throw new Error(`Unsupported archive ${t}`)}return""},Mt=(e,t,...n)=>{try{return e.runPython(He(t),...n)}catch(t){Me.get(e).stderr(t)}},It=async(e,t,...n)=>{try{return await e.runPythonAsync(He(t),...n)}catch(t){Me.get(e).stderr(t)}},Ft=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){Me.get(e).stderr(t)}};var Wt=(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 Ht=async e=>(await import("./toml-DiUM0_qs.js")).parse(e),Dt=(e,t)=>{try{e.mkdir(t)}catch(e){}};var Ct={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}=Ie({stderr:We(console.error),stdout:We(console.log)});n=n.replace(/\\.m?js$/,".wasm");const i=await a(e({linebuffer:!1,stderr:s,stdout:o,url:n})),c=Lt.bind(this,i,r);return Rt.set(i,c),t.files&&await Et(this,i,t.files,r),t.fetch&&await mt(this,i,t.fetch,r),t.js_modules&&await vt(t.js_modules,r),this.writeFile(i,"./mip.py",Wt),t.packages&&await c(t.packages),i},registerJSModule:Pt,run:Mt,runAsync:It,runEvent:Ft,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=Nt(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-CGWtiqjJ.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)Dt(s,i);else{Dt(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 Lt(e,t,n){let r;for(const s of n)if(s.endsWith(".whl")){const n=Ge(s,t),r=await pt(n).arrayBuffer();await this.writeFile(e,"./*",r,n)}else r||(r=e.pyimport("mip")),r.install(s)}const Bt={dict_converter:Object.fromEntries};let Ut=!1;const qt=e=>(...t)=>{try{return Ut=!0,e(...t)}finally{Ut=!1}};let Jt=!1;const zt=()=>{if(Jt)return;Jt=!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){Ut=!1;let o=e.get(s)?.deref();if(!o)try{o=pe(s.copy(),t),e.set(s,new WeakRef(o))}catch(e){console.error(e)}o&&(n[r]=o),Ut=!0}}},{call:r}=Function,s=r.bind(r,r.apply);Object.defineProperties(Function.prototype,{apply:{value(e,t){return Ut&&n(t),s(this,e,t)}},call:{value(e,...t){return Ut&&n(t),s(this,e,t)}}})};var Gt={type:"pyodide",module:(e="0.26.1")=>`https://cdn.jsdelivr.net/pyodide/v${e}/full/pyodide.mjs`,async engine({loadPyodide:e},t,n,r){ut||"auto"!==t.experimental_create_proxy||zt();const{stderr:s,stdout:o,get:a}=Ie(),i=n.slice(0,n.lastIndexOf("/")),c=await a(e({stderr:s,stdout:o,indexURL:i})),l=Kt.bind(c);return Rt.set(c,l),t.files&&await Et(this,c,t.files,r),t.fetch&&await mt(this,c,t.fetch,r),t.js_modules&&await vt(t.js_modules,r),t.packages&&await l(t.packages),c},registerJSModule:Pt,run:qt(Mt),runAsync:qt(It),runEvent:qt(Ft),transform:({ffi:{PyProxy:e}},t)=>t instanceof e?t.toJs(Bt):t,writeFile:(e,t,n,r)=>{const s=Nt(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 Kt(e){await this.loadPackage("micropip");const t=this.pyimport("micropip");await t.install(e,{keep_going:!0}),t.destroy()}const Yt="ruby-wasm-wasi",Xt=Yt.replace(/\\W+/g,"_");var Vt={type:Yt,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 pt(n).arrayBuffer(),o=await WebAssembly.compile(s),{vm:a}=await e(o);return t.files&&await Et(this,a,t.files,r),t.fetch&&await mt(this,a,t.fetch,r),t.js_modules&&await vt(t.js_modules,r),a},registerJSModule(e,t,n){t=t.replace(/\\W+/g,"__");const r=`__module_${Xt}_${t}`;globalThis[r]=n,this.run(e,`require "js";$${t}=JS.global[:${r}]`),delete globalThis[r]},run:(e,t,...n)=>e.eval(He(t),...n),runAsync:(e,t,...n)=>e.evalAsync(He(t),...n),async runEvent(e,t,n){if(/^xworker\\.(on\\w+)$/.test(t)){const{$1:t}=RegExp,r=`__module_${Xt}_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 ${Yt}`)}};var Zt={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}=Ie(),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 Et(this,c,n.files,s),n.fetch&&await mt(this,c,n.fetch,s),n.js_modules&&await vt(n.js_modules,s),c},registerJSModule:(e,t,n)=>{e.global.set(t,n)},run:(e,t,...n)=>{try{return e.doStringSync(He(t),...n)}catch(t){Me.get(e).stderr(t)}},runAsync:async(e,t,...n)=>{try{return await e.doString(He(t),...n)}catch(t){Me.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){Me.get(e).stderr(t)}},transform:(e,t)=>t,writeFile:({cmodule:{module:{FS:e}}},t,n)=>((e,t,n)=>(dt(e,ht(t)),t=gt(e,t),e.writeFile(t,new Uint8Array(n),{canOwn:!0})))(e,t,n)};const Qt=new WeakMap,en=async(e,t)=>{const{shelter:n,destroy:r,io:s}=Qt.get(e),{output:o,result:a}=await n.captureR(He(t));for(const{type:e,data:t}of o)s[e](t);return pe(a,r,{token:!1})};var tn={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}=Ie(),o=new e.WebR;await s(o.init().then((()=>o)));const a=await new o.Shelter;return Qt.set(o,{module:e,shelter:a,destroy:a.destroy.bind(a),io:Me.get(o)}),t.files&&await Et(this,o,t.files,r),t.fetch&&await mt(this,o,t.fetch,r),t.js_modules&&await vt(t.js_modules,r),o},registerJSModule(e,t){console.warn(`Experimental interpreter: module ${t} is not supported (yet)`)},run:en,runAsync:en,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 nn=new Map,rn=new Map,sn=new Proxy(new Map,{get(e,t){if(!e.has(t)){const[n,...r]=t.split("@"),s=nn.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=>(rn.set(t,e),s(r,e,n,o))))}}),on=e=>{for(const t of[].concat(e.type))nn.set(t,e)};for(const e of[Ct,Gt,Vt,Zt,tn])on(e);const{parse:an}=JSON,cn=e=>{try{return an(e)}catch(t){return Ht(e)}},ln=(e,t,n,r={})=>{if(t){const[e,s]=((e,t="./config.txt")=>{let n=typeof e;return"string"===n&&/\\.(json|toml|txt)$/.test(e)?n=RegExp.$1:e=t,[Ge(e),n]})(t,n);"json"===s?r=pt(e).json():"toml"===s?r=pt(e).text().then(Ht):"string"===s?r=cn(t):"object"===s&&t?r=t:"txt"===s&&"string"==typeof r&&(r=cn(r)),t=e}return ze(r).then((n=>sn[e](n,t)))},pn="BeforeRun",un="AfterRun",fn=[`code${pn}`,`code${pn}Async`,`code${un}`,`code${un}Async`],hn=["onWorker","onReady",`on${pn}`,`on${pn}Async`,`on${un}`,`on${un}Async`];function dn(e,t){const{run:n,runAsync:r}=nn.get(this.type);return{...e,run:n.bind(this,t),runAsync:r.bind(this,t)}}const gn=(e,t,n,r,s,o)=>{if(s||o){const a=dn.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 yn,wn,mn;const _n=(e,t)=>{addEventListener(e,t||(async t=>{try{await yn,wn(`xworker.on${e}`,t)}catch(e){postMessage(e)}}),!!t&&{once:!0})},{parse:bn,stringify:En}=u,{proxy:vn,window:kn,isWindowProxy:xn}=Pe(self,{parse:bn,stringify:En,transform:e=>mn?mn(e):e}),Tn={sync:vn,window:kn,isWindowProxy:xn,onmessage:console.info,onerror:console.error,onmessageerror:console.warn,postMessage:postMessage.bind(self)};_n("message",(({data:{options:e,config:t,configURL:n,code:r,hooks:s}})=>{yn=(async()=>{try{const{id:o,tag:a,type:i,custom:c,version:l,config:p,async:u}=e,f=((e,t="")=>`${e}@${t}`.replace(/@$/,""))(i,l),h=await ln(f,t,n,p),{js_modules:d,sync_main_only:g}=rn.get(f),y=d?.main;let w=!g;try{new SharedArrayBuffer(4),w=!0}catch(e){if(w)throw new Error(["Unable to use SharedArrayBuffer due insecure environment.","Please read requirements in MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer#security_requirements"].join("\\n"))}const m=Le(nn.get(i)),_=((e,t,n,r)=>({type:t,config:n,interpreter:r,io:Me.get(r),run:(t,...n)=>e.run(r,t,...n),runAsync:(t,...n)=>e.runAsync(r,t,...n),runEvent:(...t)=>e.runEvent(r,...t)}))(m,c||i,p||{},h);let b="run";if(u&&(b+="Async"),s){let e,t,n="",r="";for(const e of fn){const t=s[e];if(t){const s=e.endsWith("Async");(s&&u||!s&&!u)&&(e.startsWith("codeBefore")?n=t:r=t)}}(n||r)&&((e,t,n,r)=>{const s=e[t].bind(e);e[t]="run"===t?(e,t,...o)=>{n&&s(e,n,...o);const a=s(e,Xe(t),...o);return r&&s(e,r,...o),a}:async(e,t,...o)=>{n&&await s(e,n,...o);const a=await s(e,Xe(t),...o);return r&&await s(e,r,...o),a}})(m,b,n,r);for(const n of hn.slice(2)){const r=s[n];if(r){const s=n.endsWith("Async");if(s&&u||!s&&!u){const s=Ye(r);n.startsWith("onBefore")?e=s:t=s}}}gn(m,_,Tn,u,e,t)}let E,v,k,x=null,T="";w&&(({CustomEvent:E,document:v}=kn),x=o&&v.getElementById(o)||null,k=e=>Ke(x,c||i,e,!0,E));const S=at(kn,vn,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}`,et(r,e));t.registerJSModule(n,s,r)})(i,m,h,S),m.registerJSModule(h,"polyscript",{xworker:Tn,currentScript:x,config:_.config,js_modules:S,get target(){return!T&&x&&("SCRIPT"===a?x.after(Ce(v.createElement(`script-${c||i}`),{id:T=`${o}-target`})):(T=o,x.replaceChildren(),x.style.display="block")),T}}),wn=m.runEvent.bind(m,h),mn=m.transform.bind(m,h),x&&k("ready"),s?.onReady&&Ye(s?.onReady).call(m,dn.call(m,_,h),Tn),await m[b](h,r),["micropython","pyodide"].includes(m.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 x&&k("done"),postMessage("polyscript:done"),h}catch(e){postMessage(e)}})(),_n("error"),_n("message"),_n("messageerror")}));\n'.replace(Be,qe)],{type:"application/javascript"})),{type:"module"}),{postMessage:s}=r,o=this instanceof Lt;if(e.length){const[n,r]=e;(t=sn({},t||{type:n,version:r})).type||(t.type=n)}const[i]=Pt(t.config,t.configURL),l=a(n).text().then((e=>{const n=o?this.toJSON():void 0;s.call(r,{options:t,config:i,code:e,hooks:n})})),c=sn(ze(r,v).proxy,{importJS:On,importCSS:Pn}),p=Promise.withResolvers();return an(r,{sync:{value:c},ready:{value:p.promise},postMessage:{value:(e,...n)=>l.then((()=>s.call(r,e,...n)))},onerror:{writable:!0,configurable:!0,value:console.error}}),r.addEventListener("message",(e=>{const{data:n}=e,t=n instanceof Error;(t||"polyscript:done"===n)&&(e.stopImmediatePropagation(),t?(p.reject(n),r.onerror(on(e,{type:{value:"error"},error:{value:n}}))):p.resolve(r))})),o&&this.onWorker?.(this.interpreter,r),r};const $t="Invalid content";var It=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=tn(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([nn(r)],{type:"text/plain"}))}return r}if(n&&e.textContent.replace(/\/\*[\s\S]*?\*\//g,"").replace(/^\s*(?:\/\/|#).*/gm,"").trim())throw new SyntaxError($t)};const Ut=(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)},zt=new WeakMap,Ft={get(){let e=zt.get(this);return e||(e=document.createElement(`${this.type}-script`),zt.set(this,e),Yt(this)),e},set(e){"string"==typeof e?zt.set(this,Ut(this,e)):(zt.set(this,e),Yt(this))}},Bt=new WeakMap,qt=new Map,Jt=(e,n)=>{const t=e?.value;return t?n+t:""},Gt=(e,n,t,r,s,o,a=e)=>{if(!qt.has(n)){const i={interpreter:Rt(t,s,o),queue:fn(),XWorker:Ht(e,r)};qt.set(n,i),qt.has(e)||qt.set(e,i),qt.has(a)||qt.set(a,i)}return qt.get(n)},Yt=async e=>{if(Bt.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:f}=e,d=l?.value,u=St(f,d);let m=Jt(t,"|");const h=Jt(r,"")||`${u}${m}`;m=m.slice(1);const y=It(e);if(y){const t=new(Ht(f,d))(y,{...mn(e,f),async:!!n,config:m});Bt.set(ln(e,"xworker",{value:t}),{xworker:t});const r=s?.value;return void(r&&i[r].resolve(t.ready))}const g=Jt(o,""),_=Gt(f,h,u,d,m);Bt.set(ln(e,"target",Ft),_),g&&zt.set(e,Ut(e,g));const w=p?a(p).text():e.textContent;_.queue=_.queue.then((()=>(async(e,n,t,r)=>{const{type:s}=e,o=wt.get(s);o.experimental&&console.warn(`The ${s} interpreter is experimental`);const[a,i]=await pn([Bt.get(e).interpreter,n]);try{ln(document,"currentScript",{configurable:!0,get:()=>e}),kn(s,o,a,vn),o.registerJSModule(a,"polyscript",{XWorker:t,currentScript:e,js_modules:vn,workers:c}),hn(e,s,"ready");const n=o[r?"runAsync":"run"](a,i),l=hn.bind(null,e,s,"done");return r?n.then(l):l(),n}finally{delete document.currentScript}})(e,w,_.XWorker,!!n)))}},Kt=new Proxy(on(null),{get:(e,n)=>new Promise(queueMicrotask).then((()=>Vt(n)))}),Vt=async e=>{if(qt.has(e)){const{interpreter:n,queue:t}=qt.get(e);return(await pn([n,t]))[0]}const n=qt.size?`Available interpreters are: ${[...qt.keys()].map((e=>`"${e}"`)).join(", ")}.`:"There are no interpreters in this page.";throw new Error(`The interpreter "${e}" was not found. ${n}`)},Xt=async e=>{const{type:n,currentTarget:r}=e;if(Et.length)for(let{name:s,value:o,ownerElement:a}of t(`./@*[${Et.map((e=>`name()="${e}${n}"`)).join(" or ")}]`,r)){s=s.slice(0,-(n.length+1));const t=await Vt(a.getAttribute(`${s}-env`)||s);wt.get(s).runEvent(t,o,e)}},Zt=e=>{if(Et.length)for(let{name:n,ownerElement:r}of t(`.//@*[${Et.map((e=>`starts-with(name(),"${e}")`)).join(" or ")}]`,e)){const e=n.lastIndexOf("-"),t=n.slice(e+1);"env"!==t&&(r.addEventListener(t,Xt),"disabled"in r&&!r.disabled&&(r.disabled=!0,Kt[n.slice(0,e)].then((()=>{r.disabled=!1}))))}},Qt=Ht(),er=[],nr=new Map,tr=new Map,rr=new Map,sr=async e=>{for(const n of er)if(e.matches(n)){const t=tr.get(n),r=or.get(t),{resolve:s}=rr.get(t),{options:o,known:a}=r;if(a.has(e))return;a.add(e);for(const[n,t]of nr)e.matches(n)&&await t(e);const{interpreter:l,configURL:p,config:f,version:d,env:u,onerror:m,hooks:h}=o;let y;try{const n=It(e);if(n){const r=Qt.call(new Lt(null,h),n,{...mn(e,t),version:d,configURL:p,type:l,custom:t,config:e.getAttribute("config")||f||{},async:e.hasAttribute("async")});ln(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=St(l,d),_=u||`${g}${f?`|${f}`:""}`,{interpreter:w,XWorker:b}=Gt(t,_,g,d,f,p,l),v=await w,E=on(wt.get(l)),M=new Lt(v,h),k=function(...e){return b.apply(M,e)},O={...yn(E,t,structuredClone(bt.get(g)),v),XWorker:k};kn(l,E,v,vn),E.registerJSModule(v,"polyscript",{XWorker:k,config:O.config,currentScript:t.startsWith("_")?null:e,js_modules:vn,workers:c});for(const n of["Run","RunAsync"]){let t,r,s="",o="";for(const e of At){const t=h?.main?.[e];t&&e.endsWith(n)&&(e.startsWith("codeBefore")?s=nn(t()):o=nn(t()))}(s||o)&&_n(E,`r${n.slice(1)}`,s,o);for(let e=2;e<Nt.length;e++){const s=Nt[e],o=h?.main?.[s];o&&s.endsWith(n)&&(s.startsWith("onBefore")?t=o:r=o)}Wt(E,O,e,n.endsWith("Async"),t,r)}r.queue=r.queue.then((()=>(s(O),y&&m?.(y,e),h?.main?.onReady?.(O,e))))}},or=new Map;let ar=0;const ir=e=>(rr.has(e)||rr.set(e,Promise.withResolvers()),rr.get(e).promise),[{customObserver:lr,define:cr,whenDefined:pr,env:fr,Hook:dr,XWorker:ur},mr]=e("polyscript",{customObserver:nr,define:(e,t)=>{let r=null==e;if(r)e="_ps"+ar++;else if(wt.has(e)||or.has(e))throw new Error(`<script type="${e}"> already registered`);if(!wt.has(t?.interpreter))throw new Error("Unspecified interpreter");wt.set(e,wt.get(t.interpreter));const s=[`script[type="${e}"]`];if(ir(e),r){const{hooks:n}=t,r=n?.main?.onReady;t={...t,hooks:{...n,main:{...n?.main,onReady(n,t){er.splice(er.indexOf(e),1),wt.delete(e),or.delete(e),rr.delete(e),t.remove(),r?.(n)}}}},document.head.append(sn(document.createElement("script"),{type:e}))}else s.push(`${e}-script`),Et.push(`${e}-`);for(const n of s)tr.set(n,e);er.push(...s),or.set(e,{options:sn({env:e},t),known:new WeakSet,queue:Promise.resolve()}),r||Zt(document),n(s.join(",")).forEach(sr)},whenDefined:ir,env:Kt,Hook:Lt,XWorker:Qt});if(!mr){const e=new MutationObserver((e=>{const n=vt.join(",");for(const{type:r,target:s,attributeName:o,addedNodes:a}of e)if("attributes"!==r)for(const e of a)1===e.nodeType&&(Zt(e),n&&e.matches(n)?Yt(e):t(n,e,!0));else{const e=o.lastIndexOf("-")+1;if(e){const n=o.slice(0,e);for(const t of Et)if(n===t){const n=o.slice(e);if("env"!==n){const e=s.hasAttribute(o)?"add":"remove";s[`${e}EventListener`](n,Xt)}break}}}})),t=(e,t,r)=>{e&&n(e,t).forEach(Yt),(e=er.join(","))&&(r&&sr(t),n(e,t).forEach(sr))},r=n=>(e.observe(n,{childList:!0,subtree:!0,attributes:!0}),n),{attachShadow:s}=Element.prototype;sn(Element.prototype,{attachShadow(e){return r(s.call(this,e))}}),queueMicrotask((()=>{Zt(r(document)),t(vt.join(","),document,!1)}))}var hr=new Map([["py","pyodide"],["mpy","micropython"]]);const yr=[];for(const[e]of hr){const n=[`script[type="${e}"]`,`${e}-script`];for(const t of document.querySelectorAll(n.join(","))){const{promise:n,resolve:r}=Promise.withResolvers();yr.push(n),t.addEventListener(`${e}:done`,r,{once:!0})}}Promise.all(yr).then((()=>{dispatchEvent(new Event("py:all-done"))}));var gr={"deprecations-manager":()=>import("./deprecations-manager-BYGF73-y.js"),error:()=>import("./error-DgYfWJQg.js"),"py-editor":()=>import("./py-editor-DHmqLMO5.js"),"py-terminal":()=>import("./py-terminal-E6BBcU6N.js")};const _r={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 wr extends Error{constructor(e,n="",t="text"){super(`(${e}): ${n}`),this.errorCode=e,this.messageType=t,this.name="UserError"}}class br extends wr{constructor(e,n){super(e,n),this.name="FetchError"}}const vr=e=>e.text();async function Er(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 &lt;py-config&gt;)\n is not available when directly opening a HTML file;\n you must use a webserver to serve the additional files.\n See <a style="text-decoration: underline;" href="https://github.com/pyscript/pyscript/issues/257#issuecomment-1119595062">this reference</a>\n on starting a simple webserver with Python.\n ',new br(_r.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 br(_r.FETCH_NOT_FOUND_ERROR,n);case 401:throw new br(_r.FETCH_UNAUTHORIZED_ERROR,n);case 403:throw new br(_r.FETCH_FORBIDDEN_ERROR,n);case 500:throw new br(_r.FETCH_SERVER_ERROR,n);case 503:throw new br(_r.FETCH_UNAVAILABLE_ERROR,n);default:throw new br(_r.FETCH_ERROR,n)}}return t}const{BAD_CONFIG:Mr,CONFLICTING_CODE:kr}=_r,Or=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=`(${Mr}): Invalid URL: ${e}`;throw n&&(t+=`\nexpected ${n} content`),new Error(t)})(t,n),r=t,t=(await Er(r).then(vr)).trim()}return{json:o,toml:s||!o&&!!t,text:t,url:r}},Pr=e=>new Error(`(${kr}): ${e}`),Tr=(e,n=location.href)=>new URL(e,n).href,Rr=(e,n,{message:t})=>{let r=`(${Mr}): Invalid ${e}`;return n&&(r+=` @ ${n}`),new SyntaxError(`${r}\n${t}`)},Sr=new Map;for(const[e]of hr){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=Pr(`Too many ${e}-config`):c.length&&p.length?s=Pr(`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=Pr("Unable to use different configs on main"))),!s&&a)try{const{json:e,toml:n,text:t,url:l}=await Or(a,i);if(l&&(o=Tr(l)),a=t,e||"json"===i)try{r=JSON.parse(t)}catch(e){s=Rr("JSON",l,e)}else if(n||"toml"===i)try{const{parse:e}=await import("./toml-CvAfdf9_.js");r=e(t)}catch(e){s=Rr("TOML",l,e)}}catch(e){s=e}const f=[];for(const[e,n]of Object.entries(gr))s?"error"===e&&n().then((({notify:e})=>e(s.message))):r?.plugins?.includes(`!${e}`)||f.push(n().then((({default:e})=>e)));t=Promise.all(f),Sr.set(e,{config:r,configURL:o,plugins:t,error:s})}var Dr={is_pyterminal:()=>!1,sleep:e=>new Promise((n=>setTimeout(n,1e3*e)))};const xr=e=>{ln(document,"currentScript",{configurable:!0,get:()=>e})},jr=()=>{delete document.currentScript};var Ar=async(e,n,t,r)=>{const s=r.endsWith("Async");(r.startsWith("onBefore")?xr:jr)(t);for(const o of e(r))s?await o(n,t):o(n,t)};const Nr=()=>!0,Cr=e=>{throw new TypeError(e)},Wr=(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 Nr;case 1:return t[0];default:return e=>t.some((n=>n(e)))}},Lr=(e,n,t,r=Cr)=>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)},Hr=(e=>n=>{const[t,r]=((e,n="value")=>{const t=e?.typeof,r=e?.instanceof;return[Wr(t,r),Lr(t,r,n,e?.onerror)]})(n);return class extends e{add(e){return t(e)?super.add(e):r(e)}}})(Set);const{entries:$r}=Object,Ir=["import os as _os","from pathlib import Path as _Path","_path = None"],Ur=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}}(Ir,"-"),zr=(e,n)=>{for(const[t,r]of $r(n))if(Ur.path(`${e}/${t}`),Ur.push(`_path = _Path("${e}/${t}")`),"string"==typeof r){const e=JSON.stringify(r);Ur.push(`_path.write_text(${e},encoding="utf-8")`)}else Ur.push(`if not _os.path.exists("${e}/${t}"):`),Ur.push(" _path.mkdir(parents=True, exist_ok=True)"),zr(`${e}/${t}`,r)};zr(".",{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 globalThis.SharedArrayBuffer.new(4)\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 globalThis.console.debug("SharedArrayBuffer is not available")\n # in this scenario none of the utilities would work\n # as expected so we better export these as NotSupported\n window = NotSupported(\n "pyscript.window",\n "pyscript.window in workers works only via SharedArrayBuffer",\n )\n document = NotSupported(\n "pyscript.document",\n "pyscript.document in workers works only via SharedArrayBuffer",\n )\n\n sync = polyscript.xworker.sync\n\n # in workers the display does not have a default ID\n # but there is a sync utility from xworker\n def current_target():\n return polyscript.target\n\nelse:\n import _pyscript\n from _pyscript import PyWorker, 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 ElementCollection, element_from_dom\n\n\nclass DOM:\n def __init__(self):\n self.body = element_from_dom(document.body)\n self.head = element_from_dom(document.head)\n\n def __getitem__(self, selector):\n return self.find(selector)\n\n def find(self, selector):\n return ElementCollection(\n [element_from_dom(el) for el in document.querySelectorAll(selector)]\n )\n\n\ndom = DOM()\n","elements.py":'import 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`.\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\ndef element_from_dom(dom_element):\n """Create an instance of the appropriate subclass of `Element` for a DOM 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. If the `data-pyscript-type` attribute *is* present we look up the\n subclass by name and create an instance of that. Otherwise, we make a \'best-guess\'\n and look up the `Element` subclass by the DOM element\'s tag name (this is NOT\n fool-proof as many subclasses might use a `<div>`, but close enough 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 cls = ELEMENT_CLASSES_BY_NAME.get(cls_name.lower())\n\n else:\n cls = ELEMENT_CLASSES_BY_TAG.get(dom_element.tagName.lower())\n\n # For any unknown elements (custom tags etc.) create an instance of the \'Element\'\n # class.\n if not cls:\n cls = Element\n\n return cls(dom_element=dom_element)\n\n\nclass Element:\n tag = "div"\n\n # GLOBAL ATTRIBUTES.\n # These are attribute that all elements have (this list is a subset of the official\n # one). We are 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 text = DOMProperty("textContent")\n title = DOMProperty("title")\n translate = DOMProperty("translate")\n virtualkeyboardpolicy = DOMProperty("virtualkeyboardpolicy")\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 (say) the devtools 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 # Set any specified styles.\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} (type {type(style)}) instead."\n )\n\n self._set_dom_properties(**kwargs)\n\n def _set_dom_properties(self, **kwargs):\n """Set all the properties (of type DOMProperty) provided in input as properties\n of the class instance.\n\n Args:\n **kwargs: The properties to set\n """\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(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(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, 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(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(el)\n for el 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_name):\n if class_name in self:\n self.remove(class_name)\n return False\n\n self.add(class_name)\n return True\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 # create the option element and set the attributes\n option = document.createElement("option")\n if value is not None:\n kws["value"] = value\n if html is not None:\n option.innerHTML = html\n if text is not None:\n kws["text"] = text\n\n for key, value in kws.items():\n option.setAttribute(key, value)\n\n if before:\n if isinstance(before, Element):\n before = before._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 [element_from_dom(opt) for opt in self._element._dom_element.options]\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 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 link = self.create("a")\n link._dom_element.download = filename\n link._dom_element.href = self._dom_element.toDataURL()\n link._dom_element.click()\n\n def draw(self, what, width, height):\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 self._dom_element.getContext("2d").drawImage(what, 0, 0, width, height)\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\n def snap(\n self,\n to: Element | str = None,\n width: int | None = None,\n height: int | None = None,\n ):\n """\n Captures a snapshot of a video.\n\n Inputs:\n\n * to: element where to save the snapshot of the video frame to\n * width: width of the image\n * height: height of the image\n\n Output:\n (Element) canvas element where the video frame snapshot was drawn into\n """\n if to is None:\n to_canvas = self.create("canvas")\n if width is None:\n width = self._dom_element.width\n if height is None:\n height = self._dom_element.height\n to_canvas._dom_element.width = width\n to_canvas._dom_element.height = height\n\n elif isinstance(to, Element):\n if to._dom_element.tagName != "CANVAS":\n raise TypeError("Element to snap to must a canvas.")\n to_canvas = to\n\n elif getattr(to, "tagName", "") == "CANVAS":\n to_canvas = canvas(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)\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 a be canvas.")\n\n to_canvas = canvas(nodelist[0])\n\n to_canvas.draw(self, width, height)\n\n return canvas\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 not gap is 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_name):\n for element in self._collection:\n element.classes.toggle(class_name)\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 @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 @property\n def innerHTML(self):\n return self._get_attribute("innerHTML")\n\n @innerHTML.setter\n def innerHTML(self, value):\n self._set_attribute("innerHTML", value)\n\n @property\n def value(self):\n return self._get_attribute("value")\n\n @value.setter\n def value(self, value):\n self._set_attribute("value", value)\n\n def __eq__(self, obj):\n """Check if the element is the same as the other element by comparing\n the underlying DOM element"""\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 elements = self._elements.querySelectorAll(key)\n return ElementCollection([element_from_dom(el) for el in elements])\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 f"{self.__class__.__name__} (length: {len(self._elements)}) {self._elements}"\n\n def _get_attribute(self, attr, index=None):\n if index is None:\n return [getattr(el, attr) for el in self._elements]\n\n # As JQuery, when getting an attr, only return it for the first element\n return getattr(self._elements[index], attr)\n\n def _set_attribute(self, attr, value):\n for el in self._elements:\n setattr(el, attr, value)\n\n\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'}}),Ir.push("import pyscript as _pyscript"),Ir.push(...["_Path","_path","_os","_pyscript"].map((e=>`del ${e}`))),Ir.push("\n");const Fr=Ir.join("\n"),Br=Ur.join("\n"),qr=e=>Qr.main[e],Jr=e=>Qr.worker[e],Gr=(e,n,t,r)=>{e[t]=()=>{const e=r?[r]:[];return e.push(...n(t)),e.map(nn).join("\n")}},Yr=(e,n)=>{const t="mpy"===n?Fr.replace(Br,""):Fr,r={};return Gr(r,e,"codeBeforeRun",t),Gr(r,e,"codeBeforeRunAsync",t),Gr(r,e,"codeAfterRun"),Gr(r,e,"codeAfterRunAsync"),r},Kr=(e,n)=>{const t=[...Jr(n)];if(t.length){const r=Dt(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(Dt).join(", ");return Function(`return(w,x)=>(${r})(w,x,...[${s}])`)()}},Vr=Hr({typeof:"function"}),Xr=Hr({typeof:"string"}),Zr='\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',Qr={main:{onWorker:new Vr,onReady:new Vr,onBeforeRun:new Vr,onBeforeRunAsync:new Vr,onAfterRun:new Vr,onAfterRunAsync:new Vr,codeBeforeRun:new Xr([Zr]),codeBeforeRunAsync:new Xr,codeAfterRun:new Xr,codeAfterRunAsync:new Xr},worker:{onReady:new Vr,onBeforeRun:new Vr,onBeforeRunAsync:new Vr,onAfterRun:new Vr,onAfterRunAsync:new Vr,codeBeforeRun:new Xr,codeBeforeRunAsync:new Xr,codeAfterRun:new Xr,codeAfterRunAsync:new Xr}},es=({tagName:e})=>"SCRIPT"===e,[ns,ts]=[...hr.entries()].map((([e,n])=>async function(t,r){await Sr.get(e).plugins;const s=ur.call(new dr(null,ps.get(e)),t,{...r,type:n});return sn(s.sync,Dr),s.ready})),[{PyWorker:rs,MPWorker:ss,hooks:os,config:as,whenDefined:is},ls]=e("@pyscript/core",{PyWorker:ns,MPWorker:ts,hooks:Qr,config:{},whenDefined:pr}),cs=e=>e?.interpreter&&Tr(e.interpreter),ps=new Map;for(const[e,n]of hr){if(ls)break;const t=(n,t,r)=>{t?r.then((()=>hn(n,e,"done"))):hn(n,e,"done")},{config:r,configURL:s,plugins:o,error:a}=Sr.get(e);let i=0;const l=(n=e)=>`${n}-${i++}`,c=async(n,t,r)=>{if(n.hasAttribute("src"))try{return await Er(n.getAttribute("src")).then(vr)}catch(e){t.stderr(e)}if(r)return nn(n.textContent);const s=nn(tn(n.innerHTML));return console.warn(`Deprecated: use <script type="${e}"> for an always safe content parsing:\n`,s),s};let p,f=!1;const d=({XWorker:e,interpreter:n,io:t})=>{f||(f=!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 es(p)?p.target.id:p.id}}))};a||o.then((()=>{const o=new Map,a={main:{...Yr(qr,e),async onReady(n,r){d(n);for(const e of qr("onReady"))await e(n,r);if(o.has(r)){let{message:e}=o.get(r);o.delete(r);const t=e===$t;return e=`(${_r.CONFLICTING_CODE}) ${e} for `,e+=r.cloneNode(t).outerHTML,void n.io.stderr(e)}if(es(r)){const{attributes:{async:s,target:o}}=r,a=!!o?.value,i=a?Ut(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()),ln(r,"target",{value:i}),hn(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){sn(n.sync,Dr);for(const t of qr("onWorker"))t(e,n)},onBeforeRun(e,n){p=n,Ar(qr,e,n,"onBeforeRun")},onBeforeRunAsync:(e,n)=>(p=n,Ar(qr,e,n,"onBeforeRunAsync")),onAfterRun(e,n){Ar(qr,e,n,"onAfterRun")},onAfterRunAsync:(e,n)=>Ar(qr,e,n,"onAfterRunAsync")},worker:{...Yr(Jr,e),get onReady(){return Kr(this,"onReady")},get onBeforeRun(){return Kr(this,"onBeforeRun")},get onBeforeRunAsync(){return Kr(this,"onBeforeRunAsync")},get onAfterRun(){return Kr(this,"onAfterRun")},get onAfterRunAsync(){return Kr(this,"onAfterRunAsync")}}};ps.set(e,a),cr(e,{config:r,configURL:s,interpreter:n,hooks:a,env:`${e}-script`,version:cs(r),onerror(e,n){o.set(n,e)}}),customElements.define(`${e}-script`,class extends HTMLElement{constructor(){sn(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",hn(this,e,"ready"),t(this,n,(n?o:s)(this.srcCode))}}})})),as[e]=structuredClone(r)}export{dr as H,hr as T,ur as X,nn as a,Br as b,lr as c,an as d,os as e,rs as f,ss as g,as as h,Zr as i,is as j,cs as o,Tr as r,Fr as s};
3
+ //# sourceMappingURL=core-DKrwnOQh.js.map