@pyscript/core 0.4.5 → 0.4.7
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/{codemirror-Bc1Y52-3.js → codemirror-HQuHfCf6.js} +2 -2
- package/dist/{codemirror-Bc1Y52-3.js.map → codemirror-HQuHfCf6.js.map} +1 -1
- package/dist/{codemirror_commands-DpfBW1Yg.js → codemirror_commands-Be_sxRoS.js} +2 -2
- package/dist/{codemirror_commands-DpfBW1Yg.js.map → codemirror_commands-Be_sxRoS.js.map} +1 -1
- package/dist/{codemirror_lang-python-r06KelLU.js → codemirror_lang-python-6K8_k_-l.js} +2 -2
- package/dist/{codemirror_lang-python-r06KelLU.js.map → codemirror_lang-python-6K8_k_-l.js.map} +1 -1
- package/dist/{codemirror_language-en2b9geg.js → codemirror_language-xLdmYCLC.js} +2 -2
- package/dist/{codemirror_language-en2b9geg.js.map → codemirror_language-xLdmYCLC.js.map} +1 -1
- package/dist/{codemirror_state-BCMMU3_u.js → codemirror_state-BKbyfKsm.js} +2 -2
- package/dist/{codemirror_state-BCMMU3_u.js.map → codemirror_state-BKbyfKsm.js.map} +1 -1
- package/dist/codemirror_view-DnYSj9rm.js +2 -0
- package/dist/codemirror_view-DnYSj9rm.js.map +1 -0
- package/dist/core-C-o6YPdc.js +3 -0
- package/dist/core-C-o6YPdc.js.map +1 -0
- package/dist/core.js +1 -1
- package/dist/{deprecations-manager-160Yh7XB.js → deprecations-manager-BxfxOxJY.js} +2 -2
- package/dist/{deprecations-manager-160Yh7XB.js.map → deprecations-manager-BxfxOxJY.js.map} +1 -1
- package/dist/{error-C4n1bJ-b.js → error-DJfRAeH4.js} +2 -2
- package/dist/{error-C4n1bJ-b.js.map → error-DJfRAeH4.js.map} +1 -1
- package/dist/{index-B1rGWcUY.js → index-DV62RffY.js} +2 -2
- package/dist/{index-B1rGWcUY.js.map → index-DV62RffY.js.map} +1 -1
- package/dist/py-editor-BQGYMGSZ.js +2 -0
- package/dist/py-editor-BQGYMGSZ.js.map +1 -0
- package/dist/{py-terminal-CWQX4oMb.js → py-terminal-DvbIeXzb.js} +2 -2
- package/dist/{py-terminal-CWQX4oMb.js.map → py-terminal-DvbIeXzb.js.map} +1 -1
- package/dist/toml-DiUM0_qs.js +3 -0
- package/dist/toml-DiUM0_qs.js.map +1 -0
- package/dist/xterm_addon-fit--gyF3PcZ.js.map +1 -1
- package/package.json +9 -9
- package/src/3rd-party/xterm_addon-fit.js +1 -1
- package/src/plugins/py-editor.js +36 -21
- package/src/stdlib/pyscript/__init__.py +1 -0
- package/src/stdlib/pyscript/fetch.py +94 -0
- package/src/stdlib/pyscript.js +2 -1
- package/types/stdlib/pyscript.d.ts +1 -0
- package/dist/codemirror_view-L6gkqEE1.js +0 -2
- package/dist/codemirror_view-L6gkqEE1.js.map +0 -1
- package/dist/core-CHxEUdn6.js +0 -3
- package/dist/core-CHxEUdn6.js.map +0 -1
- package/dist/py-editor-BhXwimJa.js +0 -2
- package/dist/py-editor-BhXwimJa.js.map +0 -1
- package/dist.zip +0 -0
@@ -0,0 +1,2 @@
|
|
1
|
+
import{T as e,d as t,X as r,H as n}from"./core-C-o6YPdc.js";let o=0;const s=e=>`${e}-editor-${o++}`,i=new Map,a={worker:{onReady:({runAsync:e,io:t},{sync:r})=>{t.stdout=e=>r.write(e),t.stderr=e=>r.writeErr(e),r.revoke(),r.runAsync=e}}};async function c({currentTarget:e}){const{env:t,pySrc:o,outDiv:s}=this,c=!!e;if(c&&(e.disabled=!0,s.innerHTML=""),!i.has(t)){const e=URL.createObjectURL(new Blob([""])),o=r.call(new n(null,a),e,{type:this.interpreter}),{sync:s}=o,{promise:c,resolve:l}=Promise.withResolvers();i.set(t,c),s.revoke=()=>{URL.revokeObjectURL(e),l(o)}}i.get(t).then((t=>{t.onerror=({error:e})=>{c&&(s.innerHTML+=`<span style='color:red'>${e.message||e}</span>\n`),console.error(e)};const r=()=>{c&&(e.disabled=!1)},{sync:n}=t;n.write=e=>{c&&(s.innerText+=`${e}\n`)},n.writeErr=e=>{c&&(s.innerHTML+=`<span style='color:red'>${e}</span>\n`)},n.runAsync(o).then(r,r)}))}const l=(e,t)=>{const r=document.createElement("div");r.className=`${t}-editor-input`,r.setAttribute("aria-label","Python Script Area");const n=((e,t)=>{const r=document.createElement("button");return r.className=`absolute ${t}-editor-run-button`,r.innerHTML='<svg style="height:20px;width:20px;vertical-align:-.125em;transform-origin:center;overflow:visible;color:green" viewBox="0 0 384 512" aria-hidden="true" role="img" xmlns="http://www.w3.org/2000/svg"><g transform="translate(192 256)" transform-origin="96 0"><g transform="translate(0,0) scale(1,1)"><path d="M361 215C375.3 223.8 384 239.3 384 256C384 272.7 375.3 288.2 361 296.1L73.03 472.1C58.21 482 39.66 482.4 24.52 473.9C9.377 465.4 0 449.4 0 432V80C0 62.64 9.377 46.63 24.52 38.13C39.66 29.64 58.21 29.99 73.03 39.04L361 215z" fill="currentColor" transform="translate(-192 -256)"></path></g></g></svg>',r.setAttribute("aria-label","Python Script Run Button"),r.addEventListener("click",e),r})(e,t),o=document.createElement("div");return o.addEventListener("keydown",(e=>{e.stopPropagation()})),r.append(n,o),r},u=(e,t)=>{const r=document.createElement("div");r.className=`${t}-editor-box`;const n=l(e,t),o=(e=>{const t=document.createElement("div");return t.className=`${e}-editor-output`,t.id=`${s(e)}-output`,t})(t);return r.append(n,o),[r,o]},d=async(e,r,n)=>{const[{basicSetup:o,EditorView:i},{Compartment:a},{python:l},{indentUnit:d},{keymap:m},{defaultKeymap:p}]=await Promise.all([import("./codemirror-HQuHfCf6.js"),import("./codemirror_state-BKbyfKsm.js"),import("./codemirror_lang-python-6K8_k_-l.js"),import("./codemirror_language-xLdmYCLC.js").then((function(e){return e.x})),import("./codemirror_view-DnYSj9rm.js").then((function(e){return e.q})),import("./codemirror_commands-Be_sxRoS.js")]),v=e.hasAttribute("setup"),y=`${n}-${e.getAttribute("env")||s(r)}`,h=e.src?await fetch(e.src).then((e=>e.text())):e.textContent,f={interpreter:n,env:y,get pySrc(){return v?h:C.state.doc.toString()},get outDiv(){return v?null:$}};if(v)return void c.call(f,{currentTarget:null});const g=e.getAttribute("target");let b;if(g){if(b=document.getElementById(g)||document.querySelector(g),!b)throw new Error(`Unknown target ${g}`)}else b=document.createElement(`${r}-editor`),b.style.display="block",e.after(b);b.id||(b.id=s(r)),b.hasAttribute("exec-id")||b.setAttribute("exec-id",0),b.hasAttribute("root")||b.setAttribute("root",b.id);const w=c.bind(f),[E,$]=u(w,r);E.dataset.env=e.hasAttribute("env")?y:n;const x=E.querySelector(`.${r}-editor-input > div`).attachShadow({mode:"open"});x.innerHTML="<style> :host { all: initial; }</style>",b.appendChild(E);const A=t(e.textContent).trim(),L=/^(\s+)/m.test(A)?RegExp.$1:" ",C=new i({extensions:[d.of(L),(new a).of(l()),m.of([...p,{key:"Ctrl-Enter",run:w,preventDefault:!0},{key:"Cmd-Enter",run:w,preventDefault:!0},{key:"Shift-Enter",run:w,preventDefault:!0}]),o],parent:x,doc:A});C.focus()};let m=0,p=Promise.resolve();const v=()=>{m=0,y()},y=async()=>{if(!m){m=setTimeout(v,250);for(const[t,r]of e){const e=`script[type="${t}-editor"]`;for(const n of document.querySelectorAll(e))n.type+="-active",p=p.then((()=>d(n,t,r)))}return p}};new MutationObserver(y).observe(document,{childList:!0,subtree:!0});var h=y();export{h as default};
|
2
|
+
//# sourceMappingURL=py-editor-BQGYMGSZ.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"py-editor-BQGYMGSZ.js","sources":["../src/plugins/py-editor.js"],"sourcesContent":["// PyScript py-editor plugin\nimport { Hook, XWorker, dedent } from \"polyscript/exports\";\nimport { TYPES } from \"../core.js\";\n\nconst RUN_BUTTON = `<svg style=\"height:20px;width:20px;vertical-align:-.125em;transform-origin:center;overflow:visible;color:green\" viewBox=\"0 0 384 512\" aria-hidden=\"true\" role=\"img\" xmlns=\"http://www.w3.org/2000/svg\"><g transform=\"translate(192 256)\" transform-origin=\"96 0\"><g transform=\"translate(0,0) scale(1,1)\"><path d=\"M361 215C375.3 223.8 384 239.3 384 256C384 272.7 375.3 288.2 361 296.1L73.03 472.1C58.21 482 39.66 482.4 24.52 473.9C9.377 465.4 0 449.4 0 432V80C0 62.64 9.377 46.63 24.52 38.13C39.66 29.64 58.21 29.99 73.03 39.04L361 215z\" fill=\"currentColor\" transform=\"translate(-192 -256)\"></path></g></g></svg>`;\n\nlet id = 0;\nconst getID = (type) => `${type}-editor-${id++}`;\n\nconst envs = new Map();\n\nconst hooks = {\n worker: {\n // works on both Pyodide and MicroPython\n onReady: ({ runAsync, io }, { sync }) => {\n io.stdout = (line) => sync.write(line);\n io.stderr = (line) => sync.writeErr(line);\n sync.revoke();\n sync.runAsync = runAsync;\n },\n },\n};\n\nasync function execute({ currentTarget }) {\n const { env, pySrc, outDiv } = this;\n 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 xworker = XWorker.call(new Hook(null, hooks), srcLink, {\n type: this.interpreter,\n });\n\n const { sync } = xworker;\n const { promise, resolve } = Promise.withResolvers();\n envs.set(env, promise);\n sync.revoke = () => {\n URL.revokeObjectURL(srcLink);\n resolve(xworker);\n };\n }\n\n // wait for the env then set the target div\n // before executing the current code\n envs.get(env).then((xworker) => {\n xworker.onerror = ({ error }) => {\n if (hasRunButton) {\n outDiv.innerHTML += `<span style='color:red'>${\n error.message || error\n }</span>\\n`;\n }\n console.error(error);\n };\n\n const enable = () => {\n if (hasRunButton) currentTarget.disabled = false;\n };\n const { sync } = xworker;\n sync.write = (str) => {\n if (hasRunButton) outDiv.innerText += `${str}\\n`;\n };\n sync.writeErr = (str) => {\n if (hasRunButton) {\n outDiv.innerHTML += `<span style='color:red'>${str}</span>\\n`;\n }\n };\n sync.runAsync(pySrc).then(enable, enable);\n });\n}\n\nconst makeRunButton = (listener, type) => {\n const runButton = document.createElement(\"button\");\n runButton.className = `absolute ${type}-editor-run-button`;\n runButton.innerHTML = RUN_BUTTON;\n runButton.setAttribute(\"aria-label\", \"Python Script Run Button\");\n runButton.addEventListener(\"click\", listener);\n return runButton;\n};\n\nconst makeEditorDiv = (listener, type) => {\n const editorDiv = document.createElement(\"div\");\n editorDiv.className = `${type}-editor-input`;\n editorDiv.setAttribute(\"aria-label\", \"Python Script Area\");\n\n const runButton = makeRunButton(listener, type);\n const editorShadowContainer = document.createElement(\"div\");\n\n // avoid outer elements intercepting key events (reveal as example)\n editorShadowContainer.addEventListener(\"keydown\", (event) => {\n event.stopPropagation();\n });\n\n editorDiv.append(runButton, editorShadowContainer);\n\n return editorDiv;\n};\n\nconst makeOutDiv = (type) => {\n const outDiv = document.createElement(\"div\");\n outDiv.className = `${type}-editor-output`;\n outDiv.id = `${getID(type)}-output`;\n return outDiv;\n};\n\nconst makeBoxDiv = (listener, type) => {\n const boxDiv = document.createElement(\"div\");\n boxDiv.className = `${type}-editor-box`;\n\n const editorDiv = makeEditorDiv(listener, type);\n const outDiv = makeOutDiv(type);\n boxDiv.append(editorDiv, outDiv);\n\n return [boxDiv, outDiv];\n};\n\nconst init = async (script, type, interpreter) => {\n const [\n { basicSetup, EditorView },\n { Compartment },\n { python },\n { indentUnit },\n { keymap },\n { defaultKeymap },\n ] = await Promise.all([\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror_state.js\"),\n import(\n /* webpackIgnore: true */ \"../3rd-party/codemirror_lang-python.js\"\n ),\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror_language.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror_view.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror_commands.js\"),\n ]);\n\n const isSetup = script.hasAttribute(\"setup\");\n const env = `${interpreter}-${script.getAttribute(\"env\") || getID(type)}`;\n const source = script.src\n ? await fetch(script.src).then((b) => b.text())\n : script.textContent;\n const context = {\n interpreter,\n env,\n get pySrc() {\n return isSetup ? source : editor.state.doc.toString();\n },\n get outDiv() {\n return isSetup ? null : outDiv;\n },\n };\n\n if (isSetup) {\n execute.call(context, { currentTarget: null });\n return;\n }\n\n const selector = script.getAttribute(\"target\");\n\n let target;\n if (selector) {\n target =\n document.getElementById(selector) ||\n document.querySelector(selector);\n if (!target) throw new Error(`Unknown target ${selector}`);\n } else {\n target = document.createElement(`${type}-editor`);\n target.style.display = \"block\";\n script.after(target);\n }\n\n if (!target.id) target.id = getID(type);\n if (!target.hasAttribute(\"exec-id\")) target.setAttribute(\"exec-id\", 0);\n if (!target.hasAttribute(\"root\")) target.setAttribute(\"root\", target.id);\n\n // @see https://github.com/JeffersGlass/mkdocs-pyscript/blob/main/mkdocs_pyscript/js/makeblocks.js\n const listener = execute.bind(context);\n const [boxDiv, outDiv] = makeBoxDiv(listener, type);\n boxDiv.dataset.env = script.hasAttribute(\"env\") ? env : interpreter;\n\n const inputChild = boxDiv.querySelector(`.${type}-editor-input > div`);\n const parent = inputChild.attachShadow({ mode: \"open\" });\n // avoid inheriting styles from the outer component\n parent.innerHTML = `<style> :host { all: initial; }</style>`;\n\n target.appendChild(boxDiv);\n\n const doc = dedent(script.textContent).trim();\n\n // preserve user indentation, if any\n const indentation = /^(\\s+)/m.test(doc) ? RegExp.$1 : \" \";\n\n const editor = new EditorView({\n extensions: [\n indentUnit.of(indentation),\n new Compartment().of(python()),\n keymap.of([\n ...defaultKeymap,\n { key: \"Ctrl-Enter\", run: listener, preventDefault: true },\n { key: \"Cmd-Enter\", run: listener, preventDefault: true },\n { key: \"Shift-Enter\", run: listener, preventDefault: true },\n ]),\n basicSetup,\n ],\n parent,\n doc,\n });\n\n editor.focus();\n};\n\n// avoid too greedy MutationObserver operations at distance\nlet timeout = 0;\n\n// avoid delayed initialization\nlet queue = Promise.resolve();\n\n// reset interval value then check for new scripts\nconst resetTimeout = () => {\n timeout = 0;\n pyEditor();\n};\n\n// triggered both ASAP on the living DOM and via MutationObserver later\nconst pyEditor = async () => {\n if (timeout) return;\n timeout = setTimeout(resetTimeout, 250);\n for (const [type, interpreter] of TYPES) {\n const selector = `script[type=\"${type}-editor\"]`;\n for (const script of document.querySelectorAll(selector)) {\n // avoid any further bootstrap 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","hooks","worker","onReady","runAsync","io","sync","stdout","line","write","stderr","writeErr","revoke","async","execute","currentTarget","env","pySrc","outDiv","this","hasRunButton","disabled","innerHTML","has","srcLink","URL","createObjectURL","Blob","xworker","XWorker","call","Hook","interpreter","promise","resolve","Promise","withResolvers","set","revokeObjectURL","get","then","onerror","error","message","console","enable","str","innerText","makeEditorDiv","listener","editorDiv","document","createElement","className","setAttribute","runButton","addEventListener","makeRunButton","editorShadowContainer","event","stopPropagation","append","makeBoxDiv","boxDiv","makeOutDiv","init","script","basicSetup","EditorView","Compartment","python","indentUnit","keymap","defaultKeymap","all","import","n","x","q","isSetup","hasAttribute","getAttribute","source","src","fetch","b","text","textContent","context","editor","state","doc","toString","selector","target","getElementById","querySelector","Error","style","display","after","bind","dataset","parent","attachShadow","mode","appendChild","dedent","trim","indentation","test","RegExp","$1","extensions","of","key","run","preventDefault","focus","timeout","queue","resetTimeout","pyEditor","setTimeout","TYPES","querySelectorAll","MutationObserver","observe","childList","subtree","pyEditor$1"],"mappings":"4DAMA,IAAIA,EAAK,EACT,MAAMC,EAASC,GAAS,GAAGA,YAAeF,MAEpCG,EAAO,IAAIC,IAEXC,EAAQ,CACVC,OAAQ,CAEJC,QAAS,EAAGC,WAAUC,OAAQC,WAC1BD,EAAGE,OAAUC,GAASF,EAAKG,MAAMD,GACjCH,EAAGK,OAAUF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,EAIlB,IAAIC,EAAU,EAGVC,EAAQrF,QAAQD,UAGpB,MAAMuF,EAAe,KACjBF,EAAU,EACVG,GAAU,EAIRA,EAAW7G,UACb,IAAI0G,EAAJ,CACAA,EAAUI,WAAWF,EAAc,KACnC,IAAK,MAAO3H,EAAMkC,KAAgB4F,EAAO,CACrC,MAAM/B,EAAW,gBAAgB/F,aACjC,IAAK,MAAMoE,KAAUf,SAAS0E,iBAAiBhC,GAE3C3B,EAAOpE,MAAQ,UAGf0H,EAAQA,EAAMhF,MAAK,IAAMyB,EAAKC,EAAQpE,EAAMkC,IAEnD,CACD,OAAOwF,CAZa,CAYR,EAGhB,IAAIM,iBAAiBJ,GAAUK,QAAQ5E,SAAU,CAC7C6E,WAAW,EACXC,SAAS,IAIb,IAAAC,EAAeR"}
|
@@ -1,2 +1,2 @@
|
|
1
|
-
import{T as e,e as t,a as r}from"./core-
|
2
|
-
//# sourceMappingURL=py-terminal-
|
1
|
+
import{T as e,e as t,a as r}from"./core-C-o6YPdc.js";import{notify as n}from"./error-DJfRAeH4.js";const i=[...e.keys()].map((e=>`script[type="${e}"][terminal],${e}-script[terminal]`)).join(","),a=e=>{throw n(e),new Error(e)},o=e=>!l.has(e),s=({attributes:{worker:e}})=>!e,l=new WeakSet;let d=!0;const m=({interpreter:e,io:t,run:r},{sync:n})=>{if(!n.is_pyterminal())return;r("from polyscript.currentScript import terminal as __terminal__");const i=new TextDecoder;let a="";const o={isatty:!0,write:e=>(a=i.decode(e),n.pyterminal_write(a),e.length)};e.setStdout(o),e.setStderr(o),e.setStdin({isatty:!0,stdin:()=>n.pyterminal_read(a)}),t.stderr=e=>{n.pyterminal_write(`${e.message||e}\n`)}},c=async()=>{const e=document.querySelectorAll(i),n=[].filter.call(e,o);if(!n.length)return;n.forEach(l.add,l),[].filter.call(e,s).length>1&&a("You can use at most 1 main terminal"),d&&(d=!1,document.head.append(Object.assign(document.createElement("link"),{rel:"stylesheet",href:new URL("./xterm.css",import.meta.url)})));const[{Terminal:c},{Readline:p},{FitAddon:y}]=await Promise.all([import("./xterm-DqawCVsv.js"),import("./xterm-readline-D247p8vq.js"),import("./xterm_addon-fit--gyF3PcZ.js")]);for(const e of n){e.matches('script[type="mpy"],mpy-script')&&a("Unsupported terminal.");const n=new p,i=t=>{let i=e;const a=e.getAttribute("target");if(a){if(i=document.getElementById(a)||document.querySelector(a),!i)throw new Error(`Unknown target ${a}`)}else i=document.createElement("py-terminal"),i.style.display="block",e.after(i);const o=new c({theme:{background:"#191A19",foreground:"#F5F2E7"},...t}),s=new y;return o.loadAddon(s),o.loadAddon(n),o.open(i),s.fit(),o.focus(),r(e,"terminal",{value:o}),o};e.hasAttribute("worker")?(t.main.onWorker.add((function e(r,a){l.has(a)||(l.add(a),t.main.onWorker.delete(e),i({disableStdin:!1,cursorBlink:!0,cursorStyle:"block"}),a.sync.is_pyterminal=()=>!0,a.sync.pyterminal_read=n.read.bind(n),a.sync.pyterminal_write=n.write.bind(n))})),t.worker.onReady.add(m)):t.main.onReady.add((function e({interpreter:r,io:a,run:o}){console.warn("py-terminal is read only on main thread"),t.main.onReady.delete(e),globalThis.__py_terminal__=i({disableStdin:!0,cursorBlink:!1,cursorStyle:"underline"}),o("from js import __py_terminal__ as __terminal__"),delete globalThis.__py_terminal__;const s=new TextDecoder;let l="";const d={isatty:!0,write:e=>(l=s.decode(e),n.write(l),e.length)};r.setStdout(d),r.setStderr(d),r.setStdin({isatty:!0,stdin:()=>n.read(l)}),a.stderr=e=>{n.write(`${e.message||e}\n`)}}))}};new MutationObserver(c).observe(document,{childList:!0,subtree:!0});var p=c();export{p as default};
|
2
|
+
//# sourceMappingURL=py-terminal-DvbIeXzb.js.map
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"py-terminal-CWQX4oMb.js","sources":["../src/plugins/py-terminal.js"],"sourcesContent":["// PyScript py-terminal plugin\nimport { TYPES, hooks } from \"../core.js\";\nimport { notify } from \"./error.js\";\nimport { defineProperty } from \"polyscript/exports\";\n\nconst SELECTOR = [...TYPES.keys()]\n .map((type) => `script[type=\"${type}\"][terminal],${type}-script[terminal]`)\n .join(\",\");\n\n// show the error on main and\n// stops the module from keep executing\nconst notifyAndThrow = (message) => {\n notify(message);\n throw new Error(message);\n};\n\nconst notParsedYet = (script) => !bootstrapped.has(script);\n\nconst onceOnMain = ({ attributes: { worker } }) => !worker;\n\nconst bootstrapped = new WeakSet();\n\nlet addStyle = true;\n\n// this callback will be serialized as string and it never needs\n// to be invoked multiple times. Each xworker here is bootstrapped\n// only once thanks to the `sync.is_pyterminal()` check.\nconst workerReady = ({ interpreter, io, run }, { sync }) => {\n if (!sync.is_pyterminal()) return;\n\n // in workers it's always safe to grab the polyscript currentScript\n run(\"from polyscript.currentScript import terminal as __terminal__\");\n\n // This part is inevitably duplicated as external scope\n // can't be reached by workers out of the box.\n // The detail is that here we use sync though, not readline.\n const decoder = new TextDecoder();\n let data = \"\";\n const generic = {\n isatty: true,\n write(buffer) {\n data = decoder.decode(buffer);\n sync.pyterminal_write(data);\n return buffer.length;\n },\n };\n interpreter.setStdout(generic);\n interpreter.setStderr(generic);\n interpreter.setStdin({\n isatty: true,\n stdin: () => sync.pyterminal_read(data),\n });\n\n io.stderr = (error) => {\n sync.pyterminal_write(`${error.message || error}\\n`);\n };\n};\n\nconst pyTerminal = async () => {\n const terminals = document.querySelectorAll(SELECTOR);\n\n const unknown = [].filter.call(terminals, notParsedYet);\n\n // no results will look further for runtime nodes\n if (!unknown.length) return;\n // early flag elements as known to avoid concurrent\n // MutationObserver invokes of this async handler\n else unknown.forEach(bootstrapped.add, bootstrapped);\n\n // we currently support only one terminal as in \"classic\"\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 // lazy load these only when a valid terminal is found\n const [{ Terminal }, { Readline }, { FitAddon }] = await Promise.all([\n import(/* webpackIgnore: true */ \"../3rd-party/xterm.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/xterm-readline.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/xterm_addon-fit.js\"),\n ]);\n\n for (const element of unknown) {\n // hopefully to be removed in the near future!\n if (element.matches('script[type=\"mpy\"],mpy-script'))\n notifyAndThrow(\"Unsupported terminal.\");\n\n const readline = new Readline();\n\n // common main thread initialization for both worker\n // or main case, bootstrapping the terminal on its target\n const init = (options) => {\n let target = element;\n const selector = element.getAttribute(\"target\");\n if (selector) {\n target =\n document.getElementById(selector) ||\n document.querySelector(selector);\n if (!target) throw new Error(`Unknown target ${selector}`);\n } else {\n target = document.createElement(\"py-terminal\");\n target.style.display = \"block\";\n element.after(target);\n }\n const terminal = new Terminal({\n theme: {\n background: \"#191A19\",\n foreground: \"#F5F2E7\",\n },\n ...options,\n });\n const fitAddon = new FitAddon();\n terminal.loadAddon(fitAddon);\n terminal.loadAddon(readline);\n terminal.open(target);\n fitAddon.fit();\n terminal.focus();\n defineProperty(element, \"terminal\", { value: terminal });\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 }) {\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 // This part is inevitably duplicated as external scope\n // can't be reached by workers out of the box.\n // The detail is that here we use readline here, not sync.\n const decoder = new TextDecoder();\n let data = \"\";\n const generic = {\n isatty: true,\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: true,\n stdin: () => readline.read(data),\n });\n\n io.stderr = (error) => {\n readline.write(`${error.message || error}\\n`);\n };\n });\n }\n }\n};\n\nconst mo = new MutationObserver(pyTerminal);\nmo.observe(document, { childList: true, subtree: true });\n\n// try to check the current document ASAP\nexport default pyTerminal();\n"],"names":["SELECTOR","TYPES","keys","map","type","join","notifyAndThrow","message","notify","Error","notParsedYet","script","bootstrapped","has","onceOnMain","attributes","worker","WeakSet","addStyle","workerReady","interpreter","io","run","sync","is_pyterminal","decoder","TextDecoder","data","generic","isatty","write","buffer","decode","pyterminal_write","length","setStdout","setStderr","setStdin","stdin","pyterminal_read","stderr","error","pyTerminal","async","terminals","document","querySelectorAll","unknown","filter","call","forEach","add","head","append","Object","assign","createElement","rel","href","URL","url","Terminal","Readline","FitAddon","Promise","all","import","element","matches","readline","init","options","target","selector","getAttribute","getElementById","querySelector","style","display","after","terminal","theme","background","foreground","fitAddon","loadAddon","open","fit","focus","defineProperty","value","hasAttribute","hooks","main","onWorker","_","xworker","delete","disableStdin","cursorBlink","cursorStyle","read","bind","onReady","console","warn","globalThis","__py_terminal__","MutationObserver","observe","childList","subtree","pyTerminal$1"],"mappings":"kGAKA,MAAMA,EAAW,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B9E,EAAI,yDACGoF,WAAWC,gBAKlB,MAAMlF,EAAU,IAAIC,YACpB,IAAIC,EAAO,GACX,MAAMC,EAAU,CACZC,QAAQ,EACRC,MAAMC,IACFJ,EAAOF,EAAQO,OAAOD,GACtBsC,EAASvC,MAAMH,GACRI,EAAOG,SAGtBd,EAAYe,UAAUP,GACtBR,EAAYgB,UAAUR,GACtBR,EAAYiB,SAAS,CACjBR,QAAQ,EACRS,MAAO,IAAM+B,EAASgC,KAAK1E,KAG/BN,EAAGmB,OAAUC,IACT4B,EAASvC,MAAM,GAAGW,EAAMlC,SAAWkC,MAAU,CAEjE,GAEK,GAGM,IAAImE,iBAAiBlE,GAC7BmE,QAAQhE,SAAU,CAAEiE,WAAW,EAAMC,SAAS,IAGjD,IAAAC,EAAetE"}
|
1
|
+
{"version":3,"file":"py-terminal-DvbIeXzb.js","sources":["../src/plugins/py-terminal.js"],"sourcesContent":["// PyScript py-terminal plugin\nimport { TYPES, hooks } from \"../core.js\";\nimport { notify } from \"./error.js\";\nimport { defineProperty } from \"polyscript/exports\";\n\nconst SELECTOR = [...TYPES.keys()]\n .map((type) => `script[type=\"${type}\"][terminal],${type}-script[terminal]`)\n .join(\",\");\n\n// show the error on main and\n// stops the module from keep executing\nconst notifyAndThrow = (message) => {\n notify(message);\n throw new Error(message);\n};\n\nconst notParsedYet = (script) => !bootstrapped.has(script);\n\nconst onceOnMain = ({ attributes: { worker } }) => !worker;\n\nconst bootstrapped = new WeakSet();\n\nlet addStyle = true;\n\n// this callback will be serialized as string and it never needs\n// to be invoked multiple times. Each xworker here is bootstrapped\n// only once thanks to the `sync.is_pyterminal()` check.\nconst workerReady = ({ interpreter, io, run }, { sync }) => {\n if (!sync.is_pyterminal()) return;\n\n // in workers it's always safe to grab the polyscript currentScript\n run(\"from polyscript.currentScript import terminal as __terminal__\");\n\n // This part is inevitably duplicated as external scope\n // can't be reached by workers out of the box.\n // The detail is that here we use sync though, not readline.\n const decoder = new TextDecoder();\n let data = \"\";\n const generic = {\n isatty: true,\n write(buffer) {\n data = decoder.decode(buffer);\n sync.pyterminal_write(data);\n return buffer.length;\n },\n };\n interpreter.setStdout(generic);\n interpreter.setStderr(generic);\n interpreter.setStdin({\n isatty: true,\n stdin: () => sync.pyterminal_read(data),\n });\n\n io.stderr = (error) => {\n sync.pyterminal_write(`${error.message || error}\\n`);\n };\n};\n\nconst pyTerminal = async () => {\n const terminals = document.querySelectorAll(SELECTOR);\n\n const unknown = [].filter.call(terminals, notParsedYet);\n\n // no results will look further for runtime nodes\n if (!unknown.length) return;\n // early flag elements as known to avoid concurrent\n // MutationObserver invokes of this async handler\n else unknown.forEach(bootstrapped.add, bootstrapped);\n\n // we currently support only one terminal as in \"classic\"\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 // lazy load these only when a valid terminal is found\n const [{ Terminal }, { Readline }, { FitAddon }] = await Promise.all([\n import(/* webpackIgnore: true */ \"../3rd-party/xterm.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/xterm-readline.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/xterm_addon-fit.js\"),\n ]);\n\n for (const element of unknown) {\n // hopefully to be removed in the near future!\n if (element.matches('script[type=\"mpy\"],mpy-script'))\n notifyAndThrow(\"Unsupported terminal.\");\n\n const readline = new Readline();\n\n // common main thread initialization for both worker\n // or main case, bootstrapping the terminal on its target\n const init = (options) => {\n let target = element;\n const selector = element.getAttribute(\"target\");\n if (selector) {\n target =\n document.getElementById(selector) ||\n document.querySelector(selector);\n if (!target) throw new Error(`Unknown target ${selector}`);\n } else {\n target = document.createElement(\"py-terminal\");\n target.style.display = \"block\";\n element.after(target);\n }\n const terminal = new Terminal({\n theme: {\n background: \"#191A19\",\n foreground: \"#F5F2E7\",\n },\n ...options,\n });\n const fitAddon = new FitAddon();\n terminal.loadAddon(fitAddon);\n terminal.loadAddon(readline);\n terminal.open(target);\n fitAddon.fit();\n terminal.focus();\n defineProperty(element, \"terminal\", { value: terminal });\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 }) {\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 // This part is inevitably duplicated as external scope\n // can't be reached by workers out of the box.\n // The detail is that here we use readline here, not sync.\n const decoder = new TextDecoder();\n let data = \"\";\n const generic = {\n isatty: true,\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: true,\n stdin: () => readline.read(data),\n });\n\n io.stderr = (error) => {\n readline.write(`${error.message || error}\\n`);\n };\n });\n }\n }\n};\n\nconst mo = new MutationObserver(pyTerminal);\nmo.observe(document, { childList: true, subtree: true });\n\n// try to check the current document ASAP\nexport default pyTerminal();\n"],"names":["SELECTOR","TYPES","keys","map","type","join","notifyAndThrow","message","notify","Error","notParsedYet","script","bootstrapped","has","onceOnMain","attributes","worker","WeakSet","addStyle","workerReady","interpreter","io","run","sync","is_pyterminal","decoder","TextDecoder","data","generic","isatty","write","buffer","decode","pyterminal_write","length","setStdout","setStderr","setStdin","stdin","pyterminal_read","stderr","error","pyTerminal","async","terminals","document","querySelectorAll","unknown","filter","call","forEach","add","head","append","Object","assign","createElement","rel","href","URL","url","Terminal","Readline","FitAddon","Promise","all","import","element","matches","readline","init","options","target","selector","getAttribute","getElementById","querySelector","style","display","after","terminal","theme","background","foreground","fitAddon","loadAddon","open","fit","focus","defineProperty","value","hasAttribute","hooks","main","onWorker","_","xworker","delete","disableStdin","cursorBlink","cursorStyle","read","bind","onReady","console","warn","globalThis","__py_terminal__","MutationObserver","observe","childList","subtree","pyTerminal$1"],"mappings":"kGAKA,MAAMA,EAAW,IAAIC,EAAMC,QACtBC,KAAKC,GAAS,gBAAgBA,iBAAoBA,uBAClDC,KAAK,KAIJC,EAAkBC,IAEpB,MADAC,EAAOD,GACD,IAAIE,MAAMF,EAAQ,EAGtBG,EAAgBC,IAAYC,EAAaC,IAAIF,GAE7CG,EAAa,EAAGC,YAAcC,cAAgBA,EAE9CJ,EAAe,IAAIK,QAEzB,IAAIC,GAAW,EAKf,MAAMC,EAAc,EAAGC,cAAaC,KAAIC,QAASC,WAC7C,IAAKA,EAAKC,gBAAiB,OAG3BF,EAAI,iEAKJ,MAAMG,EAAU,IAAIC,YACpB,IAAIC,EAAO,GACX,MAAMC,EAAU,CACZC,QAAQ,EACRC,MAAMC,IACFJ,EAAOF,EAAQO,OAAOD,GACtBR,EAAKU,iBAAiBN,GACfI,EAAOG,SAGtBd,EAAYe,UAAUP,GACtBR,EAAYgB,UAAUR,GACtBR,EAAYiB,SAAS,CAC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=Array,{parse:r}=JSON,s=(e,{s:r})=>e.replace(/"s(\d+)"/g,((e,s)=>r[s])),t=(e,s)=>r(e.replace(/(\S+?)\s*=/g,'"$1":'),((e,r)=>"string"==typeof r?s[r[0]][r.slice(1)]:r)),p=(r,t,p,l)=>{for(let n=0,{length:a}=r,c=a-1;n<a;n++){const a=s(r[n],t);p=p[a]||(p[a]=l&&n===c?[]:{}),e(p)&&(n!==c&&p.length||p.push({}),p=p.at(-1))}return p},l=e=>{const[r,l]=((e,r,s)=>[e.replace(/(["'])(?:(?=(\\?))\2.)*?\1/g,(e=>`"s${r.push(e.slice(1,-1))-1}"`)).replace(/\d{2,}([:-]\d{2}){2}([ T:-][\dZ:-]+)?/g,(e=>`"d${s.push(new Date(e))-1}"`)).replace(/,\s*[\r\n]+/g,", ").replace(/\[\s*[\r\n]+/g,"[").replace(/[\r\n]+\s*]/g,"]"),{s:r,d:s}])(e,[],[]),n={};let a=n;for(let e of r.split(/[\r\n]+/))if((e=e.trim())&&!e.startsWith("#"))if(/^(\[+)(.*?)\]+/.test(e))a=p(RegExp.$2.trim().split("."),l,n,"["!==RegExp.$1);else if(/^(\S+?)\s*=([^#]+)/.test(e)){const{$1:e,$2:r}=RegExp;a[s(e,l)]=t(r.trim(),l)}return n};export{l as parse};
|
3
|
+
//# sourceMappingURL=toml-DiUM0_qs.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"toml-DiUM0_qs.js","sources":["../node_modules/polyscript/esm/3rd-party/toml.js"],"sourcesContent":["/* c8 ignore start */\n/*! (c) Andrea Giammarchi - ISC */\n\nconst {isArray} = Array;\nconst {parse: jsonParse} = JSON;\n\n/** @typedef {{s: string[], d: Date[]}} Foreign foreign strings and dates */\n\n/**\n * Transform quoted keys into regular keys.\n * @param {string} str the key to eventually normalize\n * @param {Foreign} foreign foreign strings and dates\n * @returns \n */\nconst getKey = (str, {s}) => str.replace(/\"s(\\d+)\"/g, (_, $1) => s[$1]);\n\n/**\n * Given a `'string'` or a `\"string\"` returns a JSON compatible string.\n * @param {string} str a TOML entry to parse\n * @param {Foreign} foreign foreign strings and dates\n * @returns {string}\n */\nconst getValue = (str, foreign) => jsonParse(\n str.replace(/(\\S+?)\\s*=/g, '\"$1\":'),\n (_, value) => typeof value === 'string' ?\n foreign[value[0]][value.slice(1)] :\n value\n);\n\n/**\n * Crawl the `json` object via the given array of keys and handle array entries.\n * @param {string[]} keys a path with all keys to reach the entry\n * @param {Foreign} foreign foreign strings and dates\n * @param {object} entry the root entry of the TOML\n * @param {boolean} asArray handle array entries\n * @returns {object} the current entry to handle\n */\nconst getPath = (keys, foreign, entry, asArray) => {\n for (let i = 0, {length} = keys, last = length - 1; i < length; i++) {\n const key = getKey(keys[i], foreign);\n entry = entry[key] || (entry[key] = (asArray && (i === last) ? [] : {}));\n if (isArray(entry)) {\n if ((i === last) || !entry.length)\n entry.push({});\n entry = entry.at(-1);\n }\n }\n return entry;\n};\n\n/**\n * Given a TOML text, removes stirngs and dates for easier parsing +\n * remove multi-line arrays to not need evaluation.\n * @param {string} toml the TOML text to map\n * @param {string[]} strings mapped strings\n * @param {Date[]} dates mapped Dates\n * @returns {[string, Foreign]}\n */\nconst mapForeign = (toml, strings, dates) => [\n toml\n // map strings in the TOML\n .replace(\n /([\"'])(?:(?=(\\\\?))\\2.)*?\\1/g,\n value => `\"s${strings.push(value.slice(1, -1)) - 1}\"`\n )\n // map dates in the TOML\n .replace(\n /\\d{2,}([:-]\\d{2}){2}([ T:-][\\dZ:-]+)?/g,\n value => `\"d${dates.push(new Date(value)) - 1}\"`\n )\n // avoid multi-line array entries\n .replace(/,\\s*[\\r\\n]+/g, ', ')\n .replace(/\\[\\s*[\\r\\n]+/g, '[')\n .replace(/[\\r\\n]+\\s*]/g, ']'),\n {s: strings, d: dates}\n];\n\n/**\n * Given a simple subset of a TOML file, returns its JS equivalent.\n * @param {string} toml the TOML text to parse\n * @returns {object} the TOML equivalent as JSON serializable\n */\nconst parse = toml => {\n const [text, foreign] = mapForeign(toml, [], []);\n const json = {};\n let entry = json;\n for (let line of text.split(/[\\r\\n]+/)) {\n if ((line = line.trim()) && !line.startsWith('#')) {\n if (/^(\\[+)(.*?)\\]+/.test(line))\n entry = getPath(RegExp.$2.trim().split('.'), foreign, json, RegExp.$1 !== '[');\n else if (/^(\\S+?)\\s*=([^#]+)/.test(line)) {\n const {$1: key, $2: value} = RegExp;\n entry[getKey(key, foreign)] = getValue(value.trim(), foreign);\n }\n }\n }\n return json;\n};\n\nexport { parse };\n\n/* c8 ignore stop */\n"],"names":["isArray","Array","parse","jsonParse","JSON","getKey","str","s","replace","_","$1","getValue","foreign","value","slice","getPath","keys","entry","asArray","i","length","last","key","push","at","toml","text","strings","dates","Date","d","mapForeign","json","line","split","trim","startsWith","test","RegExp","$2"],"mappings":";AAGA,MAAMA,QAACA,GAAWC,OACXC,MAAOC,GAAaC,KAUrBC,EAAS,CAACC,GAAMC,OAAOD,EAAIE,QAAQ,aAAa,CAACC,EAAGC,IAAOH,EAAEG,KAQ7DC,EAAW,CAACL,EAAKM,IAAYT,EACjCG,EAAIE,QAAQ,cAAe,UAC3B,CAACC,EAAGI,IAA2B,iBAAVA,EACnBD,EAAQC,EAAM,IAAIA,EAAMC,MAAM,IAC9BD,IAWEE,EAAU,CAACC,EAAMJ,EAASK,EAAOC,KACrC,IAAK,IAAIC,EAAI,GAAGC,OAACA,GAAUJ,EAAMK,EAAOD,EAAS,EAAGD,EAAIC,EAAQD,IAAK,CACnE,MAAMG,EAAMjB,EAAOW,EAAKG,GAAIP,GAC5BK,EAAQA,EAAMK,KAASL,EAAMK,GAAQJ,GAAYC,IAAME,EAAQ,GAAK,CAAA,GAChErB,EAAQiB,KACLE,IAAME,GAAUJ,EAAMG,QACzBH,EAAMM,KAAK,CAAA,GACbN,EAAQA,EAAMO,IAAI,GAErB,CACD,OAAOP,CAAK,EAmCRf,EAAQuB,IACZ,MAAOC,EAAMd,GAzBI,EAACa,EAAME,EAASC,IAAU,CAC3CH,EAEGjB,QACC,+BACAK,GAAS,KAAKc,EAAQJ,KAAKV,EAAMC,MAAM,GAAI,IAAM,OAGlDN,QACC,0CACAK,GAAS,KAAKe,EAAML,KAAK,IAAIM,KAAKhB,IAAU,OAG7CL,QAAQ,eAAgB,MACxBA,QAAQ,gBAAiB,KACzBA,QAAQ,eAAgB,KAC3B,CAACD,EAAGoB,EAASG,EAAGF,IASQG,CAAWN,EAAM,GAAI,IACvCO,EAAO,CAAA,EACb,IAAIf,EAAQe,EACZ,IAAK,IAAIC,KAAQP,EAAKQ,MAAM,WAC1B,IAAKD,EAAOA,EAAKE,UAAYF,EAAKG,WAAW,KAC3C,GAAI,iBAAiBC,KAAKJ,GACxBhB,EAAQF,EAAQuB,OAAOC,GAAGJ,OAAOD,MAAM,KAAMtB,EAASoB,EAAoB,MAAdM,OAAO5B,SAChE,GAAI,qBAAqB2B,KAAKJ,GAAO,CACxC,MAAOvB,GAAIY,EAAKiB,GAAI1B,GAASyB,OAC7BrB,EAAMZ,EAAOiB,EAAKV,IAAYD,EAASE,EAAMsB,OAAQvB,EACtD,CAGL,OAAOoB,CAAI","x_google_ignoreList":[0]}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"xterm_addon-fit--gyF3PcZ.js","sources":["../src/3rd-party/xterm_addon-fit.js"],"sourcesContent":["/**\n * Bundled by jsDelivr using Rollup v2.79.1 and Terser v5.19.2.\n * Original file: /npm/@xterm/addon-fit@0.9.0
|
1
|
+
{"version":3,"file":"xterm_addon-fit--gyF3PcZ.js","sources":["../src/3rd-party/xterm_addon-fit.js"],"sourcesContent":["/**\n * Bundled by jsDelivr using Rollup v2.79.1 and Terser v5.19.2.\n * Original file: /npm/@xterm/addon-fit@0.9.0/lib/addon-fit.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\nvar e,t,r={exports:{}};self;var s=r.exports=(e=t={},Object.defineProperty(e,\"__esModule\",{value:!0}),e.FitAddon=void 0,e.FitAddon=class{activate(e){this._terminal=e}dispose(){}fit(){const e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;const t=this._terminal._core;this._terminal.rows===e.rows&&this._terminal.cols===e.cols||(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal)return;if(!this._terminal.element||!this._terminal.element.parentElement)return;const e=this._terminal._core,t=e._renderService.dimensions;if(0===t.css.cell.width||0===t.css.cell.height)return;const r=0===this._terminal.options.scrollback?0:e.viewport.scrollBarWidth,s=window.getComputedStyle(this._terminal.element.parentElement),i=parseInt(s.getPropertyValue(\"height\")),o=Math.max(0,parseInt(s.getPropertyValue(\"width\"))),n=window.getComputedStyle(this._terminal.element),l=i-(parseInt(n.getPropertyValue(\"padding-top\"))+parseInt(n.getPropertyValue(\"padding-bottom\"))),a=o-(parseInt(n.getPropertyValue(\"padding-right\"))+parseInt(n.getPropertyValue(\"padding-left\")))-r;return{cols:Math.max(2,Math.floor(a/t.css.cell.width)),rows:Math.max(1,Math.floor(l/t.css.cell.height))}}},t),i=r.exports.FitAddon,o=r.exports.__esModule;export{i as FitAddon,o as __esModule,s as default};\n"],"names":["e","t","r","exports","s","Object","defineProperty","value","FitAddon","activate","this","_terminal","dispose","fit","proposeDimensions","isNaN","cols","rows","_core","_renderService","clear","resize","element","parentElement","dimensions","css","cell","width","height","options","scrollback","viewport","scrollBarWidth","window","getComputedStyle","i","parseInt","getPropertyValue","o","Math","max","n","l","a","floor","__esModule"],"mappings":"AAMA,IAAIA,EAAEC,EAAEC,EAAE,CAACC,QAAQ,CAAE,GAAWC,EAAEF,EAAEC,SAASH,EAAEC,EAAE,CAAA,EAAGI,OAAOC,eAAeN,EAAE,aAAa,CAACO,OAAM,IAAKP,EAAEQ,cAAS,EAAOR,EAAEQ,SAAS,MAAM,QAAAC,CAAST,GAAGU,KAAKC,UAAUX,CAAC,CAAC,OAAAY,IAAW,GAAAC,GAAM,MAAMb,EAAEU,KA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AAQ0C"}
|
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "@pyscript/core",
|
3
|
-
"version": "0.4.
|
3
|
+
"version": "0.4.7",
|
4
4
|
"type": "module",
|
5
5
|
"description": "PyScript",
|
6
6
|
"module": "./index.js",
|
@@ -42,7 +42,7 @@
|
|
42
42
|
"dependencies": {
|
43
43
|
"@ungap/with-resolvers": "^0.1.0",
|
44
44
|
"basic-devtools": "^0.1.6",
|
45
|
-
"polyscript": "^0.
|
45
|
+
"polyscript": "^0.11.1",
|
46
46
|
"sticky-module": "^0.1.1",
|
47
47
|
"to-json-callback": "^0.1.1",
|
48
48
|
"type-checked-collections": "^0.1.7"
|
@@ -51,22 +51,22 @@
|
|
51
51
|
"@codemirror/commands": "^6.3.3",
|
52
52
|
"@codemirror/lang-python": "^6.1.4",
|
53
53
|
"@codemirror/language": "^6.10.1",
|
54
|
-
"@codemirror/state": "^6.4.
|
55
|
-
"@codemirror/view": "^6.
|
56
|
-
"@playwright/test": "^1.
|
54
|
+
"@codemirror/state": "^6.4.1",
|
55
|
+
"@codemirror/view": "^6.26.0",
|
56
|
+
"@playwright/test": "^1.42.1",
|
57
57
|
"@rollup/plugin-commonjs": "^25.0.7",
|
58
58
|
"@rollup/plugin-node-resolve": "^15.2.3",
|
59
59
|
"@rollup/plugin-terser": "^0.4.4",
|
60
60
|
"@webreflection/toml-j0.4": "^1.1.3",
|
61
|
-
"@xterm/addon-fit": "^0.9.0
|
61
|
+
"@xterm/addon-fit": "^0.9.0",
|
62
62
|
"chokidar": "^3.6.0",
|
63
63
|
"codemirror": "^6.0.1",
|
64
|
-
"eslint": "^8.
|
65
|
-
"rollup": "^4.
|
64
|
+
"eslint": "^8.57.0",
|
65
|
+
"rollup": "^4.13.0",
|
66
66
|
"rollup-plugin-postcss": "^4.0.2",
|
67
67
|
"rollup-plugin-string": "^3.0.0",
|
68
68
|
"static-handler": "^0.4.3",
|
69
|
-
"typescript": "^5.
|
69
|
+
"typescript": "^5.4.2",
|
70
70
|
"xterm": "^5.3.0",
|
71
71
|
"xterm-readline": "^1.1.1"
|
72
72
|
},
|
@@ -1,6 +1,6 @@
|
|
1
1
|
/**
|
2
2
|
* Bundled by jsDelivr using Rollup v2.79.1 and Terser v5.19.2.
|
3
|
-
* Original file: /npm/@xterm/addon-fit@0.9.0
|
3
|
+
* Original file: /npm/@xterm/addon-fit@0.9.0/lib/addon-fit.js
|
4
4
|
*
|
5
5
|
* Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
|
6
6
|
*/
|
package/src/plugins/py-editor.js
CHANGED
@@ -23,9 +23,12 @@ const hooks = {
|
|
23
23
|
|
24
24
|
async function execute({ currentTarget }) {
|
25
25
|
const { env, pySrc, outDiv } = this;
|
26
|
+
const hasRunButton = !!currentTarget;
|
26
27
|
|
27
|
-
|
28
|
-
|
28
|
+
if (hasRunButton) {
|
29
|
+
currentTarget.disabled = true;
|
30
|
+
outDiv.innerHTML = "";
|
31
|
+
}
|
29
32
|
|
30
33
|
if (!envs.has(env)) {
|
31
34
|
const srcLink = URL.createObjectURL(new Blob([""]));
|
@@ -46,21 +49,25 @@ async function execute({ currentTarget }) {
|
|
46
49
|
// before executing the current code
|
47
50
|
envs.get(env).then((xworker) => {
|
48
51
|
xworker.onerror = ({ error }) => {
|
49
|
-
|
50
|
-
|
51
|
-
|
52
|
+
if (hasRunButton) {
|
53
|
+
outDiv.innerHTML += `<span style='color:red'>${
|
54
|
+
error.message || error
|
55
|
+
}</span>\n`;
|
56
|
+
}
|
52
57
|
console.error(error);
|
53
58
|
};
|
54
59
|
|
55
60
|
const enable = () => {
|
56
|
-
currentTarget.disabled = false;
|
61
|
+
if (hasRunButton) currentTarget.disabled = false;
|
57
62
|
};
|
58
63
|
const { sync } = xworker;
|
59
64
|
sync.write = (str) => {
|
60
|
-
outDiv.innerText += `${str}\n`;
|
65
|
+
if (hasRunButton) outDiv.innerText += `${str}\n`;
|
61
66
|
};
|
62
67
|
sync.writeErr = (str) => {
|
63
|
-
|
68
|
+
if (hasRunButton) {
|
69
|
+
outDiv.innerHTML += `<span style='color:red'>${str}</span>\n`;
|
70
|
+
}
|
64
71
|
};
|
65
72
|
sync.runAsync(pySrc).then(enable, enable);
|
66
73
|
});
|
@@ -120,7 +127,6 @@ const init = async (script, type, interpreter) => {
|
|
120
127
|
{ keymap },
|
121
128
|
{ defaultKeymap },
|
122
129
|
] = await Promise.all([
|
123
|
-
// TODO: find a way to actually produce these bundles locally
|
124
130
|
import(/* webpackIgnore: true */ "../3rd-party/codemirror.js"),
|
125
131
|
import(/* webpackIgnore: true */ "../3rd-party/codemirror_state.js"),
|
126
132
|
import(
|
@@ -131,6 +137,27 @@ const init = async (script, type, interpreter) => {
|
|
131
137
|
import(/* webpackIgnore: true */ "../3rd-party/codemirror_commands.js"),
|
132
138
|
]);
|
133
139
|
|
140
|
+
const isSetup = script.hasAttribute("setup");
|
141
|
+
const env = `${interpreter}-${script.getAttribute("env") || getID(type)}`;
|
142
|
+
const source = script.src
|
143
|
+
? await fetch(script.src).then((b) => b.text())
|
144
|
+
: script.textContent;
|
145
|
+
const context = {
|
146
|
+
interpreter,
|
147
|
+
env,
|
148
|
+
get pySrc() {
|
149
|
+
return isSetup ? source : editor.state.doc.toString();
|
150
|
+
},
|
151
|
+
get outDiv() {
|
152
|
+
return isSetup ? null : outDiv;
|
153
|
+
},
|
154
|
+
};
|
155
|
+
|
156
|
+
if (isSetup) {
|
157
|
+
execute.call(context, { currentTarget: null });
|
158
|
+
return;
|
159
|
+
}
|
160
|
+
|
134
161
|
const selector = script.getAttribute("target");
|
135
162
|
|
136
163
|
let target;
|
@@ -149,18 +176,6 @@ const init = async (script, type, interpreter) => {
|
|
149
176
|
if (!target.hasAttribute("exec-id")) target.setAttribute("exec-id", 0);
|
150
177
|
if (!target.hasAttribute("root")) target.setAttribute("root", target.id);
|
151
178
|
|
152
|
-
const env = `${interpreter}-${script.getAttribute("env") || getID(type)}`;
|
153
|
-
const context = {
|
154
|
-
interpreter,
|
155
|
-
env,
|
156
|
-
get pySrc() {
|
157
|
-
return editor.state.doc.toString();
|
158
|
-
},
|
159
|
-
get outDiv() {
|
160
|
-
return outDiv;
|
161
|
-
},
|
162
|
-
};
|
163
|
-
|
164
179
|
// @see https://github.com/JeffersGlass/mkdocs-pyscript/blob/main/mkdocs_pyscript/js/makeblocks.js
|
165
180
|
const listener = execute.bind(context);
|
166
181
|
const [boxDiv, outDiv] = makeBoxDiv(listener, type);
|
@@ -0,0 +1,94 @@
|
|
1
|
+
import json
|
2
|
+
|
3
|
+
import js
|
4
|
+
|
5
|
+
|
6
|
+
### wrap the response to grant Pythonic results
|
7
|
+
class _Response:
|
8
|
+
def __init__(self, response):
|
9
|
+
self._response = response
|
10
|
+
|
11
|
+
# grant access to response.ok and other fields
|
12
|
+
def __getattr__(self, attr):
|
13
|
+
return getattr(self._response, attr)
|
14
|
+
|
15
|
+
def _as_bytearray(self, buffer):
|
16
|
+
ui8a = js.Uint8Array.new(buffer)
|
17
|
+
size = ui8a.length
|
18
|
+
ba = bytearray(size)
|
19
|
+
for i in range(0, size):
|
20
|
+
ba[i] = ui8a[i]
|
21
|
+
return ba
|
22
|
+
|
23
|
+
# exposed methods with Pythonic results
|
24
|
+
async def arrayBuffer(self):
|
25
|
+
buffer = await self._response.arrayBuffer()
|
26
|
+
# works in Pyodide
|
27
|
+
if hasattr(buffer, "to_py"):
|
28
|
+
return buffer.to_py()
|
29
|
+
# shims in MicroPython
|
30
|
+
return memoryview(self._as_bytearray(buffer))
|
31
|
+
|
32
|
+
async def blob(self):
|
33
|
+
return await self._response.blob()
|
34
|
+
|
35
|
+
async def bytearray(self):
|
36
|
+
buffer = await self._response.arrayBuffer()
|
37
|
+
return self._as_bytearray(buffer)
|
38
|
+
|
39
|
+
async def json(self):
|
40
|
+
return json.loads(await self.text())
|
41
|
+
|
42
|
+
async def text(self):
|
43
|
+
return await self._response.text()
|
44
|
+
|
45
|
+
|
46
|
+
### allow direct await to _Response methods
|
47
|
+
class _DirectResponse:
|
48
|
+
@staticmethod
|
49
|
+
def setup(promise, response):
|
50
|
+
promise._response = _Response(response)
|
51
|
+
return promise._response
|
52
|
+
|
53
|
+
def __init__(self, promise):
|
54
|
+
self._promise = promise
|
55
|
+
promise._response = None
|
56
|
+
promise.arrayBuffer = self.arrayBuffer
|
57
|
+
promise.blob = self.blob
|
58
|
+
promise.bytearray = self.bytearray
|
59
|
+
promise.json = self.json
|
60
|
+
promise.text = self.text
|
61
|
+
|
62
|
+
async def _response(self):
|
63
|
+
if not self._promise._response:
|
64
|
+
await self._promise
|
65
|
+
return self._promise._response
|
66
|
+
|
67
|
+
async def arrayBuffer(self):
|
68
|
+
response = await self._response()
|
69
|
+
return await response.arrayBuffer()
|
70
|
+
|
71
|
+
async def blob(self):
|
72
|
+
response = await self._response()
|
73
|
+
return await response.blob()
|
74
|
+
|
75
|
+
async def bytearray(self):
|
76
|
+
response = await self._response()
|
77
|
+
return await response.bytearray()
|
78
|
+
|
79
|
+
async def json(self):
|
80
|
+
response = await self._response()
|
81
|
+
return await response.json()
|
82
|
+
|
83
|
+
async def text(self):
|
84
|
+
response = await self._response()
|
85
|
+
return await response.text()
|
86
|
+
|
87
|
+
|
88
|
+
def fetch(url, **kw):
|
89
|
+
# workaround Pyodide / MicroPython dict <-> js conversion
|
90
|
+
options = js.JSON.parse(json.dumps(kw))
|
91
|
+
awaited = lambda response, *args: _DirectResponse.setup(promise, response)
|
92
|
+
promise = js.fetch(url, options).then(awaited)
|
93
|
+
_DirectResponse(promise)
|
94
|
+
return promise
|
package/src/stdlib/pyscript.js
CHANGED
@@ -1,9 +1,10 @@
|
|
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 pyscript.display import HTML, display\nfrom pyscript.magic_js import (\n RUNNING_IN_WORKER,\n PyWorker,\n current_target,\n document,\n js_modules,\n sync,\n window,\n)\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 pyscript.display import HTML, display\nfrom pyscript.fetch import fetch\nfrom pyscript.magic_js import (\n RUNNING_IN_WORKER,\n PyWorker,\n current_target,\n document,\n js_modules,\n sync,\n window,\n)\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 \"__repr__\": \"text/plain\",\n \"_repr_html_\": \"text/html\",\n \"_repr_markdown_\": \"text/markdown\",\n \"_repr_svg_\": \"image/svg+xml\",\n \"_repr_pdf_\": \"application/pdf\",\n \"_repr_jpeg_\": \"image/jpeg\",\n \"_repr_png_\": \"image/png\",\n \"_repr_latex\": \"text/latex\",\n \"_repr_json_\": \"application/json\",\n \"_repr_javascript_\": \"application/javascript\",\n \"savefig\": \"image/png\",\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 reversed(_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 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 from pyweb import pydom\n\n if isinstance(selector, pydom.Element):\n elements = [selector._js]\n elif isinstance(selector, pydom.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 currently an quick hack to get micropython working but we need\n # to actually properly replace inspect.signature with something else\n def wrapper(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except TypeError as e:\n if \"takes 0 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
|
+
"fetch.py": "import json\n\nimport js\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\n def _as_bytearray(self, buffer):\n ui8a = js.Uint8Array.new(buffer)\n size = ui8a.length\n ba = bytearray(size)\n for i in range(0, size):\n ba[i] = ui8a[i]\n return ba\n\n # 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(self._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 self._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",
|
7
8
|
"magic_js.py": "import sys\n\nimport js as globalThis\nfrom polyscript import js_modules\nfrom pyscript.util import NotSupported\n\nRUNNING_IN_WORKER = not hasattr(globalThis, \"document\")\n\n\n# allow `from pyscript.js_modules.xxx import yyy`\nclass JSModule:\n def __init__(self, name):\n self.name = name\n\n def __getattr__(self, field):\n # avoid pyodide looking for non existent fields\n if not field.startswith(\"_\"):\n return getattr(getattr(js_modules, self.name), field)\n\n\n# generate N modules in the system that will proxy the real value\nfor name in globalThis.Reflect.ownKeys(js_modules):\n sys.modules[f\"pyscript.js_modules.{name}\"] = JSModule(name)\nsys.modules[\"pyscript.js_modules\"] = js_modules\n\nif RUNNING_IN_WORKER:\n import polyscript\n\n PyWorker = NotSupported(\n \"pyscript.PyWorker\",\n \"pyscript.PyWorker works only when running in the main thread\",\n )\n\n try:\n globalThis.SharedArrayBuffer.new(4)\n import js\n\n window = polyscript.xworker.window\n document = window.document\n js.document = document\n except:\n globalThis.console.debug(\"SharedArrayBuffer is not available\")\n # in this scenario none of the utilities would work\n # as expected so we better export these as NotSupported\n window = NotSupported(\n \"pyscript.window\",\n \"pyscript.window in workers works only via SharedArrayBuffer\",\n )\n document = NotSupported(\n \"pyscript.document\",\n \"pyscript.document in workers works only via SharedArrayBuffer\",\n )\n\n sync = polyscript.xworker.sync\n\n # in workers the display does not have a default ID\n # but there is a sync utility from xworker\n def current_target():\n return polyscript.target\n\nelse:\n import _pyscript\n from _pyscript import PyWorker\n\n window = globalThis\n document = globalThis.document\n sync = NotSupported(\n \"pyscript.sync\", \"pyscript.sync works only when running in a worker\"\n )\n\n # in MAIN the current element target exist, just use it\n def current_target():\n return _pyscript.target\n",
|
8
9
|
"util.py": "class NotSupported:\n \"\"\"\n Small helper that raises exceptions if you try to get/set any attribute on\n it.\n \"\"\"\n\n def __init__(self, name, error):\n object.__setattr__(self, \"name\", name)\n object.__setattr__(self, \"error\", error)\n\n def __repr__(self):\n return f\"<NotSupported {self.name} [{self.error}]>\"\n\n def __getattr__(self, attr):\n raise AttributeError(self.error)\n\n def __setattr__(self, attr, value):\n raise AttributeError(self.error)\n\n def __call__(self, *args):\n raise TypeError(self.error)\n"
|
9
10
|
},
|