@wp-playground/cli 3.0.54 → 3.1.1

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.
@@ -1,7 +1,8 @@
1
1
  /// <reference types="node" />
2
+ import { type Pooled } from '@php-wasm/universal';
2
3
  import type { PlaygroundCliBlueprintV1Worker } from './worker-thread-v1';
3
4
  import type { MessagePort as NodeMessagePort } from 'worker_threads';
4
- import { type RunCLIArgs, type SpawnedWorker, type WorkerType } from '../run-cli';
5
+ import { type PlaygroundCliWorker, type RunCLIArgs, type SpawnedWorker, type WorkerType } from '../run-cli';
5
6
  import type { CLIOutput } from '../cli-output';
6
7
  /**
7
8
  * Boots Playground CLI workers using Blueprint version 1.
@@ -11,20 +12,17 @@ import type { CLIOutput } from '../cli-output';
11
12
  */
12
13
  export declare class BlueprintsV1Handler {
13
14
  private siteUrl;
14
- private processIdSpaceLength;
15
15
  private args;
16
16
  private cliOutput;
17
17
  constructor(args: RunCLIArgs, options: {
18
18
  siteUrl: string;
19
- processIdSpaceLength: number;
20
19
  cliOutput: CLIOutput;
21
20
  });
22
21
  getWorkerType(): WorkerType;
23
- bootAndSetUpInitialPlayground(phpPort: NodeMessagePort, fileLockManagerPort: NodeMessagePort, nativeInternalDirPath: string): Promise<import("@php-wasm/universal").RemoteAPI<PlaygroundCliBlueprintV1Worker>>;
24
- bootPlayground({ worker, fileLockManagerPort, firstProcessId, nativeInternalDirPath, }: {
22
+ bootWordPress(playground: Pooled<PlaygroundCliWorker>, workerPostInstallMountsPort: NodeMessagePort): Promise<Pooled<PlaygroundCliWorker>>;
23
+ bootRequestHandler({ worker, fileLockManagerPort, nativeInternalDirPath, }: {
25
24
  worker: SpawnedWorker;
26
25
  fileLockManagerPort: NodeMessagePort;
27
- firstProcessId: number;
28
26
  nativeInternalDirPath: string;
29
27
  }): Promise<import("@php-wasm/universal").RemoteAPI<PlaygroundCliBlueprintV1Worker>>;
30
28
  compileInputBlueprint(additionalBlueprintSteps: any[]): Promise<import("@wp-playground/blueprints").CompiledBlueprintV1>;
@@ -1,61 +1,32 @@
1
1
  /// <reference types="node" />
2
- import type { FileLockManager } from '@php-wasm/node';
2
+ import type { FileLockManager } from '@php-wasm/universal';
3
3
  import { EmscriptenDownloadMonitor } from '@php-wasm/progress';
4
- import type { PathAlias, RemoteAPI, SupportedPHPVersion } from '@php-wasm/universal';
4
+ import type { PathAlias, SupportedPHPVersion } from '@php-wasm/universal';
5
5
  import { PHPWorker } from '@php-wasm/universal';
6
6
  import { type WordPressInstallMode } from '@wp-playground/wordpress';
7
7
  import { type MessagePort } from 'worker_threads';
8
8
  import type { Mount } from '@php-wasm/cli-util';
9
- export type WorkerBootOptions = {
10
- phpVersion: SupportedPHPVersion;
9
+ export type WorkerBootWordPressOptions = {
11
10
  siteUrl: string;
12
- mountsBeforeWpInstall: Array<Mount>;
13
- mountsAfterWpInstall: Array<Mount>;
14
- firstProcessId: number;
15
- processIdSpaceLength: number;
16
- followSymlinks: boolean;
17
- trace: boolean;
18
- /**
19
- * When true, Playground will not send cookies to the client but will manage
20
- * them internally. This can be useful in environments that can't store cookies,
21
- * e.g. VS Code WebView.
22
- *
23
- * Default: false.
24
- */
25
- internalCookieStore?: boolean;
26
- withIntl?: boolean;
27
- withRedis?: boolean;
28
- withMemcached?: boolean;
29
- withXdebug?: boolean;
30
- nativeInternalDirPath: string;
31
- /**
32
- * PHP constants to define via php.defineConstant().
33
- * Process-specific, set for each PHP instance.
34
- */
35
- constants?: Record<string, string | number | boolean | null>;
36
- /**
37
- * Path aliases that map URL prefixes to filesystem paths outside
38
- * the document root. Similar to Nginx's `alias` directive.
39
- */
40
- pathAliases?: PathAlias[];
41
- };
42
- export type PrimaryWorkerBootOptions = WorkerBootOptions & {
43
- wordpressInstallMode: WordPressInstallMode;
44
11
  wpVersion?: string;
12
+ wordpressInstallMode: WordPressInstallMode;
45
13
  wordPressZip?: ArrayBuffer;
46
14
  sqliteIntegrationPluginZip?: ArrayBuffer;
47
15
  dataSqlPath?: string;
16
+ /**
17
+ * PHP constants to define via php.defineConstant().
18
+ */
19
+ constants?: Record<string, string | number | boolean>;
48
20
  };
49
21
  interface WorkerBootRequestHandlerOptions {
50
22
  siteUrl: string;
51
- followSymlinks: boolean;
52
23
  phpVersion: SupportedPHPVersion;
53
- firstProcessId: number;
54
- processIdSpaceLength: number;
24
+ processId: number;
55
25
  trace: boolean;
56
26
  nativeInternalDirPath: string;
57
27
  mountsBeforeWpInstall: Array<Mount>;
58
28
  mountsAfterWpInstall: Array<Mount>;
29
+ followSymlinks: boolean;
59
30
  withIntl?: boolean;
60
31
  withRedis?: boolean;
61
32
  withMemcached?: boolean;
@@ -63,8 +34,9 @@ interface WorkerBootRequestHandlerOptions {
63
34
  pathAliases?: PathAlias[];
64
35
  }
65
36
  export declare class PlaygroundCliBlueprintV1Worker extends PHPWorker {
66
- booted: boolean;
67
- fileLockManager: RemoteAPI<FileLockManager> | FileLockManager | undefined;
37
+ bootedRequestHandler: boolean;
38
+ bootedWordPress: boolean;
39
+ fileLockManager: FileLockManager | undefined;
68
40
  constructor(monitor: EmscriptenDownloadMonitor);
69
41
  /**
70
42
  * Call this method before boot() to use file locking.
@@ -76,10 +48,9 @@ export declare class PlaygroundCliBlueprintV1Worker extends PHPWorker {
76
48
  * @see phpwasm-emscripten-library-file-locking-for-node.js
77
49
  */
78
50
  useFileLockManager(port: MessagePort): Promise<void>;
79
- bootAndSetUpInitialWorker(options: PrimaryWorkerBootOptions): Promise<void>;
80
- hello(): Promise<string>;
81
- bootWorker(args: WorkerBootOptions): Promise<void>;
51
+ bootWordPress(options: WorkerBootWordPressOptions, workerPostInstallMountsPort: MessagePort): Promise<void>;
82
52
  bootRequestHandler(options: WorkerBootRequestHandlerOptions): Promise<void>;
53
+ mountAfterWordPressInstall(mounts: Array<Mount>): Promise<void>;
83
54
  dispose(): Promise<void>;
84
55
  }
85
56
  export {};
@@ -1,8 +1,9 @@
1
1
  /// <reference types="node" />
2
- import type { RemoteAPI } from '@php-wasm/universal';
2
+ import type { Pooled } from '@php-wasm/universal';
3
+ import { type RemoteAPI } from '@php-wasm/universal';
3
4
  import type { PlaygroundCliBlueprintV2Worker } from './worker-thread-v2';
4
5
  import type { MessagePort as NodeMessagePort } from 'worker_threads';
5
- import { type RunCLIArgs, type SpawnedWorker, type WorkerType } from '../run-cli';
6
+ import { type PlaygroundCliWorker, type RunCLIArgs, type SpawnedWorker, type WorkerType } from '../run-cli';
6
7
  import type { CLIOutput } from '../cli-output';
7
8
  /**
8
9
  * Boots Playground CLI workers using Blueprint version 2.
@@ -13,20 +14,17 @@ import type { CLIOutput } from '../cli-output';
13
14
  export declare class BlueprintsV2Handler {
14
15
  private phpVersion;
15
16
  private siteUrl;
16
- private processIdSpaceLength;
17
17
  private args;
18
18
  private cliOutput;
19
19
  constructor(args: RunCLIArgs, options: {
20
20
  siteUrl: string;
21
- processIdSpaceLength: number;
22
21
  cliOutput: CLIOutput;
23
22
  });
24
23
  getWorkerType(): WorkerType;
25
- bootAndSetUpInitialPlayground(phpPort: NodeMessagePort, fileLockManagerPort: NodeMessagePort, nativeInternalDirPath: string): Promise<RemoteAPI<PlaygroundCliBlueprintV2Worker>>;
26
- bootPlayground({ worker, fileLockManagerPort, firstProcessId, nativeInternalDirPath, }: {
24
+ bootWordPress(playground: Pooled<PlaygroundCliWorker>, workerPostInstallMountsPort: NodeMessagePort): Promise<Pooled<PlaygroundCliWorker>>;
25
+ bootRequestHandler({ worker, fileLockManagerPort, nativeInternalDirPath, }: {
27
26
  worker: SpawnedWorker;
28
27
  fileLockManagerPort: NodeMessagePort;
29
- firstProcessId: number;
30
28
  nativeInternalDirPath: string;
31
29
  }): Promise<RemoteAPI<PlaygroundCliBlueprintV2Worker>>;
32
30
  }
@@ -1,7 +1,7 @@
1
1
  /// <reference types="node" />
2
- import type { FileLockManager } from '@php-wasm/node';
2
+ import type { FileLockManager } from '@php-wasm/universal';
3
3
  import { EmscriptenDownloadMonitor } from '@php-wasm/progress';
4
- import type { PathAlias, PHP, FileTree, RemoteAPI, SupportedPHPVersion, SpawnHandler } from '@php-wasm/universal';
4
+ import type { PathAlias, PHP, FileTree, SupportedPHPVersion, SpawnHandler } from '@php-wasm/universal';
5
5
  import { PHPWorker } from '@php-wasm/universal';
6
6
  import { type BlueprintV1Declaration } from '@wp-playground/blueprints';
7
7
  import { type ParsedBlueprintV2String, type RawBlueprintV2Data } from '@wp-playground/blueprints';
@@ -9,21 +9,9 @@ import { type MessagePort } from 'worker_threads';
9
9
  import { type RunCLIArgs } from '../run-cli';
10
10
  import type { PhpIniOptions, PHPInstanceCreatedHook } from '@wp-playground/wordpress';
11
11
  import type { Mount } from '@php-wasm/cli-util';
12
- export type PrimaryWorkerBootArgs = Omit<RunCLIArgs, 'mount-before-install' | 'mount'> & {
13
- phpVersion: SupportedPHPVersion;
12
+ export type WorkerWordPressBootArgs = Omit<RunCLIArgs, 'mount-before-install' | 'mount'> & {
14
13
  siteUrl: string;
15
- firstProcessId: number;
16
- processIdSpaceLength: number;
17
- trace: boolean;
18
14
  blueprint: RawBlueprintV2Data | ParsedBlueprintV2String | BlueprintV1Declaration;
19
- nativeInternalDirPath: string;
20
- mountsBeforeWpInstall?: Array<Mount>;
21
- mountsAfterWpInstall?: Array<Mount>;
22
- /**
23
- * PHP constants to define via php.defineConstant().
24
- * Process-specific, set for each PHP instance.
25
- */
26
- constants?: Record<string, string | number | boolean | null>;
27
15
  };
28
16
  type WorkerRunBlueprintArgs = Omit<RunCLIArgs, 'mount-before-install' | 'mount'> & {
29
17
  siteUrl: string;
@@ -37,8 +25,7 @@ export type SecondaryWorkerBootArgs = {
37
25
  phpIniEntries?: PhpIniOptions;
38
26
  constants?: Record<string, string | number | boolean | null>;
39
27
  createFiles?: FileTree;
40
- firstProcessId: number;
41
- processIdSpaceLength: number;
28
+ processId: number;
42
29
  trace: boolean;
43
30
  nativeInternalDirPath: string;
44
31
  withIntl?: boolean;
@@ -57,7 +44,7 @@ export declare class PlaygroundCliBlueprintV2Worker extends PHPWorker {
57
44
  booted: boolean;
58
45
  blueprintTargetResolved: boolean;
59
46
  phpInstancesThatNeedMountsAfterTargetResolved: Set<PHP>;
60
- fileLockManager: RemoteAPI<FileLockManager> | FileLockManager | undefined;
47
+ fileLockManager: FileLockManager | undefined;
61
48
  constructor(monitor: EmscriptenDownloadMonitor);
62
49
  /**
63
50
  * Call this method before boot() to use file locking.
@@ -69,10 +56,12 @@ export declare class PlaygroundCliBlueprintV2Worker extends PHPWorker {
69
56
  * @see phpwasm-emscripten-library-file-locking-for-node.js
70
57
  */
71
58
  useFileLockManager(port: MessagePort): Promise<void>;
72
- bootAndSetUpInitialWorker(args: PrimaryWorkerBootArgs): Promise<void>;
59
+ bootWordPress(args: WorkerWordPressBootArgs, workerPostInstallMountsPort: MessagePort): Promise<void>;
73
60
  bootWorker(args: SecondaryWorkerBootArgs): Promise<void>;
74
- runBlueprintV2(args: WorkerRunBlueprintArgs): Promise<void>;
75
- bootRequestHandler({ siteUrl, allow, phpVersion, createFiles, constants, phpIniEntries, firstProcessId, processIdSpaceLength, trace, nativeInternalDirPath, withIntl, withRedis, withMemcached, withXdebug, pathAliases, onPHPInstanceCreated, spawnHandler, }: WorkerBootRequestHandlerOptions): Promise<void>;
61
+ runBlueprintV2(args: WorkerRunBlueprintArgs, workerPostInstallMountsPort: MessagePort): Promise<void>;
62
+ bootRequestHandler({ siteUrl, allow, phpVersion, processId, createFiles, constants, phpIniEntries, trace, nativeInternalDirPath, withIntl, withRedis, withMemcached, withXdebug, pathAliases, onPHPInstanceCreated, spawnHandler, }: WorkerBootRequestHandlerOptions): Promise<void>;
63
+ mountAfterWordPressInstall(mounts: Array<Mount>): Promise<void>;
64
+ applyPostInstallMountsToAllWorkers(postInstallMountsPort: MessagePort): Promise<void>;
76
65
  dispose(): Promise<void>;
77
66
  }
78
67
  export {};
package/cli.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";const s=require("./run-cli-DHqpmO6s.cjs"),r=process.argv.slice(2);s.parseOptionsAndRunCLI(r);
1
+ "use strict";const s=require("./run-cli-D-GS-Yv7.cjs"),r=process.argv.slice(2);s.parseOptionsAndRunCLI(r);
2
2
  //# sourceMappingURL=cli.cjs.map
package/cli.js CHANGED
@@ -1,4 +1,4 @@
1
- import { p as s } from "./run-cli-Cxpf7CoX.js";
1
+ import { p as s } from "./run-cli-FHDubnX7.js";
2
2
  const r = process.argv.slice(2);
3
3
  s(r);
4
4
  //# sourceMappingURL=cli.js.map
package/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./run-cli-DHqpmO6s.cjs");exports.LogVerbosity=e.LogVerbosity;exports.internalsKeyForTesting=e.internalsKeyForTesting;exports.mergeDefinedConstants=e.mergeDefinedConstants;exports.parseOptionsAndRunCLI=e.parseOptionsAndRunCLI;exports.runCLI=e.runCLI;exports.spawnWorkerThread=e.spawnWorkerThread;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./run-cli-D-GS-Yv7.cjs");exports.LogVerbosity=e.LogVerbosity;exports.internalsKeyForTesting=e.internalsKeyForTesting;exports.mergeDefinedConstants=e.mergeDefinedConstants;exports.parseOptionsAndRunCLI=e.parseOptionsAndRunCLI;exports.runCLI=e.runCLI;exports.spawnWorkerThread=e.spawnWorkerThread;
2
2
  //# sourceMappingURL=index.cjs.map
package/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { L as r, i as a, m as n, p as o, r as t, s as i } from "./run-cli-Cxpf7CoX.js";
1
+ import { L as r, i as a, m as n, p as o, r as t, s as i } from "./run-cli-FHDubnX7.js";
2
2
  export {
3
3
  r as LogVerbosity,
4
4
  a as internalsKeyForTesting,
@@ -1,16 +1,23 @@
1
- import type { PHPRequest, PHPResponse, RemoteAPI } from '@php-wasm/universal';
2
- import type { PlaygroundCliBlueprintV1Worker as PlaygroundCliWorkerV1 } from './blueprints-v1/worker-thread-v1';
3
- import type { PlaygroundCliBlueprintV2Worker as PlaygroundCliWorkerV2 } from './blueprints-v2/worker-thread-v2';
4
- type PlaygroundCliWorker = PlaygroundCliWorkerV1 | PlaygroundCliWorkerV2;
5
- type WorkerLoad = {
6
- worker: RemoteAPI<PlaygroundCliWorker>;
7
- activeRequests: Set<Promise<PHPResponse>>;
1
+ import type { PHPRequest, PHPResponse } from '@php-wasm/universal';
2
+ export interface LoadBalancerWorker {
3
+ request(request: PHPRequest): Promise<PHPResponse>;
4
+ }
5
+ type InProgressRequest = {
6
+ request: PHPRequest;
7
+ promisedResponse: Promise<PHPResponse>;
8
+ };
9
+ type QueuedRequest = {
10
+ request: PHPRequest;
11
+ resolve: (response: PHPResponse | PromiseLike<PHPResponse>) => void;
12
+ reject: (reason?: any) => void;
8
13
  };
9
14
  export declare class LoadBalancer {
10
- workerLoads: WorkerLoad[];
11
- constructor(initialWorker: RemoteAPI<PlaygroundCliWorker>);
12
- addWorker(worker: RemoteAPI<PlaygroundCliWorker>): void;
13
- removeWorker(worker: RemoteAPI<PlaygroundCliWorker>): Promise<void>;
15
+ workers: LoadBalancerWorker[];
16
+ freeWorkers: LoadBalancerWorker[];
17
+ busyWorkers: Map<LoadBalancerWorker, InProgressRequest>;
18
+ queuedRequests: QueuedRequest[];
19
+ constructor(workers: LoadBalancerWorker[]);
14
20
  handleRequest(request: PHPRequest): Promise<PHPResponse>;
21
+ private dispatchQueuedRequests;
15
22
  }
16
23
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wp-playground/cli",
3
- "version": "3.0.54",
3
+ "version": "3.1.1",
4
4
  "description": "WordPress Playground CLI",
5
5
  "repository": {
6
6
  "type": "git",
@@ -34,7 +34,7 @@
34
34
  "bin": {
35
35
  "wp-playground-cli": "wp-playground.js"
36
36
  },
37
- "gitHead": "e449793042bf2c66f8fdd4212ef266801ae3f605",
37
+ "gitHead": "71560d81fcde96435d5730a0430abcafaa6f92b8",
38
38
  "dependencies": {
39
39
  "@zip.js/zip.js": "2.7.57",
40
40
  "ajv": "8.12.0",
@@ -44,6 +44,7 @@
44
44
  "diff3": "0.0.4",
45
45
  "express": "4.22.0",
46
46
  "fast-xml-parser": "^5.3.4",
47
+ "fs-ext-extra-prebuilt": "2.2.7",
47
48
  "fs-extra": "11.1.1",
48
49
  "ignore": "5.3.2",
49
50
  "ini": "4.1.2",
@@ -54,7 +55,6 @@
54
55
  "pify": "2.3.0",
55
56
  "ps-man": "1.1.8",
56
57
  "readable-stream": "3.6.2",
57
- "selfsigned": "5.5.0",
58
58
  "sha.js": "2.4.12",
59
59
  "simple-get": "4.0.1",
60
60
  "tmp-promise": "3.0.3",
@@ -62,18 +62,18 @@
62
62
  "ws": "8.18.3",
63
63
  "xml2js": "0.6.2",
64
64
  "yargs": "17.7.2",
65
- "@php-wasm/logger": "3.0.54",
66
- "@php-wasm/progress": "3.0.54",
67
- "@php-wasm/universal": "3.0.54",
68
- "@wp-playground/blueprints": "3.0.54",
69
- "@wp-playground/common": "3.0.54",
70
- "@wp-playground/wordpress": "3.0.54",
71
- "@php-wasm/node": "3.0.54",
72
- "@php-wasm/util": "3.0.54",
73
- "@php-wasm/cli-util": "3.0.54",
74
- "@wp-playground/storage": "3.0.54",
75
- "@php-wasm/xdebug-bridge": "3.0.54",
76
- "@wp-playground/tools": "3.0.54"
65
+ "@php-wasm/logger": "3.1.1",
66
+ "@php-wasm/progress": "3.1.1",
67
+ "@php-wasm/universal": "3.1.1",
68
+ "@wp-playground/blueprints": "3.1.1",
69
+ "@wp-playground/common": "3.1.1",
70
+ "@wp-playground/wordpress": "3.1.1",
71
+ "@php-wasm/node": "3.1.1",
72
+ "@php-wasm/util": "3.1.1",
73
+ "@php-wasm/cli-util": "3.1.1",
74
+ "@wp-playground/storage": "3.1.1",
75
+ "@php-wasm/xdebug-bridge": "3.1.1",
76
+ "@wp-playground/tools": "3.1.1"
77
77
  },
78
78
  "packageManager": "npm@10.9.2",
79
79
  "overrides": {
@@ -87,8 +87,5 @@
87
87
  "form-data": "^4.0.4",
88
88
  "lodash": "^4.17.23",
89
89
  "glob": "^9.3.0"
90
- },
91
- "optionalDependencies": {
92
- "fs-ext": "2.1.1"
93
90
  }
94
91
  }
@@ -0,0 +1,9 @@
1
+ export declare class ProcessIdAllocator {
2
+ private initialId;
3
+ private maxId;
4
+ private nextId;
5
+ private claimed;
6
+ constructor(initialId?: number, maxId?: number);
7
+ claim(): number;
8
+ release(id: number): boolean;
9
+ }
@@ -0,0 +1,66 @@
1
+ "use strict";const f=require("@php-wasm/logger"),P=require("@php-wasm/universal"),$=require("@wp-playground/blueprints"),B=require("@wp-playground/common"),c=require("fs"),_=require("worker_threads"),fe=require("@php-wasm/node"),d=require("path"),we=require("express"),H=require("os"),ye=require("yargs"),L=require("@wp-playground/storage"),ee=require("@php-wasm/progress"),be=require("@wp-playground/wordpress"),E=require("fs-extra"),ge=require("module"),Pe=require("@php-wasm/xdebug-bridge"),ve=require("child_process"),te=require("tmp-promise"),Se=require("ps-man"),U=require("@php-wasm/cli-util"),xe=require("crypto"),W=require("@wp-playground/tools"),re=require("wasm-feature-detect");var T=typeof document<"u"?document.currentScript:null;const Ie=2**31-1;class Te{constructor(t=1,r=Ie){this.claimed=new Set,this.initialId=t,this.maxId=r,this.nextId=t}claim(){const t=this.maxId-this.initialId+1;for(let r=0;r<t;r++)if(this.claimed.has(this.nextId))this.nextId++,this.nextId>this.maxId&&(this.nextId=this.initialId);else return this.claimed.add(this.nextId),this.nextId;throw new Error(`Unable to find free process ID after ${t} tries.`)}release(t){return this.claimed.has(t)?(this.claimed.delete(t),!0):!1}}function q(e){const t=[];for(const r of e){const o=r.split(":");if(o.length!==2)throw new Error(`Invalid mount format: ${r}.
2
+ Expected format: /host/path:/vfs/path.
3
+ If your path contains a colon, e.g. C:\\myplugin, use the --mount-dir option instead.
4
+ Example: --mount-dir C:\\my-plugin /wordpress/wp-content/plugins/my-plugin`);const[s,n]=o;if(!c.existsSync(s))throw new Error(`Host path does not exist: ${s}`);t.push({hostPath:s,vfsPath:n})}return t}function oe(e){if(e.length%2!==0)throw new Error("Invalid mount format. Expected: /host/path /vfs/path");const t=[];for(let r=0;r<e.length;r+=2){const o=e[r],s=e[r+1];if(!c.existsSync(o))throw new Error(`Host path does not exist: ${o}`);t.push({hostPath:d.resolve(process.cwd(),o),vfsPath:s})}return t}async function $e(e,t){for(const r of t)await e.mount(r.vfsPath,fe.createNodeFsMountHandler(r.hostPath))}const se={step:"runPHP",code:{filename:"activate-theme.php",content:`<?php
5
+ $docroot = getenv('DOCROOT') ? getenv('DOCROOT') : '/wordpress';
6
+ require_once "$docroot/wp-load.php";
7
+ $theme = wp_get_theme();
8
+ if (!$theme->exists()) {
9
+ $themes = wp_get_themes();
10
+ if (count($themes) > 0) {
11
+ $themeName = array_keys($themes)[0];
12
+ switch_theme($themeName);
13
+ }
14
+ }
15
+ `}};function ae(e){const t=e.autoMount,r=[...e.mount||[]],o=[...e["mount-before-install"]||[]],s={...e,mount:r,"mount-before-install":o,"additional-blueprint-steps":[...e["additional-blueprint-steps"]||[]]};if(Re(t)){const a=`/wordpress/wp-content/plugins/${d.basename(t)}`;r.push({hostPath:t,vfsPath:a,autoMounted:!0}),s["additional-blueprint-steps"].push({step:"activatePlugin",pluginPath:`/wordpress/wp-content/plugins/${d.basename(t)}`})}else if(Me(t)){const n=d.basename(t),a=`/wordpress/wp-content/themes/${n}`;r.push({hostPath:t,vfsPath:a,autoMounted:!0}),s["additional-blueprint-steps"].push(e["experimental-blueprints-v2-runner"]?{step:"activateTheme",themeDirectoryName:n}:{step:"activateTheme",themeFolderName:n})}else if(ke(t)){const n=c.readdirSync(t);for(const a of n)a!=="index.php"&&r.push({hostPath:`${t}/${a}`,vfsPath:`/wordpress/wp-content/${a}`,autoMounted:!0});s["additional-blueprint-steps"].push(se)}else Ee(t)&&(o.push({hostPath:t,vfsPath:"/wordpress",autoMounted:!0}),s.mode="apply-to-existing-site",s["additional-blueprint-steps"].push(se),s.wordpressInstallMode||(s.wordpressInstallMode="install-from-existing-files-if-needed"));return s}function Ee(e){const t=c.readdirSync(e);return t.includes("wp-admin")&&t.includes("wp-includes")&&t.includes("wp-content")}function ke(e){const t=c.readdirSync(e);return t.includes("themes")||t.includes("plugins")||t.includes("mu-plugins")||t.includes("uploads")}function Me(e){if(!c.readdirSync(e).includes("style.css"))return!1;const r=c.readFileSync(d.join(e,"style.css"),"utf8");return!!/^(?:[ \t]*<\?php)?[ \t/*#@]*Theme Name:(.*)$/im.exec(r)}function Re(e){const t=c.readdirSync(e),r=/^(?:[ \t]*<\?php)?[ \t/*#@]*Plugin Name:(.*)$/im;return!!t.filter(s=>s.endsWith(".php")).find(s=>{const n=c.readFileSync(d.join(e,s),"utf8");return!!r.exec(n)})}function Ce(e){if(e.length%2!==0)throw new Error("Invalid constant definition format. Expected pairs of NAME value");const t={};for(let r=0;r<e.length;r+=2){const o=e[r],s=e[r+1];if(!o||!o.trim())throw new Error("Constant name cannot be empty");t[o.trim()]=s}return t}function Be(e){if(e.length%2!==0)throw new Error("Invalid boolean constant definition format. Expected pairs of NAME value");const t={};for(let r=0;r<e.length;r+=2){const o=e[r],s=e[r+1].trim().toLowerCase();if(!o||!o.trim())throw new Error("Constant name cannot be empty");if(s==="true"||s==="1")t[o.trim()]=!0;else if(s==="false"||s==="0")t[o.trim()]=!1;else throw new Error(`Invalid boolean value for constant "${o}": "${s}". Must be "true", "false", "1", or "0".`)}return t}function Ae(e){if(e.length%2!==0)throw new Error("Invalid number constant definition format. Expected pairs of NAME value");const t={};for(let r=0;r<e.length;r+=2){const o=e[r],s=e[r+1].trim();if(!o||!o.trim())throw new Error("Constant name cannot be empty");const n=Number(s);if(isNaN(n))throw new Error(`Invalid number value for constant "${o}": "${s}". Must be a valid number.`);t[o.trim()]=n}return t}function De(e={},t={},r={}){const o={},s=new Set,n=(a,l)=>{for(const u in a){if(s.has(u))throw new Error(`Constant "${u}" is defined multiple times across different --define-${l} flags`);s.add(u),o[u]=a[u]}};return n(e,"string"),n(t,"bool"),n(r,"number"),o}function z(e){return De(e.define,e["define-bool"],e["define-number"])}async function Le(e){const t=we(),r=await new Promise((n,a)=>{const l=t.listen(e.port,()=>{const u=l.address();u===null||typeof u=="string"?a(new Error("Server address is not available")):n(l)})});t.use("/",async(n,a)=>{let l;try{l=await e.handleRequest({url:n.url,headers:We(n),method:n.method,body:await Ue(n)})}catch(u){f.logger.error(u),l=P.PHPResponse.forHttpCode(500)}a.statusCode=l.httpStatusCode;for(const u in l.headers)a.setHeader(u,l.headers[u]);a.end(l.bytes)});const s=r.address().port;return await e.onBind(r,s)}const Ue=async e=>await new Promise(t=>{const r=[];e.on("data",o=>{r.push(o)}),e.on("end",()=>{t(new Uint8Array(Buffer.concat(r)))})}),We=e=>{const t={};if(e.rawHeaders&&e.rawHeaders.length)for(let r=0;r<e.rawHeaders.length;r+=2)t[e.rawHeaders[r].toLowerCase()]=e.rawHeaders[r+1];return t};function _e(e){return/^latest$|^trunk$|^nightly$|^(?:(\d+)\.(\d+)(?:\.(\d+))?)((?:-beta(?:\d+)?)|(?:-RC(?:\d+)?))?$/.test(e)}async function He({sourceString:e,blueprintMayReadAdjacentFiles:t}){if(!e)return;if(e.startsWith("http://")||e.startsWith("https://"))return await $.resolveRemoteBlueprint(e);let r=d.resolve(process.cwd(),e);if(!c.existsSync(r))throw new Error(`Blueprint file does not exist: ${r}`);const o=c.statSync(r);if(o.isDirectory()&&(r=d.join(r,"blueprint.json")),!o.isFile()&&o.isSymbolicLink())throw new Error(`Blueprint path is neither a file nor a directory: ${r}`);const s=d.extname(r);switch(s){case".zip":return L.ZipFilesystem.fromArrayBuffer(c.readFileSync(r).buffer);case".json":{const n=c.readFileSync(r,"utf-8");try{JSON.parse(n)}catch{throw new Error(`Blueprint file at ${r} is not a valid JSON file`)}const a=d.dirname(r),l=new L.NodeJsFilesystem(a);return new L.OverlayFilesystem([new L.InMemoryFilesystem({"blueprint.json":n}),{read(u){if(!t)throw new Error(`Error: Blueprint contained tried to read a local file at path "${u}" (via a resource of type "bundled"). Playground restricts access to local resources by default as a security measure.
16
+
17
+ 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.`);return l.read(u)}}])}default:throw new Error(`Unsupported blueprint file extension: ${s}. Only .zip and .json files are supported.`)}}class Fe{constructor(t,r){this.args=t,this.siteUrl=r.siteUrl,this.phpVersion=t.php,this.cliOutput=r.cliOutput}getWorkerType(){return"v2"}async bootWordPress(t,r){const o={command:this.args.command,siteUrl:this.siteUrl,blueprint:this.args.blueprint,workerPostInstallMountsPort:r};return await t.bootWordPress(o,r),t}async bootRequestHandler({worker:t,fileLockManagerPort:r,nativeInternalDirPath:o}){const s=P.consumeAPI(t.phpPort);await s.useFileLockManager(r);const n={...this.args,phpVersion:this.phpVersion,siteUrl:this.siteUrl,processId:t.processId,trace:this.args.verbosity==="debug",withIntl:this.args.intl,withRedis:this.args.redis,withMemcached:this.args.memcached,withXdebug:!!this.args.xdebug,nativeInternalDirPath:o,mountsBeforeWpInstall:this.args["mount-before-install"]||[],mountsAfterWpInstall:this.args.mount||[],constants:z(this.args)};return await s.bootWorker(n),s}}const Y=d.join(H.homedir(),".wordpress-playground");async function Ne(){const e=typeof __dirname<"u"?__dirname:void 0;let t=d.join(e,"sqlite-database-integration.zip");if(!E.existsSync(t)){const r=ge.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:T&&T.tagName.toUpperCase()==="SCRIPT"&&T.src||new URL("run-cli-D-GS-Yv7.cjs",document.baseURI).href),o=d.dirname(r.resolve("@wp-playground/wordpress-builds/package.json"));t=d.join(o,"src","sqlite-database-integration","sqlite-database-integration-trunk.zip")}return new File([await E.readFile(t)],d.basename(t))}async function Oe(e,t,r){const o=d.join(Y,t);return E.existsSync(o)||(E.ensureDirSync(Y),await qe(e,o,r)),le(o)}async function qe(e,t,r){const s=(await r.monitorFetch(fetch(e))).body.getReader(),n=`${t}.partial`,a=E.createWriteStream(n);for(;;){const{done:l,value:u}=await s.read();if(u&&a.write(u),l)break}a.close(),a.closed||await new Promise((l,u)=>{a.on("finish",()=>{E.renameSync(n,t),l(null)}),a.on("error",I=>{E.removeSync(n),u(I)})})}function le(e,t){return new File([E.readFileSync(e)],d.basename(e))}class je{constructor(t,r){this.args=t,this.siteUrl=r.siteUrl,this.cliOutput=r.cliOutput}getWorkerType(){return"v1"}async bootWordPress(t,r){let o,s,n;const a=new ee.EmscriptenDownloadMonitor;if(this.args.wordpressInstallMode==="download-and-install"){let I=!1;a.addEventListener("progress",x=>{if(I)return;const{loaded:p,total:i}=x.detail,w=Math.floor(Math.min(100,100*p/i));I=w===100,this.cliOutput.updateProgress("Downloading WordPress",w)}),o=await be.resolveWordPressRelease(this.args.wp),n=d.join(Y,`prebuilt-wp-content-for-wp-${o.version}.zip`),s=c.existsSync(n)?le(n):await Oe(o.releaseUrl,`${o.version}.zip`,a),f.logger.debug(`Resolved WordPress release URL: ${o?.releaseUrl}`)}let l;this.args.skipSqliteSetup?(f.logger.debug("Skipping SQLite integration plugin setup..."),l=void 0):(this.cliOutput.updateProgress("Preparing SQLite database"),l=await Ne()),this.cliOutput.updateProgress("Booting WordPress");const u=await $.resolveRuntimeConfiguration(this.getEffectiveBlueprint());return await t.bootWordPress({wpVersion:u.wpVersion,siteUrl:this.siteUrl,wordpressInstallMode:this.args.wordpressInstallMode||"download-and-install",wordPressZip:s&&await s.arrayBuffer(),sqliteIntegrationPluginZip:await l?.arrayBuffer(),constants:z(this.args)},r),n&&!this.args["mount-before-install"]&&!c.existsSync(n)&&(this.cliOutput.updateProgress("Caching WordPress for next boot"),c.writeFileSync(n,await B.zipDirectory(t,"/wordpress"))),t}async bootRequestHandler({worker:t,fileLockManagerPort:r,nativeInternalDirPath:o}){const s=P.consumeAPI(t.phpPort);await s.isConnected();const n=await $.resolveRuntimeConfiguration(this.getEffectiveBlueprint());return await s.useFileLockManager(r),await s.bootRequestHandler({phpVersion:n.phpVersion,siteUrl:this.siteUrl,mountsBeforeWpInstall:this.args["mount-before-install"]||[],mountsAfterWpInstall:this.args.mount||[],processId:t.processId,followSymlinks:this.args.followSymlinks===!0,trace:this.args.experimentalTrace===!0,withIntl:this.args.intl,withRedis:this.args.redis,withMemcached:this.args.memcached,withXdebug:!!this.args.xdebug,nativeInternalDirPath:o,pathAliases:this.args.pathAliases}),await s.isReady(),s}async compileInputBlueprint(t){const r=this.getEffectiveBlueprint(),o=new ee.ProgressTracker;let s="",n=!1;return o.addEventListener("progress",a=>{if(n)return;n=a.detail.progress===100;const l=Math.floor(a.detail.progress);s=a.detail.caption||s||"Running Blueprint",this.cliOutput.updateProgress(s.trim(),l)}),await $.compileBlueprintV1(r,{progress:o,additionalSteps:t})}getEffectiveBlueprint(){const t=this.args.blueprint;return $.isBlueprintBundle(t)?t:{login:this.args.login,...t||{},preferredVersions:{php:this.args.php??t?.preferredVersions?.php??B.RecommendedPHPVersion,wp:this.args.wp??t?.preferredVersions?.wp??"latest",...t?.preferredVersions||{}}}}}async function Ve(e,t=!0){const o=`${d.basename(process.argv0)}${e}${process.pid}-`,s=await te.dir({prefix:o,unsafeCleanup:!0});return t&&te.setGracefulCleanup(),s}async function Ye(e,t,r){const s=(await ze(e,t,r)).map(n=>new Promise(a=>{c.rm(n,{recursive:!0},l=>{l?f.logger.warn(`Failed to delete stale Playground temp dir: ${n}`,l):f.logger.info(`Deleted stale Playground temp dir: ${n}`),a()})}));await Promise.all(s)}async function ze(e,t,r){try{const o=c.readdirSync(r).map(n=>d.join(r,n)),s=[];for(const n of o)await Ge(e,t,n)&&s.push(n);return s}catch(o){return f.logger.warn(`Failed to find stale Playground temp dirs: ${o}`),[]}}async function Ge(e,t,r){if(!c.lstatSync(r).isDirectory())return!1;const s=d.basename(r);if(!s.includes(e))return!1;const n=s.match(new RegExp(`^(.+)${e}(\\d+)-`));if(!n)return!1;const a={executableName:n[1],pid:n[2]};if(await Qe(a.pid,a.executableName))return!1;const l=Date.now()-t;return c.statSync(r).mtime.getTime()<l}async function Qe(e,t){const[r]=await new Promise((o,s)=>{Se.list({pid:e,name:t,clean:!0},(n,a)=>{n?s(n):o(a)})});return!!r&&r.pid===e&&r.command===t}function ue(e){return process.env.CI==="true"||process.env.CI==="1"||process.env.GITHUB_ACTIONS==="true"||process.env.GITHUB_ACTIONS==="1"||(process.env.TERM||"").toLowerCase()==="dumb"?!1:e?!!e.isTTY:process.stdout.isTTY}class Xe{constructor(t){this.lastProgressLine="",this.progressActive=!1,this.verbosity=t.verbosity,this.writeStream=t.writeStream||process.stdout}get isTTY(){return!!this.writeStream.isTTY}get shouldRender(){return ue(this.writeStream)}get isQuiet(){return this.verbosity==="quiet"}bold(t){return this.isTTY?`\x1B[1m${t}\x1B[0m`:t}dim(t){return this.isTTY?`\x1B[2m${t}\x1B[0m`:t}green(t){return this.isTTY?`\x1B[32m${t}\x1B[0m`:t}cyan(t){return this.isTTY?`\x1B[36m${t}\x1B[0m`:t}yellow(t){return this.isTTY?`\x1B[33m${t}\x1B[0m`:t}red(t){return this.isTTY?`\x1B[31m${t}\x1B[0m`:t}printBanner(){if(this.isQuiet)return;const t=this.bold("WordPress Playground CLI");this.writeStream.write(`
18
+ ${t}
19
+
20
+ `)}printConfig(t){if(this.isQuiet)return;const r=[];r.push(`${this.dim("PHP")} ${this.cyan(t.phpVersion)} ${this.dim("WordPress")} ${this.cyan(t.wpVersion)}`);const o=[];if(t.intl&&o.push("intl"),t.redis&&o.push("redis"),t.memcached&&o.push("memcached"),t.xdebug&&o.push(this.yellow("xdebug")),o.length>0&&r.push(`${this.dim("Extensions")} ${o.join(", ")}`),t.mounts.length>0)for(const s of t.mounts){const n=s.autoMounted?` ${this.dim("(auto-mount)")}`:"";r.push(`${this.dim("Mount")} ${s.hostPath} ${this.dim("→")} ${s.vfsPath}${n}`)}t.blueprint&&r.push(`${this.dim("Blueprint")} ${t.blueprint}`),this.writeStream.write(r.join(`
21
+ `)+`
22
+
23
+ `)}startProgress(t){this.isQuiet||this.shouldRender&&(this.progressActive=!0,this.updateProgress(t))}updateProgress(t,r){if(this.isQuiet||!this.shouldRender)return;this.progressActive||(this.progressActive=!0);let o=`${t}`;r!==void 0&&(o=`${t} ${this.dim(`${r}%`)}`),o!==this.lastProgressLine&&(this.lastProgressLine=o,this.isTTY?(this.writeStream.cursorTo(0),this.writeStream.write(o),this.writeStream.clearLine(1)):this.writeStream.write(`${o}
24
+ `))}finishProgress(t){this.isQuiet||this.shouldRender&&(t&&(this.isTTY?(this.writeStream.cursorTo(0),this.writeStream.write(`${t}`),this.writeStream.clearLine(1)):this.writeStream.write(`${t}
25
+ `)),this.isTTY&&this.writeStream.write(`
26
+ `),this.progressActive=!1,this.lastProgressLine="")}printStatus(t){this.isQuiet||(this.progressActive&&this.isTTY&&(this.writeStream.cursorTo(0),this.writeStream.clearLine(0)),this.writeStream.write(`${t}
27
+ `),this.progressActive=!1,this.lastProgressLine="")}printError(t){this.progressActive&&this.isTTY&&(this.writeStream.cursorTo(0),this.writeStream.clearLine(0),this.progressActive=!1),this.writeStream.write(`${this.red("Error:")} ${t}
28
+ `)}printReady(t,r){if(this.isQuiet)return;const o=r===1?"worker":"workers";this.writeStream.write(`
29
+ ${this.green("Ready!")} WordPress is running on ${this.bold(t)} ${this.dim(`(${r} ${o})`)}
30
+
31
+ `)}printWarning(t){this.isQuiet||this.writeStream.write(`${this.yellow("Warning:")} ${t}
32
+ `)}printPhpMyAdminUrl(t){this.isQuiet||this.writeStream.write(`${this.cyan("phpMyAdmin")} available at ${this.bold(t)}
33
+
34
+ `)}}const G={Quiet:{name:"quiet",severity:f.LogSeverity.Fatal},Normal:{name:"normal",severity:f.LogSeverity.Info},Debug:{name:"debug",severity:f.LogSeverity.Debug}},Ze=10;async function Ke(e){try{const t={"site-url":{describe:"Site URL to use for WordPress. Defaults to http://127.0.0.1:{port}",type:"string"},php:{describe:"PHP version to use.",type:"string",default:B.RecommendedPHPVersion,choices:P.SupportedPHPVersions},wp:{describe:"WordPress version to use.",type:"string",default:"latest"},define:{describe:'Define PHP string constants (can be used multiple times). Format: NAME value. These constants are set via php.defineConstant() and only exist for the current request. Examples: --define API_KEY secret --define CON=ST "va=lu=e"',type:"string",nargs:2,array:!0,coerce:Ce},"define-bool":{describe:'Define PHP boolean constants (can be used multiple times). Format: NAME value. Value must be "true", "false", "1", or "0". Examples: --define-bool WP_DEBUG true --define-bool MY_FEATURE false',type:"string",nargs:2,array:!0,coerce:Be},"define-number":{describe:"Define PHP number constants (can be used multiple times). Format: NAME value. Examples: --define-number LIMIT 100 --define-number RATE 45.67",type:"string",nargs:2,array:!0,coerce:Ae},mount:{describe:"Mount a directory to the PHP runtime (can be used multiple times). Format: /host/path:/vfs/path",type:"array",string:!0,coerce:q},"mount-before-install":{describe:"Mount a directory to the PHP runtime before WordPress installation (can be used multiple times). Format: /host/path:/vfs/path",type:"array",string:!0,coerce:q},"mount-dir":{describe:'Mount a directory to the PHP runtime (can be used multiple times). Format: "/host/path" "/vfs/path"',type:"array",nargs:2,array:!0,coerce:oe},"mount-dir-before-install":{describe:'Mount a directory before WordPress installation (can be used multiple times). Format: "/host/path" "/vfs/path"',type:"string",nargs:2,array:!0,coerce:oe},login:{describe:"Should log the user in",type:"boolean",default:!1},blueprint:{describe:"Blueprint to execute.",type:"string"},"blueprint-may-read-adjacent-files":{describe:'Consent flag: Allow "bundled" resources in a local blueprint to read files in the same directory as the blueprint file.',type:"boolean",default:!1},"wordpress-install-mode":{describe:"Control how Playground prepares WordPress before booting.",type:"string",default:"download-and-install",choices:["download-and-install","install-from-existing-files","install-from-existing-files-if-needed","do-not-attempt-installing"]},"skip-wordpress-install":{describe:"[Deprecated] Use --wordpress-install-mode instead.",type:"boolean",hidden:!0},"skip-sqlite-setup":{describe:"Skip the SQLite integration plugin setup to allow the WordPress site to use MySQL.",type:"boolean",default:!1},quiet:{describe:"Do not output logs and progress messages.",type:"boolean",default:!1,hidden:!0},verbosity:{describe:"Output logs and progress messages.",type:"string",choices:Object.values(G).map(i=>i.name),default:"normal"},debug:{describe:"Print PHP error log content if an error occurs during Playground boot.",type:"boolean",default:!1,hidden:!0},"auto-mount":{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.",type:"string"},"follow-symlinks":{describe:`Allow Playground to follow symlinks by automatically mounting symlinked directories and files encountered in mounted directories.
35
+ Warning: Following symlinks will expose files outside mounted directories to Playground and could be a security risk.`,type:"boolean",default:!1},"experimental-trace":{describe:"Print detailed messages about system behavior to the console. Useful for troubleshooting.",type:"boolean",default:!1,hidden:!0},"internal-cookie-store":{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).",type:"boolean",default:!1},intl:{describe:"Enable Intl.",type:"boolean",default:!0},redis:{describe:"Enable Redis (requires JSPI support).",type:"boolean"},memcached:{describe:"Enable Memcached.",type:"boolean"},xdebug:{describe:"Enable Xdebug.",type:"boolean",default:!1},"experimental-unsafe-ide-integration":{describe:"Enable experimental IDE development tools. This option edits IDE config files to set Xdebug path mappings and web server details. CAUTION: If there are bugs, this feature may break your IDE config files. Please consider backing up your IDE configs before using this feature.",type:"string",choices:["","vscode","phpstorm"],coerce:i=>i===""?["vscode","phpstorm"]:[i]},"experimental-blueprints-v2-runner":{describe:"Use the experimental Blueprint V2 runner.",type:"boolean",default:!1,hidden:!0},mode:{describe:"Blueprints v2 runner mode to use. This option is required when using the --experimental-blueprints-v2-runner flag with a blueprint.",type:"string",choices:["create-new-site","apply-to-existing-site"],hidden:!0},phpmyadmin:{describe:"Install phpMyAdmin for database management. The phpMyAdmin URL will be printed after boot. Optionally specify a custom URL path (default: /phpmyadmin).",type:"string",coerce:i=>i===""?"/phpmyadmin":i}},r={port:{describe:"Port to listen on when serving.",type:"number",default:9400},"experimental-multi-worker":{deprecated:"This option is not needed. Multiple workers are always used.",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.",type:"number"},"experimental-devtools":{describe:"Enable experimental browser development tools.",type:"boolean"}},o={path:{describe:"Path to the project directory. Playground will auto-detect if this is a plugin, theme, wp-content, or WordPress directory.",type:"string",default:process.cwd()},php:{describe:"PHP version to use.",type:"string",default:B.RecommendedPHPVersion,choices:P.SupportedPHPVersions},wp:{describe:"WordPress version to use.",type:"string",default:"latest"},port:{describe:"Port to listen on.",type:"number",default:9400},blueprint:{describe:"Path to a Blueprint JSON file to execute on startup.",type:"string"},login:{describe:"Auto-login as the admin user.",type:"boolean",default:!0},xdebug:{describe:"Enable Xdebug for debugging.",type:"boolean",default:!1},"experimental-unsafe-ide-integration":t["experimental-unsafe-ide-integration"],"skip-browser":{describe:"Do not open the site in your default browser on startup.",type:"boolean",default:!1},quiet:{describe:"Suppress non-essential output.",type:"boolean",default:!1},"site-url":{describe:"Override the site URL. By default, derived from the port (http://127.0.0.1:<port>).",type:"string"},mount:{describe:"Mount a directory to the PHP runtime (can be used multiple times). Format: /host/path:/vfs/path. Use this for additional mounts beyond auto-detection.",type:"array",string:!0,coerce:q},reset:{describe:"Deletes the stored site directory and starts a new site from scratch.",type:"boolean",default:!1},"no-auto-mount":{describe:"Disable automatic project type detection. Use --mount to manually specify mounts instead.",type:"boolean",default:!1},define:t.define,"define-bool":t["define-bool"],"define-number":t["define-number"],phpmyadmin:t.phpmyadmin},s={outfile:{describe:"When building, write to this output file.",type:"string",default:"wordpress.zip"}},n=ye(e).usage("Usage: wp-playground <command> [options]").command("start","Start a local WordPress server with automatic project detection (recommended)",i=>i.usage(`Usage: wp-playground start [options]
36
+
37
+ The easiest way to run WordPress locally. Automatically detects
38
+ if your directory contains a plugin, theme, wp-content, or
39
+ WordPress installation and configures everything for you.
40
+
41
+ Examples:
42
+ wp-playground start # Start in current directory
43
+ wp-playground start --path=./my-plugin # Start with a specific path
44
+ wp-playground start --wp=6.7 --php=8.3 # Use specific versions
45
+ wp-playground start --skip-browser # Skip opening browser
46
+ wp-playground start --no-auto-mount # Disable auto-detection`).options(o)).command("server","Start a local WordPress server (advanced, low-level)",i=>i.options({...t,...r})).command("run-blueprint","Execute a Blueprint without starting a server",i=>i.options({...t})).command("build-snapshot","Build a ZIP snapshot of a WordPress site based on a Blueprint",i=>i.options({...t,...s})).demandCommand(1,"Please specify a command").strictCommands().conflicts("experimental-unsafe-ide-integration","experimental-devtools").showHelpOnFail(!1).fail((i,w,b)=>{if(w)throw w;i&&i.includes("Please specify a command")&&(b.showHelp(),console.error(`
47
+ `+i),process.exit(1)),console.error(i),process.exit(1)}).strictOptions().check(async i=>{if(i["skip-wordpress-install"]===!0&&(i["wordpress-install-mode"]="do-not-attempt-installing",i.wordpressInstallMode="do-not-attempt-installing"),i.wp!==void 0&&typeof i.wp=="string"&&!_e(i.wp))try{new URL(i.wp)}catch{throw new Error('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"')}const w=i["site-url"];if(typeof w=="string"&&w.trim()!=="")try{new URL(w)}catch{throw new Error(`Invalid site-url "${w}". Please provide a valid URL (e.g., http://localhost:8080 or https://example.com)`)}if(i["auto-mount"]){let b=!1;try{b=c.statSync(i["auto-mount"]).isDirectory()}catch{b=!1}if(!b)throw new Error(`The specified --auto-mount path is not a directory: '${i["auto-mount"]}'.`)}if(i["experimental-blueprints-v2-runner"]===!0)throw new Error("Blueprints v2 are temporarily disabled while we rework their runtime implementation.");if(i.mode!==void 0)throw new Error("The --mode option requires the --experimentalBlueprintsV2Runner flag.");return!0});n.wrap(n.terminalWidth());const a=await n.argv,l=a._[0];["start","run-blueprint","server","build-snapshot"].includes(l)||(n.showHelp(),process.exit(1));const u=a.define||{};!("WP_DEBUG"in u)&&!("WP_DEBUG_LOG"in u)&&!("WP_DEBUG_DISPLAY"in u)&&(u.WP_DEBUG="true",u.WP_DEBUG_LOG="true",u.WP_DEBUG_DISPLAY="true");const I={...a,define:u,command:l,mount:[...a.mount||[],...a["mount-dir"]||[]],"mount-before-install":[...a["mount-before-install"]||[],...a["mount-dir-before-install"]||[]]},x=await de(I);x===void 0&&process.exit(0);const p=(()=>{let i;return async()=>{i===void 0&&(i=x[Symbol.asyncDispose]()),await i,process.exit(0)}})();return process.on("SIGINT",p),process.on("SIGTERM",p),{[Symbol.asyncDispose]:async()=>{process.off("SIGINT",p),process.off("SIGTERM",p),await x[Symbol.asyncDispose]()},[Q]:{cliServer:x}}}catch(t){if(console.error(t),!(t instanceof Error))throw t;if(process.argv.includes("--debug"))P.printDebugDetails(t);else{const o=[];let s=t;do o.push(s.message),s=s.cause;while(s instanceof Error);console.error("\x1B[1m"+o.join(" caused by: ")+"\x1B[0m")}process.exit(1)}}function ne(e,t){return e.find(r=>r.vfsPath.replace(/\/$/,"")===t.replace(/\/$/,""))}const Q=Symbol("playground-cli-testing"),C=e=>process.stdout.isTTY?"\x1B[1m"+e+"\x1B[0m":e,Je=e=>process.stdout.isTTY?"\x1B[31m"+e+"\x1B[0m":e,et=e=>process.stdout.isTTY?`\x1B[2m${e}\x1B[0m`:e,j=e=>process.stdout.isTTY?`\x1B[3m${e}\x1B[0m`:e,ie=e=>process.stdout.isTTY?`\x1B[33m${e}\x1B[0m`:e;async function de(e){let t;const r=e.internalCookieStore?new P.HttpCookieStore:void 0,o=[],s=new Map;if(e.command==="start"&&(e=tt(e)),e.autoMount!==void 0&&(e.autoMount===""&&(e={...e,autoMount:process.cwd()}),e=ae(e)),e.wordpressInstallMode===void 0&&(e.wordpressInstallMode="download-and-install"),e.quiet&&(e.verbosity="quiet",delete e.quiet),e.debug&&(e.verbosity="debug",delete e.debug),e.verbosity){const p=Object.values(G).find(i=>i.name===e.verbosity).severity;f.logger.setSeverityFilterLevel(p)}if(e.intl||(e.intl=!0),e.redis===void 0&&(e.redis=await re.jspi()),e.memcached===void 0&&(e.memcached=await re.jspi()),e.phpmyadmin){if(e.phpmyadmin===!0&&(e.phpmyadmin="/phpmyadmin"),e.skipSqliteSetup)throw new Error("--phpmyadmin requires SQLite. Cannot be used with --skip-sqlite-setup.");e.pathAliases=[{urlPrefix:e.phpmyadmin,fsPath:W.PHPMYADMIN_INSTALL_PATH}]}const n=new Xe({verbosity:e.verbosity||"normal"});e.command==="server"&&(n.printBanner(),n.printConfig({phpVersion:e.php||B.RecommendedPHPVersion,wpVersion:e.wp||"latest",port:e.port||9400,xdebug:!!e.xdebug,intl:!!e.intl,redis:!!e.redis,memcached:!!e.memcached,mounts:[...e.mount||[],...e["mount-before-install"]||[]],blueprint:typeof e.blueprint=="string"?e.blueprint:void 0}));const a=e.command==="server"?e.port??9400:0,l=new P.FileLockManagerInMemory;let u=!1,I=!0;const x=await Le({port:a,onBind:async(p,i)=>{const w="127.0.0.1",b=`http://${w}:${i}`,F=e["site-url"]||b,N=Math.max(H.cpus().length-1,Ze),X="-playground-cli-site-",M=await Ve(X);f.logger.debug(`Native temp dir for VFS root: ${M.path}`);const A="WP Playground CLI - Listen for Xdebug",Z=".playground-xdebug-root",K=d.join(process.cwd(),Z);if(await U.removeTempDirSymlink(K),e.xdebug&&e.experimentalUnsafeIdeIntegration){await U.createTempDirSymlink(M.path,K,process.platform);const m={hostPath:d.join(".",d.sep,Z),vfsPath:"/"};try{await U.clearXdebugIDEConfig(A,process.cwd());const y=typeof e.xdebug=="object"?e.xdebug:void 0,h=await U.addXdebugIDEConfig({name:A,host:w,port:i,ides:e.experimentalUnsafeIdeIntegration,cwd:process.cwd(),mounts:[m,...e["mount-before-install"]||[],...e.mount||[]],ideKey:y?.ideKey}),g=e.experimentalUnsafeIdeIntegration,v=g.includes("vscode"),S=g.includes("phpstorm"),k=Object.values(h);console.log(""),k.length>0?(console.log(C("Xdebug configured successfully")),console.log(ie("Updated IDE config: ")+k.join(" ")),console.log(ie("Playground source root: ")+".playground-xdebug-root"+j(et(" – you can set breakpoints and preview Playground's VFS structure in there.")))):(console.log(C("Xdebug configuration failed.")),console.log("No IDE-specific project settings directory was found in the current working directory.")),console.log(""),v&&h.vscode&&(console.log(C("VS Code / Cursor instructions:")),console.log(" 1. Ensure you have installed an IDE extension for PHP Debugging"),console.log(` (The ${C("PHP Debug")} extension by ${C("Xdebug")} has been a solid option)`),console.log(" 2. Open the Run and Debug panel on the left sidebar"),console.log(` 3. Select "${j(A)}" from the dropdown`),console.log(' 3. Click "start debugging"'),console.log(" 5. Set a breakpoint. For example, in .playground-xdebug-root/wordpress/index.php"),console.log(" 6. Visit Playground in your browser to hit the breakpoint"),S&&console.log("")),S&&h.phpstorm&&(console.log(C("PhpStorm instructions:")),console.log(` 1. Choose "${j(A)}" debug configuration in the toolbar`),console.log(" 2. Click the debug button (bug icon)`"),console.log(" 3. Set a breakpoint. For example, in .playground-xdebug-root/wordpress/index.php"),console.log(" 4. Visit Playground in your browser to hit the breakpoint")),console.log("")}catch(y){throw new Error("Could not configure Xdebug",{cause:y})}}const pe=d.dirname(M.path),me=2*24*60*60*1e3;Ye(X,me,pe);const J=d.join(M.path,"internal");c.mkdirSync(J);const he=["wordpress","tools","tmp","home"];for(const m of he){const y=g=>g.vfsPath===`/${m}`;if(!(e["mount-before-install"]?.some(y)||e.mount?.some(y))){const g=d.join(M.path,m);c.mkdirSync(g),e["mount-before-install"]===void 0&&(e["mount-before-install"]=[]),e["mount-before-install"].unshift({vfsPath:`/${m}`,hostPath:g})}}if(e["mount-before-install"])for(const m of e["mount-before-install"])f.logger.debug(`Mount before WP install: ${m.vfsPath} -> ${m.hostPath}`);if(e.mount)for(const m of e.mount)f.logger.debug(`Mount after WP install: ${m.vfsPath} -> ${m.hostPath}`);let R;e["experimental-blueprints-v2-runner"]?R=new Fe(e,{siteUrl:F,cliOutput:n}):(R=new je(e,{siteUrl:F,cliOutput:n}),typeof e.blueprint=="string"&&(e.blueprint=await He({sourceString:e.blueprint,blueprintMayReadAdjacentFiles:e["blueprint-may-read-adjacent-files"]===!0})));let O=!1;const D=async function(){O||(O=!0,await Promise.all(o.map(async y=>{await s.get(y)?.dispose(),await y.worker.terminate()})),p&&await new Promise(y=>{p.close(y),p.closeAllConnections()}),await M.cleanup())};try{const m=[],y=R.getWorkerType();for(let h=0;h<N;h++){const g=ce(y,{onExit:v=>{O||v===0&&f.logger.error(`Worker ${h} exited with code ${v}
48
+ `)}}).then(async v=>{o.push(v);const S=await rt(l),k=await R.bootRequestHandler({worker:v,fileLockManagerPort:S,nativeInternalDirPath:J});return s.set(v,k),[v,k]});m.push(g),h===0&&await g}await Promise.all(m),t=P.createObjectPoolProxy(o.map(h=>s.get(h)));{const h=new _.MessageChannel,g=h.port1,v=h.port2;if(await P.exposeAPI({applyPostInstallMountsToAllWorkers:async()=>{await Promise.all(Array.from(s.values()).map(S=>S.mountAfterWordPressInstall(e.mount||[])))}},void 0,g),await R.bootWordPress(t,v),g.close(),u=!0,!e["experimental-blueprints-v2-runner"]){const S=await R.compileInputBlueprint(e["additional-blueprint-steps"]||[]);S&&await $.runBlueprintV1Steps(S,t)}if(e.phpmyadmin&&!await t.fileExists(`${W.PHPMYADMIN_INSTALL_PATH}/index.php`)){const S=await W.getPhpMyAdminInstallSteps(),k=await $.compileBlueprintV1({steps:S});await $.runBlueprintV1Steps(k,t)}if(e.command==="build-snapshot"){await st(t,e.outfile),n.printStatus(`Exported to ${e.outfile}`),await D();return}else if(e.command==="run-blueprint"){n.finishProgress("Done"),await D();return}}if(n.finishProgress(),n.printReady(b,N),e.phpmyadmin){const h=d.join(e.phpmyadmin,W.PHPMYADMIN_ENTRY_PATH);n.printPhpMyAdminUrl(new URL(h,b).toString())}return e.xdebug&&e.experimentalDevtools&&(await Pe.startBridge({phpInstance:t,phpRoot:"/wordpress"})).start(),{playground:t,server:p,serverUrl:b,[Symbol.asyncDispose]:D,[Q]:{workerThreadCount:N}}}catch(m){if(e.verbosity!=="debug")throw m;let y="";throw await t?.fileExists(f.errorLogPath)&&(y=await t.readFileAsText(f.errorLogPath)),await D(),new Error(y,{cause:m})}},async handleRequest(p){if(!u)return P.PHPResponse.forHttpCode(502,"WordPress is not ready yet");if(I){I=!1;const w={"Content-Type":["text/plain"],"Content-Length":["0"],Location:[p.url]};return p.headers?.cookie?.includes("playground_auto_login_already_happened")&&(w["Set-Cookie"]=["playground_auto_login_already_happened=1; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/"]),new P.PHPResponse(302,w,new Uint8Array)}r&&(p={...p,headers:{...p.headers,cookie:r.getCookieRequestHeader()}});const i=await t.request(p);return r&&(r.rememberCookiesFromResponseHeaders(i.headers),delete i.headers["set-cookie"]),i}});return x&&e.command==="start"&&!e.skipBrowser&&ot(x.serverUrl),x}function tt(e){let t={...e,command:"server"};e.noAutoMount||(t.autoMount=d.resolve(process.cwd(),t.path??""),t=ae(t),delete t.autoMount);const r=ne(t["mount-before-install"]||[],"/wordpress")||ne(t.mount||[],"/wordpress");if(r)console.log("Site files stored at:",r?.hostPath),e.reset&&(console.log(""),console.log(Je("This site is not managed by Playground CLI and cannot be reset.")),console.log("(It's not stored in the ~/.wordpress-playground/sites/<site-id> directory.)"),console.log(""),console.log("You may still remove the site's directory manually if you wish."),process.exit(1));else{const o=t.autoMount||process.cwd(),s=xe.createHash("sha256").update(o).digest("hex"),n=H.homedir(),a=d.join(n,".wordpress-playground/sites",s);console.log("Site files stored at:",a),c.existsSync(a)&&e.reset&&(console.log("Resetting site..."),c.rmdirSync(a,{recursive:!0})),c.mkdirSync(a,{recursive:!0}),t["mount-before-install"]=[...t["mount-before-install"]||[],{vfsPath:"/wordpress",hostPath:a}],t.wordpressInstallMode=c.readdirSync(a).length===0?"download-and-install":"install-from-existing-files-if-needed"}return t}const V=new Te;function ce(e,{onExit:t}={}){let r;return e==="v1"?r=new _.Worker(new URL("./worker-thread-v1.cjs",typeof document>"u"?require("url").pathToFileURL(__filename).href:T&&T.tagName.toUpperCase()==="SCRIPT"&&T.src||new URL("run-cli-D-GS-Yv7.cjs",document.baseURI).href)):r=new _.Worker(new URL("./worker-thread-v2.cjs",typeof document>"u"?require("url").pathToFileURL(__filename).href:T&&T.tagName.toUpperCase()==="SCRIPT"&&T.src||new URL("run-cli-D-GS-Yv7.cjs",document.baseURI).href)),new Promise((o,s)=>{const n=V.claim();r.once("message",function(l){l.command==="worker-script-initialized"&&o({processId:n,worker:r,phpPort:l.phpPort})}),r.once("error",function(l){V.release(n),console.error(l);const u=new Error(`Worker failed to load worker. ${l.message?`Original error: ${l.message}`:""}`);s(u)});let a=!1;r.once("spawn",()=>{a=!0}),r.once("exit",l=>{V.release(n),a||s(new Error(`Worker exited before spawning: ${l}`)),t?.(l)})})}async function rt(e){const{port1:t,port2:r}=new _.MessageChannel;return await P.exposeSyncAPI(e,t),r}function ot(e){const t=H.platform();let r;switch(t){case"darwin":r=`open "${e}"`;break;case"win32":r=`start "" "${e}"`;break;default:r=`xdg-open "${e}"`;break}ve.exec(r,o=>{o&&f.logger.debug(`Could not open browser: ${o.message}`)})}async function st(e,t){await e.run({code:`<?php
49
+ $zip = new ZipArchive();
50
+ if(false === $zip->open('/tmp/build.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
51
+ throw new Exception('Failed to create ZIP');
52
+ }
53
+ $files = new RecursiveIteratorIterator(
54
+ new RecursiveDirectoryIterator('/wordpress')
55
+ );
56
+ foreach ($files as $file) {
57
+ echo $file . PHP_EOL;
58
+ if (!$file->isFile()) {
59
+ continue;
60
+ }
61
+ $zip->addFile($file->getPathname(), $file->getPathname());
62
+ }
63
+ $zip->close();
64
+
65
+ `});const r=await e.readFileAsBuffer("/tmp/build.zip");c.writeFileSync(t,r)}exports.LogVerbosity=G;exports.internalsKeyForTesting=Q;exports.mergeDefinedConstants=z;exports.mountResources=$e;exports.parseOptionsAndRunCLI=Ke;exports.runCLI=de;exports.shouldRenderProgress=ue;exports.spawnWorkerThread=ce;
66
+ //# sourceMappingURL=run-cli-D-GS-Yv7.cjs.map