@php-wasm/universal 1.0.15 → 1.0.16

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,4 +1,4 @@
1
- "use strict";var V=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)};var p=(t,e,r)=>(V(t,e,"read from private field"),r?r.call(t):e.get(t)),u=(t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r)},h=(t,e,r,s)=>(V(t,e,"write to private field"),s?s.call(t,r):e.set(t,r),r);var d=(t,e,r)=>(V(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,s,i){const n=i.value;i.value=function(...o){try{return n.apply(this,o)}catch(a){const l=typeof a=="object"?a==null?void 0:a.errno:null;if(l in FileErrorCodes){const c=FileErrorCodes[l],y=typeof o[1]=="string"?o[1]:null,pe=y!==null?t.replaceAll("{path}",y):t;throw new Error(`${pe}: ${c}`,{cause:a})}throw a}}}}var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=(t,e,r,s)=>{for(var i=s>1?void 0:s?__getOwnPropDesc(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(i=(s?o(e,r,i):o(i))||i);return s&&i&&__defProp(e,r,i),i};const _FSHelpers=class m{static readFileAsText(e,r){return new TextDecoder().decode(m.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=m.fileExists(e,s)?e.lookupPath(s).node.mount:e.lookupPath(util.dirname(s)).node.mount;i.mountpoint!==n.mountpoint?(m.copyRecursive(e,r,s),m.isDir(e,r)?m.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&&m.listFiles(e,r).forEach(i=>{const n=`${r}/${i}`;m.isDir(e,n)?m.rmdir(e,n,s):m.unlink(e,n)}),e.rmdir(r)}static listFiles(e,r,s={prependPath:!1}){if(!m.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 m.fileExists(e,r)?e.isDir(e.lookupPath(r,{follow:!0}).node.mode):!1}static isFile(e,r){return m.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 m.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)m.copyRecursive(e,util.joinPaths(r,o),util.joinPaths(s,o))}else e.writeFile(s,e.readFile(r))}};__decorateClass([rethrowFileSystemError('Could not read "{path}"')],_FSHelpers,"readFileAsText",1);__decorateClass([rethrowFileSystemError('Could not read "{path}"')],_FSHelpers,"readFileAsBuffer",1);__decorateClass([rethrowFileSystemError('Could not write to "{path}"')],_FSHelpers,"writeFile",1);__decorateClass([rethrowFileSystemError('Could not unlink "{path}"')],_FSHelpers,"unlink",1);__decorateClass([rethrowFileSystemError('Could not remove directory "{path}"')],_FSHelpers,"rmdir",1);__decorateClass([rethrowFileSystemError('Could not list files in "{path}"')],_FSHelpers,"listFiles",1);__decorateClass([rethrowFileSystemError('Could not stat "{path}"')],_FSHelpers,"isDir",1);__decorateClass([rethrowFileSystemError('Could not stat "{path}"')],_FSHelpers,"isFile",1);__decorateClass([rethrowFileSystemError('Could not stat "{path}"')],_FSHelpers,"realpath",1);__decorateClass([rethrowFileSystemError('Could not stat "{path}"')],_FSHelpers,"fileExists",1);__decorateClass([rethrowFileSystemError('Could not create directory "{path}"')],_FSHelpers,"mkdir",1);__decorateClass([rethrowFileSystemError('Could not copy files from "{path}"')],_FSHelpers,"copyRecursive",1);let FSHelpers=_FSHelpers;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){_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 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)}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,s,i]=makePromise(),n=t.init(currentJsRuntime,{onAbort(a){i(a),logger.logger.error(a)},ENV:{},locateFile:a=>a,...e,noInitialRun:!0,onRuntimeInitialized(){e.onRuntimeInitialized&&e.onRuntimeInitialized(),s()}});await r;const o=++lastRuntimeId;return n.FS,n.id=o,n.originalExit=n._exit,n._exit=function(a){return n.outboundNetworkProxyServer&&(n.outboundNetworkProxyServer.close(),n.outboundNetworkProxyServer.closeAllConnections()),loadedRuntimes.delete(o),n.originalExit(a)},n[RuntimeId]=o,loadedRuntimes.set(o,n),o}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},kError=Symbol("error"),kMessage=Symbol("message");class ErrorEvent2 extends Event{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 isExitCodeZero(t){return t instanceof Error?"exitCode"in t&&(t==null?void 0:t.exitCode)===0||(t==null?void 0:t.name)==="ExitStatus"&&"status"in t&&t.status===0:!1}class UnhandledRejectionsTarget extends EventTarget{constructor(){super(...arguments),this.listenersCount=0}addEventListener(e,r){++this.listenersCount,super.addEventListener(e,r)}removeEventListener(e,r){--this.listenersCount,super.removeEventListener(e,r)}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()){e.dispatchEvent(new ErrorEvent("error",{error:o,message:a}));return}throw isExitCodeZero(o)||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 V=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)};var p=(t,e,r)=>(V(t,e,"read from private field"),r?r.call(t):e.get(t)),u=(t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r)},d=(t,e,r,s)=>(V(t,e,"write to private field"),s?s.call(t,r):e.set(t,r),r);var h=(t,e,r)=>(V(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,s,i){const n=i.value;i.value=function(...o){try{return n.apply(this,o)}catch(a){const l=typeof a=="object"?a==null?void 0:a.errno:null;if(l in FileErrorCodes){const c=FileErrorCodes[l],v=typeof o[1]=="string"?o[1]:null,pe=v!==null?t.replaceAll("{path}",v):t;throw new Error(`${pe}: ${c}`,{cause:a})}throw a}}}}var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=(t,e,r,s)=>{for(var i=s>1?void 0:s?__getOwnPropDesc(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(i=(s?o(e,r,i):o(i))||i);return s&&i&&__defProp(e,r,i),i};const _FSHelpers=class m{static readFileAsText(e,r){return new TextDecoder().decode(m.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=m.fileExists(e,s)?e.lookupPath(s).node.mount:e.lookupPath(util.dirname(s)).node.mount;i.mountpoint!==n.mountpoint?(m.copyRecursive(e,r,s),m.isDir(e,r)?m.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&&m.listFiles(e,r).forEach(i=>{const n=`${r}/${i}`;m.isDir(e,n)?m.rmdir(e,n,s):m.unlink(e,n)}),e.rmdir(r)}static listFiles(e,r,s={prependPath:!1}){if(!m.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 m.fileExists(e,r)?e.isDir(e.lookupPath(r,{follow:!0}).node.mode):!1}static isFile(e,r){return m.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 m.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)m.copyRecursive(e,util.joinPaths(r,o),util.joinPaths(s,o))}else e.writeFile(s,e.readFile(r))}};__decorateClass([rethrowFileSystemError('Could not read "{path}"')],_FSHelpers,"readFileAsText",1);__decorateClass([rethrowFileSystemError('Could not read "{path}"')],_FSHelpers,"readFileAsBuffer",1);__decorateClass([rethrowFileSystemError('Could not write to "{path}"')],_FSHelpers,"writeFile",1);__decorateClass([rethrowFileSystemError('Could not unlink "{path}"')],_FSHelpers,"unlink",1);__decorateClass([rethrowFileSystemError('Could not remove directory "{path}"')],_FSHelpers,"rmdir",1);__decorateClass([rethrowFileSystemError('Could not list files in "{path}"')],_FSHelpers,"listFiles",1);__decorateClass([rethrowFileSystemError('Could not stat "{path}"')],_FSHelpers,"isDir",1);__decorateClass([rethrowFileSystemError('Could not stat "{path}"')],_FSHelpers,"isFile",1);__decorateClass([rethrowFileSystemError('Could not stat "{path}"')],_FSHelpers,"realpath",1);__decorateClass([rethrowFileSystemError('Could not stat "{path}"')],_FSHelpers,"fileExists",1);__decorateClass([rethrowFileSystemError('Could not create directory "{path}"')],_FSHelpers,"mkdir",1);__decorateClass([rethrowFileSystemError('Could not copy files from "{path}"')],_FSHelpers,"copyRecursive",1);let FSHelpers=_FSHelpers;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 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)}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,s,i]=makePromise(),n=t.init(currentJsRuntime,{onAbort(a){i(a),logger.logger.error(a)},ENV:{},locateFile:a=>a,...e,noInitialRun:!0,onRuntimeInitialized(){e.onRuntimeInitialized&&e.onRuntimeInitialized(),s()}});await r;const o=++lastRuntimeId;return n.FS,n.id=o,n.originalExit=n._exit,n._exit=function(a){return n.outboundNetworkProxyServer&&(n.outboundNetworkProxyServer.close(),n.outboundNetworkProxyServer.closeAllConnections()),loadedRuntimes.delete(o),n.originalExit(a)},n[RuntimeId]=o,loadedRuntimes.set(o,n),o}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},kError=Symbol("error"),kMessage=Symbol("message");class ErrorEvent2 extends Event{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 isExitCodeZero(t){return t instanceof Error?"exitCode"in t&&(t==null?void 0:t.exitCode)===0||(t==null?void 0:t.name)==="ExitStatus"&&"status"in t&&t.status===0:!1}class UnhandledRejectionsTarget extends EventTarget{constructor(){super(...arguments),this.listenersCount=0}addEventListener(e,r){++this.listenersCount,super.addEventListener(e,r)}removeEventListener(e,r){--this.listenersCount,super.removeEventListener(e,r)}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()){e.dispatchEvent(new ErrorEvent("error",{error:o,message:a}));return}throw isExitCodeZero(o)||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. PHPNode.load('8.1', { debug: true }).
@@ -32,7 +32,7 @@ CLI option:
32
32
  ${eol}
33
33
  ${bold} WASM ERROR${reset}${redBg}`);for(const e of t.split(`
34
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 x,g,P,_,E,T,J,I,Y,C,Z,A,K,N,X,M,Q,U,ee,j,te,L,re,q,se,b,G,$,ie,O,ne,B,oe;class PHP{constructor(t){u(this,T);u(this,I);u(this,C);u(this,A);u(this,N);u(this,M);u(this,U);u(this,j);u(this,L);u(this,q);u(this,b);u(this,$);u(this,O);u(this,B);u(this,x,void 0);u(this,g,void 0);u(this,P,void 0);u(this,_,void 0);u(this,E,void 0);h(this,g,!1),h(this,P,null),h(this,_,new Map),h(this,E,[]),this.semaphore=new util.Semaphore({concurrency:1}),t!==void 0&&this.initializeRuntime(t)}addEventListener(t,e){p(this,_).has(t)||p(this,_).set(t,new Set),p(this,_).get(t).add(e)}removeEventListener(t,e){var r;(r=p(this,_).get(t))==null||r.delete(e)}dispatchEvent(t){const e=p(this,_).get(t.type);if(e)for(const r of e)r(t)}onMessage(t){p(this,E).push(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(`
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 E,g,P,_,w,T,J,I,Y,C,Z,A,K,N,X,M,Q,U,ee,j,te,L,re,q,se,b,G,$,ie,O,ne,B,oe;class PHP{constructor(t){u(this,T);u(this,I);u(this,C);u(this,A);u(this,N);u(this,M);u(this,U);u(this,j);u(this,L);u(this,q);u(this,b);u(this,$);u(this,O);u(this,B);u(this,E,void 0);u(this,g,void 0);u(this,P,void 0);u(this,_,void 0);u(this,w,void 0);d(this,g,!1),d(this,P,null),d(this,_,new Map),d(this,w,[]),this.semaphore=new util.Semaphore({concurrency:1}),t!==void 0&&this.initializeRuntime(t)}addEventListener(t,e){p(this,_).has(t)||p(this,_).set(t,new Set),p(this,_).get(t).add(e)}removeEventListener(t,e){var r;(r=p(this,_).get(t))==null||r.delete(e)}dispatchEvent(t){const e=p(this,_).get(t.type);if(e)for(const r of e)r(t)}onMessage(t){return p(this,w).push(t),async()=>{d(this,w,p(this,w).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(`
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,10 +47,10 @@ ${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 p(this,E)){const i=await s(r);if(i)return i}return""},h(this,P,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?");h(this,x,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.semaphore.acquire();let r;try{if(p(this,g)||(d(this,I,Y).call(this),h(this,g,!0)),t.scriptPath&&!this.fileExists(t.scriptPath))throw new Error(`The script path "${t.scriptPath}" does not exist.`);d(this,A,K).call(this,t.relativeUri||""),d(this,j,te).call(this,t.method||"GET");const s=normalizeHeaders(t.headers||{}),i=s.host||"example.com:443",n=d(this,U,ee).call(this,i,t.protocol||"http");if(d(this,N,X).call(this,i),d(this,M,Q).call(this,n),d(this,L,re).call(this,s),t.body&&(r=d(this,q,se).call(this,t.body)),typeof t.code=="string")this.writeFile("/internal/eval.php",t.code),d(this,b,G).call(this,"/internal/eval.php");else if(typeof t.scriptPath=="string")d(this,b,G).call(this,t.scriptPath||"");else throw new TypeError("The request object must have either a `code` or a `scriptPath` property.");const o=d(this,T,J).call(this,t.$_SERVER,s,n);for(const c in o)d(this,$,ie).call(this,c,o[c]);const a=t.env||{};for(const c in a)d(this,O,ne).call(this,c,a[c]);const l=await d(this,B,oe).call(this);if(l.exitCode!==0){logger.logger.warn("PHP.run() output was:",l.text);const c=new PHPExecutionFailureError(`PHP.run() failed with exit code ${l.exitCode} and the following output: `+l.errors,l,"request");throw logger.logger.error(c),c}return l}catch(s){throw this.dispatchEvent({type:"request.error",error:s,source:s.source??"php-wasm"}),s}finally{try{r&&this[__private__dont__use].free(r)}finally{e(),this.dispatchEvent({type:"request.end"})}}}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)}hotSwapPHPRuntime(t,e){const r=this[__private__dont__use].FS;try{this.exit()}catch{}this.initializeRuntime(t),p(this,x)&&this.setSapiName(p(this,x)),e&&copyFS(r,this[__private__dont__use].FS,e)}async mount(t,e){return await e(this,this[__private__dont__use].FS,t)}async cli(t){for(const e of t)this[__private__dont__use].ccall("wasm_add_cli_arg",null,[STRING],[e]);try{return await this[__private__dont__use].ccall("run_cli",null,[],[],{async:!0})}catch(e){if(isExitCodeZero(e))return 0;throw e}}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{}h(this,g,!1),h(this,P,null),delete this[__private__dont__use].onMessage,delete this[__private__dont__use]}[Symbol.dispose](){p(this,g)&&this.exit(0)}}x=new WeakMap,g=new WeakMap,P=new WeakMap,_=new WeakMap,E=new WeakMap,T=new WeakSet,J=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},I=new WeakSet,Y=function(){this[__private__dont__use].ccall("php_wasm_init",null,[],[])},C=new WeakSet,Z=function(){const t="/internal/headers.json";if(!this.fileExists(t))throw new Error("SAPI Error: Could not find response headers file.");const e=JSON.parse(this.readFileAsText(t)),r={};for(const s of e.headers){if(!s.includes(": "))continue;const i=s.indexOf(": "),n=s.substring(0,i).toLowerCase(),o=s.substring(i+2);n in r||(r[n]=[]),r[n].push(o)}return{headers:r,httpStatusCode:e.status}},A=new WeakSet,K=function(t){if(this[__private__dont__use].ccall("wasm_set_request_uri",null,[STRING],[t]),t.includes("?")){const e=t.substring(t.indexOf("?")+1);this[__private__dont__use].ccall("wasm_set_query_string",null,[STRING],[e])}},N=new WeakSet,X=function(t){this[__private__dont__use].ccall("wasm_set_request_host",null,[STRING],[t])},M=new WeakSet,Q=function(t){this[__private__dont__use].ccall("wasm_set_request_port",null,[NUMBER],[t])},U=new WeakSet,ee=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},j=new WeakSet,te=function(t){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[t])},L=new WeakSet,re=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)])},q=new WeakSet,se=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},b=new WeakSet,G=function(t){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[t])},$=new WeakSet,ie=function(t,e){this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[t,e])},O=new WeakSet,ne=function(t,e){this[__private__dont__use].ccall("wasm_add_ENV_entry",null,[STRING,STRING],[t,e])},B=new WeakSet,oe=async function(){var i;let t,e;try{t=await new Promise((n,o)=>{var l;e=c=>{logger.logger.error(c),logger.logger.error(c.error);const y=new Error("Rethrown");y.cause=c.error,y.betterMessage=c.message,o(y)},(l=p(this,P))==null||l.addEventListener("error",e);const a=this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0});return a instanceof Promise?a.then(n,o):n(a)})}catch(n){for(const c in this)typeof this[c]=="function"&&(this[c]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});this.functionsMaybeMissingFromAsyncify=getFunctionsMaybeMissingFromAsyncify();const o=n,a="betterMessage"in o?o.betterMessage:o.message,l=new Error(a);throw l.cause=o,logger.logger.error(l),l}finally{(i=p(this,P))==null||i.removeEventListener("error",e)}const{headers:r,httpStatusCode:s}=d(this,C,Z).call(this);return new PHPResponse(t===0?s:500,r,this.readFileAsBuffer("/internal/stdout"),this.readFileAsText("/internal/stderr"),t)};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 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 c=`${o}/${l}`;if(i.includes(c.substring(e.length+1)))continue;await t.isDir(c)?n.push(c):yield new streamCompression.StreamedFile(streamReadFileFromPHP(t,c),r?util.joinPaths(s||"",c.substring(e.length+1)):c)}}}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().");if(!this.primaryPhp){const e=await this.spawn({isPrimary:!0});this.primaryPhp=e.php}return this.primaryPhp}async acquirePHPInstance(){if(this.primaryIdle)return this.primaryIdle=!1,{php:await this.getPrimaryPhp(),reap:()=>this.primaryIdle=!0};const e=this.nextInstance||this.spawn({isPrimary:!1});return this.semaphore.remaining>0?this.nextInstance=this.spawn({isPrimary:!1}):this.nextInstance=null,await e}spawn(e){if(e.isPrimary&&this.allInstances.length>0)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.3","8.2","8.1","8.0","7.4","7.3","7.2","7.1","7.0"],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,c]of Object.entries(t))i.push(`--${e}\r
50
+ `),e.onMessage=async r=>{for(const s of p(this,w)){const i=await s(r);if(i)return i}return""},d(this,P,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?");d(this,E,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.semaphore.acquire();let r;try{if(p(this,g)||(h(this,I,Y).call(this),d(this,g,!0)),t.scriptPath&&!this.fileExists(t.scriptPath))throw new Error(`The script path "${t.scriptPath}" does not exist.`);h(this,A,K).call(this,t.relativeUri||""),h(this,j,te).call(this,t.method||"GET");const s=normalizeHeaders(t.headers||{}),i=s.host||"example.com:443",n=h(this,U,ee).call(this,i,t.protocol||"http");if(h(this,N,X).call(this,i),h(this,M,Q).call(this,n),h(this,L,re).call(this,s),t.body&&(r=h(this,q,se).call(this,t.body)),typeof t.code=="string")this.writeFile("/internal/eval.php",t.code),h(this,b,G).call(this,"/internal/eval.php");else if(typeof t.scriptPath=="string")h(this,b,G).call(this,t.scriptPath||"");else throw new TypeError("The request object must have either a `code` or a `scriptPath` property.");const o=h(this,T,J).call(this,t.$_SERVER,s,n);for(const c in o)h(this,$,ie).call(this,c,o[c]);const a=t.env||{};for(const c in a)h(this,O,ne).call(this,c,a[c]);const l=await h(this,B,oe).call(this);if(l.exitCode!==0){logger.logger.warn("PHP.run() output was:",l.text);const c=new PHPExecutionFailureError(`PHP.run() failed with exit code ${l.exitCode} and the following output: `+l.errors,l,"request");throw logger.logger.error(c),c}return l}catch(s){throw this.dispatchEvent({type:"request.error",error:s,source:s.source??"php-wasm"}),s}finally{try{r&&this[__private__dont__use].free(r)}finally{e(),this.dispatchEvent({type:"request.end"})}}}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)}hotSwapPHPRuntime(t,e){const r=this[__private__dont__use].FS;try{this.exit()}catch{}this.initializeRuntime(t),p(this,E)&&this.setSapiName(p(this,E)),e&&copyFS(r,this[__private__dont__use].FS,e)}async mount(t,e){return await e(this,this[__private__dont__use].FS,t)}async cli(t){for(const e of t)this[__private__dont__use].ccall("wasm_add_cli_arg",null,[STRING],[e]);try{return await this[__private__dont__use].ccall("run_cli",null,[],[],{async:!0})}catch(e){if(isExitCodeZero(e))return 0;throw e}}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{}d(this,g,!1),d(this,P,null),delete this[__private__dont__use].onMessage,delete this[__private__dont__use]}[Symbol.dispose](){p(this,g)&&this.exit(0)}}E=new WeakMap,g=new WeakMap,P=new WeakMap,_=new WeakMap,w=new WeakMap,T=new WeakSet,J=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},I=new WeakSet,Y=function(){this[__private__dont__use].ccall("php_wasm_init",null,[],[])},C=new WeakSet,Z=function(){const t="/internal/headers.json";if(!this.fileExists(t))throw new Error("SAPI Error: Could not find response headers file.");const e=JSON.parse(this.readFileAsText(t)),r={};for(const s of e.headers){if(!s.includes(": "))continue;const i=s.indexOf(": "),n=s.substring(0,i).toLowerCase(),o=s.substring(i+2);n in r||(r[n]=[]),r[n].push(o)}return{headers:r,httpStatusCode:e.status}},A=new WeakSet,K=function(t){if(this[__private__dont__use].ccall("wasm_set_request_uri",null,[STRING],[t]),t.includes("?")){const e=t.substring(t.indexOf("?")+1);this[__private__dont__use].ccall("wasm_set_query_string",null,[STRING],[e])}},N=new WeakSet,X=function(t){this[__private__dont__use].ccall("wasm_set_request_host",null,[STRING],[t])},M=new WeakSet,Q=function(t){this[__private__dont__use].ccall("wasm_set_request_port",null,[NUMBER],[t])},U=new WeakSet,ee=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},j=new WeakSet,te=function(t){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[t])},L=new WeakSet,re=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)])},q=new WeakSet,se=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},b=new WeakSet,G=function(t){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[t])},$=new WeakSet,ie=function(t,e){this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[t,e])},O=new WeakSet,ne=function(t,e){this[__private__dont__use].ccall("wasm_add_ENV_entry",null,[STRING,STRING],[t,e])},B=new WeakSet,oe=async function(){var i;let t,e;try{t=await new Promise((n,o)=>{var l;e=c=>{logger.logger.error(c),logger.logger.error(c.error);const v=new Error("Rethrown");v.cause=c.error,v.betterMessage=c.message,o(v)},(l=p(this,P))==null||l.addEventListener("error",e);const a=this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0});return a instanceof Promise?a.then(n,o):n(a)})}catch(n){for(const c in this)typeof this[c]=="function"&&(this[c]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});this.functionsMaybeMissingFromAsyncify=getFunctionsMaybeMissingFromAsyncify();const o=n,a="betterMessage"in o?o.betterMessage:o.message,l=new Error(a);throw l.cause=o,logger.logger.error(l),l}finally{(i=p(this,P))==null||i.removeEventListener("error",e)}const{headers:r,httpStatusCode:s}=h(this,C,Z).call(this);return new PHPResponse(t===0?s:500,r,this.readFileAsBuffer("/internal/stdout"),this.readFileAsText("/internal/stderr"),t)};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 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 c=`${o}/${l}`;if(i.includes(c.substring(e.length+1)))continue;await t.isDir(c)?n.push(c):yield new streamCompression.StreamedFile(streamReadFileFromPHP(t,c),r?util.joinPaths(s||"",c.substring(e.length+1)):c)}}}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().");if(!this.primaryPhp){const e=await this.spawn({isPrimary:!0});this.primaryPhp=e.php}return this.primaryPhp}async acquirePHPInstance(){if(this.primaryIdle)return this.primaryIdle=!1,{php:await this.getPrimaryPhp(),reap:()=>this.primaryIdle=!0};const e=this.nextInstance||this.spawn({isPrimary:!1});return this.semaphore.remaining>0?this.nextInstance=this.spawn({isPrimary:!1}):this.nextInstance=null,await e}spawn(e){if(e.isPrimary&&this.allInstances.length>0)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.3","8.2","8.1","8.0","7.4","7.3","7.2","7.1","7.0"],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,c]of Object.entries(t))i.push(`--${e}\r
51
51
  `),i.push(`Content-Disposition: form-data; name="${l}"`),c instanceof File&&i.push(`; filename="${c.name}"`),i.push(`\r
52
52
  `),c instanceof File&&(i.push("Content-Type: application/octet-stream"),i.push(`\r
53
53
  `)),i.push(`\r
54
54
  `),c instanceof File?i.push(await fileToUint8Array(c)):i.push(c),i.push(`\r
55
55
  `);i.push(`--${e}--\r
56
- `);const n=i.reduce((l,c)=>l+c.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 new Promise(e=>{const r=new FileReader;r.onload=()=>{e(new Uint8Array(r.result))},r.readAsArrayBuffer(t)})}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,R,k,v,F,f,S,H,D,ae,z,le,W,ce;class PHPRequestHandler{constructor(e){u(this,D);u(this,z);u(this,W);u(this,w,void 0);u(this,R,void 0);u(this,k,void 0);u(this,v,void 0);u(this,F,void 0);u(this,f,void 0);u(this,S,void 0);u(this,H,void 0);const{documentRoot:r="/www/",absoluteUrl:s=typeof location=="object"?location==null?void 0:location.href:"",rewriteRules:i=[],getFileNotFoundAction:n=()=>({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.requestHandler=this,c},maxPhpInstances:e.maxPhpInstances}),h(this,H,new HttpCookieStore),h(this,w,r);const o=new URL(s);h(this,k,o.hostname),h(this,v,o.port?Number(o.port):o.protocol==="https:"?443:80),h(this,R,(o.protocol||"").replace(":",""));const a=p(this,v)!==443&&p(this,v)!==80;h(this,F,[p(this,k),a?`:${p(this,v)}`:""].join("")),h(this,f,o.pathname.replace(/\/+$/,"")),h(this,S,[`${p(this,R)}://`,p(this,F),p(this,f)].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(p(this,f))&&(r.pathname=r.pathname.slice(p(this,f).length)),toRelativeUrl(r)}get absoluteUrl(){return p(this,S)}get documentRoot(){return p(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),p(this,f)),this.rewriteRules),n=await this.getPrimaryPhp();let o=util.joinPaths(p(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(p(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,z,le).call(this,a,o)}else return d(this,D,ae).call(this,n,o);else return PHPResponse.forHttpCode(404)}}w=new WeakMap,R=new WeakMap,k=new WeakMap,v=new WeakMap,F=new WeakMap,f=new WeakMap,S=new WeakMap,H=new WeakMap,D=new WeakSet,ae=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)},z=new WeakSet,le=async function(e,r){let s;try{s=await this.processManager.acquirePHPInstance()}catch(i){return i instanceof MaxPhpInstancesError?PHPResponse.forHttpCode(502):PHPResponse.forHttpCode(500)}try{return await d(this,W,ce).call(this,s.php,e,r)}finally{s.reap()}},W=new WeakSet,ce=async function(e,r,s){let i="GET";const n={host:p(this,F),...normalizeHeaders(r.headers||{}),cookie:p(this,H).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)),p(this,f)),protocol:p(this,R),method:r.method||i,$_SERVER:{REMOTE_ADDR:"127.0.0.1",DOCUMENT_ROOT:p(this,w),HTTPS:p(this,S).startsWith("https://")?"on":""},body:o,scriptPath:s,headers:n});return p(this,H).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{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.PHPProcessManager=PHPProcessManager;exports.PHPRequestHandler=PHPRequestHandler;exports.PHPResponse=PHPResponse;exports.PHPWorker=PHPWorker;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.isExitCodeZero=isExitCodeZero;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;
56
+ `);const n=i.reduce((l,c)=>l+c.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 new Promise(e=>{const r=new FileReader;r.onload=()=>{e(new Uint8Array(r.result))},r.readAsArrayBuffer(t)})}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 y,R,k,x,F,f,S,H,D,ae,z,le,W,ce;class PHPRequestHandler{constructor(e){u(this,D);u(this,z);u(this,W);u(this,y,void 0);u(this,R,void 0);u(this,k,void 0);u(this,x,void 0);u(this,F,void 0);u(this,f,void 0);u(this,S,void 0);u(this,H,void 0);const{documentRoot:r="/www/",absoluteUrl:s=typeof location=="object"?location==null?void 0:location.href:"",rewriteRules:i=[],getFileNotFoundAction:n=()=>({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.requestHandler=this,c},maxPhpInstances:e.maxPhpInstances}),d(this,H,new HttpCookieStore),d(this,y,r);const o=new URL(s);d(this,k,o.hostname),d(this,x,o.port?Number(o.port):o.protocol==="https:"?443:80),d(this,R,(o.protocol||"").replace(":",""));const a=p(this,x)!==443&&p(this,x)!==80;d(this,F,[p(this,k),a?`:${p(this,x)}`:""].join("")),d(this,f,o.pathname.replace(/\/+$/,"")),d(this,S,[`${p(this,R)}://`,p(this,F),p(this,f)].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(p(this,f))&&(r.pathname=r.pathname.slice(p(this,f).length)),toRelativeUrl(r)}get absoluteUrl(){return p(this,S)}get documentRoot(){return p(this,y)}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),p(this,f)),this.rewriteRules),n=await this.getPrimaryPhp();let o=util.joinPaths(p(this,y),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(p(this,y),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 h(this,z,le).call(this,a,o)}else return h(this,D,ae).call(this,n,o);else return PHPResponse.forHttpCode(404)}}y=new WeakMap,R=new WeakMap,k=new WeakMap,x=new WeakMap,F=new WeakMap,f=new WeakMap,S=new WeakMap,H=new WeakMap,D=new WeakSet,ae=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)},z=new WeakSet,le=async function(e,r){let s;try{s=await this.processManager.acquirePHPInstance()}catch(i){return i instanceof MaxPhpInstancesError?PHPResponse.forHttpCode(502):PHPResponse.forHttpCode(500)}try{return await h(this,W,ce).call(this,s.php,e,r)}finally{s.reap()}},W=new WeakSet,ce=async function(e,r,s){let i="GET";const n={host:p(this,F),...normalizeHeaders(r.headers||{}),cookie:p(this,H).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)),p(this,f)),protocol:p(this,R),method:r.method||i,$_SERVER:{REMOTE_ADDR:"127.0.0.1",DOCUMENT_ROOT:p(this,y),HTTPS:p(this,S).startsWith("https://")?"on":""},body:o,scriptPath:s,headers:n});return p(this,H).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{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.PHPProcessManager=PHPProcessManager;exports.PHPRequestHandler=PHPRequestHandler;exports.PHPResponse=PHPResponse;exports.PHPWorker=PHPWorker;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.isExitCodeZero=isExitCodeZero;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;
package/index.js CHANGED
@@ -6,8 +6,8 @@ var p = (t, e, r) => (G(t, e, "read from private field"), r ? r.call(t) : e.get(
6
6
  if (e.has(t))
7
7
  throw TypeError("Cannot add the same private member more than once");
8
8
  e instanceof WeakSet ? e.add(t) : e.set(t, r);
9
- }, h = (t, e, r, s) => (G(t, e, "write to private field"), s ? s.call(t, r) : e.set(t, r), r);
10
- var d = (t, e, r) => (G(t, e, "access private method"), r);
9
+ }, d = (t, e, r, s) => (G(t, e, "write to private field"), s ? s.call(t, r) : e.set(t, r), r);
10
+ var h = (t, e, r) => (G(t, e, "access private method"), r);
11
11
  import "@php-wasm/node-polyfills";
12
12
  import { logger } from "@php-wasm/logger";
13
13
  import { dirname, joinPaths, Semaphore, createSpawnHandler, normalizePath, AcquireTimeoutError } from "@php-wasm/util";
@@ -106,7 +106,7 @@ function rethrowFileSystemError(t = "") {
106
106
  } catch (a) {
107
107
  const l = typeof a == "object" ? a == null ? void 0 : a.errno : null;
108
108
  if (l in FileErrorCodes) {
109
- const c = FileErrorCodes[l], P = typeof o[1] == "string" ? o[1] : null, pe = P !== null ? t.replaceAll("{path}", P) : t;
109
+ const c = FileErrorCodes[l], v = typeof o[1] == "string" ? o[1] : null, pe = v !== null ? t.replaceAll("{path}", v) : t;
110
110
  throw new Error(`${pe}: ${c}`, {
111
111
  cause: a
112
112
  });
@@ -397,7 +397,7 @@ class PHPWorker {
397
397
  }
398
398
  /** @inheritDoc @php-wasm/universal!/PHP.onMessage */
399
399
  onMessage(e) {
400
- _private.get(this).php.onMessage(e);
400
+ return _private.get(this).php.onMessage(e);
401
401
  }
402
402
  /** @inheritDoc @php-wasm/universal!/PHP.defineConstant */
403
403
  defineConstant(e, r) {
@@ -659,7 +659,7 @@ class PHPExecutionFailureError extends Error {
659
659
  }
660
660
  }
661
661
  const PHP_INI_PATH = "/internal/shared/php.ini", AUTO_PREPEND_SCRIPT = "/internal/shared/auto_prepend_file.php";
662
- var x, g, w, _, E, T, J, I, Y, C, Z, A, K, N, X, M, Q, j, ee, U, te, L, re, q, se, b, V, $, ie, O, ne, B, oe;
662
+ var E, g, w, _, y, T, J, I, Y, C, Z, A, K, N, X, M, Q, j, ee, U, te, L, re, q, se, b, V, $, ie, O, ne, B, oe;
663
663
  class PHP {
664
664
  /**
665
665
  * Initializes a PHP runtime.
@@ -692,12 +692,12 @@ class PHP {
692
692
  u(this, $);
693
693
  u(this, O);
694
694
  u(this, B);
695
- u(this, x, void 0);
695
+ u(this, E, void 0);
696
696
  u(this, g, void 0);
697
697
  u(this, w, void 0);
698
698
  u(this, _, void 0);
699
- u(this, E, void 0);
700
- h(this, g, !1), h(this, w, null), h(this, _, /* @__PURE__ */ new Map()), h(this, E, []), this.semaphore = new Semaphore({ concurrency: 1 }), t !== void 0 && this.initializeRuntime(t);
699
+ u(this, y, void 0);
700
+ d(this, g, !1), d(this, w, null), d(this, _, /* @__PURE__ */ new Map()), d(this, y, []), this.semaphore = new Semaphore({ concurrency: 1 }), t !== void 0 && this.initializeRuntime(t);
701
701
  }
702
702
  /**
703
703
  * Adds an event listener for a PHP event.
@@ -762,7 +762,11 @@ class PHP {
762
762
  * @param listener Callback function to handle the message.
763
763
  */
764
764
  onMessage(t) {
765
- p(this, E).push(t);
765
+ return p(this, y).push(t), async () => {
766
+ d(this, y, p(this, y).filter(
767
+ (e) => e !== t
768
+ ));
769
+ };
766
770
  }
767
771
  async setSpawnHandler(handler) {
768
772
  typeof handler == "string" && (handler = createSpawnHandler(eval(handler))), this[__private__dont__use].spawnProcess = handler;
@@ -835,13 +839,13 @@ class PHP {
835
839
  }
836
840
  `
837
841
  ), e.onMessage = async (r) => {
838
- for (const s of p(this, E)) {
842
+ for (const s of p(this, y)) {
839
843
  const i = await s(r);
840
844
  if (i)
841
845
  return i;
842
846
  }
843
847
  return "";
844
- }, h(this, w, improveWASMErrorReporting(e)), this.dispatchEvent({
848
+ }, d(this, w, improveWASMErrorReporting(e)), this.dispatchEvent({
845
849
  type: "runtime.initialized"
846
850
  });
847
851
  }
@@ -856,7 +860,7 @@ class PHP {
856
860
  throw new Error(
857
861
  "Could not set SAPI name. This can only be done before the PHP WASM module is initialized.Did you already dispatch any requests?"
858
862
  );
859
- h(this, x, t);
863
+ d(this, E, t);
860
864
  }
861
865
  /**
862
866
  * Changes the current working directory in the PHP filesystem.
@@ -953,27 +957,27 @@ class PHP {
953
957
  const e = await this.semaphore.acquire();
954
958
  let r;
955
959
  try {
956
- if (p(this, g) || (d(this, I, Y).call(this), h(this, g, !0)), t.scriptPath && !this.fileExists(t.scriptPath))
960
+ if (p(this, g) || (h(this, I, Y).call(this), d(this, g, !0)), t.scriptPath && !this.fileExists(t.scriptPath))
957
961
  throw new Error(
958
962
  `The script path "${t.scriptPath}" does not exist.`
959
963
  );
960
- d(this, A, K).call(this, t.relativeUri || ""), d(this, U, te).call(this, t.method || "GET");
961
- const s = normalizeHeaders(t.headers || {}), i = s.host || "example.com:443", n = d(this, j, ee).call(this, i, t.protocol || "http");
962
- if (d(this, N, X).call(this, i), d(this, M, Q).call(this, n), d(this, L, re).call(this, s), t.body && (r = d(this, q, se).call(this, t.body)), typeof t.code == "string")
963
- this.writeFile("/internal/eval.php", t.code), d(this, b, V).call(this, "/internal/eval.php");
964
+ h(this, A, K).call(this, t.relativeUri || ""), h(this, U, te).call(this, t.method || "GET");
965
+ const s = normalizeHeaders(t.headers || {}), i = s.host || "example.com:443", n = h(this, j, ee).call(this, i, t.protocol || "http");
966
+ if (h(this, N, X).call(this, i), h(this, M, Q).call(this, n), h(this, L, re).call(this, s), t.body && (r = h(this, q, se).call(this, t.body)), typeof t.code == "string")
967
+ this.writeFile("/internal/eval.php", t.code), h(this, b, V).call(this, "/internal/eval.php");
964
968
  else if (typeof t.scriptPath == "string")
965
- d(this, b, V).call(this, t.scriptPath || "");
969
+ h(this, b, V).call(this, t.scriptPath || "");
966
970
  else
967
971
  throw new TypeError(
968
972
  "The request object must have either a `code` or a `scriptPath` property."
969
973
  );
970
- const o = d(this, T, J).call(this, t.$_SERVER, s, n);
974
+ const o = h(this, T, J).call(this, t.$_SERVER, s, n);
971
975
  for (const c in o)
972
- d(this, $, ie).call(this, c, o[c]);
976
+ h(this, $, ie).call(this, c, o[c]);
973
977
  const a = t.env || {};
974
978
  for (const c in a)
975
- d(this, O, ne).call(this, c, a[c]);
976
- const l = await d(this, B, oe).call(this);
979
+ h(this, O, ne).call(this, c, a[c]);
980
+ const l = await h(this, B, oe).call(this);
977
981
  if (l.exitCode !== 0) {
978
982
  logger.warn("PHP.run() output was:", l.text);
979
983
  const c = new PHPExecutionFailureError(
@@ -1187,7 +1191,7 @@ class PHP {
1187
1191
  this.exit();
1188
1192
  } catch {
1189
1193
  }
1190
- this.initializeRuntime(t), p(this, x) && this.setSapiName(p(this, x)), e && copyFS(r, this[__private__dont__use].FS, e);
1194
+ this.initializeRuntime(t), p(this, E) && this.setSapiName(p(this, E)), e && copyFS(r, this[__private__dont__use].FS, e);
1191
1195
  }
1192
1196
  /**
1193
1197
  * Mounts a filesystem to a given path in the PHP filesystem.
@@ -1256,13 +1260,13 @@ class PHP {
1256
1260
  this[__private__dont__use]._exit(t);
1257
1261
  } catch {
1258
1262
  }
1259
- h(this, g, !1), h(this, w, null), delete this[__private__dont__use].onMessage, delete this[__private__dont__use];
1263
+ d(this, g, !1), d(this, w, null), delete this[__private__dont__use].onMessage, delete this[__private__dont__use];
1260
1264
  }
1261
1265
  [Symbol.dispose]() {
1262
1266
  p(this, g) && this.exit(0);
1263
1267
  }
1264
1268
  }
1265
- x = new WeakMap(), g = new WeakMap(), w = new WeakMap(), _ = new WeakMap(), E = new WeakMap(), T = new WeakSet(), J = function(t, e, r) {
1269
+ E = new WeakMap(), g = new WeakMap(), w = new WeakMap(), _ = new WeakMap(), y = new WeakMap(), T = new WeakSet(), J = function(t, e, r) {
1266
1270
  const s = {
1267
1271
  ...t || {}
1268
1272
  };
@@ -1403,8 +1407,8 @@ x = new WeakMap(), g = new WeakMap(), w = new WeakMap(), _ = new WeakMap(), E =
1403
1407
  var l;
1404
1408
  e = (c) => {
1405
1409
  logger.error(c), logger.error(c.error);
1406
- const P = new Error("Rethrown");
1407
- P.cause = c.error, P.betterMessage = c.message, o(P);
1410
+ const v = new Error("Rethrown");
1411
+ v.cause = c.error, v.betterMessage = c.message, o(v);
1408
1412
  }, (l = p(this, w)) == null || l.addEventListener(
1409
1413
  "error",
1410
1414
  e
@@ -1431,7 +1435,7 @@ x = new WeakMap(), g = new WeakMap(), w = new WeakMap(), _ = new WeakMap(), E =
1431
1435
  } finally {
1432
1436
  (i = p(this, w)) == null || i.removeEventListener("error", e);
1433
1437
  }
1434
- const { headers: r, httpStatusCode: s } = d(this, C, Z).call(this);
1438
+ const { headers: r, httpStatusCode: s } = h(this, C, Z).call(this);
1435
1439
  return new PHPResponse(
1436
1440
  t === 0 ? s : 500,
1437
1441
  r,
@@ -1812,7 +1816,7 @@ const _default = "application/octet-stream", asx = "video/x-ms-asf", atom = "app
1812
1816
  xspf,
1813
1817
  zip
1814
1818
  };
1815
- var y, R, k, v, F, f, S, H, D, ae, z, le, W, ce;
1819
+ var P, R, k, x, F, f, S, H, D, ae, z, le, W, ce;
1816
1820
  class PHPRequestHandler {
1817
1821
  /**
1818
1822
  * The request handler needs to decide whether to serve a static asset or
@@ -1845,10 +1849,10 @@ class PHPRequestHandler {
1845
1849
  * @returns The response.
1846
1850
  */
1847
1851
  u(this, W);
1848
- u(this, y, void 0);
1852
+ u(this, P, void 0);
1849
1853
  u(this, R, void 0);
1850
1854
  u(this, k, void 0);
1851
- u(this, v, void 0);
1855
+ u(this, x, void 0);
1852
1856
  u(this, F, void 0);
1853
1857
  u(this, f, void 0);
1854
1858
  u(this, S, void 0);
@@ -1868,14 +1872,14 @@ class PHPRequestHandler {
1868
1872
  return c.requestHandler = this, c;
1869
1873
  },
1870
1874
  maxPhpInstances: e.maxPhpInstances
1871
- }), h(this, H, new HttpCookieStore()), h(this, y, r);
1875
+ }), d(this, H, new HttpCookieStore()), d(this, P, r);
1872
1876
  const o = new URL(s);
1873
- h(this, k, o.hostname), h(this, v, o.port ? Number(o.port) : o.protocol === "https:" ? 443 : 80), h(this, R, (o.protocol || "").replace(":", ""));
1874
- const a = p(this, v) !== 443 && p(this, v) !== 80;
1875
- h(this, F, [
1877
+ d(this, k, o.hostname), d(this, x, o.port ? Number(o.port) : o.protocol === "https:" ? 443 : 80), d(this, R, (o.protocol || "").replace(":", ""));
1878
+ const a = p(this, x) !== 443 && p(this, x) !== 80;
1879
+ d(this, F, [
1876
1880
  p(this, k),
1877
- a ? `:${p(this, v)}` : ""
1878
- ].join("")), h(this, f, o.pathname.replace(/\/+$/, "")), h(this, S, [
1881
+ a ? `:${p(this, x)}` : ""
1882
+ ].join("")), d(this, f, o.pathname.replace(/\/+$/, "")), d(this, S, [
1879
1883
  `${p(this, R)}://`,
1880
1884
  p(this, F),
1881
1885
  p(this, f)
@@ -1916,7 +1920,7 @@ class PHPRequestHandler {
1916
1920
  * for the files to serve. Default: `/var/www`.
1917
1921
  */
1918
1922
  get documentRoot() {
1919
- return p(this, y);
1923
+ return p(this, P);
1920
1924
  }
1921
1925
  /**
1922
1926
  * Serves the request – either by serving a static file, or by
@@ -1978,7 +1982,7 @@ class PHPRequestHandler {
1978
1982
  ),
1979
1983
  this.rewriteRules
1980
1984
  ), n = await this.getPrimaryPhp();
1981
- let o = joinPaths(p(this, y), i);
1985
+ let o = joinPaths(p(this, P), i);
1982
1986
  if (n.isDir(o)) {
1983
1987
  if (!o.endsWith("/"))
1984
1988
  return new PHPResponse(
@@ -2002,7 +2006,7 @@ class PHPRequestHandler {
2002
2006
  case "response":
2003
2007
  return a.response;
2004
2008
  case "internal-redirect":
2005
- o = joinPaths(p(this, y), a.uri);
2009
+ o = joinPaths(p(this, P), a.uri);
2006
2010
  break;
2007
2011
  case "404":
2008
2012
  return PHPResponse.forHttpCode(404);
@@ -2019,14 +2023,14 @@ class PHPRequestHandler {
2019
2023
  // Pass along URL with the #fragment filtered out
2020
2024
  url: s.toString()
2021
2025
  };
2022
- return d(this, z, le).call(this, a, o);
2026
+ return h(this, z, le).call(this, a, o);
2023
2027
  } else
2024
- return d(this, D, ae).call(this, n, o);
2028
+ return h(this, D, ae).call(this, n, o);
2025
2029
  else
2026
2030
  return PHPResponse.forHttpCode(404);
2027
2031
  }
2028
2032
  }
2029
- y = new WeakMap(), R = new WeakMap(), k = new WeakMap(), v = new WeakMap(), F = new WeakMap(), f = new WeakMap(), S = new WeakMap(), H = new WeakMap(), D = new WeakSet(), ae = function(e, r) {
2033
+ P = new WeakMap(), R = new WeakMap(), k = new WeakMap(), x = new WeakMap(), F = new WeakMap(), f = new WeakMap(), S = new WeakMap(), H = new WeakMap(), D = new WeakSet(), ae = function(e, r) {
2030
2034
  const s = e.readFileAsBuffer(r);
2031
2035
  return new PHPResponse(
2032
2036
  200,
@@ -2049,7 +2053,7 @@ y = new WeakMap(), R = new WeakMap(), k = new WeakMap(), v = new WeakMap(), F =
2049
2053
  return i instanceof MaxPhpInstancesError ? PHPResponse.forHttpCode(502) : PHPResponse.forHttpCode(500);
2050
2054
  }
2051
2055
  try {
2052
- return await d(this, W, ce).call(this, s.php, e, r);
2056
+ return await h(this, W, ce).call(this, s.php, e, r);
2053
2057
  } finally {
2054
2058
  s.reap();
2055
2059
  }
@@ -2076,7 +2080,7 @@ y = new WeakMap(), R = new WeakMap(), k = new WeakMap(), v = new WeakMap(), F =
2076
2080
  method: r.method || i,
2077
2081
  $_SERVER: {
2078
2082
  REMOTE_ADDR: "127.0.0.1",
2079
- DOCUMENT_ROOT: p(this, y),
2083
+ DOCUMENT_ROOT: p(this, P),
2080
2084
  HTTPS: p(this, S).startsWith("https://") ? "on" : ""
2081
2085
  },
2082
2086
  body: o,
@@ -69,7 +69,7 @@ export declare class PHPWorker implements LimitedPHPApi {
69
69
  /** @inheritDoc @php-wasm/universal!/PHP.fileExists */
70
70
  fileExists(path: string): boolean;
71
71
  /** @inheritDoc @php-wasm/universal!/PHP.onMessage */
72
- onMessage(listener: MessageListener): void;
72
+ onMessage(listener: MessageListener): () => Promise<void>;
73
73
  /** @inheritDoc @php-wasm/universal!/PHP.defineConstant */
74
74
  defineConstant(key: string, value: string | boolean | number | null): void;
75
75
  /** @inheritDoc @php-wasm/universal!/PHP.addEventListener */
package/lib/php.d.ts CHANGED
@@ -91,7 +91,7 @@ export declare class PHP implements Disposable {
91
91
  *
92
92
  * @param listener Callback function to handle the message.
93
93
  */
94
- onMessage(listener: MessageListener): void;
94
+ onMessage(listener: MessageListener): () => Promise<void>;
95
95
  setSpawnHandler(handler: SpawnHandler | string): Promise<void>;
96
96
  /** @deprecated Use PHPRequestHandler instead. */
97
97
  get absoluteUrl(): string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@php-wasm/universal",
3
- "version": "1.0.15",
3
+ "version": "1.0.16",
4
4
  "description": "PHP.wasm – emscripten bindings for PHP",
5
5
  "repository": {
6
6
  "type": "git",
@@ -37,7 +37,7 @@
37
37
  "module": "./index.js",
38
38
  "types": "index.d.ts",
39
39
  "license": "GPL-2.0-or-later",
40
- "gitHead": "916516040522ab257109dd617bfcc493bb4f2eb1",
40
+ "gitHead": "bb91e62fb28611a9d447a182aff26dcfced2bb2e",
41
41
  "engines": {
42
42
  "node": ">=18.18.0",
43
43
  "npm": ">=8.11.0"
@@ -45,10 +45,10 @@
45
45
  "dependencies": {
46
46
  "comlink": "^4.4.1",
47
47
  "ini": "4.1.2",
48
- "@php-wasm/node-polyfills": "1.0.15",
49
- "@php-wasm/logger": "1.0.15",
50
- "@php-wasm/util": "1.0.15",
51
- "@php-wasm/stream-compression": "1.0.15",
52
- "@php-wasm/progress": "1.0.15"
48
+ "@php-wasm/node-polyfills": "1.0.16",
49
+ "@php-wasm/logger": "1.0.16",
50
+ "@php-wasm/util": "1.0.16",
51
+ "@php-wasm/stream-compression": "1.0.16",
52
+ "@php-wasm/progress": "1.0.16"
53
53
  }
54
54
  }