@php-wasm/universal 3.1.39 → 3.1.41

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 Ne=Object.create;var ge=Object.defineProperty;var Oe=Object.getOwnPropertyDescriptor;var De=Object.getOwnPropertyNames;var Ue=Object.getPrototypeOf,je=Object.prototype.hasOwnProperty;var Pe=r=>{throw TypeError(r)};var Be=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of De(e))!je.call(r,n)&&n!==t&&ge(r,n,{get:()=>e[n],enumerable:!(s=Oe(e,n))||s.enumerable});return r};var qe=(r,e,t)=>(t=r!=null?Ne(Ue(r)):{},Be(e||!r||!r.__esModule?ge(t,"default",{value:r,enumerable:!0}):t,r));var pe=(r,e,t)=>e.has(r)||Pe("Cannot "+t);var p=(r,e,t)=>(pe(r,e,"read from private field"),t?t.call(r):e.get(r)),x=(r,e,t)=>e.has(r)?Pe("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),E=(r,e,t,s)=>(pe(r,e,"write to private field"),s?s.call(r,t):e.set(r,t),t),_=(r,e,t)=>(pe(r,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const logger=require("@php-wasm/logger"),util=require("@php-wasm/util"),ini=require("ini"),streamCompression=require("@php-wasm/stream-compression");class ErrnoError extends Error{constructor(e,t,s){super(t,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(r){const e=typeof r=="object"?r==null?void 0:r.errno:null;if(e in FileErrorCodes)return FileErrorCodes[e]}function rethrowFileSystemError(r=""){return function(t){return function(...s){try{return t.apply(this,s)}catch(n){const o=typeof n=="object"?n==null?void 0:n.errno:null;if(o in FileErrorCodes){const i=FileErrorCodes[o],a=typeof s[1]=="string"?s[1]:null,l=a!==null?r.replaceAll("{path}",a):r;throw new ErrnoError(o,`${l}: ${i}`,{cause:n})}throw n}}}}class FSHelpers{static readFileAsText(e,t){return new TextDecoder().decode(FSHelpers.readFileAsBuffer(e,t))}static readFileAsBuffer(e,t){return e.readFile(t)}static writeFile(e,t,s){e.writeFile(t,s)}static unlink(e,t){e.unlink(t)}static mv(e,t,s){try{const n=e.lookupPath(t).node.mount,o=FSHelpers.fileExists(e,s)?e.lookupPath(s).node.mount:e.lookupPath(util.dirname(s)).node.mount;n.mountpoint!==o.mountpoint?(FSHelpers.copyRecursive(e,t,s),FSHelpers.isDir(e,t)?FSHelpers.rmdir(e,t,{recursive:!0}):e.unlink(t)):e.rename(t,s)}catch(n){const o=getEmscriptenFsError(n);throw o?new Error(`Could not move ${t} to ${s}: ${o}`,{cause:n}):n}}static rmdir(e,t,s={recursive:!0}){const n=e.lookupPath(t,{follow:!1});if((n==null?void 0:n.node.mount.mountpoint)===t)throw new ErrnoError(10);s!=null&&s.recursive&&FSHelpers.listFiles(e,t).forEach(o=>{const i=`${t}/${o}`;FSHelpers.isDir(e,i)?FSHelpers.rmdir(e,i,s):FSHelpers.unlink(e,i)}),e.getPath(e.lookupPath(t).node)===e.cwd()&&e.chdir(util.joinPaths(e.cwd(),"..")),e.rmdir(t)}static listFiles(e,t,s={prependPath:!1}){if(!FSHelpers.fileExists(e,t))return[];try{const n=e.readdir(t).filter(o=>o!=="."&&o!=="..");if(s.prependPath){const o=t.replace(/\/$/,"");return n.map(i=>`${o}/${i}`)}return n}catch(n){return logger.logger.error(n,{path:t}),[]}}static isDir(e,t){return FSHelpers.fileExists(e,t)?e.isDir(e.lookupPath(t,{follow:!0}).node.mode):!1}static isFile(e,t){return FSHelpers.fileExists(e,t)?e.isFile(e.lookupPath(t,{follow:!0}).node.mode):!1}static symlink(e,t,s){return e.symlink(t,s)}static isSymlink(e,t){return FSHelpers.fileExists(e,t)?e.isLink(e.lookupPath(t).node.mode):!1}static readlink(e,t){return e.readlink(t)}static realpath(e,t){return e.lookupPath(t,{follow:!0}).path}static fileExists(e,t){try{return e.lookupPath(t),!0}catch{return!1}}static mkdir(e,t){e.mkdirTree(t)}static copyRecursive(e,t,s){try{const n=e.lookupPath(t).node;if(e.isDir(n.mode)){if(t===s||s.startsWith(`${t}/`))throw new ErrnoError(28);e.mkdirTree(s);const o=e.readdir(t).filter(i=>i!=="."&&i!=="..");for(const i of o)FSHelpers.copyRecursive(e,util.joinPaths(t,i),util.joinPaths(s,i))}else e.isLink(n.mode)?e.symlink(e.readlink(t),s):e.writeFile(s,e.readFile(t))}catch(n){const o=getEmscriptenFsError(n);throw o?new Error(`Could not copy ${t} to ${s}: ${o}`,{cause:n}):n}}}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);const _private=new WeakMap;var U;class PHPWorker{constructor(e,t){x(this,U);this.absoluteUrl="",this.documentRoot="",this.chroot=null,E(this,U,new Map),this.onMessageListeners=[],_private.set(this,{monitor:t}),e&&this.__internal_setRequestHandler(e)}__internal_setRequestHandler(e){this.absoluteUrl=e.absoluteUrl,this.documentRoot=e.documentRoot,this.chroot=this.documentRoot,_private.set(this,{..._private.get(this),requestHandler:e})}__internal_getPHP(){return _private.get(this).php}__internal_getRequestHandler(){return this.getRequestHandler()}async setPrimaryPHP(e){_private.set(this,{..._private.get(this),php:e})}pathToInternalUrl(e){return this.getRequestHandler().pathToInternalUrl(e)}internalUrlToPath(e){return this.getRequestHandler().internalUrlToPath(e)}async onDownloadProgress(e){var t;return(t=_private.get(this).monitor)==null?void 0:t.addEventListener("progress",e)}async mv(e,t){return _private.get(this).php.mv(e,t)}async rmdir(e,t){return _private.get(this).php.rmdir(e,t)}async request(e){return await this.getRequestHandler().request(e)}async requestStreamed(e){return await this.getRequestHandler().requestStreamed(e)}async run(e){const t=_private.get(this),s=t.php;if(!t.requestHandler&&!(s!=null&&s.requestHandler)&&s)return await s.run(e);const{php:n,reap:o}=await this.acquirePHPInstance();try{return await n.run(e)}finally{o()}}async cli(e,t){const s=_private.get(this),n=s.php;if(!s.requestHandler&&!(n!=null&&n.requestHandler)&&n)return await n.cli(e,t);const{php:o,reap:i}=await this.acquirePHPInstance();let a;try{a=await o.cli(e,t)}catch(l){throw i(),l}return a.finished.finally(i),a}chdir(e){return this.chroot=e,_private.get(this).php.chdir(e)}cwd(){return _private.get(this).php.cwd()}async acquirePHPInstance(){const{php:e,reap:t}=await this.getRequestHandler().instanceManager.acquirePHPInstance();return this.chroot!==null&&e.chdir(this.chroot),this.registerWorkerListeners(e),{php:e,reap:t}}setSapiName(e){_private.get(this).php.setSapiName(e)}mkdir(e){return _private.get(this).php.mkdir(e)}mkdirTree(e){return _private.get(this).php.mkdirTree(e)}readFileAsText(e){return _private.get(this).php.readFileAsText(e)}readFileAsBuffer(e){return _private.get(this).php.readFileAsBuffer(e)}writeFile(e,t){return _private.get(this).php.writeFile(e,t)}unlink(e){return _private.get(this).php.unlink(e)}listFiles(e,t){return _private.get(this).php.listFiles(e,t)}isDir(e){return _private.get(this).php.isDir(e)}isFile(e){return _private.get(this).php.isFile(e)}fileExists(e){return _private.get(this).php.fileExists(e)}onMessage(e){return this.onMessageListeners.push(e),async()=>{this.onMessageListeners=this.onMessageListeners.filter(t=>t!==e)}}defineConstant(e,t){_private.get(this).php.defineConstant(e,t)}addEventListener(e,t){p(this,U).has(e)||p(this,U).set(e,new Set),p(this,U).get(e).add(t)}removeEventListener(e,t){var s;(s=p(this,U).get(e))==null||s.delete(t)}dispatchEvent(e){const t=p(this,U).get(e.type);if(t)for(const s of t)s(e)}registerWorkerListeners(e){e.addEventListener("*",async t=>{this.dispatchEvent(t)}),e.onMessage(async t=>{for(const s of this.onMessageListeners){const n=await s(t);if(n)return n}return""})}async[Symbol.asyncDispose](){var e;await((e=this.getRequestHandler(!1))==null?void 0:e[Symbol.asyncDispose]())}getRequestHandler(e=!0){var s;const t=_private.get(this);if(t.requestHandler)return t.requestHandler;if((s=t.php)!=null&&s.requestHandler)return this.__internal_setRequestHandler(t.php.requestHandler),t.php.requestHandler;if(e)throw new Error("PHPWorker is not connected to a request handler.")}}U=new WeakMap;function isExitCode(r){return r instanceof Error?(r==null?void 0:r.name)==="ExitStatus"&&"status"in r:!1}const RuntimeId=Symbol("RuntimeId"),loadedRuntimes=new Map;let lastRuntimeId=0;async function loadPHPRuntime(r,...e){const t=Object.assign({},...e),[s,n,o]=makePromise(),i=r.init(currentJsRuntime,{onAbort(c){o(c),logger.logger.error(c)},ENV:{},locateFile:c=>c,...t,noInitialRun:!0,onRuntimeInitialized(){t.onRuntimeInitialized&&t.onRuntimeInitialized(i),n()}});await s;const a=t.phpWasmAsyncMode??r.phpWasmAsyncMode;a&&(i.phpWasmAsyncMode=a);const l=++lastRuntimeId;return i.FS,i.id=l,i.originalExit=i._exit,i._exit=function(c){return i.outboundNetworkProxyServer&&(i.outboundNetworkProxyServer.close(),i.outboundNetworkProxyServer.closeAllConnections()),loadedRuntimes.delete(l),i.originalExit(c)},i[RuntimeId]=l,loadedRuntimes.set(l,i),l}function popLoadedRuntime(r,{dangerouslyKeepTheRuntimeInTheMap:e=!1}={}){var s;const t=loadedRuntimes.get(r);if(!t)throw new Error(`Runtime with id ${r} not found`);if(e){if(!((s=process==null?void 0:process.env)!=null&&s.TEST))throw new Error("Cannot pop runtime in non-test environment");return t}return loadedRuntimes.delete(r),t}const currentJsRuntime=function(){var r;return typeof process<"u"&&((r=process.release)==null?void 0:r.name)==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"}(),makePromise=()=>{const r=[],e=new Promise((t,s)=>{r.push(t,s)});return r.unshift(e),r},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"};var ee,te;const ae=class ae{constructor(e,t,s,n){x(this,ee);x(this,te);this.cachedParsedHeaders=null,this.cachedStdoutBytes=null,this.cachedStderrText=null;const[o,i]=e.tee();E(this,ee,o),E(this,te,i),this.stdout=t,this.stderr=s,this.exitCode=n}static fromPHPResponse(e){const t=new ReadableStream({start(a){a.enqueue(e.bytes),a.close()}}),s=[];for(const[a,l]of Object.entries(e.headers))for(const c of l)s.push(`${a}: ${c}`);const n=JSON.stringify({status:e.httpStatusCode,headers:s}),o=new ReadableStream({start(a){a.enqueue(new TextEncoder().encode(n)),a.close()}}),i=new ReadableStream({start(a){e.errors.length>0&&a.enqueue(new TextEncoder().encode(e.errors)),a.close()}});return new ae(o,t,i,Promise.resolve(e.exitCode))}static forHttpCode(e,t=""){return ae.fromPHPResponse(PHPResponse.forHttpCode(e,t))}getHeadersStream(){return p(this,ee)}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(t=>t.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.cachedParsedHeaders||(this.cachedParsedHeaders=parseHeadersStream(p(this,te))),await this.cachedParsedHeaders}};ee=new WeakMap,te=new WeakMap;let StreamedPHPResponse=ae;async function parseHeadersStream(r){const e=await streamToText(r);let t;try{t=JSON.parse(e)}catch{return{headers:{},httpStatusCode:200}}const s={};for(const n of t.headers){if(!n.includes(": "))continue;const o=n.indexOf(": "),i=n.substring(0,o).toLowerCase(),a=n.substring(o+2);i in s||(s[i]=[]),s[i].push(a)}return{headers:s,httpStatusCode:t.status}}async function streamToText(r){const e=r.pipeThrough(new TextDecoderStream).getReader(),t=[];for(;;){const{done:s,value:n}=await e.read();if(s)return t.join("");n&&t.push(n)}}async function streamToBytes(r){const e=r.getReader(),t=[];for(;;){const{done:s,value:n}=await e.read();if(s){const o=t.reduce((l,c)=>l+c.byteLength,0),i=new Uint8Array(o);let a=0;for(const l of t)i.set(l,a),a+=l.byteLength;return i}n&&t.push(n)}}class PHPResponse{constructor(e,t,s,n="",o=0){this.httpStatusCode=e,this.headers=t,this.bytes=s,this.exitCode=o,this.errors=n}static forHttpCode(e,t=""){return new PHPResponse(e,{},new TextEncoder().encode(t||responseTexts[e]||""))}static fromRawData(e){return new PHPResponse(e.httpStatusCode,e.headers,e.bytes,e.errors,e.exitCode)}static async fromStreamedResponse(e){return await e.finished,new PHPResponse(await e.httpStatusCode,await e.headers,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)}}var _a;const kError=Symbol("error"),kMessage=Symbol("message");class ErrorEvent2 extends(_a=Event,_a){constructor(e,t={}){super(e),this[kError]=t.error===void 0?null:t.error,this[kMessage]=t.message===void 0?"":t.message}get error(){return this[kError]}get message(){return this[kMessage]}}Object.defineProperty(ErrorEvent2.prototype,"error",{enumerable:!0});Object.defineProperty(ErrorEvent2.prototype,"message",{enumerable:!0});const ErrorEvent=typeof globalThis.ErrorEvent=="function"?globalThis.ErrorEvent:ErrorEvent2;class UnhandledRejectionsTarget extends EventTarget{constructor(){super(...arguments),this.listenersCount=0}addEventListener(e,t,s){++this.listenersCount,super.addEventListener(e,t,s)}removeEventListener(e,t,s){--this.listenersCount,super.removeEventListener(e,t,s)}hasListeners(){return this.listenersCount>0}}function improveWASMErrorReporting(r){const e=new UnhandledRejectionsTarget;for(const t in r.wasmExports)if(typeof r.wasmExports[t]=="function"){const s=r.wasmExports[t];r.wasmExports[t]=function(...n){var o;try{return s(...n)}catch(i){if(!(i instanceof Error))throw i;r.lastAsyncifyStackSource&&(i.cause=r.lastAsyncifyStackSource);const a=clarifyErrorMessage(i,(o=r.lastAsyncifyStackSource)==null?void 0:o.stack);if(e.hasListeners()){i.message=a;const l=new ErrorEvent("error",{error:i});throw e.dispatchEvent(l),i}throw(!isExitCode(i)||i.status!==0)&&showCriticalErrorBox(a),i}}}return e}let functionsMaybeMissingFromAsyncify=[];function getFunctionsMaybeMissingFromAsyncify(){return functionsMaybeMissingFromAsyncify}function clarifyErrorMessage(r,e){if(r.message==="unreachable"){let t=UNREACHABLE_ERROR;e||(t+=`
1
+ "use strict";var Ne=Object.create;var ge=Object.defineProperty;var Oe=Object.getOwnPropertyDescriptor;var De=Object.getOwnPropertyNames;var je=Object.getPrototypeOf,Ue=Object.prototype.hasOwnProperty;var Pe=r=>{throw TypeError(r)};var Be=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of De(e))!Ue.call(r,n)&&n!==t&&ge(r,n,{get:()=>e[n],enumerable:!(s=Oe(e,n))||s.enumerable});return r};var qe=(r,e,t)=>(t=r!=null?Ne(je(r)):{},Be(e||!r||!r.__esModule?ge(t,"default",{value:r,enumerable:!0}):t,r));var pe=(r,e,t)=>e.has(r)||Pe("Cannot "+t);var p=(r,e,t)=>(pe(r,e,"read from private field"),t?t.call(r):e.get(r)),x=(r,e,t)=>e.has(r)?Pe("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),E=(r,e,t,s)=>(pe(r,e,"write to private field"),s?s.call(r,t):e.set(r,t),t),_=(r,e,t)=>(pe(r,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const logger=require("@php-wasm/logger"),util=require("@php-wasm/util"),ini=require("ini"),streamCompression=require("@php-wasm/stream-compression");class ErrnoError extends Error{constructor(e,t,s){super(t,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(r){const e=typeof r=="object"?r==null?void 0:r.errno:null;if(e in FileErrorCodes)return FileErrorCodes[e]}function rethrowFileSystemError(r=""){return function(t){return function(...s){try{return t.apply(this,s)}catch(n){const o=typeof n=="object"?n==null?void 0:n.errno:null;if(o in FileErrorCodes){const i=FileErrorCodes[o],a=typeof s[1]=="string"?s[1]:null,l=a!==null?r.replaceAll("{path}",a):r;throw new ErrnoError(o,`${l}: ${i}`,{cause:n})}throw n}}}}class FSHelpers{static readFileAsText(e,t){return new TextDecoder().decode(FSHelpers.readFileAsBuffer(e,t))}static readFileAsBuffer(e,t){return e.readFile(t)}static writeFile(e,t,s){e.writeFile(t,s)}static unlink(e,t){e.unlink(t)}static mv(e,t,s){try{const n=e.lookupPath(t).node.mount,o=FSHelpers.fileExists(e,s)?e.lookupPath(s).node.mount:e.lookupPath(util.dirname(s)).node.mount;n.mountpoint!==o.mountpoint?(FSHelpers.copyRecursive(e,t,s),FSHelpers.isDir(e,t)?FSHelpers.rmdir(e,t,{recursive:!0}):e.unlink(t)):e.rename(t,s)}catch(n){const o=getEmscriptenFsError(n);throw o?new Error(`Could not move ${t} to ${s}: ${o}`,{cause:n}):n}}static rmdir(e,t,s={recursive:!0}){const n=e.lookupPath(t,{follow:!1});if((n==null?void 0:n.node.mount.mountpoint)===t)throw new ErrnoError(10);s!=null&&s.recursive&&FSHelpers.listFiles(e,t).forEach(o=>{const i=`${t}/${o}`;FSHelpers.isDir(e,i)?FSHelpers.rmdir(e,i,s):FSHelpers.unlink(e,i)}),e.getPath(e.lookupPath(t).node)===e.cwd()&&e.chdir(util.joinPaths(e.cwd(),"..")),e.rmdir(t)}static listFiles(e,t,s={prependPath:!1}){if(!FSHelpers.fileExists(e,t))return[];try{const n=e.readdir(t).filter(o=>o!=="."&&o!=="..");if(s.prependPath){const o=t.replace(/\/$/,"");return n.map(i=>`${o}/${i}`)}return n}catch(n){return logger.logger.error(n,{path:t}),[]}}static isDir(e,t){return FSHelpers.fileExists(e,t)?e.isDir(e.lookupPath(t,{follow:!0}).node.mode):!1}static isFile(e,t){return FSHelpers.fileExists(e,t)?e.isFile(e.lookupPath(t,{follow:!0}).node.mode):!1}static symlink(e,t,s){return e.symlink(t,s)}static isSymlink(e,t){return FSHelpers.fileExists(e,t)?e.isLink(e.lookupPath(t).node.mode):!1}static readlink(e,t){return e.readlink(t)}static realpath(e,t){return e.lookupPath(t,{follow:!0}).path}static fileExists(e,t){try{return e.lookupPath(t),!0}catch{return!1}}static mkdir(e,t){e.mkdirTree(t)}static copyRecursive(e,t,s){try{const n=e.lookupPath(t).node;if(e.isDir(n.mode)){if(t===s||s.startsWith(`${t}/`))throw new ErrnoError(28);e.mkdirTree(s);const o=e.readdir(t).filter(i=>i!=="."&&i!=="..");for(const i of o)FSHelpers.copyRecursive(e,util.joinPaths(t,i),util.joinPaths(s,i))}else e.isLink(n.mode)?e.symlink(e.readlink(t),s):e.writeFile(s,e.readFile(t))}catch(n){const o=getEmscriptenFsError(n);throw o?new Error(`Could not copy ${t} to ${s}: ${o}`,{cause:n}):n}}}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);const _private=new WeakMap;var j;class PHPWorker{constructor(e,t){x(this,j);this.absoluteUrl="",this.documentRoot="",this.chroot=null,E(this,j,new Map),this.onMessageListeners=[],_private.set(this,{monitor:t}),e&&this.__internal_setRequestHandler(e)}__internal_setRequestHandler(e){this.absoluteUrl=e.absoluteUrl,this.documentRoot=e.documentRoot,this.chroot=this.documentRoot,_private.set(this,{..._private.get(this),requestHandler:e})}__internal_getPHP(){return _private.get(this).php}__internal_getRequestHandler(){return this.getRequestHandler()}async setPrimaryPHP(e){_private.set(this,{..._private.get(this),php:e})}pathToInternalUrl(e){return this.getRequestHandler().pathToInternalUrl(e)}internalUrlToPath(e){return this.getRequestHandler().internalUrlToPath(e)}async onDownloadProgress(e){var t;return(t=_private.get(this).monitor)==null?void 0:t.addEventListener("progress",e)}async mv(e,t){return _private.get(this).php.mv(e,t)}async rmdir(e,t){return _private.get(this).php.rmdir(e,t)}async request(e){return await this.getRequestHandler().request(e)}async requestStreamed(e){return await this.getRequestHandler().requestStreamed(e)}async run(e){const t=_private.get(this),s=t.php;if(!t.requestHandler&&!(s!=null&&s.requestHandler)&&s)return await s.run(e);const{php:n,reap:o}=await this.acquirePHPInstance();try{return await n.run(e)}finally{o()}}async cli(e,t){const s=_private.get(this),n=s.php;if(!s.requestHandler&&!(n!=null&&n.requestHandler)&&n)return await n.cli(e,t);const{php:o,reap:i}=await this.acquirePHPInstance();let a;try{a=await o.cli(e,t)}catch(l){throw i(),l}return a.finished.finally(i),a}chdir(e){return this.chroot=e,_private.get(this).php.chdir(e)}cwd(){return _private.get(this).php.cwd()}async acquirePHPInstance(){const{php:e,reap:t}=await this.getRequestHandler().instanceManager.acquirePHPInstance();return this.chroot!==null&&e.chdir(this.chroot),this.registerWorkerListeners(e),{php:e,reap:t}}setSapiName(e){_private.get(this).php.setSapiName(e)}mkdir(e){return _private.get(this).php.mkdir(e)}mkdirTree(e){return _private.get(this).php.mkdirTree(e)}readFileAsText(e){return _private.get(this).php.readFileAsText(e)}readFileAsBuffer(e){return _private.get(this).php.readFileAsBuffer(e)}writeFile(e,t){return _private.get(this).php.writeFile(e,t)}unlink(e){return _private.get(this).php.unlink(e)}listFiles(e,t){return _private.get(this).php.listFiles(e,t)}isDir(e){return _private.get(this).php.isDir(e)}isFile(e){return _private.get(this).php.isFile(e)}fileExists(e){return _private.get(this).php.fileExists(e)}onMessage(e){return this.onMessageListeners.push(e),async()=>{this.onMessageListeners=this.onMessageListeners.filter(t=>t!==e)}}defineConstant(e,t){_private.get(this).php.defineConstant(e,t)}addEventListener(e,t){p(this,j).has(e)||p(this,j).set(e,new Set),p(this,j).get(e).add(t)}removeEventListener(e,t){var s;(s=p(this,j).get(e))==null||s.delete(t)}dispatchEvent(e){const t=p(this,j).get(e.type);if(t)for(const s of t)s(e)}registerWorkerListeners(e){e.addEventListener("*",async t=>{this.dispatchEvent(t)}),e.onMessage(async t=>{for(const s of this.onMessageListeners){const n=await s(t);if(n)return n}return""})}async[Symbol.asyncDispose](){var e;await((e=this.getRequestHandler(!1))==null?void 0:e[Symbol.asyncDispose]())}getRequestHandler(e=!0){var s;const t=_private.get(this);if(t.requestHandler)return t.requestHandler;if((s=t.php)!=null&&s.requestHandler)return this.__internal_setRequestHandler(t.php.requestHandler),t.php.requestHandler;if(e)throw new Error("PHPWorker is not connected to a request handler.")}}j=new WeakMap;function isExitCode(r){return r instanceof Error?(r==null?void 0:r.name)==="ExitStatus"&&"status"in r:!1}const RuntimeId=Symbol("RuntimeId"),loadedRuntimes=new Map;let lastRuntimeId=0;async function loadPHPRuntime(r,...e){const t=Object.assign({},...e),[s,n,o]=makePromise(),i=r.init(currentJsRuntime,{onAbort(c){o(c),logger.logger.error(c)},ENV:{},locateFile:c=>c,...t,noInitialRun:!0,onRuntimeInitialized(){t.onRuntimeInitialized&&t.onRuntimeInitialized(i),n()}});await s;const a=t.phpWasmAsyncMode??r.phpWasmAsyncMode;a&&(i.phpWasmAsyncMode=a);const l=++lastRuntimeId;return i.FS,i.id=l,i.originalExit=i._exit,i._exit=function(c){return i.outboundNetworkProxyServer&&(i.outboundNetworkProxyServer.close(),i.outboundNetworkProxyServer.closeAllConnections()),loadedRuntimes.delete(l),i.originalExit(c)},i[RuntimeId]=l,loadedRuntimes.set(l,i),l}function popLoadedRuntime(r,{dangerouslyKeepTheRuntimeInTheMap:e=!1}={}){var s;const t=loadedRuntimes.get(r);if(!t)throw new Error(`Runtime with id ${r} not found`);if(e){if(!((s=process==null?void 0:process.env)!=null&&s.TEST))throw new Error("Cannot pop runtime in non-test environment");return t}return loadedRuntimes.delete(r),t}const currentJsRuntime=function(){var r;return typeof process<"u"&&((r=process.release)==null?void 0:r.name)==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"}(),makePromise=()=>{const r=[],e=new Promise((t,s)=>{r.push(t,s)});return r.unshift(e),r},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"};var ee,te;const ae=class ae{constructor(e,t,s,n){x(this,ee);x(this,te);this.cachedParsedHeaders=null,this.cachedStdoutBytes=null,this.cachedStderrText=null;const[o,i]=e.tee();E(this,ee,o),E(this,te,i),this.stdout=t,this.stderr=s,this.exitCode=n}static fromPHPResponse(e){const t=new ReadableStream({start(a){a.enqueue(e.bytes),a.close()}}),s=[];for(const[a,l]of Object.entries(e.headers))for(const c of l)s.push(`${a}: ${c}`);const n=JSON.stringify({status:e.httpStatusCode,headers:s}),o=new ReadableStream({start(a){a.enqueue(new TextEncoder().encode(n)),a.close()}}),i=new ReadableStream({start(a){e.errors.length>0&&a.enqueue(new TextEncoder().encode(e.errors)),a.close()}});return new ae(o,t,i,Promise.resolve(e.exitCode))}static forHttpCode(e,t=""){return ae.fromPHPResponse(PHPResponse.forHttpCode(e,t))}getHeadersStream(){return p(this,ee)}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(t=>t.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.cachedParsedHeaders||(this.cachedParsedHeaders=parseHeadersStream(p(this,te))),await this.cachedParsedHeaders}};ee=new WeakMap,te=new WeakMap;let StreamedPHPResponse=ae;async function parseHeadersStream(r){const e=await streamToText(r);let t;try{t=JSON.parse(e)}catch{return{headers:{},httpStatusCode:200}}const s={};for(const n of t.headers){if(!n.includes(": "))continue;const o=n.indexOf(": "),i=n.substring(0,o).toLowerCase(),a=n.substring(o+2);i in s||(s[i]=[]),s[i].push(a)}return{headers:s,httpStatusCode:t.status}}async function streamToText(r){const e=r.pipeThrough(new TextDecoderStream).getReader(),t=[];for(;;){const{done:s,value:n}=await e.read();if(s)return t.join("");n&&t.push(n)}}async function streamToBytes(r){const e=r.getReader(),t=[];for(;;){const{done:s,value:n}=await e.read();if(s){const o=t.reduce((l,c)=>l+c.byteLength,0),i=new Uint8Array(o);let a=0;for(const l of t)i.set(l,a),a+=l.byteLength;return i}n&&t.push(n)}}class PHPResponse{constructor(e,t,s,n="",o=0){this.httpStatusCode=e,this.headers=t,this.bytes=s,this.exitCode=o,this.errors=n}static forHttpCode(e,t=""){return new PHPResponse(e,{},new TextEncoder().encode(t||responseTexts[e]||""))}static fromRawData(e){return new PHPResponse(e.httpStatusCode,e.headers,e.bytes,e.errors,e.exitCode)}static async fromStreamedResponse(e){return await e.finished,new PHPResponse(await e.httpStatusCode,await e.headers,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)}}var _a;const kError=Symbol("error"),kMessage=Symbol("message");class ErrorEvent2 extends(_a=Event,_a){constructor(e,t={}){super(e),this[kError]=t.error===void 0?null:t.error,this[kMessage]=t.message===void 0?"":t.message}get error(){return this[kError]}get message(){return this[kMessage]}}Object.defineProperty(ErrorEvent2.prototype,"error",{enumerable:!0});Object.defineProperty(ErrorEvent2.prototype,"message",{enumerable:!0});const ErrorEvent=typeof globalThis.ErrorEvent=="function"?globalThis.ErrorEvent:ErrorEvent2;class UnhandledRejectionsTarget extends EventTarget{constructor(){super(...arguments),this.listenersCount=0}addEventListener(e,t,s){++this.listenersCount,super.addEventListener(e,t,s)}removeEventListener(e,t,s){--this.listenersCount,super.removeEventListener(e,t,s)}hasListeners(){return this.listenersCount>0}}function improveWASMErrorReporting(r){const e=new UnhandledRejectionsTarget;for(const t in r.wasmExports)if(typeof r.wasmExports[t]=="function"){const s=r.wasmExports[t];r.wasmExports[t]=function(...n){var o;try{return s(...n)}catch(i){if(!(i instanceof Error))throw i;r.lastAsyncifyStackSource&&(i.cause=r.lastAsyncifyStackSource);const a=clarifyErrorMessage(i,(o=r.lastAsyncifyStackSource)==null?void 0:o.stack);if(e.hasListeners()){i.message=a;const l=new ErrorEvent("error",{error:i});throw e.dispatchEvent(l),i}throw(!isExitCode(i)||i.status!==0)&&showCriticalErrorBox(a),i}}}return e}let functionsMaybeMissingFromAsyncify=[];function getFunctionsMaybeMissingFromAsyncify(){return functionsMaybeMissingFromAsyncify}function clarifyErrorMessage(r,e){if(r.message==="unreachable"){let t=UNREACHABLE_ERROR;e||(t+=`
2
2
 
