@pyscript/core 0.4.20 → 0.4.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/core.js CHANGED
@@ -1,2 +1,2 @@
1
- export{f as MPWorker,b as PyWorker,T as TYPES,g as config,e as hooks,s as stdlib,h as whenDefined}from"./core-2NwtOg82.js";
1
+ export{f as MPWorker,b as PyWorker,T as TYPES,g as config,e as hooks,s as stdlib,h as whenDefined}from"./core-DuvgZELZ.js";
2
2
  //# sourceMappingURL=core.js.map
@@ -1,2 +1,2 @@
1
- import{e}from"./core-2NwtOg82.js";import{notify as o}from"./error-CYOIlKpM.js";function r(){const e=document.querySelectorAll("script");for(const o of e)s(o.src)}function s(e){/\/pyscript\.net\/latest/.test(e)&&o("Loading scripts from latest is deprecated and will be removed soon. Please use a specific version instead.")}e.main.onReady.add(r),e.main.onWorker.add(r);
2
- //# sourceMappingURL=deprecations-manager-Dj-XJTYm.js.map
1
+ import{e}from"./core-DuvgZELZ.js";import{notify as o}from"./error-DrF4uAd-.js";function r(){const e=document.querySelectorAll("script");for(const o of e)s(o.src)}function s(e){/\/pyscript\.net\/latest/.test(e)&&o("Loading scripts from latest is deprecated and will be removed soon. Please use a specific version instead.")}e.main.onReady.add(r),e.main.onWorker.add(r);
2
+ //# sourceMappingURL=deprecations-manager-DccuuFgk.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"deprecations-manager-Dj-XJTYm.js","sources":["../src/plugins/deprecations-manager.js"],"sourcesContent":["// PyScript Derepcations Plugin\nimport { hooks } from \"../core.js\";\nimport { notify } from \"./error.js\";\n\n// react lazily on PyScript bootstrap\nhooks.main.onReady.add(checkDeprecations);\nhooks.main.onWorker.add(checkDeprecations);\n\n/**\n * Check that there are no scripts loading from pyscript.net/latest\n */\nfunction checkDeprecations() {\n const scripts = document.querySelectorAll(\"script\");\n for (const script of scripts) checkLoadingScriptsFromLatest(script.src);\n}\n\n/**\n * Check if src being loaded from pyscript.net/latest and display a notification if true\n * * @param {string} src\n */\nfunction checkLoadingScriptsFromLatest(src) {\n if (/\\/pyscript\\.net\\/latest/.test(src)) {\n notify(\n \"Loading scripts from latest is deprecated and will be removed soon. Please use a specific version instead.\",\n );\n }\n}\n"],"names":["checkDeprecations","scripts","document","querySelectorAll","script","checkLoadingScriptsFromLatest","src","test","notify","hooks","main","onReady","add","onWorker"],"mappings":"+EAWA,SAASA,IACL,MAAMC,EAAUC,SAASC,iBAAiB,UAC1C,IAAK,MAAMC,KAAUH,EAASI,EAA8BD,EAAOE,IACvE,CAMA,SAASD,EAA8BC,GAC/B,0BAA0BC,KAAKD,IAC/BE,EACI,6GAGZ,CArBAC,EAAMC,KAAKC,QAAQC,IAAIZ,GACvBS,EAAMC,KAAKG,SAASD,IAAIZ"}
1
+ {"version":3,"file":"deprecations-manager-DccuuFgk.js","sources":["../src/plugins/deprecations-manager.js"],"sourcesContent":["// PyScript Derepcations Plugin\nimport { hooks } from \"../core.js\";\nimport { notify } from \"./error.js\";\n\n// react lazily on PyScript bootstrap\nhooks.main.onReady.add(checkDeprecations);\nhooks.main.onWorker.add(checkDeprecations);\n\n/**\n * Check that there are no scripts loading from pyscript.net/latest\n */\nfunction checkDeprecations() {\n const scripts = document.querySelectorAll(\"script\");\n for (const script of scripts) checkLoadingScriptsFromLatest(script.src);\n}\n\n/**\n * Check if src being loaded from pyscript.net/latest and display a notification if true\n * * @param {string} src\n */\nfunction checkLoadingScriptsFromLatest(src) {\n if (/\\/pyscript\\.net\\/latest/.test(src)) {\n notify(\n \"Loading scripts from latest is deprecated and will be removed soon. Please use a specific version instead.\",\n );\n }\n}\n"],"names":["checkDeprecations","scripts","document","querySelectorAll","script","checkLoadingScriptsFromLatest","src","test","notify","hooks","main","onReady","add","onWorker"],"mappings":"+EAWA,SAASA,IACL,MAAMC,EAAUC,SAASC,iBAAiB,UAC1C,IAAK,MAAMC,KAAUH,EAASI,EAA8BD,EAAOE,IACvE,CAMA,SAASD,EAA8BC,GAC/B,0BAA0BC,KAAKD,IAC/BE,EACI,6GAGZ,CArBAC,EAAMC,KAAKC,QAAQC,IAAIZ,GACvBS,EAAMC,KAAKG,SAASD,IAAIZ"}
@@ -1,2 +1,2 @@
1
- import{e}from"./core-2NwtOg82.js";function n(e){const n=document.createElement("div");n.className="py-error",n.textContent=e,n.style.cssText="\n border: 1px solid red;\n background: #ffdddd;\n color: black;\n font-family: courier, monospace;\n white-space: pre;\n overflow-x: auto;\n padding: 8px;\n margin-top: 8px;\n ",document.body.append(n)}e.main.onReady.add((function o(r){e.main.onReady.delete(o);const{stderr:t}=r.io;r.io.stderr=(e,...o)=>(n(e.message||e),t(e,...o)),addEventListener("error",(({message:e})=>{e.startsWith("Uncaught PythonError")&&n(e)}))}));export{n as notify};
2
- //# sourceMappingURL=error-CYOIlKpM.js.map
1
+ import{e}from"./core-DuvgZELZ.js";function n(e){const n=document.createElement("div");n.className="py-error",n.textContent=e,n.style.cssText="\n border: 1px solid red;\n background: #ffdddd;\n color: black;\n font-family: courier, monospace;\n white-space: pre;\n overflow-x: auto;\n padding: 8px;\n margin-top: 8px;\n ",document.body.append(n)}e.main.onReady.add((function o(r){e.main.onReady.delete(o);const{stderr:t}=r.io;r.io.stderr=(e,...o)=>(n(e.message||e),t(e,...o)),addEventListener("error",(({message:e})=>{e.startsWith("Uncaught PythonError")&&n(e)}))}));export{n as notify};
2
+ //# sourceMappingURL=error-DrF4uAd-.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"error-CYOIlKpM.js","sources":["../src/plugins/error.js"],"sourcesContent":["// PyScript Error Plugin\nimport { hooks } from \"../core.js\";\n\nhooks.main.onReady.add(function override(pyScript) {\n // be sure this override happens only once\n hooks.main.onReady.delete(override);\n\n // trap generic `stderr` to propagate to it regardless\n const { stderr } = pyScript.io;\n\n // override it with our own logic\n pyScript.io.stderr = (error, ...rest) => {\n notify(error.message || error);\n // let other plugins or stderr hook, if any, do the rest\n return stderr(error, ...rest);\n };\n\n // be sure uncaught Python errors are also visible\n addEventListener(\"error\", ({ message }) => {\n if (message.startsWith(\"Uncaught PythonError\")) notify(message);\n });\n});\n\n// Error hook utilities\n\n// Custom function to show notifications\n\n/**\n * Add a banner to the top of the page, notifying the user of an error\n * @param {string} message\n */\nexport function notify(message) {\n const div = document.createElement(\"div\");\n div.className = \"py-error\";\n div.textContent = message;\n div.style.cssText = `\n border: 1px solid red;\n background: #ffdddd;\n color: black;\n font-family: courier, monospace;\n white-space: pre;\n overflow-x: auto;\n padding: 8px;\n margin-top: 8px;\n `;\n document.body.append(div);\n}\n"],"names":["notify","message","div","document","createElement","className","textContent","style","cssText","body","append","hooks","main","onReady","add","override","pyScript","delete","stderr","io","error","rest","addEventListener","startsWith"],"mappings":"kCA+BO,SAASA,EAAOC,GACnB,MAAMC,EAAMC,SAASC,cAAc,OACnCF,EAAIG,UAAY,WAChBH,EAAII,YAAcL,EAClBC,EAAIK,MAAMC,QAAU,6MAUpBL,SAASM,KAAKC,OAAOR,EACzB,CA3CAS,EAAMC,KAAKC,QAAQC,KAAI,SAASC,EAASC,GAErCL,EAAMC,KAAKC,QAAQI,OAAOF,GAG1B,MAAMG,OAAEA,GAAWF,EAASG,GAG5BH,EAASG,GAAGD,OAAS,CAACE,KAAUC,KAC5BrB,EAAOoB,EAAMnB,SAAWmB,GAEjBF,EAAOE,KAAUC,IAI5BC,iBAAiB,SAAS,EAAGrB,cACrBA,EAAQsB,WAAW,yBAAyBvB,EAAOC,EAAQ,GAEvE"}
1
+ {"version":3,"file":"error-DrF4uAd-.js","sources":["../src/plugins/error.js"],"sourcesContent":["// PyScript Error Plugin\nimport { hooks } from \"../core.js\";\n\nhooks.main.onReady.add(function override(pyScript) {\n // be sure this override happens only once\n hooks.main.onReady.delete(override);\n\n // trap generic `stderr` to propagate to it regardless\n const { stderr } = pyScript.io;\n\n // override it with our own logic\n pyScript.io.stderr = (error, ...rest) => {\n notify(error.message || error);\n // let other plugins or stderr hook, if any, do the rest\n return stderr(error, ...rest);\n };\n\n // be sure uncaught Python errors are also visible\n addEventListener(\"error\", ({ message }) => {\n if (message.startsWith(\"Uncaught PythonError\")) notify(message);\n });\n});\n\n// Error hook utilities\n\n// Custom function to show notifications\n\n/**\n * Add a banner to the top of the page, notifying the user of an error\n * @param {string} message\n */\nexport function notify(message) {\n const div = document.createElement(\"div\");\n div.className = \"py-error\";\n div.textContent = message;\n div.style.cssText = `\n border: 1px solid red;\n background: #ffdddd;\n color: black;\n font-family: courier, monospace;\n white-space: pre;\n overflow-x: auto;\n padding: 8px;\n margin-top: 8px;\n `;\n document.body.append(div);\n}\n"],"names":["notify","message","div","document","createElement","className","textContent","style","cssText","body","append","hooks","main","onReady","add","override","pyScript","delete","stderr","io","error","rest","addEventListener","startsWith"],"mappings":"kCA+BO,SAASA,EAAOC,GACnB,MAAMC,EAAMC,SAASC,cAAc,OACnCF,EAAIG,UAAY,WAChBH,EAAII,YAAcL,EAClBC,EAAIK,MAAMC,QAAU,6MAUpBL,SAASM,KAAKC,OAAOR,EACzB,CA3CAS,EAAMC,KAAKC,QAAQC,KAAI,SAASC,EAASC,GAErCL,EAAMC,KAAKC,QAAQI,OAAOF,GAG1B,MAAMG,OAAEA,GAAWF,EAASG,GAG5BH,EAASG,GAAGD,OAAS,CAACE,KAAUC,KAC5BrB,EAAOoB,EAAMnB,SAAWmB,GAEjBF,EAAOE,KAAUC,IAI5BC,iBAAiB,SAAS,EAAGrB,cACrBA,EAAQsB,WAAW,yBAAyBvB,EAAOC,EAAQ,GAEvE"}
@@ -1,2 +1,2 @@
1
- import{T as t,d as e,X as r,H as n,s as o}from"./core-2NwtOg82.js";let i=0;const s=t=>`${t}-editor-${i++}`,a=new Map,c=new Map,l={worker:{codeBeforeRun:()=>o,onReady:({runAsync:t,io:e},{sync:r})=>{e.stdout=e.buffered(r.write),e.stderr=e.buffered(r.writeErr),r.revoke(),r.runAsync=t}}};async function u({currentTarget:t}){const{env:e,pySrc:o,outDiv:i}=this,s=!!t;if(s&&(t.disabled=!0,i.innerHTML=""),!a.has(e)){const t=URL.createObjectURL(new Blob([""])),o={type:this.interpreter},{config:i}=this;if(i){o.configURL=i;const{parse:t}=i.endsWith(".toml")?await import("./toml-CvAfdf9_.js"):JSON;o.config=t(await fetch(i).then((t=>t.text())))}const s=r.call(new n(null,l),t,o),{sync:c}=s,{promise:u,resolve:d}=Promise.withResolvers();a.set(e,u),c.revoke=()=>{URL.revokeObjectURL(t),d(s)}}a.get(e).then((e=>{e.onerror=({error:t})=>{s&&(i.innerHTML+=`<span style='color:red'>${t.message||t}</span>\n`),console.error(t)};const r=()=>{s&&(t.disabled=!1)},{sync:n}=e;n.write=t=>{s&&(i.innerText+=`${t}\n`)},n.writeErr=t=>{s&&(i.innerHTML+=`<span style='color:red'>${t}</span>\n`)},n.runAsync(o).then(r,r)}))}const d=(t,e)=>{const r=document.createElement("div");r.className=`${e}-editor-input`,r.setAttribute("aria-label","Python Script Area");const n=((t,e)=>{const r=document.createElement("button");return r.className=`absolute ${e}-editor-run-button`,r.innerHTML='<svg style="height:20px;width:20px;vertical-align:-.125em;transform-origin:center;overflow:visible;color:green" viewBox="0 0 384 512" aria-hidden="true" role="img" xmlns="http://www.w3.org/2000/svg"><g transform="translate(192 256)" transform-origin="96 0"><g transform="translate(0,0) scale(1,1)"><path d="M361 215C375.3 223.8 384 239.3 384 256C384 272.7 375.3 288.2 361 296.1L73.03 472.1C58.21 482 39.66 482.4 24.52 473.9C9.377 465.4 0 449.4 0 432V80C0 62.64 9.377 46.63 24.52 38.13C39.66 29.64 58.21 29.99 73.03 39.04L361 215z" fill="currentColor" transform="translate(-192 -256)"></path></g></g></svg>',r.setAttribute("aria-label","Python Script Run Button"),r.addEventListener("click",t),r})(t,e),o=document.createElement("div");return o.addEventListener("keydown",(t=>{t.stopPropagation()})),r.append(n,o),r},m=(t,e)=>{const r=document.createElement("div");r.className=`${e}-editor-box`;const n=d(t,e),o=(t=>{const e=document.createElement("div");return e.className=`${t}-editor-output`,e.id=`${s(t)}-output`,e})(e);return r.append(n,o),[r,o]},p=async(t,r,n)=>{const[{basicSetup:o,EditorView:i},{Compartment:a},{python:l},{indentUnit:d},{keymap:p},{defaultKeymap:f}]=await Promise.all([import("./codemirror-Da0uB6D0.js"),import("./codemirror_state-BKbyfKsm.js"),import("./codemirror_lang-python-DIyWB5tk.js"),import("./codemirror_language-DCl5sMoK.js").then((function(t){return t.x})),import("./codemirror_view-Bz8y6BoV.js").then((function(t){return t.q})),import("./codemirror_commands-Cda0Zxd7.js")]),h=t.hasAttribute("setup"),g=t.hasAttribute("config"),v=`${n}-${t.getAttribute("env")||s(r)}`;if(g&&c.has(v))throw new SyntaxError(c.get(v)?`duplicated config for env: ${v}`:`unable to add a config to the env: ${v}`);c.set(v,g);const y=t.src?await fetch(t.src).then((t=>t.text())):t.textContent,b={interpreter:n,env:v,config:g&&new URL(t.getAttribute("config"),location.href).href,get pySrc(){return h?y:k.state.doc.toString()},get outDiv(){return h?null:A}};if(h)return void u.call(b,{currentTarget:null});const w=t.getAttribute("target");let $;if(w){if($=document.getElementById(w)||document.querySelector(w),!$)throw new Error(`Unknown target ${w}`)}else $=document.createElement(`${r}-editor`),$.style.display="block",t.after($);$.id||($.id=s(r)),$.hasAttribute("exec-id")||$.setAttribute("exec-id",0),$.hasAttribute("root")||$.setAttribute("root",$.id);const E=u.bind(b),[x,A]=m(E,r);x.dataset.env=t.hasAttribute("env")?v:n;const L=x.querySelector(`.${r}-editor-input > div`).attachShadow({mode:"open"});L.innerHTML="<style> :host { all: initial; }</style>",$.appendChild(x);const C=e(t.textContent).trim(),S=/^(\s+)/m.test(C)?RegExp.$1:" ",k=new i({extensions:[d.of(S),(new a).of(l()),p.of([...f,{key:"Ctrl-Enter",run:E,preventDefault:!0},{key:"Cmd-Enter",run:E,preventDefault:!0},{key:"Shift-Enter",run:E,preventDefault:!0}]),o],parent:L,doc:C});k.focus()};let f=0,h=Promise.resolve();const g=()=>{f=0,v()},v=()=>{if(!f){f=setTimeout(g,250);for(const[e,r]of t){const t=`script[type="${e}-editor"]`;for(const n of document.querySelectorAll(t))n.type+="-active",h=h.then((()=>p(n,e,r)))}return h}};new MutationObserver(v).observe(document,{childList:!0,subtree:!0});var y=v();export{y as default};
2
- //# sourceMappingURL=py-editor-s2k8SC31.js.map
1
+ import{T as t,d as e,X as r,H as n,s as o}from"./core-DuvgZELZ.js";let i=0;const s=t=>`${t}-editor-${i++}`,a=new Map,c=new Map,l={worker:{codeBeforeRun:()=>o,onReady:({runAsync:t,io:e},{sync:r})=>{e.stdout=e.buffered(r.write),e.stderr=e.buffered(r.writeErr),r.revoke(),r.runAsync=t}}};async function u({currentTarget:t}){const{env:e,pySrc:o,outDiv:i}=this,s=!!t;if(s&&(t.disabled=!0,i.innerHTML=""),!a.has(e)){const t=URL.createObjectURL(new Blob([""])),o={type:this.interpreter},{config:i}=this;if(i){o.configURL=i;const{parse:t}=i.endsWith(".toml")?await import("./toml-CvAfdf9_.js"):JSON;o.config=t(await fetch(i).then((t=>t.text())))}const s=r.call(new n(null,l),t,o),{sync:c}=s,{promise:u,resolve:d}=Promise.withResolvers();a.set(e,u),c.revoke=()=>{URL.revokeObjectURL(t),d(s)}}a.get(e).then((e=>{e.onerror=({error:t})=>{s&&(i.innerHTML+=`<span style='color:red'>${t.message||t}</span>\n`),console.error(t)};const r=()=>{s&&(t.disabled=!1)},{sync:n}=e;n.write=t=>{s&&(i.innerText+=`${t}\n`)},n.writeErr=t=>{s&&(i.innerHTML+=`<span style='color:red'>${t}</span>\n`)},n.runAsync(o).then(r,r)}))}const d=(t,e)=>{const r=document.createElement("div");r.className=`${e}-editor-input`,r.setAttribute("aria-label","Python Script Area");const n=((t,e)=>{const r=document.createElement("button");return r.className=`absolute ${e}-editor-run-button`,r.innerHTML='<svg style="height:20px;width:20px;vertical-align:-.125em;transform-origin:center;overflow:visible;color:green" viewBox="0 0 384 512" aria-hidden="true" role="img" xmlns="http://www.w3.org/2000/svg"><g transform="translate(192 256)" transform-origin="96 0"><g transform="translate(0,0) scale(1,1)"><path d="M361 215C375.3 223.8 384 239.3 384 256C384 272.7 375.3 288.2 361 296.1L73.03 472.1C58.21 482 39.66 482.4 24.52 473.9C9.377 465.4 0 449.4 0 432V80C0 62.64 9.377 46.63 24.52 38.13C39.66 29.64 58.21 29.99 73.03 39.04L361 215z" fill="currentColor" transform="translate(-192 -256)"></path></g></g></svg>',r.setAttribute("aria-label","Python Script Run Button"),r.addEventListener("click",t),r})(t,e),o=document.createElement("div");return o.addEventListener("keydown",(t=>{t.stopPropagation()})),r.append(n,o),r},m=(t,e)=>{const r=document.createElement("div");r.className=`${e}-editor-box`;const n=d(t,e),o=(t=>{const e=document.createElement("div");return e.className=`${t}-editor-output`,e.id=`${s(t)}-output`,e})(e);return r.append(n,o),[r,o]},p=async(t,r,n)=>{const[{basicSetup:o,EditorView:i},{Compartment:a},{python:l},{indentUnit:d},{keymap:p},{defaultKeymap:f}]=await Promise.all([import("./codemirror-BQsQm483.js"),import("./codemirror_state-BKbyfKsm.js"),import("./codemirror_lang-python-DIyWB5tk.js"),import("./codemirror_language-DCl5sMoK.js").then((function(t){return t.x})),import("./codemirror_view-Bz8y6BoV.js").then((function(t){return t.q})),import("./codemirror_commands-Cda0Zxd7.js")]),h=t.hasAttribute("setup"),g=t.hasAttribute("config"),v=`${n}-${t.getAttribute("env")||s(r)}`;if(g&&c.has(v))throw new SyntaxError(c.get(v)?`duplicated config for env: ${v}`:`unable to add a config to the env: ${v}`);c.set(v,g);const y=t.src?await fetch(t.src).then((t=>t.text())):t.textContent,b={interpreter:n,env:v,config:g&&new URL(t.getAttribute("config"),location.href).href,get pySrc(){return h?y:k.state.doc.toString()},get outDiv(){return h?null:A}};if(h)return void u.call(b,{currentTarget:null});const w=t.getAttribute("target");let $;if(w){if($=document.getElementById(w)||document.querySelector(w),!$)throw new Error(`Unknown target ${w}`)}else $=document.createElement(`${r}-editor`),$.style.display="block",t.after($);$.id||($.id=s(r)),$.hasAttribute("exec-id")||$.setAttribute("exec-id",0),$.hasAttribute("root")||$.setAttribute("root",$.id);const E=u.bind(b),[x,A]=m(E,r);x.dataset.env=t.hasAttribute("env")?v:n;const L=x.querySelector(`.${r}-editor-input > div`).attachShadow({mode:"open"});L.innerHTML="<style> :host { all: initial; }</style>",$.appendChild(x);const C=e(t.textContent).trim(),S=/^(\s+)/m.test(C)?RegExp.$1:" ",k=new i({extensions:[d.of(S),(new a).of(l()),p.of([...f,{key:"Ctrl-Enter",run:E,preventDefault:!0},{key:"Cmd-Enter",run:E,preventDefault:!0},{key:"Shift-Enter",run:E,preventDefault:!0}]),o],parent:L,doc:C});k.focus()};let f=0,h=Promise.resolve();const g=()=>{f=0,v()},v=()=>{if(!f){f=setTimeout(g,250);for(const[e,r]of t){const t=`script[type="${e}-editor"]`;for(const n of document.querySelectorAll(t))n.type+="-active",h=h.then((()=>p(n,e,r)))}return h}};new MutationObserver(v).observe(document,{childList:!0,subtree:!0});var y=v();export{y as default};
2
+ //# sourceMappingURL=py-editor-Btsds6ME.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"py-editor-s2k8SC31.js","sources":["../src/plugins/py-editor.js"],"sourcesContent":["// PyScript py-editor plugin\nimport { Hook, XWorker, dedent } from \"polyscript/exports\";\nimport { TYPES, stdlib } from \"../core.js\";\n\nconst RUN_BUTTON = `<svg style=\"height:20px;width:20px;vertical-align:-.125em;transform-origin:center;overflow:visible;color:green\" viewBox=\"0 0 384 512\" aria-hidden=\"true\" role=\"img\" xmlns=\"http://www.w3.org/2000/svg\"><g transform=\"translate(192 256)\" transform-origin=\"96 0\"><g transform=\"translate(0,0) scale(1,1)\"><path d=\"M361 215C375.3 223.8 384 239.3 384 256C384 272.7 375.3 288.2 361 296.1L73.03 472.1C58.21 482 39.66 482.4 24.52 473.9C9.377 465.4 0 449.4 0 432V80C0 62.64 9.377 46.63 24.52 38.13C39.66 29.64 58.21 29.99 73.03 39.04L361 215z\" fill=\"currentColor\" transform=\"translate(-192 -256)\"></path></g></g></svg>`;\n\nlet id = 0;\nconst getID = (type) => `${type}-editor-${id++}`;\n\nconst envs = new Map();\nconst configs = new Map();\n\nconst hooks = {\n worker: {\n codeBeforeRun: () => stdlib,\n // works on both Pyodide and MicroPython\n onReady: ({ runAsync, io }, { sync }) => {\n io.stdout = io.buffered(sync.write);\n io.stderr = io.buffered(sync.writeErr);\n sync.revoke();\n sync.runAsync = runAsync;\n },\n },\n};\n\nasync function execute({ currentTarget }) {\n const { env, pySrc, outDiv } = this;\n const hasRunButton = !!currentTarget;\n\n if (hasRunButton) {\n currentTarget.disabled = true;\n outDiv.innerHTML = \"\";\n }\n\n if (!envs.has(env)) {\n const srcLink = URL.createObjectURL(new Blob([\"\"]));\n const details = { type: this.interpreter };\n const { config } = this;\n if (config) {\n details.configURL = config;\n const { parse } = config.endsWith(\".toml\")\n ? await import(/* webpackIgnore: true */ \"../3rd-party/toml.js\")\n : JSON;\n details.config = parse(await fetch(config).then((r) => r.text()));\n }\n\n const xworker = XWorker.call(new Hook(null, hooks), srcLink, details);\n\n const { sync } = xworker;\n const { promise, resolve } = Promise.withResolvers();\n envs.set(env, promise);\n sync.revoke = () => {\n URL.revokeObjectURL(srcLink);\n resolve(xworker);\n };\n }\n\n // wait for the env then set the target div\n // before executing the current code\n envs.get(env).then((xworker) => {\n xworker.onerror = ({ error }) => {\n if (hasRunButton) {\n outDiv.innerHTML += `<span style='color:red'>${\n error.message || error\n }</span>\\n`;\n }\n console.error(error);\n };\n\n const enable = () => {\n if (hasRunButton) currentTarget.disabled = false;\n };\n const { sync } = xworker;\n sync.write = (str) => {\n if (hasRunButton) outDiv.innerText += `${str}\\n`;\n };\n sync.writeErr = (str) => {\n if (hasRunButton) {\n outDiv.innerHTML += `<span style='color:red'>${str}</span>\\n`;\n }\n };\n sync.runAsync(pySrc).then(enable, enable);\n });\n}\n\nconst makeRunButton = (listener, type) => {\n const runButton = document.createElement(\"button\");\n runButton.className = `absolute ${type}-editor-run-button`;\n runButton.innerHTML = RUN_BUTTON;\n runButton.setAttribute(\"aria-label\", \"Python Script Run Button\");\n runButton.addEventListener(\"click\", listener);\n return runButton;\n};\n\nconst makeEditorDiv = (listener, type) => {\n const editorDiv = document.createElement(\"div\");\n editorDiv.className = `${type}-editor-input`;\n editorDiv.setAttribute(\"aria-label\", \"Python Script Area\");\n\n const runButton = makeRunButton(listener, type);\n const editorShadowContainer = document.createElement(\"div\");\n\n // avoid outer elements intercepting key events (reveal as example)\n editorShadowContainer.addEventListener(\"keydown\", (event) => {\n event.stopPropagation();\n });\n\n editorDiv.append(runButton, editorShadowContainer);\n\n return editorDiv;\n};\n\nconst makeOutDiv = (type) => {\n const outDiv = document.createElement(\"div\");\n outDiv.className = `${type}-editor-output`;\n outDiv.id = `${getID(type)}-output`;\n return outDiv;\n};\n\nconst makeBoxDiv = (listener, type) => {\n const boxDiv = document.createElement(\"div\");\n boxDiv.className = `${type}-editor-box`;\n\n const editorDiv = makeEditorDiv(listener, type);\n const outDiv = makeOutDiv(type);\n boxDiv.append(editorDiv, outDiv);\n\n return [boxDiv, outDiv];\n};\n\nconst init = async (script, type, interpreter) => {\n const [\n { basicSetup, EditorView },\n { Compartment },\n { python },\n { indentUnit },\n { keymap },\n { defaultKeymap },\n ] = await Promise.all([\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror_state.js\"),\n import(\n /* webpackIgnore: true */ \"../3rd-party/codemirror_lang-python.js\"\n ),\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror_language.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror_view.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror_commands.js\"),\n ]);\n\n const isSetup = script.hasAttribute(\"setup\");\n const hasConfig = script.hasAttribute(\"config\");\n const env = `${interpreter}-${script.getAttribute(\"env\") || getID(type)}`;\n\n if (hasConfig && configs.has(env)) {\n throw new SyntaxError(\n configs.get(env)\n ? `duplicated config for env: ${env}`\n : `unable to add a config to the env: ${env}`,\n );\n }\n\n configs.set(env, hasConfig);\n\n const source = script.src\n ? await fetch(script.src).then((b) => b.text())\n : script.textContent;\n const context = {\n interpreter,\n env,\n config:\n hasConfig &&\n new URL(script.getAttribute(\"config\"), location.href).href,\n get pySrc() {\n return isSetup ? source : editor.state.doc.toString();\n },\n get outDiv() {\n return isSetup ? null : outDiv;\n },\n };\n\n if (isSetup) {\n execute.call(context, { currentTarget: null });\n return;\n }\n\n const selector = script.getAttribute(\"target\");\n\n let target;\n if (selector) {\n target =\n document.getElementById(selector) ||\n document.querySelector(selector);\n if (!target) throw new Error(`Unknown target ${selector}`);\n } else {\n target = document.createElement(`${type}-editor`);\n target.style.display = \"block\";\n script.after(target);\n }\n\n if (!target.id) target.id = getID(type);\n if (!target.hasAttribute(\"exec-id\")) target.setAttribute(\"exec-id\", 0);\n if (!target.hasAttribute(\"root\")) target.setAttribute(\"root\", target.id);\n\n // @see https://github.com/JeffersGlass/mkdocs-pyscript/blob/main/mkdocs_pyscript/js/makeblocks.js\n const listener = execute.bind(context);\n const [boxDiv, outDiv] = makeBoxDiv(listener, type);\n boxDiv.dataset.env = script.hasAttribute(\"env\") ? env : interpreter;\n\n const inputChild = boxDiv.querySelector(`.${type}-editor-input > div`);\n const parent = inputChild.attachShadow({ mode: \"open\" });\n // avoid inheriting styles from the outer component\n parent.innerHTML = `<style> :host { all: initial; }</style>`;\n\n target.appendChild(boxDiv);\n\n const doc = dedent(script.textContent).trim();\n\n // preserve user indentation, if any\n const indentation = /^(\\s+)/m.test(doc) ? RegExp.$1 : \" \";\n\n const editor = new EditorView({\n extensions: [\n indentUnit.of(indentation),\n new Compartment().of(python()),\n keymap.of([\n ...defaultKeymap,\n { key: \"Ctrl-Enter\", run: listener, preventDefault: true },\n { key: \"Cmd-Enter\", run: listener, preventDefault: true },\n { key: \"Shift-Enter\", run: listener, preventDefault: true },\n ]),\n basicSetup,\n ],\n parent,\n doc,\n });\n\n editor.focus();\n};\n\n// avoid too greedy MutationObserver operations at distance\nlet timeout = 0;\n\n// avoid delayed initialization\nlet queue = Promise.resolve();\n\n// reset interval value then check for new scripts\nconst resetTimeout = () => {\n timeout = 0;\n pyEditor();\n};\n\n// triggered both ASAP on the living DOM and via MutationObserver later\nconst pyEditor = () => {\n if (timeout) return;\n timeout = setTimeout(resetTimeout, 250);\n for (const [type, interpreter] of TYPES) {\n const selector = `script[type=\"${type}-editor\"]`;\n for (const script of document.querySelectorAll(selector)) {\n // avoid any further bootstrap by changing the type as active\n script.type += \"-active\";\n // don't await in here or multiple calls might happen\n // while the first script is being initialized\n queue = queue.then(() => init(script, type, interpreter));\n }\n }\n return queue;\n};\n\nnew MutationObserver(pyEditor).observe(document, {\n childList: true,\n subtree: true,\n});\n\n// try to check the current document ASAP\nexport default pyEditor();\n"],"names":["id","getID","type","envs","Map","configs","hooks","worker","codeBeforeRun","stdlib","onReady","runAsync","io","sync","stdout","buffered","write","stderr","writeErr","revoke","async","execute","currentTarget","env","pySrc","outDiv","this","hasRunButton","disabled","innerHTML","has","srcLink","URL","createObjectURL","Blob","details","interpreter","config","configURL","parse","endsWith","import","JSON","fetch","then","r","text","xworker","XWorker","call","Hook","promise","resolve","Promise","withResolvers","set","revokeObjectURL","get","onerror","error","message","console","enable","str","innerText","makeEditorDiv","listener","editorDiv","document","createElement","className","setAttribute","runButton","addEventListener","makeRunButton","editorShadowContainer","event","stopPropagation","append","makeBoxDiv","boxDiv","makeOutDiv","init","script","basicSetup","EditorView","Compartment","python","indentUnit","keymap","defaultKeymap","all","n","x","q","isSetup","hasAttribute","hasConfig","getAttribute","SyntaxError","source","src","b","textContent","context","location","href","editor","state","doc","toString","selector","target","getElementById","querySelector","Error","style","display","after","bind","dataset","parent","attachShadow","mode","appendChild","dedent","trim","indentation","test","RegExp","$1","extensions","of","key","run","preventDefault","focus","timeout","queue","resetTimeout","pyEditor","setTimeout","TYPES","querySelectorAll","MutationObserver","observe","childList","subtree","pyEditor$1"],"mappings":"mEAMA,IAAIA,EAAK,EACT,MAAM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.js"],"sourcesContent":["// PyScript py-editor plugin\nimport { Hook, XWorker, dedent } from \"polyscript/exports\";\nimport { TYPES, stdlib } from \"../core.js\";\n\nconst RUN_BUTTON = `<svg style=\"height:20px;width:20px;vertical-align:-.125em;transform-origin:center;overflow:visible;color:green\" viewBox=\"0 0 384 512\" aria-hidden=\"true\" role=\"img\" xmlns=\"http://www.w3.org/2000/svg\"><g transform=\"translate(192 256)\" transform-origin=\"96 0\"><g transform=\"translate(0,0) scale(1,1)\"><path d=\"M361 215C375.3 223.8 384 239.3 384 256C384 272.7 375.3 288.2 361 296.1L73.03 472.1C58.21 482 39.66 482.4 24.52 473.9C9.377 465.4 0 449.4 0 432V80C0 62.64 9.377 46.63 24.52 38.13C39.66 29.64 58.21 29.99 73.03 39.04L361 215z\" fill=\"currentColor\" transform=\"translate(-192 -256)\"></path></g></g></svg>`;\n\nlet id = 0;\nconst getID = (type) => `${type}-editor-${id++}`;\n\nconst envs = new Map();\nconst configs = new Map();\n\nconst hooks = {\n worker: {\n codeBeforeRun: () => stdlib,\n // works on both Pyodide and MicroPython\n onReady: ({ runAsync, io }, { sync }) => {\n io.stdout = io.buffered(sync.write);\n io.stderr = io.buffered(sync.writeErr);\n sync.revoke();\n sync.runAsync = runAsync;\n },\n },\n};\n\nasync function execute({ currentTarget }) {\n const { env, pySrc, outDiv } = this;\n const hasRunButton = !!currentTarget;\n\n if (hasRunButton) {\n currentTarget.disabled = true;\n outDiv.innerHTML = \"\";\n }\n\n if (!envs.has(env)) {\n const srcLink = URL.createObjectURL(new Blob([\"\"]));\n const details = { type: this.interpreter };\n const { config } = this;\n if (config) {\n details.configURL = config;\n const { parse } = config.endsWith(\".toml\")\n ? await import(/* webpackIgnore: true */ \"../3rd-party/toml.js\")\n : JSON;\n details.config = parse(await fetch(config).then((r) => r.text()));\n }\n\n const xworker = XWorker.call(new Hook(null, hooks), srcLink, details);\n\n const { sync } = xworker;\n const { promise, resolve } = Promise.withResolvers();\n envs.set(env, promise);\n sync.revoke = () => {\n URL.revokeObjectURL(srcLink);\n resolve(xworker);\n };\n }\n\n // wait for the env then set the target div\n // before executing the current code\n envs.get(env).then((xworker) => {\n xworker.onerror = ({ error }) => {\n if (hasRunButton) {\n outDiv.innerHTML += `<span style='color:red'>${\n error.message || error\n }</span>\\n`;\n }\n console.error(error);\n };\n\n const enable = () => {\n if (hasRunButton) currentTarget.disabled = false;\n };\n const { sync } = xworker;\n sync.write = (str) => {\n if (hasRunButton) outDiv.innerText += `${str}\\n`;\n };\n sync.writeErr = (str) => {\n if (hasRunButton) {\n outDiv.innerHTML += `<span style='color:red'>${str}</span>\\n`;\n }\n };\n sync.runAsync(pySrc).then(enable, enable);\n });\n}\n\nconst makeRunButton = (listener, type) => {\n const runButton = document.createElement(\"button\");\n runButton.className = `absolute ${type}-editor-run-button`;\n runButton.innerHTML = RUN_BUTTON;\n runButton.setAttribute(\"aria-label\", \"Python Script Run Button\");\n runButton.addEventListener(\"click\", listener);\n return runButton;\n};\n\nconst makeEditorDiv = (listener, type) => {\n const editorDiv = document.createElement(\"div\");\n editorDiv.className = `${type}-editor-input`;\n editorDiv.setAttribute(\"aria-label\", \"Python Script Area\");\n\n const runButton = makeRunButton(listener, type);\n const editorShadowContainer = document.createElement(\"div\");\n\n // avoid outer elements intercepting key events (reveal as example)\n editorShadowContainer.addEventListener(\"keydown\", (event) => {\n event.stopPropagation();\n });\n\n editorDiv.append(runButton, editorShadowContainer);\n\n return editorDiv;\n};\n\nconst makeOutDiv = (type) => {\n const outDiv = document.createElement(\"div\");\n outDiv.className = `${type}-editor-output`;\n outDiv.id = `${getID(type)}-output`;\n return outDiv;\n};\n\nconst makeBoxDiv = (listener, type) => {\n const boxDiv = document.createElement(\"div\");\n boxDiv.className = `${type}-editor-box`;\n\n const editorDiv = makeEditorDiv(listener, type);\n const outDiv = makeOutDiv(type);\n boxDiv.append(editorDiv, outDiv);\n\n return [boxDiv, outDiv];\n};\n\nconst init = async (script, type, interpreter) => {\n const [\n { basicSetup, EditorView },\n { Compartment },\n { python },\n { indentUnit },\n { keymap },\n { defaultKeymap },\n ] = await Promise.all([\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror_state.js\"),\n import(\n /* webpackIgnore: true */ \"../3rd-party/codemirror_lang-python.js\"\n ),\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror_language.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror_view.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror_commands.js\"),\n ]);\n\n const isSetup = script.hasAttribute(\"setup\");\n const hasConfig = script.hasAttribute(\"config\");\n const env = `${interpreter}-${script.getAttribute(\"env\") || getID(type)}`;\n\n if (hasConfig && configs.has(env)) {\n throw new SyntaxError(\n configs.get(env)\n ? `duplicated config for env: ${env}`\n : `unable to add a config to the env: ${env}`,\n );\n }\n\n configs.set(env, hasConfig);\n\n const source = script.src\n ? await fetch(script.src).then((b) => b.text())\n : script.textContent;\n const context = {\n interpreter,\n env,\n config:\n hasConfig &&\n new URL(script.getAttribute(\"config\"), location.href).href,\n get pySrc() {\n return isSetup ? source : editor.state.doc.toString();\n },\n get outDiv() {\n return isSetup ? null : outDiv;\n },\n };\n\n if (isSetup) {\n execute.call(context, { currentTarget: null });\n return;\n }\n\n const selector = script.getAttribute(\"target\");\n\n let target;\n if (selector) {\n target =\n document.getElementById(selector) ||\n document.querySelector(selector);\n if (!target) throw new Error(`Unknown target ${selector}`);\n } else {\n target = document.createElement(`${type}-editor`);\n target.style.display = \"block\";\n script.after(target);\n }\n\n if (!target.id) target.id = getID(type);\n if (!target.hasAttribute(\"exec-id\")) target.setAttribute(\"exec-id\", 0);\n if (!target.hasAttribute(\"root\")) target.setAttribute(\"root\", target.id);\n\n // @see https://github.com/JeffersGlass/mkdocs-pyscript/blob/main/mkdocs_pyscript/js/makeblocks.js\n const listener = execute.bind(context);\n const [boxDiv, outDiv] = makeBoxDiv(listener, type);\n boxDiv.dataset.env = script.hasAttribute(\"env\") ? env : interpreter;\n\n const inputChild = boxDiv.querySelector(`.${type}-editor-input > div`);\n const parent = inputChild.attachShadow({ mode: \"open\" });\n // avoid inheriting styles from the outer component\n parent.innerHTML = `<style> :host { all: initial; }</style>`;\n\n target.appendChild(boxDiv);\n\n const doc = dedent(script.textContent).trim();\n\n // preserve user indentation, if any\n const indentation = /^(\\s+)/m.test(doc) ? RegExp.$1 : \" \";\n\n const editor = new EditorView({\n extensions: [\n indentUnit.of(indentation),\n new Compartment().of(python()),\n keymap.of([\n ...defaultKeymap,\n { key: \"Ctrl-Enter\", run: listener, preventDefault: true },\n { key: \"Cmd-Enter\", run: listener, preventDefault: true },\n { key: \"Shift-Enter\", run: listener, preventDefault: true },\n ]),\n basicSetup,\n ],\n parent,\n doc,\n });\n\n editor.focus();\n};\n\n// avoid too greedy MutationObserver operations at distance\nlet timeout = 0;\n\n// avoid delayed initialization\nlet queue = Promise.resolve();\n\n// reset interval value then check for new scripts\nconst resetTimeout = () => {\n timeout = 0;\n pyEditor();\n};\n\n// triggered both ASAP on the living DOM and via MutationObserver later\nconst pyEditor = () => {\n if (timeout) return;\n timeout = setTimeout(resetTimeout, 250);\n for (const [type, interpreter] of TYPES) {\n const selector = `script[type=\"${type}-editor\"]`;\n for (const script of document.querySelectorAll(selector)) {\n // avoid any further bootstrap by changing the type as active\n script.type += \"-active\";\n // don't await in here or multiple calls might happen\n // while the first script is being initialized\n queue = queue.then(() => init(script, type, interpreter));\n }\n }\n return queue;\n};\n\nnew MutationObserver(pyEditor).observe(document, {\n childList: true,\n subtree: true,\n});\n\n// try to check the current document ASAP\nexport default pyEditor();\n"],"names":["id","getID","type","envs","Map","configs","hooks","worker","codeBeforeRun","stdlib","onReady","runAsync","io","sync","stdout","buffered","write","stderr","writeErr","revoke","async","execute","currentTarget","env","pySrc","outDiv","this","hasRunButton","disabled","innerHTML","has","srcLink","URL","createObjectURL","Blob","details","interpreter","config","configURL","parse","endsWith","import","JSON","fetch","then","r","text","xworker","XWorker","call","Hook","promise","resolve","Promise","withResolvers","set","revokeObjectURL","get","onerror","error","message","console","enable","str","innerText","makeEditorDiv","listener","editorDiv","document","createElement","className","setAttribute","runButton","addEventListener","makeRunButton","editorShadowContainer","event","stopPropagation","append","makeBoxDiv","boxDiv","makeOutDiv","init","script","basicSetup","EditorView","Compartment","python","indentUnit","keymap","defaultKeymap","all","n","x","q","isSetup","hasAttribute","hasConfig","getAttribute","SyntaxError","source","src","b","textContent","context","location","href","editor","state","doc","toString","selector","target","getElementById","querySelector","Error","style","display","after","bind","dataset","parent","attachShadow","mode","appendChild","dedent","trim","indentation","test","RegExp","$1","extensions","of","key","run","preventDefault","focus","timeout","queue","resetTimeout","pyEditor","setTimeout","TYPES","querySelectorAll","MutationObserver","observe","childList","subtree","pyEditor$1"],"mappings":"mEAMA,IAAIA,EAAK,EACT,MAAMC,EAASC,GAAS,GAAGA,YAAeF,MAEpCG,EAAO,IAAIC,IACXC,EAAU,IAAID,IAEdE,EAAQ,CACVC,OAAQ,CACJC,cAAe,IAAMC,EAErBC,QAAS,EAAGC,WAAUC,OAAQC,WAC1BD,EAAGE,OAASF,EAAGG,SAASF,EAAKG,OAC7BJ,EAAGK,OAASL,EAAGG,SAASF,EAAKK,UAC7BL,EAAKM,SACLN,EAAKF,SAAWA,CAAQ,IAKpCS,eAAeC,GAAQC,cAAEA,IACrB,MAAMC,IAAEA,EAAGC,MAAEA,EAAKC,OAAEA,GAAWC,KACzBC,IAAiBL,EAOvB,GALIK,IACAL,EAAcM,UAAW,EACzBH,EAAOI,UAAY,KAGlB1B,EAAK2B,IAAIP,GAAM,CAChB,MAAMQ,EAAUC,IAAIC,gBAAgB,IAAIC,KAAK,CAAC,MACxCC,EAAU,CAAEjC,KAAMwB,KAAKU,cACvBC,OAAEA,GAAWX,KACnB,GAAIW,EAAQ,CACRF,EAAQG,UAAYD,EACpB,MAAME,MAAEA,GAAUF,EAAOG,SAAS,eACtBC,OAAiC,sBACvCC,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AO,EAIlB,IAAIC,EAAU,EAGVC,EAAQrF,QAAQD,UAGpB,MAAMuF,EAAe,KACjBF,EAAU,EACVG,GAAU,EAIRA,EAAW,KACb,IAAIH,EAAJ,CACAA,EAAUI,WAAWF,EAAc,KACnC,IAAK,MAAOzI,EAAMkC,KAAgB0G,EAAO,CACrC,MAAM/B,EAAW,gBAAgB7G,aACjC,IAAK,MAAMiF,KAAUf,SAAS2E,iBAAiBhC,GAE3C5B,EAAOjF,MAAQ,UAGfwI,EAAQA,EAAM9F,MAAK,IAAMsC,EAAKC,EAAQjF,EAAMkC,IAEnD,CACD,OAAOsG,CAZa,CAYR,EAGhB,IAAIM,iBAAiBJ,GAAUK,QAAQ7E,SAAU,CAC7C8E,WAAW,EACXC,SAAS,IAIb,IAAAC,EAAeR"}
@@ -0,0 +1,2 @@
1
+ import{T as e,c as t,e as r,a as n}from"./core-DuvgZELZ.js";import{notify as o}from"./error-DrF4uAd-.js";const i=[],s=e=>{throw o(e),new Error(e)},a=({attributes:{worker:e}})=>!e,d=new WeakSet;let l=!0;const c=({interpreter:e,io:t,run:r,type:n},{sync:o})=>{if(!o.is_pyterminal())return;r("from polyscript import currentScript as _; __terminal__ = _.terminal; del _");let i="";const{pyterminal_read:s,pyterminal_write:a}=o,d=new TextDecoder,l={isatty:!1,write:e=>(i=d.decode(e),a(i),e.length)};if(t.stderr=e=>{a(String(e.message||e))},"mpy"===n){e.registerJsModule("_pyscript_input",{input:s}),r("from _pyscript_input import input");const n=e=>{const t=[];let r=0;return n=>{let o=0;for(const i of n)t.push(i),r?r--:194<=i&&i<=223?r=1:224<=i&&i<=239?r=2:240<=i&&i<=244&&(r=3),r||(o+=t.length,e(new Uint8Array(t.splice(0))));return o}};t.stdout=n(l.write),e.registerJsModule("code",{interact(){let r="",o=1;const i=new TextEncoder,l=[],c=n((e=>{l.push(...e),a(d.decode(e))}));t.stdout=e=>o++>r.length?c(e):0,e.replInit(),function t(){const n=d.decode(new Uint8Array(l.splice(0))),a=`${s(n.split("\n").at(-1))}\r`;o=0,r=i.encode(a);for(const t of r)e.replProcessChar(t);t()}()}})}else e.setStdout(l),e.setStderr(l),e.setStdin({isatty:!1,stdin:()=>s(i)})},m=async e=>{const[{Terminal:t},{Readline:o},{FitAddon:i},{WebLinksAddon:s}]=await Promise.all([import("./xterm-DqawCVsv.js"),import("./xterm-readline-D247p8vq.js"),import("./xterm_addon-fit--gyF3PcZ.js"),import("./xterm_addon-web-links-Cnej-nJ6.js")]),a=new o,l=r=>{let o=e;const d=e.getAttribute("target");if(d){if(o=document.getElementById(d)||document.querySelector(d),!o)throw new Error(`Unknown target ${d}`)}else o=document.createElement("py-terminal"),o.style.display="block",e.after(o);const l=new t({theme:{background:"#191A19",foreground:"#F5F2E7"},...r}),c=new i;return l.loadAddon(c),l.loadAddon(a),l.loadAddon(new s),l.open(o),c.fit(),l.focus(),n(e,{terminal:{value:l},process:{value:async e=>{for(const t of e.split(/(?:\r|\n|\r\n)/)){l.paste(`${t}\n`);do{await new Promise((e=>setTimeout(e,0)))}while(!a.activeRead?.resolve);a.activeRead.resolve(t)}}}}),l};e.hasAttribute("worker")?(r.main.onWorker.add((function e(t,n){d.has(n)||(d.add(n),r.main.onWorker.delete(e),l({disableStdin:!1,cursorBlink:!0,cursorStyle:"block"}),n.sync.is_pyterminal=()=>!0,n.sync.pyterminal_read=a.read.bind(a),n.sync.pyterminal_write=a.write.bind(a))})),r.worker.onReady.add(c)):r.main.onReady.add((function e({interpreter:t,io:n,run:o,type:i}){console.warn("py-terminal is read only on main thread"),r.main.onReady.delete(e),globalThis.__py_terminal__=l({disableStdin:!0,cursorBlink:!1,cursorStyle:"underline"}),o("from js import __py_terminal__ as __terminal__"),delete globalThis.__py_terminal__,n.stderr=e=>{a.write(String(e.message||e))},"mpy"===i&&(t.setStdin=Object,t.setStderr=Object,t.setStdout=({write:e})=>{n.stdout=e});let s="";const d=new TextDecoder,c={isatty:!1,write:e=>(s=d.decode(e),a.write(s),e.length)};t.setStdout(c),t.setStderr(c),t.setStdin({isatty:!1,stdin:()=>a.read(s)})}))};for(const r of e.keys()){const e=`script[type="${r}"][terminal],${r}-script[terminal]`;i.push(e),t.set(e,(async e=>{const t=document.querySelectorAll(i.join(","));[].filter.call(t,a).length>1&&s("You can use at most 1 main terminal"),l&&(l=!1,document.head.append(Object.assign(document.createElement("link"),{rel:"stylesheet",href:new URL("./xterm.css",import.meta.url)}))),await m(e)}))}
2
+ //# sourceMappingURL=py-terminal-DDHCvl2G.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"py-terminal-DDHCvl2G.js","sources":["../src/plugins/py-terminal.js"],"sourcesContent":["// PyScript py-terminal plugin\nimport { TYPES, hooks } from \"../core.js\";\nimport { notify } from \"./error.js\";\nimport { customObserver, defineProperties } from \"polyscript/exports\";\n\n// will contain all valid selectors\nconst SELECTORS = [];\n\n// show the error on main and\n// stops the module from keep executing\nconst notifyAndThrow = (message) => {\n notify(message);\n throw new Error(message);\n};\n\nconst onceOnMain = ({ attributes: { worker } }) => !worker;\n\nconst bootstrapped = new WeakSet();\n\nlet addStyle = true;\n\n// this callback will be serialized as string and it never needs\n// to be invoked multiple times. Each xworker here is bootstrapped\n// only once thanks to the `sync.is_pyterminal()` check.\nconst workerReady = ({ interpreter, io, run, type }, { sync }) => {\n if (!sync.is_pyterminal()) return;\n\n // in workers it's always safe to grab the polyscript currentScript\n // the ugly `_` dance is due MicroPython not able to import via:\n // `from polyscript.currentScript import terminal as __terminal__`\n run(\n \"from polyscript import currentScript as _; __terminal__ = _.terminal; del _\",\n );\n\n let data = \"\";\n const { pyterminal_read, pyterminal_write } = sync;\n const decoder = new TextDecoder();\n const generic = {\n isatty: false,\n write(buffer) {\n data = decoder.decode(buffer);\n pyterminal_write(data);\n return buffer.length;\n },\n };\n\n // This part works already in both Pyodide and MicroPython\n io.stderr = (error) => {\n pyterminal_write(String(error.message || error));\n };\n\n // MicroPython has no code or code.interact()\n // This part patches it in a way that simulates\n // the code.interact() module in Pyodide.\n if (type === \"mpy\") {\n // monkey patch global input otherwise broken in MicroPython\n interpreter.registerJsModule(\"_pyscript_input\", {\n input: pyterminal_read,\n });\n run(\"from _pyscript_input import input\");\n\n // this is needed to avoid truncated unicode in MicroPython\n // the reason is that `linebuffer` false just send one byte\n // per time and readline here doesn't like it much.\n // MicroPython also has issues with code-points and\n // replProcessChar(byte) but that function accepts only\n // one byte per time so ... we have an issue!\n // @see https://github.com/pyscript/pyscript/pull/2018\n // @see https://github.com/WebReflection/buffer-points\n const bufferPoints = (stdio) => {\n const bytes = [];\n let needed = 0;\n return (buffer) => {\n let written = 0;\n for (const byte of buffer) {\n bytes.push(byte);\n // @see https://encoding.spec.whatwg.org/#utf-8-bytes-needed\n if (needed) needed--;\n else if (0xc2 <= byte && byte <= 0xdf) needed = 1;\n else if (0xe0 <= byte && byte <= 0xef) needed = 2;\n else if (0xf0 <= byte && byte <= 0xf4) needed = 3;\n if (!needed) {\n written += bytes.length;\n stdio(new Uint8Array(bytes.splice(0)));\n }\n }\n return written;\n };\n };\n\n io.stdout = bufferPoints(generic.write);\n\n // tiny shim of the code module with only interact\n // to bootstrap a REPL like environment\n interpreter.registerJsModule(\"code\", {\n interact() {\n let input = \"\";\n let length = 1;\n\n const encoder = new TextEncoder();\n const acc = [];\n const handlePoints = bufferPoints((buffer) => {\n acc.push(...buffer);\n pyterminal_write(decoder.decode(buffer));\n });\n\n // avoid duplicating the output produced by the input\n io.stdout = (buffer) =>\n length++ > input.length ? handlePoints(buffer) : 0;\n\n interpreter.replInit();\n\n // loop forever waiting for user inputs\n (function repl() {\n const out = decoder.decode(new Uint8Array(acc.splice(0)));\n // print in current line only the last line produced by the REPL\n const data = `${pyterminal_read(out.split(\"\\n\").at(-1))}\\r`;\n length = 0;\n input = encoder.encode(data);\n for (const c of input) interpreter.replProcessChar(c);\n repl();\n })();\n },\n });\n } else {\n interpreter.setStdout(generic);\n interpreter.setStderr(generic);\n interpreter.setStdin({\n isatty: false,\n stdin: () => pyterminal_read(data),\n });\n }\n};\n\nconst pyTerminal = async (element) => {\n // lazy load these only when a valid terminal is found\n const [{ Terminal }, { Readline }, { FitAddon }, { WebLinksAddon }] =\n await Promise.all([\n import(/* webpackIgnore: true */ \"../3rd-party/xterm.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/xterm-readline.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/xterm_addon-fit.js\"),\n import(\n /* webpackIgnore: true */ \"../3rd-party/xterm_addon-web-links.js\"\n ),\n ]);\n\n const readline = new Readline();\n\n // common main thread initialization for both worker\n // or main case, bootstrapping the terminal on its target\n const init = (options) => {\n let target = element;\n const selector = element.getAttribute(\"target\");\n if (selector) {\n target =\n document.getElementById(selector) ||\n document.querySelector(selector);\n if (!target) throw new Error(`Unknown target ${selector}`);\n } else {\n target = document.createElement(\"py-terminal\");\n target.style.display = \"block\";\n element.after(target);\n }\n const terminal = new Terminal({\n theme: {\n background: \"#191A19\",\n foreground: \"#F5F2E7\",\n },\n ...options,\n });\n const fitAddon = new FitAddon();\n terminal.loadAddon(fitAddon);\n terminal.loadAddon(readline);\n terminal.loadAddon(new WebLinksAddon());\n terminal.open(target);\n fitAddon.fit();\n terminal.focus();\n defineProperties(element, {\n terminal: { value: terminal },\n process: {\n value: async (code) => {\n // this loop is the only way I could find to actually simulate\n // the user input char after char in a way that works in both\n // MicroPython and Pyodide\n for (const line of code.split(/(?:\\r|\\n|\\r\\n)/)) {\n terminal.paste(`${line}\\n`);\n do {\n await new Promise((resolve) =>\n setTimeout(resolve, 0),\n );\n } while (!readline.activeRead?.resolve);\n readline.activeRead.resolve(line);\n }\n },\n },\n });\n return terminal;\n };\n\n // branch logic for the worker\n if (element.hasAttribute(\"worker\")) {\n // add a hook on the main thread to setup all sync helpers\n // also bootstrapping the XTerm target on main *BUT* ...\n hooks.main.onWorker.add(function worker(_, xworker) {\n // ... as multiple workers will add multiple callbacks\n // be sure no xworker is ever initialized twice!\n if (bootstrapped.has(xworker)) return;\n bootstrapped.add(xworker);\n\n // still cleanup this callback for future scripts/workers\n hooks.main.onWorker.delete(worker);\n\n init({\n disableStdin: false,\n cursorBlink: true,\n cursorStyle: \"block\",\n });\n\n xworker.sync.is_pyterminal = () => true;\n xworker.sync.pyterminal_read = readline.read.bind(readline);\n xworker.sync.pyterminal_write = readline.write.bind(readline);\n });\n\n // setup remote thread JS/Python code for whenever the\n // worker is ready to become a terminal\n hooks.worker.onReady.add(workerReady);\n } else {\n // in the main case, just bootstrap XTerm without\n // allowing any input as that's not possible / awkward\n hooks.main.onReady.add(function main({ interpreter, io, run, type }) {\n console.warn(\"py-terminal is read only on main thread\");\n hooks.main.onReady.delete(main);\n\n // on main, it's easy to trash and clean the current terminal\n globalThis.__py_terminal__ = init({\n disableStdin: true,\n cursorBlink: false,\n cursorStyle: \"underline\",\n });\n run(\"from js import __py_terminal__ as __terminal__\");\n delete globalThis.__py_terminal__;\n\n io.stderr = (error) => {\n readline.write(String(error.message || error));\n };\n\n if (type === \"mpy\") {\n interpreter.setStdin = Object; // as no-op\n interpreter.setStderr = Object; // as no-op\n interpreter.setStdout = ({ write }) => {\n io.stdout = write;\n };\n }\n\n let data = \"\";\n const decoder = new TextDecoder();\n const generic = {\n isatty: false,\n write(buffer) {\n data = decoder.decode(buffer);\n readline.write(data);\n return buffer.length;\n },\n };\n interpreter.setStdout(generic);\n interpreter.setStderr(generic);\n interpreter.setStdin({\n isatty: false,\n stdin: () => readline.read(data),\n });\n });\n }\n};\n\nfor (const key of TYPES.keys()) {\n const selector = `script[type=\"${key}\"][terminal],${key}-script[terminal]`;\n SELECTORS.push(selector);\n customObserver.set(selector, async (element) => {\n // we currently support only one terminal on main as in \"classic\"\n const terminals = document.querySelectorAll(SELECTORS.join(\",\"));\n if ([].filter.call(terminals, onceOnMain).length > 1)\n notifyAndThrow(\"You can use at most 1 main terminal\");\n\n // import styles lazily\n if (addStyle) {\n addStyle = false;\n document.head.append(\n Object.assign(document.createElement(\"link\"), {\n rel: \"stylesheet\",\n href: new URL(\"./xterm.css\", import.meta.url),\n }),\n );\n }\n\n await pyTerminal(element);\n });\n}\n"],"names":["SELECTORS","notifyAndThrow","message","notify","Error","onceOnMain","attributes","worker","bootstrapped","WeakSet","addStyle","workerReady","interpreter","io","run","type","sync","is_pyterminal","data","pyterminal_read","pyterminal_write","decoder","TextDecoder","generic","isatty","write","buffer","decode","length","stderr","error","String","registerJsModule","input","bufferPoints","stdio","bytes","needed","written","byte","push","Uint8Array","splice","stdout","interact","encoder","TextEncoder","acc","handlePoints","replInit","repl","out","split","at","encode","c","replProcessChar","setStdout","setStderr","setStdin","stdin","pyTerminal","async","element","Terminal","Readline","FitAddon","WebLinksAddon","Promise","all","import","readline","init","options","target","selector","getAttribute","document","getElementById","querySelector","createElement","style","display","after","terminal","theme","background","foreground","fitAddon","loadAddon","open","fit","focus","defineProperties","value","process","code","line","paste","resolve","setTimeout","activeRead","hasAttribute","hooks","main","onWorker","add","_","xworker","has","delete","disableStdin","cursorBlink","cursorStyle","read","bind","onReady","console","warn","globalThis","__py_terminal__","Object","key","TYPES","keys","customObserver","set","terminals","querySelectorAll","join","filter","call","head","append","assign","rel","href","URL","url"],"mappings":"yGAMA,MAAMA,EAAY,GAIZC,EAAkBC,IAEpB,MADAC,EAAOD,GACD,IAAIE,MAAMF,EAAQ,EAGtBG,EAAa,EAAGC,YAAcC,cAAgBA,EAE9CC,EAAe,IAAIC,QAEzB,IAAIC,GAAW,EAKf,MAAMC,EAAc,EAAGC,cAAaC,KAAIC,MAAKC,SAAUC,WACnD,IAAKA,EAAKC,gBAAiB,OAK3BH,EACI,+EAGJ,IAAII,EAAO,GACX,MAAMC,gBAAEA,EAAeC,iBAAEA,GAAqBJ,EACxCK,EAAU,IAAIC,YACdC,EAAU,CACZC,QAAQ,EACRC,MAAMC,IACFR,EAAOG,EAAQM,OAAOD,GACtBN,EAAiBF,GACVQ,EAAOE,SAYtB,GAPAf,EAAGgB,OAAUC,IACTV,EAAiBW,OAAOD,EAAM5B,SAAW4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AI,0BAA2BC,eAK/C7E,EAAWE,EAAQ,GAEjC"}
@@ -0,0 +1,2 @@
1
+ var e={exports:{}},t=e.exports=(()=>{var e={6:(e,t)=>{function r(e){try{const t=new URL(e),r=t.password&&t.username?`${t.protocol}//${t.username}:${t.password}@${t.host}`:t.username?`${t.protocol}//${t.username}@${t.host}`:`${t.protocol}//${t.host}`;return e.toLocaleLowerCase().startsWith(r.toLocaleLowerCase())}catch(e){return!1}}Object.defineProperty(t,"__esModule",{value:!0}),t.LinkComputer=t.WebLinkProvider=void 0,t.WebLinkProvider=class{constructor(e,t,r,n={}){this._terminal=e,this._regex=t,this._handler=r,this._options=n}provideLinks(e,t){const r=n.computeLink(e,this._regex,this._terminal,this._handler);t(this._addCallbacks(r))}_addCallbacks(e){return e.map((e=>(e.leave=this._options.leave,e.hover=(t,r)=>{if(this._options.hover){const{range:n}=e;this._options.hover(t,r,n)}},e)))}};class n{static computeLink(e,t,s,o){const i=new RegExp(t.source,(t.flags||"")+"g"),[a,l]=n._getWindowedLineStrings(e-1,s),c=a.join("");let d;const p=[];for(;d=i.exec(c);){const e=d[0];if(!r(e))continue;const[t,i]=n._mapStrIdx(s,l,0,d.index),[a,c]=n._mapStrIdx(s,t,i,e.length);if(-1===t||-1===i||-1===a||-1===c)continue;const h={start:{x:i+1,y:t+1},end:{x:c,y:a+1}};p.push({range:h,text:e,activate:o})}return p}static _getWindowedLineStrings(e,t){let r,n=e,s=e,o=0,i="";const a=[];if(r=t.buffer.active.getLine(e)){const e=r.translateToString(!0);if(r.isWrapped&&" "!==e[0]){for(o=0;(r=t.buffer.active.getLine(--n))&&o<2048&&(i=r.translateToString(!0),o+=i.length,a.push(i),r.isWrapped&&-1===i.indexOf(" ")););a.reverse()}for(a.push(e),o=0;(r=t.buffer.active.getLine(++s))&&r.isWrapped&&o<2048&&(i=r.translateToString(!0),o+=i.length,a.push(i),-1===i.indexOf(" ")););}return[a,n]}static _mapStrIdx(e,t,r,n){const s=e.buffer.active,o=s.getNullCell();let i=r;for(;n;){const e=s.getLine(t);if(!e)return[-1,-1];for(let r=i;r<e.length;++r){e.getCell(r,o);const i=o.getChars();if(o.getWidth()&&(n-=i.length||1,r===e.length-1&&""===i)){const e=s.getLine(t+1);e&&e.isWrapped&&(e.getCell(0,o),2===o.getWidth()&&(n+=1))}if(n<0)return[t,r]}t++,i=0}return[t,i]}}t.LinkComputer=n}},t={};function r(n){var s=t[n];if(void 0!==s)return s.exports;var o=t[n]={exports:{}};return e[n](o,o.exports,r),o.exports}var n={};return(()=>{var e=n;Object.defineProperty(e,"__esModule",{value:!0}),e.WebLinksAddon=void 0;const t=r(6),s=/(https?|HTTPS?):[/]{2}[^\s"'!*(){}|\\\^<>`]*[^\s"':,.!?{}|\\\^~\[\]`()<>]/;function o(e,t){const r=window.open();if(r){try{r.opener=null}catch{}r.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}e.WebLinksAddon=class{constructor(e=o,t={}){this._handler=e,this._options=t}activate(e){this._terminal=e;const r=this._options,n=r.urlRegex||s;this._linkProvider=this._terminal.registerLinkProvider(new t.WebLinkProvider(this._terminal,n,this._handler,r))}dispose(){this._linkProvider?.dispose()}}})(),n})(),r=e.exports.WebLinksAddon,n=e.exports.__esModule;export{r as WebLinksAddon,n as __esModule,t as default};
2
+ //# sourceMappingURL=xterm_addon-web-links-Cnej-nJ6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"xterm_addon-web-links-Cnej-nJ6.js","sources":["../src/3rd-party/xterm_addon-web-links.js"],"sourcesContent":["/**\n * Bundled by jsDelivr using Rollup v2.79.1 and Terser v5.19.2.\n * Original file: /npm/@xterm/addon-web-links@0.11.0/lib/addon-web-links.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\nvar e={exports:{}};self;var t=e.exports=(()=>{var e={6:(e,t)=>{function r(e){try{const t=new URL(e),r=t.password&&t.username?`${t.protocol}//${t.username}:${t.password}@${t.host}`:t.username?`${t.protocol}//${t.username}@${t.host}`:`${t.protocol}//${t.host}`;return e.toLocaleLowerCase().startsWith(r.toLocaleLowerCase())}catch(e){return!1}}Object.defineProperty(t,\"__esModule\",{value:!0}),t.LinkComputer=t.WebLinkProvider=void 0,t.WebLinkProvider=class{constructor(e,t,r,n={}){this._terminal=e,this._regex=t,this._handler=r,this._options=n}provideLinks(e,t){const r=n.computeLink(e,this._regex,this._terminal,this._handler);t(this._addCallbacks(r))}_addCallbacks(e){return e.map((e=>(e.leave=this._options.leave,e.hover=(t,r)=>{if(this._options.hover){const{range:n}=e;this._options.hover(t,r,n)}},e)))}};class n{static computeLink(e,t,o,s){const i=new RegExp(t.source,(t.flags||\"\")+\"g\"),[a,l]=n._getWindowedLineStrings(e-1,o),c=a.join(\"\");let d;const p=[];for(;d=i.exec(c);){const e=d[0];if(!r(e))continue;const[t,i]=n._mapStrIdx(o,l,0,d.index),[a,c]=n._mapStrIdx(o,t,i,e.length);if(-1===t||-1===i||-1===a||-1===c)continue;const h={start:{x:i+1,y:t+1},end:{x:c,y:a+1}};p.push({range:h,text:e,activate:s})}return p}static _getWindowedLineStrings(e,t){let r,n=e,o=e,s=0,i=\"\";const a=[];if(r=t.buffer.active.getLine(e)){const e=r.translateToString(!0);if(r.isWrapped&&\" \"!==e[0]){for(s=0;(r=t.buffer.active.getLine(--n))&&s<2048&&(i=r.translateToString(!0),s+=i.length,a.push(i),r.isWrapped&&-1===i.indexOf(\" \")););a.reverse()}for(a.push(e),s=0;(r=t.buffer.active.getLine(++o))&&r.isWrapped&&s<2048&&(i=r.translateToString(!0),s+=i.length,a.push(i),-1===i.indexOf(\" \")););}return[a,n]}static _mapStrIdx(e,t,r,n){const o=e.buffer.active,s=o.getNullCell();let i=r;for(;n;){const e=o.getLine(t);if(!e)return[-1,-1];for(let r=i;r<e.length;++r){e.getCell(r,s);const i=s.getChars();if(s.getWidth()&&(n-=i.length||1,r===e.length-1&&\"\"===i)){const e=o.getLine(t+1);e&&e.isWrapped&&(e.getCell(0,s),2===s.getWidth()&&(n+=1))}if(n<0)return[t,r]}t++,i=0}return[t,i]}}t.LinkComputer=n}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var s=t[n]={exports:{}};return e[n](s,s.exports,r),s.exports}var n={};return(()=>{var e=n;Object.defineProperty(e,\"__esModule\",{value:!0}),e.WebLinksAddon=void 0;const t=r(6),o=/(https?|HTTPS?):[/]{2}[^\\s\"'!*(){}|\\\\\\^<>`]*[^\\s\"':,.!?{}|\\\\\\^~\\[\\]`()<>]/;function s(e,t){const r=window.open();if(r){try{r.opener=null}catch{}r.location.href=t}else console.warn(\"Opening link blocked as opener could not be cleared\")}e.WebLinksAddon=class{constructor(e=s,t={}){this._handler=e,this._options=t}activate(e){this._terminal=e;const r=this._options,n=r.urlRegex||o;this._linkProvider=this._terminal.registerLinkProvider(new t.WebLinkProvider(this._terminal,n,this._handler,r))}dispose(){this._linkProvider?.dispose()}}})(),n})(),r=e.exports.WebLinksAddon,n=e.exports.__esModule;export{r as WebLinksAddon,n as __esModule,t as default};\n"],"names":["e","exports","t","r","URL","password","username","protocol","host","toLocaleLowerCase","startsWith","Object","defineProperty","value","LinkComputer","WebLinkProvider","constructor","n","this","_terminal","_regex","_handler","_options","provideLinks","computeLink","_addCallbacks","map","leave","hover","range","o","s","i","RegExp","source","flags","a","l","_getWindowedLineStrings","c","join","d","p","exec","_mapStrIdx","index","length","h","start","x","y","end","push","text","activate","buffer","active","getLine","translateToString","isWrapped","indexOf","reverse","getNullCell","getCell","getChars","getWidth","WebLinksAddon","window","open","opener","location","href","console","warn","urlRegex","_linkProvider","registerLinkProvider","dispose","__esModule"],"mappings":"AAMA,IAAIA,EAAE,CAACC,QAAQ,CAAE,GAAWC,EAAEF,EAAEC,QAAQ,MAAM,IAAID,EAAE,CAAC,EAAE,CAACA,EAAEE,KAAK,SAASC,EAAEH,GAAG,IAAI,MAAME,EAAE,IAAIE,IAAIJ,GAAGG,EAAED,EAAEG,UAAUH,EAAEI,S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AAI,CAAC,MAAK,CAAElE,EAAEmE,SAASC,KAAKrE,CAAC,MAAMsE,QAAQC,KAAK,sDAAsD,CAACzE,EAAEkE,cAAc,MAAM,WAAAlD,CAAYhB,EAAE+B,EAAE7B,EAAE,CAAA,GAAIgB,KAAKG,SAASrB,EAAEkB,KAAKI,SAASpB,CAAC,CAAC,QAAAoD,CAAStD,GAAGkB,KAAKC,UAAUnB,EAAE,MAAMG,EAAEe,KAAKI,SAASL,EAAEd,EAAEuE,UAAU5C,EAAEZ,KAAKyD,cAAczD,KAAKC,UAAUyD,qBAAqB,IAAI1E,EAAEa,gBAAgBG,KAAKC,UAAUF,EAAEC,KAAKG,SAASlB,GAAG,CAAC,OAAA0E,GAAU3D,KAAKyD,eAAeE,SAAS,EAAG,EAA1nB,GAA8nB5D,CAAE,EAA1vF,GAA8vFd,EAAEH,EAAEC,QAAQiE,cAAcjD,EAAEjB,EAAEC,QAAQ6E"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pyscript/core",
3
- "version": "0.4.20",
3
+ "version": "0.4.21",
4
4
  "type": "module",
5
5
  "description": "PyScript",
6
6
  "module": "./index.js",
@@ -59,6 +59,7 @@
59
59
  "@rollup/plugin-terser": "^0.4.4",
60
60
  "@webreflection/toml-j0.4": "^1.1.3",
61
61
  "@xterm/addon-fit": "^0.10.0",
62
+ "@xterm/addon-web-links": "^0.11.0",
62
63
  "chokidar": "^3.6.0",
63
64
  "codemirror": "^6.0.1",
64
65
  "eslint": "^9.0.0",
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Bundled by jsDelivr using Rollup v2.79.1 and Terser v5.19.2.
3
+ * Original file: /npm/@xterm/addon-web-links@0.11.0/lib/addon-web-links.js
4
+ *
5
+ * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
6
+ */
7
+ var e={exports:{}};self;var t=e.exports=(()=>{var e={6:(e,t)=>{function r(e){try{const t=new URL(e),r=t.password&&t.username?`${t.protocol}//${t.username}:${t.password}@${t.host}`:t.username?`${t.protocol}//${t.username}@${t.host}`:`${t.protocol}//${t.host}`;return e.toLocaleLowerCase().startsWith(r.toLocaleLowerCase())}catch(e){return!1}}Object.defineProperty(t,"__esModule",{value:!0}),t.LinkComputer=t.WebLinkProvider=void 0,t.WebLinkProvider=class{constructor(e,t,r,n={}){this._terminal=e,this._regex=t,this._handler=r,this._options=n}provideLinks(e,t){const r=n.computeLink(e,this._regex,this._terminal,this._handler);t(this._addCallbacks(r))}_addCallbacks(e){return e.map((e=>(e.leave=this._options.leave,e.hover=(t,r)=>{if(this._options.hover){const{range:n}=e;this._options.hover(t,r,n)}},e)))}};class n{static computeLink(e,t,o,s){const i=new RegExp(t.source,(t.flags||"")+"g"),[a,l]=n._getWindowedLineStrings(e-1,o),c=a.join("");let d;const p=[];for(;d=i.exec(c);){const e=d[0];if(!r(e))continue;const[t,i]=n._mapStrIdx(o,l,0,d.index),[a,c]=n._mapStrIdx(o,t,i,e.length);if(-1===t||-1===i||-1===a||-1===c)continue;const h={start:{x:i+1,y:t+1},end:{x:c,y:a+1}};p.push({range:h,text:e,activate:s})}return p}static _getWindowedLineStrings(e,t){let r,n=e,o=e,s=0,i="";const a=[];if(r=t.buffer.active.getLine(e)){const e=r.translateToString(!0);if(r.isWrapped&&" "!==e[0]){for(s=0;(r=t.buffer.active.getLine(--n))&&s<2048&&(i=r.translateToString(!0),s+=i.length,a.push(i),r.isWrapped&&-1===i.indexOf(" ")););a.reverse()}for(a.push(e),s=0;(r=t.buffer.active.getLine(++o))&&r.isWrapped&&s<2048&&(i=r.translateToString(!0),s+=i.length,a.push(i),-1===i.indexOf(" ")););}return[a,n]}static _mapStrIdx(e,t,r,n){const o=e.buffer.active,s=o.getNullCell();let i=r;for(;n;){const e=o.getLine(t);if(!e)return[-1,-1];for(let r=i;r<e.length;++r){e.getCell(r,s);const i=s.getChars();if(s.getWidth()&&(n-=i.length||1,r===e.length-1&&""===i)){const e=o.getLine(t+1);e&&e.isWrapped&&(e.getCell(0,s),2===s.getWidth()&&(n+=1))}if(n<0)return[t,r]}t++,i=0}return[t,i]}}t.LinkComputer=n}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var s=t[n]={exports:{}};return e[n](s,s.exports,r),s.exports}var n={};return(()=>{var e=n;Object.defineProperty(e,"__esModule",{value:!0}),e.WebLinksAddon=void 0;const t=r(6),o=/(https?|HTTPS?):[/]{2}[^\s"'!*(){}|\\\^<>`]*[^\s"':,.!?{}|\\\^~\[\]`()<>]/;function s(e,t){const r=window.open();if(r){try{r.opener=null}catch{}r.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}e.WebLinksAddon=class{constructor(e=s,t={}){this._handler=e,this._options=t}activate(e){this._terminal=e;const r=this._options,n=r.urlRegex||o;this._linkProvider=this._terminal.registerLinkProvider(new t.WebLinkProvider(this._terminal,n,this._handler,r))}dispose(){this._linkProvider?.dispose()}}})(),n})(),r=e.exports.WebLinksAddon,n=e.exports.__esModule;export{r as WebLinksAddon,n as __esModule,t as default};
@@ -134,11 +134,15 @@ const workerReady = ({ interpreter, io, run, type }, { sync }) => {
134
134
 
135
135
  const pyTerminal = async (element) => {
136
136
  // lazy load these only when a valid terminal is found
137
- const [{ Terminal }, { Readline }, { FitAddon }] = await Promise.all([
138
- import(/* webpackIgnore: true */ "../3rd-party/xterm.js"),
139
- import(/* webpackIgnore: true */ "../3rd-party/xterm-readline.js"),
140
- import(/* webpackIgnore: true */ "../3rd-party/xterm_addon-fit.js"),
141
- ]);
137
+ const [{ Terminal }, { Readline }, { FitAddon }, { WebLinksAddon }] =
138
+ await Promise.all([
139
+ import(/* webpackIgnore: true */ "../3rd-party/xterm.js"),
140
+ import(/* webpackIgnore: true */ "../3rd-party/xterm-readline.js"),
141
+ import(/* webpackIgnore: true */ "../3rd-party/xterm_addon-fit.js"),
142
+ import(
143
+ /* webpackIgnore: true */ "../3rd-party/xterm_addon-web-links.js"
144
+ ),
145
+ ]);
142
146
 
143
147
  const readline = new Readline();
144
148
 
@@ -167,6 +171,7 @@ const pyTerminal = async (element) => {
167
171
  const fitAddon = new FitAddon();
168
172
  terminal.loadAddon(fitAddon);
169
173
  terminal.loadAddon(readline);
174
+ terminal.loadAddon(new WebLinksAddon());
170
175
  terminal.open(target);
171
176
  fitAddon.fit();
172
177
  terminal.focus();
@@ -0,0 +1,4 @@
1
+ declare var r: any;
2
+ declare var n: any;
3
+ declare var t: {};
4
+ export { r as WebLinksAddon, n as __esModule, t as default };
@@ -1,2 +0,0 @@
1
- import{T as e,c as t,e as r,a as n}from"./core-2NwtOg82.js";import{notify as i}from"./error-CYOIlKpM.js";const o=[],s=e=>{throw i(e),new Error(e)},a=({attributes:{worker:e}})=>!e,l=new WeakSet;let d=!0;const c=({interpreter:e,io:t,run:r,type:n},{sync:i})=>{if(!i.is_pyterminal())return;r("from polyscript import currentScript as _; __terminal__ = _.terminal; del _");let o="";const{pyterminal_read:s,pyterminal_write:a}=i,l=new TextDecoder,d={isatty:!1,write:e=>(o=l.decode(e),a(o),e.length)};if(t.stderr=e=>{a(String(e.message||e))},"mpy"===n){e.registerJsModule("_pyscript_input",{input:s}),r("from _pyscript_input import input");const n=e=>{const t=[];let r=0;return n=>{let i=0;for(const o of n)t.push(o),r?r--:194<=o&&o<=223?r=1:224<=o&&o<=239?r=2:240<=o&&o<=244&&(r=3),r||(i+=t.length,e(new Uint8Array(t.splice(0))));return i}};t.stdout=n(d.write),e.registerJsModule("code",{interact(){let r="",i=1;const o=new TextEncoder,d=[],c=n((e=>{d.push(...e),a(l.decode(e))}));t.stdout=e=>i++>r.length?c(e):0,e.replInit(),function t(){const n=l.decode(new Uint8Array(d.splice(0))),a=`${s(n.split("\n").at(-1))}\r`;i=0,r=o.encode(a);for(const t of r)e.replProcessChar(t);t()}()}})}else e.setStdout(d),e.setStderr(d),e.setStdin({isatty:!1,stdin:()=>s(o)})},m=async e=>{const[{Terminal:t},{Readline:i},{FitAddon:o}]=await Promise.all([import("./xterm-DqawCVsv.js"),import("./xterm-readline-D247p8vq.js"),import("./xterm_addon-fit--gyF3PcZ.js")]),s=new i,a=r=>{let i=e;const a=e.getAttribute("target");if(a){if(i=document.getElementById(a)||document.querySelector(a),!i)throw new Error(`Unknown target ${a}`)}else i=document.createElement("py-terminal"),i.style.display="block",e.after(i);const l=new t({theme:{background:"#191A19",foreground:"#F5F2E7"},...r}),d=new o;return l.loadAddon(d),l.loadAddon(s),l.open(i),d.fit(),l.focus(),n(e,{terminal:{value:l},process:{value:async e=>{for(const t of e.split(/(?:\r|\n|\r\n)/)){l.paste(`${t}\n`);do{await new Promise((e=>setTimeout(e,0)))}while(!s.activeRead?.resolve);s.activeRead.resolve(t)}}}}),l};e.hasAttribute("worker")?(r.main.onWorker.add((function e(t,n){l.has(n)||(l.add(n),r.main.onWorker.delete(e),a({disableStdin:!1,cursorBlink:!0,cursorStyle:"block"}),n.sync.is_pyterminal=()=>!0,n.sync.pyterminal_read=s.read.bind(s),n.sync.pyterminal_write=s.write.bind(s))})),r.worker.onReady.add(c)):r.main.onReady.add((function e({interpreter:t,io:n,run:i,type:o}){console.warn("py-terminal is read only on main thread"),r.main.onReady.delete(e),globalThis.__py_terminal__=a({disableStdin:!0,cursorBlink:!1,cursorStyle:"underline"}),i("from js import __py_terminal__ as __terminal__"),delete globalThis.__py_terminal__,n.stderr=e=>{s.write(String(e.message||e))},"mpy"===o&&(t.setStdin=Object,t.setStderr=Object,t.setStdout=({write:e})=>{n.stdout=e});let l="";const d=new TextDecoder,c={isatty:!1,write:e=>(l=d.decode(e),s.write(l),e.length)};t.setStdout(c),t.setStderr(c),t.setStdin({isatty:!1,stdin:()=>s.read(l)})}))};for(const r of e.keys()){const e=`script[type="${r}"][terminal],${r}-script[terminal]`;o.push(e),t.set(e,(async e=>{const t=document.querySelectorAll(o.join(","));[].filter.call(t,a).length>1&&s("You can use at most 1 main terminal"),d&&(d=!1,document.head.append(Object.assign(document.createElement("link"),{rel:"stylesheet",href:new URL("./xterm.css",import.meta.url)}))),await m(e)}))}
2
- //# sourceMappingURL=py-terminal-4lUBhmlJ.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"py-terminal-4lUBhmlJ.js","sources":["../src/plugins/py-terminal.js"],"sourcesContent":["// PyScript py-terminal plugin\nimport { TYPES, hooks } from \"../core.js\";\nimport { notify } from \"./error.js\";\nimport { customObserver, defineProperties } from \"polyscript/exports\";\n\n// will contain all valid selectors\nconst SELECTORS = [];\n\n// show the error on main and\n// stops the module from keep executing\nconst notifyAndThrow = (message) => {\n notify(message);\n throw new Error(message);\n};\n\nconst onceOnMain = ({ attributes: { worker } }) => !worker;\n\nconst bootstrapped = new WeakSet();\n\nlet addStyle = true;\n\n// this callback will be serialized as string and it never needs\n// to be invoked multiple times. Each xworker here is bootstrapped\n// only once thanks to the `sync.is_pyterminal()` check.\nconst workerReady = ({ interpreter, io, run, type }, { sync }) => {\n if (!sync.is_pyterminal()) return;\n\n // in workers it's always safe to grab the polyscript currentScript\n // the ugly `_` dance is due MicroPython not able to import via:\n // `from polyscript.currentScript import terminal as __terminal__`\n run(\n \"from polyscript import currentScript as _; __terminal__ = _.terminal; del _\",\n );\n\n let data = \"\";\n const { pyterminal_read, pyterminal_write } = sync;\n const decoder = new TextDecoder();\n const generic = {\n isatty: false,\n write(buffer) {\n data = decoder.decode(buffer);\n pyterminal_write(data);\n return buffer.length;\n },\n };\n\n // This part works already in both Pyodide and MicroPython\n io.stderr = (error) => {\n pyterminal_write(String(error.message || error));\n };\n\n // MicroPython has no code or code.interact()\n // This part patches it in a way that simulates\n // the code.interact() module in Pyodide.\n if (type === \"mpy\") {\n // monkey patch global input otherwise broken in MicroPython\n interpreter.registerJsModule(\"_pyscript_input\", {\n input: pyterminal_read,\n });\n run(\"from _pyscript_input import input\");\n\n // this is needed to avoid truncated unicode in MicroPython\n // the reason is that `linebuffer` false just send one byte\n // per time and readline here doesn't like it much.\n // MicroPython also has issues with code-points and\n // replProcessChar(byte) but that function accepts only\n // one byte per time so ... we have an issue!\n // @see https://github.com/pyscript/pyscript/pull/2018\n // @see https://github.com/WebReflection/buffer-points\n const bufferPoints = (stdio) => {\n const bytes = [];\n let needed = 0;\n return (buffer) => {\n let written = 0;\n for (const byte of buffer) {\n bytes.push(byte);\n // @see https://encoding.spec.whatwg.org/#utf-8-bytes-needed\n if (needed) needed--;\n else if (0xc2 <= byte && byte <= 0xdf) needed = 1;\n else if (0xe0 <= byte && byte <= 0xef) needed = 2;\n else if (0xf0 <= byte && byte <= 0xf4) needed = 3;\n if (!needed) {\n written += bytes.length;\n stdio(new Uint8Array(bytes.splice(0)));\n }\n }\n return written;\n };\n };\n\n io.stdout = bufferPoints(generic.write);\n\n // tiny shim of the code module with only interact\n // to bootstrap a REPL like environment\n interpreter.registerJsModule(\"code\", {\n interact() {\n let input = \"\";\n let length = 1;\n\n const encoder = new TextEncoder();\n const acc = [];\n const handlePoints = bufferPoints((buffer) => {\n acc.push(...buffer);\n pyterminal_write(decoder.decode(buffer));\n });\n\n // avoid duplicating the output produced by the input\n io.stdout = (buffer) =>\n length++ > input.length ? handlePoints(buffer) : 0;\n\n interpreter.replInit();\n\n // loop forever waiting for user inputs\n (function repl() {\n const out = decoder.decode(new Uint8Array(acc.splice(0)));\n // print in current line only the last line produced by the REPL\n const data = `${pyterminal_read(out.split(\"\\n\").at(-1))}\\r`;\n length = 0;\n input = encoder.encode(data);\n for (const c of input) interpreter.replProcessChar(c);\n repl();\n })();\n },\n });\n } else {\n interpreter.setStdout(generic);\n interpreter.setStderr(generic);\n interpreter.setStdin({\n isatty: false,\n stdin: () => pyterminal_read(data),\n });\n }\n};\n\nconst pyTerminal = async (element) => {\n // lazy load these only when a valid terminal is found\n const [{ Terminal }, { Readline }, { FitAddon }] = await Promise.all([\n import(/* webpackIgnore: true */ \"../3rd-party/xterm.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/xterm-readline.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/xterm_addon-fit.js\"),\n ]);\n\n const readline = new Readline();\n\n // common main thread initialization for both worker\n // or main case, bootstrapping the terminal on its target\n const init = (options) => {\n let target = element;\n const selector = element.getAttribute(\"target\");\n if (selector) {\n target =\n document.getElementById(selector) ||\n document.querySelector(selector);\n if (!target) throw new Error(`Unknown target ${selector}`);\n } else {\n target = document.createElement(\"py-terminal\");\n target.style.display = \"block\";\n element.after(target);\n }\n const terminal = new Terminal({\n theme: {\n background: \"#191A19\",\n foreground: \"#F5F2E7\",\n },\n ...options,\n });\n const fitAddon = new FitAddon();\n terminal.loadAddon(fitAddon);\n terminal.loadAddon(readline);\n terminal.open(target);\n fitAddon.fit();\n terminal.focus();\n defineProperties(element, {\n terminal: { value: terminal },\n process: {\n value: async (code) => {\n // this loop is the only way I could find to actually simulate\n // the user input char after char in a way that works in both\n // MicroPython and Pyodide\n for (const line of code.split(/(?:\\r|\\n|\\r\\n)/)) {\n terminal.paste(`${line}\\n`);\n do {\n await new Promise((resolve) =>\n setTimeout(resolve, 0),\n );\n } while (!readline.activeRead?.resolve);\n readline.activeRead.resolve(line);\n }\n },\n },\n });\n return terminal;\n };\n\n // branch logic for the worker\n if (element.hasAttribute(\"worker\")) {\n // add a hook on the main thread to setup all sync helpers\n // also bootstrapping the XTerm target on main *BUT* ...\n hooks.main.onWorker.add(function worker(_, xworker) {\n // ... as multiple workers will add multiple callbacks\n // be sure no xworker is ever initialized twice!\n if (bootstrapped.has(xworker)) return;\n bootstrapped.add(xworker);\n\n // still cleanup this callback for future scripts/workers\n hooks.main.onWorker.delete(worker);\n\n init({\n disableStdin: false,\n cursorBlink: true,\n cursorStyle: \"block\",\n });\n\n xworker.sync.is_pyterminal = () => true;\n xworker.sync.pyterminal_read = readline.read.bind(readline);\n xworker.sync.pyterminal_write = readline.write.bind(readline);\n });\n\n // setup remote thread JS/Python code for whenever the\n // worker is ready to become a terminal\n hooks.worker.onReady.add(workerReady);\n } else {\n // in the main case, just bootstrap XTerm without\n // allowing any input as that's not possible / awkward\n hooks.main.onReady.add(function main({ interpreter, io, run, type }) {\n console.warn(\"py-terminal is read only on main thread\");\n hooks.main.onReady.delete(main);\n\n // on main, it's easy to trash and clean the current terminal\n globalThis.__py_terminal__ = init({\n disableStdin: true,\n cursorBlink: false,\n cursorStyle: \"underline\",\n });\n run(\"from js import __py_terminal__ as __terminal__\");\n delete globalThis.__py_terminal__;\n\n io.stderr = (error) => {\n readline.write(String(error.message || error));\n };\n\n if (type === \"mpy\") {\n interpreter.setStdin = Object; // as no-op\n interpreter.setStderr = Object; // as no-op\n interpreter.setStdout = ({ write }) => {\n io.stdout = write;\n };\n }\n\n let data = \"\";\n const decoder = new TextDecoder();\n const generic = {\n isatty: false,\n write(buffer) {\n data = decoder.decode(buffer);\n readline.write(data);\n return buffer.length;\n },\n };\n interpreter.setStdout(generic);\n interpreter.setStderr(generic);\n interpreter.setStdin({\n isatty: false,\n stdin: () => readline.read(data),\n });\n });\n }\n};\n\nfor (const key of TYPES.keys()) {\n const selector = `script[type=\"${key}\"][terminal],${key}-script[terminal]`;\n SELECTORS.push(selector);\n customObserver.set(selector, async (element) => {\n // we currently support only one terminal on main as in \"classic\"\n const terminals = document.querySelectorAll(SELECTORS.join(\",\"));\n if ([].filter.call(terminals, onceOnMain).length > 1)\n notifyAndThrow(\"You can use at most 1 main terminal\");\n\n // import styles lazily\n if (addStyle) {\n addStyle = false;\n document.head.append(\n Object.assign(document.createElement(\"link\"), {\n rel: \"stylesheet\",\n href: new URL(\"./xterm.css\", import.meta.url),\n }),\n );\n }\n\n await pyTerminal(element);\n });\n}\n"],"names":["SELECTORS","notifyAndThrow","message","notify","Error","onceOnMain","attributes","worker","bootstrapped","WeakSet","addStyle","workerReady","interpreter","io","run","type","sync","is_pyterminal","data","pyterminal_read","pyterminal_write","decoder","TextDecoder","generic","isatty","write","buffer","decode","length","stderr","error","String","registerJsModule","input","bufferPoints","stdio","bytes","needed","written","byte","push","Uint8Array","splice","stdout","interact","encoder","TextEncoder","acc","handlePoints","replInit","repl","out","split","at","encode","c","replProcessChar","setStdout","setStderr","setStdin","stdin","pyTerminal","async","element","Terminal","Readline","FitAddon","Promise","all","import","readline","init","options","target","selector","getAttribute","document","getElementById","querySelector","createElement","style","display","after","terminal","theme","background","foreground","fitAddon","loadAddon","open","fit","focus","defineProperties","value","process","code","line","paste","resolve","setTimeout","activeRead","hasAttribute","hooks","main","onWorker","add","_","xworker","has","delete","disableStdin","cursorBlink","cursorStyle","read","bind","onReady","console","warn","globalThis","__py_terminal__","Object","key","TYPES","keys","customObserver","set","terminals","querySelectorAll","join","filter","call","head","append","assign","rel","href","URL","url"],"mappings":"yGAMA,MAAMA,EAAY,GAIZC,EAAkBC,IAEpB,MADAC,EAAOD,GACD,IAAIE,MAAMF,EAAQ,EAGtBG,EAAa,EAAGC,YAAcC,cAAgBA,EAE9CC,EAAe,IAAIC,QAEzB,IAAIC,GAAW,EAKf,MAAMC,EAAc,EAAGC,cAAaC,KAAIC,MAAKC,SAAUC,WACnD,IAAKA,EAAKC,gBAAiB,OAK3BH,EACI,+EAGJ,IAAII,EAAO,GACX,MAAMC,gBAAEA,EAAeC,iBAAEA,GAAqBJ,EACxCK,EAAU,IAAIC,YACdC,EAAU,CACZC,QAAQ,EACRC,MAAMC,IACFR,EAAOG,EAAQM,OAAOD,GACtBN,EAAiBF,GACVQ,EAAOE,SAYtB,GAPAf,EAAGgB,OAAUC,IACTV,EAAiBW,OAAOD,EAAM5B,SAAW4B,GAAO,EAMvC,QAATf,EAAgB,CAEhBH,EAAYoB,iBAAiB,kBAAmB,CAC5CC,MAAOd,IAEXL,EAAI,qCAUJ,MAAMoB,EAAgBC,IAClB,MAAMC,EAAQ,GACd,IAAIC,EAAS,EACb,OAAQX,IACJ,IAAIY,EAAU,EACd,IAAK,MAAMC,KAAQb,EACfU,EAAMI,KAAKD,GAEPF,EAAQA,IACH,KAAQE,GAAQA,GAAQ,IAAMF,EAAS,EACvC,KAAQE,GAAQA,GAAQ,IAAMF,EAAS,EACvC,KAAQE,GAAQA,GA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