@php-wasm/universal 2.0.10 → 2.0.12

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 re=Object.create;var q=Object.defineProperty;var se=Object.getOwnPropertyDescriptor;var ne=Object.getOwnPropertyNames;var ie=Object.getPrototypeOf,oe=Object.prototype.hasOwnProperty;var z=t=>{throw TypeError(t)};var ae=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ne(e))!oe.call(t,n)&&n!==r&&q(t,n,{get:()=>e[n],enumerable:!(s=se(e,n))||s.enumerable});return t};var le=(t,e,r)=>(r=t!=null?re(ie(t)):{},ae(e||!t||!t.__esModule?q(r,"default",{value:t,enumerable:!0}):r,t));var N=(t,e,r)=>e.has(t)||z("Cannot "+r);var u=(t,e,r)=>(N(t,e,"read from private field"),r?r.call(t):e.get(t)),_=(t,e,r)=>e.has(t)?z("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),f=(t,e,r,s)=>(N(t,e,"write to private field"),s?s.call(t,r):e.set(t,r),r),m=(t,e,r)=>(N(t,e,"access private method"),r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("@php-wasm/node-polyfills");const logger=require("@php-wasm/logger"),util=require("@php-wasm/util"),ini=require("ini"),streamCompression=require("@php-wasm/stream-compression");var _documentCurrentScript=typeof document<"u"?document.currentScript:null;class ErrnoError extends Error{constructor(e,r,s){super(r,s),this.name="ErrnoError",this.errno=e}}const FileErrorCodes={0:"No error occurred. System call completed successfully.",1:"Argument list too long.",2:"Permission denied.",3:"Address in use.",4:"Address not available.",5:"Address family not supported.",6:"Resource unavailable, or operation would block.",7:"Connection already in progress.",8:"Bad file descriptor.",9:"Bad message.",10:"Device or resource busy.",11:"Operation canceled.",12:"No child processes.",13:"Connection aborted.",14:"Connection refused.",15:"Connection reset.",16:"Resource deadlock would occur.",17:"Destination address required.",18:"Mathematics argument out of domain of function.",19:"Reserved.",20:"File exists.",21:"Bad address.",22:"File too large.",23:"Host is unreachable.",24:"Identifier removed.",25:"Illegal byte sequence.",26:"Operation in progress.",27:"Interrupted function.",28:"Invalid argument.",29:"I/O error.",30:"Socket is connected.",31:"There is a directory under that path.",32:"Too many levels of symbolic links.",33:"File descriptor value too large.",34:"Too many links.",35:"Message too large.",36:"Reserved.",37:"Filename too long.",38:"Network is down.",39:"Connection aborted by network.",40:"Network unreachable.",41:"Too many files open in system.",42:"No buffer space available.",43:"No such device.",44:"There is no such file or directory OR the parent directory does not exist.",45:"Executable file format error.",46:"No locks available.",47:"Reserved.",48:"Not enough space.",49:"No message of the desired type.",50:"Protocol not available.",51:"No space left on device.",52:"Function not supported.",53:"The socket is not connected.",54:"Not a directory or a symbolic link to a directory.",55:"Directory not empty.",56:"State not recoverable.",57:"Not a socket.",58:"Not supported, or operation not supported on socket.",59:"Inappropriate I/O control operation.",60:"No such device or address.",61:"Value too large to be stored in data type.",62:"Previous owner died.",63:"Operation not permitted.",64:"Broken pipe.",65:"Protocol error.",66:"Protocol not supported.",67:"Protocol wrong type for socket.",68:"Result too large.",69:"Read-only file system.",70:"Invalid seek.",71:"No such process.",72:"Reserved.",73:"Connection timed out.",74:"Text file busy.",75:"Cross-device link.",76:"Extension: Capabilities insufficient."};function getEmscriptenFsError(t){const e=typeof t=="object"?t==null?void 0:t.errno:null;if(e in FileErrorCodes)return FileErrorCodes[e]}function rethrowFileSystemError(t=""){return function(r){return function(...s){try{return r.apply(this,s)}catch(n){const i=typeof n=="object"?n==null?void 0:n.errno:null;if(i in FileErrorCodes){const o=FileErrorCodes[i],a=typeof s[1]=="string"?s[1]:null,l=a!==null?t.replaceAll("{path}",a):t;throw new ErrnoError(i,`${l}: ${o}`,{cause:n})}throw n}}}}class FSHelpers{static readFileAsText(e,r){return new TextDecoder().decode(FSHelpers.readFileAsBuffer(e,r))}static readFileAsBuffer(e,r){return e.readFile(r)}static writeFile(e,r,s){e.writeFile(r,s)}static unlink(e,r){e.unlink(r)}static mv(e,r,s){try{const n=e.lookupPath(r).node.mount,i=FSHelpers.fileExists(e,s)?e.lookupPath(s).node.mount:e.lookupPath(util.dirname(s)).node.mount;n.mountpoint!==i.mountpoint?(FSHelpers.copyRecursive(e,r,s),FSHelpers.isDir(e,r)?FSHelpers.rmdir(e,r,{recursive:!0}):e.unlink(r)):e.rename(r,s)}catch(n){const i=getEmscriptenFsError(n);throw i?new Error(`Could not move ${r} to ${s}: ${i}`,{cause:n}):n}}static rmdir(e,r,s={recursive:!0}){const n=e.lookupPath(r,{follow:!1});if((n==null?void 0:n.node.mount.mountpoint)===r)throw new ErrnoError(10);s!=null&&s.recursive&&FSHelpers.listFiles(e,r).forEach(i=>{const o=`${r}/${i}`;FSHelpers.isDir(e,o)?FSHelpers.rmdir(e,o,s):FSHelpers.unlink(e,o)}),e.getPath(e.lookupPath(r).node)===e.cwd()&&e.chdir(util.joinPaths(e.cwd(),"..")),e.rmdir(r)}static listFiles(e,r,s={prependPath:!1}){if(!FSHelpers.fileExists(e,r))return[];try{const n=e.readdir(r).filter(i=>i!=="."&&i!=="..");if(s.prependPath){const i=r.replace(/\/$/,"");return n.map(o=>`${i}/${o}`)}return n}catch(n){return logger.logger.error(n,{path:r}),[]}}static isDir(e,r){return FSHelpers.fileExists(e,r)?e.isDir(e.lookupPath(r,{follow:!0}).node.mode):!1}static isFile(e,r){return FSHelpers.fileExists(e,r)?e.isFile(e.lookupPath(r,{follow:!0}).node.mode):!1}static symlink(e,r,s){return e.symlink(r,s)}static isSymlink(e,r){return FSHelpers.fileExists(e,r)?e.isLink(e.lookupPath(r).node.mode):!1}static readlink(e,r){return e.readlink(r)}static realpath(e,r){return e.lookupPath(r,{follow:!0}).path}static fileExists(e,r){try{return e.lookupPath(r),!0}catch{return!1}}static mkdir(e,r){e.mkdirTree(r)}static copyRecursive(e,r,s){const n=e.lookupPath(r).node;if(e.isDir(n.mode)){e.mkdirTree(s);const i=e.readdir(r).filter(o=>o!=="."&&o!=="..");for(const o of i)FSHelpers.copyRecursive(e,util.joinPaths(r,o),util.joinPaths(s,o))}else e.isLink(n.mode)?e.symlink(e.readlink(r),s):e.writeFile(s,e.readFile(r))}}FSHelpers.readFileAsText=rethrowFileSystemError('Could not read "{path}"')(FSHelpers.readFileAsText);FSHelpers.readFileAsBuffer=rethrowFileSystemError('Could not read "{path}"')(FSHelpers.readFileAsBuffer);FSHelpers.writeFile=rethrowFileSystemError('Could not write to "{path}"')(FSHelpers.writeFile);FSHelpers.unlink=rethrowFileSystemError('Could not unlink "{path}"')(FSHelpers.unlink);FSHelpers.rmdir=rethrowFileSystemError('Could not remove directory "{path}"')(FSHelpers.rmdir);FSHelpers.listFiles=rethrowFileSystemError('Could not list files in "{path}"')(FSHelpers.listFiles);FSHelpers.isDir=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.isDir);FSHelpers.isFile=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.isFile);FSHelpers.realpath=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.realpath);FSHelpers.fileExists=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.fileExists);FSHelpers.mkdir=rethrowFileSystemError('Could not create directory "{path}"')(FSHelpers.mkdir);FSHelpers.copyRecursive=rethrowFileSystemError('Could not copy files from "{path}"')(FSHelpers.copyRecursive);const _private=new WeakMap;class PHPWorker{constructor(e,r){this.absoluteUrl="",this.documentRoot="",_private.set(this,{monitor:r}),e&&this.__internal_setRequestHandler(e)}__internal_setRequestHandler(e){this.absoluteUrl=e.absoluteUrl,this.documentRoot=e.documentRoot,_private.set(this,{..._private.get(this),requestHandler:e})}__internal_getPHP(){return _private.get(this).php}__internal_getRequestHandler(){return _private.get(this).requestHandler}async setPrimaryPHP(e){_private.set(this,{..._private.get(this),php:e})}pathToInternalUrl(e){return _private.get(this).requestHandler.pathToInternalUrl(e)}internalUrlToPath(e){return _private.get(this).requestHandler.internalUrlToPath(e)}async onDownloadProgress(e){var r;return(r=_private.get(this).monitor)==null?void 0:r.addEventListener("progress",e)}async mv(e,r){return _private.get(this).php.mv(e,r)}async rmdir(e,r){return _private.get(this).php.rmdir(e,r)}async request(e){return await _private.get(this).requestHandler.request(e)}async run(e){const{php:r,reap:s}=await _private.get(this).requestHandler.processManager.acquirePHPInstance();try{return await r.run(e)}finally{s()}}chdir(e){return _private.get(this).php.chdir(e)}setSapiName(e){_private.get(this).php.setSapiName(e)}mkdir(e){return _private.get(this).php.mkdir(e)}mkdirTree(e){return _private.get(this).php.mkdirTree(e)}readFileAsText(e){return _private.get(this).php.readFileAsText(e)}readFileAsBuffer(e){return _private.get(this).php.readFileAsBuffer(e)}writeFile(e,r){return _private.get(this).php.writeFile(e,r)}unlink(e){return _private.get(this).php.unlink(e)}listFiles(e,r){return _private.get(this).php.listFiles(e,r)}isDir(e){return _private.get(this).php.isDir(e)}isFile(e){return _private.get(this).php.isFile(e)}fileExists(e){return _private.get(this).php.fileExists(e)}onMessage(e){return _private.get(this).php.onMessage(e)}defineConstant(e,r){_private.get(this).php.defineConstant(e,r)}addEventListener(e,r){_private.get(this).php.addEventListener(e,r)}removeEventListener(e,r){_private.get(this).php.removeEventListener(e,r)}async[Symbol.asyncDispose](){var e;await((e=_private.get(this).requestHandler)==null?void 0:e[Symbol.asyncDispose]())}}const responseTexts={500:"Internal Server Error",502:"Bad Gateway",404:"Not Found",403:"Forbidden",401:"Unauthorized",400:"Bad Request",301:"Moved Permanently",302:"Found",307:"Temporary Redirect",308:"Permanent Redirect",204:"No Content",201:"Created",200:"OK"};class StreamedPHPResponse{constructor(e,r,s,n){this.parsedHeaders=null,this.cachedStdoutText=null,this.cachedStderrText=null,this.headersStream=e,this.stdout=r,this.stderr=s,this.exitCode=n}async ok(){try{const e=await this.httpStatusCode;return e>=200&&e<400}catch{return!1}}get finished(){return Promise.allSettled([this.exitCode.finally(()=>{})]).then(()=>{})}get headers(){return this.getParsedHeaders().then(e=>e.headers)}get httpStatusCode(){return this.getParsedHeaders().then(e=>e.httpStatusCode).then(e=>e!==void 0?e:this.getParsedHeaders().then(r=>r.httpStatusCode,()=>200)).catch(()=>500)}get stdoutText(){return this.cachedStdoutText||(this.cachedStdoutText=streamToText(this.stdout)),this.cachedStdoutText}get stderrText(){return this.cachedStderrText||(this.cachedStderrText=streamToText(this.stderr)),this.cachedStderrText}async getParsedHeaders(){return this.parsedHeaders||(this.parsedHeaders=parseHeadersStream(this.headersStream)),await this.parsedHeaders}}async function parseHeadersStream(t){const e=await streamToText(t);let r;try{r=JSON.parse(e)}catch{return{headers:{},httpStatusCode:200}}const s={};for(const n of r.headers){if(!n.includes(": "))continue;const i=n.indexOf(": "),o=n.substring(0,i).toLowerCase(),a=n.substring(i+2);o in s||(s[o]=[]),s[o].push(a)}return{headers:s,httpStatusCode:r.status}}async function streamToText(t){const e=t.pipeThrough(new TextDecoderStream).getReader(),r=[];for(;;){const{done:s,value:n}=await e.read();if(s)return r.join("");n&&r.push(n)}}class PHPResponse{constructor(e,r,s,n="",i=0){this.httpStatusCode=e,this.headers=r,this.bytes=s,this.exitCode=i,this.errors=n}static forHttpCode(e,r=""){return new PHPResponse(e,{},new TextEncoder().encode(r||responseTexts[e]||""))}static fromRawData(e){return new PHPResponse(e.httpStatusCode,e.headers,e.bytes,e.errors,e.exitCode)}static async fromStreamedResponse(e){return await e.finished,new PHPResponse(await e.httpStatusCode,await e.headers,new TextEncoder().encode(await e.stdoutText),await e.stderrText,await e.exitCode)}ok(){return this.httpStatusCode>=200&&this.httpStatusCode<400}toRawData(){return{headers:this.headers,bytes:this.bytes,errors:this.errors,exitCode:this.exitCode,httpStatusCode:this.httpStatusCode}}get json(){return JSON.parse(this.text)}get text(){return new TextDecoder().decode(this.bytes)}}const RuntimeId=Symbol("RuntimeId"),loadedRuntimes=new Map;let lastRuntimeId=0;async function loadPHPRuntime(t,...e){const r=Object.assign({},...e),[s,n,i]=makePromise(),o=t.init(currentJsRuntime,{onAbort(l){i(l),logger.logger.error(l)},ENV:{},locateFile:l=>l,...r,noInitialRun:!0,onRuntimeInitialized(){r.onRuntimeInitialized&&r.onRuntimeInitialized(o),n()}});await s;const a=++lastRuntimeId;return o.FS,o.id=a,o.originalExit=o._exit,o._exit=function(l){return o.outboundNetworkProxyServer&&(o.outboundNetworkProxyServer.close(),o.outboundNetworkProxyServer.closeAllConnections()),loadedRuntimes.delete(a),o.originalExit(l)},o[RuntimeId]=a,loadedRuntimes.set(a,o),a}function getLoadedRuntime(t){return loadedRuntimes.get(t)}const currentJsRuntime=function(){var t;return typeof process<"u"&&((t=process.release)==null?void 0:t.name)==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"}(),makePromise=()=>{const t=[],e=new Promise((r,s)=>{t.push(r,s)});return t.unshift(e),t};var _a;const kError=Symbol("error"),kMessage=Symbol("message");class ErrorEvent2 extends(_a=Event,_a){constructor(e,r={}){super(e),this[kError]=r.error===void 0?null:r.error,this[kMessage]=r.message===void 0?"":r.message}get error(){return this[kError]}get message(){return this[kMessage]}}Object.defineProperty(ErrorEvent2.prototype,"error",{enumerable:!0});Object.defineProperty(ErrorEvent2.prototype,"message",{enumerable:!0});const ErrorEvent=typeof globalThis.ErrorEvent=="function"?globalThis.ErrorEvent:ErrorEvent2;function isExitCode(t){return t instanceof Error?(t==null?void 0:t.name)==="ExitStatus"&&"status"in t:!1}class UnhandledRejectionsTarget extends EventTarget{constructor(){super(...arguments),this.listenersCount=0}addEventListener(e,r,s){++this.listenersCount,super.addEventListener(e,r,s)}removeEventListener(e,r,s){--this.listenersCount,super.removeEventListener(e,r,s)}hasListeners(){return this.listenersCount>0}}function improveWASMErrorReporting(t){const e=new UnhandledRejectionsTarget;for(const r in t.wasmExports)if(typeof t.wasmExports[r]=="function"){const s=t.wasmExports[r];t.wasmExports[r]=function(...n){var i;try{return s(...n)}catch(o){if(!(o instanceof Error))throw o;t.lastAsyncifyStackSource&&(o.cause=t.lastAsyncifyStackSource);const a=clarifyErrorMessage(o,(i=t.lastAsyncifyStackSource)==null?void 0:i.stack);if(e.hasListeners()){o.message=a;const l=new ErrorEvent("error",{error:o});throw e.dispatchEvent(l),o}throw(!isExitCode(o)||o.status!==0)&&showCriticalErrorBox(a),o}}}return e}let functionsMaybeMissingFromAsyncify=[];function getFunctionsMaybeMissingFromAsyncify(){return functionsMaybeMissingFromAsyncify}function clarifyErrorMessage(t,e){if(t.message==="unreachable"){let r=UNREACHABLE_ERROR;e||(r+=`
1
+ "use strict";var re=Object.create;var q=Object.defineProperty;var se=Object.getOwnPropertyDescriptor;var ne=Object.getOwnPropertyNames;var ie=Object.getPrototypeOf,oe=Object.prototype.hasOwnProperty;var z=t=>{throw TypeError(t)};var ae=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ne(e))!oe.call(t,n)&&n!==r&&q(t,n,{get:()=>e[n],enumerable:!(s=se(e,n))||s.enumerable});return t};var le=(t,e,r)=>(r=t!=null?re(ie(t)):{},ae(e||!t||!t.__esModule?q(r,"default",{value:t,enumerable:!0}):r,t));var N=(t,e,r)=>e.has(t)||z("Cannot "+r);var u=(t,e,r)=>(N(t,e,"read from private field"),r?r.call(t):e.get(t)),_=(t,e,r)=>e.has(t)?z("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),f=(t,e,r,s)=>(N(t,e,"write to private field"),s?s.call(t,r):e.set(t,r),r),m=(t,e,r)=>(N(t,e,"access private method"),r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("@php-wasm/node-polyfills");const logger=require("@php-wasm/logger"),util=require("@php-wasm/util"),ini=require("ini"),streamCompression=require("@php-wasm/stream-compression");var _documentCurrentScript=typeof document<"u"?document.currentScript:null;class ErrnoError extends Error{constructor(e,r,s){super(r,s),this.name="ErrnoError",this.errno=e}}const FileErrorCodes={0:"No error occurred. System call completed successfully.",1:"Argument list too long.",2:"Permission denied.",3:"Address in use.",4:"Address not available.",5:"Address family not supported.",6:"Resource unavailable, or operation would block.",7:"Connection already in progress.",8:"Bad file descriptor.",9:"Bad message.",10:"Device or resource busy.",11:"Operation canceled.",12:"No child processes.",13:"Connection aborted.",14:"Connection refused.",15:"Connection reset.",16:"Resource deadlock would occur.",17:"Destination address required.",18:"Mathematics argument out of domain of function.",19:"Reserved.",20:"File exists.",21:"Bad address.",22:"File too large.",23:"Host is unreachable.",24:"Identifier removed.",25:"Illegal byte sequence.",26:"Operation in progress.",27:"Interrupted function.",28:"Invalid argument.",29:"I/O error.",30:"Socket is connected.",31:"There is a directory under that path.",32:"Too many levels of symbolic links.",33:"File descriptor value too large.",34:"Too many links.",35:"Message too large.",36:"Reserved.",37:"Filename too long.",38:"Network is down.",39:"Connection aborted by network.",40:"Network unreachable.",41:"Too many files open in system.",42:"No buffer space available.",43:"No such device.",44:"There is no such file or directory OR the parent directory does not exist.",45:"Executable file format error.",46:"No locks available.",47:"Reserved.",48:"Not enough space.",49:"No message of the desired type.",50:"Protocol not available.",51:"No space left on device.",52:"Function not supported.",53:"The socket is not connected.",54:"Not a directory or a symbolic link to a directory.",55:"Directory not empty.",56:"State not recoverable.",57:"Not a socket.",58:"Not supported, or operation not supported on socket.",59:"Inappropriate I/O control operation.",60:"No such device or address.",61:"Value too large to be stored in data type.",62:"Previous owner died.",63:"Operation not permitted.",64:"Broken pipe.",65:"Protocol error.",66:"Protocol not supported.",67:"Protocol wrong type for socket.",68:"Result too large.",69:"Read-only file system.",70:"Invalid seek.",71:"No such process.",72:"Reserved.",73:"Connection timed out.",74:"Text file busy.",75:"Cross-device link.",76:"Extension: Capabilities insufficient."};function getEmscriptenFsError(t){const e=typeof t=="object"?t==null?void 0:t.errno:null;if(e in FileErrorCodes)return FileErrorCodes[e]}function rethrowFileSystemError(t=""){return function(r){return function(...s){try{return r.apply(this,s)}catch(n){const i=typeof n=="object"?n==null?void 0:n.errno:null;if(i in FileErrorCodes){const o=FileErrorCodes[i],a=typeof s[1]=="string"?s[1]:null,l=a!==null?t.replaceAll("{path}",a):t;throw new ErrnoError(i,`${l}: ${o}`,{cause:n})}throw n}}}}class FSHelpers{static readFileAsText(e,r){return new TextDecoder().decode(FSHelpers.readFileAsBuffer(e,r))}static readFileAsBuffer(e,r){return e.readFile(r)}static writeFile(e,r,s){e.writeFile(r,s)}static unlink(e,r){e.unlink(r)}static mv(e,r,s){try{const n=e.lookupPath(r).node.mount,i=FSHelpers.fileExists(e,s)?e.lookupPath(s).node.mount:e.lookupPath(util.dirname(s)).node.mount;n.mountpoint!==i.mountpoint?(FSHelpers.copyRecursive(e,r,s),FSHelpers.isDir(e,r)?FSHelpers.rmdir(e,r,{recursive:!0}):e.unlink(r)):e.rename(r,s)}catch(n){const i=getEmscriptenFsError(n);throw i?new Error(`Could not move ${r} to ${s}: ${i}`,{cause:n}):n}}static rmdir(e,r,s={recursive:!0}){const n=e.lookupPath(r,{follow:!1});if((n==null?void 0:n.node.mount.mountpoint)===r)throw new ErrnoError(10);s!=null&&s.recursive&&FSHelpers.listFiles(e,r).forEach(i=>{const o=`${r}/${i}`;FSHelpers.isDir(e,o)?FSHelpers.rmdir(e,o,s):FSHelpers.unlink(e,o)}),e.getPath(e.lookupPath(r).node)===e.cwd()&&e.chdir(util.joinPaths(e.cwd(),"..")),e.rmdir(r)}static listFiles(e,r,s={prependPath:!1}){if(!FSHelpers.fileExists(e,r))return[];try{const n=e.readdir(r).filter(i=>i!=="."&&i!=="..");if(s.prependPath){const i=r.replace(/\/$/,"");return n.map(o=>`${i}/${o}`)}return n}catch(n){return logger.logger.error(n,{path:r}),[]}}static isDir(e,r){return FSHelpers.fileExists(e,r)?e.isDir(e.lookupPath(r,{follow:!0}).node.mode):!1}static isFile(e,r){return FSHelpers.fileExists(e,r)?e.isFile(e.lookupPath(r,{follow:!0}).node.mode):!1}static symlink(e,r,s){return e.symlink(r,s)}static isSymlink(e,r){return FSHelpers.fileExists(e,r)?e.isLink(e.lookupPath(r).node.mode):!1}static readlink(e,r){return e.readlink(r)}static realpath(e,r){return e.lookupPath(r,{follow:!0}).path}static fileExists(e,r){try{return e.lookupPath(r),!0}catch{return!1}}static mkdir(e,r){e.mkdirTree(r)}static copyRecursive(e,r,s){const n=e.lookupPath(r).node;if(e.isDir(n.mode)){e.mkdirTree(s);const i=e.readdir(r).filter(o=>o!=="."&&o!=="..");for(const o of i)FSHelpers.copyRecursive(e,util.joinPaths(r,o),util.joinPaths(s,o))}else e.isLink(n.mode)?e.symlink(e.readlink(r),s):e.writeFile(s,e.readFile(r))}}FSHelpers.readFileAsText=rethrowFileSystemError('Could not read "{path}"')(FSHelpers.readFileAsText);FSHelpers.readFileAsBuffer=rethrowFileSystemError('Could not read "{path}"')(FSHelpers.readFileAsBuffer);FSHelpers.writeFile=rethrowFileSystemError('Could not write to "{path}"')(FSHelpers.writeFile);FSHelpers.unlink=rethrowFileSystemError('Could not unlink "{path}"')(FSHelpers.unlink);FSHelpers.rmdir=rethrowFileSystemError('Could not remove directory "{path}"')(FSHelpers.rmdir);FSHelpers.listFiles=rethrowFileSystemError('Could not list files in "{path}"')(FSHelpers.listFiles);FSHelpers.isDir=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.isDir);FSHelpers.isFile=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.isFile);FSHelpers.realpath=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.realpath);FSHelpers.fileExists=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.fileExists);FSHelpers.mkdir=rethrowFileSystemError('Could not create directory "{path}"')(FSHelpers.mkdir);FSHelpers.copyRecursive=rethrowFileSystemError('Could not copy files from "{path}"')(FSHelpers.copyRecursive);const _private=new WeakMap;class PHPWorker{constructor(e,r){this.absoluteUrl="",this.documentRoot="",_private.set(this,{monitor:r}),e&&this.__internal_setRequestHandler(e)}__internal_setRequestHandler(e){this.absoluteUrl=e.absoluteUrl,this.documentRoot=e.documentRoot,_private.set(this,{..._private.get(this),requestHandler:e})}__internal_getPHP(){return _private.get(this).php}__internal_getRequestHandler(){return _private.get(this).requestHandler}async setPrimaryPHP(e){_private.set(this,{..._private.get(this),php:e})}pathToInternalUrl(e){return _private.get(this).requestHandler.pathToInternalUrl(e)}internalUrlToPath(e){return _private.get(this).requestHandler.internalUrlToPath(e)}async onDownloadProgress(e){var r;return(r=_private.get(this).monitor)==null?void 0:r.addEventListener("progress",e)}async mv(e,r){return _private.get(this).php.mv(e,r)}async rmdir(e,r){return _private.get(this).php.rmdir(e,r)}async request(e){return await _private.get(this).requestHandler.request(e)}async run(e){const{php:r,reap:s}=await _private.get(this).requestHandler.processManager.acquirePHPInstance();try{return await r.run(e)}finally{s()}}chdir(e){return _private.get(this).php.chdir(e)}setSapiName(e){_private.get(this).php.setSapiName(e)}mkdir(e){return _private.get(this).php.mkdir(e)}mkdirTree(e){return _private.get(this).php.mkdirTree(e)}readFileAsText(e){return _private.get(this).php.readFileAsText(e)}readFileAsBuffer(e){return _private.get(this).php.readFileAsBuffer(e)}writeFile(e,r){return _private.get(this).php.writeFile(e,r)}unlink(e){return _private.get(this).php.unlink(e)}listFiles(e,r){return _private.get(this).php.listFiles(e,r)}isDir(e){return _private.get(this).php.isDir(e)}isFile(e){return _private.get(this).php.isFile(e)}fileExists(e){return _private.get(this).php.fileExists(e)}onMessage(e){return _private.get(this).php.onMessage(e)}defineConstant(e,r){_private.get(this).php.defineConstant(e,r)}addEventListener(e,r){_private.get(this).php.addEventListener(e,r)}removeEventListener(e,r){_private.get(this).php.removeEventListener(e,r)}async[Symbol.asyncDispose](){var e;await((e=_private.get(this).requestHandler)==null?void 0:e[Symbol.asyncDispose]())}}const responseTexts={500:"Internal Server Error",502:"Bad Gateway",404:"Not Found",403:"Forbidden",401:"Unauthorized",400:"Bad Request",301:"Moved Permanently",302:"Found",307:"Temporary Redirect",308:"Permanent Redirect",204:"No Content",201:"Created",200:"OK"};class StreamedPHPResponse{constructor(e,r,s,n){this.parsedHeaders=null,this.cachedStdoutBytes=null,this.cachedStderrText=null,this.headersStream=e,this.stdout=r,this.stderr=s,this.exitCode=n}async ok(){try{const e=await this.httpStatusCode;return e>=200&&e<400}catch{return!1}}get finished(){return Promise.allSettled([this.exitCode.finally(()=>{})]).then(()=>{})}get headers(){return this.getParsedHeaders().then(e=>e.headers)}get httpStatusCode(){return this.getParsedHeaders().then(e=>e.httpStatusCode).then(e=>e!==void 0?e:this.getParsedHeaders().then(r=>r.httpStatusCode,()=>200)).catch(()=>500)}get stdoutText(){return this.stdoutBytes.then(e=>new TextDecoder().decode(e))}get stdoutBytes(){return this.cachedStdoutBytes||(this.cachedStdoutBytes=streamToBytes(this.stdout)),this.cachedStdoutBytes}get stderrText(){return this.cachedStderrText||(this.cachedStderrText=streamToText(this.stderr)),this.cachedStderrText}async getParsedHeaders(){return this.parsedHeaders||(this.parsedHeaders=parseHeadersStream(this.headersStream)),await this.parsedHeaders}}async function parseHeadersStream(t){const e=await streamToText(t);let r;try{r=JSON.parse(e)}catch{return{headers:{},httpStatusCode:200}}const s={};for(const n of r.headers){if(!n.includes(": "))continue;const i=n.indexOf(": "),o=n.substring(0,i).toLowerCase(),a=n.substring(i+2);o in s||(s[o]=[]),s[o].push(a)}return{headers:s,httpStatusCode:r.status}}async function streamToText(t){const e=t.pipeThrough(new TextDecoderStream).getReader(),r=[];for(;;){const{done:s,value:n}=await e.read();if(s)return r.join("");n&&r.push(n)}}async function streamToBytes(t){const e=t.getReader(),r=[];for(;;){const{done:s,value:n}=await e.read();if(s){const i=r.reduce((l,c)=>l+c.byteLength,0),o=new Uint8Array(i);let a=0;for(const l of r)o.set(l,a),a+=l.byteLength;return o}n&&r.push(n)}}class PHPResponse{constructor(e,r,s,n="",i=0){this.httpStatusCode=e,this.headers=r,this.bytes=s,this.exitCode=i,this.errors=n}static forHttpCode(e,r=""){return new PHPResponse(e,{},new TextEncoder().encode(r||responseTexts[e]||""))}static fromRawData(e){return new PHPResponse(e.httpStatusCode,e.headers,e.bytes,e.errors,e.exitCode)}static async fromStreamedResponse(e){return await e.finished,new PHPResponse(await e.httpStatusCode,await e.headers,await e.stdoutBytes,await e.stderrText,await e.exitCode)}ok(){return this.httpStatusCode>=200&&this.httpStatusCode<400}toRawData(){return{headers:this.headers,bytes:this.bytes,errors:this.errors,exitCode:this.exitCode,httpStatusCode:this.httpStatusCode}}get json(){return JSON.parse(this.text)}get text(){return new TextDecoder().decode(this.bytes)}}const RuntimeId=Symbol("RuntimeId"),loadedRuntimes=new Map;let lastRuntimeId=0;async function loadPHPRuntime(t,...e){const r=Object.assign({},...e),[s,n,i]=makePromise(),o=t.init(currentJsRuntime,{onAbort(l){i(l),logger.logger.error(l)},ENV:{},locateFile:l=>l,...r,noInitialRun:!0,onRuntimeInitialized(){r.onRuntimeInitialized&&r.onRuntimeInitialized(o),n()}});await s;const a=++lastRuntimeId;return o.FS,o.id=a,o.originalExit=o._exit,o._exit=function(l){return o.outboundNetworkProxyServer&&(o.outboundNetworkProxyServer.close(),o.outboundNetworkProxyServer.closeAllConnections()),loadedRuntimes.delete(a),o.originalExit(l)},o[RuntimeId]=a,loadedRuntimes.set(a,o),a}function getLoadedRuntime(t){return loadedRuntimes.get(t)}const currentJsRuntime=function(){var t;return typeof process<"u"&&((t=process.release)==null?void 0:t.name)==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"}(),makePromise=()=>{const t=[],e=new Promise((r,s)=>{t.push(r,s)});return t.unshift(e),t};var _a;const kError=Symbol("error"),kMessage=Symbol("message");class ErrorEvent2 extends(_a=Event,_a){constructor(e,r={}){super(e),this[kError]=r.error===void 0?null:r.error,this[kMessage]=r.message===void 0?"":r.message}get error(){return this[kError]}get message(){return this[kMessage]}}Object.defineProperty(ErrorEvent2.prototype,"error",{enumerable:!0});Object.defineProperty(ErrorEvent2.prototype,"message",{enumerable:!0});const ErrorEvent=typeof globalThis.ErrorEvent=="function"?globalThis.ErrorEvent:ErrorEvent2;function isExitCode(t){return t instanceof Error?(t==null?void 0:t.name)==="ExitStatus"&&"status"in t:!1}class UnhandledRejectionsTarget extends EventTarget{constructor(){super(...arguments),this.listenersCount=0}addEventListener(e,r,s){++this.listenersCount,super.addEventListener(e,r,s)}removeEventListener(e,r,s){--this.listenersCount,super.removeEventListener(e,r,s)}hasListeners(){return this.listenersCount>0}}function improveWASMErrorReporting(t){const e=new UnhandledRejectionsTarget;for(const r in t.wasmExports)if(typeof t.wasmExports[r]=="function"){const s=t.wasmExports[r];t.wasmExports[r]=function(...n){var i;try{return s(...n)}catch(o){if(!(o instanceof Error))throw o;t.lastAsyncifyStackSource&&(o.cause=t.lastAsyncifyStackSource);const a=clarifyErrorMessage(o,(i=t.lastAsyncifyStackSource)==null?void 0:i.stack);if(e.hasListeners()){o.message=a;const l=new ErrorEvent("error",{error:o});throw e.dispatchEvent(l),o}throw(!isExitCode(o)||o.status!==0)&&showCriticalErrorBox(a),o}}}return e}let functionsMaybeMissingFromAsyncify=[];function getFunctionsMaybeMissingFromAsyncify(){return functionsMaybeMissingFromAsyncify}function clarifyErrorMessage(t,e){if(t.message==="unreachable"){let r=UNREACHABLE_ERROR;e||(r+=`
2
2
 
3
3
  This stack trace is lacking. For a better one initialize
4
4
  the PHP runtime with debug: true, e.g. loadNodeRuntime('8.1', { emscriptenOptions: { debug: true } }).
@@ -33,7 +33,7 @@ CLI option:
33
33
  ${eol}
34
34
  ${bold} WASM ERROR${reset}${redBg}`);for(const e of t.split(`
35
35
  `))logger.logger.log(`${eol} ${e} `);logger.logger.log(`${reset}`)}}function extractPHPFunctionsFromStack(t){try{const e=t.split(`
36
- `).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",OPCACHE_FILE_FOLDER="/internal/shared/opcache";var k,x,E,g,S,T,h,W,$,B,V,G,J,Y,K,X,L,Q,O,U;class PHP{constructor(t){_(this,h);_(this,k);_(this,x);_(this,E);_(this,g);_(this,S);_(this,T);f(this,x,!1),f(this,E,null),f(this,g,new Map),f(this,S,[]),f(this,T,{}),this.cliCalled=!1,this.runStreamCalled=!1,this.semaphore=new util.Semaphore({concurrency:1}),t!==void 0&&this.initializeRuntime(t)}addEventListener(t,e){u(this,g).has(t)||u(this,g).set(t,new Set),u(this,g).get(t).add(e)}removeEventListener(t,e){var r;(r=u(this,g).get(t))==null||r.delete(e)}dispatchEvent(t){const e=u(this,g).get(t.type);if(e)for(const r of e)r(t)}onMessage(t){return u(this,S).push(t),async()=>{f(this,S,u(this,S).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.");if(this[__private__dont__use]=e,this[__private__dont__use].ccall("wasm_set_phpini_path",null,["string"],[PHP_INI_PATH]),!this.fileExists(PHP_INI_PATH)){const r=["opcache.enable = 1","opcache.enable_cli = 1","opcache.jit = 0","opcache.interned_strings_buffer = 8","opcache.max_accelerated_files = 1000","opcache.memory_consumption = 64","opcache.max_wasted_percentage = 5","opcache.file_cache = "+OPCACHE_FILE_FOLDER,"opcache.file_cache_only = 1","opcache.file_cache_consistency_checks = 1"];this.fileExists(OPCACHE_FILE_FOLDER)||this.mkdir(OPCACHE_FILE_FOLDER),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",...r].join(`
36
+ `).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",OPCACHE_FILE_FOLDER="/internal/shared/opcache";var k,x,E,g,S,T,h,B,W,$,V,G,J,Y,K,X,L,Q,U,O;class PHP{constructor(t){_(this,h);_(this,k);_(this,x);_(this,E);_(this,g);_(this,S);_(this,T);f(this,x,!1),f(this,E,null),f(this,g,new Map),f(this,S,[]),f(this,T,{}),this.cliCalled=!1,this.runStreamCalled=!1,this.semaphore=new util.Semaphore({concurrency:1}),t!==void 0&&this.initializeRuntime(t)}addEventListener(t,e){u(this,g).has(t)||u(this,g).set(t,new Set),u(this,g).get(t).add(e)}removeEventListener(t,e){var r;(r=u(this,g).get(t))==null||r.delete(e)}dispatchEvent(t){const e=u(this,g).get(t.type);if(e)for(const r of e)r(t)}onMessage(t){return u(this,S).push(t),async()=>{f(this,S,u(this,S).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.");if(this[__private__dont__use]=e,this[__private__dont__use].ccall("wasm_set_phpini_path",null,["string"],[PHP_INI_PATH]),!this.fileExists(PHP_INI_PATH)){const r=["opcache.enable = 1","opcache.enable_cli = 1","opcache.jit = 0","opcache.interned_strings_buffer = 8","opcache.max_accelerated_files = 1000","opcache.memory_consumption = 64","opcache.max_wasted_percentage = 5","opcache.file_cache = "+OPCACHE_FILE_FOLDER,"opcache.file_cache_only = 1","opcache.file_cache_consistency_checks = 1"];this.fileExists(OPCACHE_FILE_FOLDER)||this.mkdir(OPCACHE_FILE_FOLDER),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",...r].join(`
37
37
  `))}this.fileExists(AUTO_PREPEND_SCRIPT)||this.writeFile(AUTO_PREPEND_SCRIPT,`<?php
38
38
  // Define constants set via defineConstant() calls
39
39
  if(file_exists('/internal/shared/consts.json')) {
@@ -54,7 +54,7 @@ ${bold} WASM ERROR${reset}${redBg}`);for(const e of t.split(`
54
54
  ${r.text}
55
55
 
56
56
  === Stderr ===
57
- ${r.errors}`,r,"request");return r}async runStream(t){if(this.cliCalled)throw new Error("php.runStream() can only be called if php.cli() was not called before. The two methods set a conflicting C-level global state.");this.runStreamCalled=!0;const e=await this.semaphore.acquire();let r;const s=m(this,h,U).call(this,async()=>{if(u(this,x)||(await m(this,h,$).call(this),f(this,x,!0)),t.scriptPath&&!this.fileExists(t.scriptPath))throw new Error(`The script path "${t.scriptPath}" does not exist.`);m(this,h,B).call(this,t.relativeUri||""),m(this,h,Y).call(this,t.method||"GET");const i=normalizeHeaders(t.headers||{}),o=i.host||"example.com:443",a=m(this,h,J).call(this,o,t.protocol||"http");if(m(this,h,V).call(this,o),m(this,h,G).call(this,a),m(this,h,K).call(this,i),t.body&&(r=m(this,h,X).call(this,t.body)),typeof t.code=="string")this.writeFile("/internal/eval.php",t.code),m(this,h,L).call(this,"/internal/eval.php");else if(typeof t.scriptPath=="string")m(this,h,L).call(this,t.scriptPath||"");else throw new TypeError("The request object must have either a `code` or a `scriptPath` property.");const l=m(this,h,W).call(this,t.$_SERVER,i,a);for(const p in l)m(this,h,Q).call(this,p,l[p]);const c=t.env||{};for(const p in c)m(this,h,O).call(this,p,c[p]);return await this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0})}),n=()=>{if(r)try{this[__private__dont__use].free(r)}catch(i){logger.logger.error(i)}e(),this.dispatchEvent({type:"request.end"})};return s.then(i=>(i.finished.finally(n),i),i=>{throw n(),i})}defineConstant(t,e){let r={};try{r=JSON.parse(this.fileExists("/internal/shared/consts.json")&&this.readFileAsText("/internal/shared/consts.json")||"{}")}catch{}this.writeFile("/internal/shared/consts.json",JSON.stringify({...r,[t]:e}))}mkdir(t){return FSHelpers.mkdir(this[__private__dont__use].FS,t)}mkdirTree(t){return FSHelpers.mkdir(this[__private__dont__use].FS,t)}readFileAsText(t){return FSHelpers.readFileAsText(this[__private__dont__use].FS,t)}readFileAsBuffer(t){return FSHelpers.readFileAsBuffer(this[__private__dont__use].FS,t)}writeFile(t,e){return FSHelpers.writeFile(this[__private__dont__use].FS,t,e)}unlink(t){return FSHelpers.unlink(this[__private__dont__use].FS,t)}mv(t,e){return FSHelpers.mv(this[__private__dont__use].FS,t,e)}rmdir(t,e={recursive:!0}){return FSHelpers.rmdir(this[__private__dont__use].FS,t,e)}listFiles(t,e={prependPath:!1}){return FSHelpers.listFiles(this[__private__dont__use].FS,t,e)}isDir(t){return FSHelpers.isDir(this[__private__dont__use].FS,t)}isFile(t){return FSHelpers.isFile(this[__private__dont__use].FS,t)}symlink(t,e){return FSHelpers.symlink(this[__private__dont__use].FS,t,e)}isSymlink(t){return FSHelpers.isSymlink(this[__private__dont__use].FS,t)}readlink(t){return FSHelpers.readlink(this[__private__dont__use].FS,t)}realpath(t){return FSHelpers.realpath(this[__private__dont__use].FS,t)}fileExists(t){return FSHelpers.fileExists(this[__private__dont__use].FS,t)}async hotSwapPHPRuntime(t,e){const r=this[__private__dont__use].FS,s=[];for(const[n,i]of Object.entries(u(this,T)))s.push({mountHandler:i.mountHandler,vfsPath:n}),await i.unmount();try{this.exit()}catch{}this.initializeRuntime(t),u(this,k)&&this.setSapiName(u(this,k)),copyFS(r,this[__private__dont__use].FS,"/internal"),e&&copyFS(r,this[__private__dont__use].FS,e);for(const{mountHandler:n,vfsPath:i}of s)this.mkdir(i),await this.mount(i,n)}async mount(t,e){const r=await e(this,this[__private__dont__use].FS,t),s={mountHandler:e,unmount:async()=>{await r(),delete u(this,T)[t]}};return u(this,T)[t]=s,()=>{s.unmount()}}async cli(t,e={}){if(this.cliCalled)throw new Error("php.cli() can only be called once. The method sets a C-level global state that does not allow repeated calls.");if(this.runStreamCalled)throw new Error("php.cli() can only be called if php.runStream() was not called before. The two methods set a conflicting C-level global state.");this.cliCalled=!0;const r=await this.semaphore.acquire(),s=e.env||{};for(const[n,i]of Object.entries(s))m(this,h,O).call(this,n,i);t=[t[0],"-c",PHP_INI_PATH,...t.slice(1)];for(const n of t)this[__private__dont__use].ccall("wasm_add_cli_arg",null,[STRING],[n]);return await m(this,h,U).call(this,()=>this[__private__dont__use].ccall("run_cli",null,[],[],{async:!0})).then(n=>(n.exitCode.finally(r),n))}setSkipShebang(t){this[__private__dont__use].ccall("wasm_set_skip_shebang",null,[NUMBER],[t?1:0])}exit(t=0){this.dispatchEvent({type:"runtime.beforedestroy"});try{this[__private__dont__use]._exit(t)}catch{}f(this,x,!1),f(this,E,null),this[__private__dont__use]&&(delete this[__private__dont__use].onMessage,delete this[__private__dont__use])}[Symbol.dispose](){u(this,x)&&this.exit(0)}}k=new WeakMap,x=new WeakMap,E=new WeakMap,g=new WeakMap,S=new WeakMap,T=new WeakMap,h=new WeakSet,W=function(t,e,r){const s={...t||{}};s.HTTPS=s.HTTPS||r===443?"on":"off";for(const n in e){let i="HTTP_";["content-type","content-length"].includes(n.toLowerCase())&&(i=""),s[`${i}${n.toUpperCase().replace(/-/g,"_")}`]=e[n]}return s},$=function(){return this[__private__dont__use].ccall("php_wasm_init",null,[],[],{isAsync:!0})},B=function(t){this[__private__dont__use].ccall("wasm_set_request_uri",null,[STRING],[t]);let e="";t.includes("?")&&(e=t.substring(t.indexOf("?")+1)),this[__private__dont__use].ccall("wasm_set_query_string",null,[STRING],[e])},V=function(t){this[__private__dont__use].ccall("wasm_set_request_host",null,[STRING],[t])},G=function(t){this[__private__dont__use].ccall("wasm_set_request_port",null,[NUMBER],[t])},J=function(t,e){let r;try{r=parseInt(new URL(t).port,10)}catch{}return(!r||isNaN(r)||r===80)&&(r=e==="https"?443:80),r},Y=function(t){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[t])},K=function(t){t.cookie&&this[__private__dont__use].ccall("wasm_set_cookies",null,[STRING],[t.cookie]),t["content-type"]&&this[__private__dont__use].ccall("wasm_set_content_type",null,[STRING],[t["content-type"]]),t["content-length"]&&this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[parseInt(t["content-length"],10)])},X=function(t){let e,r;typeof t=="string"?(logger.logger.warn("Passing a string as the request body is deprecated. Please use a Uint8Array instead. See https://github.com/WordPress/wordpress-playground/issues/997 for more details"),r=this[__private__dont__use].lengthBytesUTF8(t),e=r+1):(r=t.byteLength,e=t.byteLength);const s=this[__private__dont__use].malloc(e);if(!s)throw new Error("Could not allocate memory for the request body.");return typeof t=="string"?this[__private__dont__use].stringToUTF8(t,s,e+1):this[__private__dont__use].HEAPU8.set(t,s),this[__private__dont__use].ccall("wasm_set_request_body",null,[NUMBER],[s]),this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[r]),s},L=function(t){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[t])},Q=function(t,e){this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[t,e])},O=function(t,e){this[__private__dont__use].ccall("wasm_add_ENV_entry",null,[STRING,STRING],[t,e])},U=async function(t){const e=this[__private__dont__use],r=await createInvertedReadableStream();e.onHeaders=d=>{a||s||r.controller.enqueue(d.slice())};let s=!1;const n=()=>{s||(s=!0,r.controller.close())},i=await createInvertedReadableStream();e.onStdout=d=>{n(),!a&&i.controller.enqueue(d.slice())};const o=await createInvertedReadableStream();e.onStderr=d=>{a||o.controller.enqueue(d.slice())};let a=!1,l;const p=(async()=>{var d;try{return await Promise.race([t(),new Promise((w,b)=>{var j;l=D=>{isExitCode(D.error)||b(D.error)},(j=u(this,E))==null||j.addEventListener("error",l,{once:!0})})])}catch(y){if(isExitCode(y))return y.status;i.controller.error(y),o.controller.error(y),r.controller.error(y),a=!0;for(const w in this)typeof this[w]=="function"&&(this[w]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});throw this.functionsMaybeMissingFromAsyncify=getFunctionsMaybeMissingFromAsyncify(),y}finally{a||(i.controller.close(),o.controller.close(),n(),a=!0),(d=u(this,E))==null||d.removeEventListener("error",l)}})().then(d=>(d!==0&&this.dispatchEvent({type:"request.error",error:new Error(`PHP.run() failed with exit code ${d}.`),source:"php-wasm"}),d),d=>{throw this.dispatchEvent({type:"request.error",error:d,source:d.source??"php-wasm"}),d});return new StreamedPHPResponse(r.stream,i.stream,o.stream,p)};function normalizeHeaders(t){const e={};for(const r in t)e[r.toLowerCase()]=t[r];return e}function copyFS(t,e,r){let s;try{s=t.lookupPath(r)}catch{return}if(!("contents"in s.node))return;if(!t.isDir(s.node.mode)){e.writeFile(r,t.readFile(r));return}e.mkdirTree(r);const n=t.readdir(r).filter(i=>i!=="."&&i!=="..");for(const i of n)copyFS(t,e,util.joinPaths(r,i))}async function createInvertedReadableStream(t={}){let e;const r=new Promise(i=>{e=i}),s=new ReadableStream({...t,start(i){if(e(i),t.start)return t.start(i)}}),n=await r;return{stream:s,controller:n}}async function getPhpIniEntries(t,e){const r=ini.parse(await t.readFileAsText(PHP_INI_PATH));if(e===void 0)return r;const s={};for(const n of e)s[n]=r[n];return s}async function setPhpIniEntries(t,e){const r=ini.parse(await t.readFileAsText(PHP_INI_PATH));for(const[s,n]of Object.entries(e))n==null?delete r[s]:r[s]=n;await t.writeFile(PHP_INI_PATH,ini.stringify(r))}async function withPHPIniValues(t,e,r){const s=await t.readFileAsText(PHP_INI_PATH);try{return await setPhpIniEntries(t,e),await r()}finally{await t.writeFile(PHP_INI_PATH,s)}}async function printDebugDetails(t,e){e&&printResponseDebugDetails(await PHPResponse.fromStreamedResponse(e)),await prettyPrintFullStackTrace(t)}async function prettyPrintFullStackTrace(t){let e=t,r=!0;for(;e;)r||process.stderr.write(`
57
+ ${r.errors}`,r,"request");return r}async runStream(t){if(this.cliCalled)throw new Error("php.runStream() can only be called if php.cli() was not called before. The two methods set a conflicting C-level global state.");this.runStreamCalled=!0;const e=await this.semaphore.acquire();let r;const s=m(this,h,O).call(this,async()=>{if(u(this,x)||(await m(this,h,W).call(this),f(this,x,!0)),t.scriptPath&&!this.fileExists(t.scriptPath))throw new Error(`The script path "${t.scriptPath}" does not exist.`);m(this,h,$).call(this,t.relativeUri||""),m(this,h,Y).call(this,t.method||"GET");const i=normalizeHeaders(t.headers||{}),o=i.host||"example.com:443",a=m(this,h,J).call(this,o,t.protocol||"http");if(m(this,h,V).call(this,o),m(this,h,G).call(this,a),m(this,h,K).call(this,i),t.body&&(r=m(this,h,X).call(this,t.body)),typeof t.code=="string")this.writeFile("/internal/eval.php",t.code),m(this,h,L).call(this,"/internal/eval.php");else if(typeof t.scriptPath=="string")m(this,h,L).call(this,t.scriptPath||"");else throw new TypeError("The request object must have either a `code` or a `scriptPath` property.");const l=m(this,h,B).call(this,t.$_SERVER,i,a);for(const p in l)m(this,h,Q).call(this,p,l[p]);const c=t.env||{};for(const p in c)m(this,h,U).call(this,p,c[p]);return await this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0})}),n=()=>{if(r)try{this[__private__dont__use].free(r)}catch(i){logger.logger.error(i)}e(),this.dispatchEvent({type:"request.end"})};return s.then(i=>(i.finished.finally(n),i),i=>{throw n(),i})}defineConstant(t,e){let r={};try{r=JSON.parse(this.fileExists("/internal/shared/consts.json")&&this.readFileAsText("/internal/shared/consts.json")||"{}")}catch{}this.writeFile("/internal/shared/consts.json",JSON.stringify({...r,[t]:e}))}mkdir(t){return FSHelpers.mkdir(this[__private__dont__use].FS,t)}mkdirTree(t){return FSHelpers.mkdir(this[__private__dont__use].FS,t)}readFileAsText(t){return FSHelpers.readFileAsText(this[__private__dont__use].FS,t)}readFileAsBuffer(t){return FSHelpers.readFileAsBuffer(this[__private__dont__use].FS,t)}writeFile(t,e){return FSHelpers.writeFile(this[__private__dont__use].FS,t,e)}unlink(t){return FSHelpers.unlink(this[__private__dont__use].FS,t)}mv(t,e){return FSHelpers.mv(this[__private__dont__use].FS,t,e)}rmdir(t,e={recursive:!0}){return FSHelpers.rmdir(this[__private__dont__use].FS,t,e)}listFiles(t,e={prependPath:!1}){return FSHelpers.listFiles(this[__private__dont__use].FS,t,e)}isDir(t){return FSHelpers.isDir(this[__private__dont__use].FS,t)}isFile(t){return FSHelpers.isFile(this[__private__dont__use].FS,t)}symlink(t,e){return FSHelpers.symlink(this[__private__dont__use].FS,t,e)}isSymlink(t){return FSHelpers.isSymlink(this[__private__dont__use].FS,t)}readlink(t){return FSHelpers.readlink(this[__private__dont__use].FS,t)}realpath(t){return FSHelpers.realpath(this[__private__dont__use].FS,t)}fileExists(t){return FSHelpers.fileExists(this[__private__dont__use].FS,t)}async hotSwapPHPRuntime(t,e){const r=this[__private__dont__use].FS,s=[];for(const[n,i]of Object.entries(u(this,T)))s.push({mountHandler:i.mountHandler,vfsPath:n}),await i.unmount();try{this.exit()}catch{}this.initializeRuntime(t),u(this,k)&&this.setSapiName(u(this,k)),copyFS(r,this[__private__dont__use].FS,"/internal"),e&&copyFS(r,this[__private__dont__use].FS,e);for(const{mountHandler:n,vfsPath:i}of s)this.mkdir(i),await this.mount(i,n)}async mount(t,e){const r=await e(this,this[__private__dont__use].FS,t),s={mountHandler:e,unmount:async()=>{await r(),delete u(this,T)[t]}};return u(this,T)[t]=s,()=>{s.unmount()}}async cli(t,e={}){if(this.cliCalled)throw new Error("php.cli() can only be called once. The method sets a C-level global state that does not allow repeated calls.");if(this.runStreamCalled)throw new Error("php.cli() can only be called if php.runStream() was not called before. The two methods set a conflicting C-level global state.");this.cliCalled=!0;const r=await this.semaphore.acquire(),s=e.env||{};for(const[n,i]of Object.entries(s))m(this,h,U).call(this,n,i);t=[t[0],"-c",PHP_INI_PATH,...t.slice(1)];for(const n of t)this[__private__dont__use].ccall("wasm_add_cli_arg",null,[STRING],[n]);return await m(this,h,O).call(this,()=>this[__private__dont__use].ccall("run_cli",null,[],[],{async:!0})).then(n=>(n.exitCode.finally(r),n))}setSkipShebang(t){this[__private__dont__use].ccall("wasm_set_skip_shebang",null,[NUMBER],[t?1:0])}exit(t=0){this.dispatchEvent({type:"runtime.beforedestroy"});try{this[__private__dont__use]._exit(t)}catch{}f(this,x,!1),f(this,E,null),this[__private__dont__use]&&(delete this[__private__dont__use].onMessage,delete this[__private__dont__use])}[Symbol.dispose](){u(this,x)&&this.exit(0)}}k=new WeakMap,x=new WeakMap,E=new WeakMap,g=new WeakMap,S=new WeakMap,T=new WeakMap,h=new WeakSet,B=function(t,e,r){const s={...t||{}};s.HTTPS=s.HTTPS||r===443?"on":"off";for(const n in e){let i="HTTP_";["content-type","content-length"].includes(n.toLowerCase())&&(i=""),s[`${i}${n.toUpperCase().replace(/-/g,"_")}`]=e[n]}return s},W=function(){return this[__private__dont__use].ccall("php_wasm_init",null,[],[],{isAsync:!0})},$=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])},U=function(t,e){this[__private__dont__use].ccall("wasm_add_ENV_entry",null,[STRING,STRING],[t,e])},O=async function(t){const e=this[__private__dont__use],r=await createInvertedReadableStream();e.onHeaders=d=>{a||s||r.controller.enqueue(d.slice())};let s=!1;const n=()=>{s||(s=!0,r.controller.close())},i=await createInvertedReadableStream();e.onStdout=d=>{n(),!a&&i.controller.enqueue(d.slice())};const o=await createInvertedReadableStream();e.onStderr=d=>{a||o.controller.enqueue(d.slice())};let a=!1,l;const p=(async()=>{var d;try{return await Promise.race([t(),new Promise((w,b)=>{var j;l=D=>{isExitCode(D.error)||b(D.error)},(j=u(this,E))==null||j.addEventListener("error",l,{once:!0})})])}catch(y){if(isExitCode(y))return y.status;i.controller.error(y),o.controller.error(y),r.controller.error(y),a=!0;for(const w in this)typeof this[w]=="function"&&(this[w]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});throw this.functionsMaybeMissingFromAsyncify=getFunctionsMaybeMissingFromAsyncify(),y}finally{a||(i.controller.close(),o.controller.close(),n(),a=!0),(d=u(this,E))==null||d.removeEventListener("error",l)}})().then(d=>(d!==0&&this.dispatchEvent({type:"request.error",error:new Error(`PHP.run() failed with exit code ${d}.`),source:"php-wasm"}),d),d=>{throw this.dispatchEvent({type:"request.error",error:d,source:d.source??"php-wasm"}),d});return new StreamedPHPResponse(r.stream,i.stream,o.stream,p)};function normalizeHeaders(t){const e={};for(const r in t)e[r.toLowerCase()]=t[r];return e}function copyFS(t,e,r){let s;try{s=t.lookupPath(r)}catch{return}if(!("contents"in s.node))return;if(!t.isDir(s.node.mode)){e.writeFile(r,t.readFile(r));return}e.mkdirTree(r);const n=t.readdir(r).filter(i=>i!=="."&&i!=="..");for(const i of n)copyFS(t,e,util.joinPaths(r,i))}async function createInvertedReadableStream(t={}){let e;const r=new Promise(i=>{e=i}),s=new ReadableStream({...t,start(i){if(e(i),t.start)return t.start(i)}}),n=await r;return{stream:s,controller:n}}async function getPhpIniEntries(t,e){const r=ini.parse(await t.readFileAsText(PHP_INI_PATH));if(e===void 0)return r;const s={};for(const n of e)s[n]=r[n];return s}async function setPhpIniEntries(t,e){const r=ini.parse(await t.readFileAsText(PHP_INI_PATH));for(const[s,n]of Object.entries(e))n==null?delete r[s]:r[s]=n;await t.writeFile(PHP_INI_PATH,ini.stringify(r))}async function withPHPIniValues(t,e,r){const s=await t.readFileAsText(PHP_INI_PATH);try{return await setPhpIniEntries(t,e),await r()}finally{await t.writeFile(PHP_INI_PATH,s)}}async function printDebugDetails(t,e){e&&printResponseDebugDetails(await PHPResponse.fromStreamedResponse(e)),await prettyPrintFullStackTrace(t)}async function prettyPrintFullStackTrace(t){let e=t,r=!0;for(;e;)r||process.stderr.write(`
58
58
  Caused by:
59
59
 
60
60
  `),process.stderr.write(e.originalErrorClassName??e.name),process.stderr.write(": "+e.message+`