@wp-playground/blueprints 0.1.40 → 0.1.42

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 (50) hide show
  1. package/index.cjs +133 -0
  2. package/index.d.ts +7 -0
  3. package/index.js +2081 -0
  4. package/lib/blueprint.d.ts +27 -0
  5. package/lib/compile.d.ts +37 -0
  6. package/lib/resources.d.ts +211 -0
  7. package/lib/steps/activate-plugin.d.ts +12 -0
  8. package/lib/steps/apply-wordpress-patches/index.d.ts +12 -0
  9. package/lib/steps/client-methods.d.ts +56 -0
  10. package/lib/steps/common.d.ts +7 -0
  11. package/lib/steps/define-site-url.d.ts +12 -0
  12. package/lib/steps/define-wp-config-consts.d.ts +12 -0
  13. package/{src/lib/steps/handlers.ts → lib/steps/handlers.d.ts} +1 -12
  14. package/lib/steps/import-export.d.ts +67 -0
  15. package/lib/steps/index.d.ts +26 -0
  16. package/lib/steps/install-plugin.d.ts +22 -0
  17. package/lib/steps/install-theme.d.ts +22 -0
  18. package/lib/steps/login.d.ts +16 -0
  19. package/lib/steps/migration.d.ts +2 -0
  20. package/lib/steps/run-wp-installation-wizard.d.ts +16 -0
  21. package/lib/steps/site-data.d.ts +12 -0
  22. package/package.json +4 -3
  23. package/.eslintrc.json +0 -18
  24. package/LICENSE +0 -339
  25. package/README.md +0 -11
  26. package/project.json +0 -58
  27. package/src/index.ts +0 -31
  28. package/src/lib/blueprint.ts +0 -28
  29. package/src/lib/compile.spec.ts +0 -34
  30. package/src/lib/compile.ts +0 -262
  31. package/src/lib/resources.ts +0 -417
  32. package/src/lib/steps/activate-plugin.ts +0 -35
  33. package/src/lib/steps/apply-wordpress-patches/index.ts +0 -113
  34. package/src/lib/steps/apply-wordpress-patches/wp-content/mu-plugins/1-show-admin-credentials-on-wp-login.php +0 -15
  35. package/src/lib/steps/client-methods.ts +0 -121
  36. package/src/lib/steps/common.ts +0 -30
  37. package/src/lib/steps/define-site-url.ts +0 -25
  38. package/src/lib/steps/define-wp-config-consts.ts +0 -45
  39. package/src/lib/steps/import-export.ts +0 -225
  40. package/src/lib/steps/index.ts +0 -67
  41. package/src/lib/steps/install-plugin.ts +0 -145
  42. package/src/lib/steps/install-theme.ts +0 -99
  43. package/src/lib/steps/login.ts +0 -37
  44. package/src/lib/steps/migration.ts +0 -63
  45. package/src/lib/steps/run-wp-installation-wizard.ts +0 -38
  46. package/src/lib/steps/site-data.ts +0 -58
  47. package/tsconfig.json +0 -23
  48. package/tsconfig.lib.json +0 -10
  49. package/tsconfig.spec.json +0 -19
  50. package/vite.config.ts +0 -58
