@pyscript/core 0.4.42 → 0.4.43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/{codemirror-Cuc1ujlq.js → codemirror-Dl5H49bb.js} +2 -2
  2. package/dist/{codemirror-Cuc1ujlq.js.map → codemirror-Dl5H49bb.js.map} +1 -1
  3. package/dist/{codemirror_commands-DrGPggEa.js → codemirror_commands-BdjCAcK-.js} +2 -2
  4. package/dist/{codemirror_commands-DrGPggEa.js.map → codemirror_commands-BdjCAcK-.js.map} +1 -1
  5. package/dist/{codemirror_lang-python-CJNnzWx3.js → codemirror_lang-python--SQq2qB4.js} +2 -2
  6. package/dist/{codemirror_lang-python-CJNnzWx3.js.map → codemirror_lang-python--SQq2qB4.js.map} +1 -1
  7. package/dist/{codemirror_language-w-S9uYcH.js → codemirror_language-CAKlJ8mf.js} +2 -2
  8. package/dist/{codemirror_language-w-S9uYcH.js.map → codemirror_language-CAKlJ8mf.js.map} +1 -1
  9. package/dist/codemirror_view-BQKcFXby.js +2 -0
  10. package/dist/codemirror_view-BQKcFXby.js.map +1 -0
  11. package/dist/core-B6hsMz8Y.js +3 -0
  12. package/dist/{core-DmXwjHtp.js.map → core-B6hsMz8Y.js.map} +1 -1
  13. package/dist/core.js +1 -1
  14. package/dist/{deprecations-manager-_UxKHXZB.js → deprecations-manager-De5K5cXk.js} +2 -2
  15. package/dist/{deprecations-manager-_UxKHXZB.js.map → deprecations-manager-De5K5cXk.js.map} +1 -1
  16. package/dist/{error-DbRphA3T.js → error-Dfrs7Q5J.js} +2 -2
  17. package/dist/{error-DbRphA3T.js.map → error-Dfrs7Q5J.js.map} +1 -1
  18. package/dist/{index-B-A3jfDu.js → index-DUXwuZn0.js} +2 -2
  19. package/dist/{index-B-A3jfDu.js.map → index-DUXwuZn0.js.map} +1 -1
  20. package/dist/{mpy-BzefGwGL.js → mpy-Noch7TCk.js} +2 -2
  21. package/dist/{mpy-BzefGwGL.js.map → mpy-Noch7TCk.js.map} +1 -1
  22. package/dist/{py-CdfTwlyw.js → py-6RmoksBq.js} +2 -2
  23. package/dist/{py-CdfTwlyw.js.map → py-6RmoksBq.js.map} +1 -1
  24. package/dist/py-editor-DeavJRm_.js +2 -0
  25. package/dist/py-editor-DeavJRm_.js.map +1 -0
  26. package/dist/{py-terminal-CnFb82OC.js → py-terminal-CVai3EuH.js} +2 -2
  27. package/dist/{py-terminal-CnFb82OC.js.map → py-terminal-CVai3EuH.js.map} +1 -1
  28. package/package.json +4 -4
  29. package/src/core.js +1 -1
  30. package/src/plugins/py-editor.js +42 -12
  31. package/src/stdlib/pyscript/__init__.py +1 -1
  32. package/src/stdlib/pyscript/event_handling.py +9 -7
  33. package/src/stdlib/pyscript/magic_js.py +4 -1
  34. package/src/stdlib/pyscript/web/__init__.py +5 -0
  35. package/src/stdlib/pyscript/web/dom.py +21 -0
  36. package/src/stdlib/pyscript/web/elements.py +1484 -0
  37. package/src/stdlib/pyscript.js +9 -8
  38. package/src/stdlib.js +1 -1
  39. package/types/stdlib/pyscript.d.ts +6 -5
  40. package/dist/codemirror_view-DfjLm8GV.js +0 -2
  41. package/dist/codemirror_view-DfjLm8GV.js.map +0 -1
  42. package/dist/core-DmXwjHtp.js +0 -3
  43. package/dist/py-editor-z9mZdLa8.js +0 -2
  44. package/dist/py-editor-z9mZdLa8.js.map +0 -1
  45. package/src/stdlib/pyweb/__init__.py +0 -1
  46. package/src/stdlib/pyweb/pydom.py +0 -550
  47. /package/src/stdlib/{pyweb → pyscript/web}/media.py +0 -0
