@php-wasm/universal 2.0.5 → 2.0.8
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/index.cjs +3 -3
- package/index.cjs.map +1 -1
- package/index.js +38 -21
- package/index.js.map +1 -1
- package/lib/php-response.d.ts +5 -0
- package/package.json +7 -7
package/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var re=Object.create;var q=Object.defineProperty;var se=Object.getOwnPropertyDescriptor;var ne=Object.getOwnPropertyNames;var ie=Object.getPrototypeOf,oe=Object.prototype.hasOwnProperty;var z=t=>{throw TypeError(t)};var ae=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ne(e))!oe.call(t,n)&&n!==r&&q(t,n,{get:()=>e[n],enumerable:!(s=se(e,n))||s.enumerable});return t};var le=(t,e,r)=>(r=t!=null?re(ie(t)):{},ae(e||!t||!t.__esModule?q(r,"default",{value:t,enumerable:!0}):r,t));var N=(t,e,r)=>e.has(t)||z("Cannot "+r);var u=(t,e,r)=>(N(t,e,"read from private field"),r?r.call(t):e.get(t)),_=(t,e,r)=>e.has(t)?z("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),f=(t,e,r,s)=>(N(t,e,"write to private field"),s?s.call(t,r):e.set(t,r),r),m=(t,e,r)=>(N(t,e,"access private method"),r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("@php-wasm/node-polyfills");const logger=require("@php-wasm/logger"),util=require("@php-wasm/util"),ini=require("ini"),streamCompression=require("@php-wasm/stream-compression");var _documentCurrentScript=typeof document<"u"?document.currentScript:null;class ErrnoError extends Error{constructor(e,r,s){super(r,s),this.name="ErrnoError",this.errno=e}}const FileErrorCodes={0:"No error occurred. System call completed successfully.",1:"Argument list too long.",2:"Permission denied.",3:"Address in use.",4:"Address not available.",5:"Address family not supported.",6:"Resource unavailable, or operation would block.",7:"Connection already in progress.",8:"Bad file descriptor.",9:"Bad message.",10:"Device or resource busy.",11:"Operation canceled.",12:"No child processes.",13:"Connection aborted.",14:"Connection refused.",15:"Connection reset.",16:"Resource deadlock would occur.",17:"Destination address required.",18:"Mathematics argument out of domain of function.",19:"Reserved.",20:"File exists.",21:"Bad address.",22:"File too large.",23:"Host is unreachable.",24:"Identifier removed.",25:"Illegal byte sequence.",26:"Operation in progress.",27:"Interrupted function.",28:"Invalid argument.",29:"I/O error.",30:"Socket is connected.",31:"There is a directory under that path.",32:"Too many levels of symbolic links.",33:"File descriptor value too large.",34:"Too many links.",35:"Message too large.",36:"Reserved.",37:"Filename too long.",38:"Network is down.",39:"Connection aborted by network.",40:"Network unreachable.",41:"Too many files open in system.",42:"No buffer space available.",43:"No such device.",44:"There is no such file or directory OR the parent directory does not exist.",45:"Executable file format error.",46:"No locks available.",47:"Reserved.",48:"Not enough space.",49:"No message of the desired type.",50:"Protocol not available.",51:"No space left on device.",52:"Function not supported.",53:"The socket is not connected.",54:"Not a directory or a symbolic link to a directory.",55:"Directory not empty.",56:"State not recoverable.",57:"Not a socket.",58:"Not supported, or operation not supported on socket.",59:"Inappropriate I/O control operation.",60:"No such device or address.",61:"Value too large to be stored in data type.",62:"Previous owner died.",63:"Operation not permitted.",64:"Broken pipe.",65:"Protocol error.",66:"Protocol not supported.",67:"Protocol wrong type for socket.",68:"Result too large.",69:"Read-only file system.",70:"Invalid seek.",71:"No such process.",72:"Reserved.",73:"Connection timed out.",74:"Text file busy.",75:"Cross-device link.",76:"Extension: Capabilities insufficient."};function getEmscriptenFsError(t){const e=typeof t=="object"?t==null?void 0:t.errno:null;if(e in FileErrorCodes)return FileErrorCodes[e]}function rethrowFileSystemError(t=""){return function(r){return function(...s){try{return r.apply(this,s)}catch(n){const i=typeof n=="object"?n==null?void 0:n.errno:null;if(i in FileErrorCodes){const o=FileErrorCodes[i],a=typeof s[1]=="string"?s[1]:null,l=a!==null?t.replaceAll("{path}",a):t;throw new ErrnoError(i,`${l}: ${o}`,{cause:n})}throw n}}}}class FSHelpers{static readFileAsText(e,r){return new TextDecoder().decode(FSHelpers.readFileAsBuffer(e,r))}static readFileAsBuffer(e,r){return e.readFile(r)}static writeFile(e,r,s){e.writeFile(r,s)}static unlink(e,r){e.unlink(r)}static mv(e,r,s){try{const n=e.lookupPath(r).node.mount,i=FSHelpers.fileExists(e,s)?e.lookupPath(s).node.mount:e.lookupPath(util.dirname(s)).node.mount;n.mountpoint!==i.mountpoint?(FSHelpers.copyRecursive(e,r,s),FSHelpers.isDir(e,r)?FSHelpers.rmdir(e,r,{recursive:!0}):e.unlink(r)):e.rename(r,s)}catch(n){const i=getEmscriptenFsError(n);throw i?new Error(`Could not move ${r} to ${s}: ${i}`,{cause:n}):n}}static rmdir(e,r,s={recursive:!0}){const n=e.lookupPath(r,{follow:!1});if((n==null?void 0:n.node.mount.mountpoint)===r)throw new ErrnoError(10);s!=null&&s.recursive&&FSHelpers.listFiles(e,r).forEach(i=>{const o=`${r}/${i}`;FSHelpers.isDir(e,o)?FSHelpers.rmdir(e,o,s):FSHelpers.unlink(e,o)}),e.getPath(e.lookupPath(r).node)===e.cwd()&&e.chdir(util.joinPaths(e.cwd(),"..")),e.rmdir(r)}static listFiles(e,r,s={prependPath:!1}){if(!FSHelpers.fileExists(e,r))return[];try{const n=e.readdir(r).filter(i=>i!=="."&&i!=="..");if(s.prependPath){const i=r.replace(/\/$/,"");return n.map(o=>`${i}/${o}`)}return n}catch(n){return logger.logger.error(n,{path:r}),[]}}static isDir(e,r){return FSHelpers.fileExists(e,r)?e.isDir(e.lookupPath(r,{follow:!0}).node.mode):!1}static isFile(e,r){return FSHelpers.fileExists(e,r)?e.isFile(e.lookupPath(r,{follow:!0}).node.mode):!1}static symlink(e,r,s){return e.symlink(r,s)}static isSymlink(e,r){return FSHelpers.fileExists(e,r)?e.isLink(e.lookupPath(r).node.mode):!1}static readlink(e,r){return e.readlink(r)}static realpath(e,r){return e.lookupPath(r,{follow:!0}).path}static fileExists(e,r){try{return e.lookupPath(r),!0}catch{return!1}}static mkdir(e,r){e.mkdirTree(r)}static copyRecursive(e,r,s){const n=e.lookupPath(r).node;if(e.isDir(n.mode)){e.mkdirTree(s);const i=e.readdir(r).filter(o=>o!=="."&&o!=="..");for(const o of i)FSHelpers.copyRecursive(e,util.joinPaths(r,o),util.joinPaths(s,o))}else e.isLink(n.mode)?e.symlink(e.readlink(r),s):e.writeFile(s,e.readFile(r))}}FSHelpers.readFileAsText=rethrowFileSystemError('Could not read "{path}"')(FSHelpers.readFileAsText);FSHelpers.readFileAsBuffer=rethrowFileSystemError('Could not read "{path}"')(FSHelpers.readFileAsBuffer);FSHelpers.writeFile=rethrowFileSystemError('Could not write to "{path}"')(FSHelpers.writeFile);FSHelpers.unlink=rethrowFileSystemError('Could not unlink "{path}"')(FSHelpers.unlink);FSHelpers.rmdir=rethrowFileSystemError('Could not remove directory "{path}"')(FSHelpers.rmdir);FSHelpers.listFiles=rethrowFileSystemError('Could not list files in "{path}"')(FSHelpers.listFiles);FSHelpers.isDir=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.isDir);FSHelpers.isFile=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.isFile);FSHelpers.realpath=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.realpath);FSHelpers.fileExists=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.fileExists);FSHelpers.mkdir=rethrowFileSystemError('Could not create directory "{path}"')(FSHelpers.mkdir);FSHelpers.copyRecursive=rethrowFileSystemError('Could not copy files from "{path}"')(FSHelpers.copyRecursive);const _private=new WeakMap;class PHPWorker{constructor(e,r){this.absoluteUrl="",this.documentRoot="",_private.set(this,{monitor:r}),e&&this.__internal_setRequestHandler(e)}__internal_setRequestHandler(e){this.absoluteUrl=e.absoluteUrl,this.documentRoot=e.documentRoot,_private.set(this,{..._private.get(this),requestHandler:e})}__internal_getPHP(){return _private.get(this).php}__internal_getRequestHandler(){return _private.get(this).requestHandler}async setPrimaryPHP(e){_private.set(this,{..._private.get(this),php:e})}pathToInternalUrl(e){return _private.get(this).requestHandler.pathToInternalUrl(e)}internalUrlToPath(e){return _private.get(this).requestHandler.internalUrlToPath(e)}async onDownloadProgress(e){var r;return(r=_private.get(this).monitor)==null?void 0:r.addEventListener("progress",e)}async mv(e,r){return _private.get(this).php.mv(e,r)}async rmdir(e,r){return _private.get(this).php.rmdir(e,r)}async request(e){return await _private.get(this).requestHandler.request(e)}async run(e){const{php:r,reap:s}=await _private.get(this).requestHandler.processManager.acquirePHPInstance();try{return await r.run(e)}finally{s()}}chdir(e){return _private.get(this).php.chdir(e)}setSapiName(e){_private.get(this).php.setSapiName(e)}mkdir(e){return _private.get(this).php.mkdir(e)}mkdirTree(e){return _private.get(this).php.mkdirTree(e)}readFileAsText(e){return _private.get(this).php.readFileAsText(e)}readFileAsBuffer(e){return _private.get(this).php.readFileAsBuffer(e)}writeFile(e,r){return _private.get(this).php.writeFile(e,r)}unlink(e){return _private.get(this).php.unlink(e)}listFiles(e,r){return _private.get(this).php.listFiles(e,r)}isDir(e){return _private.get(this).php.isDir(e)}isFile(e){return _private.get(this).php.isFile(e)}fileExists(e){return _private.get(this).php.fileExists(e)}onMessage(e){return _private.get(this).php.onMessage(e)}defineConstant(e,r){_private.get(this).php.defineConstant(e,r)}addEventListener(e,r){_private.get(this).php.addEventListener(e,r)}removeEventListener(e,r){_private.get(this).php.removeEventListener(e,r)}async[Symbol.asyncDispose](){var e;await((e=_private.get(this).requestHandler)==null?void 0:e[Symbol.asyncDispose]())}}const responseTexts={500:"Internal Server Error",502:"Bad Gateway",404:"Not Found",403:"Forbidden",401:"Unauthorized",400:"Bad Request",301:"Moved Permanently",302:"Found",307:"Temporary Redirect",308:"Permanent Redirect",204:"No Content",201:"Created",200:"OK"};class StreamedPHPResponse{constructor(e,r,s,n){this.parsedHeaders=null,this.cachedStdoutText=null,this.cachedStderrText=null,this.headersStream=e,this.stdout=r,this.stderr=s,this.exitCode=n}async ok(){try{const e=await this.httpStatusCode;return e>=200&&e<400}catch{return!1}}get finished(){return Promise.allSettled([this.exitCode.finally(()=>{})]).then(()=>{})}get headers(){return this.getParsedHeaders().then(e=>e.headers)}get httpStatusCode(){return Promise.race([this.getParsedHeaders().then(e=>e.httpStatusCode),this.exitCode.then(e=>e!==0?500:void 0)]).then(e=>e!==void 0?e:this.getParsedHeaders().then(r=>r.httpStatusCode,()=>200)).catch(()=>500)}get stdoutText(){return this.cachedStdoutText||(this.cachedStdoutText=streamToText(this.stdout)),this.cachedStdoutText}get stderrText(){return this.cachedStderrText||(this.cachedStderrText=streamToText(this.stderr)),this.cachedStderrText}async getParsedHeaders(){return this.parsedHeaders||(this.parsedHeaders=parseHeadersStream(this.headersStream)),await this.parsedHeaders}}async function parseHeadersStream(t){const e=await streamToText(t);let r;try{r=JSON.parse(e)}catch{return{headers:{},httpStatusCode:200}}const s={};for(const n of r.headers){if(!n.includes(": "))continue;const i=n.indexOf(": "),o=n.substring(0,i).toLowerCase(),a=n.substring(i+2);o in s||(s[o]=[]),s[o].push(a)}return{headers:s,httpStatusCode:r.status}}async function streamToText(t){const e=t.pipeThrough(new TextDecoderStream).getReader(),r=[];for(;;){const{done:s,value:n}=await e.read();if(s)return r.join("");n&&r.push(n)}}class PHPResponse{constructor(e,r,s,n="",i=0){this.httpStatusCode=e,this.headers=r,this.bytes=s,this.exitCode=i,this.errors=n}static forHttpCode(e,r=""){return new PHPResponse(e,{},new TextEncoder().encode(r||responseTexts[e]||""))}static fromRawData(e){return new PHPResponse(e.httpStatusCode,e.headers,e.bytes,e.errors,e.exitCode)}static async fromStreamedResponse(e){return await e.finished,new PHPResponse(await e.httpStatusCode,await e.headers,new TextEncoder().encode(await e.stdoutText),await e.stderrText,await e.exitCode)}toRawData(){return{headers:this.headers,bytes:this.bytes,errors:this.errors,exitCode:this.exitCode,httpStatusCode:this.httpStatusCode}}get json(){return JSON.parse(this.text)}get text(){return new TextDecoder().decode(this.bytes)}}const RuntimeId=Symbol("RuntimeId"),loadedRuntimes=new Map;let lastRuntimeId=0;async function loadPHPRuntime(t,...e){const r=Object.assign({},...e),[s,n,i]=makePromise(),o=t.init(currentJsRuntime,{onAbort(l){i(l),logger.logger.error(l)},ENV:{},locateFile:l=>l,...r,noInitialRun:!0,onRuntimeInitialized(){r.onRuntimeInitialized&&r.onRuntimeInitialized(o),n()}});await s;const a=++lastRuntimeId;return o.FS,o.id=a,o.originalExit=o._exit,o._exit=function(l){return o.outboundNetworkProxyServer&&(o.outboundNetworkProxyServer.close(),o.outboundNetworkProxyServer.closeAllConnections()),loadedRuntimes.delete(a),o.originalExit(l)},o[RuntimeId]=a,loadedRuntimes.set(a,o),a}function getLoadedRuntime(t){return loadedRuntimes.get(t)}const currentJsRuntime=function(){var t;return typeof process<"u"&&((t=process.release)==null?void 0:t.name)==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"}(),makePromise=()=>{const t=[],e=new Promise((r,s)=>{t.push(r,s)});return t.unshift(e),t};var _a;const kError=Symbol("error"),kMessage=Symbol("message");class ErrorEvent2 extends(_a=Event,_a){constructor(e,r={}){super(e),this[kError]=r.error===void 0?null:r.error,this[kMessage]=r.message===void 0?"":r.message}get error(){return this[kError]}get message(){return this[kMessage]}}Object.defineProperty(ErrorEvent2.prototype,"error",{enumerable:!0});Object.defineProperty(ErrorEvent2.prototype,"message",{enumerable:!0});const ErrorEvent=typeof globalThis.ErrorEvent=="function"?globalThis.ErrorEvent:ErrorEvent2;function isExitCode(t){return t instanceof Error?(t==null?void 0:t.name)==="ExitStatus"&&"status"in t:!1}class UnhandledRejectionsTarget extends EventTarget{constructor(){super(...arguments),this.listenersCount=0}addEventListener(e,r,s){++this.listenersCount,super.addEventListener(e,r,s)}removeEventListener(e,r,s){--this.listenersCount,super.removeEventListener(e,r,s)}hasListeners(){return this.listenersCount>0}}function improveWASMErrorReporting(t){const e=new UnhandledRejectionsTarget;for(const r in t.wasmExports)if(typeof t.wasmExports[r]=="function"){const s=t.wasmExports[r];t.wasmExports[r]=function(...n){var i;try{return s(...n)}catch(o){if(!(o instanceof Error))throw o;t.lastAsyncifyStackSource&&(o.cause=t.lastAsyncifyStackSource);const a=clarifyErrorMessage(o,(i=t.lastAsyncifyStackSource)==null?void 0:i.stack);if(e.hasListeners()){o.message=a;const l=new ErrorEvent("error",{error:o});throw e.dispatchEvent(l),o}throw(!isExitCode(o)||o.status!==0)&&showCriticalErrorBox(a),o}}}return e}let functionsMaybeMissingFromAsyncify=[];function getFunctionsMaybeMissingFromAsyncify(){return functionsMaybeMissingFromAsyncify}function clarifyErrorMessage(t,e){if(t.message==="unreachable"){let r=UNREACHABLE_ERROR;e||(r+=`
|
|
1
|
+
"use strict";var re=Object.create;var q=Object.defineProperty;var se=Object.getOwnPropertyDescriptor;var ne=Object.getOwnPropertyNames;var ie=Object.getPrototypeOf,oe=Object.prototype.hasOwnProperty;var z=t=>{throw TypeError(t)};var ae=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ne(e))!oe.call(t,n)&&n!==r&&q(t,n,{get:()=>e[n],enumerable:!(s=se(e,n))||s.enumerable});return t};var le=(t,e,r)=>(r=t!=null?re(ie(t)):{},ae(e||!t||!t.__esModule?q(r,"default",{value:t,enumerable:!0}):r,t));var N=(t,e,r)=>e.has(t)||z("Cannot "+r);var u=(t,e,r)=>(N(t,e,"read from private field"),r?r.call(t):e.get(t)),_=(t,e,r)=>e.has(t)?z("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),f=(t,e,r,s)=>(N(t,e,"write to private field"),s?s.call(t,r):e.set(t,r),r),m=(t,e,r)=>(N(t,e,"access private method"),r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("@php-wasm/node-polyfills");const logger=require("@php-wasm/logger"),util=require("@php-wasm/util"),ini=require("ini"),streamCompression=require("@php-wasm/stream-compression");var _documentCurrentScript=typeof document<"u"?document.currentScript:null;class ErrnoError extends Error{constructor(e,r,s){super(r,s),this.name="ErrnoError",this.errno=e}}const FileErrorCodes={0:"No error occurred. System call completed successfully.",1:"Argument list too long.",2:"Permission denied.",3:"Address in use.",4:"Address not available.",5:"Address family not supported.",6:"Resource unavailable, or operation would block.",7:"Connection already in progress.",8:"Bad file descriptor.",9:"Bad message.",10:"Device or resource busy.",11:"Operation canceled.",12:"No child processes.",13:"Connection aborted.",14:"Connection refused.",15:"Connection reset.",16:"Resource deadlock would occur.",17:"Destination address required.",18:"Mathematics argument out of domain of function.",19:"Reserved.",20:"File exists.",21:"Bad address.",22:"File too large.",23:"Host is unreachable.",24:"Identifier removed.",25:"Illegal byte sequence.",26:"Operation in progress.",27:"Interrupted function.",28:"Invalid argument.",29:"I/O error.",30:"Socket is connected.",31:"There is a directory under that path.",32:"Too many levels of symbolic links.",33:"File descriptor value too large.",34:"Too many links.",35:"Message too large.",36:"Reserved.",37:"Filename too long.",38:"Network is down.",39:"Connection aborted by network.",40:"Network unreachable.",41:"Too many files open in system.",42:"No buffer space available.",43:"No such device.",44:"There is no such file or directory OR the parent directory does not exist.",45:"Executable file format error.",46:"No locks available.",47:"Reserved.",48:"Not enough space.",49:"No message of the desired type.",50:"Protocol not available.",51:"No space left on device.",52:"Function not supported.",53:"The socket is not connected.",54:"Not a directory or a symbolic link to a directory.",55:"Directory not empty.",56:"State not recoverable.",57:"Not a socket.",58:"Not supported, or operation not supported on socket.",59:"Inappropriate I/O control operation.",60:"No such device or address.",61:"Value too large to be stored in data type.",62:"Previous owner died.",63:"Operation not permitted.",64:"Broken pipe.",65:"Protocol error.",66:"Protocol not supported.",67:"Protocol wrong type for socket.",68:"Result too large.",69:"Read-only file system.",70:"Invalid seek.",71:"No such process.",72:"Reserved.",73:"Connection timed out.",74:"Text file busy.",75:"Cross-device link.",76:"Extension: Capabilities insufficient."};function getEmscriptenFsError(t){const e=typeof t=="object"?t==null?void 0:t.errno:null;if(e in FileErrorCodes)return FileErrorCodes[e]}function rethrowFileSystemError(t=""){return function(r){return function(...s){try{return r.apply(this,s)}catch(n){const i=typeof n=="object"?n==null?void 0:n.errno:null;if(i in FileErrorCodes){const o=FileErrorCodes[i],a=typeof s[1]=="string"?s[1]:null,l=a!==null?t.replaceAll("{path}",a):t;throw new ErrnoError(i,`${l}: ${o}`,{cause:n})}throw n}}}}class FSHelpers{static readFileAsText(e,r){return new TextDecoder().decode(FSHelpers.readFileAsBuffer(e,r))}static readFileAsBuffer(e,r){return e.readFile(r)}static writeFile(e,r,s){e.writeFile(r,s)}static unlink(e,r){e.unlink(r)}static mv(e,r,s){try{const n=e.lookupPath(r).node.mount,i=FSHelpers.fileExists(e,s)?e.lookupPath(s).node.mount:e.lookupPath(util.dirname(s)).node.mount;n.mountpoint!==i.mountpoint?(FSHelpers.copyRecursive(e,r,s),FSHelpers.isDir(e,r)?FSHelpers.rmdir(e,r,{recursive:!0}):e.unlink(r)):e.rename(r,s)}catch(n){const i=getEmscriptenFsError(n);throw i?new Error(`Could not move ${r} to ${s}: ${i}`,{cause:n}):n}}static rmdir(e,r,s={recursive:!0}){const n=e.lookupPath(r,{follow:!1});if((n==null?void 0:n.node.mount.mountpoint)===r)throw new ErrnoError(10);s!=null&&s.recursive&&FSHelpers.listFiles(e,r).forEach(i=>{const o=`${r}/${i}`;FSHelpers.isDir(e,o)?FSHelpers.rmdir(e,o,s):FSHelpers.unlink(e,o)}),e.getPath(e.lookupPath(r).node)===e.cwd()&&e.chdir(util.joinPaths(e.cwd(),"..")),e.rmdir(r)}static listFiles(e,r,s={prependPath:!1}){if(!FSHelpers.fileExists(e,r))return[];try{const n=e.readdir(r).filter(i=>i!=="."&&i!=="..");if(s.prependPath){const i=r.replace(/\/$/,"");return n.map(o=>`${i}/${o}`)}return n}catch(n){return logger.logger.error(n,{path:r}),[]}}static isDir(e,r){return FSHelpers.fileExists(e,r)?e.isDir(e.lookupPath(r,{follow:!0}).node.mode):!1}static isFile(e,r){return FSHelpers.fileExists(e,r)?e.isFile(e.lookupPath(r,{follow:!0}).node.mode):!1}static symlink(e,r,s){return e.symlink(r,s)}static isSymlink(e,r){return FSHelpers.fileExists(e,r)?e.isLink(e.lookupPath(r).node.mode):!1}static readlink(e,r){return e.readlink(r)}static realpath(e,r){return e.lookupPath(r,{follow:!0}).path}static fileExists(e,r){try{return e.lookupPath(r),!0}catch{return!1}}static mkdir(e,r){e.mkdirTree(r)}static copyRecursive(e,r,s){const n=e.lookupPath(r).node;if(e.isDir(n.mode)){e.mkdirTree(s);const i=e.readdir(r).filter(o=>o!=="."&&o!=="..");for(const o of i)FSHelpers.copyRecursive(e,util.joinPaths(r,o),util.joinPaths(s,o))}else e.isLink(n.mode)?e.symlink(e.readlink(r),s):e.writeFile(s,e.readFile(r))}}FSHelpers.readFileAsText=rethrowFileSystemError('Could not read "{path}"')(FSHelpers.readFileAsText);FSHelpers.readFileAsBuffer=rethrowFileSystemError('Could not read "{path}"')(FSHelpers.readFileAsBuffer);FSHelpers.writeFile=rethrowFileSystemError('Could not write to "{path}"')(FSHelpers.writeFile);FSHelpers.unlink=rethrowFileSystemError('Could not unlink "{path}"')(FSHelpers.unlink);FSHelpers.rmdir=rethrowFileSystemError('Could not remove directory "{path}"')(FSHelpers.rmdir);FSHelpers.listFiles=rethrowFileSystemError('Could not list files in "{path}"')(FSHelpers.listFiles);FSHelpers.isDir=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.isDir);FSHelpers.isFile=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.isFile);FSHelpers.realpath=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.realpath);FSHelpers.fileExists=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.fileExists);FSHelpers.mkdir=rethrowFileSystemError('Could not create directory "{path}"')(FSHelpers.mkdir);FSHelpers.copyRecursive=rethrowFileSystemError('Could not copy files from "{path}"')(FSHelpers.copyRecursive);const _private=new WeakMap;class PHPWorker{constructor(e,r){this.absoluteUrl="",this.documentRoot="",_private.set(this,{monitor:r}),e&&this.__internal_setRequestHandler(e)}__internal_setRequestHandler(e){this.absoluteUrl=e.absoluteUrl,this.documentRoot=e.documentRoot,_private.set(this,{..._private.get(this),requestHandler:e})}__internal_getPHP(){return _private.get(this).php}__internal_getRequestHandler(){return _private.get(this).requestHandler}async setPrimaryPHP(e){_private.set(this,{..._private.get(this),php:e})}pathToInternalUrl(e){return _private.get(this).requestHandler.pathToInternalUrl(e)}internalUrlToPath(e){return _private.get(this).requestHandler.internalUrlToPath(e)}async onDownloadProgress(e){var r;return(r=_private.get(this).monitor)==null?void 0:r.addEventListener("progress",e)}async mv(e,r){return _private.get(this).php.mv(e,r)}async rmdir(e,r){return _private.get(this).php.rmdir(e,r)}async request(e){return await _private.get(this).requestHandler.request(e)}async run(e){const{php:r,reap:s}=await _private.get(this).requestHandler.processManager.acquirePHPInstance();try{return await r.run(e)}finally{s()}}chdir(e){return _private.get(this).php.chdir(e)}setSapiName(e){_private.get(this).php.setSapiName(e)}mkdir(e){return _private.get(this).php.mkdir(e)}mkdirTree(e){return _private.get(this).php.mkdirTree(e)}readFileAsText(e){return _private.get(this).php.readFileAsText(e)}readFileAsBuffer(e){return _private.get(this).php.readFileAsBuffer(e)}writeFile(e,r){return _private.get(this).php.writeFile(e,r)}unlink(e){return _private.get(this).php.unlink(e)}listFiles(e,r){return _private.get(this).php.listFiles(e,r)}isDir(e){return _private.get(this).php.isDir(e)}isFile(e){return _private.get(this).php.isFile(e)}fileExists(e){return _private.get(this).php.fileExists(e)}onMessage(e){return _private.get(this).php.onMessage(e)}defineConstant(e,r){_private.get(this).php.defineConstant(e,r)}addEventListener(e,r){_private.get(this).php.addEventListener(e,r)}removeEventListener(e,r){_private.get(this).php.removeEventListener(e,r)}async[Symbol.asyncDispose](){var e;await((e=_private.get(this).requestHandler)==null?void 0:e[Symbol.asyncDispose]())}}const responseTexts={500:"Internal Server Error",502:"Bad Gateway",404:"Not Found",403:"Forbidden",401:"Unauthorized",400:"Bad Request",301:"Moved Permanently",302:"Found",307:"Temporary Redirect",308:"Permanent Redirect",204:"No Content",201:"Created",200:"OK"};class StreamedPHPResponse{constructor(e,r,s,n){this.parsedHeaders=null,this.cachedStdoutText=null,this.cachedStderrText=null,this.headersStream=e,this.stdout=r,this.stderr=s,this.exitCode=n}async ok(){try{const e=await this.httpStatusCode;return e>=200&&e<400}catch{return!1}}get finished(){return Promise.allSettled([this.exitCode.finally(()=>{})]).then(()=>{})}get headers(){return this.getParsedHeaders().then(e=>e.headers)}get httpStatusCode(){return this.getParsedHeaders().then(e=>e.httpStatusCode).then(e=>e!==void 0?e:this.getParsedHeaders().then(r=>r.httpStatusCode,()=>200)).catch(()=>500)}get stdoutText(){return this.cachedStdoutText||(this.cachedStdoutText=streamToText(this.stdout)),this.cachedStdoutText}get stderrText(){return this.cachedStderrText||(this.cachedStderrText=streamToText(this.stderr)),this.cachedStderrText}async getParsedHeaders(){return this.parsedHeaders||(this.parsedHeaders=parseHeadersStream(this.headersStream)),await this.parsedHeaders}}async function parseHeadersStream(t){const e=await streamToText(t);let r;try{r=JSON.parse(e)}catch{return{headers:{},httpStatusCode:200}}const s={};for(const n of r.headers){if(!n.includes(": "))continue;const i=n.indexOf(": "),o=n.substring(0,i).toLowerCase(),a=n.substring(i+2);o in s||(s[o]=[]),s[o].push(a)}return{headers:s,httpStatusCode:r.status}}async function streamToText(t){const e=t.pipeThrough(new TextDecoderStream).getReader(),r=[];for(;;){const{done:s,value:n}=await e.read();if(s)return r.join("");n&&r.push(n)}}class PHPResponse{constructor(e,r,s,n="",i=0){this.httpStatusCode=e,this.headers=r,this.bytes=s,this.exitCode=i,this.errors=n}static forHttpCode(e,r=""){return new PHPResponse(e,{},new TextEncoder().encode(r||responseTexts[e]||""))}static fromRawData(e){return new PHPResponse(e.httpStatusCode,e.headers,e.bytes,e.errors,e.exitCode)}static async fromStreamedResponse(e){return await e.finished,new PHPResponse(await e.httpStatusCode,await e.headers,new TextEncoder().encode(await e.stdoutText),await e.stderrText,await e.exitCode)}ok(){return this.httpStatusCode>=200&&this.httpStatusCode<400}toRawData(){return{headers:this.headers,bytes:this.bytes,errors:this.errors,exitCode:this.exitCode,httpStatusCode:this.httpStatusCode}}get json(){return JSON.parse(this.text)}get text(){return new TextDecoder().decode(this.bytes)}}const RuntimeId=Symbol("RuntimeId"),loadedRuntimes=new Map;let lastRuntimeId=0;async function loadPHPRuntime(t,...e){const r=Object.assign({},...e),[s,n,i]=makePromise(),o=t.init(currentJsRuntime,{onAbort(l){i(l),logger.logger.error(l)},ENV:{},locateFile:l=>l,...r,noInitialRun:!0,onRuntimeInitialized(){r.onRuntimeInitialized&&r.onRuntimeInitialized(o),n()}});await s;const a=++lastRuntimeId;return o.FS,o.id=a,o.originalExit=o._exit,o._exit=function(l){return o.outboundNetworkProxyServer&&(o.outboundNetworkProxyServer.close(),o.outboundNetworkProxyServer.closeAllConnections()),loadedRuntimes.delete(a),o.originalExit(l)},o[RuntimeId]=a,loadedRuntimes.set(a,o),a}function getLoadedRuntime(t){return loadedRuntimes.get(t)}const currentJsRuntime=function(){var t;return typeof process<"u"&&((t=process.release)==null?void 0:t.name)==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"}(),makePromise=()=>{const t=[],e=new Promise((r,s)=>{t.push(r,s)});return t.unshift(e),t};var _a;const kError=Symbol("error"),kMessage=Symbol("message");class ErrorEvent2 extends(_a=Event,_a){constructor(e,r={}){super(e),this[kError]=r.error===void 0?null:r.error,this[kMessage]=r.message===void 0?"":r.message}get error(){return this[kError]}get message(){return this[kMessage]}}Object.defineProperty(ErrorEvent2.prototype,"error",{enumerable:!0});Object.defineProperty(ErrorEvent2.prototype,"message",{enumerable:!0});const ErrorEvent=typeof globalThis.ErrorEvent=="function"?globalThis.ErrorEvent:ErrorEvent2;function isExitCode(t){return t instanceof Error?(t==null?void 0:t.name)==="ExitStatus"&&"status"in t:!1}class UnhandledRejectionsTarget extends EventTarget{constructor(){super(...arguments),this.listenersCount=0}addEventListener(e,r,s){++this.listenersCount,super.addEventListener(e,r,s)}removeEventListener(e,r,s){--this.listenersCount,super.removeEventListener(e,r,s)}hasListeners(){return this.listenersCount>0}}function improveWASMErrorReporting(t){const e=new UnhandledRejectionsTarget;for(const r in t.wasmExports)if(typeof t.wasmExports[r]=="function"){const s=t.wasmExports[r];t.wasmExports[r]=function(...n){var i;try{return s(...n)}catch(o){if(!(o instanceof Error))throw o;t.lastAsyncifyStackSource&&(o.cause=t.lastAsyncifyStackSource);const a=clarifyErrorMessage(o,(i=t.lastAsyncifyStackSource)==null?void 0:i.stack);if(e.hasListeners()){o.message=a;const l=new ErrorEvent("error",{error:o});throw e.dispatchEvent(l),o}throw(!isExitCode(o)||o.status!==0)&&showCriticalErrorBox(a),o}}}return e}let functionsMaybeMissingFromAsyncify=[];function getFunctionsMaybeMissingFromAsyncify(){return functionsMaybeMissingFromAsyncify}function clarifyErrorMessage(t,e){if(t.message==="unreachable"){let r=UNREACHABLE_ERROR;e||(r+=`
|
|
2
2
|
|
|
3
3
|
This stack trace is lacking. For a better one initialize
|
|
4
4
|
the PHP runtime with debug: true, e.g. loadNodeRuntime('8.1', { emscriptenOptions: { debug: true } }).
|
|
@@ -54,7 +54,7 @@ ${bold} WASM ERROR${reset}${redBg}`);for(const e of t.split(`
|
|
|
54
54
|
${r.text}
|
|
55
55
|
|
|
56
56
|
=== Stderr ===
|
|
57
|
-
${r.errors}`,r,"request");return r}async runStream(t){if(this.cliCalled)throw new Error("php.runStream() can only be called if php.cli() was not called before. The two methods set a conflicting C-level global state.");this.runStreamCalled=!0;const e=await this.semaphore.acquire();let r;const s=m(this,h,U).call(this,async()=>{if(u(this,x)||(await m(this,h,$).call(this),f(this,x,!0)),t.scriptPath&&!this.fileExists(t.scriptPath))throw new Error(`The script path "${t.scriptPath}" does not exist.`);m(this,h,B).call(this,t.relativeUri||""),m(this,h,Y).call(this,t.method||"GET");const
|
|
57
|
+
${r.errors}`,r,"request");return r}async runStream(t){if(this.cliCalled)throw new Error("php.runStream() can only be called if php.cli() was not called before. The two methods set a conflicting C-level global state.");this.runStreamCalled=!0;const e=await this.semaphore.acquire();let r;const s=m(this,h,U).call(this,async()=>{if(u(this,x)||(await m(this,h,$).call(this),f(this,x,!0)),t.scriptPath&&!this.fileExists(t.scriptPath))throw new Error(`The script path "${t.scriptPath}" does not exist.`);m(this,h,B).call(this,t.relativeUri||""),m(this,h,Y).call(this,t.method||"GET");const i=normalizeHeaders(t.headers||{}),o=i.host||"example.com:443",a=m(this,h,J).call(this,o,t.protocol||"http");if(m(this,h,V).call(this,o),m(this,h,G).call(this,a),m(this,h,K).call(this,i),t.body&&(r=m(this,h,X).call(this,t.body)),typeof t.code=="string")this.writeFile("/internal/eval.php",t.code),m(this,h,L).call(this,"/internal/eval.php");else if(typeof t.scriptPath=="string")m(this,h,L).call(this,t.scriptPath||"");else throw new TypeError("The request object must have either a `code` or a `scriptPath` property.");const l=m(this,h,W).call(this,t.$_SERVER,i,a);for(const p in l)m(this,h,Q).call(this,p,l[p]);const c=t.env||{};for(const p in c)m(this,h,O).call(this,p,c[p]);return await this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0})}),n=()=>{if(r)try{this[__private__dont__use].free(r)}catch(i){logger.logger.error(i)}e(),this.dispatchEvent({type:"request.end"})};return s.then(i=>(i.finished.finally(n),i),i=>{throw n(),i})}defineConstant(t,e){let r={};try{r=JSON.parse(this.fileExists("/internal/shared/consts.json")&&this.readFileAsText("/internal/shared/consts.json")||"{}")}catch{}this.writeFile("/internal/shared/consts.json",JSON.stringify({...r,[t]:e}))}mkdir(t){return FSHelpers.mkdir(this[__private__dont__use].FS,t)}mkdirTree(t){return FSHelpers.mkdir(this[__private__dont__use].FS,t)}readFileAsText(t){return FSHelpers.readFileAsText(this[__private__dont__use].FS,t)}readFileAsBuffer(t){return FSHelpers.readFileAsBuffer(this[__private__dont__use].FS,t)}writeFile(t,e){return FSHelpers.writeFile(this[__private__dont__use].FS,t,e)}unlink(t){return FSHelpers.unlink(this[__private__dont__use].FS,t)}mv(t,e){return FSHelpers.mv(this[__private__dont__use].FS,t,e)}rmdir(t,e={recursive:!0}){return FSHelpers.rmdir(this[__private__dont__use].FS,t,e)}listFiles(t,e={prependPath:!1}){return FSHelpers.listFiles(this[__private__dont__use].FS,t,e)}isDir(t){return FSHelpers.isDir(this[__private__dont__use].FS,t)}isFile(t){return FSHelpers.isFile(this[__private__dont__use].FS,t)}symlink(t,e){return FSHelpers.symlink(this[__private__dont__use].FS,t,e)}isSymlink(t){return FSHelpers.isSymlink(this[__private__dont__use].FS,t)}readlink(t){return FSHelpers.readlink(this[__private__dont__use].FS,t)}realpath(t){return FSHelpers.realpath(this[__private__dont__use].FS,t)}fileExists(t){return FSHelpers.fileExists(this[__private__dont__use].FS,t)}async hotSwapPHPRuntime(t,e){const r=this[__private__dont__use].FS,s=[];for(const[n,i]of Object.entries(u(this,T)))s.push({mountHandler:i.mountHandler,vfsPath:n}),await i.unmount();try{this.exit()}catch{}this.initializeRuntime(t),u(this,k)&&this.setSapiName(u(this,k)),copyFS(r,this[__private__dont__use].FS,"/internal"),e&©FS(r,this[__private__dont__use].FS,e);for(const{mountHandler:n,vfsPath:i}of s)this.mkdir(i),await this.mount(i,n)}async mount(t,e){const r=await e(this,this[__private__dont__use].FS,t),s={mountHandler:e,unmount:async()=>{await r(),delete u(this,T)[t]}};return u(this,T)[t]=s,()=>{s.unmount()}}async cli(t,e={}){if(this.cliCalled)throw new Error("php.cli() can only be called once. The method sets a C-level global state that does not allow repeated calls.");if(this.runStreamCalled)throw new Error("php.cli() can only be called if php.runStream() was not called before. The two methods set a conflicting C-level global state.");this.cliCalled=!0;const r=await this.semaphore.acquire(),s=e.env||{};for(const[n,i]of Object.entries(s))m(this,h,O).call(this,n,i);t=[t[0],"-c",PHP_INI_PATH,...t.slice(1)];for(const n of t)this[__private__dont__use].ccall("wasm_add_cli_arg",null,[STRING],[n]);return await m(this,h,U).call(this,()=>this[__private__dont__use].ccall("run_cli",null,[],[],{async:!0})).then(n=>(n.exitCode.finally(r),n))}setSkipShebang(t){this[__private__dont__use].ccall("wasm_set_skip_shebang",null,[NUMBER],[t?1:0])}exit(t=0){this.dispatchEvent({type:"runtime.beforedestroy"});try{this[__private__dont__use]._exit(t)}catch{}f(this,x,!1),f(this,E,null),this[__private__dont__use]&&(delete this[__private__dont__use].onMessage,delete this[__private__dont__use])}[Symbol.dispose](){u(this,x)&&this.exit(0)}}k=new WeakMap,x=new WeakMap,E=new WeakMap,g=new WeakMap,S=new WeakMap,T=new WeakMap,h=new WeakSet,W=function(t,e,r){const s={...t||{}};s.HTTPS=s.HTTPS||r===443?"on":"off";for(const n in e){let i="HTTP_";["content-type","content-length"].includes(n.toLowerCase())&&(i=""),s[`${i}${n.toUpperCase().replace(/-/g,"_")}`]=e[n]}return s},$=function(){return this[__private__dont__use].ccall("php_wasm_init",null,[],[],{isAsync:!0})},B=function(t){this[__private__dont__use].ccall("wasm_set_request_uri",null,[STRING],[t]);let e="";t.includes("?")&&(e=t.substring(t.indexOf("?")+1)),this[__private__dont__use].ccall("wasm_set_query_string",null,[STRING],[e])},V=function(t){this[__private__dont__use].ccall("wasm_set_request_host",null,[STRING],[t])},G=function(t){this[__private__dont__use].ccall("wasm_set_request_port",null,[NUMBER],[t])},J=function(t,e){let r;try{r=parseInt(new URL(t).port,10)}catch{}return(!r||isNaN(r)||r===80)&&(r=e==="https"?443:80),r},Y=function(t){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[t])},K=function(t){t.cookie&&this[__private__dont__use].ccall("wasm_set_cookies",null,[STRING],[t.cookie]),t["content-type"]&&this[__private__dont__use].ccall("wasm_set_content_type",null,[STRING],[t["content-type"]]),t["content-length"]&&this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[parseInt(t["content-length"],10)])},X=function(t){let e,r;typeof t=="string"?(logger.logger.warn("Passing a string as the request body is deprecated. Please use a Uint8Array instead. See https://github.com/WordPress/wordpress-playground/issues/997 for more details"),r=this[__private__dont__use].lengthBytesUTF8(t),e=r+1):(r=t.byteLength,e=t.byteLength);const s=this[__private__dont__use].malloc(e);if(!s)throw new Error("Could not allocate memory for the request body.");return typeof t=="string"?this[__private__dont__use].stringToUTF8(t,s,e+1):this[__private__dont__use].HEAPU8.set(t,s),this[__private__dont__use].ccall("wasm_set_request_body",null,[NUMBER],[s]),this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[r]),s},L=function(t){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[t])},Q=function(t,e){this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[t,e])},O=function(t,e){this[__private__dont__use].ccall("wasm_add_ENV_entry",null,[STRING,STRING],[t,e])},U=async function(t){const e=this[__private__dont__use],r=await createInvertedReadableStream();e.onHeaders=d=>{a||s||r.controller.enqueue(d.slice())};let s=!1;const n=()=>{s||(s=!0,r.controller.close())},i=await createInvertedReadableStream();e.onStdout=d=>{n(),!a&&i.controller.enqueue(d.slice())};const o=await createInvertedReadableStream();e.onStderr=d=>{a||o.controller.enqueue(d.slice())};let a=!1,l;const p=(async()=>{var d;try{return await Promise.race([t(),new Promise((w,b)=>{var j;l=D=>{isExitCode(D.error)||b(D.error)},(j=u(this,E))==null||j.addEventListener("error",l,{once:!0})})])}catch(y){if(isExitCode(y))return y.status;i.controller.error(y),o.controller.error(y),r.controller.error(y),a=!0;for(const w in this)typeof this[w]=="function"&&(this[w]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});throw this.functionsMaybeMissingFromAsyncify=getFunctionsMaybeMissingFromAsyncify(),y}finally{a||(i.controller.close(),o.controller.close(),n(),a=!0),(d=u(this,E))==null||d.removeEventListener("error",l)}})().then(d=>(d!==0&&this.dispatchEvent({type:"request.error",error:new Error(`PHP.run() failed with exit code ${d}.`),source:"php-wasm"}),d),d=>{throw this.dispatchEvent({type:"request.error",error:d,source:d.source??"php-wasm"}),d});return new StreamedPHPResponse(r.stream,i.stream,o.stream,p)};function normalizeHeaders(t){const e={};for(const r in t)e[r.toLowerCase()]=t[r];return e}function copyFS(t,e,r){let s;try{s=t.lookupPath(r)}catch{return}if(!("contents"in s.node))return;if(!t.isDir(s.node.mode)){e.writeFile(r,t.readFile(r));return}e.mkdirTree(r);const n=t.readdir(r).filter(i=>i!=="."&&i!=="..");for(const i of n)copyFS(t,e,util.joinPaths(r,i))}async function createInvertedReadableStream(t={}){let e;const r=new Promise(i=>{e=i}),s=new ReadableStream({...t,start(i){if(e(i),t.start)return t.start(i)}}),n=await r;return{stream:s,controller:n}}async function getPhpIniEntries(t,e){const r=ini.parse(await t.readFileAsText(PHP_INI_PATH));if(e===void 0)return r;const s={};for(const n of e)s[n]=r[n];return s}async function setPhpIniEntries(t,e){const r=ini.parse(await t.readFileAsText(PHP_INI_PATH));for(const[s,n]of Object.entries(e))n==null?delete r[s]:r[s]=n;await t.writeFile(PHP_INI_PATH,ini.stringify(r))}async function withPHPIniValues(t,e,r){const s=await t.readFileAsText(PHP_INI_PATH);try{return await setPhpIniEntries(t,e),await r()}finally{await t.writeFile(PHP_INI_PATH,s)}}async function printDebugDetails(t,e){e&&printResponseDebugDetails(await PHPResponse.fromStreamedResponse(e)),await prettyPrintFullStackTrace(t)}async function prettyPrintFullStackTrace(t){let e=t,r=!0;for(;e;)r||process.stderr.write(`
|
|
58
58
|
Caused by:
|
|
59
59
|
|
|
60
60
|
`),process.stderr.write(e.originalErrorClassName??e.name),process.stderr.write(": "+e.message+`
|
|
@@ -86,7 +86,7 @@ ${JSON.stringify(t.headers,null,2)}
|
|
|
86
86
|
`)),n.push(`\r
|
|
87
87
|
`),c instanceof File?n.push(await fileToUint8Array(c)):n.push(c),n.push(`\r
|
|
88
88
|
`);n.push(`--${e}--\r
|
|
89
|
-
`);const i=n.reduce((l,c)=>l+c.length,0),o=new Uint8Array(i);let a=0;for(const l of n)o.set(typeof l=="string"?s.encode(l):l,a),a+=l.length;return{bytes:o,contentType:r}}function fileToUint8Array(t){return t.arrayBuffer().then(e=>new Uint8Array(e))}const _default="application/octet-stream",asx="video/x-ms-asf",atom="application/atom+xml",avi="video/x-msvideo",avif="image/avif",bin="application/octet-stream",bmp="image/x-ms-bmp",cco="application/x-cocoa",css="text/css",data="application/octet-stream",deb="application/octet-stream",der="application/x-x509-ca-cert",dmg="application/octet-stream",doc="application/msword",docx="application/vnd.openxmlformats-officedocument.wordprocessingml.document",eot="application/vnd.ms-fontobject",flv="video/x-flv",gif="image/gif",gz="application/gzip",hqx="application/mac-binhex40",htc="text/x-component",html="text/html",ico="image/x-icon",iso="application/octet-stream",jad="text/vnd.sun.j2me.app-descriptor",jar="application/java-archive",jardiff="application/x-java-archive-diff",jng="image/x-jng",jnlp="application/x-java-jnlp-file",jpg="image/jpeg",jpeg="image/jpeg",js="application/javascript",json="application/json",kml="application/vnd.google-earth.kml+xml",kmz="application/vnd.google-earth.kmz",m3u8="application/vnd.apple.mpegurl",m4a="audio/x-m4a",m4v="video/x-m4v",md="text/plain",mid="audio/midi",mml="text/mathml",mng="video/x-mng",mov="video/quicktime",mp3="audio/mpeg",mp4="video/mp4",mpeg="video/mpeg",msi="application/octet-stream",odg="application/vnd.oasis.opendocument.graphics",odp="application/vnd.oasis.opendocument.presentation",ods="application/vnd.oasis.opendocument.spreadsheet",odt="application/vnd.oasis.opendocument.text",ogg="audio/ogg",otf="font/otf",pdf="application/pdf",pl="application/x-perl",png="image/png",ppt="application/vnd.ms-powerpoint",pptx="application/vnd.openxmlformats-officedocument.presentationml.presentation",prc="application/x-pilot",ps="application/postscript",ra="audio/x-realaudio",rar="application/x-rar-compressed",rpm="application/x-redhat-package-manager",rss="application/rss+xml",rtf="application/rtf",run="application/x-makeself",sea="application/x-sea",sit="application/x-stuffit",svg="image/svg+xml",swf="application/x-shockwave-flash",tcl="application/x-tcl",tar="application/x-tar",tif="image/tiff",ts="video/mp2t",ttf="font/ttf",txt="text/plain",wasm="application/wasm",wbmp="image/vnd.wap.wbmp",webm="video/webm",webp="image/webp",wml="text/vnd.wap.wml",wmlc="application/vnd.wap.wmlc",wmv="video/x-ms-wmv",woff="font/woff",woff2="font/woff2",xhtml="application/xhtml+xml",xls="application/vnd.ms-excel",xlsx="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml="text/xml",xpi="application/x-xpinstall",xspf="application/xspf+xml",zip="application/zip",mimeTypes={_default,"3gpp":"video/3gpp","7z":"application/x-7z-compressed",asx,atom,avi,avif,bin,bmp,cco,css,data,deb,der,dmg,doc,docx,eot,flv,gif,gz,hqx,htc,html,ico,iso,jad,jar,jardiff,jng,jnlp,jpg,jpeg,js,json,kml,kmz,m3u8,m4a,m4v,md,mid,mml,mng,mov,mp3,mp4,mpeg,msi,odg,odp,ods,odt,ogg,otf,pdf,pl,png,ppt,pptx,prc,ps,ra,rar,rpm,rss,rtf,run,sea,sit,svg,swf,tcl,tar,tif,ts,ttf,txt,wasm,wbmp,webm,webp,wml,wmlc,wmv,woff,woff2,xhtml,xls,xlsx,xml,xpi,xspf,zip};var v,C,M,F,I,P,A,R,H,Z,ee,te;class PHPRequestHandler{constructor(e){_(this,H);_(this,v);_(this,C);_(this,M);_(this,F);_(this,I);_(this,P);_(this,A);_(this,R);const{documentRoot:r="/www/",absoluteUrl:s=typeof location=="object"?location.href:DEFAULT_BASE_URL,rewriteRules:n=[],getFileNotFoundAction:i=()=>({type:"404"})}=e;"processManager"in e?this.processManager=e.processManager:this.processManager=new PHPProcessManager({phpFactory:async l=>{const c=await e.phpFactory({...l,requestHandler:this});return c.isDir(r)||c.mkdir(r),c.chdir(r),c.requestHandler=this,c},maxPhpInstances:e.maxPhpInstances}),f(this,R,e.cookieStore===void 0?new HttpCookieStore:e.cookieStore),f(this,v,r);const o=new URL(s);f(this,M,o.hostname),f(this,F,o.port?Number(o.port):o.protocol==="https:"?443:80),f(this,C,(o.protocol||"").replace(":",""));const a=u(this,F)!==443&&u(this,F)!==80;f(this,I,[u(this,M),a?`:${u(this,F)}`:""].join("")),f(this,P,o.pathname.replace(/\/+$/,"")),f(this,A,[`${u(this,C)}://`,u(this,I),u(this,P)].join("")),this.rewriteRules=n,this.getFileNotFoundAction=i}async getPrimaryPhp(){return await this.processManager.getPrimaryPhp()}pathToInternalUrl(e){return`${this.absoluteUrl}${e}`}internalUrlToPath(e){const r=new URL(e);return r.pathname.startsWith(u(this,P))&&(r.pathname=r.pathname.slice(u(this,P).length)),toRelativeUrl(r)}get absoluteUrl(){return u(this,A)}get documentRoot(){return u(this,v)}async request(e){const r=URL.canParse(e.url),s=new URL(e.url.split("#")[0],r?void 0:DEFAULT_BASE_URL),n=applyRewriteRules(removePathPrefix(decodeURIComponent(s.pathname),u(this,P)),this.rewriteRules),i=await this.getPrimaryPhp();let o=util.joinPaths(u(this,v),n);if(i.isDir(o)){if(!o.endsWith("/"))return new PHPResponse(301,{Location:[`${s.pathname}/`]},new Uint8Array(0));for(const a of["index.php","index.html"]){const l=util.joinPaths(o,a);if(i.isFile(l)){o=l;break}}}if(!i.isFile(o)){const a=this.getFileNotFoundAction(n);switch(a.type){case"response":return a.response;case"internal-redirect":o=util.joinPaths(u(this,v),a.uri);break;case"404":return PHPResponse.forHttpCode(404);default:throw new Error(`Unsupported file-not-found action type: '${a.type}'`)}}if(i.isFile(o))if(o.endsWith(".php")){const a={...e,url:s.toString()};return m(this,H,ee).call(this,a,o)}else return m(this,H,Z).call(this,i,o);else return PHPResponse.forHttpCode(404)}async[Symbol.asyncDispose](){await this.processManager[Symbol.asyncDispose]()}}v=new WeakMap,C=new WeakMap,M=new WeakMap,F=new WeakMap,I=new WeakMap,P=new WeakMap,A=new WeakMap,R=new WeakMap,H=new WeakSet,Z=function(e,r){const s=e.readFileAsBuffer(r);return new PHPResponse(200,{"content-length":[`${s.byteLength}`],"content-type":[inferMimeType(r)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},s)},ee=async function(e,r){let s;try{s=await this.processManager.acquirePHPInstance({considerPrimary:!0})}catch(n){return n instanceof MaxPhpInstancesError?PHPResponse.forHttpCode(502):PHPResponse.forHttpCode(500)}try{return await m(this,H,te).call(this,s.php,e,r)}finally{s.reap()}},te=async function(e,r,s){let n="GET";const i={host:u(this,I),...normalizeHeaders(r.headers||{})};u(this,R)&&(i.cookie=u(this,R).getCookieRequestHeader());let o=r.body;if(typeof o=="object"&&!(o instanceof Uint8Array)){n="POST";const{bytes:a,contentType:l}=await encodeAsMultipart(o);o=a,i["content-type"]=l}try{const a=await e.run({relativeUri:ensurePathPrefix(toRelativeUrl(new URL(r.url)),u(this,P)),protocol:u(this,C),method:r.method||n,$_SERVER:{REMOTE_ADDR:"127.0.0.1",DOCUMENT_ROOT:u(this,v),HTTPS:u(this,A).startsWith("https://")?"on":""},body:o,scriptPath:s,headers:i});return u(this,R)&&u(this,R).rememberCookiesFromResponseHeaders(a.headers),a}catch(a){const l=a;if(l!=null&&l.response)return l.response;throw a}};function inferMimeType(t){const e=t.split(".").pop();return mimeTypes[e]||mimeTypes._default}function applyRewriteRules(t,e){for(const r of e)if(new RegExp(r.match).test(t))return t.replace(r.match,r.replacement);return t}function rotatePHPRuntime({php:t,cwd:e,recreateRuntime:r,maxRequests:s=400}){let n=0;async function i(){const l=await t.semaphore.acquire();try{await t.hotSwapPHPRuntime(await r(),e),n=0}finally{l()}}async function o(){++n<s||await i()}async function a(l){l.type==="request.error"&&l.source==="php-wasm"&&await i()}return t.addEventListener("request.error",a),t.addEventListener("request.end",o),function(){t.removeEventListener("request.error",a),t.removeEventListener("request.end",o)}}async function writeFiles(t,e,r,{rmRoot:s=!1}={}){s&&await t.isDir(e)&&await t.rmdir(e,{recursive:!0});for(const[n,i]of Object.entries(r)){const o=util.joinPaths(e,n);await t.fileExists(util.dirname(o))||await t.mkdir(util.dirname(o)),i instanceof Uint8Array||typeof i=="string"?await t.writeFile(o,i):await writeFiles(t,o,i)}}function proxyFileSystem(t,e,r){const s=Object.getOwnPropertySymbols(t)[0];for(const n of r)e.fileExists(n)||e.mkdir(n),t.fileExists(n)||t.mkdir(n),e[s].FS.mount(e[s].PROXYFS,{root:n,fs:t[s].FS},n)}function sandboxedSpawnHandlerFactory(t){return util.createSpawnHandler(async function(e,r,s){r.notifySpawn(),e[0]==="exec"&&e.shift(),(e[0].endsWith(".php")||e[0].endsWith(".phar"))&&e.unshift("php");const n=e[0].split("/").pop();if(e[0]==="/usr/bin/env"&&e[1]==="stty"&&e[2]==="size")r.stdout("18 140"),r.exit(0);else if(n==="tput"&&e[1]==="cols")r.stdout("140"),r.exit(0);else if(n==="less")r.on("stdin",i=>{r.stdout(i)}),r.exit(0);else if(n==="php"){const{php:i,reap:o}=await t.acquirePHPInstance({considerPrimary:!1});i.chdir(s.cwd);try{const a=await i.cli(e,{env:{...s.env,SCRIPT_PATH:e[1],SHELL_PIPE:"0"}});a.stdout.pipeTo(new WritableStream({write(l){r.stdout(l)}})),a.stderr.pipeTo(new WritableStream({write(l){r.stderr(l)}})),r.exit(await a.exitCode)}catch(a){throw r.exit(1),a}finally{o()}}else r.exit(1)})}function exposeSync(t,e,r,s=["*"]){return expose(t,e,s,r.afterResponseSent)}function createSyncProxy(t,e=[],r){return new Proxy(()=>{},{get(s,n){return n==="then"&&!e.length?{then:(i,o)=>o(createSyncProxy(t,[],r))}:createSyncProxy(t,[...e,n],r)},set(s,n,i){const[o,a]=toWireValue(i);return r.send(t,{type:MessageType.SET,path:[...e,n].map(String),value:o},a),!0},apply(s,n,i){if(e.at(-1)==="bind")return createSyncProxy(t,e.slice(0,-1),r);const[a,l]=processArguments(i),c=r.send(t,{type:MessageType.APPLY,path:e.map(String),argumentList:a},l);return fromWireValue(c)},construct(s,n){const[i,o]=processArguments(n),a=r.send(t,{type:MessageType.CONSTRUCT,path:e.map(String),argumentList:i},o);return fromWireValue(a)}})}function wrapSync(t,e){return createSyncProxy(t,[],e)}class NodeSABSyncReceiveMessageTransport{static async create(){if(!NodeSABSyncReceiveMessageTransport.receiveMessageOnPort)try{NodeSABSyncReceiveMessageTransport.receiveMessageOnPort=require("worker_threads").receiveMessageOnPort}catch{NodeSABSyncReceiveMessageTransport.receiveMessageOnPort=await import("worker_threads").then(e=>e.receiveMessageOnPort)}return new NodeSABSyncReceiveMessageTransport}constructor(){}afterResponseSent(e){const{notifyBuffer:r}=e.data;if(r){const s=new Int32Array(r);s[0]=1,Atomics.notify(s,0)}}send(e,r,s){var c;const n=new SharedArrayBuffer(4),i=new Int32Array(n);i[0]=0;const o=generateUUID();if(e.postMessage({...r,id:o,notifyBuffer:n},s),Atomics.wait(i,0,0,5e3)==="timed-out")throw new Error("Timeout waiting for response");for(;;){const p=NodeSABSyncReceiveMessageTransport.receiveMessageOnPort(e);if(((c=p.message)==null?void 0:c.id)===o)return p.message;if(!p)throw new Error("No response received")}}}/**
|
|
89
|
+
`);const i=n.reduce((l,c)=>l+c.length,0),o=new Uint8Array(i);let a=0;for(const l of n)o.set(typeof l=="string"?s.encode(l):l,a),a+=l.length;return{bytes:o,contentType:r}}function fileToUint8Array(t){return t.arrayBuffer().then(e=>new Uint8Array(e))}const _default="application/octet-stream",asx="video/x-ms-asf",atom="application/atom+xml",avi="video/x-msvideo",avif="image/avif",bin="application/octet-stream",bmp="image/x-ms-bmp",cco="application/x-cocoa",css="text/css",data="application/octet-stream",deb="application/octet-stream",der="application/x-x509-ca-cert",dmg="application/octet-stream",doc="application/msword",docx="application/vnd.openxmlformats-officedocument.wordprocessingml.document",eot="application/vnd.ms-fontobject",flv="video/x-flv",gif="image/gif",gz="application/gzip",hqx="application/mac-binhex40",htc="text/x-component",html="text/html",ico="image/x-icon",iso="application/octet-stream",jad="text/vnd.sun.j2me.app-descriptor",jar="application/java-archive",jardiff="application/x-java-archive-diff",jng="image/x-jng",jnlp="application/x-java-jnlp-file",jpg="image/jpeg",jpeg="image/jpeg",js="application/javascript",json="application/json",kml="application/vnd.google-earth.kml+xml",kmz="application/vnd.google-earth.kmz",m3u8="application/vnd.apple.mpegurl",m4a="audio/x-m4a",m4v="video/x-m4v",md="text/plain",mid="audio/midi",mml="text/mathml",mng="video/x-mng",mov="video/quicktime",mp3="audio/mpeg",mp4="video/mp4",mpeg="video/mpeg",msi="application/octet-stream",odg="application/vnd.oasis.opendocument.graphics",odp="application/vnd.oasis.opendocument.presentation",ods="application/vnd.oasis.opendocument.spreadsheet",odt="application/vnd.oasis.opendocument.text",ogg="audio/ogg",otf="font/otf",pdf="application/pdf",pl="application/x-perl",png="image/png",ppt="application/vnd.ms-powerpoint",pptx="application/vnd.openxmlformats-officedocument.presentationml.presentation",prc="application/x-pilot",ps="application/postscript",ra="audio/x-realaudio",rar="application/x-rar-compressed",rpm="application/x-redhat-package-manager",rss="application/rss+xml",rtf="application/rtf",run="application/x-makeself",sea="application/x-sea",sit="application/x-stuffit",svg="image/svg+xml",swf="application/x-shockwave-flash",tcl="application/x-tcl",tar="application/x-tar",tif="image/tiff",ts="video/mp2t",ttf="font/ttf",txt="text/plain",wasm="application/wasm",wbmp="image/vnd.wap.wbmp",webm="video/webm",webp="image/webp",wml="text/vnd.wap.wml",wmlc="application/vnd.wap.wmlc",wmv="video/x-ms-wmv",woff="font/woff",woff2="font/woff2",xhtml="application/xhtml+xml",xls="application/vnd.ms-excel",xlsx="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml="text/xml",xpi="application/x-xpinstall",xspf="application/xspf+xml",zip="application/zip",mimeTypes={_default,"3gpp":"video/3gpp","7z":"application/x-7z-compressed",asx,atom,avi,avif,bin,bmp,cco,css,data,deb,der,dmg,doc,docx,eot,flv,gif,gz,hqx,htc,html,ico,iso,jad,jar,jardiff,jng,jnlp,jpg,jpeg,js,json,kml,kmz,m3u8,m4a,m4v,md,mid,mml,mng,mov,mp3,mp4,mpeg,msi,odg,odp,ods,odt,ogg,otf,pdf,pl,png,ppt,pptx,prc,ps,ra,rar,rpm,rss,rtf,run,sea,sit,svg,swf,tcl,tar,tif,ts,ttf,txt,wasm,wbmp,webm,webp,wml,wmlc,wmv,woff,woff2,xhtml,xls,xlsx,xml,xpi,xspf,zip};var v,C,M,F,I,P,A,R,H,Z,ee,te;class PHPRequestHandler{constructor(e){_(this,H);_(this,v);_(this,C);_(this,M);_(this,F);_(this,I);_(this,P);_(this,A);_(this,R);const{documentRoot:r="/www/",absoluteUrl:s=typeof location=="object"?location.href:DEFAULT_BASE_URL,rewriteRules:n=[],getFileNotFoundAction:i=()=>({type:"404"})}=e;"processManager"in e?this.processManager=e.processManager:this.processManager=new PHPProcessManager({phpFactory:async l=>{const c=await e.phpFactory({...l,requestHandler:this});return c.isDir(r)||c.mkdir(r),c.chdir(r),c.requestHandler=this,c},maxPhpInstances:e.maxPhpInstances}),f(this,R,e.cookieStore===void 0?new HttpCookieStore:e.cookieStore),f(this,v,r);const o=new URL(s);f(this,M,o.hostname),f(this,F,o.port?Number(o.port):o.protocol==="https:"?443:80),f(this,C,(o.protocol||"").replace(":",""));const a=u(this,F)!==443&&u(this,F)!==80;f(this,I,[u(this,M),a?`:${u(this,F)}`:""].join("")),f(this,P,o.pathname.replace(/\/+$/,"")),f(this,A,[`${u(this,C)}://`,u(this,I),u(this,P)].join("")),this.rewriteRules=n,this.getFileNotFoundAction=i}async getPrimaryPhp(){return await this.processManager.getPrimaryPhp()}pathToInternalUrl(e){return`${this.absoluteUrl}${e}`}internalUrlToPath(e){const r=new URL(e);return r.pathname.startsWith(u(this,P))&&(r.pathname=r.pathname.slice(u(this,P).length)),toRelativeUrl(r)}get absoluteUrl(){return u(this,A)}get documentRoot(){return u(this,v)}async request(e){const r=URL.canParse(e.url),s=new URL(e.url.split("#")[0],r?void 0:DEFAULT_BASE_URL),n=applyRewriteRules(removePathPrefix(decodeURIComponent(s.pathname),u(this,P)),this.rewriteRules),i=await this.getPrimaryPhp();let o=util.joinPaths(u(this,v),n);if(i.isDir(o)){if(!o.endsWith("/"))return new PHPResponse(301,{Location:[`${s.pathname}/`]},new Uint8Array(0));for(const a of["index.php","index.html"]){const l=util.joinPaths(o,a);if(i.isFile(l)){o=l;break}}}if(!i.isFile(o)){const a=this.getFileNotFoundAction(n);switch(a.type){case"response":return a.response;case"internal-redirect":o=util.joinPaths(u(this,v),a.uri);break;case"404":return PHPResponse.forHttpCode(404);default:throw new Error(`Unsupported file-not-found action type: '${a.type}'`)}}if(i.isFile(o))if(o.endsWith(".php")){const a={...e,url:s.toString()},l=await m(this,H,ee).call(this,a,o);return l.ok()&&l.exitCode!==0?new PHPResponse(500,l.headers,l.bytes,l.errors,l.exitCode):l}else return m(this,H,Z).call(this,i,o);else return PHPResponse.forHttpCode(404)}async[Symbol.asyncDispose](){await this.processManager[Symbol.asyncDispose]()}}v=new WeakMap,C=new WeakMap,M=new WeakMap,F=new WeakMap,I=new WeakMap,P=new WeakMap,A=new WeakMap,R=new WeakMap,H=new WeakSet,Z=function(e,r){const s=e.readFileAsBuffer(r);return new PHPResponse(200,{"content-length":[`${s.byteLength}`],"content-type":[inferMimeType(r)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},s)},ee=async function(e,r){let s;try{s=await this.processManager.acquirePHPInstance({considerPrimary:!0})}catch(n){return n instanceof MaxPhpInstancesError?PHPResponse.forHttpCode(502):PHPResponse.forHttpCode(500)}try{return await m(this,H,te).call(this,s.php,e,r)}finally{s.reap()}},te=async function(e,r,s){let n="GET";const i={host:u(this,I),...normalizeHeaders(r.headers||{})};u(this,R)&&(i.cookie=u(this,R).getCookieRequestHeader());let o=r.body;if(typeof o=="object"&&!(o instanceof Uint8Array)){n="POST";const{bytes:a,contentType:l}=await encodeAsMultipart(o);o=a,i["content-type"]=l}try{const a=await e.run({relativeUri:ensurePathPrefix(toRelativeUrl(new URL(r.url)),u(this,P)),protocol:u(this,C),method:r.method||n,$_SERVER:{REMOTE_ADDR:"127.0.0.1",DOCUMENT_ROOT:u(this,v),HTTPS:u(this,A).startsWith("https://")?"on":""},body:o,scriptPath:s,headers:i});return u(this,R)&&u(this,R).rememberCookiesFromResponseHeaders(a.headers),a}catch(a){const l=a;if(l!=null&&l.response)return l.response;throw a}};function inferMimeType(t){const e=t.split(".").pop();return mimeTypes[e]||mimeTypes._default}function applyRewriteRules(t,e){for(const r of e)if(new RegExp(r.match).test(t))return t.replace(r.match,r.replacement);return t}function rotatePHPRuntime({php:t,cwd:e,recreateRuntime:r,maxRequests:s=400}){let n=0;async function i(){const l=await t.semaphore.acquire();try{await t.hotSwapPHPRuntime(await r(),e),n=0}finally{l()}}async function o(){++n<s||await i()}async function a(l){l.type==="request.error"&&l.source==="php-wasm"&&await i()}return t.addEventListener("request.error",a),t.addEventListener("request.end",o),function(){t.removeEventListener("request.error",a),t.removeEventListener("request.end",o)}}async function writeFiles(t,e,r,{rmRoot:s=!1}={}){s&&await t.isDir(e)&&await t.rmdir(e,{recursive:!0});for(const[n,i]of Object.entries(r)){const o=util.joinPaths(e,n);await t.fileExists(util.dirname(o))||await t.mkdir(util.dirname(o)),i instanceof Uint8Array||typeof i=="string"?await t.writeFile(o,i):await writeFiles(t,o,i)}}function proxyFileSystem(t,e,r){const s=Object.getOwnPropertySymbols(t)[0];for(const n of r)e.fileExists(n)||e.mkdir(n),t.fileExists(n)||t.mkdir(n),e[s].FS.mount(e[s].PROXYFS,{root:n,fs:t[s].FS},n)}function sandboxedSpawnHandlerFactory(t){return util.createSpawnHandler(async function(e,r,s){r.notifySpawn(),e[0]==="exec"&&e.shift(),(e[0].endsWith(".php")||e[0].endsWith(".phar"))&&e.unshift("php");const n=e[0].split("/").pop();if(e[0]==="/usr/bin/env"&&e[1]==="stty"&&e[2]==="size")r.stdout("18 140"),r.exit(0);else if(n==="tput"&&e[1]==="cols")r.stdout("140"),r.exit(0);else if(n==="less")r.on("stdin",i=>{r.stdout(i)}),r.exit(0);else if(n==="php"){const{php:i,reap:o}=await t.acquirePHPInstance({considerPrimary:!1});i.chdir(s.cwd);try{const a=await i.cli(e,{env:{...s.env,SCRIPT_PATH:e[1],SHELL_PIPE:"0"}});a.stdout.pipeTo(new WritableStream({write(l){r.stdout(l)}})),a.stderr.pipeTo(new WritableStream({write(l){r.stderr(l)}})),r.exit(await a.exitCode)}catch(a){throw r.exit(1),a}finally{o()}}else r.exit(1)})}function exposeSync(t,e,r,s=["*"]){return expose(t,e,s,r.afterResponseSent)}function createSyncProxy(t,e=[],r){return new Proxy(()=>{},{get(s,n){return n==="then"&&!e.length?{then:(i,o)=>o(createSyncProxy(t,[],r))}:createSyncProxy(t,[...e,n],r)},set(s,n,i){const[o,a]=toWireValue(i);return r.send(t,{type:MessageType.SET,path:[...e,n].map(String),value:o},a),!0},apply(s,n,i){if(e.at(-1)==="bind")return createSyncProxy(t,e.slice(0,-1),r);const[a,l]=processArguments(i),c=r.send(t,{type:MessageType.APPLY,path:e.map(String),argumentList:a},l);return fromWireValue(c)},construct(s,n){const[i,o]=processArguments(n),a=r.send(t,{type:MessageType.CONSTRUCT,path:e.map(String),argumentList:i},o);return fromWireValue(a)}})}function wrapSync(t,e){return createSyncProxy(t,[],e)}class NodeSABSyncReceiveMessageTransport{static async create(){if(!NodeSABSyncReceiveMessageTransport.receiveMessageOnPort)try{NodeSABSyncReceiveMessageTransport.receiveMessageOnPort=require("worker_threads").receiveMessageOnPort}catch{NodeSABSyncReceiveMessageTransport.receiveMessageOnPort=await import("worker_threads").then(e=>e.receiveMessageOnPort)}return new NodeSABSyncReceiveMessageTransport}constructor(){}afterResponseSent(e){const{notifyBuffer:r}=e.data;if(r){const s=new Int32Array(r);s[0]=1,Atomics.notify(s,0)}}send(e,r,s){var c;const n=new SharedArrayBuffer(4),i=new Int32Array(n);i[0]=0;const o=generateUUID();if(e.postMessage({...r,id:o,notifyBuffer:n},s),Atomics.wait(i,0,0,5e3)==="timed-out")throw new Error("Timeout waiting for response");for(;;){const p=NodeSABSyncReceiveMessageTransport.receiveMessageOnPort(e);if(((c=p.message)==null?void 0:c.id)===o)return p.message;if(!p)throw new Error("No response received")}}}/**
|
|
90
90
|
* Original, unmodified Comlink library from Google:
|
|
91
91
|
*
|
|
92
92
|
* @license
|