@php-wasm/fs-journal 0.6.3 → 0.6.4

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 +10 -10
  2. package/index.js +254 -218
  3. package/package.json +2 -2
package/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Y=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)};var o=(e,t,r)=>(Y(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)},h=(e,t,r,s)=>(Y(e,t,"write to private field"),s?s.call(e,r):t.set(e,r),r);var f=(e,t,r)=>(Y(e,t,"access private method"),r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});if(typeof File>"u"){class e extends Blob{constructor(r,s,n){super(r);let i;n!=null&&n.lastModified&&(i=new Date),(!i||isNaN(i.getFullYear()))&&(i=new Date),this.lastModifiedDate=i,this.lastModified=i.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,i=await t.slice(e,e+s.byteLength).arrayBuffer(),a=new Uint8Array(i);new Uint8Array(s.buffer).set(a);const c=a.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(...n){var i;try{return s(...n)}catch(a){if(!(a instanceof Error))throw a;const c=clarifyErrorMessage(a,(i=e.lastAsyncifyStackSource)==null?void 0:i.stack);if(e.lastAsyncifyStackSource&&(a.cause=e.lastAsyncifyStackSource),t.hasListeners()){t.dispatchEvent(new ErrorEvent("error",{error:a,message:c}));return}throw isExitCodeZero(a)||showCriticalErrorBox(c),a}}}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 Y=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)};var a=(e,t,r)=>(Y(e,t,"read from private field"),r?r.call(e):t.get(e)),u=(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)},h=(e,t,r,s)=>(Y(e,t,"write to private field"),s?s.call(e,r):t.set(e,r),r);var f=(e,t,r)=>(Y(e,t,"access private method"),r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});if(typeof File>"u"){class e extends Blob{constructor(r,s,n){super(r);let i;n!=null&&n.lastModified&&(i=new Date),(!i||isNaN(i.getFullYear()))&&(i=new Date),this.lastModifiedDate=i,this.lastModified=i.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,i=await t.slice(e,e+s.byteLength).arrayBuffer(),o=new Uint8Array(i);new Uint8Array(s.buffer).set(o);const l=o.byteLength;r.byobRequest.respond(l),e+=l,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(...n){var i;try{return s(...n)}catch(o){if(!(o instanceof Error))throw o;const l=clarifyErrorMessage(o,(i=e.lastAsyncifyStackSource)==null?void 0:i.stack);if(e.lastAsyncifyStackSource&&(o.cause=e.lastAsyncifyStackSource),t.hasListeners()){t.dispatchEvent(new ErrorEvent("error",{error:o,message:l}));return}throw isExitCodeZero(o)||showCriticalErrorBox(l),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,21 +32,21 @@ 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 n=e[s];n==="."?e.splice(s,1):n===".."?(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,n="",i=0){this.httpStatusCode=t,this.headers=r,this.bytes=s,this.exitCode=i,this.errors=n}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 v,T;class PHPBrowser{constructor(t,r={}){l(this,v,void 0);l(this,T,void 0);this.requestHandler=t,h(this,v,{}),h(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"]),o(this,T).handleRedirects&&s.headers.location&&r<o(this,T).maxRedirects){const n=new URL(s.headers.location[0],this.requestHandler.absoluteUrl);return this.request({url:n.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("="),n=r.substring(0,s),i=r.substring(s+1).split(";")[0];o(this,v)[n]=i}catch(s){console.error(s)}}serializeCookies(){const t=[];for(const r in o(this,v))t.push(`${r}=${o(this,v)[r]}`);return t.join("; ")}}v=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}async function encodeAsMultipart(e){const t=`----${Math.random().toString(36).slice(2)}`,r=`multipart/form-data; boundary=${t}`,s=new TextEncoder,n=[];for(const[d,p]of Object.entries(e))n.push(`--${t}\r
36
- `),n.push(`Content-Disposition: form-data; name="${d}"`),p instanceof File&&n.push(`; filename="${p.name}"`),n.push(`\r
37
- `),p instanceof File&&n.push("Content-Type: application/octet-stream"),n.push(`\r
38
- \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 n=e[s];n==="."?e.splice(s,1):n===".."?(e.splice(s,1),r++):r&&(e.splice(s,1),r--)}if(t)for(;r;r--)e.unshift("..");return e}function splitShellCommand(e){let s=0,n="";const i=[];let o="";for(let l=0;l<e.length;l++){const c=e[l];c==="\\"?((e[l+1]==='"'||e[l+1]==="'")&&l++,o+=e[l]):s===0?c==='"'||c==="'"?(s=1,n=c):c.match(/\s/)?(o.trim().length&&i.push(o.trim()),o=c):i.length&&!o?o=i.pop()+c:o+=c:s===1&&(c===n?(s=0,n=""):o+=c)}return o&&i.push(o.trim()),i}function createSpawnHandler(e){return function(t,r=[],s={}){const n=new ChildProcess,i=new ProcessApi(n);return setTimeout(async()=>{let o=[];if(r.length)o=[t,...r];else if(typeof t=="string")o=splitShellCommand(t);else if(Array.isArray(t))o=t;else throw new Error("Invalid command ",t);await e(o,i,s),n.emit("spawn",!0)}),n}}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)}stdoutEnd(){this.childProcess.stdout.emit("end",{})}stderr(t){typeof t=="string"&&(t=new TextEncoder().encode(t)),this.childProcess.stderr.emit("data",t)}stderrEnd(){this.childProcess.stderr.emit("end",{})}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,n="",i=0){this.httpStatusCode=t,this.headers=r,this.bytes=s,this.exitCode=i,this.errors=n}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 v,T;class PHPBrowser{constructor(t,r={}){u(this,v,void 0);u(this,T,void 0);this.requestHandler=t,h(this,v,{}),h(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 n=new URL(s.headers.location[0],this.requestHandler.absoluteUrl);return this.request({url:n.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("="),n=r.substring(0,s),i=r.substring(s+1).split(";")[0];a(this,v)[n]=i}catch(s){console.error(s)}}serializeCookies(){const t=[];for(const r in a(this,v))t.push(`${r}=${a(this,v)[r]}`);return t.join("; ")}}v=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}async function encodeAsMultipart(e){const t=`----${Math.random().toString(36).slice(2)}`,r=`multipart/form-data; boundary=${t}`,s=new TextEncoder,n=[];for(const[c,p]of Object.entries(e))n.push(`--${t}\r
36
+ `),n.push(`Content-Disposition: form-data; name="${c}"`),p instanceof File&&n.push(`; filename="${p.name}"`),n.push(`\r
37
+ `),p instanceof File&&(n.push("Content-Type: application/octet-stream"),n.push(`\r
38
+ `)),n.push(`\r
39
39
  `),p instanceof File?n.push(await fileToUint8Array(p)):n.push(p),n.push(`\r
40
40
  `);n.push(`--${t}--\r
41
- `);const i=n.reduce((d,p)=>d+p.length,0),a=new Uint8Array(i);let c=0;for(const d of n)a.set(typeof d=="string"?s.encode(d):d,c),c+=d.length;return{bytes:a,contentType:r}}function fileToUint8Array(e){return new Promise(t=>{const r=new FileReader;r.onload=()=>{t(new Uint8Array(r.result))},r.readAsArrayBuffer(e)})}var w,F,I,b,x,m,C,R,M,K,N,Z,B,Q;class PHPRequestHandler{constructor(t,r={}){l(this,M);l(this,N);l(this,B);l(this,w,void 0);l(this,F,void 0);l(this,I,void 0);l(this,b,void 0);l(this,x,void 0);l(this,m,void 0);l(this,C,void 0);l(this,R,void 0);h(this,R,new Semaphore({concurrency:1}));const{documentRoot:s="/www/",absoluteUrl:n=typeof location=="object"?location==null?void 0:location.href:""}=r;this.php=t,h(this,w,s);const i=new URL(n);h(this,I,i.hostname),h(this,b,i.port?Number(i.port):i.protocol==="https:"?443:80),h(this,F,(i.protocol||"").replace(":",""));const a=o(this,b)!==443&&o(this,b)!==80;h(this,x,[o(this,I),a?`:${o(this,b)}`:""].join("")),h(this,m,i.pathname.replace(/\/+$/,"")),h(this,C,[`${o(this,F)}://`,o(this,x),o(this,m)].join(""))}pathToInternalUrl(t){return`${this.absoluteUrl}${t}`}internalUrlToPath(t){const r=new URL(t);return r.pathname.startsWith(o(this,m))&&(r.pathname=r.pathname.slice(o(this,m).length)),toRelativeUrl(r)}get isRequestRunning(){return o(this,R).running>0}get absoluteUrl(){return o(this,C)}get documentRoot(){return o(this,w)}async request(t){const r=t.url.startsWith("http://")||t.url.startsWith("https://"),s=new URL(t.url,r?void 0:DEFAULT_BASE_URL),n=removePathPrefix(s.pathname,o(this,m)),i=`${o(this,w)}${n}`;return seemsLikeAPHPRequestHandlerPath(i)?await f(this,N,Z).call(this,t,s):f(this,M,K).call(this,i)}}w=new WeakMap,F=new WeakMap,I=new WeakMap,b=new WeakMap,x=new WeakMap,m=new WeakMap,C=new WeakMap,R=new WeakMap,M=new WeakSet,K=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)},N=new WeakSet,Z=async function(t,r){var n,i;if(o(this,R).running>0&&((n=t.headers)==null?void 0:n["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 o(this,R).acquire();try{this.php.addServerGlobalEntry("REMOTE_ADDR","127.0.0.1"),this.php.addServerGlobalEntry("DOCUMENT_ROOT",o(this,w)),this.php.addServerGlobalEntry("HTTPS",o(this,C).startsWith("https://")?"on":"");let a="GET";const c={host:o(this,x),...normalizeHeaders(t.headers||{})};let d=t.body;if(typeof d=="object"&&!(d instanceof Uint8Array)){a="POST";const{bytes:u,contentType:_}=await encodeAsMultipart(d);d=u,c["content-type"]=_}let p;try{let u=r.pathname;if((i=t.headers)!=null&&i["x-rewrite-url"])try{u=new URL(t.headers["x-rewrite-url"]).pathname}catch{}p=f(this,B,Q).call(this,u)}catch{return new PHPResponse(404,{},new TextEncoder().encode("404 File not found"))}return await this.php.run({relativeUri:ensurePathPrefix(toRelativeUrl(r),o(this,m)),protocol:o(this,F),method:t.method||a,body:d,scriptPath:p,headers:c})}finally{s()}},B=new WeakSet,Q=function(t){let r=removePathPrefix(t,o(this,m));r.includes(".php")?r=r.split(".php")[0]+".php":(r.endsWith("/")||(r+="/"),r.endsWith("index.php")||(r+="index.php"));const s=`${o(this,w)}${r}`;if(this.php.fileExists(s))return s;throw new Error(`File not found: ${s}`)};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,n){const i=n.value;n.value=function(...a){try{return i.apply(this,a)}catch(c){const d=typeof c=="object"?c==null?void 0:c.errno:null;if(d in FileErrorCodes){const p=FileErrorCodes[d],u=typeof a[0]=="string"?a[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 n=s>1?void 0:s?__getOwnPropDesc(t,r):t,i=e.length-1,a;i>=0;i--)(a=e[i])&&(n=(s?a(t,r,n):a(n))||n);return s&&n&&__defProp(t,r,n),n};const STRING="string",NUMBER="number",__private__dont__use=Symbol("__private__dont__use");var S,k,A,y,E,P,g,H,L,X,O,ee,U,te,q,re,$,se,D,ne,j,ie,W,oe,z,ae,G,le,J,ce;class BasePHP{constructor(e,t){l(this,L);l(this,O);l(this,U);l(this,q);l(this,$);l(this,D);l(this,j);l(this,W);l(this,z);l(this,G);l(this,J);l(this,S,void 0);l(this,k,void 0);l(this,A,void 0);l(this,y,void 0);l(this,E,void 0);l(this,P,void 0);l(this,g,void 0);l(this,H,void 0);h(this,S,[]),h(this,y,!1),h(this,E,null),h(this,P,{}),h(this,g,new Map),h(this,H,[]),this.semaphore=new Semaphore({concurrency:1}),e!==void 0&&this.initializeRuntime(e),t&&(this.requestHandler=new PHPBrowser(new PHPRequestHandler(this,t)))}addEventListener(e,t){o(this,g).has(e)||o(this,g).set(e,new Set),o(this,g).get(e).add(t)}removeEventListener(e,t){var r;(r=o(this,g).get(e))==null||r.delete(t)}dispatchEvent(e){const t=o(this,g).get(e.type);if(t)for(const r of t)r(e)}async onMessage(e){o(this,H).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 o(this,H)){const n=await s(r);if(n)return n}return""},h(this,E,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?");h(this,A,e)}setPhpIniPath(e){if(o(this,y))throw new Error("Cannot set PHP ini path after calling run().");h(this,k,e),this[__private__dont__use].ccall("wasm_set_phpini_path",null,["string"],[e])}setPhpIniEntry(e,t){if(o(this,y))throw new Error("Cannot set PHP ini entries after calling run().");o(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{o(this,y)||(f(this,L,X).call(this),h(this,y,!0)),f(this,W,oe).call(this,e.scriptPath||""),f(this,U,te).call(this,e.relativeUri||""),f(this,$,se).call(this,e.method||"GET");const s=normalizeHeaders(e.headers||{}),n=s.host||"example.com:443";f(this,q,re).call(this,n,e.protocol||"http"),f(this,D,ne).call(this,s),e.body&&(r=f(this,j,ie).call(this,e.body)),typeof e.code=="string"&&f(this,G,le).call(this," ?>"+e.code),f(this,z,ae).call(this);const i=await f(this,J,ce).call(this);if(e.throwOnError&&i.exitCode!==0){const a={stdout:i.text,stderr:i.errors};console.warn("PHP.run() output was:",a);const c=new Error(`PHP.run() failed with exit code ${i.exitCode} and the following output`);throw c.output=a,c}return i}finally{try{r&&this[__private__dont__use].free(r)}finally{t(),this.dispatchEvent({type:"request.end"})}}}addServerGlobalEntry(e,t){o(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(n=>`${s}/${n}`)}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),o(this,k)&&this.setPhpIniPath(o(this,k)),o(this,A)&&this.setSapiName(o(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{}h(this,y,!1),h(this,E,null),delete this[__private__dont__use].onMessage,delete this[__private__dont__use]}}S=new WeakMap,k=new WeakMap,A=new WeakMap,y=new WeakMap,E=new WeakMap,P=new WeakMap,g=new WeakMap,H=new WeakMap,L=new WeakSet,X=function(){if(this.setPhpIniEntry("auto_prepend_file","/tmp/consts.php"),this.fileExists("/tmp/consts.php")||this.writeFile("/tmp/consts.php",`<?php
42
- if(file_exists('/tmp/consts.json')) {
43
- $consts = json_decode(file_get_contents('/tmp/consts.json'), true);
41
+ `);const i=n.reduce((c,p)=>c+p.length,0),o=new Uint8Array(i);let l=0;for(const c of n)o.set(typeof c=="string"?s.encode(c):c,l),l+=c.length;return{bytes:o,contentType:r}}function fileToUint8Array(e){return new Promise(t=>{const r=new FileReader;r.onload=()=>{t(new Uint8Array(r.result))},r.readAsArrayBuffer(e)})}var y,F,I,b,x,m,C,R,N,K,O,Z,U,X;class PHPRequestHandler{constructor(t,r={}){u(this,N);u(this,O);u(this,U);u(this,y,void 0);u(this,F,void 0);u(this,I,void 0);u(this,b,void 0);u(this,x,void 0);u(this,m,void 0);u(this,C,void 0);u(this,R,void 0);h(this,R,new Semaphore({concurrency:1}));const{documentRoot:s="/www/",absoluteUrl:n=typeof location=="object"?location==null?void 0:location.href:""}=r;this.php=t,h(this,y,s);const i=new URL(n);h(this,I,i.hostname),h(this,b,i.port?Number(i.port):i.protocol==="https:"?443:80),h(this,F,(i.protocol||"").replace(":",""));const o=a(this,b)!==443&&a(this,b)!==80;h(this,x,[a(this,I),o?`:${a(this,b)}`:""].join("")),h(this,m,i.pathname.replace(/\/+$/,"")),h(this,C,[`${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,R).running>0}get absoluteUrl(){return a(this,C)}get documentRoot(){return a(this,y)}async request(t){const r=t.url.startsWith("http://")||t.url.startsWith("https://"),s=new URL(t.url,r?void 0:DEFAULT_BASE_URL),n=removePathPrefix(s.pathname,a(this,m)),i=`${a(this,y)}${n}`;return seemsLikeAPHPRequestHandlerPath(i)?await f(this,O,Z).call(this,t,s):f(this,N,K).call(this,i)}}y=new WeakMap,F=new WeakMap,I=new WeakMap,b=new WeakMap,x=new WeakMap,m=new WeakMap,C=new WeakMap,R=new WeakMap,N=new WeakSet,K=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,Z=async function(t,r){var n,i;if(a(this,R).running>0&&((n=t.headers)==null?void 0:n["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,R).acquire();try{this.php.addServerGlobalEntry("REMOTE_ADDR","127.0.0.1"),this.php.addServerGlobalEntry("DOCUMENT_ROOT",a(this,y)),this.php.addServerGlobalEntry("HTTPS",a(this,C).startsWith("https://")?"on":"");let o="GET";const l={host:a(this,x),...normalizeHeaders(t.headers||{})};let c=t.body;if(typeof c=="object"&&!(c instanceof Uint8Array)){o="POST";const{bytes:d,contentType:_}=await encodeAsMultipart(c);c=d,l["content-type"]=_}let p;try{let d=r.pathname;if((i=t.headers)!=null&&i["x-rewrite-url"])try{d=new URL(t.headers["x-rewrite-url"]).pathname}catch{}p=f(this,U,X).call(this,d)}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:c,scriptPath:p,headers:l})}finally{s()}},U=new WeakSet,X=function(t){let r=removePathPrefix(t,a(this,m));r.includes(".php")?r=r.split(".php")[0]+".php":this.php.isDir(`${a(this,y)}${r}`)?(r.endsWith("/")||(r=`${r}/`),r=`${r}index.php`):r="/index.php";const s=`${a(this,y)}${r}`;if(this.php.fileExists(s))return s;throw new Error(`File not found: ${s}`)};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,n){const i=n.value;n.value=function(...o){try{return i.apply(this,o)}catch(l){const c=typeof l=="object"?l==null?void 0:l.errno:null;if(c in FileErrorCodes){const p=FileErrorCodes[c],d=typeof o[0]=="string"?o[0]:null,_=d!==null?e.replaceAll("{path}",d):e;throw new Error(`${_}: ${p}`,{cause:l})}throw l}}}}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 n=s>1?void 0:s?__getOwnPropDesc(t,r):t,i=e.length-1,o;i>=0;i--)(o=e[i])&&(n=(s?o(t,r,n):o(n))||n);return s&&n&&__defProp(t,r,n),n};const STRING="string",NUMBER="number",__private__dont__use=Symbol("__private__dont__use");var S,A,k,E,g,P,w,H,M,ee,B,te,L,re,$,se,D,ne,q,ie,j,oe,W,ae,z,le,G,ce,J,ue,Q,de;class BasePHP{constructor(e,t){u(this,M);u(this,B);u(this,L);u(this,$);u(this,D);u(this,q);u(this,j);u(this,W);u(this,z);u(this,G);u(this,J);u(this,Q);u(this,S,void 0);u(this,A,void 0);u(this,k,void 0);u(this,E,void 0);u(this,g,void 0);u(this,P,void 0);u(this,w,void 0);u(this,H,void 0);h(this,S,[]),h(this,E,!1),h(this,g,null),h(this,P,{}),h(this,w,new Map),h(this,H,[]),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,w).has(e)||a(this,w).set(e,new Set),a(this,w).get(e).add(t)}removeEventListener(e,t){var r;(r=a(this,w).get(e))==null||r.delete(t)}dispatchEvent(e){const t=a(this,w).get(e.type);if(t)for(const r of t)r(e)}async onMessage(e){a(this,H).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,H)){const n=await s(r);if(n)return n}return""},h(this,g,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?");h(this,k,e)}setPhpIniPath(e){if(a(this,E))throw new Error("Cannot set PHP ini path after calling run().");h(this,A,e),this[__private__dont__use].ccall("wasm_set_phpini_path",null,["string"],[e])}setPhpIniEntry(e,t){if(a(this,E))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{if(a(this,E)||(f(this,M,ee).call(this),h(this,E,!0)),e.scriptPath&&!this.fileExists(e.scriptPath))throw new Error(`The script path "${e.scriptPath}" does not exist.`);f(this,W,ae).call(this,e.scriptPath||""),f(this,L,re).call(this,e.relativeUri||""),f(this,D,ne).call(this,e.method||"GET");const s=normalizeHeaders(e.headers||{}),n=s.host||"example.com:443";f(this,$,se).call(this,n,e.protocol||"http"),f(this,q,ie).call(this,s),e.body&&(r=f(this,j,oe).call(this,e.body)),typeof e.code=="string"&&f(this,J,ue).call(this," ?>"+e.code),f(this,z,le).call(this);const i=e.env||{};for(const l in i)f(this,G,ce).call(this,l,i[l]);const o=await f(this,Q,de).call(this);if(e.throwOnError&&o.exitCode!==0){const l={stdout:o.text,stderr:o.errors};console.warn("PHP.run() output was:",l);const c=new Error(`PHP.run() failed with exit code ${o.exitCode} and the following output: `+o.errors);throw c.output=l,console.error(c),c}return o}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("/internal/consts.json")&&this.readFileAsText("/internal/consts.json")||"{}")}catch{}this.writeFile("/internal/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(n=>`${s}/${n}`)}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,A)&&this.setPhpIniPath(a(this,A)),a(this,k)&&this.setSapiName(a(this,k)),this.requestHandler){const r=this.documentRoot;copyFS(t,this[__private__dont__use].FS,r)}}exit(e=0){this.dispatchEvent({type:"runtime.beforedestroy"});try{this[__private__dont__use]._exit(e)}catch{}h(this,E,!1),h(this,g,null),delete this[__private__dont__use].onMessage,delete this[__private__dont__use]}}S=new WeakMap,A=new WeakMap,k=new WeakMap,E=new WeakMap,g=new WeakMap,P=new WeakMap,w=new WeakMap,H=new WeakMap,M=new WeakSet,ee=function(){if(this.setPhpIniEntry("auto_prepend_file","/internal/consts.php"),this.fileExists("/internal/consts.php")||this.writeFile("/internal/consts.php",`<?php
42
+ if(file_exists('/internal/consts.json')) {
43
+ $consts = json_decode(file_get_contents('/internal/consts.json'), true);
44
44
  foreach ($consts as $const => $value) {
45
45
  if (!defined($const) && is_scalar($value)) {
46
46
  define($const, $value);
47
47
  }
48
48
  }
49
- }`),o(this,S).length>0){const e=o(this,S).map(([t,r])=>`${t}=${r}`).join(`
49
+ }`),a(this,S).length>0){const e=a(this,S).map(([t,r])=>`${t}=${r}`).join(`
50
50
  `)+`
51
51
 
52
- `;this[__private__dont__use].ccall("wasm_set_phpini_entries",null,[STRING],[e])}this[__private__dont__use].ccall("php_wasm_init",null,[],[])},O=new WeakSet,ee=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 n=s.indexOf(": "),i=s.substring(0,n).toLowerCase(),a=s.substring(n+2);i in r||(r[i]=[]),r[i].push(a)}return{headers:r,httpStatusCode:t.status}},U=new WeakSet,te=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,re=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")},$=new WeakSet,se=function(e){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[e])},D=new WeakSet,ne=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])}},j=new WeakSet,ie=function(e){let t,r;typeof e=="string"?(console.warn("Passing a string as the request body is deprecated. Please use a Uint8Array instead. See https://github.com/WordPress/wordpress-playground/issues/997 for more details"),r=this[__private__dont__use].lengthBytesUTF8(e),t=r+1):(r=e.byteLength,t=e.byteLength);const s=this[__private__dont__use].malloc(t);if(!s)throw new Error("Could not allocate memory for the request body.");return typeof e=="string"?this[__private__dont__use].stringToUTF8(e,s,t+1):this[__private__dont__use].HEAPU8.set(e,s),this[__private__dont__use].ccall("wasm_set_request_body",null,[NUMBER],[s]),this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[r]),s},W=new WeakSet,oe=function(e){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[e])},z=new WeakSet,ae=function(){for(const e in o(this,P))this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[e,o(this,P)[e]])},G=new WeakSet,le=function(e){this[__private__dont__use].ccall("wasm_set_php_code",null,[STRING],[e])},J=new WeakSet,ce=async function(){var n;let e,t;try{e=await new Promise((i,a)=>{var d;t=p=>{const u=new Error("Rethrown");u.cause=p.error,u.betterMessage=p.message,a(u)},(d=o(this,E))==null||d.addEventListener("error",t);const c=this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0});return c instanceof Promise?c.then(i,a):i(c)})}catch(i){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 a=i,c="betterMessage"in a?a.betterMessage:a.message,d=new Error(c);throw d.cause=a,d}finally{(n=o(this,E))==null||n.removeEventListener("error",t),h(this,P,{})}const{headers:r,httpStatusCode:s}=f(this,O,ee).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 n=t.readdir(r).filter(i=>i!=="."&&i!=="..");for(const i of n)recreateMemFS(e,t,joinPaths(r,i))}function journalFSEvents(e,t,r=()=>{}){function s(){t=normalizePath(t);const i=e[__private__dont__use].FS,a=createFSHooks(i,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(a))c[u]=i[u];function d(){for(const[u,_]of Object.entries(a))i[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:d,unbind:p},d()}e.addEventListener("runtime.initialized",s),e[__private__dont__use]&&s();function n(){e[__private__dont__use].journal.unbind(),delete e[__private__dont__use].journal}return e.addEventListener("runtime.beforedestroy",n),function(){return e.removeEventListener("runtime.initialized",s),e.removeEventListener("runtime.beforedestroy",n),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 n=e.lookupPath(r,{follow:!0}),i=e.lookupPath(s,{parent:!0}).path;t({operation:"RENAME",nodeType:e.isDir(n.node.mode)?"directory":"file",path:n.path,toPath:joinPaths(i,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 n=checkRelationship(e[r],e[s]);if(n==="none")continue;const i=e[r],a=e[s];if(i.operation==="RENAME"&&a.operation==="RENAME"){console.warn("[FS Journal] Normalizing a double rename is not yet supported:",{current:i,last:a});continue}(a.operation==="CREATE"||a.operation==="WRITE")&&(i.operation==="RENAME"?n==="same_node"?(t[s]=[],t[r]=[{...a,path:i.toPath},...t[r]||[]]):n==="descendant"&&(t[s]=[],t[r]=[{...a,path:joinPaths(i.toPath,a.path.substring(i.path.length))},...t[r]||[]]):i.operation==="WRITE"&&n==="same_node"?t[s]=[]:i.operation==="DELETE"&&n==="same_node"&&(t[s]=[],t[r]=[]))}if(Object.entries(t).length>0){const s=e.flatMap((n,i)=>i in t?t[i]:[n]);return normalizeFilesystemOperations(s)}}return e}function checkRelationship(e,t){const r=e.path,s=e.operation!=="WRITE"&&e.nodeType==="directory",n=t.operation!=="WRITE"&&t.nodeType==="directory",i=t.operation==="RENAME"?t.toPath:t.path;return i===r?"same_node":n&&r.startsWith(i+"/")?"ancestor":s&&i.startsWith(r+"/")?"descendant":"none"}async function hydrateUpdateFileOps(e,t){const s=t.filter(n=>n.operation==="WRITE").map(n=>hydrateOp(e,n));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;
52
+ `;this[__private__dont__use].ccall("wasm_set_phpini_entries",null,[STRING],[e])}this[__private__dont__use].ccall("php_wasm_init",null,[],[])},B=new WeakSet,te=function(){const e="/internal/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 n=s.indexOf(": "),i=s.substring(0,n).toLowerCase(),o=s.substring(n+2);i in r||(r[i]=[]),r[i].push(o)}return{headers:r,httpStatusCode:t.status}},L=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")},D=new WeakSet,ne=function(e){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[e])},q=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])}},j=new WeakSet,oe=function(e){let t,r;typeof e=="string"?(console.warn("Passing a string as the request body is deprecated. Please use a Uint8Array instead. See https://github.com/WordPress/wordpress-playground/issues/997 for more details"),r=this[__private__dont__use].lengthBytesUTF8(e),t=r+1):(r=e.byteLength,t=e.byteLength);const s=this[__private__dont__use].malloc(t);if(!s)throw new Error("Could not allocate memory for the request body.");return typeof e=="string"?this[__private__dont__use].stringToUTF8(e,s,t+1):this[__private__dont__use].HEAPU8.set(e,s),this[__private__dont__use].ccall("wasm_set_request_body",null,[NUMBER],[s]),this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[r]),s},W=new WeakSet,ae=function(e){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[e])},z=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]])},G=new WeakSet,ce=function(e,t){this[__private__dont__use].ccall("wasm_add_ENV_entry",null,[STRING,STRING],[e,t])},J=new WeakSet,ue=function(e){this[__private__dont__use].ccall("wasm_set_php_code",null,[STRING],[e])},Q=new WeakSet,de=async function(){var n;let e,t;try{e=await new Promise((i,o)=>{var c;t=p=>{console.error(p),console.error(p.error);const d=new Error("Rethrown");d.cause=p.error,d.betterMessage=p.message,o(d)},(c=a(this,g))==null||c.addEventListener("error",t);const l=this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0});return l instanceof Promise?l.then(i,o):i(l)})}catch(i){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=i,l="betterMessage"in o?o.betterMessage:o.message,c=new Error(l);throw c.cause=o,console.error(c),c}finally{(n=a(this,g))==null||n.removeEventListener("error",t),h(this,P,{})}const{headers:r,httpStatusCode:s}=f(this,B,te).call(this);return new PHPResponse(s,r,this.readFileAsBuffer("/internal/stdout"),this.readFileAsText("/internal/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 copyFS(e,t,r){let s;try{s=e.lookupPath(r)}catch{return}if(!("contents"in s.node))return;if(!e.isDir(s.node.mode)){t.writeFile(r,e.readFile(r));return}t.mkdirTree(r);const n=e.readdir(r).filter(i=>i!=="."&&i!=="..");for(const i of n)copyFS(e,t,joinPaths(r,i))}function journalFSEvents(e,t,r=()=>{}){function s(){t=normalizePath(t);const i=e[__private__dont__use].FS,o=createFSHooks(i,d=>{if(d.path.startsWith(t))r(d);else if(d.operation==="RENAME"&&d.toPath.startsWith(t))for(const _ of recordExistingPath(e,d.path,d.toPath))r(_)}),l={};for(const[d]of Object.entries(o))l[d]=i[d];function c(){for(const[d,_]of Object.entries(o))i[d]=function(...V){return _(...V),l[d].apply(this,V)}}function p(){for(const[d,_]of Object.entries(l))e[__private__dont__use].FS[d]=_}e[__private__dont__use].journal={bind:c,unbind:p},c()}e.addEventListener("runtime.initialized",s),e[__private__dont__use]&&s();function n(){e[__private__dont__use].journal.unbind(),delete e[__private__dont__use].journal}return e.addEventListener("runtime.beforedestroy",n),function(){return e.removeEventListener("runtime.initialized",s),e.removeEventListener("runtime.beforedestroy",n),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 n=e.lookupPath(r,{follow:!0}),i=e.lookupPath(s,{parent:!0}).path;t({operation:"RENAME",nodeType:e.isDir(n.node.mode)?"directory":"file",path:n.path,toPath:joinPaths(i,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 n=checkRelationship(e[r],e[s]);if(n==="none")continue;const i=e[r],o=e[s];if(i.operation==="RENAME"&&o.operation==="RENAME"){console.warn("[FS Journal] Normalizing a double rename is not yet supported:",{current:i,last:o});continue}(o.operation==="CREATE"||o.operation==="WRITE")&&(i.operation==="RENAME"?n==="same_node"?(t[s]=[],t[r]=[{...o,path:i.toPath},...t[r]||[]]):n==="descendant"&&(t[s]=[],t[r]=[{...o,path:joinPaths(i.toPath,o.path.substring(i.path.length))},...t[r]||[]]):i.operation==="WRITE"&&n==="same_node"?t[s]=[]:i.operation==="DELETE"&&n==="same_node"&&(t[s]=[],t[r]=[]))}if(Object.entries(t).length>0){const s=e.flatMap((n,i)=>i in t?t[i]:[n]);return normalizeFilesystemOperations(s)}}return e}function checkRelationship(e,t){const r=e.path,s=e.operation!=="WRITE"&&e.nodeType==="directory",n=t.operation!=="WRITE"&&t.nodeType==="directory",i=t.operation==="RENAME"?t.toPath:t.path;return i===r?"same_node":n&&r.startsWith(i+"/")?"ancestor":s&&i.startsWith(r+"/")?"descendant":"none"}async function hydrateUpdateFileOps(e,t){const s=t.filter(n=>n.operation==="WRITE").map(n=>hydrateOp(e,n));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
@@ -2,7 +2,7 @@ var Y = (e, t, r) => {
2
2
  if (!t.has(e))
3
3
  throw TypeError("Cannot " + r);
4
4
  };
5
- var o = (e, t, r) => (Y(e, t, "read from private field"), r ? r.call(e) : t.get(e)), l = (e, t, r) => {
5
+ var a = (e, t, r) => (Y(e, t, "read from private field"), r ? r.call(e) : t.get(e)), u = (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);
@@ -50,10 +50,10 @@ function isByobSupported() {
50
50
  // this if needed.
51
51
  autoAllocateChunkSize: 512 * 1024,
52
52
  async pull(r) {
53
- const s = r.byobRequest.view, i = await t.slice(e, e + s.byteLength).arrayBuffer(), a = new Uint8Array(i);
54
- new Uint8Array(s.buffer).set(a);
55
- const c = a.byteLength;
56
- r.byobRequest.respond(c), e += c, e >= t.size && r.close();
53
+ const s = r.byobRequest.view, i = await t.slice(e, e + s.byteLength).arrayBuffer(), o = new Uint8Array(i);
54
+ new Uint8Array(s.buffer).set(o);
55
+ const l = o.byteLength;
56
+ r.byobRequest.respond(l), e += l, e >= t.size && r.close();
57
57
  }
58
58
  });
59
59
  });
