@wp-playground/cli 3.0.22 → 3.0.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-cli-D8BNUM1f.cjs","sources":["../../../../packages/playground/cli/src/mounts.ts","../../../../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/utils/progress.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/temp-dir.ts","../../../../packages/playground/cli/src/run-cli.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';\nimport type { Mount } from '@php-wasm/cli-util';\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\t// @TODO: Remove DOCROOT check after moving totally to Blueprints v2.\n\t\tcontent: `<?php\n\t\t\t$docroot = getenv('DOCROOT') ? getenv('DOCROOT') : '/wordpress';\n\t\t\trequire_once \"$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 = args.autoMount!;\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\targs['experimental-blueprints-v2-runner']\n\t\t\t\t? {\n\t\t\t\t\t\tstep: 'activateTheme',\n\t\t\t\t\t\tthemeDirectoryName: themeName,\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tstep: 'activateTheme',\n\t\t\t\t\t\tthemeFolderName: themeName,\n\t\t\t\t\t}\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: If overriding another mode, throw an error or print a warning.\n\t\tnewArgs.mode = 'apply-to-existing-site';\n\t\tnewArgs['additional-blueprint-steps'].push(ACTIVATE_FIRST_THEME_STEP);\n\t\tif (!newArgs.wordpressInstallMode) {\n\t\t\tnewArgs.wordpressInstallMode =\n\t\t\t\t'install-from-existing-files-if-needed';\n\t\t}\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: If overriding another mode, throw an error or print a warning.\n\t\tnewArgs.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 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';\nimport { logger } from '@php-wasm/logger';\n\nexport interface ServerOptions {\n\tport: number;\n\tonBind: (server: Server, port: number) => Promise<RunCLIServer | void>;\n\thandleRequest: (request: PHPRequest) => Promise<PHPResponse>;\n}\n\nexport async function startServer(\n\toptions: ServerOptions\n): Promise<RunCLIServer | void> {\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\tlet phpResponse: PHPResponse;\n\t\ttry {\n\t\t\tphpResponse = await options.handleRequest({\n\t\t\t\turl: req.url,\n\t\t\t\theaders: parseHeaders(req),\n\t\t\t\tmethod: req.method as any,\n\t\t\t\tbody: await bufferRequestBody(req),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tlogger.error(error);\n\t\t\tphpResponse = PHPResponse.forHttpCode(500);\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\tasync removeWorker(worker: RemoteAPI<PlaygroundCliWorker>) {\n\t\tconst workerIndex = this.workerLoads.findIndex(\n\t\t\t(workerLoad) => workerLoad.worker === worker\n\t\t);\n\t\tif (workerIndex === -1) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst [removedWorker] = this.workerLoads.splice(workerIndex, 1);\n\n\t\t// A worker can only be considered fully removed once all\n\t\t// its active requests have settled.\n\t\tawait Promise.allSettled(removedWorker.activeRequests);\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 * - \"trunk\" (legacy alias: \"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","export function shouldRenderProgress(\n\twriteStream?: { isTTY?: boolean } | null\n): boolean {\n\tif (process.env['CI'] === 'true' || process.env['CI'] === '1') {\n\t\treturn false;\n\t}\n\tif (\n\t\tprocess.env['GITHUB_ACTIONS'] === 'true' ||\n\t\tprocess.env['GITHUB_ACTIONS'] === '1'\n\t) {\n\t\treturn false;\n\t}\n\tif ((process.env['TERM'] || '').toLowerCase() === 'dumb') {\n\t\treturn false;\n\t}\n\tif (writeStream) {\n\t\treturn Boolean(writeStream.isTTY);\n\t}\n\treturn process.stdout.isTTY;\n}\n","import type { RemoteAPI, SupportedPHPVersion } from '@php-wasm/universal';\nimport { consumeAPI } from '@php-wasm/universal';\nimport type {\n\tPlaygroundCliBlueprintV2Worker,\n\tSecondaryWorkerBootArgs,\n} from './worker-thread-v2';\nimport type { MessagePort as NodeMessagePort } from 'worker_threads';\nimport type { RunCLIArgs, SpawnedWorker, WorkerType } from '../run-cli';\nimport { shouldRenderProgress } from '../utils/progress';\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\tgetWorkerType(): WorkerType {\n\t\treturn 'v2';\n\t}\n\n\tasync bootAndSetUpInitialPlayground(\n\t\tphpPort: NodeMessagePort,\n\t\tfileLockManagerPort: NodeMessagePort,\n\t\tnativeInternalDirPath: string\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\tphpVersion: 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\twithIntl: this.args.intl,\n\t\t\t// We do not enable Xdebug by default for the initial worker\n\t\t\t// because we do not imagine users expect to hit breakpoints\n\t\t\t// until Playground has fully booted.\n\t\t\t// TODO: Consider supporting Xdebug for the initial worker via a dedicated flag.\n\t\t\twithXdebug: false,\n\t\t\txdebug: undefined,\n\t\t\tnativeInternalDirPath,\n\t\t\tmountsBeforeWpInstall: this.args['mount-before-install'] || [],\n\t\t\tmountsAfterWpInstall: this.args.mount || [],\n\t\t};\n\n\t\tawait playground.bootAndSetUpInitialWorker(workerBootArgs);\n\t\treturn playground;\n\t}\n\n\tasync bootPlayground({\n\t\tworker,\n\t\tfileLockManagerPort,\n\t\tfirstProcessId,\n\t\tnativeInternalDirPath,\n\t}: {\n\t\tworker: SpawnedWorker;\n\t\tfileLockManagerPort: NodeMessagePort;\n\t\tfirstProcessId: number;\n\t\tnativeInternalDirPath: string;\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: SecondaryWorkerBootArgs = {\n\t\t\t...this.args,\n\t\t\tphpVersion: 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\twithIntl: this.args.intl,\n\t\t\twithXdebug: !!this.args.xdebug,\n\t\t\tnativeInternalDirPath,\n\t\t\tmountsBeforeWpInstall: this.args['mount-before-install'] || [],\n\t\t\tmountsAfterWpInstall: this.args.mount || [],\n\t\t};\n\n\t\tawait playground.bootWorker(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 (!shouldRenderProgress(writeStream)) {\n\t\t\treturn;\n\t\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 { consumeAPI } from '@php-wasm/universal';\nimport type { BlueprintV1Declaration } from '@wp-playground/blueprints';\nimport {\n\tcompileBlueprintV1,\n\tisBlueprintBundle,\n\tresolveRuntimeConfiguration,\n} 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';\nimport type { MessagePort as NodeMessagePort } from 'worker_threads';\nimport {\n\tLogVerbosity,\n\ttype RunCLIArgs,\n\ttype SpawnedWorker,\n\ttype WorkerType,\n} from '../run-cli';\nimport { shouldRenderProgress } from '../utils/progress';\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 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\tgetWorkerType(): WorkerType {\n\t\treturn 'v1';\n\t}\n\n\tasync bootAndSetUpInitialPlayground(\n\t\tphpPort: NodeMessagePort,\n\t\tfileLockManagerPort: NodeMessagePort,\n\t\tnativeInternalDirPath: string\n\t) {\n\t\tlet wpDetails: any = undefined;\n\t\tlet wordPressZip: any = undefined;\n\t\tlet preinstalledWpContentPath: string | undefined = 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.wordpressInstallMode === 'download-and-install') {\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\tthis.writeProgressUpdate(\n\t\t\t\t\tprocess.stdout,\n\t\t\t\t\t`Downloading WordPress ${percentProgress}%...`,\n\t\t\t\t\tprogressReached100\n\t\t\t\t);\n\t\t\t}) as any);\n\n\t\t\twpDetails = await resolveWordPressRelease(this.args.wp);\n\t\t\tpreinstalledWpContentPath = path.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\t\twordPressZip = fs.existsSync(preinstalledWpContentPath)\n\t\t\t\t? readAsFile(preinstalledWpContentPath)\n\t\t\t\t: await cachedDownload(\n\t\t\t\t\t\twpDetails.releaseUrl,\n\t\t\t\t\t\t`${wpDetails.version}.zip`,\n\t\t\t\t\t\tmonitor\n\t\t\t\t\t);\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\tlet sqliteIntegrationPluginZip;\n\t\tif (this.args.skipSqliteSetup) {\n\t\t\tlogger.log(`Skipping SQLite integration plugin setup...`);\n\t\t\tsqliteIntegrationPluginZip = undefined;\n\t\t} else {\n\t\t\tlogger.log(`Fetching SQLite integration plugin...`);\n\t\t\tsqliteIntegrationPluginZip = await fetchSqliteIntegration(monitor);\n\t\t}\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\tconst runtimeConfiguration = await resolveRuntimeConfiguration(\n\t\t\tthis.getEffectiveBlueprint()\n\t\t);\n\n\t\tawait playground.useFileLockManager(fileLockManagerPort);\n\t\tawait playground.bootAndSetUpInitialWorker({\n\t\t\tphpVersion: runtimeConfiguration.phpVersion,\n\t\t\twpVersion: runtimeConfiguration.wpVersion,\n\t\t\tsiteUrl: this.siteUrl,\n\t\t\tmountsBeforeWpInstall,\n\t\t\tmountsAfterWpInstall,\n\t\t\twordpressInstallMode:\n\t\t\t\tthis.args.wordpressInstallMode || 'download-and-install',\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\twithIntl: this.args.intl,\n\t\t\t// We do not enable Xdebug by default for the initial worker\n\t\t\t// because we do not imagine users expect to hit breakpoints\n\t\t\t// until Playground has fully booted.\n\t\t\t// TODO: Consider supporting Xdebug for the initial worker via a dedicated flag.\n\t\t\twithXdebug: false,\n\t\t\tnativeInternalDirPath,\n\t\t});\n\n\t\tif (\n\t\t\tpreinstalledWpContentPath &&\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 bootPlayground({\n\t\tworker,\n\t\tfileLockManagerPort,\n\t\tfirstProcessId,\n\t\tnativeInternalDirPath,\n\t}: {\n\t\tworker: SpawnedWorker;\n\t\tfileLockManagerPort: NodeMessagePort;\n\t\tfirstProcessId: number;\n\t\tnativeInternalDirPath: string;\n\t}) {\n\t\tconst playground = consumeAPI<PlaygroundCliBlueprintV1Worker>(\n\t\t\tworker.phpPort\n\t\t);\n\n\t\tawait playground.isConnected();\n\t\tconst runtimeConfiguration = await resolveRuntimeConfiguration(\n\t\t\tthis.getEffectiveBlueprint()\n\t\t);\n\t\tawait playground.useFileLockManager(fileLockManagerPort);\n\t\tawait playground.bootWorker({\n\t\t\tphpVersion: runtimeConfiguration.phpVersion,\n\t\t\tsiteUrl: this.siteUrl,\n\t\t\tmountsBeforeWpInstall: this.args['mount-before-install'] || [],\n\t\t\tmountsAfterWpInstall: this.args['mount'] || [],\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\twithIntl: this.args.intl,\n\t\t\twithXdebug: !!this.args.xdebug,\n\t\t\tnativeInternalDirPath,\n\t\t});\n\t\tawait playground.isReady();\n\t\treturn playground;\n\t}\n\n\tasync compileInputBlueprint(additionalBlueprintSteps: any[]) {\n\t\tconst blueprint = this.getEffectiveBlueprint();\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\tthis.writeProgressUpdate(\n\t\t\t\tprocess.stdout,\n\t\t\t\tmessage,\n\t\t\t\tprogressReached100\n\t\t\t);\n\t\t});\n\t\treturn await compileBlueprintV1(blueprint as BlueprintV1Declaration, {\n\t\t\tprogress: tracker,\n\t\t\tadditionalSteps: additionalBlueprintSteps,\n\t\t});\n\t}\n\n\tprivate getEffectiveBlueprint() {\n\t\tconst resolvedBlueprint = this.args.blueprint as BlueprintV1Declaration;\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\treturn isBlueprintBundle(resolvedBlueprint)\n\t\t\t? resolvedBlueprint\n\t\t\t: {\n\t\t\t\t\tlogin: this.args.login,\n\t\t\t\t\t...(resolvedBlueprint || {}),\n\t\t\t\t\tpreferredVersions: {\n\t\t\t\t\t\tphp:\n\t\t\t\t\t\t\tthis.args.php ??\n\t\t\t\t\t\t\tresolvedBlueprint?.preferredVersions?.php ??\n\t\t\t\t\t\t\tRecommendedPHPVersion,\n\t\t\t\t\t\twp:\n\t\t\t\t\t\t\tthis.args.wp ??\n\t\t\t\t\t\t\tresolvedBlueprint?.preferredVersions?.wp ??\n\t\t\t\t\t\t\t'latest',\n\t\t\t\t\t\t...(resolvedBlueprint?.preferredVersions || {}),\n\t\t\t\t\t},\n\t\t\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 (this.args.verbosity === LogVerbosity.Quiet.name) {\n\t\t\treturn;\n\t\t}\n\t\tif (!shouldRenderProgress(writeStream)) {\n\t\t\treturn;\n\t\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 fs from 'fs';\nimport path from 'path';\nimport { logger } from '@php-wasm/logger';\nimport {\n\tdir as tmpDir,\n\tsetGracefulCleanup as tmpSetGracefulCleanup,\n} from 'tmp-promise';\n// NOTE: We use ps-man rather than more popular packages because there\n// is no native build required to install the package.\n// @ts-ignore -- There are no types for this package.\nimport ps from 'ps-man';\n\n/**\n * Create a temp dir for the Playground CLI.\n *\n * The temp dir is created in the system temp dir and is named\n * based on the Playground CLI binary name and the process ID.\n *\n * @param substrToIdentifyTempDirs The substring to identify the temp dir.\n * @param autoCleanup Whether to skip cleanup on process exit. Primarily used for unit testing.\n * @returns The path to the temp dir.\n */\nexport async function createPlaygroundCliTempDir(\n\tsubstrToIdentifyTempDirs: string,\n\t// Allow controlling auto-cleanup for test purposes.\n\tautoCleanup = true\n) {\n\tconst nodeBinaryName = path.basename(process.argv0);\n\n\t// We place the binary name before the playground-related fragment\n\t// so we can use the position of the fragment to parse the binary name.\n\t// Otherwise, we would have to parse the binary name from the full path.\n\tconst tempDirPrefix = `${nodeBinaryName}${substrToIdentifyTempDirs}${process.pid}-`;\n\n\tconst nativeDir = await tmpDir({\n\t\tprefix: tempDirPrefix,\n\t\t/*\n\t\t * Allow recursive cleanup on process exit.\n\t\t *\n\t\t * NOTE: I worried about whether this cleanup would follow symlinks\n\t\t * and delete target files instead of unlinking the symlink,\n\t\t * but this feature uses rimraf under the hood which respects symlinks:\n\t\t * https://github.com/raszi/node-tmp/blob/3d2fe387f3f91b13830b9182faa02c3231ea8258/lib/tmp.js#L318\n\t\t */\n\t\tunsafeCleanup: true,\n\t});\n\n\tif (autoCleanup) {\n\t\t// Request graceful cleanup on process exit.\n\t\ttmpSetGracefulCleanup();\n\t}\n\n\treturn nativeDir;\n}\n\n/**\n * Cleanup stale Playground temp dirs.\n *\n * A temp dir is considered stale if it is older than the specified age\n * and the associated process no longer exists.\n *\n * @param substrToIdentifyTempDirs The substring to identify the temp dir.\n * @param staleAgeInMillis The age in milliseconds after which a temp dir is considered stale.\n * @param tempRootDir The root directory of the temp dirs.\n */\nexport async function cleanupStalePlaygroundTempDirs(\n\tsubstrToIdentifyTempDirs: string,\n\tstaleAgeInMillis: number,\n\ttempRootDir: string\n) {\n\tconst stalePlaygroundTempDirs = await findStalePlaygroundTempDirs(\n\t\tsubstrToIdentifyTempDirs,\n\t\tstaleAgeInMillis,\n\t\ttempRootDir\n\t);\n\tconst promisesToRemove = stalePlaygroundTempDirs.map(\n\t\t(stalePlaygroundTempDir) =>\n\t\t\tnew Promise<void>((resolve) => {\n\t\t\t\t// TODO: Non-blocking: Consider how to avoid conflicts with another CLI doing cleanup.\n\t\t\t\tfs.rm(stalePlaygroundTempDir, { recursive: true }, (err) => {\n\t\t\t\t\tif (err) {\n\t\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t\t`Failed to delete stale Playground temp dir: ${stalePlaygroundTempDir}`,\n\t\t\t\t\t\t\terr\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlogger.info(\n\t\t\t\t\t\t\t`Deleted stale Playground temp dir: ${stalePlaygroundTempDir}`\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tresolve();\n\t\t\t\t});\n\t\t\t})\n\t);\n\tawait Promise.all(promisesToRemove);\n}\n\nasync function findStalePlaygroundTempDirs(\n\tsubstrToIdentifyTempDirs: string,\n\tstaleAgeInMillis: number,\n\ttempRootDir: string\n) {\n\ttry {\n\t\tconst tempPaths = fs\n\t\t\t.readdirSync(tempRootDir)\n\t\t\t.map((dirName) => path.join(tempRootDir, dirName));\n\n\t\tconst stalePlaygroundTempDirs = [];\n\t\tfor (const tempPath of tempPaths) {\n\t\t\tconst appearsToBeStale = await appearsToBeStalePlaygroundTempDir(\n\t\t\t\tsubstrToIdentifyTempDirs,\n\t\t\t\tstaleAgeInMillis,\n\t\t\t\ttempPath\n\t\t\t);\n\t\t\tif (appearsToBeStale) {\n\t\t\t\tstalePlaygroundTempDirs.push(tempPath);\n\t\t\t}\n\t\t}\n\t\treturn stalePlaygroundTempDirs;\n\t} catch (e) {\n\t\tlogger.warn(`Failed to find stale Playground temp dirs: ${e}`);\n\t\t// Failing to find stale temp dirs should not prevent the CLI from starting.\n\t\treturn [];\n\t}\n}\n\nasync function appearsToBeStalePlaygroundTempDir(\n\tsubstrToIdentifyTempDirs: string,\n\tstaleAgeInMillis: number,\n\tabsolutePath: string\n) {\n\tconst lstat = fs.lstatSync(absolutePath);\n\tif (!lstat.isDirectory()) {\n\t\t// A non-directory cannot be a Playground temp dir.\n\t\treturn false;\n\t}\n\n\tconst dirName = path.basename(absolutePath);\n\tif (!dirName.includes(substrToIdentifyTempDirs)) {\n\t\t// This doesn't look like one of our temp dirs.\n\t\treturn false;\n\t}\n\n\tconst match = dirName.match(\n\t\tnew RegExp(`^(.+)${substrToIdentifyTempDirs}(\\\\d+)-`)\n\t);\n\tif (!match) {\n\t\t// We cannot parse the temp dir name,\n\t\t// so there is nothing more to try.\n\t\treturn false;\n\t}\n\n\tconst info = {\n\t\tabsolutePath,\n\t\texecutableName: match[1],\n\t\tpid: match[2],\n\t};\n\n\tif (await doesProcessExist(info.pid, info.executableName)) {\n\t\t// It looks like the temp dir's process is still running.\n\t\treturn false;\n\t}\n\n\tconst STALE_DATE = Date.now() - staleAgeInMillis;\n\tconst dirStat = fs.statSync(absolutePath);\n\tif (dirStat.mtime.getTime() < STALE_DATE) {\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nasync function doesProcessExist(pid: string, executableName: string) {\n\t// Define this type because there are no types for ps.list()\n\ttype ProcessInfo = {\n\t\tpid: string;\n\t\tcommand: string;\n\t};\n\t// Look for an existing process with the same PID and executable name.\n\tconst [existingProcess] = await new Promise<ProcessInfo[]>(\n\t\t(resolve, reject) => {\n\t\t\tps.list(\n\t\t\t\t{\n\t\t\t\t\tpid,\n\t\t\t\t\tname: executableName,\n\t\t\t\t\t// Remove path from executable name in the results.\n\t\t\t\t\tclean: true,\n\t\t\t\t},\n\t\t\t\t(err: any, processes: ProcessInfo[]) => {\n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresolve(processes);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\t);\n\treturn (\n\t\t!!existingProcess &&\n\t\texistingProcess.pid === pid &&\n\t\texistingProcess.command === executableName\n\t);\n}\n","import { errorLogPath, logger, LogSeverity } from '@php-wasm/logger';\nimport type {\n\tPHPRequest,\n\tRemoteAPI,\n\tSupportedPHPVersion,\n\tUniversalPHP,\n} from '@php-wasm/universal';\nimport {\n\tPHPResponse,\n\texposeAPI,\n\texposeSyncAPI,\n\tprintDebugDetails,\n} from '@php-wasm/universal';\nimport type {\n\tBlueprintBundle,\n\tBlueprintV1Declaration,\n\tBlueprintV2Declaration,\n} from '@wp-playground/blueprints';\nimport { runBlueprintV1Steps } from '@wp-playground/blueprints';\nimport { RecommendedPHPVersion } from '@wp-playground/common';\nimport fs, { mkdirSync } 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 { PlaygroundCliBlueprintV1Worker } 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, { type Argv, type Options as YargsOptions } 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';\nimport { startBridge } from '@php-wasm/xdebug-bridge';\nimport path from 'path';\nimport os from 'os';\nimport {\n\tcleanupStalePlaygroundTempDirs,\n\tcreatePlaygroundCliTempDir,\n} from './temp-dir';\nimport { type WordPressInstallMode } from '@wp-playground/wordpress';\nimport {\n\ttype Mount,\n\taddXdebugIDEConfig,\n\tclearXdebugIDEConfig,\n\tcreateTempDirSymlink,\n\tremoveTempDirSymlink,\n} from '@php-wasm/cli-util';\n\n// Inlined worker URLs for static analysis by downstream bundlers\n// These are replaced at build time by the Vite plugin in vite.config.ts\ndeclare const __WORKER_V1_URL__: string;\ndeclare const __WORKER_V2_URL__: string;\n\nexport const LogVerbosity = {\n\tQuiet: { name: 'quiet', severity: LogSeverity.Fatal },\n\tNormal: { name: 'normal', severity: LogSeverity.Info },\n\tDebug: { name: 'debug', severity: LogSeverity.Debug },\n} as const;\n\ntype LogVerbosity = (typeof LogVerbosity)[keyof typeof LogVerbosity]['name'];\n\nexport type WorkerType = 'v1' | 'v2';\n\n/**\n * Parse the CLI args and run the appropriate command.\n *\n * @param argsToParse string[] The CLI args to parse.\n */\nexport async function parseOptionsAndRunCLI(argsToParse: string[]) {\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 sharedOptions: Record<string, YargsOptions> = {\n\t\t\t'site-url': {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Site URL to use for WordPress. Defaults to http://127.0.0.1:{port}',\n\t\t\t\ttype: 'string',\n\t\t\t},\n\t\t\tphp: {\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\twp: {\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\tmount: {\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'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'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\tcoerce: parseMountDirArguments,\n\t\t\t},\n\t\t\t'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\tlogin: {\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\tblueprint: {\n\t\t\t\tdescribe: 'Blueprint to execute.',\n\t\t\t\ttype: 'string',\n\t\t\t},\n\t\t\t'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'wordpress-install-mode': {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Control how Playground prepares WordPress before booting.',\n\t\t\t\ttype: 'string',\n\t\t\t\tdefault: 'download-and-install',\n\t\t\t\tchoices: [\n\t\t\t\t\t'download-and-install',\n\t\t\t\t\t'install-from-existing-files',\n\t\t\t\t\t'install-from-existing-files-if-needed',\n\t\t\t\t\t'do-not-attempt-installing',\n\t\t\t\t] as const,\n\t\t\t},\n\t\t\t'skip-wordpress-install': {\n\t\t\t\tdescribe: '[Deprecated] Use --wordpress-install-mode instead.',\n\t\t\t\ttype: 'boolean',\n\t\t\t\thidden: true,\n\t\t\t},\n\t\t\t'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// Hidden - Deprecated in favor of verbosity\n\t\t\tquiet: {\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\thidden: true,\n\t\t\t},\n\t\t\tverbosity: {\n\t\t\t\tdescribe: 'Output logs and progress messages.',\n\t\t\t\ttype: 'string',\n\t\t\t\tchoices: Object.values(LogVerbosity).map(\n\t\t\t\t\t(verbosity) => verbosity.name\n\t\t\t\t),\n\t\t\t\tdefault: 'normal',\n\t\t\t},\n\t\t\tdebug: {\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'auto-mount': {\n\t\t\t\tdescribe: `Automatically mount the specified directory. If no path is provided, mount the current working directory. You can mount a WordPress directory, a plugin directory, a theme directory, a wp-content directory, or any directory containing PHP and HTML files.`,\n\t\t\t\ttype: 'string',\n\t\t\t},\n\t\t\t'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'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'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\tintl: {\n\t\t\t\tdescribe: 'Enable Intl.',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: true,\n\t\t\t},\n\t\t\txdebug: {\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'experimental-unsafe-ide-integration': {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Enable experimental IDE development tools. This option edits IDE config files ' +\n\t\t\t\t\t'to set Xdebug path mappings and web server details. CAUTION: If there are bugs, ' +\n\t\t\t\t\t'this feature may break your IDE config files. Please consider backing up your IDE configs ' +\n\t\t\t\t\t'before using this feature.',\n\t\t\t\ttype: 'string',\n\t\t\t\t// The empty value means the option is enabled for all\n\t\t\t\t// supported IDEs and, if needed, will create the relevant\n\t\t\t\t// config file for each.\n\t\t\t\tchoices: ['', 'vscode', 'phpstorm'],\n\t\t\t\tcoerce: (value?: string) =>\n\t\t\t\t\tvalue === '' ? ['vscode', 'phpstorm'] : [value],\n\t\t\t},\n\t\t\t'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\tmode: {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Blueprints v2 runner mode to use. This option is required when using the --experimental-blueprints-v2-runner flag with a blueprint.',\n\t\t\t\ttype: 'string',\n\t\t\t\tchoices: ['create-new-site', 'apply-to-existing-site'],\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};\n\n\t\tconst serverOnlyOptions: Record<string, YargsOptions> = {\n\t\t\tport: {\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'experimental-multi-worker': {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Enable experimental multi-worker support which requires ' +\n\t\t\t\t\t'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'experimental-devtools': {\n\t\t\t\tdescribe: 'Enable experimental browser development tools.',\n\t\t\t\ttype: 'boolean',\n\t\t\t},\n\t\t};\n\n\t\tconst buildSnapshotOnlyOptions: Record<string, YargsOptions> = {\n\t\t\toutfile: {\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};\n\n\t\tconst yargsObject = yargs(argsToParse)\n\t\t\t.usage('Usage: wp-playground <command> [options]')\n\t\t\t.command(\n\t\t\t\t'server',\n\t\t\t\t'Start a local WordPress server',\n\t\t\t\t(yargsInstance: Argv) =>\n\t\t\t\t\tyargsInstance.options({\n\t\t\t\t\t\t...sharedOptions,\n\t\t\t\t\t\t...serverOnlyOptions,\n\t\t\t\t\t})\n\t\t\t)\n\t\t\t.command(\n\t\t\t\t'run-blueprint',\n\t\t\t\t'Execute a Blueprint without starting a server',\n\t\t\t\t(yargsInstance: Argv) =>\n\t\t\t\t\tyargsInstance.options({ ...sharedOptions })\n\t\t\t)\n\t\t\t.command(\n\t\t\t\t'build-snapshot',\n\t\t\t\t'Build a ZIP snapshot of a WordPress site based on a Blueprint',\n\t\t\t\t(yargsInstance: Argv) =>\n\t\t\t\t\tyargsInstance.options({\n\t\t\t\t\t\t...sharedOptions,\n\t\t\t\t\t\t...buildSnapshotOnlyOptions,\n\t\t\t\t\t})\n\t\t\t)\n\t\t\t.demandCommand(1, 'Please specify a command')\n\t\t\t.strictCommands()\n\t\t\t.conflicts(\n\t\t\t\t'experimental-unsafe-ide-integration',\n\t\t\t\t'experimental-devtools'\n\t\t\t)\n\t\t\t.showHelpOnFail(false)\n\t\t\t.fail((msg, err, yargsInstance) => {\n\t\t\t\tif (err) {\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t\tif (msg && msg.includes('Please specify a command')) {\n\t\t\t\t\tyargsInstance.showHelp();\n\t\t\t\t\tconsole.error('\\n' + msg);\n\t\t\t\t\tprocess.exit(1);\n\t\t\t\t}\n\t\t\t\tconsole.error(msg);\n\t\t\t\tprocess.exit(1);\n\t\t\t})\n\t\t\t.strictOptions()\n\t\t\t.check(async (args) => {\n\t\t\t\tif (args['skip-wordpress-install'] === true) {\n\t\t\t\t\targs['wordpress-install-mode'] =\n\t\t\t\t\t\t'do-not-attempt-installing';\n\t\t\t\t\targs['wordpressInstallMode'] = 'do-not-attempt-installing';\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\targs['wp'] !== undefined &&\n\t\t\t\t\ttypeof args['wp'] === 'string' &&\n\t\t\t\t\t!isValidWordPressSlug(args['wp'])\n\t\t\t\t) {\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\tconst siteUrlArg = args['site-url'];\n\t\t\t\tif (\n\t\t\t\t\ttypeof siteUrlArg === 'string' &&\n\t\t\t\t\tsiteUrlArg.trim() !== ''\n\t\t\t\t) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tnew URL(siteUrlArg);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Invalid site-url \"${siteUrlArg}\". Please provide a valid URL (e.g., http://localhost:8080 or https://example.com)`\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['auto-mount']) {\n\t\t\t\t\tlet autoMountIsDir = false;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst autoMountStats = fs.statSync(\n\t\t\t\t\t\t\targs['auto-mount'] as string\n\t\t\t\t\t\t);\n\t\t\t\t\t\tautoMountIsDir = autoMountStats.isDirectory();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tautoMountIsDir = false;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!autoMountIsDir) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`The specified --auto-mount path is not a directory: '${args['auto-mount']}'.`\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\tconst cliCommand = args._[0] as string;\n\t\t\t\t\tif (cliCommand !== 'server') {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t'The --experimental-multi-worker flag is only supported when running the server command.'\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\targs['experimental-multi-worker'] !== undefined &&\n\t\t\t\t\t\ttypeof args['experimental-multi-worker'] === 'number' &&\n\t\t\t\t\t\targs['experimental-multi-worker'] <= 1\n\t\t\t\t\t) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t'The --experimental-multi-worker flag must be a positive integer greater than 1.'\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-blueprints-v2-runner'] === true) {\n\t\t\t\t\tif (args['mode'] !== undefined) {\n\t\t\t\t\t\tif (args['wordpress-install-mode'] !== undefined) {\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t'The --wordpress-install-mode option cannot be used with the --mode option. Use one or the other.'\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ('skip-sqlite-setup' in args) {\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t'The --skipSqliteSetup option is not supported in Blueprint V2 mode.'\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (args['auto-mount'] !== undefined) {\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t'The --mode option cannot be used with --auto-mount because --auto-mount automatically sets the mode.'\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Support the legacy v1 runner options\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\targs['wordpress-install-mode'] ===\n\t\t\t\t\t\t\t'do-not-attempt-installing'\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\targs['mode'] = 'apply-to-existing-site';\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\targs['mode'] = 'create-new-site';\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Support the legacy v1 runner options\n\t\t\t\t\tconst allow = (args['allow'] as string[]) || [];\n\n\t\t\t\t\tif (args['followSymlinks'] === true) {\n\t\t\t\t\t\tallow.push('follow-symlinks');\n\t\t\t\t\t}\n\n\t\t\t\t\tif (args['blueprint-may-read-adjacent-files'] === true) {\n\t\t\t\t\t\tallow.push('read-local-fs');\n\t\t\t\t\t}\n\n\t\t\t\t\targs['allow'] = allow;\n\t\t\t\t} else {\n\t\t\t\t\tif (args['mode'] !== undefined) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t'The --mode option requires the --experimentalBlueprintsV2Runner flag.'\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\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: [\n\t\t\t\t...((args['mount'] as Mount[]) || []),\n\t\t\t\t...((args['mount-dir'] as Mount[]) || []),\n\t\t\t],\n\t\t\t'mount-before-install': [\n\t\t\t\t...((args['mount-before-install'] as Mount[]) || []),\n\t\t\t\t...((args['mount-dir-before-install'] as Mount[]) || []),\n\t\t\t],\n\t\t} as RunCLIArgs;\n\n\t\tconst cliServer = await runCLI(cliArgs);\n\t\tif (cliServer === undefined) {\n\t\t\t// No server was started, so we are done with our work.\n\t\t\tprocess.exit(0);\n\t\t}\n\n\t\tconst cleanUpCliAndExit = (() => {\n\t\t\t// Remember we are already cleaning up to preclude the possibility\n\t\t\t// of multiple, conflicting cleanup attempts.\n\t\t\tlet promiseToCleanup: Promise<void>;\n\n\t\t\treturn async () => {\n\t\t\t\tif (promiseToCleanup !== undefined) {\n\t\t\t\t\tpromiseToCleanup = cliServer[Symbol.asyncDispose]();\n\t\t\t\t}\n\t\t\t\tawait promiseToCleanup;\n\t\t\t\tprocess.exit(0);\n\t\t\t};\n\t\t})();\n\n\t\t// Playground CLI server must be killed to exit. From the terminal,\n\t\t// this may occur via Ctrl+C which sends SIGINT. Let's handle both\n\t\t// SIGINT and SIGTERM (the default kill signal) to make sure we\n\t\t// clean up after ourselves even if this process is being killed.\n\t\t// NOTE: Windows does not support SIGTERM, but Node.js provides some emulation.\n\t\tprocess.on('SIGINT', cleanUpCliAndExit);\n\t\tprocess.on('SIGTERM', cleanUpCliAndExit);\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?:\n\t\t| BlueprintV1Declaration\n\t\t| BlueprintV2Declaration\n\t\t| 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\t'site-url'?: string;\n\tquiet?: boolean;\n\tverbosity?: LogVerbosity;\n\twp?: string;\n\tautoMount?: string;\n\texperimentalMultiWorker?: number;\n\texperimentalTrace?: boolean;\n\tinternalCookieStore?: boolean;\n\t'additional-blueprint-steps'?: any[];\n\tintl?: boolean;\n\txdebug?: boolean | { ideKey?: string };\n\texperimentalUnsafeIdeIntegration?: string[];\n\texperimentalDevtools?: boolean;\n\t'experimental-blueprints-v2-runner'?: boolean;\n\twordpressInstallMode?: WordPressInstallMode;\n\n\t// --------- Blueprint V1 args -----------\n\tskipSqliteSetup?: boolean;\n\tfollowSymlinks?: boolean;\n\t'blueprint-may-read-adjacent-files'?: boolean;\n\n\t// --------- Blueprint V2 args -----------\n\tmode?: 'mount-only' | 'create-new-site' | 'apply-to-existing-site';\n\n\t// --------- Blueprint V2 args (not available via CLI yet) -----------\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 const internalsKeyForTesting = Symbol('playground-cli-testing');\n\nexport interface RunCLIServer extends AsyncDisposable {\n\tplayground: RemoteAPI<PlaygroundCliWorker>;\n\tserver: Server;\n\tserverUrl: string;\n\n\t[Symbol.asyncDispose](): Promise<void>;\n\n\t// Provide some details and helpers for automated testing.\n\t[internalsKeyForTesting]: {\n\t\tworkerThreadCount: number;\n\t\tgetWorkerNumberFromProcessId(processId: number): number;\n\t};\n}\n\nconst bold = (text: string) =>\n\tprocess.stdout.isTTY ? '\\x1b[1m' + text + '\\x1b[0m' : text;\n\nconst dim = (text: string) =>\n\tprocess.stdout.isTTY ? `\\x1b[2m${text}\\x1b[0m` : text;\n\nconst italic = (text: string) =>\n\tprocess.stdout.isTTY ? `\\x1b[3m${text}\\x1b[0m` : text;\n\nconst highlight = (text: string) =>\n\tprocess.stdout.isTTY ? `\\x1b[33m${text}\\x1b[0m` : text;\n\n// These overloads are declared for convenience so runCLI() can return\n// different things depending on the CLI command without forcing the\n// callers (mostly automated tests) to check return values.\nexport async function runCLI(\n\targs: RunCLIArgs & { command: 'build-snapshot' | 'run-blueprint' }\n): Promise<void>;\nexport async function runCLI(\n\targs: RunCLIArgs & { command: 'server' }\n): Promise<RunCLIServer>;\nexport async function runCLI(args: RunCLIArgs): Promise<RunCLIServer | void>;\nexport async function runCLI(args: RunCLIArgs): Promise<RunCLIServer | void> {\n\tlet loadBalancer: LoadBalancer;\n\tlet playground: RemoteAPI<PlaygroundCliWorker>;\n\n\tconst playgroundsToCleanUp: Map<\n\t\tWorker,\n\t\tRemoteAPI<PlaygroundCliWorker>\n\t> = new Map();\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 !== undefined) {\n\t\tif (args.autoMount === '') {\n\t\t\t// No auto-mount path was provided, so use the current working directory.\n\t\t\t// Note: We default here instead of in the yargs declaration because\n\t\t\t// it allows us to test the default as part of the runCLI() unit tests.\n\t\t\targs = { ...args, autoMount: process.cwd() };\n\t\t}\n\t\targs = expandAutoMounts(args);\n\t}\n\n\tif (args.wordpressInstallMode === undefined) {\n\t\targs.wordpressInstallMode = 'download-and-install';\n\t}\n\n\t// Keeping 'quiet' option to preserve backward compatibility\n\tif (args.quiet) {\n\t\targs.verbosity = 'quiet';\n\t\tdelete args['quiet'];\n\t}\n\n\t// Promote \"debug\" flag to verbosity but keep args.debug around – the\n\t// program behavior may change in more ways than just logging verbosity\n\t// when debug mode is enabled, e.g. error objects may carry additional details.\n\tif (args.debug) {\n\t\targs.verbosity = 'debug';\n\t} else if (args.verbosity === 'debug') {\n\t\targs.debug = true;\n\t}\n\n\tif (args.verbosity) {\n\t\tconst severity = Object.values(LogVerbosity).find(\n\t\t\t(v) => v.name === args.verbosity\n\t\t)!.severity;\n\t\tlogger.setSeverityFilterLevel(severity);\n\t}\n\n\t// Enables Intl dynamic extension by default\n\tif (!args.intl) {\n\t\targs.intl = true;\n\t}\n\n\tconst selectedPort =\n\t\targs.command === 'server' ? ((args['port'] as number) ?? 9400) : 0;\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 =\n\t\tos.platform() === 'win32'\n\t\t\t? // @TODO: Enable fs-ext here when it works with Windows.\n\t\t\t\tundefined\n\t\t\t: await import('fs-ext')\n\t\t\t\t\t.then((m) => m.flockSync)\n\t\t\t\t\t.catch(() => {\n\t\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t\t'The fs-ext package is not installed. ' +\n\t\t\t\t\t\t\t\t'Internal file locking will not be integrated with ' +\n\t\t\t\t\t\t\t\t'host OS file locking.'\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn undefined;\n\t\t\t\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: selectedPort,\n\t\tonBind: async (server: Server, port: number) => {\n\t\t\tconst host = '127.0.0.1';\n\t\t\tconst serverUrl = `http://${host}:${port}`;\n\t\t\tconst siteUrl = args['site-url'] || serverUrl;\n\n\t\t\tconst targetWorkerCount =\n\t\t\t\targs.command === 'server'\n\t\t\t\t\t? (args.experimentalMultiWorker ?? 1)\n\t\t\t\t\t: 1;\n\t\t\tconst totalWorkersToSpawn =\n\t\t\t\targs.command === 'server'\n\t\t\t\t\t? // Account for the initial worker which is discarded by the server after setup.\n\t\t\t\t\t\ttargetWorkerCount + 1\n\t\t\t\t\t: targetWorkerCount;\n\n\t\t\t// Process IDs appear to be defined as `int` in Emscripten:\n\t\t\t// https://github.com/emscripten-core/emscripten/blob/95d2bf9c5c27b88ab7de6eba2d8e61ea1af977ac/system/lib/libc/musl/arch/emscripten/bits/alltypes.h#L290\n\t\t\t// and those are typically 32 bits wide in both 32-bit and 64-bit systems.\n\t\t\t// Apparently, this is a signed type, so we cannot use the leftmost bit.\n\t\t\tconst maxValueForSigned32BitInteger = 2 ** (32 - 1) - 1;\n\t\t\tconst maxProcessIdValue = maxValueForSigned32BitInteger;\n\t\t\tconst processIdSpaceLength = Math.floor(\n\t\t\t\tmaxProcessIdValue / totalWorkersToSpawn\n\t\t\t);\n\n\t\t\t/*\n\t\t\t * Use a real temp dir as a target for the following Playground paths\n\t\t\t * so that multiple worker threads can share the same files.\n\t\t\t * - /internal\n\t\t\t * - /tmp\n\t\t\t * - /wordpress\n\t\t\t *\n\t\t\t * Sharing the same files leads to faster boot times and uses less memory\n\t\t\t * because we don't have to create or maintain multiple copies of the same files.\n\t\t\t */\n\t\t\tconst tempDirNameDelimiter = '-playground-cli-site-';\n\t\t\tconst nativeDir =\n\t\t\t\tawait createPlaygroundCliTempDir(tempDirNameDelimiter);\n\t\t\tlogger.debug(`Native temp dir for VFS root: ${nativeDir.path}`);\n\n\t\t\tconst IDEConfigName = 'WP Playground CLI - Listen for Xdebug';\n\n\t\t\t// Always clean up any existing Playground files symlink in the project root.\n\t\t\tconst symlinkName = '.playground-xdebug-root';\n\t\t\tconst symlinkPath = path.join(process.cwd(), symlinkName);\n\n\t\t\tawait removeTempDirSymlink(symlinkPath);\n\n\t\t\t// Then, if xdebug, and experimental IDE are enabled,\n\t\t\t// recreate the symlink pointing to the temporary\n\t\t\t// directory and add the new IDE config.\n\t\t\tif (args.xdebug && args.experimentalUnsafeIdeIntegration) {\n\t\t\t\tawait createTempDirSymlink(\n\t\t\t\t\tnativeDir.path,\n\t\t\t\t\tsymlinkPath,\n\t\t\t\t\tprocess.platform\n\t\t\t\t);\n\n\t\t\t\tconst symlinkMount: Mount = {\n\t\t\t\t\thostPath: path.join('.', path.sep, symlinkName),\n\t\t\t\t\tvfsPath: '/',\n\t\t\t\t};\n\n\t\t\t\ttry {\n\t\t\t\t\t// NOTE: Both the 'clear' and 'add' operations can throw errors.\n\t\t\t\t\tawait clearXdebugIDEConfig(IDEConfigName, process.cwd());\n\n\t\t\t\t\tconst xdebugOptions =\n\t\t\t\t\t\ttypeof args.xdebug === 'object'\n\t\t\t\t\t\t\t? args.xdebug\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\tconst modifiedConfig = await addXdebugIDEConfig({\n\t\t\t\t\t\tname: IDEConfigName,\n\t\t\t\t\t\thost: host,\n\t\t\t\t\t\tport: port,\n\t\t\t\t\t\tides: args.experimentalUnsafeIdeIntegration!,\n\t\t\t\t\t\tcwd: process.cwd(),\n\t\t\t\t\t\tmounts: [\n\t\t\t\t\t\t\tsymlinkMount,\n\t\t\t\t\t\t\t...(args['mount-before-install'] || []),\n\t\t\t\t\t\t\t...(args.mount || []),\n\t\t\t\t\t\t],\n\t\t\t\t\t\tideKey: xdebugOptions?.ideKey,\n\t\t\t\t\t});\n\n\t\t\t\t\t// Display IDE-specific instructions\n\t\t\t\t\tconst ides = args.experimentalUnsafeIdeIntegration;\n\t\t\t\t\tconst hasVSCode = ides.includes('vscode');\n\t\t\t\t\tconst hasPhpStorm = ides.includes('phpstorm');\n\t\t\t\t\tconst configFiles = Object.values(modifiedConfig);\n\n\t\t\t\t\tconsole.log('');\n\n\t\t\t\t\tif (configFiles.length > 0) {\n\t\t\t\t\t\tconsole.log(bold(`Xdebug configured successfully`));\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\thighlight(`Updated IDE config: `) +\n\t\t\t\t\t\t\t\tconfigFiles.join(' ')\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\thighlight('Playground source root: ') +\n\t\t\t\t\t\t\t\t`.playground-xdebug-root` +\n\t\t\t\t\t\t\t\titalic(\n\t\t\t\t\t\t\t\t\tdim(\n\t\t\t\t\t\t\t\t\t\t` – you can set breakpoints and preview Playground's VFS structure in there.`\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.log(bold(`Xdebug configuration failed.`));\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t'No IDE-specific project settings directory was found in the current working directory.'\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\tconsole.log('');\n\n\t\t\t\t\tif (hasVSCode && modifiedConfig['vscode']) {\n\t\t\t\t\t\tconsole.log(bold('VS Code / Cursor instructions:'));\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t' 1. Ensure you have installed an IDE extension for PHP Debugging'\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t` (The ${bold('PHP Debug')} extension by ${bold(\n\t\t\t\t\t\t\t\t'Xdebug'\n\t\t\t\t\t\t\t)} has been a solid option)`\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t' 2. Open the Run and Debug panel on the left sidebar'\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t` 3. Select \"${italic(\n\t\t\t\t\t\t\t\tIDEConfigName\n\t\t\t\t\t\t\t)}\" from the dropdown`\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconsole.log(' 3. Click \"start debugging\"');\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t' 5. Set a breakpoint. For example, in .playground-xdebug-root/wordpress/index.php'\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t' 6. Visit Playground in your browser to hit the breakpoint'\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (hasPhpStorm) {\n\t\t\t\t\t\t\tconsole.log('');\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (hasPhpStorm && modifiedConfig['phpstorm']) {\n\t\t\t\t\t\tconsole.log(bold('PhpStorm instructions:'));\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t` 1. Choose \"${italic(\n\t\t\t\t\t\t\t\tIDEConfigName\n\t\t\t\t\t\t\t)}\" debug configuration in the toolbar`\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconsole.log(' 2. Click the debug button (bug icon)`');\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t' 3. Set a breakpoint. For example, in .playground-xdebug-root/wordpress/index.php'\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t' 4. Visit Playground in your browser to hit the breakpoint'\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\tconsole.log('');\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthrow new Error('Could not configure Xdebug', {\n\t\t\t\t\t\tcause: error,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// We do not know the system temp dir,\n\t\t\t// but we can try to infer from the location of the current temp dir.\n\t\t\tconst tempDirRoot = path.dirname(nativeDir.path);\n\n\t\t\tconst twoDaysInMillis = 2 * 24 * 60 * 60 * 1000;\n\t\t\tconst tempDirStaleAgeInMillis = twoDaysInMillis;\n\n\t\t\t// NOTE: This is an async operation, but we do not care to block on it.\n\t\t\t// Let's let the cleanup happen as the main thread has time.\n\t\t\tcleanupStalePlaygroundTempDirs(\n\t\t\t\ttempDirNameDelimiter,\n\t\t\t\ttempDirStaleAgeInMillis,\n\t\t\t\ttempDirRoot\n\t\t\t);\n\n\t\t\t// NOTE: We do not add mount declarations for /internal here\n\t\t\t// because it will be mounted as part of php-wasm init.\n\t\t\tconst nativeInternalDirPath = path.join(nativeDir.path, 'internal');\n\t\t\tmkdirSync(nativeInternalDirPath);\n\n\t\t\tconst userProvidableNativeSubdirs = [\n\t\t\t\t'wordpress',\n\t\t\t\t// Note: These dirs are from Emscripten's \"default dirs\" list:\n\t\t\t\t// https://github.com/emscripten-core/emscripten/blob/f431ec220e472e1f8d3db6b52fe23fb377facf30/src/lib/libfs.js#L1400-L1402\n\t\t\t\t//\n\t\t\t\t// Any Playground process with multiple workers may assume\n\t\t\t\t// these are part of a shared filesystem, so let's recognize\n\t\t\t\t// them explicitly here.\n\t\t\t\t'tmp',\n\t\t\t\t'home',\n\t\t\t];\n\n\t\t\tfor (const subdirName of userProvidableNativeSubdirs) {\n\t\t\t\tconst isMountingSubdirName = (mount: Mount) =>\n\t\t\t\t\tmount.vfsPath === `/${subdirName}`;\n\t\t\t\tconst thisSubdirHasAMount =\n\t\t\t\t\targs['mount-before-install']?.some(isMountingSubdirName) ||\n\t\t\t\t\targs['mount']?.some(isMountingSubdirName);\n\t\t\t\tif (!thisSubdirHasAMount) {\n\t\t\t\t\t// The user hasn't requested mounting a different native dir for this path,\n\t\t\t\t\t// so let's create a mount from within our native temp dir.\n\t\t\t\t\tconst nativeSubdirPath = path.join(\n\t\t\t\t\t\tnativeDir.path,\n\t\t\t\t\t\tsubdirName\n\t\t\t\t\t);\n\t\t\t\t\tmkdirSync(nativeSubdirPath);\n\n\t\t\t\t\tif (args['mount-before-install'] === undefined) {\n\t\t\t\t\t\targs['mount-before-install'] = [];\n\t\t\t\t\t}\n\n\t\t\t\t\t// Make the real mount first so any further subdirs are mounted into it.\n\t\t\t\t\targs['mount-before-install'].unshift({\n\t\t\t\t\t\tvfsPath: `/${subdirName}`,\n\t\t\t\t\t\thostPath: nativeSubdirPath,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (args['mount-before-install']) {\n\t\t\t\tfor (const mount of args['mount-before-install']) {\n\t\t\t\t\tlogger.debug(\n\t\t\t\t\t\t`Mount before WP install: ${mount.vfsPath} -> ${mount.hostPath}`\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (args['mount']) {\n\t\t\t\tfor (const mount of args['mount']) {\n\t\t\t\t\tlogger.debug(\n\t\t\t\t\t\t`Mount after WP install: ${mount.vfsPath} -> ${mount.hostPath}`\n\t\t\t\t\t);\n\t\t\t\t}\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,\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,\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// Remember whether we are already disposing so we can avoid:\n\t\t\t// - we can avoid multiple, conflicting dispose attempts\n\t\t\t// - logging that a worker exited while the CLI itself is exiting\n\t\t\tlet disposing = false;\n\t\t\tconst disposeCLI = async function disposeCLI() {\n\t\t\t\tif (disposing) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tdisposing = true;\n\t\t\t\tawait Promise.all(\n\t\t\t\t\t[...playgroundsToCleanUp].map(\n\t\t\t\t\t\tasync ([worker, playground]) => {\n\t\t\t\t\t\t\tawait playground.dispose();\n\t\t\t\t\t\t\tawait worker.terminate();\n\t\t\t\t\t\t}\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t\tif (server) {\n\t\t\t\t\tawait new Promise((resolve) => server.close(resolve));\n\t\t\t\t}\n\t\t\t\tawait nativeDir.cleanup();\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\ttotalWorkersToSpawn,\n\t\t\t\thandler.getWorkerType(),\n\t\t\t\t({ exitCode, workerIndex }) => {\n\t\t\t\t\t// We are already disposing, so worker exit is expected\n\t\t\t\t\t// and does not need to be logged.\n\t\t\t\t\tif (disposing) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (exitCode !== 0) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\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// @TODO: Should we respawn the worker if it exited with an error and the CLI is not shutting down?\n\t\t\t\t}\n\t\t\t);\n\n\t\t\tlogger.log(`Starting up workers`);\n\n\t\t\ttry {\n\t\t\t\tconst workers = await promisedWorkers;\n\n\t\t\t\tconst fileLockManagerPort =\n\t\t\t\t\tawait exposeFileLockManager(fileLockManager);\n\n\t\t\t\t// NOTE: Using a free-standing block to isolate initial boot vars\n\t\t\t\t// while keeping the logic inline.\n\t\t\t\t{\n\t\t\t\t\t// Boot the primary worker using the handler\n\t\t\t\t\tconst initialWorker = workers.shift()!;\n\t\t\t\t\tconst initialPlayground =\n\t\t\t\t\t\tawait handler.bootAndSetUpInitialPlayground(\n\t\t\t\t\t\t\tinitialWorker.phpPort,\n\t\t\t\t\t\t\tfileLockManagerPort,\n\t\t\t\t\t\t\tnativeInternalDirPath\n\t\t\t\t\t\t);\n\t\t\t\t\tplaygroundsToCleanUp.set(\n\t\t\t\t\t\tinitialWorker.worker,\n\t\t\t\t\t\tinitialPlayground\n\t\t\t\t\t);\n\n\t\t\t\t\tawait initialPlayground.isReady();\n\t\t\t\t\twordPressReady = true;\n\t\t\t\t\tlogger.log(`Booted!`);\n\n\t\t\t\t\tloadBalancer = new LoadBalancer(initialPlayground);\n\n\t\t\t\t\tif (!args['experimental-blueprints-v2-runner']) {\n\t\t\t\t\t\tconst compiledBlueprint = await (\n\t\t\t\t\t\t\thandler as BlueprintsV1Handler\n\t\t\t\t\t\t).compileInputBlueprint(\n\t\t\t\t\t\t\targs['additional-blueprint-steps'] || []\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tif (compiledBlueprint) {\n\t\t\t\t\t\t\tlogger.log(`Running the Blueprint...`);\n\t\t\t\t\t\t\tawait runBlueprintV1Steps(\n\t\t\t\t\t\t\t\tcompiledBlueprint,\n\t\t\t\t\t\t\t\tinitialPlayground as UniversalPHP\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tlogger.log(`Finished running the blueprint`);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (args.command === 'build-snapshot') {\n\t\t\t\t\t\tawait zipSite(playground, args.outfile as string);\n\t\t\t\t\t\tlogger.log(`WordPress exported to ${args.outfile}`);\n\t\t\t\t\t\tawait disposeCLI();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t} else if (args.command === 'run-blueprint') {\n\t\t\t\t\t\tlogger.log(`Blueprint executed`);\n\t\t\t\t\t\tawait disposeCLI();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t// We discard the initial Playground worker because it can\n\t\t\t\t\t// be configured differently than post-boot workers.\n\t\t\t\t\t// For example, we do not enable Xdebug by default for the initial worker.\n\t\t\t\t\tawait loadBalancer.removeWorker(initialPlayground);\n\t\t\t\t\tawait initialPlayground.dispose();\n\t\t\t\t\tawait initialWorker.worker.terminate();\n\t\t\t\t\tplaygroundsToCleanUp.delete(initialWorker.worker);\n\t\t\t\t}\n\n\t\t\t\tlogger.log(`Preparing workers...`);\n\n\t\t\t\t// Boot additional workers using the handler\n\t\t\t\tconst initialWorkerProcessIdSpace = processIdSpaceLength;\n\t\t\t\t// Just take the first Playground instance to be returned to the caller.\n\t\t\t\t[playground] = await Promise.all(\n\t\t\t\t\tworkers.map(async (worker, index) => {\n\t\t\t\t\t\tconst firstProcessId =\n\t\t\t\t\t\t\tinitialWorkerProcessIdSpace +\n\t\t\t\t\t\t\tindex * processIdSpaceLength;\n\n\t\t\t\t\t\tconst fileLockManagerPort =\n\t\t\t\t\t\t\tawait exposeFileLockManager(fileLockManager);\n\n\t\t\t\t\t\tconst additionalPlayground =\n\t\t\t\t\t\t\tawait handler.bootPlayground({\n\t\t\t\t\t\t\t\tworker,\n\t\t\t\t\t\t\t\tfileLockManagerPort,\n\t\t\t\t\t\t\t\tfirstProcessId,\n\t\t\t\t\t\t\t\tnativeInternalDirPath,\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\tplaygroundsToCleanUp.set(\n\t\t\t\t\t\t\tworker.worker,\n\t\t\t\t\t\t\tadditionalPlayground\n\t\t\t\t\t\t);\n\t\t\t\t\t\tloadBalancer.addWorker(additionalPlayground);\n\n\t\t\t\t\t\treturn additionalPlayground;\n\t\t\t\t\t})\n\t\t\t\t);\n\n\t\t\t\tlogger.log(\n\t\t\t\t\t`WordPress is running on ${serverUrl} with ${targetWorkerCount} worker(s)`\n\t\t\t\t);\n\n\t\t\t\tif (args.xdebug && args.experimentalDevtools) {\n\t\t\t\t\tconst bridge = await startBridge({\n\t\t\t\t\t\tphpInstance: playground,\n\t\t\t\t\t\tphpRoot: '/wordpress',\n\t\t\t\t\t});\n\n\t\t\t\t\tbridge.start();\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\tplayground,\n\t\t\t\t\tserver,\n\t\t\t\t\tserverUrl,\n\t\t\t\t\t[Symbol.asyncDispose]: disposeCLI,\n\t\t\t\t\t[internalsKeyForTesting]: {\n\t\t\t\t\t\tworkerThreadCount: targetWorkerCount,\n\t\t\t\t\t\tgetWorkerNumberFromProcessId: (processId: number) => {\n\t\t\t\t\t\t\treturn Math.floor(processId / processIdSpaceLength);\n\t\t\t\t\t\t},\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\tawait disposeCLI();\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: [request.url],\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};\n\nasync function spawnWorkerThreads(\n\tcount: number,\n\tworkerType: WorkerType,\n\tonWorkerExit: (options: { exitCode: number; workerIndex: number }) => void\n): Promise<SpawnedWorker[]> {\n\tconst promises = [];\n\tfor (let i = 0; i < count; i++) {\n\t\tconst onExit: (code: number) => void = (code: number) => {\n\t\t\tonWorkerExit({\n\t\t\t\texitCode: code,\n\t\t\t\tworkerIndex: i,\n\t\t\t});\n\t\t};\n\t\tconst worker = spawnWorkerThread(workerType, { onExit });\n\t\tpromises.push(worker);\n\t}\n\treturn Promise.all(promises);\n}\n\n/**\n * A statically analyzable function that spawns a worker thread of a given type.\n *\n * **Important:** This function builds to code that has the worker URL hardcoded\n * inline, e.g. `new Worker(new URL('./worker-thread-v1.js', import.meta.url))`.\n * This allows the downstream consumers to statically analyze the code, recognize\n * it uses workers, create new entrypoints, and rewrite the new Worker() calls.\n *\n * @param workerType\n * @returns\n */\nexport function spawnWorkerThread(\n\tworkerType: 'v1' | 'v2',\n\t{ onExit }: { onExit?: (code: number) => void } = {}\n) {\n\t/**\n\t * When running the CLI from source via `node cli.ts`, the Vite-provided\n\t * __WORKER_V1_URL__ and __WORKER_V2_URL__ are undefined. Let's set them to\n\t * the correct paths.\n\t */\n\tif (typeof __WORKER_V1_URL__ === 'undefined') {\n\t\t// @ts-expect-error\n\t\tglobalThis['__WORKER_V1_URL__'] = './blueprints-v1/worker-thread-v1.ts';\n\t}\n\tif (typeof __WORKER_V2_URL__ === 'undefined') {\n\t\t// @ts-expect-error\n\t\tglobalThis['__WORKER_V2_URL__'] = './blueprints-v2/worker-thread-v2.ts';\n\t}\n\tlet worker: Worker;\n\tif (workerType === 'v1') {\n\t\tworker = new Worker(new URL(__WORKER_V1_URL__, import.meta.url));\n\t} else {\n\t\tworker = new Worker(new URL(__WORKER_V2_URL__, import.meta.url));\n\t}\n\n\treturn new Promise<SpawnedWorker>((resolve, reject) => {\n\t\tworker.once('message', function (message: any) {\n\t\t\t// Let the worker confirm it has initialized.\n\t\t\t// We could use the 'online' event to detect start of JS execution,\n\t\t\t// but that would miss initialization errors.\n\t\t\tif (message.command === 'worker-script-initialized') {\n\t\t\t\tresolve({ worker, phpPort: message.phpPort });\n\t\t\t}\n\t\t});\n\t\tworker.once('error', function (e: Error) {\n\t\t\tconsole.error(e);\n\t\t\tconst error = new Error(\n\t\t\t\t`Worker failed to load worker. ${\n\t\t\t\t\te.message ? `Original error: ${e.message}` : ''\n\t\t\t\t}`\n\t\t\t);\n\t\t\treject(error);\n\t\t});\n\t\tlet spawned = false;\n\t\tworker.once('spawn', () => {\n\t\t\tspawned = true;\n\t\t});\n\t\tworker.once('exit', (code) => {\n\t\t\tif (!spawned) {\n\t\t\t\treject(new Error(`Worker exited before spawning: ${code}`));\n\t\t\t}\n\t\t\tonExit?.(code);\n\t\t});\n\t});\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":["parseMountWithDelimiterArguments","mounts","parsedMounts","mount","mountParts","hostPath","vfsPath","existsSync","parseMountDirArguments","i","source","path","mountResources","php","createNodeFsMountHandler","ACTIVATE_FIRST_THEME_STEP","expandAutoMounts","args","mountBeforeInstall","newArgs","isPluginFilename","pluginName","basename","isThemeDirectory","themeName","containsWpContentDirectories","files","fs","file","containsFullWordPressInstallation","styleCssContent","join","pluginNameRegex","fileContent","startServer","options","app","express","server","resolve","reject","address","req","res","phpResponse","parseHeaders","bufferRequestBody","error","logger","PHPResponse","key","port","body","chunk","requestHeaders","LoadBalancer","initialWorker","worker","workerIndex","workerLoad","removedWorker","request","smallestWorkerLoad","promiseForResponse","isValidWordPressSlug","version","resolveBlueprint","sourceString","blueprintMayReadAdjacentFiles","resolveRemoteBlueprint","blueprintPath","stat","extension","ZipFilesystem","blueprintText","contextPath","nodeJsFilesystem","NodeJsFilesystem","OverlayFilesystem","InMemoryFilesystem","shouldRenderProgress","writeStream","BlueprintsV2Handler","phpPort","fileLockManagerPort","nativeInternalDirPath","playground","consumeAPI","workerBootArgs","firstProcessId","message","finalUpdate","CACHE_FOLDER","os","fetchSqliteIntegration","monitor","cachedDownload","remoteUrl","cacheKey","artifactPath","downloadTo","readAsFile","localPath","reader","tmpPath","writer","done","value","err","fileName","BlueprintsV1Handler","wpDetails","wordPressZip","preinstalledWpContentPath","EmscriptenDownloadMonitor","progressReached100","e","loaded","total","percentProgress","resolveWordPressRelease","sqliteIntegrationPluginZip","followSymlinks","trace","mountsBeforeWpInstall","mountsAfterWpInstall","runtimeConfiguration","resolveRuntimeConfiguration","zipDirectory","additionalBlueprintSteps","blueprint","tracker","ProgressTracker","lastCaption","progressInteger","compileBlueprintV1","resolvedBlueprint","isBlueprintBundle","RecommendedPHPVersion","LogVerbosity","createPlaygroundCliTempDir","substrToIdentifyTempDirs","autoCleanup","tempDirPrefix","nativeDir","tmpDir","tmpSetGracefulCleanup","cleanupStalePlaygroundTempDirs","staleAgeInMillis","tempRootDir","promisesToRemove","findStalePlaygroundTempDirs","stalePlaygroundTempDir","tempPaths","dirName","stalePlaygroundTempDirs","tempPath","appearsToBeStalePlaygroundTempDir","absolutePath","match","info","doesProcessExist","STALE_DATE","pid","executableName","existingProcess","ps","processes","LogSeverity","parseOptionsAndRunCLI","argsToParse","sharedOptions","SupportedPHPVersions","verbosity","serverOnlyOptions","cpus","buildSnapshotOnlyOptions","yargsObject","yargs","yargsInstance","msg","siteUrlArg","autoMountIsDir","allow","command","cliArgs","cliServer","runCLI","cleanUpCliAndExit","promiseToCleanup","printDebugDetails","messageChain","currentError","internalsKeyForTesting","bold","text","dim","italic","highlight","loadBalancer","playgroundsToCleanUp","severity","v","selectedPort","nativeFlockSync","m","fileLockManager","FileLockManagerForNode","wordPressReady","isFirstRequest","host","serverUrl","siteUrl","targetWorkerCount","totalWorkersToSpawn","maxProcessIdValue","processIdSpaceLength","tempDirNameDelimiter","IDEConfigName","symlinkName","symlinkPath","removeTempDirSymlink","createTempDirSymlink","symlinkMount","clearXdebugIDEConfig","xdebugOptions","modifiedConfig","addXdebugIDEConfig","ides","hasVSCode","hasPhpStorm","configFiles","tempDirRoot","tempDirStaleAgeInMillis","mkdirSync","userProvidableNativeSubdirs","subdirName","isMountingSubdirName","nativeSubdirPath","handler","disposing","disposeCLI","promisedWorkers","spawnWorkerThreads","exitCode","workers","exposeFileLockManager","initialPlayground","compiledBlueprint","runBlueprintV1Steps","zipSite","initialWorkerProcessIdSpace","index","additionalPlayground","startBridge","processId","phpLogs","errorLogPath","headers","count","workerType","onWorkerExit","promises","spawnWorkerThread","code","onExit","Worker","_documentCurrentScript","spawned","port1","port2","NodeMessageChannel","jspi","exposeAPI","exposeSyncAPI","outfile","zip"],"mappings":"wlCAsBO,SAASA,GAAiCC,EAA2B,CAC3E,MAAMC,EAAe,CAAA,EACrB,UAAWC,KAASF,EAAQ,CAC3B,MAAMG,EAAaD,EAAM,MAAM,GAAG,EAClC,GAAIC,EAAW,SAAW,EACzB,MAAM,IAAI,MAAM,yBAAyBD,CAAK;AAAA;AAAA;AAAA,+EAG8B,EAE7E,KAAM,CAACE,EAAUC,CAAO,EAAIF,EAC5B,GAAI,CAACG,EAAAA,WAAWF,CAAQ,EACvB,MAAM,IAAI,MAAM,6BAA6BA,CAAQ,EAAE,EAExDH,EAAa,KAAK,CAAE,SAAAG,EAAU,QAAAC,CAAA,CAAS,CACxC,CACA,OAAOJ,CACR,CAiBO,SAASM,GAAuBP,EAA2B,CACjE,GAAIA,EAAO,OAAS,IAAM,EACzB,MAAM,IAAI,MAAM,sDAAsD,EAGvE,MAAMC,EAAe,CAAA,EACrB,QAASO,EAAI,EAAGA,EAAIR,EAAO,OAAQQ,GAAK,EAAG,CAC1C,MAAMC,EAAST,EAAOQ,CAAC,EACjBH,EAAUL,EAAOQ,EAAI,CAAC,EAC5B,GAAI,CAACF,EAAAA,WAAWG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