@@ -1,2 +1,2 @@
1
- import{e,i as r,d as t}from"./core-DmXwjHtp.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-BzefGwGL.js.map
1
+ import{e,i as r,d as t}from"./core-B6hsMz8Y.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-Noch7TCk.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"mpy-BzefGwGL.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":"gDA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AAIhF,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-Noch7TCk.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,EAAGC,cAAaC,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CrB,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-DmXwjHtp.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-D247p8vq.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-CdfTwlyw.js.map
1
+ import{e,d as t}from"./core-B6hsMz8Y.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-D247p8vq.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-6RmoksBq.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"py-CdfTwlyw.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,I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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-6RmoksBq.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,WAAY,cAEbf,IA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lD,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"}
@@ -0,0 +1,2 @@
1
+ import{T as e,d as t,a as r,o as n,X as o,H as s,s as a}from"./core-B6hsMz8Y.js";let i=0;const c=e=>`${e}-editor-${i++}`,l=new Map,u=new Map,d={worker:{codeBeforeRun:()=>a,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:a}=this,i=!!e;if(i&&(e.disabled=!0,a.innerHTML=""),!l.has(t)){const e=URL.createObjectURL(new Blob([""])),r={type:this.interpreter},{config:a}=this;if(a){r.configURL=a;const{parse:e}=a.endsWith(".toml")?await import("./toml-CvAfdf9_.js"):JSON;r.config=e(await fetch(a).then((e=>e.text()))),r.version=n(r.config)}else r.config={};const i=o.call(new s(null,d),e,r),{sync:c}=i,{promise:u,resolve:p}=Promise.withResolvers();l.set(t,u),c.revoke=()=>{URL.revokeObjectURL(e),p(i)}}return l.get(t).then((t=>{t.onerror=({error:e})=>{i&&(a.innerHTML+=`<span style='color:red'>${e.message||e}</span>\n`),console.error(e)};const n=()=>{i&&(e.disabled=!1)},{sync:o}=t;o.write=e=>{i&&(a.innerText+=`${e}\n`)},o.writeErr=e=>{i&&(a.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")]},g=async(e,n,o)=>{const[{basicSetup:s,EditorView:a},{Compartment:i},{python:l},{indentUnit:d},{keymap:m},{defaultKeymap:g}]=await Promise.all([import("./codemirror-Dl5H49bb.js"),import("./codemirror_state-D1qTXrff.js"),import("./codemirror_lang-python--SQq2qB4.js"),import("./codemirror_language-CAKlJ8mf.js").then((function(e){return e.x})),import("./codemirror_view-BQKcFXby.js").then((function(e){return e.q})),import("./codemirror_commands-BdjCAcK-.js")]);let h=e.hasAttribute("setup");const v=e.hasAttribute("config"),y=`${o}-${e.getAttribute("env")||c(n)}`;if(v&&u.has(y))throw new SyntaxError(u.get(y)?`duplicated config for env: ${y}`:`unable to add a config to the env: ${y}`);u.set(y,v);let b=e.src?await fetch(e.src).then((e=>e.text())):e.textContent;const w={handleEvent:p,interpreter:o,env:y,config:v&&new URL(e.getAttribute("config"),location.href).href,get pySrc(){return h?b:R.state.doc.toString()},get outDiv(){return h?null:L}};let E;t(e,{target:{get:()=>E},handleEvent:{get:()=>w.handleEvent,set:e=>{w.handleEvent=e===p?p:async r=>{const{currentTarget:n}=r;t(r,{code:{value:w.pySrc}}),!1!==await e(r)&&await p.call(w,{currentTarget:n})}}},code:{get:()=>w.pySrc,set:e=>{h||R.update([R.state.update({changes:{from:0,to:R.state.doc.length,insert:e}})])}},process:{value(e){const t=h,r=b;h=!0,b=e;const n=()=>{h=t,b=r};return w.handleEvent({currentTarget:null}).then(n,n)}}});const $=()=>{const t=new Event(`${n}-editor`,{bubbles:!0});e.dispatchEvent(t)};if(h)return await w.handleEvent({currentTarget:null}),void $();const x=e.getAttribute("target");if(x){if(E=document.getElementById(x)||document.querySelector(x),!E)throw new Error(`Unknown target ${x}`)}else E=document.createElement(`${n}-editor`),E.style.display="block",e.after(E);E.id||(E.id=c(n)),E.hasAttribute("exec-id")||E.setAttribute("exec-id",0),E.hasAttribute("root")||E.setAttribute("root",E.id);const[A,L,S]=f(w,n);A.dataset.env=e.hasAttribute("env")?y:o;const C=A.querySelector(`.${n}-editor-input > div`).attachShadow({mode:"open"});C.innerHTML="<style> :host { all: initial; }</style>",E.appendChild(A);const k=r(e.textContent).trim(),T=/^(\s+)/m.test(k)?RegExp.$1:" ",M=()=>S.click(),R=new a({extensions:[d.of(T),(new i).of(l()),m.of([...g,{key:"Ctrl-Enter",run:M,preventDefault:!0},{key:"Cmd-Enter",run:M,preventDefault:!0},{key:"Shift-Enter",run:M,preventDefault:!0}]),s],foldGutter:!0,gutters:["CodeMirror-linenumbers","CodeMirror-foldgutter"],parent:C,doc:k});R.focus(),$()};let h=0,v=Promise.resolve();const y=()=>{h=0,b()},b=()=>{if(!h){h=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((()=>g(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-DeavJRm_.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"py-editor-DeavJRm_.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 },\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 = /^(\\s+)/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 ]),\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","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,O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ACb,IAAIH,EAAJ,CACAA,EAAUI,WAAWF,EAAc,KACnC,IAAK,MAAOlK,EAAMkC,KAAgBmI,EAAO,CACrC,MAAMhC,EAAW,gBAAgBrI,aACjC,IAAK,MAAMsF,KAAUlB,SAASkG,iBAAiBjC,GAE3C/C,EAAOtF,MAAQ,UAGfiK,EAAQA,EAAMvH,MAAK,IAAM2C,EAAKC,EAAQtF,EAAMkC,IAEnD,CACD,OAAO+H,CAZa,CAYR,EAGhB,IAAIM,iBAAiBJ,GAAUK,QAAQpG,SAAU,CAC7CqG,WAAW,EACXC,SAAS,IAIb,IAAAC,EAAeR"}
@@ -1,2 +1,2 @@
1
- import{T as e,c as t}from"./core-DmXwjHtp.js";import{notify as r}from"./error-DbRphA3T.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-BzefGwGL.js").then(c):await import("./py-CdfTwlyw.js").then(c)}))}
2
- //# sourceMappingURL=py-terminal-CnFb82OC.js.map
1
+ import{T as e,c as t}from"./core-B6hsMz8Y.js";import{notify as r}from"./error-Dfrs7Q5J.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-Noch7TCk.js").then(c):await import("./py-6RmoksBq.js").then(c)}))}
2
+ //# sourceMappingURL=py-terminal-CVai3EuH.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"py-terminal-CnFb82OC.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-CVai3EuH.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pyscript/core",
3
- "version": "0.4.42",
3
+ "version": "0.4.43",
4
4
  "type": "module",