3
3
  This stack trace is lacking. For a better one initialize
4
4
  the PHP runtime with debug: true, e.g. 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 r.split(`
35
35
  `))logger.logger.log(`${eol} ${e} `);logger.logger.log(`${reset}`)}}function extractPHPFunctionsFromStack(r){try{const e=r.split(`
36
- `).slice(1).map(t=>{const s=t.trim().substring(3).split(" ");return{fn:s.length>=2?s[0]:"<unknown>",isWasm:t.includes("wasm:/")}}).filter(({fn:t,isWasm:s})=>s&&!t.startsWith("dynCall_")&&!t.startsWith("invoke_")).map(({fn:t})=>t);return Array.from(new Set(e))}catch{return[]}}const STRING="string",NUMBER="number",__private__dont__use=Symbol("__private__dont__use");class PHPExecutionFailureError extends Error{constructor(e,t,s){super(e),this.response=t,this.source=s}}const PHP_INI_PATH="/internal/shared/php.ini",AUTO_PREPEND_SCRIPT="/internal/shared/auto_prepend_file.php",OPCACHE_FILE_FOLDER="/internal/shared/opcache";var J,V,z,j,G,X,F,g,we,_e,ve,xe,Ee,Se,Fe,ke,fe,Re,he,me;class PHP{constructor(r){x(this,g);x(this,J);x(this,V,!1);x(this,z,null);x(this,j,new Map([["*",new Set]]));x(this,G,[]);x(this,X,{});x(this,F,{enabled:!1,recreateRuntime:()=>0,needsRotating:!1,maxRequests:400,requestsMade:0});this.semaphore=new util.Semaphore({concurrency:1}),r!==void 0&&this.initializeRuntime(r),this.addEventListener("request.error",e=>{e.source==="php-wasm"&&(p(this,F).needsRotating=!0)})}addEventListener(r,e){p(this,j).has(r)||p(this,j).set(r,new Set),p(this,j).get(r).add(e)}removeEventListener(r,e){var t;(t=p(this,j).get(r))==null||t.delete(e)}dispatchEvent(r){const e=[...p(this,j).get(r.type)||[],...p(this,j).get("*")||[]];if(e)for(const t of e)t(r)}onMessage(r){return p(this,G).push(r),async()=>{E(this,G,p(this,G).filter(e=>e!==r))}}async setSpawnHandler(handler){typeof handler=="string"&&(handler=util.createSpawnHandler(eval(handler))),this[__private__dont__use].spawnProcess=handler}get absoluteUrl(){return this.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.documentRoot}pathToInternalUrl(r){return this.requestHandler.pathToInternalUrl(r)}internalUrlToPath(r){return this.requestHandler.internalUrlToPath(r)}initializeRuntime(r){if(this[__private__dont__use])throw new Error("PHP runtime already initialized.");const e=popLoadedRuntime(r);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 t=["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",...t].join(`
36
+ `).slice(1).map(t=>{const s=t.trim().substring(3).split(" ");return{fn:s.length>=2?s[0]:"<unknown>",isWasm:t.includes("wasm:/")}}).filter(({fn:t,isWasm:s})=>s&&!t.startsWith("dynCall_")&&!t.startsWith("invoke_")).map(({fn:t})=>t);return Array.from(new Set(e))}catch{return[]}}const STRING="string",NUMBER="number",__private__dont__use=Symbol("__private__dont__use");class PHPExecutionFailureError extends Error{constructor(e,t,s){super(e),this.response=t,this.source=s}}const PHP_INI_PATH="/internal/shared/php.ini",AUTO_PREPEND_SCRIPT="/internal/shared/auto_prepend_file.php",OPCACHE_FILE_FOLDER="/internal/shared/opcache";var J,V,z,U,G,X,k,g,we,_e,ve,xe,Ee,Se,ke,Fe,fe,be,he,me;class PHP{constructor(r){x(this,g);x(this,J);x(this,V,!1);x(this,z,null);x(this,U,new Map([["*",new Set]]));x(this,G,[]);x(this,X,{});x(this,k,{enabled:!1,recreateRuntime:()=>0,needsRotating:!1,maxRequests:400,requestsMade:0});this.semaphore=new util.Semaphore({concurrency:1}),r!==void 0&&this.initializeRuntime(r),this.addEventListener("request.error",e=>{e.source==="php-wasm"&&(p(this,k).needsRotating=!0)})}addEventListener(r,e){p(this,U).has(r)||p(this,U).set(r,new Set),p(this,U).get(r).add(e)}removeEventListener(r,e){var t;(t=p(this,U).get(r))==null||t.delete(e)}dispatchEvent(r){const e=[...p(this,U).get(r.type)||[],...p(this,U).get("*")||[]];if(e)for(const t of e)t(r)}onMessage(r){return p(this,G).push(r),async()=>{E(this,G,p(this,G).filter(e=>e!==r))}}async setSpawnHandler(handler){typeof handler=="string"&&(handler=util.createSpawnHandler(eval(handler))),this[__private__dont__use].spawnProcess=handler}get absoluteUrl(){return this.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.documentRoot}pathToInternalUrl(r){return this.requestHandler.pathToInternalUrl(r)}internalUrlToPath(r){return this.requestHandler.internalUrlToPath(r)}initializeRuntime(r){if(this[__private__dont__use])throw new Error("PHP runtime already initialized.");const e=popLoadedRuntime(r);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 t=["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",...t].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 r.split(`
54
54
  ${t.text}
55
55
 
56
56
  === Stderr ===
57
- ${t.errors}`,t,"request");return t}async runStream(r){const e=await this.semaphore.acquire();let t;const s=_(this,g,me).call(this,async()=>{if(p(this,V)||(await this[__private__dont__use].ccall("php_wasm_init",null,[],[],{isAsync:!0}),E(this,V,!0)),r.scriptPath&&!this.fileExists(r.scriptPath))throw new Error(`The script path "${r.scriptPath}" does not exist.`);_(this,g,_e).call(this,r.relativeUri||""),_(this,g,Se).call(this,r.method||"GET");const o=normalizeHeaders(r.headers||{}),i=o.host||"example.com:443",a=_(this,g,Ee).call(this,i,r.protocol||"http");if(_(this,g,ve).call(this,i),_(this,g,xe).call(this,a),_(this,g,Fe).call(this,o),r.body&&(t=_(this,g,ke).call(this,r.body)),typeof r.code=="string")this.writeFile("/internal/eval.php",r.code),_(this,g,fe).call(this,"/internal/eval.php");else if(typeof r.scriptPath=="string")_(this,g,fe).call(this,r.scriptPath||"");else throw new TypeError("The request object must have either a `code` or a `scriptPath` property.");const l=_(this,g,we).call(this,r.$_SERVER,o,a);for(const u in l)_(this,g,Re).call(this,u,l[u]);const c=r.env||{};for(const u in c)_(this,g,he).call(this,u,c[u]);return await this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0})}),n=()=>{if(t)try{this[__private__dont__use].free(t)}catch(o){logger.logger.error(o)}e(),this.dispatchEvent({type:"request.end"})};return s.then(o=>(o.finished.finally(n),o),o=>{try{n()}catch{}finally{throw o}})}defineConstant(r,e){let t={};try{t=JSON.parse(this.fileExists("/internal/shared/consts.json")&&this.readFileAsText("/internal/shared/consts.json")||"{}")}catch{}this.writeFile("/internal/shared/consts.json",JSON.stringify({...t,[r]:e}))}mkdir(r){const e=FSHelpers.mkdir(this[__private__dont__use].FS,r);return this.dispatchEvent({type:"filesystem.write"}),e}mkdirTree(r){return FSHelpers.mkdir(this[__private__dont__use].FS,r)}readFileAsText(r){return FSHelpers.readFileAsText(this[__private__dont__use].FS,r)}readFileAsBuffer(r){return FSHelpers.readFileAsBuffer(this[__private__dont__use].FS,r)}writeFile(r,e){const t=FSHelpers.writeFile(this[__private__dont__use].FS,r,e);return this.dispatchEvent({type:"filesystem.write"}),t}unlink(r){const e=FSHelpers.unlink(this[__private__dont__use].FS,r);return this.dispatchEvent({type:"filesystem.write"}),e}mv(r,e){const t=FSHelpers.mv(this[__private__dont__use].FS,r,e);return this.dispatchEvent({type:"filesystem.write"}),t}cp(r,e){const t=FSHelpers.copyRecursive(this[__private__dont__use].FS,r,e);return this.dispatchEvent({type:"filesystem.write"}),t}rmdir(r,e={recursive:!0}){const t=FSHelpers.rmdir(this[__private__dont__use].FS,r,e);return this.dispatchEvent({type:"filesystem.write"}),t}listFiles(r,e={prependPath:!1}){return FSHelpers.listFiles(this[__private__dont__use].FS,r,e)}isDir(r){return FSHelpers.isDir(this[__private__dont__use].FS,r)}isFile(r){return FSHelpers.isFile(this[__private__dont__use].FS,r)}symlink(r,e){return FSHelpers.symlink(this[__private__dont__use].FS,r,e)}isSymlink(r){return FSHelpers.isSymlink(this[__private__dont__use].FS,r)}readlink(r){return FSHelpers.readlink(this[__private__dont__use].FS,r)}realpath(r){return FSHelpers.realpath(this[__private__dont__use].FS,r)}fileExists(r){return FSHelpers.fileExists(this[__private__dont__use].FS,r)}enableRuntimeRotation(r){E(this,F,{...p(this,F),enabled:!0,recreateRuntime:r.recreateRuntime,maxRequests:r.maxRequests??400})}async rotateRuntime(){if(!p(this,F).enabled)throw new Error("Runtime rotation is not enabled. Call enableRuntimeRotation() first.");await this.hotSwapPHPRuntime(await p(this,F).recreateRuntime()),p(this,F).requestsMade=0,p(this,F).needsRotating=!1}async hotSwapPHPRuntime(r){const e=this[__private__dont__use].FS,t=this.listFiles("/").map(l=>`/${l}`),s=this[__private__dont__use].spawnProcess,n=e.cwd();e.chdir("/");const o=Object.entries(p(this,X)).map(([l,c])=>({mountHandler:c.mountHandler,vfsPath:l})),i=Object.values(p(this,X)).reverse();for(const l of i)await l.unmount();try{this.exit()}catch{}this.initializeRuntime(r),s&&(this[__private__dont__use].spawnProcess=s),p(this,J)&&this.setSapiName(p(this,J));const a=this[__private__dont__use].FS;for(const l of t)l&&l!=="/request"&&copyMEMFSNodes(e,a,l);for(const{mountHandler:l,vfsPath:c}of o)this.mkdir(c),await this.mount(c,l);try{a.chdir(n)}catch(l){throw new Error(`Failed to restore CWD to ${n} after PHP runtime rotation.`,{cause:l})}}async mount(r,e){const t=await e(this,this[__private__dont__use].FS,r),s={mountHandler:e,unmount:async()=>{try{await t()}finally{delete p(this,X)[r]}}};return p(this,X)[r]=s,()=>s.unmount()}async cli(r,e={}){if(util.basename(r[0]??"")!=="php")return this.subProcess(r,e);p(this,V)&&(p(this,F).needsRotating=!0);const t=await this.semaphore.acquire();return await _(this,g,me).call(this,()=>{const s=e.env||{};for(const[n,o]of Object.entries(s))_(this,g,he).call(this,n,o);r=[r[0],"-c",PHP_INI_PATH,...r.slice(1)];for(const n of r)this[__private__dont__use].ccall("wasm_add_cli_arg",null,[STRING],[n]);return this[__private__dont__use].ccall("run_cli",null,[],[],{async:!0})}).then(s=>(s.exitCode.finally(t),s)).finally(()=>{p(this,F).needsRotating=!0})}async subProcess(r,e={}){const t=this[__private__dont__use].spawnProcess(r[0],r.slice(1),{env:e.env,cwd:e.cwd??this.cwd()}),s=await createInvertedReadableStream();t.on("error",a=>{safeStreamError$1(s.controller,a)});const n=a=>{try{s.controller.enqueue(a)}catch{t.stderr.off("data",n)}};t.stderr.on("data",n);const o=await createInvertedReadableStream(),i=a=>{try{o.controller.enqueue(a)}catch{t.stdout.off("data",i)}};return t.stdout.on("data",i),t.on("exit",()=>{setTimeout(()=>{try{s.controller.close()}catch{}try{o.controller.close()}catch{}},0)}),new StreamedPHPResponse(new ReadableStream({start(a){a.close()}}),o.stream,s.stream,new Promise(a=>{t.on("exit",l=>{a(l)})}))}setSkipShebang(r){this[__private__dont__use].ccall("wasm_set_skip_shebang",null,[NUMBER],[r?1:0])}exit(r=0){this.dispatchEvent({type:"runtime.beforeExit"});try{this[__private__dont__use]._exit(r)}catch{}E(this,V,!1),E(this,z,null),this[__private__dont__use]&&(delete this[__private__dont__use].onMessage,delete this[__private__dont__use])}[Symbol.dispose](){this.exit(0)}}J=new WeakMap,V=new WeakMap,z=new WeakMap,j=new WeakMap,G=new WeakMap,X=new WeakMap,F=new WeakMap,g=new WeakSet,we=function(r,e,t){const s={...r||{}};s.HTTPS=s.HTTPS||t===443?"on":"off";for(const n in e){let o="HTTP_";["content-type","content-length"].includes(n.toLowerCase())&&(o=""),s[`${o}${n.toUpperCase().replace(/-/g,"_")}`]=e[n]}return s},_e=function(r){this[__private__dont__use].ccall("wasm_set_request_uri",null,[STRING],[r]);let e="";r.includes("?")&&(e=r.substring(r.indexOf("?")+1)),this[__private__dont__use].ccall("wasm_set_query_string",null,[STRING],[e])},ve=function(r){this[__private__dont__use].ccall("wasm_set_request_host",null,[STRING],[r])},xe=function(r){this[__private__dont__use].ccall("wasm_set_request_port",null,[NUMBER],[r])},Ee=function(r,e){let t;try{t=parseInt(new URL(r).port,10)}catch{}return(!t||isNaN(t)||t===80)&&(t=e==="https"?443:80),t},Se=function(r){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[r])},Fe=function(r){r.cookie&&this[__private__dont__use].ccall("wasm_set_cookies",null,[STRING],[r.cookie]),r["content-type"]&&this[__private__dont__use].ccall("wasm_set_content_type",null,[STRING],[r["content-type"]]),r["content-length"]&&this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[parseInt(r["content-length"],10)])},ke=function(r){let e,t;typeof r=="string"?(logger.logger.warn("Passing a string as the request body is deprecated. Please use a Uint8Array instead. See https://github.com/WordPress/wordpress-playground/issues/997 for more details"),t=this[__private__dont__use].lengthBytesUTF8(r),e=t+1):(t=r.byteLength,e=r.byteLength);const s=this[__private__dont__use].malloc(e);if(!s)throw new Error("Could not allocate memory for the request body.");return typeof r=="string"?this[__private__dont__use].stringToUTF8(r,s,e+1):this[__private__dont__use].HEAPU8.set(r,s),this[__private__dont__use].ccall("wasm_set_request_body",null,[NUMBER],[s]),this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[t]),s},fe=function(r){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[r])},Re=function(r,e){this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[r,e])},he=function(r,e){this[__private__dont__use].ccall("wasm_add_ENV_entry",null,[STRING,STRING],[r,e])},me=async function(r){p(this,F).enabled&&p(this,F).needsRotating&&await this.rotateRuntime(),++p(this,F).requestsMade,p(this,F).requestsMade>=p(this,F).maxRequests&&(p(this,F).needsRotating=!0);const e=this[__private__dont__use],t=await createInvertedReadableStream();e.onHeaders=d=>{a||s||t.controller.enqueue(d.slice())};let s=!1;const n=()=>{s||(s=!0,t.controller.close())},o=await createInvertedReadableStream();e.onStdout=d=>{n(),!a&&o.controller.enqueue(d.slice())};const i=await createInvertedReadableStream();e.onStderr=d=>{a||i.controller.enqueue(d.slice())};let a=!1,l;const u=(async()=>{var d;try{return await Promise.race([r(),new Promise((P,S)=>{var N;l=B=>{isExitCode(B.error)||S(B.error)},(N=p(this,z))==null||N.addEventListener("error",l,{once:!0})})])}catch(h){if(isExitCode(h))return h.status;safeStreamError$1(o.controller,h),safeStreamError$1(i.controller,h),safeStreamError$1(t.controller,h),a=!0;for(const P in this)typeof this[P]=="function"&&(this[P]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});throw this.functionsMaybeMissingFromAsyncify=getFunctionsMaybeMissingFromAsyncify(),h}finally{a||(safeStreamClose$1(o.controller),safeStreamClose$1(i.controller),n(),a=!0),(d=p(this,z))==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=>{const h=d.source??"php-wasm";throw this.dispatchEvent({type:"request.error",error:d,source:h}),d});return new StreamedPHPResponse(t.stream,o.stream,i.stream,u)};function normalizeHeaders(r){const e={};for(const t in r)e[t.toLowerCase()]=r[t];return e}function copyMEMFSNodes(r,e,t){if(getNodeType(r,t)!=="memfs"||!["memfs","missing"].includes(getNodeType(e,t)))return;const s=r.lookupPath(t,{follow:!1});if(r.isLink(s.node.mode)){const o=r.readlink(t);e.symlink(o,t);return}if(!r.isDir(s.node.mode)){e.writeFile(t,r.readFile(t));return}e.mkdirTree(t);const n=r.readdir(t).filter(o=>o!=="."&&o!=="..");for(const o of n)copyMEMFSNodes(r,e,util.joinPaths(t,o))}async function createInvertedReadableStream(r={}){let e;const t=new Promise(o=>{e=o}),s=new ReadableStream({...r,start(o){if(e(o),r.start)return r.start(o)}}),n=await t;return{stream:s,controller:n}}function safeStreamError$1(r,e){try{r.error(e)}catch{}}function safeStreamClose$1(r){try{r.close()}catch{}}const getNodeType=(r,e)=>{try{return"contents"in r.lookupPath(e,{follow:!0}).node?"memfs":"not-memfs"}catch{return"missing"}};async function getPhpIniEntries(r,e){const t=ini.parse(await r.readFileAsText(PHP_INI_PATH));if(e===void 0)return t;const s={};for(const n of e)s[n]=t[n];return s}async function setPhpIniEntries(r,e){const t=ini.parse(await r.readFileAsText(PHP_INI_PATH));for(const[s,n]of Object.entries(e))n==null?delete t[s]:t[s]=n;await r.writeFile(PHP_INI_PATH,ini.stringify(t))}async function withPHPIniValues(r,e,t){const s=await r.readFileAsText(PHP_INI_PATH);try{return await setPhpIniEntries(r,e),await t()}finally{await r.writeFile(PHP_INI_PATH,s)}}async function printDebugDetails(r,e){e&&printResponseDebugDetails(await PHPResponse.fromStreamedResponse(e)),await prettyPrintFullStackTrace(r)}async function prettyPrintFullStackTrace(r){let e=r,t=!0;for(;e;)t||process.stderr.write(`
57
+ ${t.errors}`,t,"request");return t}async runStream(r){const e=await this.semaphore.acquire();let t;const s=_(this,g,me).call(this,async()=>{if(p(this,V)||(await this[__private__dont__use].ccall("php_wasm_init",null,[],[],{isAsync:!0}),E(this,V,!0)),r.scriptPath&&!this.fileExists(r.scriptPath))throw new Error(`The script path "${r.scriptPath}" does not exist.`);_(this,g,_e).call(this,r.relativeUri||""),_(this,g,Se).call(this,r.method||"GET");const o=normalizeHeaders(r.headers||{}),i=o.host||"example.com:443",a=_(this,g,Ee).call(this,i,r.protocol||"http");if(_(this,g,ve).call(this,i),_(this,g,xe).call(this,a),_(this,g,ke).call(this,o),r.body&&(t=_(this,g,Fe).call(this,r.body)),typeof r.code=="string")this.writeFile("/internal/eval.php",r.code),_(this,g,fe).call(this,"/internal/eval.php");else if(typeof r.scriptPath=="string")_(this,g,fe).call(this,r.scriptPath||"");else throw new TypeError("The request object must have either a `code` or a `scriptPath` property.");const l=_(this,g,we).call(this,r.$_SERVER,o,a);for(const u in l)_(this,g,be).call(this,u,l[u]);const c=r.env||{};for(const u in c)_(this,g,he).call(this,u,c[u]);return await this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0})}),n=()=>{if(t)try{this[__private__dont__use].free(t)}catch(o){logger.logger.error(o)}e(),this.dispatchEvent({type:"request.end"})};return s.then(o=>(o.finished.finally(n),o),o=>{try{n()}catch{}finally{throw o}})}defineConstant(r,e){let t={};try{t=JSON.parse(this.fileExists("/internal/shared/consts.json")&&this.readFileAsText("/internal/shared/consts.json")||"{}")}catch{}this.writeFile("/internal/shared/consts.json",JSON.stringify({...t,[r]:e}))}mkdir(r){const e=FSHelpers.mkdir(this[__private__dont__use].FS,r);return this.dispatchEvent({type:"filesystem.write"}),e}mkdirTree(r){return FSHelpers.mkdir(this[__private__dont__use].FS,r)}readFileAsText(r){return FSHelpers.readFileAsText(this[__private__dont__use].FS,r)}readFileAsBuffer(r){return FSHelpers.readFileAsBuffer(this[__private__dont__use].FS,r)}writeFile(r,e){const t=FSHelpers.writeFile(this[__private__dont__use].FS,r,e);return this.dispatchEvent({type:"filesystem.write"}),t}unlink(r){const e=FSHelpers.unlink(this[__private__dont__use].FS,r);return this.dispatchEvent({type:"filesystem.write"}),e}mv(r,e){const t=FSHelpers.mv(this[__private__dont__use].FS,r,e);return this.dispatchEvent({type:"filesystem.write"}),t}cp(r,e){const t=FSHelpers.copyRecursive(this[__private__dont__use].FS,r,e);return this.dispatchEvent({type:"filesystem.write"}),t}rmdir(r,e={recursive:!0}){const t=FSHelpers.rmdir(this[__private__dont__use].FS,r,e);return this.dispatchEvent({type:"filesystem.write"}),t}listFiles(r,e={prependPath:!1}){return FSHelpers.listFiles(this[__private__dont__use].FS,r,e)}isDir(r){return FSHelpers.isDir(this[__private__dont__use].FS,r)}isFile(r){return FSHelpers.isFile(this[__private__dont__use].FS,r)}symlink(r,e){return FSHelpers.symlink(this[__private__dont__use].FS,r,e)}isSymlink(r){return FSHelpers.isSymlink(this[__private__dont__use].FS,r)}readlink(r){return FSHelpers.readlink(this[__private__dont__use].FS,r)}realpath(r){return FSHelpers.realpath(this[__private__dont__use].FS,r)}fileExists(r){return FSHelpers.fileExists(this[__private__dont__use].FS,r)}enableRuntimeRotation(r){E(this,k,{...p(this,k),enabled:!0,recreateRuntime:r.recreateRuntime,maxRequests:r.maxRequests??400})}async rotateRuntime(){if(!p(this,k).enabled)throw new Error("Runtime rotation is not enabled. Call enableRuntimeRotation() first.");await this.hotSwapPHPRuntime(await p(this,k).recreateRuntime()),p(this,k).requestsMade=0,p(this,k).needsRotating=!1}async hotSwapPHPRuntime(r){const e=this[__private__dont__use].FS,t=this.listFiles("/").map(l=>`/${l}`),s=this[__private__dont__use].spawnProcess,n=e.cwd();e.chdir("/");const o=Object.entries(p(this,X)).map(([l,c])=>({mountHandler:c.mountHandler,mountPointSnapshot:snapshotMountPoint(e,l),vfsPath:l})),i=Object.values(p(this,X)).reverse();for(const l of i)await l.unmount();try{this.exit()}catch{}this.initializeRuntime(r),s&&(this[__private__dont__use].spawnProcess=s),p(this,J)&&this.setSapiName(p(this,J));const a=this[__private__dont__use].FS;for(const l of t)l&&l!=="/request"&&copyMEMFSNodes(e,a,l);for(const{mountHandler:l,mountPointSnapshot:c,vfsPath:u}of o)try{await this.mount(u,l)}catch(d){if(isMissingMountSourceError(d)){restoreMountPointSnapshot(a,u,c);continue}if(!isMissingMountTargetPathError(d))throw d;this.mkdir(u),await this.mount(u,l)}try{a.chdir(n)}catch(l){throw new Error(`Failed to restore CWD to ${n} after PHP runtime rotation.`,{cause:l})}}async mount(r,e){const t=await e(this,this[__private__dont__use].FS,r),s={mountHandler:e,unmount:async()=>{try{await t()}finally{delete p(this,X)[r]}}};return p(this,X)[r]=s,()=>s.unmount()}async cli(r,e={}){if(util.basename(r[0]??"")!=="php")return this.subProcess(r,e);p(this,V)&&(p(this,k).needsRotating=!0);const t=await this.semaphore.acquire();return await _(this,g,me).call(this,()=>{const s=e.env||{};for(const[n,o]of Object.entries(s))_(this,g,he).call(this,n,o);r=[r[0],"-c",PHP_INI_PATH,...r.slice(1)];for(const n of r)this[__private__dont__use].ccall("wasm_add_cli_arg",null,[STRING],[n]);return this[__private__dont__use].ccall("run_cli",null,[],[],{async:!0})}).then(s=>(s.exitCode.finally(t),s)).finally(()=>{p(this,k).needsRotating=!0})}async subProcess(r,e={}){const t=this[__private__dont__use].spawnProcess(r[0],r.slice(1),{env:e.env,cwd:e.cwd??this.cwd()}),s=await createInvertedReadableStream();t.on("error",a=>{safeStreamError$1(s.controller,a)});const n=a=>{try{s.controller.enqueue(a)}catch{t.stderr.off("data",n)}};t.stderr.on("data",n);const o=await createInvertedReadableStream(),i=a=>{try{o.controller.enqueue(a)}catch{t.stdout.off("data",i)}};return t.stdout.on("data",i),t.on("exit",()=>{setTimeout(()=>{try{s.controller.close()}catch{}try{o.controller.close()}catch{}},0)}),new StreamedPHPResponse(new ReadableStream({start(a){a.close()}}),o.stream,s.stream,new Promise(a=>{t.on("exit",l=>{a(l)})}))}setSkipShebang(r){this[__private__dont__use].ccall("wasm_set_skip_shebang",null,[NUMBER],[r?1:0])}exit(r=0){this.dispatchEvent({type:"runtime.beforeExit"});try{this[__private__dont__use]._exit(r)}catch{}E(this,V,!1),E(this,z,null),this[__private__dont__use]&&(delete this[__private__dont__use].onMessage,delete this[__private__dont__use])}[Symbol.dispose](){this.exit(0)}}J=new WeakMap,V=new WeakMap,z=new WeakMap,U=new WeakMap,G=new WeakMap,X=new WeakMap,k=new WeakMap,g=new WeakSet,we=function(r,e,t){const s={...r||{}};s.HTTPS=s.HTTPS||t===443?"on":"off";for(const n in e){let o="HTTP_";["content-type","content-length"].includes(n.toLowerCase())&&(o=""),s[`${o}${n.toUpperCase().replace(/-/g,"_")}`]=e[n]}return s},_e=function(r){this[__private__dont__use].ccall("wasm_set_request_uri",null,[STRING],[r]);let e="";r.includes("?")&&(e=r.substring(r.indexOf("?")+1)),this[__private__dont__use].ccall("wasm_set_query_string",null,[STRING],[e])},ve=function(r){this[__private__dont__use].ccall("wasm_set_request_host",null,[STRING],[r])},xe=function(r){this[__private__dont__use].ccall("wasm_set_request_port",null,[NUMBER],[r])},Ee=function(r,e){let t;try{t=parseInt(new URL(r).port,10)}catch{}return(!t||isNaN(t)||t===80)&&(t=e==="https"?443:80),t},Se=function(r){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[r])},ke=function(r){r.cookie&&this[__private__dont__use].ccall("wasm_set_cookies",null,[STRING],[r.cookie]),r["content-type"]&&this[__private__dont__use].ccall("wasm_set_content_type",null,[STRING],[r["content-type"]]),r["content-length"]&&this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[parseInt(r["content-length"],10)])},Fe=function(r){let e,t;typeof r=="string"?(logger.logger.warn("Passing a string as the request body is deprecated. Please use a Uint8Array instead. See https://github.com/WordPress/wordpress-playground/issues/997 for more details"),t=this[__private__dont__use].lengthBytesUTF8(r),e=t+1):(t=r.byteLength,e=r.byteLength);const s=this[__private__dont__use].malloc(e);if(!s)throw new Error("Could not allocate memory for the request body.");return typeof r=="string"?this[__private__dont__use].stringToUTF8(r,s,e+1):this[__private__dont__use].HEAPU8.set(r,s),this[__private__dont__use].ccall("wasm_set_request_body",null,[NUMBER],[s]),this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[t]),s},fe=function(r){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[r])},be=function(r,e){this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[r,e])},he=function(r,e){this[__private__dont__use].ccall("wasm_add_ENV_entry",null,[STRING,STRING],[r,e])},me=async function(r){p(this,k).enabled&&p(this,k).needsRotating&&await this.rotateRuntime(),++p(this,k).requestsMade,p(this,k).requestsMade>=p(this,k).maxRequests&&(p(this,k).needsRotating=!0);const e=this[__private__dont__use],t=await createInvertedReadableStream();e.onHeaders=d=>{a||s||t.controller.enqueue(d.slice())};let s=!1;const n=()=>{s||(s=!0,t.controller.close())},o=await createInvertedReadableStream();e.onStdout=d=>{n(),!a&&o.controller.enqueue(d.slice())};const i=await createInvertedReadableStream();e.onStderr=d=>{a||i.controller.enqueue(d.slice())};let a=!1,l;const u=(async()=>{var d;try{return await Promise.race([r(),new Promise((P,S)=>{var N;l=B=>{isExitCode(B.error)||S(B.error)},(N=p(this,z))==null||N.addEventListener("error",l,{once:!0})})])}catch(h){if(isExitCode(h))return h.status;safeStreamError$1(o.controller,h),safeStreamError$1(i.controller,h),safeStreamError$1(t.controller,h),a=!0;for(const P in this)typeof this[P]=="function"&&(this[P]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});throw this.functionsMaybeMissingFromAsyncify=getFunctionsMaybeMissingFromAsyncify(),h}finally{a||(safeStreamClose$1(o.controller),safeStreamClose$1(i.controller),n(),a=!0),(d=p(this,z))==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=>{const h=d.source??"php-wasm";throw this.dispatchEvent({type:"request.error",error:d,source:h}),d});return new StreamedPHPResponse(t.stream,o.stream,i.stream,u)};function normalizeHeaders(r){const e={};for(const t in r)e[t.toLowerCase()]=r[t];return e}function copyMEMFSNodes(r,e,t){if(getNodeType(r,t)!=="memfs"||!["memfs","missing"].includes(getNodeType(e,t)))return;const s=r.lookupPath(t,{follow:!1});if(r.isLink(s.node.mode)){const o=r.readlink(t);e.symlink(o,t);return}if(!r.isDir(s.node.mode)){e.writeFile(t,r.readFile(t));return}e.mkdirTree(t);const n=r.readdir(t).filter(o=>o!=="."&&o!=="..");for(const o of n)copyMEMFSNodes(r,e,util.joinPaths(t,o))}function snapshotMountPoint(r,e){try{const t=r.lookupPath(e,{follow:!1});return r.isLink(t.node.mode)?{kind:"symlink",target:r.readlink(e)}:r.isDir(t.node.mode)?{kind:"directory"}:{kind:"file"}}catch{return}}function restoreMountPointSnapshot(r,e,t){if(!(!t||getNodeType(r,e)!=="missing")){if(t.kind==="directory"){r.mkdirTree(e);return}r.mkdirTree(util.dirname(e)),t.kind==="symlink"?r.symlink(t.target,e):r.writeFile(e,new Uint8Array)}}function isMissingMountSourceError(r){return r.phpWasmMountSourceMissing===!0}function isMissingMountTargetPathError(r){return r.errno===44}async function createInvertedReadableStream(r={}){let e;const t=new Promise(o=>{e=o}),s=new ReadableStream({...r,start(o){if(e(o),r.start)return r.start(o)}}),n=await t;return{stream:s,controller:n}}function safeStreamError$1(r,e){try{r.error(e)}catch{}}function safeStreamClose$1(r){try{r.close()}catch{}}const getNodeType=(r,e)=>{try{return"contents"in r.lookupPath(e,{follow:!0}).node?"memfs":"not-memfs"}catch{return"missing"}};async function getPhpIniEntries(r,e){const t=ini.parse(await r.readFileAsText(PHP_INI_PATH));if(e===void 0)return t;const s={};for(const n of e)s[n]=t[n];return s}async function setPhpIniEntries(r,e){const t=ini.parse(await r.readFileAsText(PHP_INI_PATH));for(const[s,n]of Object.entries(e))n==null?delete t[s]:t[s]=n;await r.writeFile(PHP_INI_PATH,ini.stringify(t))}async function withPHPIniValues(r,e,t){const s=await r.readFileAsText(PHP_INI_PATH);try{return await setPhpIniEntries(r,e),await t()}finally{await r.writeFile(PHP_INI_PATH,s)}}async function printDebugDetails(r,e){e&&printResponseDebugDetails(await PHPResponse.fromStreamedResponse(e)),await prettyPrintFullStackTrace(r)}async function prettyPrintFullStackTrace(r){let e=r,t=!0;for(;e;)t||process.stderr.write(`
58
58
  Caused by:
59
59
 
60
60
  `),process.stderr.write(e.originalErrorClassName??e.name),process.stderr.write(": "+e.message+`
@@ -66,7 +66,7 @@ Caused by:
66
66
  ==== PHP error log ====
67
67
 
68
68
  `),process.stderr.write(e.phpLogs)),e=e.cause,t=!1;process.stderr.write(`
69
- `)}function printResponseDebugDetails(r){process.stderr.write(`
69
+ `)}function describeError(r,e=new WeakSet,t=0,s={}){return t>10?"[Max error cause depth exceeded]":r instanceof Error?r.message?r.message:describeErrorObject(r,e,t,{...s,suppressGenericErrorName:!0}):r&&typeof r=="object"?describeErrorObject(r,e,t,s):String(r)}function describeErrorObject(r,e,t,s={}){if(e.has(r))return"[Circular error cause]";e.add(r);const n=[];if(r.name&&!(s.suppressGenericErrorName&&r.name==="Error")&&n.push(String(r.name)),r.message&&n.push(String(r.message)),r.errno!==void 0&&n.push(`errno: ${r.errno}`),r.code!==void 0&&n.push(`code: ${r.code}`),r.cause&&n.push(`caused by: ${describeError(r.cause,e,t+1,s)}`),n.length>0)return n.join(" — ");if(typeof r.stack=="string")return r.stack;try{return JSON.stringify(r)}catch{return String(r)}}function printResponseDebugDetails(r){process.stderr.write(`
70
70
  exitCode=${r.exitCode} httpStatusCode=${r.httpStatusCode} `);const e=r.headers&&Object.keys(r.headers).length>0;e||process.stderr.write("responseHeaders=(empty) "),r.text||process.stderr.write("stdout=(empty) "),r.errors||process.stderr.write("stderr=(empty) "),process.stderr.write(`
71
71
  `),e&&process.stderr.write(`
72
72
  ==== PHP response headers ====
@@ -87,7 +87,7 @@ ${JSON.stringify(r.headers,null,2)}
87
87
  `)),n.push(`\r
88
88
  `),c instanceof File?n.push(await fileToUint8Array(c)):n.push(c),n.push(`\r
89
89
  `);n.push(`--${e}--\r
90
- `);const o=n.reduce((l,c)=>l+c.length,0),i=new Uint8Array(o);let a=0;for(const l of n)i.set(typeof l=="string"?s.encode(l):l,a),a+=l.length;return{bytes:i,contentType:t}}function fileToUint8Array(r){return r.arrayBuffer().then(e=>new Uint8Array(e))}const _default="application/octet-stream",asx="video/x-ms-asf",atom="application/atom+xml",avi="video/x-msvideo",avif="image/avif",bin="application/octet-stream",bmp="image/x-ms-bmp",cco="application/x-cocoa",cjs="application/javascript",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",mjs="application/javascript",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,cjs,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,mjs,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 A,Q,re,Y,K,M,Z,$,se,b,be,oe,He,Te,Le;class PHPRequestHandler{constructor(e){x(this,b);x(this,A);x(this,Q);x(this,re);x(this,Y);x(this,K);x(this,M);x(this,Z);x(this,$);x(this,se);const{documentRoot:t="/www/",absoluteUrl:s=typeof location=="object"?location.href:DEFAULT_BASE_URL,rewriteRules:n=[],pathAliases:o=[],getFileNotFoundAction:i=()=>({type:"404"})}=e,a=u=>{u.isDir(t)||u.mkdir(t),u.chdir(t),u.requestHandler=this};if(e.php)a(e.php),this.instanceManager=new SinglePHPInstanceManager({php:e.php});else if(e.phpFactory)this.instanceManager=new PHPProcessManager({phpFactory:async u=>{const d=await e.phpFactory({...u,requestHandler:this});return a(d),d},maxPhpInstances:e.maxPhpInstances});else throw new Error("Either php or phpFactory must be provided in the configuration.");E(this,$,e.cookieStore===void 0?new HttpCookieStore:e.cookieStore),E(this,A,t);const l=new URL(s);E(this,re,l.hostname),E(this,Y,l.port?Number(l.port):l.protocol==="https:"?443:80),E(this,Q,(l.protocol||"").replace(":",""));const c=p(this,Y)!==443&&p(this,Y)!==80;E(this,K,[p(this,re),c?`:${p(this,Y)}`:""].join("")),E(this,M,l.pathname.replace(/\/+$/,"")),E(this,Z,[`${p(this,Q)}://`,p(this,K),p(this,M)].join("")),this.rewriteRules=n,E(this,se,o),this.getFileNotFoundAction=i}async getPrimaryPhp(){return await this.instanceManager.getPrimaryPhp()}pathToInternalUrl(e){return e.startsWith("/")||(e=`/${e}`),`${this.absoluteUrl}${e}`}internalUrlToPath(e){const t=new URL(e,"https://playground.internal");return t.pathname.startsWith(p(this,M))&&(t.pathname=t.pathname.slice(p(this,M).length)),toRelativeUrl(t)}get absoluteUrl(){return p(this,Z)}get documentRoot(){return p(this,A)}async request(e){const t=await this.requestStreamed(e),s=await PHPResponse.fromStreamedResponse(t);return s.ok()&&s.exitCode!==0?new PHPResponse(500,s.headers,s.bytes,s.errors,s.exitCode):s}async requestStreamed(e){const t=looksLikeAbsoluteUrl(e.url),s=new URL(e.url.split("#")[0],t?void 0:DEFAULT_BASE_URL),n=_(this,b,be).call(this,s),o=await this.getPrimaryPhp(),i=removePathPrefix(decodeURIComponent(n.pathname),p(this,M));let a=_(this,b,oe).call(this,i);if(o.isDir(a)){if(!i.endsWith("/"))return StreamedPHPResponse.fromPHPResponse(new PHPResponse(301,{location:[`${n.pathname}/`]},new Uint8Array(0)));for(const l of["index.php","index.html"]){const c=util.joinPaths(a,l);if(o.isFile(c)){a=c,n.pathname=util.joinPaths(n.pathname,l);break}}}if(!o.isFile(a)){let l=i;for(;l.startsWith("/")&&l!==util.dirname(l);){l=util.dirname(l);const c=_(this,b,oe).call(this,l);if(o.isFile(c)&&c.endsWith(".php")){a=_(this,b,oe).call(this,l);break}}}if(!o.isFile(a)){const l=this.getFileNotFoundAction(n.pathname);switch(l.type){case"response":return StreamedPHPResponse.fromPHPResponse(l.response);case"internal-redirect":a=util.joinPaths(p(this,A),l.uri);break;case"404":return StreamedPHPResponse.forHttpCode(404);default:throw new Error(`Unsupported file-not-found action type: '${l.type}'`)}}return o.isFile(a)?a.endsWith(".php")?await _(this,b,Te).call(this,e,s,n,a):StreamedPHPResponse.fromPHPResponse(_(this,b,He).call(this,o,a)):StreamedPHPResponse.forHttpCode(404)}prepare_$_SERVER_superglobal(e,t,s){const n={REMOTE_ADDR:"127.0.0.1",DOCUMENT_ROOT:p(this,A),HTTPS:p(this,Z).startsWith("https://")?"on":""};return n.REQUEST_URI=e.pathname+e.search,s.startsWith(p(this,A))&&(n.SCRIPT_NAME=s.substring(p(this,A).length),n.PHP_SELF=t.pathname,n.REQUEST_URI.startsWith(n.SCRIPT_NAME)&&(n.PATH_INFO=n.REQUEST_URI.substring(n.SCRIPT_NAME.length),n.PATH_INFO.includes("?")&&(n.PATH_INFO=n.PATH_INFO.substring(0,n.PATH_INFO.indexOf("?"))))),n.QUERY_STRING=t.search.substring(1),n}async[Symbol.asyncDispose](){await this.instanceManager[Symbol.asyncDispose]()}}A=new WeakMap,Q=new WeakMap,re=new WeakMap,Y=new WeakMap,K=new WeakMap,M=new WeakMap,Z=new WeakMap,$=new WeakMap,se=new WeakMap,b=new WeakSet,be=function(e){const t=removePathPrefix(decodeURIComponent(e.pathname),p(this,M)),s=applyRewriteRules(t,this.rewriteRules),n=new URL(util.joinPaths(p(this,M),s),e.toString());for(const[o,i]of e.searchParams.entries())n.searchParams.append(o,i);return n},oe=function(e){for(const t of p(this,se))if(e===t.urlPrefix||e.startsWith(t.urlPrefix+"/")){const s=e.slice(t.urlPrefix.length);return util.joinPaths(t.fsPath,s)}return util.joinPaths(p(this,A),e)},He=function(e,t){const s=e.readFileAsBuffer(t);return new PHPResponse(200,{"content-length":[`${s.byteLength}`],"content-type":[inferMimeType(t)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},s)},Te=async function(e,t,s,n){let o;try{o=await this.instanceManager.acquirePHPInstance()}catch(a){return a instanceof MaxPhpInstancesError?StreamedPHPResponse.forHttpCode(502):StreamedPHPResponse.forHttpCode(500)}let i;try{i=await _(this,b,Le).call(this,o.php,e,t,s,n)}catch(a){throw o.reap(),a}return i.finished.finally(()=>{o==null||o.reap()}),i},Le=async function(e,t,s,n,o){let i="GET";const a={host:p(this,K),...normalizeHeaders(t.headers||{})};p(this,$)&&(a.cookie=p(this,$).getCookieRequestHeader());let l=t.body;if(typeof l=="object"&&!(l instanceof Uint8Array)){i="POST";const{bytes:u,contentType:d}=await encodeAsMultipart(l);l=u,a["content-type"]=d}const c=await e.runStream({relativeUri:ensurePathPrefix(toRelativeUrl(new URL(n.toString())),p(this,M)),protocol:p(this,Q),method:t.method||i,$_SERVER:this.prepare_$_SERVER_superglobal(s,n,o),body:l,scriptPath:o,headers:a});if(p(this,$)){const u=await c.headers;p(this,$).rememberCookiesFromResponseHeaders(u)}return c};function inferMimeType(r){const e=r.split(".").pop();return mimeTypes[e]||mimeTypes._default}function applyRewriteRules(r,e){for(const t of e)if(new RegExp(t.match).test(r)){r=r.replace(t.match,t.replacement);break}return r}function looksLikeAbsoluteUrl(r){try{return new URL(r),!0}catch{return!1}}function rotatePHPRuntime({php:r,recreateRuntime:e,maxRequests:t=400}){return r.enableRuntimeRotation({recreateRuntime:e,maxRequests:t})}async function writeFiles(r,e,t,{rmRoot:s=!1}={}){s&&await r.isDir(e)&&await r.rmdir(e,{recursive:!0});for(const[n,o]of Object.entries(t)){const i=util.joinPaths(e,n);await r.fileExists(util.dirname(i))||await r.mkdir(util.dirname(i)),o instanceof Uint8Array||typeof o=="string"?await r.writeFile(i,o):await writeFiles(r,i,o)}}const schema12={properties:{name:{type:"string"},version:{type:"string"},mode:{type:"string",const:"php-extension"},loadWithIniDirective:{$ref:"#/definitions/PHPExtensionLoadDirective",description:"The first directive of the generated startup `.ini` file. Defaults to `extension`; use `zend_extension` for Zend extensions like Xdebug. Use `false` to stage the `.so` without registering it in php.ini."},iniEntries:{type:"object",additionalProperties:{type:"string"},description:"Additional `key=value` lines for the generated startup `.ini` file."},env:{type:"object",additionalProperties:{type:"string"},description:"Environment variables added before the extension is loaded."},extensionDir:{type:"string",description:"VFS directory where PHP.wasm writes the extension `.so` file and its per-extension ini file. Defaults to `PHP_EXTENSIONS_DIR`."},artifacts:{type:"array",items:{type:"object",properties:{phpVersion:{type:"string",description:"PHP major/minor version, e.g. `8.4`."},sourcePath:{type:"string",description:"Relative to the manifest URL/base URL, or an absolute URL."},extraFiles:{$ref:"#/definitions/PHPExtensionManifestExtraFiles",description:"URL-backed files needed only by this artifact."}},required:["phpVersion","sourcePath"],additionalProperties:!1}},extraFiles:{$ref:"#/definitions/PHPExtensionManifestExtraFiles",description:"URL-backed files shared by every artifact in this manifest."}}},schema15={properties:{nodes:{items:{properties:{type:{enum:["file","directory"]}}}}}},func2=Object.prototype.hasOwnProperty,schema14={enum:["extension","zend_extension"]};function validate12(r,{instancePath:e="",parentData:t,parentDataProperty:s,rootData:n=r}={}){let o=null,i=0;const a=i;let l=!1;const c=i;if(typeof r!="string"){const d={instancePath:e,schemaPath:"#/definitions/PHPExtensionIniDirective/type",keyword:"type",params:{type:"string"},message:"must be string"};o===null?o=[d]:o.push(d),i++}if(!(r==="extension"||r==="zend_extension")){const d={instancePath:e,schemaPath:"#/definitions/PHPExtensionIniDirective/enum",keyword:"enum",params:{allowedValues:schema14.enum},message:"must be equal to one of the allowed values"};o===null?o=[d]:o.push(d),i++}var u=c===i;if(l=l||u,!l){const d=i;if(typeof r!="boolean"){const P={instancePath:e,schemaPath:"#/anyOf/1/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};o===null?o=[P]:o.push(P),i++}if(r!==!1){const P={instancePath:e,schemaPath:"#/anyOf/1/const",keyword:"const",params:{allowedValue:!1},message:"must be equal to constant"};o===null?o=[P]:o.push(P),i++}var u=d===i;l=l||u}if(l)i=a,o!==null&&(a?o.length=a:o=null);else{const d={instancePath:e,schemaPath:"#/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};return o===null?o=[d]:o.push(d),i++,validate12.errors=o,!1}return validate12.errors=o,i===0}function validate11(r,{instancePath:e="",parentData:t,parentDataProperty:s,rootData:n=r}={}){let o=null,i=0;if(i===0)if(r&&typeof r=="object"&&!Array.isArray(r)){let L;if(r.name===void 0&&(L="name")||r.artifacts===void 0&&(L="artifacts"))return validate11.errors=[{instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:L},message:"must have required property '"+L+"'"}],!1;{const O=i;for(const f in r)if(!func2.call(schema12.properties,f))return validate11.errors=[{instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:f},message:"must NOT have additional properties"}],!1;if(O===i){if(r.name!==void 0){const f=i;if(typeof r.name!="string")return validate11.errors=[{instancePath:e+"/name",schemaPath:"#/properties/name/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var a=f===i}else var a=!0;if(a){if(r.version!==void 0){const f=i;if(typeof r.version!="string")return validate11.errors=[{instancePath:e+"/version",schemaPath:"#/properties/version/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var a=f===i}else var a=!0;if(a){if(r.mode!==void 0){let f=r.mode;const R=i;if(typeof f!="string")return validate11.errors=[{instancePath:e+"/mode",schemaPath:"#/properties/mode/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(f!=="php-extension")return validate11.errors=[{instancePath:e+"/mode",schemaPath:"#/properties/mode/const",keyword:"const",params:{allowedValue:"php-extension"},message:"must be equal to constant"}],!1;var a=R===i}else var a=!0;if(a){if(r.loadWithIniDirective!==void 0){const f=i;validate12(r.loadWithIniDirective,{instancePath:e+"/loadWithIniDirective",parentData:r,parentDataProperty:"loadWithIniDirective",rootData:n})||(o=o===null?validate12.errors:o.concat(validate12.errors),i=o.length);var a=f===i}else var a=!0;if(a){if(r.iniEntries!==void 0){let f=r.iniEntries;const R=i;if(i===R)if(f&&typeof f=="object"&&!Array.isArray(f))for(const D in f){const m=i;if(typeof f[D]!="string")return validate11.errors=[{instancePath:e+"/iniEntries/"+D.replace(/~/g,"~0").replace(/\//g,"~1"),schemaPath:"#/properties/iniEntries/additionalProperties/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var l=m===i;if(!l)break}else return validate11.errors=[{instancePath:e+"/iniEntries",schemaPath:"#/properties/iniEntries/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;var a=R===i}else var a=!0;if(a){if(r.env!==void 0){let f=r.env;const R=i;if(i===R)if(f&&typeof f=="object"&&!Array.isArray(f))for(const D in f){const m=i;if(typeof f[D]!="string")return validate11.errors=[{instancePath:e+"/env/"+D.replace(/~/g,"~0").replace(/\//g,"~1"),schemaPath:"#/properties/env/additionalProperties/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var c=m===i;if(!c)break}else return validate11.errors=[{instancePath:e+"/env",schemaPath:"#/properties/env/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;var a=R===i}else var a=!0;if(a){if(r.extensionDir!==void 0){const f=i;if(typeof r.extensionDir!="string")return validate11.errors=[{instancePath:e+"/extensionDir",schemaPath:"#/properties/extensionDir/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var a=f===i}else var a=!0;if(a){if(r.artifacts!==void 0){let f=r.artifacts;const R=i;if(i===R)if(Array.isArray(f)){var u=!0;const D=f.length;for(let m=0;m<D;m++){let w=f[m];const q=i;if(i===q)if(w&&typeof w=="object"&&!Array.isArray(w)){let W;if(w.phpVersion===void 0&&(W="phpVersion")||w.sourcePath===void 0&&(W="sourcePath"))return validate11.errors=[{instancePath:e+"/artifacts/"+m,schemaPath:"#/properties/artifacts/items/required",keyword:"required",params:{missingProperty:W},message:"must have required property '"+W+"'"}],!1;{const H=i;for(const y in w)if(!(y==="phpVersion"||y==="sourcePath"||y==="extraFiles"))return validate11.errors=[{instancePath:e+"/artifacts/"+m,schemaPath:"#/properties/artifacts/items/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:y},message:"must NOT have additional properties"}],!1;if(H===i){if(w.phpVersion!==void 0){const y=i;if(typeof w.phpVersion!="string")return validate11.errors=[{instancePath:e+"/artifacts/"+m+"/phpVersion",schemaPath:"#/properties/artifacts/items/properties/phpVersion/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var d=y===i}else var d=!0;if(d){if(w.sourcePath!==void 0){const y=i;if(typeof w.sourcePath!="string")return validate11.errors=[{instancePath:e+"/artifacts/"+m+"/sourcePath",schemaPath:"#/properties/artifacts/items/properties/sourcePath/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var d=y===i}else var d=!0;if(d)if(w.extraFiles!==void 0){let y=w.extraFiles;const ne=i;if(i===i)if(y&&typeof y=="object"&&!Array.isArray(y)){const ue=i;for(const v in y)if(!(v==="vfsRoot"||v==="nodes"))return validate11.errors=[{instancePath:e+"/artifacts/"+m+"/extraFiles",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:v},message:"must NOT have additional properties"}],!1;if(ue===i){if(y.vfsRoot!==void 0){const v=i;if(typeof y.vfsRoot!="string")return validate11.errors=[{instancePath:e+"/artifacts/"+m+"/extraFiles/vfsRoot",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/vfsRoot/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var h=v===i}else var h=!0;if(h)if(y.nodes!==void 0){let v=y.nodes;const ie=i;if(i===ie)if(Array.isArray(v)){var P=!0;const Me=v.length;for(let C=0;C<Me;C++){let I=v[C];const ye=i;if(i===ye)if(I&&typeof I=="object"&&!Array.isArray(I)){let de;if(I.vfsPath===void 0&&(de="vfsPath"))return validate11.errors=[{instancePath:e+"/artifacts/"+m+"/extraFiles/nodes/"+C,schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/items/required",keyword:"required",params:{missingProperty:de},message:"must have required property '"+de+"'"}],!1;{const Ce=i;for(const T in I)if(!(T==="vfsPath"||T==="type"||T==="sourcePath"))return validate11.errors=[{instancePath:e+"/artifacts/"+m+"/extraFiles/nodes/"+C,schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/items/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:T},message:"must NOT have additional properties"}],!1;if(Ce===i){if(I.vfsPath!==void 0){const T=i;if(typeof I.vfsPath!="string")return validate11.errors=[{instancePath:e+"/artifacts/"+m+"/extraFiles/nodes/"+C+"/vfsPath",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/items/properties/vfsPath/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var S=T===i}else var S=!0;if(S){if(I.type!==void 0){let T=I.type;const Ae=i;if(typeof T!="string")return validate11.errors=[{instancePath:e+"/artifacts/"+m+"/extraFiles/nodes/"+C+"/type",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/items/properties/type/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!(T==="file"||T==="directory"))return validate11.errors=[{instancePath:e+"/artifacts/"+m+"/extraFiles/nodes/"+C+"/type",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/items/properties/type/enum",keyword:"enum",params:{allowedValues:schema15.properties.nodes.items.properties.type.enum},message:"must be equal to one of the allowed values"}],!1;var S=Ae===i}else var S=!0;if(S)if(I.sourcePath!==void 0){const T=i;if(typeof I.sourcePath!="string")return validate11.errors=[{instancePath:e+"/artifacts/"+m+"/extraFiles/nodes/"+C+"/sourcePath",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/items/properties/sourcePath/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var S=T===i}else var S=!0}}}}else return validate11.errors=[{instancePath:e+"/artifacts/"+m+"/extraFiles/nodes/"+C,schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/items/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;var P=ye===i;if(!P)break}}else return validate11.errors=[{instancePath:e+"/artifacts/"+m+"/extraFiles/nodes",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/type",keyword:"type",params:{type:"array"},message:"must be array"}],!1;var h=ie===i}else var h=!0}}else return validate11.errors=[{instancePath:e+"/artifacts/"+m+"/extraFiles",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;var d=ne===i}else var d=!0}}}}else return validate11.errors=[{instancePath:e+"/artifacts/"+m,schemaPath:"#/properties/artifacts/items/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;var u=q===i;if(!u)break}}else return validate11.errors=[{instancePath:e+"/artifacts",schemaPath:"#/properties/artifacts/type",keyword:"type",params:{type:"array"},message:"must be array"}],!1;var a=R===i}else var a=!0;if(a)if(r.extraFiles!==void 0){let f=r.extraFiles;const R=i;if(i===i)if(f&&typeof f=="object"&&!Array.isArray(f)){const m=i;for(const w in f)if(!(w==="vfsRoot"||w==="nodes"))return validate11.errors=[{instancePath:e+"/extraFiles",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:w},message:"must NOT have additional properties"}],!1;if(m===i){if(f.vfsRoot!==void 0){const w=i;if(typeof f.vfsRoot!="string")return validate11.errors=[{instancePath:e+"/extraFiles/vfsRoot",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/vfsRoot/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var N=w===i}else var N=!0;if(N)if(f.nodes!==void 0){let w=f.nodes;const q=i;if(i===q)if(Array.isArray(w)){var B=!0;const W=w.length;for(let H=0;H<W;H++){let y=w[H];const ne=i;if(i===ne)if(y&&typeof y=="object"&&!Array.isArray(y)){let ce;if(y.vfsPath===void 0&&(ce="vfsPath"))return validate11.errors=[{instancePath:e+"/extraFiles/nodes/"+H,schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/items/required",keyword:"required",params:{missingProperty:ce},message:"must have required property '"+ce+"'"}],!1;{const ue=i;for(const v in y)if(!(v==="vfsPath"||v==="type"||v==="sourcePath"))return validate11.errors=[{instancePath:e+"/extraFiles/nodes/"+H,schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/items/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:v},message:"must NOT have additional properties"}],!1;if(ue===i){if(y.vfsPath!==void 0){const v=i;if(typeof y.vfsPath!="string")return validate11.errors=[{instancePath:e+"/extraFiles/nodes/"+H+"/vfsPath",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/items/properties/vfsPath/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var k=v===i}else var k=!0;if(k){if(y.type!==void 0){let v=y.type;const ie=i;if(typeof v!="string")return validate11.errors=[{instancePath:e+"/extraFiles/nodes/"+H+"/type",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/items/properties/type/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!(v==="file"||v==="directory"))return validate11.errors=[{instancePath:e+"/extraFiles/nodes/"+H+"/type",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/items/properties/type/enum",keyword:"enum",params:{allowedValues:schema15.properties.nodes.items.properties.type.enum},message:"must be equal to one of the allowed values"}],!1;var k=ie===i}else var k=!0;if(k)if(y.sourcePath!==void 0){const v=i;if(typeof y.sourcePath!="string")return validate11.errors=[{instancePath:e+"/extraFiles/nodes/"+H+"/sourcePath",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/items/properties/sourcePath/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var k=v===i}else var k=!0}}}}else return validate11.errors=[{instancePath:e+"/extraFiles/nodes/"+H,schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/items/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;var B=ne===i;if(!B)break}}else return validate11.errors=[{instancePath:e+"/extraFiles/nodes",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/type",keyword:"type",params:{type:"array"},message:"must be array"}],!1;var N=q===i}else var N=!0}}else return validate11.errors=[{instancePath:e+"/extraFiles",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;var a=R===i}else var a=!0}}}}}}}}}}else return validate11.errors=[{instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;return validate11.errors=o,i===0}function validate10(r,{instancePath:e="",parentData:t,parentDataProperty:s,rootData:n=r}={}){let o=null,i=0;return validate11(r,{instancePath:e,parentData:t,parentDataProperty:s,rootData:n})||(o=o===null?validate11.errors:o.concat(validate11.errors),i=o.length),validate10.errors=o,i===0}const PHP_EXTENSIONS_DIR="/internal/shared/extensions",MAX_EXTENSION_SIDECAR_FILE_REQUESTS=5;async function resolvePHPExtension(r){const e=r.fetch??globalThis.fetch,t=r.source;let s=r.name,n;const o={},i=[];let a,l,c,u;if(t.format==="so"){if(s||(s=t.name),!s)throw new Error("name is required when loading an extension from direct bytes.");n=toUint8Array(t.bytes)}else if(t.format==="url"){let k;try{k=new URL(String(t.url))}catch{throw new Error(`source.url must be an absolute URL when loading a PHP extension from a direct URL. Received: ${String(t.url)}`)}if(s||(s=t.name),!s&&k.pathname.endsWith(".so")&&(s=util.basename(k.pathname).slice(0,-3)),!s)throw new Error("name is required when loading an extension from a direct URL.");n=await fetchBytes(e,k)}else{let k,L;if("manifest"in t?(k=t.manifest,t.baseUrl&&(L=new URL(String(t.baseUrl)))):(L=new URL(String(t.manifestUrl)),k=await(await e(L)).json()),!validate10(k))throw new Error(`Invalid PHP extension manifest: ${JSON.stringify(validate10.errors)}`);const O=k;if(!L)throw new Error("Manifest artifacts require a manifest URL or baseUrl so relative files can be resolved.");const f=O.artifacts.find(m=>m.phpVersion===r.phpVersion);if(!f)throw new Error(`No extension artifact found for PHP ${r.phpVersion}.`);s??(s=O.name),a=O.loadWithIniDirective,l=O.iniEntries,c=O.env,u=O.extensionDir;const R=new util.Semaphore({concurrency:MAX_EXTENSION_SIDECAR_FILE_REQUESTS}),le=[];for(const m of[O.extraFiles,f.extraFiles])for(const w of(m==null?void 0:m.nodes)??[]){const q=util.joinPaths(m.vfsRoot??"",w.vfsPath);if(w.type==="directory"){i.push(q);continue}if(!w.sourcePath)continue;const Ie=new URL(w.sourcePath,L);le.push(R.run(()=>fetchBytes(e,Ie)).then(W=>{o[q]=W}))}const[D]=await Promise.all([fetchBytes(e,new URL(f.sourcePath,L)),...le]);n=D}const d=util.normalizePath(r.extensionDir??u??PHP_EXTENSIONS_DIR);r.extraFiles&&(Object.assign(o,r.extraFiles.files),i.push(...r.extraFiles.directories??[]));const h=r.loadWithIniDirective??a??"extension",P={...l,...r.iniEntries},S=util.joinPaths(d,`${s}.so`),N=createPHPExtensionIniFile({directive:h,extensionDir:d,name:s,soPath:S,iniEntries:P}),B={...c,...r.env};return{soPath:S,soBytes:n,...N,extraFiles:{files:o,directories:i},env:Object.keys(B).length?B:void 0,extensionDir:d}}function withResolvedPHPExtensions(r,e){var n;if(!e.length)return r;const t={...r.ENV};for(const o of e){if(Object.assign(t,o.env),!o.iniPath)continue;const i=((n=t.PHP_INI_SCAN_DIR)==null?void 0:n.split(":"))??[];i.includes(o.extensionDir)||(i.push(o.extensionDir),t.PHP_INI_SCAN_DIR=i.join(":"))}const s=r.preRun??[];return{...r,ENV:t,preRun:[...s,o=>{for(const i of e)installPHPExtensionFilesSync(o.FS,i)}]}}function installPHPExtensionFilesSync(r,e){let t;if("soPath"in e)t=e;else{const s=e.extensionDir??PHP_EXTENSIONS_DIR,n=e.loadWithIniDirective??"extension",o=util.joinPaths(s,`${e.name}.so`),i=createPHPExtensionIniFile({directive:n,extensionDir:s,name:e.name,soPath:o,iniEntries:e.iniEntries});t={soPath:o,soBytes:toUint8Array(e.soBytes),...i,extraFiles:e.extraFiles,env:e.env,extensionDir:s}}if(mkdirIfMissing(r,t.extensionDir),r.writeFile(t.soPath,t.soBytes),t.iniPath&&t.iniContent!==void 0&&r.writeFile(t.iniPath,t.iniContent),t.extraFiles){const{directories:s=[],files:n}=t.extraFiles;for(const o of s)mkdirIfMissing(r,o);for(const[o,i]of Object.entries(n))mkdirIfMissing(r,util.dirname(o)),r.writeFile(o,i)}return t}function createPHPExtensionIniFile(r){if(r.directive===!1)return{};const e=[`${r.directive}=${r.soPath}`,...Object.entries(r.iniEntries??{}).map(([t,s])=>`${t}=${s}`)];return{iniPath:util.joinPaths(r.extensionDir,`${r.name}.ini`),iniContent:e.join(`
90
+ `);const o=n.reduce((l,c)=>l+c.length,0),i=new Uint8Array(o);let a=0;for(const l of n)i.set(typeof l=="string"?s.encode(l):l,a),a+=l.length;return{bytes:i,contentType:t}}function fileToUint8Array(r){return r.arrayBuffer().then(e=>new Uint8Array(e))}const _default="application/octet-stream",asx="video/x-ms-asf",atom="application/atom+xml",avi="video/x-msvideo",avif="image/avif",bin="application/octet-stream",bmp="image/x-ms-bmp",cco="application/x-cocoa",cjs="application/javascript",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",mjs="application/javascript",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,cjs,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,mjs,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 A,Q,re,Y,K,M,Z,$,se,R,Re,oe,He,Te,Le;class PHPRequestHandler{constructor(e){x(this,R);x(this,A);x(this,Q);x(this,re);x(this,Y);x(this,K);x(this,M);x(this,Z);x(this,$);x(this,se);const{documentRoot:t="/www/",absoluteUrl:s=typeof location=="object"?location.href:DEFAULT_BASE_URL,rewriteRules:n=[],pathAliases:o=[],getFileNotFoundAction:i=()=>({type:"404"})}=e,a=u=>{u.isDir(t)||u.mkdir(t),u.chdir(t),u.requestHandler=this};if(e.php)a(e.php),this.instanceManager=new SinglePHPInstanceManager({php:e.php});else if(e.phpFactory)this.instanceManager=new PHPProcessManager({phpFactory:async u=>{const d=await e.phpFactory({...u,requestHandler:this});return a(d),d},maxPhpInstances:e.maxPhpInstances});else throw new Error("Either php or phpFactory must be provided in the configuration.");E(this,$,e.cookieStore===void 0?new HttpCookieStore:e.cookieStore),E(this,A,t);const l=new URL(s);E(this,re,l.hostname),E(this,Y,l.port?Number(l.port):l.protocol==="https:"?443:80),E(this,Q,(l.protocol||"").replace(":",""));const c=p(this,Y)!==443&&p(this,Y)!==80;E(this,K,[p(this,re),c?`:${p(this,Y)}`:""].join("")),E(this,M,l.pathname.replace(/\/+$/,"")),E(this,Z,[`${p(this,Q)}://`,p(this,K),p(this,M)].join("")),this.rewriteRules=n,E(this,se,o),this.getFileNotFoundAction=i}async getPrimaryPhp(){return await this.instanceManager.getPrimaryPhp()}pathToInternalUrl(e){return e.startsWith("/")||(e=`/${e}`),`${this.absoluteUrl}${e}`}internalUrlToPath(e){const t=new URL(e,"https://playground.internal");return t.pathname.startsWith(p(this,M))&&(t.pathname=t.pathname.slice(p(this,M).length)),toRelativeUrl(t)}get absoluteUrl(){return p(this,Z)}get documentRoot(){return p(this,A)}async request(e){const t=await this.requestStreamed(e),s=await PHPResponse.fromStreamedResponse(t);return s.ok()&&s.exitCode!==0?new PHPResponse(500,s.headers,s.bytes,s.errors,s.exitCode):s}async requestStreamed(e){const t=looksLikeAbsoluteUrl(e.url),s=new URL(e.url.split("#")[0],t?void 0:DEFAULT_BASE_URL),n=_(this,R,Re).call(this,s),o=await this.getPrimaryPhp(),i=removePathPrefix(decodeURIComponent(n.pathname),p(this,M));let a=_(this,R,oe).call(this,i);if(o.isDir(a)){if(!i.endsWith("/"))return StreamedPHPResponse.fromPHPResponse(new PHPResponse(301,{location:[`${n.pathname}/`]},new Uint8Array(0)));for(const l of["index.php","index.html"]){const c=util.joinPaths(a,l);if(o.isFile(c)){a=c,n.pathname=util.joinPaths(n.pathname,l);break}}}if(!o.isFile(a)){let l=i;for(;l.startsWith("/")&&l!==util.dirname(l);){l=util.dirname(l);const c=_(this,R,oe).call(this,l);if(o.isFile(c)&&c.endsWith(".php")){a=_(this,R,oe).call(this,l);break}}}if(!o.isFile(a)){const l=this.getFileNotFoundAction(n.pathname);switch(l.type){case"response":return StreamedPHPResponse.fromPHPResponse(l.response);case"internal-redirect":a=util.joinPaths(p(this,A),l.uri);break;case"404":return StreamedPHPResponse.forHttpCode(404);default:throw new Error(`Unsupported file-not-found action type: '${l.type}'`)}}return o.isFile(a)?a.endsWith(".php")?await _(this,R,Te).call(this,e,s,n,a):StreamedPHPResponse.fromPHPResponse(_(this,R,He).call(this,o,a)):StreamedPHPResponse.forHttpCode(404)}prepare_$_SERVER_superglobal(e,t,s){const n={REMOTE_ADDR:"127.0.0.1",DOCUMENT_ROOT:p(this,A),HTTPS:p(this,Z).startsWith("https://")?"on":""};return n.REQUEST_URI=e.pathname+e.search,s.startsWith(p(this,A))&&(n.SCRIPT_NAME=s.substring(p(this,A).length),n.PHP_SELF=t.pathname,n.REQUEST_URI.startsWith(n.SCRIPT_NAME)&&(n.PATH_INFO=n.REQUEST_URI.substring(n.SCRIPT_NAME.length),n.PATH_INFO.includes("?")&&(n.PATH_INFO=n.PATH_INFO.substring(0,n.PATH_INFO.indexOf("?"))))),n.QUERY_STRING=t.search.substring(1),n}async[Symbol.asyncDispose](){await this.instanceManager[Symbol.asyncDispose]()}}A=new WeakMap,Q=new WeakMap,re=new WeakMap,Y=new WeakMap,K=new WeakMap,M=new WeakMap,Z=new WeakMap,$=new WeakMap,se=new WeakMap,R=new WeakSet,Re=function(e){const t=removePathPrefix(decodeURIComponent(e.pathname),p(this,M)),s=applyRewriteRules(t,this.rewriteRules),n=new URL(util.joinPaths(p(this,M),s),e.toString());for(const[o,i]of e.searchParams.entries())n.searchParams.append(o,i);return n},oe=function(e){for(const t of p(this,se))if(e===t.urlPrefix||e.startsWith(t.urlPrefix+"/")){const s=e.slice(t.urlPrefix.length);return util.joinPaths(t.fsPath,s)}return util.joinPaths(p(this,A),e)},He=function(e,t){const s=e.readFileAsBuffer(t);return new PHPResponse(200,{"content-length":[`${s.byteLength}`],"content-type":[inferMimeType(t)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},s)},Te=async function(e,t,s,n){let o;try{o=await this.instanceManager.acquirePHPInstance()}catch(a){return a instanceof MaxPhpInstancesError?StreamedPHPResponse.forHttpCode(502):StreamedPHPResponse.forHttpCode(500)}let i;try{i=await _(this,R,Le).call(this,o.php,e,t,s,n)}catch(a){throw o.reap(),a}return i.finished.finally(()=>{o==null||o.reap()}),i},Le=async function(e,t,s,n,o){let i="GET";const a={host:p(this,K),...normalizeHeaders(t.headers||{})};p(this,$)&&(a.cookie=p(this,$).getCookieRequestHeader());let l=t.body;if(typeof l=="object"&&!(l instanceof Uint8Array)){i="POST";const{bytes:u,contentType:d}=await encodeAsMultipart(l);l=u,a["content-type"]=d}const c=await e.runStream({relativeUri:ensurePathPrefix(toRelativeUrl(new URL(n.toString())),p(this,M)),protocol:p(this,Q),method:t.method||i,$_SERVER:this.prepare_$_SERVER_superglobal(s,n,o),body:l,scriptPath:o,headers:a});if(p(this,$)){const u=await c.headers;p(this,$).rememberCookiesFromResponseHeaders(u)}return c};function inferMimeType(r){const e=r.split(".").pop();return mimeTypes[e]||mimeTypes._default}function applyRewriteRules(r,e){for(const t of e)if(new RegExp(t.match).test(r)){r=r.replace(t.match,t.replacement);break}return r}function looksLikeAbsoluteUrl(r){try{return new URL(r),!0}catch{return!1}}function rotatePHPRuntime({php:r,recreateRuntime:e,maxRequests:t=400}){return r.enableRuntimeRotation({recreateRuntime:e,maxRequests:t})}async function writeFiles(r,e,t,{rmRoot:s=!1}={}){s&&await r.isDir(e)&&await r.rmdir(e,{recursive:!0});for(const[n,o]of Object.entries(t)){const i=util.joinPaths(e,n);await r.fileExists(util.dirname(i))||await r.mkdir(util.dirname(i)),o instanceof Uint8Array||typeof o=="string"?await r.writeFile(i,o):await writeFiles(r,i,o)}}const schema12={properties:{name:{type:"string"},version:{type:"string"},mode:{type:"string",const:"php-extension"},loadWithIniDirective:{$ref:"#/definitions/PHPExtensionLoadDirective",description:"The first directive of the generated startup `.ini` file. Defaults to `extension`; use `zend_extension` for Zend extensions like Xdebug. Use `false` to stage the `.so` without registering it in php.ini."},iniEntries:{type:"object",additionalProperties:{type:"string"},description:"Additional `key=value` lines for the generated startup `.ini` file."},env:{type:"object",additionalProperties:{type:"string"},description:"Environment variables added before the extension is loaded."},extensionDir:{type:"string",description:"VFS directory where PHP.wasm writes the extension `.so` file and its per-extension ini file. Defaults to `PHP_EXTENSIONS_DIR`."},artifacts:{type:"array",items:{type:"object",properties:{phpVersion:{type:"string",description:"PHP major/minor version, e.g. `8.4`."},sourcePath:{type:"string",description:"Relative to the manifest URL/base URL, or an absolute URL."},extraFiles:{$ref:"#/definitions/PHPExtensionManifestExtraFiles",description:"URL-backed files needed only by this artifact."}},required:["phpVersion","sourcePath"],additionalProperties:!1}},extraFiles:{$ref:"#/definitions/PHPExtensionManifestExtraFiles",description:"URL-backed files shared by every artifact in this manifest."}}},schema15={properties:{nodes:{items:{properties:{type:{enum:["file","directory"]}}}}}},func2=Object.prototype.hasOwnProperty,schema14={enum:["extension","zend_extension"]};function validate12(r,{instancePath:e="",parentData:t,parentDataProperty:s,rootData:n=r}={}){let o=null,i=0;const a=i;let l=!1;const c=i;if(typeof r!="string"){const d={instancePath:e,schemaPath:"#/definitions/PHPExtensionIniDirective/type",keyword:"type",params:{type:"string"},message:"must be string"};o===null?o=[d]:o.push(d),i++}if(!(r==="extension"||r==="zend_extension")){const d={instancePath:e,schemaPath:"#/definitions/PHPExtensionIniDirective/enum",keyword:"enum",params:{allowedValues:schema14.enum},message:"must be equal to one of the allowed values"};o===null?o=[d]:o.push(d),i++}var u=c===i;if(l=l||u,!l){const d=i;if(typeof r!="boolean"){const P={instancePath:e,schemaPath:"#/anyOf/1/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};o===null?o=[P]:o.push(P),i++}if(r!==!1){const P={instancePath:e,schemaPath:"#/anyOf/1/const",keyword:"const",params:{allowedValue:!1},message:"must be equal to constant"};o===null?o=[P]:o.push(P),i++}var u=d===i;l=l||u}if(l)i=a,o!==null&&(a?o.length=a:o=null);else{const d={instancePath:e,schemaPath:"#/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};return o===null?o=[d]:o.push(d),i++,validate12.errors=o,!1}return validate12.errors=o,i===0}function validate11(r,{instancePath:e="",parentData:t,parentDataProperty:s,rootData:n=r}={}){let o=null,i=0;if(i===0)if(r&&typeof r=="object"&&!Array.isArray(r)){let L;if(r.name===void 0&&(L="name")||r.artifacts===void 0&&(L="artifacts"))return validate11.errors=[{instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:L},message:"must have required property '"+L+"'"}],!1;{const O=i;for(const f in r)if(!func2.call(schema12.properties,f))return validate11.errors=[{instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:f},message:"must NOT have additional properties"}],!1;if(O===i){if(r.name!==void 0){const f=i;if(typeof r.name!="string")return validate11.errors=[{instancePath:e+"/name",schemaPath:"#/properties/name/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var a=f===i}else var a=!0;if(a){if(r.version!==void 0){const f=i;if(typeof r.version!="string")return validate11.errors=[{instancePath:e+"/version",schemaPath:"#/properties/version/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var a=f===i}else var a=!0;if(a){if(r.mode!==void 0){let f=r.mode;const b=i;if(typeof f!="string")return validate11.errors=[{instancePath:e+"/mode",schemaPath:"#/properties/mode/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(f!=="php-extension")return validate11.errors=[{instancePath:e+"/mode",schemaPath:"#/properties/mode/const",keyword:"const",params:{allowedValue:"php-extension"},message:"must be equal to constant"}],!1;var a=b===i}else var a=!0;if(a){if(r.loadWithIniDirective!==void 0){const f=i;validate12(r.loadWithIniDirective,{instancePath:e+"/loadWithIniDirective",parentData:r,parentDataProperty:"loadWithIniDirective",rootData:n})||(o=o===null?validate12.errors:o.concat(validate12.errors),i=o.length);var a=f===i}else var a=!0;if(a){if(r.iniEntries!==void 0){let f=r.iniEntries;const b=i;if(i===b)if(f&&typeof f=="object"&&!Array.isArray(f))for(const D in f){const m=i;if(typeof f[D]!="string")return validate11.errors=[{instancePath:e+"/iniEntries/"+D.replace(/~/g,"~0").replace(/\//g,"~1"),schemaPath:"#/properties/iniEntries/additionalProperties/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var l=m===i;if(!l)break}else return validate11.errors=[{instancePath:e+"/iniEntries",schemaPath:"#/properties/iniEntries/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;var a=b===i}else var a=!0;if(a){if(r.env!==void 0){let f=r.env;const b=i;if(i===b)if(f&&typeof f=="object"&&!Array.isArray(f))for(const D in f){const m=i;if(typeof f[D]!="string")return validate11.errors=[{instancePath:e+"/env/"+D.replace(/~/g,"~0").replace(/\//g,"~1"),schemaPath:"#/properties/env/additionalProperties/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var c=m===i;if(!c)break}else return validate11.errors=[{instancePath:e+"/env",schemaPath:"#/properties/env/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;var a=b===i}else var a=!0;if(a){if(r.extensionDir!==void 0){const f=i;if(typeof r.extensionDir!="string")return validate11.errors=[{instancePath:e+"/extensionDir",schemaPath:"#/properties/extensionDir/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var a=f===i}else var a=!0;if(a){if(r.artifacts!==void 0){let f=r.artifacts;const b=i;if(i===b)if(Array.isArray(f)){var u=!0;const D=f.length;for(let m=0;m<D;m++){let w=f[m];const q=i;if(i===q)if(w&&typeof w=="object"&&!Array.isArray(w)){let W;if(w.phpVersion===void 0&&(W="phpVersion")||w.sourcePath===void 0&&(W="sourcePath"))return validate11.errors=[{instancePath:e+"/artifacts/"+m,schemaPath:"#/properties/artifacts/items/required",keyword:"required",params:{missingProperty:W},message:"must have required property '"+W+"'"}],!1;{const H=i;for(const y in w)if(!(y==="phpVersion"||y==="sourcePath"||y==="extraFiles"))return validate11.errors=[{instancePath:e+"/artifacts/"+m,schemaPath:"#/properties/artifacts/items/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:y},message:"must NOT have additional properties"}],!1;if(H===i){if(w.phpVersion!==void 0){const y=i;if(typeof w.phpVersion!="string")return validate11.errors=[{instancePath:e+"/artifacts/"+m+"/phpVersion",schemaPath:"#/properties/artifacts/items/properties/phpVersion/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var d=y===i}else var d=!0;if(d){if(w.sourcePath!==void 0){const y=i;if(typeof w.sourcePath!="string")return validate11.errors=[{instancePath:e+"/artifacts/"+m+"/sourcePath",schemaPath:"#/properties/artifacts/items/properties/sourcePath/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var d=y===i}else var d=!0;if(d)if(w.extraFiles!==void 0){let y=w.extraFiles;const ne=i;if(i===i)if(y&&typeof y=="object"&&!Array.isArray(y)){const ue=i;for(const v in y)if(!(v==="vfsRoot"||v==="nodes"))return validate11.errors=[{instancePath:e+"/artifacts/"+m+"/extraFiles",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:v},message:"must NOT have additional properties"}],!1;if(ue===i){if(y.vfsRoot!==void 0){const v=i;if(typeof y.vfsRoot!="string")return validate11.errors=[{instancePath:e+"/artifacts/"+m+"/extraFiles/vfsRoot",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/vfsRoot/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var h=v===i}else var h=!0;if(h)if(y.nodes!==void 0){let v=y.nodes;const ie=i;if(i===ie)if(Array.isArray(v)){var P=!0;const Me=v.length;for(let C=0;C<Me;C++){let I=v[C];const ye=i;if(i===ye)if(I&&typeof I=="object"&&!Array.isArray(I)){let de;if(I.vfsPath===void 0&&(de="vfsPath"))return validate11.errors=[{instancePath:e+"/artifacts/"+m+"/extraFiles/nodes/"+C,schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/items/required",keyword:"required",params:{missingProperty:de},message:"must have required property '"+de+"'"}],!1;{const Ce=i;for(const T in I)if(!(T==="vfsPath"||T==="type"||T==="sourcePath"))return validate11.errors=[{instancePath:e+"/artifacts/"+m+"/extraFiles/nodes/"+C,schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/items/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:T},message:"must NOT have additional properties"}],!1;if(Ce===i){if(I.vfsPath!==void 0){const T=i;if(typeof I.vfsPath!="string")return validate11.errors=[{instancePath:e+"/artifacts/"+m+"/extraFiles/nodes/"+C+"/vfsPath",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/items/properties/vfsPath/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var S=T===i}else var S=!0;if(S){if(I.type!==void 0){let T=I.type;const Ae=i;if(typeof T!="string")return validate11.errors=[{instancePath:e+"/artifacts/"+m+"/extraFiles/nodes/"+C+"/type",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/items/properties/type/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!(T==="file"||T==="directory"))return validate11.errors=[{instancePath:e+"/artifacts/"+m+"/extraFiles/nodes/"+C+"/type",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/items/properties/type/enum",keyword:"enum",params:{allowedValues:schema15.properties.nodes.items.properties.type.enum},message:"must be equal to one of the allowed values"}],!1;var S=Ae===i}else var S=!0;if(S)if(I.sourcePath!==void 0){const T=i;if(typeof I.sourcePath!="string")return validate11.errors=[{instancePath:e+"/artifacts/"+m+"/extraFiles/nodes/"+C+"/sourcePath",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/items/properties/sourcePath/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var S=T===i}else var S=!0}}}}else return validate11.errors=[{instancePath:e+"/artifacts/"+m+"/extraFiles/nodes/"+C,schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/items/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;var P=ye===i;if(!P)break}}else return validate11.errors=[{instancePath:e+"/artifacts/"+m+"/extraFiles/nodes",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/type",keyword:"type",params:{type:"array"},message:"must be array"}],!1;var h=ie===i}else var h=!0}}else return validate11.errors=[{instancePath:e+"/artifacts/"+m+"/extraFiles",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;var d=ne===i}else var d=!0}}}}else return validate11.errors=[{instancePath:e+"/artifacts/"+m,schemaPath:"#/properties/artifacts/items/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;var u=q===i;if(!u)break}}else return validate11.errors=[{instancePath:e+"/artifacts",schemaPath:"#/properties/artifacts/type",keyword:"type",params:{type:"array"},message:"must be array"}],!1;var a=b===i}else var a=!0;if(a)if(r.extraFiles!==void 0){let f=r.extraFiles;const b=i;if(i===i)if(f&&typeof f=="object"&&!Array.isArray(f)){const m=i;for(const w in f)if(!(w==="vfsRoot"||w==="nodes"))return validate11.errors=[{instancePath:e+"/extraFiles",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:w},message:"must NOT have additional properties"}],!1;if(m===i){if(f.vfsRoot!==void 0){const w=i;if(typeof f.vfsRoot!="string")return validate11.errors=[{instancePath:e+"/extraFiles/vfsRoot",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/vfsRoot/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var N=w===i}else var N=!0;if(N)if(f.nodes!==void 0){let w=f.nodes;const q=i;if(i===q)if(Array.isArray(w)){var B=!0;const W=w.length;for(let H=0;H<W;H++){let y=w[H];const ne=i;if(i===ne)if(y&&typeof y=="object"&&!Array.isArray(y)){let ce;if(y.vfsPath===void 0&&(ce="vfsPath"))return validate11.errors=[{instancePath:e+"/extraFiles/nodes/"+H,schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/items/required",keyword:"required",params:{missingProperty:ce},message:"must have required property '"+ce+"'"}],!1;{const ue=i;for(const v in y)if(!(v==="vfsPath"||v==="type"||v==="sourcePath"))return validate11.errors=[{instancePath:e+"/extraFiles/nodes/"+H,schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/items/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:v},message:"must NOT have additional properties"}],!1;if(ue===i){if(y.vfsPath!==void 0){const v=i;if(typeof y.vfsPath!="string")return validate11.errors=[{instancePath:e+"/extraFiles/nodes/"+H+"/vfsPath",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/items/properties/vfsPath/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var F=v===i}else var F=!0;if(F){if(y.type!==void 0){let v=y.type;const ie=i;if(typeof v!="string")return validate11.errors=[{instancePath:e+"/extraFiles/nodes/"+H+"/type",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/items/properties/type/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!(v==="file"||v==="directory"))return validate11.errors=[{instancePath:e+"/extraFiles/nodes/"+H+"/type",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/items/properties/type/enum",keyword:"enum",params:{allowedValues:schema15.properties.nodes.items.properties.type.enum},message:"must be equal to one of the allowed values"}],!1;var F=ie===i}else var F=!0;if(F)if(y.sourcePath!==void 0){const v=i;if(typeof y.sourcePath!="string")return validate11.errors=[{instancePath:e+"/extraFiles/nodes/"+H+"/sourcePath",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/items/properties/sourcePath/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var F=v===i}else var F=!0}}}}else return validate11.errors=[{instancePath:e+"/extraFiles/nodes/"+H,schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/items/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;var B=ne===i;if(!B)break}}else return validate11.errors=[{instancePath:e+"/extraFiles/nodes",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/properties/nodes/type",keyword:"type",params:{type:"array"},message:"must be array"}],!1;var N=q===i}else var N=!0}}else return validate11.errors=[{instancePath:e+"/extraFiles",schemaPath:"#/definitions/PHPExtensionManifestExtraFiles/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;var a=b===i}else var a=!0}}}}}}}}}}else return validate11.errors=[{instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;return validate11.errors=o,i===0}function validate10(r,{instancePath:e="",parentData:t,parentDataProperty:s,rootData:n=r}={}){let o=null,i=0;return validate11(r,{instancePath:e,parentData:t,parentDataProperty:s,rootData:n})||(o=o===null?validate11.errors:o.concat(validate11.errors),i=o.length),validate10.errors=o,i===0}const PHP_EXTENSIONS_DIR="/internal/shared/extensions",MAX_EXTENSION_SIDECAR_FILE_REQUESTS=5;async function resolvePHPExtension(r){const e=r.fetch??globalThis.fetch,t=r.source;let s=r.name,n;const o={},i=[];let a,l,c,u;if(t.format==="so"){if(s||(s=t.name),!s)throw new Error("name is required when loading an extension from direct bytes.");n=toUint8Array(t.bytes)}else if(t.format==="url"){let F;try{F=new URL(String(t.url))}catch{throw new Error(`source.url must be an absolute URL when loading a PHP extension from a direct URL. Received: ${String(t.url)}`)}if(s||(s=t.name),!s&&F.pathname.endsWith(".so")&&(s=util.basename(F.pathname).slice(0,-3)),!s)throw new Error("name is required when loading an extension from a direct URL.");n=await fetchBytes(e,F)}else{let F,L;if("manifest"in t?(F=t.manifest,t.baseUrl&&(L=new URL(String(t.baseUrl)))):(L=new URL(String(t.manifestUrl)),F=await(await e(L)).json()),!validate10(F))throw new Error(`Invalid PHP extension manifest: ${JSON.stringify(validate10.errors)}`);const O=F;if(!L)throw new Error("Manifest artifacts require a manifest URL or baseUrl so relative files can be resolved.");const f=O.artifacts.find(m=>m.phpVersion===r.phpVersion);if(!f)throw new Error(`No extension artifact found for PHP ${r.phpVersion}.`);s??(s=O.name),a=O.loadWithIniDirective,l=O.iniEntries,c=O.env,u=O.extensionDir;const b=new util.Semaphore({concurrency:MAX_EXTENSION_SIDECAR_FILE_REQUESTS}),le=[];for(const m of[O.extraFiles,f.extraFiles])for(const w of(m==null?void 0:m.nodes)??[]){const q=util.joinPaths(m.vfsRoot??"",w.vfsPath);if(w.type==="directory"){i.push(q);continue}if(!w.sourcePath)continue;const Ie=new URL(w.sourcePath,L);le.push(b.run(()=>fetchBytes(e,Ie)).then(W=>{o[q]=W}))}const[D]=await Promise.all([fetchBytes(e,new URL(f.sourcePath,L)),...le]);n=D}const d=util.normalizePath(r.extensionDir??u??PHP_EXTENSIONS_DIR);r.extraFiles&&(Object.assign(o,r.extraFiles.files),i.push(...r.extraFiles.directories??[]));const h=r.loadWithIniDirective??a??"extension",P={...l,...r.iniEntries},S=util.joinPaths(d,`${s}.so`),N=createPHPExtensionIniFile({directive:h,extensionDir:d,name:s,soPath:S,iniEntries:P}),B={...c,...r.env};return{soPath:S,soBytes:n,...N,extraFiles:{files:o,directories:i},env:Object.keys(B).length?B:void 0,extensionDir:d}}function withResolvedPHPExtensions(r,e){var n;if(!e.length)return r;const t={...r.ENV};for(const o of e){if(Object.assign(t,o.env),!o.iniPath)continue;const i=((n=t.PHP_INI_SCAN_DIR)==null?void 0:n.split(":"))??[];i.includes(o.extensionDir)||(i.push(o.extensionDir),t.PHP_INI_SCAN_DIR=i.join(":"))}const s=r.preRun??[];return{...r,ENV:t,preRun:[...s,o=>{for(const i of e)installPHPExtensionFilesSync(o.FS,i)}]}}function installPHPExtensionFilesSync(r,e){let t;if("soPath"in e)t=e;else{const s=e.extensionDir??PHP_EXTENSIONS_DIR,n=e.loadWithIniDirective??"extension",o=util.joinPaths(s,`${e.name}.so`),i=createPHPExtensionIniFile({directive:n,extensionDir:s,name:e.name,soPath:o,iniEntries:e.iniEntries});t={soPath:o,soBytes:toUint8Array(e.soBytes),...i,extraFiles:e.extraFiles,env:e.env,extensionDir:s}}if(mkdirIfMissing(r,t.extensionDir),r.writeFile(t.soPath,t.soBytes),t.iniPath&&t.iniContent!==void 0&&r.writeFile(t.iniPath,t.iniContent),t.extraFiles){const{directories:s=[],files:n}=t.extraFiles;for(const o of s)mkdirIfMissing(r,o);for(const[o,i]of Object.entries(n))mkdirIfMissing(r,util.dirname(o)),r.writeFile(o,i)}return t}function createPHPExtensionIniFile(r){if(r.directive===!1)return{};const e=[`${r.directive}=${r.soPath}`,...Object.entries(r.iniEntries??{}).map(([t,s])=>`${t}=${s}`)];return{iniPath:util.joinPaths(r.extensionDir,`${r.name}.ini`),iniContent:e.join(`
91
91
  `)}}function mkdirIfMissing(r,e){FSHelpers.fileExists(r,e)||r.mkdirTree(e)}async function fetchBytes(r,e){const t=await r(e);if(!t.ok)throw new Error(`Failed to fetch ${String(e)}: ${t.status}`);return new Uint8Array(await t.arrayBuffer())}function toUint8Array(r){return r instanceof Uint8Array?r:new Uint8Array(r)}function isLegacyPhpInstance(r){var n;const e=Object.getOwnPropertySymbols(r)[0],t=r[e],s=(n=t==null?void 0:t.phpVersion)==null?void 0:n.major;return typeof s=="number"&&s<7}function ensureProxyFSHasMmapSupport(r){const e=Object.getOwnPropertySymbols(r)[0],t=r[e],s=t.PROXYFS,n=t.FS;s.stream_ops.mmap||(s.stream_ops.mmap=function(o,i,a,l,c){if(!n.isFile(o.node.mode))throw new n.ErrnoError(19);if(a!==0)throw new n.ErrnoError(22);const u=t.malloc(i);if(!u)throw new n.ErrnoError(48);const d=t.HEAPU8.subarray(u,u+i);let h=0;for(;h<i;){const P=o.stream_ops.read(o,d,h,i-h,h);if(P<=0)break;h+=P}if(h!==i)throw t.free(u),new n.ErrnoError(5);return{ptr:u,allocated:!0}},s.stream_ops.msync=function(o,i,a,l,c){return c&2||o.stream_ops.write(o,i,a,l,a,!1),0})}async function proxyFileSystem(r,e,t){const s=isLegacyPhpInstance(e),n=Object.getOwnPropertySymbols(r)[0];for(const o of t)r.fileExists(o)||r.mkdir(o),e.mkdir(o),await e.mount(o,i=>{s||ensureProxyFSHasMmapSupport(i);const a=Object.getOwnPropertySymbols(i)[0];return i[a].FS.mount(i[a].PROXYFS,{root:o,fs:r[n].FS},o),()=>{try{i[a].FS.unmount(o)}catch{}}})}function isPathToSharedFS(r,e){var o;const t=Object.getOwnPropertySymbols(r)[0],n=r[t].FS.lookupPath(e,{noent_okay:!0});return((o=n==null?void 0:n.node)==null?void 0:o.isSharedFS)??!1}function sandboxedSpawnHandlerFactory(r){return util.createSpawnHandler(async function(e,t,s){t.notifySpawn(),(e==null?void 0:e[0])==="/bin/sh"&&(e==null?void 0:e[1])==="-c"&&typeof e[2]=="string"&&(e=util.splitShellCommand(e[2])),e[0]==="exec"&&e.shift(),(e[0].endsWith(".php")||e[0].endsWith(".phar"))&&e.unshift("php");const n=e[0].split("/").pop();if(e[0]==="/usr/bin/env"&&e[1]==="stty"&&e[2]==="size")t.stdout("18 140"),t.exit(0);else if(n==="tput"&&e[1]==="cols")t.stdout("140"),t.exit(0);else if(n==="less"){t.on("stdin",a=>{t.stdout(a)}),await new Promise(a=>{t.childProcess.stdin.on("finish",()=>{a(!0)})}),t.exit(0);return}if(!["php","ls","pwd"].includes(n??"")){t.exit(127);return}if(!r){logger.logger.warn("Tried to spawn a PHP subprocess, but the sandboxed spawn handler was created without a getPHPInstance function."),t.exit(127);return}const{php:o,reap:i}=await r();try{s.cwd&&await o.chdir(s.cwd);const a=await o.cwd();switch(n){case"php":{const l=await o.cli(e,{env:{...s.env,SCRIPT_PATH:e[1],SHELL_PIPE:"0"}});l.stdout.pipeTo(new WritableStream({write(c){t.stdout(c)}})),l.stderr.pipeTo(new WritableStream({write(c){t.stderr(c)}})),t.exit(await l.exitCode);break}case"ls":{const l=await o.listFiles(e[1]??a);for(const c of l)t.stdout(c+`