package/index.js ADDED
@@ -0,0 +1,2081 @@
1
+ function _(r) {
2
+ return new DOMParser().parseFromString(r.text, "text/html");
3
+ }
4
+ function E(r) {
5
+ const e = r.split(".").shift().replace("-", " ");
6
+ return e.charAt(0).toUpperCase() + e.slice(1).toLowerCase();
7
+ }
8
+ async function P(r, e, t) {
9
+ let s = "";
10
+ await r.fileExists(e) && (s = await r.readFileAsText(e)), await r.writeFile(e, t(s));
11
+ }
12
+ async function ne(r) {
13
+ return new Uint8Array(await r.arrayBuffer());
14
+ }
15
+ const ie = async (r, { plugin: e }, t) => {
16
+ t?.tracker.setCaption(`Activating ${e}`);
17
+ const i = _(
18
+ await r.request({
19
+ url: "/wp-admin/plugins.php"
20
+ })
21
+ ).querySelector(
22
+ `tr[data-slug="${e}"] a`
23
+ ).attributes.getNamedItem("href").value;
24
+ await r.request({
25
+ url: "/wp-admin/" + i
26
+ });
27
+ }, oe = async (r, e) => {
28
+ const t = new ae(
29
+ r,
30
+ e.siteUrl,
31
+ e.wordpressPath || "/wordpress"
32
+ );
33
+ e.patchSqlitePlugin !== !1 && await t.patchSqlitePlugin(), e.addPhpInfo !== !1 && await t.addPhpInfo(), e.patchSiteUrl !== !1 && await t.patchSiteUrl(), e.disableSiteHealth !== !1 && await t.disableSiteHealth(), e.disableWpNewBlogNotification !== !1 && await t.disableWpNewBlogNotification();
34
+ };
35
+ class ae {
36
+ constructor(e, t, s) {
37
+ this.php = e, this.scopedSiteUrl = t, this.wordpressPath = s;
38
+ }
39
+ async patchSqlitePlugin() {
40
+ await P(
41
+ this.php,
42
+ `${this.wordpressPath}/wp-content/plugins/sqlite-database-integration/wp-includes/sqlite/class-wp-sqlite-translator.php`,
43
+ (e) => e.replace(
44
+ "if ( false === strtotime( $value ) )",
45
+ 'if ( $value === "0000-00-00 00:00:00" || false === strtotime( $value ) )'
46
+ )
47
+ );
48
+ }
49
+ async addPhpInfo() {
50
+ await this.php.writeFile(
51
+ `${this.wordpressPath}/phpinfo.php`,
52
+ "<?php phpinfo(); "
53
+ );
54
+ }
55
+ async patchSiteUrl() {
56
+ await P(
57
+ this.php,
58
+ `${this.wordpressPath}/wp-config.php`,
59
+ (e) => `<?php
60
+ if(!defined('WP_HOME')) {
61
+ define('WP_HOME', "${this.scopedSiteUrl}");
62
+ define('WP_SITEURL', "${this.scopedSiteUrl}");
63
+ }
64
+ ?>${e}`
65
+ );
66
+ }
67
+ async disableSiteHealth() {
68
+ await P(
69
+ this.php,
70
+ `${this.wordpressPath}/wp-includes/default-filters.php`,
71
+ (e) => e.replace(
72
+ /add_filter[^;]+wp_maybe_grant_site_health_caps[^;]+;/i,
73
+ ""
74
+ )
75
+ );
76
+ }
77
+ async disableWpNewBlogNotification() {
78
+ await P(
79
+ this.php,
80
+ `${this.wordpressPath}/wp-config.php`,
81
+ // The original version of this function crashes WASM PHP, let's define an empty one instead.
82
+ (e) => `${e} function wp_new_blog_notification(...$args){} `
83
+ );
84
+ }
85
+ }
86
+ const ce = async (r, { code: e }) => await r.run({ code: e }), le = async (r, { options: e }) => await r.run(e), ue = async (r, { key: e, value: t }) => {
87
+ await r.setPhpIniEntry(e, t);
88
+ }, he = async (r, { request: e }) => await r.request(e), pe = async (r, { fromPath: e, toPath: t }) => {
89
+ await r.writeFile(
90
+ t,
91
+ await r.readFileAsBuffer(e)
92
+ );
93
+ }, de = async (r, { fromPath: e, toPath: t }) => {
94
+ await r.mv(e, t);
95
+ }, fe = async (r, { path: e }) => {
96
+ await r.mkdir(e);
97
+ }, me = async (r, { path: e }) => {
98
+ await r.unlink(e);
99
+ }, we = async (r, { path: e }) => {
100
+ await r.rmdir(e);
101
+ }, ge = async (r, { path: e, data: t }) => {
102
+ t instanceof File && (t = await ne(t)), await r.writeFile(e, t);
103
+ }, V = async (r, { consts: e }) => {
104
+ const t = await r.documentRoot;
105
+ await P(
106
+ r,
107
+ `${t}/playground-consts.json`,
108
+ (s) => JSON.stringify({
109
+ ...JSON.parse(s || "{}"),
110
+ ...e
111
+ })
112
+ ), await P(
113
+ r,
114
+ `${t}/wp-config.php`,
115
+ (s) => s.includes("playground-consts.json") ? s : `<?php
116
+ $consts = json_decode(file_get_contents('./playground-consts.json'), true);
117
+ foreach ($consts as $const => $value) {
118
+ if (!defined($const)) {
119
+ define($const, $value);
120
+ }
121
+ }
122
+ ?>${s}`
123
+ );
124
+ }, ye = async (r, { siteUrl: e }) => await V(r, {
125
+ consts: {
126
+ WP_HOME: e,
127
+ WP_SITEURL: e
128
+ }
129
+ });
130
+ class J {
131
+ constructor({ concurrency: e }) {
132
+ this._running = 0, this.concurrency = e, this.queue = [];
133
+ }
134
+ get running() {
135
+ return this._running;
136
+ }
137
+ async acquire() {
138
+ for (; ; )
139
+ if (this._running >= this.concurrency)
140
+ await new Promise((e) => this.queue.push(e));
141
+ else
142
+ return this._running++, () => {
143
+ this._running--, this.queue.length > 0 && this.queue.shift()();
144
+ };
145
+ }
146
+ async run(e) {
147
+ const t = await this.acquire();
148
+ try {
149
+ return await e();
150
+ } finally {
151
+ t();
152
+ }
153
+ }
154
+ }
155
+ const Pe = Symbol("literal");
156
+ function b(r) {
157
+ if (typeof r == "string")
158
+ return r.startsWith("$") ? r : JSON.stringify(r);
159
+ if (typeof r == "number")
160
+ return r.toString();
161
+ if (Array.isArray(r))
162
+ return `array(${r.map(b).join(", ")})`;
163
+ if (r === null)
164
+ return "null";
165
+ if (typeof r == "object")
166
+ return Pe in r ? r.toString() : `array(${Object.entries(r).map(([t, s]) => `${JSON.stringify(t)} => ${b(s)}`).join(", ")})`;
167
+ if (typeof r == "function")
168
+ return r();
169
+ throw new Error(`Unsupported value: ${r}`);
170
+ }
171
+ function x(r) {
172
+ const e = {};
173
+ for (const t in r)
174
+ e[t] = b(r[t]);
175
+ return e;
176
+ }
177
+ const A = `<?php
178
+
179
+ function zipDir($dir, $output, $additionalFiles = array())
180
+ {
181
+ $zip = new ZipArchive;
182
+ $res = $zip->open($output, ZipArchive::CREATE);
183
+ if ($res === TRUE) {
184
+ foreach ($additionalFiles as $file) {
185
+ $zip->addFile($file);
186
+ }
187
+ $directories = array(
188
+ rtrim($dir, '/') . '/'
189
+ );
190
+ while (sizeof($directories)) {
191
+ $dir = array_pop($directories);
192
+
193
+ if ($handle = opendir($dir)) {
194
+ while (false !== ($entry = readdir($handle))) {
195
+ if ($entry == '.' || $entry == '..') {
196
+ continue;
197
+ }
198
+
199
+ $entry = $dir . $entry;
200
+
201
+ if (is_dir($entry)) {
202
+ $directory_path = $entry . '/';
203
+ array_push($directories, $directory_path);
204
+ } else if (is_file($entry)) {
205
+ $zip->addFile($entry);
206
+ }
207
+ }
208
+ closedir($handle);
209
+ }
210
+ }
211
+ $zip->close();
212
+ chmod($output, 0777);
213
+ }
214
+ }
215
+
216
+ function unzip($zipPath, $extractTo, $overwrite = true)
217
+ {
218
+ if(!is_dir($extractTo)) {
219
+ mkdir($extractTo, 0777, true);
220
+ }
221
+ $zip = new ZipArchive;
222
+ $res = $zip->open($zipPath);
223
+ if ($res === TRUE) {
224
+ $zip->extractTo($extractTo);
225
+ $zip->close();
226
+ chmod($extractTo, 0777);
227
+ }
228
+ }
229
+
230
+
231
+ function delTree($dir)
232
+ {
233
+ $files = array_diff(scandir($dir), array('.', '..'));
234
+ foreach ($files as $file) {
235
+ (is_dir("$dir/$file")) ? delTree("$dir/$file") : unlink("$dir/$file");
236
+ }
237
+ return rmdir($dir);
238
+ }
239
+ `;
240
+ async function be(r) {
241
+ const e = "wordpress-playground.zip", t = `/${e}`, s = x({
242
+ zipPath: t,
243
+ documentRoot: await r.documentRoot
244
+ });
245
+ await Y(
246
+ r,
247
+ `zipDir(${s.documentRoot}, ${s.zipPath});`
248
+ );
249
+ const n = await r.readFileAsBuffer(t);
250
+ return r.unlink(t), new File([n], e);
251
+ }
252
+ const _e = async (r, { fullSiteZip: e }) => {
253
+ const t = "/import.zip";
254
+ await r.writeFile(
255
+ t,
256
+ new Uint8Array(await e.arrayBuffer())
257
+ );
258
+ const s = await r.absoluteUrl, n = await r.documentRoot;
259
+ await r.rmdir(n), await K(r, { zipPath: t, extractToPath: "/" });
260
+ const i = x({ absoluteUrl: s });
261
+ await Se(
262
+ r,
263
+ `${n}/wp-config.php`,
264
+ (o) => `<?php
265
+ if(!defined('WP_HOME')) {
266
+ define('WP_HOME', ${i.absoluteUrl});
267
+ define('WP_SITEURL', ${i.absoluteUrl});
268
+ }
269
+ ?>${o}`
270
+ );
271
+ }, K = async (r, { zipPath: e, extractToPath: t }) => {
272
+ const s = x({
273
+ zipPath: e,
274
+ extractToPath: t
275
+ });
276
+ await Y(
277
+ r,
278
+ `unzip(${s.zipPath}, ${s.extractToPath});`
279
+ );
280
+ }, $e = async (r, { file: e }) => {
281
+ const t = await r.request({
282
+ url: "/wp-admin/admin.php?import=wordpress"
283
+ }), s = O(t).getElementById("import-upload-form")?.getAttribute("action"), n = await r.request({
284
+ url: `/wp-admin/${s}`,
285
+ method: "POST",
286
+ files: { import: e }
287
+ }), i = O(n).querySelector(
288
+ "#wpbody-content form"
289
+ );
290
+ if (!i)
291
+ throw console.log(n.text), new Error(
292
+ "Could not find an importer form in response. See the response text above for details."
293
+ );
294
+ const o = ve(i);
295
+ o.fetch_attachments = "1";
296
+ for (const a in o)
297
+ if (a.startsWith("user_map[")) {
298
+ const c = "user_new[" + a.slice(9, -1) + "]";
299
+ o[c] = "1";
300
+ }
301
+ await r.request({
302
+ url: i.action,
303
+ method: "POST",
304
+ formData: o
305
+ });
306
+ };
307
+ function O(r) {
308
+ return new DOMParser().parseFromString(r.text, "text/html");
309
+ }
310
+ function ve(r) {
311
+ return Object.fromEntries(new FormData(r).entries());
312
+ }
313
+ async function Se(r, e, t) {
314
+ await r.writeFile(
315
+ e,
316
+ t(await r.readFileAsText(e))
317
+ );
318
+ }
319
+ async function Y(r, e) {
320
+ const t = await r.run({
321
+ code: A + e
322
+ });
323
+ if (t.exitCode !== 0)
324
+ throw console.log(A + e), console.log(e + ""), console.log(t.errors), t.errors;
325
+ return t;
326
+ }
327
+ const Ee = async (r, { pluginZipFile: e, options: t = {} }, s) => {
328
+ s?.tracker.setCaption(
329
+ `Installing the ${E(e?.name)} plugin`
330
+ );
331
+ try {
332
+ const n = "activate" in t ? t.activate : !0, i = await r.request({
333
+ url: "/wp-admin/plugin-install.php?tab=upload"
334
+ }), o = _(i), a = new FormData(
335
+ o.querySelector(".wp-upload-form")
336
+ ), { pluginzip: c, ...u } = Object.fromEntries(
337
+ a.entries()
338
+ ), h = await r.request({
339
+ url: "/wp-admin/update.php?action=upload-plugin",
340
+ method: "POST",
341
+ formData: u,
342
+ files: { pluginzip: e }
343
+ });
344
+ if (n) {
345
+ const v = _(h).querySelector("#wpbody-content .button.button-primary").attributes.getNamedItem("href").value, S = new URL(
346
+ v,
347
+ await r.pathToInternalUrl("/wp-admin/")
348
+ ).toString();
349
+ await r.request({
350
+ url: S
351
+ });
352
+ }
353
+ await r.isDir(
354
+ "/wordpress/wp-content/plugins/gutenberg"
355
+ ) && !await r.fileExists("/wordpress/.gutenberg-patched") && (await r.writeFile("/wordpress/.gutenberg-patched", "1"), await L(
356
+ r,
357
+ "/wordpress/wp-content/plugins/gutenberg/build/block-editor/index.js",
358
+ (d) => d.replace(
359
+ /srcDoc:("[^"]+"|[^,]+)/g,
360
+ 'src:"/wp-includes/empty.html"'
361
+ )
362
+ ), await L(
363
+ r,
364
+ "/wordpress/wp-content/plugins/gutenberg/build/block-editor/index.min.js",
365
+ (d) => d.replace(
366
+ /srcDoc:("[^"]+"|[^,]+)/g,
367
+ 'src:"/wp-includes/empty.html"'
368
+ )
369
+ ));
370
+ } catch (n) {
371
+ console.error(
372
+ `Proceeding without the ${e.name} theme. Could not install it in wp-admin. The original error was: ${n}`
373
+ ), console.error(n);
374
+ }
375
+ };
376
+ async function L(r, e, t) {
377
+ return await r.writeFile(
378
+ e,
379
+ t(await r.readFileAsText(e))
380
+ );
381
+ }
382
+ const Re = async (r, { themeZipFile: e, options: t = {} }, s) => {
383
+ s?.tracker.setCaption(
384
+ `Installing the ${E(e.name)} theme`
385
+ );
386
+ try {
387
+ const n = "activate" in t ? t.activate : !0, i = await r.request({
388
+ url: "/wp-admin/theme-install.php"
389
+ }), o = _(i), a = new FormData(
390
+ o.querySelector(".wp-upload-form")
391
+ ), { themezip: c, ...u } = Object.fromEntries(
392
+ a.entries()
393
+ ), h = await r.request({
394
+ url: "/wp-admin/update.php?action=upload-theme",
395
+ method: "POST",
396
+ formData: u,
397
+ files: { themezip: e }
398
+ });
399
+ if (n) {
400
+ const d = _(h), v = d.querySelector(
401
+ "#wpbody-content > .wrap"
402
+ );
403
+ if (v?.textContent?.includes(
404
+ "Theme installation failed."
405
+ )) {
406
+ console.error(v?.textContent);
407
+ return;
408
+ }
409
+ const S = d.querySelector(
410
+ "#wpbody-content .activatelink, .update-from-upload-actions .button.button-primary"
411
+ );
412
+ if (!S) {
413
+ console.error('The "activate" button was not found.');
414
+ return;
415
+ }
416
+ const re = S.attributes.getNamedItem("href").value, se = new URL(
417
+ re,
418
+ await r.pathToInternalUrl("/wp-admin/")
419
+ ).toString();
420
+ await r.request({
421
+ url: se
422
+ });
423
+ }
424
+ } catch (n) {
425
+ console.error(
426
+ `Proceeding without the ${e.name} theme. Could not install it in wp-admin. The original error was: ${n}`
427
+ ), console.error(n);
428
+ }
429
+ }, Te = async (r, { username: e = "admin", password: t = "password" } = {}, s) => {
430
+ s?.tracker.setCaption(s?.initialCaption || "Logging in"), await r.request({
431
+ url: "/wp-login.php"
432
+ }), await r.request({
433
+ url: "/wp-login.php",
434
+ method: "POST",
435
+ formData: {
436
+ log: e,
437
+ pwd: t,
438
+ rememberme: "forever"
439
+ }
440
+ });
441
+ }, xe = async (r, { options: e }) => {
442
+ await r.request({
443
+ url: "/wp-admin/install.php?step=2",
444
+ method: "POST",
445
+ formData: {
446
+ language: "en",
447
+ prefix: "wp_",
448
+ weblog_title: "My WordPress Website",
449
+ user_name: e.adminPassword || "admin",
450
+ admin_password: e.adminPassword || "password",
451
+ // The installation wizard demands typing the same password twice
452
+ admin_password2: e.adminPassword || "password",
453
+ Submit: "Install WordPress",
454
+ pw_weak: "1",
455
+ admin_email: "admin@localhost.com"
456
+ }
457
+ });
458
+ }, Fe = async (r, { options: e }) => {
459
+ const t = `<?php
460
+ include 'wordpress/wp-load.php';
461
+ $site_options = ${b(e)};
462
+ foreach($site_options as $name => $value) {
463
+ update_option($name, $value);
464
+ }
465
+ echo "Success";
466
+ `, s = await r.run({
467
+ code: t
468
+ });
469
+ return Z(s), { code: t, result: s };
470
+ }, ke = async (r, { meta: e, userId: t }) => {
471
+ const s = `<?php
472
+ include 'wordpress/wp-load.php';
473
+ $meta = ${b(e)};
474
+ foreach($meta as $name => $value) {
475
+ update_user_meta(${b(t)}, $name, $value);
476
+ }
477
+ echo "Success";
478
+ `, n = await r.run({
479
+ code: s
480
+ });
481
+ return Z(n), { code: s, result: n };
482
+ };
483
+ async function Z(r) {
484
+ if (r.text !== "Success")
485
+ throw console.log(r), new Error(`Failed to run code: ${r.text} ${r.errors}`);
486
+ }
487
+ const Ce = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
488
+ __proto__: null,
489
+ activatePlugin: ie,
490
+ applyWordPressPatches: oe,
491
+ cp: pe,
492
+ defineSiteUrl: ye,
493
+ defineWpConfigConsts: V,
494
+ importFile: $e,
495
+ installPlugin: Ee,
496
+ installTheme: Re,
497
+ login: Te,
498
+ mkdir: fe,
499
+ mv: de,
500
+ replaceSite: _e,
501
+ request: he,
502
+ rm: me,
503
+ rmdir: we,
504
+ runPHP: ce,
505
+ runPHPWithOptions: le,
506
+ runWpInstallationWizard: xe,
507
+ setPhpIniEntry: ue,
508
+ setSiteOptions: Fe,
509
+ unzip: K,
510
+ updateUserMeta: ke,
511
+ writeFile: ge,
512
+ zipEntireSite: be
513
+ }, Symbol.toStringTag, { value: "Module" })), Ue = 5 * 1024 * 1024;
514
+ function Ae(r, e) {
515
+ const t = r.headers.get("content-length") || "", s = parseInt(t, 10) || Ue;
516
+ function n(i, o) {
517
+ e(
518
+ new CustomEvent("progress", {
519
+ detail: {
520
+ loaded: i,
521
+ total: o
522
+ }
523
+ })
524
+ );
525
+ }
526
+ return new Response(
527
+ new ReadableStream({
528
+ async start(i) {
529
+ if (!r.body) {
530
+ i.close();
531
+ return;
532
+ }
533
+ const o = r.body.getReader();
534
+ let a = 0;
535
+ for (; ; )
536
+ try {
537
+ const { done: c, value: u } = await o.read();
538
+ if (u && (a += u.byteLength), c) {
539
+ n(a, a), i.close();
540
+ break;
541
+ } else
542
+ n(a, s), i.enqueue(u);
543
+ } catch (c) {
544
+ console.error({ e: c }), i.error(c);
545
+ break;
546
+ }
547
+ }
548
+ }),
549
+ {
550
+ status: r.status,
551
+ statusText: r.statusText,
552
+ headers: r.headers
553
+ }
554
+ );
555
+ }
556
+ const R = 1e-5;
557
+ class F extends EventTarget {
558
+ constructor({
559
+ weight: e = 1,
560
+ caption: t = "",
561
+ fillTime: s = 4
562
+ } = {}) {
563
+ super(), this._selfWeight = 1, this._selfDone = !1, this._selfProgress = 0, this._selfCaption = "", this._isFilling = !1, this._subTrackers = [], this._weight = e, this._selfCaption = t, this._fillTime = s;
564
+ }
565
+ /**
566
+ * Creates a new sub-tracker with a specific weight.
567
+ *
568
+ * The weight determines what percentage of the overall progress
569
+ * the sub-tracker represents. For example, if the main tracker is
570
+ * monitoring a process that has two stages, and the first stage
571
+ * is expected to take twice as long as the second stage, you could
572
+ * create the first sub-tracker with a weight of 0.67 and the second
573
+ * sub-tracker with a weight of 0.33.
574
+ *
575
+ * The caption is an optional string that describes the current stage
576
+ * of the operation. If provided, it will be used as the progress caption
577
+ * for the sub-tracker. If not provided, the main tracker will look for
578
+ * the next sub-tracker with a non-empty caption and use that as the progress
579
+ * caption instead.
580
+ *
581
+ * Returns the newly-created sub-tracker.
582
+ *
583
+ * @throws {Error} If the weight of the new stage would cause the total weight of all stages to exceed 1.
584
+ *
585
+ * @param weight The weight of the new stage, as a decimal value between 0 and 1.
586
+ * @param caption The caption for the new stage, which will be used as the progress caption for the sub-tracker.
587
+ *
588
+ * @example
589
+ * ```ts
590
+ * const tracker = new ProgressTracker();
591
+ * const subTracker1 = tracker.stage(0.67, 'Slow stage');
592
+ * const subTracker2 = tracker.stage(0.33, 'Fast stage');
593
+ *
594
+ * subTracker2.set(50);
595
+ * subTracker1.set(75);
596
+ * subTracker2.set(100);
597
+ * subTracker1.set(100);
598
+ * ```
599
+ */
600
+ stage(e, t = "") {
601
+ if (e || (e = this._selfWeight), this._selfWeight - e < -R)
602
+ throw new Error(
603
+ `Cannot add a stage with weight ${e} as the total weight of registered stages would exceed 1.`
604
+ );
605
+ this._selfWeight -= e;
606
+ const s = new F({
607
+ caption: t,
608
+ weight: e,
609
+ fillTime: this._fillTime
610
+ });
611
+ return this._subTrackers.push(s), s.addEventListener("progress", () => this.notifyProgress()), s.addEventListener("done", () => {
612
+ this.done && this.notifyDone();
613
+ }), s;
614
+ }
615
+ /**
616
+ * Fills the progress bar slowly over time, simulating progress.
617
+ *
618
+ * The progress bar is filled in a 100 steps, and each step, the progress
619
+ * is increased by 1. If `stopBeforeFinishing` is true, the progress bar
620
+ * will stop filling when it reaches 99% so that you can call `finish()`
621
+ * explicitly.
622
+ *
623
+ * If the progress bar is filling or already filled, this method does nothing.
624
+ *
625
+ * @example
626
+ * ```ts
627
+ * const progress = new ProgressTracker({ caption: 'Processing...' });
628
+ * progress.fillSlowly();
629
+ * ```
630
+ *
631
+ * @param options Optional options.
632
+ */
633
+ fillSlowly({ stopBeforeFinishing: e = !0 } = {}) {
634
+ if (this._isFilling)
635
+ return;
636
+ this._isFilling = !0;
637
+ const t = 100, s = this._fillTime / t;
638
+ this._fillInterval = setInterval(() => {
639
+ this.set(this._selfProgress + 1), e && this._selfProgress >= 99 && clearInterval(this._fillInterval);
640
+ }, s);
641
+ }
642
+ set(e) {
643
+ this._selfProgress = Math.min(e, 100), this.notifyProgress(), this._selfProgress + R >= 100 && this.finish();
644
+ }
645
+ finish() {
646
+ this._fillInterval && clearInterval(this._fillInterval), this._selfDone = !0, this._selfProgress = 100, this._isFilling = !1, this._fillInterval = void 0, this.notifyProgress(), this.notifyDone();
647
+ }
648
+ get caption() {
649
+ for (let e = this._subTrackers.length - 1; e >= 0; e--)
650
+ if (!this._subTrackers[e].done) {
651
+ const t = this._subTrackers[e].caption;
652
+ if (t)
653
+ return t;
654
+ }
655
+ return this._selfCaption;
656
+ }
657
+ setCaption(e) {
658
+ this._selfCaption = e, this.notifyProgress();
659
+ }
660
+ get done() {
661
+ return this.progress + R >= 100;
662
+ }
663
+ get progress() {
664
+ if (this._selfDone)
665
+ return 100;
666
+ const e = this._subTrackers.reduce(
667
+ (t, s) => t + s.progress * s.weight,
668
+ this._selfProgress * this._selfWeight
669
+ );
670
+ return Math.round(e * 1e4) / 1e4;
671
+ }
672
+ get weight() {
673
+ return this._weight;
674
+ }
675
+ get observer() {
676
+ return this._progressObserver || (this._progressObserver = (e) => {
677
+ this.set(e);
678
+ }), this._progressObserver;
679
+ }
680
+ get loadingListener() {
681
+ return this._loadingListener || (this._loadingListener = (e) => {
682
+ this.set(e.detail.loaded / e.detail.total * 100);
683
+ }), this._loadingListener;
684
+ }
685
+ pipe(e) {
686
+ e.setProgress({
687
+ progress: this.progress,
688
+ caption: this.caption
689
+ }), this.addEventListener("progress", (t) => {
690
+ e.setProgress({
691
+ progress: t.detail.progress,
692
+ caption: t.detail.caption
693
+ });
694
+ }), this.addEventListener("done", () => {
695
+ e.setLoaded();
696
+ });
697
+ }
698
+ addEventListener(e, t) {
699
+ super.addEventListener(e, t);
700
+ }
701
+ removeEventListener(e, t) {
702
+ super.removeEventListener(e, t);
703
+ }
704
+ notifyProgress() {
705
+ const e = this;
706
+ this.dispatchEvent(
707
+ new CustomEvent("progress", {
708
+ detail: {
709
+ get progress() {
710
+ return e.progress;
711
+ },
712
+ get caption() {
713
+ return e.caption;
714
+ }
715
+ }
716
+ })
717
+ );
718
+ }
719
+ notifyDone() {
720
+ this.dispatchEvent(new CustomEvent("done"));
721
+ }
722
+ }
723
+ class $ {
724
+ constructor(e, t, s, n = "", i = 0) {
725
+ this.httpStatusCode = e, this.headers = t, this.bytes = s, this.exitCode = i, this.errors = n;
726
+ }
727
+ static fromRawData(e) {
728
+ return new $(
729
+ e.httpStatusCode,
730
+ e.headers,
731
+ e.bytes,
732
+ e.errors,
733
+ e.exitCode
734
+ );
735
+ }
736
+ toRawData() {
737
+ return {
738
+ headers: this.headers,
739
+ bytes: this.bytes,
740
+ errors: this.errors,
741
+ exitCode: this.exitCode,
742
+ httpStatusCode: this.httpStatusCode
743
+ };
744
+ }
745
+ /**
746
+ * Response body as JSON.
747
+ */
748
+ get json() {
749
+ return JSON.parse(this.text);
750
+ }
751
+ /**
752
+ * Response body as text.
753
+ */
754
+ get text() {
755
+ return new TextDecoder().decode(this.bytes);
756
+ }
757
+ }
758
+ const Q = [
759
+ "8.2",
760
+ "8.1",
761
+ "8.0",
762
+ "7.4",
763
+ "7.3",
764
+ "7.2",
765
+ "7.1",
766
+ "7.0",
767
+ "5.6"
768
+ ], Oe = Q[0];
769
+ class Le {
770
+ #e;
771
+ #t;
772
+ /**
773
+ * @param server - The PHP server to browse.
774
+ * @param config - The browser configuration.
775
+ */
776
+ constructor(e, t = {}) {
777
+ this.requestHandler = e, this.#e = {}, this.#t = {
778
+ handleRedirects: !1,
779
+ maxRedirects: 4,
780
+ ...t
781
+ };
782
+ }
783
+ /**
784
+ * Sends the request to the server.
785
+ *
786
+ * When cookies are present in the response, this method stores
787
+ * them and sends them with any subsequent requests.
788
+ *
789
+ * When a redirection is present in the response, this method
790
+ * follows it by discarding a response and sending a subsequent
791
+ * request.
792
+ *
793
+ * @param request - The request.
794
+ * @param redirects - Internal. The number of redirects handled so far.
795
+ * @returns PHPRequestHandler response.
796
+ */
797
+ async request(e, t = 0) {
798
+ const s = await this.requestHandler.request({
799
+ ...e,
800
+ headers: {
801
+ ...e.headers,
802
+ cookie: this.#n()
803
+ }
804
+ });
805
+ if (s.headers["set-cookie"] && this.#r(s.headers["set-cookie"]), this.#t.handleRedirects && s.headers.location && t < this.#t.maxRedirects) {
806
+ const n = new URL(
807
+ s.headers.location[0],
808
+ this.requestHandler.absoluteUrl
809
+ );
810
+ return this.request(
811
+ {
812
+ url: n.toString(),
813
+ method: "GET",
814
+ headers: {}
815
+ },
816
+ t + 1
817
+ );
818
+ }
819
+ return s;
820
+ }
821
+ /** @inheritDoc */
822
+ pathToInternalUrl(e) {
823
+ return this.requestHandler.pathToInternalUrl(e);
824
+ }
825
+ /** @inheritDoc */
826
+ internalUrlToPath(e) {
827
+ return this.requestHandler.internalUrlToPath(e);
828
+ }
829
+ /** @inheritDoc */
830
+ get absoluteUrl() {
831
+ return this.requestHandler.absoluteUrl;
832
+ }
833
+ /** @inheritDoc */
834
+ get documentRoot() {
835
+ return this.requestHandler.documentRoot;
836
+ }
837
+ #r(e) {
838
+ for (const t of e)
839
+ try {
840
+ if (!t.includes("="))
841
+ continue;
842
+ const s = t.indexOf("="), n = t.substring(0, s), i = t.substring(s + 1).split(";")[0];
843
+ this.#e[n] = i;
844
+ } catch (s) {
845
+ console.error(s);
846
+ }
847
+ }
848
+ #n() {
849
+ const e = [];
850
+ for (const t in this.#e)
851
+ e.push(`${t}=${this.#e[t]}`);
852
+ return e.join("; ");
853
+ }
854
+ }
855
+ const Ie = "http://example.com";
856
+ function I(r) {
857
+ return r.toString().substring(r.origin.length);
858
+ }
859
+ function H(r, e) {
860
+ return !e || !r.startsWith(e) ? r : r.substring(e.length);
861
+ }
862
+ function He(r, e) {
863
+ return !e || r.startsWith(e) ? r : e + r;
864
+ }
865
+ class Ne {
866
+ #e;
867
+ #t;
868
+ #r;
869
+ #n;
870
+ #i;
871
+ #s;
872
+ #o;
873
+ #a;
874
+ #c;
875
+ /**
876
+ * @param php - The PHP instance.
877
+ * @param config - Request Handler configuration.
878
+ */
879
+ constructor(e, t = {}) {
880
+ this.#a = new J({ concurrency: 1 });
881
+ const {
882
+ documentRoot: s = "/www/",
883
+ absoluteUrl: n = typeof location == "object" ? location?.href : "",
884
+ isStaticFilePath: i = () => !1
885
+ } = t;
886
+ this.php = e, this.#e = s, this.#c = i;
887
+ const o = new URL(n);
888
+ this.#r = o.hostname, this.#n = o.port ? Number(o.port) : o.protocol === "https:" ? 443 : 80, this.#t = (o.protocol || "").replace(":", "");
889
+ const a = this.#n !== 443 && this.#n !== 80;
890
+ this.#i = [
891
+ this.#r,
892
+ a ? `:${this.#n}` : ""
893
+ ].join(""), this.#s = o.pathname.replace(/\/+$/, ""), this.#o = [
894
+ `${this.#t}://`,
895
+ this.#i,
896
+ this.#s
897
+ ].join("");
898
+ }
899
+ /** @inheritDoc */
900
+ pathToInternalUrl(e) {
901
+ return `${this.absoluteUrl}${e}`;
902
+ }
903
+ /** @inheritDoc */
904
+ internalUrlToPath(e) {
905
+ const t = new URL(e);
906
+ return t.pathname.startsWith(this.#s) && (t.pathname = t.pathname.slice(this.#s.length)), I(t);
907
+ }
908
+ get isRequestRunning() {
909
+ return this.#a.running > 0;
910
+ }
911
+ /** @inheritDoc */
912
+ get absoluteUrl() {
913
+ return this.#o;
914
+ }
915
+ /** @inheritDoc */
916
+ get documentRoot() {
917
+ return this.#e;
918
+ }
919
+ /** @inheritDoc */
920
+ async request(e) {
921
+ const t = e.url.startsWith("http://") || e.url.startsWith("https://"), s = new URL(
922
+ e.url,
923
+ t ? void 0 : Ie
924
+ ), n = H(
925
+ s.pathname,
926
+ this.#s
927
+ );
928
+ return this.#c(n) ? this.#l(n) : await this.#u(e, s);
929
+ }
930
+ /**
931
+ * Serves a static file from the PHP filesystem.
932
+ *
933
+ * @param path - The requested static file path.
934
+ * @returns The response.
935
+ */
936
+ #l(e) {
937
+ const t = `${this.#e}${e}`;
938
+ if (!this.php.fileExists(t))
939
+ return new $(
940
+ 404,
941
+ {},
942
+ new TextEncoder().encode("404 File not found")
943
+ );
944
+ const s = this.php.readFileAsBuffer(t);
945
+ return new $(
946
+ 200,
947
+ {
948
+ "content-length": [`${s.byteLength}`],
949
+ // @TODO: Infer the content-type from the arrayBuffer instead of the file path.
950
+ // The code below won't return the correct mime-type if the extension
951
+ // was tampered with.
952
+ "content-type": [De(t)],
953
+ "accept-ranges": ["bytes"],
954
+ "cache-control": ["public, max-age=0"]
955
+ },
956
+ s
957
+ );
958
+ }
959
+ /**
960
+ * Runs the requested PHP file with all the request and $_SERVER
961
+ * superglobals populated.
962
+ *
963
+ * @param request - The request.
964
+ * @returns The response.
965
+ */
966
+ async #u(e, t) {
967
+ const s = await this.#a.acquire();
968
+ try {
969
+ this.php.addServerGlobalEntry("DOCUMENT_ROOT", this.#e), this.php.addServerGlobalEntry(
970
+ "HTTPS",
971
+ this.#o.startsWith("https://") ? "on" : ""
972
+ );
973
+ let n = "GET";
974
+ const i = {
975
+ host: this.#i,
976
+ ...X(e.headers || {})
977
+ }, o = [];
978
+ if (e.files && Object.keys(e.files).length) {
979
+ n = "POST";
980
+ for (const c in e.files) {
981
+ const u = e.files[c];
982
+ o.push({
983
+ key: c,
984
+ name: u.name,
985
+ type: u.type,
986
+ data: new Uint8Array(await u.arrayBuffer())
987
+ });
988
+ }
989
+ i["content-type"]?.startsWith("multipart/form-data") && (e.formData = qe(
990
+ e.body || ""
991
+ ), i["content-type"] = "application/x-www-form-urlencoded", delete e.body);
992
+ }
993
+ let a;
994
+ return e.formData !== void 0 ? (n = "POST", i["content-type"] = i["content-type"] || "application/x-www-form-urlencoded", a = new URLSearchParams(
995
+ e.formData
996
+ ).toString()) : a = e.body, await this.php.run({
997
+ relativeUri: He(
998
+ I(t),
999
+ this.#s
1000
+ ),
1001
+ protocol: this.#t,
1002
+ method: e.method || n,
1003
+ body: a,
1004
+ fileInfos: o,
1005
+ scriptPath: this.#h(t.pathname),
1006
+ headers: i
1007
+ });
1008
+ } finally {
1009
+ s();
1010
+ }
1011
+ }
1012
+ /**
1013
+ * Resolve the requested path to the filesystem path of the requested PHP file.
1014
+ *
1015
+ * Fall back to index.php as if there was a url rewriting rule in place.
1016
+ *
1017
+ * @param requestedPath - The requested pathname.
1018
+ * @returns The resolved filesystem path.
1019
+ */
1020
+ #h(e) {
1021
+ let t = H(e, this.#s);
1022
+ t.includes(".php") ? t = t.split(".php")[0] + ".php" : (t.endsWith("/") || (t += "/"), t.endsWith("index.php") || (t += "index.php"));
1023
+ const s = `${this.#e}${t}`;
1024
+ return this.php.fileExists(s) ? s : `${this.#e}/index.php`;
1025
+ }
1026
+ }
1027
+ function qe(r) {
1028
+ const e = {}, t = r.match(/--(.*)\r\n/);
1029
+ if (!t)
1030
+ return e;
1031
+ const s = t[1], n = r.split(`--${s}`);
1032
+ return n.shift(), n.pop(), n.forEach((i) => {
1033
+ const o = i.indexOf(`\r
1034
+ \r
1035
+ `), a = i.substring(0, o).trim(), c = i.substring(o + 4).trim(), u = a.match(/name="([^"]+)"/);
1036
+ if (u) {
1037
+ const h = u[1];
1038
+ e[h] = c;
1039
+ }
1040
+ }), e;
1041
+ }
1042
+ function De(r) {
1043
+ switch (r.split(".").pop()) {
1044
+ case "css":
1045
+ return "text/css";
1046
+ case "js":
1047
+ return "application/javascript";
1048
+ case "png":
1049
+ return "image/png";
1050
+ case "jpg":
1051
+ case "jpeg":
1052
+ return "image/jpeg";
1053
+ case "gif":
1054
+ return "image/gif";
1055
+ case "svg":
1056
+ return "image/svg+xml";
1057
+ case "woff":
1058
+ return "font/woff";
1059
+ case "woff2":
1060
+ return "font/woff2";
1061
+ case "ttf":
1062
+ return "font/ttf";
1063
+ case "otf":
1064
+ return "font/otf";
1065
+ case "eot":
1066
+ return "font/eot";
1067
+ case "ico":
1068
+ return "image/x-icon";
1069
+ case "html":
1070
+ return "text/html";
1071
+ case "json":
1072
+ return "application/json";
1073
+ case "xml":
1074
+ return "application/xml";
1075
+ case "txt":
1076
+ case "md":
1077
+ return "text/plain";
1078
+ default:
1079
+ return "application-octet-stream";
1080
+ }
1081
+ }
1082
+ const N = {
1083
+ 0: "No error occurred. System call completed successfully.",
1084
+ 1: "Argument list too long.",
1085
+ 2: "Permission denied.",
1086
+ 3: "Address in use.",
1087
+ 4: "Address not available.",
1088
+ 5: "Address family not supported.",
1089
+ 6: "Resource unavailable, or operation would block.",
1090
+ 7: "Connection already in progress.",
1091
+ 8: "Bad file descriptor.",
1092
+ 9: "Bad message.",
1093
+ 10: "Device or resource busy.",
1094
+ 11: "Operation canceled.",
1095
+ 12: "No child processes.",
1096
+ 13: "Connection aborted.",
1097
+ 14: "Connection refused.",
1098
+ 15: "Connection reset.",
1099
+ 16: "Resource deadlock would occur.",
1100
+ 17: "Destination address required.",
1101
+ 18: "Mathematics argument out of domain of function.",
1102
+ 19: "Reserved.",
1103
+ 20: "File exists.",
1104
+ 21: "Bad address.",
1105
+ 22: "File too large.",
1106
+ 23: "Host is unreachable.",
1107
+ 24: "Identifier removed.",
1108
+ 25: "Illegal byte sequence.",
1109
+ 26: "Operation in progress.",
1110
+ 27: "Interrupted function.",
1111
+ 28: "Invalid argument.",
1112
+ 29: "I/O error.",
1113
+ 30: "Socket is connected.",
1114
+ 31: "There is a directory under that path.",
1115
+ 32: "Too many levels of symbolic links.",
1116
+ 33: "File descriptor value too large.",
1117
+ 34: "Too many links.",
1118
+ 35: "Message too large.",
1119
+ 36: "Reserved.",
1120
+ 37: "Filename too long.",
1121
+ 38: "Network is down.",
1122
+ 39: "Connection aborted by network.",
1123
+ 40: "Network unreachable.",
1124
+ 41: "Too many files open in system.",
1125
+ 42: "No buffer space available.",
1126
+ 43: "No such device.",
1127
+ 44: "There is no such file or directory OR the parent directory does not exist.",
1128
+ 45: "Executable file format error.",
1129
+ 46: "No locks available.",
1130
+ 47: "Reserved.",
1131
+ 48: "Not enough space.",
1132
+ 49: "No message of the desired type.",
1133
+ 50: "Protocol not available.",
1134
+ 51: "No space left on device.",
1135
+ 52: "Function not supported.",
1136
+ 53: "The socket is not connected.",
1137
+ 54: "Not a directory or a symbolic link to a directory.",
1138
+ 55: "Directory not empty.",
1139
+ 56: "State not recoverable.",
1140
+ 57: "Not a socket.",
1141
+ 58: "Not supported, or operation not supported on socket.",
1142
+ 59: "Inappropriate I/O control operation.",
1143
+ 60: "No such device or address.",
1144
+ 61: "Value too large to be stored in data type.",
1145
+ 62: "Previous owner died.",
1146
+ 63: "Operation not permitted.",
1147
+ 64: "Broken pipe.",
1148
+ 65: "Protocol error.",
1149
+ 66: "Protocol not supported.",
1150
+ 67: "Protocol wrong type for socket.",
1151
+ 68: "Result too large.",
1152
+ 69: "Read-only file system.",
1153
+ 70: "Invalid seek.",
1154
+ 71: "No such process.",
1155
+ 72: "Reserved.",
1156
+ 73: "Connection timed out.",
1157
+ 74: "Text file busy.",
1158
+ 75: "Cross-device link.",
1159
+ 76: "Extension: Capabilities insufficient."
1160
+ };
1161
+ function f(r = "") {
1162
+ return function(t, s, n) {
1163
+ const i = n.value;
1164
+ n.value = function(...o) {
1165
+ try {
1166
+ return i.apply(this, o);
1167
+ } catch (a) {
1168
+ const c = typeof a == "object" ? a?.errno : null;
1169
+ if (c in N) {
1170
+ const u = N[c], h = typeof o[0] == "string" ? o[0] : null, d = h !== null ? r.replaceAll("{path}", h) : r;
1171
+ throw new Error(`${d}: ${u}`, {
1172
+ cause: a
1173
+ });
1174
+ }
1175
+ throw a;
1176
+ }
1177
+ };
1178
+ };
1179
+ }
1180
+ const We = [];
1181
+ function Me(r) {
1182
+ return We[r];
1183
+ }
1184
+ (function() {
1185
+ return typeof process < "u" && process.release?.name === "node" ? "NODE" : typeof window < "u" ? "WEB" : typeof WorkerGlobalScope < "u" && self instanceof WorkerGlobalScope ? "WORKER" : "NODE";
1186
+ })();
1187
+ const q = Symbol("error"), D = Symbol("message");
1188
+ class k extends Event {
1189
+ /**
1190
+ * Create a new `ErrorEvent`.
1191
+ *
1192
+ * @param type The name of the event
1193
+ * @param options A dictionary object that allows for setting
1194
+ * attributes via object members of the same name.
1195
+ */
1196
+ constructor(e, t = {}) {
1197
+ super(e), this[q] = t.error === void 0 ? null : t.error, this[D] = t.message === void 0 ? "" : t.message;
1198
+ }
1199
+ get error() {
1200
+ return this[q];
1201
+ }
1202
+ get message() {
1203
+ return this[D];
1204
+ }
1205
+ }
1206
+ Object.defineProperty(k.prototype, "error", { enumerable: !0 });
1207
+ Object.defineProperty(k.prototype, "message", { enumerable: !0 });
1208
+ const ze = typeof globalThis.ErrorEvent == "function" ? globalThis.ErrorEvent : k;
1209
+ class Be extends EventTarget {
1210
+ constructor() {
1211
+ super(...arguments), this.listenersCount = 0;
1212
+ }
1213
+ addEventListener(e, t) {
1214
+ ++this.listenersCount, super.addEventListener(e, t);
1215
+ }
1216
+ removeEventListener(e, t) {
1217
+ --this.listenersCount, super.removeEventListener(e, t);
1218
+ }
1219
+ hasListeners() {
1220
+ return this.listenersCount > 0;
1221
+ }
1222
+ }
1223
+ function je(r) {
1224
+ r.asm = {
1225
+ ...r.asm
1226
+ };
1227
+ const e = new Be();
1228
+ for (const t in r.asm)
1229
+ if (typeof r.asm[t] == "function") {
1230
+ const s = r.asm[t];
1231
+ r.asm[t] = function(...n) {
1232
+ try {
1233
+ return s(...n);
1234
+ } catch (i) {
1235
+ if (!(i instanceof Error))
1236
+ throw i;
1237
+ if ("exitCode" in i && i?.exitCode === 0)
1238
+ return;
1239
+ const o = Ve(
1240
+ i,
1241
+ r.lastAsyncifyStackSource?.stack
1242
+ );
1243
+ if (r.lastAsyncifyStackSource && (i.cause = r.lastAsyncifyStackSource), !e.hasListeners())
1244
+ throw Ye(o), i;
1245
+ e.dispatchEvent(
1246
+ new ze("error", {
1247
+ error: i,
1248
+ message: o
1249
+ })
1250
+ );
1251
+ }
1252
+ };
1253
+ }
1254
+ return e;
1255
+ }
1256
+ let T = [];
1257
+ function Ge() {
1258
+ return T;
1259
+ }
1260
+ function Ve(r, e) {
1261
+ if (r.message === "unreachable") {
1262
+ let t = Je;
1263
+ e || (t += `
1264
+
1265
+ This stack trace is lacking. For a better one initialize
1266
+ the PHP runtime with { debug: true }, e.g. PHPNode.load('8.1', { debug: true }).
1267
+
1268
+ `), T = Ze(
1269
+ e || r.stack || ""
1270
+ );
1271
+ for (const s of T)
1272
+ t += ` * ${s}
1273
+ `;
1274
+ return t;
1275
+ }
1276
+ return r.message;
1277
+ }
1278
+ const Je = `
1279
+ "unreachable" WASM instruction executed.
1280
+
1281
+ The typical reason is a PHP function missing from the ASYNCIFY_ONLY
1282
+ list when building PHP.wasm.
1283
+
1284
+ You will need to file a new issue in the WordPress Playground repository
1285
+ and paste this error message there:
1286
+
1287
+ https://github.com/WordPress/wordpress-playground/issues/new
1288
+
1289
+ If you're a core developer, the typical fix is to:
1290
+
1291
+ * Isolate a minimal reproduction of the error
1292
+ * Add a reproduction of the error to php-asyncify.spec.ts in the WordPress Playground repository
1293
+ * Run 'npm run fix-asyncify'
1294
+ * Commit the changes, push to the repo, release updated NPM packages
1295
+
1296
+ Below is a list of all the PHP functions found in the stack trace to
1297
+ help with the minimal reproduction. If they're all already listed in
1298
+ the Dockerfile, you'll need to trigger this error again with long stack
1299
+ traces enabled. In node.js, you can do it using the --stack-trace-limit=100
1300
+ CLI option:
1301
+
1302
+ `, W = "\x1B[41m", Ke = "\x1B[1m", M = "\x1B[0m", z = "\x1B[K";
1303
+ let B = !1;
1304
+ function Ye(r) {
1305
+ if (!B) {
1306
+ B = !0, console.log(`${W}
1307
+ ${z}
1308
+ ${Ke} WASM ERROR${M}${W}`);
1309
+ for (const e of r.split(`
1310
+ `))
1311
+ console.log(`${z} ${e} `);
1312
+ console.log(`${M}`);
1313
+ }
1314
+ }
1315
+ function Ze(r) {
1316
+ try {
1317
+ const e = r.split(`
1318
+ `).slice(1).map((t) => {
1319
+ const s = t.trim().substring(3).split(" ");
1320
+ return {
1321
+ fn: s.length >= 2 ? s[0] : "<unknown>",
1322
+ isWasm: t.includes("wasm://")
1323
+ };
1324
+ }).filter(
1325
+ ({ fn: t, isWasm: s }) => s && !t.startsWith("dynCall_") && !t.startsWith("invoke_")
1326
+ ).map(({ fn: t }) => t);
1327
+ return Array.from(new Set(e));
1328
+ } catch {
1329
+ return [];
1330
+ }
1331
+ }
1332
+ var Qe = Object.defineProperty, Xe = Object.getOwnPropertyDescriptor, m = (r, e, t, s) => {
1333
+ for (var n = s > 1 ? void 0 : s ? Xe(e, t) : e, i = r.length - 1, o; i >= 0; i--)
1334
+ (o = r[i]) && (n = (s ? o(e, t, n) : o(n)) || n);
1335
+ return s && n && Qe(e, t, n), n;
1336
+ };
1337
+ const p = "string", y = "number", l = Symbol("__private__dont__use");
1338
+ class w {
1339
+ /**
1340
+ * Initializes a PHP runtime.
1341
+ *
1342
+ * @internal
1343
+ * @param PHPRuntime - Optional. PHP Runtime ID as initialized by loadPHPRuntime.
1344
+ * @param serverOptions - Optional. Options for the PHPRequestHandler. If undefined, no request handler will be initialized.
1345
+ */
1346
+ constructor(e, t) {
1347
+ this.#e = [], this.#t = !1, this.#r = null, e !== void 0 && this.initializeRuntime(e), t && (this.requestHandler = new Le(
1348
+ new Ne(this, t)
1349
+ ));
1350
+ }
1351
+ #e;
1352
+ #t;
1353
+ #r;
1354
+ /** @inheritDoc */
1355
+ get absoluteUrl() {
1356
+ return this.requestHandler.requestHandler.absoluteUrl;
1357
+ }
1358
+ /** @inheritDoc */
1359
+ get documentRoot() {
1360
+ return this.requestHandler.requestHandler.documentRoot;
1361
+ }
1362
+ /** @inheritDoc */
1363
+ pathToInternalUrl(e) {
1364
+ return this.requestHandler.requestHandler.pathToInternalUrl(e);
1365
+ }
1366
+ /** @inheritDoc */
1367
+ internalUrlToPath(e) {
1368
+ return this.requestHandler.requestHandler.internalUrlToPath(
1369
+ e
1370
+ );
1371
+ }
1372
+ initializeRuntime(e) {
1373
+ if (this[l])
1374
+ throw new Error("PHP runtime already initialized.");
1375
+ const t = Me(e);
1376
+ if (!t)
1377
+ throw new Error("Invalid PHP runtime id.");
1378
+ this[l] = t, this.#r = je(t);
1379
+ }
1380
+ /** @inheritDoc */
1381
+ setPhpIniPath(e) {
1382
+ if (this.#t)
1383
+ throw new Error("Cannot set PHP ini path after calling run().");
1384
+ this[l].ccall(
1385
+ "wasm_set_phpini_path",
1386
+ null,
1387
+ ["string"],
1388
+ [e]
1389
+ );
1390
+ }
1391
+ /** @inheritDoc */
1392
+ setPhpIniEntry(e, t) {
1393
+ if (this.#t)
1394
+ throw new Error("Cannot set PHP ini entries after calling run().");
1395
+ this.#e.push([e, t]);
1396
+ }
1397
+ /** @inheritDoc */
1398
+ chdir(e) {
1399
+ this[l].FS.chdir(e);
1400
+ }
1401
+ /** @inheritDoc */
1402
+ async request(e, t) {
1403
+ if (!this.requestHandler)
1404
+ throw new Error("No request handler available.");
1405
+ return this.requestHandler.request(e, t);
1406
+ }
1407
+ /** @inheritDoc */
1408
+ async run(e) {
1409
+ this.#t || (this.#n(), this.#t = !0), this.#u(e.scriptPath || ""), this.#s(e.relativeUri || ""), this.#a(e.method || "GET");
1410
+ const { host: t, ...s } = {
1411
+ host: "example.com:443",
1412
+ ...X(e.headers || {})
1413
+ };
1414
+ if (this.#o(t, e.protocol || "http"), this.#c(s), e.body && this.#l(e.body), e.fileInfos)
1415
+ for (const n of e.fileInfos)
1416
+ this.#h(n);
1417
+ return e.code && this.#p(" ?>" + e.code), await this.#d();
1418
+ }
1419
+ #n() {
1420
+ if (this.#e.length > 0) {
1421
+ const e = this.#e.map(([t, s]) => `${t}=${s}`).join(`
1422
+ `) + `
1423
+
1424
+ `;
1425
+ this[l].ccall(
1426
+ "wasm_set_phpini_entries",
1427
+ null,
1428
+ [p],
1429
+ [e]
1430
+ );
1431
+ }
1432
+ this[l].ccall("php_wasm_init", null, [], []);
1433
+ }
1434
+ #i() {
1435
+ const e = "/tmp/headers.json";
1436
+ if (!this.fileExists(e))
1437
+ throw new Error(
1438
+ "SAPI Error: Could not find response headers file."
1439
+ );
1440
+ const t = JSON.parse(this.readFileAsText(e)), s = {};
1441
+ for (const n of t.headers) {
1442
+ if (!n.includes(": "))
1443
+ continue;
1444
+ const i = n.indexOf(": "), o = n.substring(0, i).toLowerCase(), a = n.substring(i + 2);
1445
+ o in s || (s[o] = []), s[o].push(a);
1446
+ }
1447
+ return {
1448
+ headers: s,
1449
+ httpStatusCode: t.status
1450
+ };
1451
+ }
1452
+ #s(e) {
1453
+ if (this[l].ccall(
1454
+ "wasm_set_request_uri",
1455
+ null,
1456
+ [p],
1457
+ [e]
1458
+ ), e.includes("?")) {
1459
+ const t = e.substring(e.indexOf("?") + 1);
1460
+ this[l].ccall(
1461
+ "wasm_set_query_string",
1462
+ null,
1463
+ [p],
1464
+ [t]
1465
+ );
1466
+ }
1467
+ }
1468
+ #o(e, t) {
1469
+ this[l].ccall(
1470
+ "wasm_set_request_host",
1471
+ null,
1472
+ [p],
1473
+ [e]
1474
+ );
1475
+ let s;
1476
+ try {
1477
+ s = parseInt(new URL(e).port, 10);
1478
+ } catch {
1479
+ }
1480
+ (!s || isNaN(s) || s === 80) && (s = t === "https" ? 443 : 80), this[l].ccall(
1481
+ "wasm_set_request_port",
1482
+ null,
1483
+ [y],
1484
+ [s]
1485
+ ), (t === "https" || !t && s === 443) && this.addServerGlobalEntry("HTTPS", "on");
1486
+ }
1487
+ #a(e) {
1488
+ this[l].ccall(
1489
+ "wasm_set_request_method",
1490
+ null,
1491
+ [p],
1492
+ [e]
1493
+ );
1494
+ }
1495
+ #c(e) {
1496
+ e.cookie && this[l].ccall(
1497
+ "wasm_set_cookies",
1498
+ null,
1499
+ [p],
1500
+ [e.cookie]
1501
+ ), e["content-type"] && this[l].ccall(
1502
+ "wasm_set_content_type",
1503
+ null,
1504
+ [p],
1505
+ [e["content-type"]]
1506
+ ), e["content-length"] && this[l].ccall(
1507
+ "wasm_set_content_length",
1508
+ null,
1509
+ [y],
1510
+ [parseInt(e["content-length"], 10)]
1511
+ );
1512
+ for (const t in e)
1513
+ this.addServerGlobalEntry(
1514
+ `HTTP_${t.toUpperCase().replace(/-/g, "_")}`,
1515
+ e[t]
1516
+ );
1517
+ }
1518
+ #l(e) {
1519
+ this[l].ccall(
1520
+ "wasm_set_request_body",
1521
+ null,
1522
+ [p],
1523
+ [e]
1524
+ ), this[l].ccall(
1525
+ "wasm_set_content_length",
1526
+ null,
1527
+ [y],
1528
+ [new TextEncoder().encode(e).length]
1529
+ );
1530
+ }
1531
+ #u(e) {
1532
+ this[l].ccall(
1533
+ "wasm_set_path_translated",
1534
+ null,
1535
+ [p],
1536
+ [e]
1537
+ );
1538
+ }
1539
+ addServerGlobalEntry(e, t) {
1540
+ this[l].ccall(
1541
+ "wasm_add_SERVER_entry",
1542
+ null,
1543
+ [p, p],
1544
+ [e, t]
1545
+ );
1546
+ }
1547
+ /**
1548
+ * Adds file information to $_FILES superglobal in PHP.
1549
+ *
1550
+ * In particular:
1551
+ * * Creates the file data in the filesystem
1552
+ * * Registers the file details in PHP
1553
+ *
1554
+ * @param fileInfo - File details
1555
+ */
1556
+ #h(e) {
1557
+ const { key: t, name: s, type: n, data: i } = e, o = `/tmp/${Math.random().toFixed(20)}`;
1558
+ this.writeFile(o, i);
1559
+ const a = 0;
1560
+ this[l].ccall(
1561
+ "wasm_add_uploaded_file",
1562
+ null,
1563
+ [p, p, p, p, y, y],
1564
+ [t, s, n, o, a, i.byteLength]
1565
+ );
1566
+ }
1567
+ #p(e) {
1568
+ this[l].ccall(
1569
+ "wasm_set_php_code",
1570
+ null,
1571
+ [p],
1572
+ [e]
1573
+ );
1574
+ }
1575
+ async #d() {
1576
+ let e, t;
1577
+ try {
1578
+ e = await new Promise(async (i, o) => {
1579
+ t = (a) => {
1580
+ const c = new Error("Rethrown");
1581
+ c.cause = a.error, c.betterMessage = a.message, o(c);
1582
+ }, this.#r?.addEventListener(
1583
+ "error",
1584
+ t
1585
+ );
1586
+ try {
1587
+ i(
1588
+ /**
1589
+ * This is awkward, but Asyncify makes wasm_sapi_handle_request return
1590
+ * Promise<Promise<number>>.
1591
+ *
1592
+ * @TODO: Determine whether this is a bug in emscripten or in our code.
1593
+ */
1594
+ await await this[l].ccall(
1595
+ "wasm_sapi_handle_request",
1596
+ y,
1597
+ [],
1598
+ []
1599
+ )
1600
+ );
1601
+ } catch (a) {
1602
+ o(a);
1603
+ }
1604
+ });
1605
+ } catch (i) {
1606
+ for (const u in this)
1607
+ typeof this[u] == "function" && (this[u] = () => {
1608
+ throw new Error(
1609
+ "PHP runtime has crashed – see the earlier error for details."
1610
+ );
1611
+ });
1612
+ this.functionsMaybeMissingFromAsyncify = Ge();
1613
+ const o = i, a = "betterMessage" in o ? o.betterMessage : o.message, c = new Error(a);
1614
+ throw c.cause = o, c;
1615
+ } finally {
1616
+ this.#r?.removeEventListener("error", t);
1617
+ }
1618
+ const { headers: s, httpStatusCode: n } = this.#i();
1619
+ return new $(
1620
+ n,
1621
+ s,
1622
+ this.readFileAsBuffer("/tmp/stdout"),
1623
+ this.readFileAsText("/tmp/stderr"),
1624
+ e
1625
+ );
1626
+ }
1627
+ mkdir(e) {
1628
+ this[l].FS.mkdirTree(e);
1629
+ }
1630
+ mkdirTree(e) {
1631
+ this.mkdir(e);
1632
+ }
1633
+ readFileAsText(e) {
1634
+ return new TextDecoder().decode(this.readFileAsBuffer(e));
1635
+ }
1636
+ readFileAsBuffer(e) {
1637
+ return this[l].FS.readFile(e);
1638
+ }
1639
+ writeFile(e, t) {
1640
+ this[l].FS.writeFile(e, t);
1641
+ }
1642
+ unlink(e) {
1643
+ this[l].FS.unlink(e);
1644
+ }
1645
+ mv(e, t) {
1646
+ this[l].FS.mv(e, t);
1647
+ }
1648
+ rmdir(e, t = { recursive: !0 }) {
1649
+ t?.recursive && this.listFiles(e).forEach((s) => {
1650
+ const n = `${e}/${s}`;
1651
+ this.isDir(n) ? this.rmdir(n, t) : this.unlink(n);
1652
+ }), this[l].FS.rmdir(e);
1653
+ }
1654
+ listFiles(e) {
1655
+ if (!this.fileExists(e))
1656
+ return [];
1657
+ try {
1658
+ return this[l].FS.readdir(e).filter(
1659
+ (t) => t !== "." && t !== ".."
1660
+ );
1661
+ } catch (t) {
1662
+ return console.error(t, { path: e }), [];
1663
+ }
1664
+ }
1665
+ isDir(e) {
1666
+ return this.fileExists(e) ? this[l].FS.isDir(
1667
+ this[l].FS.lookupPath(e).node.mode
1668
+ ) : !1;
1669
+ }
1670
+ fileExists(e) {
1671
+ try {
1672
+ return this[l].FS.lookupPath(e), !0;
1673
+ } catch {
1674
+ return !1;
1675
+ }
1676
+ }
1677
+ }
1678
+ m([
1679
+ f('Could not create directory "{path}"')
1680
+ ], w.prototype, "mkdir", 1);
1681
+ m([
1682
+ f('Could not create directory "{path}"')
1683
+ ], w.prototype, "mkdirTree", 1);
1684
+ m([
1685
+ f('Could not read "{path}"')
1686
+ ], w.prototype, "readFileAsText", 1);
1687
+ m([
1688
+ f('Could not read "{path}"')
1689
+ ], w.prototype, "readFileAsBuffer", 1);
1690
+ m([
1691
+ f('Could not write to "{path}"')
1692
+ ], w.prototype, "writeFile", 1);
1693
+ m([
1694
+ f('Could not unlink "{path}"')
1695
+ ], w.prototype, "unlink", 1);
1696
+ m([
1697
+ f('Could not move "{path}"')
1698
+ ], w.prototype, "mv", 1);
1699
+ m([
1700
+ f('Could not remove directory "{path}"')
1701
+ ], w.prototype, "rmdir", 1);
1702
+ m([
1703
+ f('Could not list files in "{path}"')
1704
+ ], w.prototype, "listFiles", 1);
1705
+ m([
1706
+ f('Could not stat "{path}"')
1707
+ ], w.prototype, "isDir", 1);
1708
+ m([
1709
+ f('Could not stat "{path}"')
1710
+ ], w.prototype, "fileExists", 1);
1711
+ function X(r) {
1712
+ const e = {};
1713
+ for (const t in r)
1714
+ e[t.toLowerCase()] = r[t];
1715
+ return e;
1716
+ }
1717
+ const et = [
1718
+ "vfs",
1719
+ "literal",
1720
+ "wordpress.org/themes",
1721
+ "wordpress.org/plugins",
1722
+ "url"
1723
+ ];
1724
+ function tt(r) {
1725
+ return r && typeof r == "object" && typeof r.resource == "string" && et.includes(r.resource);
1726
+ }
1727
+ class g {
1728
+ /**
1729
+ * Creates a new Resource based on the given file reference
1730
+ *
1731
+ * @param ref The file reference to create the Resource for
1732
+ * @param options Additional options for the Resource
1733
+ * @returns A new Resource instance
1734
+ */
1735
+ static create(e, { semaphore: t, progress: s }) {
1736
+ let n;
1737
+ switch (e.resource) {
1738
+ case "vfs":
1739
+ n = new rt(e, s);
1740
+ break;
1741
+ case "literal":
1742
+ n = new st(e, s);
1743
+ break;
1744
+ case "wordpress.org/themes":
1745
+ n = new ot(e, s);
1746
+ break;
1747
+ case "wordpress.org/plugins":
1748
+ n = new at(e, s);
1749
+ break;
1750
+ case "url":
1751
+ n = new it(e, s);
1752
+ break;
1753
+ default:
1754
+ throw new Error(`Invalid resource: ${e}`);
1755
+ }
1756
+ return n = new ct(n), t && (n = new lt(n, t)), n;
1757
+ }
1758
+ setPlayground(e) {
1759
+ this.playground = e;
1760
+ }
1761
+ /** Whether this Resource is loaded asynchronously */
1762
+ get isAsync() {
1763
+ return !1;
1764
+ }
1765
+ }
1766
+ class rt extends g {
1767
+ /**
1768
+ * Creates a new instance of `VFSResource`.
1769
+ * @param playground The playground client.
1770
+ * @param resource The VFS reference.
1771
+ * @param progress The progress tracker.
1772
+ */
1773
+ constructor(e, t) {
1774
+ super(), this.resource = e, this.progress = t;
1775
+ }
1776
+ /** @inheritDoc */
1777
+ async resolve() {
1778
+ const e = await this.playground.readFileAsBuffer(
1779
+ this.resource.path
1780
+ );
1781
+ return this.progress?.set(100), new File([e], this.name);
1782
+ }
1783
+ /** @inheritDoc */
1784
+ get name() {
1785
+ return this.resource.path;
1786
+ }
1787
+ }
1788
+ class st extends g {
1789
+ /**
1790
+ * Creates a new instance of `LiteralResource`.
1791
+ * @param resource The literal reference.
1792
+ * @param progress The progress tracker.
1793
+ */
1794
+ constructor(e, t) {
1795
+ super(), this.resource = e, this.progress = t;
1796
+ }
1797
+ /** @inheritDoc */
1798
+ async resolve() {
1799
+ return this.progress?.set(100), new File([this.resource.contents], this.resource.name);
1800
+ }
1801
+ /** @inheritDoc */
1802
+ get name() {
1803
+ return this.resource.name;
1804
+ }
1805
+ }
1806
+ class C extends g {
1807
+ /**
1808
+ * Creates a new instance of `FetchResource`.
1809
+ * @param progress The progress tracker.
1810
+ */
1811
+ constructor(e) {
1812
+ super(), this.progress = e;
1813
+ }
1814
+ /** @inheritDoc */
1815
+ async resolve() {
1816
+ this.progress?.setCaption(this.caption);
1817
+ const e = this.getURL();
1818
+ let t = await fetch(e);
1819
+ if (t = await Ae(
1820
+ t,
1821
+ this.progress?.loadingListener ?? nt
1822
+ ), t.status !== 200)
1823
+ throw new Error(`Could not download "${e}"`);
1824
+ return new File([await t.blob()], this.name);
1825
+ }
1826
+ /**
1827
+ * Gets the caption for the progress tracker.
1828
+ * @returns The caption.
1829
+ */
1830
+ get caption() {
1831
+ return `Downloading ${this.name}`;
1832
+ }
1833
+ /** @inheritDoc */
1834
+ get name() {
1835
+ try {
1836
+ return new URL(this.getURL(), "http://example.com").pathname.split("/").pop();
1837
+ } catch {
1838
+ return this.getURL();
1839
+ }
1840
+ }
1841
+ /** @inheritDoc */
1842
+ get isAsync() {
1843
+ return !0;
1844
+ }
1845
+ }
1846
+ const nt = () => {
1847
+ };
1848
+ class it extends C {
1849
+ /**
1850
+ * Creates a new instance of `UrlResource`.
1851
+ * @param resource The URL reference.
1852
+ * @param progress The progress tracker.
1853
+ */
1854
+ constructor(e, t) {
1855
+ super(t), this.resource = e;
1856
+ }
1857
+ /** @inheritDoc */
1858
+ getURL() {
1859
+ return this.resource.url;
1860
+ }
1861
+ /** @inheritDoc */
1862
+ get caption() {
1863
+ return this.resource.caption ?? super.caption;
1864
+ }
1865
+ }
1866
+ let U = "https://playground.wordpress.net/plugin-proxy";
1867
+ function ft(r) {
1868
+ U = r;
1869
+ }
1870
+ class ot extends C {
1871
+ constructor(e, t) {
1872
+ super(t), this.resource = e;
1873
+ }
1874
+ get name() {
1875
+ return E(this.resource.slug);
1876
+ }
1877
+ getURL() {
1878
+ const e = ee(this.resource.slug);
1879
+ return `${U}?theme=` + e;
1880
+ }
1881
+ }
1882
+ class at extends C {
1883
+ constructor(e, t) {
1884
+ super(t), this.resource = e;
1885
+ }
1886
+ /** @inheritDoc */
1887
+ get name() {
1888
+ return E(this.resource.slug);
1889
+ }
1890
+ /** @inheritDoc */
1891
+ getURL() {
1892
+ const e = ee(this.resource.slug);
1893
+ return `${U}?plugin=` + e;
1894
+ }
1895
+ }
1896
+ function ee(r) {
1897
+ return !r || r.endsWith(".zip") ? r : r + ".latest-stable.zip";
1898
+ }
1899
+ class te extends g {
1900
+ constructor(e) {
1901
+ super(), this.resource = e;
1902
+ }
1903
+ /** @inheritDoc */
1904
+ async resolve() {
1905
+ return this.resource.resolve();
1906
+ }
1907
+ /** @inheritDoc */
1908
+ async setPlayground(e) {
1909
+ return this.resource.setPlayground(e);
1910
+ }
1911
+ /** @inheritDoc */
1912
+ get progress() {
1913
+ return this.resource.progress;
1914
+ }
1915
+ /** @inheritDoc */
1916
+ set progress(e) {
1917
+ this.resource.progress = e;
1918
+ }
1919
+ /** @inheritDoc */
1920
+ get name() {
1921
+ return this.resource.name;
1922
+ }
1923
+ /** @inheritDoc */
1924
+ get isAsync() {
1925
+ return this.resource.isAsync;
1926
+ }
1927
+ }
1928
+ class ct extends te {
1929
+ /** @inheritDoc */
1930
+ async resolve() {
1931
+ return this.promise || (this.promise = super.resolve()), this.promise;
1932
+ }
1933
+ }
1934
+ class lt extends te {
1935
+ constructor(e, t) {
1936
+ super(e), this.semaphore = t;
1937
+ }
1938
+ /** @inheritDoc */
1939
+ async resolve() {
1940
+ return this.isAsync ? this.semaphore.run(() => super.resolve()) : super.resolve();
1941
+ }
1942
+ }
1943
+ const ut = ["6.2", "6.1", "6.0", "5.9"];
1944
+ function mt(r, {
1945
+ progress: e = new F(),
1946
+ semaphore: t = new J({ concurrency: 3 }),
1947
+ onStepCompleted: s = () => {
1948
+ }
1949
+ } = {}) {
1950
+ const n = (r.steps || []).filter(ht), i = n.reduce(
1951
+ (a, c) => a + (c.progress?.weight || 1),
1952
+ 0
1953
+ ), o = n.map(
1954
+ (a) => pt(a, {
1955
+ semaphore: t,
1956
+ rootProgressTracker: e,
1957
+ totalProgressWeight: i
1958
+ })
1959
+ );
1960
+ return {
1961
+ versions: {
1962
+ php: j(
1963
+ r.preferredVersions?.php,
1964
+ Q,
1965
+ Oe
1966
+ ),
1967
+ wp: j(
1968
+ r.preferredVersions?.wp,
1969
+ ut,
1970
+ "6.2"
1971
+ )
1972
+ },
1973
+ run: async (a) => {
1974
+ try {
1975
+ for (const { resources: c } of o)
1976
+ for (const u of c)
1977
+ u.setPlayground(a), u.isAsync && u.resolve();
1978
+ for (const { run: c, step: u } of o) {
1979
+ const h = await c(a);
1980
+ s(h, u);
1981
+ }
1982
+ try {
1983
+ await a.goTo(
1984
+ r.landingPage || "/"
1985
+ );
1986
+ } catch {
1987
+ }
1988
+ } finally {
1989
+ e.finish();
1990
+ }
1991
+ }
1992
+ };
1993
+ }
1994
+ function j(r, e, t) {
1995
+ return r && e.includes(r) ? r : t;
1996
+ }
1997
+ function ht(r) {
1998
+ return !!(typeof r == "object" && r);
1999
+ }
2000
+ function pt(r, {
2001
+ semaphore: e,
2002
+ rootProgressTracker: t,
2003
+ totalProgressWeight: s
2004
+ }) {
2005
+ const n = t.stage(
2006
+ (r.progress?.weight || 1) / s
2007
+ ), i = {};
2008
+ for (const h of Object.keys(r)) {
2009
+ let d = r[h];
2010
+ tt(d) && (d = g.create(d, {
2011
+ semaphore: e
2012
+ })), i[h] = d;
2013
+ }
2014
+ const o = async (h) => {
2015
+ try {
2016
+ return n.fillSlowly(), await Ce[r.step](
2017
+ h,
2018
+ await dt(i),
2019
+ {
2020
+ tracker: n,
2021
+ initialCaption: r.progress?.caption
2022
+ }
2023
+ );
2024
+ } finally {
2025
+ n.finish();
2026
+ }
2027
+ }, a = G(i), c = G(i).filter(
2028
+ (h) => h.isAsync
2029
+ ), u = 1 / (c.length + 1);
2030
+ for (const h of c)
2031
+ h.progress = n.stage(u);
2032
+ return { run: o, step: r, resources: a };
2033
+ }
2034
+ function G(r) {
2035
+ const e = [];
2036
+ for (const t in r) {
2037
+ const s = r[t];
2038
+ s instanceof g && e.push(s);
2039
+ }
2040
+ return e;
2041
+ }
2042
+ async function dt(r) {
2043
+ const e = {};
2044
+ for (const t in r) {
2045
+ const s = r[t];
2046
+ s instanceof g ? e[t] = await s.resolve() : e[t] = s;
2047
+ }
2048
+ return e;
2049
+ }
2050
+ async function wt(r, e) {
2051
+ await r.run(e);
2052
+ }
2053
+ export {
2054
+ ie as activatePlugin,
2055
+ oe as applyWordPressPatches,
2056
+ mt as compileBlueprint,
2057
+ pe as cp,
2058
+ ye as defineSiteUrl,
2059
+ V as defineWpConfigConsts,
2060
+ $e as importFile,
2061
+ Ee as installPlugin,
2062
+ Re as installTheme,
2063
+ Te as login,
2064
+ fe as mkdir,
2065
+ de as mv,
2066
+ _e as replaceSite,
2067
+ he as request,
2068
+ me as rm,
2069
+ we as rmdir,
2070
+ wt as runBlueprintSteps,
2071
+ ce as runPHP,
2072
+ le as runPHPWithOptions,
2073
+ xe as runWpInstallationWizard,
2074
+ ue as setPhpIniEntry,
2075
+ ft as setPluginProxyURL,
2076
+ Fe as setSiteOptions,
2077
+ K as unzip,
2078
+ ke as updateUserMeta,
2079
+ ge as writeFile,
2080
+ be as zipEntireSite
2081
+ };