@php-wasm/fs-journal 0.6.0 → 0.6.2

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.
Files changed (3) hide show
  1. package/index.cjs +5 -5
  2. package/index.js +122 -114
  3. package/package.json +2 -2
package/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var K=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)};var a=(e,t,r)=>(K(e,t,"read from private field"),r?r.call(e):t.get(e)),l=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},d=(e,t,r,s)=>(K(e,t,"write to private field"),s?s.call(e,r):t.set(e,r),r);var f=(e,t,r)=>(K(e,t,"access private method"),r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});if(typeof File>"u"){class e extends Blob{constructor(r,s,i){super(r);let n;i!=null&&i.lastModified&&(n=new Date),(!n||isNaN(n.getFullYear()))&&(n=new Date),this.lastModifiedDate=n,this.lastModified=n.getMilliseconds(),this.name=s||""}}global.File=e}function asPromise(e){return new Promise(function(t,r){e.onload=e.onerror=function(s){e.onload=e.onerror=null,s.type==="load"?t(e.result):r(new Error("Failed to read the blob/file"))}})}typeof Blob.prototype.arrayBuffer>"u"&&(Blob.prototype.arrayBuffer=function(){const t=new FileReader;return t.readAsArrayBuffer(this),asPromise(t)});typeof Blob.prototype.text>"u"&&(Blob.prototype.text=function(){const t=new FileReader;return t.readAsText(this),asPromise(t)});function isByobSupported(){const e=new Uint8Array([1,2,3,4]),r=new File([e],"test").stream();try{return r.getReader({mode:"byob"}),!0}catch{return!1}}(typeof Blob.prototype.stream>"u"||!isByobSupported())&&(Blob.prototype.stream=function(){let e=0;const t=this;return new ReadableStream({type:"bytes",autoAllocateChunkSize:512*1024,async pull(r){const s=r.byobRequest.view,n=await t.slice(e,e+s.byteLength).arrayBuffer(),o=new Uint8Array(n);new Uint8Array(s.buffer).set(o);const c=o.byteLength;r.byobRequest.respond(c),e+=c,e>=t.size&&r.close()}})});if(typeof CustomEvent>"u"){class e extends Event{constructor(r,s={}){super(r,s),this.detail=s.detail}initCustomEvent(){}}globalThis.CustomEvent=e}const kError=Symbol("error"),kMessage=Symbol("message");class ErrorEvent2 extends Event{constructor(t,r={}){super(t),this[kError]=r.error===void 0?null:r.error,this[kMessage]=r.message===void 0?"":r.message}get error(){return this[kError]}get message(){return this[kMessage]}}Object.defineProperty(ErrorEvent2.prototype,"error",{enumerable:!0});Object.defineProperty(ErrorEvent2.prototype,"message",{enumerable:!0});const ErrorEvent=typeof globalThis.ErrorEvent=="function"?globalThis.ErrorEvent:ErrorEvent2;function isExitCodeZero(e){return e instanceof Error?"exitCode"in e&&(e==null?void 0:e.exitCode)===0||(e==null?void 0:e.name)==="ExitStatus"&&"status"in e&&e.status===0:!1}class UnhandledRejectionsTarget extends EventTarget{constructor(){super(...arguments),this.listenersCount=0}addEventListener(t,r){++this.listenersCount,super.addEventListener(t,r)}removeEventListener(t,r){--this.listenersCount,super.removeEventListener(t,r)}hasListeners(){return this.listenersCount>0}}function improveWASMErrorReporting(e){e.asm={...e.asm};const t=new UnhandledRejectionsTarget;for(const r in e.asm)if(typeof e.asm[r]=="function"){const s=e.asm[r];e.asm[r]=function(...i){var n;try{return s(...i)}catch(o){if(!(o instanceof Error))throw o;const c=clarifyErrorMessage(o,(n=e.lastAsyncifyStackSource)==null?void 0:n.stack);if(e.lastAsyncifyStackSource&&(o.cause=e.lastAsyncifyStackSource),t.hasListeners()){t.dispatchEvent(new ErrorEvent("error",{error:o,message:c}));return}throw isExitCodeZero(o)||showCriticalErrorBox(c),o}}}return t}let functionsMaybeMissingFromAsyncify=[];function getFunctionsMaybeMissingFromAsyncify(){return functionsMaybeMissingFromAsyncify}function clarifyErrorMessage(e,t){if(e.message==="unreachable"){let r=UNREACHABLE_ERROR;t||(r+=`
1
+ "use strict";var Z=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)};var a=(e,t,r)=>(Z(e,t,"read from private field"),r?r.call(e):t.get(e)),l=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},d=(e,t,r,s)=>(Z(e,t,"write to private field"),s?s.call(e,r):t.set(e,r),r);var p=(e,t,r)=>(Z(e,t,"access private method"),r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});if(typeof File>"u"){class e extends Blob{constructor(r,s,i){super(r);let n;i!=null&&i.lastModified&&(n=new Date),(!n||isNaN(n.getFullYear()))&&(n=new Date),this.lastModifiedDate=n,this.lastModified=n.getMilliseconds(),this.name=s||""}}global.File=e}function asPromise(e){return new Promise(function(t,r){e.onload=e.onerror=function(s){e.onload=e.onerror=null,s.type==="load"?t(e.result):r(new Error("Failed to read the blob/file"))}})}typeof Blob.prototype.arrayBuffer>"u"&&(Blob.prototype.arrayBuffer=function(){const t=new FileReader;return t.readAsArrayBuffer(this),asPromise(t)});typeof Blob.prototype.text>"u"&&(Blob.prototype.text=function(){const t=new FileReader;return t.readAsText(this),asPromise(t)});function isByobSupported(){const e=new Uint8Array([1,2,3,4]),r=new File([e],"test").stream();try{return r.getReader({mode:"byob"}),!0}catch{return!1}}(typeof Blob.prototype.stream>"u"||!isByobSupported())&&(Blob.prototype.stream=function(){let e=0;const t=this;return new ReadableStream({type:"bytes",autoAllocateChunkSize:512*1024,async pull(r){const s=r.byobRequest.view,n=await t.slice(e,e+s.byteLength).arrayBuffer(),o=new Uint8Array(n);new Uint8Array(s.buffer).set(o);const c=o.byteLength;r.byobRequest.respond(c),e+=c,e>=t.size&&r.close()}})});if(typeof CustomEvent>"u"){class e extends Event{constructor(r,s={}){super(r,s),this.detail=s.detail}initCustomEvent(){}}globalThis.CustomEvent=e}const kError=Symbol("error"),kMessage=Symbol("message");class ErrorEvent2 extends Event{constructor(t,r={}){super(t),this[kError]=r.error===void 0?null:r.error,this[kMessage]=r.message===void 0?"":r.message}get error(){return this[kError]}get message(){return this[kMessage]}}Object.defineProperty(ErrorEvent2.prototype,"error",{enumerable:!0});Object.defineProperty(ErrorEvent2.prototype,"message",{enumerable:!0});const ErrorEvent=typeof globalThis.ErrorEvent=="function"?globalThis.ErrorEvent:ErrorEvent2;function isExitCodeZero(e){return e instanceof Error?"exitCode"in e&&(e==null?void 0:e.exitCode)===0||(e==null?void 0:e.name)==="ExitStatus"&&"status"in e&&e.status===0:!1}class UnhandledRejectionsTarget extends EventTarget{constructor(){super(...arguments),this.listenersCount=0}addEventListener(t,r){++this.listenersCount,super.addEventListener(t,r)}removeEventListener(t,r){--this.listenersCount,super.removeEventListener(t,r)}hasListeners(){return this.listenersCount>0}}function improveWASMErrorReporting(e){e.asm={...e.asm};const t=new UnhandledRejectionsTarget;for(const r in e.asm)if(typeof e.asm[r]=="function"){const s=e.asm[r];e.asm[r]=function(...i){var n;try{return s(...i)}catch(o){if(!(o instanceof Error))throw o;const c=clarifyErrorMessage(o,(n=e.lastAsyncifyStackSource)==null?void 0:n.stack);if(e.lastAsyncifyStackSource&&(o.cause=e.lastAsyncifyStackSource),t.hasListeners()){t.dispatchEvent(new ErrorEvent("error",{error:o,message:c}));return}throw isExitCodeZero(o)||showCriticalErrorBox(c),o}}}return t}let functionsMaybeMissingFromAsyncify=[];function getFunctionsMaybeMissingFromAsyncify(){return functionsMaybeMissingFromAsyncify}function clarifyErrorMessage(e,t){if(e.message==="unreachable"){let r=UNREACHABLE_ERROR;t||(r+=`
2
2
 
3
3
  This stack trace is lacking. For a better one initialize
4
4
  the PHP runtime with { debug: true }, e.g. PHPNode.load('8.1', { debug: true }).
@@ -32,9 +32,9 @@ CLI option:
32
32
  ${eol}
33
33
  ${bold} WASM ERROR${reset}${redBg}`);for(const t of e.split(`
34
34
  `))console.log(`${eol} ${t} `);console.log(`${reset}`)}}function extractPHPFunctionsFromStack(e){try{const t=e.split(`
35
- `).slice(1).map(r=>{const s=r.trim().substring(3).split(" ");return{fn:s.length>=2?s[0]:"<unknown>",isWasm:r.includes("wasm://")}}).filter(({fn:r,isWasm:s})=>s&&!r.startsWith("dynCall_")&&!r.startsWith("invoke_")).map(({fn:r})=>r);return Array.from(new Set(t))}catch{return[]}}class Semaphore{constructor({concurrency:t}){this._running=0,this.concurrency=t,this.queue=[]}get running(){return this._running}async acquire(){for(;;)if(this._running>=this.concurrency)await new Promise(t=>this.queue.push(t));else{this._running++;let t=!1;return()=>{t||(t=!0,this._running--,this.queue.length>0&&this.queue.shift()())}}}async run(t){const r=await this.acquire();try{return await t()}finally{r()}}}function joinPaths(...e){let t=e.join("/");const r=t[0]==="/",s=t.substring(t.length-1)==="/";return t=normalizePath$1(t),!t&&!r&&(t="."),t&&s&&(t+="/"),t}function basename(e){if(e==="/")return"/";e=normalizePath$1(e);const t=e.lastIndexOf("/");return t===-1?e:e.substr(t+1)}function normalizePath$1(e){const t=e[0]==="/";return e=normalizePathsArray(e.split("/").filter(r=>!!r),!t).join("/"),(t?"/":"")+e.replace(/\/$/,"")}function normalizePathsArray(e,t){let r=0;for(let s=e.length-1;s>=0;s--){const i=e[s];i==="."?e.splice(s,1):i===".."?(e.splice(s,1),r++):r&&(e.splice(s,1),r--)}if(t)for(;r;r--)e.unshift("..");return e}function createSpawnHandler(e){return function(t){const r=new ChildProcess,s=new ProcessApi(r);return setTimeout(async()=>{await e(t,s),r.emit("spawn",!0)}),r}}class EventEmitter{constructor(){this.listeners={}}emit(t,r){this.listeners[t]&&this.listeners[t].forEach(function(s){s(r)})}on(t,r){this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(r)}}class ProcessApi extends EventEmitter{constructor(t){super(),this.childProcess=t,this.exited=!1,this.stdinData=[],t.on("stdin",r=>{this.stdinData?this.stdinData.push(r.slice()):this.emit("stdin",r)})}stdout(t){typeof t=="string"&&(t=new TextEncoder().encode(t)),this.childProcess.stdout.emit("data",t)}stderr(t){typeof t=="string"&&(t=new TextEncoder().encode(t)),this.childProcess.stderr.emit("data",t)}exit(t){this.exited||(this.exited=!0,this.childProcess.emit("exit",t))}flushStdin(){if(this.stdinData)for(let t=0;t<this.stdinData.length;t++)this.emit("stdin",this.stdinData[t]);this.stdinData=null}}let lastPid=9743;class ChildProcess extends EventEmitter{constructor(t=lastPid++){super(),this.pid=t,this.stdout=new EventEmitter,this.stderr=new EventEmitter;const r=this;this.stdin={write:s=>{r.emit("stdin",s)}}}}ReadableStream.prototype[Symbol.asyncIterator]||(ReadableStream.prototype[Symbol.asyncIterator]=async function*(){const e=this.getReader();try{for(;;){const{done:t,value:r}=await e.read();if(t)return;yield r}}finally{e.releaseLock()}},ReadableStream.prototype.iterate=ReadableStream.prototype[Symbol.asyncIterator]);class PHPResponse{constructor(t,r,s,i="",n=0){this.httpStatusCode=t,this.headers=r,this.bytes=s,this.exitCode=n,this.errors=i}static fromRawData(t){return new PHPResponse(t.httpStatusCode,t.headers,t.bytes,t.errors,t.exitCode)}toRawData(){return{headers:this.headers,bytes:this.bytes,errors:this.errors,exitCode:this.exitCode,httpStatusCode:this.httpStatusCode}}get json(){return JSON.parse(this.text)}get text(){return new TextDecoder().decode(this.bytes)}}var b,T;class PHPBrowser{constructor(t,r={}){l(this,b,void 0);l(this,T,void 0);this.requestHandler=t,d(this,b,{}),d(this,T,{handleRedirects:!1,maxRedirects:4,...r})}async request(t,r=0){const s=await this.requestHandler.request({...t,headers:{...t.headers,cookie:this.serializeCookies()}});if(s.headers["set-cookie"]&&this.setCookies(s.headers["set-cookie"]),a(this,T).handleRedirects&&s.headers.location&&r<a(this,T).maxRedirects){const i=new URL(s.headers.location[0],this.requestHandler.absoluteUrl);return this.request({url:i.toString(),method:"GET",headers:{}},r+1)}return s}pathToInternalUrl(t){return this.requestHandler.pathToInternalUrl(t)}internalUrlToPath(t){return this.requestHandler.internalUrlToPath(t)}get absoluteUrl(){return this.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.documentRoot}setCookies(t){for(const r of t)try{if(!r.includes("="))continue;const s=r.indexOf("="),i=r.substring(0,s),n=r.substring(s+1).split(";")[0];a(this,b)[i]=n}catch(s){console.error(s)}}serializeCookies(){const t=[];for(const r in a(this,b))t.push(`${r}=${a(this,b)[r]}`);return t.join("; ")}}b=new WeakMap,T=new WeakMap;const DEFAULT_BASE_URL="http://example.com";function toRelativeUrl(e){return e.toString().substring(e.origin.length)}function removePathPrefix(e,t){return!t||!e.startsWith(t)?e:e.substring(t.length)}function ensurePathPrefix(e,t){return!t||e.startsWith(t)?e:t+e}var E,F,M,R,x,m,k,C,N,Z,B,Q,O,X;class PHPRequestHandler{constructor(t,r={}){l(this,N);l(this,B);l(this,O);l(this,E,void 0);l(this,F,void 0);l(this,M,void 0);l(this,R,void 0);l(this,x,void 0);l(this,m,void 0);l(this,k,void 0);l(this,C,void 0);d(this,C,new Semaphore({concurrency:1}));const{documentRoot:s="/www/",absoluteUrl:i=typeof location=="object"?location==null?void 0:location.href:""}=r;this.php=t,d(this,E,s);const n=new URL(i);d(this,M,n.hostname),d(this,R,n.port?Number(n.port):n.protocol==="https:"?443:80),d(this,F,(n.protocol||"").replace(":",""));const o=a(this,R)!==443&&a(this,R)!==80;d(this,x,[a(this,M),o?`:${a(this,R)}`:""].join("")),d(this,m,n.pathname.replace(/\/+$/,"")),d(this,k,[`${a(this,F)}://`,a(this,x),a(this,m)].join(""))}pathToInternalUrl(t){return`${this.absoluteUrl}${t}`}internalUrlToPath(t){const r=new URL(t);return r.pathname.startsWith(a(this,m))&&(r.pathname=r.pathname.slice(a(this,m).length)),toRelativeUrl(r)}get isRequestRunning(){return a(this,C).running>0}get absoluteUrl(){return a(this,k)}get documentRoot(){return a(this,E)}async request(t){const r=t.url.startsWith("http://")||t.url.startsWith("https://"),s=new URL(t.url,r?void 0:DEFAULT_BASE_URL),i=removePathPrefix(s.pathname,a(this,m)),n=`${a(this,E)}${i}`;return seemsLikeAPHPRequestHandlerPath(n)?await f(this,B,Q).call(this,t,s):f(this,N,Z).call(this,n)}}E=new WeakMap,F=new WeakMap,M=new WeakMap,R=new WeakMap,x=new WeakMap,m=new WeakMap,k=new WeakMap,C=new WeakMap,N=new WeakSet,Z=function(t){if(!this.php.fileExists(t))return new PHPResponse(404,{"x-file-type":["static"]},new TextEncoder().encode("404 File not found"));const r=this.php.readFileAsBuffer(t);return new PHPResponse(200,{"content-length":[`${r.byteLength}`],"content-type":[inferMimeType(t)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},r)},B=new WeakSet,Q=async function(t,r){var i,n;const s=await a(this,C).acquire();try{this.php.addServerGlobalEntry("REMOTE_ADDR","127.0.0.1"),this.php.addServerGlobalEntry("DOCUMENT_ROOT",a(this,E)),this.php.addServerGlobalEntry("HTTPS",a(this,k).startsWith("https://")?"on":"");let o="GET";const c={host:a(this,x),...normalizeHeaders(t.headers||{})},h=[];if(t.files&&Object.keys(t.files).length){o="POST";for(const _ in t.files){const v=t.files[_];h.push({key:_,name:v.name,type:v.type,data:new Uint8Array(await v.arrayBuffer())})}(i=c["content-type"])!=null&&i.startsWith("multipart/form-data")&&(t.formData=parseMultipartFormDataString(t.body||""),c["content-type"]="application/x-www-form-urlencoded",delete t.body)}let p;t.formData!==void 0?(o="POST",c["content-type"]=c["content-type"]||"application/x-www-form-urlencoded",p=new URLSearchParams(t.formData).toString()):p=t.body;let u;try{let _=r.pathname;if((n=t.headers)!=null&&n["x-rewrite-url"])try{_=new URL(t.headers["x-rewrite-url"]).pathname}catch{}u=f(this,O,X).call(this,_)}catch{return new PHPResponse(404,{},new TextEncoder().encode("404 File not found"))}return await this.php.run({relativeUri:ensurePathPrefix(toRelativeUrl(r),a(this,m)),protocol:a(this,F),method:t.method||o,body:p,fileInfos:h,scriptPath:u,headers:c})}finally{s()}},O=new WeakSet,X=function(t){let r=removePathPrefix(t,a(this,m));r.includes(".php")?r=r.split(".php")[0]+".php":(r.endsWith("/")||(r+="/"),r.endsWith("index.php")||(r+="index.php"));const s=`${a(this,E)}${r}`;if(this.php.fileExists(s))return s;throw new Error(`File not found: ${s}`)};function parseMultipartFormDataString(e){const t={},r=e.match(/--(.*)\r\n/);if(!r)return t;const s=r[1],i=e.split(`--${s}`);return i.shift(),i.pop(),i.forEach(n=>{const o=n.indexOf(`\r
35
+ `).slice(1).map(r=>{const s=r.trim().substring(3).split(" ");return{fn:s.length>=2?s[0]:"<unknown>",isWasm:r.includes("wasm://")}}).filter(({fn:r,isWasm:s})=>s&&!r.startsWith("dynCall_")&&!r.startsWith("invoke_")).map(({fn:r})=>r);return Array.from(new Set(t))}catch{return[]}}class Semaphore{constructor({concurrency:t}){this._running=0,this.concurrency=t,this.queue=[]}get running(){return this._running}async acquire(){for(;;)if(this._running>=this.concurrency)await new Promise(t=>this.queue.push(t));else{this._running++;let t=!1;return()=>{t||(t=!0,this._running--,this.queue.length>0&&this.queue.shift()())}}}async run(t){const r=await this.acquire();try{return await t()}finally{r()}}}function joinPaths(...e){let t=e.join("/");const r=t[0]==="/",s=t.substring(t.length-1)==="/";return t=normalizePath$1(t),!t&&!r&&(t="."),t&&s&&(t+="/"),t}function basename(e){if(e==="/")return"/";e=normalizePath$1(e);const t=e.lastIndexOf("/");return t===-1?e:e.substr(t+1)}function normalizePath$1(e){const t=e[0]==="/";return e=normalizePathsArray(e.split("/").filter(r=>!!r),!t).join("/"),(t?"/":"")+e.replace(/\/$/,"")}function normalizePathsArray(e,t){let r=0;for(let s=e.length-1;s>=0;s--){const i=e[s];i==="."?e.splice(s,1):i===".."?(e.splice(s,1),r++):r&&(e.splice(s,1),r--)}if(t)for(;r;r--)e.unshift("..");return e}function createSpawnHandler(e){return function(t){const r=new ChildProcess,s=new ProcessApi(r);return setTimeout(async()=>{await e(t,s),r.emit("spawn",!0)}),r}}class EventEmitter{constructor(){this.listeners={}}emit(t,r){this.listeners[t]&&this.listeners[t].forEach(function(s){s(r)})}on(t,r){this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(r)}}class ProcessApi extends EventEmitter{constructor(t){super(),this.childProcess=t,this.exited=!1,this.stdinData=[],t.on("stdin",r=>{this.stdinData?this.stdinData.push(r.slice()):this.emit("stdin",r)})}stdout(t){typeof t=="string"&&(t=new TextEncoder().encode(t)),this.childProcess.stdout.emit("data",t)}stderr(t){typeof t=="string"&&(t=new TextEncoder().encode(t)),this.childProcess.stderr.emit("data",t)}exit(t){this.exited||(this.exited=!0,this.childProcess.emit("exit",t))}flushStdin(){if(this.stdinData)for(let t=0;t<this.stdinData.length;t++)this.emit("stdin",this.stdinData[t]);this.stdinData=null}}let lastPid=9743;class ChildProcess extends EventEmitter{constructor(t=lastPid++){super(),this.pid=t,this.stdout=new EventEmitter,this.stderr=new EventEmitter;const r=this;this.stdin={write:s=>{r.emit("stdin",s)}}}}ReadableStream.prototype[Symbol.asyncIterator]||(ReadableStream.prototype[Symbol.asyncIterator]=async function*(){const e=this.getReader();try{for(;;){const{done:t,value:r}=await e.read();if(t)return;yield r}}finally{e.releaseLock()}},ReadableStream.prototype.iterate=ReadableStream.prototype[Symbol.asyncIterator]);class PHPResponse{constructor(t,r,s,i="",n=0){this.httpStatusCode=t,this.headers=r,this.bytes=s,this.exitCode=n,this.errors=i}static fromRawData(t){return new PHPResponse(t.httpStatusCode,t.headers,t.bytes,t.errors,t.exitCode)}toRawData(){return{headers:this.headers,bytes:this.bytes,errors:this.errors,exitCode:this.exitCode,httpStatusCode:this.httpStatusCode}}get json(){return JSON.parse(this.text)}get text(){return new TextDecoder().decode(this.bytes)}}var b,F;class PHPBrowser{constructor(t,r={}){l(this,b,void 0);l(this,F,void 0);this.requestHandler=t,d(this,b,{}),d(this,F,{handleRedirects:!1,maxRedirects:4,...r})}async request(t,r=0){const s=await this.requestHandler.request({...t,headers:{...t.headers,cookie:this.serializeCookies()}});if(s.headers["set-cookie"]&&this.setCookies(s.headers["set-cookie"]),a(this,F).handleRedirects&&s.headers.location&&r<a(this,F).maxRedirects){const i=new URL(s.headers.location[0],this.requestHandler.absoluteUrl);return this.request({url:i.toString(),method:"GET",headers:{}},r+1)}return s}pathToInternalUrl(t){return this.requestHandler.pathToInternalUrl(t)}internalUrlToPath(t){return this.requestHandler.internalUrlToPath(t)}get absoluteUrl(){return this.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.documentRoot}setCookies(t){for(const r of t)try{if(!r.includes("="))continue;const s=r.indexOf("="),i=r.substring(0,s),n=r.substring(s+1).split(";")[0];a(this,b)[i]=n}catch(s){console.error(s)}}serializeCookies(){const t=[];for(const r in a(this,b))t.push(`${r}=${a(this,b)[r]}`);return t.join("; ")}}b=new WeakMap,F=new WeakMap;const DEFAULT_BASE_URL="http://example.com";function toRelativeUrl(e){return e.toString().substring(e.origin.length)}function removePathPrefix(e,t){return!t||!e.startsWith(t)?e:e.substring(t.length)}function ensurePathPrefix(e,t){return!t||e.startsWith(t)?e:t+e}var E,x,N,R,k,m,C,S,B,Q,O,X,L,ee;class PHPRequestHandler{constructor(t,r={}){l(this,B);l(this,O);l(this,L);l(this,E,void 0);l(this,x,void 0);l(this,N,void 0);l(this,R,void 0);l(this,k,void 0);l(this,m,void 0);l(this,C,void 0);l(this,S,void 0);d(this,S,new Semaphore({concurrency:1}));const{documentRoot:s="/www/",absoluteUrl:i=typeof location=="object"?location==null?void 0:location.href:""}=r;this.php=t,d(this,E,s);const n=new URL(i);d(this,N,n.hostname),d(this,R,n.port?Number(n.port):n.protocol==="https:"?443:80),d(this,x,(n.protocol||"").replace(":",""));const o=a(this,R)!==443&&a(this,R)!==80;d(this,k,[a(this,N),o?`:${a(this,R)}`:""].join("")),d(this,m,n.pathname.replace(/\/+$/,"")),d(this,C,[`${a(this,x)}://`,a(this,k),a(this,m)].join(""))}pathToInternalUrl(t){return`${this.absoluteUrl}${t}`}internalUrlToPath(t){const r=new URL(t);return r.pathname.startsWith(a(this,m))&&(r.pathname=r.pathname.slice(a(this,m).length)),toRelativeUrl(r)}get isRequestRunning(){return a(this,S).running>0}get absoluteUrl(){return a(this,C)}get documentRoot(){return a(this,E)}async request(t){const r=t.url.startsWith("http://")||t.url.startsWith("https://"),s=new URL(t.url,r?void 0:DEFAULT_BASE_URL),i=removePathPrefix(s.pathname,a(this,m)),n=`${a(this,E)}${i}`;return seemsLikeAPHPRequestHandlerPath(n)?await p(this,O,X).call(this,t,s):p(this,B,Q).call(this,n)}}E=new WeakMap,x=new WeakMap,N=new WeakMap,R=new WeakMap,k=new WeakMap,m=new WeakMap,C=new WeakMap,S=new WeakMap,B=new WeakSet,Q=function(t){if(!this.php.fileExists(t))return new PHPResponse(404,{"x-file-type":["static"]},new TextEncoder().encode("404 File not found"));const r=this.php.readFileAsBuffer(t);return new PHPResponse(200,{"content-length":[`${r.byteLength}`],"content-type":[inferMimeType(t)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},r)},O=new WeakSet,X=async function(t,r){var i,n,o;if(a(this,S).running>0&&((i=t.headers)==null?void 0:i["x-request-issuer"])==="php")return console.warn("Possible deadlock: Called request() before the previous request() have finished. PHP likely issued an HTTP call to itself. Normally this would lead to infinite waiting as Request 1 holds the lock that the Request 2 is waiting to acquire. That's not useful, so PHPRequestHandler will return error 502 instead."),new PHPResponse(502,{},new TextEncoder().encode("502 Bad Gateway"));const s=await a(this,S).acquire();try{this.php.addServerGlobalEntry("REMOTE_ADDR","127.0.0.1"),this.php.addServerGlobalEntry("DOCUMENT_ROOT",a(this,E)),this.php.addServerGlobalEntry("HTTPS",a(this,C).startsWith("https://")?"on":"");let c="GET";const h={host:a(this,k),...normalizeHeaders(t.headers||{})},f=[];if(t.files&&Object.keys(t.files).length){c="POST";for(const y in t.files){const M=t.files[y];f.push({key:y,name:M.name,type:M.type,data:new Uint8Array(await M.arrayBuffer())})}(n=h["content-type"])!=null&&n.startsWith("multipart/form-data")&&(t.formData=parseMultipartFormDataString(t.body||""),h["content-type"]="application/x-www-form-urlencoded",delete t.body)}let u;t.formData!==void 0?(c="POST",h["content-type"]=h["content-type"]||"application/x-www-form-urlencoded",u=new URLSearchParams(t.formData).toString()):u=t.body;let _;try{let y=r.pathname;if((o=t.headers)!=null&&o["x-rewrite-url"])try{y=new URL(t.headers["x-rewrite-url"]).pathname}catch{}_=p(this,L,ee).call(this,y)}catch{return new PHPResponse(404,{},new TextEncoder().encode("404 File not found"))}return await this.php.run({relativeUri:ensurePathPrefix(toRelativeUrl(r),a(this,m)),protocol:a(this,x),method:t.method||c,body:u,fileInfos:f,scriptPath:_,headers:h})}finally{s()}},L=new WeakSet,ee=function(t){let r=removePathPrefix(t,a(this,m));r.includes(".php")?r=r.split(".php")[0]+".php":(r.endsWith("/")||(r+="/"),r.endsWith("index.php")||(r+="index.php"));const s=`${a(this,E)}${r}`;if(this.php.fileExists(s))return s;throw new Error(`File not found: ${s}`)};function parseMultipartFormDataString(e){const t={},r=e.match(/--(.*)\r\n/);if(!r)return t;const s=r[1],i=e.split(`--${s}`);return i.shift(),i.pop(),i.forEach(n=>{const o=n.indexOf(`\r
36
36
  \r
37
- `),c=n.substring(0,o).trim(),h=n.substring(o+4).trim(),p=c.match(/name="([^"]+)"/);if(p){const u=p[1];t[u]=h}}),t}function inferMimeType(e){switch(e.split(".").pop()){case"css":return"text/css";case"js":return"application/javascript";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"gif":return"image/gif";case"svg":return"image/svg+xml";case"woff":return"font/woff";case"woff2":return"font/woff2";case"ttf":return"font/ttf";case"otf":return"font/otf";case"eot":return"font/eot";case"ico":return"image/x-icon";case"html":return"text/html";case"json":return"application/json";case"xml":return"application/xml";case"txt":case"md":return"text/plain";default:return"application-octet-stream"}}function seemsLikeAPHPRequestHandlerPath(e){return seemsLikeAPHPFile(e)||seemsLikeADirectoryRoot(e)}function seemsLikeAPHPFile(e){return e.endsWith(".php")||e.includes(".php/")}function seemsLikeADirectoryRoot(e){return!e.split("/").pop().includes(".")}const FileErrorCodes={0:"No error occurred. System call completed successfully.",1:"Argument list too long.",2:"Permission denied.",3:"Address in use.",4:"Address not available.",5:"Address family not supported.",6:"Resource unavailable, or operation would block.",7:"Connection already in progress.",8:"Bad file descriptor.",9:"Bad message.",10:"Device or resource busy.",11:"Operation canceled.",12:"No child processes.",13:"Connection aborted.",14:"Connection refused.",15:"Connection reset.",16:"Resource deadlock would occur.",17:"Destination address required.",18:"Mathematics argument out of domain of function.",19:"Reserved.",20:"File exists.",21:"Bad address.",22:"File too large.",23:"Host is unreachable.",24:"Identifier removed.",25:"Illegal byte sequence.",26:"Operation in progress.",27:"Interrupted function.",28:"Invalid argument.",29:"I/O error.",30:"Socket is connected.",31:"There is a directory under that path.",32:"Too many levels of symbolic links.",33:"File descriptor value too large.",34:"Too many links.",35:"Message too large.",36:"Reserved.",37:"Filename too long.",38:"Network is down.",39:"Connection aborted by network.",40:"Network unreachable.",41:"Too many files open in system.",42:"No buffer space available.",43:"No such device.",44:"There is no such file or directory OR the parent directory does not exist.",45:"Executable file format error.",46:"No locks available.",47:"Reserved.",48:"Not enough space.",49:"No message of the desired type.",50:"Protocol not available.",51:"No space left on device.",52:"Function not supported.",53:"The socket is not connected.",54:"Not a directory or a symbolic link to a directory.",55:"Directory not empty.",56:"State not recoverable.",57:"Not a socket.",58:"Not supported, or operation not supported on socket.",59:"Inappropriate I/O control operation.",60:"No such device or address.",61:"Value too large to be stored in data type.",62:"Previous owner died.",63:"Operation not permitted.",64:"Broken pipe.",65:"Protocol error.",66:"Protocol not supported.",67:"Protocol wrong type for socket.",68:"Result too large.",69:"Read-only file system.",70:"Invalid seek.",71:"No such process.",72:"Reserved.",73:"Connection timed out.",74:"Text file busy.",75:"Cross-device link.",76:"Extension: Capabilities insufficient."};function getEmscriptenFsError(e){const t=typeof e=="object"?e==null?void 0:e.errno:null;if(t in FileErrorCodes)return FileErrorCodes[t]}function rethrowFileSystemError(e=""){return function(r,s,i){const n=i.value;i.value=function(...o){try{return n.apply(this,o)}catch(c){const h=typeof c=="object"?c==null?void 0:c.errno:null;if(h in FileErrorCodes){const p=FileErrorCodes[h],u=typeof o[0]=="string"?o[0]:null,_=u!==null?e.replaceAll("{path}",u):e;throw new Error(`${_}: ${p}`,{cause:c})}throw c}}}}const loadedRuntimes=new Map;function getLoadedRuntime(e){return loadedRuntimes.get(e)}(function(){var e;return typeof process<"u"&&((e=process.release)==null?void 0:e.name)==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"})();var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=(e,t,r,s)=>{for(var i=s>1?void 0:s?__getOwnPropDesc(t,r):t,n=e.length-1,o;n>=0;n--)(o=e[n])&&(i=(s?o(t,r,i):o(i))||i);return s&&i&&__defProp(t,r,i),i};const STRING="string",NUMBER="number",__private__dont__use=Symbol("__private__dont__use");var S,H,A,y,w,P,g,I,L,ee,U,te,D,re,$,se,W,ne,j,ie,q,oe,z,ae,G,le,J,ce,Y,ue,V,de;class BasePHP{constructor(e,t){l(this,L);l(this,U);l(this,D);l(this,$);l(this,W);l(this,j);l(this,q);l(this,z);l(this,G);l(this,J);l(this,Y);l(this,V);l(this,S,void 0);l(this,H,void 0);l(this,A,void 0);l(this,y,void 0);l(this,w,void 0);l(this,P,void 0);l(this,g,void 0);l(this,I,void 0);d(this,S,[]),d(this,y,!1),d(this,w,null),d(this,P,{}),d(this,g,new Map),d(this,I,[]),this.semaphore=new Semaphore({concurrency:1}),e!==void 0&&this.initializeRuntime(e),t&&(this.requestHandler=new PHPBrowser(new PHPRequestHandler(this,t)))}addEventListener(e,t){a(this,g).has(e)||a(this,g).set(e,new Set),a(this,g).get(e).add(t)}removeEventListener(e,t){var r;(r=a(this,g).get(e))==null||r.delete(t)}dispatchEvent(e){const t=a(this,g).get(e.type);if(t)for(const r of t)r(e)}async onMessage(e){a(this,I).push(e)}async setSpawnHandler(handler){typeof handler=="string"&&(handler=createSpawnHandler(eval(handler))),this[__private__dont__use].spawnProcess=handler}get absoluteUrl(){return this.requestHandler.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.requestHandler.documentRoot}pathToInternalUrl(e){return this.requestHandler.requestHandler.pathToInternalUrl(e)}internalUrlToPath(e){return this.requestHandler.requestHandler.internalUrlToPath(e)}initializeRuntime(e){if(this[__private__dont__use])throw new Error("PHP runtime already initialized.");const t=getLoadedRuntime(e);if(!t)throw new Error("Invalid PHP runtime id.");this[__private__dont__use]=t,t.onMessage=async r=>{for(const s of a(this,I)){const i=await s(r);if(i)return i}return""},d(this,w,improveWASMErrorReporting(t)),this.dispatchEvent({type:"runtime.initialized"})}async setSapiName(e){if(this[__private__dont__use].ccall("wasm_set_sapi_name",NUMBER,[STRING],[e])!==0)throw new Error("Could not set SAPI name. This can only be done before the PHP WASM module is initialized.Did you already dispatch any requests?");d(this,A,e)}setPhpIniPath(e){if(a(this,y))throw new Error("Cannot set PHP ini path after calling run().");d(this,H,e),this[__private__dont__use].ccall("wasm_set_phpini_path",null,["string"],[e])}setPhpIniEntry(e,t){if(a(this,y))throw new Error("Cannot set PHP ini entries after calling run().");a(this,S).push([e,t])}chdir(e){this[__private__dont__use].FS.chdir(e)}async request(e,t){if(!this.requestHandler)throw new Error("No request handler available.");return this.requestHandler.request(e,t)}async run(e){const t=await this.semaphore.acquire();let r;try{a(this,y)||(f(this,L,ee).call(this),d(this,y,!0)),f(this,z,ae).call(this,e.scriptPath||""),f(this,D,re).call(this,e.relativeUri||""),f(this,W,ne).call(this,e.method||"GET");const s=normalizeHeaders(e.headers||{}),i=s.host||"example.com:443";if(f(this,$,se).call(this,i,e.protocol||"http"),f(this,j,ie).call(this,s),e.body&&(r=f(this,q,oe).call(this,e.body)),e.fileInfos)for(const o of e.fileInfos)f(this,J,ce).call(this,o);typeof e.code=="string"&&f(this,Y,ue).call(this," ?>"+e.code),f(this,G,le).call(this);const n=await f(this,V,de).call(this);if(e.throwOnError&&n.exitCode!==0){const o={stdout:n.text,stderr:n.errors};console.warn("PHP.run() output was:",o);const c=new Error(`PHP.run() failed with exit code ${n.exitCode} and the following output`);throw c.output=o,c}return n}finally{try{r&&this[__private__dont__use].free(r)}finally{t(),this.dispatchEvent({type:"request.end"})}}}addServerGlobalEntry(e,t){a(this,P)[e]=t}defineConstant(e,t){let r={};try{r=JSON.parse(this.fileExists("/tmp/consts.json")&&this.readFileAsText("/tmp/consts.json")||"{}")}catch{}this.writeFile("/tmp/consts.json",JSON.stringify({...r,[e]:t}))}mkdir(e){this[__private__dont__use].FS.mkdirTree(e)}mkdirTree(e){this.mkdir(e)}readFileAsText(e){return new TextDecoder().decode(this.readFileAsBuffer(e))}readFileAsBuffer(e){return this[__private__dont__use].FS.readFile(e)}writeFile(e,t){this[__private__dont__use].FS.writeFile(e,t)}unlink(e){this[__private__dont__use].FS.unlink(e)}mv(e,t){try{this[__private__dont__use].FS.rename(e,t)}catch(r){const s=getEmscriptenFsError(r);throw s?new Error(`Could not move ${e} to ${t}: ${s}`,{cause:r}):r}}rmdir(e,t={recursive:!0}){t!=null&&t.recursive&&this.listFiles(e).forEach(r=>{const s=`${e}/${r}`;this.isDir(s)?this.rmdir(s,t):this.unlink(s)}),this[__private__dont__use].FS.rmdir(e)}listFiles(e,t={prependPath:!1}){if(!this.fileExists(e))return[];try{const r=this[__private__dont__use].FS.readdir(e).filter(s=>s!=="."&&s!=="..");if(t.prependPath){const s=e.replace(/\/$/,"");return r.map(i=>`${s}/${i}`)}return r}catch(r){return console.error(r,{path:e}),[]}}isDir(e){return this.fileExists(e)?this[__private__dont__use].FS.isDir(this[__private__dont__use].FS.lookupPath(e).node.mode):!1}fileExists(e){try{return this[__private__dont__use].FS.lookupPath(e),!0}catch{return!1}}hotSwapPHPRuntime(e){const t=this[__private__dont__use].FS;try{this.exit()}catch{}if(this.initializeRuntime(e),a(this,H)&&this.setPhpIniPath(a(this,H)),a(this,A)&&this.setSapiName(a(this,A)),this.requestHandler){const r=this.documentRoot;recreateMemFS(this[__private__dont__use].FS,t,r)}}exit(e=0){this.dispatchEvent({type:"runtime.beforedestroy"});try{this[__private__dont__use]._exit(e)}catch{}d(this,y,!1),d(this,w,null),delete this[__private__dont__use].onMessage,delete this[__private__dont__use]}}S=new WeakMap,H=new WeakMap,A=new WeakMap,y=new WeakMap,w=new WeakMap,P=new WeakMap,g=new WeakMap,I=new WeakMap,L=new WeakSet,ee=function(){if(this.setPhpIniEntry("auto_prepend_file","/tmp/consts.php"),this.fileExists("/tmp/consts.php")||this.writeFile("/tmp/consts.php",`<?php
37
+ `),c=n.substring(0,o).trim(),h=n.substring(o+4).trim(),f=c.match(/name="([^"]+)"/);if(f){const u=f[1];t[u]=h}}),t}function inferMimeType(e){switch(e.split(".").pop()){case"css":return"text/css";case"js":return"application/javascript";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"gif":return"image/gif";case"svg":return"image/svg+xml";case"woff":return"font/woff";case"woff2":return"font/woff2";case"ttf":return"font/ttf";case"otf":return"font/otf";case"eot":return"font/eot";case"ico":return"image/x-icon";case"html":return"text/html";case"json":return"application/json";case"xml":return"application/xml";case"txt":case"md":return"text/plain";default:return"application-octet-stream"}}function seemsLikeAPHPRequestHandlerPath(e){return seemsLikeAPHPFile(e)||seemsLikeADirectoryRoot(e)}function seemsLikeAPHPFile(e){return e.endsWith(".php")||e.includes(".php/")}function seemsLikeADirectoryRoot(e){return!e.split("/").pop().includes(".")}const FileErrorCodes={0:"No error occurred. System call completed successfully.",1:"Argument list too long.",2:"Permission denied.",3:"Address in use.",4:"Address not available.",5:"Address family not supported.",6:"Resource unavailable, or operation would block.",7:"Connection already in progress.",8:"Bad file descriptor.",9:"Bad message.",10:"Device or resource busy.",11:"Operation canceled.",12:"No child processes.",13:"Connection aborted.",14:"Connection refused.",15:"Connection reset.",16:"Resource deadlock would occur.",17:"Destination address required.",18:"Mathematics argument out of domain of function.",19:"Reserved.",20:"File exists.",21:"Bad address.",22:"File too large.",23:"Host is unreachable.",24:"Identifier removed.",25:"Illegal byte sequence.",26:"Operation in progress.",27:"Interrupted function.",28:"Invalid argument.",29:"I/O error.",30:"Socket is connected.",31:"There is a directory under that path.",32:"Too many levels of symbolic links.",33:"File descriptor value too large.",34:"Too many links.",35:"Message too large.",36:"Reserved.",37:"Filename too long.",38:"Network is down.",39:"Connection aborted by network.",40:"Network unreachable.",41:"Too many files open in system.",42:"No buffer space available.",43:"No such device.",44:"There is no such file or directory OR the parent directory does not exist.",45:"Executable file format error.",46:"No locks available.",47:"Reserved.",48:"Not enough space.",49:"No message of the desired type.",50:"Protocol not available.",51:"No space left on device.",52:"Function not supported.",53:"The socket is not connected.",54:"Not a directory or a symbolic link to a directory.",55:"Directory not empty.",56:"State not recoverable.",57:"Not a socket.",58:"Not supported, or operation not supported on socket.",59:"Inappropriate I/O control operation.",60:"No such device or address.",61:"Value too large to be stored in data type.",62:"Previous owner died.",63:"Operation not permitted.",64:"Broken pipe.",65:"Protocol error.",66:"Protocol not supported.",67:"Protocol wrong type for socket.",68:"Result too large.",69:"Read-only file system.",70:"Invalid seek.",71:"No such process.",72:"Reserved.",73:"Connection timed out.",74:"Text file busy.",75:"Cross-device link.",76:"Extension: Capabilities insufficient."};function getEmscriptenFsError(e){const t=typeof e=="object"?e==null?void 0:e.errno:null;if(t in FileErrorCodes)return FileErrorCodes[t]}function rethrowFileSystemError(e=""){return function(r,s,i){const n=i.value;i.value=function(...o){try{return n.apply(this,o)}catch(c){const h=typeof c=="object"?c==null?void 0:c.errno:null;if(h in FileErrorCodes){const f=FileErrorCodes[h],u=typeof o[0]=="string"?o[0]:null,_=u!==null?e.replaceAll("{path}",u):e;throw new Error(`${_}: ${f}`,{cause:c})}throw c}}}}const loadedRuntimes=new Map;function getLoadedRuntime(e){return loadedRuntimes.get(e)}(function(){var e;return typeof process<"u"&&((e=process.release)==null?void 0:e.name)==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"})();var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=(e,t,r,s)=>{for(var i=s>1?void 0:s?__getOwnPropDesc(t,r):t,n=e.length-1,o;n>=0;n--)(o=e[n])&&(i=(s?o(t,r,i):o(i))||i);return s&&i&&__defProp(t,r,i),i};const STRING="string",NUMBER="number",__private__dont__use=Symbol("__private__dont__use");var T,H,A,w,P,v,g,I,U,te,D,re,$,se,q,ne,W,ie,j,oe,z,ae,G,le,J,ce,Y,ue,V,de,K,he;class BasePHP{constructor(e,t){l(this,U);l(this,D);l(this,$);l(this,q);l(this,W);l(this,j);l(this,z);l(this,G);l(this,J);l(this,Y);l(this,V);l(this,K);l(this,T,void 0);l(this,H,void 0);l(this,A,void 0);l(this,w,void 0);l(this,P,void 0);l(this,v,void 0);l(this,g,void 0);l(this,I,void 0);d(this,T,[]),d(this,w,!1),d(this,P,null),d(this,v,{}),d(this,g,new Map),d(this,I,[]),this.semaphore=new Semaphore({concurrency:1}),e!==void 0&&this.initializeRuntime(e),t&&(this.requestHandler=new PHPBrowser(new PHPRequestHandler(this,t)))}addEventListener(e,t){a(this,g).has(e)||a(this,g).set(e,new Set),a(this,g).get(e).add(t)}removeEventListener(e,t){var r;(r=a(this,g).get(e))==null||r.delete(t)}dispatchEvent(e){const t=a(this,g).get(e.type);if(t)for(const r of t)r(e)}async onMessage(e){a(this,I).push(e)}async setSpawnHandler(handler){typeof handler=="string"&&(handler=createSpawnHandler(eval(handler))),this[__private__dont__use].spawnProcess=handler}get absoluteUrl(){return this.requestHandler.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.requestHandler.documentRoot}pathToInternalUrl(e){return this.requestHandler.requestHandler.pathToInternalUrl(e)}internalUrlToPath(e){return this.requestHandler.requestHandler.internalUrlToPath(e)}initializeRuntime(e){if(this[__private__dont__use])throw new Error("PHP runtime already initialized.");const t=getLoadedRuntime(e);if(!t)throw new Error("Invalid PHP runtime id.");this[__private__dont__use]=t,t.onMessage=async r=>{for(const s of a(this,I)){const i=await s(r);if(i)return i}return""},d(this,P,improveWASMErrorReporting(t)),this.dispatchEvent({type:"runtime.initialized"})}async setSapiName(e){if(this[__private__dont__use].ccall("wasm_set_sapi_name",NUMBER,[STRING],[e])!==0)throw new Error("Could not set SAPI name. This can only be done before the PHP WASM module is initialized.Did you already dispatch any requests?");d(this,A,e)}setPhpIniPath(e){if(a(this,w))throw new Error("Cannot set PHP ini path after calling run().");d(this,H,e),this[__private__dont__use].ccall("wasm_set_phpini_path",null,["string"],[e])}setPhpIniEntry(e,t){if(a(this,w))throw new Error("Cannot set PHP ini entries after calling run().");a(this,T).push([e,t])}chdir(e){this[__private__dont__use].FS.chdir(e)}async request(e,t){if(!this.requestHandler)throw new Error("No request handler available.");return this.requestHandler.request(e,t)}async run(e){const t=await this.semaphore.acquire();let r;try{a(this,w)||(p(this,U,te).call(this),d(this,w,!0)),p(this,G,le).call(this,e.scriptPath||""),p(this,$,se).call(this,e.relativeUri||""),p(this,W,ie).call(this,e.method||"GET");const s=normalizeHeaders(e.headers||{}),i=s.host||"example.com:443";if(p(this,q,ne).call(this,i,e.protocol||"http"),p(this,j,oe).call(this,s),e.body&&(r=p(this,z,ae).call(this,e.body)),e.fileInfos)for(const o of e.fileInfos)p(this,Y,ue).call(this,o);typeof e.code=="string"&&p(this,V,de).call(this," ?>"+e.code),p(this,J,ce).call(this);const n=await p(this,K,he).call(this);if(e.throwOnError&&n.exitCode!==0){const o={stdout:n.text,stderr:n.errors};console.warn("PHP.run() output was:",o);const c=new Error(`PHP.run() failed with exit code ${n.exitCode} and the following output`);throw c.output=o,c}return n}finally{try{r&&this[__private__dont__use].free(r)}finally{t(),this.dispatchEvent({type:"request.end"})}}}addServerGlobalEntry(e,t){a(this,v)[e]=t}defineConstant(e,t){let r={};try{r=JSON.parse(this.fileExists("/tmp/consts.json")&&this.readFileAsText("/tmp/consts.json")||"{}")}catch{}this.writeFile("/tmp/consts.json",JSON.stringify({...r,[e]:t}))}mkdir(e){this[__private__dont__use].FS.mkdirTree(e)}mkdirTree(e){this.mkdir(e)}readFileAsText(e){return new TextDecoder().decode(this.readFileAsBuffer(e))}readFileAsBuffer(e){return this[__private__dont__use].FS.readFile(e)}writeFile(e,t){this[__private__dont__use].FS.writeFile(e,t)}unlink(e){this[__private__dont__use].FS.unlink(e)}mv(e,t){try{this[__private__dont__use].FS.rename(e,t)}catch(r){const s=getEmscriptenFsError(r);throw s?new Error(`Could not move ${e} to ${t}: ${s}`,{cause:r}):r}}rmdir(e,t={recursive:!0}){t!=null&&t.recursive&&this.listFiles(e).forEach(r=>{const s=`${e}/${r}`;this.isDir(s)?this.rmdir(s,t):this.unlink(s)}),this[__private__dont__use].FS.rmdir(e)}listFiles(e,t={prependPath:!1}){if(!this.fileExists(e))return[];try{const r=this[__private__dont__use].FS.readdir(e).filter(s=>s!=="."&&s!=="..");if(t.prependPath){const s=e.replace(/\/$/,"");return r.map(i=>`${s}/${i}`)}return r}catch(r){return console.error(r,{path:e}),[]}}isDir(e){return this.fileExists(e)?this[__private__dont__use].FS.isDir(this[__private__dont__use].FS.lookupPath(e).node.mode):!1}fileExists(e){try{return this[__private__dont__use].FS.lookupPath(e),!0}catch{return!1}}hotSwapPHPRuntime(e){const t=this[__private__dont__use].FS;try{this.exit()}catch{}if(this.initializeRuntime(e),a(this,H)&&this.setPhpIniPath(a(this,H)),a(this,A)&&this.setSapiName(a(this,A)),this.requestHandler){const r=this.documentRoot;recreateMemFS(this[__private__dont__use].FS,t,r)}}exit(e=0){this.dispatchEvent({type:"runtime.beforedestroy"});try{this[__private__dont__use]._exit(e)}catch{}d(this,w,!1),d(this,P,null),delete this[__private__dont__use].onMessage,delete this[__private__dont__use]}}T=new WeakMap,H=new WeakMap,A=new WeakMap,w=new WeakMap,P=new WeakMap,v=new WeakMap,g=new WeakMap,I=new WeakMap,U=new WeakSet,te=function(){if(this.setPhpIniEntry("auto_prepend_file","/tmp/consts.php"),this.fileExists("/tmp/consts.php")||this.writeFile("/tmp/consts.php",`<?php
38
38
  if(file_exists('/tmp/consts.json')) {
39
39
  $consts = json_decode(file_get_contents('/tmp/consts.json'), true);
40
40
  foreach ($consts as $const => $value) {
@@ -42,7 +42,7 @@ ${bold} WASM ERROR${reset}${redBg}`);for(const t of e.split(`
42
42
  define($const, $value);
43
43
  }
44
44
  }
45
- }`),a(this,S).length>0){const e=a(this,S).map(([t,r])=>`${t}=${r}`).join(`
45
+ }`),a(this,T).length>0){const e=a(this,T).map(([t,r])=>`${t}=${r}`).join(`
46
46
  `)+`
47
47
 
48
- `;this[__private__dont__use].ccall("wasm_set_phpini_entries",null,[STRING],[e])}this[__private__dont__use].ccall("php_wasm_init",null,[],[])},U=new WeakSet,te=function(){const e="/tmp/headers.json";if(!this.fileExists(e))throw new Error("SAPI Error: Could not find response headers file.");const t=JSON.parse(this.readFileAsText(e)),r={};for(const s of t.headers){if(!s.includes(": "))continue;const i=s.indexOf(": "),n=s.substring(0,i).toLowerCase(),o=s.substring(i+2);n in r||(r[n]=[]),r[n].push(o)}return{headers:r,httpStatusCode:t.status}},D=new WeakSet,re=function(e){if(this[__private__dont__use].ccall("wasm_set_request_uri",null,[STRING],[e]),e.includes("?")){const t=e.substring(e.indexOf("?")+1);this[__private__dont__use].ccall("wasm_set_query_string",null,[STRING],[t])}},$=new WeakSet,se=function(e,t){this[__private__dont__use].ccall("wasm_set_request_host",null,[STRING],[e]);let r;try{r=parseInt(new URL(e).port,10)}catch{}(!r||isNaN(r)||r===80)&&(r=t==="https"?443:80),this[__private__dont__use].ccall("wasm_set_request_port",null,[NUMBER],[r]),(t==="https"||!t&&r===443)&&this.addServerGlobalEntry("HTTPS","on")},W=new WeakSet,ne=function(e){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[e])},j=new WeakSet,ie=function(e){e.cookie&&this[__private__dont__use].ccall("wasm_set_cookies",null,[STRING],[e.cookie]),e["content-type"]&&this[__private__dont__use].ccall("wasm_set_content_type",null,[STRING],[e["content-type"]]),e["content-length"]&&this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[parseInt(e["content-length"],10)]);for(const t in e){let r="HTTP_";["content-type","content-length"].includes(t.toLowerCase())&&(r=""),this.addServerGlobalEntry(`${r}${t.toUpperCase().replace(/-/g,"_")}`,e[t])}},q=new WeakSet,oe=function(e){const t=this[__private__dont__use].lengthBytesUTF8(e),r=this[__private__dont__use].malloc(t+1);if(!r)throw new Error("Could not allocate memory for the request body.");return this[__private__dont__use].stringToUTF8(e,r,t+1),this[__private__dont__use].ccall("wasm_set_request_body",null,[NUMBER],[r]),this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[new TextEncoder().encode(e).length]),r},z=new WeakSet,ae=function(e){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[e])},G=new WeakSet,le=function(){for(const e in a(this,P))this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[e,a(this,P)[e]])},J=new WeakSet,ce=function(e){const{key:t,name:r,type:s,data:i}=e,n=`/tmp/${Math.random().toFixed(20)}`;this.writeFile(n,i);const o=0;this[__private__dont__use].ccall("wasm_add_uploaded_file",null,[STRING,STRING,STRING,STRING,NUMBER,NUMBER],[t,r,s,n,o,i.byteLength])},Y=new WeakSet,ue=function(e){this[__private__dont__use].ccall("wasm_set_php_code",null,[STRING],[e])},V=new WeakSet,de=async function(){var i;let e,t;try{e=await new Promise((n,o)=>{var h;t=p=>{const u=new Error("Rethrown");u.cause=p.error,u.betterMessage=p.message,o(u)},(h=a(this,w))==null||h.addEventListener("error",t);const c=this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0});return c instanceof Promise?c.then(n,o):n(c)})}catch(n){for(const p in this)typeof this[p]=="function"&&(this[p]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});this.functionsMaybeMissingFromAsyncify=getFunctionsMaybeMissingFromAsyncify();const o=n,c="betterMessage"in o?o.betterMessage:o.message,h=new Error(c);throw h.cause=o,h}finally{(i=a(this,w))==null||i.removeEventListener("error",t),d(this,P,{})}const{headers:r,httpStatusCode:s}=f(this,U,te).call(this);return new PHPResponse(s,r,this.readFileAsBuffer("/tmp/stdout"),this.readFileAsText("/tmp/stderr"),e)};__decorateClass([rethrowFileSystemError('Could not create directory "{path}"')],BasePHP.prototype,"mkdir",1);__decorateClass([rethrowFileSystemError('Could not create directory "{path}"')],BasePHP.prototype,"mkdirTree",1);__decorateClass([rethrowFileSystemError('Could not read "{path}"')],BasePHP.prototype,"readFileAsText",1);__decorateClass([rethrowFileSystemError('Could not read "{path}"')],BasePHP.prototype,"readFileAsBuffer",1);__decorateClass([rethrowFileSystemError('Could not write to "{path}"')],BasePHP.prototype,"writeFile",1);__decorateClass([rethrowFileSystemError('Could not unlink "{path}"')],BasePHP.prototype,"unlink",1);__decorateClass([rethrowFileSystemError('Could not remove directory "{path}"')],BasePHP.prototype,"rmdir",1);__decorateClass([rethrowFileSystemError('Could not list files in "{path}"')],BasePHP.prototype,"listFiles",1);__decorateClass([rethrowFileSystemError('Could not stat "{path}"')],BasePHP.prototype,"isDir",1);__decorateClass([rethrowFileSystemError('Could not stat "{path}"')],BasePHP.prototype,"fileExists",1);function normalizeHeaders(e){const t={};for(const r in e)t[r.toLowerCase()]=e[r];return t}function recreateMemFS(e,t,r){let s;try{s=t.lookupPath(r)}catch{return}if(!("contents"in s.node))return;try{e=e.lookupPath(r);return}catch{}if(!t.isDir(s.node.mode)){e.writeFile(r,t.readFile(r));return}e.mkdirTree(r);const i=t.readdir(r).filter(n=>n!=="."&&n!=="..");for(const n of i)recreateMemFS(e,t,joinPaths(r,n))}function journalFSEvents(e,t,r=()=>{}){function s(){t=normalizePath(t);const n=e[__private__dont__use].FS,o=createFSHooks(n,u=>{if(u.path.startsWith(t))r(u);else if(u.operation==="RENAME"&&u.toPath.startsWith(t))for(const _ of recordExistingPath(e,u.path,u.toPath))r(_)}),c={};for(const[u]of Object.entries(o))c[u]=n[u];function h(){for(const[u,_]of Object.entries(o))n[u]=function(...v){return _(...v),c[u].apply(this,v)}}function p(){for(const[u,_]of Object.entries(c))e[__private__dont__use].FS[u]=_}e[__private__dont__use].journal={bind:h,unbind:p},h()}e.addEventListener("runtime.initialized",s),e[__private__dont__use]&&s();function i(){e[__private__dont__use].journal.unbind(),delete e[__private__dont__use].journal}return e.addEventListener("runtime.beforedestroy",i),function(){return e.removeEventListener("runtime.initialized",s),e.removeEventListener("runtime.beforedestroy",i),e[__private__dont__use].journal.unbind()}}const createFSHooks=(e,t=()=>{})=>({write(r){t({operation:"WRITE",path:r.path,nodeType:"file"})},truncate(r){let s;typeof r=="string"?s=e.lookupPath(r,{follow:!0}).node:s=r,t({operation:"WRITE",path:e.getPath(s),nodeType:"file"})},unlink(r){t({operation:"DELETE",path:r,nodeType:"file"})},mknod(r,s){e.isFile(s)&&t({operation:"CREATE",path:r,nodeType:"file"})},mkdir(r){t({operation:"CREATE",path:r,nodeType:"directory"})},rmdir(r){t({operation:"DELETE",path:r,nodeType:"directory"})},rename(r,s){try{const i=e.lookupPath(r,{follow:!0}),n=e.lookupPath(s,{parent:!0}).path;t({operation:"RENAME",nodeType:e.isDir(i.node.mode)?"directory":"file",path:i.path,toPath:joinPaths(n,basename(s))})}catch{}}});function replayFSJournal(e,t){e[__private__dont__use].journal.unbind();try{for(const r of t)r.operation==="CREATE"?r.nodeType==="file"?e.writeFile(r.path," "):e.mkdir(r.path):r.operation==="DELETE"?r.nodeType==="file"?e.unlink(r.path):e.rmdir(r.path):r.operation==="WRITE"?e.writeFile(r.path,r.data):r.operation==="RENAME"&&e.mv(r.path,r.toPath)}finally{e[__private__dont__use].journal.bind()}}function*recordExistingPath(e,t,r){if(e.isDir(t)){yield{operation:"CREATE",path:r,nodeType:"directory"};for(const s of e.listFiles(t))yield*recordExistingPath(e,joinPaths(t,s),joinPaths(r,s))}else yield{operation:"CREATE",path:r,nodeType:"file"},yield{operation:"WRITE",nodeType:"file",path:r}}function normalizePath(e){return e.replace(/\/$/,"").replace(/\/\/+/g,"/")}function normalizeFilesystemOperations(e){const t={};for(let r=e.length-1;r>=0;r--){for(let s=r-1;s>=0;s--){const i=checkRelationship(e[r],e[s]);if(i==="none")continue;const n=e[r],o=e[s];if(n.operation==="RENAME"&&o.operation==="RENAME"){console.warn("[FS Journal] Normalizing a double rename is not yet supported:",{current:n,last:o});continue}(o.operation==="CREATE"||o.operation==="WRITE")&&(n.operation==="RENAME"?i==="same_node"?(t[s]=[],t[r]=[{...o,path:n.toPath},...t[r]||[]]):i==="descendant"&&(t[s]=[],t[r]=[{...o,path:joinPaths(n.toPath,o.path.substring(n.path.length))},...t[r]||[]]):n.operation==="WRITE"&&i==="same_node"?t[s]=[]:n.operation==="DELETE"&&i==="same_node"&&(t[s]=[],t[r]=[]))}if(Object.entries(t).length>0){const s=e.flatMap((i,n)=>n in t?t[n]:[i]);return normalizeFilesystemOperations(s)}}return e}function checkRelationship(e,t){const r=e.path,s=e.operation!=="WRITE"&&e.nodeType==="directory",i=t.operation!=="WRITE"&&t.nodeType==="directory",n=t.operation==="RENAME"?t.toPath:t.path;return n===r?"same_node":i&&r.startsWith(n+"/")?"ancestor":s&&n.startsWith(r+"/")?"descendant":"none"}async function hydrateUpdateFileOps(e,t){const s=t.filter(i=>i.operation==="WRITE").map(i=>hydrateOp(e,i));return await Promise.all(s),t}const hydrateLock=new Semaphore({concurrency:15});async function hydrateOp(e,t){const r=await hydrateLock.acquire();try{t.data=await e.readFileAsBuffer(t.path)}catch(s){console.warn(`Journal failed to hydrate a file on flush: the path ${t.path} no longer exists`),console.error(s)}r()}exports.hydrateUpdateFileOps=hydrateUpdateFileOps;exports.journalFSEvents=journalFSEvents;exports.normalizeFilesystemOperations=normalizeFilesystemOperations;exports.replayFSJournal=replayFSJournal;
48
+ `;this[__private__dont__use].ccall("wasm_set_phpini_entries",null,[STRING],[e])}this[__private__dont__use].ccall("php_wasm_init",null,[],[])},D=new WeakSet,re=function(){const e="/tmp/headers.json";if(!this.fileExists(e))throw new Error("SAPI Error: Could not find response headers file.");const t=JSON.parse(this.readFileAsText(e)),r={};for(const s of t.headers){if(!s.includes(": "))continue;const i=s.indexOf(": "),n=s.substring(0,i).toLowerCase(),o=s.substring(i+2);n in r||(r[n]=[]),r[n].push(o)}return{headers:r,httpStatusCode:t.status}},$=new WeakSet,se=function(e){if(this[__private__dont__use].ccall("wasm_set_request_uri",null,[STRING],[e]),e.includes("?")){const t=e.substring(e.indexOf("?")+1);this[__private__dont__use].ccall("wasm_set_query_string",null,[STRING],[t])}},q=new WeakSet,ne=function(e,t){this[__private__dont__use].ccall("wasm_set_request_host",null,[STRING],[e]);let r;try{r=parseInt(new URL(e).port,10)}catch{}(!r||isNaN(r)||r===80)&&(r=t==="https"?443:80),this[__private__dont__use].ccall("wasm_set_request_port",null,[NUMBER],[r]),(t==="https"||!t&&r===443)&&this.addServerGlobalEntry("HTTPS","on")},W=new WeakSet,ie=function(e){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[e])},j=new WeakSet,oe=function(e){e.cookie&&this[__private__dont__use].ccall("wasm_set_cookies",null,[STRING],[e.cookie]),e["content-type"]&&this[__private__dont__use].ccall("wasm_set_content_type",null,[STRING],[e["content-type"]]),e["content-length"]&&this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[parseInt(e["content-length"],10)]);for(const t in e){let r="HTTP_";["content-type","content-length"].includes(t.toLowerCase())&&(r=""),this.addServerGlobalEntry(`${r}${t.toUpperCase().replace(/-/g,"_")}`,e[t])}},z=new WeakSet,ae=function(e){const t=this[__private__dont__use].lengthBytesUTF8(e),r=this[__private__dont__use].malloc(t+1);if(!r)throw new Error("Could not allocate memory for the request body.");return this[__private__dont__use].stringToUTF8(e,r,t+1),this[__private__dont__use].ccall("wasm_set_request_body",null,[NUMBER],[r]),this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[new TextEncoder().encode(e).length]),r},G=new WeakSet,le=function(e){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[e])},J=new WeakSet,ce=function(){for(const e in a(this,v))this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[e,a(this,v)[e]])},Y=new WeakSet,ue=function(e){const{key:t,name:r,type:s,data:i}=e,n=`/tmp/${Math.random().toFixed(20)}`;this.writeFile(n,i);const o=0;this[__private__dont__use].ccall("wasm_add_uploaded_file",null,[STRING,STRING,STRING,STRING,NUMBER,NUMBER],[t,r,s,n,o,i.byteLength])},V=new WeakSet,de=function(e){this[__private__dont__use].ccall("wasm_set_php_code",null,[STRING],[e])},K=new WeakSet,he=async function(){var i;let e,t;try{e=await new Promise((n,o)=>{var h;t=f=>{const u=new Error("Rethrown");u.cause=f.error,u.betterMessage=f.message,o(u)},(h=a(this,P))==null||h.addEventListener("error",t);const c=this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0});return c instanceof Promise?c.then(n,o):n(c)})}catch(n){for(const f in this)typeof this[f]=="function"&&(this[f]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});this.functionsMaybeMissingFromAsyncify=getFunctionsMaybeMissingFromAsyncify();const o=n,c="betterMessage"in o?o.betterMessage:o.message,h=new Error(c);throw h.cause=o,h}finally{(i=a(this,P))==null||i.removeEventListener("error",t),d(this,v,{})}const{headers:r,httpStatusCode:s}=p(this,D,re).call(this);return new PHPResponse(s,r,this.readFileAsBuffer("/tmp/stdout"),this.readFileAsText("/tmp/stderr"),e)};__decorateClass([rethrowFileSystemError('Could not create directory "{path}"')],BasePHP.prototype,"mkdir",1);__decorateClass([rethrowFileSystemError('Could not create directory "{path}"')],BasePHP.prototype,"mkdirTree",1);__decorateClass([rethrowFileSystemError('Could not read "{path}"')],BasePHP.prototype,"readFileAsText",1);__decorateClass([rethrowFileSystemError('Could not read "{path}"')],BasePHP.prototype,"readFileAsBuffer",1);__decorateClass([rethrowFileSystemError('Could not write to "{path}"')],BasePHP.prototype,"writeFile",1);__decorateClass([rethrowFileSystemError('Could not unlink "{path}"')],BasePHP.prototype,"unlink",1);__decorateClass([rethrowFileSystemError('Could not remove directory "{path}"')],BasePHP.prototype,"rmdir",1);__decorateClass([rethrowFileSystemError('Could not list files in "{path}"')],BasePHP.prototype,"listFiles",1);__decorateClass([rethrowFileSystemError('Could not stat "{path}"')],BasePHP.prototype,"isDir",1);__decorateClass([rethrowFileSystemError('Could not stat "{path}"')],BasePHP.prototype,"fileExists",1);function normalizeHeaders(e){const t={};for(const r in e)t[r.toLowerCase()]=e[r];return t}function recreateMemFS(e,t,r){let s;try{s=t.lookupPath(r)}catch{return}if(!("contents"in s.node))return;try{e=e.lookupPath(r);return}catch{}if(!t.isDir(s.node.mode)){e.writeFile(r,t.readFile(r));return}e.mkdirTree(r);const i=t.readdir(r).filter(n=>n!=="."&&n!=="..");for(const n of i)recreateMemFS(e,t,joinPaths(r,n))}function journalFSEvents(e,t,r=()=>{}){function s(){t=normalizePath(t);const n=e[__private__dont__use].FS,o=createFSHooks(n,u=>{if(u.path.startsWith(t))r(u);else if(u.operation==="RENAME"&&u.toPath.startsWith(t))for(const _ of recordExistingPath(e,u.path,u.toPath))r(_)}),c={};for(const[u]of Object.entries(o))c[u]=n[u];function h(){for(const[u,_]of Object.entries(o))n[u]=function(...y){return _(...y),c[u].apply(this,y)}}function f(){for(const[u,_]of Object.entries(c))e[__private__dont__use].FS[u]=_}e[__private__dont__use].journal={bind:h,unbind:f},h()}e.addEventListener("runtime.initialized",s),e[__private__dont__use]&&s();function i(){e[__private__dont__use].journal.unbind(),delete e[__private__dont__use].journal}return e.addEventListener("runtime.beforedestroy",i),function(){return e.removeEventListener("runtime.initialized",s),e.removeEventListener("runtime.beforedestroy",i),e[__private__dont__use].journal.unbind()}}const createFSHooks=(e,t=()=>{})=>({write(r){t({operation:"WRITE",path:r.path,nodeType:"file"})},truncate(r){let s;typeof r=="string"?s=e.lookupPath(r,{follow:!0}).node:s=r,t({operation:"WRITE",path:e.getPath(s),nodeType:"file"})},unlink(r){t({operation:"DELETE",path:r,nodeType:"file"})},mknod(r,s){e.isFile(s)&&t({operation:"CREATE",path:r,nodeType:"file"})},mkdir(r){t({operation:"CREATE",path:r,nodeType:"directory"})},rmdir(r){t({operation:"DELETE",path:r,nodeType:"directory"})},rename(r,s){try{const i=e.lookupPath(r,{follow:!0}),n=e.lookupPath(s,{parent:!0}).path;t({operation:"RENAME",nodeType:e.isDir(i.node.mode)?"directory":"file",path:i.path,toPath:joinPaths(n,basename(s))})}catch{}}});function replayFSJournal(e,t){e[__private__dont__use].journal.unbind();try{for(const r of t)r.operation==="CREATE"?r.nodeType==="file"?e.writeFile(r.path," "):e.mkdir(r.path):r.operation==="DELETE"?r.nodeType==="file"?e.unlink(r.path):e.rmdir(r.path):r.operation==="WRITE"?e.writeFile(r.path,r.data):r.operation==="RENAME"&&e.mv(r.path,r.toPath)}finally{e[__private__dont__use].journal.bind()}}function*recordExistingPath(e,t,r){if(e.isDir(t)){yield{operation:"CREATE",path:r,nodeType:"directory"};for(const s of e.listFiles(t))yield*recordExistingPath(e,joinPaths(t,s),joinPaths(r,s))}else yield{operation:"CREATE",path:r,nodeType:"file"},yield{operation:"WRITE",nodeType:"file",path:r}}function normalizePath(e){return e.replace(/\/$/,"").replace(/\/\/+/g,"/")}function normalizeFilesystemOperations(e){const t={};for(let r=e.length-1;r>=0;r--){for(let s=r-1;s>=0;s--){const i=checkRelationship(e[r],e[s]);if(i==="none")continue;const n=e[r],o=e[s];if(n.operation==="RENAME"&&o.operation==="RENAME"){console.warn("[FS Journal] Normalizing a double rename is not yet supported:",{current:n,last:o});continue}(o.operation==="CREATE"||o.operation==="WRITE")&&(n.operation==="RENAME"?i==="same_node"?(t[s]=[],t[r]=[{...o,path:n.toPath},...t[r]||[]]):i==="descendant"&&(t[s]=[],t[r]=[{...o,path:joinPaths(n.toPath,o.path.substring(n.path.length))},...t[r]||[]]):n.operation==="WRITE"&&i==="same_node"?t[s]=[]:n.operation==="DELETE"&&i==="same_node"&&(t[s]=[],t[r]=[]))}if(Object.entries(t).length>0){const s=e.flatMap((i,n)=>n in t?t[n]:[i]);return normalizeFilesystemOperations(s)}}return e}function checkRelationship(e,t){const r=e.path,s=e.operation!=="WRITE"&&e.nodeType==="directory",i=t.operation!=="WRITE"&&t.nodeType==="directory",n=t.operation==="RENAME"?t.toPath:t.path;return n===r?"same_node":i&&r.startsWith(n+"/")?"ancestor":s&&n.startsWith(r+"/")?"descendant":"none"}async function hydrateUpdateFileOps(e,t){const s=t.filter(i=>i.operation==="WRITE").map(i=>hydrateOp(e,i));return await Promise.all(s),t}const hydrateLock=new Semaphore({concurrency:15});async function hydrateOp(e,t){const r=await hydrateLock.acquire();try{t.data=await e.readFileAsBuffer(t.path)}catch(s){console.warn(`Journal failed to hydrate a file on flush: the path ${t.path} no longer exists`),console.error(s)}r()}exports.hydrateUpdateFileOps=hydrateUpdateFileOps;exports.journalFSEvents=journalFSEvents;exports.normalizeFilesystemOperations=normalizeFilesystemOperations;exports.replayFSJournal=replayFSJournal;
package/index.js CHANGED
@@ -1,13 +1,13 @@
1
- var K = (e, t, r) => {
1
+ var Z = (e, t, r) => {
2
2
  if (!t.has(e))
3
3
  throw TypeError("Cannot " + r);
4
4
  };
5
- var a = (e, t, r) => (K(e, t, "read from private field"), r ? r.call(e) : t.get(e)), l = (e, t, r) => {
5
+ var a = (e, t, r) => (Z(e, t, "read from private field"), r ? r.call(e) : t.get(e)), l = (e, t, r) => {
6
6
  if (t.has(e))
7
7
  throw TypeError("Cannot add the same private member more than once");
8
8
  t instanceof WeakSet ? t.add(e) : t.set(e, r);
9
- }, d = (e, t, r, s) => (K(e, t, "write to private field"), s ? s.call(e, r) : t.set(e, r), r);
10
- var f = (e, t, r) => (K(e, t, "access private method"), r);
9
+ }, d = (e, t, r, s) => (Z(e, t, "write to private field"), s ? s.call(e, r) : t.set(e, r), r);
10
+ var p = (e, t, r) => (Z(e, t, "access private method"), r);
11
11
  if (typeof File > "u") {
12
12
  class e extends Blob {
13
13
  constructor(r, s, i) {
@@ -378,7 +378,7 @@ class PHPResponse {
378
378
  return new TextDecoder().decode(this.bytes);
379
379
  }
380
380
  }
381
- var b, T;
381
+ var b, F;
382
382
  class PHPBrowser {
383
383
  /**
384
384
  * @param server - The PHP server to browse.
@@ -386,8 +386,8 @@ class PHPBrowser {
386
386
  */
387
387
  constructor(t, r = {}) {
388
388
  l(this, b, void 0);
389
- l(this, T, void 0);
390
- this.requestHandler = t, d(this, b, {}), d(this, T, {
389
+ l(this, F, void 0);
390
+ this.requestHandler = t, d(this, b, {}), d(this, F, {
391
391
  handleRedirects: !1,
392
392
  maxRedirects: 4,
393
393
  ...r
@@ -415,7 +415,7 @@ class PHPBrowser {
415
415
  cookie: this.serializeCookies()
416
416
  }
417
417
  });
418
- if (s.headers["set-cookie"] && this.setCookies(s.headers["set-cookie"]), a(this, T).handleRedirects && s.headers.location && r < a(this, T).maxRedirects) {
418
+ if (s.headers["set-cookie"] && this.setCookies(s.headers["set-cookie"]), a(this, F).handleRedirects && s.headers.location && r < a(this, F).maxRedirects) {
419
419
  const i = new URL(
420
420
  s.headers.location[0],
421
421
  this.requestHandler.absoluteUrl
@@ -465,7 +465,7 @@ class PHPBrowser {
465
465
  return t.join("; ");
466
466
  }
467
467
  }
468
- b = new WeakMap(), T = new WeakMap();
468
+ b = new WeakMap(), F = new WeakMap();
469
469
  const DEFAULT_BASE_URL = "http://example.com";
470
470
  function toRelativeUrl(e) {
471
471
  return e.toString().substring(e.origin.length);
@@ -476,7 +476,7 @@ function removePathPrefix(e, t) {
476
476
  function ensurePathPrefix(e, t) {
477
477
  return !t || e.startsWith(t) ? e : t + e;
478
478
  }
479
- var E, F, N, R, x, m, k, C, M, Z, B, Q, L, X;
479
+ var E, x, N, R, k, m, C, S, B, Q, L, X, O, ee;
480
480
  class PHPRequestHandler {
481
481
  /**
482
482
  * @param php - The PHP instance.
@@ -489,7 +489,7 @@ class PHPRequestHandler {
489
489
  * @param fsPath - Absolute path of the static file to serve.
490
490
  * @returns The response.
491
491
  */
492
- l(this, M);
492
+ l(this, B);
493
493
  /**
494
494
  * Runs the requested PHP file with all the request and $_SERVER
495
495
  * superglobals populated.
@@ -497,7 +497,7 @@ class PHPRequestHandler {
497
497
  * @param request - The request.
498
498
  * @returns The response.
499
499
  */
500
- l(this, B);
500
+ l(this, L);
501
501
  /**
502
502
  * Resolve the requested path to the filesystem path of the requested PHP file.
503
503
  *
@@ -507,30 +507,30 @@ class PHPRequestHandler {
507
507
  * @throws {Error} If the requested path doesn't exist.
508
508
  * @returns The resolved filesystem path.
509
509
  */
510
- l(this, L);
510
+ l(this, O);
511
511
  l(this, E, void 0);
512
- l(this, F, void 0);
512
+ l(this, x, void 0);
513
513
  l(this, N, void 0);
514
514
  l(this, R, void 0);
515
- l(this, x, void 0);
516
- l(this, m, void 0);
517
515
  l(this, k, void 0);
516
+ l(this, m, void 0);
518
517
  l(this, C, void 0);
519
- d(this, C, new Semaphore({ concurrency: 1 }));
518
+ l(this, S, void 0);
519
+ d(this, S, new Semaphore({ concurrency: 1 }));
520
520
  const {
521
521
  documentRoot: s = "/www/",
522
522
  absoluteUrl: i = typeof location == "object" ? location == null ? void 0 : location.href : ""
523
523
  } = r;
524
524
  this.php = t, d(this, E, s);
525
525
  const n = new URL(i);
526
- d(this, N, n.hostname), d(this, R, n.port ? Number(n.port) : n.protocol === "https:" ? 443 : 80), d(this, F, (n.protocol || "").replace(":", ""));
526
+ d(this, N, n.hostname), d(this, R, n.port ? Number(n.port) : n.protocol === "https:" ? 443 : 80), d(this, x, (n.protocol || "").replace(":", ""));
527
527
  const o = a(this, R) !== 443 && a(this, R) !== 80;
528
- d(this, x, [
528
+ d(this, k, [
529
529
  a(this, N),
530
530
  o ? `:${a(this, R)}` : ""
531
- ].join("")), d(this, m, n.pathname.replace(/\/+$/, "")), d(this, k, [
532
- `${a(this, F)}://`,
533
- a(this, x),
531
+ ].join("")), d(this, m, n.pathname.replace(/\/+$/, "")), d(this, C, [
532
+ `${a(this, x)}://`,
533
+ a(this, k),
534
534
  a(this, m)
535
535
  ].join(""));
536
536
  }
@@ -544,11 +544,11 @@ class PHPRequestHandler {
544
544
  return r.pathname.startsWith(a(this, m)) && (r.pathname = r.pathname.slice(a(this, m).length)), toRelativeUrl(r);
545
545
  }
546
546
  get isRequestRunning() {
547
- return a(this, C).running > 0;
547
+ return a(this, S).running > 0;
548
548
  }
549
549
  /** @inheritDoc */
550
550
  get absoluteUrl() {
551
- return a(this, k);
551
+ return a(this, C);
552
552
  }
553
553
  /** @inheritDoc */
554
554
  get documentRoot() {
@@ -563,10 +563,10 @@ class PHPRequestHandler {
563
563
  s.pathname,
564
564
  a(this, m)
565
565
  ), n = `${a(this, E)}${i}`;
566
- return seemsLikeAPHPRequestHandlerPath(n) ? await f(this, B, Q).call(this, t, s) : f(this, M, Z).call(this, n);
566
+ return seemsLikeAPHPRequestHandlerPath(n) ? await p(this, L, X).call(this, t, s) : p(this, B, Q).call(this, n);
567
567
  }
568
568
  }
569
- E = new WeakMap(), F = new WeakMap(), N = new WeakMap(), R = new WeakMap(), x = new WeakMap(), m = new WeakMap(), k = new WeakMap(), C = new WeakMap(), M = new WeakSet(), Z = function(t) {
569
+ E = new WeakMap(), x = new WeakMap(), N = new WeakMap(), R = new WeakMap(), k = new WeakMap(), m = new WeakMap(), C = new WeakMap(), S = new WeakMap(), B = new WeakSet(), Q = function(t) {
570
570
  if (!this.php.fileExists(t))
571
571
  return new PHPResponse(
572
572
  404,
@@ -591,49 +591,57 @@ E = new WeakMap(), F = new WeakMap(), N = new WeakMap(), R = new WeakMap(), x =
591
591
  },
592
592
  r
593
593
  );
594
- }, B = new WeakSet(), Q = async function(t, r) {
595
- var i, n;
596
- const s = await a(this, C).acquire();
594
+ }, L = new WeakSet(), X = async function(t, r) {
595
+ var i, n, o;
596
+ if (a(this, S).running > 0 && ((i = t.headers) == null ? void 0 : i["x-request-issuer"]) === "php")
597
+ return console.warn(
598
+ "Possible deadlock: Called request() before the previous request() have finished. PHP likely issued an HTTP call to itself. Normally this would lead to infinite waiting as Request 1 holds the lock that the Request 2 is waiting to acquire. That's not useful, so PHPRequestHandler will return error 502 instead."
599
+ ), new PHPResponse(
600
+ 502,
601
+ {},
602
+ new TextEncoder().encode("502 Bad Gateway")
603
+ );
604
+ const s = await a(this, S).acquire();
597
605
  try {
598
606
  this.php.addServerGlobalEntry("REMOTE_ADDR", "127.0.0.1"), this.php.addServerGlobalEntry("DOCUMENT_ROOT", a(this, E)), this.php.addServerGlobalEntry(
599
607
  "HTTPS",
600
- a(this, k).startsWith("https://") ? "on" : ""
608
+ a(this, C).startsWith("https://") ? "on" : ""
601
609
  );
602
- let o = "GET";
603
- const c = {
604
- host: a(this, x),
610
+ let c = "GET";
611
+ const h = {
612
+ host: a(this, k),
605
613
  ...normalizeHeaders(t.headers || {})
606
- }, h = [];
614
+ }, f = [];
607
615
  if (t.files && Object.keys(t.files).length) {
608
- o = "POST";
609
- for (const _ in t.files) {
610
- const v = t.files[_];
611
- h.push({
612
- key: _,
613
- name: v.name,
614
- type: v.type,
615
- data: new Uint8Array(await v.arrayBuffer())
616
+ c = "POST";
617
+ for (const y in t.files) {
618
+ const M = t.files[y];
619
+ f.push({
620
+ key: y,
621
+ name: M.name,
622
+ type: M.type,
623
+ data: new Uint8Array(await M.arrayBuffer())
616
624
  });
617
625
  }
618
- (i = c["content-type"]) != null && i.startsWith("multipart/form-data") && (t.formData = parseMultipartFormDataString(
626
+ (n = h["content-type"]) != null && n.startsWith("multipart/form-data") && (t.formData = parseMultipartFormDataString(
619
627
  t.body || ""
620
- ), c["content-type"] = "application/x-www-form-urlencoded", delete t.body);
628
+ ), h["content-type"] = "application/x-www-form-urlencoded", delete t.body);
621
629
  }
622
- let p;
623
- t.formData !== void 0 ? (o = "POST", c["content-type"] = c["content-type"] || "application/x-www-form-urlencoded", p = new URLSearchParams(
624
- t.formData
625
- ).toString()) : p = t.body;
626
630
  let u;
631
+ t.formData !== void 0 ? (c = "POST", h["content-type"] = h["content-type"] || "application/x-www-form-urlencoded", u = new URLSearchParams(
632
+ t.formData
633
+ ).toString()) : u = t.body;
634
+ let _;
627
635
  try {
628
- let _ = r.pathname;
629
- if ((n = t.headers) != null && n["x-rewrite-url"])
636
+ let y = r.pathname;
637
+ if ((o = t.headers) != null && o["x-rewrite-url"])
630
638
  try {
631
- _ = new URL(
639
+ y = new URL(
632
640
  t.headers["x-rewrite-url"]
633
641
  ).pathname;
634
642
  } catch {
635
643
  }
636
- u = f(this, L, X).call(this, _);
644
+ _ = p(this, O, ee).call(this, y);
637
645
  } catch {
638
646
  return new PHPResponse(
639
647
  404,
@@ -646,17 +654,17 @@ E = new WeakMap(), F = new WeakMap(), N = new WeakMap(), R = new WeakMap(), x =
646
654
  toRelativeUrl(r),
647
655
  a(this, m)
648
656
  ),
649
- protocol: a(this, F),
650
- method: t.method || o,
651
- body: p,
652
- fileInfos: h,
653
- scriptPath: u,
654
- headers: c
657
+ protocol: a(this, x),
658
+ method: t.method || c,
659
+ body: u,
660
+ fileInfos: f,
661
+ scriptPath: _,
662
+ headers: h
655
663
  });
656
664
  } finally {
657
665
  s();
658
666
  }
659
- }, L = new WeakSet(), X = function(t) {
667
+ }, O = new WeakSet(), ee = function(t) {
660
668
  let r = removePathPrefix(t, a(this, m));
661
669
  r.includes(".php") ? r = r.split(".php")[0] + ".php" : (r.endsWith("/") || (r += "/"), r.endsWith("index.php") || (r += "index.php"));
662
670
  const s = `${a(this, E)}${r}`;
@@ -672,9 +680,9 @@ function parseMultipartFormDataString(e) {
672
680
  return i.shift(), i.pop(), i.forEach((n) => {
673
681
  const o = n.indexOf(`\r
674
682
  \r
675
- `), c = n.substring(0, o).trim(), h = n.substring(o + 4).trim(), p = c.match(/name="([^"]+)"/);
676
- if (p) {
677
- const u = p[1];
683
+ `), c = n.substring(0, o).trim(), h = n.substring(o + 4).trim(), f = c.match(/name="([^"]+)"/);
684
+ if (f) {
685
+ const u = f[1];
678
686
  t[u] = h;
679
687
  }
680
688
  }), t;
@@ -821,8 +829,8 @@ function rethrowFileSystemError(e = "") {
821
829
  } catch (c) {
822
830
  const h = typeof c == "object" ? c == null ? void 0 : c.errno : null;
823
831
  if (h in FileErrorCodes) {
824
- const p = FileErrorCodes[h], u = typeof o[0] == "string" ? o[0] : null, _ = u !== null ? e.replaceAll("{path}", u) : e;
825
- throw new Error(`${_}: ${p}`, {
832
+ const f = FileErrorCodes[h], u = typeof o[0] == "string" ? o[0] : null, _ = u !== null ? e.replaceAll("{path}", u) : e;
833
+ throw new Error(`${_}: ${f}`, {
826
834
  cause: c
827
835
  });
828
836
  }
@@ -845,7 +853,7 @@ var __defProp = Object.defineProperty, __getOwnPropDesc = Object.getOwnPropertyD
845
853
  return s && i && __defProp(t, r, i), i;
846
854
  };
847
855
  const STRING = "string", NUMBER = "number", __private__dont__use = Symbol("__private__dont__use");
848
- var S, H, A, y, g, P, w, I, O, ee, U, te, D, re, $, se, W, ne, q, ie, j, oe, z, ae, G, le, J, ce, Y, ue, V, de;
856
+ var T, H, A, w, P, v, g, I, U, te, D, re, $, se, q, ne, W, ie, j, oe, z, ae, G, le, J, ce, Y, ue, V, de, K, he;
849
857
  class BasePHP {
850
858
  /**
851
859
  * Initializes a PHP runtime.
@@ -855,15 +863,15 @@ class BasePHP {
855
863
  * @param serverOptions - Optional. Options for the PHPRequestHandler. If undefined, no request handler will be initialized.
856
864
  */
857
865
  constructor(e, t) {
858
- l(this, O);
859
866
  l(this, U);
860
867
  l(this, D);
861
868
  l(this, $);
862
- l(this, W);
863
869
  l(this, q);
870
+ l(this, W);
864
871
  l(this, j);
865
872
  l(this, z);
866
873
  l(this, G);
874
+ l(this, J);
867
875
  /**
868
876
  * Adds file information to $_FILES superglobal in PHP.
869
877
  *
@@ -873,30 +881,30 @@ class BasePHP {
873
881
  *
874
882
  * @param fileInfo - File details
875
883
  */
876
- l(this, J);
877
884
  l(this, Y);
878
885
  l(this, V);
879
- l(this, S, void 0);
886
+ l(this, K);
887
+ l(this, T, void 0);
880
888
  l(this, H, void 0);
881
889
  l(this, A, void 0);
882
- l(this, y, void 0);
883
- l(this, g, void 0);
884
- l(this, P, void 0);
885
890
  l(this, w, void 0);
891
+ l(this, P, void 0);
892
+ l(this, v, void 0);
893
+ l(this, g, void 0);
886
894
  l(this, I, void 0);
887
- d(this, S, []), d(this, y, !1), d(this, g, null), d(this, P, {}), d(this, w, /* @__PURE__ */ new Map()), d(this, I, []), this.semaphore = new Semaphore({ concurrency: 1 }), e !== void 0 && this.initializeRuntime(e), t && (this.requestHandler = new PHPBrowser(
895
+ d(this, T, []), d(this, w, !1), d(this, P, null), d(this, v, {}), d(this, g, /* @__PURE__ */ new Map()), d(this, I, []), this.semaphore = new Semaphore({ concurrency: 1 }), e !== void 0 && this.initializeRuntime(e), t && (this.requestHandler = new PHPBrowser(
888
896
  new PHPRequestHandler(this, t)
889
897
  ));
890
898
  }
891
899
  addEventListener(e, t) {
892
- a(this, w).has(e) || a(this, w).set(e, /* @__PURE__ */ new Set()), a(this, w).get(e).add(t);
900
+ a(this, g).has(e) || a(this, g).set(e, /* @__PURE__ */ new Set()), a(this, g).get(e).add(t);
893
901
  }
894
902
  removeEventListener(e, t) {
895
903
  var r;
896
- (r = a(this, w).get(e)) == null || r.delete(t);
904
+ (r = a(this, g).get(e)) == null || r.delete(t);
897
905
  }
898
906
  dispatchEvent(e) {
899
- const t = a(this, w).get(e.type);
907
+ const t = a(this, g).get(e.type);
900
908
  if (t)
901
909
  for (const r of t)
902
910
  r(e);
@@ -940,7 +948,7 @@ class BasePHP {
940
948
  return i;
941
949
  }
942
950
  return "";
943
- }, d(this, g, improveWASMErrorReporting(t)), this.dispatchEvent({
951
+ }, d(this, P, improveWASMErrorReporting(t)), this.dispatchEvent({
944
952
  type: "runtime.initialized"
945
953
  });
946
954
  }
@@ -959,7 +967,7 @@ class BasePHP {
959
967
  }
960
968
  /** @inheritDoc */
961
969
  setPhpIniPath(e) {
962
- if (a(this, y))
970
+ if (a(this, w))
963
971
  throw new Error("Cannot set PHP ini path after calling run().");
964
972
  d(this, H, e), this[__private__dont__use].ccall(
965
973
  "wasm_set_phpini_path",
@@ -970,9 +978,9 @@ class BasePHP {
970
978
  }
971
979
  /** @inheritDoc */
972
980
  setPhpIniEntry(e, t) {
973
- if (a(this, y))
981
+ if (a(this, w))
974
982
  throw new Error("Cannot set PHP ini entries after calling run().");
975
- a(this, S).push([e, t]);
983
+ a(this, T).push([e, t]);
976
984
  }
977
985
  /** @inheritDoc */
978
986
  chdir(e) {
@@ -989,13 +997,13 @@ class BasePHP {
989
997
  const t = await this.semaphore.acquire();
990
998
  let r;
991
999
  try {
992
- a(this, y) || (f(this, O, ee).call(this), d(this, y, !0)), f(this, z, ae).call(this, e.scriptPath || ""), f(this, D, re).call(this, e.relativeUri || ""), f(this, W, ne).call(this, e.method || "GET");
1000
+ a(this, w) || (p(this, U, te).call(this), d(this, w, !0)), p(this, G, le).call(this, e.scriptPath || ""), p(this, $, se).call(this, e.relativeUri || ""), p(this, W, ie).call(this, e.method || "GET");
993
1001
  const s = normalizeHeaders(e.headers || {}), i = s.host || "example.com:443";
994
- if (f(this, $, se).call(this, i, e.protocol || "http"), f(this, q, ie).call(this, s), e.body && (r = f(this, j, oe).call(this, e.body)), e.fileInfos)
1002
+ if (p(this, q, ne).call(this, i, e.protocol || "http"), p(this, j, oe).call(this, s), e.body && (r = p(this, z, ae).call(this, e.body)), e.fileInfos)
995
1003
  for (const o of e.fileInfos)
996
- f(this, J, ce).call(this, o);
997
- typeof e.code == "string" && f(this, Y, ue).call(this, " ?>" + e.code), f(this, G, le).call(this);
998
- const n = await f(this, V, de).call(this);
1004
+ p(this, Y, ue).call(this, o);
1005
+ typeof e.code == "string" && p(this, V, de).call(this, " ?>" + e.code), p(this, J, ce).call(this);
1006
+ const n = await p(this, K, he).call(this);
999
1007
  if (e.throwOnError && n.exitCode !== 0) {
1000
1008
  const o = {
1001
1009
  stdout: n.text,
@@ -1019,7 +1027,7 @@ class BasePHP {
1019
1027
  }
1020
1028
  }
1021
1029
  addServerGlobalEntry(e, t) {
1022
- a(this, P)[e] = t;
1030
+ a(this, v)[e] = t;
1023
1031
  }
1024
1032
  defineConstant(e, t) {
1025
1033
  let r = {};
@@ -1128,10 +1136,10 @@ class BasePHP {
1128
1136
  this[__private__dont__use]._exit(e);
1129
1137
  } catch {
1130
1138
  }
1131
- d(this, y, !1), d(this, g, null), delete this[__private__dont__use].onMessage, delete this[__private__dont__use];
1139
+ d(this, w, !1), d(this, P, null), delete this[__private__dont__use].onMessage, delete this[__private__dont__use];
1132
1140
  }
1133
1141
  }
1134
- S = new WeakMap(), H = new WeakMap(), A = new WeakMap(), y = new WeakMap(), g = new WeakMap(), P = new WeakMap(), w = new WeakMap(), I = new WeakMap(), O = new WeakSet(), ee = function() {
1142
+ T = new WeakMap(), H = new WeakMap(), A = new WeakMap(), w = new WeakMap(), P = new WeakMap(), v = new WeakMap(), g = new WeakMap(), I = new WeakMap(), U = new WeakSet(), te = function() {
1135
1143
  if (this.setPhpIniEntry("auto_prepend_file", "/tmp/consts.php"), this.fileExists("/tmp/consts.php") || this.writeFile(
1136
1144
  "/tmp/consts.php",
1137
1145
  `<?php
@@ -1143,8 +1151,8 @@ S = new WeakMap(), H = new WeakMap(), A = new WeakMap(), y = new WeakMap(), g =
1143
1151
  }
1144
1152
  }
1145
1153
  }`
1146
- ), a(this, S).length > 0) {
1147
- const e = a(this, S).map(([t, r]) => `${t}=${r}`).join(`
1154
+ ), a(this, T).length > 0) {
1155
+ const e = a(this, T).map(([t, r]) => `${t}=${r}`).join(`
1148
1156
  `) + `
1149
1157
 
1150
1158
  `;
@@ -1156,7 +1164,7 @@ S = new WeakMap(), H = new WeakMap(), A = new WeakMap(), y = new WeakMap(), g =
1156
1164
  );
1157
1165
  }
1158
1166
  this[__private__dont__use].ccall("php_wasm_init", null, [], []);
1159
- }, U = new WeakSet(), te = function() {
1167
+ }, D = new WeakSet(), re = function() {
1160
1168
  const e = "/tmp/headers.json";
1161
1169
  if (!this.fileExists(e))
1162
1170
  throw new Error(
@@ -1173,7 +1181,7 @@ S = new WeakMap(), H = new WeakMap(), A = new WeakMap(), y = new WeakMap(), g =
1173
1181
  headers: r,
1174
1182
  httpStatusCode: t.status
1175
1183
  };
1176
- }, D = new WeakSet(), re = function(e) {
1184
+ }, $ = new WeakSet(), se = function(e) {
1177
1185
  if (this[__private__dont__use].ccall(
1178
1186
  "wasm_set_request_uri",
1179
1187
  null,
@@ -1188,7 +1196,7 @@ S = new WeakMap(), H = new WeakMap(), A = new WeakMap(), y = new WeakMap(), g =
1188
1196
  [t]
1189
1197
  );
1190
1198
  }
1191
- }, $ = new WeakSet(), se = function(e, t) {
1199
+ }, q = new WeakSet(), ne = function(e, t) {
1192
1200
  this[__private__dont__use].ccall(
1193
1201
  "wasm_set_request_host",
1194
1202
  null,
@@ -1206,14 +1214,14 @@ S = new WeakMap(), H = new WeakMap(), A = new WeakMap(), y = new WeakMap(), g =
1206
1214
  [NUMBER],
1207
1215
  [r]
1208
1216
  ), (t === "https" || !t && r === 443) && this.addServerGlobalEntry("HTTPS", "on");
1209
- }, W = new WeakSet(), ne = function(e) {
1217
+ }, W = new WeakSet(), ie = function(e) {
1210
1218
  this[__private__dont__use].ccall(
1211
1219
  "wasm_set_request_method",
1212
1220
  null,
1213
1221
  [STRING],
1214
1222
  [e]
1215
1223
  );
1216
- }, q = new WeakSet(), ie = function(e) {
1224
+ }, j = new WeakSet(), oe = function(e) {
1217
1225
  e.cookie && this[__private__dont__use].ccall(
1218
1226
  "wasm_set_cookies",
1219
1227
  null,
@@ -1237,7 +1245,7 @@ S = new WeakMap(), H = new WeakMap(), A = new WeakMap(), y = new WeakMap(), g =
1237
1245
  e[t]
1238
1246
  );
1239
1247
  }
1240
- }, j = new WeakSet(), oe = function(e) {
1248
+ }, z = new WeakSet(), ae = function(e) {
1241
1249
  const t = this[__private__dont__use].lengthBytesUTF8(e), r = this[__private__dont__use].malloc(t + 1);
1242
1250
  if (!r)
1243
1251
  throw new Error("Could not allocate memory for the request body.");
@@ -1256,22 +1264,22 @@ S = new WeakMap(), H = new WeakMap(), A = new WeakMap(), y = new WeakMap(), g =
1256
1264
  [NUMBER],
1257
1265
  [new TextEncoder().encode(e).length]
1258
1266
  ), r;
1259
- }, z = new WeakSet(), ae = function(e) {
1267
+ }, G = new WeakSet(), le = function(e) {
1260
1268
  this[__private__dont__use].ccall(
1261
1269
  "wasm_set_path_translated",
1262
1270
  null,
1263
1271
  [STRING],
1264
1272
  [e]
1265
1273
  );
1266
- }, G = new WeakSet(), le = function() {
1267
- for (const e in a(this, P))
1274
+ }, J = new WeakSet(), ce = function() {
1275
+ for (const e in a(this, v))
1268
1276
  this[__private__dont__use].ccall(
1269
1277
  "wasm_add_SERVER_entry",
1270
1278
  null,
1271
1279
  [STRING, STRING],
1272
- [e, a(this, P)[e]]
1280
+ [e, a(this, v)[e]]
1273
1281
  );
1274
- }, J = new WeakSet(), ce = function(e) {
1282
+ }, Y = new WeakSet(), ue = function(e) {
1275
1283
  const { key: t, name: r, type: s, data: i } = e, n = `/tmp/${Math.random().toFixed(20)}`;
1276
1284
  this.writeFile(n, i);
1277
1285
  const o = 0;
@@ -1281,23 +1289,23 @@ S = new WeakMap(), H = new WeakMap(), A = new WeakMap(), y = new WeakMap(), g =
1281
1289
  [STRING, STRING, STRING, STRING, NUMBER, NUMBER],
1282
1290
  [t, r, s, n, o, i.byteLength]
1283
1291
  );
1284
- }, Y = new WeakSet(), ue = function(e) {
1292
+ }, V = new WeakSet(), de = function(e) {
1285
1293
  this[__private__dont__use].ccall(
1286
1294
  "wasm_set_php_code",
1287
1295
  null,
1288
1296
  [STRING],
1289
1297
  [e]
1290
1298
  );
1291
- }, V = new WeakSet(), de = async function() {
1299
+ }, K = new WeakSet(), he = async function() {
1292
1300
  var i;
1293
1301
  let e, t;
1294
1302
  try {
1295
1303
  e = await new Promise((n, o) => {
1296
1304
  var h;
1297
- t = (p) => {
1305
+ t = (f) => {
1298
1306
  const u = new Error("Rethrown");
1299
- u.cause = p.error, u.betterMessage = p.message, o(u);
1300
- }, (h = a(this, g)) == null || h.addEventListener(
1307
+ u.cause = f.error, u.betterMessage = f.message, o(u);
1308
+ }, (h = a(this, P)) == null || h.addEventListener(
1301
1309
  "error",
1302
1310
  t
1303
1311
  );
@@ -1311,8 +1319,8 @@ S = new WeakMap(), H = new WeakMap(), A = new WeakMap(), y = new WeakMap(), g =
1311
1319
  return c instanceof Promise ? c.then(n, o) : n(c);
1312
1320
  });
1313
1321
  } catch (n) {
1314
- for (const p in this)
1315
- typeof this[p] == "function" && (this[p] = () => {
1322
+ for (const f in this)
1323
+ typeof this[f] == "function" && (this[f] = () => {
1316
1324
  throw new Error(
1317
1325
  "PHP runtime has crashed – see the earlier error for details."
1318
1326
  );
@@ -1321,9 +1329,9 @@ S = new WeakMap(), H = new WeakMap(), A = new WeakMap(), y = new WeakMap(), g =
1321
1329
  const o = n, c = "betterMessage" in o ? o.betterMessage : o.message, h = new Error(c);
1322
1330
  throw h.cause = o, h;
1323
1331
  } finally {
1324
- (i = a(this, g)) == null || i.removeEventListener("error", t), d(this, P, {});
1332
+ (i = a(this, P)) == null || i.removeEventListener("error", t), d(this, v, {});
1325
1333
  }
1326
- const { headers: r, httpStatusCode: s } = f(this, U, te).call(this);
1334
+ const { headers: r, httpStatusCode: s } = p(this, D, re).call(this);
1327
1335
  return new PHPResponse(
1328
1336
  s,
1329
1337
  r,
@@ -1410,17 +1418,17 @@ function journalFSEvents(e, t, r = () => {
1410
1418
  c[u] = n[u];
1411
1419
  function h() {
1412
1420
  for (const [u, _] of Object.entries(o))
1413
- n[u] = function(...v) {
1414
- return _(...v), c[u].apply(this, v);
1421
+ n[u] = function(...y) {
1422
+ return _(...y), c[u].apply(this, y);
1415
1423
  };
1416
1424
  }
1417
- function p() {
1425
+ function f() {
1418
1426
  for (const [u, _] of Object.entries(c))
1419
1427
  e[__private__dont__use].FS[u] = _;
1420
1428
  }
1421
1429
  e[__private__dont__use].journal = {
1422
1430
  bind: h,
1423
- unbind: p
1431
+ unbind: f
1424
1432
  }, h();
1425
1433
  }
1426
1434
  e.addEventListener("runtime.initialized", s), e[__private__dont__use] && s();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@php-wasm/fs-journal",
3
- "version": "0.6.0",
3
+ "version": "0.6.2",
4
4
  "description": "Bindings to journal the PHP filesystem",
5
5
  "repository": {
6
6
  "type": "git",
@@ -36,7 +36,7 @@
36
36
  "main": "./index.cjs",
37
37
  "module": "./index.js",
38
38
  "license": "GPL-2.0-or-later",
39
- "gitHead": "3f137306ec8e3b10ec0674a1fe69ee43349edb4a",
39
+ "gitHead": "3c0de0d0847c3550a75a026bef9724eac421afbf",
40
40
  "engines": {
41
41
  "node": ">=18.18.2",
42
42
  "npm": ">=8.11.0"