pyrepl-web 0.1.10 → 0.1.13
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/chunk-3vjhr6cq.js +16 -0
- package/dist/chunk-7hjm8rrn.js +36 -0
- package/dist/chunk-agmzdfvt.js +2 -0
- package/dist/chunk-cmrefyz7.js +2 -0
- package/dist/chunk-n46k5haq.js +3 -0
- package/dist/chunk-t9eg0wr0.js +1 -0
- package/dist/pyrepl.esm.js +529 -0
- package/dist/pyrepl.js +1 -560
- package/package.json +3 -3
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import"./chunk-cmrefyz7.js";var{URL:J,URLSearchParams:X}=globalThis;function F(s){return typeof s==="string"}function K(s){return typeof s==="object"&&s!==null}function w(s){return s===null}function Y(s){return s==null}function m(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}var S=/^([a-z0-9.+-]+:)/i,k=/:[0-9]*$/,H=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,Q=["<",">",'"',"`"," ","\r",`
|
|
2
|
+
`,"\t"],E=["{","}","|","\\","^","`"].concat(Q),N=["'"].concat(E),M=["%","/","?",";","#"].concat(N),D=["/","?","#"],tt=255,G=/^[+a-z0-9A-Z_-]{0,63}$/,st=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,ht={javascript:!0,"javascript:":!0},Z={javascript:!0,"javascript:":!0},R={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},B={parse(s){var o=decodeURIComponent;return(s+"").replace(/\+/g," ").split("&").filter(Boolean).reduce(function(t,n,a){var l=n.split("="),f=o(l[0]||""),h=o(l[1]||""),g=t[f];return t[f]=g===void 0?h:[].concat(g,h),t},{})},stringify(s){var o=encodeURIComponent;return Object.keys(s||{}).reduce(function(t,n){return[].concat(s[n]).forEach(function(a){t.push(o(n)+"="+o(a))}),t},[]).join("&").replace(/\s/g,"+")}};function I(s,o,t){if(s&&K(s)&&s instanceof m)return s;var n=new m;return n.parse(s,o,t),n}m.prototype.parse=function(s,o,t){if(!F(s))throw TypeError("Parameter 'url' must be a string, not "+typeof s);var n=s.indexOf("?"),a=n!==-1&&n<s.indexOf("#")?"?":"#",l=s.split(a),f=/\\/g;l[0]=l[0].replace(f,"/"),s=l.join(a);var h=s;if(h=h.trim(),!t&&s.split("#").length===1){var g=H.exec(h);if(g){if(this.path=h,this.href=h,this.pathname=g[1],g[2])if(this.search=g[2],o)this.query=B.parse(this.search.substr(1));else this.query=this.search.substr(1);else if(o)this.search="",this.query={};return this}}var p=S.exec(h);if(p){p=p[0];var A=p.toLowerCase();this.protocol=A,h=h.substr(p.length)}if(t||p||h.match(/^\/\/[^@\/]+@[^@\/]+/)){var C=h.substr(0,2)==="//";if(C&&!(p&&Z[p]))h=h.substr(2),this.slashes=!0}if(!Z[p]&&(C||p&&!R[p])){var c=-1;for(var r=0;r<D.length;r++){var b=h.indexOf(D[r]);if(b!==-1&&(c===-1||b<c))c=b}var P,u;if(c===-1)u=h.lastIndexOf("@");else u=h.lastIndexOf("@",c);if(u!==-1)P=h.slice(0,u),h=h.slice(u+1),this.auth=decodeURIComponent(P);c=-1;for(var r=0;r<M.length;r++){var b=h.indexOf(M[r]);if(b!==-1&&(c===-1||b<c))c=b}if(c===-1)c=h.length;this.host=h.slice(0,c),h=h.slice(c),this.parseHost(),this.hostname=this.hostname||"";var U=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!U){var e=this.hostname.split(/\./);for(var r=0,i=e.length;r<i;r++){var d=e[r];if(!d)continue;if(!d.match(G)){var y="";for(var O=0,L=d.length;O<L;O++)if(d.charCodeAt(O)>127)y+="x";else y+=d[O];if(!y.match(G)){var x=e.slice(0,r),q=e.slice(r+1),j=d.match(st);if(j)x.push(j[1]),q.unshift(j[2]);if(q.length)h="/"+q.join(".")+h;this.hostname=x.join(".");break}}}}if(this.hostname.length>tt)this.hostname="";else this.hostname=this.hostname.toLowerCase();if(!U)this.hostname=new J(`https://${this.hostname}`).hostname;var $=this.port?":"+this.port:"",V=this.hostname||"";if(this.host=V+$,this.href+=this.host,U){if(this.hostname=this.hostname.substr(1,this.hostname.length-2),h[0]!=="/")h="/"+h}}if(!ht[A])for(var r=0,i=N.length;r<i;r++){var v=N[r];if(h.indexOf(v)===-1)continue;var z=encodeURIComponent(v);if(z===v)z=escape(v);h=h.split(v).join(z)}var T=h.indexOf("#");if(T!==-1)this.hash=h.substr(T),h=h.slice(0,T);var _=h.indexOf("?");if(_!==-1){if(this.search=h.substr(_),this.query=h.substr(_+1),o)this.query=B.parse(this.query);h=h.slice(0,_)}else if(o)this.search="",this.query={};if(h)this.pathname=h;if(R[A]&&this.hostname&&!this.pathname)this.pathname="/";if(this.pathname||this.search){var $=this.pathname||"",W=this.search||"";this.path=$+W}return this.href=this.format(),this};function et(s){if(F(s))s=I(s);if(!(s instanceof m))return m.prototype.format.call(s);return s.format()}m.prototype.format=function(){var s=this.auth||"";if(s)s=encodeURIComponent(s),s=s.replace(/%3A/i,":"),s+="@";var o=this.protocol||"",t=this.pathname||"",n=this.hash||"",a=!1,l="";if(this.host)a=s+this.host;else if(this.hostname){if(a=s+(this.hostname.indexOf(":")===-1?this.hostname:"["+this.hostname+"]"),this.port)a+=":"+this.port}if(this.query&&K(this.query)&&Object.keys(this.query).length)l=B.stringify(this.query);var f=this.search||l&&"?"+l||"";if(o&&o.substr(-1)!==":")o+=":";if(this.slashes||(!o||R[o])&&a!==!1){if(a="//"+(a||""),t&&t.charAt(0)!=="/")t="/"+t}else if(!a)a="";if(n&&n.charAt(0)!=="#")n="#"+n;if(f&&f.charAt(0)!=="?")f="?"+f;return t=t.replace(/[?#]/g,function(h){return encodeURIComponent(h)}),f=f.replace("#","%23"),o+a+t+f+n};function ot(s,o){return I(s,!1,!0).resolve(o)}m.prototype.resolve=function(s){return this.resolveObject(I(s,!1,!0)).format()};function nt(s,o){if(!s)return o;return I(s,!1,!0).resolveObject(o)}m.prototype.resolveObject=function(s){if(F(s)){var o=new m;o.parse(s,!1,!0),s=o}var t=new m,n=Object.keys(this);for(var a=0;a<n.length;a++){var l=n[a];t[l]=this[l]}if(t.hash=s.hash,s.href==="")return t.href=t.format(),t;if(s.slashes&&!s.protocol){var f=Object.keys(s);for(var h=0;h<f.length;h++){var g=f[h];if(g!=="protocol")t[g]=s[g]}if(R[t.protocol]&&t.hostname&&!t.pathname)t.path=t.pathname="/";return t.href=t.format(),t}if(s.protocol&&s.protocol!==t.protocol){if(!R[s.protocol]){var p=Object.keys(s);for(var A=0;A<p.length;A++){var C=p[A];t[C]=s[C]}return t.href=t.format(),t}if(t.protocol=s.protocol,!s.host&&!Z[s.protocol]){var i=(s.pathname||"").split("/");while(i.length&&!(s.host=i.shift()));if(!s.host)s.host="";if(!s.hostname)s.hostname="";if(i[0]!=="")i.unshift("");if(i.length<2)i.unshift("");t.pathname=i.join("/")}else t.pathname=s.pathname;if(t.search=s.search,t.query=s.query,t.host=s.host||"",t.auth=s.auth,t.hostname=s.hostname||s.host,t.port=s.port,t.pathname||t.search){var c=t.pathname||"",r=t.search||"";t.path=c+r}return t.slashes=t.slashes||s.slashes,t.href=t.format(),t}var b=t.pathname&&t.pathname.charAt(0)==="/",P=s.host||s.pathname&&s.pathname.charAt(0)==="/",u=P||b||t.host&&s.pathname,U=u,e=t.pathname&&t.pathname.split("/")||[],i=s.pathname&&s.pathname.split("/")||[],d=t.protocol&&!R[t.protocol];if(d){if(t.hostname="",t.port=null,t.host)if(e[0]==="")e[0]=t.host;else e.unshift(t.host);if(t.host="",s.protocol){if(s.hostname=null,s.port=null,s.host)if(i[0]==="")i[0]=s.host;else i.unshift(s.host);s.host=null}u=u&&(i[0]===""||e[0]==="")}if(P)t.host=s.host||s.host===""?s.host:t.host,t.hostname=s.hostname||s.hostname===""?s.hostname:t.hostname,t.search=s.search,t.query=s.query,e=i;else if(i.length){if(!e)e=[];e.pop(),e=e.concat(i),t.search=s.search,t.query=s.query}else if(!Y(s.search)){if(d){t.hostname=t.host=e.shift();var y=t.host&&t.host.indexOf("@")>0?t.host.split("@"):!1;if(y)t.auth=y.shift(),t.host=t.hostname=y.shift()}if(t.search=s.search,t.query=s.query,!w(t.pathname)||!w(t.search))t.path=(t.pathname?t.pathname:"")+(t.search?t.search:"");return t.href=t.format(),t}if(!e.length){if(t.pathname=null,t.search)t.path="/"+t.search;else t.path=null;return t.href=t.format(),t}var O=e.slice(-1)[0],L=(t.host||s.host||e.length>1)&&(O==="."||O==="..")||O==="",x=0;for(var q=e.length;q>=0;q--)if(O=e[q],O===".")e.splice(q,1);else if(O==="..")e.splice(q,1),x++;else if(x)e.splice(q,1),x--;if(!u&&!U)for(;x--;x)e.unshift("..");if(u&&e[0]!==""&&(!e[0]||e[0].charAt(0)!=="/"))e.unshift("");if(L&&e.join("/").substr(-1)!=="/")e.push("");var j=e[0]===""||e[0]&&e[0].charAt(0)==="/";if(d){t.hostname=t.host=j?"":e.length?e.shift():"";var y=t.host&&t.host.indexOf("@")>0?t.host.split("@"):!1;if(y)t.auth=y.shift(),t.host=t.hostname=y.shift()}if(u=u||t.host&&e.length,u&&!j)e.unshift("");if(!e.length)t.pathname=null,t.path=null;else t.pathname=e.join("/");if(!w(t.pathname)||!w(t.search))t.path=(t.pathname?t.pathname:"")+(t.search?t.search:"");return t.auth=s.auth||t.auth,t.slashes=t.slashes||s.slashes,t.href=t.format(),t};m.prototype.parseHost=function(){var s=this.host,o=k.exec(s);if(o){if(o=o[0],o!==":")this.port=o.substr(1);s=s.substr(0,s.length-o.length)}if(s)this.hostname=s};var at={parse:I,resolve:ot,resolveObject:nt,format:et,Url:m,URL:J,URLSearchParams:X};export{nt as resolveObject,ot as resolve,I as parse,et as format,at as default,m as Url,X as URLSearchParams,J as URL};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var j=Object.create;var{getPrototypeOf:k,defineProperty:e,getOwnPropertyNames:h,getOwnPropertyDescriptor:l}=Object,i=Object.prototype.hasOwnProperty;var m=(a,b,c)=>{c=a!=null?j(k(a)):{};let d=b||!a||!a.__esModule?e(c,"default",{value:a,enumerable:!0}):c;for(let f of h(a))if(!i.call(d,f))e(d,f,{get:()=>a[f],enumerable:!0});return d},g=new WeakMap,n=(a)=>{var b=g.get(a),c;if(b)return b;if(b=e({},"__esModule",{value:!0}),a&&typeof a==="object"||typeof a==="function")h(a).map((d)=>!i.call(b,d)&&e(b,d,{get:()=>a[d],enumerable:!(c=l(a,d))||c.enumerable}));return g.set(a,b),b},o=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var p=(a,b)=>{for(var c in b)e(a,c,{get:b[c],enumerable:!0,configurable:!0,set:(d)=>b[c]=()=>d})};var q=(a,b)=>()=>(a&&(b=a(a=0)),b);var r=((a)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(b,c)=>(typeof require<"u"?require:b)[c]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});
|
|
2
|
+
export{m as a,n as b,o as c,p as d,q as e,r as f};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{a as O,f as j}from"./chunk-cmrefyz7.js";var __dirname="/home/runner/work/pyrepl-web/pyrepl-web/node_modules/pyodide";var U0=Object.defineProperty,B=(G,Q)=>U0(G,"name",{value:Q,configurable:!0}),f=((G)=>j)(function(G){return j.apply(this,arguments)}),F0=(()=>{for(var G=new Uint8Array(128),Q=0;Q<64;Q++)G[Q<26?Q+65:Q<52?Q+71:Q<62?Q-4:Q*4-205]=Q;return(W)=>{for(var z=W.length,X=new Uint8Array((z-(W[z-1]=="=")-(W[z-2]=="="))*3/4|0),Z=0,H=0;Z<z;){var J=G[W.charCodeAt(Z++)],K=G[W.charCodeAt(Z++)],M=G[W.charCodeAt(Z++)],V=G[W.charCodeAt(Z++)];X[H++]=J<<2|K>>4,X[H++]=K<<4|M>>2,X[H++]=M<<6|V}return X}})();function u(G){return!isNaN(parseFloat(G))&&isFinite(G)}B(u,"_isNumber");function T(G){return G.charAt(0).toUpperCase()+G.substring(1)}B(T,"_capitalize");function b(G){return function(){return this[G]}}B(b,"_getter");var F=["isConstructor","isEval","isNative","isToplevel"],k=["columnNumber","lineNumber"],I=["fileName","functionName","source"],k0=["args"],I0=["evalOrigin"],E=F.concat(k,I,k0,I0);function C(G){if(G)for(var Q=0;Q<E.length;Q++)G[E[Q]]!==void 0&&this["set"+T(E[Q])](G[E[Q]])}B(C,"StackFrame");C.prototype={getArgs:B(function(){return this.args},"getArgs"),setArgs:B(function(G){if(Object.prototype.toString.call(G)!=="[object Array]")throw TypeError("Args must be an Array");this.args=G},"setArgs"),getEvalOrigin:B(function(){return this.evalOrigin},"getEvalOrigin"),setEvalOrigin:B(function(G){if(G instanceof C)this.evalOrigin=G;else if(G instanceof Object)this.evalOrigin=new C(G);else throw TypeError("Eval Origin must be an Object or StackFrame")},"setEvalOrigin"),toString:B(function(){var G=this.getFileName()||"",Q=this.getLineNumber()||"",W=this.getColumnNumber()||"",z=this.getFunctionName()||"";return this.getIsEval()?G?"[eval] ("+G+":"+Q+":"+W+")":"[eval]:"+Q+":"+W:z?z+" ("+G+":"+Q+":"+W+")":G+":"+Q+":"+W},"toString")};C.fromString=B(function(G){var Q=G.indexOf("("),W=G.lastIndexOf(")"),z=G.substring(0,Q),X=G.substring(Q+1,W).split(","),Z=G.substring(W+1);if(Z.indexOf("@")===0)var H=/@(.+?)(?::(\d+))?(?::(\d+))?$/.exec(Z,""),J=H[1],K=H[2],M=H[3];return new C({functionName:z,args:X||void 0,fileName:J,lineNumber:K||void 0,columnNumber:M||void 0})},"StackFrame$$fromString");for(x=0;x<F.length;x++)C.prototype["get"+T(F[x])]=b(F[x]),C.prototype["set"+T(F[x])]=function(G){return function(Q){this[G]=!!Q}}(F[x]);var x;for(A=0;A<k.length;A++)C.prototype["get"+T(k[A])]=b(k[A]),C.prototype["set"+T(k[A])]=function(G){return function(Q){if(!u(Q))throw TypeError(G+" must be a Number");this[G]=Number(Q)}}(k[A]);var A;for(L=0;L<I.length;L++)C.prototype["get"+T(I[L])]=b(I[L]),C.prototype["set"+T(I[L])]=function(G){return function(Q){this[G]=String(Q)}}(I[L]);var L,g=C;function c(){var G=/^\s*at .*(\S+:\d+|\(native\))/m,Q=/^(eval@)?(\[native code])?$/;return{parse:B(function(W){if(W.stack&&W.stack.match(G))return this.parseV8OrIE(W);if(W.stack)return this.parseFFOrSafari(W);throw Error("Cannot parse given Error object")},"ErrorStackParser$$parse"),extractLocation:B(function(W){if(W.indexOf(":")===-1)return[W];var z=/(.+?)(?::(\d+))?(?::(\d+))?$/,X=z.exec(W.replace(/[()]/g,""));return[X[1],X[2]||void 0,X[3]||void 0]},"ErrorStackParser$$extractLocation"),parseV8OrIE:B(function(W){var z=W.stack.split(`
|
|
2
|
+
`).filter(function(X){return!!X.match(G)},this);return z.map(function(X){X.indexOf("(eval ")>-1&&(X=X.replace(/eval code/g,"eval").replace(/(\(eval at [^()]*)|(,.*$)/g,""));var Z=X.replace(/^\s+/,"").replace(/\(eval code/g,"(").replace(/^.*?\s+/,""),H=Z.match(/ (\(.+\)$)/);Z=H?Z.replace(H[0],""):Z;var J=this.extractLocation(H?H[1]:Z),K=H&&Z||void 0,M=["eval","<anonymous>"].indexOf(J[0])>-1?void 0:J[0];return new g({functionName:K,fileName:M,lineNumber:J[1],columnNumber:J[2],source:X})},this)},"ErrorStackParser$$parseV8OrIE"),parseFFOrSafari:B(function(W){var z=W.stack.split(`
|
|
3
|
+
`).filter(function(X){return!X.match(Q)},this);return z.map(function(X){if(X.indexOf(" > eval")>-1&&(X=X.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1")),X.indexOf("@")===-1&&X.indexOf(":")===-1)return new g({functionName:X});var Z=/((.*".+"[^@]*)?[^@]*)(?:@)/,H=X.match(Z),J=H&&H[1]?H[1]:void 0,K=this.extractLocation(X.replace(Z,""));return new g({functionName:J,fileName:K[0],lineNumber:K[1],columnNumber:K[2],source:X})},this)},"ErrorStackParser$$parseFFOrSafari")}}B(c,"ErrorStackParser");var N0=new c,R0=N0;function d(){if(typeof API<"u"&&API!==globalThis.API)return API.runtimeEnv;let G=typeof Bun<"u",Q=typeof Deno<"u",W=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string"&&!1,z=typeof navigator=="object"&&typeof navigator.userAgent=="string"&&navigator.userAgent.indexOf("Chrome")===-1&&navigator.userAgent.indexOf("Safari")>-1;return l({IN_BUN:G,IN_DENO:Q,IN_NODE:W,IN_SAFARI:z,IN_SHELL:typeof read=="function"&&typeof load=="function"})}B(d,"getGlobalRuntimeEnv");var Y=d();function l(G){let Q=G.IN_NODE&&typeof p<"u"&&P0&&typeof f=="function"&&typeof __dirname=="string",W=G.IN_NODE&&!Q,z=!G.IN_NODE&&!G.IN_DENO&&!G.IN_BUN,X=z&&typeof window<"u"&&typeof window.document<"u"&&typeof document.createElement=="function"&&"sessionStorage"in window&&typeof globalThis.importScripts!="function",Z=z&&typeof globalThis.WorkerGlobalScope<"u"&&typeof globalThis.self<"u"&&globalThis.self instanceof globalThis.WorkerGlobalScope;return{...G,IN_BROWSER:z,IN_BROWSER_MAIN_THREAD:X,IN_BROWSER_WEB_WORKER:Z,IN_NODE_COMMONJS:Q,IN_NODE_ESM:W}}B(l,"calculateDerivedFlags");var s,P,a,m,v;async function y(){if(!Y.IN_NODE||(s=(await import("./chunk-agmzdfvt.js")).default,m=await import("node:fs"),v=await import("node:fs/promises"),a=(await import("node:vm")).default,P=await import("./chunk-t9eg0wr0.js"),_=P.sep,typeof f<"u"))return;let G=m,Q=await import("./chunk-3vjhr6cq.js"),W=await import("ws"),z=await import("node:child_process"),X={fs:G,crypto:Q,ws:W,child_process:z};globalThis.require=function(Z){return X[Z]}}B(y,"initNodeModules");function i(G,Q){return P.resolve(Q||".",G)}B(i,"node_resolvePath");function o(G,Q){return Q===void 0&&(Q=location),new URL(G,Q).toString()}B(o,"browser_resolvePath");var S;Y.IN_NODE?S=i:Y.IN_SHELL?S=B((G)=>G,"resolvePath"):S=o;var _;Y.IN_NODE||(_="/");function n(G,Q){return G.startsWith("file://")&&(G=G.slice(7)),G.includes("://")?{response:fetch(G)}:{binary:v.readFile(G).then((W)=>new Uint8Array(W.buffer,W.byteOffset,W.byteLength))}}B(n,"node_getBinaryResponse");function r(G,Q){if(G.startsWith("file://")&&(G=G.slice(7)),G.includes("://"))throw Error("Shell cannot fetch urls");return{binary:Promise.resolve(new Uint8Array(readbuffer(G)))}}B(r,"shell_getBinaryResponse");function t(G,Q){let W=new URL(G,location);return{response:fetch(W,Q?{integrity:Q}:{})}}B(t,"browser_getBinaryResponse");var w;Y.IN_NODE?w=n:Y.IN_SHELL?w=r:w=t;async function e(G,Q){let{response:W,binary:z}=w(G,Q);if(z)return z;let X=await W;if(!X.ok)throw Error(`Failed to load '${G}': request failed.`);return new Uint8Array(await X.arrayBuffer())}B(e,"loadBinaryFile");var N;if(Y.IN_BROWSER_MAIN_THREAD)N=B(async(G)=>await import(G),"loadScript");else if(Y.IN_BROWSER_WEB_WORKER)N=B(async(G)=>{try{globalThis.importScripts(G)}catch(Q){if(Q instanceof TypeError)await import(G);else throw Q}},"loadScript");else if(Y.IN_NODE)N=G0;else if(Y.IN_SHELL)N=load;else throw Error("Cannot determine runtime environment");async function G0(G){G.startsWith("file://")&&(G=G.slice(7)),G.includes("://")?a.runInThisContext(await(await fetch(G)).text()):await import(s.pathToFileURL(G).href)}B(G0,"nodeLoadScript");async function Q0(G){if(Y.IN_NODE){await y();let Q=await v.readFile(G,{encoding:"utf8"});return JSON.parse(Q)}else if(Y.IN_SHELL){let Q=read(G);return JSON.parse(Q)}else return await(await fetch(G)).json()}B(Q0,"loadLockFile");async function W0(){if(Y.IN_NODE_COMMONJS)return __dirname;let G;try{throw Error()}catch(z){G=z}let Q=R0.parse(G)[0].fileName;if(Y.IN_NODE&&!Q.startsWith("file://")&&(Q=`file://${Q}`),Y.IN_NODE_ESM){let z=await import("./chunk-t9eg0wr0.js");return(await import("./chunk-agmzdfvt.js")).fileURLToPath(z.dirname(Q))}let W=Q.lastIndexOf(_);if(W===-1)throw Error("Could not extract indexURL path from pyodide module location. Please pass the indexURL explicitly to loadPyodide.");return Q.slice(0,W)}B(W0,"calculateDirname");function X0(G){return G.substring(0,G.lastIndexOf("/")+1)||globalThis.location?.toString()||"."}B(X0,"calculateInstallBaseUrl");function Z0(G){let Q=G.FS,W=G.FS.filesystems.MEMFS,z=G.PATH,X={DIR_MODE:16895,FILE_MODE:33279,mount:B(function(Z){if(!Z.opts.fileSystemHandle)throw Error("opts.fileSystemHandle is required");return W.mount.apply(null,arguments)},"mount"),syncfs:B(async(Z,H,J)=>{try{let K=X.getLocalSet(Z),M=await X.getRemoteSet(Z),V=H?M:K,D=H?K:M;await X.reconcile(Z,V,D),J(null)}catch(K){J(K)}},"syncfs"),getLocalSet:B((Z)=>{let H=Object.create(null);function J(V){return V!=="."&&V!==".."}B(J,"isRealDir");function K(V){return(D)=>z.join2(V,D)}B(K,"toAbsolute");let M=Q.readdir(Z.mountpoint).filter(J).map(K(Z.mountpoint));for(;M.length;){let V=M.pop(),D=Q.stat(V);Q.isDir(D.mode)&&M.push.apply(M,Q.readdir(V).filter(J).map(K(V))),H[V]={timestamp:D.mtime,mode:D.mode}}return{type:"local",entries:H}},"getLocalSet"),getRemoteSet:B(async(Z)=>{let H=Object.create(null),J=await S0(Z.opts.fileSystemHandle);for(let[K,M]of J)K!=="."&&(H[z.join2(Z.mountpoint,K)]={timestamp:M.kind==="file"?new Date((await M.getFile()).lastModified):new Date,mode:M.kind==="file"?X.FILE_MODE:X.DIR_MODE});return{type:"remote",entries:H,handles:J}},"getRemoteSet"),loadLocalEntry:B((Z)=>{let H=Q.lookupPath(Z,{}).node,J=Q.stat(Z);if(Q.isDir(J.mode))return{timestamp:J.mtime,mode:J.mode};if(Q.isFile(J.mode))return H.contents=W.getFileDataAsTypedArray(H),{timestamp:J.mtime,mode:J.mode,contents:H.contents};throw Error("node type not supported")},"loadLocalEntry"),storeLocalEntry:B((Z,H)=>{if(Q.isDir(H.mode))Q.mkdirTree(Z,H.mode);else if(Q.isFile(H.mode))Q.writeFile(Z,H.contents,{canOwn:!0});else throw Error("node type not supported");Q.chmod(Z,H.mode),Q.utime(Z,H.timestamp,H.timestamp)},"storeLocalEntry"),removeLocalEntry:B((Z)=>{var H=Q.stat(Z);Q.isDir(H.mode)?Q.rmdir(Z):Q.isFile(H.mode)&&Q.unlink(Z)},"removeLocalEntry"),loadRemoteEntry:B(async(Z)=>{if(Z.kind==="file"){let H=await Z.getFile();return{contents:new Uint8Array(await H.arrayBuffer()),mode:X.FILE_MODE,timestamp:new Date(H.lastModified)}}else{if(Z.kind==="directory")return{mode:X.DIR_MODE,timestamp:new Date};throw Error("unknown kind: "+Z.kind)}},"loadRemoteEntry"),storeRemoteEntry:B(async(Z,H,J)=>{let K=Z.get(z.dirname(H)),M=Q.isFile(J.mode)?await K.getFileHandle(z.basename(H),{create:!0}):await K.getDirectoryHandle(z.basename(H),{create:!0});if(M.kind==="file"){let V=await M.createWritable();await V.write(J.contents),await V.close()}Z.set(H,M)},"storeRemoteEntry"),removeRemoteEntry:B(async(Z,H)=>{await Z.get(z.dirname(H)).removeEntry(z.basename(H)),Z.delete(H)},"removeRemoteEntry"),reconcile:B(async(Z,H,J)=>{let K=0,M=[];Object.keys(H.entries).forEach(function($){let q=H.entries[$],U=J.entries[$];(!U||Q.isFile(q.mode)&&q.timestamp.getTime()>U.timestamp.getTime())&&(M.push($),K++)}),M.sort();let V=[];if(Object.keys(J.entries).forEach(function($){H.entries[$]||(V.push($),K++)}),V.sort().reverse(),!K)return;let D=H.type==="remote"?H.handles:J.handles;for(let $ of M){let q=z.normalize($.replace(Z.mountpoint,"/")).substring(1);if(J.type==="local"){let U=D.get(q),L0=await X.loadRemoteEntry(U);X.storeLocalEntry($,L0)}else{let U=X.loadLocalEntry($);await X.storeRemoteEntry(D,q,U)}}for(let $ of V)if(J.type==="local")X.removeLocalEntry($);else{let q=z.normalize($.replace(Z.mountpoint,"/")).substring(1);await X.removeRemoteEntry(D,q)}},"reconcile")};G.FS.filesystems.NATIVEFS_ASYNC=X}B(Z0,"initializeNativeFS");var S0=B(async(G)=>{let Q=[];async function W(X){for await(let Z of X.values())Q.push(Z),Z.kind==="directory"&&await W(Z)}B(W,"collect"),await W(G);let z=new Map;z.set(".",G);for(let X of Q){let Z=(await G.resolve(X)).join("/");z.set(Z,X)}return z},"getFsHandles"),w0=F0("AGFzbQEAAAABDANfAGAAAW9gAW8BfwMDAgECByECD2NyZWF0ZV9zZW50aW5lbAAAC2lzX3NlbnRpbmVsAAEKEwIHAPsBAPsbCwkAIAD7GvsUAAs="),E0=async function(){if(!(globalThis.navigator&&(/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&typeof navigator.maxTouchPoints<"u"&&navigator.maxTouchPoints>1)))try{let G=await WebAssembly.compile(w0);return await WebAssembly.instantiate(G)}catch(G){if(G instanceof WebAssembly.CompileError)return;throw G}}();async function z0(){let G=await E0;if(G)return G.exports;let Q=Symbol("error marker");return{create_sentinel:B(()=>Q,"create_sentinel"),is_sentinel:B((W)=>W===Q,"is_sentinel")}}B(z0,"getSentinelImport");function B0(G){let Q={config:G,runtimeEnv:Y},W={noImageDecoding:!0,noAudioDecoding:!0,noWasmDecoding:!1,preRun:Y0(G),print:G.stdout,printErr:G.stderr,onExit(z){W.exitCode=z},thisProgram:G._sysExecutable,arguments:G.args,API:Q,locateFile:B((z)=>G.indexURL+z,"locateFile"),instantiateWasm:$0(G.indexURL)};return W}B(B0,"createSettings");function H0(G){return function(Q){let W="/";try{Q.FS.mkdirTree(G)}catch(z){console.error(`Error occurred while making a home directory '${G}':`),console.error(z),console.error(`Using '${W}' for a home directory instead`),G=W}Q.FS.chdir(G)}}B(H0,"createHomeDirectory");function J0(G){return function(Q){Object.assign(Q.ENV,G)}}B(J0,"setEnvironment");function K0(G){return G?[async(Q)=>{Q.addRunDependency("fsInitHook");try{await G(Q.FS,{sitePackages:Q.API.sitePackages})}finally{Q.removeRunDependency("fsInitHook")}}]:[]}B(K0,"callFsInitHook");function M0(G){let Q=G.HEAPU32[G._Py_Version>>>2],W=Q>>>24&255,z=Q>>>16&255,X=Q>>>8&255;return[W,z,X]}B(M0,"computeVersionTuple");function V0(G){let Q=e(G);return async(W)=>{W.API.pyVersionTuple=M0(W);let[z,X]=W.API.pyVersionTuple;W.FS.mkdirTree("/lib"),W.API.sitePackages=`/lib/python${z}.${X}/site-packages`,W.FS.mkdirTree(W.API.sitePackages),W.addRunDependency("install-stdlib");try{let Z=await Q;W.FS.writeFile(`/lib/python${z}${X}.zip`,Z)}catch(Z){console.error("Error occurred while installing the standard library:"),console.error(Z)}finally{W.removeRunDependency("install-stdlib")}}}B(V0,"installStdlib");function Y0(G){let Q;return G.stdLibURL!=null?Q=G.stdLibURL:Q=G.indexURL+"python_stdlib.zip",[V0(Q),H0(G.env.HOME),J0(G.env),Z0,...K0(G.fsInit)]}B(Y0,"getFileSystemInitializationFuncs");function $0(G){if(typeof WasmOffsetConverter<"u")return;let{binary:Q,response:W}=w(G+"pyodide.asm.wasm"),z=z0();return function(X,Z){return async function(){X.sentinel=await z;try{let H;W?H=await WebAssembly.instantiateStreaming(W,X):H=await WebAssembly.instantiate(await Q,X);let{instance:J,module:K}=H;Z(J,K)}catch(H){console.warn("wasm instantiation failed!"),console.warn(H)}}(),{}}}B($0,"getInstantiateWasmFunc");var b0="0.29.2";function R(G){return G===void 0||G.endsWith("/")?G:G+"/"}B(R,"withTrailingSlash");var h=b0;async function j0(G={}){if(await y(),G.lockFileContents&&G.lockFileURL)throw Error("Can't pass both lockFileContents and lockFileURL");let Q=G.indexURL||await W0();if(Q=R(S(Q)),G.packageBaseUrl=R(G.packageBaseUrl),G.cdnUrl=R(G.packageBaseUrl??`https://cdn.jsdelivr.net/pyodide/v${h}/full/`),!G.lockFileContents){let X=G.lockFileURL??Q+"pyodide-lock.json";G.lockFileContents=Q0(X),G.packageBaseUrl??=X0(X)}G.indexURL=Q,G.packageCacheDir&&(G.packageCacheDir=R(S(G.packageCacheDir)));let W={fullStdLib:!1,jsglobals:globalThis,stdin:globalThis.prompt?()=>globalThis.prompt():void 0,args:[],env:{},packages:[],packageCacheDir:G.packageBaseUrl,enableRunUntilComplete:!0,checkAPIVersion:!0,BUILD_ID:"02af97d1069c4309880e46f2948861ea1faae5dbb49c20d5d5970aa9ae912fd4"},z=Object.assign(W,G);return z.env.HOME??="/home/pyodide",z.env.PYTHONINSPECT??="1",z}B(j0,"initializeConfiguration");function C0(G){let Q=B0(G),W=Q.API;return W.lockFilePromise=Promise.resolve(G.lockFileContents),Q}B(C0,"createEmscriptenSettings");async function D0(G){if(typeof _createPyodideModule!="function"){let Q=`${G.indexURL}pyodide.asm.js`;await N(Q)}}B(D0,"loadWasmScript");async function O0(G,Q){if(!G._loadSnapshot)return;let W=await G._loadSnapshot,z=ArrayBuffer.isView(W)?W:new Uint8Array(W);return Q.noInitialRun=!0,Q.INITIAL_MEMORY=z.length,z}B(O0,"prepareSnapshot");async function T0(G){let Q=await _createPyodideModule(G);if(G.exitCode!==void 0)throw new Q.ExitStatus(G.exitCode);return Q}B(T0,"createPyodideModule");function q0(G,Q){let W=G.API;if(Q.pyproxyToStringRepr&&W.setPyProxyToStringMethod(!0),Q.convertNullToNone&&W.setCompatNullToNone(!0),Q.toJsLiteralMap&&W.setCompatToJsLiteralMap(!0),W.version!==h&&Q.checkAPIVersion)throw Error(`Pyodide version does not match: '${h}' <==> '${W.version}'. If you updated the Pyodide version, make sure you also updated the 'indexURL' parameter passed to loadPyodide.`);G.locateFile=(z)=>{throw z.endsWith(".so")?Error(`Failed to find dynamic library "${z}"`):Error(`Unexpected call to locateFile("${z}")`)}}B(q0,"configureAPI");function x0(G,Q,W){let z=G.API,X;return Q&&(X=z.restoreSnapshot(Q)),z.finalizeBootstrap(X,W._snapshotDeserializer)}B(x0,"bootstrapPyodide");async function A0(G,Q){let W=G._api;return W.sys.path.insert(0,""),W._pyodide.set_excepthook(),await W.packageIndexReady,W.initializeStreams(Q.stdin,Q.stdout,Q.stderr),G}B(A0,"finalizeSetup");async function g0(G={}){let Q=await j0(G),W=C0(Q);await D0(Q);let z=await O0(Q,W),X=await T0(W);q0(X,Q);let Z=x0(X,z,Q);return await A0(Z,Q)}B(g0,"loadPyodide");export{h as version,g0 as loadPyodide};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./chunk-cmrefyz7.js";function a(e){if(typeof e!=="string")throw TypeError("Path must be a string. Received "+JSON.stringify(e))}function A(e,r){var n="",l=0,f=-1,i=0,s;for(var t=0;t<=e.length;++t){if(t<e.length)s=e.charCodeAt(t);else if(s===47)break;else s=47;if(s===47){if(f===t-1||i===1);else if(f!==t-1&&i===2){if(n.length<2||l!==2||n.charCodeAt(n.length-1)!==46||n.charCodeAt(n.length-2)!==46){if(n.length>2){var u=n.lastIndexOf("/");if(u!==n.length-1){if(u===-1)n="",l=0;else n=n.slice(0,u),l=n.length-1-n.lastIndexOf("/");f=t,i=0;continue}}else if(n.length===2||n.length===1){n="",l=0,f=t,i=0;continue}}if(r){if(n.length>0)n+="/..";else n="..";l=2}}else{if(n.length>0)n+="/"+e.slice(f+1,t);else n=e.slice(f+1,t);l=t-f-1}f=t,i=0}else if(s===46&&i!==-1)++i;else i=-1}return n}function h(e,r){var n=r.dir||r.root,l=r.base||(r.name||"")+(r.ext||"");if(!n)return l;if(n===r.root)return n+l;return n+e+l}function d(){var e="",r=!1,n;for(var l=arguments.length-1;l>=-1&&!r;l--){var f;if(l>=0)f=arguments[l];else{if(n===void 0)n=process.cwd();f=n}if(a(f),f.length===0)continue;e=f+"/"+e,r=f.charCodeAt(0)===47}if(e=A(e,!r),r)if(e.length>0)return"/"+e;else return"/";else if(e.length>0)return e;else return"."}function m(e){if(a(e),e.length===0)return".";var r=e.charCodeAt(0)===47,n=e.charCodeAt(e.length-1)===47;if(e=A(e,!r),e.length===0&&!r)e=".";if(e.length>0&&n)e+="/";if(r)return"/"+e;return e}function b(e){return a(e),e.length>0&&e.charCodeAt(0)===47}function k(){if(arguments.length===0)return".";var e;for(var r=0;r<arguments.length;++r){var n=arguments[r];if(a(n),n.length>0)if(e===void 0)e=n;else e+="/"+n}if(e===void 0)return".";return m(e)}function y(e,r){if(a(e),a(r),e===r)return"";if(e=d(e),r=d(r),e===r)return"";var n=1;for(;n<e.length;++n)if(e.charCodeAt(n)!==47)break;var l=e.length,f=l-n,i=1;for(;i<r.length;++i)if(r.charCodeAt(i)!==47)break;var s=r.length,t=s-i,u=f<t?f:t,c=-1,o=0;for(;o<=u;++o){if(o===u){if(t>u){if(r.charCodeAt(i+o)===47)return r.slice(i+o+1);else if(o===0)return r.slice(i+o)}else if(f>u){if(e.charCodeAt(n+o)===47)c=o;else if(o===0)c=0}break}var v=e.charCodeAt(n+o),C=r.charCodeAt(i+o);if(v!==C)break;else if(v===47)c=o}var g="";for(o=n+c+1;o<=l;++o)if(o===l||e.charCodeAt(o)===47)if(g.length===0)g+="..";else g+="/..";if(g.length>0)return g+r.slice(i+c);else{if(i+=c,r.charCodeAt(i)===47)++i;return r.slice(i)}}function S(e){return e}function w(e){if(a(e),e.length===0)return".";var r=e.charCodeAt(0),n=r===47,l=-1,f=!0;for(var i=e.length-1;i>=1;--i)if(r=e.charCodeAt(i),r===47){if(!f){l=i;break}}else f=!1;if(l===-1)return n?"/":".";if(n&&l===1)return"//";return e.slice(0,l)}function P(e,r){if(r!==void 0&&typeof r!=="string")throw TypeError('"ext" argument must be a string');a(e);var n=0,l=-1,f=!0,i;if(r!==void 0&&r.length>0&&r.length<=e.length){if(r.length===e.length&&r===e)return"";var s=r.length-1,t=-1;for(i=e.length-1;i>=0;--i){var u=e.charCodeAt(i);if(u===47){if(!f){n=i+1;break}}else{if(t===-1)f=!1,t=i+1;if(s>=0)if(u===r.charCodeAt(s)){if(--s===-1)l=i}else s=-1,l=t}}if(n===l)l=t;else if(l===-1)l=e.length;return e.slice(n,l)}else{for(i=e.length-1;i>=0;--i)if(e.charCodeAt(i)===47){if(!f){n=i+1;break}}else if(l===-1)f=!1,l=i+1;if(l===-1)return"";return e.slice(n,l)}}function D(e){a(e);var r=-1,n=0,l=-1,f=!0,i=0;for(var s=e.length-1;s>=0;--s){var t=e.charCodeAt(s);if(t===47){if(!f){n=s+1;break}continue}if(l===-1)f=!1,l=s+1;if(t===46){if(r===-1)r=s;else if(i!==1)i=1}else if(r!==-1)i=-1}if(r===-1||l===-1||i===0||i===1&&r===l-1&&r===n+1)return"";return e.slice(r,l)}function L(e){if(e===null||typeof e!=="object")throw TypeError('The "pathObject" argument must be of type Object. Received type '+typeof e);return h("/",e)}function T(e){a(e);var r={root:"",dir:"",base:"",ext:"",name:""};if(e.length===0)return r;var n=e.charCodeAt(0),l=n===47,f;if(l)r.root="/",f=1;else f=0;var i=-1,s=0,t=-1,u=!0,c=e.length-1,o=0;for(;c>=f;--c){if(n=e.charCodeAt(c),n===47){if(!u){s=c+1;break}continue}if(t===-1)u=!1,t=c+1;if(n===46){if(i===-1)i=c;else if(o!==1)o=1}else if(i!==-1)o=-1}if(i===-1||t===-1||o===0||o===1&&i===t-1&&i===s+1){if(t!==-1)if(s===0&&l)r.base=r.name=e.slice(1,t);else r.base=r.name=e.slice(s,t)}else{if(s===0&&l)r.name=e.slice(1,i),r.base=e.slice(1,t);else r.name=e.slice(s,i),r.base=e.slice(s,t);r.ext=e.slice(i,t)}if(s>0)r.dir=e.slice(0,s-1);else if(l)r.dir="/";return r}var R="/",_=":",z=((e)=>(e.posix=e,e))({resolve:d,normalize:m,isAbsolute:b,join:k,relative:y,_makeLong:S,dirname:w,basename:P,extname:D,format:L,parse:T,sep:R,delimiter:_,win32:null,posix:null}),E=z;export{R as sep,d as resolve,y as relative,z as posix,T as parse,m as normalize,k as join,b as isAbsolute,L as format,D as extname,w as dirname,_ as delimiter,E as default,P as basename,S as _makeLong};
|
|
@@ -0,0 +1,529 @@
|
|
|
1
|
+
import{a as v,f as g}from"./chunk-cmrefyz7.js";var x=`from codeop import compile_command
|
|
2
|
+
import sys
|
|
3
|
+
from _pyrepl.console import Console, Event
|
|
4
|
+
from collections import deque
|
|
5
|
+
import js
|
|
6
|
+
from pyodide.ffi import create_proxy
|
|
7
|
+
|
|
8
|
+
# ANSI prompt strings
|
|
9
|
+
PS1 = "\\x1b[32m>>> \\x1b[0m"
|
|
10
|
+
PS2 = "\\x1b[32m... \\x1b[0m"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class BrowserConsole(Console):
|
|
14
|
+
def __init__(self, term):
|
|
15
|
+
# term is the xterm.js Terminal instance passed from JS
|
|
16
|
+
self.term = term
|
|
17
|
+
self.event_queue = deque()
|
|
18
|
+
self.encoding = "utf-8"
|
|
19
|
+
self.screen = []
|
|
20
|
+
self.posxy = (0, 0)
|
|
21
|
+
self.height, self.width = self.getheightwidth()
|
|
22
|
+
self._resolve_input = None
|
|
23
|
+
|
|
24
|
+
def getheightwidth(self):
|
|
25
|
+
return self.term.rows, self.term.cols
|
|
26
|
+
|
|
27
|
+
def refresh(self, screen, xy):
|
|
28
|
+
# TODO: redraw screen
|
|
29
|
+
pass
|
|
30
|
+
|
|
31
|
+
def prepare(self):
|
|
32
|
+
# TODO: setup
|
|
33
|
+
pass
|
|
34
|
+
|
|
35
|
+
def restore(self):
|
|
36
|
+
# TODO: teardown
|
|
37
|
+
pass
|
|
38
|
+
|
|
39
|
+
def move_cursor(self, x, y):
|
|
40
|
+
self.term.write(f"\\x1b[{y + 1};{x + 1}H")
|
|
41
|
+
self.posxy = (x, y)
|
|
42
|
+
|
|
43
|
+
def set_cursor_vis(self, visible):
|
|
44
|
+
self.term.write("\\x1b[?25h" if visible else "\\x1b[?25l")
|
|
45
|
+
|
|
46
|
+
def beep(self):
|
|
47
|
+
self.term.write("\\x07")
|
|
48
|
+
|
|
49
|
+
def clear(self):
|
|
50
|
+
self.term.write("\\x1b[2J\\x1b[H")
|
|
51
|
+
self.screen = []
|
|
52
|
+
self.posxy = (0, 0)
|
|
53
|
+
|
|
54
|
+
def flushoutput(self):
|
|
55
|
+
pass # xterm.js writes immediately
|
|
56
|
+
|
|
57
|
+
def finish(self):
|
|
58
|
+
pass
|
|
59
|
+
|
|
60
|
+
def forgetinput(self):
|
|
61
|
+
self.event_queue.clear()
|
|
62
|
+
|
|
63
|
+
def push_char(self, char):
|
|
64
|
+
self.event_queue.append(char)
|
|
65
|
+
|
|
66
|
+
if self._resolve_input:
|
|
67
|
+
resolve = self._resolve_input
|
|
68
|
+
self._resolve_input = None
|
|
69
|
+
resolve()
|
|
70
|
+
|
|
71
|
+
def getpending(self):
|
|
72
|
+
data = ""
|
|
73
|
+
raw = b""
|
|
74
|
+
while self.event_queue:
|
|
75
|
+
c = self.event_queue.popleft()
|
|
76
|
+
if isinstance(c, bytes):
|
|
77
|
+
raw += c
|
|
78
|
+
data += c.decode(self.encoding, errors="replace")
|
|
79
|
+
else:
|
|
80
|
+
raw += bytes([c])
|
|
81
|
+
data += chr(c)
|
|
82
|
+
return Event("key", data, raw)
|
|
83
|
+
|
|
84
|
+
def wait(self, timeout=None):
|
|
85
|
+
return len(self.event_queue) > 0
|
|
86
|
+
|
|
87
|
+
async def get_event(self, block=True):
|
|
88
|
+
if not block and not self.event_queue:
|
|
89
|
+
return None
|
|
90
|
+
|
|
91
|
+
while not self.event_queue:
|
|
92
|
+
promise = js.Promise.new(
|
|
93
|
+
create_proxy(
|
|
94
|
+
lambda resolve, reject: setattr(self, "_resolve_input", resolve)
|
|
95
|
+
)
|
|
96
|
+
)
|
|
97
|
+
await promise
|
|
98
|
+
|
|
99
|
+
char = self.event_queue.popleft()
|
|
100
|
+
if isinstance(char, int):
|
|
101
|
+
char_str = chr(char)
|
|
102
|
+
raw = bytes([char])
|
|
103
|
+
else:
|
|
104
|
+
char_str = char
|
|
105
|
+
raw = char.encode(self.encoding)
|
|
106
|
+
event = Event("key", char_str, raw)
|
|
107
|
+
return event
|
|
108
|
+
|
|
109
|
+
def repaint(self):
|
|
110
|
+
pass
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
async def start_repl():
|
|
114
|
+
# Create a new console for this terminal instance
|
|
115
|
+
browser_console = BrowserConsole(js.term)
|
|
116
|
+
|
|
117
|
+
# Capture startup script before JS moves to next REPL and overwrites it
|
|
118
|
+
startup_script = getattr(js, "pyreplStartupScript", None)
|
|
119
|
+
theme_name = getattr(js, "pyreplTheme", "catppuccin-mocha")
|
|
120
|
+
info_line = getattr(js, "pyreplInfo", "Python 3.13 (Pyodide)")
|
|
121
|
+
readonly = getattr(js, "pyreplReadonly", False)
|
|
122
|
+
|
|
123
|
+
# Expose to JS so it can send input (signals JS can proceed to next REPL)
|
|
124
|
+
js.currentBrowserConsole = browser_console
|
|
125
|
+
|
|
126
|
+
import micropip
|
|
127
|
+
import rlcompleter
|
|
128
|
+
import re
|
|
129
|
+
import asyncio
|
|
130
|
+
|
|
131
|
+
# Lazy-load Pygments in background while REPL starts
|
|
132
|
+
pygments_loaded = False
|
|
133
|
+
lexer = None
|
|
134
|
+
formatter = None
|
|
135
|
+
|
|
136
|
+
async def load_pygments():
|
|
137
|
+
nonlocal pygments_loaded, lexer, formatter
|
|
138
|
+
try:
|
|
139
|
+
await micropip.install("catppuccin[pygments]")
|
|
140
|
+
from pygments.lexers import Python3Lexer
|
|
141
|
+
from pygments.formatters import Terminal256Formatter
|
|
142
|
+
|
|
143
|
+
lexer = Python3Lexer()
|
|
144
|
+
formatter = Terminal256Formatter(style=theme_name)
|
|
145
|
+
pygments_loaded = True
|
|
146
|
+
except Exception:
|
|
147
|
+
# Silently fail if Pygments can't load
|
|
148
|
+
pass
|
|
149
|
+
|
|
150
|
+
# Start loading Pygments in background (non-blocking)
|
|
151
|
+
asyncio.create_task(load_pygments())
|
|
152
|
+
|
|
153
|
+
def syntax_highlight(code):
|
|
154
|
+
if not code:
|
|
155
|
+
return ""
|
|
156
|
+
if not pygments_loaded or lexer is None or formatter is None:
|
|
157
|
+
# Return unhighlighted code until Pygments loads
|
|
158
|
+
return code
|
|
159
|
+
try:
|
|
160
|
+
from pygments import highlight
|
|
161
|
+
|
|
162
|
+
result = highlight(code, lexer, formatter)
|
|
163
|
+
return result.rstrip("\\n")
|
|
164
|
+
except Exception:
|
|
165
|
+
return code
|
|
166
|
+
|
|
167
|
+
class TermWriter:
|
|
168
|
+
def write(self, data):
|
|
169
|
+
browser_console.term.write(data.replace("\\n", "\\r\\n"))
|
|
170
|
+
|
|
171
|
+
def flush(self):
|
|
172
|
+
pass
|
|
173
|
+
|
|
174
|
+
term_writer = TermWriter()
|
|
175
|
+
|
|
176
|
+
# Custom exec that redirects stdout/stderr to this REPL's terminal
|
|
177
|
+
import contextlib
|
|
178
|
+
|
|
179
|
+
def exec_with_redirect(code, globals_dict):
|
|
180
|
+
old_displayhook = sys.displayhook
|
|
181
|
+
|
|
182
|
+
def displayhook(value):
|
|
183
|
+
if value is not None:
|
|
184
|
+
globals_dict["_"] = value
|
|
185
|
+
browser_console.term.write(repr(value) + "\\r\\n")
|
|
186
|
+
|
|
187
|
+
sys.displayhook = displayhook
|
|
188
|
+
try:
|
|
189
|
+
with (
|
|
190
|
+
contextlib.redirect_stdout(term_writer),
|
|
191
|
+
contextlib.redirect_stderr(term_writer),
|
|
192
|
+
):
|
|
193
|
+
exec(code, globals_dict)
|
|
194
|
+
finally:
|
|
195
|
+
sys.displayhook = old_displayhook
|
|
196
|
+
|
|
197
|
+
def clear():
|
|
198
|
+
browser_console.clear()
|
|
199
|
+
browser_console.term.write(f"\\x1b[90m{info_line}\\x1b[0m\\r\\n")
|
|
200
|
+
|
|
201
|
+
class Exit:
|
|
202
|
+
def __repr__(self):
|
|
203
|
+
return "exit is not available in the browser"
|
|
204
|
+
|
|
205
|
+
def __call__(self):
|
|
206
|
+
browser_console.term.write("exit is not available in the browser\\r\\n")
|
|
207
|
+
|
|
208
|
+
repl_globals = {
|
|
209
|
+
"__builtins__": __builtins__,
|
|
210
|
+
"clear": clear,
|
|
211
|
+
"exit": Exit(),
|
|
212
|
+
"quit": Exit(),
|
|
213
|
+
}
|
|
214
|
+
completer = rlcompleter.Completer(repl_globals)
|
|
215
|
+
|
|
216
|
+
# Run startup script if one was provided (silently, just to populate namespace)
|
|
217
|
+
if startup_script:
|
|
218
|
+
try:
|
|
219
|
+
# Temporarily suppress stdout/stderr during startup
|
|
220
|
+
old_stdout, old_stderr = sys.stdout, sys.stderr
|
|
221
|
+
sys.stdout = sys.stderr = type(
|
|
222
|
+
"null", (), {"write": lambda s, x: None, "flush": lambda s: None}
|
|
223
|
+
)()
|
|
224
|
+
exec(startup_script, repl_globals)
|
|
225
|
+
sys.stdout, sys.stderr = old_stdout, old_stderr
|
|
226
|
+
except Exception as e:
|
|
227
|
+
sys.stdout, sys.stderr = old_stdout, old_stderr
|
|
228
|
+
browser_console.term.write(
|
|
229
|
+
f"\\x1b[31mStartup script error - {type(e).__name__}: {e}\\x1b[0m\\r\\n"
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
def get_completions(text):
|
|
233
|
+
"""Get all completions for the given text."""
|
|
234
|
+
completions = []
|
|
235
|
+
i = 0
|
|
236
|
+
while True:
|
|
237
|
+
c = completer.complete(text, i)
|
|
238
|
+
if c is None:
|
|
239
|
+
break
|
|
240
|
+
completions.append(c)
|
|
241
|
+
i += 1
|
|
242
|
+
return completions
|
|
243
|
+
|
|
244
|
+
def get_word_to_complete(line):
|
|
245
|
+
"""Extract the word to complete from the end of the line."""
|
|
246
|
+
match = re.search(r"[\\w.]*$", line)
|
|
247
|
+
return match.group(0) if match else ""
|
|
248
|
+
|
|
249
|
+
# In readonly mode, don't show prompt or accept input
|
|
250
|
+
if readonly:
|
|
251
|
+
return
|
|
252
|
+
|
|
253
|
+
browser_console.term.write(PS1)
|
|
254
|
+
lines = []
|
|
255
|
+
current_line = ""
|
|
256
|
+
|
|
257
|
+
history = []
|
|
258
|
+
history_index = 0
|
|
259
|
+
|
|
260
|
+
while True:
|
|
261
|
+
event = await browser_console.get_event(block=True)
|
|
262
|
+
if event is None:
|
|
263
|
+
continue
|
|
264
|
+
|
|
265
|
+
char = event.data
|
|
266
|
+
if char == "\\x03":
|
|
267
|
+
# Ctrl+C - interrupt/cancel current input
|
|
268
|
+
browser_console.term.write("^C\\r\\n")
|
|
269
|
+
lines = []
|
|
270
|
+
current_line = ""
|
|
271
|
+
history_index = len(history)
|
|
272
|
+
browser_console.term.write(PS1)
|
|
273
|
+
continue
|
|
274
|
+
|
|
275
|
+
if char == "\\x0c":
|
|
276
|
+
# Ctrl+L - clear screen
|
|
277
|
+
clear()
|
|
278
|
+
browser_console.term.write(PS1 + syntax_highlight(current_line))
|
|
279
|
+
continue
|
|
280
|
+
|
|
281
|
+
if char == "\\x1b":
|
|
282
|
+
# Might be an arrow key
|
|
283
|
+
event2 = await browser_console.get_event(block=True)
|
|
284
|
+
if event2 and event2.data == "[":
|
|
285
|
+
event3 = await browser_console.get_event(block=True)
|
|
286
|
+
if event3:
|
|
287
|
+
if event3.data == "A":
|
|
288
|
+
# Up arrow
|
|
289
|
+
if history:
|
|
290
|
+
history_index = max(0, history_index - 1)
|
|
291
|
+
# Clear current line
|
|
292
|
+
browser_console.term.write("\\r\\x1b[K")
|
|
293
|
+
hist_entry = history[history_index]
|
|
294
|
+
# For multiline entries, only show first line
|
|
295
|
+
current_line = (
|
|
296
|
+
hist_entry.split("\\n")[0]
|
|
297
|
+
if "\\n" in hist_entry
|
|
298
|
+
else hist_entry
|
|
299
|
+
)
|
|
300
|
+
browser_console.term.write(
|
|
301
|
+
PS1 + syntax_highlight(current_line)
|
|
302
|
+
)
|
|
303
|
+
elif event3.data == "B":
|
|
304
|
+
# Down arrow
|
|
305
|
+
if history:
|
|
306
|
+
history_index = min(len(history), history_index + 1)
|
|
307
|
+
# Clear current line
|
|
308
|
+
browser_console.term.write("\\r\\x1b[K")
|
|
309
|
+
if history_index < len(history):
|
|
310
|
+
hist_entry = history[history_index]
|
|
311
|
+
# For multiline entries, only show first line
|
|
312
|
+
current_line = (
|
|
313
|
+
hist_entry.split("\\n")[0]
|
|
314
|
+
if "\\n" in hist_entry
|
|
315
|
+
else hist_entry
|
|
316
|
+
)
|
|
317
|
+
else:
|
|
318
|
+
current_line = ""
|
|
319
|
+
browser_console.term.write(
|
|
320
|
+
PS1 + syntax_highlight(current_line)
|
|
321
|
+
)
|
|
322
|
+
# Left and Right arrows can be implemented similarly
|
|
323
|
+
continue
|
|
324
|
+
|
|
325
|
+
if char == "\\r":
|
|
326
|
+
browser_console.term.write("\\r\\n")
|
|
327
|
+
|
|
328
|
+
lines.append(current_line)
|
|
329
|
+
source = "\\n".join(lines)
|
|
330
|
+
|
|
331
|
+
if not source.strip():
|
|
332
|
+
lines = []
|
|
333
|
+
current_line = ""
|
|
334
|
+
browser_console.term.write(PS1)
|
|
335
|
+
continue
|
|
336
|
+
|
|
337
|
+
# If in multiline mode and user entered empty/whitespace line, execute
|
|
338
|
+
if len(lines) > 1 and not current_line.strip():
|
|
339
|
+
# Remove trailing empty lines
|
|
340
|
+
while lines and not lines[-1].strip():
|
|
341
|
+
lines.pop()
|
|
342
|
+
source = "\\n".join(lines)
|
|
343
|
+
try:
|
|
344
|
+
code = compile(source, "<console>", "single")
|
|
345
|
+
exec_with_redirect(code, repl_globals)
|
|
346
|
+
history.append(source)
|
|
347
|
+
history_index = len(history)
|
|
348
|
+
except SystemExit:
|
|
349
|
+
pass
|
|
350
|
+
except Exception as e:
|
|
351
|
+
browser_console.term.write(
|
|
352
|
+
f"\\x1b[31m{type(e).__name__}: {e}\\x1b[0m\\r\\n"
|
|
353
|
+
)
|
|
354
|
+
lines = []
|
|
355
|
+
current_line = ""
|
|
356
|
+
browser_console.term.write(PS1)
|
|
357
|
+
continue
|
|
358
|
+
|
|
359
|
+
try:
|
|
360
|
+
code = compile_command(source, "<console>", "single")
|
|
361
|
+
if code is None:
|
|
362
|
+
# Incomplete — need more input
|
|
363
|
+
prev_line = lines[-1] if lines else current_line
|
|
364
|
+
indent = len(prev_line) - len(prev_line.lstrip())
|
|
365
|
+
if prev_line.rstrip().endswith(":"):
|
|
366
|
+
indent += 4
|
|
367
|
+
browser_console.term.write(PS2 + " " * indent)
|
|
368
|
+
current_line = " " * indent
|
|
369
|
+
else:
|
|
370
|
+
# Complete code, execute it
|
|
371
|
+
if source.strip():
|
|
372
|
+
history.append(source)
|
|
373
|
+
history_index = len(history)
|
|
374
|
+
try:
|
|
375
|
+
exec_with_redirect(code, repl_globals)
|
|
376
|
+
except SystemExit:
|
|
377
|
+
pass
|
|
378
|
+
except Exception as e:
|
|
379
|
+
browser_console.term.write(
|
|
380
|
+
f"\\x1b[31m{type(e).__name__}: {e}\\x1b[0m\\r\\n"
|
|
381
|
+
)
|
|
382
|
+
lines = []
|
|
383
|
+
current_line = ""
|
|
384
|
+
browser_console.term.write(PS1)
|
|
385
|
+
except SyntaxError as e:
|
|
386
|
+
browser_console.term.write(f"\\x1b[31mSyntaxError: {e}\\x1b[0m\\r\\n")
|
|
387
|
+
lines = []
|
|
388
|
+
current_line = ""
|
|
389
|
+
browser_console.term.write(PS1)
|
|
390
|
+
except Exception as e:
|
|
391
|
+
browser_console.term.write(f"\\x1b[31mError: {e}\\x1b[0m\\r\\n")
|
|
392
|
+
lines = []
|
|
393
|
+
current_line = ""
|
|
394
|
+
browser_console.term.write(PS1)
|
|
395
|
+
elif char == "\\t":
|
|
396
|
+
# Tab completion
|
|
397
|
+
word = get_word_to_complete(current_line)
|
|
398
|
+
if word:
|
|
399
|
+
completions = get_completions(word)
|
|
400
|
+
if len(completions) == 1:
|
|
401
|
+
# Single match - complete it
|
|
402
|
+
completion = completions[0]
|
|
403
|
+
current_line = current_line[: -len(word)] + completion
|
|
404
|
+
browser_console.term.write("\\r\\x1b[K")
|
|
405
|
+
prompt = PS1 if len(lines) == 0 else PS2
|
|
406
|
+
browser_console.term.write(prompt + syntax_highlight(current_line))
|
|
407
|
+
elif len(completions) > 1:
|
|
408
|
+
# Multiple matches - show them in columns
|
|
409
|
+
browser_console.term.write("\\r\\n")
|
|
410
|
+
max_len = max(len(c) for c in completions) + 2
|
|
411
|
+
cols = max(1, browser_console.term.cols // max_len)
|
|
412
|
+
for i, c in enumerate(completions):
|
|
413
|
+
browser_console.term.write(c.ljust(max_len))
|
|
414
|
+
if (i + 1) % cols == 0:
|
|
415
|
+
browser_console.term.write("\\r\\n")
|
|
416
|
+
if len(completions) % cols != 0:
|
|
417
|
+
browser_console.term.write("\\r\\n")
|
|
418
|
+
prompt = PS1 if len(lines) == 0 else PS2
|
|
419
|
+
browser_console.term.write(prompt + syntax_highlight(current_line))
|
|
420
|
+
elif char == "\\x7f":
|
|
421
|
+
if current_line:
|
|
422
|
+
current_line = current_line[:-1]
|
|
423
|
+
browser_console.term.write("\\r\\x1b[K")
|
|
424
|
+
prompt = PS1 if len(lines) == 0 else PS2
|
|
425
|
+
browser_console.term.write(prompt + syntax_highlight(current_line))
|
|
426
|
+
else:
|
|
427
|
+
current_line += char
|
|
428
|
+
# Clear line and rewrite with highlighting
|
|
429
|
+
browser_console.term.write("\\r\\x1b[K") # Go to start, clear line
|
|
430
|
+
prompt = PS1 if len(lines) == 0 else PS2
|
|
431
|
+
browser_console.term.write(prompt + syntax_highlight(current_line))
|
|
432
|
+
`;var w=null,m=null,p=null,c={"catppuccin-mocha":{background:"#1e1e2e",foreground:"#cdd6f4",cursor:"#f5e0dc",cursorAccent:"#1e1e2e",selectionBackground:"#585b70",black:"#45475a",red:"#f38ba8",green:"#a6e3a1",yellow:"#f9e2af",blue:"#89b4fa",magenta:"#f5c2e7",cyan:"#94e2d5",white:"#bac2de",brightBlack:"#585b70",brightRed:"#f38ba8",brightGreen:"#a6e3a1",brightYellow:"#f9e2af",brightBlue:"#89b4fa",brightMagenta:"#f5c2e7",brightCyan:"#94e2d5",brightWhite:"#a6adc8",headerBackground:"#181825",headerTitle:"#6c7086",shadow:"0 4px 24px rgba(0, 0, 0, 0.3)"},"catppuccin-latte":{background:"#eff1f5",foreground:"#4c4f69",cursor:"#dc8a78",cursorAccent:"#eff1f5",selectionBackground:"#acb0be",black:"#5c5f77",red:"#d20f39",green:"#40a02b",yellow:"#df8e1d",blue:"#1e66f5",magenta:"#ea76cb",cyan:"#179299",white:"#acb0be",brightBlack:"#6c6f85",brightRed:"#d20f39",brightGreen:"#40a02b",brightYellow:"#df8e1d",brightBlue:"#1e66f5",brightMagenta:"#ea76cb",brightCyan:"#179299",brightWhite:"#bcc0cc",headerBackground:"#dce0e8",headerTitle:"#8c8fa1",shadow:"0 4px 24px rgba(0, 0, 0, 0.08)"}},i="catppuccin-mocha",h={copy:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg>',clear:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"></path><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"></path><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"></path></svg>'};function P(n){let e,r,t=n.dataset.themeConfig;if(t)try{e=JSON.parse(t),r="custom"}catch(_){console.warn("pyrepl-web: invalid data-theme-config JSON, falling back to default"),e=c[i],r=i}else if(r=n.dataset.theme||i,e=window.pyreplThemes?.[r]||c[r]||c[i],!window.pyreplThemes?.[r]&&!c[r])console.warn(`pyrepl-web: unknown theme "${r}", falling back to default`),r=i;let l=n.dataset.packages,o=l?l.split(",").map((_)=>_.trim()).filter(Boolean):[];return{theme:e,themeName:r,showHeader:n.dataset.header!=="false",showButtons:n.dataset.buttons!=="false",title:n.dataset.title||"python",packages:o,src:n.dataset.src||null,readonly:n.dataset.readonly==="true"}}async function E(){if(!w){let{loadPyodide:n}=await import("./chunk-n46k5haq.js");w=n({indexURL:"https://cdn.jsdelivr.net/pyodide/v0.29.2/full/",stdout:(e)=>{if(p)p.write(e+`\r
|
|
433
|
+
`)},stderr:(e)=>{if(p)p.write(e+`\r
|
|
434
|
+
`)}})}return await w}function k(){if(!m)m=Promise.resolve(x);return m}function j(){if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",b);else b()}function q(){if(document.getElementById("pyrepl-styles"))return;let n=document.createElement("link");n.rel="stylesheet",n.href="https://cdn.jsdelivr.net/npm/@xterm/xterm/css/xterm.css",document.head.appendChild(n);let e=document.createElement("style");e.id="pyrepl-styles",e.textContent=`
|
|
435
|
+
.pyrepl {
|
|
436
|
+
display: inline-block;
|
|
437
|
+
border-radius: 8px;
|
|
438
|
+
overflow: hidden;
|
|
439
|
+
box-shadow: var(--pyrepl-shadow);
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
.pyrepl-header {
|
|
443
|
+
background: var(--pyrepl-header-bg);
|
|
444
|
+
padding: 8px 12px;
|
|
445
|
+
display: flex;
|
|
446
|
+
align-items: center;
|
|
447
|
+
gap: 8px;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
.pyrepl-header-dots {
|
|
451
|
+
display: flex;
|
|
452
|
+
gap: 6px;
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
.pyrepl-header-dot {
|
|
456
|
+
width: 12px;
|
|
457
|
+
height: 12px;
|
|
458
|
+
border-radius: 50%;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
.pyrepl-header-dot.red { background: var(--pyrepl-red); }
|
|
462
|
+
.pyrepl-header-dot.yellow { background: var(--pyrepl-yellow); }
|
|
463
|
+
.pyrepl-header-dot.green { background: var(--pyrepl-green); }
|
|
464
|
+
|
|
465
|
+
.pyrepl-header-title {
|
|
466
|
+
flex: 1;
|
|
467
|
+
text-align: center;
|
|
468
|
+
color: var(--pyrepl-header-title);
|
|
469
|
+
font-family: monospace;
|
|
470
|
+
font-size: 13px;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
.pyrepl-header-buttons {
|
|
474
|
+
display: flex;
|
|
475
|
+
gap: 4px;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
.pyrepl-header-btn {
|
|
479
|
+
background: transparent;
|
|
480
|
+
border: none;
|
|
481
|
+
color: var(--pyrepl-header-title);
|
|
482
|
+
cursor: pointer;
|
|
483
|
+
padding: 4px;
|
|
484
|
+
border-radius: 4px;
|
|
485
|
+
display: flex;
|
|
486
|
+
align-items: center;
|
|
487
|
+
justify-content: center;
|
|
488
|
+
opacity: 0.7;
|
|
489
|
+
transition: opacity 0.15s;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
.pyrepl-header-btn:hover {
|
|
493
|
+
opacity: 1;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
.pyrepl-header-btn svg {
|
|
497
|
+
width: 14px;
|
|
498
|
+
height: 14px;
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
.pyrepl .xterm {
|
|
502
|
+
padding: 8px 12px 12px 12px;
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
.pyrepl .xterm-viewport::-webkit-scrollbar {
|
|
506
|
+
display: none;
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
.pyrepl .xterm-viewport {
|
|
510
|
+
scrollbar-width: none;
|
|
511
|
+
background-color: var(--pyrepl-bg) !important;
|
|
512
|
+
}
|
|
513
|
+
`,document.head.appendChild(e)}function R(n,e){let r=e.headerBackground||e.black,t=e.headerTitle||e.brightBlack,l=e.shadow||"0 4px 24px rgba(0, 0, 0, 0.3)";n.style.setProperty("--pyrepl-bg",e.background),n.style.setProperty("--pyrepl-header-bg",r),n.style.setProperty("--pyrepl-header-title",t),n.style.setProperty("--pyrepl-red",e.red),n.style.setProperty("--pyrepl-yellow",e.yellow),n.style.setProperty("--pyrepl-green",e.green),n.style.setProperty("--pyrepl-shadow",l)}function F(n){let e=document.createElement("div");return e.className="pyrepl-header",e.innerHTML=`
|
|
514
|
+
<div class="pyrepl-header-dots">
|
|
515
|
+
<div class="pyrepl-header-dot red"></div>
|
|
516
|
+
<div class="pyrepl-header-dot yellow"></div>
|
|
517
|
+
<div class="pyrepl-header-dot green"></div>
|
|
518
|
+
</div>
|
|
519
|
+
<div class="pyrepl-header-title">${n.title}</div>
|
|
520
|
+
${n.showButtons?`
|
|
521
|
+
<div class="pyrepl-header-buttons">
|
|
522
|
+
<button class="pyrepl-header-btn" data-action="copy" title="Copy output">${h.copy}</button>
|
|
523
|
+
<button class="pyrepl-header-btn" data-action="clear" title="Clear terminal">${h.clear}</button>
|
|
524
|
+
</div>
|
|
525
|
+
`:'<div style="width: 48px"></div>'}
|
|
526
|
+
`,e}async function N(n){q();let e=P(n);if(R(n,e.theme),e.showHeader)n.appendChild(F(e));let r=await import("./chunk-7hjm8rrn.js"),t=document.createElement("div");n.appendChild(t);let l=new r.Terminal({cursorBlink:!e.readonly,cursorStyle:e.readonly?"bar":"block",fontSize:14,fontFamily:"monospace",theme:e.theme,disableStdin:e.readonly});return l.open(t),{term:l,config:e}}async function I(n,e,r){let t=await E();if(await t.loadPackage("micropip"),r.packages.length>0)await t.pyimport("micropip").install(r.packages);let o=`Python 3.13${r.packages.length>0?` (installed packages: ${r.packages.join(", ")})`:""}`;if(e.write(`\x1B[90m${o}\x1B[0m\r
|
|
527
|
+
`),globalThis.term=e,globalThis.pyreplTheme=r.themeName,globalThis.pyreplInfo=o,globalThis.pyreplReadonly=r.readonly,r.src)try{let s=await fetch(r.src);if(s.ok)globalThis.pyreplStartupScript=await s.text();else console.warn(`pyrepl-web: failed to fetch script from ${r.src}`)}catch(s){console.warn(`pyrepl-web: error fetching script from ${r.src}`,s)}let _=await k();t.runPython(_),t.runPythonAsync("await start_repl()");while(!globalThis.currentBrowserConsole)await new Promise((s)=>setTimeout(s,10));let S=globalThis.currentBrowserConsole;if(globalThis.currentBrowserConsole=null,!r.readonly)e.onData((s)=>{for(let a of s)S.push_char(a.charCodeAt(0))});if(r.showHeader&&r.showButtons){let s=n.querySelector('[data-action="copy"]'),a=n.querySelector('[data-action="clear"]');s?.addEventListener("click",()=>{let u=e.buffer.active,f="";for(let d=0;d<u.length;d++){let y=u.getLine(d);if(y)f+=y.translateToString(!0)+`
|
|
528
|
+
`}navigator.clipboard.writeText(f.trimEnd())}),a?.addEventListener("click",()=>{e.reset(),e.write(`\x1B[90m${o}\x1B[0m\r
|
|
529
|
+
`),e.write("\x1B[32m>>> \x1B[0m")})}}async function b(){let n=document.querySelectorAll(".pyrepl");if(n.length===0){console.warn("pyrepl-web: no .pyrepl elements found");return}let e=await Promise.all(Array.from(n).map(async(r)=>({container:r,...await N(r)})));for(let{container:r,term:t,config:l}of e)await I(r,t,l)}j();
|