@php-wasm/web 0.5.6 → 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.
Files changed (40) hide show
  1. package/__vite-browser-external-2447137e.js +4 -0
  2. package/index.d.ts +64 -31
  3. package/index.js +1043 -876
  4. package/kitchen-sink/7_0_33/php_7_0.wasm +0 -0
  5. package/kitchen-sink/7_1_30/php_7_1.wasm +0 -0
  6. package/kitchen-sink/7_2_34/php_7_2.wasm +0 -0
  7. package/kitchen-sink/7_3_33/php_7_3.wasm +0 -0
  8. package/kitchen-sink/7_4_33/php_7_4.wasm +0 -0
  9. package/kitchen-sink/8_0_30/php_8_0.wasm +0 -0
  10. package/kitchen-sink/8_1_23/php_8_1.wasm +0 -0
  11. package/kitchen-sink/8_2_10/php_8_2.wasm +0 -0
  12. package/kitchen-sink/8_3_0/php_8_3.wasm +0 -0
  13. package/kitchen-sink/php_7_0.js +6 -3
  14. package/kitchen-sink/php_7_1.js +6 -3
  15. package/kitchen-sink/php_7_2.js +6 -3
  16. package/kitchen-sink/php_7_3.js +6 -3
  17. package/kitchen-sink/php_7_4.js +6 -3
  18. package/kitchen-sink/php_8_0.js +6 -3
  19. package/kitchen-sink/php_8_1.js +6 -3
  20. package/kitchen-sink/php_8_2.js +6 -3
  21. package/kitchen-sink/php_8_3.js +6 -3
  22. package/light/7_0_33/php_7_0.wasm +0 -0
  23. package/light/7_1_30/php_7_1.wasm +0 -0
  24. package/light/7_2_34/php_7_2.wasm +0 -0
  25. package/light/7_3_33/php_7_3.wasm +0 -0
  26. package/light/7_4_33/php_7_4.wasm +0 -0
  27. package/light/8_0_30/php_8_0.wasm +0 -0
  28. package/light/8_1_23/php_8_1.wasm +0 -0
  29. package/light/8_2_10/php_8_2.wasm +0 -0
  30. package/light/8_3_0/php_8_3.wasm +0 -0
  31. package/light/php_7_0.js +6 -3
  32. package/light/php_7_1.js +6 -3
  33. package/light/php_7_2.js +6 -3
  34. package/light/php_7_3.js +6 -3
  35. package/light/php_7_4.js +6 -3
  36. package/light/php_8_0.js +6 -3
  37. package/light/php_8_1.js +6 -3
  38. package/light/php_8_2.js +6 -3
  39. package/light/php_8_3.js +6 -3
  40. package/package.json +5 -5
