@wp-playground/cli 1.2.3 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/blueprints-BQYAZ9gc.js +9 -0
  2. package/blueprints-BQYAZ9gc.js.map +1 -0
  3. package/blueprints-DLntJtVr.js +9 -0
  4. package/blueprints-DLntJtVr.js.map +1 -0
  5. package/blueprints-ZBrY1bvK.cjs +2 -0
  6. package/blueprints-ZBrY1bvK.cjs.map +1 -0
  7. package/blueprints-v1/blueprints-v1-handler.d.ts +31 -0
  8. package/{worker-thread.d.ts → blueprints-v1/worker-thread-v1.d.ts} +4 -3
  9. package/blueprints-v2/blueprint-v2-declaration.d.ts +10 -0
  10. package/blueprints-v2/blueprints-v2-handler.d.ts +31 -0
  11. package/blueprints-v2/get-v2-runner.d.ts +1 -0
  12. package/{v2.d.ts → blueprints-v2/run-blueprint-v2.d.ts} +1 -11
  13. package/blueprints-v2/worker-thread-v2.d.ts +49 -0
  14. package/cli.cjs +1 -1
  15. package/cli.cjs.map +1 -1
  16. package/cli.js +2 -4
  17. package/cli.js.map +1 -1
  18. package/index.cjs +1 -1
  19. package/index.js +1 -1
  20. package/load-balancer.d.ts +3 -1
  21. package/package.json +11 -11
  22. package/run-cli-BaODvNPu.cjs +27 -0
  23. package/run-cli-BaODvNPu.cjs.map +1 -0
  24. package/run-cli-JA8jNok0.js +685 -0
  25. package/run-cli-JA8jNok0.js.map +1 -0
  26. package/run-cli.d.ts +27 -5
  27. package/{worker-thread-CYvRK9UX.js → worker-thread-v1-BTJIbQLy.js} +47 -44
  28. package/worker-thread-v1-BTJIbQLy.js.map +1 -0
  29. package/worker-thread-v1.cjs +3 -0
  30. package/worker-thread-v1.cjs.map +1 -0
  31. package/{worker-thread.js → worker-thread-v1.js} +34 -31
  32. package/worker-thread-v1.js.map +1 -0
  33. package/worker-thread-v2-Pfv6UYF4.js +429 -0
  34. package/worker-thread-v2-Pfv6UYF4.js.map +1 -0
  35. package/worker-thread-v2.cjs +92 -0
  36. package/worker-thread-v2.cjs.map +1 -0
  37. package/worker-thread-v2.js +432 -0
  38. package/worker-thread-v2.js.map +1 -0
  39. package/reportable-error.d.ts +0 -5
  40. package/run-cli-B5BfXxxJ.cjs +0 -24
  41. package/run-cli-B5BfXxxJ.cjs.map +0 -1
  42. package/run-cli-W9VNXESj.js +0 -586
  43. package/run-cli-W9VNXESj.js.map +0 -1
  44. package/worker-thread-CYvRK9UX.js.map +0 -1
  45. package/worker-thread.cjs +0 -3
  46. package/worker-thread.cjs.map +0 -1
  47. package/worker-thread.js.map +0 -1
  48. /package/{download.d.ts → blueprints-v1/download.d.ts} +0 -0
  49. /package/{server.d.ts → start-server.d.ts} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-cli-JA8jNok0.js","sources":["../../../../packages/playground/cli/src/start-server.ts","../../../../packages/playground/cli/src/load-balancer.ts","../../../../packages/playground/cli/src/is-valid-wordpress-slug.ts","../../../../packages/playground/cli/src/resolve-blueprint.ts","../../../../packages/playground/cli/src/blueprints-v2/blueprints-v2-handler.ts","../../../../packages/playground/cli/src/blueprints-v1/download.ts","../../../../packages/playground/cli/src/blueprints-v1/blueprints-v1-handler.ts","../../../../packages/playground/cli/src/run-cli.ts"],"sourcesContent":["import type { PHPRequest, PHPResponse } from '@php-wasm/universal';\nimport type { Request } from 'express';\nimport express from 'express';\nimport type { IncomingMessage, Server, ServerResponse } from 'http';\nimport type { AddressInfo } from 'net';\nimport type { RunCLIServer } from './run-cli';\n\nexport interface ServerOptions {\n\tport: number;\n\tonBind: (server: Server, port: number) => Promise<RunCLIServer>;\n\thandleRequest: (request: PHPRequest) => Promise<PHPResponse>;\n}\n\nexport async function startServer(\n\toptions: ServerOptions\n): Promise<RunCLIServer> {\n\tconst app = express();\n\n\tconst server = await new Promise<\n\t\tServer<typeof IncomingMessage, typeof ServerResponse>\n\t>((resolve, reject) => {\n\t\tconst server = app.listen(options.port, () => {\n\t\t\tconst address = server.address();\n\t\t\tif (address === null || typeof address === 'string') {\n\t\t\t\treject(new Error('Server address is not available'));\n\t\t\t} else {\n\t\t\t\tresolve(server);\n\t\t\t}\n\t\t});\n\t});\n\n\tapp.use('/', async (req, res) => {\n\t\tconst phpResponse = await options.handleRequest({\n\t\t\turl: req.url,\n\t\t\theaders: parseHeaders(req),\n\t\t\tmethod: req.method as any,\n\t\t\tbody: await bufferRequestBody(req),\n\t\t});\n\n\t\tres.statusCode = phpResponse.httpStatusCode;\n\t\tfor (const key in phpResponse.headers) {\n\t\t\tres.setHeader(key, phpResponse.headers[key]);\n\t\t}\n\t\tres.end(phpResponse.bytes);\n\t});\n\n\tconst address = server.address();\n\tconst port = (address! as AddressInfo).port;\n\treturn await options.onBind(server, port);\n}\n\nconst bufferRequestBody = async (req: Request): Promise<Uint8Array> =>\n\tawait new Promise((resolve) => {\n\t\tconst body: Uint8Array[] = [];\n\t\treq.on('data', (chunk) => {\n\t\t\tbody.push(chunk);\n\t\t});\n\t\treq.on('end', () => {\n\t\t\tresolve(new Uint8Array(Buffer.concat(body)));\n\t\t});\n\t});\n\nconst parseHeaders = (req: Request): Record<string, string> => {\n\tconst requestHeaders: Record<string, string> = {};\n\tif (req.rawHeaders && req.rawHeaders.length) {\n\t\tfor (let i = 0; i < req.rawHeaders.length; i += 2) {\n\t\t\trequestHeaders[req.rawHeaders[i].toLowerCase()] =\n\t\t\t\treq.rawHeaders[i + 1];\n\t\t}\n\t}\n\treturn requestHeaders;\n};\n","import type { PHPRequest, PHPResponse, RemoteAPI } from '@php-wasm/universal';\nimport type { PlaygroundCliBlueprintV1Worker as PlaygroundCliWorkerV1 } from './blueprints-v1/worker-thread-v1';\nimport type { PlaygroundCliBlueprintV2Worker as PlaygroundCliWorkerV2 } from './blueprints-v2/worker-thread-v2';\n\ntype PlaygroundCliWorker = PlaygroundCliWorkerV1 | PlaygroundCliWorkerV2;\n\n// TODO: Let's merge worker management into PHPProcessManager\n// when we can have multiple workers in both CLI and web.\n// ¡ATTENTION!:Please don't expand upon this as an independent abstraction.\n\n// TODO: Could we just spawn a worker using the factory function to PHPProcessManager?\ntype WorkerLoad = {\n\tworker: RemoteAPI<PlaygroundCliWorker>;\n\tactiveRequests: Set<Promise<PHPResponse>>;\n};\nexport class LoadBalancer {\n\tworkerLoads: WorkerLoad[] = [];\n\n\tconstructor(\n\t\t// NOTE: We require a worker to start so that a load balancer\n\t\t// may not exist without being able to service requests.\n\t\t// Playground CLI initialization, as of 2025-06-11, requires that\n\t\t// an initial worker is booted alone and initialized via Blueprint\n\t\t// before additional workers are created based on the initialized worker.\n\t\tinitialWorker: RemoteAPI<PlaygroundCliWorker>\n\t) {\n\t\tthis.addWorker(initialWorker);\n\t}\n\n\taddWorker(worker: RemoteAPI<PlaygroundCliWorker>) {\n\t\tthis.workerLoads.push({\n\t\t\tworker,\n\t\t\tactiveRequests: new Set(),\n\t\t});\n\t}\n\n\tasync handleRequest(request: PHPRequest) {\n\t\tlet smallestWorkerLoad = this.workerLoads[0];\n\n\t\t// TODO: Is there any way for us to track CPU load so we could avoid\n\t\t// picking a worker that is under heavy load despite few requests?\n\t\t// Possibly this: https://nodejs.org/api/worker_threads.html#workerperformance\n\t\t// Though we probably don't need to worry about it.\n\t\tfor (let i = 1; i < this.workerLoads.length; i++) {\n\t\t\tconst workerLoad = this.workerLoads[i];\n\t\t\tif (\n\t\t\t\tworkerLoad.activeRequests.size <\n\t\t\t\tsmallestWorkerLoad.activeRequests.size\n\t\t\t) {\n\t\t\t\tsmallestWorkerLoad = workerLoad;\n\t\t\t}\n\t\t}\n\n\t\t// TODO: Add trace facility to Playground CLI to observe internals like request routing.\n\n\t\tconst promiseForResponse = smallestWorkerLoad.worker.request(request);\n\t\tsmallestWorkerLoad.activeRequests.add(promiseForResponse);\n\n\t\t// Add URL to promise for use while debugging\n\t\t(promiseForResponse as any).url = request.url;\n\n\t\treturn promiseForResponse.finally(() => {\n\t\t\tsmallestWorkerLoad.activeRequests.delete(promiseForResponse);\n\t\t});\n\t}\n}\n","/**\n * Checks if the given version string is a valid WordPress version.\n *\n * The Regex is based on the releases on https://wordpress.org/download/releases/#betas\n * The version string can be one of the following formats:\n * - \"latest\"\n * - \"trunk\"\n * - \"nightly\"\n * - \"x.y\" (x and y are integers) e.g. \"6.2\"\n * - \"x.y.z\" (x, y and z are integers) e.g. \"6.2.1\"\n * - \"x.y.z-betaN\" (N is an integer) e.g. \"6.2.1-beta1\"\n * - \"x.y.z-RCN\" (N is an integer) e.g. \"6.2-RC1\"\n *\n * @param version The version string to check.\n * @returns A boolean value indicating whether the version string is a valid WordPress version.\n */\nexport function isValidWordPressSlug(version: string): boolean {\n\tconst versionPattern =\n\t\t/^latest$|^trunk$|^nightly$|^(?:(\\d+)\\.(\\d+)(?:\\.(\\d+))?)((?:-beta(?:\\d+)?)|(?:-RC(?:\\d+)?))?$/;\n\treturn versionPattern.test(version);\n}\n","import fs from 'fs';\nimport path from 'path';\nimport {\n\tZipFilesystem,\n\tNodeJsFilesystem,\n\tOverlayFilesystem,\n\tInMemoryFilesystem,\n} from '@wp-playground/storage';\nimport { resolveRemoteBlueprint } from '@wp-playground/blueprints';\n\ntype ResolveBlueprintOptions = {\n\tsourceString: string | undefined;\n\tblueprintMayReadAdjacentFiles: boolean;\n};\n\n/**\n * Resolves a blueprint from a URL or a local path.\n *\n * @TODO: Extract the common Blueprint resolution logic between CLI and\n * the website into a single, isomorphic resolveBlueprint() function.\n * Still retain the CLI-specific bits in the CLI package.\n *\n * @param sourceString - The source string to resolve the blueprint from.\n * @param blueprintMayReadAdjacentFiles - Whether the blueprint may read adjacent files.\n * @returns The resolved blueprint.\n */\nexport async function resolveBlueprint({\n\tsourceString,\n\tblueprintMayReadAdjacentFiles,\n}: ResolveBlueprintOptions) {\n\tif (!sourceString) {\n\t\treturn undefined;\n\t}\n\n\tif (\n\t\tsourceString.startsWith('http://') ||\n\t\tsourceString.startsWith('https://')\n\t) {\n\t\treturn await resolveRemoteBlueprint(sourceString);\n\t}\n\n\t// If the sourceString does not refer to a remote blueprint, try to\n\t// resolve it from a local filesystem.\n\n\tlet blueprintPath = path.resolve(process.cwd(), sourceString);\n\tif (!fs.existsSync(blueprintPath)) {\n\t\tthrow new Error(`Blueprint file does not exist: ${blueprintPath}`);\n\t}\n\n\tconst stat = fs.statSync(blueprintPath);\n\tif (stat.isDirectory()) {\n\t\tblueprintPath = path.join(blueprintPath, 'blueprint.json');\n\t}\n\n\tif (!stat.isFile() && stat.isSymbolicLink()) {\n\t\tthrow new Error(\n\t\t\t`Blueprint path is neither a file nor a directory: ${blueprintPath}`\n\t\t);\n\t}\n\n\tconst extension = path.extname(blueprintPath);\n\tswitch (extension) {\n\t\tcase '.zip':\n\t\t\treturn ZipFilesystem.fromArrayBuffer(\n\t\t\t\tfs.readFileSync(blueprintPath).buffer as ArrayBuffer\n\t\t\t);\n\t\tcase '.json': {\n\t\t\tconst blueprintText = fs.readFileSync(blueprintPath, 'utf-8');\n\t\t\ttry {\n\t\t\t\tJSON.parse(blueprintText);\n\t\t\t} catch {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Blueprint file at ${blueprintPath} is not a valid JSON file`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst contextPath = path.dirname(blueprintPath);\n\t\t\tconst nodeJsFilesystem = new NodeJsFilesystem(contextPath);\n\t\t\treturn new OverlayFilesystem([\n\t\t\t\tnew InMemoryFilesystem({\n\t\t\t\t\t'blueprint.json': blueprintText,\n\t\t\t\t}),\n\t\t\t\t/**\n\t\t\t\t * Wrap the NodeJS filesystem to prevent access to local files\n\t\t\t\t * unless the user explicitly allowed it.\n\t\t\t\t */\n\t\t\t\t{\n\t\t\t\t\tread(path) {\n\t\t\t\t\t\tif (!blueprintMayReadAdjacentFiles) {\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t`Error: Blueprint contained tried to read a local file at path \"${path}\" (via a resource of type \"bundled\"). ` +\n\t\t\t\t\t\t\t\t\t`Playground restricts access to local resources by default as a security measure. \\n\\n` +\n\t\t\t\t\t\t\t\t\t`You can allow this Blueprint to read files from the same parent directory by explicitly adding the ` +\n\t\t\t\t\t\t\t\t\t`--blueprint-may-read-adjacent-files option to your command.`\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn nodeJsFilesystem.read(path);\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t]);\n\t\t}\n\t\tdefault:\n\t\t\tthrow new Error(\n\t\t\t\t`Unsupported blueprint file extension: ${extension}. Only .zip and .json files are supported.`\n\t\t\t);\n\t}\n}\n","import type { RemoteAPI, SupportedPHPVersion } from '@php-wasm/universal';\nimport { consumeAPI } from '@php-wasm/universal';\nimport type {\n\tPlaygroundCliBlueprintV2Worker,\n\tWorkerBootArgs,\n} from './worker-thread-v2';\n// @ts-ignore\nimport importedWorkerV2UrlString from './worker-thread-v2?worker&url';\nimport type { MessagePort as NodeMessagePort } from 'worker_threads';\nimport type { RunCLIArgs, SpawnedWorker } from '../run-cli';\n\n/**\n * Boots Playground CLI workers using Blueprint version 2.\n *\n * Progress tracking, downloads, steps, and all other features are\n * implemented in PHP and orchestrated by the worker thread.\n */\nexport class BlueprintsV2Handler {\n\tprivate phpVersion: SupportedPHPVersion;\n\tprivate lastProgressMessage = '';\n\n\tprivate siteUrl: string;\n\tprivate processIdSpaceLength: number;\n\tprivate args: RunCLIArgs;\n\n\tconstructor(\n\t\targs: RunCLIArgs,\n\t\toptions: {\n\t\t\tsiteUrl: string;\n\t\t\tprocessIdSpaceLength: number;\n\t\t}\n\t) {\n\t\tthis.args = args;\n\t\tthis.siteUrl = options.siteUrl;\n\t\tthis.processIdSpaceLength = options.processIdSpaceLength;\n\t\tthis.phpVersion = args.php as SupportedPHPVersion;\n\t}\n\n\tgetWorkerUrl() {\n\t\treturn importedWorkerV2UrlString;\n\t}\n\n\tasync bootPrimaryWorker(\n\t\tphpPort: NodeMessagePort,\n\t\tfileLockManagerPort: NodeMessagePort\n\t) {\n\t\tconst playground: RemoteAPI<PlaygroundCliBlueprintV2Worker> =\n\t\t\tconsumeAPI(phpPort);\n\n\t\tawait playground.useFileLockManager(fileLockManagerPort);\n\n\t\tconst workerBootArgs = {\n\t\t\t...this.args,\n\t\t\tphp: this.phpVersion,\n\t\t\tsiteUrl: this.siteUrl,\n\t\t\tfirstProcessId: 1,\n\t\t\tprocessIdSpaceLength: this.processIdSpaceLength,\n\t\t\ttrace: this.args.debug || false,\n\t\t\tblueprint: this.args.blueprint!,\n\t\t};\n\n\t\tawait playground.bootAsPrimaryWorker(workerBootArgs);\n\t\treturn playground;\n\t}\n\n\tasync bootSecondaryWorker({\n\t\tworker,\n\t\tfileLockManagerPort,\n\t\tfirstProcessId,\n\t}: {\n\t\tworker: SpawnedWorker;\n\t\tfileLockManagerPort: NodeMessagePort;\n\t\tfirstProcessId: number;\n\t}) {\n\t\tconst playground: RemoteAPI<PlaygroundCliBlueprintV2Worker> =\n\t\t\tconsumeAPI(worker.phpPort);\n\n\t\tawait playground.useFileLockManager(fileLockManagerPort);\n\n\t\tconst workerBootArgs: WorkerBootArgs = {\n\t\t\t...this.args,\n\t\t\tphp: this.phpVersion!,\n\t\t\tsiteUrl: this.siteUrl,\n\t\t\tfirstProcessId,\n\t\t\tprocessIdSpaceLength: this.processIdSpaceLength,\n\t\t\ttrace: this.args.debug || false,\n\t\t\tblueprint: this.args.blueprint!,\n\t\t};\n\n\t\tawait playground.bootAsSecondaryWorker(workerBootArgs);\n\n\t\treturn playground;\n\t}\n\n\twriteProgressUpdate(\n\t\twriteStream: NodeJS.WriteStream,\n\t\tmessage: string,\n\t\tfinalUpdate: boolean\n\t) {\n\t\tif (message === this.lastProgressMessage) {\n\t\t\t// Avoid repeating the same message\n\t\t\treturn;\n\t\t}\n\t\tthis.lastProgressMessage = message;\n\n\t\tif (writeStream.isTTY) {\n\t\t\t// Overwrite previous progress updates in-place for a quieter UX.\n\t\t\twriteStream.cursorTo(0);\n\t\t\twriteStream.write(message);\n\t\t\twriteStream.clearLine(1);\n\n\t\t\tif (finalUpdate) {\n\t\t\t\twriteStream.write('\\n');\n\t\t\t}\n\t\t} else {\n\t\t\t// Fall back to writing one line per progress update\n\t\t\twriteStream.write(`${message}\\n`);\n\t\t}\n\t}\n}\n","import type { EmscriptenDownloadMonitor } from '@php-wasm/progress';\nimport fs from 'fs-extra';\nimport os from 'os';\nimport path, { basename } from 'path';\n\nexport const CACHE_FOLDER = path.join(os.homedir(), '.wordpress-playground');\n\nexport async function fetchSqliteIntegration(\n\tmonitor: EmscriptenDownloadMonitor\n) {\n\tconst sqliteZip = await cachedDownload(\n\t\t'https://github.com/WordPress/sqlite-database-integration/archive/refs/heads/develop.zip',\n\t\t'sqlite.zip',\n\t\tmonitor\n\t);\n\treturn sqliteZip;\n}\n\n// @TODO: Support HTTP cache, invalidate the local file if the remote file has\n// changed\nexport async function cachedDownload(\n\tremoteUrl: string,\n\tcacheKey: string,\n\tmonitor: EmscriptenDownloadMonitor\n) {\n\tconst artifactPath = path.join(CACHE_FOLDER, cacheKey);\n\tif (!fs.existsSync(artifactPath)) {\n\t\tfs.ensureDirSync(CACHE_FOLDER);\n\t\tawait downloadTo(remoteUrl, artifactPath, monitor);\n\t}\n\treturn readAsFile(artifactPath);\n}\n\nasync function downloadTo(\n\tremoteUrl: string,\n\tlocalPath: string,\n\tmonitor: EmscriptenDownloadMonitor\n) {\n\tconst response = await monitor.monitorFetch(fetch(remoteUrl));\n\tconst reader = response.body!.getReader();\n\tconst tmpPath = `${localPath}.partial`;\n\tconst writer = fs.createWriteStream(tmpPath);\n\twhile (true) {\n\t\tconst { done, value } = await reader.read();\n\t\tif (value) {\n\t\t\twriter.write(value);\n\t\t}\n\t\tif (done) {\n\t\t\tbreak;\n\t\t}\n\t}\n\twriter.close();\n\tif (!writer.closed) {\n\t\tawait new Promise((resolve, reject) => {\n\t\t\twriter.on('finish', () => {\n\t\t\t\tfs.renameSync(tmpPath, localPath);\n\t\t\t\tresolve(null);\n\t\t\t});\n\t\t\twriter.on('error', (err: any) => {\n\t\t\t\tfs.removeSync(tmpPath);\n\t\t\t\treject(err);\n\t\t\t});\n\t\t});\n\t}\n}\n\nexport function readAsFile(path: string, fileName?: string): File {\n\treturn new File([fs.readFileSync(path)], fileName ?? basename(path));\n}\n","import { logger } from '@php-wasm/logger';\nimport { EmscriptenDownloadMonitor, ProgressTracker } from '@php-wasm/progress';\nimport type { SupportedPHPVersion } from '@php-wasm/universal';\nimport { consumeAPI } from '@php-wasm/universal';\nimport type {\n\tBlueprintBundle,\n\tBlueprintDeclaration,\n} from '@wp-playground/blueprints';\nimport { compileBlueprint, isBlueprintBundle } from '@wp-playground/blueprints';\nimport { RecommendedPHPVersion, zipDirectory } from '@wp-playground/common';\nimport fs from 'fs';\nimport path from 'path';\nimport { resolveWordPressRelease } from '@wp-playground/wordpress';\nimport {\n\tCACHE_FOLDER,\n\tcachedDownload,\n\tfetchSqliteIntegration,\n\treadAsFile,\n} from './download';\nimport type { PlaygroundCliBlueprintV1Worker } from './worker-thread-v1';\n// @ts-ignore\nimport importedWorkerV1UrlString from './worker-thread-v1?worker&url';\nimport type { MessagePort as NodeMessagePort } from 'worker_threads';\nimport type { RunCLIArgs, SpawnedWorker } from '../run-cli';\n\n/**\n * Boots Playground CLI workers using Blueprint version 1.\n *\n * Progress tracking, downloads, steps, and all other features are\n * implemented in TypeScript and orchestrated by this class.\n */\nexport class BlueprintsV1Handler {\n\tprivate phpVersion: SupportedPHPVersion | undefined;\n\tprivate lastProgressMessage = '';\n\n\tprivate siteUrl: string;\n\tprivate processIdSpaceLength: number;\n\tprivate args: RunCLIArgs;\n\n\tconstructor(\n\t\targs: RunCLIArgs,\n\t\toptions: {\n\t\t\tsiteUrl: string;\n\t\t\tprocessIdSpaceLength: number;\n\t\t}\n\t) {\n\t\tthis.args = args;\n\t\tthis.siteUrl = options.siteUrl;\n\t\tthis.processIdSpaceLength = options.processIdSpaceLength;\n\t}\n\n\tgetWorkerUrl() {\n\t\treturn importedWorkerV1UrlString;\n\t}\n\n\tasync bootPrimaryWorker(\n\t\tphpPort: NodeMessagePort,\n\t\tfileLockManagerPort: NodeMessagePort\n\t) {\n\t\tconst compiledBlueprint = await this.compileInputBlueprint(\n\t\t\tthis.args['additional-blueprint-steps'] || []\n\t\t);\n\t\tthis.phpVersion = compiledBlueprint.versions.php;\n\n\t\tlet wpDetails: any = undefined;\n\t\t// @TODO: Rename to FetchProgressMonitor. There's nothing Emscripten\n\t\t// about that class anymore.\n\t\tconst monitor = new EmscriptenDownloadMonitor();\n\t\tif (!this.args.skipWordPressSetup) {\n\t\t\tlet progressReached100 = false;\n\t\t\tmonitor.addEventListener('progress', ((\n\t\t\t\te: CustomEvent<ProgressEvent & { finished: boolean }>\n\t\t\t) => {\n\t\t\t\tif (progressReached100) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// @TODO Every progress bar will want percentages. The\n\t\t\t\t// download monitor should just provide that.\n\t\t\t\tconst { loaded, total } = e.detail;\n\t\t\t\t// Use floor() so we don't report 100% until truly there.\n\t\t\t\tconst percentProgress = Math.floor(\n\t\t\t\t\tMath.min(100, (100 * loaded) / total)\n\t\t\t\t);\n\t\t\t\tprogressReached100 = percentProgress === 100;\n\n\t\t\t\tif (!this.args.quiet) {\n\t\t\t\t\tthis.writeProgressUpdate(\n\t\t\t\t\t\tprocess.stdout,\n\t\t\t\t\t\t`Downloading WordPress ${percentProgress}%...`,\n\t\t\t\t\t\tprogressReached100\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}) as any);\n\n\t\t\twpDetails = await resolveWordPressRelease(this.args.wp);\n\t\t\tlogger.log(\n\t\t\t\t`Resolved WordPress release URL: ${wpDetails?.releaseUrl}`\n\t\t\t);\n\t\t}\n\n\t\tconst preinstalledWpContentPath =\n\t\t\twpDetails &&\n\t\t\tpath.join(\n\t\t\t\tCACHE_FOLDER,\n\t\t\t\t`prebuilt-wp-content-for-wp-${wpDetails.version}.zip`\n\t\t\t);\n\t\tconst wordPressZip = !wpDetails\n\t\t\t? undefined\n\t\t\t: fs.existsSync(preinstalledWpContentPath)\n\t\t\t? readAsFile(preinstalledWpContentPath)\n\t\t\t: await cachedDownload(\n\t\t\t\t\twpDetails.releaseUrl,\n\t\t\t\t\t`${wpDetails.version}.zip`,\n\t\t\t\t\tmonitor\n\t\t\t );\n\n\t\tlogger.log(`Fetching SQLite integration plugin...`);\n\t\tconst sqliteIntegrationPluginZip = this.args.skipSqliteSetup\n\t\t\t? undefined\n\t\t\t: await fetchSqliteIntegration(monitor);\n\n\t\tconst followSymlinks = this.args.followSymlinks === true;\n\t\tconst trace = this.args.experimentalTrace === true;\n\n\t\tconst mountsBeforeWpInstall = this.args['mount-before-install'] || [];\n\t\tconst mountsAfterWpInstall = this.args.mount || [];\n\n\t\tconst playground = consumeAPI<PlaygroundCliBlueprintV1Worker>(phpPort);\n\n\t\t// Comlink communication proxy\n\t\tawait playground.isConnected();\n\n\t\tlogger.log(`Booting WordPress...`);\n\n\t\tawait playground.useFileLockManager(fileLockManagerPort);\n\t\tawait playground.bootAsPrimaryWorker({\n\t\t\tphpVersion: this.phpVersion,\n\t\t\twpVersion: compiledBlueprint.versions.wp,\n\t\t\tabsoluteUrl: this.siteUrl,\n\t\t\tmountsBeforeWpInstall,\n\t\t\tmountsAfterWpInstall,\n\t\t\twordPressZip: wordPressZip && (await wordPressZip!.arrayBuffer()),\n\t\t\tsqliteIntegrationPluginZip:\n\t\t\t\tawait sqliteIntegrationPluginZip!.arrayBuffer(),\n\t\t\tfirstProcessId: 0,\n\t\t\tprocessIdSpaceLength: this.processIdSpaceLength,\n\t\t\tfollowSymlinks,\n\t\t\ttrace,\n\t\t\tinternalCookieStore: this.args.internalCookieStore,\n\t\t\twithXdebug: this.args.xdebug,\n\t\t});\n\n\t\tif (\n\t\t\twpDetails &&\n\t\t\t!this.args['mount-before-install'] &&\n\t\t\t!fs.existsSync(preinstalledWpContentPath)\n\t\t) {\n\t\t\tlogger.log(`Caching preinstalled WordPress for the next boot...`);\n\t\t\tfs.writeFileSync(\n\t\t\t\tpreinstalledWpContentPath,\n\t\t\t\t(await zipDirectory(playground, '/wordpress'))!\n\t\t\t);\n\t\t\tlogger.log(`Cached!`);\n\t\t}\n\n\t\treturn playground;\n\t}\n\n\tasync bootSecondaryWorker({\n\t\tworker,\n\t\tfileLockManagerPort,\n\t\tfirstProcessId,\n\t}: {\n\t\tworker: SpawnedWorker;\n\t\tfileLockManagerPort: NodeMessagePort;\n\t\tfirstProcessId: number;\n\t}) {\n\t\tconst additionalPlayground = consumeAPI<PlaygroundCliBlueprintV1Worker>(\n\t\t\tworker.phpPort\n\t\t);\n\n\t\tawait additionalPlayground.isConnected();\n\t\tawait additionalPlayground.useFileLockManager(fileLockManagerPort);\n\t\tawait additionalPlayground.bootAsSecondaryWorker({\n\t\t\tphpVersion: this.phpVersion,\n\t\t\tabsoluteUrl: this.siteUrl,\n\t\t\tmountsBeforeWpInstall: this.args['mount-before-install'] || [],\n\t\t\tmountsAfterWpInstall: this.args['mount'] || [],\n\t\t\t// Skip WordPress zip because we share the /wordpress directory\n\t\t\t// populated by the initial worker.\n\t\t\twordPressZip: undefined,\n\t\t\t// Skip SQLite integration plugin for now because we\n\t\t\t// will copy it from primary's `/internal` directory.\n\t\t\tsqliteIntegrationPluginZip: undefined,\n\t\t\tdataSqlPath: '/wordpress/wp-content/database/.ht.sqlite',\n\t\t\tfirstProcessId,\n\t\t\tprocessIdSpaceLength: this.processIdSpaceLength,\n\t\t\tfollowSymlinks: this.args.followSymlinks === true,\n\t\t\ttrace: this.args.experimentalTrace === true,\n\t\t\t// @TODO: Move this to the request handler or else every worker\n\t\t\t// will have a separate cookie store.\n\t\t\tinternalCookieStore: this.args.internalCookieStore,\n\t\t\twithXdebug: this.args.xdebug,\n\t\t});\n\t\tawait additionalPlayground.isReady();\n\t\treturn additionalPlayground;\n\t}\n\n\tasync compileInputBlueprint(additionalBlueprintSteps: any[]) {\n\t\tconst args = this.args;\n\t\tconst resolvedBlueprint = args.blueprint as BlueprintDeclaration;\n\t\t/**\n\t\t * @TODO This looks similar to the resolveBlueprint() call in the website package:\n\t\t * \t https://github.com/WordPress/wordpress-playground/blob/ce586059e5885d185376184fdd2f52335cca32b0/packages/playground/website/src/main.tsx#L41\n\t\t *\n\t\t * \t\t Also the Blueprint Builder tool does something similar.\n\t\t * Perhaps all these cases could be handled by the same function?\n\t\t */\n\t\tconst blueprint: BlueprintDeclaration | BlueprintBundle =\n\t\t\tisBlueprintBundle(resolvedBlueprint)\n\t\t\t\t? resolvedBlueprint\n\t\t\t\t: {\n\t\t\t\t\t\tlogin: args.login,\n\t\t\t\t\t\t...(resolvedBlueprint || {}),\n\t\t\t\t\t\tpreferredVersions: {\n\t\t\t\t\t\t\tphp:\n\t\t\t\t\t\t\t\targs.php ??\n\t\t\t\t\t\t\t\tresolvedBlueprint?.preferredVersions?.php ??\n\t\t\t\t\t\t\t\tRecommendedPHPVersion,\n\t\t\t\t\t\t\twp:\n\t\t\t\t\t\t\t\targs.wp ??\n\t\t\t\t\t\t\t\tresolvedBlueprint?.preferredVersions?.wp ??\n\t\t\t\t\t\t\t\t'latest',\n\t\t\t\t\t\t\t...(resolvedBlueprint?.preferredVersions || {}),\n\t\t\t\t\t\t},\n\t\t\t\t };\n\n\t\tconst tracker = new ProgressTracker();\n\t\tlet lastCaption = '';\n\t\tlet progressReached100 = false;\n\t\ttracker.addEventListener('progress', (e: any) => {\n\t\t\tif (progressReached100) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tprogressReached100 = e.detail.progress === 100;\n\n\t\t\t// Use floor() so we don't report 100% until truly there.\n\t\t\tconst progressInteger = Math.floor(e.detail.progress);\n\t\t\tlastCaption =\n\t\t\t\te.detail.caption || lastCaption || 'Running the Blueprint';\n\t\t\tconst message = `${lastCaption.trim()} – ${progressInteger}%`;\n\t\t\tif (!args.quiet) {\n\t\t\t\tthis.writeProgressUpdate(\n\t\t\t\t\tprocess.stdout,\n\t\t\t\t\tmessage,\n\t\t\t\t\tprogressReached100\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\t\treturn await compileBlueprint(blueprint as BlueprintDeclaration, {\n\t\t\tprogress: tracker,\n\t\t\tadditionalSteps: additionalBlueprintSteps,\n\t\t});\n\t}\n\n\twriteProgressUpdate(\n\t\twriteStream: NodeJS.WriteStream,\n\t\tmessage: string,\n\t\tfinalUpdate: boolean\n\t) {\n\t\tif (message === this.lastProgressMessage) {\n\t\t\t// Avoid repeating the same message\n\t\t\treturn;\n\t\t}\n\t\tthis.lastProgressMessage = message;\n\n\t\tif (writeStream.isTTY) {\n\t\t\t// Overwrite previous progress updates in-place for a quieter UX.\n\t\t\twriteStream.cursorTo(0);\n\t\t\twriteStream.write(message);\n\t\t\twriteStream.clearLine(1);\n\n\t\t\tif (finalUpdate) {\n\t\t\t\twriteStream.write('\\n');\n\t\t\t}\n\t\t} else {\n\t\t\t// Fall back to writing one line per progress update\n\t\t\twriteStream.write(`${message}\\n`);\n\t\t}\n\t}\n}\n","import { errorLogPath, logger } from '@php-wasm/logger';\nimport type {\n\tPHPRequest,\n\tRemoteAPI,\n\tSupportedPHPVersion,\n} from '@php-wasm/universal';\nimport {\n\tPHPResponse,\n\texposeAPI,\n\texposeSyncAPI,\n\tprintDebugDetails,\n} from '@php-wasm/universal';\nimport type {\n\tBlueprintBundle,\n\tBlueprintDeclaration,\n} from '@wp-playground/blueprints';\nimport { runBlueprintSteps } from '@wp-playground/blueprints';\nimport {\n\tRecommendedPHPVersion,\n\tunzipFile,\n\tzipDirectory,\n} from '@wp-playground/common';\nimport fs from 'fs';\nimport type { Server } from 'http';\nimport { MessageChannel as NodeMessageChannel, Worker } from 'worker_threads';\n// @ts-ignore\nimport {\n\texpandAutoMounts,\n\tparseMountDirArguments,\n\tparseMountWithDelimiterArguments,\n} from './mounts';\nimport { startServer } from './start-server';\nimport type {\n\tMount,\n\tPlaygroundCliBlueprintV1Worker,\n} from './blueprints-v1/worker-thread-v1';\nimport type { PlaygroundCliBlueprintV2Worker } from './blueprints-v2/worker-thread-v2';\nimport { FileLockManagerForNode } from '@php-wasm/node';\nimport { LoadBalancer } from './load-balancer';\n/* eslint-disable no-console */\nimport { SupportedPHPVersions } from '@php-wasm/universal';\nimport { cpus } from 'os';\nimport { jspi } from 'wasm-feature-detect';\nimport type { MessagePort as NodeMessagePort } from 'worker_threads';\nimport yargs from 'yargs';\nimport { isValidWordPressSlug } from './is-valid-wordpress-slug';\nimport { resolveBlueprint } from './resolve-blueprint';\nimport { BlueprintsV2Handler } from './blueprints-v2/blueprints-v2-handler';\nimport { BlueprintsV1Handler } from './blueprints-v1/blueprints-v1-handler';\n\nexport async function parseOptionsAndRunCLI() {\n\ttry {\n\t\t/**\n\t\t * @TODO This looks similar to Query API args https://wordpress.github.io/wordpress-playground/developers/apis/query-api/\n\t\t * Perhaps the two could be handled by the same code?\n\t\t */\n\t\tconst yargsObject = yargs(process.argv.slice(2))\n\t\t\t.usage('Usage: wp-playground <command> [options]')\n\t\t\t.positional('command', {\n\t\t\t\tdescribe: 'Command to run',\n\t\t\t\tchoices: ['server', 'run-blueprint', 'build-snapshot'] as const,\n\t\t\t\tdemandOption: true,\n\t\t\t})\n\t\t\t.option('outfile', {\n\t\t\t\tdescribe: 'When building, write to this output file.',\n\t\t\t\ttype: 'string',\n\t\t\t\tdefault: 'wordpress.zip',\n\t\t\t})\n\t\t\t.option('port', {\n\t\t\t\tdescribe: 'Port to listen on when serving.',\n\t\t\t\ttype: 'number',\n\t\t\t\tdefault: 9400,\n\t\t\t})\n\t\t\t.option('php', {\n\t\t\t\tdescribe: 'PHP version to use.',\n\t\t\t\ttype: 'string',\n\t\t\t\tdefault: RecommendedPHPVersion,\n\t\t\t\tchoices: SupportedPHPVersions,\n\t\t\t})\n\t\t\t.option('wp', {\n\t\t\t\tdescribe: 'WordPress version to use.',\n\t\t\t\ttype: 'string',\n\t\t\t\tdefault: 'latest',\n\t\t\t})\n\t\t\t// @TODO: Support read-only mounts, e.g. via WORKERFS, a custom\n\t\t\t// ReadOnlyNODEFS, or by copying the files into MEMFS\n\t\t\t.option('mount', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Mount a directory to the PHP runtime (can be used multiple times). Format: /host/path:/vfs/path',\n\t\t\t\ttype: 'array',\n\t\t\t\tstring: true,\n\t\t\t\tcoerce: parseMountWithDelimiterArguments,\n\t\t\t})\n\t\t\t.option('mount-before-install', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Mount a directory to the PHP runtime before WordPress installation (can be used multiple times). Format: /host/path:/vfs/path',\n\t\t\t\ttype: 'array',\n\t\t\t\tstring: true,\n\t\t\t\tcoerce: parseMountWithDelimiterArguments,\n\t\t\t})\n\t\t\t.option('mount-dir', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Mount a directory to the PHP runtime (can be used multiple times). Format: \"/host/path\" \"/vfs/path\"',\n\t\t\t\ttype: 'array',\n\t\t\t\tnargs: 2,\n\t\t\t\tarray: true,\n\t\t\t\t// coerce: parseMountDirArguments,\n\t\t\t})\n\t\t\t.option('mount-dir-before-install', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Mount a directory before WordPress installation (can be used multiple times). Format: \"/host/path\" \"/vfs/path\"',\n\t\t\t\ttype: 'string',\n\t\t\t\tnargs: 2,\n\t\t\t\tarray: true,\n\t\t\t\tcoerce: parseMountDirArguments,\n\t\t\t})\n\t\t\t.option('login', {\n\t\t\t\tdescribe: 'Should log the user in',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t})\n\t\t\t.option('blueprint', {\n\t\t\t\tdescribe: 'Blueprint to execute.',\n\t\t\t\ttype: 'string',\n\t\t\t})\n\t\t\t.option('blueprint-may-read-adjacent-files', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Consent flag: Allow \"bundled\" resources in a local blueprint to read files in the same directory as the blueprint file.',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t})\n\t\t\t.option('skip-wordpress-setup', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Do not download, unzip, and install WordPress. Useful for mounting a pre-configured WordPress directory at /wordpress.',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t})\n\t\t\t.option('skip-sqlite-setup', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Skip the SQLite integration plugin setup to allow the WordPress site to use MySQL.',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t})\n\t\t\t.option('quiet', {\n\t\t\t\tdescribe: 'Do not output logs and progress messages.',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t})\n\t\t\t.option('debug', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Print PHP error log content if an error occurs during Playground boot.',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t})\n\t\t\t.option('auto-mount', {\n\t\t\t\tdescribe: `Automatically mount the current working directory. You can mount a WordPress directory, a plugin directory, a theme directory, a wp-content directory, or any directory containing PHP and HTML files.`,\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t})\n\t\t\t.option('follow-symlinks', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Allow Playground to follow symlinks by automatically mounting symlinked directories and files encountered in mounted directories. \\nWarning: Following symlinks will expose files outside mounted directories to Playground and could be a security risk.',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t})\n\t\t\t.option('experimental-trace', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Print detailed messages about system behavior to the console. Useful for troubleshooting.',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t\t// Hide this option because we want to replace with a more general log-level flag.\n\t\t\t\thidden: true,\n\t\t\t})\n\t\t\t.option('internal-cookie-store', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Enable internal cookie handling. When enabled, Playground will manage cookies internally using ' +\n\t\t\t\t\t'an HttpCookieStore that persists cookies across requests. When disabled, cookies are handled ' +\n\t\t\t\t\t'externally (e.g., by a browser in Node.js environments).',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t})\n\t\t\t.option('xdebug', {\n\t\t\t\tdescribe: 'Enable Xdebug.',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t})\n\t\t\t// TODO: Should we make this a hidden flag?\n\t\t\t.option('experimental-multi-worker', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Enable experimental multi-worker support which requires JSPI ' +\n\t\t\t\t\t'and a /wordpress directory backed by a real filesystem. ' +\n\t\t\t\t\t'Pass a positive number to specify the number of workers to use. ' +\n\t\t\t\t\t'Otherwise, default to the number of CPUs minus 1.',\n\t\t\t\ttype: 'number',\n\t\t\t\tcoerce: (value?: number) => value ?? cpus().length - 1,\n\t\t\t})\n\t\t\t.option('experimental-blueprints-v2-runner', {\n\t\t\t\tdescribe: 'Use the experimental Blueprint V2 runner.',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t\t// Remove the \"hidden\" flag once Blueprint V2 is fully supported\n\t\t\t\thidden: true,\n\t\t\t})\n\t\t\t.showHelpOnFail(false)\n\t\t\t.strictOptions()\n\t\t\t.check(async (args) => {\n\t\t\t\tif (args.wp !== undefined && !isValidWordPressSlug(args.wp)) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\t// Check if is valid URL\n\t\t\t\t\t\tnew URL(args.wp);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t'Unrecognized WordPress version. Please use \"latest\", a URL, or a numeric version such as \"6.2\", \"6.0.1\", \"6.2-beta1\", or \"6.2-RC1\"'\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (args['experimental-multi-worker'] !== undefined) {\n\t\t\t\t\tif (args['experimental-multi-worker'] <= 1) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t'The --experimentalMultiWorker flag must be a positive integer greater than 1.'\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\tconst isMountingWordPressDir = (mount: Mount) =>\n\t\t\t\t\t\tmount.vfsPath === '/wordpress';\n\t\t\t\t\tif (\n\t\t\t\t\t\t!args.mount?.some(isMountingWordPressDir) &&\n\t\t\t\t\t\t!(args['mount-before-install'] as any)?.some(\n\t\t\t\t\t\t\tisMountingWordPressDir\n\t\t\t\t\t\t)\n\t\t\t\t\t) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t'Please mount a real filesystem directory as the /wordpress directory before using the --experimentalMultiWorker flag. For example: ' +\n\t\t\t\t\t\t\t\t'--mount-dir-before-install ./empty-dir /wordpress'\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t});\n\n\t\tyargsObject.wrap(yargsObject.terminalWidth());\n\t\tconst args = await yargsObject.argv;\n\n\t\tconst command = args._[0] as string;\n\n\t\tif (!['run-blueprint', 'server', 'build-snapshot'].includes(command)) {\n\t\t\tyargsObject.showHelp();\n\t\t\tprocess.exit(1);\n\t\t}\n\n\t\tconst cliArgs = {\n\t\t\t...args,\n\t\t\tcommand,\n\t\t\tmount: [...(args.mount || []), ...(args['mount-dir'] || [])],\n\t\t\t'mount-before-install': [\n\t\t\t\t...(args['mount-before-install'] || []),\n\t\t\t\t...(args['mount-dir-before-install'] || []),\n\t\t\t],\n\t\t} as RunCLIArgs;\n\n\t\tawait runCLI(cliArgs);\n\t} catch (e) {\n\t\tif (!(e instanceof Error)) {\n\t\t\tthrow e;\n\t\t}\n\t\tconst debug = process.argv.includes('--debug');\n\t\tif (debug) {\n\t\t\tprintDebugDetails(e);\n\t\t} else {\n\t\t\tconst messageChain = [];\n\t\t\tlet currentError = e;\n\t\t\tdo {\n\t\t\t\tmessageChain.push(currentError.message);\n\t\t\t\tcurrentError = currentError.cause as Error;\n\t\t\t} while (currentError instanceof Error);\n\t\t\tconsole.error(\n\t\t\t\t'\\x1b[1m' + messageChain.join(' caused by ') + '\\x1b[0m'\n\t\t\t);\n\t\t}\n\t\tprocess.exit(1);\n\t}\n}\n\nexport interface RunCLIArgs {\n\tblueprint?: BlueprintDeclaration | BlueprintBundle;\n\tcommand: 'server' | 'run-blueprint' | 'build-snapshot';\n\tdebug?: boolean;\n\tlogin?: boolean;\n\tmount?: Mount[];\n\t'mount-before-install'?: Mount[];\n\toutfile?: string;\n\tphp?: SupportedPHPVersion;\n\tport?: number;\n\tquiet?: boolean;\n\twp?: string;\n\tautoMount?: boolean;\n\texperimentalMultiWorker?: number;\n\texperimentalTrace?: boolean;\n\texitOnPrimaryWorkerCrash?: boolean;\n\tinternalCookieStore?: boolean;\n\t'additional-blueprint-steps'?: any[];\n\txdebug?: boolean;\n\t'experimental-blueprints-v2-runner'?: boolean;\n\n\t// --------- Blueprint V1 args -----------\n\tskipWordPressSetup?: boolean;\n\tskipSqliteSetup?: boolean;\n\tfollowSymlinks?: boolean;\n\t'blueprint-may-read-adjacent-files'?: boolean;\n\n\t// --------- Blueprint V2 args (not available via CLI yet) -----------\n\tmode?: 'mount-only' | 'create-new-site' | 'apply-to-existing-site';\n\t'db-engine'?: 'sqlite' | 'mysql';\n\t'db-host'?: string;\n\t'db-user'?: string;\n\t'db-pass'?: string;\n\t'db-name'?: string;\n\t'db-path'?: string;\n\t'truncate-new-site-directory'?: boolean;\n\tallow?: string;\n}\n\ntype PlaygroundCliWorker =\n\t| PlaygroundCliBlueprintV1Worker\n\t| PlaygroundCliBlueprintV2Worker;\n\nexport interface RunCLIServer extends AsyncDisposable {\n\tplayground: RemoteAPI<PlaygroundCliWorker>;\n\tserver: Server;\n\t[Symbol.asyncDispose](): Promise<void>;\n}\n\nexport async function runCLI(args: RunCLIArgs): Promise<RunCLIServer> {\n\tlet loadBalancer: LoadBalancer;\n\tlet playground: RemoteAPI<PlaygroundCliWorker>;\n\n\tconst playgroundsToCleanUp: {\n\t\tplayground: RemoteAPI<PlaygroundCliWorker>;\n\t\tworker: Worker;\n\t}[] = [];\n\n\t/**\n\t * Expand auto-mounts to include the necessary mounts and steps\n\t * when running in auto-mount mode.\n\t */\n\tif (args.autoMount) {\n\t\targs = expandAutoMounts(args);\n\t}\n\n\tif (args.quiet) {\n\t\t// @ts-ignore\n\t\tlogger.handlers = [];\n\t}\n\n\t// Declare file lock manager outside scope of startServer\n\t// so we can look at it when debugging request handling.\n\tconst nativeFlockSync = await import('fs-ext')\n\t\t.then((m) => m.flockSync)\n\t\t.catch(() => {\n\t\t\tlogger.warn(\n\t\t\t\t'The fs-ext package is not installed. ' +\n\t\t\t\t\t'Internal file locking will not be integrated with ' +\n\t\t\t\t\t'host OS file locking.'\n\t\t\t);\n\t\t\treturn undefined;\n\t\t});\n\tconst fileLockManager = new FileLockManagerForNode(nativeFlockSync);\n\n\tlet wordPressReady = false;\n\tlet isFirstRequest = true;\n\n\tlogger.log('Starting a PHP server...');\n\n\treturn startServer({\n\t\tport: args['port'] as number,\n\t\tonBind: async (server: Server, port: number): Promise<RunCLIServer> => {\n\t\t\tconst absoluteUrl = `http://127.0.0.1:${port}`;\n\n\t\t\t// Create the blueprints handler\n\t\t\tconst totalWorkerCount = args.experimentalMultiWorker ?? 1;\n\t\t\tconst processIdSpaceLength = Math.floor(\n\t\t\t\tNumber.MAX_SAFE_INTEGER / totalWorkerCount\n\t\t\t);\n\n\t\t\tlet handler: BlueprintsV1Handler | BlueprintsV2Handler;\n\t\t\tif (args['experimental-blueprints-v2-runner']) {\n\t\t\t\thandler = new BlueprintsV2Handler(args, {\n\t\t\t\t\tsiteUrl: absoluteUrl,\n\t\t\t\t\tprocessIdSpaceLength,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\thandler = new BlueprintsV1Handler(args, {\n\t\t\t\t\tsiteUrl: absoluteUrl,\n\t\t\t\t\tprocessIdSpaceLength,\n\t\t\t\t});\n\n\t\t\t\tif (typeof args.blueprint === 'string') {\n\t\t\t\t\targs.blueprint = await resolveBlueprint({\n\t\t\t\t\t\tsourceString: args.blueprint,\n\t\t\t\t\t\tblueprintMayReadAdjacentFiles:\n\t\t\t\t\t\t\targs['blueprint-may-read-adjacent-files'] === true,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Kick off worker threads now to save time later.\n\t\t\t// There is no need to wait for other async processes to complete.\n\t\t\tconst promisedWorkers = spawnWorkerThreads(\n\t\t\t\thandler.getWorkerUrl(),\n\t\t\t\ttotalWorkerCount,\n\t\t\t\t({ exitCode, isMain, workerIndex }) => {\n\t\t\t\t\tif (exitCode === 0) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tlogger.error(\n\t\t\t\t\t\t`Worker ${workerIndex} exited with code ${exitCode}\\n`\n\t\t\t\t\t);\n\t\t\t\t\t// If the primary worker crashes, exit the entire process.\n\t\t\t\t\tif (!isMain) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (!args.exitOnPrimaryWorkerCrash) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tprocess.exit(1);\n\t\t\t\t}\n\t\t\t);\n\n\t\t\tlogger.log(`Setting up WordPress ${args.wp}`);\n\n\t\t\ttry {\n\t\t\t\tconst [initialWorker, ...additionalWorkers] =\n\t\t\t\t\tawait promisedWorkers;\n\n\t\t\t\tconst fileLockManagerPort = await exposeFileLockManager(\n\t\t\t\t\tfileLockManager\n\t\t\t\t);\n\n\t\t\t\t// Boot the primary worker using the handler\n\t\t\t\tplayground = await handler.bootPrimaryWorker(\n\t\t\t\t\tinitialWorker.phpPort,\n\t\t\t\t\tfileLockManagerPort\n\t\t\t\t);\n\t\t\t\tplaygroundsToCleanUp.push({\n\t\t\t\t\tplayground,\n\t\t\t\t\tworker: initialWorker.worker,\n\t\t\t\t});\n\n\t\t\t\tawait playground.isReady();\n\t\t\t\twordPressReady = true;\n\t\t\t\tlogger.log(`Booted!`);\n\n\t\t\t\tloadBalancer = new LoadBalancer(playground);\n\n\t\t\t\tif (!args['experimental-blueprints-v2-runner']) {\n\t\t\t\t\tconst compiledBlueprint = await (\n\t\t\t\t\t\thandler as BlueprintsV1Handler\n\t\t\t\t\t).compileInputBlueprint(\n\t\t\t\t\t\targs['additional-blueprint-steps'] || []\n\t\t\t\t\t);\n\n\t\t\t\t\tif (compiledBlueprint) {\n\t\t\t\t\t\tlogger.log(`Running the Blueprint...`);\n\t\t\t\t\t\tawait runBlueprintSteps(compiledBlueprint, playground);\n\t\t\t\t\t\tlogger.log(`Finished running the blueprint`);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (args.command === 'build-snapshot') {\n\t\t\t\t\tawait zipSite(playground, args.outfile as string);\n\t\t\t\t\tlogger.log(`WordPress exported to ${args.outfile}`);\n\t\t\t\t\tprocess.exit(0);\n\t\t\t\t} else if (args.command === 'run-blueprint') {\n\t\t\t\t\tlogger.log(`Blueprint executed`);\n\t\t\t\t\tprocess.exit(0);\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\targs.experimentalMultiWorker &&\n\t\t\t\t\targs.experimentalMultiWorker > 1\n\t\t\t\t) {\n\t\t\t\t\tlogger.log(`Preparing additional workers...`);\n\n\t\t\t\t\t// Save /internal directory from initial worker so we can replicate it\n\t\t\t\t\t// in each additional worker.\n\t\t\t\t\tconst internalZip = await zipDirectory(\n\t\t\t\t\t\tplayground,\n\t\t\t\t\t\t'/internal'\n\t\t\t\t\t);\n\n\t\t\t\t\t// Boot additional workers using the handler\n\t\t\t\t\tconst initialWorkerProcessIdSpace = processIdSpaceLength;\n\t\t\t\t\tawait Promise.all(\n\t\t\t\t\t\tadditionalWorkers.map(async (worker, index) => {\n\t\t\t\t\t\t\tconst firstProcessId =\n\t\t\t\t\t\t\t\tinitialWorkerProcessIdSpace +\n\t\t\t\t\t\t\t\tindex * processIdSpaceLength;\n\n\t\t\t\t\t\t\tconst fileLockManagerPort =\n\t\t\t\t\t\t\t\tawait exposeFileLockManager(fileLockManager);\n\n\t\t\t\t\t\t\tconst additionalPlayground =\n\t\t\t\t\t\t\t\tawait handler.bootSecondaryWorker({\n\t\t\t\t\t\t\t\t\tworker,\n\t\t\t\t\t\t\t\t\tfileLockManagerPort,\n\t\t\t\t\t\t\t\t\tfirstProcessId,\n\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tplaygroundsToCleanUp.push({\n\t\t\t\t\t\t\t\tplayground: additionalPlayground,\n\t\t\t\t\t\t\t\tworker: worker.worker,\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\t// Replicate the Blueprint-initialized /internal directory\n\t\t\t\t\t\t\tawait additionalPlayground.writeFile(\n\t\t\t\t\t\t\t\t'/tmp/internal.zip',\n\t\t\t\t\t\t\t\tinternalZip\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tawait unzipFile(\n\t\t\t\t\t\t\t\tadditionalPlayground,\n\t\t\t\t\t\t\t\t'/tmp/internal.zip',\n\t\t\t\t\t\t\t\t'/internal'\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tawait additionalPlayground.unlink(\n\t\t\t\t\t\t\t\t'/tmp/internal.zip'\n\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\tloadBalancer.addWorker(additionalPlayground);\n\t\t\t\t\t\t})\n\t\t\t\t\t);\n\n\t\t\t\t\tlogger.log(`Ready!`);\n\t\t\t\t}\n\n\t\t\t\tlogger.log(`WordPress is running on ${absoluteUrl}`);\n\n\t\t\t\treturn {\n\t\t\t\t\tplayground,\n\t\t\t\t\tserver,\n\t\t\t\t\t[Symbol.asyncDispose]: async function disposeCLI() {\n\t\t\t\t\t\tawait Promise.all(\n\t\t\t\t\t\t\tplaygroundsToCleanUp.map(\n\t\t\t\t\t\t\t\tasync ({ playground, worker }) => {\n\t\t\t\t\t\t\t\t\tawait playground.dispose();\n\t\t\t\t\t\t\t\t\tawait worker.terminate();\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\tawait new Promise((resolve) => server.close(resolve));\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\tif (!args.debug) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tlet phpLogs = '';\n\t\t\t\tif (await playground.fileExists(errorLogPath)) {\n\t\t\t\t\tphpLogs = await playground.readFileAsText(errorLogPath);\n\t\t\t\t}\n\t\t\t\tthrow new Error(phpLogs, { cause: error });\n\t\t\t}\n\t\t},\n\t\tasync handleRequest(request: PHPRequest) {\n\t\t\tif (!wordPressReady) {\n\t\t\t\treturn PHPResponse.forHttpCode(\n\t\t\t\t\t502,\n\t\t\t\t\t'WordPress is not ready yet'\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Clear the playground_auto_login_already_happened cookie on the first request.\n\t\t\t// Otherwise the first Playground CLI server started on the machine will set it,\n\t\t\t// all the subsequent runs will get the stale cookie, and the auto-login will\n\t\t\t// assume they don't have to auto-login again.\n\t\t\tif (isFirstRequest) {\n\t\t\t\tisFirstRequest = false;\n\t\t\t\tconst headers: Record<string, string[]> = {\n\t\t\t\t\t'Content-Type': ['text/plain'],\n\t\t\t\t\t'Content-Length': ['0'],\n\t\t\t\t\tLocation: ['/'],\n\t\t\t\t};\n\t\t\t\tif (\n\t\t\t\t\trequest.headers?.['cookie']?.includes(\n\t\t\t\t\t\t'playground_auto_login_already_happened'\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\theaders['Set-Cookie'] = [\n\t\t\t\t\t\t'playground_auto_login_already_happened=1; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/',\n\t\t\t\t\t];\n\t\t\t\t}\n\t\t\t\treturn new PHPResponse(302, headers, new Uint8Array());\n\t\t\t}\n\t\t\treturn await loadBalancer.handleRequest(request);\n\t\t},\n\t});\n}\n\nexport type SpawnedWorker = {\n\tworker: Worker;\n\tphpPort: NodeMessagePort;\n};\nfunction spawnWorkerThreads(\n\tworkerUrlString: string,\n\tcount: number,\n\tonWorkerExit: (options: {\n\t\texitCode: number;\n\t\tisMain: boolean;\n\t\tworkerIndex: number;\n\t}) => void\n): Promise<SpawnedWorker[]> {\n\tconst moduleWorkerUrl = new URL(workerUrlString, import.meta.url);\n\n\tconst promises = [];\n\tfor (let i = 0; i < count; i++) {\n\t\tconst worker = new Worker(moduleWorkerUrl);\n\t\tconst onExit: (code: number) => void = (code: number) => {\n\t\t\tonWorkerExit({\n\t\t\t\texitCode: code,\n\t\t\t\tisMain: i === 0,\n\t\t\t\tworkerIndex: i,\n\t\t\t});\n\t\t};\n\t\tpromises.push(\n\t\t\tnew Promise<{ worker: Worker; phpPort: NodeMessagePort }>(\n\t\t\t\t(resolve, reject) => {\n\t\t\t\t\tworker.once('message', function (message: any) {\n\t\t\t\t\t\t// Let the worker confirm it has initialized.\n\t\t\t\t\t\t// We could use the 'online' event to detect start of JS execution,\n\t\t\t\t\t\t// but that would miss initialization errors.\n\t\t\t\t\t\tif (message.command === 'worker-script-initialized') {\n\t\t\t\t\t\t\tresolve({ worker, phpPort: message.phpPort });\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tworker.once('error', function (e: Error) {\n\t\t\t\t\t\tconsole.error(e);\n\t\t\t\t\t\tconst error = new Error(\n\t\t\t\t\t\t\t`Worker failed to load at ${moduleWorkerUrl}. ${\n\t\t\t\t\t\t\t\te.message ? `Original error: ${e.message}` : ''\n\t\t\t\t\t\t\t}`\n\t\t\t\t\t\t);\n\t\t\t\t\t\t(error as any).filename = moduleWorkerUrl;\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t});\n\t\t\t\t\tworker.once('exit', onExit);\n\t\t\t\t}\n\t\t\t)\n\t\t);\n\t}\n\treturn Promise.all(promises);\n}\n\n/**\n * Expose the file lock manager API on a MessagePort and return it.\n *\n * @see comlink-sync.ts\n * @see phpwasm-emscripten-library-file-locking-for-node.js\n */\nasync function exposeFileLockManager(fileLockManager: FileLockManagerForNode) {\n\tconst { port1, port2 } = new NodeMessageChannel();\n\tif (await jspi()) {\n\t\t/**\n\t\t * When JSPI is available, the worker thread expects an asynchronous API.\n\t\t *\n\t\t * @see worker-thread.ts\n\t\t * @see comlink-sync.ts\n\t\t * @see phpwasm-emscripten-library-file-locking-for-node.js\n\t\t */\n\t\texposeAPI(fileLockManager, null, port1);\n\t} else {\n\t\t/**\n\t\t * When JSPI is not available, the worker thread expects a synchronous API.\n\t\t *\n\t\t * @see worker-thread.ts\n\t\t * @see comlink-sync.ts\n\t\t * @see phpwasm-emscripten-library-file-locking-for-node.js\n\t\t */\n\t\tawait exposeSyncAPI(fileLockManager, port1);\n\t}\n\treturn port2;\n}\n\nasync function zipSite(\n\tplayground: RemoteAPI<PlaygroundCliWorker>,\n\toutfile: string\n) {\n\tawait playground.run({\n\t\tcode: `<?php\n\t\t$zip = new ZipArchive();\n\t\tif(false === $zip->open('/tmp/build.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE)) {\n\t\t\tthrow new Exception('Failed to create ZIP');\n\t\t}\n\t\t$files = new RecursiveIteratorIterator(\n\t\t\tnew RecursiveDirectoryIterator('/wordpress')\n\t\t);\n\t\tforeach ($files as $file) {\n\t\t\techo $file . PHP_EOL;\n\t\t\tif (!$file->isFile()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t$zip->addFile($file->getPathname(), $file->getPathname());\n\t\t}\n\t\t$zip->close();\n\n\t`,\n\t});\n\tconst zip = await playground.readFileAsBuffer('/tmp/build.zip');\n\tfs.writeFileSync(outfile, zip);\n}\n"],"names":["startServer","options","app","express","server","resolve","reject","address","req","res","phpResponse","parseHeaders","bufferRequestBody","key","port","body","chunk","requestHeaders","i","LoadBalancer","initialWorker","worker","request","smallestWorkerLoad","workerLoad","promiseForResponse","isValidWordPressSlug","version","resolveBlueprint","sourceString","blueprintMayReadAdjacentFiles","resolveRemoteBlueprint","blueprintPath","path","fs","stat","extension","ZipFilesystem","blueprintText","contextPath","nodeJsFilesystem","NodeJsFilesystem","OverlayFilesystem","InMemoryFilesystem","BlueprintsV2Handler","args","importedWorkerV2UrlString","phpPort","fileLockManagerPort","playground","consumeAPI","workerBootArgs","firstProcessId","writeStream","message","finalUpdate","CACHE_FOLDER","os","fetchSqliteIntegration","monitor","cachedDownload","remoteUrl","cacheKey","artifactPath","downloadTo","readAsFile","localPath","reader","tmpPath","writer","done","value","err","fileName","basename","BlueprintsV1Handler","importedWorkerV1UrlString","compiledBlueprint","wpDetails","EmscriptenDownloadMonitor","progressReached100","e","loaded","total","percentProgress","resolveWordPressRelease","logger","preinstalledWpContentPath","wordPressZip","sqliteIntegrationPluginZip","followSymlinks","trace","mountsBeforeWpInstall","mountsAfterWpInstall","zipDirectory","additionalPlayground","additionalBlueprintSteps","resolvedBlueprint","blueprint","isBlueprintBundle","RecommendedPHPVersion","tracker","ProgressTracker","lastCaption","progressInteger","compileBlueprint","parseOptionsAndRunCLI","yargsObject","yargs","SupportedPHPVersions","parseMountWithDelimiterArguments","parseMountDirArguments","cpus","isMountingWordPressDir","mount","command","cliArgs","runCLI","printDebugDetails","messageChain","currentError","loadBalancer","playgroundsToCleanUp","expandAutoMounts","nativeFlockSync","m","fileLockManager","FileLockManagerForNode","wordPressReady","isFirstRequest","absoluteUrl","totalWorkerCount","processIdSpaceLength","handler","promisedWorkers","spawnWorkerThreads","exitCode","isMain","workerIndex","additionalWorkers","exposeFileLockManager","runBlueprintSteps","zipSite","internalZip","initialWorkerProcessIdSpace","index","unzipFile","error","phpLogs","errorLogPath","PHPResponse","headers","workerUrlString","count","onWorkerExit","moduleWorkerUrl","promises","Worker","onExit","code","port1","port2","NodeMessageChannel","jspi","exposeAPI","exposeSyncAPI","outfile","zip"],"mappings":";;;;;;;;;;;;;;;;;AAaA,eAAsBA,GACrBC,GACwB;AACxB,QAAMC,IAAMC,EAAQ,GAEdC,IAAS,MAAM,IAAI,QAEvB,CAACC,GAASC,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ACH,CAACvJ,GAASC,MAAW;AACb,UAAAe,EAAA,KAAK,WAAW,SAAUiC,GAAc;AAI1C,YAAAA,EAAQ,YAAY,+BACvBjD,EAAQ,EAAE,QAAAgB,GAAQ,SAASiC,EAAQ,SAAS;AAAA,UAC7C,CACA,GACMjC,EAAA,KAAK,SAAS,SAAU4D,GAAU;AACxC,oBAAQ,MAAMA,CAAC;AACf,kBAAMkE,IAAQ,IAAI;AAAA,cACjB,4BAA4BQ,CAAe,KAC1C1E,EAAE,UAAU,mBAAmBA,EAAE,OAAO,KAAK,EAC9C;AAAA,YACD;AACC,YAAAkE,EAAc,WAAWQ,GAC1BrJ,EAAO6I,CAAK;AAAA,UAAA,CACZ,GACM9H,EAAA,KAAK,QAAQyI,CAAM;AAAA,QAAA;AAAA,MAC3B;AAAA,IAEF;AAAA,EAAA;AAEM,SAAA,QAAQ,IAAIF,CAAQ;AAC5B;AAQA,eAAehB,EAAsBd,GAAyC;AAC7E,QAAM,EAAE,OAAAkC,GAAO,OAAAC,EAAM,IAAI,IAAIC,EAAmB;AAC5C,SAAA,MAAMC,OAQCC,EAAAtC,GAAiB,MAAMkC,CAAK,IAShC,MAAAK,EAAcvC,GAAiBkC,CAAK,GAEpCC;AACR;AAEA,eAAenB,GACd7F,GACAqH,GACC;AACD,QAAMrH,EAAW,IAAI;AAAA,IACpB,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAAA,CAkBN;AACD,QAAMsH,IAAM,MAAMtH,EAAW,iBAAiB,gBAAgB;AAC3D,EAAAf,EAAA,cAAcoI,GAASC,CAAG;AAC9B;"}
