"use strict";var S=Object.create;var $=Object.defineProperty;var k=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var M=Object.getPrototypeOf,H=Object.prototype.hasOwnProperty;var R=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of q(e))!H.call(t,a)&&a!==r&&$(t,a,{get:()=>e[a],enumerable:!(i=k(e,a))||i.enumerable});return t};var B=(t,e,r)=>(r=t!=null?S(M(t)):{},R(e||!t||!t.__esModule?$(r,"default",{value:t,enumerable:!0}):r,t));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const v=require("@php-wasm/logger"),b=require("@php-wasm/node"),A=require("@php-wasm/progress"),h=require("@php-wasm/universal"),y=require("@php-wasm/util"),E=require("@wp-playground/wordpress"),F=require("fs"),g=require("path"),T=require("tls"),x=require("worker_threads"),O=require("wasm-feature-detect");async function j(){let t=null;const e=(await Promise.resolve().then(()=>require("./blueprints-ZBrY1bvK.cjs"))).default;if(typeof process<"u"&&process.versions?.node){let r=e;r.startsWith("/@fs/")&&(r=r.slice(4)),r.startsWith("file://")&&(r=r.slice(7));const{readFile:i}=await import("node:fs/promises");t=await i(r)}else t=await(await fetch(e)).blob();return new File([t],"blueprints.phar",{type:"application/zip"})}function C(t){if(typeof t=="object"&&"type"in t&&["inline-file","file-reference"].includes(t.type))return t;if(!t)return{type:"inline-file",contents:"{}"};if(typeof t!="string")return{type:"inline-file",contents:JSON.stringify(t)};try{return JSON.parse(t),{type:"inline-file",contents:t}}catch{return{type:"file-reference",reference:t}}}async function D(t){const e=t.cliArgs||[];for(const n of e)if(n.startsWith("--site-path="))throw new Error("The --site-path CLI argument must not be provided. In Playground, it is always set to /wordpress.");e.push("--site-path=/wordpress"),e.find(n=>n.startsWith("--db-engine="))||e.push("--db-engine=sqlite");const i=t.php,a=t?.onMessage||(()=>{}),f=await j();i.writeFile("/tmp/blueprints.phar",new Uint8Array(await f.arrayBuffer()));const d=C(t.blueprint);let o="";switch(d.type){case"inline-file":i.writeFile("/tmp/blueprint.json",d.contents),o="/tmp/blueprint.json";break;case"file-reference":o=d.reference;break}const c=await i.onMessage(async n=>{try{const s=typeof n=="string"?JSON.parse(n):n;if(!s)return;await new Promise(u=>setTimeout(u,0)),s.type.startsWith("blueprint.")&&await a(s)}catch(s){v.logger.warn("Failed to parse message as JSON:",n,s)}});await i?.writeFile("/tmp/run-blueprints.php",`<?php
function playground_http_client_factory() {
	return new WordPress\\HttpClient\\Client([
		// sockets transport is somehow faster than curl in Playground. Maybe
		// it uses a larger chunk size?
		'transport' => 'sockets',
	]);
}
playground_add_filter('blueprint.http_client', 'playground_http_client_factory');

function playground_on_blueprint_target_resolved() {
	post_message_to_js(json_encode([
		'type' => 'blueprint.target_resolved',
	]));
}
playground_add_filter('blueprint.target_resolved', 'playground_on_blueprint_target_resolved');

playground_add_filter('blueprint.resolved', 'playground_on_blueprint_resolved');
function playground_on_blueprint_resolved($blueprint) {
	$additional_blueprint_steps = json_decode(${y.phpVar(JSON.stringify(t.blueprintOverrides?.additionalSteps||[]))}, true);
	if(count($additional_blueprint_steps) > 0) {
		$blueprint['additionalStepsAfterExecution'] = array_merge(
			$blueprint['additionalStepsAfterExecution'] ?? [],
			$additional_blueprint_steps
		);
	}

	$wp_version_override = json_decode(${y.phpVar(JSON.stringify(t.blueprintOverrides?.wordpressVersion||null))}, true);
	if($wp_version_override) {
		$blueprint['wordpressVersion'] = $wp_version_override;
	}
	return $blueprint;
}

function playground_progress_reporter() {
	class PlaygroundProgressReporter implements ProgressReporter {

		public function reportProgress(float $progress, string $caption): void {
			$this->writeJsonMessage([
				'type' => 'blueprint.progress',
				'progress' => round($progress, 2),
				'caption' => $caption
			]);
		}

		public function reportError(string $message, ?Throwable $exception = null): void {
			$errorData = [
				'type' => 'blueprint.error',
				'message' => $message
			];

			if ($exception) {
				$errorData['details'] = [
					'exception' => get_class($exception),
					'message' => $exception->getMessage(),
					'file' => $exception->getFile(),
					'line' => $exception->getLine(),
					'trace' => $exception->getTraceAsString()
				];
			}

			$this->writeJsonMessage($errorData);
		}

		public function reportCompletion(string $message): void {
			$this->writeJsonMessage([
				'type' => 'blueprint.completion',
				'message' => $message
			]);
		}

		public function close(): void {}

		private function writeJsonMessage(array $data): void {
			post_message_to_js(json_encode($data));
		}
	}
	return new PlaygroundProgressReporter();
}
playground_add_filter('blueprint.progress_reporter', 'playground_progress_reporter');
require( "/tmp/blueprints.phar" );
`);const l=await i.cli(["/internal/shared/bin/php","/tmp/run-blueprints.php","exec",o,...e]);return l.finished.finally(c),l}async function w(t,e){for(const r of e)try{t.mkdir(r.vfsPath),await t.mount(r.vfsPath,b.createNodeFsMountHandler(r.hostPath))}catch{p.stderr(`\x1B[31m\x1B[1mError mounting path ${r.hostPath} at ${r.vfsPath}\x1B[0m
`),process.exit(1)}}function L(t,e,...r){console.log(performance.now().toFixed(6).padStart(15,"0"),t.toString().padStart(16,"0"),y.sprintf(e,...r))}Object.defineProperty(process.stdout,"isTTY",{value:!0});Object.defineProperty(process.stderr,"isTTY",{value:!0});const p={lastWriteWasProgress:!1,progress(t){process.stdout.isTTY?(p.lastWriteWasProgress||process.stdout.write(`
`),process.stdout.write("\r\x1B[K"+t),p.lastWriteWasProgress=!0):console.log(t)},stdout(t){p.lastWriteWasProgress&&(process.stdout.write(`
`),p.lastWriteWasProgress=!1),process.stdout.write(t)},stderr(t){p.lastWriteWasProgress&&(process.stdout.write(`
`),p.lastWriteWasProgress=!1),process.stderr.write(t)}};class W extends h.PHPWorker{constructor(e){super(void 0,e),this.booted=!1}async useFileLockManager(e){await O.jspi()?this.fileLockManager=h.consumeAPI(e):this.fileLockManager=await h.consumeAPISync(e)}async bootAsPrimaryWorker(e){await this.bootRequestHandler(e);const r=this.__internal_getPHP();if(await w(r,e["mount-before-install"]||[]),e.mode==="mount-only"){await w(r,e.mount||[]);return}await this.runBlueprintV2(e)}async bootAsSecondaryWorker(e){await this.bootRequestHandler(e);const r=this.__internal_getPHP();await w(r,e["mount-before-install"]||[]),await w(r,e.mount||[])}async runBlueprintV2(e){const r=this.__internal_getRequestHandler(),{php:i,reap:a}=await r.processManager.acquirePHPInstance({considerPrimary:!1}),f=this.__internal_getPHP();let d=()=>{};if(typeof e.blueprint=="string"){const o=g.resolve(process.cwd(),e.blueprint);F.existsSync(o)&&(f.mkdir("/internal/shared/cwd"),d=await f.mount("/internal/shared/cwd",b.createNodeFsMountHandler(g.dirname(o))),e.blueprint=g.join("/internal/shared/cwd",g.basename(e.blueprint)))}try{const c=["mode","db-engine","db-host","db-user","db-pass","db-name","db-path","truncate-new-site-directory","allow"].filter(s=>s in e).map(s=>`--${s}=${e[s]}`);c.push(`--site-url=${e.siteUrl}`);let l=!1;const n=await D({php:i,blueprint:e.blueprint,blueprintOverrides:{additionalSteps:e["additional-blueprint-steps"],wordpressVersion:e.wp},cliArgs:c,onMessage:async s=>{switch(s.type){case"blueprint.target_resolved":{l||(await w(f,e.mount||[]),l=!0);break}case"blueprint.progress":{const u=`${s.caption.trim()} – ${s.progress.toFixed(2)}%`;p.progress(u);break}case"blueprint.error":{const u="\x1B[31m",m="\x1B[1m",P="\x1B[0m";e.debug&&s.details?p.stderr(`${u}${m}Fatal error:${P} Uncaught ${s.details.exception}: ${s.details.message}
  at ${s.details.file}:${s.details.line}
`+(s.details.trace?s.details.trace+`
`:"")):p.stderr(`${u}${m}Error:${P} ${s.message}
`);break}}}});if(e.debug&&(n.stdout.pipeTo(new WritableStream({write(s){process.stdout.write(s)}})),n.stderr.pipeTo(new WritableStream({write(s){process.stderr.write(s)}}))),await n.finished,await n.exitCode!==0){const s=await h.PHPResponse.fromStreamedResponse(n);throw new h.PHPExecutionFailureError(`PHP.run() failed with exit code ${s.exitCode}.`,s,"request")}}catch(o){let c="";try{c=i.readFileAsText(v.errorLogPath)}catch{}throw o.phpLogs=c,o}finally{a(),d()}}async bootRequestHandler({siteUrl:e,allow:r,php:i,firstProcessId:a,processIdSpaceLength:f,trace:d}){if(this.booted)throw new Error("Playground already booted");this.booted=!0;let o=a;const c=a+f-1;try{const l={WP_DEBUG:!0,WP_DEBUG_LOG:!0,WP_DEBUG_DISPLAY:!1},n=await E.bootRequestHandler({siteUrl:e,createPhpRuntime:async()=>{const u=o;return o<c?o++:o=a,await b.loadNodeRuntime(i,{emscriptenOptions:{fileLockManager:this.fileLockManager,processId:u,trace:d?L:void 0,ENV:{DOCROOT:"/wordpress"}},followSymlinks:r?.includes("follow-symlinks")})},sapiName:"cli",createFiles:{"/internal/shared/ca-bundle.crt":T.rootCertificates.join(`
`)},constants:l,phpIniEntries:{"openssl.cafile":"/internal/shared/ca-bundle.crt"},cookieStore:!1,spawnHandler:h.sandboxedSpawnHandlerFactory});this.__internal_setRequestHandler(n);const s=await n.getPrimaryPhp();await this.setPrimaryPHP(s),V()}catch(l){throw N(l),l}}async dispose(){await this[Symbol.asyncDispose]()}}const _=new x.MessageChannel,[V,N]=h.exposeAPI(new W(new A.EmscriptenDownloadMonitor),void 0,_.port1);x.parentPort.postMessage({command:"worker-script-initialized",phpPort:_.port2},[_.port2]);exports.PlaygroundCliBlueprintV2Worker=W;
//# sourceMappingURL=worker-thread-v2.cjs.map
