@php-wasm/web 0.5.5 → 0.6.0

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