5
5
  "description": "PyScript",
6
6
  "module": "./index.js",
@@ -20,7 +20,7 @@
20
20
  },
21
21
  "scripts": {
22
22
  "server": "npx static-handler --coi .",
23
- "build": "export ESLINT_USE_FLAT_CONFIG=true;npm run build:3rd-party && npm run build:stdlib && npm run build:plugins && npm run build:core && eslint src/ && npm run ts && npm run test:mpy",
23
+ "build": "export ESLINT_USE_FLAT_CONFIG=true;npm run build:3rd-party && npm run build:stdlib && npm run build:plugins && npm run build:core && if [ -z \"$NO_MIN\" ]; then eslint src/ && npm run ts && npm run test:mpy; fi",
24
24
  "build:core": "rm -rf dist && rollup --config rollup/core.config.js && cp src/3rd-party/*.css dist/",
25
25
  "build:plugins": "node rollup/plugins.cjs",
26
26
  "build:stdlib": "node rollup/stdlib.cjs",
@@ -53,9 +53,9 @@
53
53
  "@codemirror/lang-python": "^6.1.6",
54
54
  "@codemirror/language": "^6.10.2",
55
55
  "@codemirror/state": "^6.4.1",
56
- "@codemirror/view": "^6.27.0",
56
+ "@codemirror/view": "^6.28.0",
57
57
  "@playwright/test": "^1.44.1",
58
- "@rollup/plugin-commonjs": "^25.0.8",
58
+ "@rollup/plugin-commonjs": "^26.0.1",
59
59
  "@rollup/plugin-node-resolve": "^15.2.3",
60
60
  "@rollup/plugin-terser": "^0.4.4",
61
61
  "@webreflection/toml-j0.4": "^1.1.3",
package/src/core.js CHANGED
@@ -157,7 +157,7 @@ for (const [TYPE, interpreter] of TYPES) {
157
157
  // enrich the Python env with some JS utility for main
158
158
  interpreter.registerJsModule("_pyscript", {
159
159
  PyWorker,
160
- js_import: (...urls) => Promise.all(urls.map(url => import(url))),
160
+ js_import: (...urls) => Promise.all(urls.map((url) => import(url))),
161
161
  get target() {
162
162
  return isScript(currentElement)
163
163
  ? currentElement.target.id
@@ -86,21 +86,24 @@ async function execute({ currentTarget }) {
86
86
  });
87
87
  }
88
88
 
89
- const makeRunButton = (listener, type) => {
89
+ const makeRunButton = (handler, type) => {
90
90
  const runButton = document.createElement("button");
91
91
  runButton.className = `absolute ${type}-editor-run-button`;
92
92
  runButton.innerHTML = RUN_BUTTON;
93
93
  runButton.setAttribute("aria-label", "Python Script Run Button");
94
- runButton.addEventListener("click", listener);
94
+ runButton.addEventListener("click", async (event) => {
95
+ runButton.blur();
96
+ await handler.handleEvent(event);
97
+ });
95
98
  return runButton;
96
99
  };
97
100
 
98
- const makeEditorDiv = (listener, type) => {
101
+ const makeEditorDiv = (handler, type) => {
99
102
  const editorDiv = document.createElement("div");
100
103
  editorDiv.className = `${type}-editor-input`;
101
104
  editorDiv.setAttribute("aria-label", "Python Script Area");
102
105
 
103
- const runButton = makeRunButton(listener, type);
106
+ const runButton = makeRunButton(handler, type);
104
107
  const editorShadowContainer = document.createElement("div");
105
108
 
106
109
  // avoid outer elements intercepting key events (reveal as example)
@@ -120,15 +123,15 @@ const makeOutDiv = (type) => {
120
123
  return outDiv;
121
124
  };
122
125
 
123
- const makeBoxDiv = (listener, type) => {
126
+ const makeBoxDiv = (handler, type) => {
124
127
  const boxDiv = document.createElement("div");
125
128
  boxDiv.className = `${type}-editor-box`;
126
129
 
127
- const editorDiv = makeEditorDiv(listener, type);
130
+ const editorDiv = makeEditorDiv(handler, type);
128
131
  const outDiv = makeOutDiv(type);
129
132
  boxDiv.append(editorDiv, outDiv);
130
133
 
131
- return [boxDiv, outDiv];
134
+ return [boxDiv, outDiv, editorDiv.querySelector("button")];
132
135
  };
133
136
 
134
137
  const init = async (script, type, interpreter) => {
@@ -168,6 +171,8 @@ const init = async (script, type, interpreter) => {
168
171
  ? await fetch(script.src).then((b) => b.text())
169
172
  : script.textContent;
170
173
  const context = {
174
+ // allow the listener to be overridden at distance
175
+ handleEvent: execute,
171
176
  interpreter,
172
177
  env,
173
178
  config:
@@ -184,6 +189,29 @@ const init = async (script, type, interpreter) => {
184
189
  let target;
185
190
  defineProperties(script, {
186
191
  target: { get: () => target },
192
+ handleEvent: {
193
+ get: () => context.handleEvent,
194
+ set: (callback) => {
195
+ // do not bother with logic if it was set back as its original handler
196
+ if (callback === execute) context.handleEvent = execute;
197
+ // in every other case be sure that if the listener override returned
198
+ // `false` nothing happens, otherwise keep doing what it always did
199
+ else {
200
+ context.handleEvent = async (event) => {
201
+ // trap the currentTarget ASAP (if any)
202
+ // otherwise it gets lost asynchronously
203
+ const { currentTarget } = event;
204
+ // augment a code snapshot before invoking the override
205
+ defineProperties(event, {
206
+ code: { value: context.pySrc },
207
+ });
208
+ // avoid executing the default handler if the override returned `false`
209
+ if ((await callback(event)) !== false)
210
+ await execute.call(context, { currentTarget });
211
+ };
212
+ }
213
+ },
214
+ },
187
215
  code: {
188
216
  get: () => context.pySrc,
189
217
  set: (insert) => {
@@ -214,8 +242,8 @@ const init = async (script, type, interpreter) => {
214
242
  isSetup = wasSetup;
215
243
  source = wasSource;
216
244
  };
217
- return execute
218
- .call(context, { currentTarget: null })
245
+ return context
246
+ .handleEvent({ currentTarget: null })
219
247
  .then(restore, restore);
220
248
  },
221
249
  },
@@ -227,7 +255,7 @@ const init = async (script, type, interpreter) => {
227
255
  };
228
256
 
229
257
  if (isSetup) {
230
- await execute.call(context, { currentTarget: null });
258
+ await context.handleEvent({ currentTarget: null });
231
259
  notify();
232
260
  return;
233
261
  }
@@ -250,8 +278,7 @@ const init = async (script, type, interpreter) => {
250
278
  if (!target.hasAttribute("root")) target.setAttribute("root", target.id);
251
279
 
252
280
  // @see https://github.com/JeffersGlass/mkdocs-pyscript/blob/main/mkdocs_pyscript/js/makeblocks.js
253
- const listener = execute.bind(context);
254
- const [boxDiv, outDiv] = makeBoxDiv(listener, type);
281
+ const [boxDiv, outDiv, runButton] = makeBoxDiv(context, type);
255
282
  boxDiv.dataset.env = script.hasAttribute("env") ? env : interpreter;
256
283
 
257
284
  const inputChild = boxDiv.querySelector(`.${type}-editor-input > div`);
@@ -266,6 +293,7 @@ const init = async (script, type, interpreter) => {
266
293
  // preserve user indentation, if any
267
294
  const indentation = /^(\s+)/m.test(doc) ? RegExp.$1 : " ";
268
295
 
296
+ const listener = () => runButton.click();
269
297
  const editor = new EditorView({
270
298
  extensions: [
271
299
  indentUnit.of(indentation),
@@ -278,6 +306,8 @@ const init = async (script, type, interpreter) => {
278
306
  ]),
279
307
  basicSetup,
280
308
  ],
309
+ foldGutter: true,
310
+ gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
281
311
  parent,
282
312
  doc,
283
313
  });
@@ -38,8 +38,8 @@ from pyscript.magic_js import (
38
38
  config,
39
39
  current_target,
40
40
  document,
41
- js_modules,
42
41
  js_import,
42
+ js_modules,
43
43
  sync,
44
44
  window,
45
45
  )
@@ -19,16 +19,17 @@ def when(event_type=None, selector=None):
19
19
  """
20
20
 
21
21
  def decorator(func):
22
+
23
+ from pyscript.web.elements import Element, ElementCollection
24
+
22
25
  if isinstance(selector, str):
23
26
  elements = document.querySelectorAll(selector)
24
27
  else:
25
28
  # TODO: This is a hack that will be removed when pyscript becomes a package
26
29
  # and we can better manage the imports without circular dependencies
27
- from pyweb import pydom
28
-
29
- if isinstance(selector, pydom.Element):
30
+ if isinstance(selector, Element):
30
31
  elements = [selector._js]
31
- elif isinstance(selector, pydom.ElementCollection):
32
+ elif isinstance(selector, ElementCollection):
32
33
  elements = [el._js for el in selector]
33
34
  else:
34
35
  raise ValueError(
@@ -47,13 +48,14 @@ def when(event_type=None, selector=None):
47
48
  wrapper = func
48
49
 
49
50
  except AttributeError:
50
- # TODO: this is currently an quick hack to get micropython working but we need
51
- # to actually properly replace inspect.signature with something else
51
+ # TODO: this is very ugly hack to get micropython working because inspect.signature
52
+ # doesn't exist, but we need to actually properly replace inspect.signature.
53
+ # It may be actually better to not try any magic for now and raise the error
52
54
  def wrapper(*args, **kwargs):
53
55
  try:
54
56
  return func(*args, **kwargs)
55
57
  except TypeError as e:
56
- if "takes 0 positional arguments" in str(e):
58
+ if "takes" in str(e) and "positional arguments" in str(e):
57
59
  return func()
58
60
 
59
61
  raise
@@ -42,7 +42,10 @@ if RUNNING_IN_WORKER:
42
42
  window = polyscript.xworker.window
43
43
  document = window.document
44
44
  js.document = document
45
- js_import = window.Function("return (...$)=>Promise.all($.map($=>import($)))")()
45
+ # this is the same as js_import on main and it lands modules on main
46
+ js_import = window.Function(
47
+ "return (...urls) => Promise.all(urls.map((url) => import(url)))"
48
+ )()
46
49
  except:
47
50
  globalThis.console.debug("SharedArrayBuffer is not available")
48
51
  # in this scenario none of the utilities would work
@@ -0,0 +1,5 @@
1
+ from . import elements
2
+
3
+ # Ugly trick to hide the dom module in the web package since we want the module
4
+ # to allow querying right away.
5
+ from .dom import dom
@@ -0,0 +1,21 @@
1
+ from pyscript import document
2
+ from pyscript.web.elements import Element, ElementCollection
3
+
4
+
5
+ class PyDom:
6
+ # Add objects we want to expose to the DOM namespace since this class instance is being
7
+ # remapped as "the module" itself
8
+ ElementCollection = ElementCollection
9
+
10
+ def __init__(self):
11
+ self._js = document
12
+
13
+ self.body = Element(document.body)
14
+ self.head = Element(document.head)
15
+
16
+ def __getitem__(self, key):
17
+ elements = self._js.querySelectorAll(key)
18
+ return ElementCollection([Element(el) for el in elements])
19
+
20
+
21
+ dom = PyDom()