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