open-webui/static/pyodide/pyodide.mjs
2024-05-16 19:21:08 -10:00

13 lines
16 KiB
JavaScript

var oe=Object.create;var N=Object.defineProperty;var se=Object.getOwnPropertyDescriptor;var ae=Object.getOwnPropertyNames;var ce=Object.getPrototypeOf,le=Object.prototype.hasOwnProperty;var f=(t,e)=>N(t,"name",{value:e,configurable:!0}),b=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,c)=>(typeof require<"u"?require:e)[c]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+t+'" is not supported')});var D=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var de=(t,e,c,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ae(e))!le.call(t,s)&&s!==c&&N(t,s,{get:()=>e[s],enumerable:!(o=se(e,s))||o.enumerable});return t};var fe=(t,e,c)=>(c=t!=null?oe(ce(t)):{},de(e||!t||!t.__esModule?N(c,"default",{value:t,enumerable:!0}):c,t));var $=D((R,T)=>{(function(t,e){"use strict";typeof define=="function"&&define.amd?define("stackframe",[],e):typeof R=="object"?T.exports=e():t.StackFrame=e()})(R,function(){"use strict";function t(d){return!isNaN(parseFloat(d))&&isFinite(d)}f(t,"_isNumber");function e(d){return d.charAt(0).toUpperCase()+d.substring(1)}f(e,"_capitalize");function c(d){return function(){return this[d]}}f(c,"_getter");var o=["isConstructor","isEval","isNative","isToplevel"],s=["columnNumber","lineNumber"],r=["fileName","functionName","source"],n=["args"],u=["evalOrigin"],i=o.concat(s,r,n,u);function a(d){if(d)for(var g=0;g<i.length;g++)d[i[g]]!==void 0&&this["set"+e(i[g])](d[i[g]])}f(a,"StackFrame"),a.prototype={getArgs:function(){return this.args},setArgs:function(d){if(Object.prototype.toString.call(d)!=="[object Array]")throw new TypeError("Args must be an Array");this.args=d},getEvalOrigin:function(){return this.evalOrigin},setEvalOrigin:function(d){if(d instanceof a)this.evalOrigin=d;else if(d instanceof Object)this.evalOrigin=new a(d);else throw new TypeError("Eval Origin must be an Object or StackFrame")},toString:function(){var d=this.getFileName()||"",g=this.getLineNumber()||"",v=this.getColumnNumber()||"",h=this.getFunctionName()||"";return this.getIsEval()?d?"[eval] ("+d+":"+g+":"+v+")":"[eval]:"+g+":"+v:h?h+" ("+d+":"+g+":"+v+")":d+":"+g+":"+v}},a.fromString=f(function(g){var v=g.indexOf("("),h=g.lastIndexOf(")"),ee=g.substring(0,v),te=g.substring(v+1,h).split(","),A=g.substring(h+1);if(A.indexOf("@")===0)var O=/@(.+?)(?::(\d+))?(?::(\d+))?$/.exec(A,""),re=O[1],ne=O[2],ie=O[3];return new a({functionName:ee,args:te||void 0,fileName:re,lineNumber:ne||void 0,columnNumber:ie||void 0})},"StackFrame$$fromString");for(var l=0;l<o.length;l++)a.prototype["get"+e(o[l])]=c(o[l]),a.prototype["set"+e(o[l])]=function(d){return function(g){this[d]=!!g}}(o[l]);for(var m=0;m<s.length;m++)a.prototype["get"+e(s[m])]=c(s[m]),a.prototype["set"+e(s[m])]=function(d){return function(g){if(!t(g))throw new TypeError(d+" must be a Number");this[d]=Number(g)}}(s[m]);for(var p=0;p<r.length;p++)a.prototype["get"+e(r[p])]=c(r[p]),a.prototype["set"+e(r[p])]=function(d){return function(g){this[d]=String(g)}}(r[p]);return a})});var U=D((k,M)=>{(function(t,e){"use strict";typeof define=="function"&&define.amd?define("error-stack-parser",["stackframe"],e):typeof k=="object"?M.exports=e($()):t.ErrorStackParser=e(t.StackFrame)})(k,f(function(e){"use strict";var c=/(^|@)\S+:\d+/,o=/^\s*at .*(\S+:\d+|\(native\))/m,s=/^(eval@)?(\[native code])?$/;return{parse:f(function(n){if(typeof n.stacktrace<"u"||typeof n["opera#sourceloc"]<"u")return this.parseOpera(n);if(n.stack&&n.stack.match(o))return this.parseV8OrIE(n);if(n.stack)return this.parseFFOrSafari(n);throw new Error("Cannot parse given Error object")},"ErrorStackParser$$parse"),extractLocation:f(function(n){if(n.indexOf(":")===-1)return[n];var u=/(.+?)(?::(\d+))?(?::(\d+))?$/,i=u.exec(n.replace(/[()]/g,""));return[i[1],i[2]||void 0,i[3]||void 0]},"ErrorStackParser$$extractLocation"),parseV8OrIE:f(function(n){var u=n.stack.split(`
`).filter(function(i){return!!i.match(o)},this);return u.map(function(i){i.indexOf("(eval ")>-1&&(i=i.replace(/eval code/g,"eval").replace(/(\(eval at [^()]*)|(,.*$)/g,""));var a=i.replace(/^\s+/,"").replace(/\(eval code/g,"(").replace(/^.*?\s+/,""),l=a.match(/ (\(.+\)$)/);a=l?a.replace(l[0],""):a;var m=this.extractLocation(l?l[1]:a),p=l&&a||void 0,d=["eval","<anonymous>"].indexOf(m[0])>-1?void 0:m[0];return new e({functionName:p,fileName:d,lineNumber:m[1],columnNumber:m[2],source:i})},this)},"ErrorStackParser$$parseV8OrIE"),parseFFOrSafari:f(function(n){var u=n.stack.split(`
`).filter(function(i){return!i.match(s)},this);return u.map(function(i){if(i.indexOf(" > eval")>-1&&(i=i.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1")),i.indexOf("@")===-1&&i.indexOf(":")===-1)return new e({functionName:i});var a=/((.*".+"[^@]*)?[^@]*)(?:@)/,l=i.match(a),m=l&&l[1]?l[1]:void 0,p=this.extractLocation(i.replace(a,""));return new e({functionName:m,fileName:p[0],lineNumber:p[1],columnNumber:p[2],source:i})},this)},"ErrorStackParser$$parseFFOrSafari"),parseOpera:f(function(n){return!n.stacktrace||n.message.indexOf(`
`)>-1&&n.message.split(`
`).length>n.stacktrace.split(`
`).length?this.parseOpera9(n):n.stack?this.parseOpera11(n):this.parseOpera10(n)},"ErrorStackParser$$parseOpera"),parseOpera9:f(function(n){for(var u=/Line (\d+).*script (?:in )?(\S+)/i,i=n.message.split(`
`),a=[],l=2,m=i.length;l<m;l+=2){var p=u.exec(i[l]);p&&a.push(new e({fileName:p[2],lineNumber:p[1],source:i[l]}))}return a},"ErrorStackParser$$parseOpera9"),parseOpera10:f(function(n){for(var u=/Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i,i=n.stacktrace.split(`
`),a=[],l=0,m=i.length;l<m;l+=2){var p=u.exec(i[l]);p&&a.push(new e({functionName:p[3]||void 0,fileName:p[2],lineNumber:p[1],source:i[l]}))}return a},"ErrorStackParser$$parseOpera10"),parseOpera11:f(function(n){var u=n.stack.split(`
`).filter(function(i){return!!i.match(c)&&!i.match(/^Error created at/)},this);return u.map(function(i){var a=i.split("@"),l=this.extractLocation(a.pop()),m=a.shift()||"",p=m.replace(/<anonymous function(: (\w+))?>/,"$2").replace(/\([^)]*\)/g,"")||void 0,d;m.match(/\(([^)]*)\)/)&&(d=m.replace(/^[^(]+\(([^)]*)\)$/,"$1"));var g=d===void 0||d==="[arguments not available]"?void 0:d.split(",");return new e({functionName:p,args:g,fileName:l[0],lineNumber:l[1],columnNumber:l[2],source:i})},this)},"ErrorStackParser$$parseOpera11")}},"ErrorStackParser"))});var z=fe(U());var y=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string"&&typeof process.browser>"u",x=y&&typeof module<"u"&&typeof module.exports<"u"&&typeof b<"u"&&typeof __dirname<"u",C=y&&!x,ue=typeof Deno<"u",B=!y&&!ue,W=B&&typeof window<"u"&&typeof document<"u"&&typeof document.createElement<"u"&&typeof sessionStorage<"u"&&typeof importScripts>"u",j=B&&typeof importScripts<"u"&&typeof self<"u",Re=typeof navigator<"u"&&typeof navigator.userAgent<"u"&&navigator.userAgent.indexOf("Chrome")==-1&&navigator.userAgent.indexOf("Safari")>-1;var q,P,V,H,F;async function I(){if(!y||(q=(await import("node:url")).default,H=await import("node:fs"),F=await import("node:fs/promises"),V=(await import("node:vm")).default,P=await import("node:path"),L=P.sep,typeof b<"u"))return;let t=H,e=await import("node:crypto"),c=await import("ws"),o=await import("node:child_process"),s={fs:t,crypto:e,ws:c,child_process:o};globalThis.require=function(r){return s[r]}}f(I,"initNodeModules");function pe(t,e){return P.resolve(e||".",t)}f(pe,"node_resolvePath");function me(t,e){return e===void 0&&(e=location),new URL(t,e).toString()}f(me,"browser_resolvePath");var S;y?S=pe:S=me;var L;y||(L="/");function ge(t,e){return t.startsWith("file://")&&(t=t.slice(7)),t.includes("://")?{response:fetch(t)}:{binary:F.readFile(t).then(c=>new Uint8Array(c.buffer,c.byteOffset,c.byteLength))}}f(ge,"node_getBinaryResponse");function ye(t,e){let c=new URL(t,location);return{response:fetch(c,e?{integrity:e}:{})}}f(ye,"browser_getBinaryResponse");var E;y?E=ge:E=ye;async function K(t,e){let{response:c,binary:o}=E(t,e);if(o)return o;let s=await c;if(!s.ok)throw new Error(`Failed to load '${t}': request failed.`);return new Uint8Array(await s.arrayBuffer())}f(K,"loadBinaryFile");var w;if(W)w=f(async t=>await import(t),"loadScript");else if(j)w=f(async t=>{try{globalThis.importScripts(t)}catch(e){if(e instanceof TypeError)await import(t);else throw e}},"loadScript");else if(y)w=ve;else throw new Error("Cannot determine runtime environment");async function ve(t){t.startsWith("file://")&&(t=t.slice(7)),t.includes("://")?V.runInThisContext(await(await fetch(t)).text()):await import(q.pathToFileURL(t).href)}f(ve,"nodeLoadScript");async function J(t){if(y){await I();let e=await F.readFile(t,{encoding:"utf8"});return JSON.parse(e)}else return await(await fetch(t)).json()}f(J,"loadLockFile");async function X(){if(x)return __dirname;let t;try{throw new Error}catch(o){t=o}let e=z.default.parse(t)[0].fileName;if(C){let o=await import("node:path");return(await import("node:url")).fileURLToPath(o.dirname(e))}let c=e.lastIndexOf(L);if(c===-1)throw new Error("Could not extract indexURL path from pyodide module location");return e.slice(0,c)}f(X,"calculateDirname");function G(t){let e=t.FS,c=t.FS.filesystems.MEMFS,o=t.PATH,s={DIR_MODE:16895,FILE_MODE:33279,mount:function(r){if(!r.opts.fileSystemHandle)throw new Error("opts.fileSystemHandle is required");return c.mount.apply(null,arguments)},syncfs:async(r,n,u)=>{try{let i=s.getLocalSet(r),a=await s.getRemoteSet(r),l=n?a:i,m=n?i:a;await s.reconcile(r,l,m),u(null)}catch(i){u(i)}},getLocalSet:r=>{let n=Object.create(null);function u(l){return l!=="."&&l!==".."}f(u,"isRealDir");function i(l){return m=>o.join2(l,m)}f(i,"toAbsolute");let a=e.readdir(r.mountpoint).filter(u).map(i(r.mountpoint));for(;a.length;){let l=a.pop(),m=e.stat(l);e.isDir(m.mode)&&a.push.apply(a,e.readdir(l).filter(u).map(i(l))),n[l]={timestamp:m.mtime,mode:m.mode}}return{type:"local",entries:n}},getRemoteSet:async r=>{let n=Object.create(null),u=await he(r.opts.fileSystemHandle);for(let[i,a]of u)i!=="."&&(n[o.join2(r.mountpoint,i)]={timestamp:a.kind==="file"?(await a.getFile()).lastModifiedDate:new Date,mode:a.kind==="file"?s.FILE_MODE:s.DIR_MODE});return{type:"remote",entries:n,handles:u}},loadLocalEntry:r=>{let u=e.lookupPath(r).node,i=e.stat(r);if(e.isDir(i.mode))return{timestamp:i.mtime,mode:i.mode};if(e.isFile(i.mode))return u.contents=c.getFileDataAsTypedArray(u),{timestamp:i.mtime,mode:i.mode,contents:u.contents};throw new Error("node type not supported")},storeLocalEntry:(r,n)=>{if(e.isDir(n.mode))e.mkdirTree(r,n.mode);else if(e.isFile(n.mode))e.writeFile(r,n.contents,{canOwn:!0});else throw new Error("node type not supported");e.chmod(r,n.mode),e.utime(r,n.timestamp,n.timestamp)},removeLocalEntry:r=>{var n=e.stat(r);e.isDir(n.mode)?e.rmdir(r):e.isFile(n.mode)&&e.unlink(r)},loadRemoteEntry:async r=>{if(r.kind==="file"){let n=await r.getFile();return{contents:new Uint8Array(await n.arrayBuffer()),mode:s.FILE_MODE,timestamp:n.lastModifiedDate}}else{if(r.kind==="directory")return{mode:s.DIR_MODE,timestamp:new Date};throw new Error("unknown kind: "+r.kind)}},storeRemoteEntry:async(r,n,u)=>{let i=r.get(o.dirname(n)),a=e.isFile(u.mode)?await i.getFileHandle(o.basename(n),{create:!0}):await i.getDirectoryHandle(o.basename(n),{create:!0});if(a.kind==="file"){let l=await a.createWritable();await l.write(u.contents),await l.close()}r.set(n,a)},removeRemoteEntry:async(r,n)=>{await r.get(o.dirname(n)).removeEntry(o.basename(n)),r.delete(n)},reconcile:async(r,n,u)=>{let i=0,a=[];Object.keys(n.entries).forEach(function(p){let d=n.entries[p],g=u.entries[p];(!g||e.isFile(d.mode)&&d.timestamp.getTime()>g.timestamp.getTime())&&(a.push(p),i++)}),a.sort();let l=[];if(Object.keys(u.entries).forEach(function(p){n.entries[p]||(l.push(p),i++)}),l.sort().reverse(),!i)return;let m=n.type==="remote"?n.handles:u.handles;for(let p of a){let d=o.normalize(p.replace(r.mountpoint,"/")).substring(1);if(u.type==="local"){let g=m.get(d),v=await s.loadRemoteEntry(g);s.storeLocalEntry(p,v)}else{let g=s.loadLocalEntry(p);await s.storeRemoteEntry(m,d,g)}}for(let p of l)if(u.type==="local")s.removeLocalEntry(p);else{let d=o.normalize(p.replace(r.mountpoint,"/")).substring(1);await s.removeRemoteEntry(m,d)}}};t.FS.filesystems.NATIVEFS_ASYNC=s}f(G,"initializeNativeFS");var he=f(async t=>{let e=[];async function c(s){for await(let r of s.values())e.push(r),r.kind==="directory"&&await c(r)}f(c,"collect"),await c(t);let o=new Map;o.set(".",t);for(let s of e){let r=(await t.resolve(s)).join("/");o.set(r,s)}return o},"getFsHandles");function Y(){let t={};return t.noImageDecoding=!0,t.noAudioDecoding=!0,t.noWasmDecoding=!1,t.preRun=[],t.quit=(e,c)=>{throw t.exited={status:e,toThrow:c},c},t}f(Y,"createModule");function we(t,e){t.preRun.push(function(){let c="/";try{t.FS.mkdirTree(e)}catch(o){console.error(`Error occurred while making a home directory '${e}':`),console.error(o),console.error(`Using '${c}' for a home directory instead`),e=c}t.FS.chdir(e)})}f(we,"createHomeDirectory");function Ee(t,e){t.preRun.push(function(){Object.assign(t.ENV,e)})}f(Ee,"setEnvironment");function _e(t,e){t.preRun.push(()=>{for(let c of e)t.FS.mkdirTree(c),t.FS.mount(t.FS.filesystems.NODEFS,{root:c},c)})}f(_e,"mountLocalDirectories");function be(t,e){let c=K(e);t.preRun.push(()=>{let o=t._py_version_major(),s=t._py_version_minor();t.FS.mkdirTree("/lib"),t.FS.mkdirTree(`/lib/python${o}.${s}/site-packages`),t.addRunDependency("install-stdlib"),c.then(r=>{t.FS.writeFile(`/lib/python${o}${s}.zip`,r)}).catch(r=>{console.error("Error occurred while installing the standard library:"),console.error(r)}).finally(()=>{t.removeRunDependency("install-stdlib")})})}f(be,"installStdlib");function Q(t,e){let c;e.stdLibURL!=null?c=e.stdLibURL:c=e.indexURL+"python_stdlib.zip",be(t,c),we(t,e.env.HOME),Ee(t,e.env),_e(t,e._node_mounts),t.preRun.push(()=>G(t))}f(Q,"initializeFileSystem");function Z(t,e){let{binary:c,response:o}=E(e+"pyodide.asm.wasm");t.instantiateWasm=function(s,r){return async function(){try{let n;o?n=await WebAssembly.instantiateStreaming(o,s):n=await WebAssembly.instantiate(await c,s);let{instance:u,module:i}=n;typeof WasmOffsetConverter<"u"&&(wasmOffsetConverter=new WasmOffsetConverter(wasmBinary,i)),r(u,i)}catch(n){console.warn("wasm instantiation failed!"),console.warn(n)}}(),{}}}f(Z,"preloadWasm");var _="0.26.0a4";async function je(t={}){await I();let e=t.indexURL||await X();e=S(e),e.endsWith("/")||(e+="/"),t.indexURL=e;let c={fullStdLib:!1,jsglobals:globalThis,stdin:globalThis.prompt?globalThis.prompt:void 0,lockFileURL:e+"pyodide-lock.json",args:[],_node_mounts:[],env:{},packageCacheDir:e,packages:[]},o=Object.assign(c,t);o.env.HOME||(o.env.HOME="/home/pyodide");let s=Y();s.print=o.stdout,s.printErr=o.stderr,s.arguments=o.args;let r={config:o};s.API=r,r.lockFilePromise=J(o.lockFileURL),Z(s,e),Q(s,o);let n=new Promise(a=>s.postRun=a);if(s.locateFile=a=>o.indexURL+a,typeof _createPyodideModule!="function"){let a=`${o.indexURL}pyodide.asm.js`;await w(a)}if(await _createPyodideModule(s),await n,s.exited)throw s.exited.toThrow;if(t.pyproxyToStringRepr&&r.setPyProxyToStringMethod(!0),r.version!==_)throw new Error(`Pyodide version does not match: '${_}' <==> '${r.version}'. If you updated the Pyodide version, make sure you also updated the 'indexURL' parameter passed to loadPyodide.`);s.locateFile=a=>{throw new Error("Didn't expect to load any more file_packager files!")};let u=r.finalizeBootstrap();if(u.version.includes("dev")||r.setCdnUrl(`https://cdn.jsdelivr.net/pyodide/v${u.version}/full/`),await r.packageIndexReady,r._pyodide.set_excepthook(),r._pyodide._importhook.register_module_not_found_hook(r._import_name_to_package_name,r.lockfile_unvendored_stdlibs_and_test),r.lockfile_info.version!==_)throw new Error(`Lock file version doesn't match Pyodide version.
lockfile version: ${r.lockfile_info.version}
pyodide version: ${_}`);return r.package_loader.init_loaded_packages(),o.fullStdLib&&await u.loadPackage(r.lockfile_unvendored_stdlibs),r.initializeStreams(o.stdin,o.stdout,o.stderr),u}f(je,"loadPyodide");export{je as loadPyodide,_ as version};
//# sourceMappingURL=pyodide.mjs.map