@@ -118,23 +118,23 @@ function improveWASMErrorReporting(e) {
118
118
  var i;
119
119
  try {
120
120
  return s(...n);
121
- } catch (a) {
122
- if (!(a instanceof Error))
123
- throw a;
124
- const c = clarifyErrorMessage(
125
- a,
121
+ } catch (o) {
122
+ if (!(o instanceof Error))
123
+ throw o;
124
+ const l = clarifyErrorMessage(
125
+ o,
126
126
  (i = e.lastAsyncifyStackSource) == null ? void 0 : i.stack
127
127
  );
128
- if (e.lastAsyncifyStackSource && (a.cause = e.lastAsyncifyStackSource), t.hasListeners()) {
128
+ if (e.lastAsyncifyStackSource && (o.cause = e.lastAsyncifyStackSource), t.hasListeners()) {
129
129
  t.dispatchEvent(
130
130
  new ErrorEvent("error", {
131
- error: a,
132
- message: c
131
+ error: o,
132
+ message: l
133
133
  })
134
134
  );
135
135
  return;
136
136
  }
137
- throw isExitCodeZero(a) || showCriticalErrorBox(c), a;
137
+ throw isExitCodeZero(o) || showCriticalErrorBox(l), o;
138
138
  }
139
139
  };
140
140
  }
@@ -274,12 +274,31 @@ function normalizePathsArray(e, t) {
274
274
  e.unshift("..");
275
275
  return e;
276
276
  }
277
+ function splitShellCommand(e) {
278
+ let s = 0, n = "";
279
+ const i = [];
280
+ let o = "";
281
+ for (let l = 0; l < e.length; l++) {
282
+ const c = e[l];
283
+ c === "\\" ? ((e[l + 1] === '"' || e[l + 1] === "'") && l++, o += e[l]) : s === 0 ? c === '"' || c === "'" ? (s = 1, n = c) : c.match(/\s/) ? (o.trim().length && i.push(o.trim()), o = c) : i.length && !o ? o = i.pop() + c : o += c : s === 1 && (c === n ? (s = 0, n = "") : o += c);
284
+ }
285
+ return o && i.push(o.trim()), i;
286
+ }
277
287
  function createSpawnHandler(e) {
278
- return function(t) {
279
- const r = new ChildProcess(), s = new ProcessApi(r);
288
+ return function(t, r = [], s = {}) {
289
+ const n = new ChildProcess(), i = new ProcessApi(n);
280
290
  return setTimeout(async () => {
281
- await e(t, s), r.emit("spawn", !0);
282
- }), r;
291
+ let o = [];
292
+ if (r.length)
293
+ o = [t, ...r];
294
+ else if (typeof t == "string")
295
+ o = splitShellCommand(t);
296
+ else if (Array.isArray(t))
297
+ o = t;
298
+ else
299
+ throw new Error("Invalid command ", t);
300
+ await e(o, i, s), n.emit("spawn", !0);
301
+ }), n;
283
302
  };
284
303
  }
