@wp-playground/client 0.9.19 → 0.9.21

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,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ys=function(){var e;return typeof process<"u"&&((e=process.release)==null?void 0:e.name)==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"}();if(Ys==="NODE"){let e=function(r){return new Promise(function(n,s){r.onload=r.onerror=function(i){r.onload=r.onerror=null,i.type==="load"?n(r.result):s(new Error("Failed to read the blob/file"))}})},t=function(){const r=new Uint8Array([1,2,3,4]),s=new File([r],"test").stream();try{return s.getReader({mode:"byob"}),!0}catch{return!1}};if(typeof File>"u"){class r extends Blob{constructor(s,i,o){super(s);let u;o!=null&&o.lastModified&&(u=new Date),(!u||isNaN(u.getFullYear()))&&(u=new Date),this.lastModifiedDate=u,this.lastModified=u.getMilliseconds(),this.name=i||""}}global.File=r}typeof Blob.prototype.arrayBuffer>"u"&&(Blob.prototype.arrayBuffer=function(){const n=new FileReader;return n.readAsArrayBuffer(this),e(n)}),typeof Blob.prototype.text>"u"&&(Blob.prototype.text=function(){const n=new FileReader;return n.readAsText(this),e(n)}),(typeof Blob.prototype.stream>"u"||!t())&&(Blob.prototype.stream=function(){let r=0;const n=this;return new ReadableStream({type:"bytes",autoAllocateChunkSize:512*1024,async pull(s){const i=s.byobRequest.view,u=await n.slice(r,r+i.byteLength).arrayBuffer(),f=new Uint8Array(u);new Uint8Array(i.buffer).set(f);const l=f.byteLength;s.byobRequest.respond(l),r+=l,r>=n.size&&s.close()}})})}if(Ys==="NODE"&&typeof CustomEvent>"u"){class e extends Event{constructor(r,n={}){super(r,n),this.detail=n.detail}initCustomEvent(){}}globalThis.CustomEvent=e}const pn=["db.php","plugins/akismet","plugins/hello.php","plugins/wordpress-importer","mu-plugins/sqlite-database-integration","mu-plugins/playground-includes","mu-plugins/0-playground.php","mu-plugins/0-sqlite.php","themes/twentytwenty","themes/twentytwentyone","themes/twentytwentytwo","themes/twentytwentythree","themes/twentytwentyfour","themes/twentytwentyfive","themes/twentytwentysix"],Zs=Symbol("SleepFinished");function Do(e){return new Promise(t=>{setTimeout(()=>t(Zs),e)})}class Mo extends Error{constructor(){super("Acquiring lock timed out")}}class Lo{constructor({concurrency:t,timeout:r}){this._running=0,this.concurrency=t,this.timeout=r,this.queue=[]}get remaining(){return this.concurrency-this.running}get running(){return this._running}async acquire(){for(;;)if(this._running>=this.concurrency){const t=new Promise(r=>{this.queue.push(r)});this.timeout!==void 0?await Promise.race([t,Do(this.timeout)]).then(r=>{if(r===Zs)throw new Mo}):await t}else{this._running++;let t=!1;return()=>{t||(t=!0,this._running--,this.queue.length>0&&this.queue.shift()())}}}async run(t){const r=await this.acquire();try{return await t()}finally{r()}}}function de(...e){let t=e.join("/");const r=t[0]==="/",n=t.substring(t.length-1)==="/";return t=ei(t),!t&&!r&&(t="."),t&&n&&(t+="/"),t}function Xs(e){if(e==="/")return"/";e=ei(e);const t=e.lastIndexOf("/");return t===-1?"":t===0?"/":e.substr(0,t)}function ei(e){const t=e[0]==="/";return e=Fo(e.split("/").filter(r=>!!r),!t).join("/"),(t?"/":"")+e.replace(/\/$/,"")}function Fo(e,t){let r=0;for(let n=e.length-1;n>=0;n--){const s=e[n];s==="."?e.splice(n,1):s===".."?(e.splice(n,1),r++):r&&(e.splice(n,1),r--)}if(t)for(;r;r--)e.unshift("..");return e}function ti(e=36,t="!@#$%^&*()_+=-[]/.,<>?"){const r="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"+t;let n="";for(let s=e;s>0;--s)n+=r[Math.floor(Math.random()*r.length)];return n}function qo(){return ti(36,"-_")}function ae(e){return`json_decode(base64_decode('${Uo(JSON.stringify(e))}'), true)`}function Zt(e){const t={};for(const r in e)t[r]=ae(e[r]);return t}function Uo(e){return zo(new TextEncoder().encode(e))}function zo(e){const t=String.fromCodePoint(...e);return btoa(t)}const Vo="playground-log",_s=(e,...t)=>{he.dispatchEvent(new CustomEvent(Vo,{detail:{log:e,args:t}}))},Wo=(e,...t)=>{switch(typeof e.message=="string"?e.message=rn(e.message):e.message.message&&typeof e.message.message=="string"&&(e.message.message=rn(e.message.message)),e.severity){case"Debug":console.debug(e.message,...t);break;case"Info":console.info(e.message,...t);break;case"Warn":console.warn(e.message,...t);break;case"Error":console.error(e.message,...t);break;case"Fatal":console.error(e.message,...t);break;default:console.log(e.message,...t)}},xo=e=>e instanceof Error?[e.message,e.stack].join(`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ys=function(){var e;return typeof process<"u"&&((e=process.release)==null?void 0:e.name)==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"}();if(Ys==="NODE"){let e=function(r){return new Promise(function(n,s){r.onload=r.onerror=function(i){r.onload=r.onerror=null,i.type==="load"?n(r.result):s(new Error("Failed to read the blob/file"))}})},t=function(){const r=new Uint8Array([1,2,3,4]),s=new File([r],"test").stream();try{return s.getReader({mode:"byob"}),!0}catch{return!1}};if(typeof File>"u"){class r extends Blob{constructor(s,i,o){super(s);let u;o!=null&&o.lastModified&&(u=new Date),(!u||isNaN(u.getFullYear()))&&(u=new Date),this.lastModifiedDate=u,this.lastModified=u.getMilliseconds(),this.name=i||""}}global.File=r}typeof Blob.prototype.arrayBuffer>"u"&&(Blob.prototype.arrayBuffer=function(){const n=new FileReader;return n.readAsArrayBuffer(this),e(n)}),typeof Blob.prototype.text>"u"&&(Blob.prototype.text=function(){const n=new FileReader;return n.readAsText(this),e(n)}),(typeof Blob.prototype.stream>"u"||!t())&&(Blob.prototype.stream=function(){let r=0;const n=this;return new ReadableStream({type:"bytes",autoAllocateChunkSize:512*1024,async pull(s){const i=s.byobRequest.view,u=await n.slice(r,r+i.byteLength).arrayBuffer(),f=new Uint8Array(u);new Uint8Array(i.buffer).set(f);const l=f.byteLength;s.byobRequest.respond(l),r+=l,r>=n.size&&s.close()}})})}if(Ys==="NODE"&&typeof CustomEvent>"u"){class e extends Event{constructor(r,n={}){super(r,n),this.detail=n.detail}initCustomEvent(){}}globalThis.CustomEvent=e}const pn=["db.php","plugins/akismet","plugins/hello.php","plugins/wordpress-importer","mu-plugins/sqlite-database-integration","mu-plugins/playground-includes","mu-plugins/0-playground.php","mu-plugins/0-sqlite.php","themes/twentytwenty","themes/twentytwentyone","themes/twentytwentytwo","themes/twentytwentythree","themes/twentytwentyfour","themes/twentytwentyfive","themes/twentytwentysix"],Zs=Symbol("SleepFinished");function Do(e){return new Promise(t=>{setTimeout(()=>t(Zs),e)})}class Mo extends Error{constructor(){super("Acquiring lock timed out")}}class Lo{constructor({concurrency:t,timeout:r}){this._running=0,this.concurrency=t,this.timeout=r,this.queue=[]}get remaining(){return this.concurrency-this.running}get running(){return this._running}async acquire(){for(;;)if(this._running>=this.concurrency){const t=new Promise(r=>{this.queue.push(r)});this.timeout!==void 0?await Promise.race([t,Do(this.timeout)]).then(r=>{if(r===Zs)throw new Mo}):await t}else{this._running++;let t=!1;return()=>{t||(t=!0,this._running--,this.queue.length>0&&this.queue.shift()())}}}async run(t){const r=await this.acquire();try{return await t()}finally{r()}}}function de(...e){function t(i){return i.substring(i.length-1)==="/"}let r=e.join("/");const n=r[0]==="/",s=t(r);return r=ei(r),!r&&!n&&(r="."),r&&s&&!t(r)&&(r+="/"),r}function Xs(e){if(e==="/")return"/";e=ei(e);const t=e.lastIndexOf("/");return t===-1?"":t===0?"/":e.substr(0,t)}function ei(e){const t=e[0]==="/";return e=Fo(e.split("/").filter(r=>!!r),!t).join("/"),(t?"/":"")+e.replace(/\/$/,"")}function Fo(e,t){let r=0;for(let n=e.length-1;n>=0;n--){const s=e[n];s==="."?e.splice(n,1):s===".."?(e.splice(n,1),r++):r&&(e.splice(n,1),r--)}if(t)for(;r;r--)e.unshift("..");return e}function ti(e=36,t="!@#$%^&*()_+=-[]/.,<>?"){const r="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"+t;let n="";for(let s=e;s>0;--s)n+=r[Math.floor(Math.random()*r.length)];return n}function qo(){return ti(36,"-_")}function ae(e){return`json_decode(base64_decode('${Uo(JSON.stringify(e))}'), true)`}function Zt(e){const t={};for(const r in e)t[r]=ae(e[r]);return t}function Uo(e){return zo(new TextEncoder().encode(e))}function zo(e){const t=String.fromCodePoint(...e);return btoa(t)}const Vo="playground-log",_s=(e,...t)=>{he.dispatchEvent(new CustomEvent(Vo,{detail:{log:e,args:t}}))},Wo=(e,...t)=>{switch(typeof e.message=="string"?e.message=rn(e.message):e.message.message&&typeof e.message.message=="string"&&(e.message.message=rn(e.message.message)),e.severity){case"Debug":console.debug(e.message,...t);break;case"Info":console.info(e.message,...t);break;case"Warn":console.warn(e.message,...t);break;case"Error":console.error(e.message,...t);break;case"Fatal":console.error(e.message,...t);break;default:console.log(e.message,...t)}},xo=e=>e instanceof Error?[e.message,e.stack].join(`
2
2
  `):JSON.stringify(e,null,2),ri=[],ws=e=>{ri.push(e)},tn=e=>{if(e.raw===!0)ws(e.message);else{const t=Go(typeof e.message=="object"?xo(e.message):e.message,e.severity??"Info",e.prefix??"JavaScript");ws(t)}};class Ho extends EventTarget{constructor(t=[]){super(),this.handlers=t,this.fatalErrorEvent="playground-fatal-error"}getLogs(){return this.handlers.includes(tn)?[...ri]:(this.error(`Logs aren't stored because the logToMemory handler isn't registered.
3
3
  If you're using a custom logger instance, make sure to register logToMemory handler.
4
4
  `),[])}logMessage(t,...r){for(const n of this.handlers)n(t,...r)}log(t,...r){this.logMessage({message:t,severity:void 0,prefix:"JavaScript",raw:!1},...r)}debug(t,...r){this.logMessage({message:t,severity:"Debug",prefix:"JavaScript",raw:!1},...r)}info(t,...r){this.logMessage({message:t,severity:"Info",prefix:"JavaScript",raw:!1},...r)}warn(t,...r){this.logMessage({message:t,severity:"Warn",prefix:"JavaScript",raw:!1},...r)}error(t,...r){this.logMessage({message:t,severity:"Error",prefix:"JavaScript",raw:!1},...r)}}const Bo=()=>{try{if(process.env.NODE_ENV==="test")return[tn,_s]}catch{}return[tn,Wo,_s]},he=new Ho(Bo()),rn=e=>e.replace(/\t/g,""),Go=(e,t,r)=>{const n=new Date,s=new Intl.DateTimeFormat("en-GB",{year:"numeric",month:"short",day:"2-digit",timeZone:"UTC"}).format(n).replace(/ /g,"-"),i=new Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1,timeZone:"UTC",timeZoneName:"short"}).format(n),o=s+" "+i;return e=rn(e),`[${o}] ${r} ${t}: ${e}`};let xr=0;const vs="/wordpress/wp-content/debug.log",Ko=async e=>await e.fileExists(vs)?await e.readFileAsText(vs):"",Jo=(e,t)=>{t.addEventListener("request.end",async()=>{const r=await Ko(t);if(r.length>xr){const n=r.substring(xr);e.logMessage({message:n,raw:!0}),xr=r.length}}),t.addEventListener("request.error",r=>{r=r,r.error&&(e.logMessage({message:`${r.error.message} ${r.error.stack}`,severity:"Fatal",prefix:r.source==="request"?"PHP":"WASM Crash"}),e.dispatchEvent(new CustomEvent(e.fatalErrorEvent,{detail:{logs:e.getLogs(),source:r.source}})))})},Ar=async(e,{pluginPath:t,pluginName:r},n)=>{n==null||n.tracker.setCaption(`Activating ${r||t}`);const s=await e.documentRoot,i=await e.run({code:`<?php
@@ -529,8 +529,8 @@ echo json_encode($deactivated_plugins);
529
529
 
530
530
  // Publish the changeset, which publishes the starter content.
531
531
  wp_publish_post( $wp_customize->changeset_post_id() );
532
- `})},Hr="/tmp/file.zip",hi=async(e,t,r)=>{if(t instanceof File){const s=t;t=Hr,await e.writeFile(t,new Uint8Array(await s.arrayBuffer()))}const n=Zt({zipPath:t,extractToPath:r});await e.run({code:`<?php
533
- function unzip($zipPath, $extractTo, $overwrite = true)
532
+ `})},Hr="/tmp/file.zip",hi=async(e,t,r,n=!0)=>{if(t instanceof File){const i=t;t=Hr,await e.writeFile(t,new Uint8Array(await i.arrayBuffer()))}const s=Zt({zipPath:t,extractToPath:r,overwriteFiles:n});await e.run({code:`<?php
533
+ function unzip($zipPath, $extractTo, $overwriteFiles = true)
534
534
  {
535
535
  if (!is_dir($extractTo)) {
536
536
  mkdir($extractTo, 0777, true);
@@ -538,14 +538,23 @@ echo json_encode($deactivated_plugins);
538
538
  $zip = new ZipArchive;
539
539
  $res = $zip->open($zipPath);
540
540
  if ($res === TRUE) {
541
- $zip->extractTo($extractTo);
542
- $zip->close();
543
- chmod($extractTo, 0777);
541
+ for ($i = 0; $i < $zip->numFiles; $i++) {
542
+ $filename = $zip->getNameIndex($i);
543
+ $fileinfo = pathinfo($filename);
544
+ $extractFilePath = rtrim($extractTo, '/') . '/' . $filename;
545
+ // Check if file exists and $overwriteFiles is false
546
+ if (!file_exists($extractFilePath) || $overwriteFiles) {
547
+ // Extract file
548
+ $zip->extractTo($extractTo, $filename);
549
+ }
550
+ }
551
+ $zip->close();
552
+ chmod($extractTo, 0777);
544
553
  } else {
545
554
  throw new Exception("Could not unzip file");
546
555
  }
547
556
  }
548
- unzip(${n.zipPath}, ${n.extractToPath});
557
+ unzip(${s.zipPath}, ${s.extractToPath}, ${s.overwriteFiles});
549
558
  `}),await e.fileExists(Hr)&&await e.unlink(Hr)},Dr=async(e,{zipFile:t,zipPath:r,extractToPath:n})=>{if(r)he.warn('The "zipPath" option of the unzip() Blueprint step is deprecated and will be removed. Use "zipFile" instead.');else if(!t)throw new Error("Either zipPath or zipFile must be provided");await hi(e,t||r,n)},mi=async(e,{wordPressFilesZip:t,pathInZip:r=""})=>{const n=await e.documentRoot;let s=de("/tmp","import");await e.mkdir(s),await Dr(e,{zipFile:t,extractToPath:s}),s=de(s,r);const i=de(s,"wp-content"),o=de(n,"wp-content");for(const d of pn){const p=de(i,d);await bs(e,p);const _=de(o,d);await e.fileExists(_)&&(await e.mkdir(Xs(p)),await e.mv(_,p))}const u=de(s,"wp-content","database");await e.fileExists(u)||await e.mv(de(n,"wp-content","database"),u);const f=await e.listFiles(s);for(const d of f)await bs(e,de(n,d)),await e.mv(de(s,d),de(n,d));await e.rmdir(s),await $n(e,{siteUrl:await e.absoluteUrl});const l=ae(de(n,"wp-admin","upgrade.php"));await e.run({code:`<?php
550
559
  $_GET['step'] = 'upgrade_db';
551
560
  require ${l};
@@ -729,4 +738,4 @@ for existing apps using this option.`}},required:["consts","step"]},{type:"objec
729
738
  * @license
730
739
  * Copyright 2019 Google LLC
731
740
  * SPDX-License-Identifier: Apache-2.0
732
- */const mo=Symbol("Comlink.proxy"),Id=Symbol("Comlink.endpoint"),jd=Symbol("Comlink.releaseProxy"),Xr=Symbol("Comlink.finalizer"),wr=Symbol("Comlink.thrown"),yo=e=>typeof e=="object"&&e!==null||typeof e=="function",Ad={canHandle:e=>yo(e)&&e[mo],serialize(e){const{port1:t,port2:r}=new MessageChannel;return is(e,t),[r,[r]]},deserialize(e){return e.start(),os(e)}},Dd={canHandle:e=>yo(e)&&wr in e,serialize({value:e}){let t;return e instanceof Error?t={isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:t={isError:!1,value:e},[t,[]]},deserialize(e){throw e.isError?Object.assign(new Error(e.value.message),e.value):e.value}},Tt=new Map([["proxy",Ad],["throw",Dd]]);function Md(e,t){for(const r of e)if(t===r||r==="*"||r instanceof RegExp&&r.test(t))return!0;return!1}function is(e,t=globalThis,r=["*"]){t.addEventListener("message",function n(s){if(!s||!s.data)return;if(!Md(r,s.origin)){console.warn(`Invalid origin '${s.origin}' for comlink proxy`);return}const{id:i,type:o,path:u}=Object.assign({path:[]},s.data),f=(s.data.argumentList||[]).map(lt);let l;try{const d=u.slice(0,-1).reduce((_,b)=>_[b],e),p=u.reduce((_,b)=>_[b],e);switch(o){case"GET":l=p;break;case"SET":d[u.slice(-1)[0]]=lt(s.data.value),l=!0;break;case"APPLY":l=p.apply(d,f);break;case"CONSTRUCT":{const _=new p(...f);l=wo(_)}break;case"ENDPOINT":{const{port1:_,port2:b}=new MessageChannel;is(e,b),l=zd(_,[_])}break;case"RELEASE":l=void 0;break;default:return}}catch(d){l={value:d,[wr]:0}}Promise.resolve(l).catch(d=>({value:d,[wr]:0})).then(d=>{const[p,_]=jr(d);t.postMessage(Object.assign(Object.assign({},p),{id:i}),_),o==="RELEASE"&&(t.removeEventListener("message",n),go(t),Xr in e&&typeof e[Xr]=="function"&&e[Xr]())}).catch(d=>{const[p,_]=jr({value:new TypeError("Unserializable return value"),[wr]:0});t.postMessage(Object.assign(Object.assign({},p),{id:i}),_)})}),t.start&&t.start()}function Ld(e){return e.constructor.name==="MessagePort"}function go(e){Ld(e)&&e.close()}function os(e,t){return fn(e,[],t)}function hr(e){if(e)throw new Error("Proxy has been released and is not useable")}function $o(e){return St(e,{type:"RELEASE"}).then(()=>{go(e)})}const Nr=new WeakMap,Ir="FinalizationRegistry"in globalThis&&new FinalizationRegistry(e=>{const t=(Nr.get(e)||0)-1;Nr.set(e,t),t===0&&$o(e)});function Fd(e,t){const r=(Nr.get(t)||0)+1;Nr.set(t,r),Ir&&Ir.register(e,t,e)}function qd(e){Ir&&Ir.unregister(e)}function fn(e,t=[],r=function(){}){let n=!1;const s=new Proxy(r,{get(i,o){if(hr(n),o===jd)return()=>{qd(s),$o(e),n=!0};if(o==="then"){if(t.length===0)return{then:()=>s};const u=St(e,{type:"GET",path:t.map(f=>f.toString())}).then(lt);return u.then.bind(u)}return fn(e,[...t,o])},set(i,o,u){hr(n);const[f,l]=jr(u);return St(e,{type:"SET",path:[...t,o].map(d=>d.toString()),value:f},l).then(lt)},apply(i,o,u){hr(n);const f=t[t.length-1];if(f===Id)return St(e,{type:"ENDPOINT"}).then(lt);if(f==="bind")return fn(e,t.slice(0,-1));const[l,d]=Ks(u);return St(e,{type:"APPLY",path:t.map(p=>p.toString()),argumentList:l},d).then(lt)},construct(i,o){hr(n);const[u,f]=Ks(o);return St(e,{type:"CONSTRUCT",path:t.map(l=>l.toString()),argumentList:u},f).then(lt)}});return Fd(s,e),s}function Ud(e){return Array.prototype.concat.apply([],e)}function Ks(e){const t=e.map(jr);return[t.map(r=>r[0]),Ud(t.map(r=>r[1]))]}const _o=new WeakMap;function zd(e,t){return _o.set(e,t),e}function wo(e){return Object.assign(e,{[mo]:!0})}function Vd(e,t=globalThis,r="*"){return{postMessage:(n,s)=>e.postMessage(n,r,s),addEventListener:t.addEventListener.bind(t),removeEventListener:t.removeEventListener.bind(t)}}function jr(e){for(const[t,r]of Tt)if(r.canHandle(e)){const[n,s]=r.serialize(e);return[{type:"HANDLER",name:t,value:n},s]}return[{type:"RAW",value:e},_o.get(e)||[]]}function lt(e){switch(e.type){case"HANDLER":return Tt.get(e.name).deserialize(e.value);case"RAW":return e.value}}function St(e,t,r){return new Promise(n=>{const s=Wd();e.addEventListener("message",function i(o){!o.data||!o.data.id||o.data.id!==s||(e.removeEventListener("message",i),n(o.data))}),e.start&&e.start(),e.postMessage(Object.assign({id:s},t),r)})}function Wd(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}function vo(e,t=void 0){Hd();const r=e instanceof Worker?e:Vd(e,t),n=os(r),s=bo(n);return new Proxy(s,{get:(i,o)=>o==="isConnected"?async()=>{for(;;)try{await xd(n.isConnected(),200);break}catch{}}:n[o]})}async function xd(e,t){return new Promise((r,n)=>{setTimeout(n,t),e.then(r)})}let Js=!1;function Hd(){if(Js)return;Js=!0,Tt.set("EVENT",{canHandle:r=>r instanceof CustomEvent,serialize:r=>[{detail:r.detail},[]],deserialize:r=>r}),Tt.set("FUNCTION",{canHandle:r=>typeof r=="function",serialize(r){const{port1:n,port2:s}=new MessageChannel;return is(r,n),[s,[s]]},deserialize(r){return r.start(),os(r)}}),Tt.set("PHPResponse",{canHandle:r=>typeof r=="object"&&r!==null&&"headers"in r&&"bytes"in r&&"errors"in r&&"exitCode"in r&&"httpStatusCode"in r,serialize(r){return[r.toRawData(),[]]},deserialize(r){return Sr.fromRawData(r)}});const e=Tt.get("throw"),t=e==null?void 0:e.serialize;e.serialize=({value:r})=>{const n=t({value:r});return r.response&&(n[0].value.response=r.response),r.source&&(n[0].value.source=r.source),n}}function bo(e){return new Proxy(e,{get(t,r){switch(typeof t[r]){case"function":return(...n)=>t[r](...n);case"object":return t[r]===null?t[r]:bo(t[r]);case"undefined":case"number":case"string":return t[r];default:return wo(t[r])}}})}async function Eo({iframe:e,blueprint:t,remoteUrl:r,progressTracker:n=new Lr,disableProgressBar:s,onBlueprintStepCompleted:i,onClientConnected:o=()=>{},sapiName:u,onBeforeBlueprint:f,siteSlug:l}){if(Gd(r),Bd(e),r=en(r,{progressbar:!s}),n.setCaption("Preparing WordPress"),!t){const _=await Qs(e,en(r,{"php-extension":"kitchen-sink","site-slug":l}),n);return o(_),_}const d=po(t,{progress:n.stage(.5),onStepCompleted:i}),p=await Qs(e,en(r,{php:d.versions.php,wp:d.versions.wp,"sapi-name":u,"php-extension":d.phpExtensions,networking:d.features.networking?"yes":"no","site-slug":l}),n);return Jo(he,p),o(p),f&&await f(),await ho(d,p),n.finish(),p}function Bd(e){var t,r;(t=e.sandbox)!=null&&t.length&&!((r=e.sandbox)!=null&&r.contains("allow-storage-access-by-user-activation"))&&e.sandbox.add("allow-storage-access-by-user-activation")}async function Qs(e,t,r){await new Promise(i=>{e.src=t,e.addEventListener("load",i,!1)});const n=vo(e.contentWindow,e.ownerDocument.defaultView);await n.isConnected(),r.pipe(n);const s=r.stage();return await n.onDownloadProgress(s.loadingListener),await n.isReady(),s.finish(),n}const vr="https://playground.wordpress.net";function Gd(e){const t=new URL(e,vr);if((t.origin===vr||t.hostname==="localhost")&&t.pathname!=="/remote.html")throw new Error(`Invalid remote URL: ${t}. Expected origin to be ${vr}/remote.html.`)}function en(e,t){const r=new URL(e,vr),n=new URLSearchParams(r.search);for(const[s,i]of Object.entries(t))if(i!=null&&i!==!1)if(Array.isArray(i))for(const o of i)n.append(s,o.toString());else n.set(s,i.toString());return r.search=n.toString(),r.toString()}async function Kd(e,t){if(he.warn("`connectPlayground` is deprecated and will be removed. Use `startPlayground` instead."),t!=null&&t.loadRemote)return Eo({iframe:e,remoteUrl:t.loadRemote});const r=vo(e.contentWindow,e.ownerDocument.defaultView);return await r.isConnected(),r}exports.LatestSupportedPHPVersion=Ri;exports.SupportedPHPVersions=Fr;exports.SupportedPHPVersionsList=ha;exports.activatePlugin=Ar;exports.activateTheme=hn;exports.compileBlueprint=po;exports.connectPlayground=Kd;exports.cp=li;exports.defineSiteUrl=$n;exports.defineWpConfigConsts=Qt;exports.enableMultisite=ci;exports.exportWXR=yi;exports.importThemeStarterContent=_n;exports.importWordPressFiles=mi;exports.importWxr=pi;exports.installPlugin=$i;exports.installTheme=_i;exports.login=Er;exports.mkdir=di;exports.mv=ui;exports.phpVar=ae;exports.phpVars=Zt;exports.request=br;exports.resetData=wi;exports.rm=mn;exports.rmdir=fi;exports.runBlueprintSteps=ho;exports.runPHP=ni;exports.runPHPWithOptions=si;exports.runSql=ii;exports.runWpInstallationWizard=vi;exports.setPhpIniEntries=pa;exports.setPluginProxyURL=Nd;exports.setSiteLanguage=Pi;exports.setSiteOptions=yn;exports.startPlaygroundWeb=Eo;exports.unzip=Dr;exports.updateUserMeta=oi;exports.wpCLI=Ei;exports.wpContentFilesExcludedFromExport=pn;exports.writeFile=gn;exports.zipWpContent=bi;
741
+ */const mo=Symbol("Comlink.proxy"),Id=Symbol("Comlink.endpoint"),jd=Symbol("Comlink.releaseProxy"),Xr=Symbol("Comlink.finalizer"),wr=Symbol("Comlink.thrown"),yo=e=>typeof e=="object"&&e!==null||typeof e=="function",Ad={canHandle:e=>yo(e)&&e[mo],serialize(e){const{port1:t,port2:r}=new MessageChannel;return is(e,t),[r,[r]]},deserialize(e){return e.start(),os(e)}},Dd={canHandle:e=>yo(e)&&wr in e,serialize({value:e}){let t;return e instanceof Error?t={isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:t={isError:!1,value:e},[t,[]]},deserialize(e){throw e.isError?Object.assign(new Error(e.value.message),e.value):e.value}},Tt=new Map([["proxy",Ad],["throw",Dd]]);function Md(e,t){for(const r of e)if(t===r||r==="*"||r instanceof RegExp&&r.test(t))return!0;return!1}function is(e,t=globalThis,r=["*"]){t.addEventListener("message",function n(s){if(!s||!s.data)return;if(!Md(r,s.origin)){console.warn(`Invalid origin '${s.origin}' for comlink proxy`);return}const{id:i,type:o,path:u}=Object.assign({path:[]},s.data),f=(s.data.argumentList||[]).map(lt);let l;try{const d=u.slice(0,-1).reduce((_,b)=>_[b],e),p=u.reduce((_,b)=>_[b],e);switch(o){case"GET":l=p;break;case"SET":d[u.slice(-1)[0]]=lt(s.data.value),l=!0;break;case"APPLY":l=p.apply(d,f);break;case"CONSTRUCT":{const _=new p(...f);l=wo(_)}break;case"ENDPOINT":{const{port1:_,port2:b}=new MessageChannel;is(e,b),l=zd(_,[_])}break;case"RELEASE":l=void 0;break;default:return}}catch(d){l={value:d,[wr]:0}}Promise.resolve(l).catch(d=>({value:d,[wr]:0})).then(d=>{const[p,_]=jr(d);t.postMessage(Object.assign(Object.assign({},p),{id:i}),_),o==="RELEASE"&&(t.removeEventListener("message",n),go(t),Xr in e&&typeof e[Xr]=="function"&&e[Xr]())}).catch(d=>{const[p,_]=jr({value:new TypeError("Unserializable return value"),[wr]:0});t.postMessage(Object.assign(Object.assign({},p),{id:i}),_)})}),t.start&&t.start()}function Ld(e){return e.constructor.name==="MessagePort"}function go(e){Ld(e)&&e.close()}function os(e,t){return fn(e,[],t)}function hr(e){if(e)throw new Error("Proxy has been released and is not useable")}function $o(e){return St(e,{type:"RELEASE"}).then(()=>{go(e)})}const Nr=new WeakMap,Ir="FinalizationRegistry"in globalThis&&new FinalizationRegistry(e=>{const t=(Nr.get(e)||0)-1;Nr.set(e,t),t===0&&$o(e)});function Fd(e,t){const r=(Nr.get(t)||0)+1;Nr.set(t,r),Ir&&Ir.register(e,t,e)}function qd(e){Ir&&Ir.unregister(e)}function fn(e,t=[],r=function(){}){let n=!1;const s=new Proxy(r,{get(i,o){if(hr(n),o===jd)return()=>{qd(s),$o(e),n=!0};if(o==="then"){if(t.length===0)return{then:()=>s};const u=St(e,{type:"GET",path:t.map(f=>f.toString())}).then(lt);return u.then.bind(u)}return fn(e,[...t,o])},set(i,o,u){hr(n);const[f,l]=jr(u);return St(e,{type:"SET",path:[...t,o].map(d=>d.toString()),value:f},l).then(lt)},apply(i,o,u){hr(n);const f=t[t.length-1];if(f===Id)return St(e,{type:"ENDPOINT"}).then(lt);if(f==="bind")return fn(e,t.slice(0,-1));const[l,d]=Ks(u);return St(e,{type:"APPLY",path:t.map(p=>p.toString()),argumentList:l},d).then(lt)},construct(i,o){hr(n);const[u,f]=Ks(o);return St(e,{type:"CONSTRUCT",path:t.map(l=>l.toString()),argumentList:u},f).then(lt)}});return Fd(s,e),s}function Ud(e){return Array.prototype.concat.apply([],e)}function Ks(e){const t=e.map(jr);return[t.map(r=>r[0]),Ud(t.map(r=>r[1]))]}const _o=new WeakMap;function zd(e,t){return _o.set(e,t),e}function wo(e){return Object.assign(e,{[mo]:!0})}function Vd(e,t=globalThis,r="*"){return{postMessage:(n,s)=>e.postMessage(n,r,s),addEventListener:t.addEventListener.bind(t),removeEventListener:t.removeEventListener.bind(t)}}function jr(e){for(const[t,r]of Tt)if(r.canHandle(e)){const[n,s]=r.serialize(e);return[{type:"HANDLER",name:t,value:n},s]}return[{type:"RAW",value:e},_o.get(e)||[]]}function lt(e){switch(e.type){case"HANDLER":return Tt.get(e.name).deserialize(e.value);case"RAW":return e.value}}function St(e,t,r){return new Promise(n=>{const s=Wd();e.addEventListener("message",function i(o){!o.data||!o.data.id||o.data.id!==s||(e.removeEventListener("message",i),n(o.data))}),e.start&&e.start(),e.postMessage(Object.assign({id:s},t),r)})}function Wd(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}function vo(e,t=void 0){Hd();const r=e instanceof Worker?e:Vd(e,t),n=os(r),s=bo(n);return new Proxy(s,{get:(i,o)=>o==="isConnected"?async()=>{for(;;)try{await xd(n.isConnected(),200);break}catch{}}:n[o]})}async function xd(e,t){return new Promise((r,n)=>{setTimeout(n,t),e.then(r)})}let Js=!1;function Hd(){if(Js)return;Js=!0,Tt.set("EVENT",{canHandle:r=>r instanceof CustomEvent,serialize:r=>[{detail:r.detail},[]],deserialize:r=>r}),Tt.set("FUNCTION",{canHandle:r=>typeof r=="function",serialize(r){const{port1:n,port2:s}=new MessageChannel;return is(r,n),[s,[s]]},deserialize(r){return r.start(),os(r)}}),Tt.set("PHPResponse",{canHandle:r=>typeof r=="object"&&r!==null&&"headers"in r&&"bytes"in r&&"errors"in r&&"exitCode"in r&&"httpStatusCode"in r,serialize(r){return[r.toRawData(),[]]},deserialize(r){return Sr.fromRawData(r)}});const e=Tt.get("throw"),t=e==null?void 0:e.serialize;e.serialize=({value:r})=>{const n=t({value:r});return r.response&&(n[0].value.response=r.response),r.source&&(n[0].value.source=r.source),n}}function bo(e){return new Proxy(e,{get(t,r){switch(typeof t[r]){case"function":return(...n)=>t[r](...n);case"object":return t[r]===null?t[r]:bo(t[r]);case"undefined":case"number":case"string":return t[r];default:return wo(t[r])}}})}new Promise(e=>{});async function Eo({iframe:e,blueprint:t,remoteUrl:r,progressTracker:n=new Lr,disableProgressBar:s,onBlueprintStepCompleted:i,onClientConnected:o=()=>{},sapiName:u,onBeforeBlueprint:f,siteSlug:l}){if(Gd(r),Bd(e),r=en(r,{progressbar:!s}),n.setCaption("Preparing WordPress"),!t){const _=await Qs(e,en(r,{"php-extension":"kitchen-sink","site-slug":l}),n);return o(_),_}const d=po(t,{progress:n.stage(.5),onStepCompleted:i}),p=await Qs(e,en(r,{php:d.versions.php,wp:d.versions.wp,"sapi-name":u,"php-extension":d.phpExtensions,networking:d.features.networking?"yes":"no","site-slug":l}),n);return Jo(he,p),o(p),f&&await f(),await ho(d,p),n.finish(),p}function Bd(e){var t,r;(t=e.sandbox)!=null&&t.length&&!((r=e.sandbox)!=null&&r.contains("allow-storage-access-by-user-activation"))&&e.sandbox.add("allow-storage-access-by-user-activation")}async function Qs(e,t,r){await new Promise(i=>{e.src=t,e.addEventListener("load",i,!1)});const n=vo(e.contentWindow,e.ownerDocument.defaultView);await n.isConnected(),r.pipe(n);const s=r.stage();return await n.onDownloadProgress(s.loadingListener),await n.isReady(),s.finish(),n}const vr="https://playground.wordpress.net";function Gd(e){const t=new URL(e,vr);if((t.origin===vr||t.hostname==="localhost")&&t.pathname!=="/remote.html")throw new Error(`Invalid remote URL: ${t}. Expected origin to be ${vr}/remote.html.`)}function en(e,t){const r=new URL(e,vr),n=new URLSearchParams(r.search);for(const[s,i]of Object.entries(t))if(i!=null&&i!==!1)if(Array.isArray(i))for(const o of i)n.append(s,o.toString());else n.set(s,i.toString());return r.search=n.toString(),r.toString()}async function Kd(e,t){if(he.warn("`connectPlayground` is deprecated and will be removed. Use `startPlayground` instead."),t!=null&&t.loadRemote)return Eo({iframe:e,remoteUrl:t.loadRemote});const r=vo(e.contentWindow,e.ownerDocument.defaultView);return await r.isConnected(),r}exports.LatestSupportedPHPVersion=Ri;exports.SupportedPHPVersions=Fr;exports.SupportedPHPVersionsList=ha;exports.activatePlugin=Ar;exports.activateTheme=hn;exports.compileBlueprint=po;exports.connectPlayground=Kd;exports.cp=li;exports.defineSiteUrl=$n;exports.defineWpConfigConsts=Qt;exports.enableMultisite=ci;exports.exportWXR=yi;exports.importThemeStarterContent=_n;exports.importWordPressFiles=mi;exports.importWxr=pi;exports.installPlugin=$i;exports.installTheme=_i;exports.login=Er;exports.mkdir=di;exports.mv=ui;exports.phpVar=ae;exports.phpVars=Zt;exports.request=br;exports.resetData=wi;exports.rm=mn;exports.rmdir=fi;exports.runBlueprintSteps=ho;exports.runPHP=ni;exports.runPHPWithOptions=si;exports.runSql=ii;exports.runWpInstallationWizard=vi;exports.setPhpIniEntries=pa;exports.setPluginProxyURL=Nd;exports.setSiteLanguage=Pi;exports.setSiteOptions=yn;exports.startPlaygroundWeb=Eo;exports.unzip=Dr;exports.updateUserMeta=oi;exports.wpCLI=Ei;exports.wpContentFilesExcludedFromExport=pn;exports.writeFile=gn;exports.zipWpContent=bi;
package/index.d.ts CHANGED
@@ -2593,6 +2593,7 @@ declare class PlaygroundWorkerEndpoint extends PHPWorker {
2593
2593
  all: {
2594
2594
  nightly: string;
2595
2595
  beta: string;
2596
+ "6.6": string;
2596
2597
  "6.5": string;
2597
2598
  "6.4": string;
2598
2599
  "6.3": string;
@@ -2605,6 +2606,7 @@ declare class PlaygroundWorkerEndpoint extends PHPWorker {
2605
2606
  bindOpfs(options: Omit<BindOpfsOptions, "php" | "onProgress">, onProgress?: SyncProgressCallback): Promise<void>;
2606
2607
  journalFSEvents(root: string, callback: (op: FilesystemOperation) => void): Promise<() => any>;
2607
2608
  replayFSJournal(events: FilesystemOperation[]): Promise<void>;
2609
+ backfillStaticFilesRemovedFromMinifiedBuild(): Promise<void>;
2608
2610
  }
2609
2611
  export interface ProgressBarOptions {
2610
2612
  caption?: string;
@@ -2649,6 +2651,7 @@ export interface WebClientMixin extends ProgressReceiver {
2649
2651
  replayFSJournal: PlaygroundWorkerEndpoint["replayFSJournal"];
2650
2652
  addEventListener: PlaygroundWorkerEndpoint["addEventListener"];
2651
2653
  removeEventListener: PlaygroundWorkerEndpoint["removeEventListener"];
2654
+ backfillStaticFilesRemovedFromMinifiedBuild: PlaygroundWorkerEndpoint["backfillStaticFilesRemovedFromMinifiedBuild"];
2652
2655
  /** @inheritDoc @php-wasm/universal!UniversalPHP.onMessage */
2653
2656
  onMessage: PlaygroundWorkerEndpoint["onMessage"];
2654
2657
  bindOpfs(options: Omit<BindOpfsOptions, "php" | "onProgress">, onProgress?: SyncProgressCallback): Promise<void>;
package/index.js CHANGED
@@ -139,9 +139,12 @@ class ho {
139
139
  }
140
140
  }
141
141
  function ue(...e) {
142
- let t = e.join("/");
143
- const r = t[0] === "/", n = t.substring(t.length - 1) === "/";
144
- return t = Ks(t), !t && !r && (t = "."), t && n && (t += "/"), t;
142
+ function t(i) {
143
+ return i.substring(i.length - 1) === "/";
144
+ }
145
+ let r = e.join("/");
146
+ const n = r[0] === "/", s = t(r);
147
+ return r = Ks(r), !r && !n && (r = "."), r && s && !t(r) && (r += "/"), r;
145
148
  }
146
149
  function Gs(e) {
147
150
  if (e === "/")
@@ -1161,21 +1164,22 @@ const Lo = async (e, { fromPath: t, toPath: r }) => {
1161
1164
  wp_publish_post( $wp_customize->changeset_post_id() );
1162
1165
  `
1163
1166
  });
