@wp-playground/blueprints 0.1.59 → 0.1.61

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,4 +1,5 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const x=async(s,{pluginPath:e,pluginName:t},r)=>{r?.tracker.setCaption(`Activating ${t||e}`);const i=[`${await s.documentRoot}/wp-load.php`,`${await s.documentRoot}/wp-admin/includes/plugin.php`];if(!i.every(a=>s.fileExists(a)))throw new Error(`Required WordPress files do not exist: ${i.join(", ")}`);if((await s.run({code:`<?php
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const F=async(r,{pluginPath:e,pluginName:t},s)=>{s?.tracker.setCaption(`Activating ${t||e}`);const i=[`${await r.documentRoot}/wp-load.php`,`${await r.documentRoot}/wp-admin/includes/plugin.php`];if(!i.every(a=>r.fileExists(a)))throw new Error(`Required WordPress files do not exist: ${i.join(", ")}`);if((await r.run({code:`<?php
2
+ define( 'WP_ADMIN', true );
2
3
  ${i.map(a=>`require_once( '${a}' );`).join(`
3
4
  `)}
4
5
  $plugin_path = '${e}';
@@ -15,22 +16,27 @@ foreach ( ( glob( $plugin_path . '/*.php' ) ?: array() ) as $file ) {
15
16
  }
16
17
  }
17
18
  echo 'NO_ENTRY_FILE';
18
- `})).text.endsWith("NO_ENTRY_FILE"))throw new Error("Could not find plugin entry file.")},F=async(s,{themeFolderName:e},t)=>{t?.tracker.setCaption(`Activating ${e}`);const r=`${await s.documentRoot}/wp-load.php`;if(!s.fileExists(r))throw new Error(`Required WordPress file does not exist: ${r}`);await s.run({code:`<?php
19
- require_once( '${r}' );
20
- switch_theme( '${e}' );
21
- `})};function b(s){const e=s.split(".").shift().replace(/-/g," ");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}async function P(s,e,t){let r="";await s.fileExists(e)&&(r=await s.readFileAsText(e)),await s.writeFile(e,t(r))}async function xe(s){return new Uint8Array(await s.arrayBuffer())}class Fe extends File{constructor(e,t){super(e,t),this.buffers=e}async arrayBuffer(){return this.buffers[0]}}const T=File.prototype.arrayBuffer instanceof Function?File:Fe,X=async(s,e)=>{const t=new Te(s,e.siteUrl,e.wordpressPath||"/wordpress");e.patchSqlitePlugin!==!1&&await t.patchSqlitePlugin(),e.addPhpInfo!==!1&&await t.addPhpInfo(),e.patchSiteUrl!==!1&&await t.patchSiteUrl(),e.disableSiteHealth!==!1&&await t.disableSiteHealth(),e.disableWpNewBlogNotification!==!1&&await t.disableWpNewBlogNotification()};class Te{constructor(e,t,r){this.php=e,this.scopedSiteUrl=t,this.wordpressPath=r}async patchSqlitePlugin(){await P(this.php,`${this.wordpressPath}/wp-content/plugins/sqlite-database-integration/wp-includes/sqlite/class-wp-sqlite-translator.php`,e=>e.replace("if ( false === strtotime( $value ) )",'if ( $value === "0000-00-00 00:00:00" || false === strtotime( $value ) )'))}async addPhpInfo(){await this.php.writeFile(`${this.wordpressPath}/phpinfo.php`,"<?php phpinfo(); ")}async patchSiteUrl(){await P(this.php,`${this.wordpressPath}/wp-config.php`,e=>`<?php
22
- if(!defined('WP_HOME')) {
23
- define('WP_HOME', "${this.scopedSiteUrl}");
24
- define('WP_SITEURL', "${this.scopedSiteUrl}");
25
- }
26
- ?>${e}`)}async disableSiteHealth(){await P(this.php,`${this.wordpressPath}/wp-includes/default-filters.php`,e=>e.replace(/add_filter[^;]+wp_maybe_grant_site_health_caps[^;]+;/i,""))}async disableWpNewBlogNotification(){await P(this.php,`${this.wordpressPath}/wp-config.php`,e=>`${e} function wp_new_blog_notification(...$args){} `)}}const ee=async(s,{code:e})=>await s.run({code:e}),te=async(s,{options:e})=>await s.run(e),se=async(s,{key:e,value:t})=>{await s.setPhpIniEntry(e,t)},re=async(s,{request:e})=>await s.request(e),ie=async(s,{fromPath:e,toPath:t})=>{await s.writeFile(t,await s.readFileAsBuffer(e))},ne=async(s,{fromPath:e,toPath:t})=>{await s.mv(e,t)},oe=async(s,{path:e})=>{await s.mkdir(e)},ae=async(s,{path:e})=>{await s.unlink(e)},ce=async(s,{path:e})=>{await s.rmdir(e)},k=async(s,{path:e,data:t})=>{t instanceof File&&(t=await xe(t)),await s.writeFile(e,t)},W="/vfs-blueprints",C=async(s,{consts:e,virtualize:t=!1})=>{const r=await s.documentRoot,i=t?W:r,n=`${i}/playground-consts.json`,o=`${i}/wp-config.php`;return t&&(s.mkdir(W),s.setPhpIniEntry("auto_prepend_file",o)),await P(s,n,a=>JSON.stringify({...JSON.parse(a||"{}"),...e})),await P(s,o,a=>a.includes("playground-consts.json")?a:`<?php
19
+ `})).text.endsWith("NO_ENTRY_FILE"))throw new Error("Could not find plugin entry file.")},C=async(r,{themeFolderName:e},t)=>{t?.tracker.setCaption(`Activating ${e}`);const s=`${await r.documentRoot}/wp-load.php`;if(!r.fileExists(s))throw new Error(`Required WordPress file does not exist: ${s}`);await r.run({code:`<?php
20
+ define( 'WP_ADMIN', true );
21
+ require_once( '${s}' );
22
+ switch_theme( '${e}' );
23
+ `})};function v(r){const e=r.split(".").shift().replace(/-/g," ");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}async function b(r,e,t){let s="";await r.fileExists(e)&&(s=await r.readFileAsText(e)),await r.writeFile(e,t(s))}async function xe(r){return new Uint8Array(await r.arrayBuffer())}class Fe extends File{constructor(e,t){super(e,t),this.buffers=e}async arrayBuffer(){return this.buffers[0]}}const k=File.prototype.arrayBuffer instanceof Function?File:Fe,W="/vfs-blueprints",E=async(r,{consts:e,virtualize:t=!1})=>{const s=await r.documentRoot,i=t?W:s,n=`${i}/playground-consts.json`,o=`${i}/wp-config.php`;return t&&(r.mkdir(W),r.setPhpIniEntry("auto_prepend_file",o)),await b(r,n,a=>JSON.stringify({...JSON.parse(a||"{}"),...e})),await b(r,o,a=>a.includes("playground-consts.json")?a:`<?php
27
24
  $consts = json_decode(file_get_contents('${n}'), true);
28
25
  foreach ($consts as $const => $value) {
29
26
  if (!defined($const)) {
30
27
  define($const, $value);
31
28
  }
32
29
  }
33
- ?>${a}`),o},le=async(s,{siteUrl:e})=>await C(s,{consts:{WP_HOME:e,WP_SITEURL:e}});class he{constructor({concurrency:e}){this._running=0,this.concurrency=e,this.queue=[]}get running(){return this._running}async acquire(){for(;;)if(this._running>=this.concurrency)await new Promise(e=>this.queue.push(e));else return this._running++,()=>{this._running--,this.queue.length>0&&this.queue.shift()()}}async run(e){const t=await this.acquire();try{return await e()}finally{t()}}}const ke=Symbol("literal");function $(s){if(typeof s=="string")return s.startsWith("$")?s:JSON.stringify(s);if(typeof s=="number")return s.toString();if(Array.isArray(s))return`array(${s.map($).join(", ")})`;if(s===null)return"null";if(typeof s=="object")return ke in s?s.toString():`array(${Object.entries(s).map(([t,r])=>`${JSON.stringify(t)} => ${$(r)}`).join(", ")})`;if(typeof s=="function")return s();throw new Error(`Unsupported value: ${s}`)}function A(s){const e={};for(const t in s)e[t]=$(s[t]);return e}const I=`<?php
30
+ ?>${a}`),o},ee=async(r,e)=>{const t=new Ce(r,e.wordpressPath||"/wordpress",e.siteUrl);e.addPhpInfo===!0&&await t.addPhpInfo(),e.siteUrl&&await t.patchSiteUrl(),e.patchSecrets===!0&&await t.patchSecrets(),e.disableSiteHealth===!0&&await t.disableSiteHealth(),e.disableWpNewBlogNotification===!0&&await t.disableWpNewBlogNotification()};class Ce{constructor(e,t,s){this.php=e,this.scopedSiteUrl=s,this.wordpressPath=t}async addPhpInfo(){await this.php.writeFile(`${this.wordpressPath}/phpinfo.php`,"<?php phpinfo(); ")}async patchSiteUrl(){await E(this.php,{consts:{WP_HOME:this.scopedSiteUrl,WP_SITEURL:this.scopedSiteUrl},virtualize:!0})}async patchSecrets(){await b(this.php,`${this.wordpressPath}/wp-config.php`,e=>`<?php
31
+ define('AUTH_KEY', '${g(40)}');
32
+ define('SECURE_AUTH_KEY', '${g(40)}');
33
+ define('LOGGED_IN_KEY', '${g(40)}');
34
+ define('NONCE_KEY', '${g(40)}');
35
+ define('AUTH_SALT', '${g(40)}');
36
+ define('SECURE_AUTH_SALT', '${g(40)}');
37
+ define('LOGGED_IN_SALT', '${g(40)}');
38
+ define('NONCE_SALT', '${g(40)}');
39
+ ?>${e.replaceAll("', 'put your unique phrase here'","__', ''")}`)}async disableSiteHealth(){await b(this.php,`${this.wordpressPath}/wp-includes/default-filters.php`,e=>e.replace(/add_filter[^;]+wp_maybe_grant_site_health_caps[^;]+;/i,""))}async disableWpNewBlogNotification(){await b(this.php,`${this.wordpressPath}/wp-config.php`,e=>`${e} function wp_new_blog_notification(...$args){} `)}}function g(r){const e="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_+=-[]/.,<>?";let t="";for(let s=r;s>0;--s)t+=e[Math.floor(Math.random()*e.length)];return t}const te=async(r,{code:e})=>await r.run({code:e}),re=async(r,{options:e})=>await r.run(e),se=async(r,{key:e,value:t})=>{await r.setPhpIniEntry(e,t)},ie=async(r,{request:e})=>await r.request(e),ne=async(r,{fromPath:e,toPath:t})=>{await r.writeFile(t,await r.readFileAsBuffer(e))},oe=async(r,{fromPath:e,toPath:t})=>{await r.mv(e,t)},ae=async(r,{path:e})=>{await r.mkdir(e)},ce=async(r,{path:e})=>{await r.unlink(e)},le=async(r,{path:e})=>{await r.rmdir(e)},A=async(r,{path:e,data:t})=>{t instanceof File&&(t=await xe(t)),await r.writeFile(e,t)},he=async(r,{siteUrl:e})=>await E(r,{consts:{WP_HOME:e,WP_SITEURL:e}});class ue{constructor({concurrency:e}){this._running=0,this.concurrency=e,this.queue=[]}get running(){return this._running}async acquire(){for(;;)if(this._running>=this.concurrency)await new Promise(e=>this.queue.push(e));else{this._running++;let e=!1;return()=>{e||(e=!0,this._running--,this.queue.length>0&&this.queue.shift()())}}}async run(e){const t=await this.acquire();try{return await e()}finally{t()}}}const ke=Symbol("literal");function $(r){if(typeof r=="string")return r.startsWith("$")?r:JSON.stringify(r);if(typeof r=="number")return r.toString();if(Array.isArray(r))return`array(${r.map($).join(", ")})`;if(r===null)return"null";if(typeof r=="object")return ke in r?r.toString():`array(${Object.entries(r).map(([t,s])=>`${JSON.stringify(t)} => ${$(s)}`).join(", ")})`;if(typeof r=="function")return r();throw new Error(`Unsupported value: ${r}`)}function U(r){const e={};for(const t in r)e[t]=$(r[t]);return e}const M=`<?php
34
40
 
35
41
  function zipDir($dir, $output, $additionalFiles = array())
36
42
  {
@@ -92,32 +98,32 @@ function delTree($dir)
92
98
  }
93
99
  return rmdir($dir);
94
100
  }
95
- `;async function ue(s){const e="wordpress-playground.zip",t=`/${e}`,r=A({zipPath:t,documentRoot:await s.documentRoot});await fe(s,`zipDir(${r.documentRoot}, ${r.zipPath});`);const i=await s.readFileAsBuffer(t);return s.unlink(t),new File([i],e)}const pe=async(s,{fullSiteZip:e})=>{const t="/import.zip";await s.writeFile(t,new Uint8Array(await e.arrayBuffer()));const r=await s.absoluteUrl,i=await s.documentRoot;await s.rmdir(i),await v(s,{zipPath:t,extractToPath:"/"});const n=A({absoluteUrl:r});await Ae(s,`${i}/wp-config.php`,o=>`<?php
101
+ `;async function pe(r){const e="wordpress-playground.zip",t=`/${e}`,s=U({zipPath:t,documentRoot:await r.documentRoot});await me(r,`zipDir(${s.documentRoot}, ${s.zipPath});`);const i=await r.readFileAsBuffer(t);return r.unlink(t),new File([i],e)}const de=async(r,{fullSiteZip:e})=>{const t="/import.zip";await r.writeFile(t,new Uint8Array(await e.arrayBuffer()));const s=await r.absoluteUrl,i=await r.documentRoot;await r.rmdir(i),await S(r,{zipPath:t,extractToPath:"/"});const n=U({absoluteUrl:s});await Ue(r,`${i}/wp-config.php`,o=>`<?php
96
102
  if(!defined('WP_HOME')) {
97
103
  define('WP_HOME', ${n.absoluteUrl});
98
104
  define('WP_SITEURL', ${n.absoluteUrl});
99
105
  }
100
- ?>${o}`)},v=async(s,{zipPath:e,extractToPath:t})=>{const r=A({zipPath:e,extractToPath:t});await fe(s,`unzip(${r.zipPath}, ${r.extractToPath});`)},de=async(s,{file:e})=>{const t=await s.request({url:"/wp-admin/admin.php?import=wordpress"}),r=z(t).getElementById("import-upload-form")?.getAttribute("action"),i=await s.request({url:`/wp-admin/${r}`,method:"POST",files:{import:e}}),n=z(i).querySelector("#wpbody-content form");if(!n)throw console.log(i.text),new Error("Could not find an importer form in response. See the response text above for details.");const o=Ce(n);o.fetch_attachments="1";for(const a in o)if(a.startsWith("user_map[")){const l="user_new["+a.slice(9,-1)+"]";o[l]="1"}await s.request({url:n.action,method:"POST",formData:o})};function z(s){return new DOMParser().parseFromString(s.text,"text/html")}function Ce(s){return Object.fromEntries(new FormData(s).entries())}async function Ae(s,e,t){await s.writeFile(e,t(await s.readFileAsText(e)))}async function fe(s,e){const t=await s.run({code:I+e});if(t.exitCode!==0)throw console.log(I+e),console.log(e+""),console.log(t.errors),t.errors;return t}async function me(s,{targetPath:e,zipFile:t}){const r=t.name,i=r.replace(/\.zip$/,""),n=`/tmp/assets/${i}`,o=`/tmp/${r}`,a=()=>s.rmdir(n,{recursive:!0});await s.fileExists(n)&&await a(),await k(s,{path:o,data:t});const l=()=>Promise.all([a,()=>s.unlink(o)]);try{await v(s,{zipPath:o,extractToPath:n});const c=await s.listFiles(n,{prependPath:!0}),u=c.length===1&&await s.isDir(c[0]);let d,E="";u?(E=c[0],d=c[0].split("/").pop()):(E=n,d=i);const H=`${e}/${d}`;return await s.mv(E,H),await l(),{assetFolderPath:H,assetFolderName:d}}catch(c){throw await l(),c}}const we=async(s,{pluginZipFile:e,options:t={}},r)=>{const i=e.name.split("/").pop()||"plugin.zip",n=b(i);r?.tracker.setCaption(`Installing the ${n} plugin`);try{const{assetFolderPath:o}=await me(s,{zipFile:e,targetPath:`${await s.documentRoot}/wp-content/plugins`});("activate"in t?t.activate:!0)&&await x(s,{pluginPath:o,pluginName:n},r),await Ue(s)}catch(o){console.error(`Proceeding without the ${n} plugin. Could not install it in wp-admin. The original error was: ${o}`),console.error(o)}};async function Ue(s){await s.isDir("/wordpress/wp-content/plugins/gutenberg")&&!await s.fileExists("/wordpress/.gutenberg-patched")&&(await s.writeFile("/wordpress/.gutenberg-patched","1"),await q(s,"/wordpress/wp-content/plugins/gutenberg/build/block-editor/index.js",e=>e.replace(/srcDoc:("[^"]+"|[^,]+)/g,'src:"/wp-includes/empty.html"')),await q(s,"/wordpress/wp-content/plugins/gutenberg/build/block-editor/index.min.js",e=>e.replace(/srcDoc:("[^"]+"|[^,]+)/g,'src:"/wp-includes/empty.html"')))}async function q(s,e,t){return await s.writeFile(e,t(await s.readFileAsText(e)))}const ge=async(s,{themeZipFile:e,options:t={}},r)=>{const i=b(e.name);r?.tracker.setCaption(`Installing the ${i} theme`);try{const{assetFolderName:n}=await me(s,{zipFile:e,targetPath:`${await s.documentRoot}/wp-content/themes`});("activate"in t?t.activate:!0)&&await F(s,{themeFolderName:n},r)}catch(n){console.error(`Proceeding without the ${i} theme. Could not install it in wp-admin. The original error was: ${n}`),console.error(n)}},ye=async(s,{username:e="admin",password:t="password"}={},r)=>{r?.tracker.setCaption(r?.initialCaption||"Logging in"),await s.request({url:"/wp-login.php"}),await s.request({url:"/wp-login.php",method:"POST",formData:{log:e,pwd:t,rememberme:"forever"}})},Pe=async(s,{options:e})=>{await s.request({url:"/wp-admin/install.php?step=2",method:"POST",formData:{language:"en",prefix:"wp_",weblog_title:"My WordPress Website",user_name:e.adminPassword||"admin",admin_password:e.adminPassword||"password",admin_password2:e.adminPassword||"password",Submit:"Install WordPress",pw_weak:"1",admin_email:"admin@localhost.com"}})},_e=async(s,{options:e})=>{const t=`<?php
106
+ ?>${o}`)},S=async(r,{zipPath:e,extractToPath:t})=>{const s=U({zipPath:e,extractToPath:t});await me(r,`unzip(${s.zipPath}, ${s.extractToPath});`)},fe=async(r,{file:e})=>{const t=await r.request({url:"/wp-admin/admin.php?import=wordpress"}),s=z(t).getElementById("import-upload-form")?.getAttribute("action"),i=await r.request({url:`/wp-admin/${s}`,method:"POST",files:{import:e}}),n=z(i).querySelector("#wpbody-content form");if(!n)throw console.log(i.text),new Error("Could not find an importer form in response. See the response text above for details.");const o=Ae(n);o.fetch_attachments="1";for(const a in o)if(a.startsWith("user_map[")){const l="user_new["+a.slice(9,-1)+"]";o[l]="1"}await r.request({url:n.action,method:"POST",formData:o})};function z(r){return new DOMParser().parseFromString(r.text,"text/html")}function Ae(r){return Object.fromEntries(new FormData(r).entries())}async function Ue(r,e,t){await r.writeFile(e,t(await r.readFileAsText(e)))}async function me(r,e){const t=await r.run({code:M+e});if(t.exitCode!==0)throw console.log(M+e),console.log(e+""),console.log(t.errors),t.errors;return t}async function we(r,{targetPath:e,zipFile:t}){const s=t.name,i=s.replace(/\.zip$/,""),n=`/tmp/assets/${i}`,o=`/tmp/${s}`,a=()=>r.rmdir(n,{recursive:!0});await r.fileExists(n)&&await a(),await A(r,{path:o,data:t});const l=()=>Promise.all([a,()=>r.unlink(o)]);try{await S(r,{zipPath:o,extractToPath:n});const c=await r.listFiles(n,{prependPath:!0}),u=c.length===1&&await r.isDir(c[0]);let d,T="";u?(T=c[0],d=c[0].split("/").pop()):(T=n,d=i);const I=`${e}/${d}`;return await r.mv(T,I),await l(),{assetFolderPath:I,assetFolderName:d}}catch(c){throw await l(),c}}const ge=async(r,{pluginZipFile:e,options:t={}},s)=>{const i=e.name.split("/").pop()||"plugin.zip",n=v(i);s?.tracker.setCaption(`Installing the ${n} plugin`);try{const{assetFolderPath:o}=await we(r,{zipFile:e,targetPath:`${await r.documentRoot}/wp-content/plugins`});("activate"in t?t.activate:!0)&&await F(r,{pluginPath:o,pluginName:n},s),await Ne(r)}catch(o){console.error(`Proceeding without the ${n} plugin. Could not install it in wp-admin. The original error was: ${o}`),console.error(o)}};async function Ne(r){await r.isDir("/wordpress/wp-content/plugins/gutenberg")&&!await r.fileExists("/wordpress/.gutenberg-patched")&&(await r.writeFile("/wordpress/.gutenberg-patched","1"),await D(r,"/wordpress/wp-content/plugins/gutenberg/build/block-editor/index.js",e=>e.replace(/srcDoc:("[^"]+"|[^,]+)/g,'src:"/wp-includes/empty.html"')),await D(r,"/wordpress/wp-content/plugins/gutenberg/build/block-editor/index.min.js",e=>e.replace(/srcDoc:("[^"]+"|[^,]+)/g,'src:"/wp-includes/empty.html"')))}async function D(r,e,t){return await r.writeFile(e,t(await r.readFileAsText(e)))}const ye=async(r,{themeZipFile:e,options:t={}},s)=>{const i=v(e.name);s?.tracker.setCaption(`Installing the ${i} theme`);try{const{assetFolderName:n}=await we(r,{zipFile:e,targetPath:`${await r.documentRoot}/wp-content/themes`});("activate"in t?t.activate:!0)&&await C(r,{themeFolderName:n},s)}catch(n){console.error(`Proceeding without the ${i} theme. Could not install it in wp-admin. The original error was: ${n}`),console.error(n)}},Pe=async(r,{username:e="admin",password:t="password"}={},s)=>{s?.tracker.setCaption(s?.initialCaption||"Logging in"),await r.request({url:"/wp-login.php"}),await r.request({url:"/wp-login.php",method:"POST",formData:{log:e,pwd:t,rememberme:"forever"}})},_e=async(r,{options:e})=>{await r.request({url:"/wp-admin/install.php?step=2",method:"POST",formData:{language:"en",prefix:"wp_",weblog_title:"My WordPress Website",user_name:e.adminPassword||"admin",admin_password:e.adminPassword||"password",admin_password2:e.adminPassword||"password",Submit:"Install WordPress",pw_weak:"1",admin_email:"admin@localhost.com"}})},$e=async(r,{options:e})=>{const t=`<?php
101
107
  include 'wordpress/wp-load.php';
102
108
  $site_options = ${$(e)};
103
109
  foreach($site_options as $name => $value) {
104
110
  update_option($name, $value);
105
111
  }
106
112
  echo "Success";
107
- `,r=await s.run({code:t});return be(r),{code:t,result:r}},$e=async(s,{meta:e,userId:t})=>{const r=`<?php
113
+ `,s=await r.run({code:t});return ve(s),{code:t,result:s}},be=async(r,{meta:e,userId:t})=>{const s=`<?php
108
114
  include 'wordpress/wp-load.php';
109
115
  $meta = ${$(e)};
110
116
  foreach($meta as $name => $value) {
111
117
  update_user_meta(${$(t)}, $name, $value);
112
118
  }
113
119
  echo "Success";
114
- `,i=await s.run({code:r});return be(i),{code:r,result:i}};async function be(s){if(s.text!=="Success")throw console.log(s),new Error(`Failed to run code: ${s.text} ${s.errors}`)}const Oe=Object.freeze(Object.defineProperty({__proto__:null,activatePlugin:x,activateTheme:F,applyWordPressPatches:X,cp:ie,defineSiteUrl:le,defineWpConfigConsts:C,importFile:de,installPlugin:we,installTheme:ge,login:ye,mkdir:oe,mv:ne,replaceSite:pe,request:re,rm:ae,rmdir:ce,runPHP:ee,runPHPWithOptions:te,runWpInstallationWizard:Pe,setPhpIniEntry:se,setSiteOptions:_e,unzip:v,updateUserMeta:$e,writeFile:k,zipEntireSite:ue},Symbol.toStringTag,{value:"Module"})),Ne=5*1024*1024;function Le(s,e){const t=s.headers.get("content-length")||"",r=parseInt(t,10)||Ne;function i(n,o){e(new CustomEvent("progress",{detail:{loaded:n,total:o}}))}return new Response(new ReadableStream({async start(n){if(!s.body){n.close();return}const o=s.body.getReader();let a=0;for(;;)try{const{done:l,value:c}=await o.read();if(c&&(a+=c.byteLength),l){i(a,a),n.close();break}else i(a,r),n.enqueue(c)}catch(l){console.error({e:l}),n.error(l);break}}}),{status:s.status,statusText:s.statusText,headers:s.headers})}const S=1e-5;class U extends EventTarget{constructor({weight:e=1,caption:t="",fillTime:r=4}={}){super(),this._selfWeight=1,this._selfDone=!1,this._selfProgress=0,this._selfCaption="",this._isFilling=!1,this._subTrackers=[],this._weight=e,this._selfCaption=t,this._fillTime=r}stage(e,t=""){if(e||(e=this._selfWeight),this._selfWeight-e<-S)throw new Error(`Cannot add a stage with weight ${e} as the total weight of registered stages would exceed 1.`);this._selfWeight-=e;const r=new U({caption:t,weight:e,fillTime:this._fillTime});return this._subTrackers.push(r),r.addEventListener("progress",()=>this.notifyProgress()),r.addEventListener("done",()=>{this.done&&this.notifyDone()}),r}fillSlowly({stopBeforeFinishing:e=!0}={}){if(this._isFilling)return;this._isFilling=!0;const t=100,r=this._fillTime/t;this._fillInterval=setInterval(()=>{this.set(this._selfProgress+1),e&&this._selfProgress>=99&&clearInterval(this._fillInterval)},r)}set(e){this._selfProgress=Math.min(e,100),this.notifyProgress(),this._selfProgress+S>=100&&this.finish()}finish(){this._fillInterval&&clearInterval(this._fillInterval),this._selfDone=!0,this._selfProgress=100,this._isFilling=!1,this._fillInterval=void 0,this.notifyProgress(),this.notifyDone()}get caption(){for(let e=this._subTrackers.length-1;e>=0;e--)if(!this._subTrackers[e].done){const t=this._subTrackers[e].caption;if(t)return t}return this._selfCaption}setCaption(e){this._selfCaption=e,this.notifyProgress()}get done(){return this.progress+S>=100}get progress(){if(this._selfDone)return 100;const e=this._subTrackers.reduce((t,r)=>t+r.progress*r.weight,this._selfProgress*this._selfWeight);return Math.round(e*1e4)/1e4}get weight(){return this._weight}get observer(){return this._progressObserver||(this._progressObserver=e=>{this.set(e)}),this._progressObserver}get loadingListener(){return this._loadingListener||(this._loadingListener=e=>{this.set(e.detail.loaded/e.detail.total*100)}),this._loadingListener}pipe(e){e.setProgress({progress:this.progress,caption:this.caption}),this.addEventListener("progress",t=>{e.setProgress({progress:t.detail.progress,caption:t.detail.caption})}),this.addEventListener("done",()=>{e.setLoaded()})}addEventListener(e,t){super.addEventListener(e,t)}removeEventListener(e,t){super.removeEventListener(e,t)}notifyProgress(){const e=this;this.dispatchEvent(new CustomEvent("progress",{detail:{get progress(){return e.progress},get caption(){return e.caption}}}))}notifyDone(){this.dispatchEvent(new CustomEvent("done"))}}const M=Symbol("error"),D=Symbol("message");class O extends Event{constructor(e,t={}){super(e),this[M]=t.error===void 0?null:t.error,this[D]=t.message===void 0?"":t.message}get error(){return this[M]}get message(){return this[D]}}Object.defineProperty(O.prototype,"error",{enumerable:!0});Object.defineProperty(O.prototype,"message",{enumerable:!0});const He=typeof globalThis.ErrorEvent=="function"?globalThis.ErrorEvent:O;class We extends EventTarget{constructor(){super(...arguments),this.listenersCount=0}addEventListener(e,t){++this.listenersCount,super.addEventListener(e,t)}removeEventListener(e,t){--this.listenersCount,super.removeEventListener(e,t)}hasListeners(){return this.listenersCount>0}}function Ie(s){s.asm={...s.asm};const e=new We;for(const t in s.asm)if(typeof s.asm[t]=="function"){const r=s.asm[t];s.asm[t]=function(...i){try{return r(...i)}catch(n){if(!(n instanceof Error))throw n;if("exitCode"in n&&n?.exitCode===0)return;const o=qe(n,s.lastAsyncifyStackSource?.stack);if(s.lastAsyncifyStackSource&&(n.cause=s.lastAsyncifyStackSource),!e.hasListeners())throw Be(o),n;e.dispatchEvent(new He("error",{error:n,message:o}))}}}return e}let R=[];function ze(){return R}function qe(s,e){if(s.message==="unreachable"){let t=Me;e||(t+=`
120
+ `,i=await r.run({code:s});return ve(i),{code:s,result:i}};async function ve(r){if(r.text!=="Success")throw console.log(r),new Error(`Failed to run code: ${r.text} ${r.errors}`)}const Oe=Object.freeze(Object.defineProperty({__proto__:null,activatePlugin:F,activateTheme:C,applyWordPressPatches:ee,cp:ne,defineSiteUrl:he,defineWpConfigConsts:E,importFile:fe,installPlugin:ge,installTheme:ye,login:Pe,mkdir:ae,mv:oe,replaceSite:de,request:ie,rm:ce,rmdir:le,runPHP:te,runPHPWithOptions:re,runWpInstallationWizard:_e,setPhpIniEntry:se,setSiteOptions:$e,unzip:S,updateUserMeta:be,writeFile:A,zipEntireSite:pe},Symbol.toStringTag,{value:"Module"})),Le=5*1024*1024;function He(r,e){const t=r.headers.get("content-length")||"",s=parseInt(t,10)||Le;function i(n,o){e(new CustomEvent("progress",{detail:{loaded:n,total:o}}))}return new Response(new ReadableStream({async start(n){if(!r.body){n.close();return}const o=r.body.getReader();let a=0;for(;;)try{const{done:l,value:c}=await o.read();if(c&&(a+=c.byteLength),l){i(a,a),n.close();break}else i(a,s),n.enqueue(c)}catch(l){console.error({e:l}),n.error(l);break}}}),{status:r.status,statusText:r.statusText,headers:r.headers})}const R=1e-5;class N extends EventTarget{constructor({weight:e=1,caption:t="",fillTime:s=4}={}){super(),this._selfWeight=1,this._selfDone=!1,this._selfProgress=0,this._selfCaption="",this._isFilling=!1,this._subTrackers=[],this._weight=e,this._selfCaption=t,this._fillTime=s}stage(e,t=""){if(e||(e=this._selfWeight),this._selfWeight-e<-R)throw new Error(`Cannot add a stage with weight ${e} as the total weight of registered stages would exceed 1.`);this._selfWeight-=e;const s=new N({caption:t,weight:e,fillTime:this._fillTime});return this._subTrackers.push(s),s.addEventListener("progress",()=>this.notifyProgress()),s.addEventListener("done",()=>{this.done&&this.notifyDone()}),s}fillSlowly({stopBeforeFinishing:e=!0}={}){if(this._isFilling)return;this._isFilling=!0;const t=100,s=this._fillTime/t;this._fillInterval=setInterval(()=>{this.set(this._selfProgress+1),e&&this._selfProgress>=99&&clearInterval(this._fillInterval)},s)}set(e){this._selfProgress=Math.min(e,100),this.notifyProgress(),this._selfProgress+R>=100&&this.finish()}finish(){this._fillInterval&&clearInterval(this._fillInterval),this._selfDone=!0,this._selfProgress=100,this._isFilling=!1,this._fillInterval=void 0,this.notifyProgress(),this.notifyDone()}get caption(){for(let e=this._subTrackers.length-1;e>=0;e--)if(!this._subTrackers[e].done){const t=this._subTrackers[e].caption;if(t)return t}return this._selfCaption}setCaption(e){this._selfCaption=e,this.notifyProgress()}get done(){return this.progress+R>=100}get progress(){if(this._selfDone)return 100;const e=this._subTrackers.reduce((t,s)=>t+s.progress*s.weight,this._selfProgress*this._selfWeight);return Math.round(e*1e4)/1e4}get weight(){return this._weight}get observer(){return this._progressObserver||(this._progressObserver=e=>{this.set(e)}),this._progressObserver}get loadingListener(){return this._loadingListener||(this._loadingListener=e=>{this.set(e.detail.loaded/e.detail.total*100)}),this._loadingListener}pipe(e){e.setProgress({progress:this.progress,caption:this.caption}),this.addEventListener("progress",t=>{e.setProgress({progress:t.detail.progress,caption:t.detail.caption})}),this.addEventListener("done",()=>{e.setLoaded()})}addEventListener(e,t){super.addEventListener(e,t)}removeEventListener(e,t){super.removeEventListener(e,t)}notifyProgress(){const e=this;this.dispatchEvent(new CustomEvent("progress",{detail:{get progress(){return e.progress},get caption(){return e.caption}}}))}notifyDone(){this.dispatchEvent(new CustomEvent("done"))}}const q=Symbol("error"),B=Symbol("message");class O extends Event{constructor(e,t={}){super(e),this[q]=t.error===void 0?null:t.error,this[B]=t.message===void 0?"":t.message}get error(){return this[q]}get message(){return this[B]}}Object.defineProperty(O.prototype,"error",{enumerable:!0});Object.defineProperty(O.prototype,"message",{enumerable:!0});const Ie=typeof globalThis.ErrorEvent=="function"?globalThis.ErrorEvent:O;class We extends EventTarget{constructor(){super(...arguments),this.listenersCount=0}addEventListener(e,t){++this.listenersCount,super.addEventListener(e,t)}removeEventListener(e,t){--this.listenersCount,super.removeEventListener(e,t)}hasListeners(){return this.listenersCount>0}}function Me(r){r.asm={...r.asm};const e=new We;for(const t in r.asm)if(typeof r.asm[t]=="function"){const s=r.asm[t];r.asm[t]=function(...i){try{return s(...i)}catch(n){if(!(n instanceof Error))throw n;if("exitCode"in n&&n?.exitCode===0)return;const o=De(n,r.lastAsyncifyStackSource?.stack);if(r.lastAsyncifyStackSource&&(n.cause=r.lastAsyncifyStackSource),!e.hasListeners())throw je(o),n;e.dispatchEvent(new Ie("error",{error:n,message:o}))}}}return e}let x=[];function ze(){return x}function De(r,e){if(r.message==="unreachable"){let t=qe;e||(t+=`
115
121
 
116
122
  This stack trace is lacking. For a better one initialize
117
123
  the PHP runtime with { debug: true }, e.g. PHPNode.load('8.1', { debug: true }).
118
124
 
119
- `),R=je(e||s.stack||"");for(const r of R)t+=` * ${r}
120
- `;return t}return s.message}const Me=`
125
+ `),x=Ge(e||r.stack||"");for(const s of x)t+=` * ${s}
126
+ `;return t}return r.message}const qe=`
121
127
  "unreachable" WASM instruction executed.
122
128
 
123
129
  The typical reason is a PHP function missing from the ASYNCIFY_ONLY
@@ -141,13 +147,13 @@ the Dockerfile, you'll need to trigger this error again with long stack
141
147
  traces enabled. In node.js, you can do it using the --stack-trace-limit=100
142
148
  CLI option:
143
149
 
144
- `,B="\x1B[41m",De="\x1B[1m",j="\x1B[0m",G="\x1B[K";let V=!1;function Be(s){if(!V){V=!0,console.log(`${B}
145
- ${G}
146
- ${De} WASM ERROR${j}${B}`);for(const e of s.split(`
147
- `))console.log(`${G} ${e} `);console.log(`${j}`)}}function je(s){try{const e=s.split(`
148
- `).slice(1).map(t=>{const r=t.trim().substring(3).split(" ");return{fn:r.length>=2?r[0]:"<unknown>",isWasm:t.includes("wasm://")}}).filter(({fn:t,isWasm:r})=>r&&!t.startsWith("dynCall_")&&!t.startsWith("invoke_")).map(({fn:t})=>t);return Array.from(new Set(e))}catch{return[]}}class _{constructor(e,t,r,i="",n=0){this.httpStatusCode=e,this.headers=t,this.bytes=r,this.exitCode=n,this.errors=i}static fromRawData(e){return new _(e.httpStatusCode,e.headers,e.bytes,e.errors,e.exitCode)}toRawData(){return{headers:this.headers,bytes:this.bytes,errors:this.errors,exitCode:this.exitCode,httpStatusCode:this.httpStatusCode}}get json(){return JSON.parse(this.text)}get text(){return new TextDecoder().decode(this.bytes)}}const ve=["8.2","8.1","8.0","7.4","7.3","7.2","7.1","7.0","5.6"],Ge=ve[0];class Ve{#e;#t;constructor(e,t={}){this.requestHandler=e,this.#e={},this.#t={handleRedirects:!1,maxRedirects:4,...t}}async request(e,t=0){const r=await this.requestHandler.request({...e,headers:{...e.headers,cookie:this.#s()}});if(r.headers["set-cookie"]&&this.#r(r.headers["set-cookie"]),this.#t.handleRedirects&&r.headers.location&&t<this.#t.maxRedirects){const i=new URL(r.headers.location[0],this.requestHandler.absoluteUrl);return this.request({url:i.toString(),method:"GET",headers:{}},t+1)}return r}pathToInternalUrl(e){return this.requestHandler.pathToInternalUrl(e)}internalUrlToPath(e){return this.requestHandler.internalUrlToPath(e)}get absoluteUrl(){return this.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.documentRoot}#r(e){for(const t of e)try{if(!t.includes("="))continue;const r=t.indexOf("="),i=t.substring(0,r),n=t.substring(r+1).split(";")[0];this.#e[i]=n}catch(r){console.error(r)}}#s(){const e=[];for(const t in this.#e)e.push(`${t}=${this.#e[t]}`);return e.join("; ")}}const Ye="http://example.com";function Y(s){return s.toString().substring(s.origin.length)}function J(s,e){return!e||!s.startsWith(e)?s:s.substring(e.length)}function Je(s,e){return!e||s.startsWith(e)?s:e+s}class Ke{#e;#t;#r;#s;#n;#i;#o;#a;#c;constructor(e,t={}){this.#a=new he({concurrency:1});const{documentRoot:r="/www/",absoluteUrl:i=typeof location=="object"?location?.href:"",isStaticFilePath:n=()=>!1}=t;this.php=e,this.#e=r,this.#c=n;const o=new URL(i);this.#r=o.hostname,this.#s=o.port?Number(o.port):o.protocol==="https:"?443:80,this.#t=(o.protocol||"").replace(":","");const a=this.#s!==443&&this.#s!==80;this.#n=[this.#r,a?`:${this.#s}`:""].join(""),this.#i=o.pathname.replace(/\/+$/,""),this.#o=[`${this.#t}://`,this.#n,this.#i].join("")}pathToInternalUrl(e){return`${this.absoluteUrl}${e}`}internalUrlToPath(e){const t=new URL(e);return t.pathname.startsWith(this.#i)&&(t.pathname=t.pathname.slice(this.#i.length)),Y(t)}get isRequestRunning(){return this.#a.running>0}get absoluteUrl(){return this.#o}get documentRoot(){return this.#e}async request(e){const t=e.url.startsWith("http://")||e.url.startsWith("https://"),r=new URL(e.url,t?void 0:Ye),i=J(r.pathname,this.#i);return this.#c(i)?this.#l(i):await this.#h(e,r)}#l(e){const t=`${this.#e}${e}`;if(!this.php.fileExists(t))return new _(404,{},new TextEncoder().encode("404 File not found"));const r=this.php.readFileAsBuffer(t);return new _(200,{"content-length":[`${r.byteLength}`],"content-type":[Qe(t)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},r)}async#h(e,t){const r=await this.#a.acquire();try{this.php.addServerGlobalEntry("DOCUMENT_ROOT",this.#e),this.php.addServerGlobalEntry("HTTPS",this.#o.startsWith("https://")?"on":"");let i="GET";const n={host:this.#n,...Ee(e.headers||{})},o=[];if(e.files&&Object.keys(e.files).length){i="POST";for(const c in e.files){const u=e.files[c];o.push({key:c,name:u.name,type:u.type,data:new Uint8Array(await u.arrayBuffer())})}n["content-type"]?.startsWith("multipart/form-data")&&(e.formData=Ze(e.body||""),n["content-type"]="application/x-www-form-urlencoded",delete e.body)}let a;e.formData!==void 0?(i="POST",n["content-type"]=n["content-type"]||"application/x-www-form-urlencoded",a=new URLSearchParams(e.formData).toString()):a=e.body;let l;try{l=this.#u(t.pathname)}catch{return new _(404,{},new TextEncoder().encode("404 File not found"))}return await this.php.run({relativeUri:Je(Y(t),this.#i),protocol:this.#t,method:e.method||i,body:a,fileInfos:o,scriptPath:l,headers:n})}finally{r()}}#u(e){let t=J(e,this.#i);t.includes(".php")?t=t.split(".php")[0]+".php":(t.endsWith("/")||(t+="/"),t.endsWith("index.php")||(t+="index.php"));const r=`${this.#e}${t}`;if(this.php.fileExists(r))return r;if(!this.php.fileExists(`${this.#e}/index.php`))throw new Error(`File not found: ${r}`);return`${this.#e}/index.php`}}function Ze(s){const e={},t=s.match(/--(.*)\r\n/);if(!t)return e;const r=t[1],i=s.split(`--${r}`);return i.shift(),i.pop(),i.forEach(n=>{const o=n.indexOf(`\r
150
+ `,j="\x1B[41m",Be="\x1B[1m",G="\x1B[0m",V="\x1B[K";let Y=!1;function je(r){if(!Y){Y=!0,console.log(`${j}
151
+ ${V}
152
+ ${Be} WASM ERROR${G}${j}`);for(const e of r.split(`
153
+ `))console.log(`${V} ${e} `);console.log(`${G}`)}}function Ge(r){try{const e=r.split(`
154
+ `).slice(1).map(t=>{const s=t.trim().substring(3).split(" ");return{fn:s.length>=2?s[0]:"<unknown>",isWasm:t.includes("wasm://")}}).filter(({fn:t,isWasm:s})=>s&&!t.startsWith("dynCall_")&&!t.startsWith("invoke_")).map(({fn:t})=>t);return Array.from(new Set(e))}catch{return[]}}class _{constructor(e,t,s,i="",n=0){this.httpStatusCode=e,this.headers=t,this.bytes=s,this.exitCode=n,this.errors=i}static fromRawData(e){return new _(e.httpStatusCode,e.headers,e.bytes,e.errors,e.exitCode)}toRawData(){return{headers:this.headers,bytes:this.bytes,errors:this.errors,exitCode:this.exitCode,httpStatusCode:this.httpStatusCode}}get json(){return JSON.parse(this.text)}get text(){return new TextDecoder().decode(this.bytes)}}const Ee=["8.2","8.1","8.0","7.4","7.3","7.2","7.1","7.0","5.6"],Ve=Ee[0];class Ye{#e;#t;constructor(e,t={}){this.requestHandler=e,this.#e={},this.#t={handleRedirects:!1,maxRedirects:4,...t}}async request(e,t=0){const s=await this.requestHandler.request({...e,headers:{...e.headers,cookie:this.#r()}});if(s.headers["set-cookie"]&&this.#s(s.headers["set-cookie"]),this.#t.handleRedirects&&s.headers.location&&t<this.#t.maxRedirects){const i=new URL(s.headers.location[0],this.requestHandler.absoluteUrl);return this.request({url:i.toString(),method:"GET",headers:{}},t+1)}return s}pathToInternalUrl(e){return this.requestHandler.pathToInternalUrl(e)}internalUrlToPath(e){return this.requestHandler.internalUrlToPath(e)}get absoluteUrl(){return this.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.documentRoot}#s(e){for(const t of e)try{if(!t.includes("="))continue;const s=t.indexOf("="),i=t.substring(0,s),n=t.substring(s+1).split(";")[0];this.#e[i]=n}catch(s){console.error(s)}}#r(){const e=[];for(const t in this.#e)e.push(`${t}=${this.#e[t]}`);return e.join("; ")}}const Ke="http://example.com";function K(r){return r.toString().substring(r.origin.length)}function J(r,e){return!e||!r.startsWith(e)?r:r.substring(e.length)}function Je(r,e){return!e||r.startsWith(e)?r:e+r}class Ze{#e;#t;#s;#r;#n;#i;#o;#a;#c;constructor(e,t={}){this.#a=new ue({concurrency:1});const{documentRoot:s="/www/",absoluteUrl:i=typeof location=="object"?location?.href:"",isStaticFilePath:n=()=>!1}=t;this.php=e,this.#e=s,this.#c=n;const o=new URL(i);this.#s=o.hostname,this.#r=o.port?Number(o.port):o.protocol==="https:"?443:80,this.#t=(o.protocol||"").replace(":","");const a=this.#r!==443&&this.#r!==80;this.#n=[this.#s,a?`:${this.#r}`:""].join(""),this.#i=o.pathname.replace(/\/+$/,""),this.#o=[`${this.#t}://`,this.#n,this.#i].join("")}pathToInternalUrl(e){return`${this.absoluteUrl}${e}`}internalUrlToPath(e){const t=new URL(e);return t.pathname.startsWith(this.#i)&&(t.pathname=t.pathname.slice(this.#i.length)),K(t)}get isRequestRunning(){return this.#a.running>0}get absoluteUrl(){return this.#o}get documentRoot(){return this.#e}async request(e){const t=e.url.startsWith("http://")||e.url.startsWith("https://"),s=new URL(e.url,t?void 0:Ke),i=J(s.pathname,this.#i);return this.#c(i)?this.#l(i):await this.#h(e,s)}#l(e){const t=`${this.#e}${e}`;if(!this.php.fileExists(t))return new _(404,{},new TextEncoder().encode("404 File not found"));const s=this.php.readFileAsBuffer(t);return new _(200,{"content-length":[`${s.byteLength}`],"content-type":[Xe(t)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},s)}async#h(e,t){const s=await this.#a.acquire();try{this.php.addServerGlobalEntry("DOCUMENT_ROOT",this.#e),this.php.addServerGlobalEntry("HTTPS",this.#o.startsWith("https://")?"on":"");let i="GET";const n={host:this.#n,...Se(e.headers||{})},o=[];if(e.files&&Object.keys(e.files).length){i="POST";for(const c in e.files){const u=e.files[c];o.push({key:c,name:u.name,type:u.type,data:new Uint8Array(await u.arrayBuffer())})}n["content-type"]?.startsWith("multipart/form-data")&&(e.formData=Qe(e.body||""),n["content-type"]="application/x-www-form-urlencoded",delete e.body)}let a;e.formData!==void 0?(i="POST",n["content-type"]=n["content-type"]||"application/x-www-form-urlencoded",a=new URLSearchParams(e.formData).toString()):a=e.body;let l;try{l=this.#u(t.pathname)}catch{return new _(404,{},new TextEncoder().encode("404 File not found"))}return await this.php.run({relativeUri:Je(K(t),this.#i),protocol:this.#t,method:e.method||i,body:a,fileInfos:o,scriptPath:l,headers:n})}finally{s()}}#u(e){let t=J(e,this.#i);t.includes(".php")?t=t.split(".php")[0]+".php":(t.endsWith("/")||(t+="/"),t.endsWith("index.php")||(t+="index.php"));const s=`${this.#e}${t}`;if(this.php.fileExists(s))return s;if(!this.php.fileExists(`${this.#e}/index.php`))throw new Error(`File not found: ${s}`);return`${this.#e}/index.php`}}function Qe(r){const e={},t=r.match(/--(.*)\r\n/);if(!t)return e;const s=t[1],i=r.split(`--${s}`);return i.shift(),i.pop(),i.forEach(n=>{const o=n.indexOf(`\r
149
155
  \r
150
- `),a=n.substring(0,o).trim(),l=n.substring(o+4).trim(),c=a.match(/name="([^"]+)"/);if(c){const u=c[1];e[u]=l}}),e}function Qe(s){switch(s.split(".").pop()){case"css":return"text/css";case"js":return"application/javascript";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"gif":return"image/gif";case"svg":return"image/svg+xml";case"woff":return"font/woff";case"woff2":return"font/woff2";case"ttf":return"font/ttf";case"otf":return"font/otf";case"eot":return"font/eot";case"ico":return"image/x-icon";case"html":return"text/html";case"json":return"application/json";case"xml":return"application/xml";case"txt":case"md":return"text/plain";default:return"application-octet-stream"}}const K={0:"No error occurred. System call completed successfully.",1:"Argument list too long.",2:"Permission denied.",3:"Address in use.",4:"Address not available.",5:"Address family not supported.",6:"Resource unavailable, or operation would block.",7:"Connection already in progress.",8:"Bad file descriptor.",9:"Bad message.",10:"Device or resource busy.",11:"Operation canceled.",12:"No child processes.",13:"Connection aborted.",14:"Connection refused.",15:"Connection reset.",16:"Resource deadlock would occur.",17:"Destination address required.",18:"Mathematics argument out of domain of function.",19:"Reserved.",20:"File exists.",21:"Bad address.",22:"File too large.",23:"Host is unreachable.",24:"Identifier removed.",25:"Illegal byte sequence.",26:"Operation in progress.",27:"Interrupted function.",28:"Invalid argument.",29:"I/O error.",30:"Socket is connected.",31:"There is a directory under that path.",32:"Too many levels of symbolic links.",33:"File descriptor value too large.",34:"Too many links.",35:"Message too large.",36:"Reserved.",37:"Filename too long.",38:"Network is down.",39:"Connection aborted by network.",40:"Network unreachable.",41:"Too many files open in system.",42:"No buffer space available.",43:"No such device.",44:"There is no such file or directory OR the parent directory does not exist.",45:"Executable file format error.",46:"No locks available.",47:"Reserved.",48:"Not enough space.",49:"No message of the desired type.",50:"Protocol not available.",51:"No space left on device.",52:"Function not supported.",53:"The socket is not connected.",54:"Not a directory or a symbolic link to a directory.",55:"Directory not empty.",56:"State not recoverable.",57:"Not a socket.",58:"Not supported, or operation not supported on socket.",59:"Inappropriate I/O control operation.",60:"No such device or address.",61:"Value too large to be stored in data type.",62:"Previous owner died.",63:"Operation not permitted.",64:"Broken pipe.",65:"Protocol error.",66:"Protocol not supported.",67:"Protocol wrong type for socket.",68:"Result too large.",69:"Read-only file system.",70:"Invalid seek.",71:"No such process.",72:"Reserved.",73:"Connection timed out.",74:"Text file busy.",75:"Cross-device link.",76:"Extension: Capabilities insufficient."};function f(s=""){return function(t,r,i){const n=i.value;i.value=function(...o){try{return n.apply(this,o)}catch(a){const l=typeof a=="object"?a?.errno:null;if(l in K){const c=K[l],u=typeof o[0]=="string"?o[0]:null,d=u!==null?s.replaceAll("{path}",u):s;throw new Error(`${d}: ${c}`,{cause:a})}throw a}}}}const Xe=[];function et(s){return Xe[s]}(function(){return typeof process<"u"&&process.release?.name==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"})();var tt=Object.defineProperty,st=Object.getOwnPropertyDescriptor,m=(s,e,t,r)=>{for(var i=r>1?void 0:r?st(e,t):e,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(e,t,i):o(i))||i);return r&&i&&tt(e,t,i),i};const p="string",y="number",h=Symbol("__private__dont__use");class w{constructor(e,t){this.#e=[],this.#t=!1,this.#r=null,this.#s={},e!==void 0&&this.initializeRuntime(e),t&&(this.requestHandler=new Ve(new Ke(this,t)))}#e;#t;#r;#s;get absoluteUrl(){return this.requestHandler.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.requestHandler.documentRoot}pathToInternalUrl(e){return this.requestHandler.requestHandler.pathToInternalUrl(e)}internalUrlToPath(e){return this.requestHandler.requestHandler.internalUrlToPath(e)}initializeRuntime(e){if(this[h])throw new Error("PHP runtime already initialized.");const t=et(e);if(!t)throw new Error("Invalid PHP runtime id.");this[h]=t,this.#r=Ie(t)}setPhpIniPath(e){if(this.#t)throw new Error("Cannot set PHP ini path after calling run().");this[h].ccall("wasm_set_phpini_path",null,["string"],[e])}setPhpIniEntry(e,t){if(this.#t)throw new Error("Cannot set PHP ini entries after calling run().");this.#e.push([e,t])}chdir(e){this[h].FS.chdir(e)}async request(e,t){if(!this.requestHandler)throw new Error("No request handler available.");return this.requestHandler.request(e,t)}async run(e){this.#t||(this.#n(),this.#t=!0),this.#u(e.scriptPath||""),this.#o(e.relativeUri||""),this.#c(e.method||"GET");const{host:t,...r}={host:"example.com:443",...Ee(e.headers||{})};if(this.#a(t,e.protocol||"http"),this.#l(r),e.body&&this.#h(e.body),e.fileInfos)for(const i of e.fileInfos)this.#d(i);return e.code&&this.#f(" ?>"+e.code),this.#p(),await this.#m()}#n(){if(this.#e.length>0){const e=this.#e.map(([t,r])=>`${t}=${r}`).join(`
156
+ `),a=n.substring(0,o).trim(),l=n.substring(o+4).trim(),c=a.match(/name="([^"]+)"/);if(c){const u=c[1];e[u]=l}}),e}function Xe(r){switch(r.split(".").pop()){case"css":return"text/css";case"js":return"application/javascript";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"gif":return"image/gif";case"svg":return"image/svg+xml";case"woff":return"font/woff";case"woff2":return"font/woff2";case"ttf":return"font/ttf";case"otf":return"font/otf";case"eot":return"font/eot";case"ico":return"image/x-icon";case"html":return"text/html";case"json":return"application/json";case"xml":return"application/xml";case"txt":case"md":return"text/plain";default:return"application-octet-stream"}}const Z={0:"No error occurred. System call completed successfully.",1:"Argument list too long.",2:"Permission denied.",3:"Address in use.",4:"Address not available.",5:"Address family not supported.",6:"Resource unavailable, or operation would block.",7:"Connection already in progress.",8:"Bad file descriptor.",9:"Bad message.",10:"Device or resource busy.",11:"Operation canceled.",12:"No child processes.",13:"Connection aborted.",14:"Connection refused.",15:"Connection reset.",16:"Resource deadlock would occur.",17:"Destination address required.",18:"Mathematics argument out of domain of function.",19:"Reserved.",20:"File exists.",21:"Bad address.",22:"File too large.",23:"Host is unreachable.",24:"Identifier removed.",25:"Illegal byte sequence.",26:"Operation in progress.",27:"Interrupted function.",28:"Invalid argument.",29:"I/O error.",30:"Socket is connected.",31:"There is a directory under that path.",32:"Too many levels of symbolic links.",33:"File descriptor value too large.",34:"Too many links.",35:"Message too large.",36:"Reserved.",37:"Filename too long.",38:"Network is down.",39:"Connection aborted by network.",40:"Network unreachable.",41:"Too many files open in system.",42:"No buffer space available.",43:"No such device.",44:"There is no such file or directory OR the parent directory does not exist.",45:"Executable file format error.",46:"No locks available.",47:"Reserved.",48:"Not enough space.",49:"No message of the desired type.",50:"Protocol not available.",51:"No space left on device.",52:"Function not supported.",53:"The socket is not connected.",54:"Not a directory or a symbolic link to a directory.",55:"Directory not empty.",56:"State not recoverable.",57:"Not a socket.",58:"Not supported, or operation not supported on socket.",59:"Inappropriate I/O control operation.",60:"No such device or address.",61:"Value too large to be stored in data type.",62:"Previous owner died.",63:"Operation not permitted.",64:"Broken pipe.",65:"Protocol error.",66:"Protocol not supported.",67:"Protocol wrong type for socket.",68:"Result too large.",69:"Read-only file system.",70:"Invalid seek.",71:"No such process.",72:"Reserved.",73:"Connection timed out.",74:"Text file busy.",75:"Cross-device link.",76:"Extension: Capabilities insufficient."};function f(r=""){return function(t,s,i){const n=i.value;i.value=function(...o){try{return n.apply(this,o)}catch(a){const l=typeof a=="object"?a?.errno:null;if(l in Z){const c=Z[l],u=typeof o[0]=="string"?o[0]:null,d=u!==null?r.replaceAll("{path}",u):r;throw new Error(`${d}: ${c}`,{cause:a})}throw a}}}}const et=[];function tt(r){return et[r]}(function(){return typeof process<"u"&&process.release?.name==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"})();var rt=Object.defineProperty,st=Object.getOwnPropertyDescriptor,m=(r,e,t,s)=>{for(var i=s>1?void 0:s?st(e,t):e,n=r.length-1,o;n>=0;n--)(o=r[n])&&(i=(s?o(e,t,i):o(i))||i);return s&&i&&rt(e,t,i),i};const p="string",P="number",h=Symbol("__private__dont__use");class w{constructor(e,t){this.#e=[],this.#t=!1,this.#s=null,this.#r={},this.#n=[],e!==void 0&&this.initializeRuntime(e),t&&(this.requestHandler=new Ye(new Ze(this,t)))}#e;#t;#s;#r;#n;async onMessage(e){this.#n.push(e)}get absoluteUrl(){return this.requestHandler.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.requestHandler.documentRoot}pathToInternalUrl(e){return this.requestHandler.requestHandler.pathToInternalUrl(e)}internalUrlToPath(e){return this.requestHandler.requestHandler.internalUrlToPath(e)}initializeRuntime(e){if(this[h])throw new Error("PHP runtime already initialized.");const t=tt(e);if(!t)throw new Error("Invalid PHP runtime id.");this[h]=t,t.onMessage=s=>{for(const i of this.#n)i(s)},this.#s=Me(t)}setPhpIniPath(e){if(this.#t)throw new Error("Cannot set PHP ini path after calling run().");this[h].ccall("wasm_set_phpini_path",null,["string"],[e])}setPhpIniEntry(e,t){if(this.#t)throw new Error("Cannot set PHP ini entries after calling run().");this.#e.push([e,t])}chdir(e){this[h].FS.chdir(e)}async request(e,t){if(!this.requestHandler)throw new Error("No request handler available.");return this.requestHandler.request(e,t)}async run(e){this.#t||(this.#i(),this.#t=!0),this.#p(e.scriptPath||""),this.#a(e.relativeUri||""),this.#l(e.method||"GET");const{host:t,...s}={host:"example.com:443",...Se(e.headers||{})};if(this.#c(t,e.protocol||"http"),this.#h(s),e.body&&this.#u(e.body),e.fileInfos)for(const i of e.fileInfos)this.#f(i);return e.code&&this.#m(" ?>"+e.code),this.#d(),await this.#w()}#i(){if(this.#e.length>0){const e=this.#e.map(([t,s])=>`${t}=${s}`).join(`
151
157
  `)+`
152
158
 
153
- `;this[h].ccall("wasm_set_phpini_entries",null,[p],[e])}this[h].ccall("php_wasm_init",null,[],[])}#i(){const e="/tmp/headers.json";if(!this.fileExists(e))throw new Error("SAPI Error: Could not find response headers file.");const t=JSON.parse(this.readFileAsText(e)),r={};for(const i of t.headers){if(!i.includes(": "))continue;const n=i.indexOf(": "),o=i.substring(0,n).toLowerCase(),a=i.substring(n+2);o in r||(r[o]=[]),r[o].push(a)}return{headers:r,httpStatusCode:t.status}}#o(e){if(this[h].ccall("wasm_set_request_uri",null,[p],[e]),e.includes("?")){const t=e.substring(e.indexOf("?")+1);this[h].ccall("wasm_set_query_string",null,[p],[t])}}#a(e,t){this[h].ccall("wasm_set_request_host",null,[p],[e]);let r;try{r=parseInt(new URL(e).port,10)}catch{}(!r||isNaN(r)||r===80)&&(r=t==="https"?443:80),this[h].ccall("wasm_set_request_port",null,[y],[r]),(t==="https"||!t&&r===443)&&this.addServerGlobalEntry("HTTPS","on")}#c(e){this[h].ccall("wasm_set_request_method",null,[p],[e])}#l(e){e.cookie&&this[h].ccall("wasm_set_cookies",null,[p],[e.cookie]),e["content-type"]&&this[h].ccall("wasm_set_content_type",null,[p],[e["content-type"]]),e["content-length"]&&this[h].ccall("wasm_set_content_length",null,[y],[parseInt(e["content-length"],10)]);for(const t in e){let r="HTTP_";["content-type","content-length"].includes(t.toLowerCase())&&(r=""),this.addServerGlobalEntry(`${r}${t.toUpperCase().replace(/-/g,"_")}`,e[t])}}#h(e){this[h].ccall("wasm_set_request_body",null,[p],[e]),this[h].ccall("wasm_set_content_length",null,[y],[new TextEncoder().encode(e).length])}#u(e){this[h].ccall("wasm_set_path_translated",null,[p],[e])}addServerGlobalEntry(e,t){this.#s[e]=t}#p(){for(const e in this.#s)this[h].ccall("wasm_add_SERVER_entry",null,[p,p],[e,this.#s[e]])}#d(e){const{key:t,name:r,type:i,data:n}=e,o=`/tmp/${Math.random().toFixed(20)}`;this.writeFile(o,n);const a=0;this[h].ccall("wasm_add_uploaded_file",null,[p,p,p,p,y,y],[t,r,i,o,a,n.byteLength])}#f(e){this[h].ccall("wasm_set_php_code",null,[p],[e])}async#m(){let e,t;try{e=await new Promise((n,o)=>{t=l=>{const c=new Error("Rethrown");c.cause=l.error,c.betterMessage=l.message,o(c)},this.#r?.addEventListener("error",t);const a=this[h].ccall("wasm_sapi_handle_request",y,[],[]);return a instanceof Promise?a.then(n,o):n(a)})}catch(n){for(const c in this)typeof this[c]=="function"&&(this[c]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});this.functionsMaybeMissingFromAsyncify=ze();const o=n,a="betterMessage"in o?o.betterMessage:o.message,l=new Error(a);throw l.cause=o,l}finally{this.#r?.removeEventListener("error",t),this.#s={}}const{headers:r,httpStatusCode:i}=this.#i();return new _(i,r,this.readFileAsBuffer("/tmp/stdout"),this.readFileAsText("/tmp/stderr"),e)}mkdir(e){this[h].FS.mkdirTree(e)}mkdirTree(e){this.mkdir(e)}readFileAsText(e){return new TextDecoder().decode(this.readFileAsBuffer(e))}readFileAsBuffer(e){return this[h].FS.readFile(e)}writeFile(e,t){this[h].FS.writeFile(e,t)}unlink(e){this[h].FS.unlink(e)}mv(e,t){this[h].FS.rename(e,t)}rmdir(e,t={recursive:!0}){t?.recursive&&this.listFiles(e).forEach(r=>{const i=`${e}/${r}`;this.isDir(i)?this.rmdir(i,t):this.unlink(i)}),this[h].FS.rmdir(e)}listFiles(e,t={prependPath:!1}){if(!this.fileExists(e))return[];try{const r=this[h].FS.readdir(e).filter(i=>i!=="."&&i!=="..");if(t.prependPath){const i=e.replace(/\/$/,"");return r.map(n=>`${i}/${n}`)}return r}catch(r){return console.error(r,{path:e}),[]}}isDir(e){return this.fileExists(e)?this[h].FS.isDir(this[h].FS.lookupPath(e).node.mode):!1}fileExists(e){try{return this[h].FS.lookupPath(e),!0}catch{return!1}}}m([f('Could not create directory "{path}"')],w.prototype,"mkdir",1);m([f('Could not create directory "{path}"')],w.prototype,"mkdirTree",1);m([f('Could not read "{path}"')],w.prototype,"readFileAsText",1);m([f('Could not read "{path}"')],w.prototype,"readFileAsBuffer",1);m([f('Could not write to "{path}"')],w.prototype,"writeFile",1);m([f('Could not unlink "{path}"')],w.prototype,"unlink",1);m([f('Could not move "{path}"')],w.prototype,"mv",1);m([f('Could not remove directory "{path}"')],w.prototype,"rmdir",1);m([f('Could not list files in "{path}"')],w.prototype,"listFiles",1);m([f('Could not stat "{path}"')],w.prototype,"isDir",1);m([f('Could not stat "{path}"')],w.prototype,"fileExists",1);function Ee(s){const e={};for(const t in s)e[t.toLowerCase()]=s[t];return e}const rt=["vfs","literal","wordpress.org/themes","wordpress.org/plugins","url"];function it(s){return s&&typeof s=="object"&&typeof s.resource=="string"&&rt.includes(s.resource)}class g{static create(e,{semaphore:t,progress:r}){let i;switch(e.resource){case"vfs":i=new nt(e,r);break;case"literal":i=new ot(e,r);break;case"wordpress.org/themes":i=new ht(e,r);break;case"wordpress.org/plugins":i=new ut(e,r);break;case"url":i=new ct(e,r);break;default:throw new Error(`Invalid resource: ${e}`)}return i=new pt(i),t&&(i=new dt(i,t)),i}setPlayground(e){this.playground=e}get isAsync(){return!1}}class nt extends g{constructor(e,t){super(),this.resource=e,this.progress=t}async resolve(){const e=await this.playground.readFileAsBuffer(this.resource.path);return this.progress?.set(100),new T([e],this.name)}get name(){return this.resource.path.split("/").pop()||""}}class ot extends g{constructor(e,t){super(),this.resource=e,this.progress=t}async resolve(){return this.progress?.set(100),new T([this.resource.contents],this.resource.name)}get name(){return this.resource.name}}class N extends g{constructor(e){super(),this.progress=e}async resolve(){this.progress?.setCaption(this.caption);const e=this.getURL();let t=await fetch(e);if(t=await Le(t,this.progress?.loadingListener??at),t.status!==200)throw new Error(`Could not download "${e}"`);return new T([await t.blob()],this.name)}get caption(){return`Downloading ${this.name}`}get name(){try{return new URL(this.getURL(),"http://example.com").pathname.split("/").pop()}catch{return this.getURL()}}get isAsync(){return!0}}const at=()=>{};class ct extends N{constructor(e,t){super(t),this.resource=e}getURL(){return this.resource.url}get caption(){return this.resource.caption??super.caption}}let L="https://playground.wordpress.net/plugin-proxy";function lt(s){L=s}class ht extends N{constructor(e,t){super(t),this.resource=e}get name(){return b(this.resource.slug)}getURL(){const e=Se(this.resource.slug);return`${L}?theme=`+e}}class ut extends N{constructor(e,t){super(t),this.resource=e}get name(){return b(this.resource.slug)}getURL(){const e=Se(this.resource.slug);return`${L}?plugin=`+e}}function Se(s){return!s||s.endsWith(".zip")?s:s+".latest-stable.zip"}class Re extends g{constructor(e){super(),this.resource=e}async resolve(){return this.resource.resolve()}async setPlayground(e){return this.resource.setPlayground(e)}get progress(){return this.resource.progress}set progress(e){this.resource.progress=e}get name(){return this.resource.name}get isAsync(){return this.resource.isAsync}}class pt extends Re{async resolve(){return this.promise||(this.promise=super.resolve()),this.promise}}class dt extends Re{constructor(e,t){super(e),this.semaphore=t}async resolve(){return this.isAsync?this.semaphore.run(()=>super.resolve()):super.resolve()}}const ft=["6.2","6.1","6.0","5.9"];function mt(s,{progress:e=new U,semaphore:t=new he({concurrency:3}),onStepCompleted:r=()=>{}}={}){const i=(s.steps||[]).filter(wt),n=i.reduce((a,l)=>a+(l.progress?.weight||1),0),o=i.map(a=>gt(a,{semaphore:t,rootProgressTracker:e,totalProgressWeight:n}));return{versions:{php:Z(s.preferredVersions?.php,ve,Ge),wp:Z(s.preferredVersions?.wp,ft,"6.2")},run:async a=>{try{for(const{resources:l}of o)for(const c of l)c.setPlayground(a),c.isAsync&&c.resolve();for(const{run:l,step:c}of o){const u=await l(a);r(u,c)}try{await a.goTo(s.landingPage||"/")}catch{}}finally{e.finish()}}}}function Z(s,e,t){return s&&e.includes(s)?s:t}function wt(s){return!!(typeof s=="object"&&s)}function gt(s,{semaphore:e,rootProgressTracker:t,totalProgressWeight:r}){const i=t.stage((s.progress?.weight||1)/r),n={};for(const u of Object.keys(s)){let d=s[u];it(d)&&(d=g.create(d,{semaphore:e})),n[u]=d}const o=async u=>{try{return i.fillSlowly(),await Oe[s.step](u,await yt(n),{tracker:i,initialCaption:s.progress?.caption})}finally{i.finish()}},a=Q(n),l=Q(n).filter(u=>u.isAsync),c=1/(l.length+1);for(const u of l)u.progress=i.stage(c);return{run:o,step:s,resources:a}}function Q(s){const e=[];for(const t in s){const r=s[t];r instanceof g&&e.push(r)}return e}async function yt(s){const e={};for(const t in s){const r=s[t];r instanceof g?e[t]=await r.resolve():e[t]=r}return e}async function Pt(s,e){await s.run(e)}exports.activatePlugin=x;exports.activateTheme=F;exports.applyWordPressPatches=X;exports.compileBlueprint=mt;exports.cp=ie;exports.defineSiteUrl=le;exports.defineWpConfigConsts=C;exports.importFile=de;exports.installPlugin=we;exports.installTheme=ge;exports.login=ye;exports.mkdir=oe;exports.mv=ne;exports.replaceSite=pe;exports.request=re;exports.rm=ae;exports.rmdir=ce;exports.runBlueprintSteps=Pt;exports.runPHP=ee;exports.runPHPWithOptions=te;exports.runWpInstallationWizard=Pe;exports.setPhpIniEntry=se;exports.setPluginProxyURL=lt;exports.setSiteOptions=_e;exports.unzip=v;exports.updateUserMeta=$e;exports.writeFile=k;exports.zipEntireSite=ue;
159
+ `;this[h].ccall("wasm_set_phpini_entries",null,[p],[e])}this[h].ccall("php_wasm_init",null,[],[])}#o(){const e="/tmp/headers.json";if(!this.fileExists(e))throw new Error("SAPI Error: Could not find response headers file.");const t=JSON.parse(this.readFileAsText(e)),s={};for(const i of t.headers){if(!i.includes(": "))continue;const n=i.indexOf(": "),o=i.substring(0,n).toLowerCase(),a=i.substring(n+2);o in s||(s[o]=[]),s[o].push(a)}return{headers:s,httpStatusCode:t.status}}#a(e){if(this[h].ccall("wasm_set_request_uri",null,[p],[e]),e.includes("?")){const t=e.substring(e.indexOf("?")+1);this[h].ccall("wasm_set_query_string",null,[p],[t])}}#c(e,t){this[h].ccall("wasm_set_request_host",null,[p],[e]);let s;try{s=parseInt(new URL(e).port,10)}catch{}(!s||isNaN(s)||s===80)&&(s=t==="https"?443:80),this[h].ccall("wasm_set_request_port",null,[P],[s]),(t==="https"||!t&&s===443)&&this.addServerGlobalEntry("HTTPS","on")}#l(e){this[h].ccall("wasm_set_request_method",null,[p],[e])}#h(e){e.cookie&&this[h].ccall("wasm_set_cookies",null,[p],[e.cookie]),e["content-type"]&&this[h].ccall("wasm_set_content_type",null,[p],[e["content-type"]]),e["content-length"]&&this[h].ccall("wasm_set_content_length",null,[P],[parseInt(e["content-length"],10)]);for(const t in e){let s="HTTP_";["content-type","content-length"].includes(t.toLowerCase())&&(s=""),this.addServerGlobalEntry(`${s}${t.toUpperCase().replace(/-/g,"_")}`,e[t])}}#u(e){this[h].ccall("wasm_set_request_body",null,[p],[e]),this[h].ccall("wasm_set_content_length",null,[P],[new TextEncoder().encode(e).length])}#p(e){this[h].ccall("wasm_set_path_translated",null,[p],[e])}addServerGlobalEntry(e,t){this.#r[e]=t}#d(){for(const e in this.#r)this[h].ccall("wasm_add_SERVER_entry",null,[p,p],[e,this.#r[e]])}#f(e){const{key:t,name:s,type:i,data:n}=e,o=`/tmp/${Math.random().toFixed(20)}`;this.writeFile(o,n);const a=0;this[h].ccall("wasm_add_uploaded_file",null,[p,p,p,p,P,P],[t,s,i,o,a,n.byteLength])}#m(e){this[h].ccall("wasm_set_php_code",null,[p],[e])}async#w(){let e,t;try{e=await new Promise((n,o)=>{t=l=>{const c=new Error("Rethrown");c.cause=l.error,c.betterMessage=l.message,o(c)},this.#s?.addEventListener("error",t);const a=this[h].ccall("wasm_sapi_handle_request",P,[],[]);return a instanceof Promise?a.then(n,o):n(a)})}catch(n){for(const c in this)typeof this[c]=="function"&&(this[c]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});this.functionsMaybeMissingFromAsyncify=ze();const o=n,a="betterMessage"in o?o.betterMessage:o.message,l=new Error(a);throw l.cause=o,l}finally{this.#s?.removeEventListener("error",t),this.#r={}}const{headers:s,httpStatusCode:i}=this.#o();return new _(i,s,this.readFileAsBuffer("/tmp/stdout"),this.readFileAsText("/tmp/stderr"),e)}mkdir(e){this[h].FS.mkdirTree(e)}mkdirTree(e){this.mkdir(e)}readFileAsText(e){return new TextDecoder().decode(this.readFileAsBuffer(e))}readFileAsBuffer(e){return this[h].FS.readFile(e)}writeFile(e,t){this[h].FS.writeFile(e,t)}unlink(e){this[h].FS.unlink(e)}mv(e,t){this[h].FS.rename(e,t)}rmdir(e,t={recursive:!0}){t?.recursive&&this.listFiles(e).forEach(s=>{const i=`${e}/${s}`;this.isDir(i)?this.rmdir(i,t):this.unlink(i)}),this[h].FS.rmdir(e)}listFiles(e,t={prependPath:!1}){if(!this.fileExists(e))return[];try{const s=this[h].FS.readdir(e).filter(i=>i!=="."&&i!=="..");if(t.prependPath){const i=e.replace(/\/$/,"");return s.map(n=>`${i}/${n}`)}return s}catch(s){return console.error(s,{path:e}),[]}}isDir(e){return this.fileExists(e)?this[h].FS.isDir(this[h].FS.lookupPath(e).node.mode):!1}fileExists(e){try{return this[h].FS.lookupPath(e),!0}catch{return!1}}}m([f('Could not create directory "{path}"')],w.prototype,"mkdir",1);m([f('Could not create directory "{path}"')],w.prototype,"mkdirTree",1);m([f('Could not read "{path}"')],w.prototype,"readFileAsText",1);m([f('Could not read "{path}"')],w.prototype,"readFileAsBuffer",1);m([f('Could not write to "{path}"')],w.prototype,"writeFile",1);m([f('Could not unlink "{path}"')],w.prototype,"unlink",1);m([f('Could not move "{path}"')],w.prototype,"mv",1);m([f('Could not remove directory "{path}"')],w.prototype,"rmdir",1);m([f('Could not list files in "{path}"')],w.prototype,"listFiles",1);m([f('Could not stat "{path}"')],w.prototype,"isDir",1);m([f('Could not stat "{path}"')],w.prototype,"fileExists",1);function Se(r){const e={};for(const t in r)e[t.toLowerCase()]=r[t];return e}const it=["vfs","literal","wordpress.org/themes","wordpress.org/plugins","url"];function nt(r){return r&&typeof r=="object"&&typeof r.resource=="string"&&it.includes(r.resource)}class y{static create(e,{semaphore:t,progress:s}){let i;switch(e.resource){case"vfs":i=new ot(e,s);break;case"literal":i=new at(e,s);break;case"wordpress.org/themes":i=new ut(e,s);break;case"wordpress.org/plugins":i=new pt(e,s);break;case"url":i=new lt(e,s);break;default:throw new Error(`Invalid resource: ${e}`)}return i=new dt(i),t&&(i=new ft(i,t)),i}setPlayground(e){this.playground=e}get isAsync(){return!1}}class ot extends y{constructor(e,t){super(),this.resource=e,this.progress=t}async resolve(){const e=await this.playground.readFileAsBuffer(this.resource.path);return this.progress?.set(100),new k([e],this.name)}get name(){return this.resource.path.split("/").pop()||""}}class at extends y{constructor(e,t){super(),this.resource=e,this.progress=t}async resolve(){return this.progress?.set(100),new k([this.resource.contents],this.resource.name)}get name(){return this.resource.name}}class L extends y{constructor(e){super(),this.progress=e}async resolve(){this.progress?.setCaption(this.caption);const e=this.getURL();let t=await fetch(e);if(t=await He(t,this.progress?.loadingListener??ct),t.status!==200)throw new Error(`Could not download "${e}"`);return new k([await t.blob()],this.name)}get caption(){return`Downloading ${this.name}`}get name(){try{return new URL(this.getURL(),"http://example.com").pathname.split("/").pop()}catch{return this.getURL()}}get isAsync(){return!0}}const ct=()=>{};class lt extends L{constructor(e,t){super(t),this.resource=e}getURL(){return this.resource.url}get caption(){return this.resource.caption??super.caption}}let H="https://playground.wordpress.net/plugin-proxy";function ht(r){H=r}class ut extends L{constructor(e,t){super(t),this.resource=e}get name(){return v(this.resource.slug)}getURL(){const e=Te(this.resource.slug);return`${H}?theme=`+e}}class pt extends L{constructor(e,t){super(t),this.resource=e}get name(){return v(this.resource.slug)}getURL(){const e=Te(this.resource.slug);return`${H}?plugin=`+e}}function Te(r){return!r||r.endsWith(".zip")?r:r+".latest-stable.zip"}class Re extends y{constructor(e){super(),this.resource=e}async resolve(){return this.resource.resolve()}async setPlayground(e){return this.resource.setPlayground(e)}get progress(){return this.resource.progress}set progress(e){this.resource.progress=e}get name(){return this.resource.name}get isAsync(){return this.resource.isAsync}}class dt extends Re{async resolve(){return this.promise||(this.promise=super.resolve()),this.promise}}class ft extends Re{constructor(e,t){super(e),this.semaphore=t}async resolve(){return this.isAsync?this.semaphore.run(()=>super.resolve()):super.resolve()}}const mt=["6.2","6.1","6.0","5.9"];function wt(r,{progress:e=new N,semaphore:t=new ue({concurrency:3}),onStepCompleted:s=()=>{}}={}){const i=(r.steps||[]).filter(gt),n=i.reduce((a,l)=>a+(l.progress?.weight||1),0),o=i.map(a=>yt(a,{semaphore:t,rootProgressTracker:e,totalProgressWeight:n}));return{versions:{php:Q(r.preferredVersions?.php,Ee,Ve),wp:Q(r.preferredVersions?.wp,mt,"6.2")},run:async a=>{try{for(const{resources:l}of o)for(const c of l)c.setPlayground(a),c.isAsync&&c.resolve();for(const{run:l,step:c}of o){const u=await l(a);s(u,c)}try{await a.goTo(r.landingPage||"/")}catch{}}finally{e.finish()}}}}function Q(r,e,t){return r&&e.includes(r)?r:t}function gt(r){return!!(typeof r=="object"&&r)}function yt(r,{semaphore:e,rootProgressTracker:t,totalProgressWeight:s}){const i=t.stage((r.progress?.weight||1)/s),n={};for(const u of Object.keys(r)){let d=r[u];nt(d)&&(d=y.create(d,{semaphore:e})),n[u]=d}const o=async u=>{try{return i.fillSlowly(),await Oe[r.step](u,await Pt(n),{tracker:i,initialCaption:r.progress?.caption})}finally{i.finish()}},a=X(n),l=X(n).filter(u=>u.isAsync),c=1/(l.length+1);for(const u of l)u.progress=i.stage(c);return{run:o,step:r,resources:a}}function X(r){const e=[];for(const t in r){const s=r[t];s instanceof y&&e.push(s)}return e}async function Pt(r){const e={};for(const t in r){const s=r[t];s instanceof y?e[t]=await s.resolve():e[t]=s}return e}async function _t(r,e){await r.run(e)}exports.activatePlugin=F;exports.activateTheme=C;exports.applyWordPressPatches=ee;exports.compileBlueprint=wt;exports.cp=ne;exports.defineSiteUrl=he;exports.defineWpConfigConsts=E;exports.importFile=fe;exports.installPlugin=ge;exports.installTheme=ye;exports.login=Pe;exports.mkdir=ae;exports.mv=oe;exports.replaceSite=de;exports.request=ie;exports.rm=ce;exports.rmdir=le;exports.runBlueprintSteps=_t;exports.runPHP=te;exports.runPHPWithOptions=re;exports.runWpInstallationWizard=_e;exports.setPhpIniEntry=se;exports.setPluginProxyURL=ht;exports.setSiteOptions=$e;exports.unzip=S;exports.updateUserMeta=be;exports.writeFile=A;exports.zipEntireSite=pe;