@pyscript/core 0.4.47 → 0.4.49

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{g as MPWorker,f as PyWorker,T as TYPES,h as config,e as hooks,i as inputFailure,o as offline_interpreter,b as optional,s as stdlib,j as whenDefined}from"./core-CVoMgJtU.js";
1
+ export{g as MPWorker,f as PyWorker,T as TYPES,h as config,e as hooks,i as inputFailure,o as offline_interpreter,b as optional,s as stdlib,j as whenDefined}from"./core-BTbIsuak.js";
2
2
  //# sourceMappingURL=core.js.map
@@ -1,2 +1,2 @@
1
- import{e}from"./core-CVoMgJtU.js";import{notify as o}from"./error-BcdCmvJU.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-_MT-zvjy.js.map
1
+ import{e}from"./core-BTbIsuak.js";import{notify as o}from"./error-Bdm9PHt9.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-Bjh5a51H.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"deprecations-manager-_MT-zvjy.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-Bjh5a51H.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-CVoMgJtU.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-BcdCmvJU.js.map
1
+ import{e}from"./core-BTbIsuak.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-Bdm9PHt9.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"error-BcdCmvJU.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-Bdm9PHt9.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{e,i as r,d as t}from"./core-CVoMgJtU.js";const n=new WeakSet,i=({interpreter:e,io:r,run:t,type:n},{sync:i})=>{if("mpy"!==n||!i.is_pyterminal())return;const{pyterminal_ready:o,pyterminal_read:a,pyterminal_write:s}=i;e.registerJsModule("_pyscript_input",{input:a}),t(["from _pyscript_input import input","from polyscript import currentScript as _","__terminal__ = _.terminal","del _"].join(";"));const l=new Uint8Array([13]);r.stdout=e=>{10===e[0]&&s(l),s(e)},r.stderr=e=>{s(String(e.message||e))},e.registerJsModule("code",{interact(){const r=new TextEncoderStream;r.readable.pipeTo(new WritableStream({write(r){for(const t of r)e.replProcessChar(t)}}));const t=r.writable.getWriter();i.pyterminal_stream_write=e=>t.write(e),o(),e.replInit()}})};var o=async o=>{const[{Terminal:a},{FitAddon:s},{WebLinksAddon:l}]=await Promise.all([import("./xterm-BY7uk_OU.js"),import("./xterm_addon-fit--gyF3PcZ.js"),import("./xterm_addon-web-links-Cnej-nJ6.js")]),m={disableStdin:!1,cursorBlink:!0,cursorStyle:"block"};let d;const p=()=>{let e=o;const r=o.getAttribute("target");if(r){if(e=document.getElementById(r)||document.querySelector(r),!e)throw new Error(`Unknown target ${r}`)}else e=document.createElement("py-terminal"),e.style.display="block",o.after(e);const n=new a({theme:{background:"#191A19",foreground:"#F5F2E7"},...m}),i=new s;return n.loadAddon(i),n.loadAddon(new l),n.open(e),i.fit(),n.focus(),t(o,{terminal:{value:n},process:{value:async e=>{for(const r of e.split(/(?:\r\n|\r|\n)/))await d.write(`${r}\r`)}}}),n};o.hasAttribute("worker")?(e.main.onWorker.add((function r(t,i){if(n.has(i))return;n.add(i),e.main.onWorker.delete(r);const o=p(),{sync:a}=i;let s=null,l="";a.is_pyterminal=()=>!0,a.pyterminal_read=e=>(o.write(e),s=Promise.withResolvers(),s.promise),a.pyterminal_write=e=>{s||o.write(e)},a.pyterminal_ready=()=>{let e=Promise.resolve();d={write:r=>e=e.then((()=>a.pyterminal_stream_write(r)))},o.onData((e=>{s?(l+=e,o.write(e),l.endsWith("\r")&&(o.write("\n"),s.resolve(l.slice(0,-1)),s=null,l="")):d.write(e)}))}})),e.worker.onReady.add(i)):(e.main.codeBeforeRun.delete(r),e.main.onReady.add((function r({interpreter:t,io:n,run:i,type:o}){if("mpy"!==o)return;e.main.onReady.delete(r);const a=p(),s=new Uint8Array([13]);n.stdout=e=>{10===e[0]&&a.write(s),a.write(e)},globalThis.__py_terminal__=a,i(["from js import prompt as input","from js import __py_terminal__ as __terminal__"].join(";")),delete globalThis.__py_terminal__,t.registerJsModule("code",{interact(){const e=new TextEncoderStream;e.readable.pipeTo(new WritableStream({write(e){for(const r of e)t.replProcessChar(r)}})),d=e.writable.getWriter(),a.onData((e=>d.write(e))),t.replInit()}})})))};export{o as default};
2
- //# sourceMappingURL=mpy-Bfshdqz6.js.map
1
+ import{e,i as r,d as t}from"./core-BTbIsuak.js";const n=new WeakSet,i=({interpreter:e,io:r,run:t,type:n},{sync:i})=>{if("mpy"!==n||!i.is_pyterminal())return;const{pyterminal_ready:o,pyterminal_read:a,pyterminal_write:s}=i;e.registerJsModule("_pyscript_input",{input:a}),t(["from _pyscript_input import input","from polyscript import currentScript as _","__terminal__ = _.terminal","del _"].join(";"));const l=new Uint8Array([13]);r.stdout=e=>{10===e[0]&&s(l),s(e)},r.stderr=e=>{s(String(e.message||e))},e.registerJsModule("code",{interact(){const r=new TextEncoderStream;r.readable.pipeTo(new WritableStream({write(r){for(const t of r)e.replProcessChar(t)}}));const t=r.writable.getWriter();i.pyterminal_stream_write=e=>t.write(e),o(),e.replInit()}})};var o=async o=>{const[{Terminal:a},{FitAddon:s},{WebLinksAddon:l}]=await Promise.all([import("./xterm-BY7uk_OU.js"),import("./xterm_addon-fit--gyF3PcZ.js"),import("./xterm_addon-web-links-Cnej-nJ6.js")]),m={disableStdin:!1,cursorBlink:!0,cursorStyle:"block"};let d;const p=()=>{let e=o;const r=o.getAttribute("target");if(r){if(e=document.getElementById(r)||document.querySelector(r),!e)throw new Error(`Unknown target ${r}`)}else e=document.createElement("py-terminal"),e.style.display="block",o.after(e);const n=new a({theme:{background:"#191A19",foreground:"#F5F2E7"},...m}),i=new s;return n.loadAddon(i),n.loadAddon(new l),n.open(e),i.fit(),n.focus(),t(o,{terminal:{value:n},process:{value:async e=>{for(const r of e.split(/(?:\r\n|\r|\n)/))await d.write(`${r}\r`)}}}),n};o.hasAttribute("worker")?(e.main.onWorker.add((function r(t,i){if(n.has(i))return;n.add(i),e.main.onWorker.delete(r);const o=p(),{sync:a}=i;let s=null,l="";a.is_pyterminal=()=>!0,a.pyterminal_read=e=>(o.write(e),s=Promise.withResolvers(),s.promise),a.pyterminal_write=e=>{s||o.write(e)},a.pyterminal_ready=()=>{let e=Promise.resolve();d={write:r=>e=e.then((()=>a.pyterminal_stream_write(r)))},o.onData((e=>{s?(l+=e,o.write(e),l.endsWith("\r")&&(o.write("\n"),s.resolve(l.slice(0,-1)),s=null,l="")):d.write(e)}))}})),e.worker.onReady.add(i)):(e.main.codeBeforeRun.delete(r),e.main.onReady.add((function r({interpreter:t,io:n,run:i,type:o}){if("mpy"!==o)return;e.main.onReady.delete(r);const a=p(),s=new Uint8Array([13]);n.stdout=e=>{10===e[0]&&a.write(s),a.write(e)},globalThis.__py_terminal__=a,i(["from js import prompt as input","from js import __py_terminal__ as __terminal__"].join(";")),delete globalThis.__py_terminal__,t.registerJsModule("code",{interact(){const e=new TextEncoderStream;e.readable.pipeTo(new WritableStream({write(e){for(const r of e)t.replProcessChar(r)}})),d=e.writable.getWriter(),a.onData((e=>d.write(e))),t.replInit()}})})))};export{o as default};
2
+ //# sourceMappingURL=mpy-D5WLUFEd.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"mpy-Bfshdqz6.js","sources":["../src/plugins/py-terminal/mpy.js"],"sourcesContent":["// PyScript pyodide terminal plugin\nimport { hooks, inputFailure } from \"../../core.js\";\nimport { defineProperties } from \"polyscript/exports\";\n\nconst bootstrapped = new WeakSet();\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 (type !== \"mpy\" || !sync.is_pyterminal()) return;\n\n const { pyterminal_ready, pyterminal_read, pyterminal_write } = sync;\n\n interpreter.registerJsModule(\"_pyscript_input\", {\n input: pyterminal_read,\n });\n\n run(\n [\n \"from _pyscript_input import input\",\n \"from polyscript import currentScript as _\",\n \"__terminal__ = _.terminal\",\n \"del _\",\n ].join(\";\"),\n );\n\n const missingReturn = new Uint8Array([13]);\n io.stdout = (buffer) => {\n if (buffer[0] === 10) pyterminal_write(missingReturn);\n pyterminal_write(buffer);\n };\n io.stderr = (error) => {\n pyterminal_write(String(error.message || error));\n };\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 const encoder = new TextEncoderStream();\n encoder.readable.pipeTo(\n new WritableStream({\n write(buffer) {\n for (const c of buffer) interpreter.replProcessChar(c);\n },\n }),\n );\n\n const writer = encoder.writable.getWriter();\n sync.pyterminal_stream_write = (buffer) => writer.write(buffer);\n pyterminal_ready();\n\n interpreter.replInit();\n },\n });\n};\n\nexport default async (element) => {\n // lazy load these only when a valid terminal is found\n const [{ Terminal }, { FitAddon }, { WebLinksAddon }] = await Promise.all([\n import(/* webpackIgnore: true */ \"../../3rd-party/xterm.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 terminalOptions = {\n disableStdin: false,\n cursorBlink: true,\n cursorStyle: \"block\",\n };\n\n let stream;\n\n // common main thread initialization for both worker\n // or main case, bootstrapping the terminal on its target\n const init = () => {\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 ...terminalOptions,\n });\n const fitAddon = new FitAddon();\n terminal.loadAddon(fitAddon);\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 for (const line of code.split(/(?:\\r\\n|\\r|\\n)/)) {\n await stream.write(`${line}\\r`);\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 const terminal = init();\n\n const { sync } = xworker;\n\n // handle the read mode on input\n let promisedChunks = null;\n let readChunks = \"\";\n\n sync.is_pyterminal = () => true;\n\n // put the terminal in a read-only state\n // frees the worker on \\r\n sync.pyterminal_read = (buffer) => {\n terminal.write(buffer);\n promisedChunks = Promise.withResolvers();\n return promisedChunks.promise;\n };\n\n // write if not reading input\n sync.pyterminal_write = (buffer) => {\n if (!promisedChunks) terminal.write(buffer);\n };\n\n // add the onData terminal listener which forwards to the worker\n // everything typed in a queued char-by-char way\n sync.pyterminal_ready = () => {\n let queue = Promise.resolve();\n stream = {\n write: (buffer) =>\n (queue = queue.then(() =>\n sync.pyterminal_stream_write(buffer),\n )),\n };\n terminal.onData((buffer) => {\n if (promisedChunks) {\n readChunks += buffer;\n terminal.write(buffer);\n if (readChunks.endsWith(\"\\r\")) {\n terminal.write(\"\\n\");\n promisedChunks.resolve(readChunks.slice(0, -1));\n promisedChunks = null;\n readChunks = \"\";\n }\n } else {\n stream.write(buffer);\n }\n });\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 an ideal world the inputFailure should never be used on main.\n // However, Pyodide still can't compete with MicroPython REPL mode\n // so while it's OK to keep that entry on main as default, we need\n // to remove it ASAP from `mpy` use cases, otherwise MicroPython would\n // also throw whenever an `input(...)` is required / digited.\n hooks.main.codeBeforeRun.delete(inputFailure);\n\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 if (type !== \"mpy\") return;\n\n hooks.main.onReady.delete(main);\n\n const terminal = init();\n\n const missingReturn = new Uint8Array([13]);\n io.stdout = (buffer) => {\n if (buffer[0] === 10) terminal.write(missingReturn);\n terminal.write(buffer);\n };\n\n // expose the __terminal__ one-off reference\n globalThis.__py_terminal__ = terminal;\n run(\n [\n \"from js import prompt as input\",\n \"from js import __py_terminal__ as __terminal__\",\n ].join(\";\"),\n );\n delete globalThis.__py_terminal__;\n\n // NOTE: this is NOT the same as the one within\n // the onWorkerReady callback!\n interpreter.registerJsModule(\"code\", {\n interact() {\n const encoder = new TextEncoderStream();\n encoder.readable.pipeTo(\n new WritableStream({\n write(buffer) {\n for (const c of buffer)\n interpreter.replProcessChar(c);\n },\n }),\n );\n\n stream = encoder.writable.getWriter();\n terminal.onData((buffer) => stream.write(buffer));\n\n interpreter.replInit();\n },\n });\n });\n }\n};\n"],"names":["bootstrapped","WeakSet","workerReady","interpreter","io","run","type","sync","is_pyterminal","pyterminal_ready","pyterminal_read","pyterminal_write","registerJsModule","input","join","missingReturn","Uint8Array","stdout","buffer","stderr","error","String","message","interact","encoder","TextEncoderStream","readable","pipeTo","WritableStream","write","c","replProcessChar","writer","writable","getWriter","pyterminal_stream_write","replInit","mpy","async","element","Terminal","FitAddon","WebLinksAddon","Promise","all","import","terminalOptions","disableStdin","cursorBlink","cursorStyle","stream","init","target","selector","getAttribute","document","getElementById","querySelector","Error","createElement","style","display","after","terminal","theme","background","foreground","fitAddon","loadAddon","open","fit","focus","defineProperties","value","process","code","line","split","hasAttribute","hooks","main","onWorker","add","worker","_","xworker","has","delete","promisedChunks","readChunks","withResolvers","promise","queue","resolve","then","onData","endsWith","slice","onReady","codeBeforeRun","inputFailure","globalThis","__py_terminal__"],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,QAAQhB,IAAIhF,KAOzB6E,EAAMC,KAAKmB,cAAcZ,OAAOa,GAIhCrB,EAAMC,KAAKkB,QAAQhB,KAAI,SAASF,GAAK7E,YAAEA,EAAWC,GAAEA,EAAEC,IAAEA,EAAGC,KAAEA,IACzD,GAAa,QAATA,EAAgB,OAEpByE,EAAMC,KAAKkB,QAAQX,OAAOP,GAE1B,MAAMjB,EAAWZ,IAEXpC,EAAgB,IAAIC,WAAW,CAAC,KACtCZ,EAAGa,OAAUC,IACS,KAAdA,EAAO,IAAW6C,EAASlC,MAAMd,GACrCgD,EAASlC,MAAMX,EAAO,EAI1BmF,WAAWC,gBAAkBvC,EAC7B1D,EACI,CACI,iCACA,kDACFS,KAAK,aAEJuF,WAAWC,gBAIlBnG,EAAYS,iBAAiB,OAAQ,CACjC,QAAAW,GACI,MAAMC,EAAU,IAAIC,kBACpBD,EAAQE,SAASC,OACb,IAAIC,eAAe,CACf,KAAAC,CAAMX,GACF,IAAK,MAAMY,KAAKZ,EACZf,EAAY4B,gBAAgBD,EACnC,KAIToB,EAAS1B,EAAQS,SAASC,YAC1B6B,EAASgC,QAAQ7E,GAAWgC,EAAOrB,MAAMX,KAEzCf,EAAYiC,UACf,GAEjB,IACK"}
1
+ {"version":3,"file":"mpy-D5WLUFEd.js","sources":["../src/plugins/py-terminal/mpy.js"],"sourcesContent":["// PyScript pyodide terminal plugin\nimport { hooks, inputFailure } from \"../../core.js\";\nimport { defineProperties } from \"polyscript/exports\";\n\nconst bootstrapped = new WeakSet();\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 (type !== \"mpy\" || !sync.is_pyterminal()) return;\n\n const { pyterminal_ready, pyterminal_read, pyterminal_write } = sync;\n\n interpreter.registerJsModule(\"_pyscript_input\", {\n input: pyterminal_read,\n });\n\n run(\n [\n \"from _pyscript_input import input\",\n \"from polyscript import currentScript as _\",\n \"__terminal__ = _.terminal\",\n \"del _\",\n ].join(\";\"),\n );\n\n const missingReturn = new Uint8Array([13]);\n io.stdout = (buffer) => {\n if (buffer[0] === 10) pyterminal_write(missingReturn);\n pyterminal_write(buffer);\n };\n io.stderr = (error) => {\n pyterminal_write(String(error.message || error));\n };\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 const encoder = new TextEncoderStream();\n encoder.readable.pipeTo(\n new WritableStream({\n write(buffer) {\n for (const c of buffer) interpreter.replProcessChar(c);\n },\n }),\n );\n\n const writer = encoder.writable.getWriter();\n sync.pyterminal_stream_write = (buffer) => writer.write(buffer);\n pyterminal_ready();\n\n interpreter.replInit();\n },\n });\n};\n\nexport default async (element) => {\n // lazy load these only when a valid terminal is found\n const [{ Terminal }, { FitAddon }, { WebLinksAddon }] = await Promise.all([\n import(/* webpackIgnore: true */ \"../../3rd-party/xterm.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 terminalOptions = {\n disableStdin: false,\n cursorBlink: true,\n cursorStyle: \"block\",\n };\n\n let stream;\n\n // common main thread initialization for both worker\n // or main case, bootstrapping the terminal on its target\n const init = () => {\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 ...terminalOptions,\n });\n const fitAddon = new FitAddon();\n terminal.loadAddon(fitAddon);\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 for (const line of code.split(/(?:\\r\\n|\\r|\\n)/)) {\n await stream.write(`${line}\\r`);\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 const terminal = init();\n\n const { sync } = xworker;\n\n // handle the read mode on input\n let promisedChunks = null;\n let readChunks = \"\";\n\n sync.is_pyterminal = () => true;\n\n // put the terminal in a read-only state\n // frees the worker on \\r\n sync.pyterminal_read = (buffer) => {\n terminal.write(buffer);\n promisedChunks = Promise.withResolvers();\n return promisedChunks.promise;\n };\n\n // write if not reading input\n sync.pyterminal_write = (buffer) => {\n if (!promisedChunks) terminal.write(buffer);\n };\n\n // add the onData terminal listener which forwards to the worker\n // everything typed in a queued char-by-char way\n sync.pyterminal_ready = () => {\n let queue = Promise.resolve();\n stream = {\n write: (buffer) =>\n (queue = queue.then(() =>\n sync.pyterminal_stream_write(buffer),\n )),\n };\n terminal.onData((buffer) => {\n if (promisedChunks) {\n readChunks += buffer;\n terminal.write(buffer);\n if (readChunks.endsWith(\"\\r\")) {\n terminal.write(\"\\n\");\n promisedChunks.resolve(readChunks.slice(0, -1));\n promisedChunks = null;\n readChunks = \"\";\n }\n } else {\n stream.write(buffer);\n }\n });\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 an ideal world the inputFailure should never be used on main.\n // However, Pyodide still can't compete with MicroPython REPL mode\n // so while it's OK to keep that entry on main as default, we need\n // to remove it ASAP from `mpy` use cases, otherwise MicroPython would\n // also throw whenever an `input(...)` is required / digited.\n hooks.main.codeBeforeRun.delete(inputFailure);\n\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 if (type !== \"mpy\") return;\n\n hooks.main.onReady.delete(main);\n\n const terminal = init();\n\n const missingReturn = new Uint8Array([13]);\n io.stdout = (buffer) => {\n if (buffer[0] === 10) terminal.write(missingReturn);\n terminal.write(buffer);\n };\n\n // expose the __terminal__ one-off reference\n globalThis.__py_terminal__ = terminal;\n run(\n [\n \"from js import prompt as input\",\n \"from js import __py_terminal__ as __terminal__\",\n ].join(\";\"),\n );\n delete globalThis.__py_terminal__;\n\n // NOTE: this is NOT the same as the one within\n // the onWorkerReady callback!\n interpreter.registerJsModule(\"code\", {\n interact() {\n const encoder = new TextEncoderStream();\n encoder.readable.pipeTo(\n new WritableStream({\n write(buffer) {\n for (const c of buffer)\n interpreter.replProcessChar(c);\n },\n }),\n );\n\n stream = encoder.writable.getWriter();\n terminal.onData((buffer) => stream.write(buffer));\n\n interpreter.replInit();\n },\n });\n });\n }\n};\n"],"names":["bootstrapped","WeakSet","workerReady","interpreter","io","run","type","sync","is_pyterminal","pyterminal_ready","pyterminal_read","pyterminal_write","registerJsModule","input","join","missingReturn","Uint8Array","stdout","buffer","stderr","error","String","message","interact","encoder","TextEncoderStream","readable","pipeTo","WritableStream","write","c","replProcessChar","writer","writable","getWriter","pyterminal_stream_write","replInit","mpy","async","element","Terminal","FitAddon","WebLinksAddon","Promise","all","import","terminalOptions","disableStdin","cursorBlink","cursorStyle","stream","init","target","selector","getAttribute","document","getElementById","querySelector","Error","createElement","style","display","after","terminal","theme","background","foreground","fitAddon","loadAddon","open","fit","focus","defineProperties","value","process","code","line","split","hasAttribute","hooks","main","onWorker","add","worker","_","xworker","has","delete","promisedChunks","readChunks","withResolvers","promise","queue","resolve","then","onData","endsWith","slice","onReady","codeBeforeRun","inputFailure","globalThis","__py_terminal__"],"mappings":"gDAIA,MAAMA,EAAe,IAAIC,QAKnBC,EAAc,EA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OAAOa,GAIhCrB,EAAMC,KAAKkB,QAAQhB,KAAI,SAASF,GAAK7E,YAAEA,EAAWC,GAAEA,EAAEC,IAAEA,EAAGC,KAAEA,IACzD,GAAa,QAATA,EAAgB,OAEpByE,EAAMC,KAAKkB,QAAQX,OAAOP,GAE1B,MAAMjB,EAAWZ,IAEXpC,EAAgB,IAAIC,WAAW,CAAC,KACtCZ,EAAGa,OAAUC,IACS,KAAdA,EAAO,IAAW6C,EAASlC,MAAMd,GACrCgD,EAASlC,MAAMX,EAAO,EAI1BmF,WAAWC,gBAAkBvC,EAC7B1D,EACI,CACI,iCACA,kDACFS,KAAK,aAEJuF,WAAWC,gBAIlBnG,EAAYS,iBAAiB,OAAQ,CACjC,QAAAW,GACI,MAAMC,EAAU,IAAIC,kBACpBD,EAAQE,SAASC,OACb,IAAIC,eAAe,CACf,KAAAC,CAAMX,GACF,IAAK,MAAMY,KAAKZ,EACZf,EAAY4B,gBAAgBD,EACnC,KAIToB,EAAS1B,EAAQS,SAASC,YAC1B6B,EAASgC,QAAQ7E,GAAWgC,EAAOrB,MAAMX,KAEzCf,EAAYiC,UACf,GAEjB,IACK"}
@@ -1,2 +1,2 @@
1
- import{e,d as t}from"./core-CVoMgJtU.js";const r=new WeakSet,n=({interpreter:e,io:t,run:r,type:n},{sync:i})=>{if("py"!==n||!i.is_pyterminal())return;r(["from polyscript import currentScript as _","__terminal__ = _.terminal","del _"].join(";"));let o="";const{pyterminal_read:a,pyterminal_write:d}=i,s=new TextDecoder,l={isatty:!1,write:e=>(o=s.decode(e),d(o),e.length)};t.stderr=e=>{d(String(e.message||e))},e.setStdout(l),e.setStderr(l),e.setStdin({isatty:!1,stdin:()=>a(o)})};var i=async i=>{const[{Terminal:o},{Readline:a},{FitAddon:d},{WebLinksAddon:s}]=await Promise.all([import("./xterm-BY7uk_OU.js"),import("./xterm-readline-DjufFwfn.js"),import("./xterm_addon-fit--gyF3PcZ.js"),import("./xterm_addon-web-links-Cnej-nJ6.js")]),l=new a,m=e=>{let r=i;const n=i.getAttribute("target");if(n){if(r=document.getElementById(n)||document.querySelector(n),!r)throw new Error(`Unknown target ${n}`)}else r=document.createElement("py-terminal"),r.style.display="block",i.after(r);const a=new o({theme:{background:"#191A19",foreground:"#F5F2E7"},...e}),m=new d;return a.loadAddon(m),a.loadAddon(l),a.loadAddon(new s),a.open(r),m.fit(),a.focus(),t(i,{terminal:{value:a},process:{value:async e=>{for(const t of e.split(/(?:\r\n|\r|\n)/)){a.paste(`${t}`),a.write("\r\n");do{await new Promise((e=>setTimeout(e,0)))}while(!l.activeRead?.resolve);l.activeRead.resolve(t)}}}}),a};i.hasAttribute("worker")?(e.main.onWorker.add((function t(n,i){r.has(i)||(r.add(i),e.main.onWorker.delete(t),m({disableStdin:!1,cursorBlink:!0,cursorStyle:"block"}),i.sync.is_pyterminal=()=>!0,i.sync.pyterminal_read=l.read.bind(l),i.sync.pyterminal_write=l.write.bind(l))})),e.worker.onReady.add(n)):e.main.onReady.add((function t({interpreter:r,io:n,run:i,type:o}){if("py"!==o)return;console.warn("py-terminal is read only on main thread"),e.main.onReady.delete(t),globalThis.__py_terminal__=m({disableStdin:!0,cursorBlink:!1,cursorStyle:"underline"}),i("from js import __py_terminal__ as __terminal__"),delete globalThis.__py_terminal__,n.stderr=e=>{l.write(String(e.message||e))};let a="";const d=new TextDecoder,s={isatty:!1,write:e=>(a=d.decode(e),l.write(a),e.length)};r.setStdout(s),r.setStderr(s),r.setStdin({isatty:!1,stdin:()=>l.read(a)})}))};export{i as default};
2
- //# sourceMappingURL=py-DuRZhMvB.js.map
1
+ import{e,d as t}from"./core-BTbIsuak.js";const r=new WeakSet,n=({interpreter:e,io:t,run:r,type:n},{sync:i})=>{if("py"!==n||!i.is_pyterminal())return;r(["from polyscript import currentScript as _","__terminal__ = _.terminal","del _"].join(";"));let o="";const{pyterminal_read:a,pyterminal_write:d}=i,s=new TextDecoder,l={isatty:!1,write:e=>(o=s.decode(e),d(o),e.length)};t.stderr=e=>{d(String(e.message||e))},e.setStdout(l),e.setStderr(l),e.setStdin({isatty:!1,stdin:()=>a(o)})};var i=async i=>{const[{Terminal:o},{Readline:a},{FitAddon:d},{WebLinksAddon:s}]=await Promise.all([import("./xterm-BY7uk_OU.js"),import("./xterm-readline-DjufFwfn.js"),import("./xterm_addon-fit--gyF3PcZ.js"),import("./xterm_addon-web-links-Cnej-nJ6.js")]),l=new a,m=e=>{let r=i;const n=i.getAttribute("target");if(n){if(r=document.getElementById(n)||document.querySelector(n),!r)throw new Error(`Unknown target ${n}`)}else r=document.createElement("py-terminal"),r.style.display="block",i.after(r);const a=new o({theme:{background:"#191A19",foreground:"#F5F2E7"},...e}),m=new d;return a.loadAddon(m),a.loadAddon(l),a.loadAddon(new s),a.open(r),m.fit(),a.focus(),t(i,{terminal:{value:a},process:{value:async e=>{for(const t of e.split(/(?:\r\n|\r|\n)/)){a.paste(`${t}`),a.write("\r\n");do{await new Promise((e=>setTimeout(e,0)))}while(!l.activeRead?.resolve);l.activeRead.resolve(t)}}}}),a};i.hasAttribute("worker")?(e.main.onWorker.add((function t(n,i){r.has(i)||(r.add(i),e.main.onWorker.delete(t),m({disableStdin:!1,cursorBlink:!0,cursorStyle:"block"}),i.sync.is_pyterminal=()=>!0,i.sync.pyterminal_read=l.read.bind(l),i.sync.pyterminal_write=l.write.bind(l))})),e.worker.onReady.add(n)):e.main.onReady.add((function t({interpreter:r,io:n,run:i,type:o}){if("py"!==o)return;console.warn("py-terminal is read only on main thread"),e.main.onReady.delete(t),globalThis.__py_terminal__=m({disableStdin:!0,cursorBlink:!1,cursorStyle:"underline"}),i("from js import __py_terminal__ as __terminal__"),delete globalThis.__py_terminal__,n.stderr=e=>{l.write(String(e.message||e))};let a="";const d=new TextDecoder,s={isatty:!1,write:e=>(a=d.decode(e),l.write(a),e.length)};r.setStdout(s),r.setStderr(s),r.setStdin({isatty:!1,stdin:()=>l.read(a)})}))};export{i as default};
2
+ //# sourceMappingURL=py-P8nobKZC.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"py-DuRZhMvB.js","sources":["../src/plugins/py-terminal/py.js"],"sourcesContent":["// PyScript py-terminal plugin\nimport { hooks } from \"../../core.js\";\nimport { defineProperties } from \"polyscript/exports\";\n\nconst bootstrapped = new WeakSet();\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 (type !== \"py\" || !sync.is_pyterminal()) return;\n\n run(\n [\n \"from polyscript import currentScript as _\",\n \"__terminal__ = _.terminal\",\n \"del _\",\n ].join(\";\"),\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 io.stderr = (error) => {\n pyterminal_write(String(error.message || error));\n };\n\n interpreter.setStdout(generic);\n interpreter.setStderr(generic);\n interpreter.setStdin({\n isatty: false,\n stdin: () => pyterminal_read(data),\n });\n};\n\nexport default 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(\n /* webpackIgnore: true */ \"../../3rd-party/xterm-readline.js\"\n ),\n import(\n /* webpackIgnore: true */ \"../../3rd-party/xterm_addon-fit.js\"\n ),\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 for (const line of code.split(/(?:\\r\\n|\\r|\\n)/)) {\n terminal.paste(`${line}`);\n terminal.write(\"\\r\\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 if (type !== \"py\") return;\n\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 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"],"names":["bootstrapped","WeakSet","workerReady","interpreter","io","run","type","sync","is_pyterminal","join","data","pyterminal_read","pyterminal_write","decoder","TextDecoder","generic","isatty","write","buffer","decode","length","stderr","error","String","message","setStdout","setStderr","setStdin","stdin","py","async","element","Terminal","Readline","FitAddon","WebLinksAddon","Promise","all","import","readline","init","options","target","selector","getAttribute","document","getElementById","querySelector","Error","createElement","style","display","after","terminal","theme","background","foreground","fitAddon","loadAddon","open","fit","focus","defineProperties","value","process","code","line","split","paste","resolve","setTimeout","activeRead","hasAttribute","hooks","main","onWorker","add","worker","_","xworker","has","delete","disableStdin","cursorBlink","cursorStyle","read","bind","onReady","console","warn","globalThis","__py_terminal__"],"mappings":"yCAIA,MAAMA,EAAe,IAAIC,QAKnBC,EAAc,EAAGC,cAAaC,KAAIC,MAAKC,SAAUC,WACnD,GAAa,OAATD,IAAkBC,EAAKC,gBAAiB,OAE5CH,EACI,CACI,4CACA,4BACA,SACFI,KAAK,MAGX,IAAIC,EAAO,GACX,MAAMC,gBAAEA,EAAeC,iBAAEA,GAAqBL,EACxCM,EAAU,IAAIC,YACdC,EAAU,CACZC,QAAQ,EACRC,MAAMC,IACFR,EAAOG,EAAQM,OAAOD,GACtBN,EAAiBF,GACVQ,EAAOE,SAItBhB,EAAGiB,OAAUC,IACTV,EAAiBW,OAAOD,EAAME,SAAWF,GAAO,EAGpDnB,EAAYsB,UAAUV,GACtBZ,EAAYuB,UAAUX,GACtBZ,EAAYwB,SAAS,CACjBX,QAAQ,EACRY,MAAO,IAAMjB,EAAgBD,IAC/B,EAGN,IAAemB,EAAAC,MAAOC,IAElB,OAAOC,SAAEA,IAA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KC,KAAK/C,GAClDwC,EAAQxE,KAAKK,iBAAmB2B,EAAStB,MAAMqE,KAAK/C,GAChE,IAIQkC,EAAMI,OAAOU,QAAQX,IAAI1E,IAIzBuE,EAAMC,KAAKa,QAAQX,KAAI,SAASF,GAAKvE,YAAEA,EAAWC,GAAEA,EAAEC,IAAEA,EAAGC,KAAEA,IACzD,GAAa,OAATA,EAAe,OAEnBkF,QAAQC,KAAK,2CACbhB,EAAMC,KAAKa,QAAQN,OAAOP,GAG1BgB,WAAWC,gBAAkBnD,EAAK,CAC9B0C,cAAc,EACdC,aAAa,EACbC,YAAa,cAEjB/E,EAAI,yDACGqF,WAAWC,gBAElBvF,EAAGiB,OAAUC,IACTiB,EAAStB,MAAMM,OAAOD,EAAME,SAAWF,GAAO,EAGlD,IAAIZ,EAAO,GACX,MAAMG,EAAU,IAAIC,YACdC,EAAU,CACZC,QAAQ,EACRC,MAAMC,IACFR,EAAOG,EAAQM,OAAOD,GACtBqB,EAAStB,MAAMP,GACRQ,EAAOE,SAGtBjB,EAAYsB,UAAUV,GACtBZ,EAAYuB,UAAUX,GACtBZ,EAAYwB,SAAS,CACjBX,QAAQ,EACRY,MAAO,IAAMW,EAAS8C,KAAK3E,IAE3C,GACK"}
1
+ {"version":3,"file":"py-P8nobKZC.js","sources":["../src/plugins/py-terminal/py.js"],"sourcesContent":["// PyScript py-terminal plugin\nimport { hooks } from \"../../core.js\";\nimport { defineProperties } from \"polyscript/exports\";\n\nconst bootstrapped = new WeakSet();\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 (type !== \"py\" || !sync.is_pyterminal()) return;\n\n run(\n [\n \"from polyscript import currentScript as _\",\n \"__terminal__ = _.terminal\",\n \"del _\",\n ].join(\";\"),\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 io.stderr = (error) => {\n pyterminal_write(String(error.message || error));\n };\n\n interpreter.setStdout(generic);\n interpreter.setStderr(generic);\n interpreter.setStdin({\n isatty: false,\n stdin: () => pyterminal_read(data),\n });\n};\n\nexport default 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(\n /* webpackIgnore: true */ \"../../3rd-party/xterm-readline.js\"\n ),\n import(\n /* webpackIgnore: true */ \"../../3rd-party/xterm_addon-fit.js\"\n ),\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 for (const line of code.split(/(?:\\r\\n|\\r|\\n)/)) {\n terminal.paste(`${line}`);\n terminal.write(\"\\r\\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 if (type !== \"py\") return;\n\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 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"],"names":["bootstrapped","WeakSet","workerReady","interpreter","io","run","type","sync","is_pyterminal","join","data","pyterminal_read","pyterminal_write","decoder","TextDecoder","generic","isatty","write","buffer","decode","length","stderr","error","String","message","setStdout","setStderr","setStdin","stdin","py","async","element","Terminal","Readline","FitAddon","WebLinksAddon","Promise","all","import","readline","init","options","target","selector","getAttribute","document","getElementById","querySelector","Error","createElement","style","display","after","terminal","theme","background","foreground","fitAddon","loadAddon","open","fit","focus","defineProperties","value","process","code","line","split","paste","resolve","setTimeout","activeRead","hasAttribute","hooks","main","onWorker","add","worker","_","xworker","has","delete","disableStdin","cursorBlink","cursorStyle","read","bind","onReady","console","warn","globalThis","__py_terminal__"],"mappings":"yCAIA,MAAMA,EAAe,IAAIC,QAKnBC,EAAc,EAAGC,cAAaC,KAAIC,MAAKC,SAAUC,WACnD,GAAa,OAATD,IAAkBC,EAAKC,gBAAiB,OAE5CH,EACI,CACI,4CACA,4BACA,SACFI,KAAK,MAGX,IAAIC,EAAO,GACX,MAAMC,gBAAEA,EAAeC,iBAAEA,GAAqBL,EACxCM,EAAU,IAAIC,YACdC,EAAU,CACZC,QAAQ,EACRC,MAAMC,IACFR,EAAOG,EAAQM,OAAOD,GACtBN,EAAiBF,GACVQ,EAAOE,SAItBhB,EAAGiB,OAAUC,IACTV,EAAiBW,OAAOD,EAAME,SAAWF,GAAO,EAGpDnB,EAAYsB,UAAUV,GACtBZ,EAAYuB,UAAUX,GACtBZ,EAAYwB,SAAS,CACjBX,QAAQ,EACRY,MAAO,IAAMjB,EAAgBD,IAC/B,EAGN,IAAemB,EAAAC,MAAOC,IAElB,OAAOC,SAAEA,IAAYC,SAAEA,IAAYC,SAAEA,IAAYC,cAAEA,UACzCC,QAAQC,IAAI,CACdC,OAAiC,uBACjCA,OAC8B,gCAE9BA,OAC8B,iCAE9BA,OAC8B,yCAIhCC,EAAW,IAAIN,EAIfO,EAAQC,IACV,IAAIC,EAASX,EACb,MAAMY,EAAWZ,EAAQa,aAAa,UACtC,GAAID,GAIA,GAHAD,EACIG,SAASC,eAAeH,IACxBE,SAASE,cAAcJ,IACtBD,EAAQ,MAAM,IAAIM,MAAM,kBAAkBL,UAE/CD,EAASG,SAASI,cAAc,eAChCP,EAAOQ,MAAMC,QAAU,QACvBpB,EAAQqB,MAAMV,GAElB,MAAMW,EAAW,IAAIrB,EAAS,CAC1BsB,MAAO,CACHC,WAAY,UACZC,WAA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F,GAAO,EAGlD,IAAIZ,EAAO,GACX,MAAMG,EAAU,IAAIC,YACdC,EAAU,CACZC,QAAQ,EACRC,MAAMC,IACFR,EAAOG,EAAQM,OAAOD,GACtBqB,EAAStB,MAAMP,GACRQ,EAAOE,SAGtBjB,EAAYsB,UAAUV,GACtBZ,EAAYuB,UAAUX,GACtBZ,EAAYwB,SAAS,CACjBX,QAAQ,EACRY,MAAO,IAAMW,EAAS8C,KAAK3E,IAE3C,GACK"}
@@ -1,2 +1,2 @@
1
- import{T as e,d as t,a as r,o as n,X as o,H as s,s as i}from"./core-CVoMgJtU.js";let a=0;const c=e=>`${e}-editor-${a++}`,l=new Map,u=new Map,d={worker:{codeBeforeRun:()=>i,onReady:({runAsync:e,io:t},{sync:r})=>{t.stdout=t.buffered(r.write),t.stderr=t.buffered(r.writeErr),r.revoke(),r.runAsync=e}}};async function p({currentTarget:e}){const{env:t,pySrc:r,outDiv:i}=this,a=!!e;if(a&&(e.disabled=!0,i.innerHTML=""),!l.has(t)){const e=URL.createObjectURL(new Blob([""])),r={type:this.interpreter},{config:i}=this;if(i){r.configURL=i;const{parse:e}=i.endsWith(".toml")?await import("./toml-CvAfdf9_.js"):JSON;r.config=e(await fetch(i).then((e=>e.text()))),r.version=n(r.config)}else r.config={};const a=o.call(new s(null,d),e,r),{sync:c}=a,{promise:u,resolve:p}=Promise.withResolvers();l.set(t,u),c.revoke=()=>{URL.revokeObjectURL(e),p(a)}}return l.get(t).then((t=>{t.onerror=({error:e})=>{a&&(i.innerHTML+=`<span style='color:red'>${e.message||e}</span>\n`),console.error(e)};const n=()=>{a&&(e.disabled=!1)},{sync:o}=t;o.write=e=>{a&&(i.innerText+=`${e}\n`)},o.writeErr=e=>{a&&(i.innerHTML+=`<span style='color:red'>${e}</span>\n`)},o.runAsync(r).then(n,n)}))}const m=(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",(async t=>{r.blur(),await e.handleEvent(t)})),r})(e,t),o=document.createElement("div");return o.addEventListener("keydown",(e=>{e.stopPropagation()})),r.append(n,o),r},f=(e,t)=>{const r=document.createElement("div");r.className=`${t}-editor-box`;const n=m(e,t),o=(e=>{const t=document.createElement("div");return t.className=`${e}-editor-output`,t.id=`${c(e)}-output`,t})(t);return r.append(n,o),[r,o,n.querySelector("button")]},h=async(e,n,o)=>{const[{basicSetup:s,EditorView:i},{Compartment:a},{python:l},{indentUnit:d},{keymap:m},{defaultKeymap:h,indentWithTab:g}]=await Promise.all([import("./codemirror-CdY86QAP.js"),import("./codemirror_state-D1qTXrff.js"),import("./codemirror_lang-python-BVX9Mc4s.js"),import("./codemirror_language-BFA8854-.js").then((function(e){return e.x})),import("./codemirror_view-CH0UDCz6.js").then((function(e){return e.q})),import("./codemirror_commands-Cg5rCf1I.js")]);let v=e.hasAttribute("setup");const y=e.hasAttribute("config"),b=`${o}-${e.getAttribute("env")||c(n)}`;if(y&&u.has(b))throw new SyntaxError(u.get(b)?`duplicated config for env: ${b}`:`unable to add a config to the env: ${b}`);u.set(b,y);let w=e.src?await fetch(e.src).then((e=>e.text())):e.textContent;const E={handleEvent:p,interpreter:o,env:b,config:y&&new URL(e.getAttribute("config"),location.href).href,get pySrc(){return v?w:j.state.doc.toString()},get outDiv(){return v?null:S}};let $;t(e,{target:{get:()=>$},handleEvent:{get:()=>E.handleEvent,set:e=>{E.handleEvent=e===p?p:async r=>{const{currentTarget:n}=r;t(r,{code:{value:E.pySrc}}),!1!==await e(r)&&await p.call(E,{currentTarget:n})}}},code:{get:()=>E.pySrc,set:e=>{v||j.update([j.state.update({changes:{from:0,to:j.state.doc.length,insert:e}})])}},process:{value(e){const t=v,r=w;v=!0,w=e;const n=()=>{v=t,w=r};return E.handleEvent({currentTarget:null}).then(n,n)}}});const x=()=>{const t=new Event(`${n}-editor`,{bubbles:!0});e.dispatchEvent(t)};if(v)return await E.handleEvent({currentTarget:null}),void x();const A=e.getAttribute("target");if(A){if($=document.getElementById(A)||document.querySelector(A),!$)throw new Error(`Unknown target ${A}`)}else $=document.createElement(`${n}-editor`),$.style.display="block",e.after($);$.id||($.id=c(n)),$.hasAttribute("exec-id")||$.setAttribute("exec-id",0),$.hasAttribute("root")||$.setAttribute("root",$.id);const[L,S,C]=f(E,n);L.dataset.env=e.hasAttribute("env")?b:o;const T=L.querySelector(`.${n}-editor-input > div`).attachShadow({mode:"open"});T.innerHTML="<style> :host { all: initial; }</style>",$.appendChild(L);const k=r(e.textContent).trim(),M=/^([ \t]+)/m.test(k)?RegExp.$1:" ",R=()=>C.click(),j=new i({extensions:[d.of(M),(new a).of(l()),m.of([...h,{key:"Ctrl-Enter",run:R,preventDefault:!0},{key:"Cmd-Enter",run:R,preventDefault:!0},{key:"Shift-Enter",run:R,preventDefault:!0},g]),s],foldGutter:!0,gutters:["CodeMirror-linenumbers","CodeMirror-foldgutter"],parent:T,doc:k});j.focus(),x()};let g=0,v=Promise.resolve();const y=()=>{g=0,b()},b=()=>{if(!g){g=setTimeout(y,250);for(const[t,r]of e){const e=`script[type="${t}-editor"]`;for(const n of document.querySelectorAll(e))n.type+="-active",v=v.then((()=>h(n,t,r)))}return v}};new MutationObserver(b).observe(document,{childList:!0,subtree:!0});var w=b();export{w as default};
2
- //# sourceMappingURL=py-editor-C2f99cbd.js.map
1
+ import{T as e,d as t,a as r,o as n,X as o,H as s,s as i}from"./core-BTbIsuak.js";let a=0;const c=e=>`${e}-editor-${a++}`,l=new Map,u=new Map,d={worker:{codeBeforeRun:()=>i,onReady:({runAsync:e,io:t},{sync:r})=>{t.stdout=t.buffered(r.write),t.stderr=t.buffered(r.writeErr),r.revoke(),r.runAsync=e}}};async function p({currentTarget:e}){const{env:t,pySrc:r,outDiv:i}=this,a=!!e;if(a&&(e.disabled=!0,i.innerHTML=""),!l.has(t)){const e=URL.createObjectURL(new Blob([""])),r={type:this.interpreter},{config:i}=this;if(i){r.configURL=i;const{parse:e}=i.endsWith(".toml")?await import("./toml-CvAfdf9_.js"):JSON;r.config=e(await fetch(i).then((e=>e.text()))),r.version=n(r.config)}else r.config={};const a=o.call(new s(null,d),e,r),{sync:c}=a,{promise:u,resolve:p}=Promise.withResolvers();l.set(t,u),c.revoke=()=>{URL.revokeObjectURL(e),p(a)}}return l.get(t).then((t=>{t.onerror=({error:e})=>{a&&(i.innerHTML+=`<span style='color:red'>${e.message||e}</span>\n`),console.error(e)};const n=()=>{a&&(e.disabled=!1)},{sync:o}=t;o.write=e=>{a&&(i.innerText+=`${e}\n`)},o.writeErr=e=>{a&&(i.innerHTML+=`<span style='color:red'>${e}</span>\n`)},o.runAsync(r).then(n,n)}))}const m=(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",(async t=>{r.blur(),await e.handleEvent(t)})),r})(e,t),o=document.createElement("div");return o.addEventListener("keydown",(e=>{e.stopPropagation()})),r.append(n,o),r},f=(e,t)=>{const r=document.createElement("div");r.className=`${t}-editor-box`;const n=m(e,t),o=(e=>{const t=document.createElement("div");return t.className=`${e}-editor-output`,t.id=`${c(e)}-output`,t})(t);return r.append(n,o),[r,o,n.querySelector("button")]},h=async(e,n,o)=>{const[{basicSetup:s,EditorView:i},{Compartment:a},{python:l},{indentUnit:d},{keymap:m},{defaultKeymap:h,indentWithTab:g}]=await Promise.all([import("./codemirror-CdY86QAP.js"),import("./codemirror_state-D1qTXrff.js"),import("./codemirror_lang-python-BVX9Mc4s.js"),import("./codemirror_language-BFA8854-.js").then((function(e){return e.x})),import("./codemirror_view-CH0UDCz6.js").then((function(e){return e.q})),import("./codemirror_commands-Cg5rCf1I.js")]);let v=e.hasAttribute("setup");const y=e.hasAttribute("config"),b=`${o}-${e.getAttribute("env")||c(n)}`;if(y&&u.has(b))throw new SyntaxError(u.get(b)?`duplicated config for env: ${b}`:`unable to add a config to the env: ${b}`);u.set(b,y);let w=e.src?await fetch(e.src).then((e=>e.text())):e.textContent;const E={handleEvent:p,interpreter:o,env:b,config:y&&new URL(e.getAttribute("config"),location.href).href,get pySrc(){return v?w:j.state.doc.toString()},get outDiv(){return v?null:S}};let $;t(e,{target:{get:()=>$},handleEvent:{get:()=>E.handleEvent,set:e=>{E.handleEvent=e===p?p:async r=>{const{currentTarget:n}=r;t(r,{code:{value:E.pySrc}}),!1!==await e(r)&&await p.call(E,{currentTarget:n})}}},code:{get:()=>E.pySrc,set:e=>{v||j.update([j.state.update({changes:{from:0,to:j.state.doc.length,insert:e}})])}},process:{value(e){const t=v,r=w;v=!0,w=e;const n=()=>{v=t,w=r};return E.handleEvent({currentTarget:null}).then(n,n)}}});const x=()=>{const t=new Event(`${n}-editor`,{bubbles:!0});e.dispatchEvent(t)};if(v)return await E.handleEvent({currentTarget:null}),void x();const A=e.getAttribute("target");if(A){if($=document.getElementById(A)||document.querySelector(A),!$)throw new Error(`Unknown target ${A}`)}else $=document.createElement(`${n}-editor`),$.style.display="block",e.after($);$.id||($.id=c(n)),$.hasAttribute("exec-id")||$.setAttribute("exec-id",0),$.hasAttribute("root")||$.setAttribute("root",$.id);const[L,S,C]=f(E,n);L.dataset.env=e.hasAttribute("env")?b:o;const T=L.querySelector(`.${n}-editor-input > div`).attachShadow({mode:"open"});T.innerHTML="<style> :host { all: initial; }</style>",$.appendChild(L);const k=r(e.textContent).trim(),M=/^([ \t]+)/m.test(k)?RegExp.$1:" ",R=()=>C.click(),j=new i({extensions:[d.of(M),(new a).of(l()),m.of([...h,{key:"Ctrl-Enter",run:R,preventDefault:!0},{key:"Cmd-Enter",run:R,preventDefault:!0},{key:"Shift-Enter",run:R,preventDefault:!0},g]),s],foldGutter:!0,gutters:["CodeMirror-linenumbers","CodeMirror-foldgutter"],parent:T,doc:k});j.focus(),x()};let g=0,v=Promise.resolve();const y=()=>{g=0,b()},b=()=>{if(!g){g=setTimeout(y,250);for(const[t,r]of e){const e=`script[type="${t}-editor"]`;for(const n of document.querySelectorAll(e))n.type+="-active",v=v.then((()=>h(n,t,r)))}return v}};new MutationObserver(b).observe(document,{childList:!0,subtree:!0});var w=b();export{w as default};
2
+ //# sourceMappingURL=py-editor-CpkC6EqH.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"py-editor-C2f99cbd.js","sources":["../src/plugins/py-editor.js"],"sourcesContent":["// PyScript py-editor plugin\nimport { Hook, XWorker, dedent, defineProperties } from \"polyscript/exports\";\nimport { TYPES, offline_interpreter, 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 details.version = offline_interpreter(details.config);\n } else {\n details.config = {};\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 return 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 = (handler, 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\", async (event) => {\n runButton.blur();\n await handler.handleEvent(event);\n });\n return runButton;\n};\n\nconst makeEditorDiv = (handler, 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(handler, 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 = (handler, type) => {\n const boxDiv = document.createElement(\"div\");\n boxDiv.className = `${type}-editor-box`;\n\n const editorDiv = makeEditorDiv(handler, type);\n const outDiv = makeOutDiv(type);\n boxDiv.append(editorDiv, outDiv);\n\n return [boxDiv, outDiv, editorDiv.querySelector(\"button\")];\n};\n\nconst init = async (script, type, interpreter) => {\n const [\n { basicSetup, EditorView },\n { Compartment },\n { python },\n { indentUnit },\n { keymap },\n { defaultKeymap, indentWithTab },\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 let 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 let source = script.src\n ? await fetch(script.src).then((b) => b.text())\n : script.textContent;\n const context = {\n // allow the listener to be overridden at distance\n handleEvent: execute,\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 let target;\n defineProperties(script, {\n target: { get: () => target },\n handleEvent: {\n get: () => context.handleEvent,\n set: (callback) => {\n // do not bother with logic if it was set back as its original handler\n if (callback === execute) context.handleEvent = execute;\n // in every other case be sure that if the listener override returned\n // `false` nothing happens, otherwise keep doing what it always did\n else {\n context.handleEvent = async (event) => {\n // trap the currentTarget ASAP (if any)\n // otherwise it gets lost asynchronously\n const { currentTarget } = event;\n // augment a code snapshot before invoking the override\n defineProperties(event, {\n code: { value: context.pySrc },\n });\n // avoid executing the default handler if the override returned `false`\n if ((await callback(event)) !== false)\n await execute.call(context, { currentTarget });\n };\n }\n },\n },\n code: {\n get: () => context.pySrc,\n set: (insert) => {\n if (isSetup) return;\n editor.update([\n editor.state.update({\n changes: {\n from: 0,\n to: editor.state.doc.length,\n insert,\n },\n }),\n ]);\n },\n },\n process: {\n /**\n * Simulate a setup node overriding the source to evaluate.\n * @param {string} code the Python code to evaluate.\n * @returns {Promise<...>} fulfill once code has been evaluated.\n */\n value(code) {\n const wasSetup = isSetup;\n const wasSource = source;\n isSetup = true;\n source = code;\n const restore = () => {\n isSetup = wasSetup;\n source = wasSource;\n };\n return context\n .handleEvent({ currentTarget: null })\n .then(restore, restore);\n },\n },\n });\n\n const notify = () => {\n const event = new Event(`${type}-editor`, { bubbles: true });\n script.dispatchEvent(event);\n };\n\n if (isSetup) {\n await context.handleEvent({ currentTarget: null });\n notify();\n return;\n }\n\n const selector = script.getAttribute(\"target\");\n\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 [boxDiv, outDiv, runButton] = makeBoxDiv(context, 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 = /^([ \\t]+)/m.test(doc) ? RegExp.$1 : \" \";\n\n const listener = () => runButton.click();\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 // @see https://codemirror.net/examples/tab/\n indentWithTab,\n ]),\n basicSetup,\n ],\n foldGutter: true,\n gutters: [\"CodeMirror-linenumbers\", \"CodeMirror-foldgutter\"],\n parent,\n doc,\n });\n\n editor.focus();\n notify();\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","version","offline_interpreter","xworker","XWorker","call","Hook","promise","resolve","Promise","withResolvers","set","revokeObjectURL","get","onerror","error","message","console","enable","str","innerText","makeEditorDiv","handler","editorDiv","document","createElement","className","setAttribute","runButton","addEventListener","event","blur","handleEvent","makeRunButton","editorShadowContainer","stopPropagation","append","makeBoxDiv","boxDiv","makeOutDiv","querySelector","init","script","basicSetup","EditorView","Compartment","python","indentUnit","keymap","defaultKeymap","indentWithTab","all","n","x","q","isSetup","hasAttribute","hasConfig","getAttribute","SyntaxError","source","src","b","textContent","context","location","href","editor","state","doc","toString","target","defineProperties","callback","code","value","insert","update","changes","from","to","length","process","wasSetup","wasSource","restore","notify","Event","bubbles","dispatchEvent","selector","getElementById","Error","style","display","after","dataset","parent","attachShadow","mode","appendChild","dedent","trim","indentation","test","RegExp","$1","listener","click","extensions","of","key","run","preventDefault","foldGutter","gutters","focus","timeout","queue","resetTimeout","pyEditor","setTimeout","TYPES","querySelectorAll","MutationObserver","observe","childList","subtree","pyEditor$1"],"mappings":"iFAMA,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,KACNP,EAAQE,OAASE,QAAYI,MAAMN,GAAQO,MAAMC,GAAMA,EAAEC,UACzDX,EAAQY,QAAUC,EAAoBb,EAAQE,OAC1D,MACYF,EAAQE,OAAS,GAGrB,MAAMY,EAAUC,EAAQC,KAAK,IAAIC,EAAK,KAAM9C,G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AOtF,MAAQ,UAGfkK,EAAQA,EAAMxH,MAAK,IAAM2C,EAAKC,EAAQtF,EAAMkC,IAEnD,CACD,OAAOgI,CAZa,CAYR,EAGhB,IAAIM,iBAAiBJ,GAAUK,QAAQrG,SAAU,CAC7CsG,WAAW,EACXC,SAAS,IAIb,IAAAC,EAAeR"}
1
+ {"version":3,"file":"py-editor-CpkC6EqH.js","sources":["../src/plugins/py-editor.js"],"sourcesContent":["// PyScript py-editor plugin\nimport { Hook, XWorker, dedent, defineProperties } from \"polyscript/exports\";\nimport { TYPES, offline_interpreter, 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 details.version = offline_interpreter(details.config);\n } else {\n details.config = {};\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 return 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 = (handler, 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\", async (event) => {\n runButton.blur();\n await handler.handleEvent(event);\n });\n return runButton;\n};\n\nconst makeEditorDiv = (handler, 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(handler, 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 = (handler, type) => {\n const boxDiv = document.createElement(\"div\");\n boxDiv.className = `${type}-editor-box`;\n\n const editorDiv = makeEditorDiv(handler, type);\n const outDiv = makeOutDiv(type);\n boxDiv.append(editorDiv, outDiv);\n\n return [boxDiv, outDiv, editorDiv.querySelector(\"button\")];\n};\n\nconst init = async (script, type, interpreter) => {\n const [\n { basicSetup, EditorView },\n { Compartment },\n { python },\n { indentUnit },\n { keymap },\n { defaultKeymap, indentWithTab },\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 let 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 let source = script.src\n ? await fetch(script.src).then((b) => b.text())\n : script.textContent;\n const context = {\n // allow the listener to be overridden at distance\n handleEvent: execute,\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 let target;\n defineProperties(script, {\n target: { get: () => target },\n handleEvent: {\n get: () => context.handleEvent,\n set: (callback) => {\n // do not bother with logic if it was set back as its original handler\n if (callback === execute) context.handleEvent = execute;\n // in every other case be sure that if the listener override returned\n // `false` nothing happens, otherwise keep doing what it always did\n else {\n context.handleEvent = async (event) => {\n // trap the currentTarget ASAP (if any)\n // otherwise it gets lost asynchronously\n const { currentTarget } = event;\n // augment a code snapshot before invoking the override\n defineProperties(event, {\n code: { value: context.pySrc },\n });\n // avoid executing the default handler if the override returned `false`\n if ((await callback(event)) !== false)\n await execute.call(context, { currentTarget });\n };\n }\n },\n },\n code: {\n get: () => context.pySrc,\n set: (insert) => {\n if (isSetup) return;\n editor.update([\n editor.state.update({\n changes: {\n from: 0,\n to: editor.state.doc.length,\n insert,\n },\n }),\n ]);\n },\n },\n process: {\n /**\n * Simulate a setup node overriding the source to evaluate.\n * @param {string} code the Python code to evaluate.\n * @returns {Promise<...>} fulfill once code has been evaluated.\n */\n value(code) {\n const wasSetup = isSetup;\n const wasSource = source;\n isSetup = true;\n source = code;\n const restore = () => {\n isSetup = wasSetup;\n source = wasSource;\n };\n return context\n .handleEvent({ currentTarget: null })\n .then(restore, restore);\n },\n },\n });\n\n const notify = () => {\n const event = new Event(`${type}-editor`, { bubbles: true });\n script.dispatchEvent(event);\n };\n\n if (isSetup) {\n await context.handleEvent({ currentTarget: null });\n notify();\n return;\n }\n\n const selector = script.getAttribute(\"target\");\n\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 [boxDiv, outDiv, runButton] = makeBoxDiv(context, 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 = /^([ \\t]+)/m.test(doc) ? RegExp.$1 : \" \";\n\n const listener = () => runButton.click();\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 // @see https://codemirror.net/examples/tab/\n indentWithTab,\n ]),\n basicSetup,\n ],\n foldGutter: true,\n gutters: [\"CodeMirror-linenumbers\", \"CodeMirror-foldgutter\"],\n parent,\n doc,\n });\n\n editor.focus();\n notify();\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","version","offline_interpreter","xworker","XWorker","call","Hook","promise","resolve","Promise","withResolvers","set","revokeObjectURL","get","onerror","error","message","console","enable","str","innerText","makeEditorDiv","handler","editorDiv","document","createElement","className","setAttribute","runButton","addEventListener","event","blur","handleEvent","makeRunButton","editorShadowContainer","stopPropagation","append","makeBoxDiv","boxDiv","makeOutDiv","querySelector","init","script","basicSetup","EditorView","Compartment","python","indentUnit","keymap","defaultKeymap","indentWithTab","all","n","x","q","isSetup","hasAttribute","hasConfig","getAttribute","SyntaxError","source","src","b","textContent","context","location","href","editor","state","doc","toString","target","defineProperties","callback","code","value","insert","update","changes","from","to","length","process","wasSetup","wasSource","restore","notify","Event","bubbles","dispatchEvent","selector","getElementById","Error","style","display","after","dataset","parent","attachShadow","mode","appendChild","dedent","trim","indentation","test","RegExp","$1","listener","click","extensions","of","key","run","preventDefault","foldGutter","gutters","focus","timeout","queue","resetTimeout","pyEditor","setTimeout","TYPES","querySelectorAll","MutationObserver","observe","childList","subtree","pyEditor$1"],"mappings":"iFAMA,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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AAeC,IAAKL,EAAUM,gBAAgB,GAErD/D,IAEJP,GAEJuE,YAAY,EACZC,QAAS,CAAC,yBAA0B,yBACpClB,SACA5B,QAGJF,EAAOiD,QACP9B,GAAQ,EAIZ,IAAI+B,EAAU,EAGVC,EAAQ7G,QAAQD,UAGpB,MAAM+G,EAAe,KACjBF,EAAU,EACVG,GAAU,EAIRA,EAAW,KACb,IAAIH,EAAJ,CACAA,EAAUI,WAAWF,EAAc,KACnC,IAAK,MAAOnK,EAAMkC,KAAgBoI,EAAO,CACrC,MAAMhC,EAAW,gBAAgBtI,aACjC,IAAK,MAAMsF,KAAUlB,SAASmG,iBAAiBjC,GAE3ChD,EAAOtF,MAAQ,UAGfkK,EAAQA,EAAMxH,MAAK,IAAM2C,EAAKC,EAAQtF,EAAMkC,IAEnD,CACD,OAAOgI,CAZa,CAYR,EAGhB,IAAIM,iBAAiBJ,GAAUK,QAAQrG,SAAU,CAC7CsG,WAAW,EACXC,SAAS,IAIb,IAAAC,EAAeR"}
@@ -1,2 +1,2 @@
1
- import{T as e,c as t}from"./core-CVoMgJtU.js";import{notify as r}from"./error-BcdCmvJU.js";const s=[],n=new WeakSet,o=e=>{throw r(e),new Error(e)},a=({attributes:{worker:e}})=>!e;let m=!0;for(const r of e.keys()){const e=`script[type="${r}"][terminal],${r}-script[terminal]`;s.push(e),t.set(e,(async e=>{const t=document.querySelectorAll(s.join(","));if([].filter.call(t,a).length>1&&o("You can use at most 1 main terminal"),m&&(m=!1,document.head.append(Object.assign(document.createElement("link"),{rel:"stylesheet",href:new URL("./xterm.css",import.meta.url)}))),n.has(e))return;n.add(e);const c=t=>t.default(e);"mpy"===r?await import("./mpy-Bfshdqz6.js").then(c):await import("./py-DuRZhMvB.js").then(c)}))}
2
- //# sourceMappingURL=py-terminal-CvFLFMwK.js.map
1
+ import{T as e,c as t}from"./core-BTbIsuak.js";import{notify as r}from"./error-Bdm9PHt9.js";const s=[],n=new WeakSet,o=e=>{throw r(e),new Error(e)},a=({attributes:{worker:e}})=>!e;let m=!0;for(const r of e.keys()){const e=`script[type="${r}"][terminal],${r}-script[terminal]`;s.push(e),t.set(e,(async e=>{const t=document.querySelectorAll(s.join(","));if([].filter.call(t,a).length>1&&o("You can use at most 1 main terminal"),m&&(m=!1,document.head.append(Object.assign(document.createElement("link"),{rel:"stylesheet",href:new URL("./xterm.css",import.meta.url)}))),n.has(e))return;n.add(e);const c=t=>t.default(e);"mpy"===r?await import("./mpy-D5WLUFEd.js").then(c):await import("./py-P8nobKZC.js").then(c)}))}
2
+ //# sourceMappingURL=py-terminal-jFzNJtAO.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"py-terminal-CvFLFMwK.js","sources":["../src/plugins/py-terminal.js"],"sourcesContent":["// PyScript py-terminal plugin\nimport { TYPES } from \"../core.js\";\nimport { notify } from \"./error.js\";\nimport { customObserver } from \"polyscript/exports\";\n\n// will contain all valid selectors\nconst SELECTORS = [];\n\n// avoid processing same elements twice\nconst processed = new WeakSet();\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\nlet addStyle = true;\n\nfor (const type of TYPES.keys()) {\n const selector = `script[type=\"${type}\"][terminal],${type}-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 if (processed.has(element)) return;\n processed.add(element);\n\n const bootstrap = (module) => module.default(element);\n\n // we can't be smart with template literals for the dynamic import\n // or bundlers are incapable of producing multiple files around\n if (type === \"mpy\") {\n await import(/* webpackIgnore: true */ \"./py-terminal/mpy.js\").then(\n bootstrap,\n );\n } else {\n await import(/* webpackIgnore: true */ \"./py-terminal/py.js\").then(\n bootstrap,\n );\n }\n });\n}\n"],"names":["SELECTORS","processed","WeakSet","notifyAndThrow","message","notify","Error","onceOnMain","attributes","worker","addStyle","type","TYPES","keys","selector","push","customObserver","set","async","element","terminals","document","querySelectorAll","join","filter","call","length","head","append","Object","assign","createElement","rel","href","URL","url","has","add","bootstrap","module","default","import","then"],"mappings":"2FAMA,MAAMA,EAAY,GAGZC,EAAY,IAAIC,QAIhBC,EAAkBC,IAEpB,MADAC,EAAOD,GACD,IAAIE,MAAMF,EAAQ,EAGtBG,EAAa,EAAGC,YAAcC,cAAgBA,EAEpD,IAAIC,GAAW,EAEf,IAAK,MAAMC,KAAQC,EAAMC,OAAQ,CAC7B,MAAMC,EAAW,gBAAgBH,iBAAoBA,qBACrDX,EAAUe,KAAKD,GACfE,EAAeC,IAAIH,GAAUI,MAAOC,IAEhC,MAAMC,EAAYC,SAASC,iBAAiBtB,EAAUuB,KAAK,MAe3D,GAdI,GAAGC,OAAOC,KAAKL,EAAWb,GAAYmB,OAAS,GAC/CvB,EAAe,uCAGfO,IACAA,GAAW,EACXW,SAASM,KAAKC,OACVC,OAAOC,OAAOT,SAASU,cAAc,QAAS,CAC1CC,IAAK,aACLC,KAAM,IAAIC,IAAI,0BAA2BC,SAKjDlC,EAAUmC,IAAIjB,GAAU,OAC5BlB,EAAUoC,IAAIlB,GAEd,MAAMmB,EAAaC,GAAWA,EAAOC,QAAQrB,GAIhC,QAATR,QACM8B,OAAiC,qBAAwBC,KAC3DJ,SAGEG,OAAiC,oBAAuBC,KAC1DJ,EAEP,GAET"}
1
+ {"version":3,"file":"py-terminal-jFzNJtAO.js","sources":["../src/plugins/py-terminal.js"],"sourcesContent":["// PyScript py-terminal plugin\nimport { TYPES } from \"../core.js\";\nimport { notify } from \"./error.js\";\nimport { customObserver } from \"polyscript/exports\";\n\n// will contain all valid selectors\nconst SELECTORS = [];\n\n// avoid processing same elements twice\nconst processed = new WeakSet();\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\nlet addStyle = true;\n\nfor (const type of TYPES.keys()) {\n const selector = `script[type=\"${type}\"][terminal],${type}-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 if (processed.has(element)) return;\n processed.add(element);\n\n const bootstrap = (module) => module.default(element);\n\n // we can't be smart with template literals for the dynamic import\n // or bundlers are incapable of producing multiple files around\n if (type === \"mpy\") {\n await import(/* webpackIgnore: true */ \"./py-terminal/mpy.js\").then(\n bootstrap,\n );\n } else {\n await import(/* webpackIgnore: true */ \"./py-terminal/py.js\").then(\n bootstrap,\n );\n }\n });\n}\n"],"names":["SELECTORS","processed","WeakSet","notifyAndThrow","message","notify","Error","onceOnMain","attributes","worker","addStyle","type","TYPES","keys","selector","push","customObserver","set","async","element","terminals","document","querySelectorAll","join","filter","call","length","head","append","Object","assign","createElement","rel","href","URL","url","has","add","bootstrap","module","default","import","then"],"mappings":"2FAMA,MAAMA,EAAY,GAGZC,EAAY,IAAIC,QAIhBC,EAAkBC,IAEpB,MADAC,EAAOD,GACD,IAAIE,MAAMF,EAAQ,EAGtBG,EAAa,EAAGC,YAAcC,cAAgBA,EAEpD,IAAIC,GAAW,EAEf,IAAK,MAAMC,KAAQC,EAAMC,OAAQ,CAC7B,MAAMC,EAAW,gBAAgBH,iBAAoBA,qBACrDX,EAAUe,KAAKD,GACfE,EAAeC,IAAIH,GAAUI,MAAOC,IAEhC,MAAMC,EAAYC,SAASC,iBAAiBtB,EAAUuB,KAAK,MAe3D,GAdI,GAAGC,OAAOC,KAAKL,EAAWb,GAAYmB,OAAS,GAC/CvB,EAAe,uCAGfO,IACAA,GAAW,EACXW,SAASM,KAAKC,OACVC,OAAOC,OAAOT,SAASU,cAAc,QAAS,CAC1CC,IAAK,aACLC,KAAM,IAAIC,IAAI,0BAA2BC,SAKjDlC,EAAUmC,IAAIjB,GAAU,OAC5BlB,EAAUoC,IAAIlB,GAEd,MAAMmB,EAAaC,GAAWA,EAAOC,QAAQrB,GAIhC,QAATR,QACM8B,OAAiC,qBAAwBC,KAC3DJ,SAGEG,OAAiC,oBAAuBC,KAC1DJ,EAEP,GAET"}
package/dist.zip ADDED
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pyscript/core",
3
- "version": "0.4.47",
3
+ "version": "0.4.49",
4
4
  "type": "module",
5
5
  "description": "PyScript",
6
6
  "module": "./index.js",
@@ -44,7 +44,7 @@
44
44
  "dependencies": {
45
45
  "@ungap/with-resolvers": "^0.1.0",
46
46
  "basic-devtools": "^0.1.6",
47
- "polyscript": "^0.13.4",
47
+ "polyscript": "^0.13.7",
48
48
  "sticky-module": "^0.1.1",
49
49
  "to-json-callback": "^0.1.1",
50
50
  "type-checked-collections": "^0.1.7"
@@ -62,7 +62,7 @@
62
62
  "@webreflection/toml-j0.4": "^1.1.3",
63
63
  "@xterm/addon-fit": "^0.10.0",
64
64
  "@xterm/addon-web-links": "^0.11.0",
65
- "bun": "^1.1.14",
65
+ "bun": "^1.1.15",
66
66
  "chokidar": "^3.6.0",
67
67
  "codemirror": "^6.0.1",
68
68
  "eslint": "^9.5.0",
@@ -46,6 +46,9 @@ from pyscript.magic_js import (
46
46
  from pyscript.storage import Storage, storage
47
47
  from pyscript.websocket import WebSocket
48
48
 
49
+ if not RUNNING_IN_WORKER:
50
+ from polyscript import workers
51
+
49
52
  try:
50
53
  from pyscript.event_handling import when
51
54
  except:
@@ -1,7 +1,7 @@
1
1
  // ⚠️ This file is an artifact: DO NOT MODIFY
2
2
  export default {
3
3
  "pyscript": {
4
- "__init__.py": "# Some notes about the naming conventions and the relationship between various\n# similar-but-different names.\n#\n# import pyscript\n# this package contains the main user-facing API offered by pyscript. All\n# the names which are supposed be used by end users should be made\n# available in pyscript/__init__.py (i.e., this file)\n#\n# import _pyscript\n# this is an internal module implemented in JS. It is used internally by\n# the pyscript package, end users should not use it directly. For its\n# implementation, grep for `interpreter.registerJsModule(\"_pyscript\",\n# ...)` in core.js\n#\n# import js\n# this is the JS globalThis, as exported by pyodide and/or micropython's\n# FFIs. As such, it contains different things in the main thread or in a\n# worker.\n#\n# import pyscript.magic_js\n# this submodule abstracts away some of the differences between the main\n# thread and the worker. In particular, it defines `window` and `document`\n# in such a way that these names work in both cases: in the main thread,\n# they are the \"real\" objects, in the worker they are proxies which work\n# thanks to coincident.\n#\n# from pyscript import window, document\n# these are just the window and document objects as defined by\n# pyscript.magic_js. This is the blessed way to access them from pyscript,\n# as it works transparently in both the main thread and worker cases.\n\nfrom polyscript import lazy_py_modules as py_import\nfrom pyscript.display import HTML, display\nfrom pyscript.fetch import fetch\nfrom pyscript.magic_js import (\n RUNNING_IN_WORKER,\n PyWorker,\n config,\n current_target,\n document,\n js_import,\n js_modules,\n sync,\n window,\n)\nfrom pyscript.storage import Storage, storage\nfrom pyscript.websocket import WebSocket\n\ntry:\n from pyscript.event_handling import when\nexcept:\n # TODO: should we remove this? Or at the very least, we should capture\n # the traceback otherwise it's very hard to debug\n from pyscript.util import NotSupported\n\n when = NotSupported(\n \"pyscript.when\", \"pyscript.when currently not available with this interpreter\"\n )\n",
4
+ "__init__.py": "# Some notes about the naming conventions and the relationship between various\n# similar-but-different names.\n#\n# import pyscript\n# this package contains the main user-facing API offered by pyscript. All\n# the names which are supposed be used by end users should be made\n# available in pyscript/__init__.py (i.e., this file)\n#\n# import _pyscript\n# this is an internal module implemented in JS. It is used internally by\n# the pyscript package, end users should not use it directly. For its\n# implementation, grep for `interpreter.registerJsModule(\"_pyscript\",\n# ...)` in core.js\n#\n# import js\n# this is the JS globalThis, as exported by pyodide and/or micropython's\n# FFIs. As such, it contains different things in the main thread or in a\n# worker.\n#\n# import pyscript.magic_js\n# this submodule abstracts away some of the differences between the main\n# thread and the worker. In particular, it defines `window` and `document`\n# in such a way that these names work in both cases: in the main thread,\n# they are the \"real\" objects, in the worker they are proxies which work\n# thanks to coincident.\n#\n# from pyscript import window, document\n# these are just the window and document objects as defined by\n# pyscript.magic_js. This is the blessed way to access them from pyscript,\n# as it works transparently in both the main thread and worker cases.\n\nfrom polyscript import lazy_py_modules as py_import\nfrom pyscript.display import HTML, display\nfrom pyscript.fetch import fetch\nfrom pyscript.magic_js import (\n RUNNING_IN_WORKER,\n PyWorker,\n config,\n current_target,\n document,\n js_import,\n js_modules,\n sync,\n window,\n)\nfrom pyscript.storage import Storage, storage\nfrom pyscript.websocket import WebSocket\n\nif not RUNNING_IN_WORKER:\n from polyscript import workers\n\ntry:\n from pyscript.event_handling import when\nexcept:\n # TODO: should we remove this? Or at the very least, we should capture\n # the traceback otherwise it's very hard to debug\n from pyscript.util import NotSupported\n\n when = NotSupported(\n \"pyscript.when\", \"pyscript.when currently not available with this interpreter\"\n )\n",
5
5
  "display.py": "import base64\nimport html\nimport io\nimport re\n\nfrom pyscript.magic_js import current_target, document, window\n\n_MIME_METHODS = {\n \"savefig\": \"image/png\",\n \"_repr_javascript_\": \"application/javascript\",\n \"_repr_json_\": \"application/json\",\n \"_repr_latex\": \"text/latex\",\n \"_repr_png_\": \"image/png\",\n \"_repr_jpeg_\": \"image/jpeg\",\n \"_repr_pdf_\": \"application/pdf\",\n \"_repr_svg_\": \"image/svg+xml\",\n \"_repr_markdown_\": \"text/markdown\",\n \"_repr_html_\": \"text/html\",\n \"__repr__\": \"text/plain\",\n}\n\n\ndef _render_image(mime, value, meta):\n # If the image value is using bytes we should convert it to base64\n # otherwise it will return raw bytes and the browser will not be able to\n # render it.\n if isinstance(value, bytes):\n value = base64.b64encode(value).decode(\"utf-8\")\n\n # This is the pattern of base64 strings\n base64_pattern = re.compile(\n r\"^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$\"\n )\n # If value doesn't match the base64 pattern we should encode it to base64\n if len(value) > 0 and not base64_pattern.match(value):\n value = base64.b64encode(value.encode(\"utf-8\")).decode(\"utf-8\")\n\n data = f\"data:{mime};charset=utf-8;base64,{value}\"\n attrs = \" \".join(['{k}=\"{v}\"' for k, v in meta.items()])\n return f'<img src=\"{data}\" {attrs}></img>'\n\n\ndef _identity(value, meta):\n return value\n\n\n_MIME_RENDERERS = {\n \"text/plain\": html.escape,\n \"text/html\": _identity,\n \"image/png\": lambda value, meta: _render_image(\"image/png\", value, meta),\n \"image/jpeg\": lambda value, meta: _render_image(\"image/jpeg\", value, meta),\n \"image/svg+xml\": _identity,\n \"application/json\": _identity,\n \"application/javascript\": lambda value, meta: f\"<script>{value}<\\\\/script>\",\n}\n\n\nclass HTML:\n \"\"\"\n Wrap a string so that display() can render it as plain HTML\n \"\"\"\n\n def __init__(self, html):\n self._html = html\n\n def _repr_html_(self):\n return self._html\n\n\ndef _eval_formatter(obj, print_method):\n \"\"\"\n Evaluates a formatter method.\n \"\"\"\n if print_method == \"__repr__\":\n return repr(obj)\n elif hasattr(obj, print_method):\n if print_method == \"savefig\":\n buf = io.BytesIO()\n obj.savefig(buf, format=\"png\")\n buf.seek(0)\n return base64.b64encode(buf.read()).decode(\"utf-8\")\n return getattr(obj, print_method)()\n elif print_method == \"_repr_mimebundle_\":\n return {}, {}\n return None\n\n\ndef _format_mime(obj):\n \"\"\"\n Formats object using _repr_x_ methods.\n \"\"\"\n if isinstance(obj, str):\n return html.escape(obj), \"text/plain\"\n\n mimebundle = _eval_formatter(obj, \"_repr_mimebundle_\")\n if isinstance(mimebundle, tuple):\n format_dict, _ = mimebundle\n else:\n format_dict = mimebundle\n\n output, not_available = None, []\n for method, mime_type in _MIME_METHODS.items():\n if mime_type in format_dict:\n output = format_dict[mime_type]\n else:\n output = _eval_formatter(obj, method)\n\n if output is None:\n continue\n elif mime_type not in _MIME_RENDERERS:\n not_available.append(mime_type)\n continue\n break\n if output is None:\n if not_available:\n window.console.warn(\n f\"Rendered object requested unavailable MIME renderers: {not_available}\"\n )\n output = repr(output)\n mime_type = \"text/plain\"\n elif isinstance(output, tuple):\n output, meta = output\n else:\n meta = {}\n return _MIME_RENDERERS[mime_type](output, meta), mime_type\n\n\ndef _write(element, value, append=False):\n html, mime_type = _format_mime(value)\n if html == \"\\\\n\":\n return\n\n if append:\n out_element = document.createElement(\"div\")\n element.append(out_element)\n else:\n out_element = element.lastElementChild\n if out_element is None:\n out_element = element\n\n if mime_type in (\"application/javascript\", \"text/html\"):\n script_element = document.createRange().createContextualFragment(html)\n out_element.append(script_element)\n else:\n out_element.innerHTML = html\n\n\ndef display(*values, target=None, append=True):\n if target is None:\n target = current_target()\n elif not isinstance(target, str):\n raise TypeError(f\"target must be str or None, not {target.__class__.__name__}\")\n elif target == \"\":\n raise ValueError(\"Cannot have an empty target\")\n elif target.startswith(\"#\"):\n # note: here target is str and not None!\n # align with @when behavior\n target = target[1:]\n\n element = document.getElementById(target)\n\n # If target cannot be found on the page, a ValueError is raised\n if element is None:\n raise ValueError(\n f\"Invalid selector with id={target}. Cannot be found in the page.\"\n )\n\n # if element is a <script type=\"py\">, it has a 'target' attribute which\n # points to the visual element holding the displayed values. In that case,\n # use that.\n if element.tagName == \"SCRIPT\" and hasattr(element, \"target\"):\n element = element.target\n\n for v in values:\n if not append:\n element.replaceChildren()\n _write(element, v, append=append)\n",
6
6
  "event_handling.py": "import inspect\n\ntry:\n from pyodide.ffi.wrappers import add_event_listener\n\nexcept ImportError:\n\n def add_event_listener(el, event_type, func):\n el.addEventListener(event_type, func)\n\n\nfrom pyscript.magic_js import document\n\n\ndef when(event_type=None, selector=None):\n \"\"\"\n Decorates a function and passes py-* events to the decorated function\n The events might or not be an argument of the decorated function\n \"\"\"\n\n def decorator(func):\n\n from pyscript.web.elements import Element, ElementCollection\n\n if isinstance(selector, str):\n elements = document.querySelectorAll(selector)\n else:\n # TODO: This is a hack that will be removed when pyscript becomes a package\n # and we can better manage the imports without circular dependencies\n if isinstance(selector, Element):\n elements = [selector._js]\n elif isinstance(selector, ElementCollection):\n elements = [el._js for el in selector]\n else:\n raise ValueError(\n f\"Invalid selector: {selector}. Selector must\"\n \" be a string, a pydom.Element or a pydom.ElementCollection.\"\n )\n try:\n sig = inspect.signature(func)\n # Function doesn't receive events\n if not sig.parameters:\n\n def wrapper(*args, **kwargs):\n func()\n\n else:\n wrapper = func\n\n except AttributeError:\n # TODO: this is very ugly hack to get micropython working because inspect.signature\n # doesn't exist, but we need to actually properly replace inspect.signature.\n # It may be actually better to not try any magic for now and raise the error\n def wrapper(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except TypeError as e:\n if \"takes\" in str(e) and \"positional arguments\" in str(e):\n return func()\n\n raise\n\n for el in elements:\n add_event_listener(el, event_type, wrapper)\n\n return func\n\n return decorator\n",
7
7
  "fetch.py": "import json\n\nimport js\nfrom pyscript.util import as_bytearray\n\n\n### wrap the response to grant Pythonic results\nclass _Response:\n def __init__(self, response):\n self._response = response\n\n # grant access to response.ok and other fields\n def __getattr__(self, attr):\n return getattr(self._response, attr)\n\n # exposed methods with Pythonic results\n async def arrayBuffer(self):\n buffer = await self._response.arrayBuffer()\n # works in Pyodide\n if hasattr(buffer, \"to_py\"):\n return buffer.to_py()\n # shims in MicroPython\n return memoryview(as_bytearray(buffer))\n\n async def blob(self):\n return await self._response.blob()\n\n async def bytearray(self):\n buffer = await self._response.arrayBuffer()\n return as_bytearray(buffer)\n\n async def json(self):\n return json.loads(await self.text())\n\n async def text(self):\n return await self._response.text()\n\n\n### allow direct await to _Response methods\nclass _DirectResponse:\n @staticmethod\n def setup(promise, response):\n promise._response = _Response(response)\n return promise._response\n\n def __init__(self, promise):\n self._promise = promise\n promise._response = None\n promise.arrayBuffer = self.arrayBuffer\n promise.blob = self.blob\n promise.bytearray = self.bytearray\n promise.json = self.json\n promise.text = self.text\n\n async def _response(self):\n if not self._promise._response:\n await self._promise\n return self._promise._response\n\n async def arrayBuffer(self):\n response = await self._response()\n return await response.arrayBuffer()\n\n async def blob(self):\n response = await self._response()\n return await response.blob()\n\n async def bytearray(self):\n response = await self._response()\n return await response.bytearray()\n\n async def json(self):\n response = await self._response()\n return await response.json()\n\n async def text(self):\n response = await self._response()\n return await response.text()\n\n\ndef fetch(url, **kw):\n # workaround Pyodide / MicroPython dict <-> js conversion\n options = js.JSON.parse(json.dumps(kw))\n awaited = lambda response, *args: _DirectResponse.setup(promise, response)\n promise = js.fetch(url, options).then(awaited)\n _DirectResponse(promise)\n return promise\n",