92
92
  `);await new Promise(c=>setTimeout(c,10)),t.exit(0);break}case"pwd":{t.stdout(a+`
93
93
  `),await new Promise(l=>setTimeout(l,10)),t.exit(0);break}}}catch(a){const l=a instanceof Error?a.message+`
@@ -101,5 +101,5 @@ ${JSON.stringify(r.headers,null,2)}
101
101
  * @license
102
102
  * Copyright 2019 Google LLC
103
103
  * SPDX-License-Identifier: Apache-2.0
104
- */const WireValueType={RAW:"RAW",HANDLER:"HANDLER"},MessageType={GET:"GET",SET:"SET",APPLY:"APPLY",CONSTRUCT:"CONSTRUCT",ENDPOINT:"ENDPOINT",RELEASE:"RELEASE"},isObject=r=>typeof r=="object"&&r!==null||typeof r=="function",proxyTransferHandler={canHandle:r=>isObject(r)&&r[proxyMarker],serialize(r){const{port1:e,port2:t}=new MessageChannel;return expose(r,e),[t,[t]]},deserialize(r){return r.start(),wrap(r)}},throwTransferHandler$1={canHandle:r=>isObject(r)&&throwMarker in r,serialize({value:r}){let e;return r instanceof Error?e={isError:!0,value:{message:r.message,name:r.name,stack:r.stack}}:e={isError:!1,value:r},[e,[]]},deserialize(r){throw r.isError?Object.assign(new Error(r.value.message),r.value):r.value}},transferHandlers=new Map([["proxy",proxyTransferHandler],["throw",throwTransferHandler$1]]);function isAllowedOrigin(r,e){for(const t of r)if(e===t||t==="*"||t instanceof RegExp&&t.test(e))return!0;return!1}function expose(r,e=globalThis,t=["*"],s){e.addEventListener("message",function n(o){if(!o||!o.data)return;if(!isAllowedOrigin(t,o.origin)){console.warn(`Invalid origin '${o.origin}' for comlink proxy`);return}const{id:i,type:a,path:l}={path:[],...o.data},c=(o.data.argumentList||[]).map(fromWireValue);let u;try{const d=l.slice(0,-1).reduce((P,S)=>P[S],r),h=l.reduce((P,S)=>P[S],r);switch(a){case MessageType.GET:u=h;break;case MessageType.SET:d[l.slice(-1)[0]]=fromWireValue(o.data.value),u=!0;break;case MessageType.APPLY:u=h.apply(d,c);break;case MessageType.CONSTRUCT:{const P=new h(...c);u=proxy(P)}break;case MessageType.ENDPOINT:{const{port1:P,port2:S}=new MessageChannel;expose(r,S),u=transfer(P,[P])}break;case MessageType.RELEASE:u=void 0;break;default:return}}catch(d){u={value:d,[throwMarker]:0}}Promise.resolve(u).catch(d=>({value:d,[throwMarker]:0})).then(d=>{const[h,P]=toWireValue(d);e.postMessage({...h,id:i},P),a===MessageType.RELEASE&&(e.removeEventListener("message",n),closeEndPoint(e),finalizer in r&&typeof r[finalizer]=="function"&&r[finalizer]())}).catch(()=>{const[d,h]=toWireValue({value:new TypeError("Unserializable return value"),[throwMarker]:0});e.postMessage({...d,id:i},h)}).finally(()=>{s==null||s(o)})}),e.start&&e.start()}function isMessagePort(r){return r.constructor.name==="MessagePort"}function closeEndPoint(r){isMessagePort(r)&&r.close()}function wrap(r,e){const t=new Map;return r.addEventListener("message",function(n){const{data:o}=n;if(!o||!o.id)return;const i=t.get(o.id);if(i)try{i(o)}finally{t.delete(o.id)}}),createProxy(r,t,[],e)}function throwIfProxyReleased(r){if(r)throw new Error("Proxy has been released and is not useable")}function releaseEndpoint(r){return requestResponseMessage(r,new Map,{type:MessageType.RELEASE}).then(()=>{closeEndPoint(r)})}const proxyCounter=new WeakMap,proxyFinalizers="FinalizationRegistry"in globalThis&&new FinalizationRegistry(r=>{const e=(proxyCounter.get(r)||0)-1;proxyCounter.set(r,e),e===0&&releaseEndpoint(r)});function registerProxy(r,e){const t=(proxyCounter.get(e)||0)+1;proxyCounter.set(e,t),proxyFinalizers&&proxyFinalizers.register(r,e,r)}function unregisterProxy(r){proxyFinalizers&&proxyFinalizers.unregister(r)}function createProxy(r,e,t=[],s=function(){}){let n=!1;const o=new Proxy(s,{get(i,a){if(throwIfProxyReleased(n),a===releaseProxy)return()=>{unregisterProxy(o),releaseEndpoint(r),e.clear(),n=!0};if(a==="then"){if(t.length===0)return{then:()=>o};const l=requestResponseMessage(r,e,{type:MessageType.GET,path:t.map(c=>c.toString())}).then(fromWireValue);return l.then.bind(l)}return createProxy(r,e,[...t,a])},set(i,a,l){throwIfProxyReleased(n);const[c,u]=toWireValue(l);return requestResponseMessage(r,e,{type:MessageType.SET,path:[...t,a].map(d=>d.toString()),value:c},u).then(fromWireValue)},apply(i,a,l){throwIfProxyReleased(n);const c=t[t.length-1];if(c===createEndpoint)return requestResponseMessage(r,e,{type:MessageType.ENDPOINT}).then(fromWireValue);if(c==="bind")return createProxy(r,e,t.slice(0,-1));const[u,d]=processArguments(l);return requestResponseMessage(r,e,{type:MessageType.APPLY,path:t.map(h=>h.toString()),argumentList:u},d).then(fromWireValue)},construct(i,a){throwIfProxyReleased(n);const[l,c]=processArguments(a);return requestResponseMessage(r,e,{type:MessageType.CONSTRUCT,path:t.map(u=>u.toString()),argumentList:l},c).then(fromWireValue)}});return registerProxy(o,r),o}function myFlat(r){return Array.prototype.concat.apply([],r)}function processArguments(r){const e=r.map(toWireValue);return[e.map(t=>t[0]),myFlat(e.map(t=>t[1]))]}const transferCache=new WeakMap;function transfer(r,e){return transferCache.set(r,e),r}function proxy(r){return Object.assign(r,{[proxyMarker]:!0})}function windowEndpoint(r,e=globalThis,t="*"){return{postMessage:(s,n)=>r.postMessage(s,t,n),addEventListener:e.addEventListener.bind(e),removeEventListener:e.removeEventListener.bind(e)}}function toWireValue(r){for(const[e,t]of transferHandlers)if(t.canHandle(r)){const[s,n]=t.serialize(r);return[{type:WireValueType.HANDLER,name:e,value:s},n]}return[{type:WireValueType.RAW,value:r},transferCache.get(r)||[]]}function fromWireValue(r){switch(r.type){case WireValueType.HANDLER:return transferHandlers.get(r.name).deserialize(r.value);case WireValueType.RAW:return r.value}}function requestResponseMessage(r,e,t,s){return new Promise(n=>{const o=generateUUID();e.set(o,n),r.start&&r.start(),r.postMessage({id:o,...t},s)})}function generateUUID(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}function nodeEndpoint(r){const e=new WeakMap;return{postMessage:r.postMessage.bind(r),addEventListener:(t,s)=>{const n=o=>{"handleEvent"in s?s.handleEvent({data:o}):s({data:o})};r.on("message",n),e.set(s,n)},removeEventListener:(t,s)=>{const n=e.get(s);n&&(r.off("message",n),e.delete(s))},start:r.start&&r.start.bind(r)}}const proxyByListener=new WeakMap;function nodeProcessEndpoint(r){const e=r||process;if(typeof e.send!="function")throw new Error("IPC channel is not available. Did you forget to fork the process?");const t=e;return{postMessage(s,n){var o;if(n&&n.length>0)throw new Error("Transferable objects are not supported for nodeProcessEndpoint");(o=t.send)==null||o.call(t,s)},addEventListener(s,n){const o=typeof n=="function"?i=>n({data:i}):i=>n.handleEvent({data:i});proxyByListener.set(n,o),t.addListener(s,o)},removeEventListener(s,n){const o=proxyByListener.get(n);o&&(proxyByListener.delete(n),t.removeListener(s,o))},start(){}}}const list=[Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError,globalThis.DOMException,globalThis.AssertionError,globalThis.SystemError].filter(Boolean).map(r=>[r.name,r]),errorConstructors=new Map(list);class NonError extends Error{constructor(e){super(NonError._prepareSuperMessage(e)),this.name="NonError"}static _prepareSuperMessage(e){try{return JSON.stringify(e)}catch{return String(e)}}}const errorProperties=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1},{property:"errors",enumerable:!1}],toJsonWasCalled=new WeakSet,toJSON=r=>{toJsonWasCalled.add(r);const e=r.toJSON();return toJsonWasCalled.delete(r),e},newError=r=>{const e=errorConstructors.get(r)??Error;return e===AggregateError?new e([]):new e},destroyCircular=({from:r,seen:e,to:t,forceEnumerable:s,maxDepth:n,depth:o,useToJSON:i,serialize:a})=>{if(t||(Array.isArray(r)?t=[]:!a&&isErrorLike(r)?t=newError(r.name):t={}),e.push(r),o>=n)return t;if(i&&typeof r.toJSON=="function"&&!toJsonWasCalled.has(r))return toJSON(r);const l=c=>destroyCircular({from:c,seen:[...e],forceEnumerable:s,maxDepth:n,depth:o,useToJSON:i,serialize:a});for(const[c,u]of Object.entries(r)){if(u&&u instanceof Uint8Array&&u.constructor.name==="Buffer"){t[c]="[object Buffer]";continue}if(u!==null&&typeof u=="object"&&typeof u.pipe=="function"){t[c]="[object Stream]";continue}if(typeof u!="function"){if(!u||typeof u!="object"){try{t[c]=u}catch{}continue}if(!e.includes(r[c])){o++,t[c]=l(r[c]);continue}t[c]="[Circular]"}}if(a||t instanceof Error)for(const{property:c,enumerable:u}of errorProperties)r[c]!==void 0&&r[c]!==null&&Object.defineProperty(t,c,{value:isErrorLike(r[c])||Array.isArray(r[c])?l(r[c]):r[c],enumerable:s?!0:u,configurable:!0,writable:!0});return t};function serializeError(r,e={}){const{maxDepth:t=Number.POSITIVE_INFINITY,useToJSON:s=!0}=e;return typeof r=="object"&&r!==null?destroyCircular({from:r,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:s,serialize:!0}):typeof r=="function"?`[Function: ${r.name||"anonymous"}]`:r}function deserializeError(r,e={}){const{maxDepth:t=Number.POSITIVE_INFINITY}=e;return r instanceof Error?r:isMinimumViableSerializedError(r)?destroyCircular({from:r,seen:[],to:newError(r.name),maxDepth:t,depth:0,serialize:!1}):new NonError(r)}function isErrorLike(r){return!!r&&typeof r=="object"&&typeof r.name=="string"&&typeof r.message=="string"&&typeof r.stack=="string"}function isMinimumViableSerializedError(r){return!!r&&typeof r=="object"&&typeof r.message=="string"&&!Array.isArray(r)}const releaseApiProxy=releaseProxy;async function consumeAPISync(r){setupTransferHandlers();const e=await NodeSABSyncReceiveMessageTransport.create();return wrapSync(r,e)}function consumeAPI(r,e=void 0){setupTransferHandlers();let t;if(typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u")if("postMessage"in r)t=nodeEndpoint(r);else if("send"in r&&"addListener"in r)t=nodeProcessEndpoint(r);else throw new Error("consumeAPI: remote does not look like a Worker, MessagePort, or Process");else t=r instanceof Worker?r:windowEndpoint(r,e);const n=wrap(t),o=proxyClone(n);return new Proxy(o,{get:(i,a)=>a==="isConnected"?async()=>{for(;;)try{await runWithTimeout(n.isConnected(),200);break}catch{}}:n[a]})}async function runWithTimeout(r,e){return new Promise((t,s)=>{setTimeout(s,e),r.then(t)})}function exposeAPI(r,e,t){const{setReady:s,setFailed:n,exposedApi:o}=prepareForExpose(r,e);let i;if(t)if("addEventListener"in t)i=t;else if("postMessage"in t)i=nodeEndpoint(t);else if("send"in t&&"addListener"in t)i=nodeProcessEndpoint(t);else throw new Error("exposeAPI: targetWorker does not look like a Worker, MessagePort, or Process");else i=typeof window<"u"?windowEndpoint(self.parent):void 0;return expose(o,i),[s,n,o]}async function exposeSyncAPI(r,e){const{setReady:t,setFailed:s,exposedApi:n}=prepareForExpose(r),o=await NodeSABSyncReceiveMessageTransport.create(),i=nodeEndpoint(e);return exposeSync(n,i,o),[t,s,n]}function prepareForExpose(r,e){setupTransferHandlers();const t=Promise.resolve();let s,n;const o=new Promise((l,c)=>{s=l,n=c}),i=proxyClone(r),a=new Proxy(i,{get:(l,c)=>c==="isConnected"?()=>t:c==="isReady"?()=>o:c in l?l[c]:e==null?void 0:e[c]});return{setReady:s,setFailed:n,exposedApi:a}}let isTransferHandlersSetup=!1;function setupTransferHandlers(){if(isTransferHandlersSetup)return;isTransferHandlersSetup=!0,transferHandlers.set("EVENT",{canHandle:t=>t instanceof CustomEvent,serialize:t=>[{detail:t.detail},[]],deserialize:t=>t}),transferHandlers.set("FUNCTION",{canHandle:t=>typeof t=="function",serialize(t){const{port1:s,port2:n}=new MessageChannel;return expose(t,s),[n,[n]]},deserialize(t){return t.start(),wrap(t)}}),transferHandlers.set("MESSAGE_PORT",{canHandle:t=>t instanceof MessagePort,serialize(t){return[t,[t]]},deserialize(t){return t}}),transferHandlers.set("PHPResponse",{canHandle:t=>typeof t=="object"&&t!==null&&"headers"in t&&"bytes"in t&&"errors"in t&&"exitCode"in t&&"httpStatusCode"in t,serialize(t){const s=t.toRawData(),n=[];return s.bytes.buffer.byteLength>0&&n.push(s.bytes.buffer),[s,n]},deserialize(t){return PHPResponse.fromRawData(t)}});const r=transferHandlers.get("throw"),e=r==null?void 0:r.serialize;r.serialize=({value:t})=>{const s=e({value:t});return t.response&&(s[0].value.response=t.response),t.source&&(s[0].value.source=t.source),s},transferHandlers.set("StreamedPHPResponse",{canHandle:t=>t instanceof StreamedPHPResponse,serialize(t){const s=supportsTransferableStreams(),n=promiseToPort(t.exitCode),o=t.getHeadersStream();if(s)return[{__type:"StreamedPHPResponse",headers:o,stdout:t.stdout,stderr:t.stderr,exitCodePort:n},[o,t.stdout,t.stderr,n]];const i=streamToPort(o),a=streamToPort(t.stdout),l=streamToPort(t.stderr);return[{__type:"StreamedPHPResponse",headersPort:i,stdoutPort:a,stderrPort:l,exitCodePort:n},[i,a,l,n]]},deserialize(t){if(t.headers&&t.stdout&&t.stderr){const a=portToPromise(t.exitCodePort);return new StreamedPHPResponse(t.headers,t.stdout,t.stderr,a)}const s=portToStream(t.headersPort),n=portToStream(t.stdoutPort),o=portToStream(t.stderrPort),i=portToPromise(t.exitCodePort);return new StreamedPHPResponse(s,n,o,i)}})}let _cachedSupportsTransferableStreams;function supportsTransferableStreams(){if(typeof ReadableStream>"u"&&(_cachedSupportsTransferableStreams=!1),_cachedSupportsTransferableStreams===void 0)try{const{port1:r}=new MessageChannel,e=new ReadableStream;r.postMessage(e,[e]);try{r.close()}catch{}_cachedSupportsTransferableStreams=!0}catch{_cachedSupportsTransferableStreams=!1}return _cachedSupportsTransferableStreams}function streamToPort(r){const{port1:e,port2:t}=new MessageChannel;return(async()=>{const s=r.getReader();try{for(;;){const{done:n,value:o}=await s.read();if(n){try{e.postMessage({t:"close"})}catch{}try{e.close()}catch{}break}if(o){const i=o.byteOffset===0&&o.byteLength===o.buffer.byteLength?o:o.slice(),a=i.buffer;try{e.postMessage({t:"chunk",b:a},[a])}catch{e.postMessage({t:"chunk",b:i.buffer.slice(0)})}}}}catch(n){try{e.postMessage({t:"error",m:(n==null?void 0:n.message)||String(n)})}catch{}}finally{try{e.close()}catch{}}})(),t}function portToStream(r){return new ReadableStream({start(e){const t=n=>{const o=n.data;if(o)switch(o.t){case"chunk":try{e.enqueue(new Uint8Array(o.b))}catch{s()}break;case"close":safeStreamClose(e),s();break;case"error":safeStreamError(e,new Error(o.m||"Stream error")),s();break}},s=()=>{var n;try{(n=r.removeEventListener)==null||n.call(r,"message",t)}catch{}try{r.onmessage=null}catch{}try{r.close()}catch{}};r.addEventListener?r.addEventListener("message",t):r.on?r.on("message",n=>t({data:n})):r.onmessage=t,typeof r.start=="function"&&r.start()},cancel(){try{r.close()}catch{}}})}function promiseToPort(r){const{port1:e,port2:t}=new MessageChannel;return r.then(s=>{try{e.postMessage({t:"resolve",v:s})}catch{}}).catch(s=>{try{e.postMessage({t:"reject",m:(s==null?void 0:s.message)||String(s)})}catch{}}).finally(()=>{try{e.close()}catch{}}),t}function portToPromise(r){return new Promise((e,t)=>{const s=o=>{const i=o.data;i&&(i.t==="resolve"?(n(),e(i.v)):i.t==="reject"&&(n(),t(new Error(i.m||""))))},n=()=>{var o;try{(o=r.removeEventListener)==null||o.call(r,"message",s)}catch{}try{r.onmessage=null}catch{}try{r.close()}catch{}};r.addEventListener?r.addEventListener("message",s):r.on?r.on("message",o=>s({data:o})):r.onmessage=s,typeof r.start=="function"&&r.start()})}const throwTransferHandler=transferHandlers.get("throw"),throwTransferHandlerCustom={canHandle:throwTransferHandler.canHandle,serialize:({value:r})=>{let e;return r instanceof Error?(e={isError:!0,value:serializeError(r)},e.value.originalErrorClassName=r.constructor.name):e={isError:!1,value:r},[e,[]]},deserialize:r=>{if(r.isError){const e=deserializeError(r.value),t=new Error("Comlink method call failed");let s=e;for(;s.cause;)s=s.cause;throw s.cause=t,e}throw r.value}};transferHandlers.set("throw",throwTransferHandlerCustom);function proxyClone(r){return new Proxy(r,{get(e,t){switch(typeof e[t]){case"function":return(...s)=>e[t](...s);case"object":return e[t]===null?e[t]:proxyClone(e[t]);case"undefined":case"number":case"string":return e[t];default:return proxy(e[t])}}})}function safeStreamError(r,e){try{r.error(e)}catch{}}function safeStreamClose(r){try{r.close()}catch{}}const MAX_ADDRESSABLE_FILE_OFFSET=BigInt(Number.MAX_SAFE_INTEGER);class IntervalNode{constructor(e){this.left=null,this.right=null,this.range=e,this.max=e.end}}class FileLockIntervalTree{constructor(){this.root=null}isEmpty(){return this.root===null}insert(e){this.root=this.insertNode(this.root,e)}findOverlapping(e){const t=[];return this.findOverlappingRanges(this.root,e,t),t}remove(e){this.root=this.removeNode(this.root,e)}findLocksForProcess(e){const t=[];return this.findLocksForProcessInNode(this.root,e,t),t}findStrictestExistingLockType(){let e="unlocked";const t=s=>{if(s){if(s.range.type==="exclusive"){e="exclusive";return}s.range.type==="shared"&&(e="shared"),t(s.left),t(s.right)}};return t(this.root),e}insertNode(e,t){return e?(t.start<e.range.start?e.left=this.insertNode(e.left,t):e.right=this.insertNode(e.right,t),e.max=this.bigintMax(e.max,t.end),e):new IntervalNode(t)}bigintMax(...e){return e.reduce((t,s)=>s>t?s:t,e[0])}findOverlappingRanges(e,t,s){e&&(this.doRangesOverlap(e.range,t)&&s.push(e.range),e.left&&e.left.max>=t.start&&this.findOverlappingRanges(e.left,t,s),e.right&&e.range.start<=t.end&&this.findOverlappingRanges(e.right,t,s))}doRangesOverlap(e,t){return e.start<t.end&&t.start<e.end}removeNode(e,t){if(!e)return null;if(this.areRangesEqual(e.range,t)){if(!e.left)return e.right;if(!e.right)return e.left;const s=this.findMin(e.right);e.range=s.range,e.right=this.removeNode(e.right,s.range)}else t.start<e.range.start?e.left=this.removeNode(e.left,t):e.right=this.removeNode(e.right,t);return e.max=e.range.end,e.left&&(e.max=this.bigintMax(e.max,e.left.max)),e.right&&(e.max=this.bigintMax(e.max,e.right.max)),e}findMin(e){let t=e;for(;t.left;)t=t.left;return t}areRangesEqual(e,t){return e.start===t.start&&e.end===t.end&&e.pid===t.pid&&e.fd===t.fd}findLocksForProcessInNode(e,t,s){e&&(e.range.pid===t&&s.push(e.range),this.findLocksForProcessInNode(e.left,t,s),this.findLocksForProcessInNode(e.right,t,s))}}class FileLockManagerInMemory{constructor(){this.locks=new Map}lockWholeFile(e,t){if(this.locks.get(e)===void 0){if(t.type==="unlock")return!0;this.locks.set(e,new FileLock)}const n=this.locks.get(e).lockWholeFile(t);return this.forgetPathIfUnlocked(e),n}lockFileByteRange(e,t){if(!this.locks.has(e)){if(t.type==="unlocked")return!0;this.locks.set(e,new FileLock)}return this.locks.get(e).lockFileByteRange(t)}findFirstConflictingByteRangeLock(e,t){const s=this.locks.get(e);if(s!==void 0)return s.findFirstConflictingByteRangeLock(t)}releaseLocksForProcess(e){for(const[t,s]of this.locks.entries())s.releaseLocksForProcess(e),this.forgetPathIfUnlocked(t)}releaseLocksOnFdClose(e,t,s){const n=this.locks.get(s);n&&(n.releaseLocksOnFdClose(e,t),this.forgetPathIfUnlocked(s))}forgetPathIfUnlocked(e){const t=this.locks.get(e);t&&t.isUnlocked()&&this.locks.delete(e)}}class FileLock{constructor(){this.rangeLocks=new FileLockIntervalTree,this.wholeFileLock={type:"unlocked"}}lockWholeFile(e){if(e.type==="unlock")return this.wholeFileLock.type==="unlocked"||(this.wholeFileLock.type==="exclusive"&&this.wholeFileLock.pid===e.pid&&this.wholeFileLock.fd===e.fd?this.wholeFileLock={type:"unlocked"}:this.wholeFileLock.type==="shared"&&this.wholeFileLock.pidFds.has(e.pid)&&this.wholeFileLock.pidFds.get(e.pid).has(e.fd)&&(this.wholeFileLock.pidFds.get(e.pid).delete(e.fd),this.wholeFileLock.pidFds.get(e.pid).size===0&&this.wholeFileLock.pidFds.delete(e.pid),this.wholeFileLock.pidFds.size===0&&(this.wholeFileLock={type:"unlocked"}))),!0;if(this.isThereAConflictWithRequestedWholeFileLock(e))return!1;if(e.type==="exclusive")return this.wholeFileLock={type:"exclusive",pid:e.pid,fd:e.fd},!0;if(e.type==="shared"){this.wholeFileLock.type!=="shared"&&(this.wholeFileLock={type:"shared",pidFds:new Map});const t=this.wholeFileLock;return t.pidFds.has(e.pid)||t.pidFds.set(e.pid,new Set),t.pidFds.get(e.pid).add(e.fd),!0}throw new Error(`Unexpected wholeFileLock() op: '${e.type}'`)}lockFileByteRange(e){if(e.start===e.end&&(e={...e,end:MAX_ADDRESSABLE_FILE_OFFSET}),e.type==="unlocked"){const i=this.rangeLocks.findOverlapping(e).filter(a=>a.pid===e.pid);for(const a of i)this.rangeLocks.remove(a),a.start<e.start&&this.rangeLocks.insert({...a,end:e.start}),a.end>e.end&&this.rangeLocks.insert({...a,start:e.end});return!0}if(this.isThereAConflictWithRequestedRangeLock(e))return!1;const t=this.rangeLocks.findOverlapping(e).filter(i=>i.pid===e.pid);let s=e.start,n=e.end;for(const i of t)this.rangeLocks.remove(i),i.start<s&&(s=i.start),i.end>n&&(n=i.end);const o={...e,start:s,end:n};return this.rangeLocks.insert(o),!0}findFirstConflictingByteRangeLock(e){e.start===e.end&&(e={...e,end:MAX_ADDRESSABLE_FILE_OFFSET});const s=this.rangeLocks.findOverlapping(e).find(o=>o.pid!==e.pid&&(e.type==="exclusive"||o.type==="exclusive"));if(s)return s;if(this.wholeFileLock.type==="unlocked")return;if(this.wholeFileLock.type==="exclusive"||e.type==="exclusive")return{type:this.wholeFileLock.type,start:0n,end:0n,pid:-1}}releaseLocksForProcess(e){for(const t of this.rangeLocks.findLocksForProcess(e))this.lockFileByteRange({...t,type:"unlocked"});if(this.wholeFileLock.type==="exclusive"&&this.wholeFileLock.pid===e)this.lockWholeFile({pid:e,fd:this.wholeFileLock.fd,type:"unlock"});else if(this.wholeFileLock.type==="shared"&&this.wholeFileLock.pidFds.has(e))for(const t of this.wholeFileLock.pidFds.get(e))this.lockWholeFile({pid:e,fd:t,type:"unlock"})}releaseLocksOnFdClose(e,t){for(const s of this.rangeLocks.findLocksForProcess(e))this.lockFileByteRange({...s,type:"unlocked"});this.lockWholeFile({pid:e,fd:t,type:"unlock"})}isUnlocked(){return this.wholeFileLock.type==="unlocked"&&this.rangeLocks.isEmpty()}isThereAConflictWithRequestedRangeLock(e){return this.findFirstConflictingByteRangeLock(e)!==void 0}isThereAConflictWithRequestedWholeFileLock(e){return e.type==="exclusive"?!!(this.wholeFileLock.type==="exclusive"&&(this.wholeFileLock.fd!==e.fd||this.wholeFileLock.pid!==e.pid)||this.wholeFileLock.type==="shared"&&Array.from(this.wholeFileLock.pidFds).some(([s])=>s!==e.pid)||this.rangeLocks.findOverlapping({start:0n,end:MAX_ADDRESSABLE_FILE_OFFSET}).length>0):e.type==="shared"?this.wholeFileLock.type==="exclusive"&&this.wholeFileLock.pid!==e.pid||this.rangeLocks.findOverlapping({start:0n,end:MAX_ADDRESSABLE_FILE_OFFSET}).filter(n=>n.type==="exclusive").length>0:!1}}class FileLockManagerComposite{constructor({nativeLockManager:e,wasmLockManager:t}){this.nativeLockManager=e,this.wasmLockManager=t}lockWholeFile(e,t){if(t.type!=="unlock"){let s,n;try{if(s=this.nativeLockManager.lockWholeFile(e,t),!s)return!1;n=this.wasmLockManager.lockWholeFile(e,t)}catch(o){logger.logger.error("Unexpected error in lockWholeFile()",o)}finally{s&&!n&&this.nativeLockManager.lockWholeFile(e,{...t,type:"unlock"})}return!!s&&!!n}try{this.wasmLockManager.lockWholeFile(e,t)}catch(s){logger.logger.error("Unexpected error unlocking whole file with in-memory lock manager",s)}try{this.nativeLockManager.lockWholeFile(e,t)}catch(s){logger.logger.error("Unexpected error unlocking whole file with native lock manager",s)}return!0}lockFileByteRange(e,t,s){if(t.type!=="unlocked"){let n,o;try{if(n=this.nativeLockManager.lockFileByteRange(e,t,s),!n)return!1;o=this.wasmLockManager.lockFileByteRange(e,t,s)}catch(i){logger.logger.error("Unexpected error in lockFileByteRange()",i)}finally{n&&!o&&this.nativeLockManager.lockFileByteRange(e,{...t,type:"unlocked"},!1)}return!!n&&!!o}try{this.wasmLockManager.lockFileByteRange(e,t,s)}catch(n){logger.logger.error("Unexpected error unlocking byte range with in-memory lock manager",n)}try{this.nativeLockManager.lockFileByteRange(e,t,s)}catch(n){logger.logger.error("Unexpected error unlocking byte range with native lock manager",n)}return!0}findFirstConflictingByteRangeLock(e,t){try{const s=this.nativeLockManager.findFirstConflictingByteRangeLock(e,t);return s||this.wasmLockManager.findFirstConflictingByteRangeLock(e,t)}catch(s){logger.logger.error("Unexpected error in findFirstConflictingByteRangeLock()",s);return}}releaseLocksForProcess(e){try{this.wasmLockManager.releaseLocksForProcess(e)}catch(t){logger.logger.error("Unexpected error in wasmLockManager.releaseLocksForProcess()",t)}try{this.nativeLockManager.releaseLocksForProcess(e)}catch(t){logger.logger.error("Unexpected error in nativeLockManager.releaseLocksForProcess()",t)}}releaseLocksOnFdClose(e,t,s){try{this.wasmLockManager.releaseLocksOnFdClose(e,t,s)}catch(n){logger.logger.error("Unexpected error in wasmLockManager.releaseLocksOnFdClose()",n)}try{this.nativeLockManager.releaseLocksOnFdClose(e,t,s)}catch(n){logger.logger.error("Unexpected error in nativeLockManager.releaseLocksOnFdClose()",n)}}}function createObjectPoolProxy(r){if(r.length===0)throw new Error("At least one instance is required");const e=[...r],t=[];function s(){const i=e.shift();return i!==void 0?Promise.resolve(i):new Promise(a=>{t.push(a)})}function n(i){const a=t.shift();a?a(i):e.push(i)}function o(i){return s().then(a=>{const l=u=>{const d=u==null?void 0:u.finished;return d&&typeof d.then=="function"?Promise.resolve(d).then(()=>n(a),()=>n(a)):n(a),u};let c;try{c=i(a)}catch(u){throw n(a),u}return c!=null&&typeof c.then=="function"?c.then(u=>l(u),u=>{throw n(a),u}):l(c)})}return new Proxy({},{get(i,a){if(a in i)return i[a];if(a!=="then")return new Proxy(function(){},{apply(l,c,u){return o(d=>d[a](...u))},get(l,c){if(c==="then")return(u,d)=>o(h=>h[a]).then(u,d)}})}})}const maxValueForSigned32BitInteger=2**31-1;class ProcessIdAllocator{constructor(e=1,t=maxValueForSigned32BitInteger){this.claimed=new Set,this.initialId=e,this.maxId=t,this.nextId=e}claim(){const e=this.maxId-this.initialId+1;for(let t=0;t<e;t++)if(this.claimed.has(this.nextId))this.nextId++,this.nextId>this.maxId&&(this.nextId=this.initialId);else return this.claimed.add(this.nextId),this.nextId;throw new Error(`Unable to find free process ID after ${e} tries.`)}release(e){return this.claimed.has(e)?(this.claimed.delete(e),!0):!1}}exports.AllPHPVersions=AllPHPVersions;exports.DEFAULT_BASE_URL=DEFAULT_BASE_URL;exports.FSHelpers=FSHelpers;exports.FileLock=FileLock;exports.FileLockIntervalTree=FileLockIntervalTree;exports.FileLockManagerComposite=FileLockManagerComposite;exports.FileLockManagerInMemory=FileLockManagerInMemory;exports.HttpCookieStore=HttpCookieStore;exports.LEGACY_PHP_INI_CONTENT=LEGACY_PHP_INI_CONTENT;exports.LEGACY_PHP_INI_PATH=LEGACY_PHP_INI_PATH;exports.LatestSupportedPHPVersion=LatestSupportedPHPVersion;exports.LegacyPHPVersions=LegacyPHPVersions;exports.MAX_ADDRESSABLE_FILE_OFFSET=MAX_ADDRESSABLE_FILE_OFFSET;exports.PHP=PHP;exports.PHPExecutionFailureError=PHPExecutionFailureError;exports.PHPNextVersion=PHPNextVersion;exports.PHPProcessManager=PHPProcessManager;exports.PHPRequestHandler=PHPRequestHandler;exports.PHPResponse=PHPResponse;exports.PHPWorker=PHPWorker;exports.PHP_EXTENSIONS_DIR=PHP_EXTENSIONS_DIR;exports.ProcessIdAllocator=ProcessIdAllocator;exports.SinglePHPInstanceManager=SinglePHPInstanceManager;exports.StreamedPHPResponse=StreamedPHPResponse;exports.SupportedPHPVersions=SupportedPHPVersions;exports.SupportedPHPVersionsList=SupportedPHPVersionsList;exports.UnhandledRejectionsTarget=UnhandledRejectionsTarget;exports.__private__dont__use=__private__dont__use;exports.applyRewriteRules=applyRewriteRules;exports.consumeAPI=consumeAPI;exports.consumeAPISync=consumeAPISync;exports.createLegacyPhpIniPreRunStep=createLegacyPhpIniPreRunStep;exports.createObjectPoolProxy=createObjectPoolProxy;exports.ensurePathPrefix=ensurePathPrefix;exports.exposeAPI=exposeAPI;exports.exposeSyncAPI=exposeSyncAPI;exports.getPhpIniEntries=getPhpIniEntries;exports.inferMimeType=inferMimeType;exports.installPHPExtensionFilesSync=installPHPExtensionFilesSync;exports.isExitCode=isExitCode;exports.isLegacyPHPVersion=isLegacyPHPVersion;exports.isPHPNextVersion=isPHPNextVersion;exports.isPathToSharedFS=isPathToSharedFS;exports.iterateFiles=iteratePhpFiles;exports.loadPHPRuntime=loadPHPRuntime;exports.popLoadedRuntime=popLoadedRuntime;exports.portToStream=portToStream;exports.prettyPrintFullStackTrace=prettyPrintFullStackTrace;exports.printDebugDetails=printDebugDetails;exports.printResponseDebugDetails=printResponseDebugDetails;exports.proxyFileSystem=proxyFileSystem;exports.releaseApiProxy=releaseApiProxy;exports.removePathPrefix=removePathPrefix;exports.resolvePHPExtension=resolvePHPExtension;exports.rotatePHPRuntime=rotatePHPRuntime;exports.sandboxedSpawnHandlerFactory=sandboxedSpawnHandlerFactory;exports.setPhpIniEntries=setPhpIniEntries;exports.streamToPort=streamToPort;exports.toRelativeUrl=toRelativeUrl;exports.withPHPIniValues=withPHPIniValues;exports.withResolvedPHPExtensions=withResolvedPHPExtensions;exports.writeFiles=writeFiles;exports.writeFilesStreamToPhp=writeFilesStreamToPhp;
104
+ */const WireValueType={RAW:"RAW",HANDLER:"HANDLER"},MessageType={GET:"GET",SET:"SET",APPLY:"APPLY",CONSTRUCT:"CONSTRUCT",ENDPOINT:"ENDPOINT",RELEASE:"RELEASE"},isObject=r=>typeof r=="object"&&r!==null||typeof r=="function",proxyTransferHandler={canHandle:r=>isObject(r)&&r[proxyMarker],serialize(r){const{port1:e,port2:t}=new MessageChannel;return expose(r,e),[t,[t]]},deserialize(r){return r.start(),wrap(r)}},throwTransferHandler$1={canHandle:r=>isObject(r)&&throwMarker in r,serialize({value:r}){let e;return r instanceof Error?e={isError:!0,value:{message:r.message,name:r.name,stack:r.stack}}:e={isError:!1,value:r},[e,[]]},deserialize(r){throw r.isError?Object.assign(new Error(r.value.message),r.value):r.value}},transferHandlers=new Map([["proxy",proxyTransferHandler],["throw",throwTransferHandler$1]]);function isAllowedOrigin(r,e){for(const t of r)if(e===t||t==="*"||t instanceof RegExp&&t.test(e))return!0;return!1}function expose(r,e=globalThis,t=["*"],s){e.addEventListener("message",function n(o){if(!o||!o.data)return;if(!isAllowedOrigin(t,o.origin)){console.warn(`Invalid origin '${o.origin}' for comlink proxy`);return}const{id:i,type:a,path:l}={path:[],...o.data},c=(o.data.argumentList||[]).map(fromWireValue);let u;try{const d=l.slice(0,-1).reduce((P,S)=>P[S],r),h=l.reduce((P,S)=>P[S],r);switch(a){case MessageType.GET:u=h;break;case MessageType.SET:d[l.slice(-1)[0]]=fromWireValue(o.data.value),u=!0;break;case MessageType.APPLY:u=h.apply(d,c);break;case MessageType.CONSTRUCT:{const P=new h(...c);u=proxy(P)}break;case MessageType.ENDPOINT:{const{port1:P,port2:S}=new MessageChannel;expose(r,S),u=transfer(P,[P])}break;case MessageType.RELEASE:u=void 0;break;default:return}}catch(d){u={value:d,[throwMarker]:0}}Promise.resolve(u).catch(d=>({value:d,[throwMarker]:0})).then(d=>{const[h,P]=toWireValue(d);e.postMessage({...h,id:i},P),a===MessageType.RELEASE&&(e.removeEventListener("message",n),closeEndPoint(e),finalizer in r&&typeof r[finalizer]=="function"&&r[finalizer]())}).catch(()=>{const[d,h]=toWireValue({value:new TypeError("Unserializable return value"),[throwMarker]:0});e.postMessage({...d,id:i},h)}).finally(()=>{s==null||s(o)})}),e.start&&e.start()}function isMessagePort(r){return r.constructor.name==="MessagePort"}function closeEndPoint(r){isMessagePort(r)&&r.close()}function wrap(r,e){const t=new Map;return r.addEventListener("message",function(n){const{data:o}=n;if(!o||!o.id)return;const i=t.get(o.id);if(i)try{i(o)}finally{t.delete(o.id)}}),createProxy(r,t,[],e)}function throwIfProxyReleased(r){if(r)throw new Error("Proxy has been released and is not useable")}function releaseEndpoint(r){return requestResponseMessage(r,new Map,{type:MessageType.RELEASE}).then(()=>{closeEndPoint(r)})}const proxyCounter=new WeakMap,proxyFinalizers="FinalizationRegistry"in globalThis&&new FinalizationRegistry(r=>{const e=(proxyCounter.get(r)||0)-1;proxyCounter.set(r,e),e===0&&releaseEndpoint(r)});function registerProxy(r,e){const t=(proxyCounter.get(e)||0)+1;proxyCounter.set(e,t),proxyFinalizers&&proxyFinalizers.register(r,e,r)}function unregisterProxy(r){proxyFinalizers&&proxyFinalizers.unregister(r)}function createProxy(r,e,t=[],s=function(){}){let n=!1;const o=new Proxy(s,{get(i,a){if(throwIfProxyReleased(n),a===releaseProxy)return()=>{unregisterProxy(o),releaseEndpoint(r),e.clear(),n=!0};if(a==="then"){if(t.length===0)return{then:()=>o};const l=requestResponseMessage(r,e,{type:MessageType.GET,path:t.map(c=>c.toString())}).then(fromWireValue);return l.then.bind(l)}return createProxy(r,e,[...t,a])},set(i,a,l){throwIfProxyReleased(n);const[c,u]=toWireValue(l);return requestResponseMessage(r,e,{type:MessageType.SET,path:[...t,a].map(d=>d.toString()),value:c},u).then(fromWireValue)},apply(i,a,l){throwIfProxyReleased(n);const c=t[t.length-1];if(c===createEndpoint)return requestResponseMessage(r,e,{type:MessageType.ENDPOINT}).then(fromWireValue);if(c==="bind")return createProxy(r,e,t.slice(0,-1));const[u,d]=processArguments(l);return requestResponseMessage(r,e,{type:MessageType.APPLY,path:t.map(h=>h.toString()),argumentList:u},d).then(fromWireValue)},construct(i,a){throwIfProxyReleased(n);const[l,c]=processArguments(a);return requestResponseMessage(r,e,{type:MessageType.CONSTRUCT,path:t.map(u=>u.toString()),argumentList:l},c).then(fromWireValue)}});return registerProxy(o,r),o}function myFlat(r){return Array.prototype.concat.apply([],r)}function processArguments(r){const e=r.map(toWireValue);return[e.map(t=>t[0]),myFlat(e.map(t=>t[1]))]}const transferCache=new WeakMap;function transfer(r,e){return transferCache.set(r,e),r}function proxy(r){return Object.assign(r,{[proxyMarker]:!0})}function windowEndpoint(r,e=globalThis,t="*"){return{postMessage:(s,n)=>r.postMessage(s,t,n),addEventListener:e.addEventListener.bind(e),removeEventListener:e.removeEventListener.bind(e)}}function toWireValue(r){for(const[e,t]of transferHandlers)if(t.canHandle(r)){const[s,n]=t.serialize(r);return[{type:WireValueType.HANDLER,name:e,value:s},n]}return[{type:WireValueType.RAW,value:r},transferCache.get(r)||[]]}function fromWireValue(r){switch(r.type){case WireValueType.HANDLER:return transferHandlers.get(r.name).deserialize(r.value);case WireValueType.RAW:return r.value}}function requestResponseMessage(r,e,t,s){return new Promise(n=>{const o=generateUUID();e.set(o,n),r.start&&r.start(),r.postMessage({id:o,...t},s)})}function generateUUID(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}function nodeEndpoint(r){const e=new WeakMap;return{postMessage:r.postMessage.bind(r),addEventListener:(t,s)=>{const n=o=>{"handleEvent"in s?s.handleEvent({data:o}):s({data:o})};r.on("message",n),e.set(s,n)},removeEventListener:(t,s)=>{const n=e.get(s);n&&(r.off("message",n),e.delete(s))},start:r.start&&r.start.bind(r)}}const proxyByListener=new WeakMap;function nodeProcessEndpoint(r){const e=r||process;if(typeof e.send!="function")throw new Error("IPC channel is not available. Did you forget to fork the process?");const t=e;return{postMessage(s,n){var o;if(n&&n.length>0)throw new Error("Transferable objects are not supported for nodeProcessEndpoint");(o=t.send)==null||o.call(t,s)},addEventListener(s,n){const o=typeof n=="function"?i=>n({data:i}):i=>n.handleEvent({data:i});proxyByListener.set(n,o),t.addListener(s,o)},removeEventListener(s,n){const o=proxyByListener.get(n);o&&(proxyByListener.delete(n),t.removeListener(s,o))},start(){}}}const list=[Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError,globalThis.DOMException,globalThis.AssertionError,globalThis.SystemError].filter(Boolean).map(r=>[r.name,r]),errorConstructors=new Map(list);class NonError extends Error{constructor(e){super(NonError._prepareSuperMessage(e)),this.name="NonError"}static _prepareSuperMessage(e){try{return JSON.stringify(e)}catch{return String(e)}}}const errorProperties=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1},{property:"errors",enumerable:!1}],toJsonWasCalled=new WeakSet,toJSON=r=>{toJsonWasCalled.add(r);const e=r.toJSON();return toJsonWasCalled.delete(r),e},newError=r=>{const e=errorConstructors.get(r)??Error;return e===AggregateError?new e([]):new e},destroyCircular=({from:r,seen:e,to:t,forceEnumerable:s,maxDepth:n,depth:o,useToJSON:i,serialize:a})=>{if(t||(Array.isArray(r)?t=[]:!a&&isErrorLike(r)?t=newError(r.name):t={}),e.push(r),o>=n)return t;if(i&&typeof r.toJSON=="function"&&!toJsonWasCalled.has(r))return toJSON(r);const l=c=>destroyCircular({from:c,seen:[...e],forceEnumerable:s,maxDepth:n,depth:o,useToJSON:i,serialize:a});for(const[c,u]of Object.entries(r)){if(u&&u instanceof Uint8Array&&u.constructor.name==="Buffer"){t[c]="[object Buffer]";continue}if(u!==null&&typeof u=="object"&&typeof u.pipe=="function"){t[c]="[object Stream]";continue}if(typeof u!="function"){if(!u||typeof u!="object"){try{t[c]=u}catch{}continue}if(!e.includes(r[c])){o++,t[c]=l(r[c]);continue}t[c]="[Circular]"}}if(a||t instanceof Error)for(const{property:c,enumerable:u}of errorProperties)r[c]!==void 0&&r[c]!==null&&Object.defineProperty(t,c,{value:isErrorLike(r[c])||Array.isArray(r[c])?l(r[c]):r[c],enumerable:s?!0:u,configurable:!0,writable:!0});return t};function serializeError(r,e={}){const{maxDepth:t=Number.POSITIVE_INFINITY,useToJSON:s=!0}=e;return typeof r=="object"&&r!==null?destroyCircular({from:r,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:s,serialize:!0}):typeof r=="function"?`[Function: ${r.name||"anonymous"}]`:r}function deserializeError(r,e={}){const{maxDepth:t=Number.POSITIVE_INFINITY}=e;return r instanceof Error?r:isMinimumViableSerializedError(r)?destroyCircular({from:r,seen:[],to:newError(r.name),maxDepth:t,depth:0,serialize:!1}):new NonError(r)}function isErrorLike(r){return!!r&&typeof r=="object"&&typeof r.name=="string"&&typeof r.message=="string"&&typeof r.stack=="string"}function isMinimumViableSerializedError(r){return!!r&&typeof r=="object"&&typeof r.message=="string"&&!Array.isArray(r)}const releaseApiProxy=releaseProxy;async function consumeAPISync(r){setupTransferHandlers();const e=await NodeSABSyncReceiveMessageTransport.create();return wrapSync(r,e)}function consumeAPI(r,e=void 0){setupTransferHandlers();let t;if(typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u")if("postMessage"in r)t=nodeEndpoint(r);else if("send"in r&&"addListener"in r)t=nodeProcessEndpoint(r);else throw new Error("consumeAPI: remote does not look like a Worker, MessagePort, or Process");else t=r instanceof Worker?r:windowEndpoint(r,e);const n=wrap(t),o=proxyClone(n);return new Proxy(o,{get:(i,a)=>a==="isConnected"?async()=>{for(;;)try{await runWithTimeout(n.isConnected(),200);break}catch{}}:n[a]})}async function runWithTimeout(r,e){return new Promise((t,s)=>{setTimeout(s,e),r.then(t)})}function exposeAPI(r,e,t){const{setReady:s,setFailed:n,exposedApi:o}=prepareForExpose(r,e);let i;if(t)if("addEventListener"in t)i=t;else if("postMessage"in t)i=nodeEndpoint(t);else if("send"in t&&"addListener"in t)i=nodeProcessEndpoint(t);else throw new Error("exposeAPI: targetWorker does not look like a Worker, MessagePort, or Process");else i=typeof window<"u"?windowEndpoint(self.parent):void 0;return expose(o,i),[s,n,o]}async function exposeSyncAPI(r,e){const{setReady:t,setFailed:s,exposedApi:n}=prepareForExpose(r),o=await NodeSABSyncReceiveMessageTransport.create(),i=nodeEndpoint(e);return exposeSync(n,i,o),[t,s,n]}function prepareForExpose(r,e){setupTransferHandlers();const t=Promise.resolve();let s,n;const o=new Promise((l,c)=>{s=l,n=c}),i=proxyClone(r),a=new Proxy(i,{get:(l,c)=>c==="isConnected"?()=>t:c==="isReady"?()=>o:c in l?l[c]:e==null?void 0:e[c]});return{setReady:s,setFailed:n,exposedApi:a}}let isTransferHandlersSetup=!1;function setupTransferHandlers(){if(isTransferHandlersSetup)return;isTransferHandlersSetup=!0,transferHandlers.set("EVENT",{canHandle:t=>t instanceof CustomEvent,serialize:t=>[{detail:t.detail},[]],deserialize:t=>t}),transferHandlers.set("FUNCTION",{canHandle:t=>typeof t=="function",serialize(t){const{port1:s,port2:n}=new MessageChannel;return expose(t,s),[n,[n]]},deserialize(t){return t.start(),wrap(t)}}),transferHandlers.set("MESSAGE_PORT",{canHandle:t=>t instanceof MessagePort,serialize(t){return[t,[t]]},deserialize(t){return t}}),transferHandlers.set("PHPResponse",{canHandle:t=>typeof t=="object"&&t!==null&&"headers"in t&&"bytes"in t&&"errors"in t&&"exitCode"in t&&"httpStatusCode"in t,serialize(t){const s=t.toRawData(),n=[];return s.bytes.buffer.byteLength>0&&n.push(s.bytes.buffer),[s,n]},deserialize(t){return PHPResponse.fromRawData(t)}});const r=transferHandlers.get("throw"),e=r==null?void 0:r.serialize;r.serialize=({value:t})=>{const s=e({value:t});return t.response&&(s[0].value.response=t.response),t.source&&(s[0].value.source=t.source),s},transferHandlers.set("StreamedPHPResponse",{canHandle:t=>t instanceof StreamedPHPResponse,serialize(t){const s=supportsTransferableStreams(),n=promiseToPort(t.exitCode),o=t.getHeadersStream();if(s)return[{__type:"StreamedPHPResponse",headers:o,stdout:t.stdout,stderr:t.stderr,exitCodePort:n},[o,t.stdout,t.stderr,n]];const i=streamToPort(o),a=streamToPort(t.stdout),l=streamToPort(t.stderr);return[{__type:"StreamedPHPResponse",headersPort:i,stdoutPort:a,stderrPort:l,exitCodePort:n},[i,a,l,n]]},deserialize(t){if(t.headers&&t.stdout&&t.stderr){const a=portToPromise(t.exitCodePort);return new StreamedPHPResponse(t.headers,t.stdout,t.stderr,a)}const s=portToStream(t.headersPort),n=portToStream(t.stdoutPort),o=portToStream(t.stderrPort),i=portToPromise(t.exitCodePort);return new StreamedPHPResponse(s,n,o,i)}})}let _cachedSupportsTransferableStreams;function supportsTransferableStreams(){if(typeof ReadableStream>"u"&&(_cachedSupportsTransferableStreams=!1),_cachedSupportsTransferableStreams===void 0)try{const{port1:r}=new MessageChannel,e=new ReadableStream;r.postMessage(e,[e]);try{r.close()}catch{}_cachedSupportsTransferableStreams=!0}catch{_cachedSupportsTransferableStreams=!1}return _cachedSupportsTransferableStreams}function streamToPort(r){const{port1:e,port2:t}=new MessageChannel;return(async()=>{const s=r.getReader();try{for(;;){const{done:n,value:o}=await s.read();if(n){try{e.postMessage({t:"close"})}catch{}try{e.close()}catch{}break}if(o){const i=o.byteOffset===0&&o.byteLength===o.buffer.byteLength?o:o.slice(),a=i.buffer;try{e.postMessage({t:"chunk",b:a},[a])}catch{e.postMessage({t:"chunk",b:i.buffer.slice(0)})}}}}catch(n){try{e.postMessage({t:"error",m:(n==null?void 0:n.message)||String(n)})}catch{}}finally{try{e.close()}catch{}}})(),t}function portToStream(r){return new ReadableStream({start(e){const t=n=>{const o=n.data;if(o)switch(o.t){case"chunk":try{e.enqueue(new Uint8Array(o.b))}catch{s()}break;case"close":safeStreamClose(e),s();break;case"error":safeStreamError(e,new Error(o.m||"Stream error")),s();break}},s=()=>{var n;try{(n=r.removeEventListener)==null||n.call(r,"message",t)}catch{}try{r.onmessage=null}catch{}try{r.close()}catch{}};r.addEventListener?r.addEventListener("message",t):r.on?r.on("message",n=>t({data:n})):r.onmessage=t,typeof r.start=="function"&&r.start()},cancel(){try{r.close()}catch{}}})}function promiseToPort(r){const{port1:e,port2:t}=new MessageChannel;return r.then(s=>{try{e.postMessage({t:"resolve",v:s})}catch{}}).catch(s=>{try{e.postMessage({t:"reject",m:(s==null?void 0:s.message)||String(s)})}catch{}}).finally(()=>{try{e.close()}catch{}}),t}function portToPromise(r){return new Promise((e,t)=>{const s=o=>{const i=o.data;i&&(i.t==="resolve"?(n(),e(i.v)):i.t==="reject"&&(n(),t(new Error(i.m||""))))},n=()=>{var o;try{(o=r.removeEventListener)==null||o.call(r,"message",s)}catch{}try{r.onmessage=null}catch{}try{r.close()}catch{}};r.addEventListener?r.addEventListener("message",s):r.on?r.on("message",o=>s({data:o})):r.onmessage=s,typeof r.start=="function"&&r.start()})}const throwTransferHandler=transferHandlers.get("throw"),throwTransferHandlerCustom={canHandle:throwTransferHandler.canHandle,serialize:({value:r})=>{let e;return r instanceof Error?(e={isError:!0,value:serializeError(r)},e.value.originalErrorClassName=r.constructor.name):e={isError:!1,value:r},[e,[]]},deserialize:r=>{if(r.isError){const e=deserializeError(r.value),t=new Error("Comlink method call failed");let s=e;for(;s.cause;)s=s.cause;throw s.cause=t,e}throw r.value}};transferHandlers.set("throw",throwTransferHandlerCustom);function proxyClone(r){return new Proxy(r,{get(e,t){switch(typeof e[t]){case"function":return(...s)=>e[t](...s);case"object":return e[t]===null?e[t]:proxyClone(e[t]);case"undefined":case"number":case"string":return e[t];default:return proxy(e[t])}}})}function safeStreamError(r,e){try{r.error(e)}catch{}}function safeStreamClose(r){try{r.close()}catch{}}const MAX_ADDRESSABLE_FILE_OFFSET=BigInt(Number.MAX_SAFE_INTEGER);class IntervalNode{constructor(e){this.left=null,this.right=null,this.range=e,this.max=e.end}}class FileLockIntervalTree{constructor(){this.root=null}isEmpty(){return this.root===null}insert(e){this.root=this.insertNode(this.root,e)}findOverlapping(e){const t=[];return this.findOverlappingRanges(this.root,e,t),t}remove(e){this.root=this.removeNode(this.root,e)}findLocksForProcess(e){const t=[];return this.findLocksForProcessInNode(this.root,e,t),t}findStrictestExistingLockType(){let e="unlocked";const t=s=>{if(s){if(s.range.type==="exclusive"){e="exclusive";return}s.range.type==="shared"&&(e="shared"),t(s.left),t(s.right)}};return t(this.root),e}insertNode(e,t){return e?(t.start<e.range.start?e.left=this.insertNode(e.left,t):e.right=this.insertNode(e.right,t),e.max=this.bigintMax(e.max,t.end),e):new IntervalNode(t)}bigintMax(...e){return e.reduce((t,s)=>s>t?s:t,e[0])}findOverlappingRanges(e,t,s){e&&(this.doRangesOverlap(e.range,t)&&s.push(e.range),e.left&&e.left.max>=t.start&&this.findOverlappingRanges(e.left,t,s),e.right&&e.range.start<=t.end&&this.findOverlappingRanges(e.right,t,s))}doRangesOverlap(e,t){return e.start<t.end&&t.start<e.end}removeNode(e,t){if(!e)return null;if(this.areRangesEqual(e.range,t)){if(!e.left)return e.right;if(!e.right)return e.left;const s=this.findMin(e.right);e.range=s.range,e.right=this.removeNode(e.right,s.range)}else t.start<e.range.start?e.left=this.removeNode(e.left,t):e.right=this.removeNode(e.right,t);return e.max=e.range.end,e.left&&(e.max=this.bigintMax(e.max,e.left.max)),e.right&&(e.max=this.bigintMax(e.max,e.right.max)),e}findMin(e){let t=e;for(;t.left;)t=t.left;return t}areRangesEqual(e,t){return e.start===t.start&&e.end===t.end&&e.pid===t.pid&&e.fd===t.fd}findLocksForProcessInNode(e,t,s){e&&(e.range.pid===t&&s.push(e.range),this.findLocksForProcessInNode(e.left,t,s),this.findLocksForProcessInNode(e.right,t,s))}}class FileLockManagerInMemory{constructor(){this.locks=new Map}lockWholeFile(e,t){if(this.locks.get(e)===void 0){if(t.type==="unlock")return!0;this.locks.set(e,new FileLock)}const n=this.locks.get(e).lockWholeFile(t);return this.forgetPathIfUnlocked(e),n}lockFileByteRange(e,t){if(!this.locks.has(e)){if(t.type==="unlocked")return!0;this.locks.set(e,new FileLock)}return this.locks.get(e).lockFileByteRange(t)}findFirstConflictingByteRangeLock(e,t){const s=this.locks.get(e);if(s!==void 0)return s.findFirstConflictingByteRangeLock(t)}releaseLocksForProcess(e){for(const[t,s]of this.locks.entries())s.releaseLocksForProcess(e),this.forgetPathIfUnlocked(t)}releaseLocksOnFdClose(e,t,s){const n=this.locks.get(s);n&&(n.releaseLocksOnFdClose(e,t),this.forgetPathIfUnlocked(s))}forgetPathIfUnlocked(e){const t=this.locks.get(e);t&&t.isUnlocked()&&this.locks.delete(e)}}class FileLock{constructor(){this.rangeLocks=new FileLockIntervalTree,this.wholeFileLock={type:"unlocked"}}lockWholeFile(e){if(e.type==="unlock")return this.wholeFileLock.type==="unlocked"||(this.wholeFileLock.type==="exclusive"&&this.wholeFileLock.pid===e.pid&&this.wholeFileLock.fd===e.fd?this.wholeFileLock={type:"unlocked"}:this.wholeFileLock.type==="shared"&&this.wholeFileLock.pidFds.has(e.pid)&&this.wholeFileLock.pidFds.get(e.pid).has(e.fd)&&(this.wholeFileLock.pidFds.get(e.pid).delete(e.fd),this.wholeFileLock.pidFds.get(e.pid).size===0&&this.wholeFileLock.pidFds.delete(e.pid),this.wholeFileLock.pidFds.size===0&&(this.wholeFileLock={type:"unlocked"}))),!0;if(this.isThereAConflictWithRequestedWholeFileLock(e))return!1;if(e.type==="exclusive")return this.wholeFileLock={type:"exclusive",pid:e.pid,fd:e.fd},!0;if(e.type==="shared"){this.wholeFileLock.type!=="shared"&&(this.wholeFileLock={type:"shared",pidFds:new Map});const t=this.wholeFileLock;return t.pidFds.has(e.pid)||t.pidFds.set(e.pid,new Set),t.pidFds.get(e.pid).add(e.fd),!0}throw new Error(`Unexpected wholeFileLock() op: '${e.type}'`)}lockFileByteRange(e){if(e.start===e.end&&(e={...e,end:MAX_ADDRESSABLE_FILE_OFFSET}),e.type==="unlocked"){const i=this.rangeLocks.findOverlapping(e).filter(a=>a.pid===e.pid);for(const a of i)this.rangeLocks.remove(a),a.start<e.start&&this.rangeLocks.insert({...a,end:e.start}),a.end>e.end&&this.rangeLocks.insert({...a,start:e.end});return!0}if(this.isThereAConflictWithRequestedRangeLock(e))return!1;const t=this.rangeLocks.findOverlapping(e).filter(i=>i.pid===e.pid);let s=e.start,n=e.end;for(const i of t)this.rangeLocks.remove(i),i.start<s&&(s=i.start),i.end>n&&(n=i.end);const o={...e,start:s,end:n};return this.rangeLocks.insert(o),!0}findFirstConflictingByteRangeLock(e){e.start===e.end&&(e={...e,end:MAX_ADDRESSABLE_FILE_OFFSET});const s=this.rangeLocks.findOverlapping(e).find(o=>o.pid!==e.pid&&(e.type==="exclusive"||o.type==="exclusive"));if(s)return s;if(this.wholeFileLock.type==="unlocked")return;if(this.wholeFileLock.type==="exclusive"||e.type==="exclusive")return{type:this.wholeFileLock.type,start:0n,end:0n,pid:-1}}releaseLocksForProcess(e){for(const t of this.rangeLocks.findLocksForProcess(e))this.lockFileByteRange({...t,type:"unlocked"});if(this.wholeFileLock.type==="exclusive"&&this.wholeFileLock.pid===e)this.lockWholeFile({pid:e,fd:this.wholeFileLock.fd,type:"unlock"});else if(this.wholeFileLock.type==="shared"&&this.wholeFileLock.pidFds.has(e))for(const t of this.wholeFileLock.pidFds.get(e))this.lockWholeFile({pid:e,fd:t,type:"unlock"})}releaseLocksOnFdClose(e,t){for(const s of this.rangeLocks.findLocksForProcess(e))this.lockFileByteRange({...s,type:"unlocked"});this.lockWholeFile({pid:e,fd:t,type:"unlock"})}isUnlocked(){return this.wholeFileLock.type==="unlocked"&&this.rangeLocks.isEmpty()}isThereAConflictWithRequestedRangeLock(e){return this.findFirstConflictingByteRangeLock(e)!==void 0}isThereAConflictWithRequestedWholeFileLock(e){return e.type==="exclusive"?!!(this.wholeFileLock.type==="exclusive"&&(this.wholeFileLock.fd!==e.fd||this.wholeFileLock.pid!==e.pid)||this.wholeFileLock.type==="shared"&&Array.from(this.wholeFileLock.pidFds).some(([s])=>s!==e.pid)||this.rangeLocks.findOverlapping({start:0n,end:MAX_ADDRESSABLE_FILE_OFFSET}).length>0):e.type==="shared"?this.wholeFileLock.type==="exclusive"&&this.wholeFileLock.pid!==e.pid||this.rangeLocks.findOverlapping({start:0n,end:MAX_ADDRESSABLE_FILE_OFFSET}).filter(n=>n.type==="exclusive").length>0:!1}}class FileLockManagerComposite{constructor({nativeLockManager:e,wasmLockManager:t}){this.nativeLockManager=e,this.wasmLockManager=t}lockWholeFile(e,t){if(t.type!=="unlock"){let s,n;try{if(s=this.nativeLockManager.lockWholeFile(e,t),!s)return!1;n=this.wasmLockManager.lockWholeFile(e,t)}catch(o){logger.logger.error("Unexpected error in lockWholeFile()",o)}finally{s&&!n&&this.nativeLockManager.lockWholeFile(e,{...t,type:"unlock"})}return!!s&&!!n}try{this.wasmLockManager.lockWholeFile(e,t)}catch(s){logger.logger.error("Unexpected error unlocking whole file with in-memory lock manager",s)}try{this.nativeLockManager.lockWholeFile(e,t)}catch(s){logger.logger.error("Unexpected error unlocking whole file with native lock manager",s)}return!0}lockFileByteRange(e,t,s){if(t.type!=="unlocked"){let n,o;try{if(n=this.nativeLockManager.lockFileByteRange(e,t,s),!n)return!1;o=this.wasmLockManager.lockFileByteRange(e,t,s)}catch(i){logger.logger.error("Unexpected error in lockFileByteRange()",i)}finally{n&&!o&&this.nativeLockManager.lockFileByteRange(e,{...t,type:"unlocked"},!1)}return!!n&&!!o}try{this.wasmLockManager.lockFileByteRange(e,t,s)}catch(n){logger.logger.error("Unexpected error unlocking byte range with in-memory lock manager",n)}try{this.nativeLockManager.lockFileByteRange(e,t,s)}catch(n){logger.logger.error("Unexpected error unlocking byte range with native lock manager",n)}return!0}findFirstConflictingByteRangeLock(e,t){try{const s=this.nativeLockManager.findFirstConflictingByteRangeLock(e,t);return s||this.wasmLockManager.findFirstConflictingByteRangeLock(e,t)}catch(s){logger.logger.error("Unexpected error in findFirstConflictingByteRangeLock()",s);return}}releaseLocksForProcess(e){try{this.wasmLockManager.releaseLocksForProcess(e)}catch(t){logger.logger.error("Unexpected error in wasmLockManager.releaseLocksForProcess()",t)}try{this.nativeLockManager.releaseLocksForProcess(e)}catch(t){logger.logger.error("Unexpected error in nativeLockManager.releaseLocksForProcess()",t)}}releaseLocksOnFdClose(e,t,s){try{this.wasmLockManager.releaseLocksOnFdClose(e,t,s)}catch(n){logger.logger.error("Unexpected error in wasmLockManager.releaseLocksOnFdClose()",n)}try{this.nativeLockManager.releaseLocksOnFdClose(e,t,s)}catch(n){logger.logger.error("Unexpected error in nativeLockManager.releaseLocksOnFdClose()",n)}}}function createObjectPoolProxy(r){if(r.length===0)throw new Error("At least one instance is required");const e=[...r],t=[];function s(){const i=e.shift();return i!==void 0?Promise.resolve(i):new Promise(a=>{t.push(a)})}function n(i){const a=t.shift();a?a(i):e.push(i)}function o(i){return s().then(a=>{const l=u=>{const d=u==null?void 0:u.finished;return d&&typeof d.then=="function"?Promise.resolve(d).then(()=>n(a),()=>n(a)):n(a),u};let c;try{c=i(a)}catch(u){throw n(a),u}return c!=null&&typeof c.then=="function"?c.then(u=>l(u),u=>{throw n(a),u}):l(c)})}return new Proxy({},{get(i,a){if(a in i)return i[a];if(a!=="then")return new Proxy(function(){},{apply(l,c,u){return o(d=>d[a](...u))},get(l,c){if(c==="then")return(u,d)=>o(h=>h[a]).then(u,d)}})}})}const maxValueForSigned32BitInteger=2**31-1;class ProcessIdAllocator{constructor(e=1,t=maxValueForSigned32BitInteger){this.claimed=new Set,this.initialId=e,this.maxId=t,this.nextId=e}claim(){const e=this.maxId-this.initialId+1;for(let t=0;t<e;t++)if(this.claimed.has(this.nextId))this.nextId++,this.nextId>this.maxId&&(this.nextId=this.initialId);else return this.claimed.add(this.nextId),this.nextId;throw new Error(`Unable to find free process ID after ${e} tries.`)}release(e){return this.claimed.has(e)?(this.claimed.delete(e),!0):!1}}exports.AllPHPVersions=AllPHPVersions;exports.DEFAULT_BASE_URL=DEFAULT_BASE_URL;exports.FSHelpers=FSHelpers;exports.FileLock=FileLock;exports.FileLockIntervalTree=FileLockIntervalTree;exports.FileLockManagerComposite=FileLockManagerComposite;exports.FileLockManagerInMemory=FileLockManagerInMemory;exports.HttpCookieStore=HttpCookieStore;exports.LEGACY_PHP_INI_CONTENT=LEGACY_PHP_INI_CONTENT;exports.LEGACY_PHP_INI_PATH=LEGACY_PHP_INI_PATH;exports.LatestSupportedPHPVersion=LatestSupportedPHPVersion;exports.LegacyPHPVersions=LegacyPHPVersions;exports.MAX_ADDRESSABLE_FILE_OFFSET=MAX_ADDRESSABLE_FILE_OFFSET;exports.PHP=PHP;exports.PHPExecutionFailureError=PHPExecutionFailureError;exports.PHPNextVersion=PHPNextVersion;exports.PHPProcessManager=PHPProcessManager;exports.PHPRequestHandler=PHPRequestHandler;exports.PHPResponse=PHPResponse;exports.PHPWorker=PHPWorker;exports.PHP_EXTENSIONS_DIR=PHP_EXTENSIONS_DIR;exports.ProcessIdAllocator=ProcessIdAllocator;exports.SinglePHPInstanceManager=SinglePHPInstanceManager;exports.StreamedPHPResponse=StreamedPHPResponse;exports.SupportedPHPVersions=SupportedPHPVersions;exports.SupportedPHPVersionsList=SupportedPHPVersionsList;exports.UnhandledRejectionsTarget=UnhandledRejectionsTarget;exports.__private__dont__use=__private__dont__use;exports.applyRewriteRules=applyRewriteRules;exports.consumeAPI=consumeAPI;exports.consumeAPISync=consumeAPISync;exports.createLegacyPhpIniPreRunStep=createLegacyPhpIniPreRunStep;exports.createObjectPoolProxy=createObjectPoolProxy;exports.describeError=describeError;exports.ensurePathPrefix=ensurePathPrefix;exports.exposeAPI=exposeAPI;exports.exposeSyncAPI=exposeSyncAPI;exports.getPhpIniEntries=getPhpIniEntries;exports.inferMimeType=inferMimeType;exports.installPHPExtensionFilesSync=installPHPExtensionFilesSync;exports.isExitCode=isExitCode;exports.isLegacyPHPVersion=isLegacyPHPVersion;exports.isPHPNextVersion=isPHPNextVersion;exports.isPathToSharedFS=isPathToSharedFS;exports.iterateFiles=iteratePhpFiles;exports.loadPHPRuntime=loadPHPRuntime;exports.popLoadedRuntime=popLoadedRuntime;exports.portToStream=portToStream;exports.prettyPrintFullStackTrace=prettyPrintFullStackTrace;exports.printDebugDetails=printDebugDetails;exports.printResponseDebugDetails=printResponseDebugDetails;exports.proxyFileSystem=proxyFileSystem;exports.releaseApiProxy=releaseApiProxy;exports.removePathPrefix=removePathPrefix;exports.resolvePHPExtension=resolvePHPExtension;exports.rotatePHPRuntime=rotatePHPRuntime;exports.sandboxedSpawnHandlerFactory=sandboxedSpawnHandlerFactory;exports.setPhpIniEntries=setPhpIniEntries;exports.streamToPort=streamToPort;exports.toRelativeUrl=toRelativeUrl;exports.withPHPIniValues=withPHPIniValues;exports.withResolvedPHPExtensions=withResolvedPHPExtensions;exports.writeFiles=writeFiles;exports.writeFilesStreamToPhp=writeFilesStreamToPhp;
105
105
  //# sourceMappingURL=index.cjs.map