@wp-playground/cli 3.0.53 → 3.1.0

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,24 +1,23 @@
1
- import { loadNodeRuntime as H } from "@php-wasm/node";
2
- import { EmscriptenDownloadMonitor as R } from "@php-wasm/progress";
3
- import { exposeAPI as W, PHPWorker as M, consumeAPI as g, consumeAPISync as S, sandboxedSpawnHandlerFactory as w } from "@php-wasm/universal";
4
- import { sprintf as A } from "@php-wasm/util";
5
- import { RecommendedPHPVersion as q } from "@wp-playground/common";
6
- import { bootWordPressAndRequestHandler as v, bootRequestHandler as L } from "@wp-playground/wordpress";
7
- import { rootCertificates as _ } from "tls";
8
- import { jspi as F } from "wasm-feature-detect";
9
- import { MessageChannel as C, parentPort as x } from "worker_threads";
10
- import { a as o, s as E } from "./run-cli-Cxpf7CoX.js";
11
- import { logger as U } from "@php-wasm/logger";
12
- function j(t, e, ...r) {
1
+ import { loadNodeRuntime as P } from "@php-wasm/node";
2
+ import { EmscriptenDownloadMonitor as w } from "@php-wasm/progress";
3
+ import { exposeAPI as f, PHPWorker as y, consumeAPISync as g, consumeAPI as h, releaseApiProxy as I, sandboxedSpawnHandlerFactory as b } from "@php-wasm/universal";
4
+ import { sprintf as W } from "@php-wasm/util";
5
+ import { RecommendedPHPVersion as H } from "@wp-playground/common";
6
+ import { bootWordPress as R, bootRequestHandler as k } from "@wp-playground/wordpress";
7
+ import { rootCertificates as q } from "tls";
8
+ import { MessageChannel as A, parentPort as M } from "worker_threads";
9
+ import { a as n, s as _ } from "./run-cli-BzYAH0YF.js";
10
+ import { logger as v } from "@php-wasm/logger";
11
+ function S(t, e, ...r) {
13
12
  console.log(
14
13
  performance.now().toFixed(6).padStart(15, "0"),
15
14
  t.toString().padStart(16, "0"),
16
- A(e, ...r)
15
+ W(e, ...r)
17
16
  );
18
17
  }
19
- class B extends M {
18
+ class F extends y {
20
19
  constructor(e) {
21
- super(void 0, e), this.booted = !1;
20
+ super(void 0, e), this.bootedRequestHandler = !1, this.bootedWordPress = !1;
22
21
  }
23
22
  /**
24
23
  * Call this method before boot() to use file locking.
@@ -30,136 +29,118 @@ class B extends M {
30
29
  * @see phpwasm-emscripten-library-file-locking-for-node.js
31
30
  */
32
31
  async useFileLockManager(e) {
33
- await F() ? this.fileLockManager = g(e) : this.fileLockManager = await S(e);
32
+ this.fileLockManager = await g(e);
34
33
  }
35
- async bootAndSetUpInitialWorker(e) {
34
+ async bootWordPress(e, r) {
35
+ if (this.bootedWordPress)
36
+ throw new Error("WordPress already booted");
37
+ this.bootedWordPress = !0;
36
38
  const {
37
- siteUrl: r,
38
- mountsBeforeWpInstall: a,
39
- mountsAfterWpInstall: s,
40
- wordpressInstallMode: I,
39
+ siteUrl: a,
40
+ wordpressInstallMode: o,
41
41
  wordPressZip: l,
42
- sqliteIntegrationPluginZip: c,
43
- dataSqlPath: k,
44
- internalCookieStore: b
42
+ sqliteIntegrationPluginZip: d,
43
+ dataSqlPath: m,
44
+ constants: u
45
45
  } = e;
46
- if (this.booted)
47
- throw new Error("Playground already booted");
48
- this.booted = !0;
49
46
  try {
50
- const i = {
51
- ...e.constants || {}
52
- };
53
- let d = !1;
54
- const h = await v({
55
- siteUrl: r,
56
- createPhpRuntime: P(
57
- e,
58
- this.fileLockManager
59
- ),
60
- wordpressInstallMode: I,
47
+ await R(this.__internal_getRequestHandler(), {
48
+ siteUrl: a,
49
+ wordpressInstallMode: o,
61
50
  wordPressZip: l !== void 0 ? new File([l], "wordpress.zip") : void 0,
62
- sqliteIntegrationPluginZip: c !== void 0 ? new File(
63
- [c],
51
+ sqliteIntegrationPluginZip: d !== void 0 ? new File(
52
+ [d],
64
53
  "sqlite-integration-plugin.zip"
65
54
  ) : void 0,
66
- sapiName: "cli",
55
+ // TODO: Are these redundant creations?
67
56
  createFiles: {
68
- "/internal/shared/ca-bundle.crt": _.join(`
57
+ "/internal/shared/ca-bundle.crt": q.join(`
69
58
  `)
70
59
  },
71
- constants: i,
72
60
  phpIniEntries: {
73
61
  "openssl.cafile": "/internal/shared/ca-bundle.crt",
74
62
  allow_url_fopen: "1",
75
63
  disable_functions: ""
76
64
  },
77
- cookieStore: b ? void 0 : !1,
78
- dataSqlPath: k,
79
- pathAliases: e.pathAliases,
80
- spawnHandler: () => w(
81
- () => u(e, this.fileLockManager)
82
- ),
83
- async onPHPInstanceCreated(m) {
84
- await o(m, a), d && await o(m, s);
85
- }
65
+ dataSqlPath: m,
66
+ constants: u
86
67
  });
87
- this.__internal_setRequestHandler(h), d = !0;
88
- const p = await h.getPrimaryPhp();
89
- await this.setPrimaryPHP(p), await o(p, s), f();
90
- } catch (i) {
91
- throw y(i), i;
68
+ const s = h(r);
69
+ await s.applyPostInstallMountsToAllWorkers(), s[I](), c();
70
+ } catch (s) {
71
+ throw p(s), s;
92
72
  }
93
73
  }
94
- async hello() {
95
- return "hello";
96
- }
97
- async bootWorker(e) {
98
- await this.bootRequestHandler(e);
99
- }
100
74
  async bootRequestHandler(e) {
101
- if (this.booted)
75
+ if (this.bootedRequestHandler)
102
76
  throw new Error("Playground already booted");
103
- this.booted = !0;
77
+ this.bootedRequestHandler = !0;
104
78
  try {
105
- const r = await L({
79
+ const r = await k({
106
80
  siteUrl: e.siteUrl,
107
- createPhpRuntime: P(
81
+ maxPhpInstances: 1,
82
+ createPhpRuntime: x(
108
83
  e,
109
84
  this.fileLockManager
110
85
  ),
111
- onPHPInstanceCreated: async (s) => {
112
- await o(s, e.mountsBeforeWpInstall), await o(s, e.mountsAfterWpInstall);
86
+ onPHPInstanceCreated: async (o) => {
87
+ await n(o, e.mountsBeforeWpInstall), this.bootedWordPress && await n(o, e.mountsAfterWpInstall);
113
88
  },
114
89
  sapiName: "cli",
115
90
  cookieStore: !1,
116
91
  pathAliases: e.pathAliases,
117
- spawnHandler: () => w(
118
- () => u(e, this.fileLockManager)
119
- )
92
+ spawnHandler: () => b(() => {
93
+ let o = e;
94
+ return this.bootedWordPress || (o = {
95
+ ...e,
96
+ mountsAfterWpInstall: []
97
+ }), C(
98
+ o,
99
+ this.fileLockManager
100
+ );
101
+ })
120
102
  });
121
103
  this.__internal_setRequestHandler(r);
122
104
  const a = await r.getPrimaryPhp();
123
- await this.setPrimaryPHP(a), f();
105
+ await this.setPrimaryPHP(a), c();
124
106
  } catch (r) {
125
- throw y(r), r;
107
+ throw p(r), r;
126
108
  }
127
109
  }
110
+ async mountAfterWordPressInstall(e) {
111
+ this.bootedWordPress = !0, await n(this.__internal_getPHP(), e);
112
+ }
128
113
  // Provide a named disposal method that can be invoked via comlink.
129
114
  async dispose() {
130
115
  await this[Symbol.asyncDispose]();
131
116
  }
132
117
  }
133
- function P(t, e) {
134
- let r = t.firstProcessId;
135
- const a = t.firstProcessId + t.processIdSpaceLength - 1;
136
- return async () => {
137
- const s = r;
138
- return r < a ? r++ : r = t.firstProcessId, await H(
139
- t.phpVersion || q,
140
- {
141
- emscriptenOptions: {
142
- fileLockManager: e,
143
- processId: s,
144
- trace: t.trace ? j : void 0,
145
- phpWasmInitOptions: {
146
- nativeInternalDirPath: t.nativeInternalDirPath
147
- }
148
- },
149
- followSymlinks: t.followSymlinks,
150
- withIntl: t.withIntl,
151
- withRedis: t.withRedis,
152
- withMemcached: t.withMemcached,
153
- withXdebug: t.withXdebug
154
- }
155
- );
156
- };
118
+ function x(t, e) {
119
+ return async () => await P(
120
+ t.phpVersion || H,
121
+ {
122
+ fileLockManager: e,
123
+ emscriptenOptions: {
124
+ processId: t.processId,
125
+ trace: t.trace ? S : void 0,
126
+ nativeInternalDirPath: t.nativeInternalDirPath
127
+ },
128
+ followSymlinks: t.followSymlinks,
129
+ withIntl: t.withIntl,
130
+ withRedis: t.withRedis,
131
+ withMemcached: t.withMemcached,
132
+ withXdebug: t.withXdebug
133
+ }
134
+ );
157
135
  }
158
- async function u(t, e) {
159
- const r = await E("v1"), a = g(
136
+ async function C(t, e) {
137
+ const r = await _("v1"), a = h(
160
138
  r.phpPort
161
139
  );
162
- return a.useFileLockManager(e), await a.bootWorker(t), {
140
+ return a.useFileLockManager(e), await a.bootRequestHandler({
141
+ ...t,
142
+ processId: r.processId
143
+ }), {
163
144
  php: a,
164
145
  reap: () => {
165
146
  try {
@@ -174,21 +155,21 @@ async function u(t, e) {
174
155
  };
175
156
  }
176
157
  process.on("unhandledRejection", (t) => {
177
- U.error("Unhandled rejection:", t);
158
+ v.error("Unhandled rejection:", t);
178
159
  });
179
- const n = new C(), [f, y] = W(
180
- new B(new R()),
160
+ const i = new A(), [c, p] = f(
161
+ new F(new w()),
181
162
  void 0,
182
- n.port1
163
+ i.port1
183
164
  );
184
- x?.postMessage(
165
+ M?.postMessage(
185
166
  {
186
167
  command: "worker-script-initialized",
187
- phpPort: n.port2
168
+ phpPort: i.port2
188
169
  },
189
- [n.port2]
170
+ [i.port2]
190
171
  );
191
172
  export {
192
- B as PlaygroundCliBlueprintV1Worker
173
+ F as PlaygroundCliBlueprintV1Worker
193
174
  };
194
175
  //# sourceMappingURL=worker-thread-v1.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"worker-thread-v1.js","sources":["../../../../packages/playground/cli/src/blueprints-v1/worker-thread-v1.ts"],"sourcesContent":["import type { FileLockManager } from '@php-wasm/node';\nimport { loadNodeRuntime } from '@php-wasm/node';\nimport { EmscriptenDownloadMonitor } from '@php-wasm/progress';\nimport type {\n\tPathAlias,\n\tRemoteAPI,\n\tSupportedPHPVersion,\n} from '@php-wasm/universal';\nimport {\n\tPHPWorker,\n\tconsumeAPI,\n\tconsumeAPISync,\n\texposeAPI,\n\tsandboxedSpawnHandlerFactory,\n} from '@php-wasm/universal';\nimport { sprintf } from '@php-wasm/util';\nimport { RecommendedPHPVersion } from '@wp-playground/common';\nimport {\n\ttype WordPressInstallMode,\n\tbootRequestHandler,\n\tbootWordPressAndRequestHandler,\n} from '@wp-playground/wordpress';\nimport { rootCertificates } from 'tls';\nimport { jspi } from 'wasm-feature-detect';\nimport { MessageChannel, type MessagePort, parentPort } from 'worker_threads';\nimport { mountResources } from '../mounts';\nimport { logger } from '@php-wasm/logger';\nimport { spawnWorkerThread } from '../run-cli';\n\nimport type { Mount } from '@php-wasm/cli-util';\n\nexport type WorkerBootOptions = {\n\tphpVersion: SupportedPHPVersion;\n\tsiteUrl: string;\n\tmountsBeforeWpInstall: Array<Mount>;\n\tmountsAfterWpInstall: Array<Mount>;\n\tfirstProcessId: number;\n\tprocessIdSpaceLength: number;\n\tfollowSymlinks: boolean;\n\ttrace: boolean;\n\t/**\n\t * When true, Playground will not send cookies to the client but will manage\n\t * them internally. This can be useful in environments that can't store cookies,\n\t * e.g. VS Code WebView.\n\t *\n\t * Default: false.\n\t */\n\tinternalCookieStore?: boolean;\n\twithIntl?: boolean;\n\twithRedis?: boolean;\n\twithMemcached?: boolean;\n\twithXdebug?: boolean;\n\tnativeInternalDirPath: string;\n\t/**\n\t * PHP constants to define via php.defineConstant().\n\t * Process-specific, set for each PHP instance.\n\t */\n\tconstants?: Record<string, string | number | boolean | null>;\n\t/**\n\t * Path aliases that map URL prefixes to filesystem paths outside\n\t * the document root. Similar to Nginx's `alias` directive.\n\t */\n\tpathAliases?: PathAlias[];\n};\n\nexport type PrimaryWorkerBootOptions = WorkerBootOptions & {\n\twordpressInstallMode: WordPressInstallMode;\n\twpVersion?: string;\n\twordPressZip?: ArrayBuffer;\n\tsqliteIntegrationPluginZip?: ArrayBuffer;\n\tdataSqlPath?: string;\n};\n\ninterface WorkerBootRequestHandlerOptions {\n\tsiteUrl: string;\n\tfollowSymlinks: boolean;\n\tphpVersion: SupportedPHPVersion;\n\tfirstProcessId: number;\n\tprocessIdSpaceLength: number;\n\ttrace: boolean;\n\tnativeInternalDirPath: string;\n\tmountsBeforeWpInstall: Array<Mount>;\n\tmountsAfterWpInstall: Array<Mount>;\n\twithIntl?: boolean;\n\twithRedis?: boolean;\n\twithMemcached?: boolean;\n\twithXdebug?: boolean;\n\tpathAliases?: PathAlias[];\n}\n\n/**\n * Print trace messages from PHP-WASM.\n *\n * @param {number} processId - The process ID.\n * @param {string} format - The format string.\n * @param {...any} args - The arguments.\n */\nfunction tracePhpWasm(processId: number, format: string, ...args: any[]) {\n\t// eslint-disable-next-line no-console\n\tconsole.log(\n\t\tperformance.now().toFixed(6).padStart(15, '0'),\n\t\tprocessId.toString().padStart(16, '0'),\n\t\tsprintf(format, ...args)\n\t);\n}\n\nexport class PlaygroundCliBlueprintV1Worker extends PHPWorker {\n\tbooted = false;\n\tfileLockManager: RemoteAPI<FileLockManager> | FileLockManager | undefined;\n\n\tconstructor(monitor: EmscriptenDownloadMonitor) {\n\t\tsuper(undefined, monitor);\n\t}\n\n\t/**\n\t * Call this method before boot() to use file locking.\n\t *\n\t * This method is separate from boot() to simplify the related Comlink.transferHandlers\n\t * setup – if an argument is a MessagePort, we're transferring it, not copying it.\n\t *\n\t * @see comlink-sync.ts\n\t * @see phpwasm-emscripten-library-file-locking-for-node.js\n\t */\n\tasync useFileLockManager(port: MessagePort) {\n\t\tif (await jspi()) {\n\t\t\t/**\n\t\t\t * If JSPI is available, php.js supports both synchronous and asynchronous locking syscalls.\n\t\t\t * Web browsers, however, only support asynchronous message passing so let's use the\n\t\t\t * asynchronous API. Every method call will return a promise.\n\t\t\t *\n\t\t\t * @see comlink-sync.ts\n\t\t\t * @see phpwasm-emscripten-library-file-locking-for-node.js\n\t\t\t */\n\t\t\tthis.fileLockManager = consumeAPI<FileLockManager>(port);\n\t\t} else {\n\t\t\t/**\n\t\t\t * If JSPI is not available, php.js only supports synchronous locking syscalls.\n\t\t\t * Let's use the synchronous API. Every method call will block this thread\n\t\t\t * until the result is available.\n\t\t\t *\n\t\t\t * @see comlink-sync.ts\n\t\t\t * @see phpwasm-emscripten-library-file-locking-for-node.js\n\t\t\t */\n\t\t\tthis.fileLockManager = await consumeAPISync<FileLockManager>(port);\n\t\t}\n\t}\n\n\tasync bootAndSetUpInitialWorker(options: PrimaryWorkerBootOptions) {\n\t\tconst {\n\t\t\tsiteUrl,\n\t\t\tmountsBeforeWpInstall,\n\t\t\tmountsAfterWpInstall,\n\t\t\twordpressInstallMode,\n\t\t\twordPressZip,\n\t\t\tsqliteIntegrationPluginZip,\n\t\t\tdataSqlPath,\n\t\t\tinternalCookieStore,\n\t\t} = options;\n\t\tif (this.booted) {\n\t\t\tthrow new Error('Playground already booted');\n\t\t}\n\t\tthis.booted = true;\n\n\t\ttry {\n\t\t\t// Start with CLI-provided constants (if any)\n\t\t\tconst constants: Record<string, string | number | boolean | null> =\n\t\t\t\t{\n\t\t\t\t\t...(options.constants || {}),\n\t\t\t\t};\n\t\t\tlet wordpressBooted = false;\n\t\t\tconst requestHandler = await bootWordPressAndRequestHandler({\n\t\t\t\tsiteUrl,\n\t\t\t\tcreatePhpRuntime: createPhpRuntimeFactory(\n\t\t\t\t\toptions,\n\t\t\t\t\tthis.fileLockManager!\n\t\t\t\t),\n\t\t\t\twordpressInstallMode,\n\t\t\t\twordPressZip:\n\t\t\t\t\twordPressZip !== undefined\n\t\t\t\t\t\t? new File([wordPressZip], 'wordpress.zip')\n\t\t\t\t\t\t: undefined,\n\t\t\t\tsqliteIntegrationPluginZip:\n\t\t\t\t\tsqliteIntegrationPluginZip !== undefined\n\t\t\t\t\t\t? new File(\n\t\t\t\t\t\t\t\t[sqliteIntegrationPluginZip],\n\t\t\t\t\t\t\t\t'sqlite-integration-plugin.zip'\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t: undefined,\n\t\t\t\tsapiName: 'cli',\n\t\t\t\tcreateFiles: {\n\t\t\t\t\t'/internal/shared/ca-bundle.crt':\n\t\t\t\t\t\trootCertificates.join('\\n'),\n\t\t\t\t},\n\t\t\t\tconstants,\n\t\t\t\tphpIniEntries: {\n\t\t\t\t\t'openssl.cafile': '/internal/shared/ca-bundle.crt',\n\t\t\t\t\tallow_url_fopen: '1',\n\t\t\t\t\tdisable_functions: '',\n\t\t\t\t},\n\t\t\t\tcookieStore: internalCookieStore ? undefined : false,\n\t\t\t\tdataSqlPath,\n\t\t\t\tpathAliases: options.pathAliases,\n\t\t\t\tspawnHandler: () =>\n\t\t\t\t\tsandboxedSpawnHandlerFactory(() =>\n\t\t\t\t\t\tcreatePHPWorker(options, this.fileLockManager!)\n\t\t\t\t\t),\n\t\t\t\tasync onPHPInstanceCreated(php) {\n\t\t\t\t\tawait mountResources(php, mountsBeforeWpInstall);\n\t\t\t\t\tif (wordpressBooted) {\n\t\t\t\t\t\tawait mountResources(php, mountsAfterWpInstall);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t});\n\t\t\tthis.__internal_setRequestHandler(requestHandler);\n\t\t\twordpressBooted = true;\n\n\t\t\tconst primaryPhp = await requestHandler.getPrimaryPhp();\n\t\t\tawait this.setPrimaryPHP(primaryPhp);\n\n\t\t\t// The primary PHP instance is persistent, so we need to apply\n\t\t\t// post-install mounts now that WordPress has been booted.\n\t\t\t// All secondary PHP instances created after WP boot will get\n\t\t\t// these mounts automatically.\n\t\t\tawait mountResources(primaryPhp, mountsAfterWpInstall);\n\n\t\t\tsetApiReady();\n\t\t} catch (e) {\n\t\t\tsetAPIError(e as Error);\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\tasync hello() {\n\t\treturn 'hello';\n\t}\n\n\tasync bootWorker(args: WorkerBootOptions) {\n\t\tawait this.bootRequestHandler(args);\n\t}\n\n\tasync bootRequestHandler(options: WorkerBootRequestHandlerOptions) {\n\t\tif (this.booted) {\n\t\t\tthrow new Error('Playground already booted');\n\t\t}\n\t\tthis.booted = true;\n\n\t\ttry {\n\t\t\tconst requestHandler = await bootRequestHandler({\n\t\t\t\tsiteUrl: options.siteUrl,\n\t\t\t\tcreatePhpRuntime: createPhpRuntimeFactory(\n\t\t\t\t\toptions,\n\t\t\t\t\tthis.fileLockManager!\n\t\t\t\t),\n\t\t\t\tonPHPInstanceCreated: async (php) => {\n\t\t\t\t\tawait mountResources(php, options.mountsBeforeWpInstall);\n\t\t\t\t\tawait mountResources(php, options.mountsAfterWpInstall);\n\t\t\t\t},\n\t\t\t\tsapiName: 'cli',\n\t\t\t\tcookieStore: false,\n\t\t\t\tpathAliases: options.pathAliases,\n\t\t\t\tspawnHandler: () =>\n\t\t\t\t\tsandboxedSpawnHandlerFactory(() =>\n\t\t\t\t\t\tcreatePHPWorker(options, this.fileLockManager!)\n\t\t\t\t\t),\n\t\t\t});\n\t\t\tthis.__internal_setRequestHandler(requestHandler);\n\n\t\t\tconst primaryPhp = await requestHandler.getPrimaryPhp();\n\t\t\tawait this.setPrimaryPHP(primaryPhp);\n\n\t\t\tsetApiReady();\n\t\t} catch (e) {\n\t\t\tsetAPIError(e as Error);\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\t// Provide a named disposal method that can be invoked via comlink.\n\tasync dispose() {\n\t\tawait this[Symbol.asyncDispose]();\n\t}\n}\n\n/**\n * Returns a factory function that starts a new PHP runtime in the currently\n * running process. This is used for rotating the PHP runtime periodically.\n */\nfunction createPhpRuntimeFactory(\n\toptions: WorkerBootRequestHandlerOptions,\n\tfileLockManager: FileLockManager | RemoteAPI<FileLockManager>\n) {\n\tlet nextProcessId = options.firstProcessId;\n\tconst lastProcessId =\n\t\toptions.firstProcessId + options.processIdSpaceLength - 1;\n\treturn async () => {\n\t\tconst processId = nextProcessId;\n\n\t\tif (nextProcessId < lastProcessId) {\n\t\t\tnextProcessId++;\n\t\t} else {\n\t\t\t// We've reached the end of the process ID space. Start over.\n\t\t\tnextProcessId = options.firstProcessId;\n\t\t}\n\n\t\treturn await loadNodeRuntime(\n\t\t\toptions.phpVersion || RecommendedPHPVersion,\n\t\t\t{\n\t\t\t\temscriptenOptions: {\n\t\t\t\t\tfileLockManager,\n\t\t\t\t\tprocessId,\n\t\t\t\t\ttrace: options.trace ? tracePhpWasm : undefined,\n\t\t\t\t\tphpWasmInitOptions: {\n\t\t\t\t\t\tnativeInternalDirPath: options.nativeInternalDirPath,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tfollowSymlinks: options.followSymlinks,\n\t\t\t\twithIntl: options.withIntl,\n\t\t\t\twithRedis: options.withRedis,\n\t\t\t\twithMemcached: options.withMemcached,\n\t\t\t\twithXdebug: options.withXdebug,\n\t\t\t}\n\t\t);\n\t};\n}\n\n/**\n * Spawns a new PHP process to be used in the PHP spawn handler (in proc_open() etc. calls).\n * It boots from this worker-thread-v1.ts file, but is a separate process.\n *\n * We explicitly avoid using PHPProcessManager.acquirePHPInstance() here.\n *\n * Why?\n *\n * Because each PHP instance acquires actual OS-level file locks via fcntl() and LockFileEx()\n * syscalls. Running multiple PHP instances from the same OS process would allow them to\n * acquire overlapping locks. Running every PHP instance in a separate OS process ensures\n * any locks that overlap between PHP instances conflict with each other as expected.\n *\n * @param options - The options for the worker.\n * @param fileLockManager - The file lock manager to use.\n * @returns A promise that resolves to the PHP worker.\n */\nasync function createPHPWorker(\n\toptions: WorkerBootRequestHandlerOptions,\n\tfileLockManager: FileLockManager | RemoteAPI<FileLockManager>\n) {\n\tconst spawnedWorker = await spawnWorkerThread('v1');\n\n\tconst handler = consumeAPI<PlaygroundCliBlueprintV1Worker>(\n\t\tspawnedWorker.phpPort\n\t);\n\thandler.useFileLockManager(fileLockManager as any);\n\tawait handler.bootWorker(options);\n\n\treturn {\n\t\tphp: handler,\n\t\treap: () => {\n\t\t\ttry {\n\t\t\t\thandler.dispose();\n\t\t\t} catch {\n\t\t\t\t/** */\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tspawnedWorker.worker.terminate();\n\t\t\t} catch {\n\t\t\t\t/** */\n\t\t\t}\n\t\t},\n\t};\n}\n\nprocess.on('unhandledRejection', (e: any) => {\n\tlogger.error('Unhandled rejection:', e);\n});\n\nconst phpChannel = new MessageChannel();\n\nconst [setApiReady, setAPIError] = exposeAPI(\n\tnew PlaygroundCliBlueprintV1Worker(new EmscriptenDownloadMonitor()),\n\tundefined,\n\tphpChannel.port1\n);\n\nparentPort?.postMessage(\n\t{\n\t\tcommand: 'worker-script-initialized',\n\t\tphpPort: phpChannel.port2,\n\t},\n\t[phpChannel.port2 as any]\n);\n"],"names":["tracePhpWasm","processId","format","args","sprintf","PlaygroundCliBlueprintV1Worker","PHPWorker","monitor","port","jspi","consumeAPI","consumeAPISync","options","siteUrl","mountsBeforeWpInstall","mountsAfterWpInstall","wordpressInstallMode","wordPressZip","sqliteIntegrationPluginZip","dataSqlPath","internalCookieStore","constants","wordpressBooted","requestHandler","bootWordPressAndRequestHandler","createPhpRuntimeFactory","rootCertificates","sandboxedSpawnHandlerFactory","createPHPWorker","php","mountResources","primaryPhp","setApiReady","e","setAPIError","bootRequestHandler","fileLockManager","nextProcessId","lastProcessId","loadNodeRuntime","RecommendedPHPVersion","spawnedWorker","spawnWorkerThread","handler","logger","phpChannel","MessageChannel","exposeAPI","EmscriptenDownloadMonitor","parentPort"],"mappings":";;;;;;;;;;;AAiGA,SAASA,EAAaC,GAAmBC,MAAmBC,GAAa;AAExE,UAAQ;AAAA,IACP,YAAY,MAAM,QAAQ,CAAC,EAAE,SAAS,IAAI,GAAG;AAAA,IAC7CF,EAAU,SAAA,EAAW,SAAS,IAAI,GAAG;AAAA,IACrCG,EAAQF,GAAQ,GAAGC,CAAI;AAAA,EAAA;AAEzB;AAEO,MAAME,UAAuCC,EAAU;AAAA,EAI7D,YAAYC,GAAoC;AAC/C,UAAM,QAAWA,CAAO,GAJzB,KAAA,SAAS;AAAA,EAKT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,MAAM,mBAAmBC,GAAmB;AAC3C,IAAI,MAAMC,MAST,KAAK,kBAAkBC,EAA4BF,CAAI,IAUvD,KAAK,kBAAkB,MAAMG,EAAgCH,CAAI;AAAA,EAEnE;AAAA,EAEA,MAAM,0BAA0BI,GAAmC;AAClE,UAAM;AAAA,MACL,SAAAC;AAAA,MACA,uBAAAC;AAAA,MACA,sBAAAC;AAAA,MACA,sBAAAC;AAAA,MACA,cAAAC;AAAA,MACA,4BAAAC;AAAA,MACA,aAAAC;AAAA,MACA,qBAAAC;AAAA,IA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mBAAmB;AAAA,UAClB,iBAAAJ;AAAA,UACA,WAAAnC;AAAA,UACA,OAAOW,EAAQ,QAAQZ,IAAe;AAAA,UACtC,oBAAoB;AAAA,YACnB,uBAAuBY,EAAQ;AAAA,UAAA;AAAA,QAChC;AAAA,QAED,gBAAgBA,EAAQ;AAAA,QACxB,UAAUA,EAAQ;AAAA,QAClB,WAAWA,EAAQ;AAAA,QACnB,eAAeA,EAAQ;AAAA,QACvB,YAAYA,EAAQ;AAAA,MAAA;AAAA,IACrB;AAAA,EAEF;AACD;AAmBA,eAAegB,EACdhB,GACAwB,GACC;AACD,QAAMK,IAAgB,MAAMC,EAAkB,IAAI,GAE5CC,IAAUjC;AAAA,IACf+B,EAAc;AAAA,EAAA;AAEf,SAAAE,EAAQ,mBAAmBP,CAAsB,GACjD,MAAMO,EAAQ,WAAW/B,CAAO,GAEzB;AAAA,IACN,KAAK+B;AAAA,IACL,MAAM,MAAM;AACX,UAAI;AACH,QAAAA,EAAQ,QAAA;AAAA,MACT,QAAQ;AAAA,MAER;AACA,UAAI;AACH,QAAAF,EAAc,OAAO,UAAA;AAAA,MACtB,QAAQ;AAAA,MAER;AAAA,IACD;AAAA,EAAA;AAEF;AAEA,QAAQ,GAAG,sBAAsB,CAACR,MAAW;AAC5C,EAAAW,EAAO,MAAM,wBAAwBX,CAAC;AACvC,CAAC;AAED,MAAMY,IAAa,IAAIC,EAAA,GAEjB,CAACd,GAAaE,CAAW,IAAIa;AAAA,EAClC,IAAI1C,EAA+B,IAAI2C,GAA2B;AAAA,EAClE;AAAA,EACAH,EAAW;AACZ;AAEAI,GAAY;AAAA,EACX;AAAA,IACC,SAAS;AAAA,IACT,SAASJ,EAAW;AAAA,EAAA;AAAA,EAErB,CAACA,EAAW,KAAY;AACzB;"}
1
+ {"version":3,"file":"worker-thread-v1.js","sources":["../../../../packages/playground/cli/src/blueprints-v1/worker-thread-v1.ts"],"sourcesContent":["import type { FileLockManager } from '@php-wasm/universal';\nimport { loadNodeRuntime } from '@php-wasm/node';\nimport { EmscriptenDownloadMonitor } from '@php-wasm/progress';\nimport type { PathAlias, SupportedPHPVersion } from '@php-wasm/universal';\nimport {\n\tPHPWorker,\n\treleaseApiProxy,\n\tconsumeAPI,\n\tconsumeAPISync,\n\texposeAPI,\n\tsandboxedSpawnHandlerFactory,\n} from '@php-wasm/universal';\nimport { sprintf } from '@php-wasm/util';\nimport { RecommendedPHPVersion } from '@wp-playground/common';\nimport {\n\ttype WordPressInstallMode,\n\tbootRequestHandler,\n\tbootWordPress,\n} from '@wp-playground/wordpress';\nimport { rootCertificates } from 'tls';\nimport { MessageChannel, type MessagePort, parentPort } from 'worker_threads';\nimport { mountResources } from '../mounts';\nimport { logger } from '@php-wasm/logger';\nimport { spawnWorkerThread } from '../run-cli';\n\nimport type { Mount } from '@php-wasm/cli-util';\n\nexport type WorkerBootWordPressOptions = {\n\tsiteUrl: string;\n\twpVersion?: string;\n\twordpressInstallMode: WordPressInstallMode;\n\twordPressZip?: ArrayBuffer;\n\tsqliteIntegrationPluginZip?: ArrayBuffer;\n\tdataSqlPath?: string;\n\t/**\n\t * PHP constants to define via php.defineConstant().\n\t */\n\tconstants?: Record<string, string | number | boolean>;\n};\n\ninterface WorkerBootRequestHandlerOptions {\n\tsiteUrl: string;\n\tphpVersion: SupportedPHPVersion;\n\tprocessId: number;\n\ttrace: boolean;\n\tnativeInternalDirPath: string;\n\tmountsBeforeWpInstall: Array<Mount>;\n\tmountsAfterWpInstall: Array<Mount>;\n\tfollowSymlinks: boolean;\n\twithIntl?: boolean;\n\twithRedis?: boolean;\n\twithMemcached?: boolean;\n\twithXdebug?: boolean;\n\tpathAliases?: PathAlias[];\n}\n\n/**\n * Print trace messages from PHP-WASM.\n *\n * @param {number} processId - The process ID.\n * @param {string} format - The format string.\n * @param {...any} args - The arguments.\n */\nfunction tracePhpWasm(processId: number, format: string, ...args: any[]) {\n\t// eslint-disable-next-line no-console\n\tconsole.log(\n\t\tperformance.now().toFixed(6).padStart(15, '0'),\n\t\tprocessId.toString().padStart(16, '0'),\n\t\tsprintf(format, ...args)\n\t);\n}\n\nexport class PlaygroundCliBlueprintV1Worker extends PHPWorker {\n\tbootedRequestHandler = false;\n\tbootedWordPress = false;\n\tfileLockManager: FileLockManager | undefined;\n\n\tconstructor(monitor: EmscriptenDownloadMonitor) {\n\t\tsuper(undefined, monitor);\n\t}\n\n\t/**\n\t * Call this method before boot() to use file locking.\n\t *\n\t * This method is separate from boot() to simplify the related Comlink.transferHandlers\n\t * setup – if an argument is a MessagePort, we're transferring it, not copying it.\n\t *\n\t * @see comlink-sync.ts\n\t * @see phpwasm-emscripten-library-file-locking-for-node.js\n\t */\n\tasync useFileLockManager(port: MessagePort) {\n\t\tthis.fileLockManager = await consumeAPISync<FileLockManager>(port);\n\t}\n\n\tasync bootWordPress(\n\t\toptions: WorkerBootWordPressOptions,\n\t\tworkerPostInstallMountsPort: MessagePort\n\t) {\n\t\tif (this.bootedWordPress) {\n\t\t\tthrow new Error('WordPress already booted');\n\t\t}\n\t\tthis.bootedWordPress = true;\n\t\tconst {\n\t\t\tsiteUrl,\n\t\t\twordpressInstallMode,\n\t\t\twordPressZip,\n\t\t\tsqliteIntegrationPluginZip,\n\t\t\tdataSqlPath,\n\t\t\tconstants,\n\t\t} = options;\n\n\t\ttry {\n\t\t\tawait bootWordPress(this.__internal_getRequestHandler()!, {\n\t\t\t\tsiteUrl,\n\t\t\t\twordpressInstallMode,\n\t\t\t\twordPressZip:\n\t\t\t\t\twordPressZip !== undefined\n\t\t\t\t\t\t? new File([wordPressZip], 'wordpress.zip')\n\t\t\t\t\t\t: undefined,\n\t\t\t\tsqliteIntegrationPluginZip:\n\t\t\t\t\tsqliteIntegrationPluginZip !== undefined\n\t\t\t\t\t\t? new File(\n\t\t\t\t\t\t\t\t[sqliteIntegrationPluginZip],\n\t\t\t\t\t\t\t\t'sqlite-integration-plugin.zip'\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t: undefined,\n\t\t\t\t// TODO: Are these redundant creations?\n\t\t\t\tcreateFiles: {\n\t\t\t\t\t'/internal/shared/ca-bundle.crt':\n\t\t\t\t\t\trootCertificates.join('\\n'),\n\t\t\t\t},\n\t\t\t\tphpIniEntries: {\n\t\t\t\t\t'openssl.cafile': '/internal/shared/ca-bundle.crt',\n\t\t\t\t\tallow_url_fopen: '1',\n\t\t\t\t\tdisable_functions: '',\n\t\t\t\t},\n\t\t\t\tdataSqlPath,\n\t\t\t\tconstants,\n\t\t\t});\n\n\t\t\t// Notify all workers to apply post-install mounts.\n\t\t\tconst postInstall = consumeAPI<{\n\t\t\t\tapplyPostInstallMountsToAllWorkers: () => Promise<void>;\n\t\t\t}>(workerPostInstallMountsPort);\n\t\t\tawait postInstall.applyPostInstallMountsToAllWorkers();\n\t\t\tpostInstall[releaseApiProxy]();\n\n\t\t\tsetApiReady();\n\t\t} catch (e) {\n\t\t\tsetAPIError(e as Error);\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\tasync bootRequestHandler(options: WorkerBootRequestHandlerOptions) {\n\t\tif (this.bootedRequestHandler) {\n\t\t\tthrow new Error('Playground already booted');\n\t\t}\n\t\tthis.bootedRequestHandler = true;\n\n\t\ttry {\n\t\t\tconst requestHandler = await bootRequestHandler({\n\t\t\t\tsiteUrl: options.siteUrl,\n\t\t\t\tmaxPhpInstances: 1,\n\t\t\t\tcreatePhpRuntime: createPhpRuntimeFactory(\n\t\t\t\t\toptions,\n\t\t\t\t\tthis.fileLockManager!\n\t\t\t\t),\n\t\t\t\tonPHPInstanceCreated: async (php) => {\n\t\t\t\t\tawait mountResources(php, options.mountsBeforeWpInstall);\n\n\t\t\t\t\t// NOTE: We currently create all request workers up front\n\t\t\t\t\t// and apply post-install mounts to all the workers immediately\n\t\t\t\t\t// following WordPress install. But if we start creating\n\t\t\t\t\t// request-handling workers on-demand, we will to apply post-install\n\t\t\t\t\t// mounts here.\n\t\t\t\t\tif (this.bootedWordPress) {\n\t\t\t\t\t\tawait mountResources(php, options.mountsAfterWpInstall);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tsapiName: 'cli',\n\t\t\t\tcookieStore: false,\n\t\t\t\tpathAliases: options.pathAliases,\n\t\t\t\tspawnHandler: () =>\n\t\t\t\t\tsandboxedSpawnHandlerFactory(() => {\n\t\t\t\t\t\tlet effectiveOptions = options;\n\t\t\t\t\t\tif (!this.bootedWordPress) {\n\t\t\t\t\t\t\t// WordPress is not yet booted so skip the post-install mounts.\n\t\t\t\t\t\t\teffectiveOptions = {\n\t\t\t\t\t\t\t\t...options,\n\t\t\t\t\t\t\t\tmountsAfterWpInstall: [],\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn createPHPWorker(\n\t\t\t\t\t\t\teffectiveOptions,\n\t\t\t\t\t\t\tthis.fileLockManager!\n\t\t\t\t\t\t);\n\t\t\t\t\t}),\n\t\t\t});\n\t\t\tthis.__internal_setRequestHandler(requestHandler);\n\n\t\t\tconst primaryPhp = await requestHandler.getPrimaryPhp();\n\t\t\tawait this.setPrimaryPHP(primaryPhp);\n\n\t\t\tsetApiReady();\n\t\t} catch (e) {\n\t\t\tsetAPIError(e as Error);\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\tasync mountAfterWordPressInstall(mounts: Array<Mount>) {\n\t\t// Make sure workers not involved in the WordPress install\n\t\t// process know whether WordPress booted so they can\n\t\t// apply post-install mounts when spawning new PHP workers.\n\t\tthis.bootedWordPress = true;\n\t\tawait mountResources(this.__internal_getPHP()!, mounts);\n\t}\n\n\t// Provide a named disposal method that can be invoked via comlink.\n\tasync dispose() {\n\t\tawait this[Symbol.asyncDispose]();\n\t}\n}\n\n/**\n * Returns a factory function that starts a new PHP runtime in the currently\n * running process. This is used for rotating the PHP runtime periodically.\n */\nfunction createPhpRuntimeFactory(\n\toptions: WorkerBootRequestHandlerOptions,\n\tfileLockManager: FileLockManager\n) {\n\treturn async () => {\n\t\treturn await loadNodeRuntime(\n\t\t\toptions.phpVersion || RecommendedPHPVersion,\n\t\t\t{\n\t\t\t\tfileLockManager,\n\t\t\t\temscriptenOptions: {\n\t\t\t\t\tprocessId: options.processId,\n\t\t\t\t\ttrace: options.trace ? tracePhpWasm : undefined,\n\t\t\t\t\tnativeInternalDirPath: options.nativeInternalDirPath,\n\t\t\t\t},\n\t\t\t\tfollowSymlinks: options.followSymlinks,\n\t\t\t\twithIntl: options.withIntl,\n\t\t\t\twithRedis: options.withRedis,\n\t\t\t\twithMemcached: options.withMemcached,\n\t\t\t\twithXdebug: options.withXdebug,\n\t\t\t}\n\t\t);\n\t};\n}\n\n/**\n * Spawns a new PHP process to be used in the PHP spawn handler (in proc_open() etc. calls).\n * It boots from this worker-thread-v1.ts file, but is a separate process.\n *\n * We explicitly avoid using PHPProcessManager.acquirePHPInstance() here.\n *\n * Why?\n *\n * Because each PHP instance acquires actual OS-level file locks via fcntl() and LockFileEx()\n * syscalls. Running multiple PHP instances from the same OS process would allow them to\n * acquire overlapping locks. Running every PHP instance in a separate OS process ensures\n * any locks that overlap between PHP instances conflict with each other as expected.\n *\n * @param options - The options for the worker.\n * @param fileLockManager - The file lock manager to use.\n * @returns A promise that resolves to the PHP worker.\n */\nasync function createPHPWorker(\n\t// NOTE: We explicitly remove processId from the options\n\t// type so the type system will catch if we try to reuse\n\t// our parent's process ID.\n\toptions: Omit<WorkerBootRequestHandlerOptions, 'processId'>,\n\tfileLockManager: FileLockManager\n) {\n\tconst spawnedWorker = await spawnWorkerThread('v1');\n\n\tconst handler = consumeAPI<PlaygroundCliBlueprintV1Worker>(\n\t\tspawnedWorker.phpPort\n\t);\n\thandler.useFileLockManager(fileLockManager as any);\n\tawait handler.bootRequestHandler({\n\t\t...options,\n\t\tprocessId: spawnedWorker.processId,\n\t});\n\n\treturn {\n\t\tphp: handler,\n\t\treap: () => {\n\t\t\ttry {\n\t\t\t\thandler.dispose();\n\t\t\t} catch {\n\t\t\t\t/** */\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tspawnedWorker.worker.terminate();\n\t\t\t} catch {\n\t\t\t\t/** */\n\t\t\t}\n\t\t},\n\t};\n}\n\nprocess.on('unhandledRejection', (e: any) => {\n\tlogger.error('Unhandled rejection:', e);\n});\n\nconst phpChannel = new MessageChannel();\n\nconst [setApiReady, setAPIError] = exposeAPI(\n\tnew PlaygroundCliBlueprintV1Worker(new EmscriptenDownloadMonitor()),\n\tundefined,\n\tphpChannel.port1\n);\n\nparentPort?.postMessage(\n\t{\n\t\tcommand: 'worker-script-initialized',\n\t\tphpPort: phpChannel.port2,\n\t},\n\t[phpChannel.port2 as any]\n);\n"],"names":["tracePhpWasm","processId","format","args","sprintf","PlaygroundCliBlueprintV1Worker","PHPWorker","monitor","port","consumeAPISync","options","workerPostInstallMountsPort","siteUrl","wordpressInstallMode","wordPressZip","sqliteIntegrationPluginZip","dataSqlPath","constants","bootWordPress","rootCertificates","postInstall","consumeAPI","releaseApiProxy","setApiReady","e","setAPIError","requestHandler","bootRequestHandler","createPhpRuntimeFactory","php","mountResources","sandboxedSpawnHandlerFactory","effectiveOptions","createPHPWorker","primaryPhp","mounts","fileLockManager","loadNodeRuntime","RecommendedPHPVersion","spawnedWorker","spawnWorkerThread","handler","logger","phpChannel","MessageChannel","exposeAPI","EmscriptenDownloadMonitor","parentPort"],"mappings":";;;;;;;;;;AA+DA,SAASA,EAAaC,GAAmBC,MAAmBC,GAAa;AAExE,UAAQ;AAAA,IACP,YAAY,MAAM,QAAQ,CAAC,EAAE,SAAS,IAAI,GAAG;AAAA,IAC7CF,EAAU,SAAA,EAAW,SAAS,IAAI,GAAG;AAAA,IACrCG,EAAQF,GAAQ,GAAGC,CAAI;AAAA,EAAA;AAEzB;AAEO,MAAME,UAAuCC,EAAU;AAAA,EAK7D,YAAYC,GAAoC;AAC/C,UAAM,QAAWA,CAAO,GALzB,KAAA,uBAAuB,IACvB,KAAA,kBAAkB;AAAA,EAKlB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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,YAAYA,EAAQ;AAAA,IAAA;AAAA,EACrB;AAGH;AAmBA,eAAeuB,EAIdvB,GACA0B,GACC;AACD,QAAMG,IAAgB,MAAMC,EAAkB,IAAI,GAE5CC,IAAUpB;AAAA,IACfkB,EAAc;AAAA,EAAA;AAEf,SAAAE,EAAQ,mBAAmBL,CAAsB,GACjD,MAAMK,EAAQ,mBAAmB;AAAA,IAChC,GAAG/B;AAAA,IACH,WAAW6B,EAAc;AAAA,EAAA,CACzB,GAEM;AAAA,IACN,KAAKE;AAAA,IACL,MAAM,MAAM;AACX,UAAI;AACH,QAAAA,EAAQ,QAAA;AAAA,MACT,QAAQ;AAAA,MAER;AACA,UAAI;AACH,QAAAF,EAAc,OAAO,UAAA;AAAA,MACtB,QAAQ;AAAA,MAER;AAAA,IACD;AAAA,EAAA;AAEF;AAEA,QAAQ,GAAG,sBAAsB,CAACf,MAAW;AAC5C,EAAAkB,EAAO,MAAM,wBAAwBlB,CAAC;AACvC,CAAC;AAED,MAAMmB,IAAa,IAAIC,EAAA,GAEjB,CAACrB,GAAaE,CAAW,IAAIoB;AAAA,EAClC,IAAIxC,EAA+B,IAAIyC,GAA2B;AAAA,EAClE;AAAA,EACAH,EAAW;AACZ;AAEAI,GAAY;AAAA,EACX;AAAA,IACC,SAAS;AAAA,IACT,SAASJ,EAAW;AAAA,EAAA;AAAA,EAErB,CAACA,EAAW,KAAY;AACzB;"}
@@ -1,15 +1,15 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const H=require("@php-wasm/logger"),T=require("@php-wasm/node"),F=require("@php-wasm/progress"),d=require("@php-wasm/universal"),B=require("@php-wasm/util"),_=require("@wp-playground/blueprints"),C=require("@wp-playground/wordpress"),L=require("fs"),g=require("path"),E=require("tls"),I=require("worker_threads"),N=require("wasm-feature-detect"),R=require("./run-cli-DHqpmO6s.cjs");async function b(s,e){for(const r of e)try{s.mkdir(r.vfsPath),await s.mount(r.vfsPath,T.createNodeFsMountHandler(r.hostPath))}catch{i.stderr(`\x1B[31m\x1B[1mError mounting path ${r.hostPath} at ${r.vfsPath}\x1B[0m
2
- `),process.exit(1)}}function O(s,e,...r){console.log(performance.now().toFixed(6).padStart(15,"0"),s.toString().padStart(16,"0"),B.sprintf(e,...r))}Object.defineProperty(process.stdout,"isTTY",{value:!0});Object.defineProperty(process.stderr,"isTTY",{value:!0});const i={lastWriteWasProgress:!1,progress(s){R.shouldRenderProgress(process.stdout)&&(process.stdout.isTTY?(i.lastWriteWasProgress||process.stdout.write(`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _=require("@php-wasm/logger"),m=require("@php-wasm/node"),$=require("@php-wasm/progress"),n=require("@php-wasm/universal"),x=require("@php-wasm/util"),S=require("@wp-playground/blueprints"),W=require("@wp-playground/wordpress"),A=require("fs"),y=require("path"),B=require("tls"),R=require("worker_threads"),T=require("./run-cli-CIkDrr7x.cjs");async function g(s,e){for(const t of e)try{s.mkdir(t.vfsPath),await s.mount(t.vfsPath,m.createNodeFsMountHandler(t.hostPath))}catch{i.stderr(`\x1B[31m\x1B[1mError mounting path ${t.hostPath} at ${t.vfsPath}\x1B[0m
2
+ `),process.exit(1)}}function C(s,e,...t){console.log(performance.now().toFixed(6).padStart(15,"0"),s.toString().padStart(16,"0"),x.sprintf(e,...t))}Object.defineProperty(process.stdout,"isTTY",{value:!0});Object.defineProperty(process.stderr,"isTTY",{value:!0});const i={lastWriteWasProgress:!1,progress(s){T.shouldRenderProgress(process.stdout)&&(process.stdout.isTTY?(i.lastWriteWasProgress||process.stdout.write(`
3
3
  `),process.stdout.write("\r\x1B[K"+s),i.lastWriteWasProgress=!0):console.log(s))},stdout(s){process.stdout.write(`
4
4
 
5
5
 
6
6
  `),i.lastWriteWasProgress&&(i.lastWriteWasProgress=!1),process.stdout.write(s)},stderr(s){process.stdout.write(`
7
7
 
8
8
 
9
- `),i.lastWriteWasProgress&&(i.lastWriteWasProgress=!1),process.stderr.write(s)}};class q extends d.PHPWorker{constructor(e){super(void 0,e),this.booted=!1,this.blueprintTargetResolved=!1,this.phpInstancesThatNeedMountsAfterTargetResolved=new Set}async useFileLockManager(e){await N.jspi()?this.fileLockManager=d.consumeAPI(e):this.fileLockManager=await d.consumeAPISync(e)}async bootAndSetUpInitialWorker(e){const r={...e.constants||{}},p={...e,createFiles:{"/internal/shared/ca-bundle.crt":E.rootCertificates.join(`
10
- `)},constants:r,phpIniEntries:{"openssl.cafile":"/internal/shared/ca-bundle.crt"},onPHPInstanceCreated:async n=>{await b(n,e.mountsBeforeWpInstall||[]),this.blueprintTargetResolved?await b(n,e.mountsAfterWpInstall||[]):(this.phpInstancesThatNeedMountsAfterTargetResolved.add(n),n.addEventListener("runtime.beforeExit",()=>{this.phpInstancesThatNeedMountsAfterTargetResolved.delete(n)}))},spawnHandler:()=>d.sandboxedSpawnHandlerFactory(()=>v(e,this.fileLockManager))};await this.bootRequestHandler(p);const u=this.__internal_getPHP();if(e.mode==="mount-only"){await b(u,e.mountsAfterWpInstall||[]);return}await this.runBlueprintV2({...e,mountsAfterWpInstall:e.mountsAfterWpInstall||[]})}async bootWorker(e){await this.bootRequestHandler({...e,onPHPInstanceCreated:async r=>{await b(r,e.mountsBeforeWpInstall||[]),await b(r,e.mountsAfterWpInstall||[]),r.isDir("/wordpress/wp-content")||r.mkdir("/wordpress/wp-content"),r.isDir("/wordpress/wp-content/database")||r.mkdir("/wordpress/wp-content/database"),r.isFile("/wordpress/wp-content/database/.htaccess")||r.writeFile("/wordpress/wp-content/database/.htaccess","deny from all"),r.isFile("/wordpress/wp-content/database/index.php")||r.writeFile("/wordpress/wp-content/database/index.php","deny from all")},spawnHandler:()=>d.sandboxedSpawnHandlerFactory(()=>v(e,this.fileLockManager))})}async runBlueprintV2(e){const r=this.__internal_getRequestHandler(),{php:p,reap:u}=await r.instanceManager.acquirePHPInstance(),n=this.__internal_getPHP();let w=()=>{};if(typeof e.blueprint=="string"){const o=g.resolve(process.cwd(),e.blueprint);L.existsSync(o)&&(n.mkdir("/internal/shared/cwd"),w=await n.mount("/internal/shared/cwd",T.createNodeFsMountHandler(g.dirname(o))),e.blueprint=g.join("/internal/shared/cwd",g.basename(e.blueprint)))}try{const l=["mode","db-engine","db-host","db-user","db-pass","db-name","db-path","truncate-new-site-directory","allow"].filter(t=>t in e).map(t=>`--${t}=${e[t]}`);l.push(`--site-url=${e.siteUrl}`);const c=await _.runBlueprintV2({php:p,blueprint:e.blueprint,blueprintOverrides:{additionalSteps:e["additional-blueprint-steps"],wordpressVersion:e.wp},cliArgs:l,onMessage:async t=>{switch(t.type){case"blueprint.target_resolved":{if(!this.blueprintTargetResolved){this.blueprintTargetResolved=!0;for(const a of this.phpInstancesThatNeedMountsAfterTargetResolved)this.phpInstancesThatNeedMountsAfterTargetResolved.delete(a),await b(a,e.mountsAfterWpInstall||[])}break}case"blueprint.progress":{const a=`${t.caption.trim()} – ${t.progress.toFixed(2)}%`;i.progress(a);break}case"blueprint.error":{const a="\x1B[31m",h="\x1B[1m",f="\x1B[0m";e.verbosity==="debug"&&t.details?i.stderr(`${a}${h}Fatal error:${f} Uncaught ${t.details.exception}: ${t.details.message}
11
- at ${t.details.file}:${t.details.line}
12
- `+(t.details.trace?t.details.trace+`
13
- `:"")):i.stderr(`${a}${h}Error:${f} ${t.message}
14
- `);break}}}});if(e.verbosity==="debug"&&(c.stdout.pipeTo(new WritableStream({write(t){process.stdout.write(t)}})),c.stderr.pipeTo(new WritableStream({write(t){process.stderr.write(t)}}))),await c.finished,await c.exitCode!==0){const t=await d.PHPResponse.fromStreamedResponse(c);throw new d.PHPExecutionFailureError(`PHP.run() failed with exit code ${t.exitCode}. ${t.errors} ${t.text}`,t,"request")}}catch(o){let l="";try{l=p.readFileAsText(H.errorLogPath)}catch{}throw o.phpLogs=l,o}finally{u(),w()}}async bootRequestHandler({siteUrl:e,allow:r,phpVersion:p,createFiles:u,constants:n,phpIniEntries:w,firstProcessId:o,processIdSpaceLength:l,trace:c,nativeInternalDirPath:t,withIntl:a,withRedis:h,withMemcached:f,withXdebug:k,pathAliases:y,onPHPInstanceCreated:P,spawnHandler:A}){if(this.booted)throw new Error("Playground already booted");this.booted=!0;let W=o;const M=o+l-1;try{const m=await C.bootRequestHandler({siteUrl:e,createPhpRuntime:async()=>{const S=W;return W<M?W++:W=o,await T.loadNodeRuntime(p,{emscriptenOptions:{fileLockManager:this.fileLockManager,processId:S,trace:c?O:void 0,ENV:{DOCROOT:"/wordpress"},phpWasmInitOptions:{nativeInternalDirPath:t}},followSymlinks:r?.includes("follow-symlinks"),withIntl:a,withRedis:h,withMemcached:f,withXdebug:k})},maxPhpInstances:1,onPHPInstanceCreated:P,sapiName:"cli",createFiles:u,constants:n,phpIniEntries:w,pathAliases:y,cookieStore:!1,spawnHandler:A});this.__internal_setRequestHandler(m);const $=await m.getPrimaryPhp();await this.setPrimaryPHP($),j()}catch(m){throw V(m),m}}async dispose(){await this[Symbol.asyncDispose]()}}async function v({siteUrl:s,allow:e,phpVersion:r,createFiles:p,constants:u,phpIniEntries:n,firstProcessId:w,processIdSpaceLength:o,trace:l,nativeInternalDirPath:c,withXdebug:t,pathAliases:a,mountsBeforeWpInstall:h,mountsAfterWpInstall:f},k){const y=await R.spawnWorkerThread("v2"),P=d.consumeAPI(y.phpPort);return P.useFileLockManager(k),await P.bootWorker({siteUrl:s,allow:e,phpVersion:r,createFiles:p,constants:u,phpIniEntries:n,firstProcessId:w,processIdSpaceLength:o,trace:l,nativeInternalDirPath:c,withXdebug:t,pathAliases:a,mountsBeforeWpInstall:h,mountsAfterWpInstall:f}),{php:P,reap:()=>{try{P.dispose()}catch{}try{y.worker.terminate()}catch{}}}}process.on("unhandledRejection",s=>{H.logger.error("Unhandled rejection:",s)});const x=new I.MessageChannel,[j,V]=d.exposeAPI(new q(new F.EmscriptenDownloadMonitor),void 0,x.port1);I.parentPort?.postMessage({command:"worker-script-initialized",phpPort:x.port2},[x.port2]);exports.PlaygroundCliBlueprintV2Worker=q;
9
+ `),i.lastWriteWasProgress&&(i.lastWriteWasProgress=!1),process.stderr.write(s)}};class H extends n.PHPWorker{constructor(e){super(void 0,e),this.booted=!1,this.blueprintTargetResolved=!1,this.phpInstancesThatNeedMountsAfterTargetResolved=new Set}async useFileLockManager(e){this.fileLockManager=await n.consumeAPISync(e)}async bootWordPress(e,t){const o=await this.__internal_getRequestHandler().getPrimaryPhp();if(o.defineConstant("WP_DEBUG","true"),o.defineConstant("WP_DEBUG_LOG","true"),o.defineConstant("WP_DEBUG_DISPLAY","false"),o.defineConstant("WP_HOME",e.siteUrl),o.defineConstant("WP_SITEURL",e.siteUrl),await n.setPhpIniEntries(o,{"openssl.cafile":"/internal/shared/ca-bundle.crt",allow_url_fopen:"1",disable_functions:""}),await W.setupPlatformLevelMuPlugins(o),await n.writeFiles(o,"/",{"/internal/shared/ca-bundle.crt":B.rootCertificates.join(`
10
+ `)}),await W.preloadPhpInfoRoute(o,x.joinPaths(new URL(e.siteUrl).pathname,"phpinfo.php")),e.mode==="mount-only"){await this.applyPostInstallMountsToAllWorkers(t);return}await this.runBlueprintV2({...e},t)}async bootWorker(e){await this.bootRequestHandler({...e,onPHPInstanceCreated:async t=>{await g(t,e.mountsBeforeWpInstall||[]),await g(t,e.mountsAfterWpInstall||[]),t.isDir("/wordpress/wp-content")||t.mkdir("/wordpress/wp-content"),t.isDir("/wordpress/wp-content/database")||t.mkdir("/wordpress/wp-content/database"),t.isFile("/wordpress/wp-content/database/.htaccess")||t.writeFile("/wordpress/wp-content/database/.htaccess","deny from all"),t.isFile("/wordpress/wp-content/database/index.php")||t.writeFile("/wordpress/wp-content/database/index.php","deny from all")},spawnHandler:()=>n.sandboxedSpawnHandlerFactory(()=>L(e,this.fileLockManager))})}async runBlueprintV2(e,t){const o=this.__internal_getRequestHandler(),{php:w,reap:f}=await o.instanceManager.acquirePHPInstance(),h=this.__internal_getPHP();let P=()=>{};if(typeof e.blueprint=="string"){const a=y.resolve(process.cwd(),e.blueprint);A.existsSync(a)&&(h.mkdir("/internal/shared/cwd"),P=await h.mount("/internal/shared/cwd",m.createNodeFsMountHandler(y.dirname(a))),e.blueprint=y.join("/internal/shared/cwd",y.basename(e.blueprint)))}try{const l=["mode","db-engine","db-host","db-user","db-pass","db-name","db-path","truncate-new-site-directory","allow"].filter(r=>r in e).map(r=>`--${r}=${e[r]}`);l.push(`--site-url=${e.siteUrl}`);const c=await S.runBlueprintV2({php:w,blueprint:e.blueprint,blueprintOverrides:{additionalSteps:e["additional-blueprint-steps"],wordpressVersion:e.wp},cliArgs:l,onMessage:async r=>{switch(r.type){case"blueprint.target_resolved":{this.blueprintTargetResolved||(this.blueprintTargetResolved=!0,await this.applyPostInstallMountsToAllWorkers(t));break}case"blueprint.progress":{const p=`${r.caption.trim()} – ${r.progress.toFixed(2)}%`;i.progress(p);break}case"blueprint.error":{const p="\x1B[31m",u="\x1B[1m",d="\x1B[0m";e.verbosity==="debug"&&r.details?i.stderr(`${p}${u}Fatal error:${d} Uncaught ${r.details.exception}: ${r.details.message}
11
+ at ${r.details.file}:${r.details.line}
12
+ `+(r.details.trace?r.details.trace+`
13
+ `:"")):i.stderr(`${p}${u}Error:${d} ${r.message}
14
+ `);break}}}});if(e.verbosity==="debug"&&(c.stdout.pipeTo(new WritableStream({write(r){process.stdout.write(r)}})),c.stderr.pipeTo(new WritableStream({write(r){process.stderr.write(r)}}))),await c.finished,await c.exitCode!==0){const r=await n.PHPResponse.fromStreamedResponse(c);throw new n.PHPExecutionFailureError(`PHP.run() failed with exit code ${r.exitCode}. ${r.errors} ${r.text}`,r,"request")}}catch(a){let l="";try{l=w.readFileAsText(_.errorLogPath)}catch{}throw a.phpLogs=l,a}finally{f(),P()}}async bootRequestHandler({siteUrl:e,allow:t,phpVersion:o,processId:w,createFiles:f,constants:h,phpIniEntries:P,trace:a,nativeInternalDirPath:l,withIntl:c,withRedis:r,withMemcached:p,withXdebug:u,pathAliases:d,onPHPInstanceCreated:M,spawnHandler:q}){if(this.booted)throw new Error("Playground already booted");this.booted=!0;try{const b=await W.bootRequestHandler({siteUrl:e,createPhpRuntime:async()=>await m.loadNodeRuntime(o,{fileLockManager:this.fileLockManager,emscriptenOptions:{processId:w,trace:a?C:void 0,ENV:{DOCROOT:"/wordpress"},nativeInternalDirPath:l,bindUserSpace:I=>m.bindUserSpace({fileLockManager:this.fileLockManager},I)},followSymlinks:t?.includes("follow-symlinks"),withIntl:c,withRedis:r,withMemcached:p,withXdebug:u}),maxPhpInstances:1,onPHPInstanceCreated:M,sapiName:"cli",createFiles:f,constants:h,phpIniEntries:P,pathAliases:d,cookieStore:!1,spawnHandler:q});this.__internal_setRequestHandler(b);const v=await b.getPrimaryPhp();await this.setPrimaryPHP(v),F()}catch(b){throw E(b),b}}async mountAfterWordPressInstall(e){await g(this.__internal_getPHP(),e)}async applyPostInstallMountsToAllWorkers(e){const t=n.consumeAPI(e);await t(),t[n.releaseApiProxy]()}async dispose(){await this[Symbol.asyncDispose]()}}async function L({siteUrl:s,allow:e,phpVersion:t,createFiles:o,constants:w,phpIniEntries:f,trace:h,nativeInternalDirPath:P,withXdebug:a,pathAliases:l,mountsBeforeWpInstall:c,mountsAfterWpInstall:r},p){const u=await T.spawnWorkerThread("v2"),d=n.consumeAPI(u.phpPort);return d.useFileLockManager(p),await d.bootWorker({siteUrl:s,allow:e,phpVersion:t,createFiles:o,constants:w,phpIniEntries:f,processId:u.processId,trace:h,nativeInternalDirPath:P,withXdebug:a,pathAliases:l,mountsBeforeWpInstall:c,mountsAfterWpInstall:r}),{php:d,reap:()=>{try{d.dispose()}catch{}try{u.worker.terminate()}catch{}}}}process.on("unhandledRejection",s=>{_.logger.error("Unhandled rejection:",s)});const k=new R.MessageChannel,[F,E]=n.exposeAPI(new H(new $.EmscriptenDownloadMonitor),void 0,k.port1);R.parentPort?.postMessage({command:"worker-script-initialized",phpPort:k.port2},[k.port2]);exports.PlaygroundCliBlueprintV2Worker=H;
15
15
  //# sourceMappingURL=worker-thread-v2.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"worker-thread-v2.cjs","sources":["../../../../packages/playground/cli/src/blueprints-v2/worker-thread-v2.ts"],"sourcesContent":["import { errorLogPath, logger } from '@php-wasm/logger';\nimport type { FileLockManager } from '@php-wasm/node';\nimport { createNodeFsMountHandler, loadNodeRuntime } from '@php-wasm/node';\nimport { EmscriptenDownloadMonitor } from '@php-wasm/progress';\nimport type {\n\tPathAlias,\n\tPHP,\n\tFileTree,\n\tRemoteAPI,\n\tSupportedPHPVersion,\n\tSpawnHandler,\n} from '@php-wasm/universal';\nimport {\n\tPHPExecutionFailureError,\n\tPHPResponse,\n\tPHPWorker,\n\tconsumeAPI,\n\tconsumeAPISync,\n\texposeAPI,\n\tsandboxedSpawnHandlerFactory,\n} from '@php-wasm/universal';\nimport { sprintf } from '@php-wasm/util';\nimport {\n\ttype BlueprintMessage,\n\trunBlueprintV2,\n\ttype BlueprintV1Declaration,\n} from '@wp-playground/blueprints';\nimport {\n\ttype ParsedBlueprintV2String,\n\ttype RawBlueprintV2Data,\n} from '@wp-playground/blueprints';\nimport { bootRequestHandler } from '@wp-playground/wordpress';\nimport { existsSync } from 'fs';\nimport path from 'path';\nimport { rootCertificates } from 'tls';\nimport { MessageChannel, type MessagePort, parentPort } from 'worker_threads';\nimport { jspi } from 'wasm-feature-detect';\nimport { spawnWorkerThread, type RunCLIArgs } from '../run-cli';\nimport type {\n\tPhpIniOptions,\n\tPHPInstanceCreatedHook,\n} from '@wp-playground/wordpress';\nimport { shouldRenderProgress } from '../utils/progress';\nimport type { Mount } from '@php-wasm/cli-util';\n\nasync function mountResources(php: PHP, mounts: Mount[]) {\n\tfor (const mount of mounts) {\n\t\ttry {\n\t\t\tphp.mkdir(mount.vfsPath);\n\t\t\tawait php.mount(\n\t\t\t\tmount.vfsPath,\n\t\t\t\tcreateNodeFsMountHandler(mount.hostPath)\n\t\t\t);\n\t\t} catch {\n\t\t\toutput.stderr(\n\t\t\t\t`\\x1b[31m\\x1b[1mError mounting path ${mount.hostPath} at ${mount.vfsPath}\\x1b[0m\\n`\n\t\t\t);\n\t\t\tprocess.exit(1);\n\t\t}\n\t}\n}\n\n/**\n * Print trace messages from PHP-WASM.\n *\n * @param {number} processId - The process ID.\n * @param {string} format - The format string.\n * @param {...any} args - The arguments.\n */\nfunction tracePhpWasm(processId: number, format: string, ...args: any[]) {\n\t// eslint-disable-next-line no-console\n\tconsole.log(\n\t\tperformance.now().toFixed(6).padStart(15, '0'),\n\t\tprocessId.toString().padStart(16, '0'),\n\t\tsprintf(format, ...args)\n\t);\n}\n\n/**\n * Force TTY status to preserve ANSI control codes in the output\n * when the environment is interactive.\n *\n * This script is spawned as `new Worker()` and process.stdout and process.stderr are\n * WritableWorkerStdio objects. By default, they strip ANSI control codes from the output\n * causing every progress bar update to be printed in a new line instead of updating the\n * same line.\n */\nObject.defineProperty(process.stdout, 'isTTY', { value: true });\nObject.defineProperty(process.stderr, 'isTTY', { value: true });\n\n/**\n * Output writer that ensures that progress bars are not printed on the same line as other output.\n */\nconst output = {\n\tlastWriteWasProgress: false,\n\tprogress(data: string) {\n\t\tif (!shouldRenderProgress(process.stdout)) {\n\t\t\treturn;\n\t\t}\n\t\tif (!process.stdout.isTTY) {\n\t\t\t// eslint-disable-next-line no-console\n\t\t\tconsole.log(data);\n\t\t} else {\n\t\t\tif (!output.lastWriteWasProgress) {\n\t\t\t\tprocess.stdout.write('\\n');\n\t\t\t}\n\t\t\tprocess.stdout.write('\\r\\x1b[K' + data);\n\t\t\toutput.lastWriteWasProgress = true;\n\t\t}\n\t},\n\tstdout(data: string) {\n\t\tprocess.stdout.write('\\n\\n\\n');\n\t\tif (output.lastWriteWasProgress) {\n\t\t\toutput.lastWriteWasProgress = false;\n\t\t}\n\t\tprocess.stdout.write(data);\n\t},\n\tstderr(data: string) {\n\t\tprocess.stdout.write('\\n\\n\\n');\n\t\tif (output.lastWriteWasProgress) {\n\t\t\toutput.lastWriteWasProgress = false;\n\t\t}\n\t\tprocess.stderr.write(data);\n\t},\n};\n\nexport type PrimaryWorkerBootArgs = Omit<\n\tRunCLIArgs,\n\t'mount-before-install' | 'mount'\n> & {\n\tphpVersion: SupportedPHPVersion;\n\tsiteUrl: string;\n\tfirstProcessId: number;\n\tprocessIdSpaceLength: number;\n\ttrace: boolean;\n\tblueprint:\n\t\t| RawBlueprintV2Data\n\t\t| ParsedBlueprintV2String\n\t\t| BlueprintV1Declaration;\n\tnativeInternalDirPath: string;\n\tmountsBeforeWpInstall?: Array<Mount>;\n\tmountsAfterWpInstall?: Array<Mount>;\n\t/**\n\t * PHP constants to define via php.defineConstant().\n\t * Process-specific, set for each PHP instance.\n\t */\n\tconstants?: Record<string, string | number | boolean | null>;\n};\n\ntype WorkerRunBlueprintArgs = Omit<\n\tRunCLIArgs,\n\t'mount-before-install' | 'mount'\n> & {\n\tsiteUrl: string;\n\tblueprint:\n\t\t| RawBlueprintV2Data\n\t\t| ParsedBlueprintV2String\n\t\t| BlueprintV1Declaration;\n\tmountsAfterWpInstall?: Array<Mount>;\n};\n\nexport type SecondaryWorkerBootArgs = {\n\tsiteUrl: string;\n\tallow?: string;\n\tphpVersion: SupportedPHPVersion;\n\tphpIniEntries?: PhpIniOptions;\n\tconstants?: Record<string, string | number | boolean | null>;\n\tcreateFiles?: FileTree;\n\tfirstProcessId: number;\n\tprocessIdSpaceLength: number;\n\ttrace: boolean;\n\tnativeInternalDirPath: string;\n\twithIntl?: boolean;\n\twithRedis?: boolean;\n\twithMemcached?: boolean;\n\twithXdebug?: boolean;\n\tpathAliases?: PathAlias[];\n\tmountsBeforeWpInstall?: Array<Mount>;\n\tmountsAfterWpInstall?: Array<Mount>;\n};\n\nexport type WorkerBootRequestHandlerOptions = Omit<\n\tSecondaryWorkerBootArgs,\n\t'mountsBeforeWpInstall' | 'mountsAfterWpInstall'\n> & {\n\tonPHPInstanceCreated: PHPInstanceCreatedHook;\n\tspawnHandler: () => SpawnHandler;\n};\n\nexport class PlaygroundCliBlueprintV2Worker extends PHPWorker {\n\tbooted = false;\n\tblueprintTargetResolved = false;\n\tphpInstancesThatNeedMountsAfterTargetResolved = new Set<PHP>();\n\tfileLockManager: RemoteAPI<FileLockManager> | FileLockManager | undefined;\n\n\tconstructor(monitor: EmscriptenDownloadMonitor) {\n\t\tsuper(undefined, monitor);\n\t}\n\n\t/**\n\t * Call this method before boot() to use file locking.\n\t *\n\t * This method is separate from boot() to simplify the related Comlink.transferHandlers\n\t * setup – if an argument is a MessagePort, we're transferring it, not copying it.\n\t *\n\t * @see comlink-sync.ts\n\t * @see phpwasm-emscripten-library-file-locking-for-node.js\n\t */\n\tasync useFileLockManager(port: MessagePort) {\n\t\tif (await jspi()) {\n\t\t\t/**\n\t\t\t * If JSPI is available, php.js supports both synchronous and asynchronous locking syscalls.\n\t\t\t * Web browsers, however, only support asynchronous message passing so let's use the\n\t\t\t * asynchronous API. Every method call will return a promise.\n\t\t\t *\n\t\t\t * @see comlink-sync.ts\n\t\t\t * @see phpwasm-emscripten-library-file-locking-for-node.js\n\t\t\t */\n\t\t\tthis.fileLockManager = consumeAPI<FileLockManager>(port);\n\t\t} else {\n\t\t\t/**\n\t\t\t * If JSPI is not available, php.js only supports synchronous locking syscalls.\n\t\t\t * Let's use the synchronous API. Every method call will block this thread\n\t\t\t * until the result is available.\n\t\t\t *\n\t\t\t * @see comlink-sync.ts\n\t\t\t * @see phpwasm-emscripten-library-file-locking-for-node.js\n\t\t\t */\n\t\t\tthis.fileLockManager = await consumeAPISync<FileLockManager>(port);\n\t\t}\n\t}\n\n\tasync bootAndSetUpInitialWorker(args: PrimaryWorkerBootArgs) {\n\t\t// Start with CLI-provided constants (if any)\n\t\tconst constants = {\n\t\t\t...(args.constants || {}),\n\t\t};\n\t\tconst requestHandlerOptions: WorkerBootRequestHandlerOptions = {\n\t\t\t...args,\n\t\t\tcreateFiles: {\n\t\t\t\t'/internal/shared/ca-bundle.crt': rootCertificates.join('\\n'),\n\t\t\t},\n\t\t\tconstants,\n\t\t\tphpIniEntries: {\n\t\t\t\t'openssl.cafile': '/internal/shared/ca-bundle.crt',\n\t\t\t},\n\t\t\tonPHPInstanceCreated: async (php: PHP) => {\n\t\t\t\tawait mountResources(php, args.mountsBeforeWpInstall || []);\n\t\t\t\tif (this.blueprintTargetResolved) {\n\t\t\t\t\tawait mountResources(php, args.mountsAfterWpInstall || []);\n\t\t\t\t} else {\n\t\t\t\t\t// NOTE: Today (2025-09-11), during boot with a plugin auto-mount,\n\t\t\t\t\t// the Blueprint runner fails unless post-resolution mounts are\n\t\t\t\t\t// added to existing PHP instances. So we track them here so they\n\t\t\t\t\t// can be mounted at the necessary time.\n\t\t\t\t\t// Only plugin auto-mounts seem to need this, so perhaps there\n\t\t\t\t\t// is a change we can make to the Blueprint runner so such\n\t\t\t\t\t// a dance is unnecessary.\n\t\t\t\t\tthis.phpInstancesThatNeedMountsAfterTargetResolved.add(php);\n\t\t\t\t\tphp.addEventListener('runtime.beforeExit', () => {\n\t\t\t\t\t\tthis.phpInstancesThatNeedMountsAfterTargetResolved.delete(\n\t\t\t\t\t\t\tphp\n\t\t\t\t\t\t);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t},\n\t\t\tspawnHandler: () =>\n\t\t\t\tsandboxedSpawnHandlerFactory(() =>\n\t\t\t\t\tcreatePHPWorker(args, this.fileLockManager!)\n\t\t\t\t),\n\t\t};\n\t\tawait this.bootRequestHandler(requestHandlerOptions);\n\n\t\tconst primaryPhp = this.__internal_getPHP()!;\n\n\t\tif (args.mode === 'mount-only') {\n\t\t\tawait mountResources(primaryPhp, args.mountsAfterWpInstall || []);\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.runBlueprintV2({\n\t\t\t...args,\n\t\t\tmountsAfterWpInstall: args.mountsAfterWpInstall || [],\n\t\t});\n\t}\n\n\tasync bootWorker(args: SecondaryWorkerBootArgs) {\n\t\tawait this.bootRequestHandler({\n\t\t\t...args,\n\t\t\tonPHPInstanceCreated: async (php: PHP) => {\n\t\t\t\tawait mountResources(php, args.mountsBeforeWpInstall || []);\n\t\t\t\tawait mountResources(php, args.mountsAfterWpInstall || []);\n\n\t\t\t\t// Temporary workaround for LOCK_EX in sqlite-database-integration.\n\t\t\t\t// Creation of these files results in this error:\n\t\t\t\t// PHP Warning: file_put_contents(): Exclusive locks are not supported for this stream\n\t\t\t\t// in\n\t\t\t\t// /wordpress/wp-content/plugins/sqlite-database-integration/wp-includes/sqlite/class-wp-sqlite-db.php\n\t\t\t\t// on line 670\n\t\t\t\tif (!php.isDir('/wordpress/wp-content')) {\n\t\t\t\t\tphp.mkdir('/wordpress/wp-content');\n\t\t\t\t}\n\t\t\t\tif (!php.isDir('/wordpress/wp-content/database')) {\n\t\t\t\t\tphp.mkdir('/wordpress/wp-content/database');\n\t\t\t\t}\n\t\t\t\tif (!php.isFile('/wordpress/wp-content/database/.htaccess')) {\n\t\t\t\t\tphp.writeFile(\n\t\t\t\t\t\t'/wordpress/wp-content/database/.htaccess',\n\t\t\t\t\t\t'deny from all'\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (!php.isFile('/wordpress/wp-content/database/index.php')) {\n\t\t\t\t\tphp.writeFile(\n\t\t\t\t\t\t'/wordpress/wp-content/database/index.php',\n\t\t\t\t\t\t'deny from all'\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t},\n\t\t\tspawnHandler: () =>\n\t\t\t\tsandboxedSpawnHandlerFactory(() =>\n\t\t\t\t\tcreatePHPWorker(args, this.fileLockManager!)\n\t\t\t\t),\n\t\t});\n\t}\n\n\tasync runBlueprintV2(args: WorkerRunBlueprintArgs) {\n\t\tconst requestHandler = this.__internal_getRequestHandler()!;\n\t\tconst { php, reap } =\n\t\t\tawait requestHandler.instanceManager.acquirePHPInstance();\n\n\t\t// Mount the current working directory to the PHP runtime for the purposes of\n\t\t// Blueprint resolution.\n\t\tconst primaryPhp = this.__internal_getPHP()!;\n\t\tlet unmountCwd = () => {};\n\t\tif (typeof args.blueprint === 'string') {\n\t\t\tconst blueprintPath = path.resolve(process.cwd(), args.blueprint);\n\t\t\tif (existsSync(blueprintPath)) {\n\t\t\t\tprimaryPhp.mkdir('/internal/shared/cwd');\n\t\t\t\tunmountCwd = await primaryPhp.mount(\n\t\t\t\t\t'/internal/shared/cwd',\n\t\t\t\t\tcreateNodeFsMountHandler(path.dirname(blueprintPath))\n\t\t\t\t);\n\t\t\t\targs.blueprint = path.join(\n\t\t\t\t\t'/internal/shared/cwd',\n\t\t\t\t\tpath.basename(args.blueprint)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\tconst cliArgsToPass: (keyof WorkerRunBlueprintArgs)[] = [\n\t\t\t\t'mode',\n\t\t\t\t'db-engine',\n\t\t\t\t'db-host',\n\t\t\t\t'db-user',\n\t\t\t\t'db-pass',\n\t\t\t\t'db-name',\n\t\t\t\t'db-path',\n\t\t\t\t'truncate-new-site-directory',\n\t\t\t\t'allow',\n\t\t\t];\n\t\t\tconst cliArgs = cliArgsToPass\n\t\t\t\t.filter((arg) => arg in args)\n\t\t\t\t.map((arg) => `--${arg}=${args[arg]}`);\n\t\t\tcliArgs.push(`--site-url=${args.siteUrl}`);\n\n\t\t\tconst streamedResponse = await runBlueprintV2({\n\t\t\t\tphp,\n\t\t\t\tblueprint: args.blueprint,\n\t\t\t\tblueprintOverrides: {\n\t\t\t\t\tadditionalSteps: args['additional-blueprint-steps'],\n\t\t\t\t\twordpressVersion: args.wp,\n\t\t\t\t},\n\t\t\t\tcliArgs,\n\t\t\t\tonMessage: async (message: BlueprintMessage) => {\n\t\t\t\t\tswitch (message.type) {\n\t\t\t\t\t\tcase 'blueprint.target_resolved': {\n\t\t\t\t\t\t\tif (!this.blueprintTargetResolved) {\n\t\t\t\t\t\t\t\tthis.blueprintTargetResolved = true;\n\t\t\t\t\t\t\t\tfor (const php of this\n\t\t\t\t\t\t\t\t\t.phpInstancesThatNeedMountsAfterTargetResolved) {\n\t\t\t\t\t\t\t\t\t// console.log('mounting resources for php', php);\n\t\t\t\t\t\t\t\t\tthis.phpInstancesThatNeedMountsAfterTargetResolved.delete(\n\t\t\t\t\t\t\t\t\t\tphp\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\tawait mountResources(\n\t\t\t\t\t\t\t\t\t\tphp,\n\t\t\t\t\t\t\t\t\t\targs.mountsAfterWpInstall || []\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 'blueprint.progress': {\n\t\t\t\t\t\t\tconst progressMessage = `${message.caption.trim()} – ${message.progress.toFixed(\n\t\t\t\t\t\t\t\t2\n\t\t\t\t\t\t\t)}%`;\n\t\t\t\t\t\t\toutput.progress(progressMessage);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 'blueprint.error': {\n\t\t\t\t\t\t\tconst red = '\\x1b[31m';\n\t\t\t\t\t\t\tconst bold = '\\x1b[1m';\n\t\t\t\t\t\t\tconst reset = '\\x1b[0m';\n\t\t\t\t\t\t\tif (args.verbosity === 'debug' && message.details) {\n\t\t\t\t\t\t\t\toutput.stderr(\n\t\t\t\t\t\t\t\t\t`${red}${bold}Fatal error:${reset} Uncaught ${message.details.exception}: ${message.details.message}\\n` +\n\t\t\t\t\t\t\t\t\t\t` at ${message.details.file}:${message.details.line}\\n` +\n\t\t\t\t\t\t\t\t\t\t(message.details.trace\n\t\t\t\t\t\t\t\t\t\t\t? message.details.trace + '\\n'\n\t\t\t\t\t\t\t\t\t\t\t: '')\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\toutput.stderr(\n\t\t\t\t\t\t\t\t\t`${red}${bold}Error:${reset} ${message.message}\\n`\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t});\n\t\t\t/**\n\t\t\t * When we're debugging, every bit of information matters – let's immediately output\n\t\t\t * everything we get from the PHP output streams.\n\t\t\t */\n\t\t\tif (args.verbosity === 'debug') {\n\t\t\t\tstreamedResponse!.stdout.pipeTo(\n\t\t\t\t\tnew WritableStream({\n\t\t\t\t\t\twrite(chunk) {\n\t\t\t\t\t\t\tprocess.stdout.write(chunk);\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t);\n\t\t\t\tstreamedResponse!.stderr.pipeTo(\n\t\t\t\t\tnew WritableStream({\n\t\t\t\t\t\twrite(chunk) {\n\t\t\t\t\t\t\tprocess.stderr.write(chunk);\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t);\n\t\t\t}\n\t\t\tawait streamedResponse!.finished;\n\t\t\tif ((await streamedResponse!.exitCode) !== 0) {\n\t\t\t\t// exitCode != 1 means the blueprint execution failed. Let's throw an error.\n\t\t\t\t// and clean up.\n\t\t\t\tconst syncResponse =\n\t\t\t\t\tawait PHPResponse.fromStreamedResponse(streamedResponse);\n\t\t\t\tthrow new PHPExecutionFailureError(\n\t\t\t\t\t`PHP.run() failed with exit code ${syncResponse.exitCode}. ${syncResponse.errors} ${syncResponse.text}`,\n\t\t\t\t\tsyncResponse,\n\t\t\t\t\t'request'\n\t\t\t\t);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// Capture the PHP error log details to provide more context for debugging.\n\t\t\tlet phpLogs = '';\n\t\t\ttry {\n\t\t\t\t// @TODO: Don't assume errorLogPath starts with /wordpress/\n\t\t\t\t// ...or maybe we can assume that in Playground CLI?\n\t\t\t\tphpLogs = php.readFileAsText(errorLogPath);\n\t\t\t} catch {\n\t\t\t\t// Ignore errors reading the PHP error log.\n\t\t\t}\n\t\t\t(error as any).phpLogs = phpLogs;\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\treap();\n\t\t\tunmountCwd();\n\t\t}\n\t}\n\n\tasync bootRequestHandler({\n\t\tsiteUrl,\n\t\tallow,\n\t\tphpVersion,\n\t\tcreateFiles,\n\t\tconstants,\n\t\tphpIniEntries,\n\t\tfirstProcessId,\n\t\tprocessIdSpaceLength,\n\t\ttrace,\n\t\tnativeInternalDirPath,\n\t\twithIntl,\n\t\twithRedis,\n\t\twithMemcached,\n\t\twithXdebug,\n\t\tpathAliases,\n\t\tonPHPInstanceCreated,\n\t\tspawnHandler,\n\t}: WorkerBootRequestHandlerOptions) {\n\t\tif (this.booted) {\n\t\t\tthrow new Error('Playground already booted');\n\t\t}\n\t\tthis.booted = true;\n\n\t\tlet nextProcessId = firstProcessId;\n\t\tconst lastProcessId = firstProcessId + processIdSpaceLength - 1;\n\n\t\ttry {\n\t\t\tconst requestHandler = await bootRequestHandler({\n\t\t\t\tsiteUrl,\n\t\t\t\tcreatePhpRuntime: async () => {\n\t\t\t\t\tconst processId = nextProcessId;\n\n\t\t\t\t\tif (nextProcessId < lastProcessId) {\n\t\t\t\t\t\tnextProcessId++;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// We've reached the end of the process ID space. Start over.\n\t\t\t\t\t\tnextProcessId = firstProcessId;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn await loadNodeRuntime(phpVersion, {\n\t\t\t\t\t\temscriptenOptions: {\n\t\t\t\t\t\t\tfileLockManager: this.fileLockManager!,\n\t\t\t\t\t\t\tprocessId,\n\t\t\t\t\t\t\ttrace: trace ? tracePhpWasm : undefined,\n\t\t\t\t\t\t\tENV: {\n\t\t\t\t\t\t\t\tDOCROOT: '/wordpress',\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tphpWasmInitOptions: { nativeInternalDirPath },\n\t\t\t\t\t\t},\n\t\t\t\t\t\tfollowSymlinks: allow?.includes('follow-symlinks'),\n\t\t\t\t\t\twithIntl: withIntl,\n\t\t\t\t\t\twithRedis,\n\t\t\t\t\t\twithMemcached,\n\t\t\t\t\t\twithXdebug,\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\tmaxPhpInstances: 1,\n\t\t\t\tonPHPInstanceCreated,\n\t\t\t\tsapiName: 'cli',\n\t\t\t\tcreateFiles,\n\t\t\t\tconstants,\n\t\t\t\tphpIniEntries,\n\t\t\t\tpathAliases,\n\t\t\t\tcookieStore: false,\n\t\t\t\tspawnHandler,\n\t\t\t});\n\t\t\tthis.__internal_setRequestHandler(requestHandler);\n\n\t\t\tconst primaryPhp = await requestHandler.getPrimaryPhp();\n\t\t\tawait this.setPrimaryPHP(primaryPhp);\n\n\t\t\tsetApiReady();\n\t\t} catch (e) {\n\t\t\tsetAPIError(e as Error);\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\t// Provide a named disposal method that can be invoked via comlink.\n\tasync dispose() {\n\t\tawait this[Symbol.asyncDispose]();\n\t}\n}\n\n/**\n * Spawns a new PHP process to be used in the PHP spawn handler (in proc_open() etc. calls).\n * It boots from this worker-thread-v1.ts file, but is a separate process.\n *\n * We explicitly avoid using PHPProcessManager.acquirePHPInstance() here.\n *\n * Why?\n *\n * Because each PHP instance acquires actual OS-level file locks via fcntl() and LockFileEx()\n * syscalls. Running multiple PHP instances from the same OS process would allow them to\n * acquire overlapping locks. Running every PHP instance in a separate OS process ensures\n * any locks that overlap between PHP instances conflict with each other as expected.\n *\n * @param options - The options for the worker.\n * @param fileLockManager - The file lock manager to use.\n * @returns A promise that resolves to the PHP worker.\n */\nasync function createPHPWorker(\n\t{\n\t\tsiteUrl,\n\t\tallow,\n\t\tphpVersion,\n\t\tcreateFiles,\n\t\tconstants,\n\t\tphpIniEntries,\n\t\tfirstProcessId,\n\t\tprocessIdSpaceLength,\n\t\ttrace,\n\t\tnativeInternalDirPath,\n\t\twithXdebug,\n\t\tpathAliases,\n\t\tmountsBeforeWpInstall,\n\t\tmountsAfterWpInstall,\n\t}: SecondaryWorkerBootArgs,\n\tfileLockManager: FileLockManager | RemoteAPI<FileLockManager>\n) {\n\tconst spawnedWorker = await spawnWorkerThread('v2');\n\n\tconst handler = consumeAPI<PlaygroundCliBlueprintV2Worker>(\n\t\tspawnedWorker.phpPort\n\t);\n\thandler.useFileLockManager(fileLockManager as any);\n\tawait handler.bootWorker({\n\t\tsiteUrl,\n\t\tallow,\n\t\tphpVersion,\n\t\tcreateFiles,\n\t\tconstants,\n\t\tphpIniEntries,\n\t\tfirstProcessId,\n\t\tprocessIdSpaceLength,\n\t\ttrace,\n\t\tnativeInternalDirPath,\n\t\twithXdebug,\n\t\tpathAliases,\n\t\tmountsBeforeWpInstall,\n\t\tmountsAfterWpInstall,\n\t});\n\n\treturn {\n\t\tphp: handler,\n\t\treap: () => {\n\t\t\ttry {\n\t\t\t\thandler.dispose();\n\t\t\t} catch {\n\t\t\t\t/** */\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tspawnedWorker.worker.terminate();\n\t\t\t} catch {\n\t\t\t\t/** */\n\t\t\t}\n\t\t},\n\t};\n}\n\nprocess.on('unhandledRejection', (e: any) => {\n\tlogger.error('Unhandled rejection:', e);\n});\n\nconst phpChannel = new MessageChannel();\n\nconst [setApiReady, setAPIError] = exposeAPI(\n\tnew PlaygroundCliBlueprintV2Worker(new EmscriptenDownloadMonitor()),\n\tundefined,\n\tphpChannel.port1\n);\n\nparentPort?.postMessage(\n\t{\n\t\tcommand: 'worker-script-initialized',\n\t\tphpPort: phpChannel.port2,\n\t},\n\t[phpChannel.port2 as any]\n);\n"],"names":["mountResources","php","mounts","mount","createNodeFsMountHandler","output","tracePhpWasm","processId","format","args","sprintf","data","shouldRenderProgress","PlaygroundCliBlueprintV2Worker","PHPWorker","monitor","port","jspi","consumeAPI","consumeAPISync","constants","requestHandlerOptions","rootCertificates","sandboxedSpawnHandlerFactory","createPHPWorker","primaryPhp","requestHandler","reap","unmountCwd","blueprintPath","path","existsSync","cliArgs","arg","streamedResponse","runBlueprintV2","message","progressMessage","red","bold","reset","chunk","syncResponse","PHPResponse","PHPExecutionFailureError","error","phpLogs","errorLogPath","siteUrl","allow","phpVersion","createFiles","phpIniEntries","firstProcessId","processIdSpaceLength","trace","nativeInternalDirPath","withIntl","withRedis","withMemcached","withXdebug","pathAliases","onPHPInstanceCreated","spawnHandler","nextProcessId","lastProcessId","bootRequestHandler","loadNodeRuntime","setApiReady","e","setAPIError","mountsBeforeWpInstall","mountsAfterWpInstall","fileLockManager","spawnedWorker","spawnWorkerThread","handler","logger","phpChannel","MessageChannel","exposeAPI","EmscriptenDownloadMonitor","parentPort"],"mappings":"8cA6CA,eAAeA,EAAeC,EAAUC,EAAiB,CACxD,UAAWC,KAASD,EACnB,GAAI,CACHD,EAAI,MAAME,EAAM,OAAO,EACvB,MAAMF,EAAI,MACTE,EAAM,QACNC,EAAAA,yBAAyBD,EAAM,QAAQ,CAAA,CAEzC,MAAQ,CACPE,EAAO,OACN,sCAAsCF,EAAM,QAAQ,OAAOA,EAAM,OAAO;AAAA,CAAA,EAEzE,QAAQ,KAAK,CAAC,CACf,CAEF,CASA,SAASG,EAAaC,EAAmBC,KAAmBC,EAAa,CAExE,QAAQ,IACP,YAAY,MAAM,QAAQ,CAAC,EAAE,SAAS,GAAI,GAAG,EAC7CF,EAAU,SAAA,EAAW,SAAS,GAAI,GAAG,EACrCG,EAAAA,QAAQF,EAAQ,GAAGC,CAAI,CAAA,CAEzB,CAWA,OAAO,eAAe,QAAQ,OAAQ,QAAS,CAAE,MAAO,GAAM,EAC9D,OAAO,eAAe,QAAQ,OAAQ,QAAS,CAAE,MAAO,GAAM,EAK9D,MAAMJ,EAAS,CACd,qBAAsB,GACtB,SAASM,EAAc,CACjBC,EAAAA,qBAAqB,QAAQ,MAAM,IAGnC,QAAQ,OAAO,OAIdP,EAAO,sBACX,QAAQ,OAAO,MAAM;AAAA,CAAI,EAE1B,QAAQ,OAAO,MAAM,WAAaM,CAAI,EACtCN,EAAO,qBAAuB,IAN9B,QAAQ,IAAIM,CAAI,EAQlB,EACA,OAAOA,EAAc,CACpB,QAAQ,OAAO,MAAM;AAAA;AAAA;AAAA,CAAQ,EACzBN,EAAO,uBACVA,EAAO,qBAAuB,IAE/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CACHF,EAAc,OAAO,UAAA,CACtB,MAAQ,CAER,CACD,CAAA,CAEF,CAEA,QAAQ,GAAG,qBAAuBL,GAAW,CAC5CQ,SAAO,MAAM,uBAAwBR,CAAC,CACvC,CAAC,EAED,MAAMS,EAAa,IAAIC,EAAAA,eAEjB,CAACX,EAAaE,CAAW,EAAIU,EAAAA,UAClC,IAAInE,EAA+B,IAAIoE,EAAAA,yBAA2B,EAClE,OACAH,EAAW,KACZ,EAEAI,EAAAA,YAAY,YACX,CACC,QAAS,4BACT,QAASJ,EAAW,KAAA,EAErB,CAACA,EAAW,KAAY,CACzB"}
1
+ {"version":3,"file":"worker-thread-v2.cjs","sources":["../../../../packages/playground/cli/src/blueprints-v2/worker-thread-v2.ts"],"sourcesContent":["import { errorLogPath, logger } from '@php-wasm/logger';\nimport type { FileLockManager } from '@php-wasm/universal';\nimport {\n\tbindUserSpace,\n\tcreateNodeFsMountHandler,\n\tloadNodeRuntime,\n\ttype WasmUserSpaceContext,\n} from '@php-wasm/node';\nimport { EmscriptenDownloadMonitor } from '@php-wasm/progress';\nimport type {\n\tPathAlias,\n\tPHP,\n\tFileTree,\n\tRemoteAPI,\n\tSupportedPHPVersion,\n\tSpawnHandler,\n} from '@php-wasm/universal';\nimport {\n\tPHPExecutionFailureError,\n\tPHPResponse,\n\tPHPWorker,\n\treleaseApiProxy,\n\tconsumeAPI,\n\tconsumeAPISync,\n\texposeAPI,\n\tsandboxedSpawnHandlerFactory,\n\tsetPhpIniEntries,\n\twriteFiles,\n} from '@php-wasm/universal';\nimport { joinPaths, sprintf } from '@php-wasm/util';\nimport {\n\ttype BlueprintMessage,\n\trunBlueprintV2,\n\ttype BlueprintV1Declaration,\n} from '@wp-playground/blueprints';\nimport {\n\ttype ParsedBlueprintV2String,\n\ttype RawBlueprintV2Data,\n} from '@wp-playground/blueprints';\nimport {\n\tbootRequestHandler,\n\tpreloadPhpInfoRoute,\n\tsetupPlatformLevelMuPlugins,\n} from '@wp-playground/wordpress';\nimport { existsSync } from 'fs';\nimport path from 'path';\nimport { rootCertificates } from 'tls';\nimport { MessageChannel, type MessagePort, parentPort } from 'worker_threads';\nimport { type RunCLIArgs, spawnWorkerThread } from '../run-cli';\nimport type {\n\tPhpIniOptions,\n\tPHPInstanceCreatedHook,\n} from '@wp-playground/wordpress';\nimport { shouldRenderProgress } from '../utils/progress';\nimport type { Mount } from '@php-wasm/cli-util';\n\nasync function mountResources(php: PHP, mounts: Mount[]) {\n\tfor (const mount of mounts) {\n\t\ttry {\n\t\t\tphp.mkdir(mount.vfsPath);\n\t\t\tawait php.mount(\n\t\t\t\tmount.vfsPath,\n\t\t\t\tcreateNodeFsMountHandler(mount.hostPath)\n\t\t\t);\n\t\t} catch {\n\t\t\toutput.stderr(\n\t\t\t\t`\\x1b[31m\\x1b[1mError mounting path ${mount.hostPath} at ${mount.vfsPath}\\x1b[0m\\n`\n\t\t\t);\n\t\t\tprocess.exit(1);\n\t\t}\n\t}\n}\n\n/**\n * Print trace messages from PHP-WASM.\n *\n * @param {number} processId - The process ID.\n * @param {string} format - The format string.\n * @param {...any} args - The arguments.\n */\nfunction tracePhpWasm(processId: number, format: string, ...args: any[]) {\n\t// eslint-disable-next-line no-console\n\tconsole.log(\n\t\tperformance.now().toFixed(6).padStart(15, '0'),\n\t\tprocessId.toString().padStart(16, '0'),\n\t\tsprintf(format, ...args)\n\t);\n}\n\n/**\n * Force TTY status to preserve ANSI control codes in the output\n * when the environment is interactive.\n *\n * This script is spawned as `new Worker()` and process.stdout and process.stderr are\n * WritableWorkerStdio objects. By default, they strip ANSI control codes from the output\n * causing every progress bar update to be printed in a new line instead of updating the\n * same line.\n */\nObject.defineProperty(process.stdout, 'isTTY', { value: true });\nObject.defineProperty(process.stderr, 'isTTY', { value: true });\n\n/**\n * Output writer that ensures that progress bars are not printed on the same line as other output.\n */\nconst output = {\n\tlastWriteWasProgress: false,\n\tprogress(data: string) {\n\t\tif (!shouldRenderProgress(process.stdout)) {\n\t\t\treturn;\n\t\t}\n\t\tif (!process.stdout.isTTY) {\n\t\t\t// eslint-disable-next-line no-console\n\t\t\tconsole.log(data);\n\t\t} else {\n\t\t\tif (!output.lastWriteWasProgress) {\n\t\t\t\tprocess.stdout.write('\\n');\n\t\t\t}\n\t\t\tprocess.stdout.write('\\r\\x1b[K' + data);\n\t\t\toutput.lastWriteWasProgress = true;\n\t\t}\n\t},\n\tstdout(data: string) {\n\t\tprocess.stdout.write('\\n\\n\\n');\n\t\tif (output.lastWriteWasProgress) {\n\t\t\toutput.lastWriteWasProgress = false;\n\t\t}\n\t\tprocess.stdout.write(data);\n\t},\n\tstderr(data: string) {\n\t\tprocess.stdout.write('\\n\\n\\n');\n\t\tif (output.lastWriteWasProgress) {\n\t\t\toutput.lastWriteWasProgress = false;\n\t\t}\n\t\tprocess.stderr.write(data);\n\t},\n};\n\nexport type WorkerWordPressBootArgs = Omit<\n\tRunCLIArgs,\n\t'mount-before-install' | 'mount'\n> & {\n\tsiteUrl: string;\n\tblueprint:\n\t\t| RawBlueprintV2Data\n\t\t| ParsedBlueprintV2String\n\t\t| BlueprintV1Declaration;\n};\n\ntype WorkerRunBlueprintArgs = Omit<\n\tRunCLIArgs,\n\t'mount-before-install' | 'mount'\n> & {\n\tsiteUrl: string;\n\tblueprint:\n\t\t| RawBlueprintV2Data\n\t\t| ParsedBlueprintV2String\n\t\t| BlueprintV1Declaration;\n\tmountsAfterWpInstall?: Array<Mount>;\n};\n\nexport type SecondaryWorkerBootArgs = {\n\tsiteUrl: string;\n\tallow?: string;\n\tphpVersion: SupportedPHPVersion;\n\tphpIniEntries?: PhpIniOptions;\n\tconstants?: Record<string, string | number | boolean | null>;\n\tcreateFiles?: FileTree;\n\tprocessId: number;\n\ttrace: boolean;\n\tnativeInternalDirPath: string;\n\twithIntl?: boolean;\n\twithRedis?: boolean;\n\twithMemcached?: boolean;\n\twithXdebug?: boolean;\n\tpathAliases?: PathAlias[];\n\tmountsBeforeWpInstall?: Array<Mount>;\n\tmountsAfterWpInstall?: Array<Mount>;\n};\n\nexport type WorkerBootRequestHandlerOptions = Omit<\n\tSecondaryWorkerBootArgs,\n\t'mountsBeforeWpInstall' | 'mountsAfterWpInstall'\n> & {\n\tonPHPInstanceCreated: PHPInstanceCreatedHook;\n\tspawnHandler: () => SpawnHandler;\n};\n\nexport class PlaygroundCliBlueprintV2Worker extends PHPWorker {\n\tbooted = false;\n\tblueprintTargetResolved = false;\n\tphpInstancesThatNeedMountsAfterTargetResolved = new Set<PHP>();\n\tfileLockManager: FileLockManager | undefined;\n\n\tconstructor(monitor: EmscriptenDownloadMonitor) {\n\t\tsuper(undefined, monitor);\n\t}\n\n\t/**\n\t * Call this method before boot() to use file locking.\n\t *\n\t * This method is separate from boot() to simplify the related Comlink.transferHandlers\n\t * setup – if an argument is a MessagePort, we're transferring it, not copying it.\n\t *\n\t * @see comlink-sync.ts\n\t * @see phpwasm-emscripten-library-file-locking-for-node.js\n\t */\n\tasync useFileLockManager(port: MessagePort) {\n\t\t/**\n\t\t * If JSPI is not available, php.js only supports synchronous locking syscalls.\n\t\t * Let's use the synchronous API. Every method call will block this thread\n\t\t * until the result is available.\n\t\t *\n\t\t * @see comlink-sync.ts\n\t\t * @see phpwasm-emscripten-library-file-locking-for-node.js\n\t\t */\n\t\tthis.fileLockManager = await consumeAPISync<FileLockManager>(port);\n\t}\n\n\tasync bootWordPress(\n\t\targs: WorkerWordPressBootArgs,\n\t\tworkerPostInstallMountsPort: MessagePort\n\t) {\n\t\t// TODO: Should we move a process like this back into the\n\t\t// `@wp-playground/wordpress` package?\n\t\tconst php = await this.__internal_getRequestHandler()!.getPrimaryPhp();\n\t\tphp.defineConstant('WP_DEBUG', 'true');\n\t\tphp.defineConstant('WP_DEBUG_LOG', 'true');\n\t\tphp.defineConstant('WP_DEBUG_DISPLAY', 'false');\n\t\tphp.defineConstant('WP_HOME', args.siteUrl);\n\t\tphp.defineConstant('WP_SITEURL', args.siteUrl);\n\n\t\tawait setPhpIniEntries(php, {\n\t\t\t'openssl.cafile': '/internal/shared/ca-bundle.crt',\n\t\t\tallow_url_fopen: '1',\n\t\t\tdisable_functions: '',\n\t\t});\n\n\t\tawait setupPlatformLevelMuPlugins(php);\n\t\tawait writeFiles(php, '/', {\n\t\t\t'/internal/shared/ca-bundle.crt': rootCertificates.join('\\n'),\n\t\t});\n\t\tawait preloadPhpInfoRoute(\n\t\t\tphp,\n\t\t\tjoinPaths(new URL(args.siteUrl).pathname, 'phpinfo.php')\n\t\t);\n\n\t\tif (args.mode === 'mount-only') {\n\t\t\tawait this.applyPostInstallMountsToAllWorkers(\n\t\t\t\tworkerPostInstallMountsPort\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.runBlueprintV2(\n\t\t\t{\n\t\t\t\t// TODO: Do we really want to create a new object or can we pass args directly?\n\t\t\t\t...args,\n\t\t\t},\n\t\t\tworkerPostInstallMountsPort\n\t\t);\n\t}\n\n\tasync bootWorker(args: SecondaryWorkerBootArgs) {\n\t\tawait this.bootRequestHandler({\n\t\t\t...args,\n\t\t\tonPHPInstanceCreated: async (php: PHP) => {\n\t\t\t\tawait mountResources(php, args.mountsBeforeWpInstall || []);\n\t\t\t\tawait mountResources(php, args.mountsAfterWpInstall || []);\n\n\t\t\t\t// Temporary workaround for LOCK_EX in sqlite-database-integration.\n\t\t\t\t// Creation of these files results in this error:\n\t\t\t\t// PHP Warning: file_put_contents(): Exclusive locks are not supported for this stream\n\t\t\t\t// in\n\t\t\t\t// /wordpress/wp-content/plugins/sqlite-database-integration/wp-includes/sqlite/class-wp-sqlite-db.php\n\t\t\t\t// on line 670\n\t\t\t\tif (!php.isDir('/wordpress/wp-content')) {\n\t\t\t\t\tphp.mkdir('/wordpress/wp-content');\n\t\t\t\t}\n\t\t\t\tif (!php.isDir('/wordpress/wp-content/database')) {\n\t\t\t\t\tphp.mkdir('/wordpress/wp-content/database');\n\t\t\t\t}\n\t\t\t\tif (!php.isFile('/wordpress/wp-content/database/.htaccess')) {\n\t\t\t\t\tphp.writeFile(\n\t\t\t\t\t\t'/wordpress/wp-content/database/.htaccess',\n\t\t\t\t\t\t'deny from all'\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (!php.isFile('/wordpress/wp-content/database/index.php')) {\n\t\t\t\t\tphp.writeFile(\n\t\t\t\t\t\t'/wordpress/wp-content/database/index.php',\n\t\t\t\t\t\t'deny from all'\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t},\n\t\t\tspawnHandler: () =>\n\t\t\t\tsandboxedSpawnHandlerFactory(() =>\n\t\t\t\t\tcreatePHPWorker(args, this.fileLockManager!)\n\t\t\t\t),\n\t\t});\n\t}\n\n\tasync runBlueprintV2(\n\t\targs: WorkerRunBlueprintArgs,\n\t\tworkerPostInstallMountsPort: MessagePort\n\t) {\n\t\tconst requestHandler = this.__internal_getRequestHandler()!;\n\t\tconst { php, reap } =\n\t\t\tawait requestHandler.instanceManager.acquirePHPInstance();\n\n\t\t// Mount the current working directory to the PHP runtime for the purposes of\n\t\t// Blueprint resolution.\n\t\tconst primaryPhp = this.__internal_getPHP()!;\n\t\tlet unmountCwd = () => {};\n\t\tif (typeof args.blueprint === 'string') {\n\t\t\tconst blueprintPath = path.resolve(process.cwd(), args.blueprint);\n\t\t\tif (existsSync(blueprintPath)) {\n\t\t\t\tprimaryPhp.mkdir('/internal/shared/cwd');\n\t\t\t\tunmountCwd = await primaryPhp.mount(\n\t\t\t\t\t'/internal/shared/cwd',\n\t\t\t\t\tcreateNodeFsMountHandler(path.dirname(blueprintPath))\n\t\t\t\t);\n\t\t\t\targs.blueprint = path.join(\n\t\t\t\t\t'/internal/shared/cwd',\n\t\t\t\t\tpath.basename(args.blueprint)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\tconst cliArgsToPass: (keyof WorkerRunBlueprintArgs)[] = [\n\t\t\t\t'mode',\n\t\t\t\t'db-engine',\n\t\t\t\t'db-host',\n\t\t\t\t'db-user',\n\t\t\t\t'db-pass',\n\t\t\t\t'db-name',\n\t\t\t\t'db-path',\n\t\t\t\t'truncate-new-site-directory',\n\t\t\t\t'allow',\n\t\t\t];\n\t\t\tconst cliArgs = cliArgsToPass\n\t\t\t\t.filter((arg) => arg in args)\n\t\t\t\t.map((arg) => `--${arg}=${args[arg]}`);\n\t\t\tcliArgs.push(`--site-url=${args.siteUrl}`);\n\n\t\t\tconst streamedResponse = await runBlueprintV2({\n\t\t\t\tphp,\n\t\t\t\tblueprint: args.blueprint,\n\t\t\t\tblueprintOverrides: {\n\t\t\t\t\tadditionalSteps: args['additional-blueprint-steps'],\n\t\t\t\t\twordpressVersion: args.wp,\n\t\t\t\t},\n\t\t\t\tcliArgs,\n\t\t\t\tonMessage: async (message: BlueprintMessage) => {\n\t\t\t\t\tswitch (message.type) {\n\t\t\t\t\t\tcase 'blueprint.target_resolved': {\n\t\t\t\t\t\t\tif (!this.blueprintTargetResolved) {\n\t\t\t\t\t\t\t\tthis.blueprintTargetResolved = true;\n\t\t\t\t\t\t\t\tawait this.applyPostInstallMountsToAllWorkers(\n\t\t\t\t\t\t\t\t\tworkerPostInstallMountsPort\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 'blueprint.progress': {\n\t\t\t\t\t\t\tconst progressMessage = `${message.caption.trim()} – ${message.progress.toFixed(\n\t\t\t\t\t\t\t\t2\n\t\t\t\t\t\t\t)}%`;\n\t\t\t\t\t\t\toutput.progress(progressMessage);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 'blueprint.error': {\n\t\t\t\t\t\t\tconst red = '\\x1b[31m';\n\t\t\t\t\t\t\tconst bold = '\\x1b[1m';\n\t\t\t\t\t\t\tconst reset = '\\x1b[0m';\n\t\t\t\t\t\t\tif (args.verbosity === 'debug' && message.details) {\n\t\t\t\t\t\t\t\toutput.stderr(\n\t\t\t\t\t\t\t\t\t`${red}${bold}Fatal error:${reset} Uncaught ${message.details.exception}: ${message.details.message}\\n` +\n\t\t\t\t\t\t\t\t\t\t` at ${message.details.file}:${message.details.line}\\n` +\n\t\t\t\t\t\t\t\t\t\t(message.details.trace\n\t\t\t\t\t\t\t\t\t\t\t? message.details.trace + '\\n'\n\t\t\t\t\t\t\t\t\t\t\t: '')\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\toutput.stderr(\n\t\t\t\t\t\t\t\t\t`${red}${bold}Error:${reset} ${message.message}\\n`\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t});\n\t\t\t/**\n\t\t\t * When we're debugging, every bit of information matters – let's immediately output\n\t\t\t * everything we get from the PHP output streams.\n\t\t\t */\n\t\t\tif (args.verbosity === 'debug') {\n\t\t\t\tstreamedResponse!.stdout.pipeTo(\n\t\t\t\t\tnew WritableStream({\n\t\t\t\t\t\twrite(chunk) {\n\t\t\t\t\t\t\tprocess.stdout.write(chunk);\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t);\n\t\t\t\tstreamedResponse!.stderr.pipeTo(\n\t\t\t\t\tnew WritableStream({\n\t\t\t\t\t\twrite(chunk) {\n\t\t\t\t\t\t\tprocess.stderr.write(chunk);\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t);\n\t\t\t}\n\t\t\tawait streamedResponse!.finished;\n\t\t\tif ((await streamedResponse!.exitCode) !== 0) {\n\t\t\t\t// exitCode != 1 means the blueprint execution failed. Let's throw an error.\n\t\t\t\t// and clean up.\n\t\t\t\tconst syncResponse =\n\t\t\t\t\tawait PHPResponse.fromStreamedResponse(streamedResponse);\n\t\t\t\tthrow new PHPExecutionFailureError(\n\t\t\t\t\t`PHP.run() failed with exit code ${syncResponse.exitCode}. ${syncResponse.errors} ${syncResponse.text}`,\n\t\t\t\t\tsyncResponse,\n\t\t\t\t\t'request'\n\t\t\t\t);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// Capture the PHP error log details to provide more context for debugging.\n\t\t\tlet phpLogs = '';\n\t\t\ttry {\n\t\t\t\t// @TODO: Don't assume errorLogPath starts with /wordpress/\n\t\t\t\t// ...or maybe we can assume that in Playground CLI?\n\t\t\t\tphpLogs = php.readFileAsText(errorLogPath);\n\t\t\t} catch {\n\t\t\t\t// Ignore errors reading the PHP error log.\n\t\t\t}\n\t\t\t(error as any).phpLogs = phpLogs;\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\treap();\n\t\t\tunmountCwd();\n\t\t}\n\t}\n\n\tasync bootRequestHandler({\n\t\tsiteUrl,\n\t\tallow,\n\t\tphpVersion,\n\t\tprocessId,\n\t\tcreateFiles,\n\t\tconstants,\n\t\tphpIniEntries,\n\t\ttrace,\n\t\tnativeInternalDirPath,\n\t\twithIntl,\n\t\twithRedis,\n\t\twithMemcached,\n\t\twithXdebug,\n\t\tpathAliases,\n\t\tonPHPInstanceCreated,\n\t\tspawnHandler,\n\t}: WorkerBootRequestHandlerOptions) {\n\t\tif (this.booted) {\n\t\t\tthrow new Error('Playground already booted');\n\t\t}\n\t\tthis.booted = true;\n\n\t\ttry {\n\t\t\tconst requestHandler = await bootRequestHandler({\n\t\t\t\tsiteUrl,\n\t\t\t\tcreatePhpRuntime: async () => {\n\t\t\t\t\treturn await loadNodeRuntime(phpVersion, {\n\t\t\t\t\t\tfileLockManager: this.fileLockManager!,\n\t\t\t\t\t\temscriptenOptions: {\n\t\t\t\t\t\t\tprocessId,\n\t\t\t\t\t\t\ttrace: trace ? tracePhpWasm : undefined,\n\t\t\t\t\t\t\tENV: {\n\t\t\t\t\t\t\t\tDOCROOT: '/wordpress',\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tnativeInternalDirPath,\n\t\t\t\t\t\t\tbindUserSpace: (\n\t\t\t\t\t\t\t\tuserSpaceContext: WasmUserSpaceContext\n\t\t\t\t\t\t\t) => {\n\t\t\t\t\t\t\t\treturn bindUserSpace(\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tfileLockManager: this.fileLockManager!,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tuserSpaceContext\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tfollowSymlinks: allow?.includes('follow-symlinks'),\n\t\t\t\t\t\twithIntl: withIntl,\n\t\t\t\t\t\twithRedis,\n\t\t\t\t\t\twithMemcached,\n\t\t\t\t\t\twithXdebug,\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\tmaxPhpInstances: 1,\n\t\t\t\tonPHPInstanceCreated,\n\t\t\t\tsapiName: 'cli',\n\t\t\t\tcreateFiles,\n\t\t\t\tconstants,\n\t\t\t\tphpIniEntries,\n\t\t\t\tpathAliases,\n\t\t\t\tcookieStore: false,\n\t\t\t\tspawnHandler,\n\t\t\t});\n\t\t\tthis.__internal_setRequestHandler(requestHandler);\n\n\t\t\tconst primaryPhp = await requestHandler.getPrimaryPhp();\n\t\t\tawait this.setPrimaryPHP(primaryPhp);\n\n\t\t\tsetApiReady();\n\t\t} catch (e) {\n\t\t\tsetAPIError(e as Error);\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\tasync mountAfterWordPressInstall(mounts: Array<Mount>) {\n\t\tawait mountResources(this.__internal_getPHP()!, mounts);\n\t}\n\n\tasync applyPostInstallMountsToAllWorkers(\n\t\tpostInstallMountsPort: MessagePort\n\t): Promise<void> {\n\t\tconst applyPostInstallMountsToAllWorkers = consumeAPI<\n\t\t\t() => Promise<void>\n\t\t>(postInstallMountsPort);\n\t\tawait applyPostInstallMountsToAllWorkers();\n\t\tapplyPostInstallMountsToAllWorkers[releaseApiProxy]();\n\t}\n\n\t// Provide a named disposal method that can be invoked via comlink.\n\tasync dispose() {\n\t\tawait this[Symbol.asyncDispose]();\n\t}\n}\n\n/**\n * Spawns a new PHP process to be used in the PHP spawn handler (in proc_open() etc. calls).\n * It boots from this worker-thread-v1.ts file, but is a separate process.\n *\n * We explicitly avoid using PHPProcessManager.acquirePHPInstance() here.\n *\n * Why?\n *\n * Because each PHP instance acquires actual OS-level file locks via fcntl() and LockFileEx()\n * syscalls. Running multiple PHP instances from the same OS process would allow them to\n * acquire overlapping locks. Running every PHP instance in a separate OS process ensures\n * any locks that overlap between PHP instances conflict with each other as expected.\n *\n * @param options - The options for the worker.\n * @param fileLockManager - The file lock manager to use.\n * @returns A promise that resolves to the PHP worker.\n */\nasync function createPHPWorker(\n\t{\n\t\tsiteUrl,\n\t\tallow,\n\t\tphpVersion,\n\t\tcreateFiles,\n\t\tconstants,\n\t\tphpIniEntries,\n\t\ttrace,\n\t\tnativeInternalDirPath,\n\t\twithXdebug,\n\t\tpathAliases,\n\t\tmountsBeforeWpInstall,\n\t\tmountsAfterWpInstall,\n\t}: // NOTE: We explicitly remove processId from the options\n\t// type so the type system will catch if we try to reuse\n\t// our parent's process ID.\n\tOmit<SecondaryWorkerBootArgs, 'processId'>,\n\tfileLockManager: FileLockManager | RemoteAPI<FileLockManager>\n) {\n\tconst spawnedWorker = await spawnWorkerThread('v2');\n\n\tconst handler = consumeAPI<PlaygroundCliBlueprintV2Worker>(\n\t\tspawnedWorker.phpPort\n\t);\n\thandler.useFileLockManager(fileLockManager as any);\n\tawait handler.bootWorker({\n\t\tsiteUrl,\n\t\tallow,\n\t\tphpVersion,\n\t\tcreateFiles,\n\t\tconstants,\n\t\tphpIniEntries,\n\t\tprocessId: spawnedWorker.processId,\n\t\ttrace,\n\t\tnativeInternalDirPath,\n\t\twithXdebug,\n\t\tpathAliases,\n\t\tmountsBeforeWpInstall,\n\t\tmountsAfterWpInstall,\n\t});\n\n\treturn {\n\t\tphp: handler,\n\t\treap: () => {\n\t\t\ttry {\n\t\t\t\thandler.dispose();\n\t\t\t} catch {\n\t\t\t\t/** */\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tspawnedWorker.worker.terminate();\n\t\t\t} catch {\n\t\t\t\t/** */\n\t\t\t}\n\t\t},\n\t};\n}\n\nprocess.on('unhandledRejection', (e: any) => {\n\tlogger.error('Unhandled rejection:', e);\n});\n\nconst phpChannel = new MessageChannel();\n\nconst [setApiReady, setAPIError] = exposeAPI(\n\tnew PlaygroundCliBlueprintV2Worker(new EmscriptenDownloadMonitor()),\n\tundefined,\n\tphpChannel.port1\n);\n\nparentPort?.postMessage(\n\t{\n\t\tcommand: 'worker-script-initialized',\n\t\tphpPort: phpChannel.port2,\n\t},\n\t[phpChannel.port2 as any]\n);\n"],"names":["mountResources","php","mounts","mount","createNodeFsMountHandler","output","tracePhpWasm","processId","format","args","sprintf","data","shouldRenderProgress","PlaygroundCliBlueprintV2Worker","PHPWorker","monitor","port","consumeAPISync","workerPostInstallMountsPort","setPhpIniEntries","setupPlatformLevelMuPlugins","writeFiles","rootCertificates","preloadPhpInfoRoute","joinPaths","sandboxedSpawnHandlerFactory","createPHPWorker","requestHandler","reap","primaryPhp","unmountCwd","blueprintPath","path","existsSync","cliArgs","arg","streamedResponse","runBlueprintV2","message","progressMessage","red","bold","reset","chunk","syncResponse","PHPResponse","PHPExecutionFailureError","error","phpLogs","errorLogPath","siteUrl","allow","phpVersion","createFiles","constants","phpIniEntries","trace","nativeInternalDirPath","withIntl","withRedis","withMemcached","withXdebug","pathAliases","onPHPInstanceCreated","spawnHandler","bootRequestHandler","loadNodeRuntime","userSpaceContext","bindUserSpace","setApiReady","e","setAPIError","postInstallMountsPort","applyPostInstallMountsToAllWorkers","consumeAPI","releaseApiProxy","mountsBeforeWpInstall","mountsAfterWpInstall","fileLockManager","spawnedWorker","spawnWorkerThread","handler","logger","phpChannel","MessageChannel","exposeAPI","EmscriptenDownloadMonitor","parentPort"],"mappings":"6aAwDA,eAAeA,EAAeC,EAAUC,EAAiB,CACxD,UAAWC,KAASD,EACnB,GAAI,CACHD,EAAI,MA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