@php-wasm/universal 3.0.14 → 3.0.15
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 +6 -6
- package/index.cjs.map +1 -1
- package/index.js +22 -5
- package/index.js.map +1 -1
- package/lib/universal-php.d.ts +8 -1
- package/package.json +7 -7
package/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var se=Object.create;var B=Object.defineProperty;var ne=Object.getOwnPropertyDescriptor;var ie=Object.getOwnPropertyNames;var oe=Object.getPrototypeOf,ae=Object.prototype.hasOwnProperty;var z=t=>{throw TypeError(t)};var ce=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ie(e))!ae.call(t,n)&&n!==r&&B(t,n,{get:()=>e[n],enumerable:!(s=ne(e,n))||s.enumerable});return t};var le=(t,e,r)=>(r=t!=null?se(oe(t)):{},ce(e||!t||!t.__esModule?B(r,"default",{value:t,enumerable:!0}):r,t));var O=(t,e,r)=>e.has(t)||z("Cannot "+r);var u=(t,e,r)=>(O(t,e,"read from private field"),r?r.call(t):e.get(t)),m=(t,e,r)=>e.has(t)?z("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),g=(t,e,r,s)=>(O(t,e,"write to private field"),s?s.call(t,r):e.set(t,r),r),y=(t,e,r)=>(O(t,e,"access private method"),r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("@php-wasm/node-polyfills");const logger=require("@php-wasm/logger"),util=require("@php-wasm/util"),ini=require("ini"),streamCompression=require("@php-wasm/stream-compression");var _documentCurrentScript=typeof document<"u"?document.currentScript:null;class ErrnoError extends Error{constructor(e,r,s){super(r,s),this.name="ErrnoError",this.errno=e}}const FileErrorCodes={0:"No error occurred. System call completed successfully.",1:"Argument list too long.",2:"Permission denied.",3:"Address in use.",4:"Address not available.",5:"Address family not supported.",6:"Resource unavailable, or operation would block.",7:"Connection already in progress.",8:"Bad file descriptor.",9:"Bad message.",10:"Device or resource busy.",11:"Operation canceled.",12:"No child processes.",13:"Connection aborted.",14:"Connection refused.",15:"Connection reset.",16:"Resource deadlock would occur.",17:"Destination address required.",18:"Mathematics argument out of domain of function.",19:"Reserved.",20:"File exists.",21:"Bad address.",22:"File too large.",23:"Host is unreachable.",24:"Identifier removed.",25:"Illegal byte sequence.",26:"Operation in progress.",27:"Interrupted function.",28:"Invalid argument.",29:"I/O error.",30:"Socket is connected.",31:"There is a directory under that path.",32:"Too many levels of symbolic links.",33:"File descriptor value too large.",34:"Too many links.",35:"Message too large.",36:"Reserved.",37:"Filename too long.",38:"Network is down.",39:"Connection aborted by network.",40:"Network unreachable.",41:"Too many files open in system.",42:"No buffer space available.",43:"No such device.",44:"There is no such file or directory OR the parent directory does not exist.",45:"Executable file format error.",46:"No locks available.",47:"Reserved.",48:"Not enough space.",49:"No message of the desired type.",50:"Protocol not available.",51:"No space left on device.",52:"Function not supported.",53:"The socket is not connected.",54:"Not a directory or a symbolic link to a directory.",55:"Directory not empty.",56:"State not recoverable.",57:"Not a socket.",58:"Not supported, or operation not supported on socket.",59:"Inappropriate I/O control operation.",60:"No such device or address.",61:"Value too large to be stored in data type.",62:"Previous owner died.",63:"Operation not permitted.",64:"Broken pipe.",65:"Protocol error.",66:"Protocol not supported.",67:"Protocol wrong type for socket.",68:"Result too large.",69:"Read-only file system.",70:"Invalid seek.",71:"No such process.",72:"Reserved.",73:"Connection timed out.",74:"Text file busy.",75:"Cross-device link.",76:"Extension: Capabilities insufficient."};function getEmscriptenFsError(t){const e=typeof t=="object"?t==null?void 0:t.errno:null;if(e in FileErrorCodes)return FileErrorCodes[e]}function rethrowFileSystemError(t=""){return function(r){return function(...s){try{return r.apply(this,s)}catch(n){const i=typeof n=="object"?n==null?void 0:n.errno:null;if(i in FileErrorCodes){const o=FileErrorCodes[i],a=typeof s[1]=="string"?s[1]:null,c=a!==null?t.replaceAll("{path}",a):t;throw new ErrnoError(i,`${c}: ${o}`,{cause:n})}throw n}}}}class FSHelpers{static readFileAsText(e,r){return new TextDecoder().decode(FSHelpers.readFileAsBuffer(e,r))}static readFileAsBuffer(e,r){return e.readFile(r)}static writeFile(e,r,s){e.writeFile(r,s)}static unlink(e,r){e.unlink(r)}static mv(e,r,s){try{const n=e.lookupPath(r).node.mount,i=FSHelpers.fileExists(e,s)?e.lookupPath(s).node.mount:e.lookupPath(util.dirname(s)).node.mount;n.mountpoint!==i.mountpoint?(FSHelpers.copyRecursive(e,r,s),FSHelpers.isDir(e,r)?FSHelpers.rmdir(e,r,{recursive:!0}):e.unlink(r)):e.rename(r,s)}catch(n){const i=getEmscriptenFsError(n);throw i?new Error(`Could not move ${r} to ${s}: ${i}`,{cause:n}):n}}static rmdir(e,r,s={recursive:!0}){const n=e.lookupPath(r,{follow:!1});if((n==null?void 0:n.node.mount.mountpoint)===r)throw new ErrnoError(10);s!=null&&s.recursive&&FSHelpers.listFiles(e,r).forEach(i=>{const o=`${r}/${i}`;FSHelpers.isDir(e,o)?FSHelpers.rmdir(e,o,s):FSHelpers.unlink(e,o)}),e.getPath(e.lookupPath(r).node)===e.cwd()&&e.chdir(util.joinPaths(e.cwd(),"..")),e.rmdir(r)}static listFiles(e,r,s={prependPath:!1}){if(!FSHelpers.fileExists(e,r))return[];try{const n=e.readdir(r).filter(i=>i!=="."&&i!=="..");if(s.prependPath){const i=r.replace(/\/$/,"");return n.map(o=>`${i}/${o}`)}return n}catch(n){return logger.logger.error(n,{path:r}),[]}}static isDir(e,r){return FSHelpers.fileExists(e,r)?e.isDir(e.lookupPath(r,{follow:!0}).node.mode):!1}static isFile(e,r){return FSHelpers.fileExists(e,r)?e.isFile(e.lookupPath(r,{follow:!0}).node.mode):!1}static symlink(e,r,s){return e.symlink(r,s)}static isSymlink(e,r){return FSHelpers.fileExists(e,r)?e.isLink(e.lookupPath(r).node.mode):!1}static readlink(e,r){return e.readlink(r)}static realpath(e,r){return e.lookupPath(r,{follow:!0}).path}static fileExists(e,r){try{return e.lookupPath(r),!0}catch{return!1}}static mkdir(e,r){e.mkdirTree(r)}static copyRecursive(e,r,s){const n=e.lookupPath(r).node;if(e.isDir(n.mode)){e.mkdirTree(s);const i=e.readdir(r).filter(o=>o!=="."&&o!=="..");for(const o of i)FSHelpers.copyRecursive(e,util.joinPaths(r,o),util.joinPaths(s,o))}else e.isLink(n.mode)?e.symlink(e.readlink(r),s):e.writeFile(s,e.readFile(r))}}FSHelpers.readFileAsText=rethrowFileSystemError('Could not read "{path}"')(FSHelpers.readFileAsText);FSHelpers.readFileAsBuffer=rethrowFileSystemError('Could not read "{path}"')(FSHelpers.readFileAsBuffer);FSHelpers.writeFile=rethrowFileSystemError('Could not write to "{path}"')(FSHelpers.writeFile);FSHelpers.unlink=rethrowFileSystemError('Could not unlink "{path}"')(FSHelpers.unlink);FSHelpers.rmdir=rethrowFileSystemError('Could not remove directory "{path}"')(FSHelpers.rmdir);FSHelpers.listFiles=rethrowFileSystemError('Could not list files in "{path}"')(FSHelpers.listFiles);FSHelpers.isDir=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.isDir);FSHelpers.isFile=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.isFile);FSHelpers.realpath=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.realpath);FSHelpers.fileExists=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.fileExists);FSHelpers.mkdir=rethrowFileSystemError('Could not create directory "{path}"')(FSHelpers.mkdir);FSHelpers.copyRecursive=rethrowFileSystemError('Could not copy files from "{path}"')(FSHelpers.copyRecursive);const _private=new WeakMap;var P;class PHPWorker{constructor(e,r){m(this,P);this.absoluteUrl="",this.documentRoot="",this.chroot=null,g(this,P,new Map),this.onMessageListeners=[],_private.set(this,{monitor:r}),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 _private.get(this).requestHandler}async setPrimaryPHP(e){_private.set(this,{..._private.get(this),php:e})}pathToInternalUrl(e){return _private.get(this).requestHandler.pathToInternalUrl(e)}internalUrlToPath(e){return _private.get(this).requestHandler.internalUrlToPath(e)}async onDownloadProgress(e){var r;return(r=_private.get(this).monitor)==null?void 0:r.addEventListener("progress",e)}async mv(e,r){return _private.get(this).php.mv(e,r)}async rmdir(e,r){return _private.get(this).php.rmdir(e,r)}async request(e){return await _private.get(this).requestHandler.request(e)}async run(e){const{php:r,reap:s}=await this.acquirePHPInstance();try{return await r.run(e)}finally{s()}}async cli(e,r){const{php:s,reap:n}=await this.acquirePHPInstance();let i;try{i=await s.cli(e,r)}catch(o){throw n(),o}return i.finished.finally(n),i}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:r}=await _private.get(this).requestHandler.processManager.acquirePHPInstance();return this.chroot!==null&&e.chdir(this.chroot),this.registerWorkerListeners(e),{php:e,reap:r}}setSapiName(e){_private.get(this).php.setSapiName(e)}mkdir(e){return _private.get(this).php.mkdir(e)}mkdirTree(e){return _private.get(this).php.mkdirTree(e)}readFileAsText(e){return _private.get(this).php.readFileAsText(e)}readFileAsBuffer(e){return _private.get(this).php.readFileAsBuffer(e)}writeFile(e,r){return _private.get(this).php.writeFile(e,r)}unlink(e){return _private.get(this).php.unlink(e)}listFiles(e,r){return _private.get(this).php.listFiles(e,r)}isDir(e){return _private.get(this).php.isDir(e)}isFile(e){return _private.get(this).php.isFile(e)}fileExists(e){return _private.get(this).php.fileExists(e)}onMessage(e){return this.onMessageListeners.push(e),async()=>{this.onMessageListeners=this.onMessageListeners.filter(r=>r!==e)}}defineConstant(e,r){_private.get(this).php.defineConstant(e,r)}addEventListener(e,r){u(this,P).has(e)||u(this,P).set(e,new Set),u(this,P).get(e).add(r)}removeEventListener(e,r){var s;(s=u(this,P).get(e))==null||s.delete(r)}dispatchEvent(e){const r=u(this,P).get(e.type);if(r)for(const s of r)s(e)}registerWorkerListeners(e){e.addEventListener("*",async r=>{this.dispatchEvent(r)}),e.onMessage(async r=>{for(const s of this.onMessageListeners){const n=await s(r);if(n)return n}return""})}async[Symbol.asyncDispose](){var e;await((e=_private.get(this).requestHandler)==null?void 0:e[Symbol.asyncDispose]())}}P=new WeakMap;function isExitCode(t){return t instanceof Error?(t==null?void 0:t.name)==="ExitStatus"&&"status"in t:!1}const RuntimeId=Symbol("RuntimeId"),loadedRuntimes=new Map;let lastRuntimeId=0;async function loadPHPRuntime(t,...e){const r=Object.assign({},...e),[s,n,i]=makePromise(),o=t.init(currentJsRuntime,{onAbort(c){i(c),logger.logger.error(c)},ENV:{},locateFile:c=>c,...r,noInitialRun:!0,onRuntimeInitialized(){r.onRuntimeInitialized&&r.onRuntimeInitialized(o),n()}});await s;const a=++lastRuntimeId;return o.FS,o.id=a,o.originalExit=o._exit,o._exit=function(c){return o.outboundNetworkProxyServer&&(o.outboundNetworkProxyServer.close(),o.outboundNetworkProxyServer.closeAllConnections()),loadedRuntimes.delete(a),o.originalExit(c)},o[RuntimeId]=a,loadedRuntimes.set(a,o),a}function getLoadedRuntime(t){return loadedRuntimes.get(t)}const currentJsRuntime=function(){var t;return typeof process<"u"&&((t=process.release)==null?void 0:t.name)==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"}(),makePromise=()=>{const t=[],e=new Promise((r,s)=>{t.push(r,s)});return t.unshift(e),t},responseTexts={500:"Internal Server Error",502:"Bad Gateway",404:"Not Found",403:"Forbidden",401:"Unauthorized",400:"Bad Request",301:"Moved Permanently",302:"Found",307:"Temporary Redirect",308:"Permanent Redirect",204:"No Content",201:"Created",200:"OK"};class StreamedPHPResponse{constructor(e,r,s,n){this.parsedHeaders=null,this.cachedStdoutBytes=null,this.cachedStderrText=null,this.headersStream=e,this.stdout=r,this.stderr=s,this.exitCode=n}async ok(){try{const e=await this.httpStatusCode;return e>=200&&e<400}catch{return!1}}get finished(){return Promise.allSettled([this.exitCode.finally(()=>{})]).then(()=>{})}get headers(){return this.getParsedHeaders().then(e=>e.headers)}get httpStatusCode(){return this.getParsedHeaders().then(e=>e.httpStatusCode).then(e=>e!==void 0?e:this.getParsedHeaders().then(r=>r.httpStatusCode,()=>200)).catch(()=>500)}get stdoutText(){return this.stdoutBytes.then(e=>new TextDecoder().decode(e))}get stdoutBytes(){return this.cachedStdoutBytes||(this.cachedStdoutBytes=streamToBytes(this.stdout)),this.cachedStdoutBytes}get stderrText(){return this.cachedStderrText||(this.cachedStderrText=streamToText(this.stderr)),this.cachedStderrText}async getParsedHeaders(){return this.parsedHeaders||(this.parsedHeaders=parseHeadersStream(this.headersStream)),await this.parsedHeaders}}async function parseHeadersStream(t){const e=await streamToText(t);let r;try{r=JSON.parse(e)}catch{return{headers:{},httpStatusCode:200}}const s={};for(const n of r.headers){if(!n.includes(": "))continue;const i=n.indexOf(": "),o=n.substring(0,i).toLowerCase(),a=n.substring(i+2);o in s||(s[o]=[]),s[o].push(a)}return{headers:s,httpStatusCode:r.status}}async function streamToText(t){const e=t.pipeThrough(new TextDecoderStream).getReader(),r=[];for(;;){const{done:s,value:n}=await e.read();if(s)return r.join("");n&&r.push(n)}}async function streamToBytes(t){const e=t.getReader(),r=[];for(;;){const{done:s,value:n}=await e.read();if(s){const i=r.reduce((c,l)=>c+l.byteLength,0),o=new Uint8Array(i);let a=0;for(const c of r)o.set(c,a),a+=c.byteLength;return o}n&&r.push(n)}}class PHPResponse{constructor(e,r,s,n="",i=0){this.httpStatusCode=e,this.headers=r,this.bytes=s,this.exitCode=i,this.errors=n}static forHttpCode(e,r=""){return new PHPResponse(e,{},new TextEncoder().encode(r||responseTexts[e]||""))}static fromRawData(e){return new PHPResponse(e.httpStatusCode,e.headers,e.bytes,e.errors,e.exitCode)}static async fromStreamedResponse(e){return await e.finished,new PHPResponse(await e.httpStatusCode,await e.headers,await e.stdoutBytes,await e.stderrText,await e.exitCode)}ok(){return this.httpStatusCode>=200&&this.httpStatusCode<400}toRawData(){return{headers:this.headers,bytes:this.bytes,errors:this.errors,exitCode:this.exitCode,httpStatusCode:this.httpStatusCode}}get json(){return JSON.parse(this.text)}get text(){return new TextDecoder().decode(this.bytes)}}var _a;const kError=Symbol("error"),kMessage=Symbol("message");class ErrorEvent2 extends(_a=Event,_a){constructor(e,r={}){super(e),this[kError]=r.error===void 0?null:r.error,this[kMessage]=r.message===void 0?"":r.message}get error(){return this[kError]}get message(){return this[kMessage]}}Object.defineProperty(ErrorEvent2.prototype,"error",{enumerable:!0});Object.defineProperty(ErrorEvent2.prototype,"message",{enumerable:!0});const ErrorEvent=typeof globalThis.ErrorEvent=="function"?globalThis.ErrorEvent:ErrorEvent2;class UnhandledRejectionsTarget extends EventTarget{constructor(){super(...arguments),this.listenersCount=0}addEventListener(e,r,s){++this.listenersCount,super.addEventListener(e,r,s)}removeEventListener(e,r,s){--this.listenersCount,super.removeEventListener(e,r,s)}hasListeners(){return this.listenersCount>0}}function improveWASMErrorReporting(t){const e=new UnhandledRejectionsTarget;for(const r in t.wasmExports)if(typeof t.wasmExports[r]=="function"){const s=t.wasmExports[r];t.wasmExports[r]=function(...n){var i;try{return s(...n)}catch(o){if(!(o instanceof Error))throw o;t.lastAsyncifyStackSource&&(o.cause=t.lastAsyncifyStackSource);const a=clarifyErrorMessage(o,(i=t.lastAsyncifyStackSource)==null?void 0:i.stack);if(e.hasListeners()){o.message=a;const c=new ErrorEvent("error",{error:o});throw e.dispatchEvent(c),o}throw(!isExitCode(o)||o.status!==0)&&showCriticalErrorBox(a),o}}}return e}let functionsMaybeMissingFromAsyncify=[];function getFunctionsMaybeMissingFromAsyncify(){return functionsMaybeMissingFromAsyncify}function clarifyErrorMessage(t,e){if(t.message==="unreachable"){let r=UNREACHABLE_ERROR;e||(r+=`
|
|
1
|
+
"use strict";var se=Object.create;var B=Object.defineProperty;var ne=Object.getOwnPropertyDescriptor;var ie=Object.getOwnPropertyNames;var oe=Object.getPrototypeOf,ae=Object.prototype.hasOwnProperty;var z=t=>{throw TypeError(t)};var ce=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ie(e))!ae.call(t,n)&&n!==r&&B(t,n,{get:()=>e[n],enumerable:!(s=ne(e,n))||s.enumerable});return t};var le=(t,e,r)=>(r=t!=null?se(oe(t)):{},ce(e||!t||!t.__esModule?B(r,"default",{value:t,enumerable:!0}):r,t));var O=(t,e,r)=>e.has(t)||z("Cannot "+r);var u=(t,e,r)=>(O(t,e,"read from private field"),r?r.call(t):e.get(t)),m=(t,e,r)=>e.has(t)?z("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),w=(t,e,r,s)=>(O(t,e,"write to private field"),s?s.call(t,r):e.set(t,r),r),y=(t,e,r)=>(O(t,e,"access private method"),r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("@php-wasm/node-polyfills");const logger=require("@php-wasm/logger"),util=require("@php-wasm/util"),ini=require("ini"),streamCompression=require("@php-wasm/stream-compression");var _documentCurrentScript=typeof document<"u"?document.currentScript:null;class ErrnoError extends Error{constructor(e,r,s){super(r,s),this.name="ErrnoError",this.errno=e}}const FileErrorCodes={0:"No error occurred. System call completed successfully.",1:"Argument list too long.",2:"Permission denied.",3:"Address in use.",4:"Address not available.",5:"Address family not supported.",6:"Resource unavailable, or operation would block.",7:"Connection already in progress.",8:"Bad file descriptor.",9:"Bad message.",10:"Device or resource busy.",11:"Operation canceled.",12:"No child processes.",13:"Connection aborted.",14:"Connection refused.",15:"Connection reset.",16:"Resource deadlock would occur.",17:"Destination address required.",18:"Mathematics argument out of domain of function.",19:"Reserved.",20:"File exists.",21:"Bad address.",22:"File too large.",23:"Host is unreachable.",24:"Identifier removed.",25:"Illegal byte sequence.",26:"Operation in progress.",27:"Interrupted function.",28:"Invalid argument.",29:"I/O error.",30:"Socket is connected.",31:"There is a directory under that path.",32:"Too many levels of symbolic links.",33:"File descriptor value too large.",34:"Too many links.",35:"Message too large.",36:"Reserved.",37:"Filename too long.",38:"Network is down.",39:"Connection aborted by network.",40:"Network unreachable.",41:"Too many files open in system.",42:"No buffer space available.",43:"No such device.",44:"There is no such file or directory OR the parent directory does not exist.",45:"Executable file format error.",46:"No locks available.",47:"Reserved.",48:"Not enough space.",49:"No message of the desired type.",50:"Protocol not available.",51:"No space left on device.",52:"Function not supported.",53:"The socket is not connected.",54:"Not a directory or a symbolic link to a directory.",55:"Directory not empty.",56:"State not recoverable.",57:"Not a socket.",58:"Not supported, or operation not supported on socket.",59:"Inappropriate I/O control operation.",60:"No such device or address.",61:"Value too large to be stored in data type.",62:"Previous owner died.",63:"Operation not permitted.",64:"Broken pipe.",65:"Protocol error.",66:"Protocol not supported.",67:"Protocol wrong type for socket.",68:"Result too large.",69:"Read-only file system.",70:"Invalid seek.",71:"No such process.",72:"Reserved.",73:"Connection timed out.",74:"Text file busy.",75:"Cross-device link.",76:"Extension: Capabilities insufficient."};function getEmscriptenFsError(t){const e=typeof t=="object"?t==null?void 0:t.errno:null;if(e in FileErrorCodes)return FileErrorCodes[e]}function rethrowFileSystemError(t=""){return function(r){return function(...s){try{return r.apply(this,s)}catch(n){const i=typeof n=="object"?n==null?void 0:n.errno:null;if(i in FileErrorCodes){const o=FileErrorCodes[i],a=typeof s[1]=="string"?s[1]:null,c=a!==null?t.replaceAll("{path}",a):t;throw new ErrnoError(i,`${c}: ${o}`,{cause:n})}throw n}}}}class FSHelpers{static readFileAsText(e,r){return new TextDecoder().decode(FSHelpers.readFileAsBuffer(e,r))}static readFileAsBuffer(e,r){return e.readFile(r)}static writeFile(e,r,s){e.writeFile(r,s)}static unlink(e,r){e.unlink(r)}static mv(e,r,s){try{const n=e.lookupPath(r).node.mount,i=FSHelpers.fileExists(e,s)?e.lookupPath(s).node.mount:e.lookupPath(util.dirname(s)).node.mount;n.mountpoint!==i.mountpoint?(FSHelpers.copyRecursive(e,r,s),FSHelpers.isDir(e,r)?FSHelpers.rmdir(e,r,{recursive:!0}):e.unlink(r)):e.rename(r,s)}catch(n){const i=getEmscriptenFsError(n);throw i?new Error(`Could not move ${r} to ${s}: ${i}`,{cause:n}):n}}static rmdir(e,r,s={recursive:!0}){const n=e.lookupPath(r,{follow:!1});if((n==null?void 0:n.node.mount.mountpoint)===r)throw new ErrnoError(10);s!=null&&s.recursive&&FSHelpers.listFiles(e,r).forEach(i=>{const o=`${r}/${i}`;FSHelpers.isDir(e,o)?FSHelpers.rmdir(e,o,s):FSHelpers.unlink(e,o)}),e.getPath(e.lookupPath(r).node)===e.cwd()&&e.chdir(util.joinPaths(e.cwd(),"..")),e.rmdir(r)}static listFiles(e,r,s={prependPath:!1}){if(!FSHelpers.fileExists(e,r))return[];try{const n=e.readdir(r).filter(i=>i!=="."&&i!=="..");if(s.prependPath){const i=r.replace(/\/$/,"");return n.map(o=>`${i}/${o}`)}return n}catch(n){return logger.logger.error(n,{path:r}),[]}}static isDir(e,r){return FSHelpers.fileExists(e,r)?e.isDir(e.lookupPath(r,{follow:!0}).node.mode):!1}static isFile(e,r){return FSHelpers.fileExists(e,r)?e.isFile(e.lookupPath(r,{follow:!0}).node.mode):!1}static symlink(e,r,s){return e.symlink(r,s)}static isSymlink(e,r){return FSHelpers.fileExists(e,r)?e.isLink(e.lookupPath(r).node.mode):!1}static readlink(e,r){return e.readlink(r)}static realpath(e,r){return e.lookupPath(r,{follow:!0}).path}static fileExists(e,r){try{return e.lookupPath(r),!0}catch{return!1}}static mkdir(e,r){e.mkdirTree(r)}static copyRecursive(e,r,s){const n=e.lookupPath(r).node;if(e.isDir(n.mode)){e.mkdirTree(s);const i=e.readdir(r).filter(o=>o!=="."&&o!=="..");for(const o of i)FSHelpers.copyRecursive(e,util.joinPaths(r,o),util.joinPaths(s,o))}else e.isLink(n.mode)?e.symlink(e.readlink(r),s):e.writeFile(s,e.readFile(r))}}FSHelpers.readFileAsText=rethrowFileSystemError('Could not read "{path}"')(FSHelpers.readFileAsText);FSHelpers.readFileAsBuffer=rethrowFileSystemError('Could not read "{path}"')(FSHelpers.readFileAsBuffer);FSHelpers.writeFile=rethrowFileSystemError('Could not write to "{path}"')(FSHelpers.writeFile);FSHelpers.unlink=rethrowFileSystemError('Could not unlink "{path}"')(FSHelpers.unlink);FSHelpers.rmdir=rethrowFileSystemError('Could not remove directory "{path}"')(FSHelpers.rmdir);FSHelpers.listFiles=rethrowFileSystemError('Could not list files in "{path}"')(FSHelpers.listFiles);FSHelpers.isDir=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.isDir);FSHelpers.isFile=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.isFile);FSHelpers.realpath=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.realpath);FSHelpers.fileExists=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.fileExists);FSHelpers.mkdir=rethrowFileSystemError('Could not create directory "{path}"')(FSHelpers.mkdir);FSHelpers.copyRecursive=rethrowFileSystemError('Could not copy files from "{path}"')(FSHelpers.copyRecursive);const _private=new WeakMap;var P;class PHPWorker{constructor(e,r){m(this,P);this.absoluteUrl="",this.documentRoot="",this.chroot=null,w(this,P,new Map),this.onMessageListeners=[],_private.set(this,{monitor:r}),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 _private.get(this).requestHandler}async setPrimaryPHP(e){_private.set(this,{..._private.get(this),php:e})}pathToInternalUrl(e){return _private.get(this).requestHandler.pathToInternalUrl(e)}internalUrlToPath(e){return _private.get(this).requestHandler.internalUrlToPath(e)}async onDownloadProgress(e){var r;return(r=_private.get(this).monitor)==null?void 0:r.addEventListener("progress",e)}async mv(e,r){return _private.get(this).php.mv(e,r)}async rmdir(e,r){return _private.get(this).php.rmdir(e,r)}async request(e){return await _private.get(this).requestHandler.request(e)}async run(e){const{php:r,reap:s}=await this.acquirePHPInstance();try{return await r.run(e)}finally{s()}}async cli(e,r){const{php:s,reap:n}=await this.acquirePHPInstance();let i;try{i=await s.cli(e,r)}catch(o){throw n(),o}return i.finished.finally(n),i}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:r}=await _private.get(this).requestHandler.processManager.acquirePHPInstance();return this.chroot!==null&&e.chdir(this.chroot),this.registerWorkerListeners(e),{php:e,reap:r}}setSapiName(e){_private.get(this).php.setSapiName(e)}mkdir(e){return _private.get(this).php.mkdir(e)}mkdirTree(e){return _private.get(this).php.mkdirTree(e)}readFileAsText(e){return _private.get(this).php.readFileAsText(e)}readFileAsBuffer(e){return _private.get(this).php.readFileAsBuffer(e)}writeFile(e,r){return _private.get(this).php.writeFile(e,r)}unlink(e){return _private.get(this).php.unlink(e)}listFiles(e,r){return _private.get(this).php.listFiles(e,r)}isDir(e){return _private.get(this).php.isDir(e)}isFile(e){return _private.get(this).php.isFile(e)}fileExists(e){return _private.get(this).php.fileExists(e)}onMessage(e){return this.onMessageListeners.push(e),async()=>{this.onMessageListeners=this.onMessageListeners.filter(r=>r!==e)}}defineConstant(e,r){_private.get(this).php.defineConstant(e,r)}addEventListener(e,r){u(this,P).has(e)||u(this,P).set(e,new Set),u(this,P).get(e).add(r)}removeEventListener(e,r){var s;(s=u(this,P).get(e))==null||s.delete(r)}dispatchEvent(e){const r=u(this,P).get(e.type);if(r)for(const s of r)s(e)}registerWorkerListeners(e){e.addEventListener("*",async r=>{this.dispatchEvent(r)}),e.onMessage(async r=>{for(const s of this.onMessageListeners){const n=await s(r);if(n)return n}return""})}async[Symbol.asyncDispose](){var e;await((e=_private.get(this).requestHandler)==null?void 0:e[Symbol.asyncDispose]())}}P=new WeakMap;function isExitCode(t){return t instanceof Error?(t==null?void 0:t.name)==="ExitStatus"&&"status"in t:!1}const RuntimeId=Symbol("RuntimeId"),loadedRuntimes=new Map;let lastRuntimeId=0;async function loadPHPRuntime(t,...e){const r=Object.assign({},...e),[s,n,i]=makePromise(),o=t.init(currentJsRuntime,{onAbort(c){i(c),logger.logger.error(c)},ENV:{},locateFile:c=>c,...r,noInitialRun:!0,onRuntimeInitialized(){r.onRuntimeInitialized&&r.onRuntimeInitialized(o),n()}});await s;const a=++lastRuntimeId;return o.FS,o.id=a,o.originalExit=o._exit,o._exit=function(c){return o.outboundNetworkProxyServer&&(o.outboundNetworkProxyServer.close(),o.outboundNetworkProxyServer.closeAllConnections()),loadedRuntimes.delete(a),o.originalExit(c)},o[RuntimeId]=a,loadedRuntimes.set(a,o),a}function getLoadedRuntime(t){return loadedRuntimes.get(t)}const currentJsRuntime=function(){var t;return typeof process<"u"&&((t=process.release)==null?void 0:t.name)==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"}(),makePromise=()=>{const t=[],e=new Promise((r,s)=>{t.push(r,s)});return t.unshift(e),t},responseTexts={500:"Internal Server Error",502:"Bad Gateway",404:"Not Found",403:"Forbidden",401:"Unauthorized",400:"Bad Request",301:"Moved Permanently",302:"Found",307:"Temporary Redirect",308:"Permanent Redirect",204:"No Content",201:"Created",200:"OK"};class StreamedPHPResponse{constructor(e,r,s,n){this.parsedHeaders=null,this.cachedStdoutBytes=null,this.cachedStderrText=null,this.headersStream=e,this.stdout=r,this.stderr=s,this.exitCode=n}async ok(){try{const e=await this.httpStatusCode;return e>=200&&e<400}catch{return!1}}get finished(){return Promise.allSettled([this.exitCode.finally(()=>{})]).then(()=>{})}get headers(){return this.getParsedHeaders().then(e=>e.headers)}get httpStatusCode(){return this.getParsedHeaders().then(e=>e.httpStatusCode).then(e=>e!==void 0?e:this.getParsedHeaders().then(r=>r.httpStatusCode,()=>200)).catch(()=>500)}get stdoutText(){return this.stdoutBytes.then(e=>new TextDecoder().decode(e))}get stdoutBytes(){return this.cachedStdoutBytes||(this.cachedStdoutBytes=streamToBytes(this.stdout)),this.cachedStdoutBytes}get stderrText(){return this.cachedStderrText||(this.cachedStderrText=streamToText(this.stderr)),this.cachedStderrText}async getParsedHeaders(){return this.parsedHeaders||(this.parsedHeaders=parseHeadersStream(this.headersStream)),await this.parsedHeaders}}async function parseHeadersStream(t){const e=await streamToText(t);let r;try{r=JSON.parse(e)}catch{return{headers:{},httpStatusCode:200}}const s={};for(const n of r.headers){if(!n.includes(": "))continue;const i=n.indexOf(": "),o=n.substring(0,i).toLowerCase(),a=n.substring(i+2);o in s||(s[o]=[]),s[o].push(a)}return{headers:s,httpStatusCode:r.status}}async function streamToText(t){const e=t.pipeThrough(new TextDecoderStream).getReader(),r=[];for(;;){const{done:s,value:n}=await e.read();if(s)return r.join("");n&&r.push(n)}}async function streamToBytes(t){const e=t.getReader(),r=[];for(;;){const{done:s,value:n}=await e.read();if(s){const i=r.reduce((c,l)=>c+l.byteLength,0),o=new Uint8Array(i);let a=0;for(const c of r)o.set(c,a),a+=c.byteLength;return o}n&&r.push(n)}}class PHPResponse{constructor(e,r,s,n="",i=0){this.httpStatusCode=e,this.headers=r,this.bytes=s,this.exitCode=i,this.errors=n}static forHttpCode(e,r=""){return new PHPResponse(e,{},new TextEncoder().encode(r||responseTexts[e]||""))}static fromRawData(e){return new PHPResponse(e.httpStatusCode,e.headers,e.bytes,e.errors,e.exitCode)}static async fromStreamedResponse(e){return await e.finished,new PHPResponse(await e.httpStatusCode,await e.headers,await e.stdoutBytes,await e.stderrText,await e.exitCode)}ok(){return this.httpStatusCode>=200&&this.httpStatusCode<400}toRawData(){return{headers:this.headers,bytes:this.bytes,errors:this.errors,exitCode:this.exitCode,httpStatusCode:this.httpStatusCode}}get json(){return JSON.parse(this.text)}get text(){return new TextDecoder().decode(this.bytes)}}var _a;const kError=Symbol("error"),kMessage=Symbol("message");class ErrorEvent2 extends(_a=Event,_a){constructor(e,r={}){super(e),this[kError]=r.error===void 0?null:r.error,this[kMessage]=r.message===void 0?"":r.message}get error(){return this[kError]}get message(){return this[kMessage]}}Object.defineProperty(ErrorEvent2.prototype,"error",{enumerable:!0});Object.defineProperty(ErrorEvent2.prototype,"message",{enumerable:!0});const ErrorEvent=typeof globalThis.ErrorEvent=="function"?globalThis.ErrorEvent:ErrorEvent2;class UnhandledRejectionsTarget extends EventTarget{constructor(){super(...arguments),this.listenersCount=0}addEventListener(e,r,s){++this.listenersCount,super.addEventListener(e,r,s)}removeEventListener(e,r,s){--this.listenersCount,super.removeEventListener(e,r,s)}hasListeners(){return this.listenersCount>0}}function improveWASMErrorReporting(t){const e=new UnhandledRejectionsTarget;for(const r in t.wasmExports)if(typeof t.wasmExports[r]=="function"){const s=t.wasmExports[r];t.wasmExports[r]=function(...n){var i;try{return s(...n)}catch(o){if(!(o instanceof Error))throw o;t.lastAsyncifyStackSource&&(o.cause=t.lastAsyncifyStackSource);const a=clarifyErrorMessage(o,(i=t.lastAsyncifyStackSource)==null?void 0:i.stack);if(e.hasListeners()){o.message=a;const c=new ErrorEvent("error",{error:o});throw e.dispatchEvent(c),o}throw(!isExitCode(o)||o.status!==0)&&showCriticalErrorBox(a),o}}}return e}let functionsMaybeMissingFromAsyncify=[];function getFunctionsMaybeMissingFromAsyncify(){return functionsMaybeMissingFromAsyncify}function clarifyErrorMessage(t,e){if(t.message==="unreachable"){let r=UNREACHABLE_ERROR;e||(r+=`
|
|
2
2
|
|
|
3
3
|
This stack trace is lacking. For a better one initialize
|
|
4
4
|
the PHP runtime with debug: true, e.g. loadNodeRuntime('8.1', { emscriptenOptions: { debug: true } }).
|
|
@@ -33,7 +33,7 @@ CLI option:
|
|
|
33
33
|
${eol}
|
|
34
34
|
${bold} WASM ERROR${reset}${redBg}`);for(const e of t.split(`
|
|
35
35
|
`))logger.logger.log(`${eol} ${e} `);logger.logger.log(`${reset}`)}}function extractPHPFunctionsFromStack(t){try{const e=t.split(`
|
|
36
|
-
`).slice(1).map(r=>{const s=r.trim().substring(3).split(" ");return{fn:s.length>=2?s[0]:"<unknown>",isWasm:r.includes("wasm:/")}}).filter(({fn:r,isWasm:s})=>s&&!r.startsWith("dynCall_")&&!r.startsWith("invoke_")).map(({fn:r})=>r);return Array.from(new Set(e))}catch{return[]}}const STRING="string",NUMBER="number",__private__dont__use=Symbol("__private__dont__use");class PHPExecutionFailureError extends Error{constructor(e,r,s){super(e),this.response=r,this.source=s}}const PHP_INI_PATH="/internal/shared/php.ini",AUTO_PREPEND_SCRIPT="/internal/shared/auto_prepend_file.php",OPCACHE_FILE_FOLDER="/internal/shared/opcache";var C,b,T,x,F,M,_,h,$,V,G,J,Y,K,X,Q,U,Z,q,D;class PHP{constructor(t){m(this,h);m(this,C);m(this,b,!1);m(this,T,null);m(this,x,new Map([["*",new Set]]));m(this,F,[]);m(this,M,{});m(this,_,{enabled:!1,recreateRuntime:()=>0,needsRotating:!1,maxRequests:400,requestsMade:0});this.semaphore=new util.Semaphore({concurrency:1}),t!==void 0&&this.initializeRuntime(t),this.addEventListener("request.error",e=>{e.source==="php-wasm"&&(u(this,_).needsRotating=!0)})}addEventListener(t,e){u(this,x).has(t)||u(this,x).set(t,new Set),u(this,x).get(t).add(e)}removeEventListener(t,e){var r;(r=u(this,x).get(t))==null||r.delete(e)}dispatchEvent(t){const e=[...u(this,x).get(t.type)||[],...u(this,x).get("*")||[]];if(e)for(const r of e)r(t)}onMessage(t){return u(this,F).push(t),async()=>{
|
|
36
|
+
`).slice(1).map(r=>{const s=r.trim().substring(3).split(" ");return{fn:s.length>=2?s[0]:"<unknown>",isWasm:r.includes("wasm:/")}}).filter(({fn:r,isWasm:s})=>s&&!r.startsWith("dynCall_")&&!r.startsWith("invoke_")).map(({fn:r})=>r);return Array.from(new Set(e))}catch{return[]}}const STRING="string",NUMBER="number",__private__dont__use=Symbol("__private__dont__use");class PHPExecutionFailureError extends Error{constructor(e,r,s){super(e),this.response=r,this.source=s}}const PHP_INI_PATH="/internal/shared/php.ini",AUTO_PREPEND_SCRIPT="/internal/shared/auto_prepend_file.php",OPCACHE_FILE_FOLDER="/internal/shared/opcache";var C,b,T,x,F,M,_,h,$,V,G,J,Y,K,X,Q,U,Z,q,D;class PHP{constructor(t){m(this,h);m(this,C);m(this,b,!1);m(this,T,null);m(this,x,new Map([["*",new Set]]));m(this,F,[]);m(this,M,{});m(this,_,{enabled:!1,recreateRuntime:()=>0,needsRotating:!1,maxRequests:400,requestsMade:0});this.semaphore=new util.Semaphore({concurrency:1}),t!==void 0&&this.initializeRuntime(t),this.addEventListener("request.error",e=>{e.source==="php-wasm"&&(u(this,_).needsRotating=!0)})}addEventListener(t,e){u(this,x).has(t)||u(this,x).set(t,new Set),u(this,x).get(t).add(e)}removeEventListener(t,e){var r;(r=u(this,x).get(t))==null||r.delete(e)}dispatchEvent(t){const e=[...u(this,x).get(t.type)||[],...u(this,x).get("*")||[]];if(e)for(const r of e)r(t)}onMessage(t){return u(this,F).push(t),async()=>{w(this,F,u(this,F).filter(e=>e!==t))}}async setSpawnHandler(handler){typeof handler=="string"&&(handler=util.createSpawnHandler(eval(handler))),this[__private__dont__use].spawnProcess=handler}get absoluteUrl(){return this.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.documentRoot}pathToInternalUrl(t){return this.requestHandler.pathToInternalUrl(t)}internalUrlToPath(t){return this.requestHandler.internalUrlToPath(t)}initializeRuntime(t){if(this[__private__dont__use])throw new Error("PHP runtime already initialized.");const e=getLoadedRuntime(t);if(!e)throw new Error("Invalid PHP runtime id.");if(this[__private__dont__use]=e,this[__private__dont__use].ccall("wasm_set_phpini_path",null,["string"],[PHP_INI_PATH]),!this.fileExists(PHP_INI_PATH)){const r=["opcache.enable = 1","opcache.enable_cli = 1","opcache.jit = 0","opcache.interned_strings_buffer = 8","opcache.max_accelerated_files = 1000","opcache.memory_consumption = 64","opcache.max_wasted_percentage = 5","opcache.file_cache = "+OPCACHE_FILE_FOLDER,"opcache.file_cache_only = 1","opcache.file_cache_consistency_checks = 1"];this.fileExists(OPCACHE_FILE_FOLDER)||this.mkdir(OPCACHE_FILE_FOLDER),this.writeFile(PHP_INI_PATH,["auto_prepend_file="+AUTO_PREPEND_SCRIPT,"memory_limit=256M","ignore_repeated_errors = 1","error_reporting = E_ALL","display_errors = 1","html_errors = 1","display_startup_errors = On","log_errors = 1","always_populate_raw_post_data = -1","upload_max_filesize = 2000M","post_max_size = 2000M","allow_url_fopen = On","allow_url_include = Off","session.save_path = /home/web_user","implicit_flush = 1","output_buffering = 0","max_execution_time = 0","max_input_time = -1",...r].join(`
|
|
37
37
|
`))}this.fileExists(AUTO_PREPEND_SCRIPT)||this.writeFile(AUTO_PREPEND_SCRIPT,`<?php
|
|
38
38
|
// Define constants set via defineConstant() calls
|
|
39
39
|
if(file_exists('/internal/shared/consts.json')) {
|
|
@@ -48,13 +48,13 @@ ${bold} WASM ERROR${reset}${redBg}`);for(const e of t.split(`
|
|
|
48
48
|
foreach (glob('/internal/shared/preload/*.php') as $file) {
|
|
49
49
|
require_once $file;
|
|
50
50
|
}
|
|
51
|
-
`),e.onMessage=async r=>{for(const s of u(this,F)){const n=await s(r);if(n)return n}return""},
|
|
51
|
+
`),e.onMessage=async r=>{for(const s of u(this,F)){const n=await s(r);if(n)return n}return""},w(this,T,improveWASMErrorReporting(e)),this.dispatchEvent({type:"runtime.initialized"})}async setSapiName(t){if(this[__private__dont__use].ccall("wasm_set_sapi_name",NUMBER,[STRING],[t])!==0)throw new Error("Could not set SAPI name. This can only be done before the PHP WASM module is initialized.Did you already dispatch any requests?");w(this,C,t)}chdir(t){this[__private__dont__use].FS.chdir(t)}cwd(){return this[__private__dont__use].FS.cwd()}chmod(t,e){this[__private__dont__use].FS.chmod(t,e)}async request(t){if(logger.logger.warn("PHP.request() is deprecated. Please use new PHPRequestHandler() instead."),!this.requestHandler)throw new Error("No request handler available.");return this.requestHandler.request(t)}async run(t){const e=await this.runStream(t),r=await PHPResponse.fromStreamedResponse(e);if(r.exitCode!==0)throw new PHPExecutionFailureError(`PHP.run() failed with exit code ${r.exitCode}.
|
|
52
52
|
|
|
53
53
|
=== Stdout ===
|
|
54
54
|
${r.text}
|
|
55
55
|
|
|
56
56
|
=== Stderr ===
|
|
57
|
-
${r.errors}`,r,"request");return r}async runStream(t){const e=await this.semaphore.acquire();let r;const s=y(this,h,D).call(this,async()=>{if(u(this,b)||(await this[__private__dont__use].ccall("php_wasm_init",null,[],[],{isAsync:!0}),g(this,b,!0)),t.scriptPath&&!this.fileExists(t.scriptPath))throw new Error(`The script path "${t.scriptPath}" does not exist.`);y(this,h,V).call(this,t.relativeUri||""),y(this,h,K).call(this,t.method||"GET");const i=normalizeHeaders(t.headers||{}),o=i.host||"example.com:443",a=y(this,h,Y).call(this,o,t.protocol||"http");if(y(this,h,G).call(this,o),y(this,h,J).call(this,a),y(this,h,X).call(this,i),t.body&&(r=y(this,h,Q).call(this,t.body)),typeof t.code=="string")this.writeFile("/internal/eval.php",t.code),y(this,h,U).call(this,"/internal/eval.php");else if(typeof t.scriptPath=="string")y(this,h,U).call(this,t.scriptPath||"");else throw new TypeError("The request object must have either a `code` or a `scriptPath` property.");const c=y(this,h,$).call(this,t.$_SERVER,i,a);for(const d in c)y(this,h,Z).call(this,d,c[d]);const l=t.env||{};for(const d in l)y(this,h,q).call(this,d,l[d]);return await this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0})}),n=()=>{if(r)try{this[__private__dont__use].free(r)}catch(i){logger.logger.error(i)}e(),this.dispatchEvent({type:"request.end"})};return s.then(i=>(i.finished.finally(n),i),i=>{try{n()}catch{}finally{throw i}})}defineConstant(t,e){let r={};try{r=JSON.parse(this.fileExists("/internal/shared/consts.json")&&this.readFileAsText("/internal/shared/consts.json")||"{}")}catch{}this.writeFile("/internal/shared/consts.json",JSON.stringify({...r,[t]:e}))}mkdir(t){return FSHelpers.mkdir(this[__private__dont__use].FS,t)}mkdirTree(t){return FSHelpers.mkdir(this[__private__dont__use].FS,t)}readFileAsText(t){return FSHelpers.readFileAsText(this[__private__dont__use].FS,t)}readFileAsBuffer(t){return FSHelpers.readFileAsBuffer(this[__private__dont__use].FS,t)}writeFile(t,e){return FSHelpers.writeFile(this[__private__dont__use].FS,t,e)}unlink(t){return FSHelpers.unlink(this[__private__dont__use].FS,t)}mv(t,e){return FSHelpers.mv(this[__private__dont__use].FS,t,e)}rmdir(t,e={recursive:!0}){return FSHelpers.rmdir(this[__private__dont__use].FS,t,e)}listFiles(t,e={prependPath:!1}){return FSHelpers.listFiles(this[__private__dont__use].FS,t,e)}isDir(t){return FSHelpers.isDir(this[__private__dont__use].FS,t)}isFile(t){return FSHelpers.isFile(this[__private__dont__use].FS,t)}symlink(t,e){return FSHelpers.symlink(this[__private__dont__use].FS,t,e)}isSymlink(t){return FSHelpers.isSymlink(this[__private__dont__use].FS,t)}readlink(t){return FSHelpers.readlink(this[__private__dont__use].FS,t)}realpath(t){return FSHelpers.realpath(this[__private__dont__use].FS,t)}fileExists(t){return FSHelpers.fileExists(this[__private__dont__use].FS,t)}enableRuntimeRotation(t){g(this,_,{...u(this,_),enabled:!0,recreateRuntime:t.recreateRuntime,maxRequests:t.maxRequests??400})}async rotateRuntime(){if(!u(this,_).enabled)throw new Error("Runtime rotation is not enabled. Call enableRuntimeRotation() first.");await this.hotSwapPHPRuntime(await u(this,_).recreateRuntime()),u(this,_).requestsMade=0,u(this,_).needsRotating=!1}async hotSwapPHPRuntime(t){const e=this[__private__dont__use].FS,r=this.listFiles("/").map(a=>`/${a}`),s=this[__private__dont__use].spawnProcess,n=e.cwd();e.chdir("/");const i=[];for(const[a,c]of Object.entries(u(this,M)))i.push({mountHandler:c.mountHandler,vfsPath:a}),await c.unmount();try{this.exit()}catch{}this.initializeRuntime(t),s&&(this[__private__dont__use].spawnProcess=s),u(this,C)&&this.setSapiName(u(this,C));const o=this[__private__dont__use].FS;for(const a of r)a&&a!=="/request"&©MEMFSNodes(e,o,a);for(const{mountHandler:a,vfsPath:c}of i)this.mkdir(c),await this.mount(c,a);try{o.chdir(n)}catch(a){throw new Error(`Failed to restore CWD to ${n} after PHP runtime rotation.`,{cause:a})}}async mount(t,e){const r=await e(this,this[__private__dont__use].FS,t),s={mountHandler:e,unmount:async()=>{await r(),delete u(this,M)[t]}};return u(this,M)[t]=s,()=>{s.unmount()}}async cli(t,e={}){if(util.basename(t[0]??"")!=="php")return this.subProcess(t,e);u(this,b)&&(u(this,_).needsRotating=!0);const r=await this.semaphore.acquire();return await y(this,h,D).call(this,()=>{const s=e.env||{};for(const[n,i]of Object.entries(s))y(this,h,q).call(this,n,i);t=[t[0],"-c",PHP_INI_PATH,...t.slice(1)];for(const n of t)this[__private__dont__use].ccall("wasm_add_cli_arg",null,[STRING],[n]);return this[__private__dont__use].ccall("run_cli",null,[],[],{async:!0})}).then(s=>(s.exitCode.finally(r),s)).finally(()=>{u(this,_).needsRotating=!0})}async subProcess(t,e={}){const r=this[__private__dont__use].spawnProcess(t[0],t.slice(1),{env:e.env,cwd:e.cwd??this.cwd()}),s=await createInvertedReadableStream();r.on("error",i=>{s.controller.error(i)}),r.stderr.on("data",i=>{s.controller.enqueue(i)});const n=await createInvertedReadableStream();return r.stdout.on("data",i=>{n.controller.enqueue(i)}),r.on("exit",()=>{setTimeout(()=>{try{s.controller.close()}catch{}try{n.controller.close()}catch{}},0)}),new StreamedPHPResponse(new ReadableStream({start(i){i.close()}}),n.stream,s.stream,new Promise(i=>{r.on("exit",o=>{i(o)})}))}setSkipShebang(t){this[__private__dont__use].ccall("wasm_set_skip_shebang",null,[NUMBER],[t?1:0])}exit(t=0){this.dispatchEvent({type:"runtime.beforeExit"});try{this[__private__dont__use]._exit(t)}catch{}g(this,b,!1),g(this,T,null),this[__private__dont__use]&&(delete this[__private__dont__use].onMessage,delete this[__private__dont__use])}[Symbol.dispose](){this.exit(0)}}C=new WeakMap,b=new WeakMap,T=new WeakMap,x=new WeakMap,F=new WeakMap,M=new WeakMap,_=new WeakMap,h=new WeakSet,$=function(t,e,r){const s={...t||{}};s.HTTPS=s.HTTPS||r===443?"on":"off";for(const n in e){let i="HTTP_";["content-type","content-length"].includes(n.toLowerCase())&&(i=""),s[`${i}${n.toUpperCase().replace(/-/g,"_")}`]=e[n]}return s},V=function(t){this[__private__dont__use].ccall("wasm_set_request_uri",null,[STRING],[t]);let e="";t.includes("?")&&(e=t.substring(t.indexOf("?")+1)),this[__private__dont__use].ccall("wasm_set_query_string",null,[STRING],[e])},G=function(t){this[__private__dont__use].ccall("wasm_set_request_host",null,[STRING],[t])},J=function(t){this[__private__dont__use].ccall("wasm_set_request_port",null,[NUMBER],[t])},Y=function(t,e){let r;try{r=parseInt(new URL(t).port,10)}catch{}return(!r||isNaN(r)||r===80)&&(r=e==="https"?443:80),r},K=function(t){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[t])},X=function(t){t.cookie&&this[__private__dont__use].ccall("wasm_set_cookies",null,[STRING],[t.cookie]),t["content-type"]&&this[__private__dont__use].ccall("wasm_set_content_type",null,[STRING],[t["content-type"]]),t["content-length"]&&this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[parseInt(t["content-length"],10)])},Q=function(t){let e,r;typeof t=="string"?(logger.logger.warn("Passing a string as the request body is deprecated. Please use a Uint8Array instead. See https://github.com/WordPress/wordpress-playground/issues/997 for more details"),r=this[__private__dont__use].lengthBytesUTF8(t),e=r+1):(r=t.byteLength,e=t.byteLength);const s=this[__private__dont__use].malloc(e);if(!s)throw new Error("Could not allocate memory for the request body.");return typeof t=="string"?this[__private__dont__use].stringToUTF8(t,s,e+1):this[__private__dont__use].HEAPU8.set(t,s),this[__private__dont__use].ccall("wasm_set_request_body",null,[NUMBER],[s]),this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[r]),s},U=function(t){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[t])},Z=function(t,e){this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[t,e])},q=function(t,e){this[__private__dont__use].ccall("wasm_add_ENV_entry",null,[STRING,STRING],[t,e])},D=async function(t){u(this,_).enabled&&u(this,_).needsRotating&&await this.rotateRuntime(),++u(this,_).requestsMade,u(this,_).requestsMade>=u(this,_).maxRequests&&(u(this,_).needsRotating=!0);const e=this[__private__dont__use],r=await createInvertedReadableStream();e.onHeaders=p=>{a||s||r.controller.enqueue(p.slice())};let s=!1;const n=()=>{s||(s=!0,r.controller.close())},i=await createInvertedReadableStream();e.onStdout=p=>{n(),!a&&i.controller.enqueue(p.slice())};const o=await createInvertedReadableStream();e.onStderr=p=>{a||o.controller.enqueue(p.slice())};let a=!1,c;const d=(async()=>{var p;try{return await Promise.race([t(),new Promise((w,H)=>{var j;c=W=>{isExitCode(W.error)||H(W.error)},(j=u(this,T))==null||j.addEventListener("error",c,{once:!0})})])}catch(f){if(isExitCode(f))return f.status;i.controller.error(f),o.controller.error(f),r.controller.error(f),a=!0;for(const w in this)typeof this[w]=="function"&&(this[w]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});throw this.functionsMaybeMissingFromAsyncify=getFunctionsMaybeMissingFromAsyncify(),f}finally{a||(i.controller.close(),o.controller.close(),n(),a=!0),(p=u(this,T))==null||p.removeEventListener("error",c)}})().then(p=>(p!==0&&this.dispatchEvent({type:"request.error",error:new Error(`PHP.run() failed with exit code ${p}.`),source:"php-wasm"}),p),p=>{const f=p.source??"php-wasm";throw this.dispatchEvent({type:"request.error",error:p,source:f}),p});return new StreamedPHPResponse(r.stream,i.stream,o.stream,d)};function normalizeHeaders(t){const e={};for(const r in t)e[r.toLowerCase()]=t[r];return e}function copyMEMFSNodes(t,e,r){if(getNodeType(t,r)!=="memfs"||!["memfs","missing"].includes(getNodeType(e,r)))return;const s=t.lookupPath(r);if(!t.isDir(s.node.mode)){e.writeFile(r,t.readFile(r));return}e.mkdirTree(r);const n=t.readdir(r).filter(i=>i!=="."&&i!=="..");for(const i of n)copyMEMFSNodes(t,e,util.joinPaths(r,i))}async function createInvertedReadableStream(t={}){let e;const r=new Promise(i=>{e=i}),s=new ReadableStream({...t,start(i){if(e(i),t.start)return t.start(i)}}),n=await r;return{stream:s,controller:n}}const getNodeType=(t,e)=>{try{return"contents"in t.lookupPath(e,{follow:!0}).node?"memfs":"not-memfs"}catch{return"missing"}};async function getPhpIniEntries(t,e){const r=ini.parse(await t.readFileAsText(PHP_INI_PATH));if(e===void 0)return r;const s={};for(const n of e)s[n]=r[n];return s}async function setPhpIniEntries(t,e){const r=ini.parse(await t.readFileAsText(PHP_INI_PATH));for(const[s,n]of Object.entries(e))n==null?delete r[s]:r[s]=n;await t.writeFile(PHP_INI_PATH,ini.stringify(r))}async function withPHPIniValues(t,e,r){const s=await t.readFileAsText(PHP_INI_PATH);try{return await setPhpIniEntries(t,e),await r()}finally{await t.writeFile(PHP_INI_PATH,s)}}async function printDebugDetails(t,e){e&&printResponseDebugDetails(await PHPResponse.fromStreamedResponse(e)),await prettyPrintFullStackTrace(t)}async function prettyPrintFullStackTrace(t){let e=t,r=!0;for(;e;)r||process.stderr.write(`
|
|
57
|
+
${r.errors}`,r,"request");return r}async runStream(t){const e=await this.semaphore.acquire();let r;const s=y(this,h,D).call(this,async()=>{if(u(this,b)||(await this[__private__dont__use].ccall("php_wasm_init",null,[],[],{isAsync:!0}),w(this,b,!0)),t.scriptPath&&!this.fileExists(t.scriptPath))throw new Error(`The script path "${t.scriptPath}" does not exist.`);y(this,h,V).call(this,t.relativeUri||""),y(this,h,K).call(this,t.method||"GET");const i=normalizeHeaders(t.headers||{}),o=i.host||"example.com:443",a=y(this,h,Y).call(this,o,t.protocol||"http");if(y(this,h,G).call(this,o),y(this,h,J).call(this,a),y(this,h,X).call(this,i),t.body&&(r=y(this,h,Q).call(this,t.body)),typeof t.code=="string")this.writeFile("/internal/eval.php",t.code),y(this,h,U).call(this,"/internal/eval.php");else if(typeof t.scriptPath=="string")y(this,h,U).call(this,t.scriptPath||"");else throw new TypeError("The request object must have either a `code` or a `scriptPath` property.");const c=y(this,h,$).call(this,t.$_SERVER,i,a);for(const d in c)y(this,h,Z).call(this,d,c[d]);const l=t.env||{};for(const d in l)y(this,h,q).call(this,d,l[d]);return await this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0})}),n=()=>{if(r)try{this[__private__dont__use].free(r)}catch(i){logger.logger.error(i)}e(),this.dispatchEvent({type:"request.end"})};return s.then(i=>(i.finished.finally(n),i),i=>{try{n()}catch{}finally{throw i}})}defineConstant(t,e){let r={};try{r=JSON.parse(this.fileExists("/internal/shared/consts.json")&&this.readFileAsText("/internal/shared/consts.json")||"{}")}catch{}this.writeFile("/internal/shared/consts.json",JSON.stringify({...r,[t]:e}))}mkdir(t){const e=FSHelpers.mkdir(this[__private__dont__use].FS,t);return this.dispatchEvent({type:"filesystem.write"}),e}mkdirTree(t){return FSHelpers.mkdir(this[__private__dont__use].FS,t)}readFileAsText(t){return FSHelpers.readFileAsText(this[__private__dont__use].FS,t)}readFileAsBuffer(t){return FSHelpers.readFileAsBuffer(this[__private__dont__use].FS,t)}writeFile(t,e){const r=FSHelpers.writeFile(this[__private__dont__use].FS,t,e);return this.dispatchEvent({type:"filesystem.write"}),r}unlink(t){const e=FSHelpers.unlink(this[__private__dont__use].FS,t);return this.dispatchEvent({type:"filesystem.write"}),e}mv(t,e){const r=FSHelpers.mv(this[__private__dont__use].FS,t,e);return this.dispatchEvent({type:"filesystem.write"}),r}rmdir(t,e={recursive:!0}){const r=FSHelpers.rmdir(this[__private__dont__use].FS,t,e);return this.dispatchEvent({type:"filesystem.write"}),r}listFiles(t,e={prependPath:!1}){return FSHelpers.listFiles(this[__private__dont__use].FS,t,e)}isDir(t){return FSHelpers.isDir(this[__private__dont__use].FS,t)}isFile(t){return FSHelpers.isFile(this[__private__dont__use].FS,t)}symlink(t,e){return FSHelpers.symlink(this[__private__dont__use].FS,t,e)}isSymlink(t){return FSHelpers.isSymlink(this[__private__dont__use].FS,t)}readlink(t){return FSHelpers.readlink(this[__private__dont__use].FS,t)}realpath(t){return FSHelpers.realpath(this[__private__dont__use].FS,t)}fileExists(t){return FSHelpers.fileExists(this[__private__dont__use].FS,t)}enableRuntimeRotation(t){w(this,_,{...u(this,_),enabled:!0,recreateRuntime:t.recreateRuntime,maxRequests:t.maxRequests??400})}async rotateRuntime(){if(!u(this,_).enabled)throw new Error("Runtime rotation is not enabled. Call enableRuntimeRotation() first.");await this.hotSwapPHPRuntime(await u(this,_).recreateRuntime()),u(this,_).requestsMade=0,u(this,_).needsRotating=!1}async hotSwapPHPRuntime(t){const e=this[__private__dont__use].FS,r=this.listFiles("/").map(a=>`/${a}`),s=this[__private__dont__use].spawnProcess,n=e.cwd();e.chdir("/");const i=[];for(const[a,c]of Object.entries(u(this,M)))i.push({mountHandler:c.mountHandler,vfsPath:a}),await c.unmount();try{this.exit()}catch{}this.initializeRuntime(t),s&&(this[__private__dont__use].spawnProcess=s),u(this,C)&&this.setSapiName(u(this,C));const o=this[__private__dont__use].FS;for(const a of r)a&&a!=="/request"&©MEMFSNodes(e,o,a);for(const{mountHandler:a,vfsPath:c}of i)this.mkdir(c),await this.mount(c,a);try{o.chdir(n)}catch(a){throw new Error(`Failed to restore CWD to ${n} after PHP runtime rotation.`,{cause:a})}}async mount(t,e){const r=await e(this,this[__private__dont__use].FS,t),s={mountHandler:e,unmount:async()=>{await r(),delete u(this,M)[t]}};return u(this,M)[t]=s,()=>{s.unmount()}}async cli(t,e={}){if(util.basename(t[0]??"")!=="php")return this.subProcess(t,e);u(this,b)&&(u(this,_).needsRotating=!0);const r=await this.semaphore.acquire();return await y(this,h,D).call(this,()=>{const s=e.env||{};for(const[n,i]of Object.entries(s))y(this,h,q).call(this,n,i);t=[t[0],"-c",PHP_INI_PATH,...t.slice(1)];for(const n of t)this[__private__dont__use].ccall("wasm_add_cli_arg",null,[STRING],[n]);return this[__private__dont__use].ccall("run_cli",null,[],[],{async:!0})}).then(s=>(s.exitCode.finally(r),s)).finally(()=>{u(this,_).needsRotating=!0})}async subProcess(t,e={}){const r=this[__private__dont__use].spawnProcess(t[0],t.slice(1),{env:e.env,cwd:e.cwd??this.cwd()}),s=await createInvertedReadableStream();r.on("error",i=>{s.controller.error(i)}),r.stderr.on("data",i=>{s.controller.enqueue(i)});const n=await createInvertedReadableStream();return r.stdout.on("data",i=>{n.controller.enqueue(i)}),r.on("exit",()=>{setTimeout(()=>{try{s.controller.close()}catch{}try{n.controller.close()}catch{}},0)}),new StreamedPHPResponse(new ReadableStream({start(i){i.close()}}),n.stream,s.stream,new Promise(i=>{r.on("exit",o=>{i(o)})}))}setSkipShebang(t){this[__private__dont__use].ccall("wasm_set_skip_shebang",null,[NUMBER],[t?1:0])}exit(t=0){this.dispatchEvent({type:"runtime.beforeExit"});try{this[__private__dont__use]._exit(t)}catch{}w(this,b,!1),w(this,T,null),this[__private__dont__use]&&(delete this[__private__dont__use].onMessage,delete this[__private__dont__use])}[Symbol.dispose](){this.exit(0)}}C=new WeakMap,b=new WeakMap,T=new WeakMap,x=new WeakMap,F=new WeakMap,M=new WeakMap,_=new WeakMap,h=new WeakSet,$=function(t,e,r){const s={...t||{}};s.HTTPS=s.HTTPS||r===443?"on":"off";for(const n in e){let i="HTTP_";["content-type","content-length"].includes(n.toLowerCase())&&(i=""),s[`${i}${n.toUpperCase().replace(/-/g,"_")}`]=e[n]}return s},V=function(t){this[__private__dont__use].ccall("wasm_set_request_uri",null,[STRING],[t]);let e="";t.includes("?")&&(e=t.substring(t.indexOf("?")+1)),this[__private__dont__use].ccall("wasm_set_query_string",null,[STRING],[e])},G=function(t){this[__private__dont__use].ccall("wasm_set_request_host",null,[STRING],[t])},J=function(t){this[__private__dont__use].ccall("wasm_set_request_port",null,[NUMBER],[t])},Y=function(t,e){let r;try{r=parseInt(new URL(t).port,10)}catch{}return(!r||isNaN(r)||r===80)&&(r=e==="https"?443:80),r},K=function(t){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[t])},X=function(t){t.cookie&&this[__private__dont__use].ccall("wasm_set_cookies",null,[STRING],[t.cookie]),t["content-type"]&&this[__private__dont__use].ccall("wasm_set_content_type",null,[STRING],[t["content-type"]]),t["content-length"]&&this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[parseInt(t["content-length"],10)])},Q=function(t){let e,r;typeof t=="string"?(logger.logger.warn("Passing a string as the request body is deprecated. Please use a Uint8Array instead. See https://github.com/WordPress/wordpress-playground/issues/997 for more details"),r=this[__private__dont__use].lengthBytesUTF8(t),e=r+1):(r=t.byteLength,e=t.byteLength);const s=this[__private__dont__use].malloc(e);if(!s)throw new Error("Could not allocate memory for the request body.");return typeof t=="string"?this[__private__dont__use].stringToUTF8(t,s,e+1):this[__private__dont__use].HEAPU8.set(t,s),this[__private__dont__use].ccall("wasm_set_request_body",null,[NUMBER],[s]),this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[r]),s},U=function(t){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[t])},Z=function(t,e){this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[t,e])},q=function(t,e){this[__private__dont__use].ccall("wasm_add_ENV_entry",null,[STRING,STRING],[t,e])},D=async function(t){u(this,_).enabled&&u(this,_).needsRotating&&await this.rotateRuntime(),++u(this,_).requestsMade,u(this,_).requestsMade>=u(this,_).maxRequests&&(u(this,_).needsRotating=!0);const e=this[__private__dont__use],r=await createInvertedReadableStream();e.onHeaders=p=>{a||s||r.controller.enqueue(p.slice())};let s=!1;const n=()=>{s||(s=!0,r.controller.close())},i=await createInvertedReadableStream();e.onStdout=p=>{n(),!a&&i.controller.enqueue(p.slice())};const o=await createInvertedReadableStream();e.onStderr=p=>{a||o.controller.enqueue(p.slice())};let a=!1,c;const d=(async()=>{var p;try{return await Promise.race([t(),new Promise((g,H)=>{var j;c=W=>{isExitCode(W.error)||H(W.error)},(j=u(this,T))==null||j.addEventListener("error",c,{once:!0})})])}catch(f){if(isExitCode(f))return f.status;i.controller.error(f),o.controller.error(f),r.controller.error(f),a=!0;for(const g in this)typeof this[g]=="function"&&(this[g]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});throw this.functionsMaybeMissingFromAsyncify=getFunctionsMaybeMissingFromAsyncify(),f}finally{a||(i.controller.close(),o.controller.close(),n(),a=!0),(p=u(this,T))==null||p.removeEventListener("error",c)}})().then(p=>(p!==0&&this.dispatchEvent({type:"request.error",error:new Error(`PHP.run() failed with exit code ${p}.`),source:"php-wasm"}),p),p=>{const f=p.source??"php-wasm";throw this.dispatchEvent({type:"request.error",error:p,source:f}),p});return new StreamedPHPResponse(r.stream,i.stream,o.stream,d)};function normalizeHeaders(t){const e={};for(const r in t)e[r.toLowerCase()]=t[r];return e}function copyMEMFSNodes(t,e,r){if(getNodeType(t,r)!=="memfs"||!["memfs","missing"].includes(getNodeType(e,r)))return;const s=t.lookupPath(r);if(!t.isDir(s.node.mode)){e.writeFile(r,t.readFile(r));return}e.mkdirTree(r);const n=t.readdir(r).filter(i=>i!=="."&&i!=="..");for(const i of n)copyMEMFSNodes(t,e,util.joinPaths(r,i))}async function createInvertedReadableStream(t={}){let e;const r=new Promise(i=>{e=i}),s=new ReadableStream({...t,start(i){if(e(i),t.start)return t.start(i)}}),n=await r;return{stream:s,controller:n}}const getNodeType=(t,e)=>{try{return"contents"in t.lookupPath(e,{follow:!0}).node?"memfs":"not-memfs"}catch{return"missing"}};async function getPhpIniEntries(t,e){const r=ini.parse(await t.readFileAsText(PHP_INI_PATH));if(e===void 0)return r;const s={};for(const n of e)s[n]=r[n];return s}async function setPhpIniEntries(t,e){const r=ini.parse(await t.readFileAsText(PHP_INI_PATH));for(const[s,n]of Object.entries(e))n==null?delete r[s]:r[s]=n;await t.writeFile(PHP_INI_PATH,ini.stringify(r))}async function withPHPIniValues(t,e,r){const s=await t.readFileAsText(PHP_INI_PATH);try{return await setPhpIniEntries(t,e),await r()}finally{await t.writeFile(PHP_INI_PATH,s)}}async function printDebugDetails(t,e){e&&printResponseDebugDetails(await PHPResponse.fromStreamedResponse(e)),await prettyPrintFullStackTrace(t)}async function prettyPrintFullStackTrace(t){let e=t,r=!0;for(;e;)r||process.stderr.write(`
|
|
58
58
|
Caused by:
|
|
59
59
|
|
|
60
60
|
`),process.stderr.write(e.originalErrorClassName??e.name),process.stderr.write(": "+e.message+`
|
|
@@ -86,7 +86,7 @@ ${JSON.stringify(t.headers,null,2)}
|
|
|
86
86
|
`)),n.push(`\r
|
|
87
87
|
`),l instanceof File?n.push(await fileToUint8Array(l)):n.push(l),n.push(`\r
|
|
88
88
|
`);n.push(`--${e}--\r
|
|
89
|
-
`);const i=n.reduce((c,l)=>c+l.length,0),o=new Uint8Array(i);let a=0;for(const c of n)o.set(typeof c=="string"?s.encode(c):c,a),a+=c.length;return{bytes:o,contentType:r}}function fileToUint8Array(t){return t.arrayBuffer().then(e=>new Uint8Array(e))}const _default="application/octet-stream",asx="video/x-ms-asf",atom="application/atom+xml",avi="video/x-msvideo",avif="image/avif",bin="application/octet-stream",bmp="image/x-ms-bmp",cco="application/x-cocoa",css="text/css",data="application/octet-stream",deb="application/octet-stream",der="application/x-x509-ca-cert",dmg="application/octet-stream",doc="application/msword",docx="application/vnd.openxmlformats-officedocument.wordprocessingml.document",eot="application/vnd.ms-fontobject",flv="video/x-flv",gif="image/gif",gz="application/gzip",hqx="application/mac-binhex40",htc="text/x-component",html="text/html",ico="image/x-icon",iso="application/octet-stream",jad="text/vnd.sun.j2me.app-descriptor",jar="application/java-archive",jardiff="application/x-java-archive-diff",jng="image/x-jng",jnlp="application/x-java-jnlp-file",jpg="image/jpeg",jpeg="image/jpeg",js="application/javascript",json="application/json",kml="application/vnd.google-earth.kml+xml",kmz="application/vnd.google-earth.kmz",m3u8="application/vnd.apple.mpegurl",m4a="audio/x-m4a",m4v="video/x-m4v",md="text/plain",mid="audio/midi",mml="text/mathml",mng="video/x-mng",mov="video/quicktime",mp3="audio/mpeg",mp4="video/mp4",mpeg="video/mpeg",msi="application/octet-stream",odg="application/vnd.oasis.opendocument.graphics",odp="application/vnd.oasis.opendocument.presentation",ods="application/vnd.oasis.opendocument.spreadsheet",odt="application/vnd.oasis.opendocument.text",ogg="audio/ogg",otf="font/otf",pdf="application/pdf",pl="application/x-perl",png="image/png",ppt="application/vnd.ms-powerpoint",pptx="application/vnd.openxmlformats-officedocument.presentationml.presentation",prc="application/x-pilot",ps="application/postscript",ra="audio/x-realaudio",rar="application/x-rar-compressed",rpm="application/x-redhat-package-manager",rss="application/rss+xml",rtf="application/rtf",run="application/x-makeself",sea="application/x-sea",sit="application/x-stuffit",svg="image/svg+xml",swf="application/x-shockwave-flash",tcl="application/x-tcl",tar="application/x-tar",tif="image/tiff",ts="video/mp2t",ttf="font/ttf",txt="text/plain",wasm="application/wasm",wbmp="image/vnd.wap.wbmp",webm="video/webm",webp="image/webp",wml="text/vnd.wap.wml",wmlc="application/vnd.wap.wmlc",wmv="video/x-ms-wmv",woff="font/woff",woff2="font/woff2",xhtml="application/xhtml+xml",xls="application/vnd.ms-excel",xlsx="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml="text/xml",xpi="application/x-xpinstall",xspf="application/xspf+xml",zip="application/zip",mimeTypes={_default,"3gpp":"video/3gpp","7z":"application/x-7z-compressed",asx,atom,avi,avif,bin,bmp,cco,css,data,deb,der,dmg,doc,docx,eot,flv,gif,gz,hqx,htc,html,ico,iso,jad,jar,jardiff,jng,jnlp,jpg,jpeg,js,json,kml,kmz,m3u8,m4a,m4v,md,mid,mml,mng,mov,mp3,mp4,mpeg,msi,odg,odp,ods,odt,ogg,otf,pdf,pl,png,ppt,pptx,prc,ps,ra,rar,rpm,rss,rtf,run,sea,sit,svg,swf,tcl,tar,tif,ts,ttf,txt,wasm,wbmp,webm,webp,wml,wmlc,wmv,woff,woff2,xhtml,xls,xlsx,xml,xpi,xspf,zip};var S,I,L,k,A,E,N,v,R,ee,te,re;class PHPRequestHandler{constructor(e){m(this,R);m(this,S);m(this,I);m(this,L);m(this,k);m(this,A);m(this,E);m(this,N);m(this,v);const{documentRoot:r="/www/",absoluteUrl:s=typeof location=="object"?location.href:DEFAULT_BASE_URL,rewriteRules:n=[],getFileNotFoundAction:i=()=>({type:"404"})}=e;"processManager"in e?this.processManager=e.processManager:this.processManager=new PHPProcessManager({phpFactory:async c=>{const l=await e.phpFactory({...c,requestHandler:this});return l.isDir(r)||l.mkdir(r),l.chdir(r),l.requestHandler=this,l},maxPhpInstances:e.maxPhpInstances}),
|
|
89
|
+
`);const i=n.reduce((c,l)=>c+l.length,0),o=new Uint8Array(i);let a=0;for(const c of n)o.set(typeof c=="string"?s.encode(c):c,a),a+=c.length;return{bytes:o,contentType:r}}function fileToUint8Array(t){return t.arrayBuffer().then(e=>new Uint8Array(e))}const _default="application/octet-stream",asx="video/x-ms-asf",atom="application/atom+xml",avi="video/x-msvideo",avif="image/avif",bin="application/octet-stream",bmp="image/x-ms-bmp",cco="application/x-cocoa",css="text/css",data="application/octet-stream",deb="application/octet-stream",der="application/x-x509-ca-cert",dmg="application/octet-stream",doc="application/msword",docx="application/vnd.openxmlformats-officedocument.wordprocessingml.document",eot="application/vnd.ms-fontobject",flv="video/x-flv",gif="image/gif",gz="application/gzip",hqx="application/mac-binhex40",htc="text/x-component",html="text/html",ico="image/x-icon",iso="application/octet-stream",jad="text/vnd.sun.j2me.app-descriptor",jar="application/java-archive",jardiff="application/x-java-archive-diff",jng="image/x-jng",jnlp="application/x-java-jnlp-file",jpg="image/jpeg",jpeg="image/jpeg",js="application/javascript",json="application/json",kml="application/vnd.google-earth.kml+xml",kmz="application/vnd.google-earth.kmz",m3u8="application/vnd.apple.mpegurl",m4a="audio/x-m4a",m4v="video/x-m4v",md="text/plain",mid="audio/midi",mml="text/mathml",mng="video/x-mng",mov="video/quicktime",mp3="audio/mpeg",mp4="video/mp4",mpeg="video/mpeg",msi="application/octet-stream",odg="application/vnd.oasis.opendocument.graphics",odp="application/vnd.oasis.opendocument.presentation",ods="application/vnd.oasis.opendocument.spreadsheet",odt="application/vnd.oasis.opendocument.text",ogg="audio/ogg",otf="font/otf",pdf="application/pdf",pl="application/x-perl",png="image/png",ppt="application/vnd.ms-powerpoint",pptx="application/vnd.openxmlformats-officedocument.presentationml.presentation",prc="application/x-pilot",ps="application/postscript",ra="audio/x-realaudio",rar="application/x-rar-compressed",rpm="application/x-redhat-package-manager",rss="application/rss+xml",rtf="application/rtf",run="application/x-makeself",sea="application/x-sea",sit="application/x-stuffit",svg="image/svg+xml",swf="application/x-shockwave-flash",tcl="application/x-tcl",tar="application/x-tar",tif="image/tiff",ts="video/mp2t",ttf="font/ttf",txt="text/plain",wasm="application/wasm",wbmp="image/vnd.wap.wbmp",webm="video/webm",webp="image/webp",wml="text/vnd.wap.wml",wmlc="application/vnd.wap.wmlc",wmv="video/x-ms-wmv",woff="font/woff",woff2="font/woff2",xhtml="application/xhtml+xml",xls="application/vnd.ms-excel",xlsx="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml="text/xml",xpi="application/x-xpinstall",xspf="application/xspf+xml",zip="application/zip",mimeTypes={_default,"3gpp":"video/3gpp","7z":"application/x-7z-compressed",asx,atom,avi,avif,bin,bmp,cco,css,data,deb,der,dmg,doc,docx,eot,flv,gif,gz,hqx,htc,html,ico,iso,jad,jar,jardiff,jng,jnlp,jpg,jpeg,js,json,kml,kmz,m3u8,m4a,m4v,md,mid,mml,mng,mov,mp3,mp4,mpeg,msi,odg,odp,ods,odt,ogg,otf,pdf,pl,png,ppt,pptx,prc,ps,ra,rar,rpm,rss,rtf,run,sea,sit,svg,swf,tcl,tar,tif,ts,ttf,txt,wasm,wbmp,webm,webp,wml,wmlc,wmv,woff,woff2,xhtml,xls,xlsx,xml,xpi,xspf,zip};var S,I,L,k,A,E,N,v,R,ee,te,re;class PHPRequestHandler{constructor(e){m(this,R);m(this,S);m(this,I);m(this,L);m(this,k);m(this,A);m(this,E);m(this,N);m(this,v);const{documentRoot:r="/www/",absoluteUrl:s=typeof location=="object"?location.href:DEFAULT_BASE_URL,rewriteRules:n=[],getFileNotFoundAction:i=()=>({type:"404"})}=e;"processManager"in e?this.processManager=e.processManager:this.processManager=new PHPProcessManager({phpFactory:async c=>{const l=await e.phpFactory({...c,requestHandler:this});return l.isDir(r)||l.mkdir(r),l.chdir(r),l.requestHandler=this,l},maxPhpInstances:e.maxPhpInstances}),w(this,v,e.cookieStore===void 0?new HttpCookieStore:e.cookieStore),w(this,S,r);const o=new URL(s);w(this,L,o.hostname),w(this,k,o.port?Number(o.port):o.protocol==="https:"?443:80),w(this,I,(o.protocol||"").replace(":",""));const a=u(this,k)!==443&&u(this,k)!==80;w(this,A,[u(this,L),a?`:${u(this,k)}`:""].join("")),w(this,E,o.pathname.replace(/\/+$/,"")),w(this,N,[`${u(this,I)}://`,u(this,A),u(this,E)].join("")),this.rewriteRules=n,this.getFileNotFoundAction=i}async getPrimaryPhp(){return await this.processManager.getPrimaryPhp()}pathToInternalUrl(e){return e.startsWith("/")||(e=`/${e}`),`${this.absoluteUrl}${e}`}internalUrlToPath(e){const r=new URL(e,"https://playground.internal");return r.pathname.startsWith(u(this,E))&&(r.pathname=r.pathname.slice(u(this,E).length)),toRelativeUrl(r)}get absoluteUrl(){return u(this,N)}get documentRoot(){return u(this,S)}async request(e){const r=URL.canParse(e.url),s=new URL(e.url.split("#")[0],r?void 0:DEFAULT_BASE_URL),n=applyRewriteRules(removePathPrefix(decodeURIComponent(s.pathname),u(this,E)),this.rewriteRules),i=await this.getPrimaryPhp();let o=util.joinPaths(u(this,S),n);if(i.isDir(o)){if(!o.endsWith("/"))return new PHPResponse(301,{Location:[`${s.pathname}/`]},new Uint8Array(0));for(const a of["index.php","index.html"]){const c=util.joinPaths(o,a);if(i.isFile(c)){o=c;break}}}if(!i.isFile(o)){const a=this.getFileNotFoundAction(n);switch(a.type){case"response":return a.response;case"internal-redirect":o=util.joinPaths(u(this,S),a.uri);break;case"404":return PHPResponse.forHttpCode(404);default:throw new Error(`Unsupported file-not-found action type: '${a.type}'`)}}if(i.isFile(o))if(o.endsWith(".php")){const a={...e,url:s.toString()},c=await y(this,R,te).call(this,a,o);return c.ok()&&c.exitCode!==0?new PHPResponse(500,c.headers,c.bytes,c.errors,c.exitCode):c}else return y(this,R,ee).call(this,i,o);else return PHPResponse.forHttpCode(404)}async[Symbol.asyncDispose](){await this.processManager[Symbol.asyncDispose]()}}S=new WeakMap,I=new WeakMap,L=new WeakMap,k=new WeakMap,A=new WeakMap,E=new WeakMap,N=new WeakMap,v=new WeakMap,R=new WeakSet,ee=function(e,r){const s=e.readFileAsBuffer(r);return new PHPResponse(200,{"content-length":[`${s.byteLength}`],"content-type":[inferMimeType(r)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},s)},te=async function(e,r){let s;try{s=await this.processManager.acquirePHPInstance({considerPrimary:!0})}catch(n){return n instanceof MaxPhpInstancesError?PHPResponse.forHttpCode(502):PHPResponse.forHttpCode(500)}try{return await y(this,R,re).call(this,s.php,e,r)}finally{s.reap()}},re=async function(e,r,s){let n="GET";const i={host:u(this,A),...normalizeHeaders(r.headers||{})};u(this,v)&&(i.cookie=u(this,v).getCookieRequestHeader());let o=r.body;if(typeof o=="object"&&!(o instanceof Uint8Array)){n="POST";const{bytes:a,contentType:c}=await encodeAsMultipart(o);o=a,i["content-type"]=c}try{const a=await e.run({relativeUri:ensurePathPrefix(toRelativeUrl(new URL(r.url)),u(this,E)),protocol:u(this,I),method:r.method||n,$_SERVER:{REMOTE_ADDR:"127.0.0.1",DOCUMENT_ROOT:u(this,S),HTTPS:u(this,N).startsWith("https://")?"on":""},body:o,scriptPath:s,headers:i});return u(this,v)&&u(this,v).rememberCookiesFromResponseHeaders(a.headers),a}catch(a){const c=a;if(c!=null&&c.response)return c.response;throw a}};function inferMimeType(t){const e=t.split(".").pop();return mimeTypes[e]||mimeTypes._default}function applyRewriteRules(t,e){for(const r of e)if(new RegExp(r.match).test(t))return t.replace(r.match,r.replacement);return t}function rotatePHPRuntime({php:t,recreateRuntime:e,maxRequests:r=400}){return t.enableRuntimeRotation({recreateRuntime:e,maxRequests:r})}async function writeFiles(t,e,r,{rmRoot:s=!1}={}){s&&await t.isDir(e)&&await t.rmdir(e,{recursive:!0});for(const[n,i]of Object.entries(r)){const o=util.joinPaths(e,n);await t.fileExists(util.dirname(o))||await t.mkdir(util.dirname(o)),i instanceof Uint8Array||typeof i=="string"?await t.writeFile(o,i):await writeFiles(t,o,i)}}function proxyFileSystem(t,e,r){const s=Object.getOwnPropertySymbols(t)[0];for(const n of r)e.fileExists(n)||e.mkdir(n),t.fileExists(n)||t.mkdir(n),e[s].FS.mount(e[s].PROXYFS,{root:n,fs:t[s].FS},n)}function isPathToSharedFS(t,e){var i;const r=Object.getOwnPropertySymbols(t)[0],n=t[r].FS.lookupPath(e,{noent_okay:!0});return((i=n==null?void 0:n.node)==null?void 0:i.isSharedFS)??!1}function sandboxedSpawnHandlerFactory(t){return util.createSpawnHandler(async function(e,r,s){r.notifySpawn(),e[0]==="exec"&&e.shift(),(e[0].endsWith(".php")||e[0].endsWith(".phar"))&&e.unshift("php");const n=e[0].split("/").pop();if(e[0]==="/usr/bin/env"&&e[1]==="stty"&&e[2]==="size")r.stdout("18 140"),r.exit(0);else if(n==="tput"&&e[1]==="cols")r.stdout("140"),r.exit(0);else if(n==="less"){r.on("stdin",a=>{r.stdout(a)}),await new Promise(a=>{r.childProcess.stdin.on("finish",()=>{a(!0)})}),r.exit(0);return}if(!["php","ls","pwd"].includes(n??"")){r.exit(127);return}const{php:i,reap:o}=await t.acquirePHPInstance({considerPrimary:!1});try{s.cwd&&i.chdir(s.cwd);const a=i.cwd();switch(n){case"php":{const c=await i.cli(e,{env:{...s.env,SCRIPT_PATH:e[1],SHELL_PIPE:"0"}});c.stdout.pipeTo(new WritableStream({write(l){r.stdout(l)}})),c.stderr.pipeTo(new WritableStream({write(l){r.stderr(l)}})),r.exit(await c.exitCode);break}case"ls":{const c=i.listFiles(e[1]??a);for(const l of c)r.stdout(l+`
|
|
90
90
|
`);await new Promise(l=>setTimeout(l,10)),r.exit(0);break}case"pwd":{r.stdout(a+`
|
|
91
91
|
`),await new Promise(c=>setTimeout(c,10)),r.exit(0);break}}}catch(a){throw r.exit(1),a}finally{o()}})}function exposeSync(t,e,r,s=["*"]){return expose(t,e,s,r.afterResponseSent)}function createSyncProxy(t,e=[],r){return new Proxy(()=>{},{get(s,n){return n==="then"&&!e.length?{then:(i,o)=>o(createSyncProxy(t,[],r))}:createSyncProxy(t,[...e,n],r)},set(s,n,i){const[o,a]=toWireValue(i);return r.send(t,{type:MessageType.SET,path:[...e,n].map(String),value:o},a),!0},apply(s,n,i){if(e.at(-1)==="bind")return createSyncProxy(t,e.slice(0,-1),r);const[a,c]=processArguments(i),l=r.send(t,{type:MessageType.APPLY,path:e.map(String),argumentList:a},c);return fromWireValue(l)},construct(s,n){const[i,o]=processArguments(n),a=r.send(t,{type:MessageType.CONSTRUCT,path:e.map(String),argumentList:i},o);return fromWireValue(a)}})}function wrapSync(t,e){return createSyncProxy(t,[],e)}class NodeSABSyncReceiveMessageTransport{static async create(){if(!NodeSABSyncReceiveMessageTransport.receiveMessageOnPort)try{NodeSABSyncReceiveMessageTransport.receiveMessageOnPort=require("worker_threads").receiveMessageOnPort}catch{NodeSABSyncReceiveMessageTransport.receiveMessageOnPort=await import("worker_threads").then(e=>e.receiveMessageOnPort)}return new NodeSABSyncReceiveMessageTransport}constructor(){}afterResponseSent(e){const{notifyBuffer:r}=e.data;if(r){const s=new Int32Array(r);s[0]=1,Atomics.notify(s,0)}}send(e,r,s){var l;const n=new SharedArrayBuffer(4),i=new Int32Array(n);i[0]=0;const o=generateUUID();if(e.postMessage({...r,id:o,notifyBuffer:n},s),Atomics.wait(i,0,0,5e3)==="timed-out")throw new Error("Timeout waiting for response");for(;;){const d=NodeSABSyncReceiveMessageTransport.receiveMessageOnPort(e);if(((l=d.message)==null?void 0:l.id)===o)return d.message;if(!d)throw new Error("No response received")}}}/**
|
|
92
92
|
* Original, unmodified Comlink library from Google:
|
|
@@ -98,5 +98,5 @@ ${JSON.stringify(t.headers,null,2)}
|
|
|
98
98
|
* @license
|
|
99
99
|
* Copyright 2019 Google LLC
|
|
100
100
|
* SPDX-License-Identifier: Apache-2.0
|
|
101
|
-
*/const WireValueType={RAW:"RAW",HANDLER:"HANDLER"},MessageType={GET:"GET",SET:"SET",APPLY:"APPLY",CONSTRUCT:"CONSTRUCT",ENDPOINT:"ENDPOINT",RELEASE:"RELEASE"},isObject=t=>typeof t=="object"&&t!==null||typeof t=="function",proxyTransferHandler={canHandle:t=>isObject(t)&&t[proxyMarker],serialize(t){const{port1:e,port2:r}=new MessageChannel;return expose(t,e),[r,[r]]},deserialize(t){return t.start(),wrap(t)}},throwTransferHandler$1={canHandle:t=>isObject(t)&&throwMarker in t,serialize({value:t}){let e;return t instanceof Error?e={isError:!0,value:{message:t.message,name:t.name,stack:t.stack}}:e={isError:!1,value:t},[e,[]]},deserialize(t){throw t.isError?Object.assign(new Error(t.value.message),t.value):t.value}},transferHandlers=new Map([["proxy",proxyTransferHandler],["throw",throwTransferHandler$1]]);function isAllowedOrigin(t,e){for(const r of t)if(e===r||r==="*"||r instanceof RegExp&&r.test(e))return!0;return!1}function expose(t,e=globalThis,r=["*"],s){e.addEventListener("message",function n(i){if(!i||!i.data)return;if(!isAllowedOrigin(r,i.origin)){console.warn(`Invalid origin '${i.origin}' for comlink proxy`);return}const{id:o,type:a,path:c}={path:[],...i.data},l=(i.data.argumentList||[]).map(fromWireValue);let d;try{const p=c.slice(0,-1).reduce((w,H)=>w[H],t),f=c.reduce((w,H)=>w[H],t);switch(a){case MessageType.GET:d=f;break;case MessageType.SET:p[c.slice(-1)[0]]=fromWireValue(i.data.value),d=!0;break;case MessageType.APPLY:d=f.apply(p,l);break;case MessageType.CONSTRUCT:{const w=new f(...l);d=proxy(w)}break;case MessageType.ENDPOINT:{const{port1:w,port2:H}=new MessageChannel;expose(t,H),d=transfer(w,[w])}break;case MessageType.RELEASE:d=void 0;break;default:return}}catch(p){d={value:p,[throwMarker]:0}}Promise.resolve(d).catch(p=>({value:p,[throwMarker]:0})).then(p=>{const[f,w]=toWireValue(p);e.postMessage({...f,id:o},w),a===MessageType.RELEASE&&(e.removeEventListener("message",n),closeEndPoint(e),finalizer in t&&typeof t[finalizer]=="function"&&t[finalizer]())}).catch(()=>{const[p,f]=toWireValue({value:new TypeError("Unserializable return value"),[throwMarker]:0});e.postMessage({...p,id:o},f)}).finally(()=>{s==null||s(i)})}),e.start&&e.start()}function isMessagePort(t){return t.constructor.name==="MessagePort"}function closeEndPoint(t){isMessagePort(t)&&t.close()}function wrap(t,e){const r=new Map;return t.addEventListener("message",function(n){const{data:i}=n;if(!i||!i.id)return;const o=r.get(i.id);if(o)try{o(i)}finally{r.delete(i.id)}}),createProxy(t,r,[],e)}function throwIfProxyReleased(t){if(t)throw new Error("Proxy has been released and is not useable")}function releaseEndpoint(t){return requestResponseMessage(t,new Map,{type:MessageType.RELEASE}).then(()=>{closeEndPoint(t)})}const proxyCounter=new WeakMap,proxyFinalizers="FinalizationRegistry"in globalThis&&new FinalizationRegistry(t=>{const e=(proxyCounter.get(t)||0)-1;proxyCounter.set(t,e),e===0&&releaseEndpoint(t)});function registerProxy(t,e){const r=(proxyCounter.get(e)||0)+1;proxyCounter.set(e,r),proxyFinalizers&&proxyFinalizers.register(t,e,t)}function unregisterProxy(t){proxyFinalizers&&proxyFinalizers.unregister(t)}function createProxy(t,e,r=[],s=function(){}){let n=!1;const i=new Proxy(s,{get(o,a){if(throwIfProxyReleased(n),a===releaseProxy)return()=>{unregisterProxy(i),releaseEndpoint(t),e.clear(),n=!0};if(a==="then"){if(r.length===0)return{then:()=>i};const c=requestResponseMessage(t,e,{type:MessageType.GET,path:r.map(l=>l.toString())}).then(fromWireValue);return c.then.bind(c)}return createProxy(t,e,[...r,a])},set(o,a,c){throwIfProxyReleased(n);const[l,d]=toWireValue(c);return requestResponseMessage(t,e,{type:MessageType.SET,path:[...r,a].map(p=>p.toString()),value:l},d).then(fromWireValue)},apply(o,a,c){throwIfProxyReleased(n);const l=r[r.length-1];if(l===createEndpoint)return requestResponseMessage(t,e,{type:MessageType.ENDPOINT}).then(fromWireValue);if(l==="bind")return createProxy(t,e,r.slice(0,-1));const[d,p]=processArguments(c);return requestResponseMessage(t,e,{type:MessageType.APPLY,path:r.map(f=>f.toString()),argumentList:d},p).then(fromWireValue)},construct(o,a){throwIfProxyReleased(n);const[c,l]=processArguments(a);return requestResponseMessage(t,e,{type:MessageType.CONSTRUCT,path:r.map(d=>d.toString()),argumentList:c},l).then(fromWireValue)}});return registerProxy(i,t),i}function myFlat(t){return Array.prototype.concat.apply([],t)}function processArguments(t){const e=t.map(toWireValue);return[e.map(r=>r[0]),myFlat(e.map(r=>r[1]))]}const transferCache=new WeakMap;function transfer(t,e){return transferCache.set(t,e),t}function proxy(t){return Object.assign(t,{[proxyMarker]:!0})}function windowEndpoint(t,e=globalThis,r="*"){return{postMessage:(s,n)=>t.postMessage(s,r,n),addEventListener:e.addEventListener.bind(e),removeEventListener:e.removeEventListener.bind(e)}}function toWireValue(t){for(const[e,r]of transferHandlers)if(r.canHandle(t)){const[s,n]=r.serialize(t);return[{type:WireValueType.HANDLER,name:e,value:s},n]}return[{type:WireValueType.RAW,value:t},transferCache.get(t)||[]]}function fromWireValue(t){switch(t.type){case WireValueType.HANDLER:return transferHandlers.get(t.name).deserialize(t.value);case WireValueType.RAW:return t.value}}function requestResponseMessage(t,e,r,s){return new Promise(n=>{const i=generateUUID();e.set(i,n),t.start&&t.start(),t.postMessage({id:i,...r},s)})}function generateUUID(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}function nodeEndpoint(t){const e=new WeakMap;return{postMessage:t.postMessage.bind(t),addEventListener:(r,s)=>{const n=i=>{"handleEvent"in s?s.handleEvent({data:i}):s({data:i})};t.on("message",n),e.set(s,n)},removeEventListener:(r,s)=>{const n=e.get(s);n&&(t.off("message",n),e.delete(s))},start:t.start&&t.start.bind(t)}}const list=[Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError,globalThis.DOMException,globalThis.AssertionError,globalThis.SystemError].filter(Boolean).map(t=>[t.name,t]),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=t=>{toJsonWasCalled.add(t);const e=t.toJSON();return toJsonWasCalled.delete(t),e},newError=t=>{const e=errorConstructors.get(t)??Error;return e===AggregateError?new e([]):new e},destroyCircular=({from:t,seen:e,to:r,forceEnumerable:s,maxDepth:n,depth:i,useToJSON:o,serialize:a})=>{if(r||(Array.isArray(t)?r=[]:!a&&isErrorLike(t)?r=newError(t.name):r={}),e.push(t),i>=n)return r;if(o&&typeof t.toJSON=="function"&&!toJsonWasCalled.has(t))return toJSON(t);const c=l=>destroyCircular({from:l,seen:[...e],forceEnumerable:s,maxDepth:n,depth:i,useToJSON:o,serialize:a});for(const[l,d]of Object.entries(t)){if(d&&d instanceof Uint8Array&&d.constructor.name==="Buffer"){r[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){r[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){try{r[l]=d}catch{}continue}if(!e.includes(t[l])){i++,r[l]=c(t[l]);continue}r[l]="[Circular]"}}if(a||r instanceof Error)for(const{property:l,enumerable:d}of errorProperties)t[l]!==void 0&&t[l]!==null&&Object.defineProperty(r,l,{value:isErrorLike(t[l])||Array.isArray(t[l])?c(t[l]):t[l],enumerable:s?!0:d,configurable:!0,writable:!0});return r};function serializeError(t,e={}){const{maxDepth:r=Number.POSITIVE_INFINITY,useToJSON:s=!0}=e;return typeof t=="object"&&t!==null?destroyCircular({from:t,seen:[],forceEnumerable:!0,maxDepth:r,depth:0,useToJSON:s,serialize:!0}):typeof t=="function"?`[Function: ${t.name||"anonymous"}]`:t}function deserializeError(t,e={}){const{maxDepth:r=Number.POSITIVE_INFINITY}=e;return t instanceof Error?t:isMinimumViableSerializedError(t)?destroyCircular({from:t,seen:[],to:newError(t.name),maxDepth:r,depth:0,serialize:!1}):new NonError(t)}function isErrorLike(t){return!!t&&typeof t=="object"&&typeof t.name=="string"&&typeof t.message=="string"&&typeof t.stack=="string"}function isMinimumViableSerializedError(t){return!!t&&typeof t=="object"&&typeof t.message=="string"&&!Array.isArray(t)}async function consumeAPISync(t){setupTransferHandlers();const e=await NodeSABSyncReceiveMessageTransport.create();return wrapSync(t,e)}function consumeAPI(t,e=void 0){setupTransferHandlers();let r;(typeof document>"u"?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&_documentCurrentScript.tagName.toUpperCase()==="SCRIPT"&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href).startsWith("file://")?r=nodeEndpoint(t):r=t instanceof Worker?t:windowEndpoint(t,e);const n=wrap(r),i=proxyClone(n);return new Proxy(i,{get:(o,a)=>a==="isConnected"?async()=>{for(;;)try{await runWithTimeout(n.isConnected(),200);break}catch{}}:n[a]})}async function runWithTimeout(t,e){return new Promise((r,s)=>{setTimeout(s,e),t.then(r)})}function exposeAPI(t,e,r){const{setReady:s,setFailed:n,exposedApi:i}=prepareForExpose(t,e);let o;return r?o=nodeEndpoint(r):o=typeof window<"u"?windowEndpoint(self.parent):void 0,expose(i,o),[s,n,i]}async function exposeSyncAPI(t,e){const{setReady:r,setFailed:s,exposedApi:n}=prepareForExpose(t),i=await NodeSABSyncReceiveMessageTransport.create(),o=nodeEndpoint(e);return exposeSync(n,o,i),[r,s,n]}function prepareForExpose(t,e){setupTransferHandlers();const r=Promise.resolve();let s,n;const i=new Promise((c,l)=>{s=c,n=l}),o=proxyClone(t),a=new Proxy(o,{get:(c,l)=>l==="isConnected"?()=>r:l==="isReady"?()=>i:l in c?c[l]:e==null?void 0:e[l]});return{setReady:s,setFailed:n,exposedApi:a}}let isTransferHandlersSetup=!1;function setupTransferHandlers(){if(isTransferHandlersSetup)return;isTransferHandlersSetup=!0,transferHandlers.set("EVENT",{canHandle:r=>r instanceof CustomEvent,serialize:r=>[{detail:r.detail},[]],deserialize:r=>r}),transferHandlers.set("FUNCTION",{canHandle:r=>typeof r=="function",serialize(r){const{port1:s,port2:n}=new MessageChannel;return expose(r,s),[n,[n]]},deserialize(r){return r.start(),wrap(r)}}),transferHandlers.set("MESSAGE_PORT",{canHandle:r=>r instanceof MessagePort,serialize(r){return[r,[r]]},deserialize(r){return r}}),transferHandlers.set("PHPResponse",{canHandle:r=>typeof r=="object"&&r!==null&&"headers"in r&&"bytes"in r&&"errors"in r&&"exitCode"in r&&"httpStatusCode"in r,serialize(r){return[r.toRawData(),[]]},deserialize(r){return PHPResponse.fromRawData(r)}});const t=transferHandlers.get("throw"),e=t==null?void 0:t.serialize;t.serialize=({value:r})=>{const s=e({value:r});return r.response&&(s[0].value.response=r.response),r.source&&(s[0].value.source=r.source),s},transferHandlers.set("StreamedPHPResponse",{canHandle:r=>r instanceof StreamedPHPResponse,serialize(r){const s=supportsTransferableStreams(),n=promiseToPort(r.exitCode);if(s)return[{__type:"StreamedPHPResponse",headers:r.headersStream,stdout:r.stdout,stderr:r.stderr,exitCodePort:n},[n]];const i=streamToPort(r.headersStream),o=streamToPort(r.stdout),a=streamToPort(r.stderr);return[{__type:"StreamedPHPResponse",headersPort:i,stdoutPort:o,stderrPort:a,exitCodePort:n},[i,o,a,n]]},deserialize(r){if(r.headers&&r.stdout&&r.stderr){const a=portToPromise(r.exitCodePort);return new StreamedPHPResponse(r.headers,r.stdout,r.stderr,a)}const s=portToStream(r.headersPort),n=portToStream(r.stdoutPort),i=portToStream(r.stderrPort),o=portToPromise(r.exitCodePort);return new StreamedPHPResponse(s,n,i,o)}})}function supportsTransferableStreams(){try{if(typeof ReadableStream>"u")return!1;const{port1:t}=new MessageChannel,e=new ReadableStream;t.postMessage(e);try{t.close()}catch{}return!0}catch{return!1}}function streamToPort(t){const{port1:e,port2:r}=new MessageChannel;return(async()=>{const s=t.getReader();try{for(;;){const{done:n,value:i}=await s.read();if(n){try{e.postMessage({t:"close"})}catch{}try{e.close()}catch{}break}if(i){const o=i.byteOffset===0&&i.byteLength===i.buffer.byteLength?i:i.slice(),a=o.buffer;try{e.postMessage({t:"chunk",b:a},[a])}catch{e.postMessage({t:"chunk",b:o.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{}}})(),r}function portToStream(t){return new ReadableStream({start(e){const r=n=>{const i=n.data;if(i)switch(i.t){case"chunk":e.enqueue(new Uint8Array(i.b));break;case"close":e.close(),s();break;case"error":e.error(new Error(i.m||"Stream error")),s();break}},s=()=>{var n;try{(n=t.removeEventListener)==null||n.call(t,"message",r)}catch{}try{t.onmessage=null}catch{}try{t.close()}catch{}};t.addEventListener?t.addEventListener("message",r):t.on?t.on("message",n=>r({data:n})):t.onmessage=r,typeof t.start=="function"&&t.start()},cancel(){try{t.close()}catch{}}})}function promiseToPort(t){const{port1:e,port2:r}=new MessageChannel;return t.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{}}),r}function portToPromise(t){return new Promise((e,r)=>{const s=i=>{const o=i.data;o&&(o.t==="resolve"?(n(),e(o.v)):o.t==="reject"&&(n(),r(new Error(o.m||""))))},n=()=>{var i;try{(i=t.removeEventListener)==null||i.call(t,"message",s)}catch{}try{t.onmessage=null}catch{}try{t.close()}catch{}};t.addEventListener?t.addEventListener("message",s):t.on?t.on("message",i=>s({data:i})):t.onmessage=s,typeof t.start=="function"&&t.start()})}const throwTransferHandler=transferHandlers.get("throw"),throwTransferHandlerCustom={canHandle:throwTransferHandler.canHandle,serialize:({value:t})=>{let e;return t instanceof Error?(e={isError:!0,value:serializeError(t)},e.value.originalErrorClassName=t.constructor.name):e={isError:!1,value:t},[e,[]]},deserialize:t=>{if(t.isError){const e=deserializeError(t.value),r=new Error("Comlink method call failed");let s=e;for(;s.cause;)s=s.cause;throw s.cause=r,e}throw t.value}};transferHandlers.set("throw",throwTransferHandlerCustom);function proxyClone(t){return new Proxy(t,{get(e,r){switch(typeof e[r]){case"function":return(...s)=>e[r](...s);case"object":return e[r]===null?e[r]:proxyClone(e[r]);case"undefined":case"number":case"string":return e[r];default:return proxy(e[r])}}})}exports.DEFAULT_BASE_URL=DEFAULT_BASE_URL;exports.FSHelpers=FSHelpers;exports.HttpCookieStore=HttpCookieStore;exports.LatestSupportedPHPVersion=LatestSupportedPHPVersion;exports.PHP=PHP;exports.PHPExecutionFailureError=PHPExecutionFailureError;exports.PHPProcessManager=PHPProcessManager;exports.PHPRequestHandler=PHPRequestHandler;exports.PHPResponse=PHPResponse;exports.PHPWorker=PHPWorker;exports.StreamedPHPResponse=StreamedPHPResponse;exports.SupportedPHPVersions=SupportedPHPVersions;exports.SupportedPHPVersionsList=SupportedPHPVersionsList;exports.UnhandledRejectionsTarget=UnhandledRejectionsTarget;exports.__private__dont__use=__private__dont__use;exports.applyRewriteRules=applyRewriteRules;exports.consumeAPI=consumeAPI;exports.consumeAPISync=consumeAPISync;exports.ensurePathPrefix=ensurePathPrefix;exports.exposeAPI=exposeAPI;exports.exposeSyncAPI=exposeSyncAPI;exports.getLoadedRuntime=getLoadedRuntime;exports.getPhpIniEntries=getPhpIniEntries;exports.isExitCode=isExitCode;exports.isPathToSharedFS=isPathToSharedFS;exports.iterateFiles=iteratePhpFiles;exports.loadPHPRuntime=loadPHPRuntime;exports.prettyPrintFullStackTrace=prettyPrintFullStackTrace;exports.printDebugDetails=printDebugDetails;exports.printResponseDebugDetails=printResponseDebugDetails;exports.proxyFileSystem=proxyFileSystem;exports.removePathPrefix=removePathPrefix;exports.rotatePHPRuntime=rotatePHPRuntime;exports.sandboxedSpawnHandlerFactory=sandboxedSpawnHandlerFactory;exports.setPhpIniEntries=setPhpIniEntries;exports.toRelativeUrl=toRelativeUrl;exports.withPHPIniValues=withPHPIniValues;exports.writeFiles=writeFiles;exports.writeFilesStreamToPhp=writeFilesStreamToPhp;
|
|
101
|
+
*/const WireValueType={RAW:"RAW",HANDLER:"HANDLER"},MessageType={GET:"GET",SET:"SET",APPLY:"APPLY",CONSTRUCT:"CONSTRUCT",ENDPOINT:"ENDPOINT",RELEASE:"RELEASE"},isObject=t=>typeof t=="object"&&t!==null||typeof t=="function",proxyTransferHandler={canHandle:t=>isObject(t)&&t[proxyMarker],serialize(t){const{port1:e,port2:r}=new MessageChannel;return expose(t,e),[r,[r]]},deserialize(t){return t.start(),wrap(t)}},throwTransferHandler$1={canHandle:t=>isObject(t)&&throwMarker in t,serialize({value:t}){let e;return t instanceof Error?e={isError:!0,value:{message:t.message,name:t.name,stack:t.stack}}:e={isError:!1,value:t},[e,[]]},deserialize(t){throw t.isError?Object.assign(new Error(t.value.message),t.value):t.value}},transferHandlers=new Map([["proxy",proxyTransferHandler],["throw",throwTransferHandler$1]]);function isAllowedOrigin(t,e){for(const r of t)if(e===r||r==="*"||r instanceof RegExp&&r.test(e))return!0;return!1}function expose(t,e=globalThis,r=["*"],s){e.addEventListener("message",function n(i){if(!i||!i.data)return;if(!isAllowedOrigin(r,i.origin)){console.warn(`Invalid origin '${i.origin}' for comlink proxy`);return}const{id:o,type:a,path:c}={path:[],...i.data},l=(i.data.argumentList||[]).map(fromWireValue);let d;try{const p=c.slice(0,-1).reduce((g,H)=>g[H],t),f=c.reduce((g,H)=>g[H],t);switch(a){case MessageType.GET:d=f;break;case MessageType.SET:p[c.slice(-1)[0]]=fromWireValue(i.data.value),d=!0;break;case MessageType.APPLY:d=f.apply(p,l);break;case MessageType.CONSTRUCT:{const g=new f(...l);d=proxy(g)}break;case MessageType.ENDPOINT:{const{port1:g,port2:H}=new MessageChannel;expose(t,H),d=transfer(g,[g])}break;case MessageType.RELEASE:d=void 0;break;default:return}}catch(p){d={value:p,[throwMarker]:0}}Promise.resolve(d).catch(p=>({value:p,[throwMarker]:0})).then(p=>{const[f,g]=toWireValue(p);e.postMessage({...f,id:o},g),a===MessageType.RELEASE&&(e.removeEventListener("message",n),closeEndPoint(e),finalizer in t&&typeof t[finalizer]=="function"&&t[finalizer]())}).catch(()=>{const[p,f]=toWireValue({value:new TypeError("Unserializable return value"),[throwMarker]:0});e.postMessage({...p,id:o},f)}).finally(()=>{s==null||s(i)})}),e.start&&e.start()}function isMessagePort(t){return t.constructor.name==="MessagePort"}function closeEndPoint(t){isMessagePort(t)&&t.close()}function wrap(t,e){const r=new Map;return t.addEventListener("message",function(n){const{data:i}=n;if(!i||!i.id)return;const o=r.get(i.id);if(o)try{o(i)}finally{r.delete(i.id)}}),createProxy(t,r,[],e)}function throwIfProxyReleased(t){if(t)throw new Error("Proxy has been released and is not useable")}function releaseEndpoint(t){return requestResponseMessage(t,new Map,{type:MessageType.RELEASE}).then(()=>{closeEndPoint(t)})}const proxyCounter=new WeakMap,proxyFinalizers="FinalizationRegistry"in globalThis&&new FinalizationRegistry(t=>{const e=(proxyCounter.get(t)||0)-1;proxyCounter.set(t,e),e===0&&releaseEndpoint(t)});function registerProxy(t,e){const r=(proxyCounter.get(e)||0)+1;proxyCounter.set(e,r),proxyFinalizers&&proxyFinalizers.register(t,e,t)}function unregisterProxy(t){proxyFinalizers&&proxyFinalizers.unregister(t)}function createProxy(t,e,r=[],s=function(){}){let n=!1;const i=new Proxy(s,{get(o,a){if(throwIfProxyReleased(n),a===releaseProxy)return()=>{unregisterProxy(i),releaseEndpoint(t),e.clear(),n=!0};if(a==="then"){if(r.length===0)return{then:()=>i};const c=requestResponseMessage(t,e,{type:MessageType.GET,path:r.map(l=>l.toString())}).then(fromWireValue);return c.then.bind(c)}return createProxy(t,e,[...r,a])},set(o,a,c){throwIfProxyReleased(n);const[l,d]=toWireValue(c);return requestResponseMessage(t,e,{type:MessageType.SET,path:[...r,a].map(p=>p.toString()),value:l},d).then(fromWireValue)},apply(o,a,c){throwIfProxyReleased(n);const l=r[r.length-1];if(l===createEndpoint)return requestResponseMessage(t,e,{type:MessageType.ENDPOINT}).then(fromWireValue);if(l==="bind")return createProxy(t,e,r.slice(0,-1));const[d,p]=processArguments(c);return requestResponseMessage(t,e,{type:MessageType.APPLY,path:r.map(f=>f.toString()),argumentList:d},p).then(fromWireValue)},construct(o,a){throwIfProxyReleased(n);const[c,l]=processArguments(a);return requestResponseMessage(t,e,{type:MessageType.CONSTRUCT,path:r.map(d=>d.toString()),argumentList:c},l).then(fromWireValue)}});return registerProxy(i,t),i}function myFlat(t){return Array.prototype.concat.apply([],t)}function processArguments(t){const e=t.map(toWireValue);return[e.map(r=>r[0]),myFlat(e.map(r=>r[1]))]}const transferCache=new WeakMap;function transfer(t,e){return transferCache.set(t,e),t}function proxy(t){return Object.assign(t,{[proxyMarker]:!0})}function windowEndpoint(t,e=globalThis,r="*"){return{postMessage:(s,n)=>t.postMessage(s,r,n),addEventListener:e.addEventListener.bind(e),removeEventListener:e.removeEventListener.bind(e)}}function toWireValue(t){for(const[e,r]of transferHandlers)if(r.canHandle(t)){const[s,n]=r.serialize(t);return[{type:WireValueType.HANDLER,name:e,value:s},n]}return[{type:WireValueType.RAW,value:t},transferCache.get(t)||[]]}function fromWireValue(t){switch(t.type){case WireValueType.HANDLER:return transferHandlers.get(t.name).deserialize(t.value);case WireValueType.RAW:return t.value}}function requestResponseMessage(t,e,r,s){return new Promise(n=>{const i=generateUUID();e.set(i,n),t.start&&t.start(),t.postMessage({id:i,...r},s)})}function generateUUID(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}function nodeEndpoint(t){const e=new WeakMap;return{postMessage:t.postMessage.bind(t),addEventListener:(r,s)=>{const n=i=>{"handleEvent"in s?s.handleEvent({data:i}):s({data:i})};t.on("message",n),e.set(s,n)},removeEventListener:(r,s)=>{const n=e.get(s);n&&(t.off("message",n),e.delete(s))},start:t.start&&t.start.bind(t)}}const list=[Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError,globalThis.DOMException,globalThis.AssertionError,globalThis.SystemError].filter(Boolean).map(t=>[t.name,t]),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=t=>{toJsonWasCalled.add(t);const e=t.toJSON();return toJsonWasCalled.delete(t),e},newError=t=>{const e=errorConstructors.get(t)??Error;return e===AggregateError?new e([]):new e},destroyCircular=({from:t,seen:e,to:r,forceEnumerable:s,maxDepth:n,depth:i,useToJSON:o,serialize:a})=>{if(r||(Array.isArray(t)?r=[]:!a&&isErrorLike(t)?r=newError(t.name):r={}),e.push(t),i>=n)return r;if(o&&typeof t.toJSON=="function"&&!toJsonWasCalled.has(t))return toJSON(t);const c=l=>destroyCircular({from:l,seen:[...e],forceEnumerable:s,maxDepth:n,depth:i,useToJSON:o,serialize:a});for(const[l,d]of Object.entries(t)){if(d&&d instanceof Uint8Array&&d.constructor.name==="Buffer"){r[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){r[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){try{r[l]=d}catch{}continue}if(!e.includes(t[l])){i++,r[l]=c(t[l]);continue}r[l]="[Circular]"}}if(a||r instanceof Error)for(const{property:l,enumerable:d}of errorProperties)t[l]!==void 0&&t[l]!==null&&Object.defineProperty(r,l,{value:isErrorLike(t[l])||Array.isArray(t[l])?c(t[l]):t[l],enumerable:s?!0:d,configurable:!0,writable:!0});return r};function serializeError(t,e={}){const{maxDepth:r=Number.POSITIVE_INFINITY,useToJSON:s=!0}=e;return typeof t=="object"&&t!==null?destroyCircular({from:t,seen:[],forceEnumerable:!0,maxDepth:r,depth:0,useToJSON:s,serialize:!0}):typeof t=="function"?`[Function: ${t.name||"anonymous"}]`:t}function deserializeError(t,e={}){const{maxDepth:r=Number.POSITIVE_INFINITY}=e;return t instanceof Error?t:isMinimumViableSerializedError(t)?destroyCircular({from:t,seen:[],to:newError(t.name),maxDepth:r,depth:0,serialize:!1}):new NonError(t)}function isErrorLike(t){return!!t&&typeof t=="object"&&typeof t.name=="string"&&typeof t.message=="string"&&typeof t.stack=="string"}function isMinimumViableSerializedError(t){return!!t&&typeof t=="object"&&typeof t.message=="string"&&!Array.isArray(t)}async function consumeAPISync(t){setupTransferHandlers();const e=await NodeSABSyncReceiveMessageTransport.create();return wrapSync(t,e)}function consumeAPI(t,e=void 0){setupTransferHandlers();let r;(typeof document>"u"?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&_documentCurrentScript.tagName.toUpperCase()==="SCRIPT"&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href).startsWith("file://")?r=nodeEndpoint(t):r=t instanceof Worker?t:windowEndpoint(t,e);const n=wrap(r),i=proxyClone(n);return new Proxy(i,{get:(o,a)=>a==="isConnected"?async()=>{for(;;)try{await runWithTimeout(n.isConnected(),200);break}catch{}}:n[a]})}async function runWithTimeout(t,e){return new Promise((r,s)=>{setTimeout(s,e),t.then(r)})}function exposeAPI(t,e,r){const{setReady:s,setFailed:n,exposedApi:i}=prepareForExpose(t,e);let o;return r?o=nodeEndpoint(r):o=typeof window<"u"?windowEndpoint(self.parent):void 0,expose(i,o),[s,n,i]}async function exposeSyncAPI(t,e){const{setReady:r,setFailed:s,exposedApi:n}=prepareForExpose(t),i=await NodeSABSyncReceiveMessageTransport.create(),o=nodeEndpoint(e);return exposeSync(n,o,i),[r,s,n]}function prepareForExpose(t,e){setupTransferHandlers();const r=Promise.resolve();let s,n;const i=new Promise((c,l)=>{s=c,n=l}),o=proxyClone(t),a=new Proxy(o,{get:(c,l)=>l==="isConnected"?()=>r:l==="isReady"?()=>i:l in c?c[l]:e==null?void 0:e[l]});return{setReady:s,setFailed:n,exposedApi:a}}let isTransferHandlersSetup=!1;function setupTransferHandlers(){if(isTransferHandlersSetup)return;isTransferHandlersSetup=!0,transferHandlers.set("EVENT",{canHandle:r=>r instanceof CustomEvent,serialize:r=>[{detail:r.detail},[]],deserialize:r=>r}),transferHandlers.set("FUNCTION",{canHandle:r=>typeof r=="function",serialize(r){const{port1:s,port2:n}=new MessageChannel;return expose(r,s),[n,[n]]},deserialize(r){return r.start(),wrap(r)}}),transferHandlers.set("MESSAGE_PORT",{canHandle:r=>r instanceof MessagePort,serialize(r){return[r,[r]]},deserialize(r){return r}}),transferHandlers.set("PHPResponse",{canHandle:r=>typeof r=="object"&&r!==null&&"headers"in r&&"bytes"in r&&"errors"in r&&"exitCode"in r&&"httpStatusCode"in r,serialize(r){return[r.toRawData(),[]]},deserialize(r){return PHPResponse.fromRawData(r)}});const t=transferHandlers.get("throw"),e=t==null?void 0:t.serialize;t.serialize=({value:r})=>{const s=e({value:r});return r.response&&(s[0].value.response=r.response),r.source&&(s[0].value.source=r.source),s},transferHandlers.set("StreamedPHPResponse",{canHandle:r=>r instanceof StreamedPHPResponse,serialize(r){const s=supportsTransferableStreams(),n=promiseToPort(r.exitCode);if(s)return[{__type:"StreamedPHPResponse",headers:r.headersStream,stdout:r.stdout,stderr:r.stderr,exitCodePort:n},[n]];const i=streamToPort(r.headersStream),o=streamToPort(r.stdout),a=streamToPort(r.stderr);return[{__type:"StreamedPHPResponse",headersPort:i,stdoutPort:o,stderrPort:a,exitCodePort:n},[i,o,a,n]]},deserialize(r){if(r.headers&&r.stdout&&r.stderr){const a=portToPromise(r.exitCodePort);return new StreamedPHPResponse(r.headers,r.stdout,r.stderr,a)}const s=portToStream(r.headersPort),n=portToStream(r.stdoutPort),i=portToStream(r.stderrPort),o=portToPromise(r.exitCodePort);return new StreamedPHPResponse(s,n,i,o)}})}function supportsTransferableStreams(){try{if(typeof ReadableStream>"u")return!1;const{port1:t}=new MessageChannel,e=new ReadableStream;t.postMessage(e);try{t.close()}catch{}return!0}catch{return!1}}function streamToPort(t){const{port1:e,port2:r}=new MessageChannel;return(async()=>{const s=t.getReader();try{for(;;){const{done:n,value:i}=await s.read();if(n){try{e.postMessage({t:"close"})}catch{}try{e.close()}catch{}break}if(i){const o=i.byteOffset===0&&i.byteLength===i.buffer.byteLength?i:i.slice(),a=o.buffer;try{e.postMessage({t:"chunk",b:a},[a])}catch{e.postMessage({t:"chunk",b:o.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{}}})(),r}function portToStream(t){return new ReadableStream({start(e){const r=n=>{const i=n.data;if(i)switch(i.t){case"chunk":e.enqueue(new Uint8Array(i.b));break;case"close":e.close(),s();break;case"error":e.error(new Error(i.m||"Stream error")),s();break}},s=()=>{var n;try{(n=t.removeEventListener)==null||n.call(t,"message",r)}catch{}try{t.onmessage=null}catch{}try{t.close()}catch{}};t.addEventListener?t.addEventListener("message",r):t.on?t.on("message",n=>r({data:n})):t.onmessage=r,typeof t.start=="function"&&t.start()},cancel(){try{t.close()}catch{}}})}function promiseToPort(t){const{port1:e,port2:r}=new MessageChannel;return t.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{}}),r}function portToPromise(t){return new Promise((e,r)=>{const s=i=>{const o=i.data;o&&(o.t==="resolve"?(n(),e(o.v)):o.t==="reject"&&(n(),r(new Error(o.m||""))))},n=()=>{var i;try{(i=t.removeEventListener)==null||i.call(t,"message",s)}catch{}try{t.onmessage=null}catch{}try{t.close()}catch{}};t.addEventListener?t.addEventListener("message",s):t.on?t.on("message",i=>s({data:i})):t.onmessage=s,typeof t.start=="function"&&t.start()})}const throwTransferHandler=transferHandlers.get("throw"),throwTransferHandlerCustom={canHandle:throwTransferHandler.canHandle,serialize:({value:t})=>{let e;return t instanceof Error?(e={isError:!0,value:serializeError(t)},e.value.originalErrorClassName=t.constructor.name):e={isError:!1,value:t},[e,[]]},deserialize:t=>{if(t.isError){const e=deserializeError(t.value),r=new Error("Comlink method call failed");let s=e;for(;s.cause;)s=s.cause;throw s.cause=r,e}throw t.value}};transferHandlers.set("throw",throwTransferHandlerCustom);function proxyClone(t){return new Proxy(t,{get(e,r){switch(typeof e[r]){case"function":return(...s)=>e[r](...s);case"object":return e[r]===null?e[r]:proxyClone(e[r]);case"undefined":case"number":case"string":return e[r];default:return proxy(e[r])}}})}exports.DEFAULT_BASE_URL=DEFAULT_BASE_URL;exports.FSHelpers=FSHelpers;exports.HttpCookieStore=HttpCookieStore;exports.LatestSupportedPHPVersion=LatestSupportedPHPVersion;exports.PHP=PHP;exports.PHPExecutionFailureError=PHPExecutionFailureError;exports.PHPProcessManager=PHPProcessManager;exports.PHPRequestHandler=PHPRequestHandler;exports.PHPResponse=PHPResponse;exports.PHPWorker=PHPWorker;exports.StreamedPHPResponse=StreamedPHPResponse;exports.SupportedPHPVersions=SupportedPHPVersions;exports.SupportedPHPVersionsList=SupportedPHPVersionsList;exports.UnhandledRejectionsTarget=UnhandledRejectionsTarget;exports.__private__dont__use=__private__dont__use;exports.applyRewriteRules=applyRewriteRules;exports.consumeAPI=consumeAPI;exports.consumeAPISync=consumeAPISync;exports.ensurePathPrefix=ensurePathPrefix;exports.exposeAPI=exposeAPI;exports.exposeSyncAPI=exposeSyncAPI;exports.getLoadedRuntime=getLoadedRuntime;exports.getPhpIniEntries=getPhpIniEntries;exports.isExitCode=isExitCode;exports.isPathToSharedFS=isPathToSharedFS;exports.iterateFiles=iteratePhpFiles;exports.loadPHPRuntime=loadPHPRuntime;exports.prettyPrintFullStackTrace=prettyPrintFullStackTrace;exports.printDebugDetails=printDebugDetails;exports.printResponseDebugDetails=printResponseDebugDetails;exports.proxyFileSystem=proxyFileSystem;exports.removePathPrefix=removePathPrefix;exports.rotatePHPRuntime=rotatePHPRuntime;exports.sandboxedSpawnHandlerFactory=sandboxedSpawnHandlerFactory;exports.setPhpIniEntries=setPhpIniEntries;exports.toRelativeUrl=toRelativeUrl;exports.withPHPIniValues=withPHPIniValues;exports.writeFiles=writeFiles;exports.writeFilesStreamToPhp=writeFilesStreamToPhp;
|
|
102
102
|
//# sourceMappingURL=index.cjs.map
|