@wp-playground/cli 1.1.0 → 1.1.2

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.
package/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./run-cli-D-8hdNJ9.cjs");exports.runCLI=e.runCLI;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./run-cli-BSw9FKSW.cjs");exports.runCLI=e.runCLI;
2
2
  //# sourceMappingURL=index.cjs.map
package/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { r as a } from "./run-cli-j-geJYS3.js";
1
+ import { r as a } from "./run-cli-_8y4VW5F.js";
2
2
  export {
3
3
  a as runCLI
4
4
  };
package/mount.d.ts ADDED
@@ -0,0 +1,38 @@
1
+ import type { PHP } from '@php-wasm/universal';
2
+ export interface Mount {
3
+ hostPath: string;
4
+ vfsPath: string;
5
+ }
6
+ /**
7
+ * Parse an array of mount argument strings where the host path and VFS path
8
+ * are separated by a colon.
9
+ *
10
+ * Example:
11
+ * parseMountWithDelimiterArguments( [ '/host/path:/vfs/path', '/host/path:/vfs/path' ] )
12
+ * // returns:
13
+ * [
14
+ * { hostPath: '/host/path', vfsPath: '/vfs/path' },
15
+ * { hostPath: '/host/path', vfsPath: '/vfs/path' }
16
+ * ]
17
+ *
18
+ * @param mounts - An array of mount argument strings separated by a colon.
19
+ * @returns An array of Mount objects.
20
+ */
21
+ export declare function parseMountWithDelimiterArguments(mounts: string[]): Mount[];
22
+ /**
23
+ * Parse an array of mount argument strings where each odd array element is a host path
24
+ * and each even element is the VFS path.
25
+ * e.g. [ '/host/path', '/vfs/path', '/host/path2', '/vfs/path2' ]
26
+ *
27
+ * The result will be an array of Mount objects for each host path the
28
+ * following element is it's VFS path.
29
+ * e.g. [
30
+ * { hostPath: '/host/path', vfsPath: '/vfs/path' },
31
+ * { hostPath: '/host/path2', vfsPath: '/vfs/path2' }
32
+ * ]
33
+ *
34
+ * @param mounts - An array of paths
35
+ * @returns An array of Mount objects.
36
+ */
37
+ export declare function parseMountDirArguments(mounts: string[]): Mount[];
38
+ export declare function mountResources(php: PHP, mounts: Mount[]): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wp-playground/cli",
3
- "version": "1.1.0",
3
+ "version": "1.1.2",
4
4
  "description": "WordPress Playground CLI",