1164
- }, Ur = "/tmp/file.zip", si = async (e, t, r) => {
1167
+ }, Ur = "/tmp/file.zip", si = async (e, t, r, n = !0) => {
1165
1168
  if (t instanceof File) {
1166
- const s = t;
1169
+ const i = t;
1167
1170
  t = Ur, await e.writeFile(
1168
1171
  t,
1169
- new Uint8Array(await s.arrayBuffer())
1172
+ new Uint8Array(await i.arrayBuffer())
1170
1173
  );
1171
1174
  }
1172
- const n = Nr({
1175
+ const s = Nr({
1173
1176
  zipPath: t,
1174
- extractToPath: r
1177
+ extractToPath: r,
1178
+ overwriteFiles: n
1175
1179
  });
1176
1180
  await e.run({
1177
1181
  code: `<?php
1178
- function unzip($zipPath, $extractTo, $overwrite = true)
1182
+ function unzip($zipPath, $extractTo, $overwriteFiles = true)
1179
1183
  {
1180
1184
  if (!is_dir($extractTo)) {
1181
1185
  mkdir($extractTo, 0777, true);
@@ -1183,14 +1187,23 @@ const Lo = async (e, { fromPath: t, toPath: r }) => {
1183
1187
  $zip = new ZipArchive;
1184
1188
  $res = $zip->open($zipPath);
1185
1189
  if ($res === TRUE) {
1186
- $zip->extractTo($extractTo);
1187
- $zip->close();
1188
- chmod($extractTo, 0777);
1190
+ for ($i = 0; $i < $zip->numFiles; $i++) {
1191
+ $filename = $zip->getNameIndex($i);
1192
+ $fileinfo = pathinfo($filename);
1193
+ $extractFilePath = rtrim($extractTo, '/') . '/' . $filename;
1194
+ // Check if file exists and $overwriteFiles is false
1195
+ if (!file_exists($extractFilePath) || $overwriteFiles) {
1196
+ // Extract file
1197
+ $zip->extractTo($extractTo, $filename);
1198
+ }
1199
+ }
1200
+ $zip->close();
1201
+ chmod($extractTo, 0777);
1189
1202
  } else {
1190
1203
  throw new Exception("Could not unzip file");
1191
1204
  }
1192
1205
  }
1193
- unzip(${n.zipPath}, ${n.extractToPath});
1206
+ unzip(${s.zipPath}, ${s.extractToPath}, ${s.overwriteFiles});
1194
1207
  `
1195
1208
  }), await e.fileExists(Ur) && await e.unlink(Ur);
1196
1209
  }, dn = async (e, { zipFile: t, zipPath: r, extractToPath: n }) => {
@@ -9422,6 +9435,8 @@ function Xi(e) {
9422
9435
  }
9423
9436
  });
9424
9437
  }
9438
+ new Promise((e) => {
9439
+ });
9425
9440
  async function Vd({
9426
9441
  iframe: e,
9427
9442
  blueprint: t,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wp-playground/client",
3
- "version": "0.9.19",
3
+ "version": "0.9.21",
4
4
  "description": "WordPress Playground client",
5
5
  "repository": {
6
6
  "type": "git",
@@ -37,7 +37,7 @@
37
37
  "main": "./index.cjs",
38
38
  "module": "./index.js",
39
39
  "types": "index.d.ts",
40
- "gitHead": "aafbbcdc4b0644885bd55d0ed67381952f0b16b6",
40
+ "gitHead": "a497916495035caba2f28cfdef75a8a0f3732f0e",
41
41
  "engines": {
42
42
  "node": ">=18.18.0",
43
43
  "npm": ">=8.11.0"