@wp-playground/cli 2.0.11 → 2.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,772 @@
1
+ import { logger as p, LogSeverity as F, errorLogPath as E } from "@php-wasm/logger";
2
+ import { consumeAPI as L, SupportedPHPVersions as O, printDebugDetails as Z, PHPResponse as $, exposeAPI as _, exposeSyncAPI as N } from "@php-wasm/universal";
3
+ import { resolveRemoteBlueprint as J, isBlueprintBundle as Q, compileBlueprint as Y, runBlueprintSteps as X } from "@wp-playground/blueprints";
4
+ import { zipDirectory as C, RecommendedPHPVersion as H, unzipFile as G } from "@wp-playground/common";
5
+ import m from "fs";
6
+ import { Worker as K, MessageChannel as ee } from "worker_threads";
7
+ import { p as T, a as te, e as re } from "./mounts-D1_eXSTw.js";
8
+ import oe from "express";
9
+ import { FileLockManagerForNode as ie } from "@php-wasm/node";
10
+ import se, { cpus as ne } from "os";
11
+ import { jspi as ae } from "wasm-feature-detect";
12
+ import le from "yargs";
13
+ import w, { basename as pe } from "path";
14
+ import { NodeJsFilesystem as ue, OverlayFilesystem as de, InMemoryFilesystem as ce, ZipFilesystem as he } from "@wp-playground/storage";
15
+ import { EmscriptenDownloadMonitor as fe, ProgressTracker as me } from "@php-wasm/progress";
16
+ import { resolveWordPressRelease as we } from "@wp-playground/wordpress";
17
+ import v from "fs-extra";
18
+ import { startBridge as ye } from "@php-wasm/xdebug-bridge";
19
+ async function be(e) {
20
+ const r = oe(), t = await new Promise((s, n) => {
21
+ const l = r.listen(e.port, () => {
22
+ const a = l.address();
23
+ a === null || typeof a == "string" ? n(new Error("Server address is not available")) : s(l);
24
+ });
25
+ });
26
+ r.use("/", async (s, n) => {
27
+ const l = await e.handleRequest({
28
+ url: s.url,
29
+ headers: Pe(s),
30
+ method: s.method,
31
+ body: await ge(s)
32
+ });
33
+ n.statusCode = l.httpStatusCode;
34
+ for (const a in l.headers)
35
+ n.setHeader(a, l.headers[a]);
36
+ n.end(l.bytes);
37
+ });
38
+ const o = t.address().port;
39
+ return await e.onBind(t, o);
40
+ }
41
+ const ge = async (e) => await new Promise((r) => {
42
+ const t = [];
43
+ e.on("data", (i) => {
44
+ t.push(i);
45
+ }), e.on("end", () => {
46
+ r(new Uint8Array(Buffer.concat(t)));
47
+ });
48
+ }), Pe = (e) => {
49
+ const r = {};
50
+ if (e.rawHeaders && e.rawHeaders.length)
51
+ for (let t = 0; t < e.rawHeaders.length; t += 2)
52
+ r[e.rawHeaders[t].toLowerCase()] = e.rawHeaders[t + 1];
53
+ return r;
54
+ };
55
+ class ke {
56
+ constructor(r) {
57
+ this.workerLoads = [], this.addWorker(r);
58
+ }
59
+ addWorker(r) {
60
+ this.workerLoads.push({
61
+ worker: r,
62
+ activeRequests: /* @__PURE__ */ new Set()
63
+ });
64
+ }
65
+ async handleRequest(r) {
66
+ let t = this.workerLoads[0];
67
+ for (let o = 1; o < this.workerLoads.length; o++) {
68
+ const s = this.workerLoads[o];
69
+ s.activeRequests.size < t.activeRequests.size && (t = s);
70
+ }
71
+ const i = t.worker.request(r);
72
+ return t.activeRequests.add(i), i.url = r.url, i.finally(() => {
73
+ t.activeRequests.delete(i);
74
+ });
75
+ }
76
+ }
77
+ function ve(e) {
78
+ return /^latest$|^trunk$|^nightly$|^(?:(\d+)\.(\d+)(?:\.(\d+))?)((?:-beta(?:\d+)?)|(?:-RC(?:\d+)?))?$/.test(e);
79
+ }
80
+ async function Se({
81
+ sourceString: e,
82
+ blueprintMayReadAdjacentFiles: r
83
+ }) {
84
+ if (!e)
85
+ return;
86
+ if (e.startsWith("http://") || e.startsWith("https://"))
87
+ return await J(e);
88
+ let t = w.resolve(process.cwd(), e);
89
+ if (!m.existsSync(t))
90
+ throw new Error(`Blueprint file does not exist: ${t}`);
91
+ const i = m.statSync(t);
92
+ if (i.isDirectory() && (t = w.join(t, "blueprint.json")), !i.isFile() && i.isSymbolicLink())
93
+ throw new Error(
94
+ `Blueprint path is neither a file nor a directory: ${t}`
95
+ );
96
+ const o = w.extname(t);
97
+ switch (o) {
98
+ case ".zip":
99
+ return he.fromArrayBuffer(
100
+ m.readFileSync(t).buffer
101
+ );
102
+ case ".json": {
103
+ const s = m.readFileSync(t, "utf-8");
104
+ try {
105
+ JSON.parse(s);
106
+ } catch {
107
+ throw new Error(
108
+ `Blueprint file at ${t} is not a valid JSON file`
109
+ );
110
+ }
111
+ const n = w.dirname(t), l = new ue(n);
112
+ return new de([
113
+ new ce({
114
+ "blueprint.json": s
115
+ }),
116
+ /**
117
+ * Wrap the NodeJS filesystem to prevent access to local files
118
+ * unless the user explicitly allowed it.
119
+ */
120
+ {
121
+ read(a) {
122
+ if (!r)
123
+ throw new Error(
124
+ `Error: Blueprint contained tried to read a local file at path "${a}" (via a resource of type "bundled"). Playground restricts access to local resources by default as a security measure.
125
+
126
+ You can allow this Blueprint to read files from the same parent directory by explicitly adding the --blueprint-may-read-adjacent-files option to your command.`
127
+ );
128
+ return l.read(a);
129
+ }
130
+ }
131
+ ]);
132
+ }
133
+ default:
134
+ throw new Error(
135
+ `Unsupported blueprint file extension: ${o}. Only .zip and .json files are supported.`
136
+ );
137
+ }
138
+ }
139
+ const R = "" + new URL("worker-thread-v2-Pfv6UYF4.js", import.meta.url).href;
140
+ class xe {
141
+ constructor(r, t) {
142
+ this.lastProgressMessage = "", this.args = r, this.siteUrl = t.siteUrl, this.processIdSpaceLength = t.processIdSpaceLength, this.phpVersion = r.php;
143
+ }
144
+ getWorkerUrl() {
145
+ return process.env.VITEST && R.startsWith("/src/") ? w.join(
146
+ import.meta.dirname,
147
+ "..",
148
+ "..",
149
+ R
150
+ ) : R;
151
+ }
152
+ async bootPrimaryWorker(r, t) {
153
+ const i = L(r);
154
+ await i.useFileLockManager(t);
155
+ const o = {
156
+ ...this.args,
157
+ php: this.phpVersion,
158
+ siteUrl: this.siteUrl,
159
+ firstProcessId: 1,
160
+ processIdSpaceLength: this.processIdSpaceLength,
161
+ trace: this.args.debug || !1,
162
+ blueprint: this.args.blueprint
163
+ };
164
+ return await i.bootAsPrimaryWorker(o), i;
165
+ }
166
+ async bootSecondaryWorker({
167
+ worker: r,
168
+ fileLockManagerPort: t,
169
+ firstProcessId: i
170
+ }) {
171
+ const o = L(r.phpPort);
172
+ await o.useFileLockManager(t);
173
+ const s = {
174
+ ...this.args,
175
+ php: this.phpVersion,
176
+ siteUrl: this.siteUrl,
177
+ firstProcessId: i,
178
+ processIdSpaceLength: this.processIdSpaceLength,
179
+ trace: this.args.debug || !1,
180
+ blueprint: this.args.blueprint
181
+ };
182
+ return await o.bootAsSecondaryWorker(s), o;
183
+ }
184
+ writeProgressUpdate(r, t, i) {
185
+ t !== this.lastProgressMessage && (this.lastProgressMessage = t, r.isTTY ? (r.cursorTo(0), r.write(t), r.clearLine(1), i && r.write(`
186
+ `)) : r.write(`${t}
187
+ `));
188
+ }
189
+ }
190
+ const U = w.join(se.homedir(), ".wordpress-playground");
191
+ async function We(e) {
192
+ return await V(
193
+ "https://github.com/WordPress/sqlite-database-integration/archive/refs/heads/develop.zip",
194
+ "sqlite.zip",
195
+ e
196
+ );
197
+ }
198
+ async function V(e, r, t) {
199
+ const i = w.join(U, r);
200
+ return v.existsSync(i) || (v.ensureDirSync(U), await Le(e, i, t)), q(i);
201
+ }
202
+ async function Le(e, r, t) {
203
+ const o = (await t.monitorFetch(fetch(e))).body.getReader(), s = `${r}.partial`, n = v.createWriteStream(s);
204
+ for (; ; ) {
205
+ const { done: l, value: a } = await o.read();
206
+ if (a && n.write(a), l)
207
+ break;
208
+ }
209
+ n.close(), n.closed || await new Promise((l, a) => {
210
+ n.on("finish", () => {
211
+ v.renameSync(s, r), l(null);
212
+ }), n.on("error", (u) => {
213
+ v.removeSync(s), a(u);
214
+ });
215
+ });
216
+ }
217
+ function q(e, r) {
218
+ return new File([v.readFileSync(e)], pe(e));
219
+ }
220
+ const B = "" + new URL("worker-thread-v1-BTJIbQLy.js", import.meta.url).href;
221
+ class Ie {
222
+ constructor(r, t) {
223
+ this.lastProgressMessage = "", this.args = r, this.siteUrl = t.siteUrl, this.processIdSpaceLength = t.processIdSpaceLength;
224
+ }
225
+ getWorkerUrl() {
226
+ return process.env.VITEST && B.startsWith("/src/") ? w.join(
227
+ import.meta.dirname,
228
+ "..",
229
+ "..",
230
+ B
231
+ ) : B;
232
+ }
233
+ async bootPrimaryWorker(r, t) {
234
+ const i = await this.compileInputBlueprint(
235
+ this.args["additional-blueprint-steps"] || []
236
+ );
237
+ this.phpVersion = i.versions.php;
238
+ let o;
239
+ const s = new fe();
240
+ if (!this.args.skipWordPressSetup) {
241
+ let h = !1;
242
+ s.addEventListener("progress", (I) => {
243
+ if (h)
244
+ return;
245
+ const { loaded: f, total: y } = I.detail, P = Math.floor(
246
+ Math.min(100, 100 * f / y)
247
+ );
248
+ h = P === 100, this.writeProgressUpdate(
249
+ process.stdout,
250
+ `Downloading WordPress ${P}%...`,
251
+ h
252
+ );
253
+ }), o = await we(this.args.wp), p.log(
254
+ `Resolved WordPress release URL: ${o?.releaseUrl}`
255
+ );
256
+ }
257
+ const n = o && w.join(
258
+ U,
259
+ `prebuilt-wp-content-for-wp-${o.version}.zip`
260
+ ), l = o ? m.existsSync(n) ? q(n) : await V(
261
+ o.releaseUrl,
262
+ `${o.version}.zip`,
263
+ s
264
+ ) : void 0;
265
+ p.log("Fetching SQLite integration plugin...");
266
+ const a = this.args.skipSqliteSetup ? void 0 : await We(s), u = this.args.followSymlinks === !0, d = this.args.experimentalTrace === !0, b = this.args["mount-before-install"] || [], S = this.args.mount || [], c = L(r);
267
+ return await c.isConnected(), p.log("Booting WordPress..."), await c.useFileLockManager(t), await c.bootAsPrimaryWorker({
268
+ phpVersion: this.phpVersion,
269
+ wpVersion: i.versions.wp,
270
+ absoluteUrl: this.siteUrl,
271
+ mountsBeforeWpInstall: b,
272
+ mountsAfterWpInstall: S,
273
+ wordPressZip: l && await l.arrayBuffer(),
274
+ sqliteIntegrationPluginZip: await a?.arrayBuffer(),
275
+ firstProcessId: 0,
276
+ processIdSpaceLength: this.processIdSpaceLength,
277
+ followSymlinks: u,
278
+ trace: d,
279
+ internalCookieStore: this.args.internalCookieStore,
280
+ withXdebug: this.args.xdebug
281
+ }), o && !this.args["mount-before-install"] && !m.existsSync(n) && (p.log("Caching preinstalled WordPress for the next boot..."), m.writeFileSync(
282
+ n,
283
+ await C(c, "/wordpress")
284
+ ), p.log("Cached!")), c;
285
+ }
286
+ async bootSecondaryWorker({
287
+ worker: r,
288
+ fileLockManagerPort: t,
289
+ firstProcessId: i
290
+ }) {
291
+ const o = L(
292
+ r.phpPort
293
+ );
294
+ return await o.isConnected(), await o.useFileLockManager(t), await o.bootAsSecondaryWorker({
295
+ phpVersion: this.phpVersion,
296
+ absoluteUrl: this.siteUrl,
297
+ mountsBeforeWpInstall: this.args["mount-before-install"] || [],
298
+ mountsAfterWpInstall: this.args.mount || [],
299
+ // Skip WordPress zip because we share the /wordpress directory
300
+ // populated by the initial worker.
301
+ wordPressZip: void 0,
302
+ // Skip SQLite integration plugin for now because we
303
+ // will copy it from primary's `/internal` directory.
304
+ sqliteIntegrationPluginZip: void 0,
305
+ dataSqlPath: "/wordpress/wp-content/database/.ht.sqlite",
306
+ firstProcessId: i,
307
+ processIdSpaceLength: this.processIdSpaceLength,
308
+ followSymlinks: this.args.followSymlinks === !0,
309
+ trace: this.args.experimentalTrace === !0,
310
+ // @TODO: Move this to the request handler or else every worker
311
+ // will have a separate cookie store.
312
+ internalCookieStore: this.args.internalCookieStore,
313
+ withXdebug: this.args.xdebug
314
+ }), await o.isReady(), o;
315
+ }
316
+ async compileInputBlueprint(r) {
317
+ const t = this.args, i = t.blueprint, o = Q(i) ? i : {
318
+ login: t.login,
319
+ ...i || {},
320
+ preferredVersions: {
321
+ php: t.php ?? i?.preferredVersions?.php ?? H,
322
+ wp: t.wp ?? i?.preferredVersions?.wp ?? "latest",
323
+ ...i?.preferredVersions || {}
324
+ }
325
+ }, s = new me();
326
+ let n = "", l = !1;
327
+ return s.addEventListener("progress", (a) => {
328
+ if (l)
329
+ return;
330
+ l = a.detail.progress === 100;
331
+ const u = Math.floor(a.detail.progress);
332
+ n = a.detail.caption || n || "Running the Blueprint";
333
+ const d = `${n.trim()} – ${u}%`;
334
+ this.writeProgressUpdate(
335
+ process.stdout,
336
+ d,
337
+ l
338
+ );
339
+ }), await Y(o, {
340
+ progress: s,
341
+ additionalSteps: r
342
+ });
343
+ }
344
+ writeProgressUpdate(r, t, i) {
345
+ this.args.verbosity !== M.Quiet.name && t !== this.lastProgressMessage && (this.lastProgressMessage = t, r.isTTY ? (r.cursorTo(0), r.write(t), r.clearLine(1), i && r.write(`
346
+ `)) : r.write(`${t}
347
+ `));
348
+ }
349
+ }
350
+ const M = {
351
+ Quiet: { name: "quiet", severity: F.Fatal },
352
+ Normal: { name: "normal", severity: F.Info },
353
+ Debug: { name: "debug", severity: F.Debug }
354
+ };
355
+ async function Qe() {
356
+ try {
357
+ const e = le(process.argv.slice(2)).usage("Usage: wp-playground <command> [options]").positional("command", {
358
+ describe: "Command to run",
359
+ choices: ["server", "run-blueprint", "build-snapshot"],
360
+ demandOption: !0
361
+ }).option("outfile", {
362
+ describe: "When building, write to this output file.",
363
+ type: "string",
364
+ default: "wordpress.zip"
365
+ }).option("port", {
366
+ describe: "Port to listen on when serving.",
367
+ type: "number",
368
+ default: 9400
369
+ }).option("site-url", {
370
+ describe: "Site URL to use for WordPress. Defaults to http://127.0.0.1:{port}",
371
+ type: "string"
372
+ }).option("php", {
373
+ describe: "PHP version to use.",
374
+ type: "string",
375
+ default: H,
376
+ choices: O
377
+ }).option("wp", {
378
+ describe: "WordPress version to use.",
379
+ type: "string",
380
+ default: "latest"
381
+ }).option("mount", {
382
+ describe: "Mount a directory to the PHP runtime (can be used multiple times). Format: /host/path:/vfs/path",
383
+ type: "array",
384
+ string: !0,
385
+ coerce: T
386
+ }).option("mount-before-install", {
387
+ describe: "Mount a directory to the PHP runtime before WordPress installation (can be used multiple times). Format: /host/path:/vfs/path",
388
+ type: "array",
389
+ string: !0,
390
+ coerce: T
391
+ }).option("mount-dir", {
392
+ describe: 'Mount a directory to the PHP runtime (can be used multiple times). Format: "/host/path" "/vfs/path"',
393
+ type: "array",
394
+ nargs: 2,
395
+ array: !0
396
+ // coerce: parseMountDirArguments,
397
+ }).option("mount-dir-before-install", {
398
+ describe: 'Mount a directory before WordPress installation (can be used multiple times). Format: "/host/path" "/vfs/path"',
399
+ type: "string",
400
+ nargs: 2,
401
+ array: !0,
402
+ coerce: te
403
+ }).option("login", {
404
+ describe: "Should log the user in",
405
+ type: "boolean",
406
+ default: !1
407
+ }).option("blueprint", {
408
+ describe: "Blueprint to execute.",
409
+ type: "string"
410
+ }).option("blueprint-may-read-adjacent-files", {
411
+ describe: 'Consent flag: Allow "bundled" resources in a local blueprint to read files in the same directory as the blueprint file.',
412
+ type: "boolean",
413
+ default: !1
414
+ }).option("skip-wordpress-setup", {
415
+ describe: "Do not download, unzip, and install WordPress. Useful for mounting a pre-configured WordPress directory at /wordpress.",
416
+ type: "boolean",
417
+ default: !1
418
+ }).option("skip-sqlite-setup", {
419
+ describe: "Skip the SQLite integration plugin setup to allow the WordPress site to use MySQL.",
420
+ type: "boolean",
421
+ default: !1
422
+ }).option("quiet", {
423
+ describe: "Do not output logs and progress messages.",
424
+ type: "boolean",
425
+ default: !1,
426
+ hidden: !0
427
+ }).option("verbosity", {
428
+ describe: "Output logs and progress messages.",
429
+ type: "string",
430
+ choices: Object.values(M).map(
431
+ (o) => o.name
432
+ ),
433
+ default: "normal"
434
+ }).option("debug", {
435
+ describe: "Print PHP error log content if an error occurs during Playground boot.",
436
+ type: "boolean",
437
+ default: !1
438
+ }).option("auto-mount", {
439
+ describe: "Automatically mount the specified directory. If no path is provided, mount the current working directory. You can mount a WordPress directory, a plugin directory, a theme directory, a wp-content directory, or any directory containing PHP and HTML files.",
440
+ type: "string"
441
+ }).option("follow-symlinks", {
442
+ describe: `Allow Playground to follow symlinks by automatically mounting symlinked directories and files encountered in mounted directories.
443
+ Warning: Following symlinks will expose files outside mounted directories to Playground and could be a security risk.`,
444
+ type: "boolean",
445
+ default: !1
446
+ }).option("experimental-trace", {
447
+ describe: "Print detailed messages about system behavior to the console. Useful for troubleshooting.",
448
+ type: "boolean",
449
+ default: !1,
450
+ // Hide this option because we want to replace with a more general log-level flag.
451
+ hidden: !0
452
+ }).option("internal-cookie-store", {
453
+ describe: "Enable internal cookie handling. When enabled, Playground will manage cookies internally using an HttpCookieStore that persists cookies across requests. When disabled, cookies are handled externally (e.g., by a browser in Node.js environments).",
454
+ type: "boolean",
455
+ default: !1
456
+ }).option("xdebug", {
457
+ describe: "Enable Xdebug.",
458
+ type: "boolean",
459
+ default: !1
460
+ }).option("experimental-devtools", {
461
+ describe: "Enable experimental browser development tools.",
462
+ type: "boolean",
463
+ default: !1
464
+ }).option("experimental-multi-worker", {
465
+ describe: "Enable experimental multi-worker support which requires a /wordpress directory backed by a real filesystem. Pass a positive number to specify the number of workers to use. Otherwise, default to the number of CPUs minus 1.",
466
+ type: "number",
467
+ coerce: (o) => o ?? ne().length - 1
468
+ }).option("experimental-blueprints-v2-runner", {
469
+ describe: "Use the experimental Blueprint V2 runner.",
470
+ type: "boolean",
471
+ default: !1,
472
+ // Remove the "hidden" flag once Blueprint V2 is fully supported
473
+ hidden: !0
474
+ }).option("mode", {
475
+ describe: "Blueprints v2 runner mode to use. This option is required when using the --experimental-blueprints-v2-runner flag with a blueprint.",
476
+ type: "string",
477
+ choices: ["create-new-site", "apply-to-existing-site"],
478
+ // Remove the "hidden" flag once Blueprint V2 is fully supported
479
+ hidden: !0
480
+ }).showHelpOnFail(!1).strictOptions().check(async (o) => {
481
+ if (o.wp !== void 0 && !ve(o.wp))
482
+ try {
483
+ new URL(o.wp);
484
+ } catch {
485
+ throw new Error(
486
+ 'Unrecognized WordPress version. Please use "latest", a URL, or a numeric version such as "6.2", "6.0.1", "6.2-beta1", or "6.2-RC1"'
487
+ );
488
+ }
489
+ if (o["site-url"] !== void 0 && o["site-url"] !== "")
490
+ try {
491
+ new URL(o["site-url"]);
492
+ } catch {
493
+ throw new Error(
494
+ `Invalid site-url "${o["site-url"]}". Please provide a valid URL (e.g., http://localhost:8080 or https://example.com)`
495
+ );
496
+ }
497
+ if (o["auto-mount"]) {
498
+ let s = !1;
499
+ try {
500
+ s = m.statSync(o["auto-mount"]).isDirectory();
501
+ } catch {
502
+ s = !1;
503
+ }
504
+ if (!s)
505
+ throw new Error(
506
+ `The specified --auto-mount path is not a directory: '${o["auto-mount"]}'.`
507
+ );
508
+ }
509
+ if (o["experimental-multi-worker"] !== void 0) {
510
+ if (o["experimental-multi-worker"] <= 1)
511
+ throw new Error(
512
+ "The --experimental-multi-worker flag must be a positive integer greater than 1."
513
+ );
514
+ const s = (n) => n.vfsPath === "/wordpress";
515
+ if (!o.mount?.some(s) && !o["mount-before-install"]?.some(
516
+ s
517
+ ))
518
+ throw new Error(
519
+ "Please mount a real filesystem directory as the /wordpress directory before using the --experimental-multi-worker flag. For example: --mount-dir-before-install ./empty-dir /wordpress"
520
+ );
521
+ }
522
+ if (o["experimental-blueprints-v2-runner"] === !0) {
523
+ if (o.mode !== void 0) {
524
+ if ("skip-wordpress-setup" in o)
525
+ throw new Error(
526
+ "The --skipWordPressSetup option cannot be used with the --mode option. Use one or the other."
527
+ );
528
+ if ("skip-sqlite-setup" in o)
529
+ throw new Error(
530
+ "The --skipSqliteSetup option is not supported in Blueprint V2 mode."
531
+ );
532
+ if (o["auto-mount"] !== void 0)
533
+ throw new Error(
534
+ "The --mode option cannot be used with --auto-mount because --auto-mount automatically sets the mode."
535
+ );
536
+ } else
537
+ o["skip-wordpress-setup"] === !0 ? o.mode = "apply-to-existing-site" : o.mode = "create-new-site";
538
+ const s = o.allow || [];
539
+ o.followSymlinks === !0 && s.push("follow-symlinks"), o["blueprint-may-read-adjacent-files"] === !0 && s.push("read-local-fs"), o.allow = s;
540
+ } else if (o.mode !== void 0)
541
+ throw new Error(
542
+ "The --mode option requires the --experimentalBlueprintsV2Runner flag."
543
+ );
544
+ return !0;
545
+ });
546
+ e.wrap(e.terminalWidth());
547
+ const r = await e.argv, t = r._[0];
548
+ ["run-blueprint", "server", "build-snapshot"].includes(t) || (e.showHelp(), process.exit(1));
549
+ const i = {
550
+ ...r,
551
+ command: t,
552
+ mount: [...r.mount || [], ...r["mount-dir"] || []],
553
+ "mount-before-install": [
554
+ ...r["mount-before-install"] || [],
555
+ ...r["mount-dir-before-install"] || []
556
+ ]
557
+ };
558
+ await Fe(i);
559
+ } catch (e) {
560
+ if (!(e instanceof Error))
561
+ throw e;
562
+ if (process.argv.includes("--debug"))
563
+ Z(e);
564
+ else {
565
+ const t = [];
566
+ let i = e;
567
+ do
568
+ t.push(i.message), i = i.cause;
569
+ while (i instanceof Error);
570
+ console.error(
571
+ "\x1B[1m" + t.join(" caused by ") + "\x1B[0m"
572
+ );
573
+ }
574
+ process.exit(1);
575
+ }
576
+ }
577
+ async function Fe(e) {
578
+ let r, t;
579
+ const i = [];
580
+ if (e.autoMount !== void 0 && (e.autoMount === "" && (e = { ...e, autoMount: process.cwd() }), e = re(e)), e.quiet && (e.verbosity = "quiet", delete e.quiet), e.debug ? e.verbosity = "debug" : e.verbosity === "debug" && (e.debug = !0), e.verbosity) {
581
+ const a = Object.values(M).find(
582
+ (u) => u.name === e.verbosity
583
+ ).severity;
584
+ p.setSeverityFilterLevel(a);
585
+ }
586
+ const o = await import("fs-ext").then((a) => a.flockSync).catch(() => {
587
+ p.warn(
588
+ "The fs-ext package is not installed. Internal file locking will not be integrated with host OS file locking."
589
+ );
590
+ }), s = new ie(o);
591
+ let n = !1, l = !0;
592
+ return p.log("Starting a PHP server..."), be({
593
+ port: e.port,
594
+ onBind: async (a, u) => {
595
+ const d = `http://127.0.0.1:${u}`, b = e["site-url"] || d, S = e.experimentalMultiWorker ?? 1, c = Math.floor(
596
+ Number.MAX_SAFE_INTEGER / S
597
+ );
598
+ let h;
599
+ e["experimental-blueprints-v2-runner"] ? h = new xe(e, {
600
+ siteUrl: b,
601
+ processIdSpaceLength: c
602
+ }) : (h = new Ie(e, {
603
+ siteUrl: b,
604
+ processIdSpaceLength: c
605
+ }), typeof e.blueprint == "string" && (e.blueprint = await Se({
606
+ sourceString: e.blueprint,
607
+ blueprintMayReadAdjacentFiles: e["blueprint-may-read-adjacent-files"] === !0
608
+ })));
609
+ const I = Re(
610
+ h.getWorkerUrl(),
611
+ S,
612
+ ({ exitCode: f, isMain: y, workerIndex: P }) => {
613
+ f !== 0 && (p.error(
614
+ `Worker ${P} exited with code ${f}
615
+ `
616
+ ), y && e.exitOnPrimaryWorkerCrash && process.exit(1));
617
+ }
618
+ );
619
+ p.log(`Setting up WordPress ${e.wp}`);
620
+ try {
621
+ const [f, ...y] = await I, P = await A(
622
+ s
623
+ );
624
+ if (t = await h.bootPrimaryWorker(
625
+ f.phpPort,
626
+ P
627
+ ), i.push({
628
+ playground: t,
629
+ worker: f.worker
630
+ }), await t.isReady(), n = !0, p.log("Booted!"), r = new ke(t), !e["experimental-blueprints-v2-runner"]) {
631
+ const k = await h.compileInputBlueprint(
632
+ e["additional-blueprint-steps"] || []
633
+ );
634
+ k && (p.log("Running the Blueprint..."), await X(k, t), p.log("Finished running the blueprint"));
635
+ }
636
+ if (e.command === "build-snapshot" ? (await Be(t, e.outfile), p.log(`WordPress exported to ${e.outfile}`), process.exit(0)) : e.command === "run-blueprint" && (p.log("Blueprint executed"), process.exit(0)), e.experimentalMultiWorker && e.experimentalMultiWorker > 1) {
637
+ p.log("Preparing additional workers...");
638
+ const k = await C(
639
+ t,
640
+ "/internal"
641
+ ), g = c;
642
+ await Promise.all(
643
+ y.map(async (W, z) => {
644
+ const j = g + z * c, D = await A(s), x = await h.bootSecondaryWorker({
645
+ worker: W,
646
+ fileLockManagerPort: D,
647
+ firstProcessId: j
648
+ });
649
+ i.push({
650
+ playground: x,
651
+ worker: W.worker
652
+ }), await x.writeFile(
653
+ "/tmp/internal.zip",
654
+ k
655
+ ), await G(
656
+ x,
657
+ "/tmp/internal.zip",
658
+ "/internal"
659
+ ), await x.unlink(
660
+ "/tmp/internal.zip"
661
+ ), r.addWorker(x);
662
+ })
663
+ ), p.log("Ready!");
664
+ }
665
+ return p.log(`WordPress is running on ${d}`), e.experimentalDevtools && e.xdebug && (await ye({
666
+ getPHPFile: async (g) => await t.readFileAsText(g)
667
+ })).start(), {
668
+ playground: t,
669
+ server: a,
670
+ [Symbol.asyncDispose]: async function() {
671
+ await Promise.all(
672
+ i.map(
673
+ async ({ playground: g, worker: W }) => {
674
+ await g.dispose(), await W.terminate();
675
+ }
676
+ )
677
+ ), await new Promise((g) => a.close(g));
678
+ },
679
+ workerThreadCount: S
680
+ };
681
+ } catch (f) {
682
+ if (!e.debug)
683
+ throw f;
684
+ let y = "";
685
+ throw await t?.fileExists(E) && (y = await t.readFileAsText(E)), new Error(y, { cause: f });
686
+ }
687
+ },
688
+ async handleRequest(a) {
689
+ if (!n)
690
+ return $.forHttpCode(
691
+ 502,
692
+ "WordPress is not ready yet"
693
+ );
694
+ if (l) {
695
+ l = !1;
696
+ const u = {
697
+ "Content-Type": ["text/plain"],
698
+ "Content-Length": ["0"],
699
+ Location: ["/"]
700
+ };
701
+ return a.headers?.cookie?.includes(
702
+ "playground_auto_login_already_happened"
703
+ ) && (u["Set-Cookie"] = [
704
+ "playground_auto_login_already_happened=1; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/"
705
+ ]), new $(302, u, new Uint8Array());
706
+ }
707
+ return await r.handleRequest(a);
708
+ }
709
+ });
710
+ }
711
+ function Re(e, r, t) {
712
+ const i = new URL(e, import.meta.url), o = [];
713
+ for (let s = 0; s < r; s++) {
714
+ const n = new K(i), l = (a) => {
715
+ t({
716
+ exitCode: a,
717
+ isMain: s === 0,
718
+ workerIndex: s
719
+ });
720
+ };
721
+ o.push(
722
+ new Promise(
723
+ (a, u) => {
724
+ n.once("message", function(d) {
725
+ d.command === "worker-script-initialized" && a({ worker: n, phpPort: d.phpPort });
726
+ }), n.once("error", function(d) {
727
+ console.error(d);
728
+ const b = new Error(
729
+ `Worker failed to load at ${i}. ${d.message ? `Original error: ${d.message}` : ""}`
730
+ );
731
+ b.filename = i, u(b);
732
+ }), n.once("exit", l);
733
+ }
734
+ )
735
+ );
736
+ }
737
+ return Promise.all(o);
738
+ }
739
+ async function A(e) {
740
+ const { port1: r, port2: t } = new ee();
741
+ return await ae() ? _(e, null, r) : await N(e, r), t;
742
+ }
743
+ async function Be(e, r) {
744
+ await e.run({
745
+ code: `<?php
746
+ $zip = new ZipArchive();
747
+ if(false === $zip->open('/tmp/build.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
748
+ throw new Exception('Failed to create ZIP');
749
+ }
750
+ $files = new RecursiveIteratorIterator(
751
+ new RecursiveDirectoryIterator('/wordpress')
752
+ );
753
+ foreach ($files as $file) {
754
+ echo $file . PHP_EOL;
755
+ if (!$file->isFile()) {
756
+ continue;
757
+ }
758
+ $zip->addFile($file->getPathname(), $file->getPathname());
759
+ }
760
+ $zip->close();
761
+
762
+ `
763
+ });
764
+ const t = await e.readFileAsBuffer("/tmp/build.zip");
765
+ m.writeFileSync(r, t);
766
+ }
767
+ export {
768
+ M as L,
769
+ Qe as p,
770
+ Fe as r
771
+ };
772
+ //# sourceMappingURL=run-cli-ob90MazJ.js.map