package/run-cli.d.ts CHANGED
@@ -1,9 +1,13 @@
1
1
  /// <reference types="node" />
2
+ /// <reference types="node" />
2
3
  import type { RemoteAPI, SupportedPHPVersion } from '@php-wasm/universal';
3
4
  import type { BlueprintBundle, BlueprintDeclaration } from '@wp-playground/blueprints';
4
5
  import type { Server } from 'http';
5
- import type { Mount, PlaygroundCliWorker } from './worker-thread';
6
- export declare function parseOptionsAndRunCLI(): Promise<RunCLIServer>;
6
+ import { Worker } from 'worker_threads';
7
+ import type { Mount, PlaygroundCliBlueprintV1Worker } from './blueprints-v1/worker-thread-v1';
8
+ import type { PlaygroundCliBlueprintV2Worker } from './blueprints-v2/worker-thread-v2';
9
+ import type { MessagePort as NodeMessagePort } from 'worker_threads';
10
+ export declare function parseOptionsAndRunCLI(): Promise<void>;
7
11
  export interface RunCLIArgs {
8
12
  blueprint?: BlueprintDeclaration | BlueprintBundle;
9
13
  command: 'server' | 'run-blueprint' | 'build-snapshot';
@@ -15,20 +19,38 @@ export interface RunCLIArgs {
15
19
  php?: SupportedPHPVersion;
16
20
  port?: number;
17
21
  quiet?: boolean;
18
- skipWordPressSetup?: boolean;
19
- skipSqliteSetup?: boolean;
20
22
  wp?: string;
21
23
  autoMount?: boolean;
22
- followSymlinks?: boolean;
23
24
  experimentalMultiWorker?: number;
24
25
  experimentalTrace?: boolean;
26
+ exitOnPrimaryWorkerCrash?: boolean;
25
27
  internalCookieStore?: boolean;
26
28
  'additional-blueprint-steps'?: any[];
27
29
  xdebug?: boolean;
30
+ 'experimental-blueprints-v2-runner'?: boolean;
31
+ skipWordPressSetup?: boolean;
32
+ skipSqliteSetup?: boolean;
33
+ followSymlinks?: boolean;
34
+ 'blueprint-may-read-adjacent-files'?: boolean;
35
+ mode?: 'mount-only' | 'create-new-site' | 'apply-to-existing-site';
36
+ 'db-engine'?: 'sqlite' | 'mysql';
37
+ 'db-host'?: string;
38
+ 'db-user'?: string;
39
+ 'db-pass'?: string;
40
+ 'db-name'?: string;
41
+ 'db-path'?: string;
42
+ 'truncate-new-site-directory'?: boolean;
43
+ allow?: string;
28
44
  }
45
+ type PlaygroundCliWorker = PlaygroundCliBlueprintV1Worker | PlaygroundCliBlueprintV2Worker;
29
46
  export interface RunCLIServer extends AsyncDisposable {
30
47
  playground: RemoteAPI<PlaygroundCliWorker>;
31
48
  server: Server;
32
49
  [Symbol.asyncDispose](): Promise<void>;
33
50
  }
34
51
  export declare function runCLI(args: RunCLIArgs): Promise<RunCLIServer>;
52
+ export type SpawnedWorker = {
53
+ worker: Worker;
54
+ phpPort: NodeMessagePort;
55
+ };
56
+ export {};
@@ -1,29 +1,29 @@
1
- import { createNodeFsMountHandler as k, loadNodeRuntime as v } from "@php-wasm/node";
2
- import { EmscriptenDownloadMonitor as M } from "@php-wasm/progress";
3
- import { exposeAPI as F, PHPWorker as H, consumeAPI as S, consumeAPISync as W, sandboxedSpawnHandlerFactory as E } from "@php-wasm/universal";
4
- import { sprintf as I } from "@php-wasm/util";
5
- import { RecommendedPHPVersion as L } from "@wp-playground/common";
6
- import { bootWordPress as A } from "@wp-playground/wordpress";
1
+ import { createNodeFsMountHandler as W, loadNodeRuntime as _ } from "@php-wasm/node";
2
+ import { EmscriptenDownloadMonitor as v } from "@php-wasm/progress";
3
+ import { exposeAPI as A, PHPWorker as M, consumeAPI as S, consumeAPISync as F, sandboxedSpawnHandlerFactory as H } from "@php-wasm/universal";
4
+ import { sprintf as E } from "@php-wasm/util";
5
+ import { RecommendedPHPVersion as I } from "@wp-playground/common";
6
+ import { bootWordPress as L } from "@wp-playground/wordpress";
7
7
  import { rootCertificates as D } from "tls";
8
8
  import { jspi as R } from "wasm-feature-detect";
9
- import { MessageChannel as x, parentPort as C } from "worker_threads";
9
+ import { MessageChannel as x, parentPort as B } from "worker_threads";
10
10
  import "fs";
11
11
  import "path";
12
- async function m(t, e) {
12
+ async function m(r, e) {
13
13
  for (const o of e)
14
- await t.mount(
14
+ await r.mount(
15
15
  o.vfsPath,
16
- k(o.hostPath)
16
+ W(o.hostPath)
17
17
  );
18
18
  }
19
- function G(t, e, ...o) {
19
+ function C(r, e, ...o) {
20
20
  console.log(
21
21
  performance.now().toFixed(6).padStart(15, "0"),
22
- t.toString().padStart(16, "0"),
23
- I(e, ...o)
22
+ r.toString().padStart(16, "0"),
23
+ E(e, ...o)
24
24
  );
25
25
  }
26
- class U extends H {
26
+ class G extends M {
27
27
  constructor(e) {
28
28
  super(void 0, e), this.booted = !1;
29
29
  }
@@ -37,45 +37,45 @@ class U extends H {
37
37
  * @see phpwasm-emscripten-library-file-locking-for-node.js
38
38
  */
39
39
  async useFileLockManager(e) {
40
- await R() ? this.fileLockManager = S(e) : this.fileLockManager = await W(e);
40
+ await R() ? this.fileLockManager = S(e) : this.fileLockManager = await F(e);
41
41
  }
42
- async boot({
42
+ async bootAsPrimaryWorker({
43
43
  absoluteUrl: e,
44
44
  mountsBeforeWpInstall: o,
45
- mountsAfterWpInstall: f,
46
- phpVersion: P = L,
45
+ mountsAfterWpInstall: P,
46
+ phpVersion: f = I,
47
47
  wordPressZip: c,
48
48
  sqliteIntegrationPluginZip: p,
49
49
  firstProcessId: n,
50
- processIdSpaceLength: h,
51
- dataSqlPath: u,
50
+ processIdSpaceLength: u,
51
+ dataSqlPath: h,
52
52
  followSymlinks: w,
53
53
  trace: y,
54
- internalCookieStore: g,
55
- withXdebug: b
54
+ internalCookieStore: b,
55
+ withXdebug: g
56
56
  }) {
57
57
  if (this.booted)
58
58
  throw new Error("Playground already booted");
59
59
  this.booted = !0;
60
- let r = n;
61
- const _ = n + h - 1;
60
+ let t = n;
61
+ const k = n + u - 1;
62
62
  try {
63
63
  const a = {
64
64
  WP_DEBUG: !0,
65
65
  WP_DEBUG_LOG: !0,
66
66
  WP_DEBUG_DISPLAY: !1
67
- }, l = await A({
67
+ }, l = await L({
68
68
  siteUrl: e,
69
69
  createPhpRuntime: async () => {
70
- const i = r;
71
- return r < _ ? r++ : r = n, await v(P, {
70
+ const s = t;
71
+ return t < k ? t++ : t = n, await _(f, {
72
72
  emscriptenOptions: {
73
73
  fileLockManager: this.fileLockManager,
74
- processId: i,
75
- trace: y ? G : void 0
74
+ processId: s,
75
+ trace: y ? C : void 0
76
76
  },
77
77
  followSymlinks: w,
78
- withXdebug: b
78
+ withXdebug: g
79
79
  });
80
80
  },
81
81
  wordPressZip: c !== void 0 ? new File([c], "wordpress.zip") : void 0,
@@ -95,36 +95,39 @@ class U extends H {
95
95
  disable_functions: ""
96
96
  },
97
97
  hooks: {
98
- async beforeWordPressFiles(i) {
99
- m(i, o);
98
+ async beforeWordPressFiles(s) {
99
+ m(s, o);
100
100
  }
101
101
  },
102
- cookieStore: g ? void 0 : !1,
103
- dataSqlPath: u,
104
- spawnHandler: E
102
+ cookieStore: b ? void 0 : !1,
103
+ dataSqlPath: h,
104
+ spawnHandler: H
105
105
  });
106
106
  this.__internal_setRequestHandler(l);
107
107
  const d = await l.getPrimaryPhp();
108
- await this.setPrimaryPHP(d), m(d, f), q();
108
+ await this.setPrimaryPHP(d), m(d, P), U();
109
109
  } catch (a) {
110
- throw z(a), a;
110
+ throw q(a), a;
111
111
  }
112
112
  }
113
+ async bootAsSecondaryWorker(e) {
114
+ return this.bootAsPrimaryWorker(e);
115
+ }
113
116
  // Provide a named disposal method that can be invoked via comlink.
114
117
  async dispose() {
115
118
  await this[Symbol.asyncDispose]();
116
119
  }
117
120
  }
118
- const s = new x(), [q, z] = F(
119
- new U(new M()),
121
+ const i = new x(), [U, q] = A(
122
+ new G(new v()),
120
123
  void 0,
121
- s.port1
124
+ i.port1
122
125
  );
123
- C.postMessage(
126
+ B.postMessage(
124
127
  {
125
128
  command: "worker-script-initialized",
126
- phpPort: s.port2
129
+ phpPort: i.port2
127
130
  },
128
- [s.port2]
131
+ [i.port2]
129
132
  );
130
- //# sourceMappingURL=worker-thread-CYvRK9UX.js.map
133
+ //# sourceMappingURL=worker-thread-v1-BTJIbQLy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker-thread-v1-BTJIbQLy.js","sources":["packages/playground/cli/src/mounts.ts","packages/playground/cli/src/blueprints-v1/worker-thread-v1.ts"],"sourcesContent":["import { createNodeFsMountHandler } from '@php-wasm/node';\nimport type { PHP } from '@php-wasm/universal';\nimport fs, { existsSync } from 'fs';\nimport path, { basename, join } from 'path';\nimport type { RunCLIArgs } from './run-cli';\n\nexport interface Mount {\n\thostPath: string;\n\tvfsPath: string;\n}\n\n/**\n * Parse an array of mount argument strings where the host path and VFS path\n * are separated by a colon.\n *\n * Example:\n * parseMountWithDelimiterArguments( [ '/host/path:/vfs/path', '/host/path:/vfs/path' ] )\n * // returns:\n * [\n * { hostPath: '/host/path', vfsPath: '/vfs/path' },\n * { hostPath: '/host/path', vfsPath: '/vfs/path' }\n * ]\n *\n * @param mounts - An array of mount argument strings separated by a colon.\n * @returns An array of Mount objects.\n */\nexport function parseMountWithDelimiterArguments(mounts: string[]): Mount[] {\n\tconst parsedMounts = [];\n\tfor (const mount of mounts) {\n\t\tconst mountParts = mount.split(':');\n\t\tif (mountParts.length !== 2) {\n\t\t\tthrow new Error(`Invalid mount format: ${mount}.\n\t\t\t\tExpected format: /host/path:/vfs/path.\n\t\t\t\tIf your path contains a colon, e.g. C:\\\\myplugin, use the --mount-dir option instead.\n\t\t\t\tExample: --mount-dir C:\\\\my-plugin /wordpress/wp-content/plugins/my-plugin`);\n\t\t}\n\t\tconst [hostPath, vfsPath] = mountParts;\n\t\tif (!existsSync(hostPath)) {\n\t\t\tthrow new Error(`Host path does not exist: ${hostPath}`);\n\t\t}\n\t\tparsedMounts.push({ hostPath, vfsPath });\n\t}\n\treturn parsedMounts;\n}\n\n/**\n * Parse an array of mount argument strings where each odd array element is a host path\n * and each even element is the VFS path.\n * e.g. [ '/host/path', '/vfs/path', '/host/path2', '/vfs/path2' ]\n *\n * The result will be an array of Mount objects for each host path the\n * following element is it's VFS path.\n * e.g. [\n * { hostPath: '/host/path', vfsPath: '/vfs/path' },\n * { hostPath: '/host/path2', vfsPath: '/vfs/path2' }\n * ]\n *\n * @param mounts - An array of paths\n * @returns An array of Mount objects.\n */\nexport function parseMountDirArguments(mounts: string[]): Mount[] {\n\tif (mounts.length % 2 !== 0) {\n\t\tthrow new Error('Invalid mount format. Expected: /host/path /vfs/path');\n\t}\n\n\tconst parsedMounts = [];\n\tfor (let i = 0; i < mounts.length; i += 2) {\n\t\tconst source = mounts[i];\n\t\tconst vfsPath = mounts[i + 1];\n\t\tif (!existsSync(source)) {\n\t\t\tthrow new Error(`Host path does not exist: ${source}`);\n\t\t}\n\t\tparsedMounts.push({\n\t\t\thostPath: path.resolve(process.cwd(), source),\n\t\t\tvfsPath,\n\t\t});\n\t}\n\treturn parsedMounts;\n}\n\nexport async function mountResources(php: PHP, mounts: Mount[]) {\n\tfor (const mount of mounts) {\n\t\tawait php.mount(\n\t\t\tmount.vfsPath,\n\t\t\tcreateNodeFsMountHandler(mount.hostPath)\n\t\t);\n\t}\n}\n\nconst ACTIVATE_FIRST_THEME_STEP = {\n\tstep: 'runPHP',\n\tcode: {\n\t\tfilename: 'activate-theme.php',\n\t\tcontent: `<?php\n\t\t\trequire_once getenv('DOCROOT') . '/wp-load.php';\n\t\t\t$theme = wp_get_theme();\n\t\t\tif (!$theme->exists()) {\n\t\t\t\t$themes = wp_get_themes();\n\t\t\t\tif (count($themes) > 0) {\n\t\t\t\t\t$themeName = array_keys($themes)[0];\n\t\t\t\t\tswitch_theme($themeName);\n\t\t\t\t}\n\t\t\t}\n\t\t`,\n\t},\n};\n\n/**\n * Auto-mounts resolution logic:\n */\nexport function expandAutoMounts(args: RunCLIArgs): RunCLIArgs {\n\tconst path = process.cwd();\n\n\tconst mount = [...(args.mount || [])];\n\tconst mountBeforeInstall = [...(args['mount-before-install'] || [])];\n\n\tconst newArgs = {\n\t\t...args,\n\t\tmount,\n\t\t'mount-before-install': mountBeforeInstall,\n\t\t'additional-blueprint-steps': [\n\t\t\t...((args as any)['additional-blueprint-steps'] || []),\n\t\t],\n\t};\n\n\tif (isPluginFilename(path)) {\n\t\tconst pluginName = basename(path);\n\t\tmount.push({\n\t\t\thostPath: path,\n\t\t\tvfsPath: `/wordpress/wp-content/plugins/${pluginName}`,\n\t\t});\n\t\tnewArgs['additional-blueprint-steps'].push({\n\t\t\tstep: 'activatePlugin',\n\t\t\tpluginPath: `/wordpress/wp-content/plugins/${basename(path)}`,\n\t\t});\n\t} else if (isThemeDirectory(path)) {\n\t\tconst themeName = basename(path);\n\t\tmount.push({\n\t\t\thostPath: path,\n\t\t\tvfsPath: `/wordpress/wp-content/themes/${themeName}`,\n\t\t});\n\t\tnewArgs['additional-blueprint-steps'].push({\n\t\t\tstep: 'activateTheme',\n\t\t\tthemeDirectoryName: themeName,\n\t\t});\n\t} else if (containsWpContentDirectories(path)) {\n\t\t/**\n\t\t * Mount each wp-content file and directory individually.\n\t\t */\n\t\tconst files = fs.readdirSync(path);\n\t\tfor (const file of files) {\n\t\t\t/**\n\t\t\t * WordPress already ships with the wp-content/index.php file\n\t\t\t * and Playground does not support overriding existing VFS files\n\t\t\t * with mounts.\n\t\t\t */\n\t\t\tif (file === 'index.php') {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tmount.push({\n\t\t\t\thostPath: `${path}/${file}`,\n\t\t\t\tvfsPath: `/wordpress/wp-content/${file}`,\n\t\t\t});\n\t\t}\n\t\tnewArgs['additional-blueprint-steps'].push(ACTIVATE_FIRST_THEME_STEP);\n\t} else if (containsFullWordPressInstallation(path)) {\n\t\tmountBeforeInstall.push({ hostPath: path, vfsPath: '/wordpress' });\n\t\t// @TODO: Uncomment when merging Blueprints v2 support\n\t\t// newArgs.mode = 'apply-to-existing-site';\n\t\tnewArgs['additional-blueprint-steps'].push(ACTIVATE_FIRST_THEME_STEP);\n\t} else {\n\t\t/**\n\t\t * By default, mount the current working directory as the Playground root.\n\t\t * This allows users to run and PHP or HTML files using the Playground CLI.\n\t\t */\n\t\tmount.push({ hostPath: path, vfsPath: '/wordpress' });\n\t\t// @TODO: Uncomment when merging Blueprints v2 support\n\t\t// newArgs.mode = 'mount-only';\n\t}\n\n\treturn newArgs as RunCLIArgs;\n}\n\nexport function containsFullWordPressInstallation(path: string): boolean {\n\tconst files = fs.readdirSync(path);\n\treturn (\n\t\tfiles.includes('wp-admin') &&\n\t\tfiles.includes('wp-includes') &&\n\t\tfiles.includes('wp-content')\n\t);\n}\n\nexport function containsWpContentDirectories(path: string): boolean {\n\tconst files = fs.readdirSync(path);\n\treturn (\n\t\tfiles.includes('themes') ||\n\t\tfiles.includes('plugins') ||\n\t\tfiles.includes('mu-plugins') ||\n\t\tfiles.includes('uploads')\n\t);\n}\n\nexport function isThemeDirectory(path: string): boolean {\n\tconst files = fs.readdirSync(path);\n\tif (!files.includes('style.css')) {\n\t\treturn false;\n\t}\n\tconst styleCssContent = fs.readFileSync(join(path, 'style.css'), 'utf8');\n\tconst themeNameRegex = /^(?:[ \\t]*<\\?php)?[ \\t/*#@]*Theme Name:(.*)$/im;\n\treturn !!themeNameRegex.exec(styleCssContent);\n}\n\nexport function isPluginFilename(path: string): boolean {\n\tconst files = fs.readdirSync(path);\n\tconst pluginNameRegex = /^(?:[ \\t]*<\\?php)?[ \\t/*#@]*Plugin Name:(.*)$/im;\n\tconst pluginNameMatch = files\n\t\t.filter((file) => file.endsWith('.php'))\n\t\t.find((file) => {\n\t\t\tconst fileContent = fs.readFileSync(join(path, file), 'utf8');\n\t\t\treturn !!pluginNameRegex.exec(fileContent);\n\t\t});\n\treturn !!pluginNameMatch;\n}\n","import type { FileLockManager } from '@php-wasm/node';\nimport { loadNodeRuntime } from '@php-wasm/node';\nimport { EmscriptenDownloadMonitor } from '@php-wasm/progress';\nimport type { RemoteAPI, SupportedPHPVersion } 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 { bootWordPress } 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';\n\nexport interface Mount {\n\thostPath: string;\n\tvfsPath: string;\n}\n\nexport type WorkerBootOptions = {\n\twpVersion?: string;\n\tphpVersion?: SupportedPHPVersion;\n\tabsoluteUrl: string;\n\tmountsBeforeWpInstall: Array<Mount>;\n\tmountsAfterWpInstall: Array<Mount>;\n\twordPressZip?: ArrayBuffer;\n\tsqliteIntegrationPluginZip?: ArrayBuffer;\n\tfirstProcessId: number;\n\tprocessIdSpaceLength: number;\n\tdataSqlPath?: string;\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\twithXdebug?: boolean;\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 bootAsPrimaryWorker({\n\t\tabsoluteUrl,\n\t\tmountsBeforeWpInstall,\n\t\tmountsAfterWpInstall,\n\t\tphpVersion = RecommendedPHPVersion,\n\t\twordPressZip,\n\t\tsqliteIntegrationPluginZip,\n\t\tfirstProcessId,\n\t\tprocessIdSpaceLength,\n\t\tdataSqlPath,\n\t\tfollowSymlinks,\n\t\ttrace,\n\t\tinternalCookieStore,\n\t\twithXdebug,\n\t}: WorkerBootOptions) {\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 constants: Record<string, string | number | boolean | null> =\n\t\t\t\t{\n\t\t\t\t\tWP_DEBUG: true,\n\t\t\t\t\tWP_DEBUG_LOG: true,\n\t\t\t\t\tWP_DEBUG_DISPLAY: false,\n\t\t\t\t};\n\n\t\t\tconst requestHandler = await bootWordPress({\n\t\t\t\tsiteUrl: absoluteUrl,\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},\n\t\t\t\t\t\tfollowSymlinks,\n\t\t\t\t\t\twithXdebug,\n\t\t\t\t\t});\n\t\t\t\t},\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 )\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\thooks: {\n\t\t\t\t\tasync beforeWordPressFiles(php) {\n\t\t\t\t\t\tmountResources(php, mountsBeforeWpInstall);\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tcookieStore: internalCookieStore ? undefined : false,\n\t\t\t\tdataSqlPath,\n\t\t\t\tspawnHandler: sandboxedSpawnHandlerFactory,\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\tmountResources(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 bootAsSecondaryWorker(args: WorkerBootOptions) {\n\t\treturn this.bootAsPrimaryWorker(args);\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\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":["mountResources","php","mounts","mount","createNodeFsMountHandler","tracePhpWasm","processId","format","args","sprintf","PlaygroundCliBlueprintV1Worker","PHPWorker","monitor","port","jspi","consumeAPI","consumeAPISync","absoluteUrl","mountsBeforeWpInstall","mountsAfterWpInstall","phpVersion","RecommendedPHPVersion","wordPressZip","sqliteIntegrationPluginZip","firstProcessId","processIdSpaceLength","dataSqlPath","followSymlinks","trace","internalCookieStore","withXdebug","nextProcessId","lastProcessId","constants","requestHandler","bootWordPress","loadNodeRuntime","rootCertificates","sandboxedSpawnHandlerFactory","primaryPhp","setApiReady","e","setAPIError","phpChannel","MessageChannel","exposeAPI","EmscriptenDownloadMonitor","parentPort"],"mappings":";;;;;;;;;;;AAgFsB,eAAAA,EAAeC,GAAUC,GAAiB;AAC/D,aAAWC,KAASD;AACnB,UAAMD,EAAI;AAAA,MACTE,EAAM;AAAA,MACNC,EAAyBD,EAAM,QAAQ;AAAA,IACxC;AAEF;AChCA,SAASE,EAAaC,GAAmBC,MAAmBC,GAAa;AAEhE,UAAA;AAAA,I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A,EACX;AAAA,IACC,SAAS;AAAA,IACT,SAASJ,EAAW;AAAA,EACrB;AAAA,EACA,CAACA,EAAW,KAAY;AACzB;"}
@@ -0,0 +1,3 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const S=require("@php-wasm/node"),v=require("@php-wasm/progress"),r=require("@php-wasm/universal"),A=require("@php-wasm/util"),M=require("@wp-playground/common"),F=require("@wp-playground/wordpress"),D=require("tls"),E=require("wasm-feature-detect"),h=require("worker_threads"),P=require("./mounts-D7bhhGq3.cjs");function H(c,e,...s){console.log(performance.now().toFixed(6).padStart(15,"0"),c.toString().padStart(16,"0"),A.sprintf(e,...s))}class m extends r.PHPWorker{constructor(e){super(void 0,e),this.booted=!1}async useFileLockManager(e){await E.jspi()?this.fileLockManager=r.consumeAPI(e):this.fileLockManager=await r.consumeAPISync(e)}async bootAsPrimaryWorker({absoluteUrl:e,mountsBeforeWpInstall:s,mountsAfterWpInstall:w,phpVersion:y=M.RecommendedPHPVersion,wordPressZip:l,sqliteIntegrationPluginZip:d,firstProcessId:n,processIdSpaceLength:g,dataSqlPath:f,followSymlinks:b,trace:k,internalCookieStore:q,withXdebug:W}){if(this.booted)throw new Error("Playground already booted");this.booted=!0;let o=n;const _=n+g-1;try{const t={WP_DEBUG:!0,WP_DEBUG_LOG:!0,WP_DEBUG_DISPLAY:!1},u=await F.bootWordPress({siteUrl:e,createPhpRuntime:async()=>{const i=o;return o<_?o++:o=n,await S.loadNodeRuntime(y,{emscriptenOptions:{fileLockManager:this.fileLockManager,processId:i,trace:k?H:void 0},followSymlinks:b,withXdebug:W})},wordPressZip:l!==void 0?new File([l],"wordpress.zip"):void 0,sqliteIntegrationPluginZip:d!==void 0?new File([d],"sqlite-integration-plugin.zip"):void 0,sapiName:"cli",createFiles:{"/internal/shared/ca-bundle.crt":D.rootCertificates.join(`
2
+ `)},constants:t,phpIniEntries:{"openssl.cafile":"/internal/shared/ca-bundle.crt",allow_url_fopen:"1",disable_functions:""},hooks:{async beforeWordPressFiles(i){P.mountResources(i,s)}},cookieStore:q?void 0:!1,dataSqlPath:f,spawnHandler:r.sandboxedSpawnHandlerFactory});this.__internal_setRequestHandler(u);const p=await u.getPrimaryPhp();await this.setPrimaryPHP(p),P.mountResources(p,w),I()}catch(t){throw L(t),t}}async bootAsSecondaryWorker(e){return this.bootAsPrimaryWorker(e)}async dispose(){await this[Symbol.asyncDispose]()}}const a=new h.MessageChannel,[I,L]=r.exposeAPI(new m(new v.EmscriptenDownloadMonitor),void 0,a.port1);h.parentPort.postMessage({command:"worker-script-initialized",phpPort:a.port2},[a.port2]);exports.PlaygroundCliBlueprintV1Worker=m;
3
+ //# sourceMappingURL=worker-thread-v1.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker-thread-v1.cjs","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 { RemoteAPI, SupportedPHPVersion } 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 { bootWordPress } 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';\n\nexport interface Mount {\n\thostPath: string;\n\tvfsPath: string;\n}\n\nexport type WorkerBootOptions = {\n\twpVersion?: string;\n\tphpVersion?: SupportedPHPVersion;\n\tabsoluteUrl: string;\n\tmountsBeforeWpInstall: Array<Mount>;\n\tmountsAfterWpInstall: Array<Mount>;\n\twordPressZip?: ArrayBuffer;\n\tsqliteIntegrationPluginZip?: ArrayBuffer;\n\tfirstProcessId: number;\n\tprocessIdSpaceLength: number;\n\tdataSqlPath?: string;\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\twithXdebug?: boolean;\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 bootAsPrimaryWorker({\n\t\tabsoluteUrl,\n\t\tmountsBeforeWpInstall,\n\t\tmountsAfterWpInstall,\n\t\tphpVersion = RecommendedPHPVersion,\n\t\twordPressZip,\n\t\tsqliteIntegrationPluginZip,\n\t\tfirstProcessId,\n\t\tprocessIdSpaceLength,\n\t\tdataSqlPath,\n\t\tfollowSymlinks,\n\t\ttrace,\n\t\tinternalCookieStore,\n\t\twithXdebug,\n\t}: WorkerBootOptions) {\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 constants: Record<string, string | number | boolean | null> =\n\t\t\t\t{\n\t\t\t\t\tWP_DEBUG: true,\n\t\t\t\t\tWP_DEBUG_LOG: true,\n\t\t\t\t\tWP_DEBUG_DISPLAY: false,\n\t\t\t\t};\n\n\t\t\tconst requestHandler = await bootWordPress({\n\t\t\t\tsiteUrl: absoluteUrl,\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},\n\t\t\t\t\t\tfollowSymlinks,\n\t\t\t\t\t\twithXdebug,\n\t\t\t\t\t});\n\t\t\t\t},\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 )\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\thooks: {\n\t\t\t\t\tasync beforeWordPressFiles(php) {\n\t\t\t\t\t\tmountResources(php, mountsBeforeWpInstall);\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tcookieStore: internalCookieStore ? undefined : false,\n\t\t\t\tdataSqlPath,\n\t\t\t\tspawnHandler: sandboxedSpawnHandlerFactory,\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\tmountResources(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 bootAsSecondaryWorker(args: WorkerBootOptions) {\n\t\treturn this.bootAsPrimaryWorker(args);\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\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","absoluteUrl","mountsBeforeWpInstall","mountsAfterWpInstall","phpVersion","RecommendedPHPVersion","wordPressZip","sqliteIntegrationPluginZip","firstProcessId","processIdSpaceLength","dataSqlPath","followSymlinks","trace","internalCookieStore","withXdebug","nextProcessId","lastProcessId","constants","requestHandler","bootWordPress","loadNodeRuntime","rootCertificates","php","mountResources","sandboxedSpawnHandlerFactory","primaryPhp","setApiReady","e","setAPIError","phpChannel","MessageChannel","exposeAPI","EmscriptenDownloadMonitor","parentPort"],"mappings":"yYAuDA,SAASA,EAAaC,EAAmBC,KAAmBC,EAAa,CAEhE,QAAA,IACP,YAAY,MAAM,QAAQ,CAAC,EAAE,SAAS,GAAI,GAAG,EAC7CF,EAAU,SAAW,EAAA,SAAS,GAAI,GAAG,EACrCG,EAAA,QAAQF,EAAQ,GAAGC,CAAI,CACxB,CACD,CAEO,MAAME,UAAuCC,EAAAA,SAAU,CAI7D,YAAYC,EAAoC,CAC/C,MAAM,OAAWA,CAAO,EAJhB,KAAA,OAAA,EAAA,CAgBT,MAAM,mBAAmBC,EAAmB,CACvC,MAAMC,SASJ,KAAA,gBAAkBC,aAA4BF,CAAI,EAUlD,KAAA,gBAAkB,MAAMG,EAAA,eAAgCH,CAA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AK,cAAcO,CAAU,EAEnCF,EAAA,eAAeE,EAAYtB,CAAoB,EAEnCuB,EAAA,QACJC,EAAG,CACX,MAAAC,EAAYD,CAAU,EAChBA,CAAA,CACP,CAGD,MAAM,sBAAsBnC,EAAyB,CAC7C,OAAA,KAAK,oBAAoBA,CAAI,CAAA,CAIrC,MAAM,SAAU,CACT,MAAA,KAAK,OAAO,YAAY,EAAE,CAAA,CAElC,CAEA,MAAMqC,EAAa,IAAIC,EAAAA,eAEjB,CAACJ,EAAaE,CAAW,EAAIG,EAAA,UAClC,IAAIrC,EAA+B,IAAIsC,EAAAA,yBAA2B,EAClE,OACAH,EAAW,KACZ,EAEAI,EAAAA,WAAY,YACX,CACC,QAAS,4BACT,QAASJ,EAAW,KACrB,EACA,CAACA,EAAW,KAAY,CACzB"}
@@ -1,21 +1,21 @@
1
- import { loadNodeRuntime as k } from "@php-wasm/node";
2
- import { EmscriptenDownloadMonitor as v } from "@php-wasm/progress";
3
- import { exposeAPI as M, PHPWorker as S, consumeAPI as W, consumeAPISync as E, sandboxedSpawnHandlerFactory as F } from "@php-wasm/universal";
4
- import { sprintf as H } from "@php-wasm/util";
5
- import { RecommendedPHPVersion as I } from "@wp-playground/common";
6
- import { bootWordPress as L } from "@wp-playground/wordpress";
7
- import { rootCertificates as x } from "tls";
8
- import { jspi as A } from "wasm-feature-detect";
1
+ import { loadNodeRuntime as W } from "@php-wasm/node";
2
+ import { EmscriptenDownloadMonitor as _ } from "@php-wasm/progress";
3
+ import { exposeAPI as A, PHPWorker as S, consumeAPI as v, consumeAPISync as M, sandboxedSpawnHandlerFactory as E } from "@php-wasm/universal";
4
+ import { sprintf as F } from "@php-wasm/util";
5
+ import { RecommendedPHPVersion as H } from "@wp-playground/common";
6
+ import { bootWordPress as I } from "@wp-playground/wordpress";
7
+ import { rootCertificates as L } from "tls";
8
+ import { jspi as x } from "wasm-feature-detect";
9
9
  import { MessageChannel as D, parentPort as R } from "worker_threads";
10
10
  import { m } from "./mounts-B-Qdcyyt.js";
11
- function C(n, e, ...t) {
11
+ function B(n, e, ...t) {
12
12
  console.log(
13
13
  performance.now().toFixed(6).padStart(15, "0"),
14
14
  n.toString().padStart(16, "0"),
15
- H(e, ...t)
15
+ F(e, ...t)
16
16
  );
17
17
  }
18
- class G extends S {
18
+ class C extends S {
19
19
  constructor(e) {
20
20
  super(void 0, e), this.booted = !1;
21
21
  }
@@ -29,13 +29,13 @@ class G extends S {
29
29
  * @see phpwasm-emscripten-library-file-locking-for-node.js
30
30
  */
31
31
  async useFileLockManager(e) {
32
- await A() ? this.fileLockManager = W(e) : this.fileLockManager = await E(e);
32
+ await x() ? this.fileLockManager = v(e) : this.fileLockManager = await M(e);
33
33
  }
34
- async boot({
34
+ async bootAsPrimaryWorker({
35
35
  absoluteUrl: e,
36
36
  mountsBeforeWpInstall: t,
37
- mountsAfterWpInstall: f,
38
- phpVersion: P = I,
37
+ mountsAfterWpInstall: P,
38
+ phpVersion: f = H,
39
39
  wordPressZip: c,
40
40
  sqliteIntegrationPluginZip: p,
41
41
  firstProcessId: i,
@@ -43,31 +43,31 @@ class G extends S {
43
43
  dataSqlPath: u,
44
44
  followSymlinks: w,
45
45
  trace: y,
46
- internalCookieStore: g,
47
- withXdebug: b
46
+ internalCookieStore: b,
47
+ withXdebug: g
48
48
  }) {
49
49
  if (this.booted)
50
50
  throw new Error("Playground already booted");
51
51
  this.booted = !0;
52
52
  let o = i;
53
- const _ = i + h - 1;
53
+ const k = i + h - 1;
54
54
  try {
55
55
  const r = {
56
56
  WP_DEBUG: !0,
57
57
  WP_DEBUG_LOG: !0,
58
58
  WP_DEBUG_DISPLAY: !1
59
- }, l = await L({
59
+ }, l = await I({
60
60
  siteUrl: e,
61
61
  createPhpRuntime: async () => {
62
62
  const s = o;
63
- return o < _ ? o++ : o = i, await k(P, {
63
+ return o < k ? o++ : o = i, await W(f, {
64
64
  emscriptenOptions: {
65
65
  fileLockManager: this.fileLockManager,
66
66
  processId: s,
67
- trace: y ? C : void 0
67
+ trace: y ? B : void 0
68
68
  },
69
69
  followSymlinks: w,
70
- withXdebug: b
70
+ withXdebug: g
71
71
  });
72
72
  },
73
73
  wordPressZip: c !== void 0 ? new File([c], "wordpress.zip") : void 0,
@@ -77,7 +77,7 @@ class G extends S {
77
77
  ) : void 0,
78
78
  sapiName: "cli",
79
79
  createFiles: {
80
- "/internal/shared/ca-bundle.crt": x.join(`
80
+ "/internal/shared/ca-bundle.crt": L.join(`
81
81
  `)
82
82
  },
83
83
  constants: r,
@@ -91,24 +91,27 @@ class G extends S {
91
91
  m(s, t);
92
92
  }
93
93
  },
94
- cookieStore: g ? void 0 : !1,
94
+ cookieStore: b ? void 0 : !1,
95
95
  dataSqlPath: u,
96
- spawnHandler: F
96
+ spawnHandler: E
97
97
  });
98
98
  this.__internal_setRequestHandler(l);
99
99
  const d = await l.getPrimaryPhp();
100
- await this.setPrimaryPHP(d), m(d, f), U();
100
+ await this.setPrimaryPHP(d), m(d, P), G();
101
101
  } catch (r) {
102
- throw q(r), r;
102
+ throw U(r), r;
103
103
  }
104
104
  }
105
+ async bootAsSecondaryWorker(e) {
106
+ return this.bootAsPrimaryWorker(e);
107
+ }
105
108
  // Provide a named disposal method that can be invoked via comlink.
106
109
  async dispose() {
107
110
  await this[Symbol.asyncDispose]();
108
111
  }
109
112
  }
110
- const a = new D(), [U, q] = M(
111
- new G(new v()),
113
+ const a = new D(), [G, U] = A(
114
+ new C(new _()),
112
115
  void 0,
113
116
  a.port1
114
117
  );
@@ -120,6 +123,6 @@ R.postMessage(
120
123
  [a.port2]
121
124
  );
122
125
  export {
123
- G as PlaygroundCliWorker
126
+ C as PlaygroundCliBlueprintV1Worker
124
127
  };
125
- //# sourceMappingURL=worker-thread.js.map
128
+ //# sourceMappingURL=worker-thread-v1.js.map