@php-wasm/universal 1.1.3 → 1.1.5

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 CHANGED
@@ -1,10 +1,10 @@
1
- "use strict";var D=t=>{throw TypeError(t)};var U=(t,e,r)=>e.has(t)||D("Cannot "+r);var c=(t,e,r)=>(U(t,e,"read from private field"),r?r.call(t):e.get(t)),h=(t,e,r)=>e.has(t)?D("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),m=(t,e,r,s)=>(U(t,e,"write to private field"),s?s.call(t,r):e.set(t,r),r),d=(t,e,r)=>(U(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"),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(i){const n=typeof i=="object"?i==null?void 0:i.errno:null;if(n in FileErrorCodes){const o=FileErrorCodes[n],a=typeof s[1]=="string"?s[1]:null,l=a!==null?t.replaceAll("{path}",a):t;throw new Error(`${l}: ${o}`,{cause:i})}throw i}}}}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 i=e.lookupPath(r).node.mount,n=FSHelpers.fileExists(e,s)?e.lookupPath(s).node.mount:e.lookupPath(util.dirname(s)).node.mount;i.mountpoint!==n.mountpoint?(FSHelpers.copyRecursive(e,r,s),FSHelpers.isDir(e,r)?FSHelpers.rmdir(e,r,{recursive:!0}):e.unlink(r)):e.rename(r,s)}catch(i){const n=getEmscriptenFsError(i);throw n?new Error(`Could not move ${r} to ${s}: ${n}`,{cause:i}):i}}static rmdir(e,r,s={recursive:!0}){s!=null&&s.recursive&&FSHelpers.listFiles(e,r).forEach(i=>{const n=`${r}/${i}`;FSHelpers.isDir(e,n)?FSHelpers.rmdir(e,n,s):FSHelpers.unlink(e,n)}),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 i=e.readdir(r).filter(n=>n!=="."&&n!=="..");if(s.prependPath){const n=r.replace(/\/$/,"");return i.map(o=>`${n}/${o}`)}return i}catch(i){return logger.logger.error(i,{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 i=e.lookupPath(r).node;if(e.isDir(i.mode)){e.mkdirTree(s);const n=e.readdir(r).filter(o=>o!=="."&&o!=="..");for(const o of n)FSHelpers.copyRecursive(e,util.joinPaths(r,o),util.joinPaths(s,o))}else 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}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)}}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,i){this.parsedHeaders=null,this.cachedStdoutText=null,this.cachedStderrText=null,this.headersStream=e,this.stdout=r,this.stderr=s,this.exitCode=i}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 i of r.headers){if(!i.includes(": "))continue;const n=i.indexOf(": "),o=i.substring(0,n).toLowerCase(),a=i.substring(n+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:i}=await e.read();if(s)return r.join("");i&&r.push(i)}}class PHPResponse{constructor(e,r,s,i="",n=0){this.httpStatusCode=e,this.headers=r,this.bytes=s,this.exitCode=n,this.errors=i}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,i,n]=makePromise(),o=t.init(currentJsRuntime,{onAbort(l){n(l),logger.logger.error(l)},ENV:{},locateFile:l=>l,...r,noInitialRun:!0,onRuntimeInitialized(){r.onRuntimeInitialized&&r.onRuntimeInitialized(o),i()}});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?"exitCode"in t||(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(...i){var n;try{return s(...i)}catch(o){if(!(o instanceof Error))throw o;const a=clarifyErrorMessage(o,(n=t.lastAsyncifyStackSource)==null?void 0:n.stack);if(t.lastAsyncifyStackSource&&(o.cause=t.lastAsyncifyStackSource),e.hasListeners()){const l=new ErrorEvent("error",{error:o,message:a});throw e.dispatchEvent(l),o}throw(!isExitCode(o)||o.exitCode!==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 B=r=>{throw TypeError(r)};var q=(r,e,t)=>e.has(r)||B("Cannot "+t);var c=(r,e,t)=>(q(r,e,"read from private field"),t?t.call(r):e.get(r)),h=(r,e,t)=>e.has(r)?B("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),f=(r,e,t,s)=>(q(r,e,"write to private field"),s?s.call(r,t):e.set(r,t),t),d=(r,e,t)=>(q(r,e,"access private method"),t);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"),Comlink=require("comlink");var _documentCurrentScript=typeof document<"u"?document.currentScript:null;function _interopNamespaceDefault(r){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const t in r)if(t!=="default"){const s=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,s.get?s:{enumerable:!0,get:()=>r[t]})}}return e.default=r,Object.freeze(e)}const Comlink__namespace=_interopNamespaceDefault(Comlink),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(r){const e=typeof r=="object"?r==null?void 0:r.errno:null;if(e in FileErrorCodes)return FileErrorCodes[e]}function rethrowFileSystemError(r=""){return function(t){return function(...s){try{return t.apply(this,s)}catch(i){const n=typeof i=="object"?i==null?void 0:i.errno:null;if(n in FileErrorCodes){const o=FileErrorCodes[n],a=typeof s[1]=="string"?s[1]:null,l=a!==null?r.replaceAll("{path}",a):r;throw new Error(`${l}: ${o}`,{cause:i})}throw i}}}}class FSHelpers{static readFileAsText(e,t){return new TextDecoder().decode(FSHelpers.readFileAsBuffer(e,t))}static readFileAsBuffer(e,t){return e.readFile(t)}static writeFile(e,t,s){e.writeFile(t,s)}static unlink(e,t){e.unlink(t)}static mv(e,t,s){try{const i=e.lookupPath(t).node.mount,n=FSHelpers.fileExists(e,s)?e.lookupPath(s).node.mount:e.lookupPath(util.dirname(s)).node.mount;i.mountpoint!==n.mountpoint?(FSHelpers.copyRecursive(e,t,s),FSHelpers.isDir(e,t)?FSHelpers.rmdir(e,t,{recursive:!0}):e.unlink(t)):e.rename(t,s)}catch(i){const n=getEmscriptenFsError(i);throw n?new Error(`Could not move ${t} to ${s}: ${n}`,{cause:i}):i}}static rmdir(e,t,s={recursive:!0}){s!=null&&s.recursive&&FSHelpers.listFiles(e,t).forEach(i=>{const n=`${t}/${i}`;FSHelpers.isDir(e,n)?FSHelpers.rmdir(e,n,s):FSHelpers.unlink(e,n)}),e.getPath(e.lookupPath(t).node)===e.cwd()&&e.chdir(util.joinPaths(e.cwd(),"..")),e.rmdir(t)}static listFiles(e,t,s={prependPath:!1}){if(!FSHelpers.fileExists(e,t))return[];try{const i=e.readdir(t).filter(n=>n!=="."&&n!=="..");if(s.prependPath){const n=t.replace(/\/$/,"");return i.map(o=>`${n}/${o}`)}return i}catch(i){return logger.logger.error(i,{path:t}),[]}}static isDir(e,t){return FSHelpers.fileExists(e,t)?e.isDir(e.lookupPath(t,{follow:!0}).node.mode):!1}static isFile(e,t){return FSHelpers.fileExists(e,t)?e.isFile(e.lookupPath(t,{follow:!0}).node.mode):!1}static symlink(e,t,s){return e.symlink(t,s)}static isSymlink(e,t){return FSHelpers.fileExists(e,t)?e.isLink(e.lookupPath(t).node.mode):!1}static readlink(e,t){return e.readlink(t)}static realpath(e,t){return e.lookupPath(t,{follow:!0}).path}static fileExists(e,t){try{return e.lookupPath(t),!0}catch{return!1}}static mkdir(e,t){e.mkdirTree(t)}static copyRecursive(e,t,s){const i=e.lookupPath(t).node;if(e.isDir(i.mode)){e.mkdirTree(s);const n=e.readdir(t).filter(o=>o!=="."&&o!=="..");for(const o of n)FSHelpers.copyRecursive(e,util.joinPaths(t,o),util.joinPaths(s,o))}else e.writeFile(s,e.readFile(t))}}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,t){this.absoluteUrl="",this.documentRoot="",_private.set(this,{monitor:t}),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}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 t;return(t=_private.get(this).monitor)==null?void 0:t.addEventListener("progress",e)}async mv(e,t){return _private.get(this).php.mv(e,t)}async rmdir(e,t){return _private.get(this).php.rmdir(e,t)}async request(e){return await _private.get(this).requestHandler.request(e)}async run(e){const{php:t,reap:s}=await _private.get(this).requestHandler.processManager.acquirePHPInstance();try{return await t.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,t){return _private.get(this).php.writeFile(e,t)}unlink(e){return _private.get(this).php.unlink(e)}listFiles(e,t){return _private.get(this).php.listFiles(e,t)}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,t){_private.get(this).php.defineConstant(e,t)}addEventListener(e,t){_private.get(this).php.addEventListener(e,t)}removeEventListener(e,t){_private.get(this).php.removeEventListener(e,t)}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,t,s,i){this.parsedHeaders=null,this.cachedStdoutText=null,this.cachedStderrText=null,this.headersStream=e,this.stdout=t,this.stderr=s,this.exitCode=i}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(t=>t.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(r){const e=await streamToText(r);let t;try{t=JSON.parse(e)}catch{return{headers:{},httpStatusCode:200}}const s={};for(const i of t.headers){if(!i.includes(": "))continue;const n=i.indexOf(": "),o=i.substring(0,n).toLowerCase(),a=i.substring(n+2);o in s||(s[o]=[]),s[o].push(a)}return{headers:s,httpStatusCode:t.status}}async function streamToText(r){const e=r.pipeThrough(new TextDecoderStream).getReader(),t=[];for(;;){const{done:s,value:i}=await e.read();if(s)return t.join("");i&&t.push(i)}}class PHPResponse{constructor(e,t,s,i="",n=0){this.httpStatusCode=e,this.headers=t,this.bytes=s,this.exitCode=n,this.errors=i}static forHttpCode(e,t=""){return new PHPResponse(e,{},new TextEncoder().encode(t||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(r,...e){const t=Object.assign({},...e),[s,i,n]=makePromise(),o=r.init(currentJsRuntime,{onAbort(l){n(l),logger.logger.error(l)},ENV:{},locateFile:l=>l,...t,noInitialRun:!0,onRuntimeInitialized(){t.onRuntimeInitialized&&t.onRuntimeInitialized(o),i()}});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(r){return loadedRuntimes.get(r)}const currentJsRuntime=function(){var r;return typeof process<"u"&&((r=process.release)==null?void 0:r.name)==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"}(),makePromise=()=>{const r=[],e=new Promise((t,s)=>{r.push(t,s)});return r.unshift(e),r};var _a;const kError=Symbol("error"),kMessage=Symbol("message");class ErrorEvent2 extends(_a=Event,_a){constructor(e,t={}){super(e),this[kError]=t.error===void 0?null:t.error,this[kMessage]=t.message===void 0?"":t.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(r){return r instanceof Error?"exitCode"in r||(r==null?void 0:r.name)==="ExitStatus"&&"status"in r:!1}class UnhandledRejectionsTarget extends EventTarget{constructor(){super(...arguments),this.listenersCount=0}addEventListener(e,t,s){++this.listenersCount,super.addEventListener(e,t,s)}removeEventListener(e,t,s){--this.listenersCount,super.removeEventListener(e,t,s)}hasListeners(){return this.listenersCount>0}}function improveWASMErrorReporting(r){const e=new UnhandledRejectionsTarget;for(const t in r.wasmExports)if(typeof r.wasmExports[t]=="function"){const s=r.wasmExports[t];r.wasmExports[t]=function(...i){var n;try{return s(...i)}catch(o){if(!(o instanceof Error))throw o;r.lastAsyncifyStackSource&&(o.cause=r.lastAsyncifyStackSource);const a=clarifyErrorMessage(o,(n=r.lastAsyncifyStackSource)==null?void 0:n.stack);if(e.hasListeners()){const l=new ErrorEvent("error",{error:o,message:a});throw e.dispatchEvent(l),o}throw(!isExitCode(o)||o.exitCode!==0)&&showCriticalErrorBox(a),o}}}return e}let functionsMaybeMissingFromAsyncify=[];function getFunctionsMaybeMissingFromAsyncify(){return functionsMaybeMissingFromAsyncify}function clarifyErrorMessage(r,e){if(r.message==="unreachable"){let t=UNREACHABLE_ERROR;e||(t+=`
2
2
 
3
3
  This stack trace is lacking. For a better one initialize
4
4
  the PHP runtime with { debug: true }, e.g. PHPNode.load('8.1', { debug: true }).
5
5
 
6
- `),functionsMaybeMissingFromAsyncify=extractPHPFunctionsFromStack(e||t.stack||"");for(const s of functionsMaybeMissingFromAsyncify)r+=` * ${s}
7
- `;return r}return t.message}const UNREACHABLE_ERROR=`
6
+ `);const s=new Set(extractPHPFunctionsFromStack(e||""));let i=r;do{for(const n of extractPHPFunctionsFromStack(i.stack||""))s.add(n);i=i.cause}while(i);functionsMaybeMissingFromAsyncify=Array.from(s);for(const n of s)t+=` * ${n}
7
+ `;return t}return r.message}const UNREACHABLE_ERROR=`
8
8
  "unreachable" WASM instruction executed.
9
9
 
10
10
  The typical reason is a PHP function missing from the ASYNCIFY_ONLY
@@ -28,11 +28,11 @@ the Dockerfile, you'll need to trigger this error again with long stack
28
28
  traces enabled. In node.js, you can do it using the --stack-trace-limit=100
29
29
  CLI option:
30
30
 
31
- `,redBg="\x1B[41m",bold="\x1B[1m",reset="\x1B[0m",eol="\x1B[K";let logged=!1;function showCriticalErrorBox(t){if(!logged&&(logged=!0,!(t!=null&&t.trim().startsWith("Program terminated with exit")))){logger.logger.log(`${redBg}
31
+ `,redBg="\x1B[41m",bold="\x1B[1m",reset="\x1B[0m",eol="\x1B[K";let logged=!1;function showCriticalErrorBox(r){if(!logged&&(logged=!0,!(r!=null&&r.trim().startsWith("Program terminated with exit")))){logger.logger.log(`${redBg}
32
32
  ${eol}
33
- ${bold} WASM ERROR${reset}${redBg}`);for(const e of t.split(`
34
- `))logger.logger.log(`${eol} ${e} `);logger.logger.log(`${reset}`)}}function extractPHPFunctionsFromStack(t){try{const e=t.split(`
35
- `).slice(1).map(r=>{const s=r.trim().substring(3).split(" ");return{fn:s.length>=2?s[0]:"<unknown>",isWasm:r.includes("wasm://")}}).filter(({fn:r,isWasm:s})=>s&&!r.startsWith("dynCall_")&&!r.startsWith("invoke_")).map(({fn:r})=>r);return Array.from(new Set(e))}catch{return[]}}const STRING="string",NUMBER="number",__private__dont__use=Symbol("__private__dont__use");class PHPExecutionFailureError extends Error{constructor(e,r,s){super(e),this.response=r,this.source=s}}const PHP_INI_PATH="/internal/shared/php.ini",AUTO_PREPEND_SCRIPT="/internal/shared/auto_prepend_file.php";var b,f,E,y,H,T,p,z,q,W,V,G,J,Y,K,X,L,Q,$,B;class PHP{constructor(t){h(this,p);h(this,b);h(this,f,!1);h(this,E,null);h(this,y,new Map);h(this,H,[]);h(this,T,{});this.semaphore=new util.Semaphore({concurrency:1}),t!==void 0&&this.initializeRuntime(t)}addEventListener(t,e){c(this,y).has(t)||c(this,y).set(t,new Set),c(this,y).get(t).add(e)}removeEventListener(t,e){var r;(r=c(this,y).get(t))==null||r.delete(e)}dispatchEvent(t){const e=c(this,y).get(t.type);if(e)for(const r of e)r(t)}onMessage(t){return c(this,H).push(t),async()=>{m(this,H,c(this,H).filter(e=>e!==t))}}async setSpawnHandler(handler){typeof handler=="string"&&(handler=util.createSpawnHandler(eval(handler))),this[__private__dont__use].spawnProcess=handler}get absoluteUrl(){return this.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.documentRoot}pathToInternalUrl(t){return this.requestHandler.pathToInternalUrl(t)}internalUrlToPath(t){return this.requestHandler.internalUrlToPath(t)}initializeRuntime(t){if(this[__private__dont__use])throw new Error("PHP runtime already initialized.");const e=getLoadedRuntime(t);if(!e)throw new Error("Invalid PHP runtime id.");this[__private__dont__use]=e,this[__private__dont__use].ccall("wasm_set_phpini_path",null,["string"],[PHP_INI_PATH]),this.fileExists(PHP_INI_PATH)||this.writeFile(PHP_INI_PATH,["auto_prepend_file="+AUTO_PREPEND_SCRIPT,"memory_limit=256M","ignore_repeated_errors = 1","error_reporting = E_ALL","display_errors = 1","html_errors = 1","display_startup_errors = On","log_errors = 1","always_populate_raw_post_data = -1","upload_max_filesize = 2000M","post_max_size = 2000M","allow_url_fopen = On","allow_url_include = Off","session.save_path = /home/web_user","implicit_flush = 1","output_buffering = 0","max_execution_time = 0","max_input_time = -1"].join(`
33
+ ${bold} WASM ERROR${reset}${redBg}`);for(const e of r.split(`
34
+ `))logger.logger.log(`${eol} ${e} `);logger.logger.log(`${reset}`)}}function extractPHPFunctionsFromStack(r){try{const e=r.split(`
35
+ `).slice(1).map(t=>{const s=t.trim().substring(3).split(" ");return{fn:s.length>=2?s[0]:"<unknown>",isWasm:t.includes("wasm:/")}}).filter(({fn:t,isWasm:s})=>s&&!t.startsWith("dynCall_")&&!t.startsWith("invoke_")).map(({fn:t})=>t);return Array.from(new Set(e))}catch{return[]}}const STRING="string",NUMBER="number",__private__dont__use=Symbol("__private__dont__use");class PHPExecutionFailureError extends Error{constructor(e,t,s){super(e),this.response=t,this.source=s}}const PHP_INI_PATH="/internal/shared/php.ini",AUTO_PREPEND_SCRIPT="/internal/shared/auto_prepend_file.php";var T,_,H,g,R,k,u,z,L,W,V,G,J,Y,K,X,D,Q,O,$;class PHP{constructor(r){h(this,u);h(this,T);h(this,_,!1);h(this,H,null);h(this,g,new Map);h(this,R,[]);h(this,k,{});this.semaphore=new util.Semaphore({concurrency:1}),r!==void 0&&this.initializeRuntime(r)}addEventListener(r,e){c(this,g).has(r)||c(this,g).set(r,new Set),c(this,g).get(r).add(e)}removeEventListener(r,e){var t;(t=c(this,g).get(r))==null||t.delete(e)}dispatchEvent(r){const e=c(this,g).get(r.type);if(e)for(const t of e)t(r)}onMessage(r){return c(this,R).push(r),async()=>{f(this,R,c(this,R).filter(e=>e!==r))}}async setSpawnHandler(handler){typeof handler=="string"&&(handler=util.createSpawnHandler(eval(handler))),this[__private__dont__use].spawnProcess=handler}get absoluteUrl(){return this.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.documentRoot}pathToInternalUrl(r){return this.requestHandler.pathToInternalUrl(r)}internalUrlToPath(r){return this.requestHandler.internalUrlToPath(r)}initializeRuntime(r){if(this[__private__dont__use])throw new Error("PHP runtime already initialized.");const e=getLoadedRuntime(r);if(!e)throw new Error("Invalid PHP runtime id.");this[__private__dont__use]=e,this[__private__dont__use].ccall("wasm_set_phpini_path",null,["string"],[PHP_INI_PATH]),this.fileExists(PHP_INI_PATH)||this.writeFile(PHP_INI_PATH,["auto_prepend_file="+AUTO_PREPEND_SCRIPT,"memory_limit=256M","ignore_repeated_errors = 1","error_reporting = E_ALL","display_errors = 1","html_errors = 1","display_startup_errors = On","log_errors = 1","always_populate_raw_post_data = -1","upload_max_filesize = 2000M","post_max_size = 2000M","allow_url_fopen = On","allow_url_include = Off","session.save_path = /home/web_user","implicit_flush = 1","output_buffering = 0","max_execution_time = 0","max_input_time = -1"].join(`
36
36
  `)),this.fileExists(AUTO_PREPEND_SCRIPT)||this.writeFile(AUTO_PREPEND_SCRIPT,`<?php
37
37
  // Define constants set via defineConstant() calls
38
38
  if(file_exists('/internal/shared/consts.json')) {
@@ -47,13 +47,17 @@ ${bold} WASM ERROR${reset}${redBg}`);for(const e of t.split(`
47
47
  foreach (glob('/internal/shared/preload/*.php') as $file) {
48
48
  require_once $file;
49
49
  }
50
- `),e.onMessage=async r=>{for(const s of c(this,H)){const i=await s(r);if(i)return i}return""},m(this,E,improveWASMErrorReporting(e)),this.dispatchEvent({type:"runtime.initialized"})}async setSapiName(t){if(this[__private__dont__use].ccall("wasm_set_sapi_name",NUMBER,[STRING],[t])!==0)throw new Error("Could not set SAPI name. This can only be done before the PHP WASM module is initialized.Did you already dispatch any requests?");m(this,b,t)}chdir(t){this[__private__dont__use].FS.chdir(t)}async request(t){if(logger.logger.warn("PHP.request() is deprecated. Please use new PHPRequestHandler() instead."),!this.requestHandler)throw new Error("No request handler available.");return this.requestHandler.request(t)}async run(t){const e=await this.runStream(t),r=await PHPResponse.fromStreamedResponse(e);if(r.exitCode!==0){logger.logger.warn("PHP.run() output was:",r.text);const s=new PHPExecutionFailureError(`PHP.run() failed with exit code ${r.exitCode} and the following output: `+r.errors+`
50
+ `),e.onMessage=async t=>{for(const s of c(this,R)){const i=await s(t);if(i)return i}return""},f(this,H,improveWASMErrorReporting(e)),this.dispatchEvent({type:"runtime.initialized"})}async setSapiName(r){if(this[__private__dont__use].ccall("wasm_set_sapi_name",NUMBER,[STRING],[r])!==0)throw new Error("Could not set SAPI name. This can only be done before the PHP WASM module is initialized.Did you already dispatch any requests?");f(this,T,r)}chdir(r){this[__private__dont__use].FS.chdir(r)}async request(r){if(logger.logger.warn("PHP.request() is deprecated. Please use new PHPRequestHandler() instead."),!this.requestHandler)throw new Error("No request handler available.");return this.requestHandler.request(r)}async run(r){const e=await this.runStream(r),t=await PHPResponse.fromStreamedResponse(e);if(t.exitCode!==0){logger.logger.warn("PHP.run() output was:",t.text);const s=new PHPExecutionFailureError(`PHP.run() failed with exit code ${t.exitCode} and the following output: `+t.errors+`
51
51
 
52
- `+r.text,r,"request");throw logger.logger.error(s),this.dispatchEvent({type:"request.error",error:new Error("PHP.run() failed with exit code "+r.exitCode),source:"request"}),s}return r}async runStream(t){const e=await this.semaphore.acquire();let r;const s=d(this,p,B).call(this,()=>{if(c(this,f)||(d(this,p,q).call(this),m(this,f,!0)),t.scriptPath&&!this.fileExists(t.scriptPath))throw new Error(`The script path "${t.scriptPath}" does not exist.`);d(this,p,W).call(this,t.relativeUri||""),d(this,p,Y).call(this,t.method||"GET");const i=normalizeHeaders(t.headers||{}),n=i.host||"example.com:443",o=d(this,p,J).call(this,n,t.protocol||"http");if(d(this,p,V).call(this,n),d(this,p,G).call(this,o),d(this,p,K).call(this,i),t.body&&(r=d(this,p,X).call(this,t.body)),typeof t.code=="string")this.writeFile("/internal/eval.php",t.code),d(this,p,L).call(this,"/internal/eval.php");else if(typeof t.scriptPath=="string")d(this,p,L).call(this,t.scriptPath||"");else throw new TypeError("The request object must have either a `code` or a `scriptPath` property.");const a=d(this,p,z).call(this,t.$_SERVER,i,o);for(const u in a)d(this,p,Q).call(this,u,a[u]);const l=t.env||{};for(const u in l)d(this,p,$).call(this,u,l[u]);return c(this,f)||(d(this,p,q).call(this),m(this,f,!0)),this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0})});return await s.catch(i=>{this.dispatchEvent({type:"request.error",error:i,source:i.source??"php-wasm"})}).finally(()=>{r&&this[__private__dont__use].free(r)}).finally(()=>{e(),this.dispatchEvent({type:"request.end"})}),s}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[i,n]of Object.entries(c(this,T)))s.push({mountHandler:n.mountHandler,vfsPath:i}),await n.unmount();try{this.exit()}catch{}this.initializeRuntime(t),c(this,b)&&this.setSapiName(c(this,b)),copyFS(r,this[__private__dont__use].FS,"/internal"),e&&copyFS(r,this[__private__dont__use].FS,e);for(const{mountHandler:i,vfsPath:n}of s)this.mkdir(n),await this.mount(n,i)}async mount(t,e){const r=await e(this,this[__private__dont__use].FS,t),s={mountHandler:e,unmount:async()=>{await r(),delete c(this,T)[t]}};return c(this,T)[t]=s,()=>{s.unmount()}}async cli(t,e={}){const r=await this.semaphore.acquire(),s=e.env||{};for(const[i,n]of Object.entries(s))d(this,p,$).call(this,i,n);t=[t[0],"-c",PHP_INI_PATH,...t.slice(1)];for(const i of t)this[__private__dont__use].ccall("wasm_add_cli_arg",null,[STRING],[i]);return await d(this,p,B).call(this,()=>this[__private__dont__use].ccall("run_cli",null,[],[],{async:!0})).then(i=>(i.exitCode.finally(r),i))}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{}m(this,f,!1),m(this,E,null),delete this[__private__dont__use].onMessage,delete this[__private__dont__use]}[Symbol.dispose](){c(this,f)&&this.exit(0)}}b=new WeakMap,f=new WeakMap,E=new WeakMap,y=new WeakMap,H=new WeakMap,T=new WeakMap,p=new WeakSet,z=function(t,e,r){const s={...t||{}};s.HTTPS=s.HTTPS||r===443?"on":"off";for(const i in e){let n="HTTP_";["content-type","content-length"].includes(i.toLowerCase())&&(n=""),s[`${n}${i.toUpperCase().replace(/-/g,"_")}`]=e[i]}return s},q=function(){this[__private__dont__use].ccall("php_wasm_init",null,[],[])},W=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])},$=function(t,e){this[__private__dont__use].ccall("wasm_add_ENV_entry",null,[STRING,STRING],[t,e])},B=async function(t){const e=this[__private__dont__use],r=await createInvertedReadableStream();e.onHeaders=P=>{a||s||r.controller.enqueue(P.slice())};let s=!1;const i=()=>{s||(s=!0,r.controller.close())},n=await createInvertedReadableStream();e.onStdout=P=>{i(),!a&&n.controller.enqueue(P.slice())};const o=await createInvertedReadableStream();e.onStderr=P=>{a||o.controller.enqueue(P.slice())};let a=!1,l;const O=(async()=>{var P;try{return await Promise.race([t(),new Promise((A,M)=>{var F;l=g=>{if(logger.logger.error(g),logger.logger.error(g.error),!isExitCode(g.error)){const j=new Error("Rethrown");j.cause=g.error,j.betterMessage=g.message,M(j)}},(F=c(this,E))==null||F.addEventListener("error",l,{once:!0})})])}catch(S){if(isExitCode(S))return S.exitCode;n.controller.error(S),o.controller.error(S),r.controller.error(S),a=!0;for(const g in this)typeof this[g]=="function"&&(this[g]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});this.functionsMaybeMissingFromAsyncify=getFunctionsMaybeMissingFromAsyncify();const A=S,M="betterMessage"in A?A.betterMessage:A.message,F=new Error(M);throw F.cause=A,logger.logger.error(F),F}finally{a||(n.controller.close(),o.controller.close(),i(),a=!0),(P=c(this,E))==null||P.removeEventListener("error",l)}})();return new StreamedPHPResponse(r.stream,n.stream,o.stream,O)};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 i=t.readdir(r).filter(n=>n!=="."&&n!=="..");for(const n of i)copyFS(t,e,util.joinPaths(r,n))}async function createInvertedReadableStream(t={}){let e;const r=new Promise(n=>{e=n}),s=new ReadableStream({...t,start(n){if(e(n),t.start)return t.start(n)}}),i=await r;return{stream:s,controller:i}}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 i of e)s[i]=r[i];return s}async function setPhpIniEntries(t,e){const r=ini.parse(await t.readFileAsText(PHP_INI_PATH));for(const[s,i]of Object.entries(e))i==null?delete r[s]:r[s]=i;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)}}class HttpCookieStore{constructor(){this.cookies={}}rememberCookiesFromResponseHeaders(e){if(e!=null&&e["set-cookie"])for(const r of e["set-cookie"])try{if(!r.includes("="))continue;const s=r.indexOf("="),i=r.substring(0,s),n=r.substring(s+1).split(";")[0];this.cookies[i]=n}catch(s){logger.logger.error(s)}}getCookieRequestHeader(){const e=[];for(const r in this.cookies)e.push(`${r}=${this.cookies[r]}`);return e.join("; ")}}function streamReadFileFromPHP(t,e){return new ReadableStream({async pull(r){const s=await t.readFileAsBuffer(e);r.enqueue(s),r.close()}})}async function*iteratePhpFiles(t,e,{relativePaths:r=!0,pathPrefix:s,exceptPaths:i=[]}={}){e=util.normalizePath(e);const n=[e];for(;n.length;){const o=n.pop();if(!o)return;const a=await t.listFiles(o);for(const l of a){const u=`${o}/${l}`;if(i.includes(u.substring(e.length+1)))continue;await t.isDir(u)?n.push(u):yield new streamCompression.StreamedFile(streamReadFileFromPHP(t,u),r?util.joinPaths(s||"",u.substring(e.length+1)):u)}}}function writeFilesStreamToPhp(t,e){return new WritableStream({async write(r){const s=util.joinPaths(e,r.name);r.type==="directory"?await t.mkdir(s):(await t.mkdir(util.dirname(s)),await t.writeFile(s,new Uint8Array(await r.arrayBuffer())))}})}class MaxPhpInstancesError extends Error{constructor(e){super(`Requested more concurrent PHP instances than the limit (${e}).`),this.name=this.constructor.name}}class PHPProcessManager{constructor(e){this.primaryIdle=!0,this.nextInstance=null,this.allInstances=[],this.maxPhpInstances=(e==null?void 0:e.maxPhpInstances)??5,this.phpFactory=e==null?void 0:e.phpFactory,this.primaryPhp=e==null?void 0:e.primaryPhp,this.semaphore=new util.Semaphore({concurrency:this.maxPhpInstances,timeout:(e==null?void 0:e.timeout)||5e3})}async getPrimaryPhp(){if(!this.phpFactory&&!this.primaryPhp)throw new Error("phpFactory or primaryPhp must be set before calling getPrimaryPhp().");return this.primaryPhp||(this.primaryPhpPromise||(this.primaryPhpPromise=this.spawn({isPrimary:!0})),this.primaryPhp=(await this.primaryPhpPromise).php,this.primaryPhpPromise=void 0),this.primaryPhp}async acquirePHPInstance({considerPrimary:e=!0}={}){if(this.primaryPhp||await this.getPrimaryPhp(),this.primaryIdle&&e)return this.primaryIdle=!1,{php:await this.getPrimaryPhp(),reap:()=>{this.primaryIdle=!0}};const r=this.nextInstance||this.spawn({isPrimary:!1});return this.semaphore.remaining>0?this.nextInstance=this.spawn({isPrimary:!1}):this.nextInstance=null,await r}spawn(e){if(e.isPrimary&&this.primaryPhpPromise&&!this.primaryPhp)throw new Error("Requested spawning a primary PHP instance when another primary instance already started spawning.");const r=this.doSpawn(e);this.allInstances.push(r);const s=()=>{this.allInstances=this.allInstances.filter(i=>i!==r)};return r.catch(i=>{throw s(),i}).then(i=>({...i,reap:()=>{s(),i.reap()}}))}async doSpawn(e){let r;try{r=await this.semaphore.acquire()}catch(s){throw s instanceof util.AcquireTimeoutError?new MaxPhpInstancesError(this.maxPhpInstances):s}try{const s=await this.phpFactory(e);return{php:s,reap(){s.exit(),r()}}}catch(s){throw r(),s}}async[Symbol.asyncDispose](){this.primaryPhp&&this.primaryPhp.exit(),await Promise.all(this.allInstances.map(e=>e.then(({reap:r})=>r())))}}const SupportedPHPVersions=["8.4","8.3","8.2","8.1","8.0","7.4","7.3","7.2"],LatestSupportedPHPVersion=SupportedPHPVersions[0],SupportedPHPVersionsList=SupportedPHPVersions,DEFAULT_BASE_URL="http://example.com";function toRelativeUrl(t){return t.toString().substring(t.origin.length)}function removePathPrefix(t,e){return!e||!t.startsWith(e)?t:t.substring(e.length)}function ensurePathPrefix(t,e){return!e||t.startsWith(e)?t:e+t}async function encodeAsMultipart(t){const e=`----${Math.random().toString(36).slice(2)}`,r=`multipart/form-data; boundary=${e}`,s=new TextEncoder,i=[];for(const[l,u]of Object.entries(t))i.push(`--${e}\r
53
- `),i.push(`Content-Disposition: form-data; name="${l}"`),u instanceof File&&i.push(`; filename="${u.name}"`),i.push(`\r
54
- `),u instanceof File&&(i.push("Content-Type: application/octet-stream"),i.push(`\r
52
+ `+t.text,t,"request");throw logger.logger.error(s),this.dispatchEvent({type:"request.error",error:new Error("PHP.run() failed with exit code "+t.exitCode),source:"request"}),s}return t}async runStream(r){const e=await this.semaphore.acquire();let t;const s=d(this,u,$).call(this,()=>{if(c(this,_)||(d(this,u,L).call(this),f(this,_,!0)),r.scriptPath&&!this.fileExists(r.scriptPath))throw new Error(`The script path "${r.scriptPath}" does not exist.`);d(this,u,W).call(this,r.relativeUri||""),d(this,u,Y).call(this,r.method||"GET");const i=normalizeHeaders(r.headers||{}),n=i.host||"example.com:443",o=d(this,u,J).call(this,n,r.protocol||"http");if(d(this,u,V).call(this,n),d(this,u,G).call(this,o),d(this,u,K).call(this,i),r.body&&(t=d(this,u,X).call(this,r.body)),typeof r.code=="string")this.writeFile("/internal/eval.php",r.code),d(this,u,D).call(this,"/internal/eval.php");else if(typeof r.scriptPath=="string")d(this,u,D).call(this,r.scriptPath||"");else throw new TypeError("The request object must have either a `code` or a `scriptPath` property.");const a=d(this,u,z).call(this,r.$_SERVER,i,o);for(const p in a)d(this,u,Q).call(this,p,a[p]);const l=r.env||{};for(const p in l)d(this,u,O).call(this,p,l[p]);return c(this,_)||(d(this,u,L).call(this),f(this,_,!0)),this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0})});return await s.catch(i=>{this.dispatchEvent({type:"request.error",error:i,source:i.source??"php-wasm"})}).finally(()=>{t&&this[__private__dont__use].free(t)}).finally(()=>{e(),this.dispatchEvent({type:"request.end"})}),s}defineConstant(r,e){let t={};try{t=JSON.parse(this.fileExists("/internal/shared/consts.json")&&this.readFileAsText("/internal/shared/consts.json")||"{}")}catch{}this.writeFile("/internal/shared/consts.json",JSON.stringify({...t,[r]:e}))}mkdir(r){return FSHelpers.mkdir(this[__private__dont__use].FS,r)}mkdirTree(r){return FSHelpers.mkdir(this[__private__dont__use].FS,r)}readFileAsText(r){return FSHelpers.readFileAsText(this[__private__dont__use].FS,r)}readFileAsBuffer(r){return FSHelpers.readFileAsBuffer(this[__private__dont__use].FS,r)}writeFile(r,e){return FSHelpers.writeFile(this[__private__dont__use].FS,r,e)}unlink(r){return FSHelpers.unlink(this[__private__dont__use].FS,r)}mv(r,e){return FSHelpers.mv(this[__private__dont__use].FS,r,e)}rmdir(r,e={recursive:!0}){return FSHelpers.rmdir(this[__private__dont__use].FS,r,e)}listFiles(r,e={prependPath:!1}){return FSHelpers.listFiles(this[__private__dont__use].FS,r,e)}isDir(r){return FSHelpers.isDir(this[__private__dont__use].FS,r)}isFile(r){return FSHelpers.isFile(this[__private__dont__use].FS,r)}symlink(r,e){return FSHelpers.symlink(this[__private__dont__use].FS,r,e)}isSymlink(r){return FSHelpers.isSymlink(this[__private__dont__use].FS,r)}readlink(r){return FSHelpers.readlink(this[__private__dont__use].FS,r)}realpath(r){return FSHelpers.realpath(this[__private__dont__use].FS,r)}fileExists(r){return FSHelpers.fileExists(this[__private__dont__use].FS,r)}async hotSwapPHPRuntime(r,e){const t=this[__private__dont__use].FS,s=[];for(const[i,n]of Object.entries(c(this,k)))s.push({mountHandler:n.mountHandler,vfsPath:i}),await n.unmount();try{this.exit()}catch{}this.initializeRuntime(r),c(this,T)&&this.setSapiName(c(this,T)),copyFS(t,this[__private__dont__use].FS,"/internal"),e&&copyFS(t,this[__private__dont__use].FS,e);for(const{mountHandler:i,vfsPath:n}of s)this.mkdir(n),await this.mount(n,i)}async mount(r,e){const t=await e(this,this[__private__dont__use].FS,r),s={mountHandler:e,unmount:async()=>{await t(),delete c(this,k)[r]}};return c(this,k)[r]=s,()=>{s.unmount()}}async cli(r,e={}){const t=await this.semaphore.acquire(),s=e.env||{};for(const[i,n]of Object.entries(s))d(this,u,O).call(this,i,n);r=[r[0],"-c",PHP_INI_PATH,...r.slice(1)];for(const i of r)this[__private__dont__use].ccall("wasm_add_cli_arg",null,[STRING],[i]);return await d(this,u,$).call(this,()=>this[__private__dont__use].ccall("run_cli",null,[],[],{async:!0})).then(i=>(i.exitCode.finally(t),i))}setSkipShebang(r){this[__private__dont__use].ccall("wasm_set_skip_shebang",null,[NUMBER],[r?1:0])}exit(r=0){this.dispatchEvent({type:"runtime.beforedestroy"});try{this[__private__dont__use]._exit(r)}catch{}f(this,_,!1),f(this,H,null),this[__private__dont__use]&&(delete this[__private__dont__use].onMessage,delete this[__private__dont__use])}[Symbol.dispose](){c(this,_)&&this.exit(0)}}T=new WeakMap,_=new WeakMap,H=new WeakMap,g=new WeakMap,R=new WeakMap,k=new WeakMap,u=new WeakSet,z=function(r,e,t){const s={...r||{}};s.HTTPS=s.HTTPS||t===443?"on":"off";for(const i in e){let n="HTTP_";["content-type","content-length"].includes(i.toLowerCase())&&(n=""),s[`${n}${i.toUpperCase().replace(/-/g,"_")}`]=e[i]}return s},L=function(){this[__private__dont__use].ccall("php_wasm_init",null,[],[])},W=function(r){this[__private__dont__use].ccall("wasm_set_request_uri",null,[STRING],[r]);let e="";r.includes("?")&&(e=r.substring(r.indexOf("?")+1)),this[__private__dont__use].ccall("wasm_set_query_string",null,[STRING],[e])},V=function(r){this[__private__dont__use].ccall("wasm_set_request_host",null,[STRING],[r])},G=function(r){this[__private__dont__use].ccall("wasm_set_request_port",null,[NUMBER],[r])},J=function(r,e){let t;try{t=parseInt(new URL(r).port,10)}catch{}return(!t||isNaN(t)||t===80)&&(t=e==="https"?443:80),t},Y=function(r){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[r])},K=function(r){r.cookie&&this[__private__dont__use].ccall("wasm_set_cookies",null,[STRING],[r.cookie]),r["content-type"]&&this[__private__dont__use].ccall("wasm_set_content_type",null,[STRING],[r["content-type"]]),r["content-length"]&&this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[parseInt(r["content-length"],10)])},X=function(r){let e,t;typeof r=="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"),t=this[__private__dont__use].lengthBytesUTF8(r),e=t+1):(t=r.byteLength,e=r.byteLength);const s=this[__private__dont__use].malloc(e);if(!s)throw new Error("Could not allocate memory for the request body.");return typeof r=="string"?this[__private__dont__use].stringToUTF8(r,s,e+1):this[__private__dont__use].HEAPU8.set(r,s),this[__private__dont__use].ccall("wasm_set_request_body",null,[NUMBER],[s]),this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[t]),s},D=function(r){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[r])},Q=function(r,e){this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[r,e])},O=function(r,e){this[__private__dont__use].ccall("wasm_add_ENV_entry",null,[STRING,STRING],[r,e])},$=async function(r){const e=this[__private__dont__use],t=await createInvertedReadableStream();e.onHeaders=m=>{a||s||t.controller.enqueue(m.slice())};let s=!1;const i=()=>{s||(s=!0,t.controller.close())},n=await createInvertedReadableStream();e.onStdout=m=>{i(),!a&&n.controller.enqueue(m.slice())};const o=await createInvertedReadableStream();e.onStderr=m=>{a||o.controller.enqueue(m.slice())};let a=!1,l;const S=(async()=>{var m;try{return await Promise.race([r(),new Promise((N,U)=>{var b;l=y=>{if(logger.logger.error(y),logger.logger.error(y.error),!isExitCode(y.error)){const j=new Error("Rethrown");j.cause=y.error,j.betterMessage=y.message,U(j)}},(b=c(this,H))==null||b.addEventListener("error",l,{once:!0})})])}catch(E){if(isExitCode(E))return E.exitCode;n.controller.error(E),o.controller.error(E),t.controller.error(E),a=!0;for(const y in this)typeof this[y]=="function"&&(this[y]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});this.functionsMaybeMissingFromAsyncify=getFunctionsMaybeMissingFromAsyncify();const N=E,U="betterMessage"in N?N.betterMessage:N.message,b=new Error(U);throw b.cause=N,logger.logger.error(b),b}finally{a||(n.controller.close(),o.controller.close(),i(),a=!0),(m=c(this,H))==null||m.removeEventListener("error",l)}})();return new StreamedPHPResponse(t.stream,n.stream,o.stream,S)};function normalizeHeaders(r){const e={};for(const t in r)e[t.toLowerCase()]=r[t];return e}function copyFS(r,e,t){let s;try{s=r.lookupPath(t)}catch{return}if(!("contents"in s.node))return;if(!r.isDir(s.node.mode)){e.writeFile(t,r.readFile(t));return}e.mkdirTree(t);const i=r.readdir(t).filter(n=>n!=="."&&n!=="..");for(const n of i)copyFS(r,e,util.joinPaths(t,n))}async function createInvertedReadableStream(r={}){let e;const t=new Promise(n=>{e=n}),s=new ReadableStream({...r,start(n){if(e(n),r.start)return r.start(n)}}),i=await t;return{stream:s,controller:i}}async function getPhpIniEntries(r,e){const t=ini.parse(await r.readFileAsText(PHP_INI_PATH));if(e===void 0)return t;const s={};for(const i of e)s[i]=t[i];return s}async function setPhpIniEntries(r,e){const t=ini.parse(await r.readFileAsText(PHP_INI_PATH));for(const[s,i]of Object.entries(e))i==null?delete t[s]:t[s]=i;await r.writeFile(PHP_INI_PATH,ini.stringify(t))}async function withPHPIniValues(r,e,t){const s=await r.readFileAsText(PHP_INI_PATH);try{return await setPhpIniEntries(r,e),await t()}finally{await r.writeFile(PHP_INI_PATH,s)}}class HttpCookieStore{constructor(){this.cookies={}}rememberCookiesFromResponseHeaders(e){if(e!=null&&e["set-cookie"])for(const t of e["set-cookie"])try{if(!t.includes("="))continue;const s=t.indexOf("="),i=t.substring(0,s),n=t.substring(s+1).split(";")[0];this.cookies[i]=n}catch(s){logger.logger.error(s)}}getCookieRequestHeader(){const e=[];for(const t in this.cookies)e.push(`${t}=${this.cookies[t]}`);return e.join("; ")}}function streamReadFileFromPHP(r,e){return new ReadableStream({async pull(t){const s=await r.readFileAsBuffer(e);t.enqueue(s),t.close()}})}async function*iteratePhpFiles(r,e,{relativePaths:t=!0,pathPrefix:s,exceptPaths:i=[]}={}){e=util.normalizePath(e);const n=[e];for(;n.length;){const o=n.pop();if(!o)return;const a=await r.listFiles(o);for(const l of a){const p=`${o}/${l}`;if(i.includes(p.substring(e.length+1)))continue;await r.isDir(p)?n.push(p):yield new streamCompression.StreamedFile(streamReadFileFromPHP(r,p),t?util.joinPaths(s||"",p.substring(e.length+1)):p)}}}function writeFilesStreamToPhp(r,e){return new WritableStream({async write(t){const s=util.joinPaths(e,t.name);t.type==="directory"?await r.mkdir(s):(await r.mkdir(util.dirname(s)),await r.writeFile(s,new Uint8Array(await t.arrayBuffer())))}})}class MaxPhpInstancesError extends Error{constructor(e){super(`Requested more concurrent PHP instances than the limit (${e}).`),this.name=this.constructor.name}}class PHPProcessManager{constructor(e){this.primaryIdle=!0,this.nextInstance=null,this.allInstances=[],this.maxPhpInstances=(e==null?void 0:e.maxPhpInstances)??5,this.phpFactory=e==null?void 0:e.phpFactory,this.primaryPhp=e==null?void 0:e.primaryPhp,this.semaphore=new util.Semaphore({concurrency:this.maxPhpInstances,timeout:(e==null?void 0:e.timeout)||5e3})}async getPrimaryPhp(){if(!this.phpFactory&&!this.primaryPhp)throw new Error("phpFactory or primaryPhp must be set before calling getPrimaryPhp().");return this.primaryPhp||(this.primaryPhpPromise||(this.primaryPhpPromise=this.spawn({isPrimary:!0})),this.primaryPhp=(await this.primaryPhpPromise).php,this.primaryPhpPromise=void 0),this.primaryPhp}async acquirePHPInstance({considerPrimary:e=!0}={}){if(this.primaryPhp||await this.getPrimaryPhp(),this.primaryIdle&&e)return this.primaryIdle=!1,{php:await this.getPrimaryPhp(),reap:()=>{this.primaryIdle=!0}};const t=this.nextInstance||this.spawn({isPrimary:!1});return this.semaphore.remaining>0?this.nextInstance=this.spawn({isPrimary:!1}):this.nextInstance=null,await t}spawn(e){if(e.isPrimary&&this.primaryPhpPromise&&!this.primaryPhp)throw new Error("Requested spawning a primary PHP instance when another primary instance already started spawning.");const t=this.doSpawn(e);this.allInstances.push(t);const s=()=>{this.allInstances=this.allInstances.filter(i=>i!==t)};return t.catch(i=>{throw s(),i}).then(i=>({...i,reap:()=>{s(),i.reap()}}))}async doSpawn(e){let t;try{t=await this.semaphore.acquire()}catch(s){throw s instanceof util.AcquireTimeoutError?new MaxPhpInstancesError(this.maxPhpInstances):s}try{const s=await this.phpFactory(e);return{php:s,reap(){s.exit(),t()}}}catch(s){throw t(),s}}async[Symbol.asyncDispose](){this.primaryPhp&&this.primaryPhp.exit(),await Promise.all(this.allInstances.map(e=>e.then(({reap:t})=>t())))}}const SupportedPHPVersions=["8.4","8.3","8.2","8.1","8.0","7.4","7.3","7.2"],LatestSupportedPHPVersion=SupportedPHPVersions[0],SupportedPHPVersionsList=SupportedPHPVersions,DEFAULT_BASE_URL="http://example.com";function toRelativeUrl(r){return r.toString().substring(r.origin.length)}function removePathPrefix(r,e){return!e||!r.startsWith(e)?r:r.substring(e.length)}function ensurePathPrefix(r,e){return!e||r.startsWith(e)?r:e+r}async function encodeAsMultipart(r){const e=`----${Math.random().toString(36).slice(2)}`,t=`multipart/form-data; boundary=${e}`,s=new TextEncoder,i=[];for(const[l,p]of Object.entries(r))i.push(`--${e}\r
53
+ `),i.push(`Content-Disposition: form-data; name="${l}"`),p instanceof File&&i.push(`; filename="${p.name}"`),i.push(`\r
54
+ `),p instanceof File&&(i.push("Content-Type: application/octet-stream"),i.push(`\r
55
55
  `)),i.push(`\r
56
- `),u instanceof File?i.push(await fileToUint8Array(u)):i.push(u),i.push(`\r
56
+ `),p instanceof File?i.push(await fileToUint8Array(p)):i.push(p),i.push(`\r
57
57
  `);i.push(`--${e}--\r
58
- `);const n=i.reduce((l,u)=>l+u.length,0),o=new Uint8Array(n);let a=0;for(const l of i)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 w,k,N,R,I,_,C,v,x,Z,ee,te;class PHPRequestHandler{constructor(e){h(this,x);h(this,w);h(this,k);h(this,N);h(this,R);h(this,I);h(this,_);h(this,C);h(this,v);const{documentRoot:r="/www/",absoluteUrl:s=typeof location=="object"?location.href:DEFAULT_BASE_URL,rewriteRules:i=[],getFileNotFoundAction:n=()=>({type:"404"})}=e;"processManager"in e?this.processManager=e.processManager:this.processManager=new PHPProcessManager({phpFactory:async l=>{const u=await e.phpFactory({...l,requestHandler:this});return u.isDir(r)||u.mkdir(r),u.chdir(r),u.requestHandler=this,u},maxPhpInstances:e.maxPhpInstances}),m(this,v,e.cookieStore===void 0?new HttpCookieStore:e.cookieStore),m(this,w,r);const o=new URL(s);m(this,N,o.hostname),m(this,R,o.port?Number(o.port):o.protocol==="https:"?443:80),m(this,k,(o.protocol||"").replace(":",""));const a=c(this,R)!==443&&c(this,R)!==80;m(this,I,[c(this,N),a?`:${c(this,R)}`:""].join("")),m(this,_,o.pathname.replace(/\/+$/,"")),m(this,C,[`${c(this,k)}://`,c(this,I),c(this,_)].join("")),this.rewriteRules=i,this.getFileNotFoundAction=n}async getPrimaryPhp(){return await this.processManager.getPrimaryPhp()}pathToInternalUrl(e){return`${this.absoluteUrl}${e}`}internalUrlToPath(e){const r=new URL(e);return r.pathname.startsWith(c(this,_))&&(r.pathname=r.pathname.slice(c(this,_).length)),toRelativeUrl(r)}get absoluteUrl(){return c(this,C)}get documentRoot(){return c(this,w)}async request(e){const r=URL.canParse(e.url),s=new URL(e.url.split("#")[0],r?void 0:DEFAULT_BASE_URL),i=applyRewriteRules(removePathPrefix(decodeURIComponent(s.pathname),c(this,_)),this.rewriteRules),n=await this.getPrimaryPhp();let o=util.joinPaths(c(this,w),i);if(n.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(n.isFile(l)){o=l;break}}}if(!n.isFile(o)){const a=this.getFileNotFoundAction(i);switch(a.type){case"response":return a.response;case"internal-redirect":o=util.joinPaths(c(this,w),a.uri);break;case"404":return PHPResponse.forHttpCode(404);default:throw new Error(`Unsupported file-not-found action type: '${a.type}'`)}}if(n.isFile(o))if(o.endsWith(".php")){const a={...e,url:s.toString()};return d(this,x,ee).call(this,a,o)}else return d(this,x,Z).call(this,n,o);else return PHPResponse.forHttpCode(404)}}w=new WeakMap,k=new WeakMap,N=new WeakMap,R=new WeakMap,I=new WeakMap,_=new WeakMap,C=new WeakMap,v=new WeakMap,x=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(i){return i instanceof MaxPhpInstancesError?PHPResponse.forHttpCode(502):PHPResponse.forHttpCode(500)}try{return await d(this,x,te).call(this,s.php,e,r)}finally{s.reap()}},te=async function(e,r,s){let i="GET";const n={host:c(this,I),...normalizeHeaders(r.headers||{})};c(this,v)&&(n.cookie=c(this,v).getCookieRequestHeader());let o=r.body;if(typeof o=="object"&&!(o instanceof Uint8Array)){i="POST";const{bytes:a,contentType:l}=await encodeAsMultipart(o);o=a,n["content-type"]=l}try{const a=await e.run({relativeUri:ensurePathPrefix(toRelativeUrl(new URL(r.url)),c(this,_)),protocol:c(this,k),method:r.method||i,$_SERVER:{REMOTE_ADDR:"127.0.0.1",DOCUMENT_ROOT:c(this,w),HTTPS:c(this,C).startsWith("https://")?"on":""},body:o,scriptPath:s,headers:n});return c(this,v)&&c(this,v).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 i=0;async function n(){const l=await t.semaphore.acquire();try{await t.hotSwapPHPRuntime(await r(),e),i=0}finally{l()}}async function o(){++i<s||await n()}async function a(l){l.type==="request.error"&&l.source==="php-wasm"&&await n()}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[i,n]of Object.entries(r)){const o=util.joinPaths(e,i);await t.fileExists(util.dirname(o))||await t.mkdir(util.dirname(o)),n instanceof Uint8Array||typeof n=="string"?await t.writeFile(o,n):await writeFiles(t,o,n)}}function proxyFileSystem(t,e,r){const s=Object.getOwnPropertySymbols(t)[0];for(const i of r)e.fileExists(i)||e.mkdir(i),t.fileExists(i)||t.mkdir(i),e[s].FS.mount(e[s].PROXYFS,{root:i,fs:t[s].FS},i)}exports.DEFAULT_BASE_URL=DEFAULT_BASE_URL;exports.FSHelpers=FSHelpers;exports.HttpCookieStore=HttpCookieStore;exports.LatestSupportedPHPVersion=LatestSupportedPHPVersion;exports.PHP=PHP;exports.PHPExecutionFailureError=PHPExecutionFailureError;exports.PHPProcessManager=PHPProcessManager;exports.PHPRequestHandler=PHPRequestHandler;exports.PHPResponse=PHPResponse;exports.PHPWorker=PHPWorker;exports.StreamedPHPResponse=StreamedPHPResponse;exports.SupportedPHPVersions=SupportedPHPVersions;exports.SupportedPHPVersionsList=SupportedPHPVersionsList;exports.UnhandledRejectionsTarget=UnhandledRejectionsTarget;exports.__private__dont__use=__private__dont__use;exports.applyRewriteRules=applyRewriteRules;exports.ensurePathPrefix=ensurePathPrefix;exports.getLoadedRuntime=getLoadedRuntime;exports.getPhpIniEntries=getPhpIniEntries;exports.isExitCode=isExitCode;exports.iterateFiles=iteratePhpFiles;exports.loadPHPRuntime=loadPHPRuntime;exports.proxyFileSystem=proxyFileSystem;exports.removePathPrefix=removePathPrefix;exports.rotatePHPRuntime=rotatePHPRuntime;exports.setPhpIniEntries=setPhpIniEntries;exports.toRelativeUrl=toRelativeUrl;exports.withPHPIniValues=withPHPIniValues;exports.writeFiles=writeFiles;exports.writeFilesStreamToPhp=writeFilesStreamToPhp;
58
+ `);const n=i.reduce((l,p)=>l+p.length,0),o=new Uint8Array(n);let a=0;for(const l of i)o.set(typeof l=="string"?s.encode(l):l,a),a+=l.length;return{bytes:o,contentType:t}}function fileToUint8Array(r){return r.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 w,C,M,F,I,P,A,v,x,Z,ee,te;class PHPRequestHandler{constructor(e){h(this,x);h(this,w);h(this,C);h(this,M);h(this,F);h(this,I);h(this,P);h(this,A);h(this,v);const{documentRoot:t="/www/",absoluteUrl:s=typeof location=="object"?location.href:DEFAULT_BASE_URL,rewriteRules:i=[],getFileNotFoundAction:n=()=>({type:"404"})}=e;"processManager"in e?this.processManager=e.processManager:this.processManager=new PHPProcessManager({phpFactory:async l=>{const p=await e.phpFactory({...l,requestHandler:this});return p.isDir(t)||p.mkdir(t),p.chdir(t),p.requestHandler=this,p},maxPhpInstances:e.maxPhpInstances}),f(this,v,e.cookieStore===void 0?new HttpCookieStore:e.cookieStore),f(this,w,t);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=c(this,F)!==443&&c(this,F)!==80;f(this,I,[c(this,M),a?`:${c(this,F)}`:""].join("")),f(this,P,o.pathname.replace(/\/+$/,"")),f(this,A,[`${c(this,C)}://`,c(this,I),c(this,P)].join("")),this.rewriteRules=i,this.getFileNotFoundAction=n}async getPrimaryPhp(){return await this.processManager.getPrimaryPhp()}pathToInternalUrl(e){return`${this.absoluteUrl}${e}`}internalUrlToPath(e){const t=new URL(e);return t.pathname.startsWith(c(this,P))&&(t.pathname=t.pathname.slice(c(this,P).length)),toRelativeUrl(t)}get absoluteUrl(){return c(this,A)}get documentRoot(){return c(this,w)}async request(e){const t=URL.canParse(e.url),s=new URL(e.url.split("#")[0],t?void 0:DEFAULT_BASE_URL),i=applyRewriteRules(removePathPrefix(decodeURIComponent(s.pathname),c(this,P)),this.rewriteRules),n=await this.getPrimaryPhp();let o=util.joinPaths(c(this,w),i);if(n.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(n.isFile(l)){o=l;break}}}if(!n.isFile(o)){const a=this.getFileNotFoundAction(i);switch(a.type){case"response":return a.response;case"internal-redirect":o=util.joinPaths(c(this,w),a.uri);break;case"404":return PHPResponse.forHttpCode(404);default:throw new Error(`Unsupported file-not-found action type: '${a.type}'`)}}if(n.isFile(o))if(o.endsWith(".php")){const a={...e,url:s.toString()};return d(this,x,ee).call(this,a,o)}else return d(this,x,Z).call(this,n,o);else return PHPResponse.forHttpCode(404)}async[Symbol.asyncDispose](){await this.processManager[Symbol.asyncDispose]()}}w=new WeakMap,C=new WeakMap,M=new WeakMap,F=new WeakMap,I=new WeakMap,P=new WeakMap,A=new WeakMap,v=new WeakMap,x=new WeakSet,Z=function(e,t){const s=e.readFileAsBuffer(t);return new PHPResponse(200,{"content-length":[`${s.byteLength}`],"content-type":[inferMimeType(t)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},s)},ee=async function(e,t){let s;try{s=await this.processManager.acquirePHPInstance({considerPrimary:!0})}catch(i){return i instanceof MaxPhpInstancesError?PHPResponse.forHttpCode(502):PHPResponse.forHttpCode(500)}try{return await d(this,x,te).call(this,s.php,e,t)}finally{s.reap()}},te=async function(e,t,s){let i="GET";const n={host:c(this,I),...normalizeHeaders(t.headers||{})};c(this,v)&&(n.cookie=c(this,v).getCookieRequestHeader());let o=t.body;if(typeof o=="object"&&!(o instanceof Uint8Array)){i="POST";const{bytes:a,contentType:l}=await encodeAsMultipart(o);o=a,n["content-type"]=l}try{const a=await e.run({relativeUri:ensurePathPrefix(toRelativeUrl(new URL(t.url)),c(this,P)),protocol:c(this,C),method:t.method||i,$_SERVER:{REMOTE_ADDR:"127.0.0.1",DOCUMENT_ROOT:c(this,w),HTTPS:c(this,A).startsWith("https://")?"on":""},body:o,scriptPath:s,headers:n});return c(this,v)&&c(this,v).rememberCookiesFromResponseHeaders(a.headers),a}catch(a){const l=a;if(l!=null&&l.response)return l.response;throw a}};function inferMimeType(r){const e=r.split(".").pop();return mimeTypes[e]||mimeTypes._default}function applyRewriteRules(r,e){for(const t of e)if(new RegExp(t.match).test(r))return r.replace(t.match,t.replacement);return r}function rotatePHPRuntime({php:r,cwd:e,recreateRuntime:t,maxRequests:s=400}){let i=0;async function n(){const l=await r.semaphore.acquire();try{await r.hotSwapPHPRuntime(await t(),e),i=0}finally{l()}}async function o(){++i<s||await n()}async function a(l){l.type==="request.error"&&l.source==="php-wasm"&&await n()}return r.addEventListener("request.error",a),r.addEventListener("request.end",o),function(){r.removeEventListener("request.error",a),r.removeEventListener("request.end",o)}}async function writeFiles(r,e,t,{rmRoot:s=!1}={}){s&&await r.isDir(e)&&await r.rmdir(e,{recursive:!0});for(const[i,n]of Object.entries(t)){const o=util.joinPaths(e,i);await r.fileExists(util.dirname(o))||await r.mkdir(util.dirname(o)),n instanceof Uint8Array||typeof n=="string"?await r.writeFile(o,n):await writeFiles(r,o,n)}}function proxyFileSystem(r,e,t){const s=Object.getOwnPropertySymbols(r)[0];for(const i of t)e.fileExists(i)||e.mkdir(i),r.fileExists(i)||r.mkdir(i),e[s].FS.mount(e[s].PROXYFS,{root:i,fs:r[s].FS},i)}/**
59
+ * @license
60
+ * Copyright 2019 Google LLC
61
+ * SPDX-License-Identifier: Apache-2.0
62
+ */function nodeEndpoint(r){const e=new WeakMap;return{postMessage:r.postMessage.bind(r),addEventListener:(t,s)=>{const i=n=>{"handleEvent"in s?s.handleEvent({data:n}):s({data:n})};r.on("message",i),e.set(s,i)},removeEventListener:(t,s)=>{const i=e.get(s);i&&(r.off("message",i),e.delete(s))},start:r.start&&r.start.bind(r)}}function consumeAPI(r,e=void 0){setupTransferHandlers();let t;(typeof document>"u"?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&_documentCurrentScript.tagName.toUpperCase()==="SCRIPT"&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href).startsWith("file://")?t=nodeEndpoint(r):t=r instanceof Worker?r:Comlink__namespace.windowEndpoint(r,e);const i=Comlink__namespace.wrap(t),n=proxyClone(i);return new Proxy(n,{get:(o,a)=>a==="isConnected"?async()=>{for(;;)try{await runWithTimeout(i.isConnected(),200);break}catch{}}:i[a]})}async function runWithTimeout(r,e){return new Promise((t,s)=>{setTimeout(s,e),r.then(t)})}function exposeAPI(r,e,t){setupTransferHandlers();const s=Promise.resolve();let i,n;const o=new Promise((S,m)=>{i=S,n=m}),a=proxyClone(r),l=new Proxy(a,{get:(S,m)=>m==="isConnected"?()=>s:m==="isReady"?()=>o:m in S?S[m]:e==null?void 0:e[m]});let p;return t?p=nodeEndpoint(t):p=typeof window<"u"?Comlink__namespace.windowEndpoint(self.parent):void 0,Comlink__namespace.expose(l,p),[i,n,l]}let isTransferHandlersSetup=!1;function setupTransferHandlers(){if(isTransferHandlersSetup)return;isTransferHandlersSetup=!0,Comlink__namespace.transferHandlers.set("EVENT",{canHandle:t=>t instanceof CustomEvent,serialize:t=>[{detail:t.detail},[]],deserialize:t=>t}),Comlink__namespace.transferHandlers.set("FUNCTION",{canHandle:t=>typeof t=="function",serialize(t){const{port1:s,port2:i}=new MessageChannel;return Comlink__namespace.expose(t,s),[i,[i]]},deserialize(t){return t.start(),Comlink__namespace.wrap(t)}}),Comlink__namespace.transferHandlers.set("PHPResponse",{canHandle:t=>typeof t=="object"&&t!==null&&"headers"in t&&"bytes"in t&&"errors"in t&&"exitCode"in t&&"httpStatusCode"in t,serialize(t){return[t.toRawData(),[]]},deserialize(t){return PHPResponse.fromRawData(t)}});const r=Comlink__namespace.transferHandlers.get("throw"),e=r==null?void 0:r.serialize;r.serialize=({value:t})=>{const s=e({value:t});return t.response&&(s[0].value.response=t.response),t.source&&(s[0].value.source=t.source),s}}function proxyClone(r){return new Proxy(r,{get(e,t){switch(typeof e[t]){case"function":return(...s)=>e[t](...s);case"object":return e[t]===null?e[t]:proxyClone(e[t]);case"undefined":case"number":case"string":return e[t];default:return Comlink__namespace.proxy(e[t])}}})}exports.DEFAULT_BASE_URL=DEFAULT_BASE_URL;exports.FSHelpers=FSHelpers;exports.HttpCookieStore=HttpCookieStore;exports.LatestSupportedPHPVersion=LatestSupportedPHPVersion;exports.PHP=PHP;exports.PHPExecutionFailureError=PHPExecutionFailureError;exports.PHPProcessManager=PHPProcessManager;exports.PHPRequestHandler=PHPRequestHandler;exports.PHPResponse=PHPResponse;exports.PHPWorker=PHPWorker;exports.StreamedPHPResponse=StreamedPHPResponse;exports.SupportedPHPVersions=SupportedPHPVersions;exports.SupportedPHPVersionsList=SupportedPHPVersionsList;exports.UnhandledRejectionsTarget=UnhandledRejectionsTarget;exports.__private__dont__use=__private__dont__use;exports.applyRewriteRules=applyRewriteRules;exports.consumeAPI=consumeAPI;exports.ensurePathPrefix=ensurePathPrefix;exports.exposeAPI=exposeAPI;exports.getLoadedRuntime=getLoadedRuntime;exports.getPhpIniEntries=getPhpIniEntries;exports.isExitCode=isExitCode;exports.iterateFiles=iteratePhpFiles;exports.loadPHPRuntime=loadPHPRuntime;exports.proxyFileSystem=proxyFileSystem;exports.removePathPrefix=removePathPrefix;exports.rotatePHPRuntime=rotatePHPRuntime;exports.setPhpIniEntries=setPhpIniEntries;exports.toRelativeUrl=toRelativeUrl;exports.withPHPIniValues=withPHPIniValues;exports.writeFiles=writeFiles;exports.writeFilesStreamToPhp=writeFilesStreamToPhp;
59
63
  //# sourceMappingURL=index.cjs.map