code-playpad 0.5.1 → 0.5.2
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/README.md +37 -10
- package/dist/THIRD-PARTY-NOTICES.txt +347 -0
- package/dist/cdn.js +2 -2
- package/dist/config-D9w0xYhX.js +6 -0
- package/dist/{element-CthH7rm5.js → element-Bb_ST7mq.js} +1 -1
- package/dist/element.js +1 -1
- package/dist/index.js +1 -1
- package/dist/{java-Dd7T9rVc.js → java-ZNMW01Qb.js} +1 -1
- package/dist/javascript-CX-lsX2u.js +14 -0
- package/dist/javascript-DeH32mx7.js +9 -0
- package/dist/{pyodide-BeJ9RqWJ.js → pyodide-Crdd9em4.js} +1 -1
- package/dist/{pyodide-FRnMyCht.js → pyodide-DSeVedct.js} +1 -1
- package/dist/react.js +1 -1
- package/dist/runtime/config.d.ts +6 -3
- package/dist/runtime/javascript.d.ts +3 -0
- package/dist/runtime/js-worker.d.ts +5 -3
- package/dist/runtime/sucrase-chunk.generated.d.ts +2 -0
- package/dist/runtime/sucrase.generated.d.ts +5 -0
- package/dist/standalone.js +1 -1
- package/dist/sucrase-3.35.1.js +6 -0
- package/dist/{worker-runtime-owJ7Wwco.js → worker-runtime-CP8YJgwA.js} +1 -1
- package/package.json +3 -1
- package/dist/config-DZqcFPEP.js +0 -6
- package/dist/javascript-BiwxX4vc.js +0 -9
- package/dist/javascript-EtrNZmfD.js +0 -14
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* code-playpad — MIT © 2026 Seung Hun Lee
|
|
3
|
+
* Bundles CodeMirror 6 and Lezer (MIT) © Marijn Haverbeke and others.
|
|
4
|
+
* Full third-party licences: THIRD-PARTY-NOTICES.txt in this package.
|
|
5
|
+
*/
|
|
6
|
+
import{a as e}from"./config-D9w0xYhX.js";import{t}from"./worker-runtime-CNPpMRo1.js";var n=`let currentId=null,stdinLines=[],stdinExhausted=!1,nextRequest=1,inputWaitMs=0;const pendingLines=new Map;let sucrasePromise=null,sucraseURL=null;const pendingModules=new Map;class TransformLoadError extends Error{}function requestModule(t){return new Promise((e,r)=>{pendingModules.set(t,{resolve:e,reject:r}),post({type:"module-request",id:currentId,name:t})})}function post(t){self.postMessage(t)}let functionLineOffset=0;try{new Function('throw new Error("probe")')()}catch(t){const e=/<anonymous>:(\\d+):/.exec(t.stack||"");e&&(functionLineOffset=Number(e[1])-1)}let currentFiles=[];const FLUSH_BYTES=8192,FLUSH_MS=16,EAGER_POSTS=32;let outputQueue=[],queuedChars=0,windowStart=-1/0,windowPosts=0;function writeOutput(t,e){const r=outputQueue[outputQueue.length-1];r&&r.type===t?r.text+=e:outputQueue.push({type:t,text:e}),queuedChars+=e.length;const i=performance.now();i-windowStart>=FLUSH_MS&&(windowStart=i,windowPosts=0),(windowPosts<EAGER_POSTS||queuedChars>=FLUSH_BYTES)&&flushOutput()}function flushOutput(){if(!outputQueue.length)return;windowPosts++;const t=outputQueue;outputQueue=[],queuedChars=0;for(const e of t)post({type:e.type,id:currentId,text:e.text})}function format(t,e,r){if(e=e||new Set,typeof t=="string")return r?t:JSON.stringify(t);if(typeof t=="bigint")return String(t)+"n";if(typeof t=="function")return"[Function"+(t.name?": "+t.name:"")+"]";if(typeof t=="symbol"||t==null||typeof t!="object")return String(t);if(e.has(t))return"[Circular]";e.add(t);try{if(t instanceof Error)return t.stack||t.name+": "+t.message;if(Array.isArray(t))return"[ "+t.map(n=>format(n,e)).join(", ")+" ]";if(t instanceof Map)return"Map("+t.size+") { "+[...t].map(([n,o])=>format(n,e)+" => "+format(o,e)).join(", ")+" }";if(t instanceof Set)return"Set("+t.size+") { "+[...t].map(n=>format(n,e)).join(", ")+" }";if(t instanceof Date)return t.toISOString();if(t instanceof Promise)return"Promise { \\u2026 }";const i=Object.entries(t).map(([n,o])=>n+": "+format(o,e)),a=t.constructor&&t.constructor.name;return(a&&a!=="Object"?a+" ":"")+"{ "+i.join(", ")+" }"}finally{e.delete(t)}}function formatArgs(t){return t.map(e=>format(e,null,!0)).join(" ")+\`
|
|
7
|
+
\`}const nativeConsole=self.console;self.console=Object.assign(Object.create(nativeConsole),{log:(...t)=>writeOutput("stdout",formatArgs(t)),info:(...t)=>writeOutput("stdout",formatArgs(t)),debug:(...t)=>writeOutput("stdout",formatArgs(t)),warn:(...t)=>writeOutput("stderr",formatArgs(t)),error:(...t)=>writeOutput("stderr",formatArgs(t))}),self._ppReadLine=async()=>{if(stdinLines.length){const i=stdinLines.shift();return writeOutput("echo",i+\`
|
|
8
|
+
\`),i}const t=nextRequest++;flushOutput();const e=performance.now(),r=await new Promise(i=>{pendingLines.set(t,i),post({type:"stdin-request",id:currentId,request:t})});return inputWaitMs+=performance.now()-e,typeof r!="string"&&(stdinExhausted=!0),typeof r=="string"?r:null};async function input(t){t!==void 0&&writeOutput("stdout",String(t));const e=await self._ppReadLine();if(e===null)throw new Error("EOF: no more input");return e}self.input=input;async function loadSucrase(){return sucrasePromise||(sucrasePromise=(async()=>{try{if(sucraseURL)return await import(sucraseURL);const t=await requestModule("sucrase"),e=URL.createObjectURL(new Blob([t],{type:"text/javascript"}));try{return await import(e)}finally{URL.revokeObjectURL(e)}}catch(t){const e=sucraseURL?" from "+sucraseURL:"";throw new TransformLoadError("Could not load the TypeScript transform (Sucrase)"+e+": "+(t&&t.message?t.message:String(t)))}})(),sucrasePromise.catch(()=>{sucrasePromise=null})),sucrasePromise}function isModule(t,e){return Object.keys(t).length>1?!0:/^\\s*(import|export)\\s/m.test(t[e]||"")}function needsTypeScript(t){return/\\.(ts|tsx|jsx|mts|cts)$/.test(t)}function transformsFor(t){const e=["imports"];return/\\.tsx?$|\\.mts$|\\.cts$/.test(t)&&e.push("typescript"),/\\.[jt]sx$/.test(t)&&e.push("jsx"),e}async function runAsModules(t,e){const{transform:r}=await loadSucrase(),i=new Map,a=(n,o)=>{if(!o.startsWith("."))return null;const u=((n.includes("/")?n.slice(0,n.lastIndexOf("/")+1):"")+o).split("/"),d=[];for(const p of u)p==="."||p===""||(p===".."?d.pop():d.push(p));const c=d.join("/");return[c,c+".js",c+".ts",c+".tsx",c+".jsx",c+".json",c+"/index.js",c+"/index.ts"].find(p=>p in t)||null};function s(n){if(i.has(n))return i.get(n).exports;const o={exports:{}};if(i.set(n,o),n.endsWith(".json")){try{o.exports=JSON.parse(t[n])}catch(c){throw new SyntaxError("Invalid JSON in "+n+": "+c.message)}return o.exports}const{code:f}=r(t[n],{transforms:transformsFor(n),filePath:n,preserveDynamicImport:!0}),u=c=>{const l=a(n,c);if(!l)throw new Error('Cannot find module "'+c+'" from "'+n+'"');return s(l)};return new Function("exports","require","module","__filename","input","console",f+\`
|
|
9
|
+
//# sourceURL=\`+n)(o.exports,u,o,n,input,self.console),o.exports}s(e)}async function run(t){currentId=t.id,stdinLines=t.stdin?String(t.stdin).replace(/\\n$/,"").split(\`
|
|
10
|
+
\`):[],stdinExhausted=!1,inputWaitMs=0,windowStart=-1/0;for(const s of pendingLines.values())s(null);pendingLines.clear();const e=t.files&&Object.keys(t.files).length?t.files:{"main.js":t.code},r=t.entry&&e[t.entry]?t.entry:Object.keys(e)[0],i=performance.now();currentFiles=Object.keys(e);const a=isModule(e,r);try{let s;if(a)s=await runAsModules(e,r);else{let n=e[r];if(needsTypeScript(r)){const{transform:f}=await loadSucrase();n=f(n,{transforms:transformsFor(r).filter(u=>u!=="imports"),filePath:r}).code}const o=n+\`
|
|
11
|
+
//# sourceURL=\`+r;try{s=(0,eval)(o)}catch(f){if(f instanceof SyntaxError&&(/await|import/i.test(f.message)||/\\bawait\\b/.test(n))){const u=Object.getPrototypeOf(async function(){}).constructor;s=await new u("input",o)(input)}else throw f}s&&typeof s.then=="function"&&(s=await s)}flushOutput(),post({type:"result",id:t.id,value:s===void 0?void 0:format(s),durationMs:performance.now()-i-inputWaitMs})}catch(s){flushOutput();const n=s instanceof TransformLoadError;post({type:"error",id:t.id,message:n?s.message:formatError(s,a),hint:n?"This is not an error in your code: the TypeScript transform did not load. Check the connection (or anything that blocks scripts on this page), then press Run again, or reload the page if it keeps failing.":stdinExhausted&&/EOF/.test(String(s&&s.message))?"input() asked for a line that standard input did not have. Add one line per input() call in the box above, then run again.":void 0,hintAbout:stdinExhausted&&/EOF/.test(String(s&&s.message))?"stdin":void 0,durationMs:performance.now()-i-inputWaitMs})}finally{currentId=null}}function formatError(t,e){if(!(t instanceof Error))return"Uncaught "+format(t);const r=t.stack||t.name+": "+t.message,i=e?functionLineOffset:0,a=[];for(const s of r.split(\`
|
|
12
|
+
\`))!currentFiles.some(o=>s.includes(o+":"))&&/\\bat |blob:/.test(s)||a.push(i?s.replace(/([\\w./-]+):(\\d+):(\\d+)/g,(o,f,u,d)=>currentFiles.indexOf(f)===-1?o:f+":"+(Number(u)-i)+":"+d):s);return a.join(\`
|
|
13
|
+
\`).replace(/\\s+$/,"")}self.onmessage=async t=>{const e=t.data;try{if(e.type==="init")e.sucraseURL&&(sucraseURL=e.sucraseURL),post({type:"ready",version:"es2022",interactiveStdin:!0});else if(e.type==="run")await run(e);else if(e.type==="stdin-response"){const r=pendingLines.get(e.request);r&&(pendingLines.delete(e.request),r(e.text))}else if(e.type==="module"){const r=pendingModules.get(e.name);r&&(pendingModules.delete(e.name),typeof e.code=="string"?r.resolve(e.code):r.reject(new Error(e.error||"the page did not provide "+e.name)))}}catch(r){post({type:"fatal",id:e&&e.id,message:formatError(r)})}};
|
|
14
|
+
`,r=`sucrase-3.35.1.js`,i=new class extends t{id=`javascript`;get source(){return n}initPayload(){return{sucraseURL:e()}}async loadModule(e){if(e!==`sucrase`)throw Error(`no module named ${e}`);try{let{SUCRASE_SOURCE:e}=this.#e===0?await import(`./sucrase-3.35.1.js`):await import(this.#t());return e}catch(e){throw this.#e++,e}}#e=0;#t(){let e=import.meta.url;return new URL(`./`+r+`?retry=`+this.#e,e).href}get label(){return`JavaScript`}};function a(e,t,n){return{id:e,get label(){return t},get ready(){return i.ready},get interactiveStdin(){return i.interactiveStdin},async editorLanguage(){let{javascript:e}=await import(`./dist-CqpVTRAq.js`);return e({typescript:n})},load:e=>i.load(e),run:(e,t)=>i.run(e,t),stop:e=>i.stop(e)}}var o=a(`javascript`,`JavaScript`,!1),s=a(`typescript`,`TypeScript`,!0);export{o as javascriptRuntime,s as typescriptRuntime};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{a as e}from"./config-D9w0xYhX.js";import{t}from"./worker-runtime-CP8YJgwA.js";var n=`let currentId=null,stdinLines=[],stdinExhausted=!1,nextRequest=1,inputWaitMs=0;const pendingLines=new Map;let sucrasePromise=null,sucraseURL=null;const pendingModules=new Map;class TransformLoadError extends Error{}function requestModule(t){return new Promise((e,r)=>{pendingModules.set(t,{resolve:e,reject:r}),post({type:"module-request",id:currentId,name:t})})}function post(t){self.postMessage(t)}let functionLineOffset=0;try{new Function('throw new Error("probe")')()}catch(t){const e=/<anonymous>:(\\d+):/.exec(t.stack||"");e&&(functionLineOffset=Number(e[1])-1)}let currentFiles=[];const FLUSH_BYTES=8192,FLUSH_MS=16,EAGER_POSTS=32;let outputQueue=[],queuedChars=0,windowStart=-1/0,windowPosts=0;function writeOutput(t,e){const r=outputQueue[outputQueue.length-1];r&&r.type===t?r.text+=e:outputQueue.push({type:t,text:e}),queuedChars+=e.length;const i=performance.now();i-windowStart>=FLUSH_MS&&(windowStart=i,windowPosts=0),(windowPosts<EAGER_POSTS||queuedChars>=FLUSH_BYTES)&&flushOutput()}function flushOutput(){if(!outputQueue.length)return;windowPosts++;const t=outputQueue;outputQueue=[],queuedChars=0;for(const e of t)post({type:e.type,id:currentId,text:e.text})}function format(t,e,r){if(e=e||new Set,typeof t=="string")return r?t:JSON.stringify(t);if(typeof t=="bigint")return String(t)+"n";if(typeof t=="function")return"[Function"+(t.name?": "+t.name:"")+"]";if(typeof t=="symbol"||t==null||typeof t!="object")return String(t);if(e.has(t))return"[Circular]";e.add(t);try{if(t instanceof Error)return t.stack||t.name+": "+t.message;if(Array.isArray(t))return"[ "+t.map(n=>format(n,e)).join(", ")+" ]";if(t instanceof Map)return"Map("+t.size+") { "+[...t].map(([n,o])=>format(n,e)+" => "+format(o,e)).join(", ")+" }";if(t instanceof Set)return"Set("+t.size+") { "+[...t].map(n=>format(n,e)).join(", ")+" }";if(t instanceof Date)return t.toISOString();if(t instanceof Promise)return"Promise { \\u2026 }";const i=Object.entries(t).map(([n,o])=>n+": "+format(o,e)),a=t.constructor&&t.constructor.name;return(a&&a!=="Object"?a+" ":"")+"{ "+i.join(", ")+" }"}finally{e.delete(t)}}function formatArgs(t){return t.map(e=>format(e,null,!0)).join(" ")+\`
|
|
2
|
+
\`}const nativeConsole=self.console;self.console=Object.assign(Object.create(nativeConsole),{log:(...t)=>writeOutput("stdout",formatArgs(t)),info:(...t)=>writeOutput("stdout",formatArgs(t)),debug:(...t)=>writeOutput("stdout",formatArgs(t)),warn:(...t)=>writeOutput("stderr",formatArgs(t)),error:(...t)=>writeOutput("stderr",formatArgs(t))}),self._ppReadLine=async()=>{if(stdinLines.length){const i=stdinLines.shift();return writeOutput("echo",i+\`
|
|
3
|
+
\`),i}const t=nextRequest++;flushOutput();const e=performance.now(),r=await new Promise(i=>{pendingLines.set(t,i),post({type:"stdin-request",id:currentId,request:t})});return inputWaitMs+=performance.now()-e,typeof r!="string"&&(stdinExhausted=!0),typeof r=="string"?r:null};async function input(t){t!==void 0&&writeOutput("stdout",String(t));const e=await self._ppReadLine();if(e===null)throw new Error("EOF: no more input");return e}self.input=input;async function loadSucrase(){return sucrasePromise||(sucrasePromise=(async()=>{try{if(sucraseURL)return await import(sucraseURL);const t=await requestModule("sucrase"),e=URL.createObjectURL(new Blob([t],{type:"text/javascript"}));try{return await import(e)}finally{URL.revokeObjectURL(e)}}catch(t){const e=sucraseURL?" from "+sucraseURL:"";throw new TransformLoadError("Could not load the TypeScript transform (Sucrase)"+e+": "+(t&&t.message?t.message:String(t)))}})(),sucrasePromise.catch(()=>{sucrasePromise=null})),sucrasePromise}function isModule(t,e){return Object.keys(t).length>1?!0:/^\\s*(import|export)\\s/m.test(t[e]||"")}function needsTypeScript(t){return/\\.(ts|tsx|jsx|mts|cts)$/.test(t)}function transformsFor(t){const e=["imports"];return/\\.tsx?$|\\.mts$|\\.cts$/.test(t)&&e.push("typescript"),/\\.[jt]sx$/.test(t)&&e.push("jsx"),e}async function runAsModules(t,e){const{transform:r}=await loadSucrase(),i=new Map,a=(n,o)=>{if(!o.startsWith("."))return null;const u=((n.includes("/")?n.slice(0,n.lastIndexOf("/")+1):"")+o).split("/"),d=[];for(const p of u)p==="."||p===""||(p===".."?d.pop():d.push(p));const c=d.join("/");return[c,c+".js",c+".ts",c+".tsx",c+".jsx",c+".json",c+"/index.js",c+"/index.ts"].find(p=>p in t)||null};function s(n){if(i.has(n))return i.get(n).exports;const o={exports:{}};if(i.set(n,o),n.endsWith(".json")){try{o.exports=JSON.parse(t[n])}catch(c){throw new SyntaxError("Invalid JSON in "+n+": "+c.message)}return o.exports}const{code:f}=r(t[n],{transforms:transformsFor(n),filePath:n,preserveDynamicImport:!0}),u=c=>{const l=a(n,c);if(!l)throw new Error('Cannot find module "'+c+'" from "'+n+'"');return s(l)};return new Function("exports","require","module","__filename","input","console",f+\`
|
|
4
|
+
//# sourceURL=\`+n)(o.exports,u,o,n,input,self.console),o.exports}s(e)}async function run(t){currentId=t.id,stdinLines=t.stdin?String(t.stdin).replace(/\\n$/,"").split(\`
|
|
5
|
+
\`):[],stdinExhausted=!1,inputWaitMs=0,windowStart=-1/0;for(const s of pendingLines.values())s(null);pendingLines.clear();const e=t.files&&Object.keys(t.files).length?t.files:{"main.js":t.code},r=t.entry&&e[t.entry]?t.entry:Object.keys(e)[0],i=performance.now();currentFiles=Object.keys(e);const a=isModule(e,r);try{let s;if(a)s=await runAsModules(e,r);else{let n=e[r];if(needsTypeScript(r)){const{transform:f}=await loadSucrase();n=f(n,{transforms:transformsFor(r).filter(u=>u!=="imports"),filePath:r}).code}const o=n+\`
|
|
6
|
+
//# sourceURL=\`+r;try{s=(0,eval)(o)}catch(f){if(f instanceof SyntaxError&&(/await|import/i.test(f.message)||/\\bawait\\b/.test(n))){const u=Object.getPrototypeOf(async function(){}).constructor;s=await new u("input",o)(input)}else throw f}s&&typeof s.then=="function"&&(s=await s)}flushOutput(),post({type:"result",id:t.id,value:s===void 0?void 0:format(s),durationMs:performance.now()-i-inputWaitMs})}catch(s){flushOutput();const n=s instanceof TransformLoadError;post({type:"error",id:t.id,message:n?s.message:formatError(s,a),hint:n?"This is not an error in your code: the TypeScript transform did not load. Check the connection (or anything that blocks scripts on this page), then press Run again, or reload the page if it keeps failing.":stdinExhausted&&/EOF/.test(String(s&&s.message))?"input() asked for a line that standard input did not have. Add one line per input() call in the box above, then run again.":void 0,hintAbout:stdinExhausted&&/EOF/.test(String(s&&s.message))?"stdin":void 0,durationMs:performance.now()-i-inputWaitMs})}finally{currentId=null}}function formatError(t,e){if(!(t instanceof Error))return"Uncaught "+format(t);const r=t.stack||t.name+": "+t.message,i=e?functionLineOffset:0,a=[];for(const s of r.split(\`
|
|
7
|
+
\`))!currentFiles.some(o=>s.includes(o+":"))&&/\\bat |blob:/.test(s)||a.push(i?s.replace(/([\\w./-]+):(\\d+):(\\d+)/g,(o,f,u,d)=>currentFiles.indexOf(f)===-1?o:f+":"+(Number(u)-i)+":"+d):s);return a.join(\`
|
|
8
|
+
\`).replace(/\\s+$/,"")}self.onmessage=async t=>{const e=t.data;try{if(e.type==="init")e.sucraseURL&&(sucraseURL=e.sucraseURL),post({type:"ready",version:"es2022",interactiveStdin:!0});else if(e.type==="run")await run(e);else if(e.type==="stdin-response"){const r=pendingLines.get(e.request);r&&(pendingLines.delete(e.request),r(e.text))}else if(e.type==="module"){const r=pendingModules.get(e.name);r&&(pendingModules.delete(e.name),typeof e.code=="string"?r.resolve(e.code):r.reject(new Error(e.error||"the page did not provide "+e.name)))}}catch(r){post({type:"fatal",id:e&&e.id,message:formatError(r)})}};
|
|
9
|
+
`,r=`sucrase-3.35.1.js`,i=new class extends t{id=`javascript`;get source(){return n}initPayload(){return{sucraseURL:e()}}async loadModule(e){if(e!==`sucrase`)throw Error(`no module named ${e}`);try{let{SUCRASE_SOURCE:e}=this.#e===0?await import(`./sucrase-3.35.1.js`):await import(this.#t());return e}catch(e){throw this.#e++,e}}#e=0;#t(){let e=import.meta.url;return new URL(`./`+r+`?retry=`+this.#e,e).href}get label(){return`JavaScript`}};function a(e,t,n){return{id:e,get label(){return t},get ready(){return i.ready},get interactiveStdin(){return i.interactiveStdin},async editorLanguage(){let{javascript:e}=await import(`@codemirror/lang-javascript`);return e({typescript:n})},load:e=>i.load(e),run:(e,t)=>i.run(e,t),stop:e=>i.stop(e)}}var o=a(`javascript`,`JavaScript`,!1),s=a(`typescript`,`TypeScript`,!0);export{o as javascriptRuntime,s as typescriptRuntime};
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* Bundles CodeMirror 6 and Lezer (MIT) © Marijn Haverbeke and others.
|
|
4
4
|
* Full third-party licences: THIRD-PARTY-NOTICES.txt in this package.
|
|
5
5
|
*/
|
|
6
|
-
import{i as e}from"./config-
|
|
6
|
+
import{i as e}from"./config-D9w0xYhX.js";import{t}from"./worker-runtime-CNPpMRo1.js";var n=`let pyodide=null,stdinLines=[],stdinExhausted=!1,currentId=null,interactive=!1,inputWaitMs=0,nextRequest=1;const pendingLines=new Map,MOUNT="/home/pyodide/playground";let written=new Set,internals=null;const REFRESH=["import importlib, os, sys","MOUNT = "+JSON.stringify(MOUNT),"os.makedirs(MOUNT, exist_ok=True)","sys.path.insert(0, MOUNT) if MOUNT not in sys.path else None","os.chdir(MOUNT)","for _name, _mod in list(sys.modules.items()):",' _file = getattr(_mod, "__file__", None) or ""',' _paths = list(getattr(_mod, "__path__", None) or [])'," if _file.startswith(MOUNT) or any(str(p).startswith(MOUNT) for p in _paths):"," del sys.modules[_name]","importlib.invalidate_caches()"].join(\`
|
|
7
7
|
\`);function flushStreams(){try{pyodide.runPython(\`import sys
|
|
8
8
|
sys.stdout.flush()
|
|
9
9
|
sys.stderr.flush()\`,{globals:internals})}catch{}flushOutput()}const INPUT_OVERRIDE=["import builtins, sys, js","from pyodide.ffi import run_sync","",'def _pg_input(prompt=""):',' if prompt != "":'," sys.stdout.write(str(prompt))"," sys.stdout.flush()"," line = run_sync(js._pgReadLine())"," # Pyodide maps JS null to its own JsNull singleton, not None, so test"," # for what we want rather than for the several ways EOF can arrive."," if not isinstance(line, str):",' raise EOFError("EOF when reading a line")'," return line","",'_pg_input.__name__ = "input"','_pg_input.__qualname__ = "input"',"_pg_input.__doc__ = builtins.input.__doc__","builtins.input = _pg_input"].join(\`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{i as e}from"./config-
|
|
1
|
+
import{i as e}from"./config-D9w0xYhX.js";import{t}from"./worker-runtime-CP8YJgwA.js";var n=`let pyodide=null,stdinLines=[],stdinExhausted=!1,currentId=null,interactive=!1,inputWaitMs=0,nextRequest=1;const pendingLines=new Map,MOUNT="/home/pyodide/playground";let written=new Set,internals=null;const REFRESH=["import importlib, os, sys","MOUNT = "+JSON.stringify(MOUNT),"os.makedirs(MOUNT, exist_ok=True)","sys.path.insert(0, MOUNT) if MOUNT not in sys.path else None","os.chdir(MOUNT)","for _name, _mod in list(sys.modules.items()):",' _file = getattr(_mod, "__file__", None) or ""',' _paths = list(getattr(_mod, "__path__", None) or [])'," if _file.startswith(MOUNT) or any(str(p).startswith(MOUNT) for p in _paths):"," del sys.modules[_name]","importlib.invalidate_caches()"].join(\`
|
|
2
2
|
\`);function flushStreams(){try{pyodide.runPython(\`import sys
|
|
3
3
|
sys.stdout.flush()
|
|
4
4
|
sys.stderr.flush()\`,{globals:internals})}catch{}flushOutput()}const INPUT_OVERRIDE=["import builtins, sys, js","from pyodide.ffi import run_sync","",'def _pg_input(prompt=""):',' if prompt != "":'," sys.stdout.write(str(prompt))"," sys.stdout.flush()"," line = run_sync(js._pgReadLine())"," # Pyodide maps JS null to its own JsNull singleton, not None, so test"," # for what we want rather than for the several ways EOF can arrive."," if not isinstance(line, str):",' raise EOFError("EOF when reading a line")'," return line","",'_pg_input.__name__ = "input"','_pg_input.__qualname__ = "input"',"_pg_input.__doc__ = builtins.input.__doc__","builtins.input = _pg_input"].join(\`
|
package/dist/react.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e}from"./element-
|
|
1
|
+
import{n as e}from"./element-Bb_ST7mq.js";import{useEffect as t,useRef as n}from"react";import{jsx as r}from"react/jsx-runtime";e();function i({code:e=``,files:i,entry:a,stdin:o,language:s=`python`,height:c,minHeight:l,maxHeight:u,theme:d=`auto`,readOnly:f,autoRun:p,persist:m,practice:h,className:g,style:_,onReady:v,onRun:y,onOutput:b,onError:x}){let S=n(null),C=n({onReady:v,onRun:y,onOutput:b,onError:x});C.current={onReady:v,onRun:y,onOutput:b,onError:x},t(()=>{let e=S.current;if(!e)return;let t=(t,n)=>{let r=e=>n(C.current)?.(e.detail);return e.addEventListener(t,r),()=>e.removeEventListener(t,r)},n=[t(`py-ready`,e=>e.onReady),t(`py-run`,e=>e.onRun),t(`py-output`,e=>e.onOutput),t(`py-error`,e=>e.onError)];return()=>n.forEach(e=>e())},[]);let w=i?JSON.stringify(i):null;t(()=>{let t=S.current;t&&(w?t.files=JSON.parse(w):e!==t.code&&(t.code=e))},[e,w]),t(()=>{S.current&&o!==void 0&&(S.current.stdin=o)},[o]);let T=h?JSON.stringify(h):null;return t(()=>{S.current&&(S.current.practice=T?JSON.parse(T):null)},[T]),r(`code-playpad`,{ref:S,language:s,theme:d,class:g,style:_,...c===void 0?{}:{height:String(c)},...l===void 0?{}:{"min-height":String(l)},...u===void 0?{}:{"max-height":String(u)},...f?{readonly:``}:{},...p?{autorun:``}:{},...m?{persist:m}:{},...a?{entry:a}:{},children:i?null:e})}export{i as CodePlayPad,i as default};
|
package/dist/runtime/config.d.ts
CHANGED
|
@@ -13,13 +13,16 @@ export declare const PYODIDE_VERSION = "314.0.5";
|
|
|
13
13
|
export declare function configurePython(options: {
|
|
14
14
|
indexURL: string;
|
|
15
15
|
}): void;
|
|
16
|
-
/**
|
|
17
|
-
*
|
|
16
|
+
/** Load the TypeScript/JSX transform (Sucrase) from a URL of your own instead of
|
|
17
|
+
* the copy this package ships, which needs no configuration. The URL must be an
|
|
18
|
+
* absolute URL of a self-contained ES module exporting `transform`. Call it
|
|
19
|
+
* before the first JavaScript or TypeScript widget starts its runtime; it is
|
|
20
|
+
* read once, when the worker starts. */
|
|
18
21
|
export declare function configureTypeScript(options: {
|
|
19
22
|
sucraseURL: string;
|
|
20
23
|
}): void;
|
|
21
24
|
export declare function getPyodideIndexURL(): string;
|
|
22
|
-
export declare function getSucraseURL(): string;
|
|
25
|
+
export declare function getSucraseURL(): string | null;
|
|
23
26
|
/** The files worth `<link rel="preload">`-ing in the document head, so the
|
|
24
27
|
* network fetch starts before app JS runs. Python only — JavaScript has
|
|
25
28
|
* nothing to preload, which is rather the point of it. */
|
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { WorkerRuntime } from './worker-runtime.js';
|
|
1
2
|
import type { Runtime } from '../types.js';
|
|
3
|
+
/** The shared worker runtime itself, for the package's own tests (not exported by any entry point). */
|
|
4
|
+
export declare const javaScriptWorkerRuntime: WorkerRuntime;
|
|
2
5
|
export declare const javascriptRuntime: Runtime;
|
|
3
6
|
export declare const typescriptRuntime: Runtime;
|
|
@@ -2,8 +2,10 @@
|
|
|
2
2
|
* Source for the JavaScript / TypeScript worker.
|
|
3
3
|
*
|
|
4
4
|
* Unlike Python there is no runtime to download — the engine is already here.
|
|
5
|
-
* The only thing that may be
|
|
6
|
-
* the code actually needs one (a .ts file, JSX, or ES module syntax
|
|
7
|
-
* several files).
|
|
5
|
+
* The only thing that may be loaded is a TypeScript transform (Sucrase), and
|
|
6
|
+
* only when the code actually needs one (a .ts file, JSX, or ES module syntax
|
|
7
|
+
* across several files). It ships in this package: the worker asks the page
|
|
8
|
+
* for it (module-request), as the Java worker asks for its library. Plain
|
|
9
|
+
* single-file JavaScript costs nothing beyond this file.
|
|
8
10
|
*/
|
|
9
11
|
export declare const JS_WORKER_SOURCE: string;
|
package/dist/standalone.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* Bundles CodeMirror 6 and Lezer (MIT) © Marijn Haverbeke and others.
|
|
4
4
|
* Full third-party licences: THIRD-PARTY-NOTICES.txt in this package.
|
|
5
5
|
*/
|
|
6
|
-
import{n as e,r as t,t as n}from"./hints-v5iHTd1l.js";import{n as r,o as i,r as a,t as o}from"./config-
|
|
6
|
+
import{n as e,r as t,t as n}from"./hints-v5iHTd1l.js";import{n as r,o as i,r as a,t as o}from"./config-D9w0xYhX.js";async function s(e){try{return await c(e)}catch(t){return console.warn(`[code-playpad] CodeMirror unavailable, using plain textarea:`,t),l(e)}}async function c(e){let[t,n,r,i,a,o]=await Promise.all([import(`./dist-BThnYaQ5.js`).then(e=>e.s),import(`./dist-DOsLUKSb.js`).then(e=>e.x),import(`./dist-CnC1nMtN.js`),import(`./dist-D0FPZcUi.js`),import(`./dist-DmrP6yta.js`),import(`./dist-DlIO0dzi.js`)]),{EditorView:s,keymap:c,lineNumbers:l,highlightActiveLine:u,highlightActiveLineGutter:d,highlightSpecialChars:f,drawSelection:p,rectangularSelection:m,crosshairCursor:h}=t,{EditorState:g,Compartment:_}=n,{defaultKeymap:v,history:y,historyKeymap:b,indentWithTab:x}=r,{syntaxHighlighting:S,defaultHighlightStyle:C,indentOnInput:w,bracketMatching:T,foldGutter:E,foldKeymap:D}=i,{autocompletion:O,closeBrackets:k,closeBracketsKeymap:A,completionKeymap:j}=a,M=new _,N=new _,P=new _,F=[s.theme({"&":{color:`#1f2328`,backgroundColor:`#ffffff`},".cm-gutters":{backgroundColor:`#f6f8fa`,color:`#8b949e`,border:`none`},".cm-activeLine":{backgroundColor:`#f6f8fa88`},".cm-activeLineGutter":{backgroundColor:`#eaeef2`},".cm-cursor":{borderLeftColor:`#1f2328`},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, ::selection":{backgroundColor:`#cfe3ff`}}),S(C,{fallback:!0})],I=e=>e?o.oneDark:F,L=c.of([{key:`Mod-Enter`,preventDefault:!0,run:()=>(e.onRun?.(),!0)},{key:`Shift-Enter`,preventDefault:!0,run:()=>(e.onRun?.(),!0)}]),R=e.dark,z=e.readOnly,B=e.language??[],V=t=>g.create({doc:t,extensions:[l(),d(),f(),y(),E(),p(),g.allowMultipleSelections.of(!0),w(),T(),k(),O(),m(),h(),u(),L,c.of([...A,...v,...b,...D,...j,x]),s.lineWrapping,P.of(B),M.of(I(R)),N.of(g.readOnly.of(z)),s.updateListener.of(t=>{t.docChanged&&e.onChange?.(t.state.doc.toString())})]}),H=new s({parent:e.parent,state:V(e.doc)}),U=new Map,W=e.name??``;return{fallback:!1,getCode:()=>H.state.doc.toString(),setCode(e){H.dispatch({changes:{from:0,to:H.state.doc.length,insert:e}})},openFile(e,t){if(e===W)return;U.set(W,H.state);let n=U.get(e);H.setState(n??V(t)),W=e,n&&H.dispatch({effects:[M.reconfigure(I(R)),N.reconfigure(g.readOnly.of(z)),P.reconfigure(B)]})},fileCode(e,t){if(e===W)return H.state.doc.toString();let n=U.get(e);return n?n.doc.toString():t},forgetFiles(e){for(let t of[...U.keys()])e.includes(t)||U.delete(t)},setTheme(e){R=e,H.dispatch({effects:M.reconfigure(I(R))})},setReadOnly(e){z=e,H.dispatch({effects:N.reconfigure(g.readOnly.of(z))})},setLanguage(e){B=e,H.dispatch({effects:P.reconfigure(B)})},focus:()=>H.focus(),destroy:()=>H.destroy()}}function l(e){let t=document.createElement(`textarea`);t.className=`cp-fallback-editor`,t.spellcheck=!1,t.value=e.doc,t.readOnly=e.readOnly,t.addEventListener(`input`,()=>e.onChange?.(t.value)),t.addEventListener(`keydown`,t=>{(t.metaKey||t.ctrlKey)&&t.key===`Enter`&&(t.preventDefault(),e.onRun?.())}),e.parent.appendChild(t);let n=new Map,r=e.name??``;return{fallback:!0,getCode:()=>t.value,setCode:e=>{t.value=e},openFile(e,i){e!==r&&(n.set(r,t.value),t.value=n.get(e)??i,r=e)},fileCode(e,i){return e===r?t.value:n.get(e)??i},forgetFiles(e){for(let t of[...n.keys()])e.includes(t)||n.delete(t)},setTheme:()=>{},setReadOnly:e=>{t.readOnly=e},setLanguage:()=>{},focus:()=>t.focus(),destroy:()=>t.remove()}}var u=new Map,d=new Map;function f(e,t){u.set(e,t)}function p(){return[...u.keys()]}function m(e){let t=d.get(e);if(t)return t;let n=u.get(e);if(!n)return Promise.reject(Error(`Unknown runtime "${e}". Registered: ${p().join(`, `)||`none`}`));let r=n().catch(t=>{throw d.delete(e),t});return d.set(e,r),r}f(`python`,()=>import(`./pyodide-Crdd9em4.js`).then(e=>e.pythonRuntime)),f(`javascript`,()=>import(`./javascript-CX-lsX2u.js`).then(e=>e.javascriptRuntime)),f(`typescript`,()=>import(`./javascript-CX-lsX2u.js`).then(e=>e.typescriptRuntime)),f(`java`,()=>import(`./java-C6Gdqz5p.js`).then(e=>e.javaRuntime));var h=String.raw`
|
|
7
7
|
:host {
|
|
8
8
|
--cp-bg: #ffffff;
|
|
9
9
|
--cp-fg: #1f2328;
|