@wp-playground/blueprints 0.1.40 → 0.1.43

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