@php-wasm/web 0.1.10 → 0.1.19

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.
@@ -0,0 +1,1342 @@
1
+ const W = [
2
+ "8.2",
3
+ "8.1",
4
+ "8.0",
5
+ "7.4",
6
+ "7.3",
7
+ "7.2",
8
+ "7.1",
9
+ "7.0",
10
+ "5.6"
11
+ ], Y = W[0], Se = W;
12
+ class K {
13
+ #e;
14
+ #t;
15
+ /**
16
+ * @param server - The PHP server to browse.
17
+ * @param config - The browser configuration.
18
+ */
19
+ constructor(e, r = {}) {
20
+ this.server = e, this.#e = {}, this.#t = {
21
+ handleRedirects: !1,
22
+ maxRedirects: 4,
23
+ ...r
24
+ };
25
+ }
26
+ /**
27
+ * Sends the request to the server.
28
+ *
29
+ * When cookies are present in the response, this method stores
30
+ * them and sends them with any subsequent requests.
31
+ *
32
+ * When a redirection is present in the response, this method
33
+ * follows it by discarding a response and sending a subsequent
34
+ * request.
35
+ *
36
+ * @param request - The request.
37
+ * @param redirects - Internal. The number of redirects handled so far.
38
+ * @returns PHPRequestHandler response.
39
+ */
40
+ async request(e, r = 0) {
41
+ const n = await this.server.request({
42
+ ...e,
43
+ headers: {
44
+ ...e.headers,
45
+ cookie: this.#s()
46
+ }
47
+ });
48
+ if (n.headers["set-cookie"] && this.#r(n.headers["set-cookie"]), this.#t.handleRedirects && n.headers.location && r < this.#t.maxRedirects) {
49
+ const s = new URL(
50
+ n.headers.location[0],
51
+ this.server.absoluteUrl
52
+ );
53
+ return this.request(
54
+ {
55
+ url: s.toString(),
56
+ method: "GET",
57
+ headers: {}
58
+ },
59
+ r + 1
60
+ );
61
+ }
62
+ return n;
63
+ }
64
+ #r(e) {
65
+ for (const r of e)
66
+ try {
67
+ if (!r.includes("="))
68
+ continue;
69
+ const n = r.indexOf("="), s = r.substring(0, n), a = r.substring(n + 1).split(";")[0];
70
+ this.#e[s] = a;
71
+ } catch (n) {
72
+ console.error(n);
73
+ }
74
+ }
75
+ #s() {
76
+ const e = [];
77
+ for (const r in this.#e)
78
+ e.push(`${r}=${this.#e[r]}`);
79
+ return e.join("; ");
80
+ }
81
+ }
82
+ const Q = "http://example.com";
83
+ function N(t) {
84
+ return t.toString().substring(t.origin.length);
85
+ }
86
+ function M(t, e) {
87
+ return !e || !t.startsWith(e) ? t : t.substring(e.length);
88
+ }
89
+ function X(t, e) {
90
+ return !e || t.startsWith(e) ? t : e + t;
91
+ }
92
+ class Z {
93
+ constructor({ concurrency: e }) {
94
+ this._running = 0, this.concurrency = e, this.queue = [];
95
+ }
96
+ get running() {
97
+ return this._running;
98
+ }
99
+ async acquire() {
100
+ for (; ; )
101
+ if (this._running >= this.concurrency)
102
+ await new Promise((e) => this.queue.push(e));
103
+ else
104
+ return this._running++, () => {
105
+ this._running--, this.queue.length > 0 && this.queue.shift()();
106
+ };
107
+ }
108
+ }
109
+ class E {
110
+ constructor(e, r, n, s = "", a = 0) {
111
+ this.httpStatusCode = e, this.headers = r, this.bytes = n, this.exitCode = a, this.errors = s;
112
+ }
113
+ static fromRawData(e) {
114
+ return new E(
115
+ e.httpStatusCode,
116
+ e.headers,
117
+ e.bytes,
118
+ e.errors,
119
+ e.exitCode
120
+ );
121
+ }
122
+ toRawData() {
123
+ return {
124
+ headers: this.headers,
125
+ bytes: this.bytes,
126
+ errors: this.errors,
127
+ exitCode: this.exitCode,
128
+ httpStatusCode: this.httpStatusCode
129
+ };
130
+ }
131
+ /**
132
+ * Response body as JSON.
133
+ */
134
+ get json() {
135
+ return JSON.parse(this.text);
136
+ }
137
+ /**
138
+ * Response body as text.
139
+ */
140
+ get text() {
141
+ return new TextDecoder().decode(this.bytes);
142
+ }
143
+ }
144
+ class ee {
145
+ #e;
146
+ #t;
147
+ #r;
148
+ #s;
149
+ #i;
150
+ #n;
151
+ #o;
152
+ #a;
153
+ #l;
154
+ /**
155
+ * @param php - The PHP instance.
156
+ * @param config - Request Handler configuration.
157
+ */
158
+ constructor(e, r = {}) {
159
+ this.#a = new Z({ concurrency: 1 });
160
+ const {
161
+ documentRoot: n = "/www/",
162
+ absoluteUrl: s = location.origin,
163
+ isStaticFilePath: a = () => !1
164
+ } = r;
165
+ this.php = e, this.#e = n, this.#l = a;
166
+ const i = new URL(s);
167
+ this.#r = i.hostname, this.#s = i.port ? Number(i.port) : i.protocol === "https:" ? 443 : 80, this.#t = (i.protocol || "").replace(":", "");
168
+ const o = this.#s !== 443 && this.#s !== 80;
169
+ this.#i = [
170
+ this.#r,
171
+ o ? `:${this.#s}` : ""
172
+ ].join(""), this.#n = i.pathname.replace(/\/+$/, ""), this.#o = [
173
+ `${this.#t}://`,
174
+ this.#i,
175
+ this.#n
176
+ ].join("");
177
+ }
178
+ /**
179
+ * Converts a path to an absolute URL based at the PHPRequestHandler
180
+ * root.
181
+ *
182
+ * @param path The server path to convert to an absolute URL.
183
+ * @returns The absolute URL.
184
+ */
185
+ pathToInternalUrl(e) {
186
+ return `${this.absoluteUrl}${e}`;
187
+ }
188
+ /**
189
+ * Converts an absolute URL based at the PHPRequestHandler to a relative path
190
+ * without the server pathname and scope.
191
+ *
192
+ * @param internalUrl An absolute URL based at the PHPRequestHandler root.
193
+ * @returns The relative path.
194
+ */
195
+ internalUrlToPath(e) {
196
+ const r = new URL(e);
197
+ return r.pathname.startsWith(this.#n) && (r.pathname = r.pathname.slice(this.#n.length)), N(r);
198
+ }
199
+ get isRequestRunning() {
200
+ return this.#a.running > 0;
201
+ }
202
+ /**
203
+ * The absolute URL of this PHPRequestHandler instance.
204
+ */
205
+ get absoluteUrl() {
206
+ return this.#o;
207
+ }
208
+ /**
209
+ * The absolute URL of this PHPRequestHandler instance.
210
+ */
211
+ get documentRoot() {
212
+ return this.#e;
213
+ }
214
+ /**
215
+ * Serves the request – either by serving a static file, or by
216
+ * dispatching it to the PHP runtime.
217
+ *
218
+ * @param request - The request.
219
+ * @returns The response.
220
+ */
221
+ async request(e) {
222
+ const r = e.url.startsWith("http://") || e.url.startsWith("https://"), n = new URL(
223
+ e.url,
224
+ r ? void 0 : Q
225
+ ), s = M(
226
+ n.pathname,
227
+ this.#n
228
+ );
229
+ return this.#l(s) ? this.#c(s) : await this.#u(e, n);
230
+ }
231
+ /**
232
+ * Serves a static file from the PHP filesystem.
233
+ *
234
+ * @param path - The requested static file path.
235
+ * @returns The response.
236
+ */
237
+ #c(e) {
238
+ const r = `${this.#e}${e}`;
239
+ if (!this.php.fileExists(r))
240
+ return new E(
241
+ 404,
242
+ {},
243
+ new TextEncoder().encode("404 File not found")
244
+ );
245
+ const n = this.php.readFileAsBuffer(r);
246
+ return new E(
247
+ 200,
248
+ {
249
+ "content-length": [`${n.byteLength}`],
250
+ // @TODO: Infer the content-type from the arrayBuffer instead of the file path.
251
+ // The code below won't return the correct mime-type if the extension
252
+ // was tampered with.
253
+ "content-type": [te(r)],
254
+ "accept-ranges": ["bytes"],
255
+ "cache-control": ["public, max-age=0"]
256
+ },
257
+ n
258
+ );
259
+ }
260
+ /**
261
+ * Runs the requested PHP file with all the request and $_SERVER
262
+ * superglobals populated.
263
+ *
264
+ * @param request - The request.
265
+ * @returns The response.
266
+ */
267
+ async #u(e, r) {
268
+ const n = await this.#a.acquire();
269
+ try {
270
+ this.php.addServerGlobalEntry("DOCUMENT_ROOT", this.#e), this.php.addServerGlobalEntry(
271
+ "HTTPS",
272
+ this.#o.startsWith("https://") ? "on" : ""
273
+ );
274
+ let s = "GET";
275
+ const a = [];
276
+ if (e.files) {
277
+ s = "POST";
278
+ for (const l in e.files) {
279
+ const c = e.files[l];
280
+ a.push({
281
+ key: l,
282
+ name: c.name,
283
+ type: c.type,
284
+ data: new Uint8Array(await c.arrayBuffer())
285
+ });
286
+ }
287
+ }
288
+ const i = {
289
+ host: this.#i
290
+ };
291
+ let o;
292
+ return e.formData !== void 0 ? (s = "POST", i["content-type"] = "application/x-www-form-urlencoded", o = new URLSearchParams(
293
+ e.formData
294
+ ).toString()) : o = e.body, await this.php.run({
295
+ relativeUri: X(
296
+ N(r),
297
+ this.#n
298
+ ),
299
+ protocol: this.#t,
300
+ method: e.method || s,
301
+ body: o,
302
+ fileInfos: a,
303
+ scriptPath: this.#h(r.pathname),
304
+ headers: {
305
+ ...i,
306
+ ...e.headers || {}
307
+ }
308
+ });
309
+ } finally {
310
+ n();
311
+ }
312
+ }
313
+ /**
314
+ * Resolve the requested path to the filesystem path of the requested PHP file.
315
+ *
316
+ * Fall back to index.php as if there was a url rewriting rule in place.
317
+ *
318
+ * @param requestedPath - The requested pathname.
319
+ * @returns The resolved filesystem path.
320
+ */
321
+ #h(e) {
322
+ let r = M(e, this.#n);
323
+ r.includes(".php") ? r = r.split(".php")[0] + ".php" : (r.endsWith("/") || (r += "/"), r.endsWith("index.php") || (r += "index.php"));
324
+ const n = `${this.#e}${r}`;
325
+ return this.php.fileExists(n) ? n : `${this.#e}/index.php`;
326
+ }
327
+ }
328
+ function te(t) {
329
+ switch (t.split(".").pop()) {
330
+ case "css":
331
+ return "text/css";
332
+ case "js":
333
+ return "application/javascript";
334
+ case "png":
335
+ return "image/png";
336
+ case "jpg":
337
+ case "jpeg":
338
+ return "image/jpeg";
339
+ case "gif":
340
+ return "image/gif";
341
+ case "svg":
342
+ return "image/svg+xml";
343
+ case "woff":
344
+ return "font/woff";
345
+ case "woff2":
346
+ return "font/woff2";
347
+ case "ttf":
348
+ return "font/ttf";
349
+ case "otf":
350
+ return "font/otf";
351
+ case "eot":
352
+ return "font/eot";
353
+ case "ico":
354
+ return "image/x-icon";
355
+ case "html":
356
+ return "text/html";
357
+ case "json":
358
+ return "application/json";
359
+ case "xml":
360
+ return "application/xml";
361
+ case "txt":
362
+ case "md":
363
+ return "text/plain";
364
+ default:
365
+ return "application-octet-stream";
366
+ }
367
+ }
368
+ const I = {
369
+ 0: "No error occurred. System call completed successfully.",
370
+ 1: "Argument list too long.",
371
+ 2: "Permission denied.",
372
+ 3: "Address in use.",
373
+ 4: "Address not available.",
374
+ 5: "Address family not supported.",
375
+ 6: "Resource unavailable, or operation would block.",
376
+ 7: "Connection already in progress.",
377
+ 8: "Bad file descriptor.",
378
+ 9: "Bad message.",
379
+ 10: "Device or resource busy.",
380
+ 11: "Operation canceled.",
381
+ 12: "No child processes.",
382
+ 13: "Connection aborted.",
383
+ 14: "Connection refused.",
384
+ 15: "Connection reset.",
385
+ 16: "Resource deadlock would occur.",
386
+ 17: "Destination address required.",
387
+ 18: "Mathematics argument out of domain of function.",
388
+ 19: "Reserved.",
389
+ 20: "File exists.",
390
+ 21: "Bad address.",
391
+ 22: "File too large.",
392
+ 23: "Host is unreachable.",
393
+ 24: "Identifier removed.",
394
+ 25: "Illegal byte sequence.",
395
+ 26: "Operation in progress.",
396
+ 27: "Interrupted function.",
397
+ 28: "Invalid argument.",
398
+ 29: "I/O error.",
399
+ 30: "Socket is connected.",
400
+ 31: "There is a directory under that path.",
401
+ 32: "Too many levels of symbolic links.",
402
+ 33: "File descriptor value too large.",
403
+ 34: "Too many links.",
404
+ 35: "Message too large.",
405
+ 36: "Reserved.",
406
+ 37: "Filename too long.",
407
+ 38: "Network is down.",
408
+ 39: "Connection aborted by network.",
409
+ 40: "Network unreachable.",
410
+ 41: "Too many files open in system.",
411
+ 42: "No buffer space available.",
412
+ 43: "No such device.",
413
+ 44: "There is no such file or directory OR the parent directory does not exist.",
414
+ 45: "Executable file format error.",
415
+ 46: "No locks available.",
416
+ 47: "Reserved.",
417
+ 48: "Not enough space.",
418
+ 49: "No message of the desired type.",
419
+ 50: "Protocol not available.",
420
+ 51: "No space left on device.",
421
+ 52: "Function not supported.",
422
+ 53: "The socket is not connected.",
423
+ 54: "Not a directory or a symbolic link to a directory.",
424
+ 55: "Directory not empty.",
425
+ 56: "State not recoverable.",
426
+ 57: "Not a socket.",
427
+ 58: "Not supported, or operation not supported on socket.",
428
+ 59: "Inappropriate I/O control operation.",
429
+ 60: "No such device or address.",
430
+ 61: "Value too large to be stored in data type.",
431
+ 62: "Previous owner died.",
432
+ 63: "Operation not permitted.",
433
+ 64: "Broken pipe.",
434
+ 65: "Protocol error.",
435
+ 66: "Protocol not supported.",
436
+ 67: "Protocol wrong type for socket.",
437
+ 68: "Result too large.",
438
+ 69: "Read-only file system.",
439
+ 70: "Invalid seek.",
440
+ 71: "No such process.",
441
+ 72: "Reserved.",
442
+ 73: "Connection timed out.",
443
+ 74: "Text file busy.",
444
+ 75: "Cross-device link.",
445
+ 76: "Extension: Capabilities insufficient."
446
+ };
447
+ function g(t = "") {
448
+ return function(r, n, s) {
449
+ const a = s.value;
450
+ s.value = function(...i) {
451
+ try {
452
+ return a.apply(this, i);
453
+ } catch (o) {
454
+ const l = typeof o == "object" ? o?.errno : null;
455
+ if (l in I) {
456
+ const c = I[l], u = typeof i[0] == "string" ? i[0] : null, p = u !== null ? t.replaceAll("{path}", u) : t;
457
+ throw new Error(`${p}: ${c}`, {
458
+ cause: o
459
+ });
460
+ }
461
+ throw o;
462
+ }
463
+ };
464
+ };
465
+ }
466
+ var re = Object.defineProperty, ne = Object.getOwnPropertyDescriptor, w = (t, e, r, n) => {
467
+ for (var s = n > 1 ? void 0 : n ? ne(e, r) : e, a = t.length - 1, i; a >= 0; a--)
468
+ (i = t[a]) && (s = (n ? i(e, r, s) : i(s)) || s);
469
+ return n && s && re(e, r, s), s;
470
+ };
471
+ const h = "string", y = "number", _ = [], se = function() {
472
+ return typeof window < "u" && !{}.TEST ? "WEB" : typeof WorkerGlobalScope < "u" && self instanceof WorkerGlobalScope ? "WORKER" : "NODE";
473
+ }();
474
+ class m {
475
+ /**
476
+ * Initializes a PHP runtime.
477
+ *
478
+ * @internal
479
+ * @param PHPRuntime - Optional. PHP Runtime ID as initialized by loadPHPRuntime.
480
+ * @param serverOptions - Optional. Options for the PHPRequestHandler. If undefined, no request handler will be initialized.
481
+ */
482
+ constructor(e, r) {
483
+ this.#t = [], this.#r = !1, e !== void 0 && this.initializeRuntime(e), r && (this.requestHandler = new K(
484
+ new ee(this, r)
485
+ ));
486
+ }
487
+ #e;
488
+ #t;
489
+ #r;
490
+ initializeRuntime(e) {
491
+ if (this.#e)
492
+ throw new Error("PHP runtime already initialized.");
493
+ if (!_[e])
494
+ throw new Error("Invalid PHP runtime id.");
495
+ this.#e = _[e];
496
+ }
497
+ /** @inheritDoc */
498
+ setPhpIniPath(e) {
499
+ if (this.#r)
500
+ throw new Error("Cannot set PHP ini path after calling run().");
501
+ this.#e.ccall("wasm_set_phpini_path", null, ["string"], [e]);
502
+ }
503
+ /** @inheritDoc */
504
+ setPhpIniEntry(e, r) {
505
+ if (this.#r)
506
+ throw new Error("Cannot set PHP ini entries after calling run().");
507
+ this.#t.push([e, r]);
508
+ }
509
+ /** @inheritDoc */
510
+ chdir(e) {
511
+ this.#e.FS.chdir(e);
512
+ }
513
+ /** @inheritDoc */
514
+ async request(e, r) {
515
+ if (!this.requestHandler)
516
+ throw new Error("No request handler available.");
517
+ return this.requestHandler.request(e, r);
518
+ }
519
+ /** @inheritDoc */
520
+ async run(e = {}) {
521
+ this.#r || (this.#s(), this.#r = !0), this.#u(e.scriptPath || ""), this.#n(e.relativeUri || ""), this.#a(e.method || "GET");
522
+ const { host: r, ...n } = {
523
+ host: "example.com:443",
524
+ ...ie(e.headers || {})
525
+ };
526
+ if (this.#o(r, e.protocol || "http"), this.#l(n), e.body && this.#c(e.body), e.fileInfos)
527
+ for (const s of e.fileInfos)
528
+ this.#h(s);
529
+ return e.code && this.#d(" ?>" + e.code), await this.#f();
530
+ }
531
+ #s() {
532
+ if (this.#t.length > 0) {
533
+ const e = this.#t.map(([r, n]) => `${r}=${n}`).join(`
534
+ `) + `
535
+
536
+ `;
537
+ this.#e.ccall(
538
+ "wasm_set_phpini_entries",
539
+ null,
540
+ [h],
541
+ [e]
542
+ );
543
+ }
544
+ this.#e.ccall("php_wasm_init", null, [], []);
545
+ }
546
+ cli(e) {
547
+ for (const r of e)
548
+ this.#e.ccall("wasm_add_cli_arg", null, [h], [r]);
549
+ return this.#e.ccall("run_cli", null, [], [], { async: !0 });
550
+ }
551
+ #i() {
552
+ const e = "/tmp/headers.json";
553
+ if (!this.fileExists(e))
554
+ throw new Error(
555
+ "SAPI Error: Could not find response headers file."
556
+ );
557
+ const r = JSON.parse(this.readFileAsText(e)), n = {};
558
+ for (const s of r.headers) {
559
+ if (!s.includes(": "))
560
+ continue;
561
+ const a = s.indexOf(": "), i = s.substring(0, a).toLowerCase(), o = s.substring(a + 2);
562
+ i in n || (n[i] = []), n[i].push(o);
563
+ }
564
+ return {
565
+ headers: n,
566
+ httpStatusCode: r.status
567
+ };
568
+ }
569
+ #n(e) {
570
+ if (this.#e.ccall("wasm_set_request_uri", null, [h], [e]), e.includes("?")) {
571
+ const r = e.substring(e.indexOf("?") + 1);
572
+ this.#e.ccall(
573
+ "wasm_set_query_string",
574
+ null,
575
+ [h],
576
+ [r]
577
+ );
578
+ }
579
+ }
580
+ #o(e, r) {
581
+ this.#e.ccall("wasm_set_request_host", null, [h], [e]);
582
+ let n;
583
+ try {
584
+ n = parseInt(new URL(e).port, 10);
585
+ } catch {
586
+ }
587
+ (!n || isNaN(n) || n === 80) && (n = r === "https" ? 443 : 80), this.#e.ccall("wasm_set_request_port", null, [y], [n]), (r === "https" || !r && n === 443) && this.addServerGlobalEntry("HTTPS", "on");
588
+ }
589
+ #a(e) {
590
+ this.#e.ccall("wasm_set_request_method", null, [h], [e]);
591
+ }
592
+ setSkipShebang(e) {
593
+ this.#e.ccall(
594
+ "wasm_set_skip_shebang",
595
+ null,
596
+ [y],
597
+ [e ? 1 : 0]
598
+ );
599
+ }
600
+ #l(e) {
601
+ e.cookie && this.#e.ccall(
602
+ "wasm_set_cookies",
603
+ null,
604
+ [h],
605
+ [e.cookie]
606
+ ), e["content-type"] && this.#e.ccall(
607
+ "wasm_set_content_type",
608
+ null,
609
+ [h],
610
+ [e["content-type"]]
611
+ ), e["content-length"] && this.#e.ccall(
612
+ "wasm_set_content_length",
613
+ null,
614
+ [y],
615
+ [parseInt(e["content-length"], 10)]
616
+ );
617
+ for (const r in e)
618
+ this.addServerGlobalEntry(
619
+ `HTTP_${r.toUpperCase().replace(/-/g, "_")}`,
620
+ e[r]
621
+ );
622
+ }
623
+ #c(e) {
624
+ this.#e.ccall("wasm_set_request_body", null, [h], [e]), this.#e.ccall(
625
+ "wasm_set_content_length",
626
+ null,
627
+ [y],
628
+ [e.length]
629
+ );
630
+ }
631
+ #u(e) {
632
+ this.#e.ccall("wasm_set_path_translated", null, [h], [e]);
633
+ }
634
+ addServerGlobalEntry(e, r) {
635
+ this.#e.ccall(
636
+ "wasm_add_SERVER_entry",
637
+ null,
638
+ [h, h],
639
+ [e, r]
640
+ );
641
+ }
642
+ /**
643
+ * Adds file information to $_FILES superglobal in PHP.
644
+ *
645
+ * In particular:
646
+ * * Creates the file data in the filesystem
647
+ * * Registers the file details in PHP
648
+ *
649
+ * @param fileInfo - File details
650
+ */
651
+ #h(e) {
652
+ const { key: r, name: n, type: s, data: a } = e, i = `/tmp/${Math.random().toFixed(20)}`;
653
+ this.writeFile(i, a);
654
+ const o = 0;
655
+ this.#e.ccall(
656
+ "wasm_add_uploaded_file",
657
+ null,
658
+ [h, h, h, h, y, y],
659
+ [r, n, s, i, o, a.byteLength]
660
+ );
661
+ }
662
+ #d(e) {
663
+ this.#e.ccall("wasm_set_php_code", null, [h], [e]);
664
+ }
665
+ async #f() {
666
+ const e = await await this.#e.ccall(
667
+ "wasm_sapi_handle_request",
668
+ y,
669
+ [],
670
+ []
671
+ ), { headers: r, httpStatusCode: n } = this.#i();
672
+ return new E(
673
+ n,
674
+ r,
675
+ this.readFileAsBuffer("/tmp/stdout"),
676
+ this.readFileAsText("/tmp/stderr"),
677
+ e
678
+ );
679
+ }
680
+ mkdirTree(e) {
681
+ this.#e.FS.mkdirTree(e);
682
+ }
683
+ readFileAsText(e) {
684
+ return new TextDecoder().decode(this.readFileAsBuffer(e));
685
+ }
686
+ readFileAsBuffer(e) {
687
+ return this.#e.FS.readFile(e);
688
+ }
689
+ writeFile(e, r) {
690
+ this.#e.FS.writeFile(e, r);
691
+ }
692
+ unlink(e) {
693
+ this.#e.FS.unlink(e);
694
+ }
695
+ listFiles(e) {
696
+ if (!this.fileExists(e))
697
+ return [];
698
+ try {
699
+ return this.#e.FS.readdir(e).filter(
700
+ (r) => r !== "." && r !== ".."
701
+ );
702
+ } catch (r) {
703
+ return console.error(r, { path: e }), [];
704
+ }
705
+ }
706
+ isDir(e) {
707
+ return this.fileExists(e) ? this.#e.FS.isDir(
708
+ this.#e.FS.lookupPath(e).node.mode
709
+ ) : !1;
710
+ }
711
+ fileExists(e) {
712
+ try {
713
+ return this.#e.FS.lookupPath(e), !0;
714
+ } catch {
715
+ return !1;
716
+ }
717
+ }
718
+ mount(e, r) {
719
+ this.#e.FS.mount(
720
+ this.#e.FS.filesystems.NODEFS,
721
+ e,
722
+ r
723
+ );
724
+ }
725
+ }
726
+ w([
727
+ g('Could not create directory "{path}"')
728
+ ], m.prototype, "mkdirTree", 1);
729
+ w([
730
+ g('Could not read "{path}"')
731
+ ], m.prototype, "readFileAsText", 1);
732
+ w([
733
+ g('Could not read "{path}"')
734
+ ], m.prototype, "readFileAsBuffer", 1);
735
+ w([
736
+ g('Could not write to "{path}"')
737
+ ], m.prototype, "writeFile", 1);
738
+ w([
739
+ g('Could not unlink "{path}"')
740
+ ], m.prototype, "unlink", 1);
741
+ w([
742
+ g('Could not list files in "{path}"')
743
+ ], m.prototype, "listFiles", 1);
744
+ w([
745
+ g('Could not stat "{path}"')
746
+ ], m.prototype, "isDir", 1);
747
+ w([
748
+ g('Could not stat "{path}"')
749
+ ], m.prototype, "fileExists", 1);
750
+ w([
751
+ g("Could not mount a directory")
752
+ ], m.prototype, "mount", 1);
753
+ function ie(t) {
754
+ const e = {};
755
+ for (const r in t)
756
+ e[r.toLowerCase()] = t[r];
757
+ return e;
758
+ }
759
+ async function oe(t, e = {}, r = []) {
760
+ let n, s;
761
+ const a = new Promise((l) => {
762
+ s = l;
763
+ }), i = new Promise((l) => {
764
+ n = l;
765
+ }), o = t.init(se, {
766
+ onAbort(l) {
767
+ console.error("WASM aborted: "), console.error(l);
768
+ },
769
+ ENV: {},
770
+ // Emscripten sometimes prepends a '/' to the path, which
771
+ // breaks vite dev mode. An identity `locateFile` function
772
+ // fixes it.
773
+ locateFile: (l) => l,
774
+ ...e,
775
+ noInitialRun: !0,
776
+ onRuntimeInitialized() {
777
+ e.onRuntimeInitialized && e.onRuntimeInitialized(), n();
778
+ },
779
+ monitorRunDependencies(l) {
780
+ l === 0 && (delete o.monitorRunDependencies, s());
781
+ }
782
+ });
783
+ for (const { default: l } of r)
784
+ l(o);
785
+ return r.length || s(), await a, await i, _.push(o), _.length - 1;
786
+ }
787
+ /**
788
+ * @license
789
+ * Copyright 2019 Google LLC
790
+ * SPDX-License-Identifier: Apache-2.0
791
+ */
792
+ const D = Symbol("Comlink.proxy"), ae = Symbol("Comlink.endpoint"), le = Symbol("Comlink.releaseProxy"), O = Symbol("Comlink.finalizer"), x = Symbol("Comlink.thrown"), z = (t) => typeof t == "object" && t !== null || typeof t == "function", ce = {
793
+ canHandle: (t) => z(t) && t[D],
794
+ serialize(t) {
795
+ const { port1: e, port2: r } = new MessageChannel();
796
+ return F(t, e), [r, [r]];
797
+ },
798
+ deserialize(t) {
799
+ return t.start(), L(t);
800
+ }
801
+ }, ue = {
802
+ canHandle: (t) => z(t) && x in t,
803
+ serialize({ value: t }) {
804
+ let e;
805
+ return t instanceof Error ? e = {
806
+ isError: !0,
807
+ value: {
808
+ message: t.message,
809
+ name: t.name,
810
+ stack: t.stack
811
+ }
812
+ } : e = { isError: !1, value: t }, [e, []];
813
+ },
814
+ deserialize(t) {
815
+ throw t.isError ? Object.assign(new Error(t.value.message), t.value) : t.value;
816
+ }
817
+ }, S = /* @__PURE__ */ new Map([
818
+ ["proxy", ce],
819
+ ["throw", ue]
820
+ ]);
821
+ function he(t, e) {
822
+ for (const r of t)
823
+ if (e === r || r === "*" || r instanceof RegExp && r.test(e))
824
+ return !0;
825
+ return !1;
826
+ }
827
+ function F(t, e = globalThis, r = ["*"]) {
828
+ e.addEventListener("message", function n(s) {
829
+ if (!s || !s.data)
830
+ return;
831
+ if (!he(r, s.origin)) {
832
+ console.warn(`Invalid origin '${s.origin}' for comlink proxy`);
833
+ return;
834
+ }
835
+ const { id: a, type: i, path: o } = Object.assign({ path: [] }, s.data), l = (s.data.argumentList || []).map(P);
836
+ let c;
837
+ try {
838
+ const u = o.slice(0, -1).reduce((f, R) => f[R], t), p = o.reduce((f, R) => f[R], t);
839
+ switch (i) {
840
+ case "GET":
841
+ c = p;
842
+ break;
843
+ case "SET":
844
+ u[o.slice(-1)[0]] = P(s.data.value), c = !0;
845
+ break;
846
+ case "APPLY":
847
+ c = p.apply(u, l);
848
+ break;
849
+ case "CONSTRUCT":
850
+ {
851
+ const f = new p(...l);
852
+ c = B(f);
853
+ }
854
+ break;
855
+ case "ENDPOINT":
856
+ {
857
+ const { port1: f, port2: R } = new MessageChannel();
858
+ F(t, R), c = ge(f, [f]);
859
+ }
860
+ break;
861
+ case "RELEASE":
862
+ c = void 0;
863
+ break;
864
+ default:
865
+ return;
866
+ }
867
+ } catch (u) {
868
+ c = { value: u, [x]: 0 };
869
+ }
870
+ Promise.resolve(c).catch((u) => ({ value: u, [x]: 0 })).then((u) => {
871
+ const [p, f] = C(u);
872
+ e.postMessage(Object.assign(Object.assign({}, p), { id: a }), f), i === "RELEASE" && (e.removeEventListener("message", n), $(e), O in t && typeof t[O] == "function" && t[O]());
873
+ }).catch((u) => {
874
+ const [p, f] = C({
875
+ value: new TypeError("Unserializable return value"),
876
+ [x]: 0
877
+ });
878
+ e.postMessage(Object.assign(Object.assign({}, p), { id: a }), f);
879
+ });
880
+ }), e.start && e.start();
881
+ }
882
+ function de(t) {
883
+ return t.constructor.name === "MessagePort";
884
+ }
885
+ function $(t) {
886
+ de(t) && t.close();
887
+ }
888
+ function L(t, e) {
889
+ return H(t, [], e);
890
+ }
891
+ function v(t) {
892
+ if (t)
893
+ throw new Error("Proxy has been released and is not useable");
894
+ }
895
+ function q(t) {
896
+ return b(t, {
897
+ type: "RELEASE"
898
+ }).then(() => {
899
+ $(t);
900
+ });
901
+ }
902
+ const k = /* @__PURE__ */ new WeakMap(), T = "FinalizationRegistry" in globalThis && new FinalizationRegistry((t) => {
903
+ const e = (k.get(t) || 0) - 1;
904
+ k.set(t, e), e === 0 && q(t);
905
+ });
906
+ function fe(t, e) {
907
+ const r = (k.get(e) || 0) + 1;
908
+ k.set(e, r), T && T.register(t, e, t);
909
+ }
910
+ function pe(t) {
911
+ T && T.unregister(t);
912
+ }
913
+ function H(t, e = [], r = function() {
914
+ }) {
915
+ let n = !1;
916
+ const s = new Proxy(r, {
917
+ get(a, i) {
918
+ if (v(n), i === le)
919
+ return () => {
920
+ pe(s), q(t), n = !0;
921
+ };
922
+ if (i === "then") {
923
+ if (e.length === 0)
924
+ return { then: () => s };
925
+ const o = b(t, {
926
+ type: "GET",
927
+ path: e.map((l) => l.toString())
928
+ }).then(P);
929
+ return o.then.bind(o);
930
+ }
931
+ return H(t, [...e, i]);
932
+ },
933
+ set(a, i, o) {
934
+ v(n);
935
+ const [l, c] = C(o);
936
+ return b(t, {
937
+ type: "SET",
938
+ path: [...e, i].map((u) => u.toString()),
939
+ value: l
940
+ }, c).then(P);
941
+ },
942
+ apply(a, i, o) {
943
+ v(n);
944
+ const l = e[e.length - 1];
945
+ if (l === ae)
946
+ return b(t, {
947
+ type: "ENDPOINT"
948
+ }).then(P);
949
+ if (l === "bind")
950
+ return H(t, e.slice(0, -1));
951
+ const [c, u] = U(o);
952
+ return b(t, {
953
+ type: "APPLY",
954
+ path: e.map((p) => p.toString()),
955
+ argumentList: c
956
+ }, u).then(P);
957
+ },
958
+ construct(a, i) {
959
+ v(n);
960
+ const [o, l] = U(i);
961
+ return b(t, {
962
+ type: "CONSTRUCT",
963
+ path: e.map((c) => c.toString()),
964
+ argumentList: o
965
+ }, l).then(P);
966
+ }
967
+ });
968
+ return fe(s, t), s;
969
+ }
970
+ function me(t) {
971
+ return Array.prototype.concat.apply([], t);
972
+ }
973
+ function U(t) {
974
+ const e = t.map(C);
975
+ return [e.map((r) => r[0]), me(e.map((r) => r[1]))];
976
+ }
977
+ const j = /* @__PURE__ */ new WeakMap();
978
+ function ge(t, e) {
979
+ return j.set(t, e), t;
980
+ }
981
+ function B(t) {
982
+ return Object.assign(t, { [D]: !0 });
983
+ }
984
+ function V(t, e = globalThis, r = "*") {
985
+ return {
986
+ postMessage: (n, s) => t.postMessage(n, r, s),
987
+ addEventListener: e.addEventListener.bind(e),
988
+ removeEventListener: e.removeEventListener.bind(e)
989
+ };
990
+ }
991
+ function C(t) {
992
+ for (const [e, r] of S)
993
+ if (r.canHandle(t)) {
994
+ const [n, s] = r.serialize(t);
995
+ return [
996
+ {
997
+ type: "HANDLER",
998
+ name: e,
999
+ value: n
1000
+ },
1001
+ s
1002
+ ];
1003
+ }
1004
+ return [
1005
+ {
1006
+ type: "RAW",
1007
+ value: t
1008
+ },
1009
+ j.get(t) || []
1010
+ ];
1011
+ }
1012
+ function P(t) {
1013
+ switch (t.type) {
1014
+ case "HANDLER":
1015
+ return S.get(t.name).deserialize(t.value);
1016
+ case "RAW":
1017
+ return t.value;
1018
+ }
1019
+ }
1020
+ function b(t, e, r) {
1021
+ return new Promise((n) => {
1022
+ const s = we();
1023
+ t.addEventListener("message", function a(i) {
1024
+ !i.data || !i.data.id || i.data.id !== s || (t.removeEventListener("message", a), n(i.data));
1025
+ }), t.start && t.start(), t.postMessage(Object.assign({ id: s }, e), r);
1026
+ });
1027
+ }
1028
+ function we() {
1029
+ return new Array(4).fill(0).map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16)).join("-");
1030
+ }
1031
+ function ve(t) {
1032
+ G();
1033
+ const e = t instanceof Worker ? t : V(t);
1034
+ return L(e);
1035
+ }
1036
+ function xe(t, e) {
1037
+ G();
1038
+ let r;
1039
+ const n = new Promise((i) => {
1040
+ r = i;
1041
+ }), s = J(t), a = new Proxy(s, {
1042
+ get: (i, o) => o === "isReady" ? () => n : o in i ? i[o] : e?.[o]
1043
+ });
1044
+ return F(
1045
+ a,
1046
+ typeof window < "u" ? V(self.parent) : void 0
1047
+ ), [r, a];
1048
+ }
1049
+ function G() {
1050
+ S.set("EVENT", {
1051
+ canHandle: (t) => t instanceof CustomEvent,
1052
+ serialize: (t) => [
1053
+ {
1054
+ detail: t.detail
1055
+ },
1056
+ []
1057
+ ],
1058
+ deserialize: (t) => t
1059
+ }), S.set("FUNCTION", {
1060
+ canHandle: (t) => typeof t == "function",
1061
+ serialize(t) {
1062
+ console.debug("[Comlink][Performance] Proxying a function");
1063
+ const { port1: e, port2: r } = new MessageChannel();
1064
+ return F(t, e), [r, [r]];
1065
+ },
1066
+ deserialize(t) {
1067
+ return t.start(), L(t);
1068
+ }
1069
+ }), S.set("PHPResponse", {
1070
+ canHandle: (t) => typeof t == "object" && t !== null && "headers" in t && "bytes" in t && "errors" in t && "exitCode" in t && "httpStatusCode" in t,
1071
+ serialize(t) {
1072
+ return [t.toRawData(), []];
1073
+ },
1074
+ deserialize(t) {
1075
+ return E.fromRawData(t);
1076
+ }
1077
+ });
1078
+ }
1079
+ function J(t) {
1080
+ return new Proxy(t, {
1081
+ get(e, r) {
1082
+ switch (typeof e[r]) {
1083
+ case "function":
1084
+ return (...n) => e[r](...n);
1085
+ case "object":
1086
+ return e[r] === null ? e[r] : J(e[r]);
1087
+ case "undefined":
1088
+ case "number":
1089
+ case "string":
1090
+ return e[r];
1091
+ default:
1092
+ return B(e[r]);
1093
+ }
1094
+ }
1095
+ });
1096
+ }
1097
+ async function ye(t = Y) {
1098
+ switch (t) {
1099
+ case "8.2":
1100
+ return await import("php_8_2.js");
1101
+ case "8.1":
1102
+ return await import("php_8_1.js");
1103
+ case "8.0":
1104
+ return await import("php_8_0.js");
1105
+ case "7.4":
1106
+ return await import("php_7_4.js");
1107
+ case "7.3":
1108
+ return await import("php_7_3.js");
1109
+ case "7.2":
1110
+ return await import("php_7_2.js");
1111
+ case "7.1":
1112
+ return await import("php_7_1.js");
1113
+ case "7.0":
1114
+ return await import("php_7_0.js");
1115
+ case "5.6":
1116
+ return await import("php_5_6.js");
1117
+ }
1118
+ throw new Error(`Unsupported PHP version ${t}`);
1119
+ }
1120
+ class A extends m {
1121
+ /**
1122
+ * Creates a new PHP instance.
1123
+ *
1124
+ * Dynamically imports the PHP module, initializes the runtime,
1125
+ * and sets up networking. It's a shorthand for the lower-level
1126
+ * functions like `getPHPLoaderModule`, `loadPHPRuntime`, and
1127
+ * `PHP.initializeRuntime`
1128
+ *
1129
+ * @param phpVersion The PHP Version to load
1130
+ * @param options The options to use when loading PHP
1131
+ * @returns A new PHP instance
1132
+ */
1133
+ static async load(e, r = {}) {
1134
+ return await A.loadSync(e, r).phpReady;
1135
+ }
1136
+ /**
1137
+ * Does what load() does, but synchronously returns
1138
+ * an object with the PHP instance and a promise that
1139
+ * resolves when the PHP instance is ready.
1140
+ *
1141
+ * @see load
1142
+ */
1143
+ static loadSync(e, r = {}) {
1144
+ const n = new A(void 0, r.requestHandler), a = (async () => {
1145
+ const i = await Promise.all([
1146
+ ye(e),
1147
+ ...r.dataModules || []
1148
+ ]), [o, ...l] = i;
1149
+ r.downloadMonitor?.setModules(i);
1150
+ const c = await oe(
1151
+ o,
1152
+ {
1153
+ ...r.emscriptenOptions || {},
1154
+ ...r.downloadMonitor?.getEmscriptenOptions() || {}
1155
+ },
1156
+ l
1157
+ );
1158
+ return n.initializeRuntime(c), { dataModules: l };
1159
+ })();
1160
+ return {
1161
+ php: n,
1162
+ phpReady: a.then(() => n),
1163
+ dataModules: a.then((i) => i.dataModules)
1164
+ };
1165
+ }
1166
+ }
1167
+ const d = /* @__PURE__ */ new WeakMap();
1168
+ class _e {
1169
+ /** @inheritDoc */
1170
+ constructor(e, r) {
1171
+ d.set(this, {
1172
+ php: e,
1173
+ monitor: r
1174
+ }), this.absoluteUrl = Promise.resolve(
1175
+ e.requestHandler.server.absoluteUrl
1176
+ ), this.documentRoot = Promise.resolve(
1177
+ e.requestHandler.server.documentRoot
1178
+ );
1179
+ }
1180
+ /** @inheritDoc @php-wasm/web!PHPRequestHandler.pathToInternalUrl */
1181
+ async pathToInternalUrl(e) {
1182
+ return d.get(this).php.requestHandler.server.pathToInternalUrl(e);
1183
+ }
1184
+ /** @inheritDoc @php-wasm/web!PHPRequestHandler.internalUrlToPath */
1185
+ async internalUrlToPath(e) {
1186
+ return d.get(this).php.requestHandler.server.internalUrlToPath(e);
1187
+ }
1188
+ async onDownloadProgress(e) {
1189
+ d.get(this).monitor?.addEventListener("progress", e);
1190
+ }
1191
+ /** @inheritDoc @php-wasm/web!PHPRequestHandler.request */
1192
+ request(e, r) {
1193
+ return d.get(this).php.request(e, r);
1194
+ }
1195
+ /** @inheritDoc @php-wasm/web!PHP.run */
1196
+ async run(e) {
1197
+ return d.get(this).php.run(e);
1198
+ }
1199
+ /** @inheritDoc @php-wasm/web!PHP.chdir */
1200
+ chdir(e) {
1201
+ return d.get(this).php.chdir(e);
1202
+ }
1203
+ /** @inheritDoc @php-wasm/web!PHP.setPhpIniPath */
1204
+ setPhpIniPath(e) {
1205
+ return d.get(this).php.setPhpIniPath(e);
1206
+ }
1207
+ /** @inheritDoc @php-wasm/web!PHP.setPhpIniEntry */
1208
+ setPhpIniEntry(e, r) {
1209
+ d.get(this).php.setPhpIniEntry(e, r);
1210
+ }
1211
+ /** @inheritDoc @php-wasm/web!PHP.mkdirTree */
1212
+ mkdirTree(e) {
1213
+ d.get(this).php.mkdirTree(e);
1214
+ }
1215
+ /** @inheritDoc @php-wasm/web!PHP.readFileAsText */
1216
+ async readFileAsText(e) {
1217
+ return d.get(this).php.readFileAsText(e);
1218
+ }
1219
+ /** @inheritDoc @php-wasm/web!PHP.readFileAsBuffer */
1220
+ async readFileAsBuffer(e) {
1221
+ return d.get(this).php.readFileAsBuffer(e);
1222
+ }
1223
+ /** @inheritDoc @php-wasm/web!PHP.writeFile */
1224
+ writeFile(e, r) {
1225
+ d.get(this).php.writeFile(e, r);
1226
+ }
1227
+ /** @inheritDoc @php-wasm/web!PHP.unlink */
1228
+ unlink(e) {
1229
+ d.get(this).php.unlink(e);
1230
+ }
1231
+ /** @inheritDoc @php-wasm/web!PHP.listFiles */
1232
+ async listFiles(e) {
1233
+ return d.get(this).php.listFiles(e);
1234
+ }
1235
+ /** @inheritDoc @php-wasm/web!PHP.isDir */
1236
+ async isDir(e) {
1237
+ return d.get(this).php.isDir(e);
1238
+ }
1239
+ /** @inheritDoc @php-wasm/web!PHP.fileExists */
1240
+ async fileExists(e) {
1241
+ return d.get(this).php.fileExists(e);
1242
+ }
1243
+ }
1244
+ function Pe(t, e) {
1245
+ return {
1246
+ type: "response",
1247
+ requestId: t,
1248
+ response: e
1249
+ };
1250
+ }
1251
+ async function ke(t, e, r, n) {
1252
+ const s = navigator.serviceWorker;
1253
+ if (!s)
1254
+ throw new Error("Service workers are not supported in this browser.");
1255
+ const a = await s.getRegistrations();
1256
+ if (a.length > 0) {
1257
+ const i = await be();
1258
+ if (n !== i) {
1259
+ console.debug(
1260
+ `[window] Reloading the currently registered Service Worker (expected version: ${n}, registered version: ${i})`
1261
+ );
1262
+ for (const o of a) {
1263
+ let l = !1;
1264
+ try {
1265
+ await o.update();
1266
+ } catch {
1267
+ l = !0;
1268
+ }
1269
+ const c = o.waiting || o.installing;
1270
+ c && !l && (i !== null ? c.postMessage("skip-waiting") : l = !0), l && (await o.unregister(), window.location.reload());
1271
+ }
1272
+ }
1273
+ } else
1274
+ console.debug(
1275
+ `[window] Creating a Service Worker registration (version: ${n})`
1276
+ ), await s.register(r, {
1277
+ type: "module"
1278
+ });
1279
+ navigator.serviceWorker.addEventListener(
1280
+ "message",
1281
+ async function(o) {
1282
+ if (console.debug("Message from ServiceWorker", o), e && o.data.scope !== e)
1283
+ return;
1284
+ const l = o.data.args || [], c = o.data.method, u = await t[c](...l);
1285
+ o.source.postMessage(Pe(o.data.requestId, u));
1286
+ }
1287
+ ), s.startMessages();
1288
+ }
1289
+ async function be() {
1290
+ try {
1291
+ return (await (await fetch("/version")).json()).version;
1292
+ } catch {
1293
+ return null;
1294
+ }
1295
+ }
1296
+ function Te() {
1297
+ const t = {};
1298
+ return typeof self?.location?.href < "u" && new URL(self.location.href).searchParams.forEach((r, n) => {
1299
+ t[n] = r;
1300
+ }), t;
1301
+ }
1302
+ const Ce = function() {
1303
+ return navigator.userAgent.toLowerCase().indexOf("firefox") > -1 ? "iframe" : "webworker";
1304
+ }();
1305
+ async function Fe(t, e = "webworker", r = {}) {
1306
+ if (t = Ee(t, r), e === "webworker")
1307
+ return new Worker(t, { type: "module" });
1308
+ if (e === "iframe")
1309
+ return (await Re(t)).contentWindow;
1310
+ throw new Error(`Unknown backendName: ${e}`);
1311
+ }
1312
+ function Ee(t, e) {
1313
+ if (!Object.entries(e).length)
1314
+ return t + "";
1315
+ const r = new URL(t);
1316
+ for (const [n, s] of Object.entries(e))
1317
+ r.searchParams.set(n, s);
1318
+ return r.toString();
1319
+ }
1320
+ async function Re(t) {
1321
+ const e = document.createElement("iframe"), r = "/" + t.split("/").slice(-1)[0];
1322
+ return e.src = r, e.style.display = "none", document.body.appendChild(e), await new Promise((n) => {
1323
+ e.addEventListener("load", n);
1324
+ }), e;
1325
+ }
1326
+ export {
1327
+ Y as LatestSupportedPHPVersion,
1328
+ A as PHP,
1329
+ K as PHPBrowser,
1330
+ _e as PHPClient,
1331
+ ee as PHPRequestHandler,
1332
+ W as SupportedPHPVersions,
1333
+ Se as SupportedPHPVersionsList,
1334
+ ve as consumeAPI,
1335
+ xe as exposeAPI,
1336
+ ye as getPHPLoaderModule,
1337
+ oe as loadPHPRuntime,
1338
+ Te as parseWorkerStartupOptions,
1339
+ Ce as recommendedWorkerBackend,
1340
+ ke as registerServiceWorker,
1341
+ Fe as spawnPHPWorkerThread
1342
+ };