package/index.js CHANGED
@@ -1,74 +1,77 @@
1
- var me = (t, e, r) => {
2
- if (!e.has(t))
1
+ var Q = (e, t, r) => {
2
+ if (!t.has(e))
3
3
  throw TypeError("Cannot " + r);
4
4
  };
5
- var c = (t, e, r) => (me(t, e, "read from private field"), r ? r.call(t) : e.get(t)), d = (t, e, r) => {
6
- if (e.has(t))
5
+ var l = (e, t, r) => (Q(e, t, "read from private field"), r ? r.call(e) : t.get(e)), d = (e, t, r) => {
6
+ if (t.has(e))
7
7
  throw TypeError("Cannot add the same private member more than once");
8
- e instanceof WeakSet ? e.add(t) : e.set(t, r);
9
- }, y = (t, e, r, n) => (me(t, e, "write to private field"), n ? n.call(t, r) : e.set(t, r), r);
10
- var g = (t, e, r) => (me(t, e, "access private method"), r);
8
+ t instanceof WeakSet ? t.add(e) : t.set(e, r);
9
+ }, p = (e, t, r, s) => (Q(e, t, "write to private field"), s ? s.call(e, r) : t.set(e, r), r);
10
+ var m = (e, t, r) => (Q(e, t, "access private method"), r);
11
11
  if (typeof File > "u") {
12
- class t extends Blob {
13
- constructor(r, n, s) {
12
+ class e extends Blob {
13
+ constructor(r, s, i) {
14
14
  super(r);
15
- let o;
16
- s != null && s.lastModified && (o = /* @__PURE__ */ new Date()), (!o || isNaN(o.getFullYear())) && (o = /* @__PURE__ */ new Date()), this.lastModifiedDate = o, this.lastModified = o.getMilliseconds(), this.name = n || "";
15
+ let n;
16
+ i != null && i.lastModified && (n = /* @__PURE__ */ new Date()), (!n || isNaN(n.getFullYear())) && (n = /* @__PURE__ */ new Date()), this.lastModifiedDate = n, this.lastModified = n.getMilliseconds(), this.name = s || "";
17
17
  }
18
18
  }
19
- global.File = t;
19
+ global.File = e;
20
20
  }
21
- function Me(t) {
22
- return new Promise(function(e, r) {
23
- t.onload = t.onerror = function(n) {
24
- t.onload = t.onerror = null, n.type === "load" ? e(t.result) : r(new Error("Failed to read the blob/file"));
21
+ function asPromise(e) {
22
+ return new Promise(function(t, r) {
23
+ e.onload = e.onerror = function(s) {
24
+ e.onload = e.onerror = null, s.type === "load" ? t(e.result) : r(new Error("Failed to read the blob/file"));
25
25
  };
26
26
  });
27
27
  }
28
28
  typeof Blob.prototype.arrayBuffer > "u" && (Blob.prototype.arrayBuffer = function() {
29
- const e = new FileReader();
30
- return e.readAsArrayBuffer(this), Me(e);
29
+ const t = new FileReader();
30
+ return t.readAsArrayBuffer(this), asPromise(t);
31
31
  });
32
32
  typeof Blob.prototype.text > "u" && (Blob.prototype.text = function() {
33
- const e = new FileReader();
34
- return e.readAsText(this), Me(e);
33
+ const t = new FileReader();
34
+ return t.readAsText(this), asPromise(t);
35
35
  });
36
- function ot() {
37
- const t = new Uint8Array([1, 2, 3, 4]), r = new File([t], "test").stream();
36
+ function isByobSupported() {
37
+ const e = new Uint8Array([1, 2, 3, 4]), r = new File([e], "test").stream();
38
38
  try {
39
39
  return r.getReader({ mode: "byob" }), !0;
40
40
  } catch {
41
41
  return !1;
42
42
  }
43
43
  }
44
- (typeof Blob.prototype.stream > "u" || !ot()) && (Blob.prototype.stream = function() {
45
- let t = 0;
46
- const e = this;
44
+ (typeof Blob.prototype.stream > "u" || !isByobSupported()) && (Blob.prototype.stream = function() {
45
+ let e = 0;
46
+ const t = this;
47
47
  return new ReadableStream({
48
48
  type: "bytes",
49
49
  // 0.5 MB seems like a reasonable chunk size, let's adjust
50
50
  // this if needed.
51
51
  autoAllocateChunkSize: 512 * 1024,
52
52
  async pull(r) {
53
- const n = r.byobRequest.view, o = await e.slice(t, t + n.byteLength).arrayBuffer(), i = new Uint8Array(o);
54
- new Uint8Array(n.buffer).set(i);
55
- const a = i.byteLength;
56
- r.byobRequest.respond(a), t += a, t >= e.size && r.close();
53
+ const s = r.byobRequest.view, n = await t.slice(e, e + s.byteLength).arrayBuffer(), o = new Uint8Array(n);
54
+ new Uint8Array(s.buffer).set(o);
55
+ const a = o.byteLength;
56
+ r.byobRequest.respond(a), e += a, e >= t.size && r.close();
57
57
  }
58
58
  });
59
59
  });
60
60
  if (typeof CustomEvent > "u") {
61
- class t extends Event {
62
- constructor(r, n = {}) {
63
- super(r, n), this.detail = n.detail;
61
+ class e extends Event {
62
+ constructor(r, s = {}) {
63
+ super(r, s), this.detail = s.detail;
64
64
  }
65
65
  initCustomEvent() {
66
66
  }
67
67
  }
68
- globalThis.CustomEvent = t;
68
+ globalThis.CustomEvent = e;
69
69
  }
70
- const Re = Symbol("error"), xe = Symbol("message");
71
- class Pe extends Event {
70
+ typeof crypto > "u" && import("./__vite-browser-external-2447137e.js").then((e) => {
71
+ global.crypto = e;
72
+ });
73
+ const kError = Symbol("error"), kMessage = Symbol("message");
74
+ class ErrorEvent2 extends Event {
72
75
  /**
73
76
  * Create a new `ErrorEvent`.
74
77
  *
@@ -76,93 +79,93 @@ class Pe extends Event {
76
79
  * @param options A dictionary object that allows for setting
77
80
  * attributes via object members of the same name.
78
81
  */
79
- constructor(e, r = {}) {
80
- super(e), this[Re] = r.error === void 0 ? null : r.error, this[xe] = r.message === void 0 ? "" : r.message;
82
+ constructor(t, r = {}) {
83
+ super(t), this[kError] = r.error === void 0 ? null : r.error, this[kMessage] = r.message === void 0 ? "" : r.message;
81
84
  }
82
85
  get error() {
83
- return this[Re];
86
+ return this[kError];
84
87
  }
85
88
  get message() {
86
- return this[xe];
89
+ return this[kMessage];
87
90
  }
88
91
  }
89
- Object.defineProperty(Pe.prototype, "error", { enumerable: !0 });
90
- Object.defineProperty(Pe.prototype, "message", { enumerable: !0 });
91
- const at = typeof globalThis.ErrorEvent == "function" ? globalThis.ErrorEvent : Pe;
92
- function ct(t) {
93
- return t instanceof Error ? "exitCode" in t && (t == null ? void 0 : t.exitCode) === 0 || (t == null ? void 0 : t.name) === "ExitStatus" && "status" in t && t.status === 0 : !1;
92
+ Object.defineProperty(ErrorEvent2.prototype, "error", { enumerable: !0 });
93
+ Object.defineProperty(ErrorEvent2.prototype, "message", { enumerable: !0 });
94
+ const ErrorEvent = typeof globalThis.ErrorEvent == "function" ? globalThis.ErrorEvent : ErrorEvent2;
95
+ function isExitCodeZero(e) {
96
+ 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;
94
97
  }
95
- class lt extends EventTarget {
98
+ class UnhandledRejectionsTarget extends EventTarget {
96
99
  constructor() {
97
100
  super(...arguments), this.listenersCount = 0;
98
101
  }
99
- addEventListener(e, r) {
100
- ++this.listenersCount, super.addEventListener(e, r);
102
+ addEventListener(t, r) {
103
+ ++this.listenersCount, super.addEventListener(t, r);
101
104
  }
102
- removeEventListener(e, r) {
103
- --this.listenersCount, super.removeEventListener(e, r);
105
+ removeEventListener(t, r) {
106
+ --this.listenersCount, super.removeEventListener(t, r);
104
107
  }
105
108
  hasListeners() {
106
109
  return this.listenersCount > 0;
107
110
  }
108
111
  }
109
- function ut(t) {
110
- t.asm = {
111
- ...t.asm
112
+ function improveWASMErrorReporting(e) {
113
+ e.asm = {
114
+ ...e.asm
112
115
  };
113
- const e = new lt();
114
- for (const r in t.asm)
115
- if (typeof t.asm[r] == "function") {
116
- const n = t.asm[r];
117
- t.asm[r] = function(...s) {
118
- var o;
116
+ const t = new UnhandledRejectionsTarget();
117
+ for (const r in e.asm)
118
+ if (typeof e.asm[r] == "function") {
119
+ const s = e.asm[r];
120
+ e.asm[r] = function(...i) {
121
+ var n;
119
122
  try {
120
- return n(...s);
121
- } catch (i) {
122
- if (!(i instanceof Error))
123
- throw i;
124
- const a = dt(
125
- i,
126
- (o = t.lastAsyncifyStackSource) == null ? void 0 : o.stack
123
+ return s(...i);
124
+ } catch (o) {
125
+ if (!(o instanceof Error))
126
+ throw o;
127
+ const a = clarifyErrorMessage(
128
+ o,
129
+ (n = e.lastAsyncifyStackSource) == null ? void 0 : n.stack
127
130
  );
128
- if (t.lastAsyncifyStackSource && (i.cause = t.lastAsyncifyStackSource), e.hasListeners()) {
129
- e.dispatchEvent(
130
- new at("error", {
131
- error: i,
131
+ if (e.lastAsyncifyStackSource && (o.cause = e.lastAsyncifyStackSource), t.hasListeners()) {
132
+ t.dispatchEvent(
133
+ new ErrorEvent("error", {
134
+ error: o,
132
135
  message: a
133
136
  })
134
137
  );
135
138
  return;
136
139
  }
137
- throw ct(i) || mt(a), i;
140
+ throw isExitCodeZero(o) || showCriticalErrorBox(a), o;
138
141
  }
139
142
  };
140
143
  }
141
- return e;
144
+ return t;
142
145
  }
143
- let ge = [];
144
- function ht() {
145
- return ge;
146
+ let functionsMaybeMissingFromAsyncify = [];
147
+ function getFunctionsMaybeMissingFromAsyncify() {
148
+ return functionsMaybeMissingFromAsyncify;
146
149
  }
147
- function dt(t, e) {
148
- if (t.message === "unreachable") {
149
- let r = ft;
150
- e || (r += `
150
+ function clarifyErrorMessage(e, t) {
151
+ if (e.message === "unreachable") {
152
+ let r = UNREACHABLE_ERROR;
153
+ t || (r += `
151
154
 
152
155
  This stack trace is lacking. For a better one initialize
153
156
  the PHP runtime with { debug: true }, e.g. PHPNode.load('8.1', { debug: true }).
154
157
 
155
- `), ge = yt(
156
- e || t.stack || ""
158
+ `), functionsMaybeMissingFromAsyncify = extractPHPFunctionsFromStack(
159
+ t || e.stack || ""
157
160
  );
158
- for (const n of ge)
159
- r += ` * ${n}
161
+ for (const s of functionsMaybeMissingFromAsyncify)
162
+ r += ` * ${s}
160
163
  `;
161
164
  return r;
162
165
  }
163
- return t.message;
166
+ return e.message;
164
167
  }
165
- const ft = `
168
+ const UNREACHABLE_ERROR = `
166
169
  "unreachable" WASM instruction executed.
167
170
 
168
171
  The typical reason is a PHP function missing from the ASYNCIFY_ONLY
@@ -186,39 +189,39 @@ the Dockerfile, you'll need to trigger this error again with long stack
186
189
  traces enabled. In node.js, you can do it using the --stack-trace-limit=100
187
190
  CLI option:
188
191
 
189
- `, Se = "\x1B[41m", pt = "\x1B[1m", ke = "\x1B[0m", _e = "\x1B[K";
190
- let Te = !1;
191
- function mt(t) {
192
- if (!Te && (Te = !0, !(t != null && t.trim().startsWith("Program terminated with exit")))) {
193
- console.log(`${Se}
194
- ${_e}
195
- ${pt} WASM ERROR${ke}${Se}`);
196
- for (const e of t.split(`
192
+ `, redBg = "\x1B[41m", bold = "\x1B[1m", reset = "\x1B[0m", eol = "\x1B[K";
193
+ let logged = !1;
194
+ function showCriticalErrorBox(e) {
195
+ if (!logged && (logged = !0, !(e != null && e.trim().startsWith("Program terminated with exit")))) {
196
+ console.log(`${redBg}
197
+ ${eol}
198
+ ${bold} WASM ERROR${reset}${redBg}`);
199
+ for (const t of e.split(`
197
200
  `))
198
- console.log(`${_e} ${e} `);
199
- console.log(`${ke}`);
201
+ console.log(`${eol} ${t} `);
202
+ console.log(`${reset}`);
200
203
  }
201
204
  }
202
- function yt(t) {
205
+ function extractPHPFunctionsFromStack(e) {
203
206
  try {
204
- const e = t.split(`
207
+ const t = e.split(`
205
208
  `).slice(1).map((r) => {
206
- const n = r.trim().substring(3).split(" ");
209
+ const s = r.trim().substring(3).split(" ");
207
210
  return {
208
- fn: n.length >= 2 ? n[0] : "<unknown>",
211
+ fn: s.length >= 2 ? s[0] : "<unknown>",
209
212
  isWasm: r.includes("wasm://")
210
213
  };
211
214
  }).filter(
212
- ({ fn: r, isWasm: n }) => n && !r.startsWith("dynCall_") && !r.startsWith("invoke_")
215
+ ({ fn: r, isWasm: s }) => s && !r.startsWith("dynCall_") && !r.startsWith("invoke_")
213
216
  ).map(({ fn: r }) => r);
214
- return Array.from(new Set(e));
217
+ return Array.from(new Set(t));
215
218
  } catch {
216
219
  return [];
217
220
  }
218
221
  }
219
- class Oe {
220
- constructor({ concurrency: e }) {
221
- this._running = 0, this.concurrency = e, this.queue = [];
222
+ class Semaphore {
223
+ constructor({ concurrency: t }) {
224
+ this._running = 0, this.concurrency = t, this.queue = [];
222
225
  }
223
226
  get running() {
224
227
  return this._running;
@@ -226,49 +229,127 @@ class Oe {
226
229
  async acquire() {
227
230
  for (; ; )
228
231
  if (this._running >= this.concurrency)
229
- await new Promise((e) => this.queue.push(e));
232
+ await new Promise((t) => this.queue.push(t));
230
233
  else {
231
234
  this._running++;
232
- let e = !1;
235
+ let t = !1;
233
236
  return () => {
234
- e || (e = !0, this._running--, this.queue.length > 0 && this.queue.shift()());
237
+ t || (t = !0, this._running--, this.queue.length > 0 && this.queue.shift()());
235
238
  };
236
239
  }
237
240
  }
238
- async run(e) {
241
+ async run(t) {
239
242
  const r = await this.acquire();
240
243
  try {
241
- return await e();
244
+ return await t();
242
245
  } finally {
243
246
  r();
244
247
  }
245
248
  }
246
249
  }
250
+ function joinPaths(...e) {
251
+ let t = e.join("/");
252
+ const r = t[0] === "/", s = t.substring(t.length - 1) === "/";
253
+ return t = normalizePath(t), !t && !r && (t = "."), t && s && (t += "/"), t;
254
+ }
255
+ function normalizePath(e) {
256
+ const t = e[0] === "/";
257
+ return e = normalizePathsArray(
258
+ e.split("/").filter((r) => !!r),
259
+ !t
260
+ ).join("/"), (t ? "/" : "") + e.replace(/\/$/, "");
261
+ }
262
+ function normalizePathsArray(e, t) {
263
+ let r = 0;
264
+ for (let s = e.length - 1; s >= 0; s--) {
265
+ const i = e[s];
266
+ i === "." ? e.splice(s, 1) : i === ".." ? (e.splice(s, 1), r++) : r && (e.splice(s, 1), r--);
267
+ }
268
+ if (t)
269
+ for (; r; r--)
270
+ e.unshift("..");
271
+ return e;
272
+ }
273
+ function createSpawnHandler(e) {
274
+ return function(t) {
275
+ const r = new ChildProcess(), s = new ProcessApi(r);
276
+ return setTimeout(async () => {
277
+ await e(t, s), r.emit("spawn", !0);
278
+ }), r;
279
+ };
280
+ }
281
+ class EventEmitter {
282
+ constructor() {
283
+ this.listeners = {};
284
+ }
285
+ emit(t, r) {
286
+ this.listeners[t] && this.listeners[t].forEach(function(s) {
287
+ s(r);
288
+ });
289
+ }
290
+ on(t, r) {
291
+ this.listeners[t] || (this.listeners[t] = []), this.listeners[t].push(r);
292
+ }
293
+ }
294
+ class ProcessApi extends EventEmitter {
295
+ constructor(t) {
296
+ super(), this.childProcess = t, this.exited = !1, this.stdinData = [], t.on("stdin", (r) => {
297
+ this.stdinData ? this.stdinData.push(r.slice()) : this.emit("stdin", r);
298
+ });
299
+ }
300
+ stdout(t) {
301
+ typeof t == "string" && (t = new TextEncoder().encode(t)), this.childProcess.stdout.emit("data", t);
302
+ }
303
+ stderr(t) {
304
+ typeof t == "string" && (t = new TextEncoder().encode(t)), this.childProcess.stderr.emit("data", t);
305
+ }
306
+ exit(t) {
307
+ this.exited || (this.exited = !0, this.childProcess.emit("exit", t));
308
+ }
309
+ flushStdin() {
310
+ if (this.stdinData)
311
+ for (let t = 0; t < this.stdinData.length; t++)
312
+ this.emit("stdin", this.stdinData[t]);
313
+ this.stdinData = null;
314
+ }
315
+ }
316
+ let lastPid = 9743;
317
+ class ChildProcess extends EventEmitter {
318
+ constructor(t = lastPid++) {
319
+ super(), this.pid = t, this.stdout = new EventEmitter(), this.stderr = new EventEmitter();
320
+ const r = this;
321
+ this.stdin = {
322
+ write: (s) => {
323
+ r.emit("stdin", s);
324
+ }
325
+ };
326
+ }
327
+ }
247
328
  ReadableStream.prototype[Symbol.asyncIterator] || (ReadableStream.prototype[Symbol.asyncIterator] = async function* () {
248
- const t = this.getReader();
329
+ const e = this.getReader();
249
330
  try {
250
331
  for (; ; ) {
251
- const { done: e, value: r } = await t.read();
252
- if (e)
332
+ const { done: t, value: r } = await e.read();
333
+ if (t)
253
334
  return;
254
335
  yield r;
255
336
  }
256
337
  } finally {
257
- t.releaseLock();
338
+ e.releaseLock();
258
339
  }
259
340
  }, ReadableStream.prototype.iterate = // @ts-ignore
260
341
  ReadableStream.prototype[Symbol.asyncIterator]);
261
- class L {
262
- constructor(e, r, n, s = "", o = 0) {
263
- this.httpStatusCode = e, this.headers = r, this.bytes = n, this.exitCode = o, this.errors = s;
264
- }
265
- static fromRawData(e) {
266
- return new L(
267
- e.httpStatusCode,
268
- e.headers,
269
- e.bytes,
270
- e.errors,
271
- e.exitCode
342
+ class PHPResponse {
343
+ constructor(t, r, s, i = "", n = 0) {
344
+ this.httpStatusCode = t, this.headers = r, this.bytes = s, this.exitCode = n, this.errors = i;
345
+ }
346
+ static fromRawData(t) {
347
+ return new PHPResponse(
348
+ t.httpStatusCode,
349
+ t.headers,
350
+ t.bytes,
351
+ t.errors,
352
+ t.exitCode
272
353
  );
273
354
  }
274
355
  toRawData() {
@@ -293,7 +374,7 @@ class L {
293
374
  return new TextDecoder().decode(this.bytes);
294
375
  }
295
376
  }
296
- const gt = [
377
+ const SupportedPHPVersions = [
297
378
  "8.3",
298
379
  "8.2",
299
380
  "8.1",
@@ -303,17 +384,17 @@ const gt = [
303
384
  "7.2",
304
385
  "7.1",
305
386
  "7.0"
306
- ], wt = gt[0];
307
- var C, I;
308
- class bt {
387
+ ], LatestSupportedPHPVersion = SupportedPHPVersions[0];
388
+ var R, H;
389
+ class PHPBrowser {
309
390
  /**
310
391
  * @param server - The PHP server to browse.
311
392
  * @param config - The browser configuration.
312
393
  */
313
- constructor(e, r = {}) {
314
- d(this, C, void 0);
315
- d(this, I, void 0);
316
- this.requestHandler = e, y(this, C, {}), y(this, I, {
394
+ constructor(t, r = {}) {
395
+ d(this, R, void 0);
396
+ d(this, H, void 0);
397
+ this.requestHandler = t, p(this, R, {}), p(this, H, {
317
398
  handleRedirects: !1,
318
399
  maxRedirects: 4,
319
400
  ...r
@@ -333,37 +414,37 @@ class bt {
333
414
  * @param redirects - Internal. The number of redirects handled so far.
334
415
  * @returns PHPRequestHandler response.
335
416
  */
336
- async request(e, r = 0) {
337
- const n = await this.requestHandler.request({
338
- ...e,
417
+ async request(t, r = 0) {
418
+ const s = await this.requestHandler.request({
419
+ ...t,
339
420
  headers: {
340
- ...e.headers,
421
+ ...t.headers,
341
422
  cookie: this.serializeCookies()
342
423
  }
343
424
  });
344
- if (n.headers["set-cookie"] && this.setCookies(n.headers["set-cookie"]), c(this, I).handleRedirects && n.headers.location && r < c(this, I).maxRedirects) {
345
- const s = new URL(
346
- n.headers.location[0],
425
+ if (s.headers["set-cookie"] && this.setCookies(s.headers["set-cookie"]), l(this, H).handleRedirects && s.headers.location && r < l(this, H).maxRedirects) {
426
+ const i = new URL(
427
+ s.headers.location[0],
347
428
  this.requestHandler.absoluteUrl
348
429
  );
349
430
  return this.request(
350
431
  {
351
- url: s.toString(),
432
+ url: i.toString(),
352
433
  method: "GET",
353
434
  headers: {}
354
435
  },
355
436
  r + 1
356
437
  );
357
438
  }
358
- return n;
439
+ return s;
359
440
  }
360
441
  /** @inheritDoc */
361
- pathToInternalUrl(e) {
362
- return this.requestHandler.pathToInternalUrl(e);
442
+ pathToInternalUrl(t) {
443
+ return this.requestHandler.pathToInternalUrl(t);
363
444
  }
364
445
  /** @inheritDoc */
365
- internalUrlToPath(e) {
366
- return this.requestHandler.internalUrlToPath(e);
446
+ internalUrlToPath(t) {
447
+ return this.requestHandler.internalUrlToPath(t);
367
448
  }
368
449
  /** @inheritDoc */
369
450
  get absoluteUrl() {
@@ -373,49 +454,49 @@ class bt {
373
454
  get documentRoot() {
374
455
  return this.requestHandler.documentRoot;
375
456
  }
376
- setCookies(e) {
377
- for (const r of e)
457
+ setCookies(t) {
458
+ for (const r of t)
378
459
  try {
379
460
  if (!r.includes("="))
380
461
  continue;
381
- const n = r.indexOf("="), s = r.substring(0, n), o = r.substring(n + 1).split(";")[0];
382
- c(this, C)[s] = o;
383
- } catch (n) {
384
- console.error(n);
462
+ const s = r.indexOf("="), i = r.substring(0, s), n = r.substring(s + 1).split(";")[0];
463
+ l(this, R)[i] = n;
464
+ } catch (s) {
465
+ console.error(s);
385
466
  }
386
467
  }
387
468
  serializeCookies() {
388
- const e = [];
389
- for (const r in c(this, C))
390
- e.push(`${r}=${c(this, C)[r]}`);
391
- return e.join("; ");
469
+ const t = [];
470
+ for (const r in l(this, R))
471
+ t.push(`${r}=${l(this, R)[r]}`);
472
+ return t.join("; ");
392
473
  }
393
474
  }
394
- C = new WeakMap(), I = new WeakMap();
395
- const Pt = "http://example.com";
396
- function Ce(t) {
397
- return t.toString().substring(t.origin.length);
475
+ R = new WeakMap(), H = new WeakMap();
476
+ const DEFAULT_BASE_URL = "http://example.com";
477
+ function toRelativeUrl(e) {
478
+ return e.toString().substring(e.origin.length);
398
479
  }
399
- function Fe(t, e) {
400
- return !e || !t.startsWith(e) ? t : t.substring(e.length);
480
+ function removePathPrefix(e, t) {
481
+ return !t || !e.startsWith(t) ? e : e.substring(t.length);
401
482
  }
402
- function Et(t, e) {
403
- return !e || t.startsWith(e) ? t : e + t;
483
+ function ensurePathPrefix(e, t) {
484
+ return !t || e.startsWith(t) ? e : t + e;
404
485
  }
405
- var E, N, z, F, U, v, $, W, Z, Ie, ee, Ne, te, Ue;
406
- class vt {
486
+ var E, k, L, S, C, g, F, x, N, Z, U, X, B, ee;
487
+ class PHPRequestHandler {
407
488
  /**
408
489
  * @param php - The PHP instance.
409
490
  * @param config - Request Handler configuration.
410
491
  */
411
- constructor(e, r = {}) {
492
+ constructor(t, r = {}) {
412
493
  /**
413
494
  * Serves a static file from the PHP filesystem.
414
495
  *
415
496
  * @param fsPath - Absolute path of the static file to serve.
416
497
  * @returns The response.
417
498
  */
418
- d(this, Z);
499
+ d(this, N);
419
500
  /**
420
501
  * Runs the requested PHP file with all the request and $_SERVER
421
502
  * superglobals populated.
@@ -423,7 +504,7 @@ class vt {
423
504
  * @param request - The request.
424
505
  * @returns The response.
425
506
  */
426
- d(this, ee);
507
+ d(this, U);
427
508
  /**
428
509
  * Resolve the requested path to the filesystem path of the requested PHP file.
429
510
  *
@@ -433,68 +514,68 @@ class vt {
433
514
  * @throws {Error} If the requested path doesn't exist.
434
515
  * @returns The resolved filesystem path.
435
516
  */
436
- d(this, te);
517
+ d(this, B);
437
518
  d(this, E, void 0);
438
- d(this, N, void 0);
439
- d(this, z, void 0);
519
+ d(this, k, void 0);
520
+ d(this, L, void 0);
521
+ d(this, S, void 0);
522
+ d(this, C, void 0);
523
+ d(this, g, void 0);
440
524
  d(this, F, void 0);
441
- d(this, U, void 0);
442
- d(this, v, void 0);
443
- d(this, $, void 0);
444
- d(this, W, void 0);
445
- y(this, W, new Oe({ concurrency: 1 }));
525
+ d(this, x, void 0);
526
+ p(this, x, new Semaphore({ concurrency: 1 }));
446
527
  const {
447
- documentRoot: n = "/www/",
448
- absoluteUrl: s = typeof location == "object" ? location == null ? void 0 : location.href : ""
528
+ documentRoot: s = "/www/",
529
+ absoluteUrl: i = typeof location == "object" ? location == null ? void 0 : location.href : ""
449
530
  } = r;
450
- this.php = e, y(this, E, n);
451
- const o = new URL(s);
452
- y(this, z, o.hostname), y(this, F, o.port ? Number(o.port) : o.protocol === "https:" ? 443 : 80), y(this, N, (o.protocol || "").replace(":", ""));
453
- const i = c(this, F) !== 443 && c(this, F) !== 80;
454
- y(this, U, [
455
- c(this, z),
456
- i ? `:${c(this, F)}` : ""
457
- ].join("")), y(this, v, o.pathname.replace(/\/+$/, "")), y(this, $, [
458
- `${c(this, N)}://`,
459
- c(this, U),
460
- c(this, v)
531
+ this.php = t, p(this, E, s);
532
+ const n = new URL(i);
533
+ p(this, L, n.hostname), p(this, S, n.port ? Number(n.port) : n.protocol === "https:" ? 443 : 80), p(this, k, (n.protocol || "").replace(":", ""));
534
+ const o = l(this, S) !== 443 && l(this, S) !== 80;
535
+ p(this, C, [
536
+ l(this, L),
537
+ o ? `:${l(this, S)}` : ""
538
+ ].join("")), p(this, g, n.pathname.replace(/\/+$/, "")), p(this, F, [
539
+ `${l(this, k)}://`,
540
+ l(this, C),
541
+ l(this, g)
461
542
  ].join(""));
462
543
  }
463
544
  /** @inheritDoc */
464
- pathToInternalUrl(e) {
465
- return `${this.absoluteUrl}${e}`;
545
+ pathToInternalUrl(t) {
546
+ return `${this.absoluteUrl}${t}`;
466
547
  }
467
548
  /** @inheritDoc */
468
- internalUrlToPath(e) {
469
- const r = new URL(e);
470
- return r.pathname.startsWith(c(this, v)) && (r.pathname = r.pathname.slice(c(this, v).length)), Ce(r);
549
+ internalUrlToPath(t) {
550
+ const r = new URL(t);
551
+ return r.pathname.startsWith(l(this, g)) && (r.pathname = r.pathname.slice(l(this, g).length)), toRelativeUrl(r);
471
552
  }
472
553
  get isRequestRunning() {
473
- return c(this, W).running > 0;
554
+ return l(this, x).running > 0;
474
555
  }
475
556
  /** @inheritDoc */
476
557
  get absoluteUrl() {
477
- return c(this, $);
558
+ return l(this, F);
478
559
  }
479
560
  /** @inheritDoc */
480
561
  get documentRoot() {
481
- return c(this, E);
562
+ return l(this, E);
482
563
  }
483
564
  /** @inheritDoc */
484
- async request(e) {
485
- const r = e.url.startsWith("http://") || e.url.startsWith("https://"), n = new URL(
486
- e.url,
487
- r ? void 0 : Pt
488
- ), s = Fe(
489
- n.pathname,
490
- c(this, v)
491
- ), o = `${c(this, E)}${s}`;
492
- return St(o) ? await g(this, ee, Ne).call(this, e, n) : g(this, Z, Ie).call(this, o);
493
- }
494
- }
495
- E = new WeakMap(), N = new WeakMap(), z = new WeakMap(), F = new WeakMap(), U = new WeakMap(), v = new WeakMap(), $ = new WeakMap(), W = new WeakMap(), Z = new WeakSet(), Ie = function(e) {
496
- if (!this.php.fileExists(e))
497
- return new L(
565
+ async request(t) {
566
+ const r = t.url.startsWith("http://") || t.url.startsWith("https://"), s = new URL(
567
+ t.url,
568
+ r ? void 0 : DEFAULT_BASE_URL
569
+ ), i = removePathPrefix(
570
+ s.pathname,
571
+ l(this, g)
572
+ ), n = `${l(this, E)}${i}`;
573
+ return seemsLikeAPHPRequestHandlerPath(n) ? await m(this, U, X).call(this, t, s) : m(this, N, Z).call(this, n);
574
+ }
575
+ }
576
+ E = new WeakMap(), k = new WeakMap(), L = new WeakMap(), S = new WeakMap(), C = new WeakMap(), g = new WeakMap(), F = new WeakMap(), x = new WeakMap(), N = new WeakSet(), Z = function(t) {
577
+ if (!this.php.fileExists(t))
578
+ return new PHPResponse(
498
579
  404,
499
580
  // Let the service worker know that no static file was found
500
581
  // and that it's okay to issue a real fetch() to the server.
@@ -503,104 +584,118 @@ E = new WeakMap(), N = new WeakMap(), z = new WeakMap(), F = new WeakMap(), U =
503
584
  },
504
585
  new TextEncoder().encode("404 File not found")
505
586
  );
506
- const r = this.php.readFileAsBuffer(e);
507
- return new L(
587
+ const r = this.php.readFileAsBuffer(t);
588
+ return new PHPResponse(
508
589
  200,
509
590
  {
510
591
  "content-length": [`${r.byteLength}`],
511
592
  // @TODO: Infer the content-type from the arrayBuffer instead of the file path.
512
593
  // The code below won't return the correct mime-type if the extension
513
594
  // was tampered with.
514
- "content-type": [xt(e)],
595
+ "content-type": [inferMimeType(t)],
515
596
  "accept-ranges": ["bytes"],
516
597
  "cache-control": ["public, max-age=0"]
517
598
  },
518
599
  r
519
600
  );
520
- }, ee = new WeakSet(), Ne = async function(e, r) {
521
- var s;
522
- const n = await c(this, W).acquire();
601
+ }, U = new WeakSet(), X = async function(t, r) {
602
+ var i, n, o;
603
+ if (l(this, x).running > 0 && ((i = t.headers) == null ? void 0 : i["x-request-issuer"]) === "php")
604
+ return console.warn(
605
+ "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."
606
+ ), new PHPResponse(
607
+ 502,
608
+ {},
609
+ new TextEncoder().encode("502 Bad Gateway")
610
+ );
611
+ const s = await l(this, x).acquire();
523
612
  try {
524
- this.php.addServerGlobalEntry("DOCUMENT_ROOT", c(this, E)), this.php.addServerGlobalEntry(
613
+ this.php.addServerGlobalEntry("REMOTE_ADDR", "127.0.0.1"), this.php.addServerGlobalEntry("DOCUMENT_ROOT", l(this, E)), this.php.addServerGlobalEntry(
525
614
  "HTTPS",
526
- c(this, $).startsWith("https://") ? "on" : ""
615
+ l(this, F).startsWith("https://") ? "on" : ""
527
616
  );
528
- let o = "GET";
529
- const i = {
530
- host: c(this, U),
531
- ...Qe(e.headers || {})
532
- }, a = [];
533
- if (e.files && Object.keys(e.files).length) {
534
- o = "POST";
535
- for (const h in e.files) {
536
- const m = e.files[h];
537
- a.push({
538
- key: h,
539
- name: m.name,
540
- type: m.type,
541
- data: new Uint8Array(await m.arrayBuffer())
617
+ let a = "GET";
618
+ const u = {
619
+ host: l(this, C),
620
+ ...normalizeHeaders(t.headers || {})
621
+ }, c = [];
622
+ if (t.files && Object.keys(t.files).length) {
623
+ a = "POST";
624
+ for (const f in t.files) {
625
+ const y = t.files[f];
626
+ c.push({
627
+ key: f,
628
+ name: y.name,
629
+ type: y.type,
630
+ data: new Uint8Array(await y.arrayBuffer())
542
631
  });
543
632
  }
544
- (s = i["content-type"]) != null && s.startsWith("multipart/form-data") && (e.formData = Rt(
545
- e.body || ""
546
- ), i["content-type"] = "application/x-www-form-urlencoded", delete e.body);
633
+ (n = u["content-type"]) != null && n.startsWith("multipart/form-data") && (t.formData = parseMultipartFormDataString(
634
+ t.body || ""
635
+ ), u["content-type"] = "application/x-www-form-urlencoded", delete t.body);
547
636
  }
548
- let u;
549
- e.formData !== void 0 ? (o = "POST", i["content-type"] = i["content-type"] || "application/x-www-form-urlencoded", u = new URLSearchParams(
550
- e.formData
551
- ).toString()) : u = e.body;
552
- let l;
637
+ let h;
638
+ t.formData !== void 0 ? (a = "POST", u["content-type"] = u["content-type"] || "application/x-www-form-urlencoded", h = new URLSearchParams(
639
+ t.formData
640
+ ).toString()) : h = t.body;
641
+ let _;
553
642
  try {
554
- l = g(this, te, Ue).call(this, r.pathname);
643
+ let f = r.pathname;
644
+ if ((o = t.headers) != null && o["x-rewrite-url"])
645
+ try {
646
+ f = new URL(
647
+ t.headers["x-rewrite-url"]
648
+ ).pathname;
649
+ } catch {
650
+ }
651
+ _ = m(this, B, ee).call(this, f);
555
652
  } catch {
556
- return new L(
653
+ return new PHPResponse(
557
654
  404,
558
655
  {},
559
656
  new TextEncoder().encode("404 File not found")
560
657
  );
561
658
  }
562
659
  return await this.php.run({
563
- relativeUri: Et(
564
- Ce(r),
565
- c(this, v)
660
+ relativeUri: ensurePathPrefix(
661
+ toRelativeUrl(r),
662
+ l(this, g)
566
663
  ),
567
- protocol: c(this, N),
568
- method: e.method || o,
569
- body: u,
570
- fileInfos: a,
571
- scriptPath: l,
572
- headers: i
664
+ protocol: l(this, k),
665
+ method: t.method || a,
666
+ body: h,
667
+ fileInfos: c,
668
+ scriptPath: _,
669
+ headers: u
573
670
  });
574
671
  } finally {
575
- n();
672
+ s();
576
673
  }
577
- }, te = new WeakSet(), Ue = function(e) {
578
- let r = Fe(e, c(this, v));
674
+ }, B = new WeakSet(), ee = function(t) {
675
+ let r = removePathPrefix(t, l(this, g));
579
676
  r.includes(".php") ? r = r.split(".php")[0] + ".php" : (r.endsWith("/") || (r += "/"), r.endsWith("index.php") || (r += "index.php"));
580
- const n = `${c(this, E)}${r}`;
581
- if (this.php.fileExists(n))
582
- return n;
583
- if (!this.php.fileExists(`${c(this, E)}/index.php`))
584
- throw new Error(`File not found: ${n}`);
585
- return `${c(this, E)}/index.php`;
677
+ const s = `${l(this, E)}${r}`;
678
+ if (this.php.fileExists(s))
679
+ return s;
680
+ throw new Error(`File not found: ${s}`);
586
681
  };
587
- function Rt(t) {
588
- const e = {}, r = t.match(/--(.*)\r\n/);
682
+ function parseMultipartFormDataString(e) {
683
+ const t = {}, r = e.match(/--(.*)\r\n/);
589
684
  if (!r)
590
- return e;
591
- const n = r[1], s = t.split(`--${n}`);
592
- return s.shift(), s.pop(), s.forEach((o) => {
593
- const i = o.indexOf(`\r
685
+ return t;
686
+ const s = r[1], i = e.split(`--${s}`);
687
+ return i.shift(), i.pop(), i.forEach((n) => {
688
+ const o = n.indexOf(`\r
594
689
  \r
595
- `), a = o.substring(0, i).trim(), u = o.substring(i + 4).trim(), l = a.match(/name="([^"]+)"/);
596
- if (l) {
597
- const h = l[1];
598
- e[h] = u;
690
+ `), a = n.substring(0, o).trim(), u = n.substring(o + 4).trim(), c = a.match(/name="([^"]+)"/);
691
+ if (c) {
692
+ const h = c[1];
693
+ t[h] = u;
599
694
  }
600
- }), e;
695
+ }), t;
601
696
  }
602
- function xt(t) {
603
- switch (t.split(".").pop()) {
697
+ function inferMimeType(e) {
698
+ switch (e.split(".").pop()) {
604
699
  case "css":
605
700
  return "text/css";
606
701
  case "js":
@@ -639,16 +734,16 @@ function xt(t) {
639
734
  return "application-octet-stream";
640
735
  }
641
736
  }
642
- function St(t) {
643
- return kt(t) || _t(t);
737
+ function seemsLikeAPHPRequestHandlerPath(e) {
738
+ return seemsLikeAPHPFile(e) || seemsLikeADirectoryRoot(e);
644
739
  }
645
- function kt(t) {
646
- return t.endsWith(".php") || t.includes(".php/");
740
+ function seemsLikeAPHPFile(e) {
741
+ return e.endsWith(".php") || e.includes(".php/");
647
742
  }
648
- function _t(t) {
649
- return !t.split("/").pop().includes(".");
743
+ function seemsLikeADirectoryRoot(e) {
744
+ return !e.split("/").pop().includes(".");
650
745
  }
651
- const J = {
746
+ const FileErrorCodes = {
652
747
  0: "No error occurred. System call completed successfully.",
653
748
  1: "Argument list too long.",
654
749
  2: "Permission denied.",
@@ -727,22 +822,22 @@ const J = {
727
822
  75: "Cross-device link.",
728
823
  76: "Extension: Capabilities insufficient."
729
824
  };
730
- function Tt(t) {
731
- const e = typeof t == "object" ? t == null ? void 0 : t.errno : null;
732
- if (e in J)
733
- return J[e];
734
- }
735
- function R(t = "") {
736
- return function(r, n, s) {
737
- const o = s.value;
738
- s.value = function(...i) {
825
+ function getEmscriptenFsError(e) {
826
+ const t = typeof e == "object" ? e == null ? void 0 : e.errno : null;
827
+ if (t in FileErrorCodes)
828
+ return FileErrorCodes[t];
829
+ }
830
+ function rethrowFileSystemError(e = "") {
831
+ return function(r, s, i) {
832
+ const n = i.value;
833
+ i.value = function(...o) {
739
834
  try {
740
- return o.apply(this, i);
835
+ return n.apply(this, o);
741
836
  } catch (a) {
742
837
  const u = typeof a == "object" ? a == null ? void 0 : a.errno : null;
743
- if (u in J) {
744
- const l = J[u], h = typeof i[0] == "string" ? i[0] : null, m = h !== null ? t.replaceAll("{path}", h) : t;
745
- throw new Error(`${m}: ${l}`, {
838
+ if (u in FileErrorCodes) {
839
+ const c = FileErrorCodes[u], h = typeof o[0] == "string" ? o[0] : null, _ = h !== null ? e.replaceAll("{path}", h) : e;
840
+ throw new Error(`${_}: ${c}`, {
746
841
  cause: a
747
842
  });
748
843
  }
@@ -751,56 +846,50 @@ function R(t = "") {
751
846
  };
752
847
  };
753
848
  }
754
- const Ct = Symbol("RuntimeId"), V = /* @__PURE__ */ new Map();
755
- async function Ft(t, e = {}, r = []) {
756
- const [n, s, o] = He(), [i, a] = He(), u = t.init(At, {
757
- onAbort(h) {
758
- o(h), a(), console.error(h);
849
+ const RuntimeId = Symbol("RuntimeId"), loadedRuntimes = /* @__PURE__ */ new Map();
850
+ let lastRuntimeId = 0;
851
+ async function loadPHPRuntime(e, t = {}) {
852
+ const [r, s, i] = makePromise(), n = e.init(currentJsRuntime, {
853
+ onAbort(a) {
854
+ i(a), console.error(a);
759
855
  },
760
856
  ENV: {},
761
857
  // Emscripten sometimes prepends a '/' to the path, which
762
858
  // breaks vite dev mode. An identity `locateFile` function
763
859
  // fixes it.
764
- locateFile: (h) => h,
765
- ...e,
860
+ locateFile: (a) => a,
861
+ ...t,
766
862
  noInitialRun: !0,
767
863
  onRuntimeInitialized() {
768
- e.onRuntimeInitialized && e.onRuntimeInitialized(), s();
769
- },
770
- monitorRunDependencies(h) {
771
- h === 0 && (delete u.monitorRunDependencies, a());
864
+ t.onRuntimeInitialized && t.onRuntimeInitialized(), s();
772
865
  }
773
866
  });
774
- await Promise.all(
775
- r.map(
776
- ({ default: h }) => h(u)
777
- )
778
- ), r.length || a(), await i, await n;
779
- const l = V.size;
780
- return u.originalExit = u._exit, u._exit = function(h) {
781
- return V.delete(l), u.originalExit(h);
782
- }, u[Ct] = l, V.set(l, u), l;
783
- }
784
- function Ht(t) {
785
- return V.get(t);
786
- }
787
- const At = function() {
788
- var t;
789
- return typeof process < "u" && ((t = process.release) == null ? void 0 : t.name) === "node" ? "NODE" : typeof window < "u" ? "WEB" : typeof WorkerGlobalScope < "u" && self instanceof WorkerGlobalScope ? "WORKER" : "NODE";
790
- }(), He = () => {
791
- const t = [], e = new Promise((r, n) => {
792
- t.push(r, n);
867
+ await r;
868
+ const o = ++lastRuntimeId;
869
+ return n.id = o, n.originalExit = n._exit, n._exit = function(a) {
870
+ return loadedRuntimes.delete(o), n.originalExit(a);
871
+ }, n[RuntimeId] = o, loadedRuntimes.set(o, n), o;
872
+ }
873
+ function getLoadedRuntime(e) {
874
+ return loadedRuntimes.get(e);
875
+ }
876
+ const currentJsRuntime = function() {
877
+ var e;
878
+ 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";
879
+ }(), makePromise = () => {
880
+ const e = [], t = new Promise((r, s) => {
881
+ e.push(r, s);
793
882
  });
794
- return t.unshift(e), t;
883
+ return e.unshift(t), e;
795
884
  };
796
- var Lt = Object.defineProperty, Mt = Object.getOwnPropertyDescriptor, x = (t, e, r, n) => {
797
- for (var s = n > 1 ? void 0 : n ? Mt(e, r) : e, o = t.length - 1, i; o >= 0; o--)
798
- (i = t[o]) && (s = (n ? i(e, r, s) : i(s)) || s);
799
- return n && s && Lt(e, r, s), s;
885
+ var __defProp = Object.defineProperty, __getOwnPropDesc = Object.getOwnPropertyDescriptor, __decorateClass = (e, t, r, s) => {
886
+ for (var i = s > 1 ? void 0 : s ? __getOwnPropDesc(t, r) : t, n = e.length - 1, o; n >= 0; n--)
887
+ (o = e[n]) && (i = (s ? o(t, r, i) : o(i)) || i);
888
+ return s && i && __defProp(t, r, i), i;
800
889
  };
801
- const w = "string", M = "number", f = Symbol("__private__dont__use");
802
- var H, k, A, _, S, B, j, re, $e, ne, We, se, Be, ie, De, oe, qe, ae, ze, ce, je, le, Ge, ue, Ve, he, Ye, de, Je, fe, Ke;
803
- class P {
890
+ const STRING = "string", NUMBER = "number", __private__dont__use = Symbol("__private__dont__use");
891
+ var T, M, I, w, v, b, P, A, O, te, W, re, q, se, z, ne, D, ie, $, oe, j, ae, G, le, V, ce, Y, ue, J, de, K, he;
892
+ class BasePHP {
804
893
  /**
805
894
  * Initializes a PHP runtime.
806
895
  *
@@ -808,16 +897,16 @@ class P {
808
897
  * @param PHPRuntime - Optional. PHP Runtime ID as initialized by loadPHPRuntime.
809
898
  * @param serverOptions - Optional. Options for the PHPRequestHandler. If undefined, no request handler will be initialized.
810
899
  */
811
- constructor(e, r) {
812
- d(this, re);
813
- d(this, ne);
814
- d(this, se);
815
- d(this, ie);
816
- d(this, oe);
817
- d(this, ae);
818
- d(this, ce);
819
- d(this, le);
820
- d(this, ue);
900
+ constructor(e, t) {
901
+ d(this, O);
902
+ d(this, W);
903
+ d(this, q);
904
+ d(this, z);
905
+ d(this, D);
906
+ d(this, $);
907
+ d(this, j);
908
+ d(this, G);
909
+ d(this, V);
821
910
  /**
822
911
  * Adds file information to $_FILES superglobal in PHP.
823
912
  *
@@ -827,40 +916,41 @@ class P {
827
916
  *
828
917
  * @param fileInfo - File details
829
918
  */
830
- d(this, he);
831
- d(this, de);
832
- d(this, fe);
833
- d(this, H, void 0);
834
- d(this, k, void 0);
919
+ d(this, Y);
920
+ d(this, J);
921
+ d(this, K);
922
+ d(this, T, void 0);
923
+ d(this, M, void 0);
924
+ d(this, I, void 0);
925
+ d(this, w, void 0);
926
+ d(this, v, void 0);
927
+ d(this, b, void 0);
928
+ d(this, P, void 0);
835
929
  d(this, A, void 0);
836
- d(this, _, void 0);
837
- d(this, S, void 0);
838
- d(this, B, void 0);
839
- d(this, j, void 0);
840
- y(this, H, []), y(this, k, !1), y(this, A, null), y(this, _, {}), y(this, S, /* @__PURE__ */ new Map()), y(this, B, []), y(this, j, new Oe({ concurrency: 1 })), e !== void 0 && this.initializeRuntime(e), r && (this.requestHandler = new bt(
841
- new vt(this, r)
930
+ p(this, T, []), p(this, w, !1), p(this, v, null), p(this, b, {}), p(this, P, /* @__PURE__ */ new Map()), p(this, A, []), this.semaphore = new Semaphore({ concurrency: 1 }), e !== void 0 && this.initializeRuntime(e), t && (this.requestHandler = new PHPBrowser(
931
+ new PHPRequestHandler(this, t)
842
932
  ));
843
933
  }
844
- addEventListener(e, r) {
845
- c(this, S).has(e) || c(this, S).set(e, /* @__PURE__ */ new Set()), c(this, S).get(e).add(r);
934
+ addEventListener(e, t) {
935
+ l(this, P).has(e) || l(this, P).set(e, /* @__PURE__ */ new Set()), l(this, P).get(e).add(t);
846
936
  }
847
- removeEventListener(e, r) {
848
- var n;
849
- (n = c(this, S).get(e)) == null || n.delete(r);
937
+ removeEventListener(e, t) {
938
+ var r;
939
+ (r = l(this, P).get(e)) == null || r.delete(t);
850
940
  }
851
941
  dispatchEvent(e) {
852
- const r = c(this, S).get(e.type);
853
- if (r)
854
- for (const n of r)
855
- n(e);
942
+ const t = l(this, P).get(e.type);
943
+ if (t)
944
+ for (const r of t)
945
+ r(e);
856
946
  }
857
947
  /** @inheritDoc */
858
948
  async onMessage(e) {
859
- c(this, B).push(e);
949
+ l(this, A).push(e);
860
950
  }
861
951
  /** @inheritDoc */
862
- async setSpawnHandler(e) {
863
- this[f].spawnProcess = e;
952
+ async setSpawnHandler(handler) {
953
+ typeof handler == "string" && (handler = createSpawnHandler(eval(handler))), this[__private__dont__use].spawnProcess = handler;
864
954
  }
865
955
  /** @inheritDoc */
866
956
  get absoluteUrl() {
@@ -881,25 +971,40 @@ class P {
881
971
  );
882
972
  }
883
973
  initializeRuntime(e) {
884
- if (this[f])
974
+ if (this[__private__dont__use])
885
975
  throw new Error("PHP runtime already initialized.");
886
- const r = Ht(e);
887
- if (!r)
976
+ const t = getLoadedRuntime(e);
977
+ if (!t)
888
978
  throw new Error("Invalid PHP runtime id.");
889
- this[f] = r, r.onMessage = async (n) => {
890
- for (const s of c(this, B)) {
891
- const o = await s(n);
892
- if (o)
893
- return o;
979
+ this[__private__dont__use] = t, t.onMessage = async (r) => {
980
+ for (const s of l(this, A)) {
981
+ const i = await s(r);
982
+ if (i)
983
+ return i;
894
984
  }
895
985
  return "";
896
- }, y(this, A, ut(r));
986
+ }, p(this, v, improveWASMErrorReporting(t)), this.dispatchEvent({
987
+ type: "runtime.initialized"
988
+ });
989
+ }
990
+ /** @inheritDoc */
991
+ async setSapiName(e) {
992
+ if (this[__private__dont__use].ccall(
993
+ "wasm_set_sapi_name",
994
+ NUMBER,
995
+ [STRING],
996
+ [e]
997
+ ) !== 0)
998
+ throw new Error(
999
+ "Could not set SAPI name. This can only be done before the PHP WASM module is initialized.Did you already dispatch any requests?"
1000
+ );
1001
+ p(this, I, e);
897
1002
  }
898
1003
  /** @inheritDoc */
899
1004
  setPhpIniPath(e) {
900
- if (c(this, k))
1005
+ if (l(this, w))
901
1006
  throw new Error("Cannot set PHP ini path after calling run().");
902
- this[f].ccall(
1007
+ p(this, M, e), this[__private__dont__use].ccall(
903
1008
  "wasm_set_phpini_path",
904
1009
  null,
905
1010
  ["string"],
@@ -907,44 +1012,62 @@ class P {
907
1012
  );
908
1013
  }
909
1014
  /** @inheritDoc */
910
- setPhpIniEntry(e, r) {
911
- if (c(this, k))
1015
+ setPhpIniEntry(e, t) {
1016
+ if (l(this, w))
912
1017
  throw new Error("Cannot set PHP ini entries after calling run().");
913
- c(this, H).push([e, r]);
1018
+ l(this, T).push([e, t]);
914
1019
  }
915
1020
  /** @inheritDoc */
916
1021
  chdir(e) {
917
- this[f].FS.chdir(e);
1022
+ this[__private__dont__use].FS.chdir(e);
918
1023
  }
919
1024
  /** @inheritDoc */
920
- async request(e, r) {
1025
+ async request(e, t) {
921
1026
  if (!this.requestHandler)
922
1027
  throw new Error("No request handler available.");
923
- return this.requestHandler.request(e, r);
1028
+ return this.requestHandler.request(e, t);
924
1029
  }
925
1030
  /** @inheritDoc */
926
1031
  async run(e) {
927
- const r = await c(this, j).acquire();
1032
+ const t = await this.semaphore.acquire();
1033
+ let r;
928
1034
  try {
929
- c(this, k) || (g(this, re, $e).call(this), y(this, k, !0)), g(this, le, Ge).call(this, e.scriptPath || ""), g(this, se, Be).call(this, e.relativeUri || ""), g(this, oe, qe).call(this, e.method || "GET");
930
- const n = Qe(e.headers || {}), s = n.host || "example.com:443";
931
- if (g(this, ie, De).call(this, s, e.protocol || "http"), g(this, ae, ze).call(this, n), e.body && g(this, ce, je).call(this, e.body), e.fileInfos)
1035
+ l(this, w) || (m(this, O, te).call(this), p(this, w, !0)), m(this, G, le).call(this, e.scriptPath || ""), m(this, q, se).call(this, e.relativeUri || ""), m(this, D, ie).call(this, e.method || "GET");
1036
+ const s = normalizeHeaders(e.headers || {}), i = s.host || "example.com:443";
1037
+ if (m(this, z, ne).call(this, i, e.protocol || "http"), m(this, $, oe).call(this, s), e.body && (r = m(this, j, ae).call(this, e.body)), e.fileInfos)
932
1038
  for (const o of e.fileInfos)
933
- g(this, he, Ye).call(this, o);
934
- return e.code && g(this, de, Je).call(this, " ?>" + e.code), g(this, ue, Ve).call(this), await g(this, fe, Ke).call(this);
1039
+ m(this, Y, ue).call(this, o);
1040
+ typeof e.code == "string" && m(this, J, de).call(this, " ?>" + e.code), m(this, V, ce).call(this);
1041
+ const n = await m(this, K, he).call(this);
1042
+ if (e.throwOnError && n.exitCode !== 0) {
1043
+ const o = {
1044
+ stdout: n.text,
1045
+ stderr: n.errors
1046
+ };
1047
+ console.warn("PHP.run() output was:", o);
1048
+ const a = new Error(
1049
+ `PHP.run() failed with exit code ${n.exitCode} and the following output`
1050
+ );
1051
+ throw a.output = o, a;
1052
+ }
1053
+ return n;
935
1054
  } finally {
936
- r(), this.dispatchEvent({
937
- type: "request.end"
938
- });
1055
+ try {
1056
+ r && this[__private__dont__use].free(r);
1057
+ } finally {
1058
+ t(), this.dispatchEvent({
1059
+ type: "request.end"
1060
+ });
1061
+ }
939
1062
  }
940
1063
  }
941
- addServerGlobalEntry(e, r) {
942
- c(this, _)[e] = r;
1064
+ addServerGlobalEntry(e, t) {
1065
+ l(this, b)[e] = t;
943
1066
  }
944
- defineConstant(e, r) {
945
- let n = {};
1067
+ defineConstant(e, t) {
1068
+ let r = {};
946
1069
  try {
947
- n = JSON.parse(
1070
+ r = JSON.parse(
948
1071
  this.fileExists("/tmp/consts.json") && this.readFileAsText("/tmp/consts.json") || "{}"
949
1072
  );
950
1073
  } catch {
@@ -952,13 +1075,13 @@ class P {
952
1075
  this.writeFile(
953
1076
  "/tmp/consts.json",
954
1077
  JSON.stringify({
955
- ...n,
956
- [e]: r
1078
+ ...r,
1079
+ [e]: t
957
1080
  })
958
1081
  );
959
1082
  }
960
1083
  mkdir(e) {
961
- this[f].FS.mkdirTree(e);
1084
+ this[__private__dont__use].FS.mkdirTree(e);
962
1085
  }
963
1086
  mkdirTree(e) {
964
1087
  this.mkdir(e);
@@ -967,67 +1090,91 @@ class P {
967
1090
  return new TextDecoder().decode(this.readFileAsBuffer(e));
968
1091
  }
969
1092
  readFileAsBuffer(e) {
970
- return this[f].FS.readFile(e);
1093
+ return this[__private__dont__use].FS.readFile(e);
971
1094
  }
972
- writeFile(e, r) {
973
- this[f].FS.writeFile(e, r);
1095
+ writeFile(e, t) {
1096
+ this[__private__dont__use].FS.writeFile(e, t);
974
1097
  }
975
1098
  unlink(e) {
976
- this[f].FS.unlink(e);
1099
+ this[__private__dont__use].FS.unlink(e);
977
1100
  }
978
1101
  /** @inheritDoc */
979
- mv(e, r) {
1102
+ mv(e, t) {
980
1103
  try {
981
- this[f].FS.rename(e, r);
982
- } catch (n) {
983
- const s = Tt(n);
1104
+ this[__private__dont__use].FS.rename(e, t);
1105
+ } catch (r) {
1106
+ const s = getEmscriptenFsError(r);
984
1107
  throw s ? new Error(
985
- `Could not move ${e} to ${r}: ${s}`,
1108
+ `Could not move ${e} to ${t}: ${s}`,
986
1109
  {
987
- cause: n
1110
+ cause: r
988
1111
  }
989
- ) : n;
1112
+ ) : r;
990
1113
  }
991
1114
  }
992
- rmdir(e, r = { recursive: !0 }) {
993
- r != null && r.recursive && this.listFiles(e).forEach((n) => {
994
- const s = `${e}/${n}`;
995
- this.isDir(s) ? this.rmdir(s, r) : this.unlink(s);
996
- }), this[f].FS.rmdir(e);
1115
+ rmdir(e, t = { recursive: !0 }) {
1116
+ t != null && t.recursive && this.listFiles(e).forEach((r) => {
1117
+ const s = `${e}/${r}`;
1118
+ this.isDir(s) ? this.rmdir(s, t) : this.unlink(s);
1119
+ }), this[__private__dont__use].FS.rmdir(e);
997
1120
  }
998
- listFiles(e, r = { prependPath: !1 }) {
1121
+ listFiles(e, t = { prependPath: !1 }) {
999
1122
  if (!this.fileExists(e))
1000
1123
  return [];
1001
1124
  try {
1002
- const n = this[f].FS.readdir(e).filter(
1125
+ const r = this[__private__dont__use].FS.readdir(e).filter(
1003
1126
  (s) => s !== "." && s !== ".."
1004
1127
  );
1005
- if (r.prependPath) {
1128
+ if (t.prependPath) {
1006
1129
  const s = e.replace(/\/$/, "");
1007
- return n.map((o) => `${s}/${o}`);
1130
+ return r.map((i) => `${s}/${i}`);
1008
1131
  }
1009
- return n;
1010
- } catch (n) {
1011
- return console.error(n, { path: e }), [];
1132
+ return r;
1133
+ } catch (r) {
1134
+ return console.error(r, { path: e }), [];
1012
1135
  }
1013
1136
  }
1014
1137
  isDir(e) {
1015
- return this.fileExists(e) ? this[f].FS.isDir(
1016
- this[f].FS.lookupPath(e).node.mode
1138
+ return this.fileExists(e) ? this[__private__dont__use].FS.isDir(
1139
+ this[__private__dont__use].FS.lookupPath(e).node.mode
1017
1140
  ) : !1;
1018
1141
  }
1019
1142
  fileExists(e) {
1020
1143
  try {
1021
- return this[f].FS.lookupPath(e), !0;
1144
+ return this[__private__dont__use].FS.lookupPath(e), !0;
1022
1145
  } catch {
1023
1146
  return !1;
1024
1147
  }
1025
1148
  }
1149
+ /**
1150
+ * Hot-swaps the PHP runtime for a new one without
1151
+ * interrupting the operations of this PHP instance.
1152
+ *
1153
+ * @param runtime
1154
+ */
1155
+ hotSwapPHPRuntime(e) {
1156
+ const t = this[__private__dont__use].FS;
1157
+ try {
1158
+ this.exit();
1159
+ } catch {
1160
+ }
1161
+ if (this.initializeRuntime(e), l(this, M) && this.setPhpIniPath(l(this, M)), l(this, I) && this.setSapiName(l(this, I)), this.requestHandler) {
1162
+ const r = this.documentRoot;
1163
+ recreateMemFS(this[__private__dont__use].FS, t, r);
1164
+ }
1165
+ }
1026
1166
  exit(e = 0) {
1027
- return this[f]._exit(e);
1167
+ this.dispatchEvent({
1168
+ type: "runtime.beforedestroy"
1169
+ });
1170
+ try {
1171
+ this[__private__dont__use]._exit(e);
1172
+ } catch {
1173
+ }
1174
+ p(this, w, !1), p(this, v, null), delete this[__private__dont__use].onMessage, delete this[__private__dont__use];
1028
1175
  }
1029
1176
  }
1030
- H = new WeakMap(), k = new WeakMap(), A = new WeakMap(), _ = new WeakMap(), S = new WeakMap(), B = new WeakMap(), j = new WeakMap(), re = new WeakSet(), $e = function() {
1177
+ T = new WeakMap(), M = new WeakMap(), I = new WeakMap(), w = new WeakMap(), v = new WeakMap(), b = new WeakMap(), P = new WeakMap(), A = new WeakMap(), O = new WeakSet(), te = function() {
1031
1178
  if (this.setPhpIniEntry("auto_prepend_file", "/tmp/consts.php"), this.fileExists("/tmp/consts.php") || this.writeFile(
1032
1179
  "/tmp/consts.php",
1033
1180
  `<?php
@@ -1039,553 +1186,583 @@ H = new WeakMap(), k = new WeakMap(), A = new WeakMap(), _ = new WeakMap(), S =
1039
1186
  }
1040
1187
  }
1041
1188
  }`
1042
- ), c(this, H).length > 0) {
1043
- const e = c(this, H).map(([r, n]) => `${r}=${n}`).join(`
1189
+ ), l(this, T).length > 0) {
1190
+ const e = l(this, T).map(([t, r]) => `${t}=${r}`).join(`
1044
1191
  `) + `
1045
1192
 
1046
1193
  `;
1047
- this[f].ccall(
1194
+ this[__private__dont__use].ccall(
1048
1195
  "wasm_set_phpini_entries",
1049
1196
  null,
1050
- [w],
1197
+ [STRING],
1051
1198
  [e]
1052
1199
  );
1053
1200
  }
1054
- this[f].ccall("php_wasm_init", null, [], []);
1055
- }, ne = new WeakSet(), We = function() {
1201
+ this[__private__dont__use].ccall("php_wasm_init", null, [], []);
1202
+ }, W = new WeakSet(), re = function() {
1056
1203
  const e = "/tmp/headers.json";
1057
1204
  if (!this.fileExists(e))
1058
1205
  throw new Error(
1059
1206
  "SAPI Error: Could not find response headers file."
1060
1207
  );
1061
- const r = JSON.parse(this.readFileAsText(e)), n = {};
1062
- for (const s of r.headers) {
1208
+ const t = JSON.parse(this.readFileAsText(e)), r = {};
1209
+ for (const s of t.headers) {
1063
1210
  if (!s.includes(": "))
1064
1211
  continue;
1065
- const o = s.indexOf(": "), i = s.substring(0, o).toLowerCase(), a = s.substring(o + 2);
1066
- i in n || (n[i] = []), n[i].push(a);
1212
+ const i = s.indexOf(": "), n = s.substring(0, i).toLowerCase(), o = s.substring(i + 2);
1213
+ n in r || (r[n] = []), r[n].push(o);
1067
1214
  }
1068
1215
  return {
1069
- headers: n,
1070
- httpStatusCode: r.status
1216
+ headers: r,
1217
+ httpStatusCode: t.status
1071
1218
  };
1072
- }, se = new WeakSet(), Be = function(e) {
1073
- if (this[f].ccall(
1219
+ }, q = new WeakSet(), se = function(e) {
1220
+ if (this[__private__dont__use].ccall(
1074
1221
  "wasm_set_request_uri",
1075
1222
  null,
1076
- [w],
1223
+ [STRING],
1077
1224
  [e]
1078
1225
  ), e.includes("?")) {
1079
- const r = e.substring(e.indexOf("?") + 1);
1080
- this[f].ccall(
1226
+ const t = e.substring(e.indexOf("?") + 1);
1227
+ this[__private__dont__use].ccall(
1081
1228
  "wasm_set_query_string",
1082
1229
  null,
1083
- [w],
1084
- [r]
1230
+ [STRING],
1231
+ [t]
1085
1232
  );
1086
1233
  }
1087
- }, ie = new WeakSet(), De = function(e, r) {
1088
- this[f].ccall(
1234
+ }, z = new WeakSet(), ne = function(e, t) {
1235
+ this[__private__dont__use].ccall(
1089
1236
  "wasm_set_request_host",
1090
1237
  null,
1091
- [w],
1238
+ [STRING],
1092
1239
  [e]
1093
1240
  );
1094
- let n;
1241
+ let r;
1095
1242
  try {
1096
- n = parseInt(new URL(e).port, 10);
1243
+ r = parseInt(new URL(e).port, 10);
1097
1244
  } catch {
1098
1245
  }
1099
- (!n || isNaN(n) || n === 80) && (n = r === "https" ? 443 : 80), this[f].ccall(
1246
+ (!r || isNaN(r) || r === 80) && (r = t === "https" ? 443 : 80), this[__private__dont__use].ccall(
1100
1247
  "wasm_set_request_port",
1101
1248
  null,
1102
- [M],
1103
- [n]
1104
- ), (r === "https" || !r && n === 443) && this.addServerGlobalEntry("HTTPS", "on");
1105
- }, oe = new WeakSet(), qe = function(e) {
1106
- this[f].ccall(
1249
+ [NUMBER],
1250
+ [r]
1251
+ ), (t === "https" || !t && r === 443) && this.addServerGlobalEntry("HTTPS", "on");
1252
+ }, D = new WeakSet(), ie = function(e) {
1253
+ this[__private__dont__use].ccall(
1107
1254
  "wasm_set_request_method",
1108
1255
  null,
1109
- [w],
1256
+ [STRING],
1110
1257
  [e]
1111
1258
  );
1112
- }, ae = new WeakSet(), ze = function(e) {
1113
- e.cookie && this[f].ccall(
1259
+ }, $ = new WeakSet(), oe = function(e) {
1260
+ e.cookie && this[__private__dont__use].ccall(
1114
1261
  "wasm_set_cookies",
1115
1262
  null,
1116
- [w],
1263
+ [STRING],
1117
1264
  [e.cookie]
1118
- ), e["content-type"] && this[f].ccall(
1265
+ ), e["content-type"] && this[__private__dont__use].ccall(
1119
1266
  "wasm_set_content_type",
1120
1267
  null,
1121
- [w],
1268
+ [STRING],
1122
1269
  [e["content-type"]]
1123
- ), e["content-length"] && this[f].ccall(
1270
+ ), e["content-length"] && this[__private__dont__use].ccall(
1124
1271
  "wasm_set_content_length",
1125
1272
  null,
1126
- [M],
1273
+ [NUMBER],
1127
1274
  [parseInt(e["content-length"], 10)]
1128
1275
  );
1129
- for (const r in e) {
1130
- let n = "HTTP_";
1131
- ["content-type", "content-length"].includes(r.toLowerCase()) && (n = ""), this.addServerGlobalEntry(
1132
- `${n}${r.toUpperCase().replace(/-/g, "_")}`,
1133
- e[r]
1276
+ for (const t in e) {
1277
+ let r = "HTTP_";
1278
+ ["content-type", "content-length"].includes(t.toLowerCase()) && (r = ""), this.addServerGlobalEntry(
1279
+ `${r}${t.toUpperCase().replace(/-/g, "_")}`,
1280
+ e[t]
1134
1281
  );
1135
1282
  }
1136
- }, ce = new WeakSet(), je = function(e) {
1137
- this[f].ccall(
1283
+ }, j = new WeakSet(), ae = function(e) {
1284
+ const t = this[__private__dont__use].lengthBytesUTF8(e), r = this[__private__dont__use].malloc(t + 1);
1285
+ if (!r)
1286
+ throw new Error("Could not allocate memory for the request body.");
1287
+ return this[__private__dont__use].stringToUTF8(
1288
+ e,
1289
+ r,
1290
+ t + 1
1291
+ ), this[__private__dont__use].ccall(
1138
1292
  "wasm_set_request_body",
1139
1293
  null,
1140
- [w],
1141
- [e]
1142
- ), this[f].ccall(
1294
+ [NUMBER],
1295
+ [r]
1296
+ ), this[__private__dont__use].ccall(
1143
1297
  "wasm_set_content_length",
1144
1298
  null,
1145
- [M],
1299
+ [NUMBER],
1146
1300
  [new TextEncoder().encode(e).length]
1147
- );
1148
- }, le = new WeakSet(), Ge = function(e) {
1149
- this[f].ccall(
1301
+ ), r;
1302
+ }, G = new WeakSet(), le = function(e) {
1303
+ this[__private__dont__use].ccall(
1150
1304
  "wasm_set_path_translated",
1151
1305
  null,
1152
- [w],
1306
+ [STRING],
1153
1307
  [e]
1154
1308
  );
1155
- }, ue = new WeakSet(), Ve = function() {
1156
- for (const e in c(this, _))
1157
- this[f].ccall(
1309
+ }, V = new WeakSet(), ce = function() {
1310
+ for (const e in l(this, b))
1311
+ this[__private__dont__use].ccall(
1158
1312
  "wasm_add_SERVER_entry",
1159
1313
  null,
1160
- [w, w],
1161
- [e, c(this, _)[e]]
1314
+ [STRING, STRING],
1315
+ [e, l(this, b)[e]]
1162
1316
  );
1163
- }, he = new WeakSet(), Ye = function(e) {
1164
- const { key: r, name: n, type: s, data: o } = e, i = `/tmp/${Math.random().toFixed(20)}`;
1165
- this.writeFile(i, o);
1166
- const a = 0;
1167
- this[f].ccall(
1317
+ }, Y = new WeakSet(), ue = function(e) {
1318
+ const { key: t, name: r, type: s, data: i } = e, n = `/tmp/${Math.random().toFixed(20)}`;
1319
+ this.writeFile(n, i);
1320
+ const o = 0;
1321
+ this[__private__dont__use].ccall(
1168
1322
  "wasm_add_uploaded_file",
1169
1323
  null,
1170
- [w, w, w, w, M, M],
1171
- [r, n, s, i, a, o.byteLength]
1324
+ [STRING, STRING, STRING, STRING, NUMBER, NUMBER],
1325
+ [t, r, s, n, o, i.byteLength]
1172
1326
  );
1173
- }, de = new WeakSet(), Je = function(e) {
1174
- this[f].ccall(
1327
+ }, J = new WeakSet(), de = function(e) {
1328
+ this[__private__dont__use].ccall(
1175
1329
  "wasm_set_php_code",
1176
1330
  null,
1177
- [w],
1331
+ [STRING],
1178
1332
  [e]
1179
1333
  );
1180
- }, fe = new WeakSet(), Ke = async function() {
1181
- var o;
1182
- let e, r;
1334
+ }, K = new WeakSet(), he = async function() {
1335
+ var i;
1336
+ let e, t;
1183
1337
  try {
1184
- e = await new Promise((i, a) => {
1185
- var l;
1186
- r = (h) => {
1187
- const m = new Error("Rethrown");
1188
- m.cause = h.error, m.betterMessage = h.message, a(m);
1189
- }, (l = c(this, A)) == null || l.addEventListener(
1338
+ e = await new Promise((n, o) => {
1339
+ var u;
1340
+ t = (c) => {
1341
+ const h = new Error("Rethrown");
1342
+ h.cause = c.error, h.betterMessage = c.message, o(h);
1343
+ }, (u = l(this, v)) == null || u.addEventListener(
1190
1344
  "error",
1191
- r
1345
+ t
1192
1346
  );
1193
- const u = this[f].ccall(
1347
+ const a = this[__private__dont__use].ccall(
1194
1348
  "wasm_sapi_handle_request",
1195
- M,
1349
+ NUMBER,
1196
1350
  [],
1197
1351
  [],
1198
1352
  { async: !0 }
1199
1353
  );
1200
- return u instanceof Promise ? u.then(i, a) : i(u);
1354
+ return a instanceof Promise ? a.then(n, o) : n(a);
1201
1355
  });
1202
- } catch (i) {
1203
- for (const h in this)
1204
- typeof this[h] == "function" && (this[h] = () => {
1356
+ } catch (n) {
1357
+ for (const c in this)
1358
+ typeof this[c] == "function" && (this[c] = () => {
1205
1359
  throw new Error(
1206
1360
  "PHP runtime has crashed – see the earlier error for details."
1207
1361
  );
1208
1362
  });
1209
- this.functionsMaybeMissingFromAsyncify = ht();
1210
- const a = i, u = "betterMessage" in a ? a.betterMessage : a.message, l = new Error(u);
1211
- throw l.cause = a, l;
1363
+ this.functionsMaybeMissingFromAsyncify = getFunctionsMaybeMissingFromAsyncify();
1364
+ const o = n, a = "betterMessage" in o ? o.betterMessage : o.message, u = new Error(a);
1365
+ throw u.cause = o, u;
1212
1366
  } finally {
1213
- (o = c(this, A)) == null || o.removeEventListener("error", r), y(this, _, {});
1367
+ (i = l(this, v)) == null || i.removeEventListener("error", t), p(this, b, {});
1214
1368
  }
1215
- const { headers: n, httpStatusCode: s } = g(this, ne, We).call(this);
1216
- return new L(
1369
+ const { headers: r, httpStatusCode: s } = m(this, W, re).call(this);
1370
+ return new PHPResponse(
1217
1371
  s,
1218
- n,
1372
+ r,
1219
1373
  this.readFileAsBuffer("/tmp/stdout"),
1220
1374
  this.readFileAsText("/tmp/stderr"),
1221
1375
  e
1222
1376
  );
1223
1377
  };
1224
- x([
1225
- R('Could not create directory "{path}"')
1226
- ], P.prototype, "mkdir", 1);
1227
- x([
1228
- R('Could not create directory "{path}"')
1229
- ], P.prototype, "mkdirTree", 1);
1230
- x([
1231
- R('Could not read "{path}"')
1232
- ], P.prototype, "readFileAsText", 1);
1233
- x([
1234
- R('Could not read "{path}"')
1235
- ], P.prototype, "readFileAsBuffer", 1);
1236
- x([
1237
- R('Could not write to "{path}"')
1238
- ], P.prototype, "writeFile", 1);
1239
- x([
1240
- R('Could not unlink "{path}"')
1241
- ], P.prototype, "unlink", 1);
1242
- x([
1243
- R('Could not remove directory "{path}"')
1244
- ], P.prototype, "rmdir", 1);
1245
- x([
1246
- R('Could not list files in "{path}"')
1247
- ], P.prototype, "listFiles", 1);
1248
- x([
1249
- R('Could not stat "{path}"')
1250
- ], P.prototype, "isDir", 1);
1251
- x([
1252
- R('Could not stat "{path}"')
1253
- ], P.prototype, "fileExists", 1);
1254
- function Qe(t) {
1255
- const e = {};
1256
- for (const r in t)
1257
- e[r.toLowerCase()] = t[r];
1258
- return e;
1378
+ __decorateClass([
1379
+ rethrowFileSystemError('Could not create directory "{path}"')
1380
+ ], BasePHP.prototype, "mkdir", 1);
1381
+ __decorateClass([
1382
+ rethrowFileSystemError('Could not create directory "{path}"')
1383
+ ], BasePHP.prototype, "mkdirTree", 1);
1384
+ __decorateClass([
1385
+ rethrowFileSystemError('Could not read "{path}"')
1386
+ ], BasePHP.prototype, "readFileAsText", 1);
1387
+ __decorateClass([
1388
+ rethrowFileSystemError('Could not read "{path}"')
1389
+ ], BasePHP.prototype, "readFileAsBuffer", 1);
1390
+ __decorateClass([
1391
+ rethrowFileSystemError('Could not write to "{path}"')
1392
+ ], BasePHP.prototype, "writeFile", 1);
1393
+ __decorateClass([
1394
+ rethrowFileSystemError('Could not unlink "{path}"')
1395
+ ], BasePHP.prototype, "unlink", 1);
1396
+ __decorateClass([
1397
+ rethrowFileSystemError('Could not remove directory "{path}"')
1398
+ ], BasePHP.prototype, "rmdir", 1);
1399
+ __decorateClass([
1400
+ rethrowFileSystemError('Could not list files in "{path}"')
1401
+ ], BasePHP.prototype, "listFiles", 1);
1402
+ __decorateClass([
1403
+ rethrowFileSystemError('Could not stat "{path}"')
1404
+ ], BasePHP.prototype, "isDir", 1);
1405
+ __decorateClass([
1406
+ rethrowFileSystemError('Could not stat "{path}"')
1407
+ ], BasePHP.prototype, "fileExists", 1);
1408
+ function normalizeHeaders(e) {
1409
+ const t = {};
1410
+ for (const r in e)
1411
+ t[r.toLowerCase()] = e[r];
1412
+ return t;
1413
+ }
1414
+ function recreateMemFS(e, t, r) {
1415
+ let s;
1416
+ try {
1417
+ s = t.lookupPath(r);
1418
+ } catch {
1419
+ return;
1420
+ }
1421
+ if (!("contents" in s.node))
1422
+ return;
1423
+ try {
1424
+ e = e.lookupPath(r);
1425
+ return;
1426
+ } catch {
1427
+ }
1428
+ if (!t.isDir(s.node.mode)) {
1429
+ e.writeFile(r, t.readFile(r));
1430
+ return;
1431
+ }
1432
+ e.mkdirTree(r);
1433
+ const i = t.readdir(r).filter((n) => n !== "." && n !== "..");
1434
+ for (const n of i)
1435
+ recreateMemFS(e, t, joinPaths(r, n));
1259
1436
  }
1260
1437
  /**
1261
1438
  * @license
1262
1439
  * Copyright 2019 Google LLC
1263
1440
  * SPDX-License-Identifier: Apache-2.0
1264
1441
  */
1265
- const Xe = Symbol("Comlink.proxy"), Ot = Symbol("Comlink.endpoint"), It = Symbol("Comlink.releaseProxy"), ye = Symbol("Comlink.finalizer"), Y = Symbol("Comlink.thrown"), Ze = (t) => typeof t == "object" && t !== null || typeof t == "function", Nt = {
1266
- canHandle: (t) => Ze(t) && t[Xe],
1267
- serialize(t) {
1268
- const { port1: e, port2: r } = new MessageChannel();
1269
- return pe(t, e), [r, [r]];
1442
+ const proxyMarker = Symbol("Comlink.proxy"), createEndpoint = Symbol("Comlink.endpoint"), releaseProxy = Symbol("Comlink.releaseProxy"), finalizer = Symbol("Comlink.finalizer"), throwMarker = Symbol("Comlink.thrown"), isObject = (e) => typeof e == "object" && e !== null || typeof e == "function", proxyTransferHandler = {
1443
+ canHandle: (e) => isObject(e) && e[proxyMarker],
1444
+ serialize(e) {
1445
+ const { port1: t, port2: r } = new MessageChannel();
1446
+ return expose(e, t), [r, [r]];
1270
1447
  },
1271
- deserialize(t) {
1272
- return t.start(), Ee(t);
1273
- }
1274
- }, Ut = {
1275
- canHandle: (t) => Ze(t) && Y in t,
1276
- serialize({ value: t }) {
1277
- let e;
1278
- return t instanceof Error ? e = {
1448
+ deserialize(e) {
1449
+ return e.start(), wrap(e);
1450
+ }
1451
+ }, throwTransferHandler = {
1452
+ canHandle: (e) => isObject(e) && throwMarker in e,
1453
+ serialize({ value: e }) {
1454
+ let t;
1455
+ return e instanceof Error ? t = {
1279
1456
  isError: !0,
1280
1457
  value: {
1281
- message: t.message,
1282
- name: t.name,
1283
- stack: t.stack
1458
+ message: e.message,
1459
+ name: e.name,
1460
+ stack: e.stack
1284
1461
  }
1285
- } : e = { isError: !1, value: t }, [e, []];
1462
+ } : t = { isError: !1, value: e }, [t, []];
1286
1463
  },
1287
- deserialize(t) {
1288
- throw t.isError ? Object.assign(new Error(t.value.message), t.value) : t.value;
1464
+ deserialize(e) {
1465
+ throw e.isError ? Object.assign(new Error(e.value.message), e.value) : e.value;
1289
1466
  }
1290
- }, q = /* @__PURE__ */ new Map([
1291
- ["proxy", Nt],
1292
- ["throw", Ut]
1467
+ }, transferHandlers = /* @__PURE__ */ new Map([
1468
+ ["proxy", proxyTransferHandler],
1469
+ ["throw", throwTransferHandler]
1293
1470
  ]);
1294
- function $t(t, e) {
1295
- for (const r of t)
1296
- if (e === r || r === "*" || r instanceof RegExp && r.test(e))
1471
+ function isAllowedOrigin(e, t) {
1472
+ for (const r of e)
1473
+ if (t === r || r === "*" || r instanceof RegExp && r.test(t))
1297
1474
  return !0;
1298
1475
  return !1;
1299
1476
  }
1300
- function pe(t, e = globalThis, r = ["*"]) {
1301
- e.addEventListener("message", function n(s) {
1302
- if (!s || !s.data)
1477
+ function expose(e, t = globalThis, r = ["*"]) {
1478
+ t.addEventListener("message", function s(i) {
1479
+ if (!i || !i.data)
1303
1480
  return;
1304
- if (!$t(r, s.origin)) {
1305
- console.warn(`Invalid origin '${s.origin}' for comlink proxy`);
1481
+ if (!isAllowedOrigin(r, i.origin)) {
1482
+ console.warn(`Invalid origin '${i.origin}' for comlink proxy`);
1306
1483
  return;
1307
1484
  }
1308
- const { id: o, type: i, path: a } = Object.assign({ path: [] }, s.data), u = (s.data.argumentList || []).map(T);
1309
- let l;
1485
+ const { id: n, type: o, path: a } = Object.assign({ path: [] }, i.data), u = (i.data.argumentList || []).map(fromWireValue);
1486
+ let c;
1310
1487
  try {
1311
- const h = a.slice(0, -1).reduce((b, D) => b[D], t), m = a.reduce((b, D) => b[D], t);
1312
- switch (i) {
1488
+ const h = a.slice(0, -1).reduce((f, y) => f[y], e), _ = a.reduce((f, y) => f[y], e);
1489
+ switch (o) {
1313
1490
  case "GET":
1314
- l = m;
1491
+ c = _;
1315
1492
  break;
1316
1493
  case "SET":
1317
- h[a.slice(-1)[0]] = T(s.data.value), l = !0;
1494
+ h[a.slice(-1)[0]] = fromWireValue(i.data.value), c = !0;
1318
1495
  break;
1319
1496
  case "APPLY":
1320
- l = m.apply(h, u);
1497
+ c = _.apply(h, u);
1321
1498
  break;
1322
1499
  case "CONSTRUCT":
1323
1500
  {
1324
- const b = new m(...u);
1325
- l = nt(b);
1501
+ const f = new _(...u);
1502
+ c = proxy(f);
1326
1503
  }
1327
1504
  break;
1328
1505
  case "ENDPOINT":
1329
1506
  {
1330
- const { port1: b, port2: D } = new MessageChannel();
1331
- pe(t, D), l = zt(b, [b]);
1507
+ const { port1: f, port2: y } = new MessageChannel();
1508
+ expose(e, y), c = transfer(f, [f]);
1332
1509
  }
1333
1510
  break;
1334
1511
  case "RELEASE":
1335
- l = void 0;
1512
+ c = void 0;
1336
1513
  break;
1337
1514
  default:
1338
1515
  return;
1339
1516
  }
1340
1517
  } catch (h) {
1341
- l = { value: h, [Y]: 0 };
1518
+ c = { value: h, [throwMarker]: 0 };
1342
1519
  }
1343
- Promise.resolve(l).catch((h) => ({ value: h, [Y]: 0 })).then((h) => {
1344
- const [m, b] = X(h);
1345
- e.postMessage(Object.assign(Object.assign({}, m), { id: o }), b), i === "RELEASE" && (e.removeEventListener("message", n), et(e), ye in t && typeof t[ye] == "function" && t[ye]());
1520
+ Promise.resolve(c).catch((h) => ({ value: h, [throwMarker]: 0 })).then((h) => {
1521
+ const [_, f] = toWireValue(h);
1522
+ t.postMessage(Object.assign(Object.assign({}, _), { id: n }), f), o === "RELEASE" && (t.removeEventListener("message", s), closeEndPoint(t), finalizer in e && typeof e[finalizer] == "function" && e[finalizer]());
1346
1523
  }).catch((h) => {
1347
- const [m, b] = X({
1524
+ const [_, f] = toWireValue({
1348
1525
  value: new TypeError("Unserializable return value"),
1349
- [Y]: 0
1526
+ [throwMarker]: 0
1350
1527
  });
1351
- e.postMessage(Object.assign(Object.assign({}, m), { id: o }), b);
1528
+ t.postMessage(Object.assign(Object.assign({}, _), { id: n }), f);
1352
1529
  });
1353
- }), e.start && e.start();
1530
+ }), t.start && t.start();
1354
1531
  }
1355
- function Wt(t) {
1356
- return t.constructor.name === "MessagePort";
1532
+ function isMessagePort(e) {
1533
+ return e.constructor.name === "MessagePort";
1357
1534
  }
1358
- function et(t) {
1359
- Wt(t) && t.close();
1535
+ function closeEndPoint(e) {
1536
+ isMessagePort(e) && e.close();
1360
1537
  }
1361
- function Ee(t, e) {
1362
- return we(t, [], e);
1538
+ function wrap(e, t) {
1539
+ return createProxy(e, [], t);
1363
1540
  }
1364
- function G(t) {
1365
- if (t)
1541
+ function throwIfProxyReleased(e) {
1542
+ if (e)
1366
1543
  throw new Error("Proxy has been released and is not useable");
1367
1544
  }
1368
- function tt(t) {
1369
- return O(t, {
1545
+ function releaseEndpoint(e) {
1546
+ return requestResponseMessage(e, {
1370
1547
  type: "RELEASE"
1371
1548
  }).then(() => {
1372
- et(t);
1549
+ closeEndPoint(e);
1373
1550
  });
1374
1551
  }
1375
- const K = /* @__PURE__ */ new WeakMap(), Q = "FinalizationRegistry" in globalThis && new FinalizationRegistry((t) => {
1376
- const e = (K.get(t) || 0) - 1;
1377
- K.set(t, e), e === 0 && tt(t);
1552
+ const proxyCounter = /* @__PURE__ */ new WeakMap(), proxyFinalizers = "FinalizationRegistry" in globalThis && new FinalizationRegistry((e) => {
1553
+ const t = (proxyCounter.get(e) || 0) - 1;
1554
+ proxyCounter.set(e, t), t === 0 && releaseEndpoint(e);
1378
1555
  });
1379
- function Bt(t, e) {
1380
- const r = (K.get(e) || 0) + 1;
1381
- K.set(e, r), Q && Q.register(t, e, t);
1556
+ function registerProxy(e, t) {
1557
+ const r = (proxyCounter.get(t) || 0) + 1;
1558
+ proxyCounter.set(t, r), proxyFinalizers && proxyFinalizers.register(e, t, e);
1382
1559
  }
1383
- function Dt(t) {
1384
- Q && Q.unregister(t);
1560
+ function unregisterProxy(e) {
1561
+ proxyFinalizers && proxyFinalizers.unregister(e);
1385
1562
  }
1386
- function we(t, e = [], r = function() {
1563
+ function createProxy(e, t = [], r = function() {
1387
1564
  }) {
1388
- let n = !1;
1389
- const s = new Proxy(r, {
1390
- get(o, i) {
1391
- if (G(n), i === It)
1565
+ let s = !1;
1566
+ const i = new Proxy(r, {
1567
+ get(n, o) {
1568
+ if (throwIfProxyReleased(s), o === releaseProxy)
1392
1569
  return () => {
1393
- Dt(s), tt(t), n = !0;
1570
+ unregisterProxy(i), releaseEndpoint(e), s = !0;
1394
1571
  };
1395
- if (i === "then") {
1396
- if (e.length === 0)
1397
- return { then: () => s };
1398
- const a = O(t, {
1572
+ if (o === "then") {
1573
+ if (t.length === 0)
1574
+ return { then: () => i };
1575
+ const a = requestResponseMessage(e, {
1399
1576
  type: "GET",
1400
- path: e.map((u) => u.toString())
1401
- }).then(T);
1577
+ path: t.map((u) => u.toString())
1578
+ }).then(fromWireValue);
1402
1579
  return a.then.bind(a);
1403
1580
  }
1404
- return we(t, [...e, i]);
1581
+ return createProxy(e, [...t, o]);
1405
1582
  },
1406
- set(o, i, a) {
1407
- G(n);
1408
- const [u, l] = X(a);
1409
- return O(t, {
1583
+ set(n, o, a) {
1584
+ throwIfProxyReleased(s);
1585
+ const [u, c] = toWireValue(a);
1586
+ return requestResponseMessage(e, {
1410
1587
  type: "SET",
1411
- path: [...e, i].map((h) => h.toString()),
1588
+ path: [...t, o].map((h) => h.toString()),
1412
1589
  value: u
1413
- }, l).then(T);
1590
+ }, c).then(fromWireValue);
1414
1591
  },
1415
- apply(o, i, a) {
1416
- G(n);
1417
- const u = e[e.length - 1];
1418
- if (u === Ot)
1419
- return O(t, {
1592
+ apply(n, o, a) {
1593
+ throwIfProxyReleased(s);
1594
+ const u = t[t.length - 1];
1595
+ if (u === createEndpoint)
1596
+ return requestResponseMessage(e, {
1420
1597
  type: "ENDPOINT"
1421
- }).then(T);
1598
+ }).then(fromWireValue);
1422
1599
  if (u === "bind")
1423
- return we(t, e.slice(0, -1));
1424
- const [l, h] = Ae(a);
1425
- return O(t, {
1600
+ return createProxy(e, t.slice(0, -1));
1601
+ const [c, h] = processArguments(a);
1602
+ return requestResponseMessage(e, {
1426
1603
  type: "APPLY",
1427
- path: e.map((m) => m.toString()),
1428
- argumentList: l
1429
- }, h).then(T);
1604
+ path: t.map((_) => _.toString()),
1605
+ argumentList: c
1606
+ }, h).then(fromWireValue);
1430
1607
  },
1431
- construct(o, i) {
1432
- G(n);
1433
- const [a, u] = Ae(i);
1434
- return O(t, {
1608
+ construct(n, o) {
1609
+ throwIfProxyReleased(s);
1610
+ const [a, u] = processArguments(o);
1611
+ return requestResponseMessage(e, {
1435
1612
  type: "CONSTRUCT",
1436
- path: e.map((l) => l.toString()),
1613
+ path: t.map((c) => c.toString()),
1437
1614
  argumentList: a
1438
- }, u).then(T);
1615
+ }, u).then(fromWireValue);
1439
1616
  }
1440
1617
  });
1441
- return Bt(s, t), s;
1618
+ return registerProxy(i, e), i;
1442
1619
  }
1443
- function qt(t) {
1444
- return Array.prototype.concat.apply([], t);
1620
+ function myFlat(e) {
1621
+ return Array.prototype.concat.apply([], e);
1445
1622
  }
1446
- function Ae(t) {
1447
- const e = t.map(X);
1448
- return [e.map((r) => r[0]), qt(e.map((r) => r[1]))];
1623
+ function processArguments(e) {
1624
+ const t = e.map(toWireValue);
1625
+ return [t.map((r) => r[0]), myFlat(t.map((r) => r[1]))];
1449
1626
  }
1450
- const rt = /* @__PURE__ */ new WeakMap();
1451
- function zt(t, e) {
1452
- return rt.set(t, e), t;
1627
+ const transferCache = /* @__PURE__ */ new WeakMap();
1628
+ function transfer(e, t) {
1629
+ return transferCache.set(e, t), e;
1453
1630
  }
1454
- function nt(t) {
1455
- return Object.assign(t, { [Xe]: !0 });
1631
+ function proxy(e) {
1632
+ return Object.assign(e, { [proxyMarker]: !0 });
1456
1633
  }
1457
- function st(t, e = globalThis, r = "*") {
1634
+ function windowEndpoint(e, t = globalThis, r = "*") {
1458
1635
  return {
1459
- postMessage: (n, s) => t.postMessage(n, r, s),
1460
- addEventListener: e.addEventListener.bind(e),
1461
- removeEventListener: e.removeEventListener.bind(e)
1636
+ postMessage: (s, i) => e.postMessage(s, r, i),
1637
+ addEventListener: t.addEventListener.bind(t),
1638
+ removeEventListener: t.removeEventListener.bind(t)
1462
1639
  };
1463
1640
  }
1464
- function X(t) {
1465
- for (const [e, r] of q)
1466
- if (r.canHandle(t)) {
1467
- const [n, s] = r.serialize(t);
1641
+ function toWireValue(e) {
1642
+ for (const [t, r] of transferHandlers)
1643
+ if (r.canHandle(e)) {
1644
+ const [s, i] = r.serialize(e);
1468
1645
  return [
1469
1646
  {
1470
1647
  type: "HANDLER",
1471
- name: e,
1472
- value: n
1648
+ name: t,
1649
+ value: s
1473
1650
  },
1474
- s
1651
+ i
1475
1652
  ];
1476
1653
  }
1477
1654
  return [
1478
1655
  {
1479
1656
  type: "RAW",
1480
- value: t
1657
+ value: e
1481
1658
  },
1482
- rt.get(t) || []
1659
+ transferCache.get(e) || []
1483
1660
  ];
1484
1661
  }
1485
- function T(t) {
1486
- switch (t.type) {
1662
+ function fromWireValue(e) {
1663
+ switch (e.type) {
1487
1664
  case "HANDLER":
1488
- return q.get(t.name).deserialize(t.value);
1665
+ return transferHandlers.get(e.name).deserialize(e.value);
1489
1666
  case "RAW":
1490
- return t.value;
1667
+ return e.value;
1491
1668
  }
1492
1669
  }
1493
- function O(t, e, r) {
1494
- return new Promise((n) => {
1495
- const s = jt();
1496
- t.addEventListener("message", function o(i) {
1497
- !i.data || !i.data.id || i.data.id !== s || (t.removeEventListener("message", o), n(i.data));
1498
- }), t.start && t.start(), t.postMessage(Object.assign({ id: s }, e), r);
1670
+ function requestResponseMessage(e, t, r) {
1671
+ return new Promise((s) => {
1672
+ const i = generateUUID();
1673
+ e.addEventListener("message", function n(o) {
1674
+ !o.data || !o.data.id || o.data.id !== i || (e.removeEventListener("message", n), s(o.data));
1675
+ }), e.start && e.start(), e.postMessage(Object.assign({ id: i }, t), r);
1499
1676
  });
1500
1677
  }
1501
- function jt() {
1678
+ function generateUUID() {
1502
1679
  return new Array(4).fill(0).map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16)).join("-");
1503
1680
  }
1504
- function Xt(t) {
1505
- it();
1506
- const e = t instanceof Worker ? t : st(t), r = Ee(e), n = ve(r);
1507
- return new Proxy(n, {
1508
- get: (s, o) => o === "isConnected" ? async () => {
1509
- for (let i = 0; i < 10; i++)
1681
+ function consumeAPI(e) {
1682
+ setupTransferHandlers();
1683
+ const t = e instanceof Worker ? e : windowEndpoint(e), r = wrap(t), s = proxyClone(r);
1684
+ return new Proxy(s, {
1685
+ get: (i, n) => n === "isConnected" ? async () => {
1686
+ for (let o = 0; o < 10; o++)
1510
1687
  try {
1511
- await Gt(r.isConnected(), 200);
1688
+ await runWithTimeout(r.isConnected(), 200);
1512
1689
  break;
1513
1690
  } catch {
1514
1691
  }
1515
- } : r[o]
1692
+ } : r[n]
1516
1693
  });
1517
1694
  }
1518
- async function Gt(t, e) {
1519
- return new Promise((r, n) => {
1520
- setTimeout(n, e), t.then(r);
1695
+ async function runWithTimeout(e, t) {
1696
+ return new Promise((r, s) => {
1697
+ setTimeout(s, t), e.then(r);
1521
1698
  });
1522
1699
  }
1523
- function Zt(t, e) {
1524
- it();
1700
+ function exposeAPI(e, t) {
1701
+ setupTransferHandlers();
1525
1702
  const r = Promise.resolve();
1526
- let n, s;
1527
- const o = new Promise((u, l) => {
1528
- n = u, s = l;
1529
- }), i = ve(t), a = new Proxy(i, {
1530
- get: (u, l) => l === "isConnected" ? () => r : l === "isReady" ? () => o : l in u ? u[l] : e == null ? void 0 : e[l]
1703
+ let s, i;
1704
+ const n = new Promise((u, c) => {
1705
+ s = u, i = c;
1706
+ }), o = proxyClone(e), a = new Proxy(o, {
1707
+ get: (u, c) => c === "isConnected" ? () => r : c === "isReady" ? () => n : c in u ? u[c] : t == null ? void 0 : t[c]
1531
1708
  });
1532
- return pe(
1709
+ return expose(
1533
1710
  a,
1534
- typeof window < "u" ? st(self.parent) : void 0
1535
- ), [n, s, a];
1536
- }
1537
- let Le = !1;
1538
- function it() {
1539
- Le || (Le = !0, q.set("EVENT", {
1540
- canHandle: (t) => t instanceof CustomEvent,
1541
- serialize: (t) => [
1711
+ typeof window < "u" ? windowEndpoint(self.parent) : void 0
1712
+ ), [s, i, a];
1713
+ }
1714
+ let isTransferHandlersSetup = !1;
1715
+ function setupTransferHandlers() {
1716
+ isTransferHandlersSetup || (isTransferHandlersSetup = !0, transferHandlers.set("EVENT", {
1717
+ canHandle: (e) => e instanceof CustomEvent,
1718
+ serialize: (e) => [
1542
1719
  {
1543
- detail: t.detail
1720
+ detail: e.detail
1544
1721
  },
1545
1722
  []
1546
1723
  ],
1547
- deserialize: (t) => t
1548
- }), q.set("FUNCTION", {
1549
- canHandle: (t) => typeof t == "function",
1550
- serialize(t) {
1724
+ deserialize: (e) => e
1725
+ }), transferHandlers.set("FUNCTION", {
1726
+ canHandle: (e) => typeof e == "function",
1727
+ serialize(e) {
1551
1728
  console.debug("[Comlink][Performance] Proxying a function");
1552
- const { port1: e, port2: r } = new MessageChannel();
1553
- return pe(t, e), [r, [r]];
1729
+ const { port1: t, port2: r } = new MessageChannel();
1730
+ return expose(e, t), [r, [r]];
1554
1731
  },
1555
- deserialize(t) {
1556
- return t.start(), Ee(t);
1732
+ deserialize(e) {
1733
+ return e.start(), wrap(e);
1557
1734
  }
1558
- }), q.set("PHPResponse", {
1559
- canHandle: (t) => typeof t == "object" && t !== null && "headers" in t && "bytes" in t && "errors" in t && "exitCode" in t && "httpStatusCode" in t,
1560
- serialize(t) {
1561
- return [t.toRawData(), []];
1735
+ }), transferHandlers.set("PHPResponse", {
1736
+ canHandle: (e) => typeof e == "object" && e !== null && "headers" in e && "bytes" in e && "errors" in e && "exitCode" in e && "httpStatusCode" in e,
1737
+ serialize(e) {
1738
+ return [e.toRawData(), []];
1562
1739
  },
1563
- deserialize(t) {
1564
- return L.fromRawData(t);
1740
+ deserialize(e) {
1741
+ return PHPResponse.fromRawData(e);
1565
1742
  }
1566
1743
  }));
1567
1744
  }
1568
- function ve(t) {
1569
- return new Proxy(t, {
1570
- get(e, r) {
1571
- switch (typeof e[r]) {
1745
+ function proxyClone(e) {
1746
+ return new Proxy(e, {
1747
+ get(t, r) {
1748
+ switch (typeof t[r]) {
1572
1749
  case "function":
1573
- return (...n) => e[r](...n);
1750
+ return (...s) => t[r](...s);
1574
1751
  case "object":
1575
- return e[r] === null ? e[r] : ve(e[r]);
1752
+ return t[r] === null ? t[r] : proxyClone(t[r]);
1576
1753
  case "undefined":
1577
1754
  case "number":
1578
1755
  case "string":
1579
- return e[r];
1756
+ return t[r];
1580
1757
  default:
1581
- return nt(e[r]);
1758
+ return proxy(t[r]);
1582
1759
  }
1583
1760
  }
1584
1761
  });
1585
1762
  }
1586
- async function Vt(t = wt, e = "light") {
1587
- if (e === "kitchen-sink")
1588
- switch (t) {
1763
+ async function getPHPLoaderModule(e = LatestSupportedPHPVersion, t = "light") {
1764
+ if (t === "kitchen-sink")
1765
+ switch (e) {
1589
1766
  case "8.3":
1590
1767
  return await import("./kitchen-sink/php_8_3.js");
1591
1768
  case "8.2":
@@ -1606,7 +1783,7 @@ async function Vt(t = wt, e = "light") {
1606
1783
  return await import("./kitchen-sink/php_7_0.js");
1607
1784
  }
1608
1785
  else
1609
- switch (t) {
1786
+ switch (e) {
1610
1787
  case "8.3":
1611
1788
  return await import("./light/php_8_3.js");
1612
1789
  case "8.2":
@@ -1626,11 +1803,11 @@ async function Vt(t = wt, e = "light") {
1626
1803
  case "7.0":
1627
1804
  return await import("./light/php_7_0.js");
1628
1805
  }
1629
- throw new Error(`Unsupported PHP version ${t}`);
1806
+ throw new Error(`Unsupported PHP version ${e}`);
1630
1807
  }
1631
- const Yt = () => ({
1808
+ const fakeWebsocket = () => ({
1632
1809
  websocket: {
1633
- decorator: (t) => class extends t {
1810
+ decorator: (e) => class extends e {
1634
1811
  constructor() {
1635
1812
  try {
1636
1813
  super();
@@ -1643,7 +1820,7 @@ const Yt = () => ({
1643
1820
  }
1644
1821
  }
1645
1822
  });
1646
- class be extends P {
1823
+ class WebPHP extends BasePHP {
1647
1824
  /**
1648
1825
  * Creates a new PHP instance.
1649
1826
  *
@@ -1656,209 +1833,199 @@ class be extends P {
1656
1833
  * @param options The options to use when loading PHP
1657
1834
  * @returns A new PHP instance
1658
1835
  */
1659
- static async load(e, r = {}) {
1660
- return await be.loadSync(e, r).phpReady;
1836
+ static async load(t, r = {}) {
1837
+ return new WebPHP(
1838
+ await WebPHP.loadRuntime(t, r),
1839
+ r.requestHandler
1840
+ );
1661
1841
  }
1662
- /**
1663
- * Does what load() does, but synchronously returns
1664
- * an object with the PHP instance and a promise that
1665
- * resolves when the PHP instance is ready.
1666
- *
1667
- * @see load
1668
- */
1669
- static loadSync(e, r = {}) {
1670
- const n = new be(void 0, r.requestHandler), s = r.loadAllExtensions ? "kitchen-sink" : "light", i = (async () => {
1671
- var m, b;
1672
- const a = await Promise.all([
1673
- Vt(e, s),
1674
- ...r.dataModules || []
1675
- ]), [u, ...l] = a;
1676
- (m = r.downloadMonitor) == null || m.setModules(a);
1677
- const h = await Ft(
1678
- u,
1679
- {
1680
- ...r.emscriptenOptions || {},
1681
- ...((b = r.downloadMonitor) == null ? void 0 : b.getEmscriptenOptions()) || {},
1682
- ...Yt()
1683
- },
1684
- l
1685
- );
1686
- n.initializeRuntime(h);
1687
- })();
1688
- return {
1689
- php: n,
1690
- phpReady: i.then(() => n)
1691
- };
1842
+ static async loadRuntime(t, r = {}) {
1843
+ var n;
1844
+ const s = r.loadAllExtensions ? "kitchen-sink" : "light", i = await getPHPLoaderModule(t, s);
1845
+ return (n = r.downloadMonitor) == null || n.expectAssets({
1846
+ [i.dependencyFilename]: i.dependenciesTotalSize
1847
+ }), await loadPHPRuntime(i, {
1848
+ ...r.emscriptenOptions || {},
1849
+ ...fakeWebsocket()
1850
+ });
1692
1851
  }
1693
1852
  }
1694
- const p = /* @__PURE__ */ new WeakMap();
1695
- class tr {
1853
+ const _private = /* @__PURE__ */ new WeakMap();
1854
+ class WebPHPEndpoint {
1696
1855
  /** @inheritDoc */
1697
- constructor(e, r) {
1698
- p.set(this, {
1699
- php: e,
1856
+ constructor(t, r) {
1857
+ _private.set(this, {
1858
+ php: t,
1700
1859
  monitor: r
1701
- }), this.absoluteUrl = e.absoluteUrl, this.documentRoot = e.documentRoot;
1860
+ }), this.absoluteUrl = t.absoluteUrl, this.documentRoot = t.documentRoot;
1702
1861
  }
1703
1862
  /** @inheritDoc @php-wasm/universal!RequestHandler.pathToInternalUrl */
1704
- pathToInternalUrl(e) {
1705
- return p.get(this).php.pathToInternalUrl(e);
1863
+ pathToInternalUrl(t) {
1864
+ return _private.get(this).php.pathToInternalUrl(t);
1706
1865
  }
1707
1866
  /** @inheritDoc @php-wasm/universal!RequestHandler.internalUrlToPath */
1708
- internalUrlToPath(e) {
1709
- return p.get(this).php.internalUrlToPath(e);
1867
+ internalUrlToPath(t) {
1868
+ return _private.get(this).php.internalUrlToPath(t);
1710
1869
  }
1711
1870
  /**
1712
1871
  * The onDownloadProgress event listener.
1713
1872
  */
1714
- async onDownloadProgress(e) {
1873
+ async onDownloadProgress(t) {
1715
1874
  var r;
1716
- return (r = p.get(this).monitor) == null ? void 0 : r.addEventListener("progress", e);
1875
+ return (r = _private.get(this).monitor) == null ? void 0 : r.addEventListener("progress", t);
1717
1876
  }
1718
1877
  /** @inheritDoc @php-wasm/universal!IsomorphicLocalPHP.mv */
1719
- mv(e, r) {
1720
- return p.get(this).php.mv(e, r);
1878
+ mv(t, r) {
1879
+ return _private.get(this).php.mv(t, r);
1721
1880
  }
1722
1881
  /** @inheritDoc @php-wasm/universal!IsomorphicLocalPHP.rmdir */
1723
- rmdir(e, r) {
1724
- return p.get(this).php.rmdir(e, r);
1882
+ rmdir(t, r) {
1883
+ return _private.get(this).php.rmdir(t, r);
1725
1884
  }
1726
1885
  /** @inheritDoc @php-wasm/universal!RequestHandler.request */
1727
- request(e, r) {
1728
- return p.get(this).php.request(e, r);
1886
+ request(t, r) {
1887
+ return _private.get(this).php.request(t, r);
1729
1888
  }
1730
1889
  /** @inheritDoc @php-wasm/web!WebPHP.run */
1731
- async run(e) {
1732
- return p.get(this).php.run(e);
1890
+ async run(t) {
1891
+ return _private.get(this).php.run(t);
1733
1892
  }
1734
1893
  /** @inheritDoc @php-wasm/web!WebPHP.setSpawnHandler */
1735
- setSpawnHandler(e) {
1736
- p.get(this).php.setSpawnHandler(e);
1894
+ setSpawnHandler(t) {
1895
+ _private.get(this).php.setSpawnHandler(t);
1737
1896
  }
1738
1897
  /** @inheritDoc @php-wasm/web!WebPHP.chdir */
1739
- chdir(e) {
1740
- return p.get(this).php.chdir(e);
1898
+ chdir(t) {
1899
+ return _private.get(this).php.chdir(t);
1900
+ }
1901
+ /** @inheritDoc @php-wasm/web!WebPHP.setSapiName */
1902
+ setSapiName(t) {
1903
+ _private.get(this).php.setSapiName(t);
1741
1904
  }
1742
1905
  /** @inheritDoc @php-wasm/web!WebPHP.setPhpIniPath */
1743
- setPhpIniPath(e) {
1744
- return p.get(this).php.setPhpIniPath(e);
1906
+ setPhpIniPath(t) {
1907
+ return _private.get(this).php.setPhpIniPath(t);
1745
1908
  }
1746
1909
  /** @inheritDoc @php-wasm/web!WebPHP.setPhpIniEntry */
1747
- setPhpIniEntry(e, r) {
1748
- return p.get(this).php.setPhpIniEntry(e, r);
1910
+ setPhpIniEntry(t, r) {
1911
+ return _private.get(this).php.setPhpIniEntry(t, r);
1749
1912
  }
1750
1913
  /** @inheritDoc @php-wasm/web!WebPHP.mkdir */
1751
- mkdir(e) {
1752
- return p.get(this).php.mkdir(e);
1914
+ mkdir(t) {
1915
+ return _private.get(this).php.mkdir(t);
1753
1916
  }
1754
1917
  /** @inheritDoc @php-wasm/web!WebPHP.mkdirTree */
1755
- mkdirTree(e) {
1756
- return p.get(this).php.mkdirTree(e);
1918
+ mkdirTree(t) {
1919
+ return _private.get(this).php.mkdirTree(t);
1757
1920
  }
1758
1921
  /** @inheritDoc @php-wasm/web!WebPHP.readFileAsText */
1759
- readFileAsText(e) {
1760
- return p.get(this).php.readFileAsText(e);
1922
+ readFileAsText(t) {
1923
+ return _private.get(this).php.readFileAsText(t);
1761
1924
  }
1762
1925
  /** @inheritDoc @php-wasm/web!WebPHP.readFileAsBuffer */
1763
- readFileAsBuffer(e) {
1764
- return p.get(this).php.readFileAsBuffer(e);
1926
+ readFileAsBuffer(t) {
1927
+ return _private.get(this).php.readFileAsBuffer(t);
1765
1928
  }
1766
1929
  /** @inheritDoc @php-wasm/web!WebPHP.writeFile */
1767
- writeFile(e, r) {
1768
- return p.get(this).php.writeFile(e, r);
1930
+ writeFile(t, r) {
1931
+ return _private.get(this).php.writeFile(t, r);
1769
1932
  }
1770
1933
  /** @inheritDoc @php-wasm/web!WebPHP.unlink */
1771
- unlink(e) {
1772
- return p.get(this).php.unlink(e);
1934
+ unlink(t) {
1935
+ return _private.get(this).php.unlink(t);
1773
1936
  }
1774
1937
  /** @inheritDoc @php-wasm/web!WebPHP.listFiles */
1775
- listFiles(e, r) {
1776
- return p.get(this).php.listFiles(e, r);
1938
+ listFiles(t, r) {
1939
+ return _private.get(this).php.listFiles(t, r);
1777
1940
  }
1778
1941
  /** @inheritDoc @php-wasm/web!WebPHP.isDir */
1779
- isDir(e) {
1780
- return p.get(this).php.isDir(e);
1942
+ isDir(t) {
1943
+ return _private.get(this).php.isDir(t);
1781
1944
  }
1782
1945
  /** @inheritDoc @php-wasm/web!WebPHP.fileExists */
1783
- fileExists(e) {
1784
- return p.get(this).php.fileExists(e);
1946
+ fileExists(t) {
1947
+ return _private.get(this).php.fileExists(t);
1785
1948
  }
1786
1949
  /** @inheritDoc @php-wasm/web!WebPHP.onMessage */
1787
- onMessage(e) {
1788
- p.get(this).php.onMessage(e);
1950
+ onMessage(t) {
1951
+ _private.get(this).php.onMessage(t);
1789
1952
  }
1790
1953
  /** @inheritDoc @php-wasm/web!WebPHP.defineConstant */
1791
- defineConstant(e, r) {
1792
- p.get(this).php.defineConstant(e, r);
1954
+ defineConstant(t, r) {
1955
+ _private.get(this).php.defineConstant(t, r);
1793
1956
  }
1794
1957
  /** @inheritDoc @php-wasm/web!WebPHP.addEventListener */
1795
- addEventListener(e, r) {
1796
- p.get(this).php.addEventListener(e, r);
1958
+ addEventListener(t, r) {
1959
+ _private.get(this).php.addEventListener(t, r);
1797
1960
  }
1798
1961
  /** @inheritDoc @php-wasm/web!WebPHP.removeEventListener */
1799
- removeEventListener(e, r) {
1800
- p.get(this).php.removeEventListener(e, r);
1962
+ removeEventListener(t, r) {
1963
+ _private.get(this).php.removeEventListener(t, r);
1801
1964
  }
1802
1965
  }
1803
- function Jt(t, e) {
1966
+ function responseTo(e, t) {
1804
1967
  return {
1805
1968
  type: "response",
1806
- requestId: t,
1807
- response: e
1969
+ requestId: e,
1970
+ response: t
1808
1971
  };
1809
1972
  }
1810
- async function rr(t, e, r) {
1811
- const n = navigator.serviceWorker;
1812
- if (!n)
1813
- throw new Error("Service workers are not supported in this browser.");
1814
- console.debug("[window][sw] Registering a Service Worker"), await (await n.register(r, {
1973
+ async function registerServiceWorker(e, t, r) {
1974
+ const s = navigator.serviceWorker;
1975
+ if (!s)
1976
+ throw location.protocol === "https:" ? new Error(
1977
+ "Service workers are not supported in this browser."
1978
+ ) : new Error(
1979
+ "WordPress Playground requires service workers which are only supported on HTTPS sites. This site does not use HTTPS, please retry on one that does. "
1980
+ );
1981
+ console.debug("[window][sw] Registering a Service Worker"), await (await s.register(r, {
1815
1982
  type: "module",
1816
1983
  // Always bypass HTTP cache when fetching the new Service Worker script:
1817
1984
  updateViaCache: "none"
1818
1985
  })).update(), navigator.serviceWorker.addEventListener(
1819
1986
  "message",
1820
- async function(i) {
1821
- if (console.debug("[window][sw] Message from ServiceWorker", i), e && i.data.scope !== e)
1987
+ async function(o) {
1988
+ if (console.debug("[window][sw] Message from ServiceWorker", o), t && o.data.scope !== t)
1822
1989
  return;
1823
- const a = i.data.args || [], u = i.data.method, l = await t[u](...a);
1824
- i.source.postMessage(Jt(i.data.requestId, l));
1990
+ const a = o.data.args || [], u = o.data.method, c = await e[u](...a);
1991
+ o.source.postMessage(responseTo(o.data.requestId, c));
1825
1992
  }
1826
- ), n.startMessages();
1993
+ ), s.startMessages();
1827
1994
  }
1828
- async function nr(t, e = {}) {
1829
- t = Kt(t, e);
1830
- const r = new Worker(t, { type: "module" });
1831
- return new Promise((n, s) => {
1832
- r.onerror = (i) => {
1995
+ async function spawnPHPWorkerThread(e, t = {}) {
1996
+ e = addQueryParams(e, t);
1997
+ const r = new Worker(e, { type: "module" });
1998
+ return new Promise((s, i) => {
1999
+ r.onerror = (o) => {
1833
2000
  const a = new Error(
1834
- `WebWorker failed to load at ${t}. ${i.message ? `Original error: ${i.message}` : ""}`
2001
+ `WebWorker failed to load at ${e}. ${o.message ? `Original error: ${o.message}` : ""}`
1835
2002
  );
1836
- a.filename = i.filename, s(a);
2003
+ a.filename = o.filename, i(a);
1837
2004
  };
1838
- function o(i) {
1839
- i.data === "worker-script-started" && (n(r), r.removeEventListener("message", o));
2005
+ function n(o) {
2006
+ o.data === "worker-script-started" && (s(r), r.removeEventListener("message", n));
1840
2007
  }
1841
- r.addEventListener("message", o);
2008
+ r.addEventListener("message", n);
1842
2009
  });
1843
2010
  }
1844
- function Kt(t, e) {
1845
- if (!Object.entries(e).length)
1846
- return t + "";
1847
- const r = new URL(t);
1848
- for (const [n, s] of Object.entries(e))
1849
- if (Array.isArray(s))
1850
- for (const o of s)
1851
- r.searchParams.append(n, o);
2011
+ function addQueryParams(e, t) {
2012
+ if (!Object.entries(t).length)
2013
+ return e + "";
2014
+ const r = new URL(e);
2015
+ for (const [s, i] of Object.entries(t))
2016
+ if (Array.isArray(i))
2017
+ for (const n of i)
2018
+ r.searchParams.append(s, n);
1852
2019
  else
1853
- r.searchParams.set(n, s);
2020
+ r.searchParams.set(s, i);
1854
2021
  return r.toString();
1855
2022
  }
1856
2023
  export {
1857
- be as WebPHP,
1858
- tr as WebPHPEndpoint,
1859
- Xt as consumeAPI,
1860
- Zt as exposeAPI,
1861
- Vt as getPHPLoaderModule,
1862
- rr as registerServiceWorker,
1863
- nr as spawnPHPWorkerThread
2024
+ WebPHP,
2025
+ WebPHPEndpoint,
2026
+ consumeAPI,
2027
+ exposeAPI,
2028
+ getPHPLoaderModule,
2029
+ registerServiceWorker,
2030
+ spawnPHPWorkerThread
1864
2031
  };