285
304
  class EventEmitter {
@@ -304,9 +323,15 @@ class ProcessApi extends EventEmitter {
304
323
  stdout(t) {
305
324
  typeof t == "string" && (t = new TextEncoder().encode(t)), this.childProcess.stdout.emit("data", t);
306
325
  }
326
+ stdoutEnd() {
327
+ this.childProcess.stdout.emit("end", {});
328
+ }
307
329
  stderr(t) {
308
330
  typeof t == "string" && (t = new TextEncoder().encode(t)), this.childProcess.stderr.emit("data", t);
309
331
  }
332
+ stderrEnd() {
333
+ this.childProcess.stderr.emit("end", {});
334
+ }
310
335
  exit(t) {
311
336
  this.exited || (this.exited = !0, this.childProcess.emit("exit", t));
312
337
  }
@@ -385,8 +410,8 @@ class PHPBrowser {
385
410
  * @param config - The browser configuration.
386
411
  */
387
412
  constructor(t, r = {}) {
388
- l(this, v, void 0);
389
- l(this, T, void 0);
413
+ u(this, v, void 0);
414
+ u(this, T, void 0);
390
415
  this.requestHandler = t, h(this, v, {}), h(this, T, {
391
416
  handleRedirects: !1,
392
417
  maxRedirects: 4,
@@ -415,7 +440,7 @@ class PHPBrowser {
415
440
  cookie: this.serializeCookies()
416
441
  }
417
442
  });
418
- if (s.headers["set-cookie"] && this.setCookies(s.headers["set-cookie"]), o(this, T).handleRedirects && s.headers.location && r < o(this, T).maxRedirects) {
443
+ if (s.headers["set-cookie"] && this.setCookies(s.headers["set-cookie"]), a(this, T).handleRedirects && s.headers.location && r < a(this, T).maxRedirects) {
419
444
  const n = new URL(
420
445
  s.headers.location[0],
421
446
  this.requestHandler.absoluteUrl
@@ -453,15 +478,15 @@ class PHPBrowser {
453
478
  if (!r.includes("="))
454
479
  continue;
455
480
  const s = r.indexOf("="), n = r.substring(0, s), i = r.substring(s + 1).split(";")[0];
456
- o(this, v)[n] = i;
481
+ a(this, v)[n] = i;
457
482
  } catch (s) {
458
483
  console.error(s);
459
484
  }
460
485
  }
461
486
  serializeCookies() {
462
487
  const t = [];
463
- for (const r in o(this, v))
464
- t.push(`${r}=${o(this, v)[r]}`);
488
+ for (const r in a(this, v))
489
+ t.push(`${r}=${a(this, v)[r]}`);
465
490
  return t.join("; ");
466
491
  }
467
492
  }
@@ -478,23 +503,23 @@ function ensurePathPrefix(e, t) {
478
503
  }
479
504
  async function encodeAsMultipart(e) {
480
505
  const t = `----${Math.random().toString(36).slice(2)}`, r = `multipart/form-data; boundary=${t}`, s = new TextEncoder(), n = [];
481
- for (const [d, p] of Object.entries(e))
506
+ for (const [c, p] of Object.entries(e))
482
507
  n.push(`--${t}\r
483
- `), n.push(`Content-Disposition: form-data; name="${d}"`), p instanceof File && n.push(`; filename="${p.name}"`), n.push(`\r
484
- `), p instanceof File && n.push("Content-Type: application/octet-stream"), n.push(`\r
485
- \r
508
+ `), n.push(`Content-Disposition: form-data; name="${c}"`), p instanceof File && n.push(`; filename="${p.name}"`), n.push(`\r
509
+ `), p instanceof File && (n.push("Content-Type: application/octet-stream"), n.push(`\r
510
+ `)), n.push(`\r
486
511
  `), p instanceof File ? n.push(await fileToUint8Array(p)) : n.push(p), n.push(`\r
487
512
  `);
488
513
  n.push(`--${t}--\r
489
514
  `);
490
- const i = n.reduce((d, p) => d + p.length, 0), a = new Uint8Array(i);
491
- let c = 0;
492
- for (const d of n)
493
- a.set(
494
- typeof d == "string" ? s.encode(d) : d,
495
- c
496
- ), c += d.length;
497
- return { bytes: a, contentType: r };
515
+ const i = n.reduce((c, p) => c + p.length, 0), o = new Uint8Array(i);
516
+ let l = 0;
517
+ for (const c of n)
518
+ o.set(
519
+ typeof c == "string" ? s.encode(c) : c,
520
+ l
521
+ ), l += c.length;
522
+ return { bytes: o, contentType: r };
498
523
  }
499
524
  function fileToUint8Array(e) {
500
525
  return new Promise((t) => {
@@ -504,7 +529,7 @@ function fileToUint8Array(e) {
504
529
  }, r.readAsArrayBuffer(e);
505
530
  });
506
531
  }
507
- var w, F, I, b, x, m, C, R, M, K, N, Z, B, Q;
532
+ var y, F, I, b, x, m, C, R, N, K, O, Z, U, X;
508
533
  class PHPRequestHandler {
509
534
  /**
510
535
  * @param php - The PHP instance.
@@ -517,7 +542,7 @@ class PHPRequestHandler {
517
542
  * @param fsPath - Absolute path of the static file to serve.
518
543
  * @returns The response.
519
544
  */
520
- l(this, M);
545
+ u(this, N);
521
546
  /**
522
547
  * Runs the requested PHP file with all the request and $_SERVER
523
548
  * superglobals populated.
@@ -525,7 +550,7 @@ class PHPRequestHandler {
525
550
  * @param request - The request.
526
551
  * @returns The response.
527
552
  */
528
- l(this, N);
553
+ u(this, O);
529
554
  /**
530
555
  * Resolve the requested path to the filesystem path of the requested PHP file.
531
556
  *
@@ -535,31 +560,31 @@ class PHPRequestHandler {
535
560
  * @throws {Error} If the requested path doesn't exist.
536
561
  * @returns The resolved filesystem path.
537
562
  */
538
- l(this, B);
539
- l(this, w, void 0);
540
- l(this, F, void 0);
541
- l(this, I, void 0);
542
- l(this, b, void 0);
543
- l(this, x, void 0);
544
- l(this, m, void 0);
545
- l(this, C, void 0);
546
- l(this, R, void 0);
563
+ u(this, U);
564
+ u(this, y, void 0);
565
+ u(this, F, void 0);
566
+ u(this, I, void 0);
567
+ u(this, b, void 0);
568
+ u(this, x, void 0);
569
+ u(this, m, void 0);
570
+ u(this, C, void 0);
571
+ u(this, R, void 0);
547
572
  h(this, R, new Semaphore({ concurrency: 1 }));
548
573
  const {
549
574
  documentRoot: s = "/www/",
550
575
  absoluteUrl: n = typeof location == "object" ? location == null ? void 0 : location.href : ""
551
576
  } = r;
552
- this.php = t, h(this, w, s);
577
+ this.php = t, h(this, y, s);
553
578
  const i = new URL(n);
554
579
  h(this, I, i.hostname), h(this, b, i.port ? Number(i.port) : i.protocol === "https:" ? 443 : 80), h(this, F, (i.protocol || "").replace(":", ""));
555
- const a = o(this, b) !== 443 && o(this, b) !== 80;
580
+ const o = a(this, b) !== 443 && a(this, b) !== 80;
556
581
  h(this, x, [
557
- o(this, I),
558
- a ? `:${o(this, b)}` : ""
582
+ a(this, I),
583
+ o ? `:${a(this, b)}` : ""
559
584
  ].join("")), h(this, m, i.pathname.replace(/\/+$/, "")), h(this, C, [
560
- `${o(this, F)}://`,
561
- o(this, x),
562
- o(this, m)
585
+ `${a(this, F)}://`,
586
+ a(this, x),
587
+ a(this, m)
563
588
  ].join(""));
564
589
  }
565
590
  /** @inheritDoc */
@@ -569,18 +594,18 @@ class PHPRequestHandler {
569
594
  /** @inheritDoc */
570
595
  internalUrlToPath(t) {
571
596
  const r = new URL(t);
572
- return r.pathname.startsWith(o(this, m)) && (r.pathname = r.pathname.slice(o(this, m).length)), toRelativeUrl(r);
597
+ return r.pathname.startsWith(a(this, m)) && (r.pathname = r.pathname.slice(a(this, m).length)), toRelativeUrl(r);
573
598
  }
574
599
  get isRequestRunning() {
575
- return o(this, R).running > 0;
600
+ return a(this, R).running > 0;
576
601
  }
577
602
  /** @inheritDoc */
578
603
  get absoluteUrl() {
579
- return o(this, C);
604
+ return a(this, C);
580
605
  }
581
606
  /** @inheritDoc */
582
607
  get documentRoot() {
583
- return o(this, w);
608
+ return a(this, y);
584
609
  }
585
610
  /** @inheritDoc */
586
611
  async request(t) {
@@ -589,12 +614,12 @@ class PHPRequestHandler {
589
614
  r ? void 0 : DEFAULT_BASE_URL
590
615
  ), n = removePathPrefix(
591
616
  s.pathname,
592
- o(this, m)
593
- ), i = `${o(this, w)}${n}`;
594
- return seemsLikeAPHPRequestHandlerPath(i) ? await f(this, N, Z).call(this, t, s) : f(this, M, K).call(this, i);
617
+ a(this, m)
618
+ ), i = `${a(this, y)}${n}`;
619
+ return seemsLikeAPHPRequestHandlerPath(i) ? await f(this, O, Z).call(this, t, s) : f(this, N, K).call(this, i);
595
620
  }
596
621
  }
597
- w = new WeakMap(), F = new WeakMap(), I = new WeakMap(), b = new WeakMap(), x = new WeakMap(), m = new WeakMap(), C = new WeakMap(), R = new WeakMap(), M = new WeakSet(), K = function(t) {
622
+ y = new WeakMap(), F = new WeakMap(), I = new WeakMap(), b = new WeakMap(), x = new WeakMap(), m = new WeakMap(), C = new WeakMap(), R = new WeakMap(), N = new WeakSet(), K = function(t) {
598
623
  if (!this.php.fileExists(t))
599
624
  return new PHPResponse(
600
625
  404,
@@ -619,9 +644,9 @@ w = new WeakMap(), F = new WeakMap(), I = new WeakMap(), b = new WeakMap(), x =
619
644
  },
620
645
  r
621
646
  );
622
- }, N = new WeakSet(), Z = async function(t, r) {
647
+ }, O = new WeakSet(), Z = async function(t, r) {
623
648
  var n, i;
624
- if (o(this, R).running > 0 && ((n = t.headers) == null ? void 0 : n["x-request-issuer"]) === "php")
649
+ if (a(this, R).running > 0 && ((n = t.headers) == null ? void 0 : n["x-request-issuer"]) === "php")
625
650
  return console.warn(
626
651
  "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."
627
652
  ), new PHPResponse(
@@ -629,34 +654,34 @@ w = new WeakMap(), F = new WeakMap(), I = new WeakMap(), b = new WeakMap(), x =
629
654
  {},
630
655
  new TextEncoder().encode("502 Bad Gateway")
631
656
  );
632
- const s = await o(this, R).acquire();
657
+ const s = await a(this, R).acquire();
633
658
  try {
634
- this.php.addServerGlobalEntry("REMOTE_ADDR", "127.0.0.1"), this.php.addServerGlobalEntry("DOCUMENT_ROOT", o(this, w)), this.php.addServerGlobalEntry(
659
+ this.php.addServerGlobalEntry("REMOTE_ADDR", "127.0.0.1"), this.php.addServerGlobalEntry("DOCUMENT_ROOT", a(this, y)), this.php.addServerGlobalEntry(
635
660
  "HTTPS",
636
- o(this, C).startsWith("https://") ? "on" : ""
661
+ a(this, C).startsWith("https://") ? "on" : ""
637
662
  );
638
- let a = "GET";
639
- const c = {
640
- host: o(this, x),
663
+ let o = "GET";
664
+ const l = {
665
+ host: a(this, x),
641
666
  ...normalizeHeaders(t.headers || {})
642
667
  };
643
- let d = t.body;
644
- if (typeof d == "object" && !(d instanceof Uint8Array)) {
645
- a = "POST";
646
- const { bytes: u, contentType: _ } = await encodeAsMultipart(d);
647
- d = u, c["content-type"] = _;
668
+ let c = t.body;
669
+ if (typeof c == "object" && !(c instanceof Uint8Array)) {
670
+ o = "POST";
671
+ const { bytes: d, contentType: _ } = await encodeAsMultipart(c);
672
+ c = d, l["content-type"] = _;
648
673
  }
649
674
  let p;
650
675
  try {
651
- let u = r.pathname;
676
+ let d = r.pathname;
652
677
  if ((i = t.headers) != null && i["x-rewrite-url"])
653
678
  try {
654
- u = new URL(
679
+ d = new URL(
655
680
  t.headers["x-rewrite-url"]
656
681
  ).pathname;
657
682
  } catch {
658
683
  }
659
- p = f(this, B, Q).call(this, u);
684
+ p = f(this, U, X).call(this, d);
660
685
  } catch {
661
686
  return new PHPResponse(
662
687
  404,
@@ -667,21 +692,21 @@ w = new WeakMap(), F = new WeakMap(), I = new WeakMap(), b = new WeakMap(), x =
667
692
  return await this.php.run({
668
693
  relativeUri: ensurePathPrefix(
669
694
  toRelativeUrl(r),
670
- o(this, m)
695
+ a(this, m)
671
696
  ),
672
- protocol: o(this, F),
673
- method: t.method || a,
674
- body: d,
697
+ protocol: a(this, F),
698
+ method: t.method || o,
699
+ body: c,
675
700
  scriptPath: p,
676
- headers: c
701
+ headers: l
677
702
  });
678
703
  } finally {
679
704
  s();
680
705
  }
681
- }, B = new WeakSet(), Q = function(t) {
682
- let r = removePathPrefix(t, o(this, m));
683
- r.includes(".php") ? r = r.split(".php")[0] + ".php" : (r.endsWith("/") || (r += "/"), r.endsWith("index.php") || (r += "index.php"));
684
- const s = `${o(this, w)}${r}`;
706
+ }, U = new WeakSet(), X = function(t) {
707
+ let r = removePathPrefix(t, a(this, m));
708
+ r.includes(".php") ? r = r.split(".php")[0] + ".php" : this.php.isDir(`${a(this, y)}${r}`) ? (r.endsWith("/") || (r = `${r}/`), r = `${r}index.php`) : r = "/index.php";
709
+ const s = `${a(this, y)}${r}`;
685
710
  if (this.php.fileExists(s))
686
711
  return s;
687
712
  throw new Error(`File not found: ${s}`);
@@ -822,18 +847,18 @@ function getEmscriptenFsError(e) {
822
847
  function rethrowFileSystemError(e = "") {
823
848
  return function(r, s, n) {
824
849
  const i = n.value;
825
- n.value = function(...a) {
850
+ n.value = function(...o) {
826
851
  try {
827
- return i.apply(this, a);
828
- } catch (c) {
829
- const d = typeof c == "object" ? c == null ? void 0 : c.errno : null;
830
- if (d in FileErrorCodes) {
831
- const p = FileErrorCodes[d], u = typeof a[0] == "string" ? a[0] : null, _ = u !== null ? e.replaceAll("{path}", u) : e;
852
+ return i.apply(this, o);
853
+ } catch (l) {
854
+ const c = typeof l == "object" ? l == null ? void 0 : l.errno : null;
855
+ if (c in FileErrorCodes) {
856
+ const p = FileErrorCodes[c], d = typeof o[0] == "string" ? o[0] : null, _ = d !== null ? e.replaceAll("{path}", d) : e;
832
857
  throw new Error(`${_}: ${p}`, {
833
- cause: c
858
+ cause: l
834
859
  });
835
860
  }
836
- throw c;
861
+ throw l;
837
862
  }
838
863
  };
839
864
  };
@@ -847,12 +872,12 @@ function getLoadedRuntime(e) {
847
872
  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";
848
873
  })();
849
874
  var __defProp = Object.defineProperty, __getOwnPropDesc = Object.getOwnPropertyDescriptor, __decorateClass = (e, t, r, s) => {
850
- for (var n = s > 1 ? void 0 : s ? __getOwnPropDesc(t, r) : t, i = e.length - 1, a; i >= 0; i--)
851
- (a = e[i]) && (n = (s ? a(t, r, n) : a(n)) || n);
875
+ for (var n = s > 1 ? void 0 : s ? __getOwnPropDesc(t, r) : t, i = e.length - 1, o; i >= 0; i--)
876
+ (o = e[i]) && (n = (s ? o(t, r, n) : o(n)) || n);
852
877
  return s && n && __defProp(t, r, n), n;
853
878
  };
854
879
  const STRING = "string", NUMBER = "number", __private__dont__use = Symbol("__private__dont__use");
855
- var S, k, A, y, E, P, g, H, L, X, U, ee, O, te, q, re, $, se, D, ne, W, ie, j, oe, z, ae, G, le, J, ce;
880
+ var S, A, k, E, g, P, w, H, M, ee, B, te, L, re, $, se, D, ne, q, ie, W, oe, j, ae, z, le, G, ce, J, ue, Q, de;
856
881
  class BasePHP {
857
882
  /**
858
883
  * Initializes a PHP runtime.
@@ -862,45 +887,46 @@ class BasePHP {
862
887
  * @param serverOptions - Optional. Options for the PHPRequestHandler. If undefined, no request handler will be initialized.
863
888
  */
864
889
  constructor(e, t) {
865
- l(this, L);
866
- l(this, U);
867
- l(this, O);
868
- l(this, q);
869
- l(this, $);
870
- l(this, D);
871
- l(this, W);
872
- l(this, j);
873
- l(this, z);
874
- l(this, G);
875
- l(this, J);
876
- l(this, S, void 0);
877
- l(this, k, void 0);
878
- l(this, A, void 0);
879
- l(this, y, void 0);
880
- l(this, E, void 0);
881
- l(this, P, void 0);
882
- l(this, g, void 0);
883
- l(this, H, void 0);
884
- h(this, S, []), h(this, y, !1), h(this, E, null), h(this, P, {}), h(this, g, /* @__PURE__ */ new Map()), h(this, H, []), this.semaphore = new Semaphore({ concurrency: 1 }), e !== void 0 && this.initializeRuntime(e), t && (this.requestHandler = new PHPBrowser(
890
+ u(this, M);
891
+ u(this, B);
892
+ u(this, L);
893
+ u(this, $);
894
+ u(this, D);
895
+ u(this, q);
896
+ u(this, W);
897
+ u(this, j);
898
+ u(this, z);
899
+ u(this, G);
900
+ u(this, J);
901
+ u(this, Q);
902
+ u(this, S, void 0);
903
+ u(this, A, void 0);
904
+ u(this, k, void 0);
905
+ u(this, E, void 0);
906
+ u(this, g, void 0);
907
+ u(this, P, void 0);
908
+ u(this, w, void 0);
909
+ u(this, H, void 0);
910
+ h(this, S, []), h(this, E, !1), h(this, g, null), h(this, P, {}), h(this, w, /* @__PURE__ */ new Map()), h(this, H, []), this.semaphore = new Semaphore({ concurrency: 1 }), e !== void 0 && this.initializeRuntime(e), t && (this.requestHandler = new PHPBrowser(
885
911
  new PHPRequestHandler(this, t)
886
912
  ));
887
913
  }
888
914
  addEventListener(e, t) {
889
- o(this, g).has(e) || o(this, g).set(e, /* @__PURE__ */ new Set()), o(this, g).get(e).add(t);
915
+ a(this, w).has(e) || a(this, w).set(e, /* @__PURE__ */ new Set()), a(this, w).get(e).add(t);
890
916
  }
891
917
  removeEventListener(e, t) {
892
918
  var r;
893
- (r = o(this, g).get(e)) == null || r.delete(t);
919
+ (r = a(this, w).get(e)) == null || r.delete(t);
894
920
  }
895
921
  dispatchEvent(e) {
896
- const t = o(this, g).get(e.type);
922
+ const t = a(this, w).get(e.type);
897
923
  if (t)
898
924
  for (const r of t)
899
925
  r(e);
900
926
  }
901
927
  /** @inheritDoc */
902
928
  async onMessage(e) {
903
- o(this, H).push(e);
929
+ a(this, H).push(e);
904
930
  }
905
931
  /** @inheritDoc */
906
932
  async setSpawnHandler(handler) {
@@ -931,13 +957,13 @@ class BasePHP {
931
957
  if (!t)
932
958
  throw new Error("Invalid PHP runtime id.");
933
959
  this[__private__dont__use] = t, t.onMessage = async (r) => {
934
- for (const s of o(this, H)) {
960
+ for (const s of a(this, H)) {
935
961
  const n = await s(r);
936
962
  if (n)
937
963
  return n;
938
964
  }
939
965
  return "";
940
- }, h(this, E, improveWASMErrorReporting(t)), this.dispatchEvent({
966
+ }, h(this, g, improveWASMErrorReporting(t)), this.dispatchEvent({
941
967
  type: "runtime.initialized"
942
968
  });
943
969
  }
@@ -952,13 +978,13 @@ class BasePHP {
952
978
  throw new Error(
953
979
  "Could not set SAPI name. This can only be done before the PHP WASM module is initialized.Did you already dispatch any requests?"
954
980
  );
955
- h(this, A, e);
981
+ h(this, k, e);
956
982
  }
957
983
  /** @inheritDoc */
958
984
  setPhpIniPath(e) {
959
- if (o(this, y))
985
+ if (a(this, E))
960
986
  throw new Error("Cannot set PHP ini path after calling run().");
961
- h(this, k, e), this[__private__dont__use].ccall(
987
+ h(this, A, e), this[__private__dont__use].ccall(
962
988
  "wasm_set_phpini_path",
963
989
  null,
964
990
  ["string"],
@@ -967,9 +993,9 @@ class BasePHP {
967
993
  }
968
994
  /** @inheritDoc */
969
995
  setPhpIniEntry(e, t) {
970
- if (o(this, y))
996
+ if (a(this, E))
971
997
  throw new Error("Cannot set PHP ini entries after calling run().");
972
- o(this, S).push([e, t]);
998
+ a(this, S).push([e, t]);
973
999
  }
974
1000
  /** @inheritDoc */
975
1001
  chdir(e) {
@@ -986,22 +1012,29 @@ class BasePHP {
986
1012
  const t = await this.semaphore.acquire();
987
1013
  let r;
988
1014
  try {
989
- o(this, y) || (f(this, L, X).call(this), h(this, y, !0)), f(this, j, oe).call(this, e.scriptPath || ""), f(this, O, te).call(this, e.relativeUri || ""), f(this, $, se).call(this, e.method || "GET");
1015
+ if (a(this, E) || (f(this, M, ee).call(this), h(this, E, !0)), e.scriptPath && !this.fileExists(e.scriptPath))
1016
+ throw new Error(
1017
+ `The script path "${e.scriptPath}" does not exist.`
1018
+ );
1019
+ f(this, j, ae).call(this, e.scriptPath || ""), f(this, L, re).call(this, e.relativeUri || ""), f(this, D, ne).call(this, e.method || "GET");
990
1020
  const s = normalizeHeaders(e.headers || {}), n = s.host || "example.com:443";
991
- f(this, q, re).call(this, n, e.protocol || "http"), f(this, D, ne).call(this, s), e.body && (r = f(this, W, ie).call(this, e.body)), typeof e.code == "string" && f(this, G, le).call(this, " ?>" + e.code), f(this, z, ae).call(this);
992
- const i = await f(this, J, ce).call(this);
993
- if (e.throwOnError && i.exitCode !== 0) {
994
- const a = {
995
- stdout: i.text,
996
- stderr: i.errors
1021
+ f(this, $, se).call(this, n, e.protocol || "http"), f(this, q, ie).call(this, s), e.body && (r = f(this, W, oe).call(this, e.body)), typeof e.code == "string" && f(this, J, ue).call(this, " ?>" + e.code), f(this, z, le).call(this);
1022
+ const i = e.env || {};
1023
+ for (const l in i)
1024
+ f(this, G, ce).call(this, l, i[l]);
1025
+ const o = await f(this, Q, de).call(this);
1026
+ if (e.throwOnError && o.exitCode !== 0) {
1027
+ const l = {
1028
+ stdout: o.text,
1029
+ stderr: o.errors
997
1030
  };
998
- console.warn("PHP.run() output was:", a);
1031
+ console.warn("PHP.run() output was:", l);
999
1032
  const c = new Error(
1000
- `PHP.run() failed with exit code ${i.exitCode} and the following output`
1033
+ `PHP.run() failed with exit code ${o.exitCode} and the following output: ` + o.errors
1001
1034
  );
1002
- throw c.output = a, c;
1035
+ throw c.output = l, console.error(c), c;
1003
1036
  }
1004
- return i;
1037
+ return o;
1005
1038
  } finally {
1006
1039
  try {
1007
1040
  r && this[__private__dont__use].free(r);
@@ -1013,18 +1046,18 @@ class BasePHP {
1013
1046
  }
1014
1047
  }
1015
1048
  addServerGlobalEntry(e, t) {
1016
- o(this, P)[e] = t;
1049
+ a(this, P)[e] = t;
1017
1050
  }
1018
1051
  defineConstant(e, t) {
1019
1052
  let r = {};
1020
1053
  try {
1021
1054
  r = JSON.parse(
1022
- this.fileExists("/tmp/consts.json") && this.readFileAsText("/tmp/consts.json") || "{}"
1055
+ this.fileExists("/internal/consts.json") && this.readFileAsText("/internal/consts.json") || "{}"
1023
1056
  );
1024
1057
  } catch {
1025
1058
  }
1026
1059
  this.writeFile(
1027
- "/tmp/consts.json",
1060
+ "/internal/consts.json",
1028
1061
  JSON.stringify({
1029
1062
  ...r,
1030
1063
  [e]: t
@@ -1109,9 +1142,9 @@ class BasePHP {
1109
1142
  this.exit();
1110
1143
  } catch {
1111
1144
  }
1112
- if (this.initializeRuntime(e), o(this, k) && this.setPhpIniPath(o(this, k)), o(this, A) && this.setSapiName(o(this, A)), this.requestHandler) {
1145
+ if (this.initializeRuntime(e), a(this, A) && this.setPhpIniPath(a(this, A)), a(this, k) && this.setSapiName(a(this, k)), this.requestHandler) {
1113
1146
  const r = this.documentRoot;
1114
- recreateMemFS(this[__private__dont__use].FS, t, r);
1147
+ copyFS(t, this[__private__dont__use].FS, r);
1115
1148
  }
1116
1149
  }
1117
1150
  exit(e = 0) {
@@ -1122,23 +1155,23 @@ class BasePHP {
1122
1155
  this[__private__dont__use]._exit(e);
1123
1156
  } catch {
1124
1157
  }
1125
- h(this, y, !1), h(this, E, null), delete this[__private__dont__use].onMessage, delete this[__private__dont__use];
1158
+ h(this, E, !1), h(this, g, null), delete this[__private__dont__use].onMessage, delete this[__private__dont__use];
1126
1159
  }
1127
1160
  }
1128
- S = new WeakMap(), k = new WeakMap(), A = new WeakMap(), y = new WeakMap(), E = new WeakMap(), P = new WeakMap(), g = new WeakMap(), H = new WeakMap(), L = new WeakSet(), X = function() {
1129
- if (this.setPhpIniEntry("auto_prepend_file", "/tmp/consts.php"), this.fileExists("/tmp/consts.php") || this.writeFile(
1130
- "/tmp/consts.php",
1161
+ S = new WeakMap(), A = new WeakMap(), k = new WeakMap(), E = new WeakMap(), g = new WeakMap(), P = new WeakMap(), w = new WeakMap(), H = new WeakMap(), M = new WeakSet(), ee = function() {
1162
+ if (this.setPhpIniEntry("auto_prepend_file", "/internal/consts.php"), this.fileExists("/internal/consts.php") || this.writeFile(
1163
+ "/internal/consts.php",
1131
1164
  `<?php
1132
- if(file_exists('/tmp/consts.json')) {
1133
- $consts = json_decode(file_get_contents('/tmp/consts.json'), true);
1165
+ if(file_exists('/internal/consts.json')) {
1166
+ $consts = json_decode(file_get_contents('/internal/consts.json'), true);
1134
1167
  foreach ($consts as $const => $value) {
1135
1168
  if (!defined($const) && is_scalar($value)) {
1136
1169
  define($const, $value);
1137
1170
  }
1138
1171
  }
1139
1172
  }`
1140
- ), o(this, S).length > 0) {
1141
- const e = o(this, S).map(([t, r]) => `${t}=${r}`).join(`
1173
+ ), a(this, S).length > 0) {
1174
+ const e = a(this, S).map(([t, r]) => `${t}=${r}`).join(`
1142
1175
  `) + `
1143
1176
 
1144
1177
  `;
@@ -1150,8 +1183,8 @@ S = new WeakMap(), k = new WeakMap(), A = new WeakMap(), y = new WeakMap(), E =
1150
1183
  );
1151
1184
  }
1152
1185
  this[__private__dont__use].ccall("php_wasm_init", null, [], []);
1153
- }, U = new WeakSet(), ee = function() {
1154
- const e = "/tmp/headers.json";
1186
+ }, B = new WeakSet(), te = function() {
1187
+ const e = "/internal/headers.json";
1155
1188
  if (!this.fileExists(e))
1156
1189
  throw new Error(
1157
1190
  "SAPI Error: Could not find response headers file."
@@ -1160,14 +1193,14 @@ S = new WeakMap(), k = new WeakMap(), A = new WeakMap(), y = new WeakMap(), E =
1160
1193
  for (const s of t.headers) {
1161
1194
  if (!s.includes(": "))
1162
1195
  continue;
1163
- const n = s.indexOf(": "), i = s.substring(0, n).toLowerCase(), a = s.substring(n + 2);
1164
- i in r || (r[i] = []), r[i].push(a);
1196
+ const n = s.indexOf(": "), i = s.substring(0, n).toLowerCase(), o = s.substring(n + 2);
1197
+ i in r || (r[i] = []), r[i].push(o);
1165
1198
  }
1166
1199
  return {
1167
1200
  headers: r,
1168
1201
  httpStatusCode: t.status
1169
1202
  };
1170
- }, O = new WeakSet(), te = function(e) {
1203
+ }, L = new WeakSet(), re = function(e) {
1171
1204
  if (this[__private__dont__use].ccall(
1172
1205
  "wasm_set_request_uri",
1173
1206
  null,
@@ -1182,7 +1215,7 @@ S = new WeakMap(), k = new WeakMap(), A = new WeakMap(), y = new WeakMap(), E =
1182
1215
  [t]
1183
1216
  );
1184
1217
  }
1185
- }, q = new WeakSet(), re = function(e, t) {
1218
+ }, $ = new WeakSet(), se = function(e, t) {
1186
1219
  this[__private__dont__use].ccall(
1187
1220
  "wasm_set_request_host",
1188
1221
  null,
@@ -1200,14 +1233,14 @@ S = new WeakMap(), k = new WeakMap(), A = new WeakMap(), y = new WeakMap(), E =
1200
1233
  [NUMBER],
1201
1234
  [r]
1202
1235
  ), (t === "https" || !t && r === 443) && this.addServerGlobalEntry("HTTPS", "on");
1203
- }, $ = new WeakSet(), se = function(e) {
1236
+ }, D = new WeakSet(), ne = function(e) {
1204
1237
  this[__private__dont__use].ccall(
1205
1238
  "wasm_set_request_method",
1206
1239
  null,
1207
1240
  [STRING],
1208
1241
  [e]
1209
1242
  );
1210
- }, D = new WeakSet(), ne = function(e) {
1243
+ }, q = new WeakSet(), ie = function(e) {
1211
1244
  e.cookie && this[__private__dont__use].ccall(
1212
1245
  "wasm_set_cookies",
1213
1246
  null,
@@ -1231,7 +1264,7 @@ S = new WeakMap(), k = new WeakMap(), A = new WeakMap(), y = new WeakMap(), E =
1231
1264
  e[t]
1232
1265
  );
1233
1266
  }
1234
- }, W = new WeakSet(), ie = function(e) {
1267
+ }, W = new WeakSet(), oe = function(e) {
1235
1268
  let t, r;
1236
1269
  typeof e == "string" ? (console.warn(
1237
1270
  "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"
@@ -1254,49 +1287,57 @@ S = new WeakMap(), k = new WeakMap(), A = new WeakMap(), y = new WeakMap(), E =
1254
1287
  [NUMBER],
1255
1288
  [r]
1256
1289
  ), s;
1257
- }, j = new WeakSet(), oe = function(e) {
1290
+ }, j = new WeakSet(), ae = function(e) {
1258
1291
  this[__private__dont__use].ccall(
1259
1292
  "wasm_set_path_translated",
1260
1293
  null,
1261
1294
  [STRING],
1262
1295
  [e]
1263
1296
  );
1264
- }, z = new WeakSet(), ae = function() {
1265
- for (const e in o(this, P))
1297
+ }, z = new WeakSet(), le = function() {
1298
+ for (const e in a(this, P))
1266
1299
  this[__private__dont__use].ccall(
1267
1300
  "wasm_add_SERVER_entry",
1268
1301
  null,
1269
1302
  [STRING, STRING],
1270
- [e, o(this, P)[e]]
1303
+ [e, a(this, P)[e]]
1271
1304
  );
1272
- }, G = new WeakSet(), le = function(e) {
1305
+ }, G = new WeakSet(), ce = function(e, t) {
1306
+ this[__private__dont__use].ccall(
1307
+ "wasm_add_ENV_entry",
1308
+ null,
1309
+ [STRING, STRING],
1310
+ [e, t]
1311
+ );
1312
+ }, J = new WeakSet(), ue = function(e) {
1273
1313
  this[__private__dont__use].ccall(
1274
1314
  "wasm_set_php_code",
1275
1315
  null,
1276
1316
  [STRING],
1277
1317
  [e]
1278
1318
  );
1279
- }, J = new WeakSet(), ce = async function() {
1319
+ }, Q = new WeakSet(), de = async function() {
1280
1320
  var n;
1281
1321
  let e, t;
1282
1322
  try {
1283
- e = await new Promise((i, a) => {
1284
- var d;
1323
+ e = await new Promise((i, o) => {
1324
+ var c;
1285
1325
  t = (p) => {
1286
- const u = new Error("Rethrown");
1287
- u.cause = p.error, u.betterMessage = p.message, a(u);
1288
- }, (d = o(this, E)) == null || d.addEventListener(
1326
+ console.error(p), console.error(p.error);
1327
+ const d = new Error("Rethrown");
1328
+ d.cause = p.error, d.betterMessage = p.message, o(d);
1329
+ }, (c = a(this, g)) == null || c.addEventListener(
1289
1330
  "error",
1290
1331
  t
1291
1332
  );
1292
- const c = this[__private__dont__use].ccall(
1333
+ const l = this[__private__dont__use].ccall(
1293
1334
  "wasm_sapi_handle_request",
1294
1335
  NUMBER,
1295
1336
  [],
1296
1337
  [],
1297
1338
  { async: !0 }
1298
1339
  );
1299
- return c instanceof Promise ? c.then(i, a) : i(c);
1340
+ return l instanceof Promise ? l.then(i, o) : i(l);
1300
1341
  });
1301
1342
  } catch (i) {
1302
1343
  for (const p in this)
@@ -1306,17 +1347,17 @@ S = new WeakMap(), k = new WeakMap(), A = new WeakMap(), y = new WeakMap(), E =
1306
1347
  );
1307
1348
  });
1308
1349
  this.functionsMaybeMissingFromAsyncify = getFunctionsMaybeMissingFromAsyncify();
1309
- const a = i, c = "betterMessage" in a ? a.betterMessage : a.message, d = new Error(c);
1310
- throw d.cause = a, d;
1350
+ const o = i, l = "betterMessage" in o ? o.betterMessage : o.message, c = new Error(l);
1351
+ throw c.cause = o, console.error(c), c;
1311
1352
  } finally {
1312
- (n = o(this, E)) == null || n.removeEventListener("error", t), h(this, P, {});
1353
+ (n = a(this, g)) == null || n.removeEventListener("error", t), h(this, P, {});
1313
1354
  }
1314
- const { headers: r, httpStatusCode: s } = f(this, U, ee).call(this);
1355
+ const { headers: r, httpStatusCode: s } = f(this, B, te).call(this);
1315
1356
  return new PHPResponse(
1316
1357
  s,
1317
1358
  r,
1318
- this.readFileAsBuffer("/tmp/stdout"),
1319
- this.readFileAsText("/tmp/stderr"),
1359
+ this.readFileAsBuffer("/internal/stdout"),
1360
+ this.readFileAsText("/internal/stderr"),
1320
1361
  e
1321
1362
  );
1322
1363
  };
@@ -1356,60 +1397,55 @@ function normalizeHeaders(e) {
1356
1397
  t[r.toLowerCase()] = e[r];
1357
1398
  return t;
1358
1399
  }
1359
- function recreateMemFS(e, t, r) {
1400
+ function copyFS(e, t, r) {
1360
1401
  let s;
1361
1402
  try {
1362
- s = t.lookupPath(r);
1403
+ s = e.lookupPath(r);
1363
1404
  } catch {
1364
1405
  return;
1365
1406
  }
1366
1407
  if (!("contents" in s.node))
1367
1408
  return;
1368
- try {
1369
- e = e.lookupPath(r);
1370
- return;
1371
- } catch {
1372
- }
1373
- if (!t.isDir(s.node.mode)) {
1374
- e.writeFile(r, t.readFile(r));
1409
+ if (!e.isDir(s.node.mode)) {
1410
+ t.writeFile(r, e.readFile(r));
1375
1411
  return;
1376
1412
  }
1377
- e.mkdirTree(r);
1378
- const n = t.readdir(r).filter((i) => i !== "." && i !== "..");
1413
+ t.mkdirTree(r);
1414
+ const n = e.readdir(r).filter((i) => i !== "." && i !== "..");
1379
1415
  for (const i of n)
1380
- recreateMemFS(e, t, joinPaths(r, i));
1416
+ copyFS(e, t, joinPaths(r, i));
1381
1417
  }
1382
1418
  function journalFSEvents(e, t, r = () => {
1383
1419
  }) {
1384
1420
  function s() {
1385
1421
  t = normalizePath(t);
1386
- const i = e[__private__dont__use].FS, a = createFSHooks(i, (u) => {
1387
- if (u.path.startsWith(t))
1388
- r(u);
1389
- else if (u.operation === "RENAME" && u.toPath.startsWith(t))
1422
+ const i = e[__private__dont__use].FS, o = createFSHooks(i, (d) => {
1423
+ if (d.path.startsWith(t))
1424
+ r(d);
1425
+ else if (d.operation === "RENAME" && d.toPath.startsWith(t))
1390
1426
  for (const _ of recordExistingPath(
1391
1427
  e,
1392
- u.path,
1393
- u.toPath
1428
+ d.path,
1429
+ d.toPath
1394
1430
  ))
1395
1431
  r(_);
1396
- }), c = {};
1397
- for (const [u] of Object.entries(a))
1398
- c[u] = i[u];
1399
- function d() {
1400
- for (const [u, _] of Object.entries(a))
1401
- i[u] = function(...V) {
1402
- return _(...V), c[u].apply(this, V);
1432
+ }), l = {};
1433
+ for (const [d] of Object.entries(o))
1434
+ l[d] = i[d];
1435
+ function c() {
1436
+ for (const [d, _] of Object.entries(o))
1437
+ i[d] = function(...V) {
1438
+ return _(...V), l[d].apply(this, V);
1403
1439
  };
1404
1440
  }
1405
1441
  function p() {
1406
- for (const [u, _] of Object.entries(c))
1407
- e[__private__dont__use].FS[u] = _;
1442
+ for (const [d, _] of Object.entries(l))
1443
+ e[__private__dont__use].FS[d] = _;
1408
1444
  }
1409
1445
  e[__private__dont__use].journal = {
1410
- bind: d,
1446
+ bind: c,
1411
1447
  unbind: p
1412
- }, d();
1448
+ }, c();
1413
1449
  }
1414
1450
  e.addEventListener("runtime.initialized", s), e[__private__dont__use] && s();
1415
1451
  function n() {
@@ -1526,29 +1562,29 @@ function normalizeFilesystemOperations(e) {
1526
1562
  const n = checkRelationship(e[r], e[s]);
1527
1563
  if (n === "none")
1528
1564
  continue;
1529
- const i = e[r], a = e[s];
1530
- if (i.operation === "RENAME" && a.operation === "RENAME") {
1565
+ const i = e[r], o = e[s];
1566
+ if (i.operation === "RENAME" && o.operation === "RENAME") {
1531
1567
  console.warn(
1532
1568
  "[FS Journal] Normalizing a double rename is not yet supported:",
1533
1569
  {
1534
1570
  current: i,
1535
- last: a
1571
+ last: o
1536
1572
  }
1537
1573
  );
1538
1574
  continue;
1539
1575
  }
1540
- (a.operation === "CREATE" || a.operation === "WRITE") && (i.operation === "RENAME" ? n === "same_node" ? (t[s] = [], t[r] = [
1576
+ (o.operation === "CREATE" || o.operation === "WRITE") && (i.operation === "RENAME" ? n === "same_node" ? (t[s] = [], t[r] = [
1541
1577
  {
1542
- ...a,
1578
+ ...o,
1543
1579
  path: i.toPath
1544
1580
  },
1545
1581
  ...t[r] || []
1546
1582
  ]) : n === "descendant" && (t[s] = [], t[r] = [
1547
1583
  {
1548
- ...a,
1584
+ ...o,
1549
1585
  path: joinPaths(
1550
1586
  i.toPath,
1551
- a.path.substring(i.path.length)
1587
+ o.path.substring(i.path.length)
1552
1588
  )
1553
1589
  },
1554
1590
  ...t[r] || []
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@php-wasm/fs-journal",
3
- "version": "0.6.3",
3
+ "version": "0.6.4",
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": "0a8916ec08aa5f02de5fea308b287171e7948e4b",
39
+ "gitHead": "8b74852e9701f5083b367f9a294f34200230ce79",
40
40
  "engines": {
41
41
  "node": ">=18.18.2",
42
42
  "npm": ">=8.11.0"