@wp-playground/client 0.1.34 → 0.1.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/index.cjs +10 -10
  2. package/index.d.ts +4 -1
  3. package/index.js +307 -273
  4. package/package.json +2 -2
package/index.cjs CHANGED
@@ -1,16 +1,16 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function T(t){return new DOMParser().parseFromString(t.text,"text/html")}function L(t){const e=t.split(".").shift().replace("-"," ");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}async function E(t,e,r){await t.writeFile(e,r(await t.readFileAsText(e)))}async function De(t){return new Uint8Array(await t.arrayBuffer())}const re=async(t,{plugin:e},r)=>{r?.tracker.setCaption(`Activating ${e}`);const i=T(await t.request({url:"/wp-admin/plugins.php"})).querySelector(`tr[data-slug="${e}"] a`).attributes.getNamedItem("href").value;await t.request({url:"/wp-admin/"+i})},se=async(t,e)=>{const r=new Me(t,e.siteUrl,e.wordpressPath||"/wordpress");e.patchSqlitePlugin!==!1&&await r.patchSqlitePlugin(),e.addPhpInfo!==!1&&await r.addPhpInfo(),e.patchSiteUrl!==!1&&await r.patchSiteUrl(),e.disableSiteHealth!==!1&&await r.disableSiteHealth(),e.disableWpNewBlogNotification!==!1&&await r.disableWpNewBlogNotification()};class Me{constructor(e,r,s){this.php=e,this.scopedSiteUrl=r,this.wordpressPath=s}async patchSqlitePlugin(){await E(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 E(this.php,`${this.wordpressPath}/wp-config.php`,e=>`<?php
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function T(t){return new DOMParser().parseFromString(t.text,"text/html")}function L(t){const e=t.split(".").shift().replace("-"," ");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}async function E(t,e,r){await t.writeFile(e,r(await t.readFileAsText(e)))}async function Ve(t){return new Uint8Array(await t.arrayBuffer())}const ne=async(t,{plugin:e},r)=>{r?.tracker.setCaption(`Activating ${e}`);const i=T(await t.request({url:"/wp-admin/plugins.php"})).querySelector(`tr[data-slug="${e}"] a`).attributes.getNamedItem("href").value;await t.request({url:"/wp-admin/"+i})},ie=async(t,e)=>{const r=new Ge(t,e.siteUrl,e.wordpressPath||"/wordpress");e.patchSqlitePlugin!==!1&&await r.patchSqlitePlugin(),e.addPhpInfo!==!1&&await r.addPhpInfo(),e.patchSiteUrl!==!1&&await r.patchSiteUrl(),e.disableSiteHealth!==!1&&await r.disableSiteHealth(),e.disableWpNewBlogNotification!==!1&&await r.disableWpNewBlogNotification()};class Ge{constructor(e,r,s){this.php=e,this.scopedSiteUrl=r,this.wordpressPath=s}async patchSqlitePlugin(){await E(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 E(this.php,`${this.wordpressPath}/wp-config.php`,e=>`<?php
2
2
  if(!defined('WP_HOME')) {
3
3
  define('WP_HOME', "${this.scopedSiteUrl}");
4
4
  define('WP_SITEURL', "${this.scopedSiteUrl}");
5
5
  }
6
- ?>${e}`)}async disableSiteHealth(){await E(this.php,`${this.wordpressPath}/wp-includes/default-filters.php`,e=>e.replace(/add_filter[^;]+wp_maybe_grant_site_health_caps[^;]+;/i,""))}async disableWpNewBlogNotification(){await E(this.php,`${this.wordpressPath}/wp-config.php`,e=>`${e} function wp_new_blog_notification(...$args){} `)}}const ne=async(t,{code:e})=>await t.run({code:e}),ie=async(t,{options:e})=>await t.run(e),oe=async(t,{key:e,value:r})=>{await t.setPhpIniEntry(e,r)},ae=async(t,{request:e})=>await t.request(e),ce=async(t,{fromPath:e,toPath:r})=>{await t.writeFile(r,await t.readFileAsBuffer(e))},le=async(t,{fromPath:e,toPath:r})=>{await t.mv(e,r)},ue=async(t,{path:e})=>{await t.mkdir(e)},he=async(t,{path:e})=>{await t.unlink(e)},de=async(t,{path:e})=>{await t.rmdir(e)},pe=async(t,{path:e,data:r})=>{r instanceof File&&(r=await De(r)),await t.writeFile(e,r)},fe=async(t,{siteUrl:e})=>{await E(t,"/wordpress/wp-config.php",r=>`<?php
6
+ ?>${e}`)}async disableSiteHealth(){await E(this.php,`${this.wordpressPath}/wp-includes/default-filters.php`,e=>e.replace(/add_filter[^;]+wp_maybe_grant_site_health_caps[^;]+;/i,""))}async disableWpNewBlogNotification(){await E(this.php,`${this.wordpressPath}/wp-config.php`,e=>`${e} function wp_new_blog_notification(...$args){} `)}}const oe=async(t,{code:e})=>await t.run({code:e}),ae=async(t,{options:e})=>await t.run(e),ce=async(t,{key:e,value:r})=>{await t.setPhpIniEntry(e,r)},le=async(t,{request:e})=>await t.request(e),ue=async(t,{fromPath:e,toPath:r})=>{await t.writeFile(r,await t.readFileAsBuffer(e))},he=async(t,{fromPath:e,toPath:r})=>{await t.mv(e,r)},de=async(t,{path:e})=>{await t.mkdir(e)},pe=async(t,{path:e})=>{await t.unlink(e)},fe=async(t,{path:e})=>{await t.rmdir(e)},me=async(t,{path:e,data:r})=>{r instanceof File&&(r=await Ve(r)),await t.writeFile(e,r)},we=async(t,{siteUrl:e})=>{const r=await t.documentRoot;await E(t,`${r}/wp-config.php`,s=>`<?php
7
7
  if ( ! defined( 'WP_HOME' ) ) {
8
8
  define('WP_HOME', "${e}");
9
9
  }
10
10
  if ( ! defined( 'WP_SITEURL' ) ) {
11
11
  define('WP_SITEURL', "${e}");
12
12
  }
13
- ?>${r}`)};class me{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 r=await this.acquire();try{return await e()}finally{r()}}}const je=Symbol("literal");function b(t){if(typeof t=="string")return t.startsWith("$")?t:JSON.stringify(t);if(typeof t=="number")return t.toString();if(Array.isArray(t))return`array(${t.map(b).join(", ")})`;if(t===null)return"null";if(typeof t=="object")return je in t?t.toString():`array(${Object.entries(t).map(([r,s])=>`${JSON.stringify(r)} => ${b(s)}`).join(", ")})`;if(typeof t=="function")return t();throw new Error(`Unsupported value: ${t}`)}function A(t){const e={};for(const r in t)e[r]=b(t[r]);return e}const B=`<?php
13
+ ?>${s}`)};class ge{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 r=await this.acquire();try{return await e()}finally{r()}}}const Je=Symbol("literal");function b(t){if(typeof t=="string")return t.startsWith("$")?t:JSON.stringify(t);if(typeof t=="number")return t.toString();if(Array.isArray(t))return`array(${t.map(b).join(", ")})`;if(t===null)return"null";if(typeof t=="object")return Je in t?t.toString():`array(${Object.entries(t).map(([r,s])=>`${JSON.stringify(r)} => ${b(s)}`).join(", ")})`;if(typeof t=="function")return t();throw new Error(`Unsupported value: ${t}`)}function A(t){const e={};for(const r in t)e[r]=b(t[r]);return e}const V=`<?php
14
14
 
15
15
  function zipDir($dir, $output, $additionalFiles = array())
16
16
  {
@@ -72,32 +72,32 @@ function delTree($dir)
72
72
  }
73
73
  return rmdir($dir);
74
74
  }
75
- `;async function we(t){const e="wordpress-playground.zip",r=`/${e}`,s=A({zipPath:r,documentRoot:await t.documentRoot});await Pe(t,`zipDir(${s.documentRoot}, ${s.zipPath});`);const n=await t.readFileAsBuffer(r);return t.unlink(r),new File([n],e)}const ge=async(t,{fullSiteZip:e})=>{const r="/import.zip";await t.writeFile(r,new Uint8Array(await e.arrayBuffer()));const s=await t.absoluteUrl,n=await t.documentRoot;await t.rmdir(n),await q(t,{zipPath:r,extractToPath:"/"});const i=A({absoluteUrl:s});await Ve(t,`${n}/wp-config.php`,o=>`<?php
75
+ `;async function ye(t){const e="wordpress-playground.zip",r=`/${e}`,s=A({zipPath:r,documentRoot:await t.documentRoot});await _e(t,`zipDir(${s.documentRoot}, ${s.zipPath});`);const n=await t.readFileAsBuffer(r);return t.unlink(r),new File([n],e)}const Pe=async(t,{fullSiteZip:e})=>{const r="/import.zip";await t.writeFile(r,new Uint8Array(await e.arrayBuffer()));const s=await t.absoluteUrl,n=await t.documentRoot;await t.rmdir(n),await D(t,{zipPath:r,extractToPath:"/"});const i=A({absoluteUrl:s});await Ye(t,`${n}/wp-config.php`,o=>`<?php
76
76
  if(!defined('WP_HOME')) {
77
77
  define('WP_HOME', ${i.absoluteUrl});
78
78
  define('WP_SITEURL', ${i.absoluteUrl});
79
79
  }
80
- ?>${o}`)},q=async(t,{zipPath:e,extractToPath:r})=>{const s=A({zipPath:e,extractToPath:r});await Pe(t,`unzip(${s.zipPath}, ${s.extractToPath});`)},ye=async(t,{file:e})=>{const r=await t.request({url:"/wp-admin/admin.php?import=wordpress"}),s=V(r).getElementById("import-upload-form")?.getAttribute("action"),n=await t.request({url:`/wp-admin/${s}`,method:"POST",files:{import:e}}),i=V(n).querySelector("#wpbody-content form");if(!i)throw console.log(n.text),new Error("Could not find an importer form in response. See the response text above for details.");const o=Be(i);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 t.request({url:i.action,method:"POST",formData:o})};function V(t){return new DOMParser().parseFromString(t.text,"text/html")}function Be(t){return Object.fromEntries(new FormData(t).entries())}async function Ve(t,e,r){await t.writeFile(e,r(await t.readFileAsText(e)))}async function Pe(t,e){const r=await t.run({code:B+e});if(r.exitCode!==0)throw console.log(B+e),console.log(e+""),console.log(r.errors),r.errors;return r}const be=async(t,{pluginZipFile:e,options:r={}},s)=>{s?.tracker.setCaption(`Installing the ${L(e?.name)} plugin`);try{const n="activate"in r?r.activate:!0,i=await t.request({url:"/wp-admin/plugin-install.php?tab=upload"}),o=T(i),a=new FormData(o.querySelector(".wp-upload-form")),{pluginzip:l,...c}=Object.fromEntries(a.entries()),u=await t.request({url:"/wp-admin/update.php?action=upload-plugin",method:"POST",formData:c,files:{pluginzip:e}});if(n){const p=T(u).querySelector("#wpbody-content .button.button-primary").attributes.getNamedItem("href").value,y=new URL(p,await t.pathToInternalUrl("/wp-admin/")).toString();await t.request({url:y})}await t.isDir("/wordpress/wp-content/plugins/gutenberg")&&!await t.fileExists("/wordpress/.gutenberg-patched")&&(await t.writeFile("/wordpress/.gutenberg-patched","1"),await G(t,"/wordpress/wp-content/plugins/gutenberg/build/block-editor/index.js",d=>d.replace(/srcDoc:("[^"]+"|[^,]+)/g,'src:"/wp-includes/empty.html"')),await G(t,"/wordpress/wp-content/plugins/gutenberg/build/block-editor/index.min.js",d=>d.replace(/srcDoc:("[^"]+"|[^,]+)/g,'src:"/wp-includes/empty.html"')))}catch(n){console.error(`Proceeding without the ${e.name} theme. Could not install it in wp-admin. The original error was: ${n}`),console.error(n)}};async function G(t,e,r){return await t.writeFile(e,r(await t.readFileAsText(e)))}const _e=async(t,{themeZipFile:e,options:r={}},s)=>{s?.tracker.setCaption(`Installing the ${L(e.name)} theme`);try{const n="activate"in r?r.activate:!0,i=await t.request({url:"/wp-admin/theme-install.php"}),o=T(i),a=new FormData(o.querySelector(".wp-upload-form")),{themezip:l,...c}=Object.fromEntries(a.entries()),u=await t.request({url:"/wp-admin/update.php?action=upload-theme",method:"POST",formData:c,files:{themezip:e}});if(n){const d=T(u),p=d.querySelector("#wpbody-content > .wrap");if(p?.textContent?.includes("Theme installation failed.")){console.error(p?.textContent);return}const y=d.querySelector("#wpbody-content .activatelink, .update-from-upload-actions .button.button-primary");if(!y){console.error('The "activate" button was not found.');return}const We=y.attributes.getNamedItem("href").value,qe=new URL(We,await t.pathToInternalUrl("/wp-admin/")).toString();await t.request({url:qe})}}catch(n){console.error(`Proceeding without the ${e.name} theme. Could not install it in wp-admin. The original error was: ${n}`),console.error(n)}},Se=async(t,{username:e="admin",password:r="password"}={},s)=>{s?.tracker.setCaption(s?.initialCaption||"Logging in"),await t.request({url:"/wp-login.php"}),await t.request({url:"/wp-login.php",method:"POST",formData:{log:e,pwd:r,rememberme:"forever"}})},$e=async(t,{options:e})=>{await t.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"}})},ve=async(t,{options:e})=>{const r=`<?php
80
+ ?>${o}`)},D=async(t,{zipPath:e,extractToPath:r})=>{const s=A({zipPath:e,extractToPath:r});await _e(t,`unzip(${s.zipPath}, ${s.extractToPath});`)},be=async(t,{file:e})=>{const r=await t.request({url:"/wp-admin/admin.php?import=wordpress"}),s=G(r).getElementById("import-upload-form")?.getAttribute("action"),n=await t.request({url:`/wp-admin/${s}`,method:"POST",files:{import:e}}),i=G(n).querySelector("#wpbody-content form");if(!i)throw console.log(n.text),new Error("Could not find an importer form in response. See the response text above for details.");const o=Ke(i);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 t.request({url:i.action,method:"POST",formData:o})};function G(t){return new DOMParser().parseFromString(t.text,"text/html")}function Ke(t){return Object.fromEntries(new FormData(t).entries())}async function Ye(t,e,r){await t.writeFile(e,r(await t.readFileAsText(e)))}async function _e(t,e){const r=await t.run({code:V+e});if(r.exitCode!==0)throw console.log(V+e),console.log(e+""),console.log(r.errors),r.errors;return r}const Se=async(t,{pluginZipFile:e,options:r={}},s)=>{s?.tracker.setCaption(`Installing the ${L(e?.name)} plugin`);try{const n="activate"in r?r.activate:!0,i=await t.request({url:"/wp-admin/plugin-install.php?tab=upload"}),o=T(i),a=new FormData(o.querySelector(".wp-upload-form")),{pluginzip:l,...c}=Object.fromEntries(a.entries()),u=await t.request({url:"/wp-admin/update.php?action=upload-plugin",method:"POST",formData:c,files:{pluginzip:e}});if(n){const p=T(u).querySelector("#wpbody-content .button.button-primary").attributes.getNamedItem("href").value,y=new URL(p,await t.pathToInternalUrl("/wp-admin/")).toString();await t.request({url:y})}await t.isDir("/wordpress/wp-content/plugins/gutenberg")&&!await t.fileExists("/wordpress/.gutenberg-patched")&&(await t.writeFile("/wordpress/.gutenberg-patched","1"),await J(t,"/wordpress/wp-content/plugins/gutenberg/build/block-editor/index.js",d=>d.replace(/srcDoc:("[^"]+"|[^,]+)/g,'src:"/wp-includes/empty.html"')),await J(t,"/wordpress/wp-content/plugins/gutenberg/build/block-editor/index.min.js",d=>d.replace(/srcDoc:("[^"]+"|[^,]+)/g,'src:"/wp-includes/empty.html"')))}catch(n){console.error(`Proceeding without the ${e.name} theme. Could not install it in wp-admin. The original error was: ${n}`),console.error(n)}};async function J(t,e,r){return await t.writeFile(e,r(await t.readFileAsText(e)))}const $e=async(t,{themeZipFile:e,options:r={}},s)=>{s?.tracker.setCaption(`Installing the ${L(e.name)} theme`);try{const n="activate"in r?r.activate:!0,i=await t.request({url:"/wp-admin/theme-install.php"}),o=T(i),a=new FormData(o.querySelector(".wp-upload-form")),{themezip:l,...c}=Object.fromEntries(a.entries()),u=await t.request({url:"/wp-admin/update.php?action=upload-theme",method:"POST",formData:c,files:{themezip:e}});if(n){const d=T(u),p=d.querySelector("#wpbody-content > .wrap");if(p?.textContent?.includes("Theme installation failed.")){console.error(p?.textContent);return}const y=d.querySelector("#wpbody-content .activatelink, .update-from-upload-actions .button.button-primary");if(!y){console.error('The "activate" button was not found.');return}const je=y.attributes.getNamedItem("href").value,Be=new URL(je,await t.pathToInternalUrl("/wp-admin/")).toString();await t.request({url:Be})}}catch(n){console.error(`Proceeding without the ${e.name} theme. Could not install it in wp-admin. The original error was: ${n}`),console.error(n)}},ve=async(t,{username:e="admin",password:r="password"}={},s)=>{s?.tracker.setCaption(s?.initialCaption||"Logging in"),await t.request({url:"/wp-login.php"}),await t.request({url:"/wp-login.php",method:"POST",formData:{log:e,pwd:r,rememberme:"forever"}})},Ee=async(t,{options:e})=>{await t.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"}})},Re=async(t,{options:e})=>{const r=`<?php
81
81
  include 'wordpress/wp-load.php';
82
82
  $site_options = ${b(e)};
83
83
  foreach($site_options as $name => $value) {
84
84
  update_option($name, $value);
85
85
  }
86
86
  echo "Success";
87
- `,s=await t.run({code:r});return Re(s),{code:r,result:s}},Ee=async(t,{meta:e,userId:r})=>{const s=`<?php
87
+ `,s=await t.run({code:r});return xe(s),{code:r,result:s}},Te=async(t,{meta:e,userId:r})=>{const s=`<?php
88
88
  include 'wordpress/wp-load.php';
89
89
  $meta = ${b(e)};
90
90
  foreach($meta as $name => $value) {
91
91
  update_user_meta(${b(r)}, $name, $value);
92
92
  }
93
93
  echo "Success";
94
- `,n=await t.run({code:s});return Re(n),{code:s,result:n}};async function Re(t){if(t.text!=="Success")throw console.log(t),new Error(`Failed to run code: ${t.text} ${t.errors}`)}const Ge=Object.freeze(Object.defineProperty({__proto__:null,activatePlugin:re,applyWordPressPatches:se,cp:ce,defineSiteUrl:fe,importFile:ye,installPlugin:be,installTheme:_e,login:Se,mkdir:ue,mv:le,replaceSite:ge,request:ae,rm:he,rmdir:de,runPHP:ne,runPHPWithOptions:ie,runWpInstallationWizard:$e,setPhpIniEntry:oe,setSiteOptions:ve,unzip:q,updateUserMeta:Ee,writeFile:pe,zipEntireSite:we},Symbol.toStringTag,{value:"Module"})),Je=5*1024*1024;function Ke(t,e){const r=t.headers.get("content-length")||"",s=parseInt(r,10)||Je;function n(i,o){e(new CustomEvent("progress",{detail:{loaded:i,total:o}}))}return new Response(new ReadableStream({async start(i){if(!t.body){i.close();return}const o=t.body.getReader();let a=0;for(;;)try{const{done:l,value:c}=await o.read();if(c&&(a+=c.byteLength),l){n(a,a),i.close();break}else n(a,s),i.enqueue(c)}catch(l){console.error({e:l}),i.error(l);break}}}),{status:t.status,statusText:t.statusText,headers:t.headers})}const z=1e-5;class H extends EventTarget{constructor({weight:e=1,caption:r="",fillTime:s=4}={}){super(),this._selfWeight=1,this._selfProgress=0,this._selfCaption="",this._isFilling=!1,this._subTrackers=[],this._weight=e,this._selfCaption=r,this._fillTime=s}stage(e,r=""){if(e||(e=this._selfWeight),this._selfWeight-e<-z)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 H({caption:r,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 r=100,s=this._fillTime/r;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+z>=100&&this.finish()}finish(){this._fillInterval&&clearInterval(this._fillInterval),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 r=this._subTrackers[e].caption;if(r)return r}return this._selfCaption}setCaption(e){this._selfCaption=e,this.notifyProgress()}get done(){return this.progress+z>=100}get progress(){const e=this._subTrackers.reduce((r,s)=>r+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){this.addEventListener("progress",r=>{e.setProgress({progress:r.detail.progress,caption:r.detail.caption})}),this.addEventListener("done",()=>{e.setLoaded()})}addEventListener(e,r){super.addEventListener(e,r)}removeEventListener(e,r){super.removeEventListener(e,r)}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"))}}class v{constructor(e,r,s,n="",i=0){this.httpStatusCode=e,this.headers=r,this.bytes=s,this.exitCode=i,this.errors=n}static fromRawData(e){return new v(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 I=["8.2","8.1","8.0","7.4","7.3","7.2","7.1","7.0","5.6"],Te=I[0],Ye=I;class Qe{#e;#t;constructor(e,r={}){this.requestHandler=e,this.#e={},this.#t={handleRedirects:!1,maxRedirects:4,...r}}async request(e,r=0){const s=await this.requestHandler.request({...e,headers:{...e.headers,cookie:this.#s()}});if(s.headers["set-cookie"]&&this.#n(s.headers["set-cookie"]),this.#t.handleRedirects&&s.headers.location&&r<this.#t.maxRedirects){const n=new URL(s.headers.location[0],this.requestHandler.absoluteUrl);return this.request({url:n.toString(),method:"GET",headers:{}},r+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}#n(e){for(const r of e)try{if(!r.includes("="))continue;const s=r.indexOf("="),n=r.substring(0,s),i=r.substring(s+1).split(";")[0];this.#e[n]=i}catch(s){console.error(s)}}#s(){const e=[];for(const r in this.#e)e.push(`${r}=${this.#e[r]}`);return e.join("; ")}}const Xe="http://example.com";function J(t){return t.toString().substring(t.origin.length)}function K(t,e){return!e||!t.startsWith(e)?t:t.substring(e.length)}function Ze(t,e){return!e||t.startsWith(e)?t:e+t}class et{#e;#t;#n;#s;#i;#r;#o;#a;#c;constructor(e,r={}){this.#a=new me({concurrency:1});const{documentRoot:s="/www/",absoluteUrl:n=typeof location=="object"?location?.href:"",isStaticFilePath:i=()=>!1}=r;this.php=e,this.#e=s,this.#c=i;const o=new URL(n);this.#n=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.#i=[this.#n,a?`:${this.#s}`:""].join(""),this.#r=o.pathname.replace(/\/+$/,""),this.#o=[`${this.#t}://`,this.#i,this.#r].join("")}pathToInternalUrl(e){return`${this.absoluteUrl}${e}`}internalUrlToPath(e){const r=new URL(e);return r.pathname.startsWith(this.#r)&&(r.pathname=r.pathname.slice(this.#r.length)),J(r)}get isRequestRunning(){return this.#a.running>0}get absoluteUrl(){return this.#o}get documentRoot(){return this.#e}async request(e){const r=e.url.startsWith("http://")||e.url.startsWith("https://"),s=new URL(e.url,r?void 0:Xe),n=K(s.pathname,this.#r);return this.#c(n)?this.#l(n):await this.#u(e,s)}#l(e){const r=`${this.#e}${e}`;if(!this.php.fileExists(r))return new v(404,{},new TextEncoder().encode("404 File not found"));const s=this.php.readFileAsBuffer(r);return new v(200,{"content-length":[`${s.byteLength}`],"content-type":[rt(r)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},s)}async#u(e,r){const s=await this.#a.acquire();try{this.php.addServerGlobalEntry("DOCUMENT_ROOT",this.#e),this.php.addServerGlobalEntry("HTTPS",this.#o.startsWith("https://")?"on":"");let n="GET";const i={host:this.#i,...xe(e.headers||{})},o=[];if(e.files&&Object.keys(e.files).length){n="POST";for(const l in e.files){const c=e.files[l];o.push({key:l,name:c.name,type:c.type,data:new Uint8Array(await c.arrayBuffer())})}i["content-type"]?.startsWith("multipart/form-data")&&(e.formData=tt(e.body||""),i["content-type"]="application/x-www-form-urlencoded",delete e.body)}let a;return e.formData!==void 0?(n="POST",i["content-type"]=i["content-type"]||"application/x-www-form-urlencoded",a=new URLSearchParams(e.formData).toString()):a=e.body,await this.php.run({relativeUri:Ze(J(r),this.#r),protocol:this.#t,method:e.method||n,body:a,fileInfos:o,scriptPath:this.#h(r.pathname),headers:i})}finally{s()}}#h(e){let r=K(e,this.#r);r.includes(".php")?r=r.split(".php")[0]+".php":(r.endsWith("/")||(r+="/"),r.endsWith("index.php")||(r+="index.php"));const s=`${this.#e}${r}`;return this.php.fileExists(s)?s:`${this.#e}/index.php`}}function tt(t){const e={},r=t.match(/--(.*)\r\n/);if(!r)return e;const s=r[1],n=t.split(`--${s}`);return n.shift(),n.pop(),n.forEach(i=>{const o=i.indexOf(`\r
94
+ `,n=await t.run({code:s});return xe(n),{code:s,result:n}};async function xe(t){if(t.text!=="Success")throw console.log(t),new Error(`Failed to run code: ${t.text} ${t.errors}`)}const Qe=Object.freeze(Object.defineProperty({__proto__:null,activatePlugin:ne,applyWordPressPatches:ie,cp:ue,defineSiteUrl:we,importFile:be,installPlugin:Se,installTheme:$e,login:ve,mkdir:de,mv:he,replaceSite:Pe,request:le,rm:pe,rmdir:fe,runPHP:oe,runPHPWithOptions:ae,runWpInstallationWizard:Ee,setPhpIniEntry:ce,setSiteOptions:Re,unzip:D,updateUserMeta:Te,writeFile:me,zipEntireSite:ye},Symbol.toStringTag,{value:"Module"})),Xe=5*1024*1024;function Ze(t,e){const r=t.headers.get("content-length")||"",s=parseInt(r,10)||Xe;function n(i,o){e(new CustomEvent("progress",{detail:{loaded:i,total:o}}))}return new Response(new ReadableStream({async start(i){if(!t.body){i.close();return}const o=t.body.getReader();let a=0;for(;;)try{const{done:l,value:c}=await o.read();if(c&&(a+=c.byteLength),l){n(a,a),i.close();break}else n(a,s),i.enqueue(c)}catch(l){console.error({e:l}),i.error(l);break}}}),{status:t.status,statusText:t.statusText,headers:t.headers})}const z=1e-5;class H extends EventTarget{constructor({weight:e=1,caption:r="",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=r,this._fillTime=s}stage(e,r=""){if(e||(e=this._selfWeight),this._selfWeight-e<-z)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 H({caption:r,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 r=100,s=this._fillTime/r;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+z>=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 r=this._subTrackers[e].caption;if(r)return r}return this._selfCaption}setCaption(e){this._selfCaption=e,this.notifyProgress()}get done(){return this.progress+z>=100}get progress(){if(this._selfDone)return 100;const e=this._subTrackers.reduce((r,s)=>r+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",r=>{e.setProgress({progress:r.detail.progress,caption:r.detail.caption})}),this.addEventListener("done",()=>{e.setLoaded()})}addEventListener(e,r){super.addEventListener(e,r)}removeEventListener(e,r){super.removeEventListener(e,r)}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"))}}class v{constructor(e,r,s,n="",i=0){this.httpStatusCode=e,this.headers=r,this.bytes=s,this.exitCode=i,this.errors=n}static fromRawData(e){return new v(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 I=["8.2","8.1","8.0","7.4","7.3","7.2","7.1","7.0","5.6"],Ce=I[0],et=I;class tt{#e;#t;constructor(e,r={}){this.requestHandler=e,this.#e={},this.#t={handleRedirects:!1,maxRedirects:4,...r}}async request(e,r=0){const s=await this.requestHandler.request({...e,headers:{...e.headers,cookie:this.#s()}});if(s.headers["set-cookie"]&&this.#n(s.headers["set-cookie"]),this.#t.handleRedirects&&s.headers.location&&r<this.#t.maxRedirects){const n=new URL(s.headers.location[0],this.requestHandler.absoluteUrl);return this.request({url:n.toString(),method:"GET",headers:{}},r+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}#n(e){for(const r of e)try{if(!r.includes("="))continue;const s=r.indexOf("="),n=r.substring(0,s),i=r.substring(s+1).split(";")[0];this.#e[n]=i}catch(s){console.error(s)}}#s(){const e=[];for(const r in this.#e)e.push(`${r}=${this.#e[r]}`);return e.join("; ")}}const rt="http://example.com";function K(t){return t.toString().substring(t.origin.length)}function Y(t,e){return!e||!t.startsWith(e)?t:t.substring(e.length)}function st(t,e){return!e||t.startsWith(e)?t:e+t}class nt{#e;#t;#n;#s;#i;#r;#o;#a;#c;constructor(e,r={}){this.#a=new ge({concurrency:1});const{documentRoot:s="/www/",absoluteUrl:n=typeof location=="object"?location?.href:"",isStaticFilePath:i=()=>!1}=r;this.php=e,this.#e=s,this.#c=i;const o=new URL(n);this.#n=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.#i=[this.#n,a?`:${this.#s}`:""].join(""),this.#r=o.pathname.replace(/\/+$/,""),this.#o=[`${this.#t}://`,this.#i,this.#r].join("")}pathToInternalUrl(e){return`${this.absoluteUrl}${e}`}internalUrlToPath(e){const r=new URL(e);return r.pathname.startsWith(this.#r)&&(r.pathname=r.pathname.slice(this.#r.length)),K(r)}get isRequestRunning(){return this.#a.running>0}get absoluteUrl(){return this.#o}get documentRoot(){return this.#e}async request(e){const r=e.url.startsWith("http://")||e.url.startsWith("https://"),s=new URL(e.url,r?void 0:rt),n=Y(s.pathname,this.#r);return this.#c(n)?this.#l(n):await this.#u(e,s)}#l(e){const r=`${this.#e}${e}`;if(!this.php.fileExists(r))return new v(404,{},new TextEncoder().encode("404 File not found"));const s=this.php.readFileAsBuffer(r);return new v(200,{"content-length":[`${s.byteLength}`],"content-type":[ot(r)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},s)}async#u(e,r){const s=await this.#a.acquire();try{this.php.addServerGlobalEntry("DOCUMENT_ROOT",this.#e),this.php.addServerGlobalEntry("HTTPS",this.#o.startsWith("https://")?"on":"");let n="GET";const i={host:this.#i,...Fe(e.headers||{})},o=[];if(e.files&&Object.keys(e.files).length){n="POST";for(const l in e.files){const c=e.files[l];o.push({key:l,name:c.name,type:c.type,data:new Uint8Array(await c.arrayBuffer())})}i["content-type"]?.startsWith("multipart/form-data")&&(e.formData=it(e.body||""),i["content-type"]="application/x-www-form-urlencoded",delete e.body)}let a;return e.formData!==void 0?(n="POST",i["content-type"]=i["content-type"]||"application/x-www-form-urlencoded",a=new URLSearchParams(e.formData).toString()):a=e.body,await this.php.run({relativeUri:st(K(r),this.#r),protocol:this.#t,method:e.method||n,body:a,fileInfos:o,scriptPath:this.#h(r.pathname),headers:i})}finally{s()}}#h(e){let r=Y(e,this.#r);r.includes(".php")?r=r.split(".php")[0]+".php":(r.endsWith("/")||(r+="/"),r.endsWith("index.php")||(r+="index.php"));const s=`${this.#e}${r}`;return this.php.fileExists(s)?s:`${this.#e}/index.php`}}function it(t){const e={},r=t.match(/--(.*)\r\n/);if(!r)return e;const s=r[1],n=t.split(`--${s}`);return n.shift(),n.pop(),n.forEach(i=>{const o=i.indexOf(`\r
95
95
  \r
96
- `),a=i.substring(0,o).trim(),l=i.substring(o+4).trim(),c=a.match(/name="([^"]+)"/);if(c){const u=c[1];e[u]=l}}),e}function rt(t){switch(t.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 Y={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 m(t=""){return function(r,s,n){const i=n.value;n.value=function(...o){try{return i.apply(this,o)}catch(a){const l=typeof a=="object"?a?.errno:null;if(l in Y){const c=Y[l],u=typeof o[0]=="string"?o[0]:null,d=u!==null?t.replaceAll("{path}",u):t;throw new Error(`${d}: ${c}`,{cause:a})}throw a}}}}const st=[];function nt(t){return st[t]}(function(){return typeof window<"u"&&!{}.TEST?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"})();var it=Object.defineProperty,ot=Object.getOwnPropertyDescriptor,w=(t,e,r,s)=>{for(var n=s>1?void 0:s?ot(e,r):e,i=t.length-1,o;i>=0;i--)(o=t[i])&&(n=(s?o(e,r,n):o(n))||n);return s&&n&&it(e,r,n),n};const f="string",S="number",h=Symbol("__private__dont__use");class g{constructor(e,r){this.#e=[],this.#t=!1,e!==void 0&&this.initializeRuntime(e),r&&(this.requestHandler=new Qe(new et(this,r)))}#e;#t;get absoluteUrl(){return this.requestHandler.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.requestHandler.absoluteUrl}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 r=nt(e);if(!r)throw new Error("Invalid PHP runtime id.");this[h]=r}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,r){if(this.#t)throw new Error("Cannot set PHP ini entries after calling run().");this.#e.push([e,r])}chdir(e){this[h].FS.chdir(e)}async request(e,r){if(!this.requestHandler)throw new Error("No request handler available.");return this.requestHandler.request(e,r)}async run(e){this.#t||(this.#n(),this.#t=!0),this.#l(e.scriptPath||""),this.#i(e.relativeUri||""),this.#o(e.method||"GET");const{host:r,...s}={host:"example.com:443",...xe(e.headers||{})};if(this.#r(r,e.protocol||"http"),this.#a(s),e.body&&this.#c(e.body),e.fileInfos)for(const n of e.fileInfos)this.#u(n);return e.code&&this.#h(" ?>"+e.code),await this.#d()}#n(){if(this.#e.length>0){const e=this.#e.map(([r,s])=>`${r}=${s}`).join(`
96
+ `),a=i.substring(0,o).trim(),l=i.substring(o+4).trim(),c=a.match(/name="([^"]+)"/);if(c){const u=c[1];e[u]=l}}),e}function ot(t){switch(t.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 Q={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 m(t=""){return function(r,s,n){const i=n.value;n.value=function(...o){try{return i.apply(this,o)}catch(a){const l=typeof a=="object"?a?.errno:null;if(l in Q){const c=Q[l],u=typeof o[0]=="string"?o[0]:null,d=u!==null?t.replaceAll("{path}",u):t;throw new Error(`${d}: ${c}`,{cause:a})}throw a}}}}const at=[];function ct(t){return at[t]}(function(){return typeof window<"u"&&!{}.TEST?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"})();var lt=Object.defineProperty,ut=Object.getOwnPropertyDescriptor,w=(t,e,r,s)=>{for(var n=s>1?void 0:s?ut(e,r):e,i=t.length-1,o;i>=0;i--)(o=t[i])&&(n=(s?o(e,r,n):o(n))||n);return s&&n&&lt(e,r,n),n};const f="string",S="number",h=Symbol("__private__dont__use");class g{constructor(e,r){this.#e=[],this.#t=!1,e!==void 0&&this.initializeRuntime(e),r&&(this.requestHandler=new tt(new nt(this,r)))}#e;#t;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 r=ct(e);if(!r)throw new Error("Invalid PHP runtime id.");this[h]=r}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,r){if(this.#t)throw new Error("Cannot set PHP ini entries after calling run().");this.#e.push([e,r])}chdir(e){this[h].FS.chdir(e)}async request(e,r){if(!this.requestHandler)throw new Error("No request handler available.");return this.requestHandler.request(e,r)}async run(e){this.#t||(this.#n(),this.#t=!0),this.#l(e.scriptPath||""),this.#i(e.relativeUri||""),this.#o(e.method||"GET");const{host:r,...s}={host:"example.com:443",...Fe(e.headers||{})};if(this.#r(r,e.protocol||"http"),this.#a(s),e.body&&this.#c(e.body),e.fileInfos)for(const n of e.fileInfos)this.#u(n);return e.code&&this.#h(" ?>"+e.code),await this.#d()}#n(){if(this.#e.length>0){const e=this.#e.map(([r,s])=>`${r}=${s}`).join(`
97
97
  `)+`
98
98
 
99
- `;this[h].ccall("wasm_set_phpini_entries",null,[f],[e])}this[h].ccall("php_wasm_init",null,[],[])}#s(){const e="/tmp/headers.json";if(!this.fileExists(e))throw new Error("SAPI Error: Could not find response headers file.");const r=JSON.parse(this.readFileAsText(e)),s={};for(const n of r.headers){if(!n.includes(": "))continue;const i=n.indexOf(": "),o=n.substring(0,i).toLowerCase(),a=n.substring(i+2);o in s||(s[o]=[]),s[o].push(a)}return{headers:s,httpStatusCode:r.status}}#i(e){if(this[h].ccall("wasm_set_request_uri",null,[f],[e]),e.includes("?")){const r=e.substring(e.indexOf("?")+1);this[h].ccall("wasm_set_query_string",null,[f],[r])}}#r(e,r){this[h].ccall("wasm_set_request_host",null,[f],[e]);let s;try{s=parseInt(new URL(e).port,10)}catch{}(!s||isNaN(s)||s===80)&&(s=r==="https"?443:80),this[h].ccall("wasm_set_request_port",null,[S],[s]),(r==="https"||!r&&s===443)&&this.addServerGlobalEntry("HTTPS","on")}#o(e){this[h].ccall("wasm_set_request_method",null,[f],[e])}#a(e){e.cookie&&this[h].ccall("wasm_set_cookies",null,[f],[e.cookie]),e["content-type"]&&this[h].ccall("wasm_set_content_type",null,[f],[e["content-type"]]),e["content-length"]&&this[h].ccall("wasm_set_content_length",null,[S],[parseInt(e["content-length"],10)]);for(const r in e)this.addServerGlobalEntry(`HTTP_${r.toUpperCase().replace(/-/g,"_")}`,e[r])}#c(e){this[h].ccall("wasm_set_request_body",null,[f],[e]),this[h].ccall("wasm_set_content_length",null,[S],[e.length])}#l(e){this[h].ccall("wasm_set_path_translated",null,[f],[e])}addServerGlobalEntry(e,r){this[h].ccall("wasm_add_SERVER_entry",null,[f,f],[e,r])}#u(e){const{key:r,name:s,type:n,data:i}=e,o=`/tmp/${Math.random().toFixed(20)}`;this.writeFile(o,i);const a=0;this[h].ccall("wasm_add_uploaded_file",null,[f,f,f,f,S,S],[r,s,n,o,a,i.byteLength])}#h(e){this[h].ccall("wasm_set_php_code",null,[f],[e])}async#d(){const e=await await this[h].ccall("wasm_sapi_handle_request",S,[],[]),{headers:r,httpStatusCode:s}=this.#s();return new v(s,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,r){this[h].FS.writeFile(e,r)}unlink(e){this[h].FS.unlink(e)}mv(e,r){this[h].FS.mv(e,r)}rmdir(e,r={recursive:!0}){r?.recursive&&this.listFiles(e).forEach(s=>{const n=`${e}/${s}`;this.isDir(n)?this.rmdir(n,r):this.unlink(n)}),this[h].FS.rmdir(e)}listFiles(e){if(!this.fileExists(e))return[];try{return this[h].FS.readdir(e).filter(r=>r!=="."&&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}}}w([m('Could not create directory "{path}"')],g.prototype,"mkdir",1);w([m('Could not create directory "{path}"')],g.prototype,"mkdirTree",1);w([m('Could not read "{path}"')],g.prototype,"readFileAsText",1);w([m('Could not read "{path}"')],g.prototype,"readFileAsBuffer",1);w([m('Could not write to "{path}"')],g.prototype,"writeFile",1);w([m('Could not unlink "{path}"')],g.prototype,"unlink",1);w([m('Could not move "{path}"')],g.prototype,"mv",1);w([m('Could not remove directory "{path}"')],g.prototype,"rmdir",1);w([m('Could not list files in "{path}"')],g.prototype,"listFiles",1);w([m('Could not stat "{path}"')],g.prototype,"isDir",1);w([m('Could not stat "{path}"')],g.prototype,"fileExists",1);function xe(t){const e={};for(const r in t)e[r.toLowerCase()]=t[r];return e}const at=["vfs","literal","wordpress.org/themes","wordpress.org/plugins","url"];function ct(t){return t&&typeof t=="object"&&typeof t.resource=="string"&&at.includes(t.resource)}class _{static create(e,{semaphore:r,progress:s}){let n;switch(e.resource){case"vfs":n=new lt(e,s);break;case"literal":n=new ut(e,s);break;case"wordpress.org/themes":n=new pt(e,s);break;case"wordpress.org/plugins":n=new ft(e,s);break;case"url":n=new dt(e,s);break;default:throw new Error(`Invalid resource: ${e}`)}return n=new mt(n),r&&(n=new wt(n,r)),n}setPlayground(e){this.playground=e}get isAsync(){return!1}}class lt extends _{constructor(e,r){super(),this.resource=e,this.progress=r}async resolve(){const e=await this.playground.readFileAsBuffer(this.resource.path);return this.progress?.set(100),new File([e],this.name)}get name(){return this.resource.path}}class ut extends _{constructor(e,r){super(),this.resource=e,this.progress=r}async resolve(){return this.progress?.set(100),new File([this.resource.contents],this.resource.name)}get name(){return this.resource.name}}class D extends _{constructor(e){super(),this.progress=e}async resolve(){this.progress?.setCaption(this.caption);const e=this.getURL();let r=await fetch(e);if(r=await Ke(r,this.progress?.loadingListener??ht),r.status!==200)throw new Error(`Could not download "${e}"`);return new File([await r.blob()],this.name)}get caption(){return`Downloading ${this.name}`}get name(){return this.getURL()}get isAsync(){return!0}}const ht=()=>{};class dt extends D{constructor(e,r){super(r),this.resource=e}getURL(){return this.resource.url}get caption(){return this.resource.caption??super.caption}}class pt extends D{constructor(e,r){super(r),this.resource=e}get name(){return L(this.resource.slug)}getURL(){return"/plugin-proxy?theme="+Fe(this.resource.slug)}}class ft extends D{constructor(e,r){super(r),this.resource=e}get name(){return L(this.resource.slug)}getURL(){return"/plugin-proxy?plugin="+Fe(this.resource.slug)}}function Fe(t){return!t||t.endsWith(".zip")?t:t+".latest-stable.zip"}class Ce extends _{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 mt extends Ce{async resolve(){return this.promise||(this.promise=super.resolve()),this.promise}}class wt extends Ce{constructor(e,r){super(e),this.semaphore=r}async resolve(){return this.isAsync?this.semaphore.run(()=>super.resolve()):super.resolve()}}const gt=["6.2","6.1","6.0","5.9"];function ke(t,{progress:e=new H,semaphore:r=new me({concurrency:3}),onStepCompleted:s=()=>{}}={}){const n=(t.steps||[]).filter(yt),i=n.reduce((a,l)=>a+(l.progress?.weight||1),0),o=n.map(a=>Pt(a,{semaphore:r,rootProgressTracker:e,totalProgressWeight:i}));return{versions:{php:Q(t.preferredVersions?.php,I,Te),wp:Q(t.preferredVersions?.wp,gt,"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(t.landingPage||"/")}catch{}}finally{e.finish()}}}}function Q(t,e,r){return t&&e.includes(t)?t:r}function yt(t){return!!(typeof t=="object"&&t)}function Pt(t,{semaphore:e,rootProgressTracker:r,totalProgressWeight:s}){const n=r.stage((t.progress?.weight||1)/s),i={};for(const u of Object.keys(t)){let d=t[u];ct(d)&&(d=_.create(d,{semaphore:e})),i[u]=d}const o=async u=>{try{return n.fillSlowly(),await Ge[t.step](u,await bt(i),{tracker:n,initialCaption:t.progress?.caption})}finally{n.finish()}},a=X(i),l=X(i).filter(u=>u.isAsync),c=1/(l.length+1);for(const u of l)u.progress=n.stage(c);return{run:o,step:t,resources:a}}function X(t){const e=[];for(const r in t){const s=t[r];s instanceof _&&e.push(s)}return e}async function bt(t){const e={};for(const r in t){const s=t[r];s instanceof _?e[r]=await s.resolve():e[r]=s}return e}async function Oe(t,e){await t.run(e)}/**
99
+ `;this[h].ccall("wasm_set_phpini_entries",null,[f],[e])}this[h].ccall("php_wasm_init",null,[],[])}#s(){const e="/tmp/headers.json";if(!this.fileExists(e))throw new Error("SAPI Error: Could not find response headers file.");const r=JSON.parse(this.readFileAsText(e)),s={};for(const n of r.headers){if(!n.includes(": "))continue;const i=n.indexOf(": "),o=n.substring(0,i).toLowerCase(),a=n.substring(i+2);o in s||(s[o]=[]),s[o].push(a)}return{headers:s,httpStatusCode:r.status}}#i(e){if(this[h].ccall("wasm_set_request_uri",null,[f],[e]),e.includes("?")){const r=e.substring(e.indexOf("?")+1);this[h].ccall("wasm_set_query_string",null,[f],[r])}}#r(e,r){this[h].ccall("wasm_set_request_host",null,[f],[e]);let s;try{s=parseInt(new URL(e).port,10)}catch{}(!s||isNaN(s)||s===80)&&(s=r==="https"?443:80),this[h].ccall("wasm_set_request_port",null,[S],[s]),(r==="https"||!r&&s===443)&&this.addServerGlobalEntry("HTTPS","on")}#o(e){this[h].ccall("wasm_set_request_method",null,[f],[e])}#a(e){e.cookie&&this[h].ccall("wasm_set_cookies",null,[f],[e.cookie]),e["content-type"]&&this[h].ccall("wasm_set_content_type",null,[f],[e["content-type"]]),e["content-length"]&&this[h].ccall("wasm_set_content_length",null,[S],[parseInt(e["content-length"],10)]);for(const r in e)this.addServerGlobalEntry(`HTTP_${r.toUpperCase().replace(/-/g,"_")}`,e[r])}#c(e){this[h].ccall("wasm_set_request_body",null,[f],[e]),this[h].ccall("wasm_set_content_length",null,[S],[e.length])}#l(e){this[h].ccall("wasm_set_path_translated",null,[f],[e])}addServerGlobalEntry(e,r){this[h].ccall("wasm_add_SERVER_entry",null,[f,f],[e,r])}#u(e){const{key:r,name:s,type:n,data:i}=e,o=`/tmp/${Math.random().toFixed(20)}`;this.writeFile(o,i);const a=0;this[h].ccall("wasm_add_uploaded_file",null,[f,f,f,f,S,S],[r,s,n,o,a,i.byteLength])}#h(e){this[h].ccall("wasm_set_php_code",null,[f],[e])}async#d(){const e=await await this[h].ccall("wasm_sapi_handle_request",S,[],[]),{headers:r,httpStatusCode:s}=this.#s();return new v(s,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,r){this[h].FS.writeFile(e,r)}unlink(e){this[h].FS.unlink(e)}mv(e,r){this[h].FS.mv(e,r)}rmdir(e,r={recursive:!0}){r?.recursive&&this.listFiles(e).forEach(s=>{const n=`${e}/${s}`;this.isDir(n)?this.rmdir(n,r):this.unlink(n)}),this[h].FS.rmdir(e)}listFiles(e){if(!this.fileExists(e))return[];try{return this[h].FS.readdir(e).filter(r=>r!=="."&&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}}}w([m('Could not create directory "{path}"')],g.prototype,"mkdir",1);w([m('Could not create directory "{path}"')],g.prototype,"mkdirTree",1);w([m('Could not read "{path}"')],g.prototype,"readFileAsText",1);w([m('Could not read "{path}"')],g.prototype,"readFileAsBuffer",1);w([m('Could not write to "{path}"')],g.prototype,"writeFile",1);w([m('Could not unlink "{path}"')],g.prototype,"unlink",1);w([m('Could not move "{path}"')],g.prototype,"mv",1);w([m('Could not remove directory "{path}"')],g.prototype,"rmdir",1);w([m('Could not list files in "{path}"')],g.prototype,"listFiles",1);w([m('Could not stat "{path}"')],g.prototype,"isDir",1);w([m('Could not stat "{path}"')],g.prototype,"fileExists",1);function Fe(t){const e={};for(const r in t)e[r.toLowerCase()]=t[r];return e}const ht=["vfs","literal","wordpress.org/themes","wordpress.org/plugins","url"];function dt(t){return t&&typeof t=="object"&&typeof t.resource=="string"&&ht.includes(t.resource)}class _{static create(e,{semaphore:r,progress:s}){let n;switch(e.resource){case"vfs":n=new pt(e,s);break;case"literal":n=new ft(e,s);break;case"wordpress.org/themes":n=new yt(e,s);break;case"wordpress.org/plugins":n=new Pt(e,s);break;case"url":n=new wt(e,s);break;default:throw new Error(`Invalid resource: ${e}`)}return n=new bt(n),r&&(n=new _t(n,r)),n}setPlayground(e){this.playground=e}get isAsync(){return!1}}class pt extends _{constructor(e,r){super(),this.resource=e,this.progress=r}async resolve(){const e=await this.playground.readFileAsBuffer(this.resource.path);return this.progress?.set(100),new File([e],this.name)}get name(){return this.resource.path}}class ft extends _{constructor(e,r){super(),this.resource=e,this.progress=r}async resolve(){return this.progress?.set(100),new File([this.resource.contents],this.resource.name)}get name(){return this.resource.name}}class q extends _{constructor(e){super(),this.progress=e}async resolve(){this.progress?.setCaption(this.caption);const e=this.getURL();let r=await fetch(e);if(r=await Ze(r,this.progress?.loadingListener??mt),r.status!==200)throw new Error(`Could not download "${e}"`);return new File([await r.blob()],this.name)}get caption(){return`Downloading ${this.name}`}get name(){return this.getURL()}get isAsync(){return!0}}const mt=()=>{};class wt extends q{constructor(e,r){super(r),this.resource=e}getURL(){return this.resource.url}get caption(){return this.resource.caption??super.caption}}let M="/plugin-proxy";function gt(t){M=t}class yt extends q{constructor(e,r){super(r),this.resource=e}get name(){return L(this.resource.slug)}getURL(){const e=ke(this.resource.slug);return`${M}?theme=`+e}}class Pt extends q{constructor(e,r){super(r),this.resource=e}get name(){return L(this.resource.slug)}getURL(){const e=ke(this.resource.slug);return`${M}?plugin=`+e}}function ke(t){return!t||t.endsWith(".zip")?t:t+".latest-stable.zip"}class Oe extends _{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 bt extends Oe{async resolve(){return this.promise||(this.promise=super.resolve()),this.promise}}class _t extends Oe{constructor(e,r){super(e),this.semaphore=r}async resolve(){return this.isAsync?this.semaphore.run(()=>super.resolve()):super.resolve()}}const St=["6.2","6.1","6.0","5.9"];function Ue(t,{progress:e=new H,semaphore:r=new ge({concurrency:3}),onStepCompleted:s=()=>{}}={}){const n=(t.steps||[]).filter($t),i=n.reduce((a,l)=>a+(l.progress?.weight||1),0),o=n.map(a=>vt(a,{semaphore:r,rootProgressTracker:e,totalProgressWeight:i}));return{versions:{php:X(t.preferredVersions?.php,I,Ce),wp:X(t.preferredVersions?.wp,St,"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(t.landingPage||"/")}catch{}}finally{e.finish()}}}}function X(t,e,r){return t&&e.includes(t)?t:r}function $t(t){return!!(typeof t=="object"&&t)}function vt(t,{semaphore:e,rootProgressTracker:r,totalProgressWeight:s}){const n=r.stage((t.progress?.weight||1)/s),i={};for(const u of Object.keys(t)){let d=t[u];dt(d)&&(d=_.create(d,{semaphore:e})),i[u]=d}const o=async u=>{try{return n.fillSlowly(),await Qe[t.step](u,await Et(i),{tracker:n,initialCaption:t.progress?.caption})}finally{n.finish()}},a=Z(i),l=Z(i).filter(u=>u.isAsync),c=1/(l.length+1);for(const u of l)u.progress=n.stage(c);return{run:o,step:t,resources:a}}function Z(t){const e=[];for(const r in t){const s=t[r];s instanceof _&&e.push(s)}return e}async function Et(t){const e={};for(const r in t){const s=t[r];s instanceof _?e[r]=await s.resolve():e[r]=s}return e}async function Le(t,e){await t.run(e)}/**
100
100
  * @license
101
101
  * Copyright 2019 Google LLC
102
102
  * SPDX-License-Identifier: Apache-2.0
103
- */const Ue=Symbol("Comlink.proxy"),_t=Symbol("Comlink.endpoint"),St=Symbol("Comlink.releaseProxy"),N=Symbol("Comlink.finalizer"),F=Symbol("Comlink.thrown"),Le=t=>typeof t=="object"&&t!==null||typeof t=="function",$t={canHandle:t=>Le(t)&&t[Ue],serialize(t){const{port1:e,port2:r}=new MessageChannel;return M(t,e),[r,[r]]},deserialize(t){return t.start(),j(t)}},vt={canHandle:t=>Le(t)&&F in t,serialize({value:t}){let e;return t instanceof Error?e={isError:!0,value:{message:t.message,name:t.name,stack:t.stack}}:e={isError:!1,value:t},[e,[]]},deserialize(t){throw t.isError?Object.assign(new Error(t.value.message),t.value):t.value}},R=new Map([["proxy",$t],["throw",vt]]);function Et(t,e){for(const r of t)if(e===r||r==="*"||r instanceof RegExp&&r.test(e))return!0;return!1}function M(t,e=globalThis,r=["*"]){e.addEventListener("message",function s(n){if(!n||!n.data)return;if(!Et(r,n.origin)){console.warn(`Invalid origin '${n.origin}' for comlink proxy`);return}const{id:i,type:o,path:a}=Object.assign({path:[]},n.data),l=(n.data.argumentList||[]).map(P);let c;try{const u=a.slice(0,-1).reduce((p,y)=>p[y],t),d=a.reduce((p,y)=>p[y],t);switch(o){case"GET":c=d;break;case"SET":u[a.slice(-1)[0]]=P(n.data.value),c=!0;break;case"APPLY":c=d.apply(u,l);break;case"CONSTRUCT":{const p=new d(...l);c=kt(p)}break;case"ENDPOINT":{const{port1:p,port2:y}=new MessageChannel;M(t,y),c=Ct(p,[p])}break;case"RELEASE":c=void 0;break;default:return}}catch(u){c={value:u,[F]:0}}Promise.resolve(c).catch(u=>({value:u,[F]:0})).then(u=>{const[d,p]=U(u);e.postMessage(Object.assign(Object.assign({},d),{id:i}),p),o==="RELEASE"&&(e.removeEventListener("message",s),Ae(e),N in t&&typeof t[N]=="function"&&t[N]())}).catch(u=>{const[d,p]=U({value:new TypeError("Unserializable return value"),[F]:0});e.postMessage(Object.assign(Object.assign({},d),{id:i}),p)})}),e.start&&e.start()}function Rt(t){return t.constructor.name==="MessagePort"}function Ae(t){Rt(t)&&t.close()}function j(t,e){return W(t,[],e)}function x(t){if(t)throw new Error("Proxy has been released and is not useable")}function He(t){return $(t,{type:"RELEASE"}).then(()=>{Ae(t)})}const k=new WeakMap,O="FinalizationRegistry"in globalThis&&new FinalizationRegistry(t=>{const e=(k.get(t)||0)-1;k.set(t,e),e===0&&He(t)});function Tt(t,e){const r=(k.get(e)||0)+1;k.set(e,r),O&&O.register(t,e,t)}function xt(t){O&&O.unregister(t)}function W(t,e=[],r=function(){}){let s=!1;const n=new Proxy(r,{get(i,o){if(x(s),o===St)return()=>{xt(n),He(t),s=!0};if(o==="then"){if(e.length===0)return{then:()=>n};const a=$(t,{type:"GET",path:e.map(l=>l.toString())}).then(P);return a.then.bind(a)}return W(t,[...e,o])},set(i,o,a){x(s);const[l,c]=U(a);return $(t,{type:"SET",path:[...e,o].map(u=>u.toString()),value:l},c).then(P)},apply(i,o,a){x(s);const l=e[e.length-1];if(l===_t)return $(t,{type:"ENDPOINT"}).then(P);if(l==="bind")return W(t,e.slice(0,-1));const[c,u]=Z(a);return $(t,{type:"APPLY",path:e.map(d=>d.toString()),argumentList:c},u).then(P)},construct(i,o){x(s);const[a,l]=Z(o);return $(t,{type:"CONSTRUCT",path:e.map(c=>c.toString()),argumentList:a},l).then(P)}});return Tt(n,t),n}function Ft(t){return Array.prototype.concat.apply([],t)}function Z(t){const e=t.map(U);return[e.map(r=>r[0]),Ft(e.map(r=>r[1]))]}const Ie=new WeakMap;function Ct(t,e){return Ie.set(t,e),t}function kt(t){return Object.assign(t,{[Ue]:!0})}function Ot(t,e=globalThis,r="*"){return{postMessage:(s,n)=>t.postMessage(s,r,n),addEventListener:e.addEventListener.bind(e),removeEventListener:e.removeEventListener.bind(e)}}function U(t){for(const[e,r]of R)if(r.canHandle(t)){const[s,n]=r.serialize(t);return[{type:"HANDLER",name:e,value:s},n]}return[{type:"RAW",value:t},Ie.get(t)||[]]}function P(t){switch(t.type){case"HANDLER":return R.get(t.name).deserialize(t.value);case"RAW":return t.value}}function $(t,e,r){return new Promise(s=>{const n=Ut();t.addEventListener("message",function i(o){!o.data||!o.data.id||o.data.id!==n||(t.removeEventListener("message",i),s(o.data))}),t.start&&t.start(),t.postMessage(Object.assign({id:n},e),r)})}function Ut(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}function ze(t){Lt();const e=t instanceof Worker?t:Ot(t);return j(e)}function Lt(){R.set("EVENT",{canHandle:t=>t instanceof CustomEvent,serialize:t=>[{detail:t.detail},[]],deserialize:t=>t}),R.set("FUNCTION",{canHandle:t=>typeof t=="function",serialize(t){console.debug("[Comlink][Performance] Proxying a function");const{port1:e,port2:r}=new MessageChannel;return M(t,e),[r,[r]]},deserialize(t){return t.start(),j(t)}}),R.set("PHPResponse",{canHandle:t=>typeof t=="object"&&t!==null&&"headers"in t&&"bytes"in t&&"errors"in t&&"exitCode"in t&&"httpStatusCode"in t,serialize(t){return[t.toRawData(),[]]},deserialize(t){return v.fromRawData(t)}})}(function(){return typeof navigator<"u"&&navigator?.userAgent?.toLowerCase().indexOf("firefox")>-1?"iframe":"webworker"})();async function Ne({iframe:t,blueprint:e,remoteUrl:r,progressTracker:s=new H,disableProgressBar:n,onBlueprintStepCompleted:i}){if(At(r),r=te(r,{progressbar:!n}),s.setCaption("Preparing WordPress"),!e)return ee(t,r,s);const o=ke(e,{progress:s.stage(.5),onStepCompleted:i}),a=await ee(t,te(r,{php:o.versions.php,wp:o.versions.wp}),s);return await Oe(o,a),a}async function ee(t,e,r){await new Promise(n=>{t.src=e,t.addEventListener("load",n,!1)});const s=ze(t.contentWindow);return await s.isConnected(),r.pipe(s),await s.onDownloadProgress(r.stage().loadingListener),await s.isReady(),s}const C="https://playground.wordpress.net";function At(t){const e=new URL(t,C);if((e.origin===C||e.hostname==="localhost")&&e.pathname!=="/remote.html")throw new Error(`Invalid remote URL: ${e}. Expected origin to be ${C}/remote.html.`)}function te(t,e){const r=new URL(t,C),s=new URLSearchParams(r.search);for(const[n,i]of Object.entries(e))i!=null&&i!==!1&&s.set(n,i.toString());return r.search=s.toString(),r.toString()}async function Ht(t,e){if(console.warn("`connectPlayground` is deprecated and will be removed. Use `startPlayground` instead."),e?.loadRemote)return Ne({iframe:t,remoteUrl:e.loadRemote});const r=ze(t.contentWindow);return await r.isConnected(),r}exports.LatestSupportedPHPVersion=Te;exports.SupportedPHPVersions=I;exports.SupportedPHPVersionsList=Ye;exports.activatePlugin=re;exports.applyWordPressPatches=se;exports.compileBlueprint=ke;exports.connectPlayground=Ht;exports.cp=ce;exports.defineSiteUrl=fe;exports.importFile=ye;exports.installPlugin=be;exports.installTheme=_e;exports.login=Se;exports.mkdir=ue;exports.mv=le;exports.phpVar=b;exports.phpVars=A;exports.replaceSite=ge;exports.request=ae;exports.rm=he;exports.rmdir=de;exports.runBlueprintSteps=Oe;exports.runPHP=ne;exports.runPHPWithOptions=ie;exports.runWpInstallationWizard=$e;exports.setPhpIniEntry=oe;exports.setSiteOptions=ve;exports.startPlaygroundWeb=Ne;exports.unzip=q;exports.updateUserMeta=Ee;exports.writeFile=pe;exports.zipEntireSite=we;
103
+ */const Ae=Symbol("Comlink.proxy"),Rt=Symbol("Comlink.endpoint"),Tt=Symbol("Comlink.releaseProxy"),N=Symbol("Comlink.finalizer"),C=Symbol("Comlink.thrown"),He=t=>typeof t=="object"&&t!==null||typeof t=="function",xt={canHandle:t=>He(t)&&t[Ae],serialize(t){const{port1:e,port2:r}=new MessageChannel;return j(t,e),[r,[r]]},deserialize(t){return t.start(),B(t)}},Ct={canHandle:t=>He(t)&&C in t,serialize({value:t}){let e;return t instanceof Error?e={isError:!0,value:{message:t.message,name:t.name,stack:t.stack}}:e={isError:!1,value:t},[e,[]]},deserialize(t){throw t.isError?Object.assign(new Error(t.value.message),t.value):t.value}},R=new Map([["proxy",xt],["throw",Ct]]);function Ft(t,e){for(const r of t)if(e===r||r==="*"||r instanceof RegExp&&r.test(e))return!0;return!1}function j(t,e=globalThis,r=["*"]){e.addEventListener("message",function s(n){if(!n||!n.data)return;if(!Ft(r,n.origin)){console.warn(`Invalid origin '${n.origin}' for comlink proxy`);return}const{id:i,type:o,path:a}=Object.assign({path:[]},n.data),l=(n.data.argumentList||[]).map(P);let c;try{const u=a.slice(0,-1).reduce((p,y)=>p[y],t),d=a.reduce((p,y)=>p[y],t);switch(o){case"GET":c=d;break;case"SET":u[a.slice(-1)[0]]=P(n.data.value),c=!0;break;case"APPLY":c=d.apply(u,l);break;case"CONSTRUCT":{const p=new d(...l);c=We(p)}break;case"ENDPOINT":{const{port1:p,port2:y}=new MessageChannel;j(t,y),c=At(p,[p])}break;case"RELEASE":c=void 0;break;default:return}}catch(u){c={value:u,[C]:0}}Promise.resolve(c).catch(u=>({value:u,[C]:0})).then(u=>{const[d,p]=U(u);e.postMessage(Object.assign(Object.assign({},d),{id:i}),p),o==="RELEASE"&&(e.removeEventListener("message",s),Ie(e),N in t&&typeof t[N]=="function"&&t[N]())}).catch(u=>{const[d,p]=U({value:new TypeError("Unserializable return value"),[C]:0});e.postMessage(Object.assign(Object.assign({},d),{id:i}),p)})}),e.start&&e.start()}function kt(t){return t.constructor.name==="MessagePort"}function Ie(t){kt(t)&&t.close()}function B(t,e){return W(t,[],e)}function x(t){if(t)throw new Error("Proxy has been released and is not useable")}function ze(t){return $(t,{type:"RELEASE"}).then(()=>{Ie(t)})}const k=new WeakMap,O="FinalizationRegistry"in globalThis&&new FinalizationRegistry(t=>{const e=(k.get(t)||0)-1;k.set(t,e),e===0&&ze(t)});function Ot(t,e){const r=(k.get(e)||0)+1;k.set(e,r),O&&O.register(t,e,t)}function Ut(t){O&&O.unregister(t)}function W(t,e=[],r=function(){}){let s=!1;const n=new Proxy(r,{get(i,o){if(x(s),o===Tt)return()=>{Ut(n),ze(t),s=!0};if(o==="then"){if(e.length===0)return{then:()=>n};const a=$(t,{type:"GET",path:e.map(l=>l.toString())}).then(P);return a.then.bind(a)}return W(t,[...e,o])},set(i,o,a){x(s);const[l,c]=U(a);return $(t,{type:"SET",path:[...e,o].map(u=>u.toString()),value:l},c).then(P)},apply(i,o,a){x(s);const l=e[e.length-1];if(l===Rt)return $(t,{type:"ENDPOINT"}).then(P);if(l==="bind")return W(t,e.slice(0,-1));const[c,u]=ee(a);return $(t,{type:"APPLY",path:e.map(d=>d.toString()),argumentList:c},u).then(P)},construct(i,o){x(s);const[a,l]=ee(o);return $(t,{type:"CONSTRUCT",path:e.map(c=>c.toString()),argumentList:a},l).then(P)}});return Ot(n,t),n}function Lt(t){return Array.prototype.concat.apply([],t)}function ee(t){const e=t.map(U);return[e.map(r=>r[0]),Lt(e.map(r=>r[1]))]}const Ne=new WeakMap;function At(t,e){return Ne.set(t,e),t}function We(t){return Object.assign(t,{[Ae]:!0})}function Ht(t,e=globalThis,r="*"){return{postMessage:(s,n)=>t.postMessage(s,r,n),addEventListener:e.addEventListener.bind(e),removeEventListener:e.removeEventListener.bind(e)}}function U(t){for(const[e,r]of R)if(r.canHandle(t)){const[s,n]=r.serialize(t);return[{type:"HANDLER",name:e,value:s},n]}return[{type:"RAW",value:t},Ne.get(t)||[]]}function P(t){switch(t.type){case"HANDLER":return R.get(t.name).deserialize(t.value);case"RAW":return t.value}}function $(t,e,r){return new Promise(s=>{const n=It();t.addEventListener("message",function i(o){!o.data||!o.data.id||o.data.id!==n||(t.removeEventListener("message",i),s(o.data))}),t.start&&t.start(),t.postMessage(Object.assign({id:n},e),r)})}function It(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}function De(t){zt();const e=t instanceof Worker?t:Ht(t),r=B(e),s=qe(r);return new Proxy(s,{get:(n,i)=>i==="isConnected"?()=>r.isConnected():r[i]})}let te=!1;function zt(){te||(te=!0,R.set("EVENT",{canHandle:t=>t instanceof CustomEvent,serialize:t=>[{detail:t.detail},[]],deserialize:t=>t}),R.set("FUNCTION",{canHandle:t=>typeof t=="function",serialize(t){console.debug("[Comlink][Performance] Proxying a function");const{port1:e,port2:r}=new MessageChannel;return j(t,e),[r,[r]]},deserialize(t){return t.start(),B(t)}}),R.set("PHPResponse",{canHandle:t=>typeof t=="object"&&t!==null&&"headers"in t&&"bytes"in t&&"errors"in t&&"exitCode"in t&&"httpStatusCode"in t,serialize(t){return[t.toRawData(),[]]},deserialize(t){return v.fromRawData(t)}}))}function qe(t){return new Proxy(t,{get(e,r){switch(typeof e[r]){case"function":return(...s)=>e[r](...s);case"object":return e[r]===null?e[r]:qe(e[r]);case"undefined":case"number":case"string":return e[r];default:return We(e[r])}}})}(function(){return typeof navigator<"u"&&navigator?.userAgent?.toLowerCase().indexOf("firefox")>-1?"iframe":"webworker"})();async function Me({iframe:t,blueprint:e,remoteUrl:r,progressTracker:s=new H,disableProgressBar:n,onBlueprintStepCompleted:i}){if(Nt(r),r=se(r,{progressbar:!n}),s.setCaption("Preparing WordPress"),!e)return re(t,r,s);const o=Ue(e,{progress:s.stage(.5),onStepCompleted:i}),a=await re(t,se(r,{php:o.versions.php,wp:o.versions.wp}),s);return await Le(o,a),s.finish(),a}async function re(t,e,r){await new Promise(i=>{t.src=e,t.addEventListener("load",i,!1)});const s=De(t.contentWindow);await s.isConnected(),r.pipe(s);const n=r.stage();return await s.onDownloadProgress(n.loadingListener),await s.isReady(),n.finish(),s}const F="https://playground.wordpress.net";function Nt(t){const e=new URL(t,F);if((e.origin===F||e.hostname==="localhost")&&e.pathname!=="/remote.html")throw new Error(`Invalid remote URL: ${e}. Expected origin to be ${F}/remote.html.`)}function se(t,e){const r=new URL(t,F),s=new URLSearchParams(r.search);for(const[n,i]of Object.entries(e))i!=null&&i!==!1&&s.set(n,i.toString());return r.search=s.toString(),r.toString()}async function Wt(t,e){if(console.warn("`connectPlayground` is deprecated and will be removed. Use `startPlayground` instead."),e?.loadRemote)return Me({iframe:t,remoteUrl:e.loadRemote});const r=De(t.contentWindow);return await r.isConnected(),r}exports.LatestSupportedPHPVersion=Ce;exports.SupportedPHPVersions=I;exports.SupportedPHPVersionsList=et;exports.activatePlugin=ne;exports.applyWordPressPatches=ie;exports.compileBlueprint=Ue;exports.connectPlayground=Wt;exports.cp=ue;exports.defineSiteUrl=we;exports.importFile=be;exports.installPlugin=Se;exports.installTheme=$e;exports.login=ve;exports.mkdir=de;exports.mv=he;exports.phpVar=b;exports.phpVars=A;exports.replaceSite=Pe;exports.request=le;exports.rm=pe;exports.rmdir=fe;exports.runBlueprintSteps=Le;exports.runPHP=oe;exports.runPHPWithOptions=ae;exports.runWpInstallationWizard=Ee;exports.setPhpIniEntry=ce;exports.setPluginProxyURL=gt;exports.setSiteOptions=Re;exports.startPlaygroundWeb=Me;exports.unzip=D;exports.updateUserMeta=Te;exports.writeFile=me;exports.zipEntireSite=ye;
package/index.d.ts CHANGED
@@ -64,6 +64,7 @@ export interface ProgressReceiver {
64
64
  }
65
65
  declare class ProgressTracker extends EventTarget {
66
66
  private _selfWeight;
67
+ private _selfDone;
67
68
  private _selfProgress;
68
69
  private _selfCaption;
69
70
  private _weight;
@@ -299,7 +300,8 @@ export interface RequestHandler {
299
300
  */
300
301
  absoluteUrl: string;
301
302
  /**
302
- * The absolute URL of this PHPRequestHandler instance.
303
+ * The directory in the PHP filesystem where the server will look
304
+ * for the files to serve. Default: `/var/www`.
303
305
  */
304
306
  documentRoot: string;
305
307
  }
@@ -860,6 +862,7 @@ export declare class UrlResource extends FetchResource {
860
862
  /** @inheritDoc */
861
863
  protected get caption(): string;
862
864
  }
865
+ export declare function setPluginProxyURL(url: string): void;
863
866
  /**
864
867
  * A `Resource` that represents a WordPress core theme.
865
868
  */