@pyscript/core 0.3.9 → 0.3.10

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{a as PyWorker,T as TYPES,b as config,e as hooks,c as whenDefined}from"./core-ifSZyON7.js";
1
+ export{a as PyWorker,T as TYPES,b as config,e as hooks,c as whenDefined}from"./core-HRYUl_m-.js";
2
2
  //# sourceMappingURL=core.js.map
@@ -1,2 +1,2 @@
1
- import{e}from"./core-ifSZyON7.js";import{notify as o}from"./error-ZSXf8h5x.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-u20LUlLl.js.map
1
+ import{e}from"./core-HRYUl_m-.js";import{notify as o}from"./error-YvVW0ykk.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-rPh7IQGA.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"deprecations-manager-u20LUlLl.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-rPh7IQGA.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-ifSZyON7.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-ZSXf8h5x.js.map
1
+ import{e}from"./core-HRYUl_m-.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-YvVW0ykk.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"error-ZSXf8h5x.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-YvVW0ykk.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 e,d as t,X as r,H as n}from"./core-ifSZyON7.js";let o=0;const i=e=>`${e}-editor-${o++}`,s=new Map,a={worker:{onReady:({runAsync:e,io:t},{sync:r})=>{t.stdout=e=>r.write(e),t.stderr=e=>r.writeErr(e),r.revoke(),r.runAsync=e}}};async function c({currentTarget:e}){const{env:t,pySrc:o,outDiv:i}=this;if(e.disabled=!0,i.innerHTML="",!s.has(t)){const e=URL.createObjectURL(new Blob([""])),o=r.call(new n(null,a),e,{type:this.interpreter}),{sync:i}=o,{promise:c,resolve:l}=Promise.withResolvers();s.set(t,c),i.revoke=()=>{URL.revokeObjectURL(e),l(o)}}s.get(t).then((t=>{t.onerror=({error:e})=>{i.innerHTML+=`<span style='color:red'>${e.message||e}</span>\n`,console.error(e)};const r=()=>{e.disabled=!1},{sync:n}=t;n.write=e=>{i.innerText+=`${e}\n`},n.writeErr=e=>{i.innerHTML+=`<span style='color:red'>${e}</span>\n`},n.runAsync(o).then(r,r)}))}const l=(e,t)=>{const r=document.createElement("div");r.className=`${t}-editor-input`,r.setAttribute("aria-label","Python Script Area");const n=((e,t)=>{const r=document.createElement("button");return r.className=`absolute ${t}-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",e),r})(e,t),o=document.createElement("div");return o.addEventListener("keydown",(e=>{e.stopPropagation()})),r.append(n,o),r},d=(e,t)=>{const r=document.createElement("div");r.className=`${t}-editor-box`;const n=l(e,t),o=(e=>{const t=document.createElement("div");return t.className=`${e}-editor-output`,t.id=`${i(e)}-output`,t})(t);return r.append(n,o),[r,o]},u=async(e,r,n)=>{const[{basicSetup:o,EditorView:s},{Compartment:a},{python:l},{indentUnit:u},{keymap:m},{defaultKeymap:p}]=await Promise.all([import("./codemirror-3hMOlj_s.js"),import("./codemirror_state-zH-H1oSI.js"),import("./codemirror_lang-python-p0uky9oC.js"),import("./codemirror_language-U9l5bLBC.js").then((function(e){return e.x})),import("./codemirror_view-tmIj4olz.js").then((function(e){return e.q})),import("./codemirror_commands-Y4OsE8Y2.js")]),y=e.getAttribute("target");let v;if(y){if(v=document.getElementById(y)||document.querySelector(y),!v)throw new Error(`Unknown target ${y}`)}else v=document.createElement(`${r}-editor`),v.style.display="block",e.after(v);v.id||(v.id=i(r)),v.hasAttribute("exec-id")||v.setAttribute("exec-id",0),v.hasAttribute("root")||v.setAttribute("root",v.id);const f=`${n}-${e.getAttribute("env")||i(r)}`,g={interpreter:n,env:f,get pySrc(){return L.state.doc.toString()},get outDiv(){return w}},h=c.bind(g),[b,w]=d(h,r);b.dataset.env=e.hasAttribute("env")?f:n;const E=b.querySelector(`.${r}-editor-input > div`).attachShadow({mode:"open"});E.innerHTML="<style> :host { all: initial; }</style>",v.appendChild(b);const $=t(e.textContent).trim(),A=/^(\s+)/m.test($)?RegExp.$1:" ",L=new s({extensions:[u.of(A),(new a).of(l()),m.of([...p,{key:"Ctrl-Enter",run:h,preventDefault:!0},{key:"Cmd-Enter",run:h,preventDefault:!0},{key:"Shift-Enter",run:h,preventDefault:!0}]),o],parent:E,doc:$});L.focus()};let m=0;const p=()=>{m=0,y()},y=async()=>{if(!m){m=setTimeout(p,250);for(const[t,r]of e){const e=`script[type="${t}-editor"]`;for(const n of document.querySelectorAll(e))n.type+="-active",await u(n,t,r)}}};new MutationObserver(y).observe(document,{childList:!0,subtree:!0});var v=y();export{v as default};
2
- //# sourceMappingURL=py-editor-HVgDslnW.js.map
1
+ import{T as e,d as t,X as r,H as n}from"./core-HRYUl_m-.js";let o=0;const i=e=>`${e}-editor-${o++}`,s=new Map,a={worker:{onReady:({runAsync:e,io:t},{sync:r})=>{t.stdout=e=>r.write(e),t.stderr=e=>r.writeErr(e),r.revoke(),r.runAsync=e}}};async function c({currentTarget:e}){const{env:t,pySrc:o,outDiv:i}=this;if(e.disabled=!0,i.innerHTML="",!s.has(t)){const e=URL.createObjectURL(new Blob([""])),o=r.call(new n(null,a),e,{type:this.interpreter}),{sync:i}=o,{promise:c,resolve:l}=Promise.withResolvers();s.set(t,c),i.revoke=()=>{URL.revokeObjectURL(e),l(o)}}s.get(t).then((t=>{t.onerror=({error:e})=>{i.innerHTML+=`<span style='color:red'>${e.message||e}</span>\n`,console.error(e)};const r=()=>{e.disabled=!1},{sync:n}=t;n.write=e=>{i.innerText+=`${e}\n`},n.writeErr=e=>{i.innerHTML+=`<span style='color:red'>${e}</span>\n`},n.runAsync(o).then(r,r)}))}const l=(e,t)=>{const r=document.createElement("div");r.className=`${t}-editor-input`,r.setAttribute("aria-label","Python Script Area");const n=((e,t)=>{const r=document.createElement("button");return r.className=`absolute ${t}-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",e),r})(e,t),o=document.createElement("div");return o.addEventListener("keydown",(e=>{e.stopPropagation()})),r.append(n,o),r},d=(e,t)=>{const r=document.createElement("div");r.className=`${t}-editor-box`;const n=l(e,t),o=(e=>{const t=document.createElement("div");return t.className=`${e}-editor-output`,t.id=`${i(e)}-output`,t})(t);return r.append(n,o),[r,o]},u=async(e,r,n)=>{const[{basicSetup:o,EditorView:s},{Compartment:a},{python:l},{indentUnit:u},{keymap:m},{defaultKeymap:p}]=await Promise.all([import("./codemirror-3hMOlj_s.js"),import("./codemirror_state-zH-H1oSI.js"),import("./codemirror_lang-python-p0uky9oC.js"),import("./codemirror_language-U9l5bLBC.js").then((function(e){return e.x})),import("./codemirror_view-tmIj4olz.js").then((function(e){return e.q})),import("./codemirror_commands-Y4OsE8Y2.js")]),y=e.getAttribute("target");let v;if(y){if(v=document.getElementById(y)||document.querySelector(y),!v)throw new Error(`Unknown target ${y}`)}else v=document.createElement(`${r}-editor`),v.style.display="block",e.after(v);v.id||(v.id=i(r)),v.hasAttribute("exec-id")||v.setAttribute("exec-id",0),v.hasAttribute("root")||v.setAttribute("root",v.id);const f=`${n}-${e.getAttribute("env")||i(r)}`,g={interpreter:n,env:f,get pySrc(){return L.state.doc.toString()},get outDiv(){return w}},h=c.bind(g),[b,w]=d(h,r);b.dataset.env=e.hasAttribute("env")?f:n;const E=b.querySelector(`.${r}-editor-input > div`).attachShadow({mode:"open"});E.innerHTML="<style> :host { all: initial; }</style>",v.appendChild(b);const $=t(e.textContent).trim(),A=/^(\s+)/m.test($)?RegExp.$1:" ",L=new s({extensions:[u.of(A),(new a).of(l()),m.of([...p,{key:"Ctrl-Enter",run:h,preventDefault:!0},{key:"Cmd-Enter",run:h,preventDefault:!0},{key:"Shift-Enter",run:h,preventDefault:!0}]),o],parent:E,doc:$});L.focus()};let m=0;const p=()=>{m=0,y()},y=async()=>{if(!m){m=setTimeout(p,250);for(const[t,r]of e){const e=`script[type="${t}-editor"]`;for(const n of document.querySelectorAll(e))n.type+="-active",await u(n,t,r)}}};new MutationObserver(y).observe(document,{childList:!0,subtree:!0});var v=y();export{v as default};
2
+ //# sourceMappingURL=py-editor-5GWEvCXg.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"py-editor-HVgDslnW.js","sources":["../src/plugins/py-editor.js"],"sourcesContent":["// PyScript py-editor plugin\nimport { Hook, XWorker, dedent } from \"polyscript/exports\";\nimport { TYPES } 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();\n\nconst hooks = {\n worker: {\n // works on both Pyodide and MicroPython\n onReady: ({ runAsync, io }, { sync }) => {\n io.stdout = (line) => sync.write(line);\n io.stderr = (line) => sync.writeErr(line);\n sync.revoke();\n sync.runAsync = runAsync;\n },\n },\n};\n\nasync function execute({ currentTarget }) {\n const { env, pySrc, outDiv } = this;\n\n currentTarget.disabled = true;\n outDiv.innerHTML = \"\";\n\n if (!envs.has(env)) {\n const srcLink = URL.createObjectURL(new Blob([\"\"]));\n const xworker = XWorker.call(new Hook(null, hooks), srcLink, {\n type: this.interpreter,\n });\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 outDiv.innerHTML += `<span style='color:red'>${\n error.message || error\n }</span>\\n`;\n console.error(error);\n };\n\n const enable = () => {\n currentTarget.disabled = false;\n };\n const { sync } = xworker;\n sync.write = (str) => {\n outDiv.innerText += `${str}\\n`;\n };\n sync.writeErr = (str) => {\n outDiv.innerHTML += `<span style='color:red'>${str}</span>\\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 // TODO: find a way to actually produce these bundles locally\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 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 const env = `${interpreter}-${script.getAttribute(\"env\") || getID(type)}`;\n const context = {\n interpreter,\n env,\n get pySrc() {\n return editor.state.doc.toString();\n },\n get outDiv() {\n return outDiv;\n },\n };\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// 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 = async () => {\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\n script.type += \"-active\";\n await init(script, type, interpreter);\n }\n }\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","hooks","worker","onReady","runAsync","io","sync","stdout","line","write","stderr","writeErr","revoke","async","execute","currentTarget","env","pySrc","outDiv","this","disabled","innerHTML","has","srcLink","URL","createObjectURL","Blob","xworker","XWorker","call","Hook","interpreter","promise","resolve","Promise","withResolvers","set","revokeObjectURL","get","then","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","import","n","x","q","selector","getAttribute","target","getElementById","querySelector","Error","style","display","after","hasAttribute","context","editor","state","doc","toString","bind","dataset","parent","attachShadow","mode","appendChild","dedent","textContent","trim","indentation","test","RegExp","$1","extensions","of","key","run","preventDefault","focus","timeout","resetTimeout","pyEditor","setTimeout","TYPES","querySelectorAll","MutationObserver","observe","childList","subtree","pyEditor$1"],"mappings":"4DAMA,IAAIA,EAAK,EACT,MAAMC,EAASC,GAAS,GAAGA,YAAeF,MAEpCG,EAAO,IAAIC,IAEXC,EAAQ,CACVC,OAAQ,CAEJC,QAAS,EAAGC,WAAUC,OAAQC,WAC1BD,EAAGE,OAAUC,GAASF,EAAKG,MAAMD,GACjCH,EAAGK,OAAUF,GAASF,EAAKK,SAASH,GACpCF,EAAKM,SACLN,EAAKF,SAAWA,CAAQ,IAKpCS,eAAeC,GAAQC,cAAEA,IACrB,MAAMC,IAAEA,EAAGC,MAAEA,EAAKC,OAAEA,GAAWC,KAK/B,GAHAJ,EAAcK,UAAW,EACzBF,EAAOG,UAAY,IAEdtB,EAAKuB,IAAIN,GAAM,CAChB,MAAMO,EAAUC,IAAIC,gBAAgB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,GAIC8B,EAAWlC,EAAQ+E,KAAKL,IACvB1B,EAAQ5C,GAAU2C,EAAWb,EAAUlD,GAC9CgE,EAAOgC,QAAQ9E,IAAMiD,EAAOsB,aAAa,OAASvE,EAAMe,EAExD,MACMgE,EADajC,EAAOoB,cAAc,IAAIpF,wBAClBkG,aAAa,CAAEC,KAAM,SAE/CF,EAAO1E,UAAY,0CAEnB2D,EAAOkB,YAAYpC,GAEnB,MAAM6B,EAAMQ,EAAOlC,EAAOmC,aAAaC,OAGjCC,EAAc,UAAUC,KAAKZ,GAAOa,OAAOC,GAAK,OAEhDhB,EAAS,IAAItB,EAAW,CAC1BuC,WAAY,CACRpC,EAAWqC,GAAGL,IACd,IAAIlC,GAAcuC,GAAGtC,KACrBE,EAAOoC,GAAG,IACHnC,EACH,CAAEoC,IAAK,aAAcC,IAAK7D,EAAU8D,gBAAgB,GACpD,CAAEF,IAAK,YAAaC,IAAK7D,EAAU8D,gBAAgB,GACnD,CAAEF,IAAK,cAAeC,IAAK7D,EAAU8D,gBAAgB,KAEzD5C,GAEJ6B,SACAJ,QAGJF,EAAOsB,OAAO,EAIlB,IAAIC,EAAU,EAGd,MAAMC,EAAe,KACjBD,EAAU,EACVE,GAAU,EAIRA,EAAWrG,UACb,IAAImG,EAAJ,CACAA,EAAUG,WAAWF,EAAc,KACnC,IAAK,MAAOnH,EAAMiC,KAAgBqF,EAAO,CACrC,MAAMtC,EAAW,gBAAgBhF,aACjC,IAAK,MAAMmE,KAAUf,SAASmE,iBAAiBvC,GAE3Cb,EAAOnE,MAAQ,gBACTkE,EAAKC,EAAQnE,EAAMiC,EAEhC,CATmB,CASnB,EAGL,IAAIuF,iBAAiBJ,GAAUK,QAAQrE,SAAU,CAC7CsE,WAAW,EACXC,SAAS,IAIb,IAAAC,EAAeR"}
1
+ {"version":3,"file":"py-editor-5GWEvCXg.js","sources":["../src/plugins/py-editor.js"],"sourcesContent":["// PyScript py-editor plugin\nimport { Hook, XWorker, dedent } from \"polyscript/exports\";\nimport { TYPES } 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();\n\nconst hooks = {\n worker: {\n // works on both Pyodide and MicroPython\n onReady: ({ runAsync, io }, { sync }) => {\n io.stdout = (line) => sync.write(line);\n io.stderr = (line) => sync.writeErr(line);\n sync.revoke();\n sync.runAsync = runAsync;\n },\n },\n};\n\nasync function execute({ currentTarget }) {\n const { env, pySrc, outDiv } = this;\n\n currentTarget.disabled = true;\n outDiv.innerHTML = \"\";\n\n if (!envs.has(env)) {\n const srcLink = URL.createObjectURL(new Blob([\"\"]));\n const xworker = XWorker.call(new Hook(null, hooks), srcLink, {\n type: this.interpreter,\n });\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 outDiv.innerHTML += `<span style='color:red'>${\n error.message || error\n }</span>\\n`;\n console.error(error);\n };\n\n const enable = () => {\n currentTarget.disabled = false;\n };\n const { sync } = xworker;\n sync.write = (str) => {\n outDiv.innerText += `${str}\\n`;\n };\n sync.writeErr = (str) => {\n outDiv.innerHTML += `<span style='color:red'>${str}</span>\\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 // TODO: find a way to actually produce these bundles locally\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 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 const env = `${interpreter}-${script.getAttribute(\"env\") || getID(type)}`;\n const context = {\n interpreter,\n env,\n get pySrc() {\n return editor.state.doc.toString();\n },\n get outDiv() {\n return outDiv;\n },\n };\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// 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 = async () => {\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\n script.type += \"-active\";\n await init(script, type, interpreter);\n }\n }\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","hooks","worker","onReady","runAsync","io","sync","stdout","line","write","stderr","writeErr","revoke","async","execute","currentTarget","env","pySrc","outDiv","this","disabled","innerHTML","has","srcLink","URL","createObjectURL","Blob","xworker","XWorker","call","Hook","interpreter","promise","resolve","Promise","withResolvers","set","revokeObjectURL","get","then","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","import","n","x","q","selector","getAttribute","target","getElementById","querySelector","Error","style","display","after","hasAttribute","context","editor","state","doc","toString","bind","dataset","parent","attachShadow","mode","appendChild","dedent","textContent","trim","indentation","test","RegExp","$1","extensions","of","key","run","preventDefault","focus","timeout","resetTimeout","pyEditor","setTimeout","TYPES","querySelectorAll","MutationObserver","observe","childList","subtree","pyEditor$1"],"mappings":"4DAMA,IAAIA,EAAK,EACT,MAAMC,EAASC,GAAS,GAAGA,YAAeF,MAEpCG,EAAO,IAAIC,IAEXC,EAAQ,CACVC,OAAQ,CAEJC,QAAS,EAAGC,WAAUC,OAAQC,WAC1BD,EAAGE,OAAUC,GAASF,EAAKG,MAAMD,GACjCH,EAAGK,OAAUF,GAASF,EAAKK,SAASH,GACpCF,EAAKM,SACLN,EAAKF,SAAWA,CAAQ,IAKpCS,eAAeC,GAAQC,cAAEA,IACrB,MAAMC,IAAEA,EAAGC,MAAEA,EAAKC,O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EAAeR"}
@@ -1,2 +1,2 @@
1
- import{T as e,e as t}from"./core-ifSZyON7.js";import{notify as r}from"./error-ZSXf8h5x.js";const n=[...e.keys()].map((e=>`script[type="${e}"][terminal],${e}-script[terminal]`)).join(","),o=e=>{throw r(e),new Error(e)},i=async()=>{const e=document.querySelectorAll(n);if(!e.length)return;s.disconnect(),e.length>1&&o("You can use at most 1 terminal.");const[r]=e;r.matches('script[type="mpy"],mpy-script')&&o("Unsupported terminal."),document.head.append(Object.assign(document.createElement("link"),{rel:"stylesheet",href:new URL("./xterm.css",import.meta.url)}));const[{Terminal:i},{Readline:a},{FitAddon:d}]=await Promise.all([import("./xterm-f2QfYNGL.js"),import("./xterm-readline-ONk85xtH.js"),import("./xterm_addon-fit-E4yMPZTX.js")]),l=new a,c=e=>{let t=r;const n=r.getAttribute("target");if(n){if(t=document.getElementById(n)||document.querySelector(n),!t)throw new Error(`Unknown target ${n}`)}else t=document.createElement("py-terminal"),t.style.display="block",r.after(t);const o=new i({theme:{background:"#191A19",foreground:"#F5F2E7"},...e}),s=new d;o.loadAddon(s),o.loadAddon(l),o.open(t),s.fit(),o.focus()};if(r.hasAttribute("worker")){const e=({interpreter:e},{sync:t})=>{t.pyterminal_drop_hooks();const r=new TextDecoder;let n="";const o={isatty:!0,write:e=>(n=r.decode(e),t.pyterminal_write(n),e.length)};e.setStdout(o),e.setStderr(o),e.setStdin({isatty:!0,stdin:()=>t.pyterminal_read(n)})};t.main.onWorker.add((function r(n,o){t.main.onWorker.delete(r),c({disableStdin:!1,cursorBlink:!0,cursorStyle:"block"}),o.sync.pyterminal_read=l.read.bind(l),o.sync.pyterminal_write=l.write.bind(l),o.sync.pyterminal_drop_hooks=()=>{t.worker.onReady.delete(e)}})),t.worker.onReady.add(e)}else t.main.onReady.add((function e({io:r}){console.warn("py-terminal is read only on main thread"),t.main.onReady.delete(e),c({disableStdin:!0,cursorBlink:!1,cursorStyle:"underline"}),r.stdout=e=>{l.write(`${e}\n`)},r.stderr=e=>{l.write(`${e.message||e}\n`)}}))},s=new MutationObserver(i);s.observe(document,{childList:!0,subtree:!0});var a=i();export{a as default};
2
- //# sourceMappingURL=py-terminal-lYFDY-Tg.js.map
1
+ import{T as e,e as t}from"./core-HRYUl_m-.js";import{notify as r}from"./error-YvVW0ykk.js";const n=[...e.keys()].map((e=>`script[type="${e}"][terminal],${e}-script[terminal]`)).join(","),o=e=>{throw r(e),new Error(e)},i=async()=>{const e=document.querySelectorAll(n);if(!e.length)return;s.disconnect(),e.length>1&&o("You can use at most 1 terminal.");const[r]=e;r.matches('script[type="mpy"],mpy-script')&&o("Unsupported terminal."),document.head.append(Object.assign(document.createElement("link"),{rel:"stylesheet",href:new URL("./xterm.css",import.meta.url)}));const[{Terminal:i},{Readline:a},{FitAddon:d}]=await Promise.all([import("./xterm-f2QfYNGL.js"),import("./xterm-readline-ONk85xtH.js"),import("./xterm_addon-fit-E4yMPZTX.js")]),l=new a,c=e=>{let t=r;const n=r.getAttribute("target");if(n){if(t=document.getElementById(n)||document.querySelector(n),!t)throw new Error(`Unknown target ${n}`)}else t=document.createElement("py-terminal"),t.style.display="block",r.after(t);const o=new i({theme:{background:"#191A19",foreground:"#F5F2E7"},...e}),s=new d;o.loadAddon(s),o.loadAddon(l),o.open(t),s.fit(),o.focus()};if(r.hasAttribute("worker")){const e=({interpreter:e},{sync:t})=>{t.pyterminal_drop_hooks();const r=new TextDecoder;let n="";const o={isatty:!0,write:e=>(n=r.decode(e),t.pyterminal_write(n),e.length)};e.setStdout(o),e.setStderr(o),e.setStdin({isatty:!0,stdin:()=>t.pyterminal_read(n)})};t.main.onWorker.add((function r(n,o){t.main.onWorker.delete(r),c({disableStdin:!1,cursorBlink:!0,cursorStyle:"block"}),o.sync.pyterminal_read=l.read.bind(l),o.sync.pyterminal_write=l.write.bind(l),o.sync.pyterminal_drop_hooks=()=>{t.worker.onReady.delete(e)}})),t.worker.onReady.add(e)}else t.main.onReady.add((function e({io:r}){console.warn("py-terminal is read only on main thread"),t.main.onReady.delete(e),c({disableStdin:!0,cursorBlink:!1,cursorStyle:"underline"}),r.stdout=e=>{l.write(`${e}\n`)},r.stderr=e=>{l.write(`${e.message||e}\n`)}}))},s=new MutationObserver(i);s.observe(document,{childList:!0,subtree:!0});var a=i();export{a as default};
2
+ //# sourceMappingURL=py-terminal-yPjeDRpg.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"py-terminal-lYFDY-Tg.js","sources":["../src/plugins/py-terminal.js"],"sourcesContent":["// PyScript py-terminal plugin\nimport { TYPES, hooks } from \"../core.js\";\nimport { notify } from \"./error.js\";\n\nconst SELECTOR = [...TYPES.keys()]\n .map((type) => `script[type=\"${type}\"][terminal],${type}-script[terminal]`)\n .join(\",\");\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 pyTerminal = async () => {\n const terminals = document.querySelectorAll(SELECTOR);\n\n // no results will look further for runtime nodes\n if (!terminals.length) return;\n\n // if we arrived this far, let's drop the MutationObserver\n // as we only support one terminal per page (right now).\n mo.disconnect();\n\n // we currently support only one terminal as in \"classic\"\n if (terminals.length > 1) notifyAndThrow(\"You can use at most 1 terminal.\");\n\n const [element] = terminals;\n // hopefully to be removed in the near future!\n if (element.matches('script[type=\"mpy\"],mpy-script'))\n notifyAndThrow(\"Unsupported terminal.\");\n\n // import styles lazily\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 // 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 };\n\n // branch logic for the worker\n if (element.hasAttribute(\"worker\")) {\n // when the remote thread onReady triggers:\n // setup the interpreter stdout and stderr\n const workerReady = ({ interpreter }, { sync }) => {\n sync.pyterminal_drop_hooks();\n const decoder = new TextDecoder();\n let data = \"\";\n const generic = {\n isatty: true,\n write(buffer) {\n data = decoder.decode(buffer);\n sync.pyterminal_write(data);\n return buffer.length;\n },\n };\n interpreter.setStdout(generic);\n interpreter.setStderr(generic);\n interpreter.setStdin({\n isatty: true,\n stdin: () => sync.pyterminal_read(data),\n });\n };\n\n // add a hook on the main thread to setup all sync helpers\n // also bootstrapping the XTerm target on main\n hooks.main.onWorker.add(function worker(_, xworker) {\n hooks.main.onWorker.delete(worker);\n init({\n disableStdin: false,\n cursorBlink: true,\n cursorStyle: \"block\",\n });\n xworker.sync.pyterminal_read = readline.read.bind(readline);\n xworker.sync.pyterminal_write = readline.write.bind(readline);\n // allow a worker to drop main thread hooks ASAP\n xworker.sync.pyterminal_drop_hooks = () => {\n hooks.worker.onReady.delete(workerReady);\n };\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({ io }) {\n console.warn(\"py-terminal is read only on main thread\");\n hooks.main.onReady.delete(main);\n init({\n disableStdin: true,\n cursorBlink: false,\n cursorStyle: \"underline\",\n });\n io.stdout = (value) => {\n readline.write(`${value}\\n`);\n };\n io.stderr = (error) => {\n readline.write(`${error.message || error}\\n`);\n };\n });\n }\n};\n\nconst mo = new MutationObserver(pyTerminal);\nmo.observe(document, { childList: true, subtree: true });\n\n// try to check the current document ASAP\nexport default pyTerminal();\n"],"names":["SELECTOR","TYPES","keys","map","type","join","notifyAndThrow","message","notify","Error","pyTerminal","async","terminals","document","querySelectorAll","length","mo","disconnect","element","matches","head","append","Object","assign","createElement","rel","href","URL","url","Terminal","Readline","FitAddon","Promise","all","import","readline","init","options","target","selector","getAttribute","getElementById","querySelector","style","display","after","terminal","theme","background","foreground","fitAddon","loadAddon","open","fit","focus","hasAttribute","workerReady","interpreter","sync","pyterminal_drop_hooks","decoder","TextDecoder","data","generic","isatty","write","buffer","decode","pyterminal_write","setStdout","setStderr","setStdin","stdin","pyterminal_read","hooks","main","onWorker","add","worker","_","xworker","delete","disableStdin","cursorBlink","cursorStyle","read","bind","onReady","io","console","warn","stdout","value","stderr","error","MutationObserver","observe","childList","subtree","pyTerminal$1"],"mappings":"2FAIA,MAAMA,EAAW,IAAIC,EAAMC,QACtBC,KAAKC,GAAS,gBAAgBA,iBAAoBA,uBAClDC,KAAK,KAIJC,EAAkBC,IAEpB,MADAC,EAAOD,GACD,IAAIE,MAAMF,EAAQ,EAGtBG,EAAaC,UACf,MAAMC,EAAYC,SAASC,iBAAiBd,GAG5C,IAAKY,EAAUG,OAAQ,OAIvBC,EAAGC,aAGCL,EAAUG,OAAS,GAAGT,EAAe,mCAEzC,MAAOY,GAAWN,EAEdM,EAAQC,QAAQ,kCAChBb,EAAe,yBAGnBO,SAASO,KAAKC,OACVC,OAAOC,OAAOV,SAASW,cAAc,QAAS,CAC1CC,IAAK,aACLC,KAAM,IAAIC,IAAI,0BAA2BC,QAKjD,OAAOC,SAAEA,IAAYC,SAAEA,IAAYC,SAAEA,UAAoBC,QAAQC,IAAI,CACjEC,OAAiC,uBACjCA,OAAiC,gCACjCA,OAAiC,mCAG/BC,EAAW,IAAI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kB,EAAMC,KAAKY,QAAQV,KAAI,SAASF,GAAKa,GAAEA,IACnCC,QAAQC,KAAK,2CACbhB,EAAMC,KAAKY,QAAQN,OAAON,GAC1BvC,EAAK,CACD8C,cAAc,EACdC,aAAa,EACbC,YAAa,cAEjBI,EAAGG,OAAUC,IACTzD,EAAS8B,MAAM,GAAG2B,MAAU,EAEhCJ,EAAGK,OAAUC,IACT3D,EAAS8B,MAAM,GAAG6B,EAAMvF,SAAWuF,MAAU,CAE7D,GACK,EAGC9E,EAAK,IAAI+E,iBAAiBrF,GAChCM,EAAGgF,QAAQnF,SAAU,CAAEoF,WAAW,EAAMC,SAAS,IAGjD,IAAAC,EAAezF"}
1
+ {"version":3,"file":"py-terminal-yPjeDRpg.js","sources":["../src/plugins/py-terminal.js"],"sourcesContent":["// PyScript py-terminal plugin\nimport { TYPES, hooks } from \"../core.js\";\nimport { notify } from \"./error.js\";\n\nconst SELECTOR = [...TYPES.keys()]\n .map((type) => `script[type=\"${type}\"][terminal],${type}-script[terminal]`)\n .join(\",\");\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 pyTerminal = async () => {\n const terminals = document.querySelectorAll(SELECTOR);\n\n // no results will look further for runtime nodes\n if (!terminals.length) return;\n\n // if we arrived this far, let's drop the MutationObserver\n // as we only support one terminal per page (right now).\n mo.disconnect();\n\n // we currently support only one terminal as in \"classic\"\n if (terminals.length > 1) notifyAndThrow(\"You can use at most 1 terminal.\");\n\n const [element] = terminals;\n // hopefully to be removed in the near future!\n if (element.matches('script[type=\"mpy\"],mpy-script'))\n notifyAndThrow(\"Unsupported terminal.\");\n\n // import styles lazily\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 // 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 };\n\n // branch logic for the worker\n if (element.hasAttribute(\"worker\")) {\n // when the remote thread onReady triggers:\n // setup the interpreter stdout and stderr\n const workerReady = ({ interpreter }, { sync }) => {\n sync.pyterminal_drop_hooks();\n const decoder = new TextDecoder();\n let data = \"\";\n const generic = {\n isatty: true,\n write(buffer) {\n data = decoder.decode(buffer);\n sync.pyterminal_write(data);\n return buffer.length;\n },\n };\n interpreter.setStdout(generic);\n interpreter.setStderr(generic);\n interpreter.setStdin({\n isatty: true,\n stdin: () => sync.pyterminal_read(data),\n });\n };\n\n // add a hook on the main thread to setup all sync helpers\n // also bootstrapping the XTerm target on main\n hooks.main.onWorker.add(function worker(_, xworker) {\n hooks.main.onWorker.delete(worker);\n init({\n disableStdin: false,\n cursorBlink: true,\n cursorStyle: \"block\",\n });\n xworker.sync.pyterminal_read = readline.read.bind(readline);\n xworker.sync.pyterminal_write = readline.write.bind(readline);\n // allow a worker to drop main thread hooks ASAP\n xworker.sync.pyterminal_drop_hooks = () => {\n hooks.worker.onReady.delete(workerReady);\n };\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({ io }) {\n console.warn(\"py-terminal is read only on main thread\");\n hooks.main.onReady.delete(main);\n init({\n disableStdin: true,\n cursorBlink: false,\n cursorStyle: \"underline\",\n });\n io.stdout = (value) => {\n readline.write(`${value}\\n`);\n };\n io.stderr = (error) => {\n readline.write(`${error.message || error}\\n`);\n };\n });\n }\n};\n\nconst mo = new MutationObserver(pyTerminal);\nmo.observe(document, { childList: true, subtree: true });\n\n// try to check the current document ASAP\nexport default pyTerminal();\n"],"names":["SELECTOR","TYPES","keys","map","type","join","notifyAndThrow","message","notify","Error","pyTerminal","async","terminals","document","querySelectorAll","length","mo","disconnect","element","matches","head","append","Object","assign","createElement","rel","href","URL","url","Terminal","Readline","FitAddon","Promise","all","import","readline","init","options","target","selector","getAttribute","getElementById","querySelector","style","display","after","terminal","theme","background","foreground","fitAddon","loadAddon","open","fit","focus","hasAttribute","workerReady","interpreter","sync","pyterminal_drop_hooks","decoder","TextDecoder","data","generic","isatty","write","buffer","decode","pyterminal_write","setStdout","setStderr","setStdin","stdin","pyterminal_read","hooks","main","onWorker","add","worker","_","xworker","delete","disableStdin","cursorBlink","cursorStyle","read","bind","onReady","io","console","warn","stdout","value","stderr","error","MutationObserver","observe","childList","subtree","pyTerminal$1"],"mappings":"2FAIA,MAAMA,EAAW,IAAIC,EAAMC,QACtBC,KAAKC,GAAS,gBAAgBA,iBAAoBA,uBAClDC,KAAK,KAIJC,EAAkBC,IAEpB,MADAC,EAAOD,GACD,IAAIE,MAAMF,EAAQ,EAGtBG,EAAaC,UACf,MAAMC,EAAYC,SAASC,iBAAiBd,GAG5C,IAAKY,EAAUG,OAAQ,OAIvBC,EAAGC,aAGCL,EAAUG,OAAS,GAAGT,EAAe,mCAEzC,MAAOY,GAAWN,EAEdM,EAAQC,QAAQ,kCAChBb,EAAe,yBAGnBO,SAASO,KAAKC,OACVC,OAAOC,OAAOV,SAASW,cAAc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D,GAClD6C,EAAQtB,KAAKU,iBAAmBjC,EAAS8B,MAAMqB,KAAKnD,GAEpD6C,EAAQtB,KAAKC,sBAAwB,KACjCe,EAAMI,OAAOS,QAAQN,OAAOzB,EAAY,CAExD,IAIQkB,EAAMI,OAAOS,QAAQV,IAAIrB,EACjC,MAGQkB,EAAMC,KAAKY,QAAQV,KAAI,SAASF,GAAKa,GAAEA,IACnCC,QAAQC,KAAK,2CACbhB,EAAMC,KAAKY,QAAQN,OAAON,GAC1BvC,EAAK,CACD8C,cAAc,EACdC,aAAa,EACbC,YAAa,cAEjBI,EAAGG,OAAUC,IACTzD,EAAS8B,MAAM,GAAG2B,MAAU,EAEhCJ,EAAGK,OAAUC,IACT3D,EAAS8B,MAAM,GAAG6B,EAAMvF,SAAWuF,MAAU,CAE7D,GACK,EAGC9E,EAAK,IAAI+E,iBAAiBrF,GAChCM,EAAGgF,QAAQnF,SAAU,CAAEoF,WAAW,EAAMC,SAAS,IAGjD,IAAAC,EAAezF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pyscript/core",
3
- "version": "0.3.9",
3
+ "version": "0.3.10",
4
4
  "type": "module",
5
5
  "description": "PyScript",
6
6
  "module": "./index.js",
package/src/core.js CHANGED
@@ -26,33 +26,9 @@ import { ErrorCode } from "./exceptions.js";
26
26
  import { robustFetch as fetch, getText } from "./fetch.js";
27
27
  import { hooks, main, worker, codeFor, createFunction } from "./hooks.js";
28
28
 
29
- // allows lazy element features on code evaluation
30
- let currentElement;
31
-
32
29
  // generic helper to disambiguate between custom element and script
33
30
  const isScript = ({ tagName }) => tagName === "SCRIPT";
34
31
 
35
- let shouldRegister = true;
36
- const registerModule = ({ XWorker: $XWorker, interpreter, io }) => {
37
- // automatically use the pyscript stderr (when/if defined)
38
- // this defaults to console.error
39
- function PyWorker(...args) {
40
- const worker = $XWorker(...args);
41
- worker.onerror = ({ error }) => io.stderr(error);
42
- return worker;
43
- }
44
-
45
- // enrich the Python env with some JS utility for main
46
- interpreter.registerJsModule("_pyscript", {
47
- PyWorker,
48
- get target() {
49
- return isScript(currentElement)
50
- ? currentElement.target.id
51
- : currentElement.id;
52
- },
53
- });
54
- };
55
-
56
32
  // avoid multiple initialization of the same library
57
33
  const [
58
34
  {
@@ -118,6 +94,36 @@ for (const [TYPE, interpreter] of TYPES) {
118
94
  return code;
119
95
  };
120
96
 
97
+ // register once any interpreter
98
+ let alreadyRegistered = false;
99
+
100
+ // allows lazy element features on code evaluation
101
+ let currentElement;
102
+
103
+ const registerModule = ({ XWorker, interpreter, io }) => {
104
+ // avoid multiple registration of the same interpreter
105
+ if (alreadyRegistered) return;
106
+ alreadyRegistered = true;
107
+
108
+ // automatically use the pyscript stderr (when/if defined)
109
+ // this defaults to console.error
110
+ function PyWorker(...args) {
111
+ const worker = XWorker(...args);
112
+ worker.onerror = ({ error }) => io.stderr(error);
113
+ return worker;
114
+ }
115
+
116
+ // enrich the Python env with some JS utility for main
117
+ interpreter.registerJsModule("_pyscript", {
118
+ PyWorker,
119
+ get target() {
120
+ return isScript(currentElement)
121
+ ? currentElement.target.id
122
+ : currentElement.id;
123
+ },
124
+ });
125
+ };
126
+
121
127
  // define the module as both `<script type="py">` and `<py-script>`
122
128
  // but only if the config didn't throw an error
123
129
  if (!error) {
@@ -133,10 +139,7 @@ for (const [TYPE, interpreter] of TYPES) {
133
139
  main: {
134
140
  ...codeFor(main),
135
141
  async onReady(wrap, element) {
136
- if (shouldRegister) {
137
- shouldRegister = false;
138
- registerModule(wrap);
139
- }
142
+ registerModule(wrap);
140
143
 
141
144
  // allows plugins to do whatever they want with the element
142
145
  // before regular stuff happens in here
@@ -320,7 +323,7 @@ for (const [TYPE, interpreter] of TYPES) {
320
323
  function PyWorker(file, options) {
321
324
  const hooks = hooked.get("py");
322
325
  // this propagates pyscript worker hooks without needing a pyscript
323
- // bootstrap + it passes arguments and enforces `pyodide`
326
+ // bootstrap + it passes arguments and it defaults to `pyodide`
324
327
  // as the interpreter to use in the worker, as all hooks assume that
325
328
  // and as `pyodide` is the only default interpreter that can deal with
326
329
  // all the features we need to deliver pyscript out there.