5
5
  "repository": {
6
6
  "type": "git",
@@ -32,7 +32,7 @@
32
32
  "module": "./index.js",
33
33
  "types": "index.d.ts",
34
34
  "bin": "wp-playground.js",
35
- "gitHead": "9dbbe2b22ccbacda9c0da4444c51d5739e784302",
35
+ "gitHead": "59c2db1ec41efa10ffa01e6e1ea7ac6e78bc693e",
36
36
  "dependencies": {
37
37
  "@zip.js/zip.js": "2.7.57",
38
38
  "ajv": "8.12.0",
@@ -55,14 +55,14 @@
55
55
  "wasm-feature-detect": "1.8.0",
56
56
  "ws": "8.18.1",
57
57
  "yargs": "17.7.2",
58
- "@wp-playground/blueprints": "1.1.0",
59
- "@php-wasm/universal": "1.1.0",
60
- "@wp-playground/common": "1.1.0",
61
- "@php-wasm/progress": "1.1.0",
62
- "@php-wasm/logger": "1.1.0",
63
- "@wp-playground/storage": "1.1.0",
64
- "@php-wasm/node": "1.1.0",
65
- "@wp-playground/wordpress": "1.1.0"
58
+ "@wp-playground/blueprints": "1.1.2",
59
+ "@php-wasm/universal": "1.1.2",
60
+ "@wp-playground/common": "1.1.2",
61
+ "@php-wasm/progress": "1.1.2",
62
+ "@php-wasm/node": "1.1.2",
63
+ "@php-wasm/logger": "1.1.2",
64
+ "@wp-playground/storage": "1.1.2",
65
+ "@wp-playground/wordpress": "1.1.2"
66
66
  },
67
67
  "overrides": {
68
68
  "rollup": "^4.34.6",
@@ -0,0 +1,35 @@
1
+ "use strict";const p=require("@php-wasm/logger"),H=require("@php-wasm/node"),x=require("@php-wasm/progress"),z=require("@php-wasm/universal"),b=require("@wp-playground/blueprints"),q=require("@wp-playground/common"),B=require("@wp-playground/wordpress"),d=require("fs"),f=require("path"),L=require("tls"),P=require("fs-extra"),T=require("os"),U=require("express");function Z(e){const t=process.cwd(),n=[...e.mount||[]],o=[...e.mountBeforeInstall||[]];if(M(t)){const r=f.basename(t);n.push({hostPath:t,vfsPath:`/wordpress/wp-content/plugins/${r}`})}else if(F(t)){const r=f.basename(t);n.push({hostPath:t,vfsPath:`/wordpress/wp-content/themes/${r}`})}else if(C(t))n.push(...E(t));else if(S(t)){const r=d.readdirSync(t),l=[];for(const s of r)s.startsWith("wp-content")||l.push({hostPath:`${t}/${s}`,vfsPath:`/wordpress/${s}`});o.push(...l,...E(f.join(t,"wp-content")))}else n.push({hostPath:t,vfsPath:"/wordpress"});const i=e.blueprint||{};i.steps=[...i.steps||[],...j(t)];const a=e.skipWordPressSetup||S(t);return{...e,blueprint:i,mount:n,mountBeforeInstall:o,skipWordPressSetup:a}}function S(e){const t=d.readdirSync(e);return t.includes("wp-admin")&&t.includes("wp-includes")&&t.includes("wp-content")}function C(e){const t=d.readdirSync(e);return t.includes("themes")||t.includes("plugins")||t.includes("mu-plugins")||t.includes("uploads")}function F(e){if(!d.readdirSync(e).includes("style.css"))return!1;const n=d.readFileSync(f.join(e,"style.css"),"utf8");return!!/^(?:[ \t]*<\?php)?[ \t/*#@]*Theme Name:(.*)$/im.exec(n)}function M(e){const t=d.readdirSync(e),n=/^(?:[ \t]*<\?php)?[ \t/*#@]*Plugin Name:(.*)$/im;return!!t.filter(i=>i.endsWith(".php")).find(i=>{const a=d.readFileSync(f.join(e,i),"utf8");return!!n.exec(a)})}function E(e){return d.readdirSync(e).filter(n=>!n.startsWith("index.php")).map(n=>({hostPath:`${e}/${n}`,vfsPath:`/wordpress/wp-content/${n}`}))}function j(e){return M(e)?[{step:"activatePlugin",pluginPath:`/wordpress/wp-content/plugins/${f.basename(e)}`}]:F(e)?[{step:"activateTheme",themeFolderName:f.basename(e)}]:C(e)||S(e)?[{step:"runPHP",code:`<?php
2
+ require_once '/wordpress/wp-load.php';
3
+ $theme = wp_get_theme();
4
+ if (!$theme->exists()) {
5
+ $themes = wp_get_themes();
6
+ if (count($themes) > 0) {
7
+ $themeName = array_keys($themes)[0];
8
+ switch_theme($themeName);
9
+ }
10
+ }
11
+ `}]:[]}const W=f.join(T.homedir(),".wordpress-playground");async function V(e){return await D("https://github.com/WordPress/sqlite-database-integration/archive/refs/heads/develop.zip","sqlite.zip",e)}async function D(e,t,n){const o=f.join(W,t);return P.existsSync(o)||(P.ensureDirSync(W),await G(e,o,n)),_(o)}async function G(e,t,n){const i=(await n.monitorFetch(fetch(e))).body.getReader(),a=`${t}.partial`,r=P.createWriteStream(a);for(;;){const{done:l,value:s}=await i.read();if(s&&r.write(s),l)break}r.close(),r.closed||await new Promise((l,s)=>{r.on("finish",()=>{P.renameSync(a,t),l(null)}),r.on("error",c=>{P.removeSync(a),s(c)})})}function _(e,t){return new File([P.readFileSync(e)],f.basename(e))}async function O(e){const t=U(),n=await new Promise((a,r)=>{const l=t.listen(e.port,()=>{const s=l.address();s===null||typeof s=="string"?r(new Error("Server address is not available")):a(l)})});t.use("/",async(a,r)=>{const l=await e.handleRequest({url:a.url,headers:J(a),method:a.method,body:await Y(a)});r.statusCode=l.httpStatusCode;for(const s in l.headers)r.setHeader(s,l.headers[s]);r.end(l.bytes)});const i=n.address().port;return await e.onBind(n,i)}const Y=async e=>await new Promise(t=>{const n=[];e.on("data",o=>{n.push(o)}),e.on("end",()=>{t(new Uint8Array(Buffer.concat(n)))})}),J=e=>{const t={};if(e.rawHeaders&&e.rawHeaders.length)for(let n=0;n<e.rawHeaders.length;n+=2)t[e.rawHeaders[n].toLowerCase()]=e.rawHeaders[n+1];return t};function K(e){const t=[];for(const n of e){const o=n.split(":");if(o.length!==2)throw new Error(`Invalid mount format: ${n}.
12
+ Expected format: /host/path:/vfs/path.
13
+ If your path contains a colon, e.g. C:\\myplugin, use the --mount-dir option instead.
14
+ Example: --mount-dir C:\\my-plugin /wordpress/wp-content/plugins/my-plugin`);const[i,a]=o;if(!d.existsSync(i))throw new Error(`Host path does not exist: ${i}`);t.push({hostPath:i,vfsPath:a})}return t}function Q(e){if(e.length%2!==0)throw new Error("Invalid mount format. Expected: /host/path /vfs/path");const t=[];for(let n=0;n<e.length;n+=2){const o=e[n],i=e[n+1];if(!d.existsSync(o))throw new Error(`Host path does not exist: ${o}`);t.push({hostPath:f.resolve(process.cwd(),o),vfsPath:i})}return t}function I(e,t){for(const n of t)e.mkdir(n.vfsPath),e.mount(n.vfsPath,H.createNodeFsMountHandler(n.hostPath))}async function X(e){e.autoMount&&(e=Z(e));async function t(s){const{php:c,reap:h}=await r.processManager.acquirePHPInstance();try{await c.run({code:`<?php
15
+ $zip = new ZipArchive();
16
+ if(false === $zip->open('/tmp/build.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
17
+ throw new Exception('Failed to create ZIP');
18
+ }
19
+ $files = new RecursiveIteratorIterator(
20
+ new RecursiveDirectoryIterator('/wordpress')
21
+ );
22
+ foreach ($files as $file) {
23
+ echo $file . PHP_EOL;
24
+ if (!$file->isFile()) {
25
+ continue;
26
+ }
27
+ $zip->addFile($file->getPathname(), $file->getPathname());
28
+ }
29
+ $zip->close();
30
+
31
+ `});const u=c.readFileAsBuffer("/tmp/build.zip");d.writeFileSync(s,u)}finally{h()}}async function n(){const s=b.isBlueprintBundle(e.blueprint)?e.blueprint:{login:e.login,...e.blueprint,preferredVersions:{php:e.php??e?.blueprint?.preferredVersions?.php??q.RecommendedPHPVersion,wp:e.wp??e?.blueprint?.preferredVersions?.wp??"latest",...e.blueprint?.preferredVersions||{}}},c=new x.ProgressTracker;let h="",u=!1;return c.addEventListener("progress",m=>{if(u)return;u=m.detail.progress===100;const g=Math.floor(m.detail.progress);h=m.detail.caption||h||"Running the Blueprint";const v=`${h.trim()} – ${g}%`;e.quiet||i(process.stdout,v,u)}),await b.compileBlueprint(s,{progress:c})}let o="";function i(s,c,h){c!==o&&(o=c,s.isTTY?(s.cursorTo(0),s.write(c),s.clearLine(1),h&&s.write(`
32
+ `)):s.write(`${c}
33
+ `))}e.quiet&&(p.logger.handlers=[]);const a=await n();let r,l=!1;return p.logger.log("Starting a PHP server..."),O({port:e.port,onBind:async(s,c)=>{const h=`http://127.0.0.1:${c}`;p.logger.log(`Setting up WordPress ${e.wp}`);let u;const m=new x.EmscriptenDownloadMonitor;if(!e.skipWordPressSetup){let w=!1;m.addEventListener("progress",y=>{if(w)return;const{loaded:A,total:k}=y.detail,R=Math.floor(Math.min(100,100*A/k));w=R===100,e.quiet||i(process.stdout,`Downloading WordPress ${R}%...`,w)}),u=await B.resolveWordPressRelease(e.wp)}p.logger.log(`Resolved WordPress release URL: ${u?.releaseUrl}`);const g=u&&f.join(W,`prebuilt-wp-content-for-wp-${u.version}.zip`),v=u?d.existsSync(g)?_(g):await D(u.releaseUrl,`${u.version}.zip`,m):void 0,N={WP_DEBUG:!0,WP_DEBUG_LOG:!0,WP_DEBUG_DISPLAY:!1};p.logger.log("Booting WordPress..."),r=await B.bootWordPress({siteUrl:h,createPhpRuntime:async()=>await H.loadNodeRuntime(a.versions.php,{followSymlinks:e.followSymlinks===!0}),wordPressZip:v,sqliteIntegrationPluginZip:e.skipSqliteSetup?void 0:V(m),sapiName:"cli",createFiles:{"/internal/shared/ca-bundle.crt":L.rootCertificates.join(`
34
+ `)},constants:N,phpIniEntries:{"openssl.cafile":"/internal/shared/ca-bundle.crt",allow_url_fopen:"1",disable_functions:""},hooks:{async beforeWordPressFiles(w){e.mountBeforeInstall&&I(w,e.mountBeforeInstall)}},cookieStore:!1}),p.logger.log("Booted!");const $=await r.getPrimaryPhp();try{if(u&&!e.mountBeforeInstall&&!d.existsSync(g)&&(p.logger.log("Caching preinstalled WordPress for the next boot..."),d.writeFileSync(g,await q.zipDirectory($,"/wordpress")),p.logger.log("Cached!")),e.mount&&I($,e.mount),l=!0,a){const{php:w,reap:y}=await r.processManager.acquirePHPInstance();try{p.logger.log("Running the Blueprint..."),await b.runBlueprintSteps(a,w),p.logger.log("Finished running the blueprint")}finally{y()}}return e.command==="build-snapshot"?(await t(e.outfile),p.logger.log(`WordPress exported to ${e.outfile}`),process.exit(0)):e.command==="run-blueprint"?(p.logger.log("Blueprint executed"),process.exit(0)):p.logger.log(`WordPress is running on ${h}`),{requestHandler:r,server:s}}catch(w){if(!e.debug)throw w;const y=$.readFileAsText(p.errorLogPath);throw new Error(y,{cause:w})}},async handleRequest(s){return l?await r.request(s):z.PHPResponse.forHttpCode(502,"WordPress is not ready yet")}})}exports.parseMountDirArguments=Q;exports.parseMountWithDelimiterArguments=K;exports.runCLI=X;
35
+ //# sourceMappingURL=run-cli-BSw9FKSW.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-cli-BSw9FKSW.cjs","sources":["../../../../packages/playground/cli/src/cli-auto-mount.ts","../../../../packages/playground/cli/src/download.ts","../../../../packages/playground/cli/src/server.ts","../../../../packages/playground/cli/src/mount.ts","../../../../packages/playground/cli/src/run-cli.ts"],"sourcesContent":["import { basename, join } from 'path';\nimport type {\n\tBlueprintDeclaration,\n\tStepDefinition,\n} from '@wp-playground/blueprints';\nimport fs from 'fs';\nimport type { RunCLIArgs } from './run-cli';\nimport type { Mount } from './mount';\n\nexport function expandAutoMounts(args: RunCLIArgs): RunCLIArgs {\n\tconst path = process.cwd();\n\n\tconst mount = [...(args.mount || [])];\n\tconst mountBeforeInstall = [...(args.mountBeforeInstall || [])];\n\n\tif (isPluginDirectory(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} 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} else if (containsWpContentDirectories(path)) {\n\t\tmount.push(...wpContentMounts(path));\n\t} else if (containsFullWordPressInstallation(path)) {\n\t\t/**\n\t\t * We don't want Playground and WordPress to modify the OS filesystem on their own\n\t\t * by creating files like wp-config.php or wp-content/db.php.\n\t\t * To ensure WordPress can write to the /wordpress/ and /wordpress/wp-content/ directories,\n\t\t * we leave these directories as MEMFS nodes and mount individual files\n\t\t * and directories into them instead of mounting the entire directory as a NODEFS node.\n\t\t */\n\t\tconst files = fs.readdirSync(path);\n\t\tconst mounts: Mount[] = [];\n\t\tfor (const file of files) {\n\t\t\tif (file.startsWith('wp-content')) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tmounts.push({\n\t\t\t\thostPath: `${path}/${file}`,\n\t\t\t\tvfsPath: `/wordpress/${file}`,\n\t\t\t});\n\t\t}\n\t\tmountBeforeInstall.push(\n\t\t\t...mounts,\n\t\t\t...wpContentMounts(join(path, 'wp-content'))\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}\n\n\tconst blueprint = (args.blueprint as BlueprintDeclaration) || {};\n\tblueprint.steps = [...(blueprint.steps || []), ...getSteps(path)];\n\n\t/**\n\t * If Playground is mounting a full WordPress directory,\n\t * it doesn't need to setup WordPress.\n\t */\n\tconst skipWordPressSetup =\n\t\targs.skipWordPressSetup || containsFullWordPressInstallation(path);\n\n\treturn {\n\t\t...args,\n\t\tblueprint,\n\t\tmount,\n\t\tmountBeforeInstall,\n\t\tskipWordPressSetup,\n\t} 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 isPluginDirectory(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\n/**\n * Returns a list of files and directories in the wp-content directory\n * to be mounted individually.\n *\n * This is needed because WordPress needs to be able to write to the\n * wp-content directory without Playground modifying the OS filesystem.\n *\n * See expandAutoMounts for more details.\n */\nexport function wpContentMounts(wpContentDir: string): Mount[] {\n\tconst files = fs.readdirSync(wpContentDir);\n\treturn (\n\t\tfiles\n\t\t\t/**\n\t\t\t * index.php is added by WordPress automatically and\n\t\t\t * can't be mounted from the current working directory\n\t\t\t * because it already exists.\n\t\t\t *\n\t\t\t * Because index.php should be empty, it's safe to not include it.\n\t\t\t */\n\t\t\t.filter((file) => !file.startsWith('index.php'))\n\t\t\t.map((file) => ({\n\t\t\t\thostPath: `${wpContentDir}/${file}`,\n\t\t\t\tvfsPath: `/wordpress/wp-content/${file}`,\n\t\t\t}))\n\t);\n}\n\nexport function getSteps(path: string): StepDefinition[] {\n\tif (isPluginDirectory(path)) {\n\t\treturn [\n\t\t\t{\n\t\t\t\tstep: 'activatePlugin',\n\t\t\t\tpluginPath: `/wordpress/wp-content/plugins/${basename(path)}`,\n\t\t\t},\n\t\t];\n\t} else if (isThemeDirectory(path)) {\n\t\treturn [\n\t\t\t{\n\t\t\t\tstep: 'activateTheme',\n\t\t\t\tthemeFolderName: basename(path),\n\t\t\t},\n\t\t];\n\t} else if (\n\t\tcontainsWpContentDirectories(path) ||\n\t\tcontainsFullWordPressInstallation(path)\n\t) {\n\t\t/**\n\t\t * Playground needs to ensure there is an active theme.\n\t\t * Otherwise when WordPress loads it will show a white screen.\n\t\t */\n\t\treturn [\n\t\t\t{\n\t\t\t\tstep: 'runPHP',\n\t\t\t\tcode: `<?php\n\t\t\t\t\trequire_once '/wordpress/wp-load.php';\n\t\t\t\t\t$theme = wp_get_theme();\n\t\t\t\t\tif (!$theme->exists()) {\n\t\t\t\t\t\t$themes = wp_get_themes();\n\t\t\t\t\t\tif (count($themes) > 0) {\n\t\t\t\t\t\t\t$themeName = array_keys($themes)[0];\n\t\t\t\t\t\t\tswitch_theme($themeName);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t`,\n\t\t\t},\n\t\t];\n\t}\n\treturn [];\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 type { PHPRequest, PHPResponse } from '@php-wasm/universal';\nimport type { Request } from 'express';\nimport express from 'express';\nimport type { IncomingMessage, Server, ServerResponse } from 'http';\nimport type { AddressInfo } from 'net';\nimport type { RunCLIServer } from './run-cli';\n\nexport interface ServerOptions {\n\tport: number;\n\tonBind: (server: Server, port: number) => Promise<RunCLIServer>;\n\thandleRequest: (request: PHPRequest) => Promise<PHPResponse>;\n}\n\nexport async function startServer(\n\toptions: ServerOptions\n): Promise<RunCLIServer> {\n\tconst app = express();\n\n\tconst server = await new Promise<\n\t\tServer<typeof IncomingMessage, typeof ServerResponse>\n\t>((resolve, reject) => {\n\t\tconst server = app.listen(options.port, () => {\n\t\t\tconst address = server.address();\n\t\t\tif (address === null || typeof address === 'string') {\n\t\t\t\treject(new Error('Server address is not available'));\n\t\t\t} else {\n\t\t\t\tresolve(server);\n\t\t\t}\n\t\t});\n\t});\n\n\tapp.use('/', async (req, res) => {\n\t\tconst phpResponse = await options.handleRequest({\n\t\t\turl: req.url,\n\t\t\theaders: parseHeaders(req),\n\t\t\tmethod: req.method as any,\n\t\t\tbody: await bufferRequestBody(req),\n\t\t});\n\n\t\tres.statusCode = phpResponse.httpStatusCode;\n\t\tfor (const key in phpResponse.headers) {\n\t\t\tres.setHeader(key, phpResponse.headers[key]);\n\t\t}\n\t\tres.end(phpResponse.bytes);\n\t});\n\n\tconst address = server.address();\n\tconst port = (address! as AddressInfo).port;\n\treturn await options.onBind(server, port);\n}\n\nconst bufferRequestBody = async (req: Request): Promise<Uint8Array> =>\n\tawait new Promise((resolve) => {\n\t\tconst body: Uint8Array[] = [];\n\t\treq.on('data', (chunk) => {\n\t\t\tbody.push(chunk);\n\t\t});\n\t\treq.on('end', () => {\n\t\t\tresolve(new Uint8Array(Buffer.concat(body)));\n\t\t});\n\t});\n\nconst parseHeaders = (req: Request): Record<string, string> => {\n\tconst requestHeaders: Record<string, string> = {};\n\tif (req.rawHeaders && req.rawHeaders.length) {\n\t\tfor (let i = 0; i < req.rawHeaders.length; i += 2) {\n\t\t\trequestHeaders[req.rawHeaders[i].toLowerCase()] =\n\t\t\t\treq.rawHeaders[i + 1];\n\t\t}\n\t}\n\treturn requestHeaders;\n};\n","import { existsSync } from 'fs';\nimport path from 'path';\nimport { createNodeFsMountHandler } from '@php-wasm/node';\nimport type { PHP } from '@php-wasm/universal';\n\nexport interface Mount {\n\thostPath: string;\n\tvfsPath: string;\n}\n\n/**\n * Parse an array of mount argument strings where the host path and VFS path\n * are separated by a colon.\n * \n * Example:\n * parseMountWithDelimiterArguments( [ '/host/path:/vfs/path', '/host/path:/vfs/path' ] )\n * // returns:\n * [ \n * { hostPath: '/host/path', vfsPath: '/vfs/path' },\n * { hostPath: '/host/path', vfsPath: '/vfs/path' }\n * ]\n *\n * @param mounts - An array of mount argument strings separated by a colon.\n * @returns An array of Mount objects.\n */\nexport function parseMountWithDelimiterArguments(mounts: string[]): Mount[] {\n\tconst parsedMounts = [];\n\tfor (const mount of mounts) {\n\t\tconst mountParts = mount.split(':');\n\t\tif (mountParts.length !== 2) {\n\t\t\tthrow new Error(`Invalid mount format: ${mount}.\n\t\t\t\tExpected format: /host/path:/vfs/path.\n\t\t\t\tIf your path contains a colon, e.g. C:\\\\myplugin, use the --mount-dir option instead.\n\t\t\t\tExample: --mount-dir C:\\\\my-plugin /wordpress/wp-content/plugins/my-plugin`);\n\t\t}\n\t\tconst [hostPath, vfsPath] = mountParts;\n\t\tif (!existsSync(hostPath)) {\n\t\t\tthrow new Error(`Host path does not exist: ${hostPath}`);\n\t\t}\n\t\tparsedMounts.push({ hostPath, vfsPath });\n\t}\n\treturn parsedMounts;\n}\n\n/**\n * Parse an array of mount argument strings where each odd array element is a host path\n * and each even element is the VFS path.\n * e.g. [ '/host/path', '/vfs/path', '/host/path2', '/vfs/path2' ]\n *\n * The result will be an array of Mount objects for each host path the\n * following element is it's VFS path.\n * e.g. [\n * { hostPath: '/host/path', vfsPath: '/vfs/path' },\n * { hostPath: '/host/path2', vfsPath: '/vfs/path2' }\n * ]\n *\n * @param mounts - An array of paths\n * @returns An array of Mount objects.\n */\nexport function parseMountDirArguments(mounts: string[]): Mount[] {\n\tif (mounts.length % 2 !== 0) {\n\t\tthrow new Error('Invalid mount format. Expected: /host/path /vfs/path');\n\t}\n\n\tconst parsedMounts = [];\n\tfor (let i = 0; i < mounts.length; i += 2) {\n\t\tconst source = mounts[i];\n\t\tconst vfsPath = mounts[i + 1];\n\t\tif (!existsSync(source)) {\n\t\t\tthrow new Error(`Host path does not exist: ${source}`);\n\t\t}\n\t\tparsedMounts.push({\n\t\t\thostPath: path.resolve(process.cwd(), source),\n\t\t\tvfsPath,\n\t\t});\n\t}\n\treturn parsedMounts;\n}\n\nexport function mountResources(php: PHP, mounts: Mount[]) {\n\tfor (const mount of mounts) {\n\t\tphp.mkdir(mount.vfsPath);\n\t\tphp.mount(mount.vfsPath, createNodeFsMountHandler(mount.hostPath));\n\t}\n}\n","import { errorLogPath, logger } from '@php-wasm/logger';\nimport { loadNodeRuntime } from '@php-wasm/node';\nimport { EmscriptenDownloadMonitor, ProgressTracker } from '@php-wasm/progress';\nimport type {\n\tPHPRequest,\n\tPHPRequestHandler,\n\tSupportedPHPVersion,\n} from '@php-wasm/universal';\nimport { PHPResponse } from '@php-wasm/universal';\nimport type {\n\tBlueprintDeclaration,\n\tBlueprintBundle,\n} from '@wp-playground/blueprints';\nimport {\n\tcompileBlueprint,\n\trunBlueprintSteps,\n\tisBlueprintBundle,\n} from '@wp-playground/blueprints';\nimport { RecommendedPHPVersion, zipDirectory } from '@wp-playground/common';\nimport {\n\tbootWordPress,\n\tresolveWordPressRelease,\n} from '@wp-playground/wordpress';\nimport fs from 'fs';\nimport type { Server } from 'http';\nimport path from 'path';\nimport { rootCertificates } from 'tls';\nimport { expandAutoMounts } from './cli-auto-mount';\nimport {\n\tCACHE_FOLDER,\n\tcachedDownload,\n\tfetchSqliteIntegration,\n\treadAsFile,\n} from './download';\nimport { startServer } from './server';\nimport { type Mount, mountResources } from './mount';\n\nexport interface RunCLIArgs {\n\tblueprint?: BlueprintDeclaration | BlueprintBundle;\n\tcommand: 'server' | 'run-blueprint' | 'build-snapshot';\n\tdebug?: boolean;\n\tlogin?: boolean;\n\tmount?: Mount[];\n\tmountBeforeInstall?: Mount[];\n\toutfile?: string;\n\tphp?: SupportedPHPVersion;\n\tport?: number;\n\tquiet?: boolean;\n\tskipWordPressSetup?: boolean;\n\tskipSqliteSetup?: boolean;\n\twp?: string;\n\tautoMount?: boolean;\n\tfollowSymlinks?: boolean;\n}\n\nexport interface RunCLIServer {\n\trequestHandler: PHPRequestHandler;\n\tserver: Server;\n}\n\nexport async function runCLI(args: RunCLIArgs): Promise<RunCLIServer> {\n\t/**\n\t * Expand auto-mounts to include the necessary mounts and steps\n\t * when running in auto-mount mode.\n\t */\n\tif (args.autoMount) {\n\t\targs = expandAutoMounts(args);\n\t}\n\n\t/**\n\t * TODO: This exact feature will be provided in the PHP Blueprints library.\n\t * Let's use it when it ships. Let's also use it in the web Playground\n\t * app.\n\t */\n\tasync function zipSite(outfile: string) {\n\t\t// Fake URL for the build\n\t\tconst { php, reap } =\n\t\t\tawait requestHandler.processManager.acquirePHPInstance();\n\t\ttry {\n\t\t\tawait php.run({\n\t\t\t\tcode: `<?php\n\t\t\t\t$zip = new ZipArchive();\n\t\t\t\tif(false === $zip->open('/tmp/build.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE)) {\n\t\t\t\t\tthrow new Exception('Failed to create ZIP');\n\t\t\t\t}\n\t\t\t\t$files = new RecursiveIteratorIterator(\n\t\t\t\t\tnew RecursiveDirectoryIterator('/wordpress')\n\t\t\t\t);\n\t\t\t\tforeach ($files as $file) {\n\t\t\t\t\techo $file . PHP_EOL;\n\t\t\t\t\tif (!$file->isFile()) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\t$zip->addFile($file->getPathname(), $file->getPathname());\n\t\t\t\t}\n\t\t\t\t$zip->close();\n\n\t\t\t`,\n\t\t\t});\n\t\t\tconst zip = php.readFileAsBuffer('/tmp/build.zip');\n\t\t\tfs.writeFileSync(outfile, zip);\n\t\t} finally {\n\t\t\treap();\n\t\t}\n\t}\n\n\tasync function compileInputBlueprint() {\n\t\t/**\n\t\t * @TODO This looks similar to the resolveBlueprint() call in the website package:\n\t\t * \t https://github.com/WordPress/wordpress-playground/blob/ce586059e5885d185376184fdd2f52335cca32b0/packages/playground/website/src/main.tsx#L41\n\t\t *\n\t\t * \t\t Also the Blueprint Builder tool does something similar.\n\t\t * Perhaps all these cases could be handled by the same function?\n\t\t */\n\t\tconst blueprint: BlueprintDeclaration | BlueprintBundle =\n\t\t\tisBlueprintBundle(args.blueprint)\n\t\t\t\t? args.blueprint\n\t\t\t\t: {\n\t\t\t\t\t\tlogin: args.login,\n\t\t\t\t\t\t...args.blueprint,\n\t\t\t\t\t\tpreferredVersions: {\n\t\t\t\t\t\t\tphp:\n\t\t\t\t\t\t\t\targs.php ??\n\t\t\t\t\t\t\t\targs?.blueprint?.preferredVersions?.php ??\n\t\t\t\t\t\t\t\tRecommendedPHPVersion,\n\t\t\t\t\t\t\twp:\n\t\t\t\t\t\t\t\targs.wp ??\n\t\t\t\t\t\t\t\targs?.blueprint?.preferredVersions?.wp ??\n\t\t\t\t\t\t\t\t'latest',\n\t\t\t\t\t\t\t...(args.blueprint?.preferredVersions || {}),\n\t\t\t\t\t\t},\n\t\t\t\t };\n\n\t\tconst tracker = new ProgressTracker();\n\t\tlet lastCaption = '';\n\t\tlet progressReached100 = false;\n\t\ttracker.addEventListener('progress', (e: any) => {\n\t\t\tif (progressReached100) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tprogressReached100 = e.detail.progress === 100;\n\n\t\t\t// Use floor() so we don't report 100% until truly there.\n\t\t\tconst progressInteger = Math.floor(e.detail.progress);\n\t\t\tlastCaption =\n\t\t\t\te.detail.caption || lastCaption || 'Running the Blueprint';\n\t\t\tconst message = `${lastCaption.trim()} – ${progressInteger}%`;\n\t\t\tif (!args.quiet) {\n\t\t\t\twriteProgressUpdate(\n\t\t\t\t\tprocess.stdout,\n\t\t\t\t\tmessage,\n\t\t\t\t\tprogressReached100\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\t\treturn await compileBlueprint(blueprint as BlueprintDeclaration, {\n\t\t\tprogress: tracker,\n\t\t});\n\t}\n\n\tlet lastProgressMessage = '';\n\tfunction writeProgressUpdate(\n\t\twriteStream: NodeJS.WriteStream,\n\t\tmessage: string,\n\t\tfinalUpdate: boolean\n\t) {\n\t\tif (message === lastProgressMessage) {\n\t\t\t// Avoid repeating the same message\n\t\t\treturn;\n\t\t}\n\t\tlastProgressMessage = 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\tif (args.quiet) {\n\t\t// @ts-ignore\n\t\tlogger.handlers = [];\n\t}\n\n\tconst compiledBlueprint = await compileInputBlueprint();\n\n\tlet requestHandler: PHPRequestHandler;\n\tlet wordPressReady = false;\n\n\tlogger.log('Starting a PHP server...');\n\n\treturn startServer({\n\t\tport: args['port'] as number,\n\t\tonBind: async (server: Server, port: number): Promise<RunCLIServer> => {\n\t\t\tconst absoluteUrl = `http://127.0.0.1:${port}`;\n\n\t\t\tlogger.log(`Setting up WordPress ${args.wp}`);\n\t\t\tlet wpDetails: any = undefined;\n\t\t\t// @TODO: Rename to FetchProgressMonitor. There's nothing Emscripten\n\t\t\t// about that class anymore.\n\t\t\tconst monitor = new EmscriptenDownloadMonitor();\n\t\t\tif (!args.skipWordPressSetup) {\n\t\t\t\tlet progressReached100 = false;\n\t\t\t\tmonitor.addEventListener('progress', ((\n\t\t\t\t\te: CustomEvent<ProgressEvent & { finished: boolean }>\n\t\t\t\t) => {\n\t\t\t\t\tif (progressReached100) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t// @TODO Every progress bar will want percentages. The\n\t\t\t\t\t// download monitor should just provide that.\n\t\t\t\t\tconst { loaded, total } = e.detail;\n\t\t\t\t\t// Use floor() so we don't report 100% until truly there.\n\t\t\t\t\tconst percentProgress = Math.floor(\n\t\t\t\t\t\tMath.min(100, (100 * loaded) / total)\n\t\t\t\t\t);\n\t\t\t\t\tprogressReached100 = percentProgress === 100;\n\n\t\t\t\t\tif (!args.quiet) {\n\t\t\t\t\t\twriteProgressUpdate(\n\t\t\t\t\t\t\tprocess.stdout,\n\t\t\t\t\t\t\t`Downloading WordPress ${percentProgress}%...`,\n\t\t\t\t\t\t\tprogressReached100\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}) as any);\n\n\t\t\t\twpDetails = await resolveWordPressRelease(args.wp);\n\t\t\t}\n\t\t\tlogger.log(\n\t\t\t\t`Resolved WordPress release URL: ${wpDetails?.releaseUrl}`\n\t\t\t);\n\n\t\t\tconst preinstalledWpContentPath =\n\t\t\t\twpDetails &&\n\t\t\t\tpath.join(\n\t\t\t\t\tCACHE_FOLDER,\n\t\t\t\t\t`prebuilt-wp-content-for-wp-${wpDetails.version}.zip`\n\t\t\t\t);\n\t\t\tconst wordPressZip = !wpDetails\n\t\t\t\t? undefined\n\t\t\t\t: 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 );\n\n\t\t\tconst constants: Record<string, string | number | boolean | null> =\n\t\t\t\t{\n\t\t\t\t\tWP_DEBUG: true,\n\t\t\t\t\tWP_DEBUG_LOG: true,\n\t\t\t\t\tWP_DEBUG_DISPLAY: false,\n\t\t\t\t};\n\n\t\t\tlogger.log(`Booting WordPress...`);\n\t\t\trequestHandler = await bootWordPress({\n\t\t\t\tsiteUrl: absoluteUrl,\n\t\t\t\tcreatePhpRuntime: async () =>\n\t\t\t\t\tawait loadNodeRuntime(compiledBlueprint.versions.php, {\n\t\t\t\t\t\tfollowSymlinks: args.followSymlinks === true,\n\t\t\t\t\t}),\n\t\t\t\twordPressZip,\n\t\t\t\tsqliteIntegrationPluginZip: args.skipSqliteSetup\n\t\t\t\t\t? undefined\n\t\t\t\t\t: fetchSqliteIntegration(monitor),\n\t\t\t\tsapiName: 'cli',\n\t\t\t\tcreateFiles: {\n\t\t\t\t\t'/internal/shared/ca-bundle.crt':\n\t\t\t\t\t\trootCertificates.join('\\n'),\n\t\t\t\t},\n\t\t\t\tconstants,\n\t\t\t\tphpIniEntries: {\n\t\t\t\t\t'openssl.cafile': '/internal/shared/ca-bundle.crt',\n\t\t\t\t\tallow_url_fopen: '1',\n\t\t\t\t\tdisable_functions: '',\n\t\t\t\t},\n\t\t\t\thooks: {\n\t\t\t\t\tasync beforeWordPressFiles(php) {\n\t\t\t\t\t\tif (args.mountBeforeInstall) {\n\t\t\t\t\t\t\tmountResources(php, args.mountBeforeInstall);\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tcookieStore: false,\n\t\t\t});\n\t\t\tlogger.log(`Booted!`);\n\n\t\t\tconst php = await requestHandler.getPrimaryPhp();\n\t\t\ttry {\n\t\t\t\tif (\n\t\t\t\t\twpDetails &&\n\t\t\t\t\t!args.mountBeforeInstall &&\n\t\t\t\t\t!fs.existsSync(preinstalledWpContentPath)\n\t\t\t\t) {\n\t\t\t\t\tlogger.log(\n\t\t\t\t\t\t`Caching preinstalled WordPress for the next boot...`\n\t\t\t\t\t);\n\t\t\t\t\tfs.writeFileSync(\n\t\t\t\t\t\tpreinstalledWpContentPath,\n\t\t\t\t\t\tawait zipDirectory(php, '/wordpress')\n\t\t\t\t\t);\n\t\t\t\t\tlogger.log(`Cached!`);\n\t\t\t\t}\n\n\t\t\t\tif (args.mount) {\n\t\t\t\t\tmountResources(php, args.mount);\n\t\t\t\t}\n\n\t\t\t\twordPressReady = true;\n\n\t\t\t\tif (compiledBlueprint) {\n\t\t\t\t\tconst { php, reap } =\n\t\t\t\t\t\tawait requestHandler.processManager.acquirePHPInstance();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tlogger.log(`Running the Blueprint...`);\n\t\t\t\t\t\tawait runBlueprintSteps(compiledBlueprint, php);\n\t\t\t\t\t\tlogger.log(`Finished running the blueprint`);\n\t\t\t\t\t} finally {\n\t\t\t\t\t\treap();\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (args.command === 'build-snapshot') {\n\t\t\t\t\tawait zipSite(args.outfile as string);\n\t\t\t\t\tlogger.log(`WordPress exported to ${args.outfile}`);\n\t\t\t\t\tprocess.exit(0);\n\t\t\t\t} else if (args.command === 'run-blueprint') {\n\t\t\t\t\tlogger.log(`Blueprint executed`);\n\t\t\t\t\tprocess.exit(0);\n\t\t\t\t} else {\n\t\t\t\t\tlogger.log(`WordPress is running on ${absoluteUrl}`);\n\t\t\t\t}\n\n\t\t\t\treturn { requestHandler, server };\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\tconst phpLogs = php.readFileAsText(errorLogPath);\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\treturn await requestHandler.request(request);\n\t\t},\n\t});\n}\n"],"names":["expandAutoMounts","args","path","mount","mountBeforeInstall","isPluginDirectory","pluginName","basename","isThemeDirectory","themeName","containsWpContentDirectories","wpContentMounts","containsFullWordPressInstallation","files","fs","mounts","file","join","blueprint","getSteps","skipWordPressSetup","styleCssContent","pluginNameRegex","fileContent","wpContentDir","CACHE_FOLDER","os","fetchSqliteIntegration","monitor","cachedDownload","remoteUrl","cacheKey","artifactPath","downloadTo","readAsFile","localPath","reader","tmpPath","writer","done","value","resolve","reject","err","fileName","startServer","options","app","express","server","address","req","res","phpResponse","parseHeaders","bufferRequestBody","key","port","body","chunk","requestHeaders","i","parseMountWithDelimiterArguments","parsedMounts","mountParts","hostPath","vfsPath","existsSync","parseMountDirArguments","source","mountResources","php","createNodeFsMountHandler","runCLI","zipSite","outfile","reap","requestHandler","zip","compileInputBlueprint","isBlueprintBundle","RecommendedPHPVersion","tracker","ProgressTracker","lastCaption","progressReached100","e","progressInteger","message","writeProgressUpdate","compileBlueprint","lastProgressMessage","writeStream","finalUpdate","logger","compiledBlueprint","wordPressReady","absoluteUrl","wpDetails","EmscriptenDownloadMonitor","loaded","total","percentProgress","resolveWordPressRelease","preinstalledWpContentPath","wordPressZip","constants","bootWordPress","loadNodeRuntime","rootCertificates","zipDirectory","runBlueprintSteps","error","phpLogs","errorLogPath","request","PHPResponse"],"mappings":"4WASO,SAASA,EAAiBC,EAA8B,CACxD,MAAAC,EAAO,QAAQ,IAAI,EAEnBC,EAAQ,CAAC,GAAIF,EAAK,OAAS,CAAA,CAAG,EAC9BG,EAAqB,CAAC,GAAIH,EAAK,oBAAsB,CAAA,CAAG,EAE1D,GAAAI,EAAkBH,CAAI,EAAG,CACtB,MAAAI,EAAaC,WAASL,CAAI,EAChCC,EAAM,KAAK,CACV,SAAUD,EACV,QAAS,iCAAiCI,CAAU,EAAA,CACpD,CAAA,SACSE,EAAiBN,CAAI,EAAG,CAC5B,MAAAO,EAAYF,WAASL,CAAI,EAC/BC,EAAM,KAAK,CACV,SAAUD,EACV,QAAS,gCAAgCO,CAAS,EAAA,CAClD,CAAA,SACSC,EAA6BR,CAAI,EAC3CC,EAAM,KAAK,GAAGQ,EAAgBT,CAAI,CAAC,UACzBU,EAAkCV,CAAI,EAAG,CAQ7C,MAAAW,EAAQC,EAAG,YAAYZ,CAAI,EAC3Ba,EAAkB,CAAC,EACzB,UAAWC,KAAQH,EACdG,EAAK,WAAW,YAAY,GAGhCD,EAAO,KAAK,CACX,SAAU,GAAGb,CAAI,IAAIc,CAAI,GACzB,QAAS,cAAcA,CAAI,EAAA,CAC3B,EAEiBZ,EAAA,KAClB,GAAGW,EACH,GAAGJ,EAAgBM,EAAAA,KAAKf,EAAM,YAAY,CAAC,CAC5C,CAAA,MAMAC,EAAM,KAAK,CAAE,SAAUD,EAAM,QAAS,aAAc,EAG/C,MAAAgB,EAAajB,EAAK,WAAsC,CAAC,EACrDiB,EAAA,MAAQ,CAAC,GAAIA,EAAU,OAAS,G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AAA,kBAAkBhB,EAAmBxB,CAAG,EAC9CuB,SAAO,IAAI,gCAAgC,CAAA,QAC1C,CACIlB,EAAA,CAAA,CACN,CAGG,OAAA3E,EAAK,UAAY,kBACd,MAAAyE,EAAQzE,EAAK,OAAiB,EACpC6F,EAAA,OAAO,IAAI,yBAAyB7F,EAAK,OAAO,EAAE,EAClD,QAAQ,KAAK,CAAC,GACJA,EAAK,UAAY,iBAC3B6F,SAAO,IAAI,oBAAoB,EAC/B,QAAQ,KAAK,CAAC,GAEPA,EAAAA,OAAA,IAAI,2BAA2BG,CAAW,EAAE,EAG7C,CAAE,eAAApB,EAAgB,OAAA5B,CAAO,QACxB+D,EAAO,CACX,GAAA,CAAC/G,EAAK,MACH,MAAA+G,EAED,MAAAC,EAAU1C,EAAI,eAAe2C,cAAY,EAC/C,MAAM,IAAI,MAAMD,EAAS,CAAE,MAAOD,EAAO,CAAA,CAE3C,EACA,MAAM,cAAcG,EAAqB,CACxC,OAAKnB,EAME,MAAMnB,EAAe,QAAQsC,CAAO,EALnCC,EAAY,YAAA,YAClB,IACA,4BACD,CAE0C,CAC5C,CACA,CACF"}
@@ -0,0 +1,375 @@
1
+ import { logger as u, errorLogPath as z } from "@php-wasm/logger";
2
+ import { createNodeFsMountHandler as A, loadNodeRuntime as L } from "@php-wasm/node";
3
+ import { ProgressTracker as q, EmscriptenDownloadMonitor as T } from "@php-wasm/progress";
4
+ import { PHPResponse as U } from "@php-wasm/universal";
5
+ import { isBlueprintBundle as Z, compileBlueprint as V, runBlueprintSteps as j } from "@wp-playground/blueprints";
6
+ import { RecommendedPHPVersion as G, zipDirectory as O } from "@wp-playground/common";
7
+ import { resolveWordPressRelease as Y, bootWordPress as J } from "@wp-playground/wordpress";
8
+ import d, { existsSync as I } from "fs";
9
+ import $, { basename as g, join as W } from "path";
10
+ import { rootCertificates as K } from "tls";
11
+ import P from "fs-extra";
12
+ import Q from "os";
13
+ import X from "express";
14
+ function ee(e) {
15
+ const t = process.cwd(), n = [...e.mount || []], o = [...e.mountBeforeInstall || []];
16
+ if (C(t)) {
17
+ const s = g(t);
18
+ n.push({
19
+ hostPath: t,
20
+ vfsPath: `/wordpress/wp-content/plugins/${s}`
21
+ });
22
+ } else if (F(t)) {
23
+ const s = g(t);
24
+ n.push({
25
+ hostPath: t,
26
+ vfsPath: `/wordpress/wp-content/themes/${s}`
27
+ });
28
+ } else if (H(t))
29
+ n.push(...B(t));
30
+ else if (S(t)) {
31
+ const s = d.readdirSync(t), l = [];
32
+ for (const r of s)
33
+ r.startsWith("wp-content") || l.push({
34
+ hostPath: `${t}/${r}`,
35
+ vfsPath: `/wordpress/${r}`
36
+ });
37
+ o.push(
38
+ ...l,
39
+ ...B(W(t, "wp-content"))
40
+ );
41
+ } else
42
+ n.push({ hostPath: t, vfsPath: "/wordpress" });
43
+ const i = e.blueprint || {};
44
+ i.steps = [...i.steps || [], ...te(t)];
45
+ const a = e.skipWordPressSetup || S(t);
46
+ return {
47
+ ...e,
48
+ blueprint: i,
49
+ mount: n,
50
+ mountBeforeInstall: o,
51
+ skipWordPressSetup: a
52
+ };
53
+ }
54
+ function S(e) {
55
+ const t = d.readdirSync(e);
56
+ return t.includes("wp-admin") && t.includes("wp-includes") && t.includes("wp-content");
57
+ }
58
+ function H(e) {
59
+ const t = d.readdirSync(e);
60
+ return t.includes("themes") || t.includes("plugins") || t.includes("mu-plugins") || t.includes("uploads");
61
+ }
62
+ function F(e) {
63
+ if (!d.readdirSync(e).includes("style.css"))
64
+ return !1;
65
+ const n = d.readFileSync(W(e, "style.css"), "utf8");
66
+ return !!/^(?:[ \t]*<\?php)?[ \t/*#@]*Theme Name:(.*)$/im.exec(n);
67
+ }
68
+ function C(e) {
69
+ const t = d.readdirSync(e), n = /^(?:[ \t]*<\?php)?[ \t/*#@]*Plugin Name:(.*)$/im;
70
+ return !!t.filter((i) => i.endsWith(".php")).find((i) => {
71
+ const a = d.readFileSync(W(e, i), "utf8");
72
+ return !!n.exec(a);
73
+ });
74
+ }
75
+ function B(e) {
76
+ return d.readdirSync(e).filter((n) => !n.startsWith("index.php")).map((n) => ({
77
+ hostPath: `${e}/${n}`,
78
+ vfsPath: `/wordpress/wp-content/${n}`
79
+ }));
80
+ }
81
+ function te(e) {
82
+ return C(e) ? [
83
+ {
84
+ step: "activatePlugin",
85
+ pluginPath: `/wordpress/wp-content/plugins/${g(e)}`
86
+ }
87
+ ] : F(e) ? [
88
+ {
89
+ step: "activateTheme",
90
+ themeFolderName: g(e)
91
+ }
92
+ ] : H(e) || S(e) ? [
93
+ {
94
+ step: "runPHP",
95
+ code: `<?php
96
+ require_once '/wordpress/wp-load.php';
97
+ $theme = wp_get_theme();
98
+ if (!$theme->exists()) {
99
+ $themes = wp_get_themes();
100
+ if (count($themes) > 0) {
101
+ $themeName = array_keys($themes)[0];
102
+ switch_theme($themeName);
103
+ }
104
+ }
105
+ `
106
+ }
107
+ ] : [];
108
+ }
109
+ const R = $.join(Q.homedir(), ".wordpress-playground");
110
+ async function ne(e) {
111
+ return await M(
112
+ "https://github.com/WordPress/sqlite-database-integration/archive/refs/heads/develop.zip",
113
+ "sqlite.zip",
114
+ e
115
+ );
116
+ }
117
+ async function M(e, t, n) {
118
+ const o = $.join(R, t);
119
+ return P.existsSync(o) || (P.ensureDirSync(R), await re(e, o, n)), _(o);
120
+ }
121
+ async function re(e, t, n) {
122
+ const i = (await n.monitorFetch(fetch(e))).body.getReader(), a = `${t}.partial`, s = P.createWriteStream(a);
123
+ for (; ; ) {
124
+ const { done: l, value: r } = await i.read();
125
+ if (r && s.write(r), l)
126
+ break;
127
+ }
128
+ s.close(), s.closed || await new Promise((l, r) => {
129
+ s.on("finish", () => {
130
+ P.renameSync(a, t), l(null);
131
+ }), s.on("error", (p) => {
132
+ P.removeSync(a), r(p);
133
+ });
134
+ });
135
+ }
136
+ function _(e, t) {
137
+ return new File([P.readFileSync(e)], g(e));
138
+ }
139
+ async function se(e) {
140
+ const t = X(), n = await new Promise((a, s) => {
141
+ const l = t.listen(e.port, () => {
142
+ const r = l.address();
143
+ r === null || typeof r == "string" ? s(new Error("Server address is not available")) : a(l);
144
+ });
145
+ });
146
+ t.use("/", async (a, s) => {
147
+ const l = await e.handleRequest({
148
+ url: a.url,
149
+ headers: ie(a),
150
+ method: a.method,
151
+ body: await oe(a)
152
+ });
153
+ s.statusCode = l.httpStatusCode;
154
+ for (const r in l.headers)
155
+ s.setHeader(r, l.headers[r]);
156
+ s.end(l.bytes);
157
+ });
158
+ const i = n.address().port;
159
+ return await e.onBind(n, i);
160
+ }
161
+ const oe = async (e) => await new Promise((t) => {
162
+ const n = [];
163
+ e.on("data", (o) => {
164
+ n.push(o);
165
+ }), e.on("end", () => {
166
+ t(new Uint8Array(Buffer.concat(n)));
167
+ });
168
+ }), ie = (e) => {
169
+ const t = {};
170
+ if (e.rawHeaders && e.rawHeaders.length)
171
+ for (let n = 0; n < e.rawHeaders.length; n += 2)
172
+ t[e.rawHeaders[n].toLowerCase()] = e.rawHeaders[n + 1];
173
+ return t;
174
+ };
175
+ function $e(e) {
176
+ const t = [];
177
+ for (const n of e) {
178
+ const o = n.split(":");
179
+ if (o.length !== 2)
180
+ throw new Error(`Invalid mount format: ${n}.
181
+ Expected format: /host/path:/vfs/path.
182
+ If your path contains a colon, e.g. C:\\myplugin, use the --mount-dir option instead.
183
+ Example: --mount-dir C:\\my-plugin /wordpress/wp-content/plugins/my-plugin`);
184
+ const [i, a] = o;
185
+ if (!I(i))
186
+ throw new Error(`Host path does not exist: ${i}`);
187
+ t.push({ hostPath: i, vfsPath: a });
188
+ }
189
+ return t;
190
+ }
191
+ function ve(e) {
192
+ if (e.length % 2 !== 0)
193
+ throw new Error("Invalid mount format. Expected: /host/path /vfs/path");
194
+ const t = [];
195
+ for (let n = 0; n < e.length; n += 2) {
196
+ const o = e[n], i = e[n + 1];
197
+ if (!I(o))
198
+ throw new Error(`Host path does not exist: ${o}`);
199
+ t.push({
200
+ hostPath: $.resolve(process.cwd(), o),
201
+ vfsPath: i
202
+ });
203
+ }
204
+ return t;
205
+ }
206
+ function E(e, t) {
207
+ for (const n of t)
208
+ e.mkdir(n.vfsPath), e.mount(n.vfsPath, A(n.hostPath));
209
+ }
210
+ async function be(e) {
211
+ e.autoMount && (e = ee(e));
212
+ async function t(r) {
213
+ const { php: p, reap: f } = await s.processManager.acquirePHPInstance();
214
+ try {
215
+ await p.run({
216
+ code: `<?php
217
+ $zip = new ZipArchive();
218
+ if(false === $zip->open('/tmp/build.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
219
+ throw new Exception('Failed to create ZIP');
220
+ }
221
+ $files = new RecursiveIteratorIterator(
222
+ new RecursiveDirectoryIterator('/wordpress')
223
+ );
224
+ foreach ($files as $file) {
225
+ echo $file . PHP_EOL;
226
+ if (!$file->isFile()) {
227
+ continue;
228
+ }
229
+ $zip->addFile($file->getPathname(), $file->getPathname());
230
+ }
231
+ $zip->close();
232
+
233
+ `
234
+ });
235
+ const c = p.readFileAsBuffer("/tmp/build.zip");
236
+ d.writeFileSync(r, c);
237
+ } finally {
238
+ f();
239
+ }
240
+ }
241
+ async function n() {
242
+ const r = Z(e.blueprint) ? e.blueprint : {
243
+ login: e.login,
244
+ ...e.blueprint,
245
+ preferredVersions: {
246
+ php: e.php ?? e?.blueprint?.preferredVersions?.php ?? G,
247
+ wp: e.wp ?? e?.blueprint?.preferredVersions?.wp ?? "latest",
248
+ ...e.blueprint?.preferredVersions || {}
249
+ }
250
+ }, p = new q();
251
+ let f = "", c = !1;
252
+ return p.addEventListener("progress", (m) => {
253
+ if (c)
254
+ return;
255
+ c = m.detail.progress === 100;
256
+ const w = Math.floor(m.detail.progress);
257
+ f = m.detail.caption || f || "Running the Blueprint";
258
+ const v = `${f.trim()} – ${w}%`;
259
+ e.quiet || i(
260
+ process.stdout,
261
+ v,
262
+ c
263
+ );
264
+ }), await V(r, {
265
+ progress: p
266
+ });
267
+ }
268
+ let o = "";
269
+ function i(r, p, f) {
270
+ p !== o && (o = p, r.isTTY ? (r.cursorTo(0), r.write(p), r.clearLine(1), f && r.write(`
271
+ `)) : r.write(`${p}
272
+ `));
273
+ }
274
+ e.quiet && (u.handlers = []);
275
+ const a = await n();
276
+ let s, l = !1;
277
+ return u.log("Starting a PHP server..."), se({
278
+ port: e.port,
279
+ onBind: async (r, p) => {
280
+ const f = `http://127.0.0.1:${p}`;
281
+ u.log(`Setting up WordPress ${e.wp}`);
282
+ let c;
283
+ const m = new T();
284
+ if (!e.skipWordPressSetup) {
285
+ let h = !1;
286
+ m.addEventListener("progress", (y) => {
287
+ if (h)
288
+ return;
289
+ const { loaded: N, total: k } = y.detail, x = Math.floor(
290
+ Math.min(100, 100 * N / k)
291
+ );
292
+ h = x === 100, e.quiet || i(
293
+ process.stdout,
294
+ `Downloading WordPress ${x}%...`,
295
+ h
296
+ );
297
+ }), c = await Y(e.wp);
298
+ }
299
+ u.log(
300
+ `Resolved WordPress release URL: ${c?.releaseUrl}`
301
+ );
302
+ const w = c && $.join(
303
+ R,
304
+ `prebuilt-wp-content-for-wp-${c.version}.zip`
305
+ ), v = c ? d.existsSync(w) ? _(w) : await M(
306
+ c.releaseUrl,
307
+ `${c.version}.zip`,
308
+ m
309
+ ) : void 0, D = {
310
+ WP_DEBUG: !0,
311
+ WP_DEBUG_LOG: !0,
312
+ WP_DEBUG_DISPLAY: !1
313
+ };
314
+ u.log("Booting WordPress..."), s = await J({
315
+ siteUrl: f,
316
+ createPhpRuntime: async () => await L(a.versions.php, {
317
+ followSymlinks: e.followSymlinks === !0
318
+ }),
319
+ wordPressZip: v,
320
+ sqliteIntegrationPluginZip: e.skipSqliteSetup ? void 0 : ne(m),
321
+ sapiName: "cli",
322
+ createFiles: {
323
+ "/internal/shared/ca-bundle.crt": K.join(`
324
+ `)
325
+ },
326
+ constants: D,
327
+ phpIniEntries: {
328
+ "openssl.cafile": "/internal/shared/ca-bundle.crt",
329
+ allow_url_fopen: "1",
330
+ disable_functions: ""
331
+ },
332
+ hooks: {
333
+ async beforeWordPressFiles(h) {
334
+ e.mountBeforeInstall && E(h, e.mountBeforeInstall);
335
+ }
336
+ },
337
+ cookieStore: !1
338
+ }), u.log("Booted!");
339
+ const b = await s.getPrimaryPhp();
340
+ try {
341
+ if (c && !e.mountBeforeInstall && !d.existsSync(w) && (u.log(
342
+ "Caching preinstalled WordPress for the next boot..."
343
+ ), d.writeFileSync(
344
+ w,
345
+ await O(b, "/wordpress")
346
+ ), u.log("Cached!")), e.mount && E(b, e.mount), l = !0, a) {
347
+ const { php: h, reap: y } = await s.processManager.acquirePHPInstance();
348
+ try {
349
+ u.log("Running the Blueprint..."), await j(a, h), u.log("Finished running the blueprint");
350
+ } finally {
351
+ y();
352
+ }
353
+ }
354
+ return e.command === "build-snapshot" ? (await t(e.outfile), u.log(`WordPress exported to ${e.outfile}`), process.exit(0)) : e.command === "run-blueprint" ? (u.log("Blueprint executed"), process.exit(0)) : u.log(`WordPress is running on ${f}`), { requestHandler: s, server: r };
355
+ } catch (h) {
356
+ if (!e.debug)
357
+ throw h;
358
+ const y = b.readFileAsText(z);
359
+ throw new Error(y, { cause: h });
360
+ }
361
+ },
362
+ async handleRequest(r) {
363
+ return l ? await s.request(r) : U.forHttpCode(
364
+ 502,
365
+ "WordPress is not ready yet"
366
+ );
367
+ }
368
+ });
369
+ }
370
+ export {
371
+ ve as a,
372
+ $e as p,
373
+ be as r
374
+ };
375
+ //# sourceMappingURL=run-cli-_8y4VW5F.js.map