@php-wasm/universal 3.1.14 → 3.1.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 +5 -5
- package/index.cjs.map +1 -1
- package/index.js +93 -52
- package/index.js.map +1 -1
- package/lib/universal-php.d.ts +1 -0
- package/package.json +7 -7
package/index.cjs
CHANGED
|
@@ -33,7 +33,7 @@ CLI option:
|
|
|
33
33
|
${eol}
|
|
34
34
|
${bold} WASM ERROR${reset}${redBg}`);for(const e of r.split(`
|
|
35
35
|
`))logger.logger.log(`${eol} ${e} `);logger.logger.log(`${reset}`)}}function extractPHPFunctionsFromStack(r){try{const e=r.split(`
|
|
36
|
-
`).slice(1).map(t=>{const s=t.trim().substring(3).split(" ");return{fn:s.length>=2?s[0]:"<unknown>",isWasm:t.includes("wasm:/")}}).filter(({fn:t,isWasm:s})=>s&&!t.startsWith("dynCall_")&&!t.startsWith("invoke_")).map(({fn:t})=>t);return Array.from(new Set(e))}catch{return[]}}const STRING="string",NUMBER="number",__private__dont__use=Symbol("__private__dont__use");class PHPExecutionFailureError extends Error{constructor(e,t,s){super(e),this.response=t,this.source=s}}const PHP_INI_PATH="/internal/shared/php.ini",AUTO_PREPEND_SCRIPT="/internal/shared/auto_prepend_file.php",OPCACHE_FILE_FOLDER="/internal/shared/opcache";var
|
|
36
|
+
`).slice(1).map(t=>{const s=t.trim().substring(3).split(" ");return{fn:s.length>=2?s[0]:"<unknown>",isWasm:t.includes("wasm:/")}}).filter(({fn:t,isWasm:s})=>s&&!t.startsWith("dynCall_")&&!t.startsWith("invoke_")).map(({fn:t})=>t);return Array.from(new Set(e))}catch{return[]}}const STRING="string",NUMBER="number",__private__dont__use=Symbol("__private__dont__use");class PHPExecutionFailureError extends Error{constructor(e,t,s){super(e),this.response=t,this.source=s}}const PHP_INI_PATH="/internal/shared/php.ini",AUTO_PREPEND_SCRIPT="/internal/shared/auto_prepend_file.php",OPCACHE_FILE_FOLDER="/internal/shared/opcache";var C,R,b,v,H,T,w,h,X,Q,K,Z,ee,te,re,se,$,ne,q,z;class PHP{constructor(r){y(this,h);y(this,C);y(this,R,!1);y(this,b,null);y(this,v,new Map([["*",new Set]]));y(this,H,[]);y(this,T,{});y(this,w,{enabled:!1,recreateRuntime:()=>0,needsRotating:!1,maxRequests:400,requestsMade:0});this.semaphore=new util.Semaphore({concurrency:1}),r!==void 0&&this.initializeRuntime(r),this.addEventListener("request.error",e=>{e.source==="php-wasm"&&(u(this,w).needsRotating=!0)})}addEventListener(r,e){u(this,v).has(r)||u(this,v).set(r,new Set),u(this,v).get(r).add(e)}removeEventListener(r,e){var t;(t=u(this,v).get(r))==null||t.delete(e)}dispatchEvent(r){const e=[...u(this,v).get(r.type)||[],...u(this,v).get("*")||[]];if(e)for(const t of e)t(r)}onMessage(r){return u(this,H).push(r),async()=>{g(this,H,u(this,H).filter(e=>e!==r))}}async setSpawnHandler(handler){typeof handler=="string"&&(handler=util.createSpawnHandler(eval(handler))),this[__private__dont__use].spawnProcess=handler}get absoluteUrl(){return this.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.documentRoot}pathToInternalUrl(r){return this.requestHandler.pathToInternalUrl(r)}internalUrlToPath(r){return this.requestHandler.internalUrlToPath(r)}initializeRuntime(r){if(this[__private__dont__use])throw new Error("PHP runtime already initialized.");const e=popLoadedRuntime(r);if(!e)throw new Error("Invalid PHP runtime id.");if(this[__private__dont__use]=e,this[__private__dont__use].ccall("wasm_set_phpini_path",null,["string"],[PHP_INI_PATH]),!this.fileExists(PHP_INI_PATH)){const t=["opcache.enable = 1","opcache.enable_cli = 1","opcache.jit = 0","opcache.interned_strings_buffer = 8","opcache.max_accelerated_files = 1000","opcache.memory_consumption = 64","opcache.max_wasted_percentage = 5","opcache.file_cache = "+OPCACHE_FILE_FOLDER,"opcache.file_cache_only = 1","opcache.file_cache_consistency_checks = 1"];this.fileExists(OPCACHE_FILE_FOLDER)||this.mkdir(OPCACHE_FILE_FOLDER),this.writeFile(PHP_INI_PATH,["auto_prepend_file="+AUTO_PREPEND_SCRIPT,"memory_limit=256M","ignore_repeated_errors = 1","error_reporting = E_ALL","display_errors = 1","html_errors = 1","display_startup_errors = On","log_errors = 1","always_populate_raw_post_data = -1","upload_max_filesize = 2000M","post_max_size = 2000M","allow_url_fopen = On","allow_url_include = Off","session.save_path = /home/web_user","implicit_flush = 1","output_buffering = 0","max_execution_time = 0","max_input_time = -1",...t].join(`
|
|
37
37
|
`))}this.fileExists(AUTO_PREPEND_SCRIPT)||this.writeFile(AUTO_PREPEND_SCRIPT,`<?php
|
|
38
38
|
// Define constants set via defineConstant() calls
|
|
39
39
|
if(file_exists('/internal/shared/consts.json')) {
|
|
@@ -48,13 +48,13 @@ ${bold} WASM ERROR${reset}${redBg}`);for(const e of r.split(`
|
|
|
48
48
|
foreach (glob('/internal/shared/preload/*.php') as $file) {
|
|
49
49
|
require_once $file;
|
|
50
50
|
}
|
|
51
|
-
`),e.onMessage=async t=>{for(const s of u(this,H)){const n=await s(t);if(n)return n}return""},g(this,b,improveWASMErrorReporting(e)),this.dispatchEvent({type:"runtime.initialized"})}async setSapiName(r){if(this[__private__dont__use].ccall("wasm_set_sapi_name",NUMBER,[STRING],[r])!==0)throw new Error("Could not set SAPI name. This can only be done before the PHP WASM module is initialized.Did you already dispatch any requests?");g(this,
|
|
51
|
+
`),e.onMessage=async t=>{for(const s of u(this,H)){const n=await s(t);if(n)return n}return""},g(this,b,improveWASMErrorReporting(e)),this.dispatchEvent({type:"runtime.initialized"})}async setSapiName(r){if(this[__private__dont__use].ccall("wasm_set_sapi_name",NUMBER,[STRING],[r])!==0)throw new Error("Could not set SAPI name. This can only be done before the PHP WASM module is initialized.Did you already dispatch any requests?");g(this,C,r)}chdir(r){this[__private__dont__use].FS.chdir(r)}cwd(){return this[__private__dont__use].FS.cwd()}chmod(r,e){this[__private__dont__use].FS.chmod(r,e)}async request(r){if(logger.logger.debug("PHP.request() is deprecated. Please use new PHPRequestHandler() instead."),!this.requestHandler)throw new Error("No request handler available.");return this.requestHandler.request(r)}async run(r){const e=await this.runStream(r),t=await PHPResponse.fromStreamedResponse(e);if(t.exitCode!==0)throw new PHPExecutionFailureError(`PHP.run() failed with exit code ${t.exitCode}.
|
|
52
52
|
|
|
53
53
|
=== Stdout ===
|
|
54
54
|
${t.text}
|
|
55
55
|
|
|
56
56
|
=== Stderr ===
|
|
57
|
-
${t.errors}`,t,"request");return t}async runStream(r){const e=await this.semaphore.acquire();let t;const s=m(this,h,z).call(this,async()=>{if(u(this,R)||(await this[__private__dont__use].ccall("php_wasm_init",null,[],[],{isAsync:!0}),g(this,R,!0)),r.scriptPath&&!this.fileExists(r.scriptPath))throw new Error(`The script path "${r.scriptPath}" does not exist.`);m(this,h,Q).call(this,r.relativeUri||""),m(this,h,te).call(this,r.method||"GET");const i=normalizeHeaders(r.headers||{}),o=i.host||"example.com:443",a=m(this,h,ee).call(this,o,r.protocol||"http");if(m(this,h,K).call(this,o),m(this,h,Z).call(this,a),m(this,h,re).call(this,i),r.body&&(t=m(this,h,se).call(this,r.body)),typeof r.code=="string")this.writeFile("/internal/eval.php",r.code),m(this,h,q).call(this,"/internal/eval.php");else if(typeof r.scriptPath=="string")m(this,h,q).call(this,r.scriptPath||"");else throw new TypeError("The request object must have either a `code` or a `scriptPath` property.");const c=m(this,h,X).call(this,r.$_SERVER,i,a);for(const d in c)m(this,h,ne).call(this,d,c[d]);const l=r.env||{};for(const d in l)m(this,h,$).call(this,d,l[d]);return await this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0})}),n=()=>{if(t)try{this[__private__dont__use].free(t)}catch(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(r,e){let t={};try{t=JSON.parse(this.fileExists("/internal/shared/consts.json")&&this.readFileAsText("/internal/shared/consts.json")||"{}")}catch{}this.writeFile("/internal/shared/consts.json",JSON.stringify({...t,[r]:e}))}mkdir(r){const e=FSHelpers.mkdir(this[__private__dont__use].FS,r);return this.dispatchEvent({type:"filesystem.write"}),e}mkdirTree(r){return FSHelpers.mkdir(this[__private__dont__use].FS,r)}readFileAsText(r){return FSHelpers.readFileAsText(this[__private__dont__use].FS,r)}readFileAsBuffer(r){return FSHelpers.readFileAsBuffer(this[__private__dont__use].FS,r)}writeFile(r,e){const t=FSHelpers.writeFile(this[__private__dont__use].FS,r,e);return this.dispatchEvent({type:"filesystem.write"}),t}unlink(r){const e=FSHelpers.unlink(this[__private__dont__use].FS,r);return this.dispatchEvent({type:"filesystem.write"}),e}mv(r,e){const t=FSHelpers.mv(this[__private__dont__use].FS,r,e);return this.dispatchEvent({type:"filesystem.write"}),t}cp(r,e){const t=FSHelpers.copyRecursive(this[__private__dont__use].FS,r,e);return this.dispatchEvent({type:"filesystem.write"}),t}rmdir(r,e={recursive:!0}){const t=FSHelpers.rmdir(this[__private__dont__use].FS,r,e);return this.dispatchEvent({type:"filesystem.write"}),t}listFiles(r,e={prependPath:!1}){return FSHelpers.listFiles(this[__private__dont__use].FS,r,e)}isDir(r){return FSHelpers.isDir(this[__private__dont__use].FS,r)}isFile(r){return FSHelpers.isFile(this[__private__dont__use].FS,r)}symlink(r,e){return FSHelpers.symlink(this[__private__dont__use].FS,r,e)}isSymlink(r){return FSHelpers.isSymlink(this[__private__dont__use].FS,r)}readlink(r){return FSHelpers.readlink(this[__private__dont__use].FS,r)}realpath(r){return FSHelpers.realpath(this[__private__dont__use].FS,r)}fileExists(r){return FSHelpers.fileExists(this[__private__dont__use].FS,r)}enableRuntimeRotation(r){g(this,w,{...u(this,w),enabled:!0,recreateRuntime:r.recreateRuntime,maxRequests:r.maxRequests??400})}async rotateRuntime(){if(!u(this,w).enabled)throw new Error("Runtime rotation is not enabled. Call enableRuntimeRotation() first.");await this.hotSwapPHPRuntime(await u(this,w).recreateRuntime()),u(this,w).requestsMade=0,u(this,w).needsRotating=!1}async hotSwapPHPRuntime(r){const e=this[__private__dont__use].FS,t=this.listFiles("/").map(c=>`/${c}`),s=this[__private__dont__use].spawnProcess,n=e.cwd();e.chdir("/");const i=Object.entries(u(this,T)).map(([c,l])=>({mountHandler:l.mountHandler,vfsPath:c})),o=Object.values(u(this,T)).reverse();for(const c of o)await c.unmount();try{this.exit()}catch{}this.initializeRuntime(r),s&&(this[__private__dont__use].spawnProcess=s),u(this,M)&&this.setSapiName(u(this,M));const a=this[__private__dont__use].FS;for(const c of t)c&&c!=="/request"&©MEMFSNodes(e,a,c);for(const{mountHandler:c,vfsPath:l}of i)this.mkdir(l),await this.mount(l,c);try{a.chdir(n)}catch(c){throw new Error(`Failed to restore CWD to ${n} after PHP runtime rotation.`,{cause:c})}}async mount(r,e){const t=await e(this,this[__private__dont__use].FS,r),s={mountHandler:e,unmount:async()=>{await t(),delete u(this,T)[r]}};return u(this,T)[r]=s,()=>{s.unmount()}}async cli(r,e={}){if(util.basename(r[0]??"")!=="php")return this.subProcess(r,e);u(this,R)&&(u(this,w).needsRotating=!0);const t=await this.semaphore.acquire();return await m(this,h,z).call(this,()=>{const s=e.env||{};for(const[n,i]of Object.entries(s))m(this,h,$).call(this,n,i);r=[r[0],"-c",PHP_INI_PATH,...r.slice(1)];for(const n of r)this[__private__dont__use].ccall("wasm_add_cli_arg",null,[STRING],[n]);return this[__private__dont__use].ccall("run_cli",null,[],[],{async:!0})}).then(s=>(s.exitCode.finally(t),s)).finally(()=>{u(this,w).needsRotating=!0})}async subProcess(r,e={}){const t=this[__private__dont__use].spawnProcess(r[0],r.slice(1),{env:e.env,cwd:e.cwd??this.cwd()}),s=await createInvertedReadableStream();t.on("error",i=>{s.controller.error(i)}),t.stderr.on("data",i=>{s.controller.enqueue(i)});const n=await createInvertedReadableStream();return t.stdout.on("data",i=>{n.controller.enqueue(i)}),t.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=>{t.on("exit",o=>{i(o)})}))}setSkipShebang(r){this[__private__dont__use].ccall("wasm_set_skip_shebang",null,[NUMBER],[r?1:0])}exit(r=0){this.dispatchEvent({type:"runtime.beforeExit"});try{this[__private__dont__use]._exit(r)}catch{}g(this,R,!1),g(this,b,null),this[__private__dont__use]&&(delete this[__private__dont__use].onMessage,delete this[__private__dont__use])}[Symbol.dispose](){this.exit(0)}}M=new WeakMap,R=new WeakMap,b=new WeakMap,v=new WeakMap,H=new WeakMap,T=new WeakMap,w=new WeakMap,h=new WeakSet,X=function(r,e,t){const s={...r||{}};s.HTTPS=s.HTTPS||t===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},Q=function(r){this[__private__dont__use].ccall("wasm_set_request_uri",null,[STRING],[r]);let e="";r.includes("?")&&(e=r.substring(r.indexOf("?")+1)),this[__private__dont__use].ccall("wasm_set_query_string",null,[STRING],[e])},K=function(r){this[__private__dont__use].ccall("wasm_set_request_host",null,[STRING],[r])},Z=function(r){this[__private__dont__use].ccall("wasm_set_request_port",null,[NUMBER],[r])},ee=function(r,e){let t;try{t=parseInt(new URL(r).port,10)}catch{}return(!t||isNaN(t)||t===80)&&(t=e==="https"?443:80),t},te=function(r){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[r])},re=function(r){r.cookie&&this[__private__dont__use].ccall("wasm_set_cookies",null,[STRING],[r.cookie]),r["content-type"]&&this[__private__dont__use].ccall("wasm_set_content_type",null,[STRING],[r["content-type"]]),r["content-length"]&&this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[parseInt(r["content-length"],10)])},se=function(r){let e,t;typeof r=="string"?(logger.logger.warn("Passing a string as the request body is deprecated. Please use a Uint8Array instead. See https://github.com/WordPress/wordpress-playground/issues/997 for more details"),t=this[__private__dont__use].lengthBytesUTF8(r),e=t+1):(t=r.byteLength,e=r.byteLength);const s=this[__private__dont__use].malloc(e);if(!s)throw new Error("Could not allocate memory for the request body.");return typeof r=="string"?this[__private__dont__use].stringToUTF8(r,s,e+1):this[__private__dont__use].HEAPU8.set(r,s),this[__private__dont__use].ccall("wasm_set_request_body",null,[NUMBER],[s]),this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[t]),s},q=function(r){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[r])},ne=function(r,e){this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[r,e])},$=function(r,e){this[__private__dont__use].ccall("wasm_add_ENV_entry",null,[STRING,STRING],[r,e])},z=async function(r){u(this,w).enabled&&u(this,w).needsRotating&&await this.rotateRuntime(),++u(this,w).requestsMade,u(this,w).requestsMade>=u(this,w).maxRequests&&(u(this,w).needsRotating=!0);const e=this[__private__dont__use],t=await createInvertedReadableStream();e.onHeaders=p=>{a||s||t.controller.enqueue(p.slice())};let s=!1;const n=()=>{s||(s=!0,t.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([r(),new Promise((_,k)=>{var V;c=G=>{isExitCode(G.error)||k(G.error)},(V=u(this,b))==null||V.addEventListener("error",c,{once:!0})})])}catch(f){if(isExitCode(f))return f.status;i.controller.error(f),o.controller.error(f),t.controller.error(f),a=!0;for(const _ in this)typeof this[_]=="function"&&(this[_]=()=>{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,b))==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(t.stream,i.stream,o.stream,d)};function normalizeHeaders(r){const e={};for(const t in r)e[t.toLowerCase()]=r[t];return e}function copyMEMFSNodes(r,e,t){if(getNodeType(r,t)!=="memfs"||!["memfs","missing"].includes(getNodeType(e,t)))return;const s=r.lookupPath(t);if(!r.isDir(s.node.mode)){e.writeFile(t,r.readFile(t));return}e.mkdirTree(t);const n=r.readdir(t).filter(i=>i!=="."&&i!=="..");for(const i of n)copyMEMFSNodes(r,e,util.joinPaths(t,i))}async function createInvertedReadableStream(r={}){let e;const t=new Promise(i=>{e=i}),s=new ReadableStream({...r,start(i){if(e(i),r.start)return r.start(i)}}),n=await t;return{stream:s,controller:n}}const getNodeType=(r,e)=>{try{return"contents"in r.lookupPath(e,{follow:!0}).node?"memfs":"not-memfs"}catch{return"missing"}};async function getPhpIniEntries(r,e){const t=ini.parse(await r.readFileAsText(PHP_INI_PATH));if(e===void 0)return t;const s={};for(const n of e)s[n]=t[n];return s}async function setPhpIniEntries(r,e){const t=ini.parse(await r.readFileAsText(PHP_INI_PATH));for(const[s,n]of Object.entries(e))n==null?delete t[s]:t[s]=n;await r.writeFile(PHP_INI_PATH,ini.stringify(t))}async function withPHPIniValues(r,e,t){const s=await r.readFileAsText(PHP_INI_PATH);try{return await setPhpIniEntries(r,e),await t()}finally{await r.writeFile(PHP_INI_PATH,s)}}async function printDebugDetails(r,e){e&&printResponseDebugDetails(await PHPResponse.fromStreamedResponse(e)),await prettyPrintFullStackTrace(r)}async function prettyPrintFullStackTrace(r){let e=r,t=!0;for(;e;)t||process.stderr.write(`
|
|
57
|
+
${t.errors}`,t,"request");return t}async runStream(r){const e=await this.semaphore.acquire();let t;const s=m(this,h,z).call(this,async()=>{if(u(this,R)||(await this[__private__dont__use].ccall("php_wasm_init",null,[],[],{isAsync:!0}),g(this,R,!0)),r.scriptPath&&!this.fileExists(r.scriptPath))throw new Error(`The script path "${r.scriptPath}" does not exist.`);m(this,h,Q).call(this,r.relativeUri||""),m(this,h,te).call(this,r.method||"GET");const i=normalizeHeaders(r.headers||{}),o=i.host||"example.com:443",a=m(this,h,ee).call(this,o,r.protocol||"http");if(m(this,h,K).call(this,o),m(this,h,Z).call(this,a),m(this,h,re).call(this,i),r.body&&(t=m(this,h,se).call(this,r.body)),typeof r.code=="string")this.writeFile("/internal/eval.php",r.code),m(this,h,$).call(this,"/internal/eval.php");else if(typeof r.scriptPath=="string")m(this,h,$).call(this,r.scriptPath||"");else throw new TypeError("The request object must have either a `code` or a `scriptPath` property.");const c=m(this,h,X).call(this,r.$_SERVER,i,a);for(const d in c)m(this,h,ne).call(this,d,c[d]);const l=r.env||{};for(const d in l)m(this,h,q).call(this,d,l[d]);return await this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0})}),n=()=>{if(t)try{this[__private__dont__use].free(t)}catch(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(r,e){let t={};try{t=JSON.parse(this.fileExists("/internal/shared/consts.json")&&this.readFileAsText("/internal/shared/consts.json")||"{}")}catch{}this.writeFile("/internal/shared/consts.json",JSON.stringify({...t,[r]:e}))}mkdir(r){const e=FSHelpers.mkdir(this[__private__dont__use].FS,r);return this.dispatchEvent({type:"filesystem.write"}),e}mkdirTree(r){return FSHelpers.mkdir(this[__private__dont__use].FS,r)}readFileAsText(r){return FSHelpers.readFileAsText(this[__private__dont__use].FS,r)}readFileAsBuffer(r){return FSHelpers.readFileAsBuffer(this[__private__dont__use].FS,r)}writeFile(r,e){const t=FSHelpers.writeFile(this[__private__dont__use].FS,r,e);return this.dispatchEvent({type:"filesystem.write"}),t}unlink(r){const e=FSHelpers.unlink(this[__private__dont__use].FS,r);return this.dispatchEvent({type:"filesystem.write"}),e}mv(r,e){const t=FSHelpers.mv(this[__private__dont__use].FS,r,e);return this.dispatchEvent({type:"filesystem.write"}),t}cp(r,e){const t=FSHelpers.copyRecursive(this[__private__dont__use].FS,r,e);return this.dispatchEvent({type:"filesystem.write"}),t}rmdir(r,e={recursive:!0}){const t=FSHelpers.rmdir(this[__private__dont__use].FS,r,e);return this.dispatchEvent({type:"filesystem.write"}),t}listFiles(r,e={prependPath:!1}){return FSHelpers.listFiles(this[__private__dont__use].FS,r,e)}isDir(r){return FSHelpers.isDir(this[__private__dont__use].FS,r)}isFile(r){return FSHelpers.isFile(this[__private__dont__use].FS,r)}symlink(r,e){return FSHelpers.symlink(this[__private__dont__use].FS,r,e)}isSymlink(r){return FSHelpers.isSymlink(this[__private__dont__use].FS,r)}readlink(r){return FSHelpers.readlink(this[__private__dont__use].FS,r)}realpath(r){return FSHelpers.realpath(this[__private__dont__use].FS,r)}fileExists(r){return FSHelpers.fileExists(this[__private__dont__use].FS,r)}enableRuntimeRotation(r){g(this,w,{...u(this,w),enabled:!0,recreateRuntime:r.recreateRuntime,maxRequests:r.maxRequests??400})}async rotateRuntime(){if(!u(this,w).enabled)throw new Error("Runtime rotation is not enabled. Call enableRuntimeRotation() first.");await this.hotSwapPHPRuntime(await u(this,w).recreateRuntime()),u(this,w).requestsMade=0,u(this,w).needsRotating=!1}async hotSwapPHPRuntime(r){const e=this[__private__dont__use].FS,t=this.listFiles("/").map(c=>`/${c}`),s=this[__private__dont__use].spawnProcess,n=e.cwd();e.chdir("/");const i=Object.entries(u(this,T)).map(([c,l])=>({mountHandler:l.mountHandler,vfsPath:c})),o=Object.values(u(this,T)).reverse();for(const c of o)await c.unmount();try{this.exit()}catch{}this.initializeRuntime(r),s&&(this[__private__dont__use].spawnProcess=s),u(this,C)&&this.setSapiName(u(this,C));const a=this[__private__dont__use].FS;for(const c of t)c&&c!=="/request"&©MEMFSNodes(e,a,c);for(const{mountHandler:c,vfsPath:l}of i)this.mkdir(l),await this.mount(l,c);try{a.chdir(n)}catch(c){throw new Error(`Failed to restore CWD to ${n} after PHP runtime rotation.`,{cause:c})}}async mount(r,e){const t=await e(this,this[__private__dont__use].FS,r),s={mountHandler:e,unmount:async()=>{await t(),delete u(this,T)[r]}};return u(this,T)[r]=s,()=>{s.unmount()}}async cli(r,e={}){if(util.basename(r[0]??"")!=="php")return this.subProcess(r,e);u(this,R)&&(u(this,w).needsRotating=!0);const t=await this.semaphore.acquire();return await m(this,h,z).call(this,()=>{const s=e.env||{};for(const[n,i]of Object.entries(s))m(this,h,q).call(this,n,i);r=[r[0],"-c",PHP_INI_PATH,...r.slice(1)];for(const n of r)this[__private__dont__use].ccall("wasm_add_cli_arg",null,[STRING],[n]);return this[__private__dont__use].ccall("run_cli",null,[],[],{async:!0})}).then(s=>(s.exitCode.finally(t),s)).finally(()=>{u(this,w).needsRotating=!0})}async subProcess(r,e={}){const t=this[__private__dont__use].spawnProcess(r[0],r.slice(1),{env:e.env,cwd:e.cwd??this.cwd()}),s=await createInvertedReadableStream();t.on("error",a=>{safeStreamError$1(s.controller,a)});const n=a=>{try{s.controller.enqueue(a)}catch{t.stderr.off("data",n)}};t.stderr.on("data",n);const i=await createInvertedReadableStream(),o=a=>{try{i.controller.enqueue(a)}catch{t.stdout.off("data",o)}};return t.stdout.on("data",o),t.on("exit",()=>{setTimeout(()=>{try{s.controller.close()}catch{}try{i.controller.close()}catch{}},0)}),new StreamedPHPResponse(new ReadableStream({start(a){a.close()}}),i.stream,s.stream,new Promise(a=>{t.on("exit",c=>{a(c)})}))}setSkipShebang(r){this[__private__dont__use].ccall("wasm_set_skip_shebang",null,[NUMBER],[r?1:0])}exit(r=0){this.dispatchEvent({type:"runtime.beforeExit"});try{this[__private__dont__use]._exit(r)}catch{}g(this,R,!1),g(this,b,null),this[__private__dont__use]&&(delete this[__private__dont__use].onMessage,delete this[__private__dont__use])}[Symbol.dispose](){this.exit(0)}}C=new WeakMap,R=new WeakMap,b=new WeakMap,v=new WeakMap,H=new WeakMap,T=new WeakMap,w=new WeakMap,h=new WeakSet,X=function(r,e,t){const s={...r||{}};s.HTTPS=s.HTTPS||t===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},Q=function(r){this[__private__dont__use].ccall("wasm_set_request_uri",null,[STRING],[r]);let e="";r.includes("?")&&(e=r.substring(r.indexOf("?")+1)),this[__private__dont__use].ccall("wasm_set_query_string",null,[STRING],[e])},K=function(r){this[__private__dont__use].ccall("wasm_set_request_host",null,[STRING],[r])},Z=function(r){this[__private__dont__use].ccall("wasm_set_request_port",null,[NUMBER],[r])},ee=function(r,e){let t;try{t=parseInt(new URL(r).port,10)}catch{}return(!t||isNaN(t)||t===80)&&(t=e==="https"?443:80),t},te=function(r){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[r])},re=function(r){r.cookie&&this[__private__dont__use].ccall("wasm_set_cookies",null,[STRING],[r.cookie]),r["content-type"]&&this[__private__dont__use].ccall("wasm_set_content_type",null,[STRING],[r["content-type"]]),r["content-length"]&&this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[parseInt(r["content-length"],10)])},se=function(r){let e,t;typeof r=="string"?(logger.logger.warn("Passing a string as the request body is deprecated. Please use a Uint8Array instead. See https://github.com/WordPress/wordpress-playground/issues/997 for more details"),t=this[__private__dont__use].lengthBytesUTF8(r),e=t+1):(t=r.byteLength,e=r.byteLength);const s=this[__private__dont__use].malloc(e);if(!s)throw new Error("Could not allocate memory for the request body.");return typeof r=="string"?this[__private__dont__use].stringToUTF8(r,s,e+1):this[__private__dont__use].HEAPU8.set(r,s),this[__private__dont__use].ccall("wasm_set_request_body",null,[NUMBER],[s]),this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[t]),s},$=function(r){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[r])},ne=function(r,e){this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[r,e])},q=function(r,e){this[__private__dont__use].ccall("wasm_add_ENV_entry",null,[STRING,STRING],[r,e])},z=async function(r){u(this,w).enabled&&u(this,w).needsRotating&&await this.rotateRuntime(),++u(this,w).requestsMade,u(this,w).requestsMade>=u(this,w).maxRequests&&(u(this,w).needsRotating=!0);const e=this[__private__dont__use],t=await createInvertedReadableStream();e.onHeaders=p=>{a||s||t.controller.enqueue(p.slice())};let s=!1;const n=()=>{s||(s=!0,t.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([r(),new Promise((_,k)=>{var V;c=G=>{isExitCode(G.error)||k(G.error)},(V=u(this,b))==null||V.addEventListener("error",c,{once:!0})})])}catch(f){if(isExitCode(f))return f.status;safeStreamError$1(i.controller,f),safeStreamError$1(o.controller,f),safeStreamError$1(t.controller,f),a=!0;for(const _ in this)typeof this[_]=="function"&&(this[_]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});throw this.functionsMaybeMissingFromAsyncify=getFunctionsMaybeMissingFromAsyncify(),f}finally{a||(safeStreamClose$1(i.controller),safeStreamClose$1(o.controller),n(),a=!0),(p=u(this,b))==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(t.stream,i.stream,o.stream,d)};function normalizeHeaders(r){const e={};for(const t in r)e[t.toLowerCase()]=r[t];return e}function copyMEMFSNodes(r,e,t){if(getNodeType(r,t)!=="memfs"||!["memfs","missing"].includes(getNodeType(e,t)))return;const s=r.lookupPath(t);if(!r.isDir(s.node.mode)){e.writeFile(t,r.readFile(t));return}e.mkdirTree(t);const n=r.readdir(t).filter(i=>i!=="."&&i!=="..");for(const i of n)copyMEMFSNodes(r,e,util.joinPaths(t,i))}async function createInvertedReadableStream(r={}){let e;const t=new Promise(i=>{e=i}),s=new ReadableStream({...r,start(i){if(e(i),r.start)return r.start(i)}}),n=await t;return{stream:s,controller:n}}function safeStreamError$1(r,e){try{r.error(e)}catch{}}function safeStreamClose$1(r){try{r.close()}catch{}}const getNodeType=(r,e)=>{try{return"contents"in r.lookupPath(e,{follow:!0}).node?"memfs":"not-memfs"}catch{return"missing"}};async function getPhpIniEntries(r,e){const t=ini.parse(await r.readFileAsText(PHP_INI_PATH));if(e===void 0)return t;const s={};for(const n of e)s[n]=t[n];return s}async function setPhpIniEntries(r,e){const t=ini.parse(await r.readFileAsText(PHP_INI_PATH));for(const[s,n]of Object.entries(e))n==null?delete t[s]:t[s]=n;await r.writeFile(PHP_INI_PATH,ini.stringify(t))}async function withPHPIniValues(r,e,t){const s=await r.readFileAsText(PHP_INI_PATH);try{return await setPhpIniEntries(r,e),await t()}finally{await r.writeFile(PHP_INI_PATH,s)}}async function printDebugDetails(r,e){e&&printResponseDebugDetails(await PHPResponse.fromStreamedResponse(e)),await prettyPrintFullStackTrace(r)}async function prettyPrintFullStackTrace(r){let e=r,t=!0;for(;e;)t||process.stderr.write(`
|
|
58
58
|
Caused by:
|
|
59
59
|
|
|
60
60
|
`),process.stderr.write(e.originalErrorClassName??e.name),process.stderr.write(": "+e.message+`
|
|
@@ -86,7 +86,7 @@ ${JSON.stringify(r.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:t}}function fileToUint8Array(r){return r.arrayBuffer().then(e=>new Uint8Array(e))}const _default="application/octet-stream",asx="video/x-ms-asf",atom="application/atom+xml",avi="video/x-msvideo",avif="image/avif",bin="application/octet-stream",bmp="image/x-ms-bmp",cco="application/x-cocoa",cjs="application/javascript",css="text/css",data="application/octet-stream",deb="application/octet-stream",der="application/x-x509-ca-cert",dmg="application/octet-stream",doc="application/msword",docx="application/vnd.openxmlformats-officedocument.wordprocessingml.document",eot="application/vnd.ms-fontobject",flv="video/x-flv",gif="image/gif",gz="application/gzip",hqx="application/mac-binhex40",htc="text/x-component",html="text/html",ico="image/x-icon",iso="application/octet-stream",jad="text/vnd.sun.j2me.app-descriptor",jar="application/java-archive",jardiff="application/x-java-archive-diff",jng="image/x-jng",jnlp="application/x-java-jnlp-file",jpg="image/jpeg",jpeg="image/jpeg",js="application/javascript",json="application/json",kml="application/vnd.google-earth.kml+xml",kmz="application/vnd.google-earth.kmz",m3u8="application/vnd.apple.mpegurl",m4a="audio/x-m4a",m4v="video/x-m4v",md="text/plain",mid="audio/midi",mjs="application/javascript",mml="text/mathml",mng="video/x-mng",mov="video/quicktime",mp3="audio/mpeg",mp4="video/mp4",mpeg="video/mpeg",msi="application/octet-stream",odg="application/vnd.oasis.opendocument.graphics",odp="application/vnd.oasis.opendocument.presentation",ods="application/vnd.oasis.opendocument.spreadsheet",odt="application/vnd.oasis.opendocument.text",ogg="audio/ogg",otf="font/otf",pdf="application/pdf",pl="application/x-perl",png="image/png",ppt="application/vnd.ms-powerpoint",pptx="application/vnd.openxmlformats-officedocument.presentationml.presentation",prc="application/x-pilot",ps="application/postscript",ra="audio/x-realaudio",rar="application/x-rar-compressed",rpm="application/x-redhat-package-manager",rss="application/rss+xml",rtf="application/rtf",run="application/x-makeself",sea="application/x-sea",sit="application/x-stuffit",svg="image/svg+xml",swf="application/x-shockwave-flash",tcl="application/x-tcl",tar="application/x-tar",tif="image/tiff",ts="video/mp2t",ttf="font/ttf",txt="text/plain",wasm="application/wasm",wbmp="image/vnd.wap.wbmp",webm="video/webm",webp="image/webp",wml="text/vnd.wap.wml",wmlc="application/vnd.wap.wmlc",wmv="video/x-ms-wmv",woff="font/woff",woff2="font/woff2",xhtml="application/xhtml+xml",xls="application/vnd.ms-excel",xlsx="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml="text/xml",xpi="application/x-xpinstall",xspf="application/xspf+xml",zip="application/zip",mimeTypes={_default,"3gpp":"video/3gpp","7z":"application/x-7z-compressed",asx,atom,avi,avif,bin,bmp,cco,cjs,css,data,deb,der,dmg,doc,docx,eot,flv,gif,gz,hqx,htc,html,ico,iso,jad,jar,jardiff,jng,jnlp,jpg,jpeg,js,json,kml,kmz,m3u8,m4a,m4v,md,mid,mjs,mml,mng,mov,mp3,mp4,mpeg,msi,odg,odp,ods,odt,ogg,otf,pdf,pl,png,ppt,pptx,prc,ps,ra,rar,rpm,rss,rtf,run,sea,sit,svg,swf,tcl,tar,tif,ts,ttf,txt,wasm,wbmp,webm,webp,wml,wmlc,wmv,woff,woff2,xhtml,xls,xlsx,xml,xpi,xspf,zip};var E,C,U,L,I,x,A,F,B,P,ie,D,oe,ae,ce;class PHPRequestHandler{constructor(e){y(this,P);y(this,E);y(this,C);y(this,U);y(this,L);y(this,I);y(this,x);y(this,A);y(this,F);y(this,B);const{documentRoot:t="/www/",absoluteUrl:s=typeof location=="object"?location.href:DEFAULT_BASE_URL,rewriteRules:n=[],pathAliases:i=[],getFileNotFoundAction:o=()=>({type:"404"})}=e,a=d=>{d.isDir(t)||d.mkdir(t),d.chdir(t),d.requestHandler=this};if(e.php)a(e.php),this.instanceManager=new SinglePHPInstanceManager({php:e.php});else if(e.phpFactory)this.instanceManager=new PHPProcessManager({phpFactory:async d=>{const p=await e.phpFactory({...d,requestHandler:this});return a(p),p},maxPhpInstances:e.maxPhpInstances});else throw new Error("Either php or phpFactory must be provided in the configuration.");g(this,F,e.cookieStore===void 0?new HttpCookieStore:e.cookieStore),g(this,E,t);const c=new URL(s);g(this,U,c.hostname),g(this,L,c.port?Number(c.port):c.protocol==="https:"?443:80),g(this,C,(c.protocol||"").replace(":",""));const l=u(this,L)!==443&&u(this,L)!==80;g(this,I,[u(this,U),l?`:${u(this,L)}`:""].join("")),g(this,x,c.pathname.replace(/\/+$/,"")),g(this,A,[`${u(this,C)}://`,u(this,I),u(this,x)].join("")),this.rewriteRules=n,g(this,B,i),this.getFileNotFoundAction=o}async getPrimaryPhp(){return await this.instanceManager.getPrimaryPhp()}pathToInternalUrl(e){return e.startsWith("/")||(e=`/${e}`),`${this.absoluteUrl}${e}`}internalUrlToPath(e){const t=new URL(e,"https://playground.internal");return t.pathname.startsWith(u(this,x))&&(t.pathname=t.pathname.slice(u(this,x).length)),toRelativeUrl(t)}get absoluteUrl(){return u(this,A)}get documentRoot(){return u(this,E)}async request(e){const t=await this.requestStreamed(e),s=await PHPResponse.fromStreamedResponse(t);return s.ok()&&s.exitCode!==0?new PHPResponse(500,s.headers,s.bytes,s.errors,s.exitCode):s}async requestStreamed(e){const t=looksLikeAbsoluteUrl(e.url),s=new URL(e.url.split("#")[0],t?void 0:DEFAULT_BASE_URL),n=m(this,P,ie).call(this,s),i=await this.getPrimaryPhp(),o=removePathPrefix(decodeURIComponent(n.pathname),u(this,x));let a=m(this,P,D).call(this,o);if(i.isDir(a)){if(!o.endsWith("/"))return StreamedPHPResponse.fromPHPResponse(new PHPResponse(301,{location:[`${n.pathname}/`]},new Uint8Array(0)));for(const c of["index.php","index.html"]){const l=util.joinPaths(a,c);if(i.isFile(l)){a=l,n.pathname=util.joinPaths(n.pathname,c);break}}}if(!i.isFile(a)){let c=o;for(;c.startsWith("/")&&c!==util.dirname(c);){c=util.dirname(c);const l=m(this,P,D).call(this,c);if(i.isFile(l)&&l.endsWith(".php")){a=m(this,P,D).call(this,c);break}}}if(!i.isFile(a)){const c=this.getFileNotFoundAction(n.pathname);switch(c.type){case"response":return StreamedPHPResponse.fromPHPResponse(c.response);case"internal-redirect":a=util.joinPaths(u(this,E),c.uri);break;case"404":return StreamedPHPResponse.forHttpCode(404);default:throw new Error(`Unsupported file-not-found action type: '${c.type}'`)}}return i.isFile(a)?a.endsWith(".php")?await m(this,P,ae).call(this,e,s,n,a):StreamedPHPResponse.fromPHPResponse(m(this,P,oe).call(this,i,a)):StreamedPHPResponse.forHttpCode(404)}prepare_$_SERVER_superglobal(e,t,s){const n={REMOTE_ADDR:"127.0.0.1",DOCUMENT_ROOT:u(this,E),HTTPS:u(this,A).startsWith("https://")?"on":""};return n.REQUEST_URI=e.pathname+e.search,s.startsWith(u(this,E))&&(n.SCRIPT_NAME=s.substring(u(this,E).length),n.PHP_SELF=t.pathname,n.REQUEST_URI.startsWith(n.SCRIPT_NAME)&&(n.PATH_INFO=n.REQUEST_URI.substring(n.SCRIPT_NAME.length),n.PATH_INFO.includes("?")&&(n.PATH_INFO=n.PATH_INFO.substring(0,n.PATH_INFO.indexOf("?"))))),n.QUERY_STRING=t.search.substring(1),n}async[Symbol.asyncDispose](){await this.instanceManager[Symbol.asyncDispose]()}}E=new WeakMap,C=new WeakMap,U=new WeakMap,L=new WeakMap,I=new WeakMap,x=new WeakMap,A=new WeakMap,F=new WeakMap,B=new WeakMap,P=new WeakSet,ie=function(e){const t=removePathPrefix(decodeURIComponent(e.pathname),u(this,x)),s=applyRewriteRules(t,this.rewriteRules),n=new URL(util.joinPaths(u(this,x),s),e.toString());for(const[i,o]of e.searchParams.entries())n.searchParams.append(i,o);return n},D=function(e){for(const t of u(this,B))if(e===t.urlPrefix||e.startsWith(t.urlPrefix+"/")){const s=e.slice(t.urlPrefix.length);return util.joinPaths(t.fsPath,s)}return util.joinPaths(u(this,E),e)},oe=function(e,t){const s=e.readFileAsBuffer(t);return new PHPResponse(200,{"content-length":[`${s.byteLength}`],"content-type":[inferMimeType(t)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},s)},ae=async function(e,t,s,n){let i;try{i=await this.instanceManager.acquirePHPInstance()}catch(a){return a instanceof MaxPhpInstancesError?StreamedPHPResponse.forHttpCode(502):StreamedPHPResponse.forHttpCode(500)}let o;try{o=await m(this,P,ce).call(this,i.php,e,t,s,n)}catch(a){throw i.reap(),a}return o.finished.finally(()=>{i==null||i.reap()}),o},ce=async function(e,t,s,n,i){let o="GET";const a={host:u(this,I),...normalizeHeaders(t.headers||{})};u(this,F)&&(a.cookie=u(this,F).getCookieRequestHeader());let c=t.body;if(typeof c=="object"&&!(c instanceof Uint8Array)){o="POST";const{bytes:d,contentType:p}=await encodeAsMultipart(c);c=d,a["content-type"]=p}const l=await e.runStream({relativeUri:ensurePathPrefix(toRelativeUrl(new URL(n.toString())),u(this,x)),protocol:u(this,C),method:t.method||o,$_SERVER:this.prepare_$_SERVER_superglobal(s,n,i),body:c,scriptPath:i,headers:a});if(u(this,F)){const d=await l.headers;u(this,F).rememberCookiesFromResponseHeaders(d)}return l};function inferMimeType(r){const e=r.split(".").pop();return mimeTypes[e]||mimeTypes._default}function applyRewriteRules(r,e){for(const t of e)if(new RegExp(t.match).test(r)){r=r.replace(t.match,t.replacement);break}return r}function looksLikeAbsoluteUrl(r){try{return new URL(r),!0}catch{return!1}}function rotatePHPRuntime({php:r,recreateRuntime:e,maxRequests:t=400}){return r.enableRuntimeRotation({recreateRuntime:e,maxRequests:t})}async function writeFiles(r,e,t,{rmRoot:s=!1}={}){s&&await r.isDir(e)&&await r.rmdir(e,{recursive:!0});for(const[n,i]of Object.entries(t)){const o=util.joinPaths(e,n);await r.fileExists(util.dirname(o))||await r.mkdir(util.dirname(o)),i instanceof Uint8Array||typeof i=="string"?await r.writeFile(o,i):await writeFiles(r,o,i)}}function ensureProxyFSHasMmapSupport(r){const e=Object.getOwnPropertySymbols(r)[0],t=r[e],s=t.PROXYFS,n=t.FS;s.stream_ops.mmap||(s.stream_ops.mmap=function(i,o,a,c,l){if(!n.isFile(i.node.mode))throw new n.ErrnoError(19);if(a!==0)throw new n.ErrnoError(22);const d=t.malloc(o);if(!d)throw new n.ErrnoError(48);const p=t.HEAPU8.subarray(d,d+o);let f=0;for(;f<o;){const _=i.stream_ops.read(i,p,f,o-f,f);if(_<=0)break;f+=_}if(f!==o)throw t.free(d),new n.ErrnoError(5);return{ptr:d,allocated:!0}},s.stream_ops.msync=function(i,o,a,c,l){return l&2||i.stream_ops.write(i,o,a,c,a,!1),0})}async function proxyFileSystem(r,e,t){const s=Object.getOwnPropertySymbols(r)[0];for(const n of t)r.fileExists(n)||r.mkdir(n),e.mkdir(n),await e.mount(n,i=>{ensureProxyFSHasMmapSupport(i);const o=Object.getOwnPropertySymbols(i)[0];return i[o].FS.mount(i[o].PROXYFS,{root:n,fs:r[s].FS},n),()=>{try{i[o].FS.unmount(n)}catch{}}})}function isPathToSharedFS(r,e){var i;const t=Object.getOwnPropertySymbols(r)[0],n=r[t].FS.lookupPath(e,{noent_okay:!0});return((i=n==null?void 0:n.node)==null?void 0:i.isSharedFS)??!1}function sandboxedSpawnHandlerFactory(r){return util.createSpawnHandler(async function(e,t,s){t.notifySpawn(),(e==null?void 0:e[0])==="/bin/sh"&&(e==null?void 0:e[1])==="-c"&&typeof e[2]=="string"&&(e=util.splitShellCommand(e[2])),e[0]==="exec"&&e.shift(),(e[0].endsWith(".php")||e[0].endsWith(".phar"))&&e.unshift("php");const n=e[0].split("/").pop();if(e[0]==="/usr/bin/env"&&e[1]==="stty"&&e[2]==="size")t.stdout("18 140"),t.exit(0);else if(n==="tput"&&e[1]==="cols")t.stdout("140"),t.exit(0);else if(n==="less"){t.on("stdin",a=>{t.stdout(a)}),await new Promise(a=>{t.childProcess.stdin.on("finish",()=>{a(!0)})}),t.exit(0);return}if(!["php","ls","pwd"].includes(n??"")){t.exit(127);return}if(!r){logger.logger.warn("Tried to spawn a PHP subprocess, but the sandboxed spawn handler was created without a getPHPInstance function."),t.exit(127);return}const{php:i,reap:o}=await r();try{s.cwd&&await i.chdir(s.cwd);const a=await 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){t.stdout(l)}})),c.stderr.pipeTo(new WritableStream({write(l){t.stderr(l)}})),t.exit(await c.exitCode);break}case"ls":{const c=await i.listFiles(e[1]??a);for(const l of c)t.stdout(l+`
|
|
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:t}}function fileToUint8Array(r){return r.arrayBuffer().then(e=>new Uint8Array(e))}const _default="application/octet-stream",asx="video/x-ms-asf",atom="application/atom+xml",avi="video/x-msvideo",avif="image/avif",bin="application/octet-stream",bmp="image/x-ms-bmp",cco="application/x-cocoa",cjs="application/javascript",css="text/css",data="application/octet-stream",deb="application/octet-stream",der="application/x-x509-ca-cert",dmg="application/octet-stream",doc="application/msword",docx="application/vnd.openxmlformats-officedocument.wordprocessingml.document",eot="application/vnd.ms-fontobject",flv="video/x-flv",gif="image/gif",gz="application/gzip",hqx="application/mac-binhex40",htc="text/x-component",html="text/html",ico="image/x-icon",iso="application/octet-stream",jad="text/vnd.sun.j2me.app-descriptor",jar="application/java-archive",jardiff="application/x-java-archive-diff",jng="image/x-jng",jnlp="application/x-java-jnlp-file",jpg="image/jpeg",jpeg="image/jpeg",js="application/javascript",json="application/json",kml="application/vnd.google-earth.kml+xml",kmz="application/vnd.google-earth.kmz",m3u8="application/vnd.apple.mpegurl",m4a="audio/x-m4a",m4v="video/x-m4v",md="text/plain",mid="audio/midi",mjs="application/javascript",mml="text/mathml",mng="video/x-mng",mov="video/quicktime",mp3="audio/mpeg",mp4="video/mp4",mpeg="video/mpeg",msi="application/octet-stream",odg="application/vnd.oasis.opendocument.graphics",odp="application/vnd.oasis.opendocument.presentation",ods="application/vnd.oasis.opendocument.spreadsheet",odt="application/vnd.oasis.opendocument.text",ogg="audio/ogg",otf="font/otf",pdf="application/pdf",pl="application/x-perl",png="image/png",ppt="application/vnd.ms-powerpoint",pptx="application/vnd.openxmlformats-officedocument.presentationml.presentation",prc="application/x-pilot",ps="application/postscript",ra="audio/x-realaudio",rar="application/x-rar-compressed",rpm="application/x-redhat-package-manager",rss="application/rss+xml",rtf="application/rtf",run="application/x-makeself",sea="application/x-sea",sit="application/x-stuffit",svg="image/svg+xml",swf="application/x-shockwave-flash",tcl="application/x-tcl",tar="application/x-tar",tif="image/tiff",ts="video/mp2t",ttf="font/ttf",txt="text/plain",wasm="application/wasm",wbmp="image/vnd.wap.wbmp",webm="video/webm",webp="image/webp",wml="text/vnd.wap.wml",wmlc="application/vnd.wap.wmlc",wmv="video/x-ms-wmv",woff="font/woff",woff2="font/woff2",xhtml="application/xhtml+xml",xls="application/vnd.ms-excel",xlsx="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml="text/xml",xpi="application/x-xpinstall",xspf="application/xspf+xml",zip="application/zip",mimeTypes={_default,"3gpp":"video/3gpp","7z":"application/x-7z-compressed",asx,atom,avi,avif,bin,bmp,cco,cjs,css,data,deb,der,dmg,doc,docx,eot,flv,gif,gz,hqx,htc,html,ico,iso,jad,jar,jardiff,jng,jnlp,jpg,jpeg,js,json,kml,kmz,m3u8,m4a,m4v,md,mid,mjs,mml,mng,mov,mp3,mp4,mpeg,msi,odg,odp,ods,odt,ogg,otf,pdf,pl,png,ppt,pptx,prc,ps,ra,rar,rpm,rss,rtf,run,sea,sit,svg,swf,tcl,tar,tif,ts,ttf,txt,wasm,wbmp,webm,webp,wml,wmlc,wmv,woff,woff2,xhtml,xls,xlsx,xml,xpi,xspf,zip};var E,M,U,L,I,x,A,F,D,P,ie,B,oe,ae,ce;class PHPRequestHandler{constructor(e){y(this,P);y(this,E);y(this,M);y(this,U);y(this,L);y(this,I);y(this,x);y(this,A);y(this,F);y(this,D);const{documentRoot:t="/www/",absoluteUrl:s=typeof location=="object"?location.href:DEFAULT_BASE_URL,rewriteRules:n=[],pathAliases:i=[],getFileNotFoundAction:o=()=>({type:"404"})}=e,a=d=>{d.isDir(t)||d.mkdir(t),d.chdir(t),d.requestHandler=this};if(e.php)a(e.php),this.instanceManager=new SinglePHPInstanceManager({php:e.php});else if(e.phpFactory)this.instanceManager=new PHPProcessManager({phpFactory:async d=>{const p=await e.phpFactory({...d,requestHandler:this});return a(p),p},maxPhpInstances:e.maxPhpInstances});else throw new Error("Either php or phpFactory must be provided in the configuration.");g(this,F,e.cookieStore===void 0?new HttpCookieStore:e.cookieStore),g(this,E,t);const c=new URL(s);g(this,U,c.hostname),g(this,L,c.port?Number(c.port):c.protocol==="https:"?443:80),g(this,M,(c.protocol||"").replace(":",""));const l=u(this,L)!==443&&u(this,L)!==80;g(this,I,[u(this,U),l?`:${u(this,L)}`:""].join("")),g(this,x,c.pathname.replace(/\/+$/,"")),g(this,A,[`${u(this,M)}://`,u(this,I),u(this,x)].join("")),this.rewriteRules=n,g(this,D,i),this.getFileNotFoundAction=o}async getPrimaryPhp(){return await this.instanceManager.getPrimaryPhp()}pathToInternalUrl(e){return e.startsWith("/")||(e=`/${e}`),`${this.absoluteUrl}${e}`}internalUrlToPath(e){const t=new URL(e,"https://playground.internal");return t.pathname.startsWith(u(this,x))&&(t.pathname=t.pathname.slice(u(this,x).length)),toRelativeUrl(t)}get absoluteUrl(){return u(this,A)}get documentRoot(){return u(this,E)}async request(e){const t=await this.requestStreamed(e),s=await PHPResponse.fromStreamedResponse(t);return s.ok()&&s.exitCode!==0?new PHPResponse(500,s.headers,s.bytes,s.errors,s.exitCode):s}async requestStreamed(e){const t=looksLikeAbsoluteUrl(e.url),s=new URL(e.url.split("#")[0],t?void 0:DEFAULT_BASE_URL),n=m(this,P,ie).call(this,s),i=await this.getPrimaryPhp(),o=removePathPrefix(decodeURIComponent(n.pathname),u(this,x));let a=m(this,P,B).call(this,o);if(i.isDir(a)){if(!o.endsWith("/"))return StreamedPHPResponse.fromPHPResponse(new PHPResponse(301,{location:[`${n.pathname}/`]},new Uint8Array(0)));for(const c of["index.php","index.html"]){const l=util.joinPaths(a,c);if(i.isFile(l)){a=l,n.pathname=util.joinPaths(n.pathname,c);break}}}if(!i.isFile(a)){let c=o;for(;c.startsWith("/")&&c!==util.dirname(c);){c=util.dirname(c);const l=m(this,P,B).call(this,c);if(i.isFile(l)&&l.endsWith(".php")){a=m(this,P,B).call(this,c);break}}}if(!i.isFile(a)){const c=this.getFileNotFoundAction(n.pathname);switch(c.type){case"response":return StreamedPHPResponse.fromPHPResponse(c.response);case"internal-redirect":a=util.joinPaths(u(this,E),c.uri);break;case"404":return StreamedPHPResponse.forHttpCode(404);default:throw new Error(`Unsupported file-not-found action type: '${c.type}'`)}}return i.isFile(a)?a.endsWith(".php")?await m(this,P,ae).call(this,e,s,n,a):StreamedPHPResponse.fromPHPResponse(m(this,P,oe).call(this,i,a)):StreamedPHPResponse.forHttpCode(404)}prepare_$_SERVER_superglobal(e,t,s){const n={REMOTE_ADDR:"127.0.0.1",DOCUMENT_ROOT:u(this,E),HTTPS:u(this,A).startsWith("https://")?"on":""};return n.REQUEST_URI=e.pathname+e.search,s.startsWith(u(this,E))&&(n.SCRIPT_NAME=s.substring(u(this,E).length),n.PHP_SELF=t.pathname,n.REQUEST_URI.startsWith(n.SCRIPT_NAME)&&(n.PATH_INFO=n.REQUEST_URI.substring(n.SCRIPT_NAME.length),n.PATH_INFO.includes("?")&&(n.PATH_INFO=n.PATH_INFO.substring(0,n.PATH_INFO.indexOf("?"))))),n.QUERY_STRING=t.search.substring(1),n}async[Symbol.asyncDispose](){await this.instanceManager[Symbol.asyncDispose]()}}E=new WeakMap,M=new WeakMap,U=new WeakMap,L=new WeakMap,I=new WeakMap,x=new WeakMap,A=new WeakMap,F=new WeakMap,D=new WeakMap,P=new WeakSet,ie=function(e){const t=removePathPrefix(decodeURIComponent(e.pathname),u(this,x)),s=applyRewriteRules(t,this.rewriteRules),n=new URL(util.joinPaths(u(this,x),s),e.toString());for(const[i,o]of e.searchParams.entries())n.searchParams.append(i,o);return n},B=function(e){for(const t of u(this,D))if(e===t.urlPrefix||e.startsWith(t.urlPrefix+"/")){const s=e.slice(t.urlPrefix.length);return util.joinPaths(t.fsPath,s)}return util.joinPaths(u(this,E),e)},oe=function(e,t){const s=e.readFileAsBuffer(t);return new PHPResponse(200,{"content-length":[`${s.byteLength}`],"content-type":[inferMimeType(t)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},s)},ae=async function(e,t,s,n){let i;try{i=await this.instanceManager.acquirePHPInstance()}catch(a){return a instanceof MaxPhpInstancesError?StreamedPHPResponse.forHttpCode(502):StreamedPHPResponse.forHttpCode(500)}let o;try{o=await m(this,P,ce).call(this,i.php,e,t,s,n)}catch(a){throw i.reap(),a}return o.finished.finally(()=>{i==null||i.reap()}),o},ce=async function(e,t,s,n,i){let o="GET";const a={host:u(this,I),...normalizeHeaders(t.headers||{})};u(this,F)&&(a.cookie=u(this,F).getCookieRequestHeader());let c=t.body;if(typeof c=="object"&&!(c instanceof Uint8Array)){o="POST";const{bytes:d,contentType:p}=await encodeAsMultipart(c);c=d,a["content-type"]=p}const l=await e.runStream({relativeUri:ensurePathPrefix(toRelativeUrl(new URL(n.toString())),u(this,x)),protocol:u(this,M),method:t.method||o,$_SERVER:this.prepare_$_SERVER_superglobal(s,n,i),body:c,scriptPath:i,headers:a});if(u(this,F)){const d=await l.headers;u(this,F).rememberCookiesFromResponseHeaders(d)}return l};function inferMimeType(r){const e=r.split(".").pop();return mimeTypes[e]||mimeTypes._default}function applyRewriteRules(r,e){for(const t of e)if(new RegExp(t.match).test(r)){r=r.replace(t.match,t.replacement);break}return r}function looksLikeAbsoluteUrl(r){try{return new URL(r),!0}catch{return!1}}function rotatePHPRuntime({php:r,recreateRuntime:e,maxRequests:t=400}){return r.enableRuntimeRotation({recreateRuntime:e,maxRequests:t})}async function writeFiles(r,e,t,{rmRoot:s=!1}={}){s&&await r.isDir(e)&&await r.rmdir(e,{recursive:!0});for(const[n,i]of Object.entries(t)){const o=util.joinPaths(e,n);await r.fileExists(util.dirname(o))||await r.mkdir(util.dirname(o)),i instanceof Uint8Array||typeof i=="string"?await r.writeFile(o,i):await writeFiles(r,o,i)}}function ensureProxyFSHasMmapSupport(r){const e=Object.getOwnPropertySymbols(r)[0],t=r[e],s=t.PROXYFS,n=t.FS;s.stream_ops.mmap||(s.stream_ops.mmap=function(i,o,a,c,l){if(!n.isFile(i.node.mode))throw new n.ErrnoError(19);if(a!==0)throw new n.ErrnoError(22);const d=t.malloc(o);if(!d)throw new n.ErrnoError(48);const p=t.HEAPU8.subarray(d,d+o);let f=0;for(;f<o;){const _=i.stream_ops.read(i,p,f,o-f,f);if(_<=0)break;f+=_}if(f!==o)throw t.free(d),new n.ErrnoError(5);return{ptr:d,allocated:!0}},s.stream_ops.msync=function(i,o,a,c,l){return l&2||i.stream_ops.write(i,o,a,c,a,!1),0})}async function proxyFileSystem(r,e,t){const s=Object.getOwnPropertySymbols(r)[0];for(const n of t)r.fileExists(n)||r.mkdir(n),e.mkdir(n),await e.mount(n,i=>{ensureProxyFSHasMmapSupport(i);const o=Object.getOwnPropertySymbols(i)[0];return i[o].FS.mount(i[o].PROXYFS,{root:n,fs:r[s].FS},n),()=>{try{i[o].FS.unmount(n)}catch{}}})}function isPathToSharedFS(r,e){var i;const t=Object.getOwnPropertySymbols(r)[0],n=r[t].FS.lookupPath(e,{noent_okay:!0});return((i=n==null?void 0:n.node)==null?void 0:i.isSharedFS)??!1}function sandboxedSpawnHandlerFactory(r){return util.createSpawnHandler(async function(e,t,s){t.notifySpawn(),(e==null?void 0:e[0])==="/bin/sh"&&(e==null?void 0:e[1])==="-c"&&typeof e[2]=="string"&&(e=util.splitShellCommand(e[2])),e[0]==="exec"&&e.shift(),(e[0].endsWith(".php")||e[0].endsWith(".phar"))&&e.unshift("php");const n=e[0].split("/").pop();if(e[0]==="/usr/bin/env"&&e[1]==="stty"&&e[2]==="size")t.stdout("18 140"),t.exit(0);else if(n==="tput"&&e[1]==="cols")t.stdout("140"),t.exit(0);else if(n==="less"){t.on("stdin",a=>{t.stdout(a)}),await new Promise(a=>{t.childProcess.stdin.on("finish",()=>{a(!0)})}),t.exit(0);return}if(!["php","ls","pwd"].includes(n??"")){t.exit(127);return}if(!r){logger.logger.warn("Tried to spawn a PHP subprocess, but the sandboxed spawn handler was created without a getPHPInstance function."),t.exit(127);return}const{php:i,reap:o}=await r();try{s.cwd&&await i.chdir(s.cwd);const a=await 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){t.stdout(l)}})),c.stderr.pipeTo(new WritableStream({write(l){t.stderr(l)}})),t.exit(await c.exitCode);break}case"ls":{const c=await i.listFiles(e[1]??a);for(const l of c)t.stdout(l+`
|
|
90
90
|
`);await new Promise(l=>setTimeout(l,10)),t.exit(0);break}case"pwd":{t.stdout(a+`
|
|
91
91
|
`),await new Promise(c=>setTimeout(c,10)),t.exit(0);break}}}catch(a){const c=a instanceof Error?a.message+`
|
|
92
92
|
`+a.stack:typeof a=="object"&&a!==null?JSON.stringify(a,Object.getOwnPropertyNames(a)):String(a);throw t.stderr(`[spawn error] ${c}`),t.exit(1),a}finally{o()}})}function exposeSync(r,e,t,s=["*"]){return expose(r,e,s,t.afterResponseSent)}function createSyncProxy(r,e=[],t){return new Proxy(()=>{},{get(s,n){return n==="then"&&!e.length?{then:(i,o)=>o(createSyncProxy(r,[],t))}:createSyncProxy(r,[...e,n],t)},set(s,n,i){const[o,a]=toWireValue(i);return t.send(r,{type:MessageType.SET,path:[...e,n].map(String),value:o},a),!0},apply(s,n,i){if(e.at(-1)==="bind")return createSyncProxy(r,e.slice(0,-1),t);const[a,c]=processArguments(i),l=t.send(r,{type:MessageType.APPLY,path:e.map(String),argumentList:a},c);return fromWireValue(l)},construct(s,n){const[i,o]=processArguments(n),a=t.send(r,{type:MessageType.CONSTRUCT,path:e.map(String),argumentList:i},o);return fromWireValue(a)}})}function wrapSync(r,e){return createSyncProxy(r,[],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:t}=e.data;if(t){const s=new Int32Array(t);s[0]=1,Atomics.notify(s,0)}}send(e,t,s){var l;const n=new SharedArrayBuffer(4),i=new Int32Array(n);i[0]=0;const o=generateUUID();if(e.postMessage({...t,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")}}}/**
|
|
@@ -99,5 +99,5 @@ ${JSON.stringify(r.headers,null,2)}
|
|
|
99
99
|
* @license
|
|
100
100
|
* Copyright 2019 Google LLC
|
|
101
101
|
* SPDX-License-Identifier: Apache-2.0
|
|
102
|
-
*/const WireValueType={RAW:"RAW",HANDLER:"HANDLER"},MessageType={GET:"GET",SET:"SET",APPLY:"APPLY",CONSTRUCT:"CONSTRUCT",ENDPOINT:"ENDPOINT",RELEASE:"RELEASE"},isObject=r=>typeof r=="object"&&r!==null||typeof r=="function",proxyTransferHandler={canHandle:r=>isObject(r)&&r[proxyMarker],serialize(r){const{port1:e,port2:t}=new MessageChannel;return expose(r,e),[t,[t]]},deserialize(r){return r.start(),wrap(r)}},throwTransferHandler$1={canHandle:r=>isObject(r)&&throwMarker in r,serialize({value:r}){let e;return r instanceof Error?e={isError:!0,value:{message:r.message,name:r.name,stack:r.stack}}:e={isError:!1,value:r},[e,[]]},deserialize(r){throw r.isError?Object.assign(new Error(r.value.message),r.value):r.value}},transferHandlers=new Map([["proxy",proxyTransferHandler],["throw",throwTransferHandler$1]]);function isAllowedOrigin(r,e){for(const t of r)if(e===t||t==="*"||t instanceof RegExp&&t.test(e))return!0;return!1}function expose(r,e=globalThis,t=["*"],s){e.addEventListener("message",function n(i){if(!i||!i.data)return;if(!isAllowedOrigin(t,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((_,k)=>_[k],r),f=c.reduce((_,k)=>_[k],r);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 _=new f(...l);d=proxy(_)}break;case MessageType.ENDPOINT:{const{port1:_,port2:k}=new MessageChannel;expose(r,k),d=transfer(_,[_])}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,_]=toWireValue(p);e.postMessage({...f,id:o},_),a===MessageType.RELEASE&&(e.removeEventListener("message",n),closeEndPoint(e),finalizer in r&&typeof r[finalizer]=="function"&&r[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(r){return r.constructor.name==="MessagePort"}function closeEndPoint(r){isMessagePort(r)&&r.close()}function wrap(r,e){const t=new Map;return r.addEventListener("message",function(n){const{data:i}=n;if(!i||!i.id)return;const o=t.get(i.id);if(o)try{o(i)}finally{t.delete(i.id)}}),createProxy(r,t,[],e)}function throwIfProxyReleased(r){if(r)throw new Error("Proxy has been released and is not useable")}function releaseEndpoint(r){return requestResponseMessage(r,new Map,{type:MessageType.RELEASE}).then(()=>{closeEndPoint(r)})}const proxyCounter=new WeakMap,proxyFinalizers="FinalizationRegistry"in globalThis&&new FinalizationRegistry(r=>{const e=(proxyCounter.get(r)||0)-1;proxyCounter.set(r,e),e===0&&releaseEndpoint(r)});function registerProxy(r,e){const t=(proxyCounter.get(e)||0)+1;proxyCounter.set(e,t),proxyFinalizers&&proxyFinalizers.register(r,e,r)}function unregisterProxy(r){proxyFinalizers&&proxyFinalizers.unregister(r)}function createProxy(r,e,t=[],s=function(){}){let n=!1;const i=new Proxy(s,{get(o,a){if(throwIfProxyReleased(n),a===releaseProxy)return()=>{unregisterProxy(i),releaseEndpoint(r),e.clear(),n=!0};if(a==="then"){if(t.length===0)return{then:()=>i};const c=requestResponseMessage(r,e,{type:MessageType.GET,path:t.map(l=>l.toString())}).then(fromWireValue);return c.then.bind(c)}return createProxy(r,e,[...t,a])},set(o,a,c){throwIfProxyReleased(n);const[l,d]=toWireValue(c);return requestResponseMessage(r,e,{type:MessageType.SET,path:[...t,a].map(p=>p.toString()),value:l},d).then(fromWireValue)},apply(o,a,c){throwIfProxyReleased(n);const l=t[t.length-1];if(l===createEndpoint)return requestResponseMessage(r,e,{type:MessageType.ENDPOINT}).then(fromWireValue);if(l==="bind")return createProxy(r,e,t.slice(0,-1));const[d,p]=processArguments(c);return requestResponseMessage(r,e,{type:MessageType.APPLY,path:t.map(f=>f.toString()),argumentList:d},p).then(fromWireValue)},construct(o,a){throwIfProxyReleased(n);const[c,l]=processArguments(a);return requestResponseMessage(r,e,{type:MessageType.CONSTRUCT,path:t.map(d=>d.toString()),argumentList:c},l).then(fromWireValue)}});return registerProxy(i,r),i}function myFlat(r){return Array.prototype.concat.apply([],r)}function processArguments(r){const e=r.map(toWireValue);return[e.map(t=>t[0]),myFlat(e.map(t=>t[1]))]}const transferCache=new WeakMap;function transfer(r,e){return transferCache.set(r,e),r}function proxy(r){return Object.assign(r,{[proxyMarker]:!0})}function windowEndpoint(r,e=globalThis,t="*"){return{postMessage:(s,n)=>r.postMessage(s,t,n),addEventListener:e.addEventListener.bind(e),removeEventListener:e.removeEventListener.bind(e)}}function toWireValue(r){for(const[e,t]of transferHandlers)if(t.canHandle(r)){const[s,n]=t.serialize(r);return[{type:WireValueType.HANDLER,name:e,value:s},n]}return[{type:WireValueType.RAW,value:r},transferCache.get(r)||[]]}function fromWireValue(r){switch(r.type){case WireValueType.HANDLER:return transferHandlers.get(r.name).deserialize(r.value);case WireValueType.RAW:return r.value}}function requestResponseMessage(r,e,t,s){return new Promise(n=>{const i=generateUUID();e.set(i,n),r.start&&r.start(),r.postMessage({id:i,...t},s)})}function generateUUID(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}function nodeEndpoint(r){const e=new WeakMap;return{postMessage:r.postMessage.bind(r),addEventListener:(t,s)=>{const n=i=>{"handleEvent"in s?s.handleEvent({data:i}):s({data:i})};r.on("message",n),e.set(s,n)},removeEventListener:(t,s)=>{const n=e.get(s);n&&(r.off("message",n),e.delete(s))},start:r.start&&r.start.bind(r)}}const proxyByListener=new WeakMap;function nodeProcessEndpoint(r){const e=r||process;if(typeof e.send!="function")throw new Error("IPC channel is not available. Did you forget to fork the process?");const t=e;return{postMessage(s,n){var i;if(n&&n.length>0)throw new Error("Transferable objects are not supported for nodeProcessEndpoint");(i=t.send)==null||i.call(t,s)},addEventListener(s,n){const i=typeof n=="function"?o=>n({data:o}):o=>n.handleEvent({data:o});proxyByListener.set(n,i),t.addListener(s,i)},removeEventListener(s,n){const i=proxyByListener.get(n);i&&(proxyByListener.delete(n),t.removeListener(s,i))},start(){}}}const list=[Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError,globalThis.DOMException,globalThis.AssertionError,globalThis.SystemError].filter(Boolean).map(r=>[r.name,r]),errorConstructors=new Map(list);class NonError extends Error{constructor(e){super(NonError._prepareSuperMessage(e)),this.name="NonError"}static _prepareSuperMessage(e){try{return JSON.stringify(e)}catch{return String(e)}}}const errorProperties=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1},{property:"errors",enumerable:!1}],toJsonWasCalled=new WeakSet,toJSON=r=>{toJsonWasCalled.add(r);const e=r.toJSON();return toJsonWasCalled.delete(r),e},newError=r=>{const e=errorConstructors.get(r)??Error;return e===AggregateError?new e([]):new e},destroyCircular=({from:r,seen:e,to:t,forceEnumerable:s,maxDepth:n,depth:i,useToJSON:o,serialize:a})=>{if(t||(Array.isArray(r)?t=[]:!a&&isErrorLike(r)?t=newError(r.name):t={}),e.push(r),i>=n)return t;if(o&&typeof r.toJSON=="function"&&!toJsonWasCalled.has(r))return toJSON(r);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(r)){if(d&&d instanceof Uint8Array&&d.constructor.name==="Buffer"){t[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){t[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){try{t[l]=d}catch{}continue}if(!e.includes(r[l])){i++,t[l]=c(r[l]);continue}t[l]="[Circular]"}}if(a||t instanceof Error)for(const{property:l,enumerable:d}of errorProperties)r[l]!==void 0&&r[l]!==null&&Object.defineProperty(t,l,{value:isErrorLike(r[l])||Array.isArray(r[l])?c(r[l]):r[l],enumerable:s?!0:d,configurable:!0,writable:!0});return t};function serializeError(r,e={}){const{maxDepth:t=Number.POSITIVE_INFINITY,useToJSON:s=!0}=e;return typeof r=="object"&&r!==null?destroyCircular({from:r,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:s,serialize:!0}):typeof r=="function"?`[Function: ${r.name||"anonymous"}]`:r}function deserializeError(r,e={}){const{maxDepth:t=Number.POSITIVE_INFINITY}=e;return r instanceof Error?r:isMinimumViableSerializedError(r)?destroyCircular({from:r,seen:[],to:newError(r.name),maxDepth:t,depth:0,serialize:!1}):new NonError(r)}function isErrorLike(r){return!!r&&typeof r=="object"&&typeof r.name=="string"&&typeof r.message=="string"&&typeof r.stack=="string"}function isMinimumViableSerializedError(r){return!!r&&typeof r=="object"&&typeof r.message=="string"&&!Array.isArray(r)}const releaseApiProxy=releaseProxy;async function consumeAPISync(r){setupTransferHandlers();const e=await NodeSABSyncReceiveMessageTransport.create();return wrapSync(r,e)}function consumeAPI(r,e=void 0){setupTransferHandlers();let t;if(typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u")if("postMessage"in r)t=nodeEndpoint(r);else if("send"in r&&"addListener"in r)t=nodeProcessEndpoint(r);else throw new Error("consumeAPI: remote does not look like a Worker, MessagePort, or Process");else t=r instanceof Worker?r:windowEndpoint(r,e);const n=wrap(t),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(r,e){return new Promise((t,s)=>{setTimeout(s,e),r.then(t)})}function exposeAPI(r,e,t){const{setReady:s,setFailed:n,exposedApi:i}=prepareForExpose(r,e);let o;if(t)if("addEventListener"in t)o=t;else if("postMessage"in t)o=nodeEndpoint(t);else if("send"in t&&"addListener"in t)o=nodeProcessEndpoint(t);else throw new Error("exposeAPI: targetWorker does not look like a Worker, MessagePort, or Process");else o=typeof window<"u"?windowEndpoint(self.parent):void 0;return expose(i,o),[s,n,i]}async function exposeSyncAPI(r,e){const{setReady:t,setFailed:s,exposedApi:n}=prepareForExpose(r),i=await NodeSABSyncReceiveMessageTransport.create(),o=nodeEndpoint(e);return exposeSync(n,o,i),[t,s,n]}function prepareForExpose(r,e){setupTransferHandlers();const t=Promise.resolve();let s,n;const i=new Promise((c,l)=>{s=c,n=l}),o=proxyClone(r),a=new Proxy(o,{get:(c,l)=>l==="isConnected"?()=>t: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:t=>t instanceof CustomEvent,serialize:t=>[{detail:t.detail},[]],deserialize:t=>t}),transferHandlers.set("FUNCTION",{canHandle:t=>typeof t=="function",serialize(t){const{port1:s,port2:n}=new MessageChannel;return expose(t,s),[n,[n]]},deserialize(t){return t.start(),wrap(t)}}),transferHandlers.set("MESSAGE_PORT",{canHandle:t=>t instanceof MessagePort,serialize(t){return[t,[t]]},deserialize(t){return t}}),transferHandlers.set("PHPResponse",{canHandle:t=>typeof t=="object"&&t!==null&&"headers"in t&&"bytes"in t&&"errors"in t&&"exitCode"in t&&"httpStatusCode"in t,serialize(t){const s=t.toRawData(),n=[];return s.bytes.buffer.byteLength>0&&n.push(s.bytes.buffer),[s,n]},deserialize(t){return PHPResponse.fromRawData(t)}});const r=transferHandlers.get("throw"),e=r==null?void 0:r.serialize;r.serialize=({value:t})=>{const s=e({value:t});return t.response&&(s[0].value.response=t.response),t.source&&(s[0].value.source=t.source),s},transferHandlers.set("StreamedPHPResponse",{canHandle:t=>t instanceof StreamedPHPResponse,serialize(t){const s=supportsTransferableStreams(),n=promiseToPort(t.exitCode),i=t.getHeadersStream();if(s)return[{__type:"StreamedPHPResponse",headers:i,stdout:t.stdout,stderr:t.stderr,exitCodePort:n},[i,t.stdout,t.stderr,n]];const o=streamToPort(i),a=streamToPort(t.stdout),c=streamToPort(t.stderr);return[{__type:"StreamedPHPResponse",headersPort:o,stdoutPort:a,stderrPort:c,exitCodePort:n},[o,a,c,n]]},deserialize(t){if(t.headers&&t.stdout&&t.stderr){const a=portToPromise(t.exitCodePort);return new StreamedPHPResponse(t.headers,t.stdout,t.stderr,a)}const s=portToStream(t.headersPort),n=portToStream(t.stdoutPort),i=portToStream(t.stderrPort),o=portToPromise(t.exitCodePort);return new StreamedPHPResponse(s,n,i,o)}})}let _cachedSupportsTransferableStreams;function supportsTransferableStreams(){if(typeof ReadableStream>"u"&&(_cachedSupportsTransferableStreams=!1),_cachedSupportsTransferableStreams===void 0)try{const{port1:r}=new MessageChannel,e=new ReadableStream;r.postMessage(e,[e]);try{r.close()}catch{}_cachedSupportsTransferableStreams=!0}catch{_cachedSupportsTransferableStreams=!1}return _cachedSupportsTransferableStreams}function streamToPort(r){const{port1:e,port2:t}=new MessageChannel;return(async()=>{const s=r.getReader();try{for(;;){const{done:n,value: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{}}})(),t}function portToStream(r){return new ReadableStream({start(e){const t=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=r.removeEventListener)==null||n.call(r,"message",t)}catch{}try{r.onmessage=null}catch{}try{r.close()}catch{}};r.addEventListener?r.addEventListener("message",t):r.on?r.on("message",n=>t({data:n})):r.onmessage=t,typeof r.start=="function"&&r.start()},cancel(){try{r.close()}catch{}}})}function promiseToPort(r){const{port1:e,port2:t}=new MessageChannel;return r.then(s=>{try{e.postMessage({t:"resolve",v:s})}catch{}}).catch(s=>{try{e.postMessage({t:"reject",m:(s==null?void 0:s.message)||String(s)})}catch{}}).finally(()=>{try{e.close()}catch{}}),t}function portToPromise(r){return new Promise((e,t)=>{const s=i=>{const o=i.data;o&&(o.t==="resolve"?(n(),e(o.v)):o.t==="reject"&&(n(),t(new Error(o.m||""))))},n=()=>{var i;try{(i=r.removeEventListener)==null||i.call(r,"message",s)}catch{}try{r.onmessage=null}catch{}try{r.close()}catch{}};r.addEventListener?r.addEventListener("message",s):r.on?r.on("message",i=>s({data:i})):r.onmessage=s,typeof r.start=="function"&&r.start()})}const throwTransferHandler=transferHandlers.get("throw"),throwTransferHandlerCustom={canHandle:throwTransferHandler.canHandle,serialize:({value:r})=>{let e;return r instanceof Error?(e={isError:!0,value:serializeError(r)},e.value.originalErrorClassName=r.constructor.name):e={isError:!1,value:r},[e,[]]},deserialize:r=>{if(r.isError){const e=deserializeError(r.value),t=new Error("Comlink method call failed");let s=e;for(;s.cause;)s=s.cause;throw s.cause=t,e}throw r.value}};transferHandlers.set("throw",throwTransferHandlerCustom);function proxyClone(r){return new Proxy(r,{get(e,t){switch(typeof e[t]){case"function":return(...s)=>e[t](...s);case"object":return e[t]===null?e[t]:proxyClone(e[t]);case"undefined":case"number":case"string":return e[t];default:return proxy(e[t])}}})}const MAX_ADDRESSABLE_FILE_OFFSET=BigInt(Number.MAX_SAFE_INTEGER);class IntervalNode{constructor(e){this.left=null,this.right=null,this.range=e,this.max=e.end}}class FileLockIntervalTree{constructor(){this.root=null}isEmpty(){return this.root===null}insert(e){this.root=this.insertNode(this.root,e)}findOverlapping(e){const t=[];return this.findOverlappingRanges(this.root,e,t),t}remove(e){this.root=this.removeNode(this.root,e)}findLocksForProcess(e){const t=[];return this.findLocksForProcessInNode(this.root,e,t),t}findStrictestExistingLockType(){let e="unlocked";const t=s=>{if(s){if(s.range.type==="exclusive"){e="exclusive";return}s.range.type==="shared"&&(e="shared"),t(s.left),t(s.right)}};return t(this.root),e}insertNode(e,t){return e?(t.start<e.range.start?e.left=this.insertNode(e.left,t):e.right=this.insertNode(e.right,t),e.max=this.bigintMax(e.max,t.end),e):new IntervalNode(t)}bigintMax(...e){return e.reduce((t,s)=>s>t?s:t,e[0])}findOverlappingRanges(e,t,s){e&&(this.doRangesOverlap(e.range,t)&&s.push(e.range),e.left&&e.left.max>=t.start&&this.findOverlappingRanges(e.left,t,s),e.right&&e.range.start<=t.end&&this.findOverlappingRanges(e.right,t,s))}doRangesOverlap(e,t){return e.start<t.end&&t.start<e.end}removeNode(e,t){if(!e)return null;if(this.areRangesEqual(e.range,t)){if(!e.left)return e.right;if(!e.right)return e.left;const s=this.findMin(e.right);e.range=s.range,e.right=this.removeNode(e.right,s.range)}else t.start<e.range.start?e.left=this.removeNode(e.left,t):e.right=this.removeNode(e.right,t);return e.max=e.range.end,e.left&&(e.max=this.bigintMax(e.max,e.left.max)),e.right&&(e.max=this.bigintMax(e.max,e.right.max)),e}findMin(e){let t=e;for(;t.left;)t=t.left;return t}areRangesEqual(e,t){return e.start===t.start&&e.end===t.end&&e.pid===t.pid&&e.fd===t.fd}findLocksForProcessInNode(e,t,s){e&&(e.range.pid===t&&s.push(e.range),this.findLocksForProcessInNode(e.left,t,s),this.findLocksForProcessInNode(e.right,t,s))}}class FileLockManagerInMemory{constructor(){this.locks=new Map}lockWholeFile(e,t){if(this.locks.get(e)===void 0){if(t.type==="unlock")return!0;this.locks.set(e,new FileLock)}const n=this.locks.get(e).lockWholeFile(t);return this.forgetPathIfUnlocked(e),n}lockFileByteRange(e,t){if(!this.locks.has(e)){if(t.type==="unlocked")return!0;this.locks.set(e,new FileLock)}return this.locks.get(e).lockFileByteRange(t)}findFirstConflictingByteRangeLock(e,t){const s=this.locks.get(e);if(s!==void 0)return s.findFirstConflictingByteRangeLock(t)}releaseLocksForProcess(e){for(const[t,s]of this.locks.entries())s.releaseLocksForProcess(e),this.forgetPathIfUnlocked(t)}releaseLocksOnFdClose(e,t,s){const n=this.locks.get(s);n&&(n.releaseLocksOnFdClose(e,t),this.forgetPathIfUnlocked(s))}forgetPathIfUnlocked(e){const t=this.locks.get(e);t&&t.isUnlocked()&&this.locks.delete(e)}}class FileLock{constructor(){this.rangeLocks=new FileLockIntervalTree,this.wholeFileLock={type:"unlocked"}}lockWholeFile(e){if(e.type==="unlock")return this.wholeFileLock.type==="unlocked"||(this.wholeFileLock.type==="exclusive"&&this.wholeFileLock.pid===e.pid&&this.wholeFileLock.fd===e.fd?this.wholeFileLock={type:"unlocked"}:this.wholeFileLock.type==="shared"&&this.wholeFileLock.pidFds.has(e.pid)&&this.wholeFileLock.pidFds.get(e.pid).has(e.fd)&&(this.wholeFileLock.pidFds.get(e.pid).delete(e.fd),this.wholeFileLock.pidFds.get(e.pid).size===0&&this.wholeFileLock.pidFds.delete(e.pid),this.wholeFileLock.pidFds.size===0&&(this.wholeFileLock={type:"unlocked"}))),!0;if(this.isThereAConflictWithRequestedWholeFileLock(e))return!1;if(e.type==="exclusive")return this.wholeFileLock={type:"exclusive",pid:e.pid,fd:e.fd},!0;if(e.type==="shared"){this.wholeFileLock.type!=="shared"&&(this.wholeFileLock={type:"shared",pidFds:new Map});const t=this.wholeFileLock;return t.pidFds.has(e.pid)||t.pidFds.set(e.pid,new Set),t.pidFds.get(e.pid).add(e.fd),!0}throw new Error(`Unexpected wholeFileLock() op: '${e.type}'`)}lockFileByteRange(e){if(e.start===e.end&&(e={...e,end:MAX_ADDRESSABLE_FILE_OFFSET}),e.type==="unlocked"){const o=this.rangeLocks.findOverlapping(e).filter(a=>a.pid===e.pid);for(const a of o)this.rangeLocks.remove(a),a.start<e.start&&this.rangeLocks.insert({...a,end:e.start}),a.end>e.end&&this.rangeLocks.insert({...a,start:e.end});return!0}if(this.isThereAConflictWithRequestedRangeLock(e))return!1;const t=this.rangeLocks.findOverlapping(e).filter(o=>o.pid===e.pid);let s=e.start,n=e.end;for(const o of t)this.rangeLocks.remove(o),o.start<s&&(s=o.start),o.end>n&&(n=o.end);const i={...e,start:s,end:n};return this.rangeLocks.insert(i),!0}findFirstConflictingByteRangeLock(e){e.start===e.end&&(e={...e,end:MAX_ADDRESSABLE_FILE_OFFSET});const s=this.rangeLocks.findOverlapping(e).find(i=>i.pid!==e.pid&&(e.type==="exclusive"||i.type==="exclusive"));if(s)return s;if(this.wholeFileLock.type==="unlocked")return;if(this.wholeFileLock.type==="exclusive"||e.type==="exclusive")return{type:this.wholeFileLock.type,start:0n,end:0n,pid:-1}}releaseLocksForProcess(e){for(const t of this.rangeLocks.findLocksForProcess(e))this.lockFileByteRange({...t,type:"unlocked"});if(this.wholeFileLock.type==="exclusive"&&this.wholeFileLock.pid===e)this.lockWholeFile({pid:e,fd:this.wholeFileLock.fd,type:"unlock"});else if(this.wholeFileLock.type==="shared"&&this.wholeFileLock.pidFds.has(e))for(const t of this.wholeFileLock.pidFds.get(e))this.lockWholeFile({pid:e,fd:t,type:"unlock"})}releaseLocksOnFdClose(e,t){for(const s of this.rangeLocks.findLocksForProcess(e))this.lockFileByteRange({...s,type:"unlocked"});this.lockWholeFile({pid:e,fd:t,type:"unlock"})}isUnlocked(){return this.wholeFileLock.type==="unlocked"&&this.rangeLocks.isEmpty()}isThereAConflictWithRequestedRangeLock(e){return this.findFirstConflictingByteRangeLock(e)!==void 0}isThereAConflictWithRequestedWholeFileLock(e){return e.type==="exclusive"?!!(this.wholeFileLock.type==="exclusive"&&(this.wholeFileLock.fd!==e.fd||this.wholeFileLock.pid!==e.pid)||this.wholeFileLock.type==="shared"&&Array.from(this.wholeFileLock.pidFds).some(([s])=>s!==e.pid)||this.rangeLocks.findOverlapping({start:0n,end:MAX_ADDRESSABLE_FILE_OFFSET}).length>0):e.type==="shared"?this.wholeFileLock.type==="exclusive"&&this.wholeFileLock.pid!==e.pid||this.rangeLocks.findOverlapping({start:0n,end:MAX_ADDRESSABLE_FILE_OFFSET}).filter(n=>n.type==="exclusive").length>0:!1}}class FileLockManagerComposite{constructor({nativeLockManager:e,wasmLockManager:t}){this.nativeLockManager=e,this.wasmLockManager=t}lockWholeFile(e,t){if(t.type!=="unlock"){let s,n;try{if(s=this.nativeLockManager.lockWholeFile(e,t),!s)return!1;n=this.wasmLockManager.lockWholeFile(e,t)}catch(i){logger.logger.error("Unexpected error in lockWholeFile()",i)}finally{s&&!n&&this.nativeLockManager.lockWholeFile(e,{...t,type:"unlock"})}return!!s&&!!n}try{this.wasmLockManager.lockWholeFile(e,t)}catch(s){logger.logger.error("Unexpected error unlocking whole file with in-memory lock manager",s)}try{this.nativeLockManager.lockWholeFile(e,t)}catch(s){logger.logger.error("Unexpected error unlocking whole file with native lock manager",s)}return!0}lockFileByteRange(e,t,s){if(t.type!=="unlocked"){let n,i;try{if(n=this.nativeLockManager.lockFileByteRange(e,t,s),!n)return!1;i=this.wasmLockManager.lockFileByteRange(e,t,s)}catch(o){logger.logger.error("Unexpected error in lockFileByteRange()",o)}finally{n&&!i&&this.nativeLockManager.lockFileByteRange(e,{...t,type:"unlocked"},!1)}return!!n&&!!i}try{this.wasmLockManager.lockFileByteRange(e,t,s)}catch(n){logger.logger.error("Unexpected error unlocking byte range with in-memory lock manager",n)}try{this.nativeLockManager.lockFileByteRange(e,t,s)}catch(n){logger.logger.error("Unexpected error unlocking byte range with native lock manager",n)}return!0}findFirstConflictingByteRangeLock(e,t){try{const s=this.nativeLockManager.findFirstConflictingByteRangeLock(e,t);return s||this.wasmLockManager.findFirstConflictingByteRangeLock(e,t)}catch(s){logger.logger.error("Unexpected error in findFirstConflictingByteRangeLock()",s);return}}releaseLocksForProcess(e){try{this.wasmLockManager.releaseLocksForProcess(e)}catch(t){logger.logger.error("Unexpected error in wasmLockManager.releaseLocksForProcess()",t)}try{this.nativeLockManager.releaseLocksForProcess(e)}catch(t){logger.logger.error("Unexpected error in nativeLockManager.releaseLocksForProcess()",t)}}releaseLocksOnFdClose(e,t,s){try{this.wasmLockManager.releaseLocksOnFdClose(e,t,s)}catch(n){logger.logger.error("Unexpected error in wasmLockManager.releaseLocksOnFdClose()",n)}try{this.nativeLockManager.releaseLocksOnFdClose(e,t,s)}catch(n){logger.logger.error("Unexpected error in nativeLockManager.releaseLocksOnFdClose()",n)}}}function createObjectPoolProxy(r){if(r.length===0)throw new Error("At least one instance is required");const e=[...r],t=[];function s(){const o=e.shift();return o!==void 0?Promise.resolve(o):new Promise(a=>{t.push(a)})}function n(o){const a=t.shift();a?a(o):e.push(o)}function i(o){return s().then(a=>{let c;try{c=o(a)}catch(l){throw n(a),l}return c!=null&&typeof c.then=="function"?c.then(l=>(n(a),l),l=>{throw n(a),l}):(n(a),c)})}return new Proxy({},{get(o,a){if(a in o)return o[a];if(a!=="then")return new Proxy(function(){},{apply(c,l,d){return i(p=>p[a](...d))},get(c,l){if(l==="then")return(d,p)=>i(f=>f[a]).then(d,p)}})}})}const maxValueForSigned32BitInteger=2**31-1;class ProcessIdAllocator{constructor(e=1,t=maxValueForSigned32BitInteger){this.claimed=new Set,this.initialId=e,this.maxId=t,this.nextId=e}claim(){const e=this.maxId-this.initialId+1;for(let t=0;t<e;t++)if(this.claimed.has(this.nextId))this.nextId++,this.nextId>this.maxId&&(this.nextId=this.initialId);else return this.claimed.add(this.nextId),this.nextId;throw new Error(`Unable to find free process ID after ${e} tries.`)}release(e){return this.claimed.has(e)?(this.claimed.delete(e),!0):!1}}exports.DEFAULT_BASE_URL=DEFAULT_BASE_URL;exports.FSHelpers=FSHelpers;exports.FileLock=FileLock;exports.FileLockIntervalTree=FileLockIntervalTree;exports.FileLockManagerComposite=FileLockManagerComposite;exports.FileLockManagerInMemory=FileLockManagerInMemory;exports.HttpCookieStore=HttpCookieStore;exports.LatestSupportedPHPVersion=LatestSupportedPHPVersion;exports.MAX_ADDRESSABLE_FILE_OFFSET=MAX_ADDRESSABLE_FILE_OFFSET;exports.PHP=PHP;exports.PHPExecutionFailureError=PHPExecutionFailureError;exports.PHPProcessManager=PHPProcessManager;exports.PHPRequestHandler=PHPRequestHandler;exports.PHPResponse=PHPResponse;exports.PHPWorker=PHPWorker;exports.ProcessIdAllocator=ProcessIdAllocator;exports.SinglePHPInstanceManager=SinglePHPInstanceManager;exports.StreamedPHPResponse=StreamedPHPResponse;exports.SupportedPHPVersions=SupportedPHPVersions;exports.SupportedPHPVersionsList=SupportedPHPVersionsList;exports.UnhandledRejectionsTarget=UnhandledRejectionsTarget;exports.__private__dont__use=__private__dont__use;exports.applyRewriteRules=applyRewriteRules;exports.consumeAPI=consumeAPI;exports.consumeAPISync=consumeAPISync;exports.createObjectPoolProxy=createObjectPoolProxy;exports.ensurePathPrefix=ensurePathPrefix;exports.exposeAPI=exposeAPI;exports.exposeSyncAPI=exposeSyncAPI;exports.getPhpIniEntries=getPhpIniEntries;exports.inferMimeType=inferMimeType;exports.isExitCode=isExitCode;exports.isPathToSharedFS=isPathToSharedFS;exports.iterateFiles=iteratePhpFiles;exports.loadPHPRuntime=loadPHPRuntime;exports.popLoadedRuntime=popLoadedRuntime;exports.portToStream=portToStream;exports.prettyPrintFullStackTrace=prettyPrintFullStackTrace;exports.printDebugDetails=printDebugDetails;exports.printResponseDebugDetails=printResponseDebugDetails;exports.proxyFileSystem=proxyFileSystem;exports.releaseApiProxy=releaseApiProxy;exports.removePathPrefix=removePathPrefix;exports.rotatePHPRuntime=rotatePHPRuntime;exports.sandboxedSpawnHandlerFactory=sandboxedSpawnHandlerFactory;exports.setPhpIniEntries=setPhpIniEntries;exports.streamToPort=streamToPort;exports.toRelativeUrl=toRelativeUrl;exports.withPHPIniValues=withPHPIniValues;exports.writeFiles=writeFiles;exports.writeFilesStreamToPhp=writeFilesStreamToPhp;
|
|
102
|
+
*/const WireValueType={RAW:"RAW",HANDLER:"HANDLER"},MessageType={GET:"GET",SET:"SET",APPLY:"APPLY",CONSTRUCT:"CONSTRUCT",ENDPOINT:"ENDPOINT",RELEASE:"RELEASE"},isObject=r=>typeof r=="object"&&r!==null||typeof r=="function",proxyTransferHandler={canHandle:r=>isObject(r)&&r[proxyMarker],serialize(r){const{port1:e,port2:t}=new MessageChannel;return expose(r,e),[t,[t]]},deserialize(r){return r.start(),wrap(r)}},throwTransferHandler$1={canHandle:r=>isObject(r)&&throwMarker in r,serialize({value:r}){let e;return r instanceof Error?e={isError:!0,value:{message:r.message,name:r.name,stack:r.stack}}:e={isError:!1,value:r},[e,[]]},deserialize(r){throw r.isError?Object.assign(new Error(r.value.message),r.value):r.value}},transferHandlers=new Map([["proxy",proxyTransferHandler],["throw",throwTransferHandler$1]]);function isAllowedOrigin(r,e){for(const t of r)if(e===t||t==="*"||t instanceof RegExp&&t.test(e))return!0;return!1}function expose(r,e=globalThis,t=["*"],s){e.addEventListener("message",function n(i){if(!i||!i.data)return;if(!isAllowedOrigin(t,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((_,k)=>_[k],r),f=c.reduce((_,k)=>_[k],r);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 _=new f(...l);d=proxy(_)}break;case MessageType.ENDPOINT:{const{port1:_,port2:k}=new MessageChannel;expose(r,k),d=transfer(_,[_])}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,_]=toWireValue(p);e.postMessage({...f,id:o},_),a===MessageType.RELEASE&&(e.removeEventListener("message",n),closeEndPoint(e),finalizer in r&&typeof r[finalizer]=="function"&&r[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(r){return r.constructor.name==="MessagePort"}function closeEndPoint(r){isMessagePort(r)&&r.close()}function wrap(r,e){const t=new Map;return r.addEventListener("message",function(n){const{data:i}=n;if(!i||!i.id)return;const o=t.get(i.id);if(o)try{o(i)}finally{t.delete(i.id)}}),createProxy(r,t,[],e)}function throwIfProxyReleased(r){if(r)throw new Error("Proxy has been released and is not useable")}function releaseEndpoint(r){return requestResponseMessage(r,new Map,{type:MessageType.RELEASE}).then(()=>{closeEndPoint(r)})}const proxyCounter=new WeakMap,proxyFinalizers="FinalizationRegistry"in globalThis&&new FinalizationRegistry(r=>{const e=(proxyCounter.get(r)||0)-1;proxyCounter.set(r,e),e===0&&releaseEndpoint(r)});function registerProxy(r,e){const t=(proxyCounter.get(e)||0)+1;proxyCounter.set(e,t),proxyFinalizers&&proxyFinalizers.register(r,e,r)}function unregisterProxy(r){proxyFinalizers&&proxyFinalizers.unregister(r)}function createProxy(r,e,t=[],s=function(){}){let n=!1;const i=new Proxy(s,{get(o,a){if(throwIfProxyReleased(n),a===releaseProxy)return()=>{unregisterProxy(i),releaseEndpoint(r),e.clear(),n=!0};if(a==="then"){if(t.length===0)return{then:()=>i};const c=requestResponseMessage(r,e,{type:MessageType.GET,path:t.map(l=>l.toString())}).then(fromWireValue);return c.then.bind(c)}return createProxy(r,e,[...t,a])},set(o,a,c){throwIfProxyReleased(n);const[l,d]=toWireValue(c);return requestResponseMessage(r,e,{type:MessageType.SET,path:[...t,a].map(p=>p.toString()),value:l},d).then(fromWireValue)},apply(o,a,c){throwIfProxyReleased(n);const l=t[t.length-1];if(l===createEndpoint)return requestResponseMessage(r,e,{type:MessageType.ENDPOINT}).then(fromWireValue);if(l==="bind")return createProxy(r,e,t.slice(0,-1));const[d,p]=processArguments(c);return requestResponseMessage(r,e,{type:MessageType.APPLY,path:t.map(f=>f.toString()),argumentList:d},p).then(fromWireValue)},construct(o,a){throwIfProxyReleased(n);const[c,l]=processArguments(a);return requestResponseMessage(r,e,{type:MessageType.CONSTRUCT,path:t.map(d=>d.toString()),argumentList:c},l).then(fromWireValue)}});return registerProxy(i,r),i}function myFlat(r){return Array.prototype.concat.apply([],r)}function processArguments(r){const e=r.map(toWireValue);return[e.map(t=>t[0]),myFlat(e.map(t=>t[1]))]}const transferCache=new WeakMap;function transfer(r,e){return transferCache.set(r,e),r}function proxy(r){return Object.assign(r,{[proxyMarker]:!0})}function windowEndpoint(r,e=globalThis,t="*"){return{postMessage:(s,n)=>r.postMessage(s,t,n),addEventListener:e.addEventListener.bind(e),removeEventListener:e.removeEventListener.bind(e)}}function toWireValue(r){for(const[e,t]of transferHandlers)if(t.canHandle(r)){const[s,n]=t.serialize(r);return[{type:WireValueType.HANDLER,name:e,value:s},n]}return[{type:WireValueType.RAW,value:r},transferCache.get(r)||[]]}function fromWireValue(r){switch(r.type){case WireValueType.HANDLER:return transferHandlers.get(r.name).deserialize(r.value);case WireValueType.RAW:return r.value}}function requestResponseMessage(r,e,t,s){return new Promise(n=>{const i=generateUUID();e.set(i,n),r.start&&r.start(),r.postMessage({id:i,...t},s)})}function generateUUID(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}function nodeEndpoint(r){const e=new WeakMap;return{postMessage:r.postMessage.bind(r),addEventListener:(t,s)=>{const n=i=>{"handleEvent"in s?s.handleEvent({data:i}):s({data:i})};r.on("message",n),e.set(s,n)},removeEventListener:(t,s)=>{const n=e.get(s);n&&(r.off("message",n),e.delete(s))},start:r.start&&r.start.bind(r)}}const proxyByListener=new WeakMap;function nodeProcessEndpoint(r){const e=r||process;if(typeof e.send!="function")throw new Error("IPC channel is not available. Did you forget to fork the process?");const t=e;return{postMessage(s,n){var i;if(n&&n.length>0)throw new Error("Transferable objects are not supported for nodeProcessEndpoint");(i=t.send)==null||i.call(t,s)},addEventListener(s,n){const i=typeof n=="function"?o=>n({data:o}):o=>n.handleEvent({data:o});proxyByListener.set(n,i),t.addListener(s,i)},removeEventListener(s,n){const i=proxyByListener.get(n);i&&(proxyByListener.delete(n),t.removeListener(s,i))},start(){}}}const list=[Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError,globalThis.DOMException,globalThis.AssertionError,globalThis.SystemError].filter(Boolean).map(r=>[r.name,r]),errorConstructors=new Map(list);class NonError extends Error{constructor(e){super(NonError._prepareSuperMessage(e)),this.name="NonError"}static _prepareSuperMessage(e){try{return JSON.stringify(e)}catch{return String(e)}}}const errorProperties=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1},{property:"errors",enumerable:!1}],toJsonWasCalled=new WeakSet,toJSON=r=>{toJsonWasCalled.add(r);const e=r.toJSON();return toJsonWasCalled.delete(r),e},newError=r=>{const e=errorConstructors.get(r)??Error;return e===AggregateError?new e([]):new e},destroyCircular=({from:r,seen:e,to:t,forceEnumerable:s,maxDepth:n,depth:i,useToJSON:o,serialize:a})=>{if(t||(Array.isArray(r)?t=[]:!a&&isErrorLike(r)?t=newError(r.name):t={}),e.push(r),i>=n)return t;if(o&&typeof r.toJSON=="function"&&!toJsonWasCalled.has(r))return toJSON(r);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(r)){if(d&&d instanceof Uint8Array&&d.constructor.name==="Buffer"){t[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){t[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){try{t[l]=d}catch{}continue}if(!e.includes(r[l])){i++,t[l]=c(r[l]);continue}t[l]="[Circular]"}}if(a||t instanceof Error)for(const{property:l,enumerable:d}of errorProperties)r[l]!==void 0&&r[l]!==null&&Object.defineProperty(t,l,{value:isErrorLike(r[l])||Array.isArray(r[l])?c(r[l]):r[l],enumerable:s?!0:d,configurable:!0,writable:!0});return t};function serializeError(r,e={}){const{maxDepth:t=Number.POSITIVE_INFINITY,useToJSON:s=!0}=e;return typeof r=="object"&&r!==null?destroyCircular({from:r,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:s,serialize:!0}):typeof r=="function"?`[Function: ${r.name||"anonymous"}]`:r}function deserializeError(r,e={}){const{maxDepth:t=Number.POSITIVE_INFINITY}=e;return r instanceof Error?r:isMinimumViableSerializedError(r)?destroyCircular({from:r,seen:[],to:newError(r.name),maxDepth:t,depth:0,serialize:!1}):new NonError(r)}function isErrorLike(r){return!!r&&typeof r=="object"&&typeof r.name=="string"&&typeof r.message=="string"&&typeof r.stack=="string"}function isMinimumViableSerializedError(r){return!!r&&typeof r=="object"&&typeof r.message=="string"&&!Array.isArray(r)}const releaseApiProxy=releaseProxy;async function consumeAPISync(r){setupTransferHandlers();const e=await NodeSABSyncReceiveMessageTransport.create();return wrapSync(r,e)}function consumeAPI(r,e=void 0){setupTransferHandlers();let t;if(typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u")if("postMessage"in r)t=nodeEndpoint(r);else if("send"in r&&"addListener"in r)t=nodeProcessEndpoint(r);else throw new Error("consumeAPI: remote does not look like a Worker, MessagePort, or Process");else t=r instanceof Worker?r:windowEndpoint(r,e);const n=wrap(t),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(r,e){return new Promise((t,s)=>{setTimeout(s,e),r.then(t)})}function exposeAPI(r,e,t){const{setReady:s,setFailed:n,exposedApi:i}=prepareForExpose(r,e);let o;if(t)if("addEventListener"in t)o=t;else if("postMessage"in t)o=nodeEndpoint(t);else if("send"in t&&"addListener"in t)o=nodeProcessEndpoint(t);else throw new Error("exposeAPI: targetWorker does not look like a Worker, MessagePort, or Process");else o=typeof window<"u"?windowEndpoint(self.parent):void 0;return expose(i,o),[s,n,i]}async function exposeSyncAPI(r,e){const{setReady:t,setFailed:s,exposedApi:n}=prepareForExpose(r),i=await NodeSABSyncReceiveMessageTransport.create(),o=nodeEndpoint(e);return exposeSync(n,o,i),[t,s,n]}function prepareForExpose(r,e){setupTransferHandlers();const t=Promise.resolve();let s,n;const i=new Promise((c,l)=>{s=c,n=l}),o=proxyClone(r),a=new Proxy(o,{get:(c,l)=>l==="isConnected"?()=>t: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:t=>t instanceof CustomEvent,serialize:t=>[{detail:t.detail},[]],deserialize:t=>t}),transferHandlers.set("FUNCTION",{canHandle:t=>typeof t=="function",serialize(t){const{port1:s,port2:n}=new MessageChannel;return expose(t,s),[n,[n]]},deserialize(t){return t.start(),wrap(t)}}),transferHandlers.set("MESSAGE_PORT",{canHandle:t=>t instanceof MessagePort,serialize(t){return[t,[t]]},deserialize(t){return t}}),transferHandlers.set("PHPResponse",{canHandle:t=>typeof t=="object"&&t!==null&&"headers"in t&&"bytes"in t&&"errors"in t&&"exitCode"in t&&"httpStatusCode"in t,serialize(t){const s=t.toRawData(),n=[];return s.bytes.buffer.byteLength>0&&n.push(s.bytes.buffer),[s,n]},deserialize(t){return PHPResponse.fromRawData(t)}});const r=transferHandlers.get("throw"),e=r==null?void 0:r.serialize;r.serialize=({value:t})=>{const s=e({value:t});return t.response&&(s[0].value.response=t.response),t.source&&(s[0].value.source=t.source),s},transferHandlers.set("StreamedPHPResponse",{canHandle:t=>t instanceof StreamedPHPResponse,serialize(t){const s=supportsTransferableStreams(),n=promiseToPort(t.exitCode),i=t.getHeadersStream();if(s)return[{__type:"StreamedPHPResponse",headers:i,stdout:t.stdout,stderr:t.stderr,exitCodePort:n},[i,t.stdout,t.stderr,n]];const o=streamToPort(i),a=streamToPort(t.stdout),c=streamToPort(t.stderr);return[{__type:"StreamedPHPResponse",headersPort:o,stdoutPort:a,stderrPort:c,exitCodePort:n},[o,a,c,n]]},deserialize(t){if(t.headers&&t.stdout&&t.stderr){const a=portToPromise(t.exitCodePort);return new StreamedPHPResponse(t.headers,t.stdout,t.stderr,a)}const s=portToStream(t.headersPort),n=portToStream(t.stdoutPort),i=portToStream(t.stderrPort),o=portToPromise(t.exitCodePort);return new StreamedPHPResponse(s,n,i,o)}})}let _cachedSupportsTransferableStreams;function supportsTransferableStreams(){if(typeof ReadableStream>"u"&&(_cachedSupportsTransferableStreams=!1),_cachedSupportsTransferableStreams===void 0)try{const{port1:r}=new MessageChannel,e=new ReadableStream;r.postMessage(e,[e]);try{r.close()}catch{}_cachedSupportsTransferableStreams=!0}catch{_cachedSupportsTransferableStreams=!1}return _cachedSupportsTransferableStreams}function streamToPort(r){const{port1:e,port2:t}=new MessageChannel;return(async()=>{const s=r.getReader();try{for(;;){const{done:n,value: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{}}})(),t}function portToStream(r){return new ReadableStream({start(e){const t=n=>{const i=n.data;if(i)switch(i.t){case"chunk":try{e.enqueue(new Uint8Array(i.b))}catch{s()}break;case"close":safeStreamClose(e),s();break;case"error":safeStreamError(e,new Error(i.m||"Stream error")),s();break}},s=()=>{var n;try{(n=r.removeEventListener)==null||n.call(r,"message",t)}catch{}try{r.onmessage=null}catch{}try{r.close()}catch{}};r.addEventListener?r.addEventListener("message",t):r.on?r.on("message",n=>t({data:n})):r.onmessage=t,typeof r.start=="function"&&r.start()},cancel(){try{r.close()}catch{}}})}function promiseToPort(r){const{port1:e,port2:t}=new MessageChannel;return r.then(s=>{try{e.postMessage({t:"resolve",v:s})}catch{}}).catch(s=>{try{e.postMessage({t:"reject",m:(s==null?void 0:s.message)||String(s)})}catch{}}).finally(()=>{try{e.close()}catch{}}),t}function portToPromise(r){return new Promise((e,t)=>{const s=i=>{const o=i.data;o&&(o.t==="resolve"?(n(),e(o.v)):o.t==="reject"&&(n(),t(new Error(o.m||""))))},n=()=>{var i;try{(i=r.removeEventListener)==null||i.call(r,"message",s)}catch{}try{r.onmessage=null}catch{}try{r.close()}catch{}};r.addEventListener?r.addEventListener("message",s):r.on?r.on("message",i=>s({data:i})):r.onmessage=s,typeof r.start=="function"&&r.start()})}const throwTransferHandler=transferHandlers.get("throw"),throwTransferHandlerCustom={canHandle:throwTransferHandler.canHandle,serialize:({value:r})=>{let e;return r instanceof Error?(e={isError:!0,value:serializeError(r)},e.value.originalErrorClassName=r.constructor.name):e={isError:!1,value:r},[e,[]]},deserialize:r=>{if(r.isError){const e=deserializeError(r.value),t=new Error("Comlink method call failed");let s=e;for(;s.cause;)s=s.cause;throw s.cause=t,e}throw r.value}};transferHandlers.set("throw",throwTransferHandlerCustom);function proxyClone(r){return new Proxy(r,{get(e,t){switch(typeof e[t]){case"function":return(...s)=>e[t](...s);case"object":return e[t]===null?e[t]:proxyClone(e[t]);case"undefined":case"number":case"string":return e[t];default:return proxy(e[t])}}})}function safeStreamError(r,e){try{r.error(e)}catch{}}function safeStreamClose(r){try{r.close()}catch{}}const MAX_ADDRESSABLE_FILE_OFFSET=BigInt(Number.MAX_SAFE_INTEGER);class IntervalNode{constructor(e){this.left=null,this.right=null,this.range=e,this.max=e.end}}class FileLockIntervalTree{constructor(){this.root=null}isEmpty(){return this.root===null}insert(e){this.root=this.insertNode(this.root,e)}findOverlapping(e){const t=[];return this.findOverlappingRanges(this.root,e,t),t}remove(e){this.root=this.removeNode(this.root,e)}findLocksForProcess(e){const t=[];return this.findLocksForProcessInNode(this.root,e,t),t}findStrictestExistingLockType(){let e="unlocked";const t=s=>{if(s){if(s.range.type==="exclusive"){e="exclusive";return}s.range.type==="shared"&&(e="shared"),t(s.left),t(s.right)}};return t(this.root),e}insertNode(e,t){return e?(t.start<e.range.start?e.left=this.insertNode(e.left,t):e.right=this.insertNode(e.right,t),e.max=this.bigintMax(e.max,t.end),e):new IntervalNode(t)}bigintMax(...e){return e.reduce((t,s)=>s>t?s:t,e[0])}findOverlappingRanges(e,t,s){e&&(this.doRangesOverlap(e.range,t)&&s.push(e.range),e.left&&e.left.max>=t.start&&this.findOverlappingRanges(e.left,t,s),e.right&&e.range.start<=t.end&&this.findOverlappingRanges(e.right,t,s))}doRangesOverlap(e,t){return e.start<t.end&&t.start<e.end}removeNode(e,t){if(!e)return null;if(this.areRangesEqual(e.range,t)){if(!e.left)return e.right;if(!e.right)return e.left;const s=this.findMin(e.right);e.range=s.range,e.right=this.removeNode(e.right,s.range)}else t.start<e.range.start?e.left=this.removeNode(e.left,t):e.right=this.removeNode(e.right,t);return e.max=e.range.end,e.left&&(e.max=this.bigintMax(e.max,e.left.max)),e.right&&(e.max=this.bigintMax(e.max,e.right.max)),e}findMin(e){let t=e;for(;t.left;)t=t.left;return t}areRangesEqual(e,t){return e.start===t.start&&e.end===t.end&&e.pid===t.pid&&e.fd===t.fd}findLocksForProcessInNode(e,t,s){e&&(e.range.pid===t&&s.push(e.range),this.findLocksForProcessInNode(e.left,t,s),this.findLocksForProcessInNode(e.right,t,s))}}class FileLockManagerInMemory{constructor(){this.locks=new Map}lockWholeFile(e,t){if(this.locks.get(e)===void 0){if(t.type==="unlock")return!0;this.locks.set(e,new FileLock)}const n=this.locks.get(e).lockWholeFile(t);return this.forgetPathIfUnlocked(e),n}lockFileByteRange(e,t){if(!this.locks.has(e)){if(t.type==="unlocked")return!0;this.locks.set(e,new FileLock)}return this.locks.get(e).lockFileByteRange(t)}findFirstConflictingByteRangeLock(e,t){const s=this.locks.get(e);if(s!==void 0)return s.findFirstConflictingByteRangeLock(t)}releaseLocksForProcess(e){for(const[t,s]of this.locks.entries())s.releaseLocksForProcess(e),this.forgetPathIfUnlocked(t)}releaseLocksOnFdClose(e,t,s){const n=this.locks.get(s);n&&(n.releaseLocksOnFdClose(e,t),this.forgetPathIfUnlocked(s))}forgetPathIfUnlocked(e){const t=this.locks.get(e);t&&t.isUnlocked()&&this.locks.delete(e)}}class FileLock{constructor(){this.rangeLocks=new FileLockIntervalTree,this.wholeFileLock={type:"unlocked"}}lockWholeFile(e){if(e.type==="unlock")return this.wholeFileLock.type==="unlocked"||(this.wholeFileLock.type==="exclusive"&&this.wholeFileLock.pid===e.pid&&this.wholeFileLock.fd===e.fd?this.wholeFileLock={type:"unlocked"}:this.wholeFileLock.type==="shared"&&this.wholeFileLock.pidFds.has(e.pid)&&this.wholeFileLock.pidFds.get(e.pid).has(e.fd)&&(this.wholeFileLock.pidFds.get(e.pid).delete(e.fd),this.wholeFileLock.pidFds.get(e.pid).size===0&&this.wholeFileLock.pidFds.delete(e.pid),this.wholeFileLock.pidFds.size===0&&(this.wholeFileLock={type:"unlocked"}))),!0;if(this.isThereAConflictWithRequestedWholeFileLock(e))return!1;if(e.type==="exclusive")return this.wholeFileLock={type:"exclusive",pid:e.pid,fd:e.fd},!0;if(e.type==="shared"){this.wholeFileLock.type!=="shared"&&(this.wholeFileLock={type:"shared",pidFds:new Map});const t=this.wholeFileLock;return t.pidFds.has(e.pid)||t.pidFds.set(e.pid,new Set),t.pidFds.get(e.pid).add(e.fd),!0}throw new Error(`Unexpected wholeFileLock() op: '${e.type}'`)}lockFileByteRange(e){if(e.start===e.end&&(e={...e,end:MAX_ADDRESSABLE_FILE_OFFSET}),e.type==="unlocked"){const o=this.rangeLocks.findOverlapping(e).filter(a=>a.pid===e.pid);for(const a of o)this.rangeLocks.remove(a),a.start<e.start&&this.rangeLocks.insert({...a,end:e.start}),a.end>e.end&&this.rangeLocks.insert({...a,start:e.end});return!0}if(this.isThereAConflictWithRequestedRangeLock(e))return!1;const t=this.rangeLocks.findOverlapping(e).filter(o=>o.pid===e.pid);let s=e.start,n=e.end;for(const o of t)this.rangeLocks.remove(o),o.start<s&&(s=o.start),o.end>n&&(n=o.end);const i={...e,start:s,end:n};return this.rangeLocks.insert(i),!0}findFirstConflictingByteRangeLock(e){e.start===e.end&&(e={...e,end:MAX_ADDRESSABLE_FILE_OFFSET});const s=this.rangeLocks.findOverlapping(e).find(i=>i.pid!==e.pid&&(e.type==="exclusive"||i.type==="exclusive"));if(s)return s;if(this.wholeFileLock.type==="unlocked")return;if(this.wholeFileLock.type==="exclusive"||e.type==="exclusive")return{type:this.wholeFileLock.type,start:0n,end:0n,pid:-1}}releaseLocksForProcess(e){for(const t of this.rangeLocks.findLocksForProcess(e))this.lockFileByteRange({...t,type:"unlocked"});if(this.wholeFileLock.type==="exclusive"&&this.wholeFileLock.pid===e)this.lockWholeFile({pid:e,fd:this.wholeFileLock.fd,type:"unlock"});else if(this.wholeFileLock.type==="shared"&&this.wholeFileLock.pidFds.has(e))for(const t of this.wholeFileLock.pidFds.get(e))this.lockWholeFile({pid:e,fd:t,type:"unlock"})}releaseLocksOnFdClose(e,t){for(const s of this.rangeLocks.findLocksForProcess(e))this.lockFileByteRange({...s,type:"unlocked"});this.lockWholeFile({pid:e,fd:t,type:"unlock"})}isUnlocked(){return this.wholeFileLock.type==="unlocked"&&this.rangeLocks.isEmpty()}isThereAConflictWithRequestedRangeLock(e){return this.findFirstConflictingByteRangeLock(e)!==void 0}isThereAConflictWithRequestedWholeFileLock(e){return e.type==="exclusive"?!!(this.wholeFileLock.type==="exclusive"&&(this.wholeFileLock.fd!==e.fd||this.wholeFileLock.pid!==e.pid)||this.wholeFileLock.type==="shared"&&Array.from(this.wholeFileLock.pidFds).some(([s])=>s!==e.pid)||this.rangeLocks.findOverlapping({start:0n,end:MAX_ADDRESSABLE_FILE_OFFSET}).length>0):e.type==="shared"?this.wholeFileLock.type==="exclusive"&&this.wholeFileLock.pid!==e.pid||this.rangeLocks.findOverlapping({start:0n,end:MAX_ADDRESSABLE_FILE_OFFSET}).filter(n=>n.type==="exclusive").length>0:!1}}class FileLockManagerComposite{constructor({nativeLockManager:e,wasmLockManager:t}){this.nativeLockManager=e,this.wasmLockManager=t}lockWholeFile(e,t){if(t.type!=="unlock"){let s,n;try{if(s=this.nativeLockManager.lockWholeFile(e,t),!s)return!1;n=this.wasmLockManager.lockWholeFile(e,t)}catch(i){logger.logger.error("Unexpected error in lockWholeFile()",i)}finally{s&&!n&&this.nativeLockManager.lockWholeFile(e,{...t,type:"unlock"})}return!!s&&!!n}try{this.wasmLockManager.lockWholeFile(e,t)}catch(s){logger.logger.error("Unexpected error unlocking whole file with in-memory lock manager",s)}try{this.nativeLockManager.lockWholeFile(e,t)}catch(s){logger.logger.error("Unexpected error unlocking whole file with native lock manager",s)}return!0}lockFileByteRange(e,t,s){if(t.type!=="unlocked"){let n,i;try{if(n=this.nativeLockManager.lockFileByteRange(e,t,s),!n)return!1;i=this.wasmLockManager.lockFileByteRange(e,t,s)}catch(o){logger.logger.error("Unexpected error in lockFileByteRange()",o)}finally{n&&!i&&this.nativeLockManager.lockFileByteRange(e,{...t,type:"unlocked"},!1)}return!!n&&!!i}try{this.wasmLockManager.lockFileByteRange(e,t,s)}catch(n){logger.logger.error("Unexpected error unlocking byte range with in-memory lock manager",n)}try{this.nativeLockManager.lockFileByteRange(e,t,s)}catch(n){logger.logger.error("Unexpected error unlocking byte range with native lock manager",n)}return!0}findFirstConflictingByteRangeLock(e,t){try{const s=this.nativeLockManager.findFirstConflictingByteRangeLock(e,t);return s||this.wasmLockManager.findFirstConflictingByteRangeLock(e,t)}catch(s){logger.logger.error("Unexpected error in findFirstConflictingByteRangeLock()",s);return}}releaseLocksForProcess(e){try{this.wasmLockManager.releaseLocksForProcess(e)}catch(t){logger.logger.error("Unexpected error in wasmLockManager.releaseLocksForProcess()",t)}try{this.nativeLockManager.releaseLocksForProcess(e)}catch(t){logger.logger.error("Unexpected error in nativeLockManager.releaseLocksForProcess()",t)}}releaseLocksOnFdClose(e,t,s){try{this.wasmLockManager.releaseLocksOnFdClose(e,t,s)}catch(n){logger.logger.error("Unexpected error in wasmLockManager.releaseLocksOnFdClose()",n)}try{this.nativeLockManager.releaseLocksOnFdClose(e,t,s)}catch(n){logger.logger.error("Unexpected error in nativeLockManager.releaseLocksOnFdClose()",n)}}}function createObjectPoolProxy(r){if(r.length===0)throw new Error("At least one instance is required");const e=[...r],t=[];function s(){const o=e.shift();return o!==void 0?Promise.resolve(o):new Promise(a=>{t.push(a)})}function n(o){const a=t.shift();a?a(o):e.push(o)}function i(o){return s().then(a=>{let c;try{c=o(a)}catch(l){throw n(a),l}return c!=null&&typeof c.then=="function"?c.then(l=>(n(a),l),l=>{throw n(a),l}):(n(a),c)})}return new Proxy({},{get(o,a){if(a in o)return o[a];if(a!=="then")return new Proxy(function(){},{apply(c,l,d){return i(p=>p[a](...d))},get(c,l){if(l==="then")return(d,p)=>i(f=>f[a]).then(d,p)}})}})}const maxValueForSigned32BitInteger=2**31-1;class ProcessIdAllocator{constructor(e=1,t=maxValueForSigned32BitInteger){this.claimed=new Set,this.initialId=e,this.maxId=t,this.nextId=e}claim(){const e=this.maxId-this.initialId+1;for(let t=0;t<e;t++)if(this.claimed.has(this.nextId))this.nextId++,this.nextId>this.maxId&&(this.nextId=this.initialId);else return this.claimed.add(this.nextId),this.nextId;throw new Error(`Unable to find free process ID after ${e} tries.`)}release(e){return this.claimed.has(e)?(this.claimed.delete(e),!0):!1}}exports.DEFAULT_BASE_URL=DEFAULT_BASE_URL;exports.FSHelpers=FSHelpers;exports.FileLock=FileLock;exports.FileLockIntervalTree=FileLockIntervalTree;exports.FileLockManagerComposite=FileLockManagerComposite;exports.FileLockManagerInMemory=FileLockManagerInMemory;exports.HttpCookieStore=HttpCookieStore;exports.LatestSupportedPHPVersion=LatestSupportedPHPVersion;exports.MAX_ADDRESSABLE_FILE_OFFSET=MAX_ADDRESSABLE_FILE_OFFSET;exports.PHP=PHP;exports.PHPExecutionFailureError=PHPExecutionFailureError;exports.PHPProcessManager=PHPProcessManager;exports.PHPRequestHandler=PHPRequestHandler;exports.PHPResponse=PHPResponse;exports.PHPWorker=PHPWorker;exports.ProcessIdAllocator=ProcessIdAllocator;exports.SinglePHPInstanceManager=SinglePHPInstanceManager;exports.StreamedPHPResponse=StreamedPHPResponse;exports.SupportedPHPVersions=SupportedPHPVersions;exports.SupportedPHPVersionsList=SupportedPHPVersionsList;exports.UnhandledRejectionsTarget=UnhandledRejectionsTarget;exports.__private__dont__use=__private__dont__use;exports.applyRewriteRules=applyRewriteRules;exports.consumeAPI=consumeAPI;exports.consumeAPISync=consumeAPISync;exports.createObjectPoolProxy=createObjectPoolProxy;exports.ensurePathPrefix=ensurePathPrefix;exports.exposeAPI=exposeAPI;exports.exposeSyncAPI=exposeSyncAPI;exports.getPhpIniEntries=getPhpIniEntries;exports.inferMimeType=inferMimeType;exports.isExitCode=isExitCode;exports.isPathToSharedFS=isPathToSharedFS;exports.iterateFiles=iteratePhpFiles;exports.loadPHPRuntime=loadPHPRuntime;exports.popLoadedRuntime=popLoadedRuntime;exports.portToStream=portToStream;exports.prettyPrintFullStackTrace=prettyPrintFullStackTrace;exports.printDebugDetails=printDebugDetails;exports.printResponseDebugDetails=printResponseDebugDetails;exports.proxyFileSystem=proxyFileSystem;exports.releaseApiProxy=releaseApiProxy;exports.removePathPrefix=removePathPrefix;exports.rotatePHPRuntime=rotatePHPRuntime;exports.sandboxedSpawnHandlerFactory=sandboxedSpawnHandlerFactory;exports.setPhpIniEntries=setPhpIniEntries;exports.streamToPort=streamToPort;exports.toRelativeUrl=toRelativeUrl;exports.withPHPIniValues=withPHPIniValues;exports.writeFiles=writeFiles;exports.writeFilesStreamToPhp=writeFilesStreamToPhp;
|
|
103
103
|
//# sourceMappingURL=index.cjs.map
|