@wp-playground/wordpress 0.9.14 → 0.9.16

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.js CHANGED
@@ -1,85 +1,10 @@
1
- import{parse,stringify}from"/home/runner/work/wordpress-playground/wordpress-playground/node_modules/ini/lib/ini.js";const SleepFinished=Symbol("SleepFinished");function sleep(e){return new Promise(t=>{setTimeout(()=>t(SleepFinished),e)})}class AcquireTimeoutError extends Error{constructor(){super("Acquiring lock timed out")}}class Semaphore{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,sleep(this.timeout)]).then(r=>{if(r===SleepFinished)throw new AcquireTimeoutError}):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 joinPaths(...e){let t=e.join("/");const r=t[0]==="/",s=t.substring(t.length-1)==="/";return t=normalizePath(t),!t&&!r&&(t="."),t&&s&&(t+="/"),t}function dirname(e){if(e==="/")return"/";e=normalizePath(e);const t=e.lastIndexOf("/");return t===-1?"":t===0?"/":e.substr(0,t)}function normalizePath(e){const t=e[0]==="/";return e=normalizePathsArray(e.split("/").filter(r=>!!r),!t).join("/"),(t?"/":"")+e.replace(/\/$/,"")}function normalizePathsArray(e,t){let r=0;for(let s=e.length-1;s>=0;s--){const i=e[s];i==="."?e.splice(s,1):i===".."?(e.splice(s,1),r++):r&&(e.splice(s,1),r--)}if(t)for(;r;r--)e.unshift("..");return e}function splitShellCommand(e){let s=0,i="";const n=[];let o="";for(let a=0;a<e.length;a++){const l=e[a];l==="\\"?((e[a+1]==='"'||e[a+1]==="'")&&a++,o+=e[a]):s===0?l==='"'||l==="'"?(s=1,i=l):l.match(/\s/)?(o.trim().length&&n.push(o.trim()),o=l):n.length&&!o?o=n.pop()+l:o+=l:s===1&&(l===i?(s=0,i=""):o+=l)}return o&&n.push(o.trim()),n}function createSpawnHandler(e){return function(t,r=[],s={}){const i=new ChildProcess,n=new ProcessApi(i);return setTimeout(async()=>{let o=[];if(r.length)o=[t,...r];else if(typeof t=="string")o=splitShellCommand(t);else if(Array.isArray(t))o=t;else throw new Error("Invalid command ",t);try{await e(o,n,s)}catch(a){i.emit("error",a),typeof a=="object"&&a!==null&&"message"in a&&typeof a.message=="string"&&n.stderr(a.message),n.exit(1)}i.emit("spawn",!0)}),i}}class EventEmitter{constructor(){this.listeners={}}emit(t,r){this.listeners[t]&&this.listeners[t].forEach(function(s){s(r)})}on(t,r){this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(r)}}class ProcessApi extends EventEmitter{constructor(t){super(),this.childProcess=t,this.exited=!1,this.stdinData=[],t.on("stdin",r=>{this.stdinData?this.stdinData.push(r.slice()):this.emit("stdin",r)})}stdout(t){typeof t=="string"&&(t=new TextEncoder().encode(t)),this.childProcess.stdout.emit("data",t)}stdoutEnd(){this.childProcess.stdout.emit("end",{})}stderr(t){typeof t=="string"&&(t=new TextEncoder().encode(t)),this.childProcess.stderr.emit("data",t)}stderrEnd(){this.childProcess.stderr.emit("end",{})}exit(t){this.exited||(this.exited=!0,this.childProcess.emit("exit",t))}flushStdin(){if(this.stdinData)for(let t=0;t<this.stdinData.length;t++)this.emit("stdin",this.stdinData[t]);this.stdinData=null}}let lastPid=9743;class ChildProcess extends EventEmitter{constructor(t=lastPid++){super(),this.pid=t,this.stdout=new EventEmitter,this.stderr=new EventEmitter;const r=this;this.stdin={write:s=>{r.emit("stdin",s)}}}}function phpVar(e){return`json_decode(base64_decode('${stringToBase64(JSON.stringify(e))}'), true)`}function phpVars(e){const t={};for(const r in e)t[r]=phpVar(e[r]);return t}function stringToBase64(e){return bytesToBase64(new TextEncoder().encode(e))}function bytesToBase64(e){const t=String.fromCodePoint(...e);return btoa(t)}const tmpPath="/tmp/file.zip",unzipFile=async(e,t,r)=>{if(t instanceof File){const i=t;t=tmpPath,await e.writeFile(t,new Uint8Array(await i.arrayBuffer()))}const s=phpVars({zipPath:t,extractToPath:r});await e.run({code:`<?php
2
- function unzip($zipPath, $extractTo, $overwrite = true)
3
- {
4
- if (!is_dir($extractTo)) {
5
- mkdir($extractTo, 0777, true);
6
- }
7
- $zip = new ZipArchive;
8
- $res = $zip->open($zipPath);
9
- if ($res === TRUE) {
10
- $zip->extractTo($extractTo);
11
- $zip->close();
12
- chmod($extractTo, 0777);
13
- } else {
14
- throw new Exception("Could not unzip file");
15
- }
16
- }
17
- unzip(${s.zipPath}, ${s.extractToPath});
18
- `}),await e.fileExists(tmpPath)&&await e.unlink(tmpPath)},currentJsRuntime=function(){return typeof process<"u"&&process.release?.name==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"}();if(currentJsRuntime==="NODE"){let e=function(r){return new Promise(function(s,i){r.onload=r.onerror=function(n){r.onload=r.onerror=null,n.type==="load"?s(r.result):i(new Error("Failed to read the blob/file"))}})},t=function(){const r=new Uint8Array([1,2,3,4]),i=new File([r],"test").stream();try{return i.getReader({mode:"byob"}),!0}catch{return!1}};if(typeof File>"u"){class r extends Blob{constructor(i,n,o){super(i);let a;o?.lastModified&&(a=new Date),(!a||isNaN(a.getFullYear()))&&(a=new Date),this.lastModifiedDate=a,this.lastModified=a.getMilliseconds(),this.name=n||""}}global.File=r}typeof Blob.prototype.arrayBuffer>"u"&&(Blob.prototype.arrayBuffer=function(){const s=new FileReader;return s.readAsArrayBuffer(this),e(s)}),typeof Blob.prototype.text>"u"&&(Blob.prototype.text=function(){const s=new FileReader;return s.readAsText(this),e(s)}),(typeof Blob.prototype.stream>"u"||!t())&&(Blob.prototype.stream=function(){let r=0;const s=this;return new ReadableStream({type:"bytes",autoAllocateChunkSize:512*1024,async pull(i){const n=i.byobRequest.view,a=await s.slice(r,r+n.byteLength).arrayBuffer(),l=new Uint8Array(a);new Uint8Array(n.buffer).set(l);const c=l.byteLength;i.byobRequest.respond(c),r+=c,r>=s.size&&i.close()}})})}if(currentJsRuntime==="NODE"&&typeof CustomEvent>"u"){class e extends Event{constructor(r,s={}){super(r,s),this.detail=s.detail}initCustomEvent(){}}globalThis.CustomEvent=e}const FileErrorCodes={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 getEmscriptenFsError(e){const t=typeof e=="object"?e?.errno:null;if(t in FileErrorCodes)return FileErrorCodes[t]}function rethrowFileSystemError(e=""){return function(r,s,i){const n=i.value;i.value=function(...o){try{return n.apply(this,o)}catch(a){const l=typeof a=="object"?a?.errno:null;if(l in FileErrorCodes){const c=FileErrorCodes[l],p=typeof o[1]=="string"?o[1]:null,u=p!==null?e.replaceAll("{path}",p):e;throw new Error(`${u}: ${c}`,{cause:a})}throw a}}}}const logEventType="playground-log",logEvent=(e,...t)=>{logger.dispatchEvent(new CustomEvent(logEventType,{detail:{log:e,args:t}}))},logToConsole=(e,...t)=>{switch(typeof e.message=="string"?e.message=prepareLogMessage(e.message):e.message.message&&typeof e.message.message=="string"&&(e.message.message=prepareLogMessage(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)}},prepareLogMessage$1=e=>e instanceof Error?[e.message,e.stack].join(`
19
- `):JSON.stringify(e,null,2),logs=[],addToLogArray=e=>{logs.push(e)},logToMemory=e=>{if(e.raw===!0)addToLogArray(e.message);else{const t=formatLogEntry(typeof e.message=="object"?prepareLogMessage$1(e.message):e.message,e.severity??"Info",e.prefix??"JavaScript");addToLogArray(t)}};class Logger extends EventTarget{constructor(t=[]){super(),this.handlers=t,this.fatalErrorEvent="playground-fatal-error"}getLogs(){return this.handlers.includes(logToMemory)?[...logs]:(this.error(`Logs aren't stored because the logToMemory handler isn't registered.
20
- If you're using a custom logger instance, make sure to register logToMemory handler.
21
- `),[])}logMessage(t,...r){for(const s of this.handlers)s(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 getDefaultHandlers=()=>{try{if(process.env.NODE_ENV==="test")return[logToMemory,logEvent]}catch{}return[logToMemory,logToConsole,logEvent]},logger=new Logger(getDefaultHandlers()),prepareLogMessage=e=>e.replace(/\t/g,""),formatLogEntry=(e,t,r)=>{const s=new Date,i=new Intl.DateTimeFormat("en-GB",{year:"numeric",month:"short",day:"2-digit",timeZone:"UTC"}).format(s).replace(/ /g,"-"),n=new Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1,timeZone:"UTC",timeZoneName:"short"}).format(s),o=i+" "+n;return e=prepareLogMessage(e),`[${o}] ${r} ${t}: ${e}`};var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=(e,t,r,s)=>{for(var i=s>1?void 0:s?__getOwnPropDesc(t,r):t,n=e.length-1,o;n>=0;n--)(o=e[n])&&(i=(s?o(t,r,i):o(i))||i);return s&&i&&__defProp(t,r,i),i};const _FSHelpers=class d{static readFileAsText(t,r){return new TextDecoder().decode(d.readFileAsBuffer(t,r))}static readFileAsBuffer(t,r){return t.readFile(r)}static writeFile(t,r,s){t.writeFile(r,s)}static unlink(t,r){t.unlink(r)}static mv(t,r,s){try{const i=t.lookupPath(r).node.mount,n=d.fileExists(t,s)?t.lookupPath(s).node.mount:t.lookupPath(dirname(s)).node.mount;i.mountpoint!==n.mountpoint?(d.copyRecursive(t,r,s),d.rmdir(t,r,{recursive:!0})):t.rename(r,s)}catch(i){const n=getEmscriptenFsError(i);throw n?new Error(`Could not move ${r} to ${s}: ${n}`,{cause:i}):i}}static rmdir(t,r,s={recursive:!0}){s?.recursive&&d.listFiles(t,r).forEach(i=>{const n=`${r}/${i}`;d.isDir(t,n)?d.rmdir(t,n,s):d.unlink(t,n)}),t.rmdir(r)}static listFiles(t,r,s={prependPath:!1}){if(!d.fileExists(t,r))return[];try{const i=t.readdir(r).filter(n=>n!=="."&&n!=="..");if(s.prependPath){const n=r.replace(/\/$/,"");return i.map(o=>`${n}/${o}`)}return i}catch(i){return logger.error(i,{path:r}),[]}}static isDir(t,r){return d.fileExists(t,r)?t.isDir(t.lookupPath(r).node.mode):!1}static fileExists(t,r){try{return t.lookupPath(r),!0}catch{return!1}}static mkdir(t,r){t.mkdirTree(r)}static copyRecursive(t,r,s){const i=t.lookupPath(r).node;if(t.isDir(i.mode)){t.mkdirTree(s);const n=t.readdir(r).filter(o=>o!=="."&&o!=="..");for(const o of n)d.copyRecursive(t,joinPaths(r,o),joinPaths(s,o))}else t.writeFile(s,t.readFile(r))}};__decorateClass([rethrowFileSystemError('Could not read "{path}"')],_FSHelpers,"readFileAsText",1);__decorateClass([rethrowFileSystemError('Could not read "{path}"')],_FSHelpers,"readFileAsBuffer",1);__decorateClass([rethrowFileSystemError('Could not write to "{path}"')],_FSHelpers,"writeFile",1);__decorateClass([rethrowFileSystemError('Could not unlink "{path}"')],_FSHelpers,"unlink",1);__decorateClass([rethrowFileSystemError('Could not remove directory "{path}"')],_FSHelpers,"rmdir",1);__decorateClass([rethrowFileSystemError('Could not list files in "{path}"')],_FSHelpers,"listFiles",1);__decorateClass([rethrowFileSystemError('Could not stat "{path}"')],_FSHelpers,"isDir",1);__decorateClass([rethrowFileSystemError('Could not stat "{path}"')],_FSHelpers,"fileExists",1);__decorateClass([rethrowFileSystemError('Could not create directory "{path}"')],_FSHelpers,"mkdir",1);__decorateClass([rethrowFileSystemError('Could not copy files from "{path}"')],_FSHelpers,"copyRecursive",1);let FSHelpers=_FSHelpers;const responseTexts={500:"Internal Server Error",502:"Bad Gateway",404:"Not Found",403:"Forbidden",401:"Unauthorized",400:"Bad Request",301:"Moved Permanently",302:"Found",307:"Temporary Redirect",308:"Permanent Redirect",204:"No Content",201:"Created",200:"OK"};class PHPResponse{constructor(t,r,s,i="",n=0){this.httpStatusCode=t,this.headers=r,this.bytes=s,this.exitCode=n,this.errors=i}static forHttpCode(t,r=""){return new PHPResponse(t,{},new TextEncoder().encode(r||responseTexts[t]||""))}static fromRawData(t){return new PHPResponse(t.httpStatusCode,t.headers,t.bytes,t.errors,t.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 loadedRuntimes=new Map;function getLoadedRuntime(e){return loadedRuntimes.get(e)}(function(){return typeof process<"u"&&process.release?.name==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"})();const kError=Symbol("error"),kMessage=Symbol("message");class ErrorEvent2 extends Event{constructor(t,r={}){super(t),this[kError]=r.error===void 0?null:r.error,this[kMessage]=r.message===void 0?"":r.message}get error(){return this[kError]}get message(){return this[kMessage]}}Object.defineProperty(ErrorEvent2.prototype,"error",{enumerable:!0});Object.defineProperty(ErrorEvent2.prototype,"message",{enumerable:!0});const ErrorEvent=typeof globalThis.ErrorEvent=="function"?globalThis.ErrorEvent:ErrorEvent2;function isExitCodeZero(e){return e instanceof Error?"exitCode"in e&&e?.exitCode===0||e?.name==="ExitStatus"&&"status"in e&&e.status===0:!1}class UnhandledRejectionsTarget extends EventTarget{constructor(){super(...arguments),this.listenersCount=0}addEventListener(t,r){++this.listenersCount,super.addEventListener(t,r)}removeEventListener(t,r){--this.listenersCount,super.removeEventListener(t,r)}hasListeners(){return this.listenersCount>0}}function improveWASMErrorReporting(e){const t=new UnhandledRejectionsTarget;for(const r in e.wasmExports)if(typeof e.wasmExports[r]=="function"){const s=e.wasmExports[r];e.wasmExports[r]=function(...i){try{return s(...i)}catch(n){if(!(n instanceof Error))throw n;const o=clarifyErrorMessage(n,e.lastAsyncifyStackSource?.stack);if(e.lastAsyncifyStackSource&&(n.cause=e.lastAsyncifyStackSource),t.hasListeners()){t.dispatchEvent(new ErrorEvent("error",{error:n,message:o}));return}throw isExitCodeZero(n)||showCriticalErrorBox(o),n}}}return t}let functionsMaybeMissingFromAsyncify=[];function getFunctionsMaybeMissingFromAsyncify(){return functionsMaybeMissingFromAsyncify}function clarifyErrorMessage(e,t){if(e.message==="unreachable"){let r=UNREACHABLE_ERROR;t||(r+=`
22
-
23
- This stack trace is lacking. For a better one initialize
24
- the PHP runtime with { debug: true }, e.g. PHPNode.load('8.1', { debug: true }).
25
-
26
- `),functionsMaybeMissingFromAsyncify=extractPHPFunctionsFromStack(t||e.stack||"");for(const s of functionsMaybeMissingFromAsyncify)r+=` * ${s}
27
- `;return r}return e.message}const UNREACHABLE_ERROR=`
28
- "unreachable" WASM instruction executed.
29
-
30
- The typical reason is a PHP function missing from the ASYNCIFY_ONLY
31
- list when building PHP.wasm.
32
-
33
- You will need to file a new issue in the WordPress Playground repository
34
- and paste this error message there:
35
-
36
- https://github.com/WordPress/wordpress-playground/issues/new
37
-
38
- If you're a core developer, the typical fix is to:
39
-
40
- * Isolate a minimal reproduction of the error
41
- * Add a reproduction of the error to php-asyncify.spec.ts in the WordPress Playground repository
42
- * Run 'npm run fix-asyncify'
43
- * Commit the changes, push to the repo, release updated NPM packages
44
-
45
- Below is a list of all the PHP functions found in the stack trace to
46
- help with the minimal reproduction. If they're all already listed in
47
- the Dockerfile, you'll need to trigger this error again with long stack
48
- traces enabled. In node.js, you can do it using the --stack-trace-limit=100
49
- CLI option:
50
-
51
- `,redBg="\x1B[41m",bold="\x1B[1m",reset="\x1B[0m",eol="\x1B[K";let logged=!1;function showCriticalErrorBox(e){if(!logged&&(logged=!0,!e?.trim().startsWith("Program terminated with exit"))){logger.log(`${redBg}
52
- ${eol}
53
- ${bold} WASM ERROR${reset}${redBg}`);for(const t of e.split(`
54
- `))logger.log(`${eol} ${t} `);logger.log(`${reset}`)}}function extractPHPFunctionsFromStack(e){try{const t=e.split(`
55
- `).slice(1).map(r=>{const s=r.trim().substring(3).split(" ");return{fn:s.length>=2?s[0]:"<unknown>",isWasm:r.includes("wasm://")}}).filter(({fn:r,isWasm:s})=>s&&!r.startsWith("dynCall_")&&!r.startsWith("invoke_")).map(({fn:r})=>r);return Array.from(new Set(t))}catch{return[]}}const STRING="string",NUMBER="number",__private__dont__use=Symbol("__private__dont__use");class PHPExecutionFailureError extends Error{constructor(t,r,s){super(t),this.response=r,this.source=s}}const PHP_INI_PATH="/internal/shared/php.ini",AUTO_PREPEND_SCRIPT="/internal/shared/auto_prepend_file.php";class PHP{constructor(e){this.#webSapiInitialized=!1,this.#wasmErrorsTarget=null,this.#eventListeners=new Map,this.#messageListeners=[],this.semaphore=new Semaphore({concurrency:1}),e!==void 0&&this.initializeRuntime(e)}#sapiName;#webSapiInitialized;#wasmErrorsTarget;#eventListeners;#messageListeners;addEventListener(e,t){this.#eventListeners.has(e)||this.#eventListeners.set(e,new Set),this.#eventListeners.get(e).add(t)}removeEventListener(e,t){this.#eventListeners.get(e)?.delete(t)}dispatchEvent(e){const t=this.#eventListeners.get(e.type);if(t)for(const r of t)r(e)}onMessage(e){this.#messageListeners.push(e)}async setSpawnHandler(handler){typeof handler=="string"&&(handler=createSpawnHandler(eval(handler))),this[__private__dont__use].spawnProcess=handler}get absoluteUrl(){return this.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.documentRoot}pathToInternalUrl(e){return this.requestHandler.pathToInternalUrl(e)}internalUrlToPath(e){return this.requestHandler.internalUrlToPath(e)}initializeRuntime(e){if(this[__private__dont__use])throw new Error("PHP runtime already initialized.");const t=getLoadedRuntime(e);if(!t)throw new Error("Invalid PHP runtime id.");this[__private__dont__use]=t,this[__private__dont__use].ccall("wasm_set_phpini_path",null,["string"],[PHP_INI_PATH]),this.fileExists(PHP_INI_PATH)||this.writeFile(PHP_INI_PATH,["auto_prepend_file="+AUTO_PREPEND_SCRIPT,"memory_limit=256M","ignore_repeated_errors = 1","error_reporting = E_ALL","display_errors = 1","html_errors = 1","display_startup_errors = On","log_errors = 1","always_populate_raw_post_data = -1","upload_max_filesize = 2000M","post_max_size = 2000M","disable_functions = curl_exec,curl_multi_exec","allow_url_fopen = Off","allow_url_include = Off","session.save_path = /home/web_user","implicit_flush = 1","output_buffering = 0","max_execution_time = 0","max_input_time = -1"].join(`
56
- `)),this.fileExists(AUTO_PREPEND_SCRIPT)||this.writeFile(AUTO_PREPEND_SCRIPT,`<?php
57
- // Define constants set via defineConstant() calls
58
- if(file_exists('/internal/shared/consts.json')) {
59
- $consts = json_decode(file_get_contents('/internal/shared/consts.json'), true);
60
- foreach ($consts as $const => $value) {
61
- if (!defined($const) && is_scalar($value)) {
62
- define($const, $value);
63
- }
64
- }
65
- }
66
- // Preload all the files from /internal/shared/preload
67
- foreach (glob('/internal/shared/preload/*.php') as $file) {
68
- require_once $file;
69
- }
70
- `),t.onMessage=async r=>{for(const s of this.#messageListeners){const i=await s(r);if(i)return i}return""},this.#wasmErrorsTarget=improveWASMErrorReporting(t),this.dispatchEvent({type:"runtime.initialized"})}async setSapiName(e){if(this[__private__dont__use].ccall("wasm_set_sapi_name",NUMBER,[STRING],[e])!==0)throw new Error("Could not set SAPI name. This can only be done before the PHP WASM module is initialized.Did you already dispatch any requests?");this.#sapiName=e}chdir(e){this[__private__dont__use].FS.chdir(e)}async request(e){if(logger.warn("PHP.request() is deprecated. Please use new PHPRequestHandler() instead."),!this.requestHandler)throw new Error("No request handler available.");return this.requestHandler.request(e)}async run(e){const t=await this.semaphore.acquire();let r;try{if(this.#webSapiInitialized||(this.#initWebRuntime(),this.#webSapiInitialized=!0),e.scriptPath&&!this.fileExists(e.scriptPath))throw new Error(`The script path "${e.scriptPath}" does not exist.`);this.#setRelativeRequestUri(e.relativeUri||""),this.#setRequestMethod(e.method||"GET");const s=normalizeHeaders(e.headers||{}),i=s.host||"example.com:443",n=this.#inferPortFromHostAndProtocol(i,e.protocol||"http");this.#setRequestHost(i),this.#setRequestPort(n),this.#setRequestHeaders(s),e.body&&(r=this.#setRequestBody(e.body)),typeof e.code=="string"?(this.writeFile("/internal/eval.php",e.code),this.#setScriptPath("/internal/eval.php")):this.#setScriptPath(e.scriptPath||"");const o=this.#prepareServerEntries(e.$_SERVER,s,n);for(const c in o)this.#setServerGlobalEntry(c,o[c]);const a=e.env||{};for(const c in a)this.#setEnv(c,a[c]);const l=await this.#handleRequest();if(l.exitCode!==0){logger.warn("PHP.run() output was:",l.text);const c=new PHPExecutionFailureError(`PHP.run() failed with exit code ${l.exitCode} and the following output: `+l.errors,l,"request");throw logger.error(c),c}return l}catch(s){throw this.dispatchEvent({type:"request.error",error:s,source:s.source??"php-wasm"}),s}finally{try{r&&this[__private__dont__use].free(r)}finally{t(),this.dispatchEvent({type:"request.end"})}}}#prepareServerEntries(e,t,r){const s={...e||{}};s.HTTPS=s.HTTPS||r===443?"on":"off";for(const i in t){let n="HTTP_";["content-type","content-length"].includes(i.toLowerCase())&&(n=""),s[`${n}${i.toUpperCase().replace(/-/g,"_")}`]=t[i]}return s}#initWebRuntime(){this[__private__dont__use].ccall("php_wasm_init",null,[],[])}#getResponseHeaders(){const e="/internal/headers.json";if(!this.fileExists(e))throw new Error("SAPI Error: Could not find response headers file.");const t=JSON.parse(this.readFileAsText(e)),r={};for(const s of t.headers){if(!s.includes(": "))continue;const i=s.indexOf(": "),n=s.substring(0,i).toLowerCase(),o=s.substring(i+2);n in r||(r[n]=[]),r[n].push(o)}return{headers:r,httpStatusCode:t.status}}#setRelativeRequestUri(e){if(this[__private__dont__use].ccall("wasm_set_request_uri",null,[STRING],[e]),e.includes("?")){const t=e.substring(e.indexOf("?")+1);this[__private__dont__use].ccall("wasm_set_query_string",null,[STRING],[t])}}#setRequestHost(e){this[__private__dont__use].ccall("wasm_set_request_host",null,[STRING],[e])}#setRequestPort(e){this[__private__dont__use].ccall("wasm_set_request_port",null,[NUMBER],[e])}#inferPortFromHostAndProtocol(e,t){let r;try{r=parseInt(new URL(e).port,10)}catch{}return(!r||isNaN(r)||r===80)&&(r=t==="https"?443:80),r}#setRequestMethod(e){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[e])}#setRequestHeaders(e){e.cookie&&this[__private__dont__use].ccall("wasm_set_cookies",null,[STRING],[e.cookie]),e["content-type"]&&this[__private__dont__use].ccall("wasm_set_content_type",null,[STRING],[e["content-type"]]),e["content-length"]&&this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[parseInt(e["content-length"],10)])}#setRequestBody(e){let t,r;typeof e=="string"?(logger.warn("Passing a string as the request body is deprecated. Please use a Uint8Array instead. See https://github.com/WordPress/wordpress-playground/issues/997 for more details"),r=this[__private__dont__use].lengthBytesUTF8(e),t=r+1):(r=e.byteLength,t=e.byteLength);const s=this[__private__dont__use].malloc(t);if(!s)throw new Error("Could not allocate memory for the request body.");return typeof e=="string"?this[__private__dont__use].stringToUTF8(e,s,t+1):this[__private__dont__use].HEAPU8.set(e,s),this[__private__dont__use].ccall("wasm_set_request_body",null,[NUMBER],[s]),this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[r]),s}#setScriptPath(e){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[e])}#setServerGlobalEntry(e,t){this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[e,t])}#setEnv(e,t){this[__private__dont__use].ccall("wasm_add_ENV_entry",null,[STRING,STRING],[e,t])}defineConstant(e,t){let r={};try{r=JSON.parse(this.fileExists("/internal/shared/consts.json")&&this.readFileAsText("/internal/shared/consts.json")||"{}")}catch{}this.writeFile("/internal/shared/consts.json",JSON.stringify({...r,[e]:t}))}async#handleRequest(){let e,t;try{e=await new Promise((i,n)=>{t=a=>{logger.error(a),logger.error(a.error);const l=new Error("Rethrown");l.cause=a.error,l.betterMessage=a.message,n(l)},this.#wasmErrorsTarget?.addEventListener("error",t);const o=this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0});return o instanceof Promise?o.then(i,n):i(o)})}catch(i){for(const l in this)typeof this[l]=="function"&&(this[l]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});this.functionsMaybeMissingFromAsyncify=getFunctionsMaybeMissingFromAsyncify();const n=i,o="betterMessage"in n?n.betterMessage:n.message,a=new Error(o);throw a.cause=n,logger.error(a),a}finally{this.#wasmErrorsTarget?.removeEventListener("error",t)}const{headers:r,httpStatusCode:s}=this.#getResponseHeaders();return new PHPResponse(e===0?s:500,r,this.readFileAsBuffer("/internal/stdout"),this.readFileAsText("/internal/stderr"),e)}mkdir(e){return FSHelpers.mkdir(this[__private__dont__use].FS,e)}mkdirTree(e){return FSHelpers.mkdir(this[__private__dont__use].FS,e)}readFileAsText(e){return FSHelpers.readFileAsText(this[__private__dont__use].FS,e)}readFileAsBuffer(e){return FSHelpers.readFileAsBuffer(this[__private__dont__use].FS,e)}writeFile(e,t){return FSHelpers.writeFile(this[__private__dont__use].FS,e,t)}unlink(e){return FSHelpers.unlink(this[__private__dont__use].FS,e)}mv(e,t){return FSHelpers.mv(this[__private__dont__use].FS,e,t)}rmdir(e,t={recursive:!0}){return FSHelpers.rmdir(this[__private__dont__use].FS,e,t)}listFiles(e,t={prependPath:!1}){return FSHelpers.listFiles(this[__private__dont__use].FS,e,t)}isDir(e){return FSHelpers.isDir(this[__private__dont__use].FS,e)}fileExists(e){return FSHelpers.fileExists(this[__private__dont__use].FS,e)}hotSwapPHPRuntime(e,t){const r=this[__private__dont__use].FS;try{this.exit()}catch{}this.initializeRuntime(e),this.#sapiName&&this.setSapiName(this.#sapiName),t&&copyFS(r,this[__private__dont__use].FS,t)}async mount(e,t){return await t(this,this[__private__dont__use].FS,e)}async cli(e){for(const t of e)this[__private__dont__use].ccall("wasm_add_cli_arg",null,[STRING],[t]);try{return await this[__private__dont__use].ccall("run_cli",null,[],[],{async:!0})}catch(t){if(isExitCodeZero(t))return 0;throw t}}setSkipShebang(e){this[__private__dont__use].ccall("wasm_set_skip_shebang",null,[NUMBER],[e?1:0])}exit(e=0){this.dispatchEvent({type:"runtime.beforedestroy"});try{this[__private__dont__use]._exit(e)}catch{}this.#webSapiInitialized=!1,this.#wasmErrorsTarget=null,delete this[__private__dont__use].onMessage,delete this[__private__dont__use]}[Symbol.dispose](){this.#webSapiInitialized&&this.exit(0)}}function normalizeHeaders(e){const t={};for(const r in e)t[r.toLowerCase()]=e[r];return t}function copyFS(e,t,r){let s;try{s=e.lookupPath(r)}catch{return}if(!("contents"in s.node))return;if(!e.isDir(s.node.mode)){t.writeFile(r,e.readFile(r));return}t.mkdirTree(r);const i=e.readdir(r).filter(n=>n!=="."&&n!=="..");for(const n of i)copyFS(e,t,joinPaths(r,n))}async function setPhpIniEntries(e,t){const r=parse(await e.readFileAsText(PHP_INI_PATH));for(const[s,i]of Object.entries(t))i==null?delete r[s]:r[s]=i;await e.writeFile(PHP_INI_PATH,stringify(r))}async function withPHPIniValues(e,t,r){const s=await e.readFileAsText(PHP_INI_PATH);try{return await setPhpIniEntries(e,t),await r()}finally{await e.writeFile(PHP_INI_PATH,s)}}class HttpCookieStore{constructor(){this.cookies={}}rememberCookiesFromResponseHeaders(t){if(t?.["set-cookie"])for(const r of t["set-cookie"])try{if(!r.includes("="))continue;const s=r.indexOf("="),i=r.substring(0,s),n=r.substring(s+1).split(";")[0];this.cookies[i]=n}catch(s){logger.error(s)}}getCookieRequestHeader(){const t=[];for(const r in this.cookies)t.push(`${r}=${this.cookies[r]}`);return t.join("; ")}}ReadableStream.prototype[Symbol.asyncIterator]||(ReadableStream.prototype[Symbol.asyncIterator]=async function*(){const e=this.getReader();try{for(;;){const{done:t,value:r}=await e.read();if(t)return;yield r}}finally{e.releaseLock()}},ReadableStream.prototype.iterate=ReadableStream.prototype[Symbol.asyncIterator]);class MaxPhpInstancesError extends Error{constructor(t){super(`Requested more concurrent PHP instances than the limit (${t}).`),this.name=this.constructor.name}}class PHPProcessManager{constructor(t){this.primaryIdle=!0,this.nextInstance=null,this.allInstances=[],this.maxPhpInstances=t?.maxPhpInstances??5,this.phpFactory=t?.phpFactory,this.primaryPhp=t?.primaryPhp,this.semaphore=new Semaphore({concurrency:this.maxPhpInstances,timeout:t?.timeout||5e3})}async getPrimaryPhp(){if(!this.phpFactory&&!this.primaryPhp)throw new Error("phpFactory or primaryPhp must be set before calling getPrimaryPhp().");if(!this.primaryPhp){const t=await this.spawn({isPrimary:!0});this.primaryPhp=t.php}return this.primaryPhp}async acquirePHPInstance(){if(this.primaryIdle)return this.primaryIdle=!1,{php:await this.getPrimaryPhp(),reap:()=>this.primaryIdle=!0};const t=this.nextInstance||this.spawn({isPrimary:!1});return this.semaphore.remaining>0?this.nextInstance=this.spawn({isPrimary:!1}):this.nextInstance=null,await t}spawn(t){if(t.isPrimary&&this.allInstances.length>0)throw new Error("Requested spawning a primary PHP instance when another primary instance already started spawning.");const r=this.doSpawn(t);this.allInstances.push(r);const s=()=>{this.allInstances=this.allInstances.filter(i=>i!==r)};return r.catch(i=>{throw s(),i}).then(i=>({...i,reap:()=>{s(),i.reap()}}))}async doSpawn(t){let r;try{r=await this.semaphore.acquire()}catch(s){throw s instanceof AcquireTimeoutError?new MaxPhpInstancesError(this.maxPhpInstances):s}try{const s=await this.phpFactory(t);return{php:s,reap(){s.exit(),r()}}}catch(s){throw r(),s}}async[Symbol.asyncDispose](){this.primaryPhp&&this.primaryPhp.exit(),await Promise.all(this.allInstances.map(t=>t.then(({reap:r})=>r())))}}const DEFAULT_BASE_URL="http://example.com";function toRelativeUrl(e){return e.toString().substring(e.origin.length)}function removePathPrefix(e,t){return!t||!e.startsWith(t)?e:e.substring(t.length)}function ensurePathPrefix(e,t){return!t||e.startsWith(t)?e:t+e}async function encodeAsMultipart(e){const t=`----${Math.random().toString(36).slice(2)}`,r=`multipart/form-data; boundary=${t}`,s=new TextEncoder,i=[];for(const[l,c]of Object.entries(e))i.push(`--${t}\r
71
- `),i.push(`Content-Disposition: form-data; name="${l}"`),c instanceof File&&i.push(`; filename="${c.name}"`),i.push(`\r
72
- `),c instanceof File&&(i.push("Content-Type: application/octet-stream"),i.push(`\r
73
- `)),i.push(`\r
74
- `),c instanceof File?i.push(await fileToUint8Array(c)):i.push(c),i.push(`\r
75
- `);i.push(`--${t}--\r
76
- `);const n=i.reduce((l,c)=>l+c.length,0),o=new Uint8Array(n);let a=0;for(const l of i)o.set(typeof l=="string"?s.encode(l):l,a),a+=l.length;return{bytes:o,contentType:r}}function fileToUint8Array(e){return new Promise(t=>{const r=new FileReader;r.onload=()=>{t(new Uint8Array(r.result))},r.readAsArrayBuffer(e)})}const _default="application/octet-stream",asx="video/x-ms-asf",atom="application/atom+xml",avi="video/x-msvideo",avif="image/avif",bin="application/octet-stream",bmp="image/x-ms-bmp",cco="application/x-cocoa",css="text/css",data="application/octet-stream",deb="application/octet-stream",der="application/x-x509-ca-cert",dmg="application/octet-stream",doc="application/msword",docx="application/vnd.openxmlformats-officedocument.wordprocessingml.document",eot="application/vnd.ms-fontobject",flv="video/x-flv",gif="image/gif",gz="application/gzip",hqx="application/mac-binhex40",htc="text/x-component",html="text/html",ico="image/x-icon",iso="application/octet-stream",jad="text/vnd.sun.j2me.app-descriptor",jar="application/java-archive",jardiff="application/x-java-archive-diff",jng="image/x-jng",jnlp="application/x-java-jnlp-file",jpg="image/jpeg",jpeg="image/jpeg",js="application/javascript",json="application/json",kml="application/vnd.google-earth.kml+xml",kmz="application/vnd.google-earth.kmz",m3u8="application/vnd.apple.mpegurl",m4a="audio/x-m4a",m4v="video/x-m4v",md="text/plain",mid="audio/midi",mml="text/mathml",mng="video/x-mng",mov="video/quicktime",mp3="audio/mpeg",mp4="video/mp4",mpeg="video/mpeg",msi="application/octet-stream",odg="application/vnd.oasis.opendocument.graphics",odp="application/vnd.oasis.opendocument.presentation",ods="application/vnd.oasis.opendocument.spreadsheet",odt="application/vnd.oasis.opendocument.text",ogg="audio/ogg",otf="font/otf",pdf="application/pdf",pl="application/x-perl",png="image/png",ppt="application/vnd.ms-powerpoint",pptx="application/vnd.openxmlformats-officedocument.presentationml.presentation",prc="application/x-pilot",ps="application/postscript",ra="audio/x-realaudio",rar="application/x-rar-compressed",rpm="application/x-redhat-package-manager",rss="application/rss+xml",rtf="application/rtf",run="application/x-makeself",sea="application/x-sea",sit="application/x-stuffit",svg="image/svg+xml",swf="application/x-shockwave-flash",tcl="application/x-tcl",tar="application/x-tar",tif="image/tiff",ts="video/mp2t",ttf="font/ttf",txt="text/plain",wasm="application/wasm",wbmp="image/vnd.wap.wbmp",webm="video/webm",webp="image/webp",wml="text/vnd.wap.wml",wmlc="application/vnd.wap.wmlc",wmv="video/x-ms-wmv",woff="font/woff",woff2="font/woff2",xhtml="application/xhtml+xml",xls="application/vnd.ms-excel",xlsx="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml="text/xml",xpi="application/x-xpinstall",xspf="application/xspf+xml",zip="application/zip",mimeTypes={_default,"3gpp":"video/3gpp","7z":"application/x-7z-compressed",asx,atom,avi,avif,bin,bmp,cco,css,data,deb,der,dmg,doc,docx,eot,flv,gif,gz,hqx,htc,html,ico,iso,jad,jar,jardiff,jng,jnlp,jpg,jpeg,js,json,kml,kmz,m3u8,m4a,m4v,md,mid,mml,mng,mov,mp3,mp4,mpeg,msi,odg,odp,ods,odt,ogg,otf,pdf,pl,png,ppt,pptx,prc,ps,ra,rar,rpm,rss,rtf,run,sea,sit,svg,swf,tcl,tar,tif,ts,ttf,txt,wasm,wbmp,webm,webp,wml,wmlc,wmv,woff,woff2,xhtml,xls,xlsx,xml,xpi,xspf,zip};class PHPRequestHandler{#e;#s;#a;#r;#i;#t;#n;#o;constructor(t){const{documentRoot:r="/www/",absoluteUrl:s=typeof location=="object"?location?.href:"",rewriteRules:i=[]}=t;"processManager"in t?this.processManager=t.processManager:this.processManager=new PHPProcessManager({phpFactory:async a=>{const l=await t.phpFactory({...a,requestHandler:this});return l.requestHandler=this,l},maxPhpInstances:t.maxPhpInstances}),this.#o=new HttpCookieStore,this.#e=r;const n=new URL(s);this.#a=n.hostname,this.#r=n.port?Number(n.port):n.protocol==="https:"?443:80,this.#s=(n.protocol||"").replace(":","");const o=this.#r!==443&&this.#r!==80;this.#i=[this.#a,o?`:${this.#r}`:""].join(""),this.#t=n.pathname.replace(/\/+$/,""),this.#n=[`${this.#s}://`,this.#i,this.#t].join(""),this.rewriteRules=i}async getPrimaryPhp(){return await this.processManager.getPrimaryPhp()}pathToInternalUrl(t){return`${this.absoluteUrl}${t}`}internalUrlToPath(t){const r=new URL(t);return r.pathname.startsWith(this.#t)&&(r.pathname=r.pathname.slice(this.#t.length)),toRelativeUrl(r)}get absoluteUrl(){return this.#n}get documentRoot(){return this.#e}async request(t){const r=t.url.startsWith("http://")||t.url.startsWith("https://"),s=new URL(t.url.split("#")[0],r?void 0:DEFAULT_BASE_URL),i=applyRewriteRules(removePathPrefix(decodeURIComponent(s.pathname),this.#t),this.rewriteRules),n=joinPaths(this.#e,i);return seemsLikeAPHPRequestHandlerPath(n)?this.#c(t,s):this.#l(await this.processManager.getPrimaryPhp(),n)}#l(t,r){if(!t.fileExists(r))return new PHPResponse(404,{"x-file-type":["static"]},new TextEncoder().encode("404 File not found"));const s=t.readFileAsBuffer(r);return new PHPResponse(200,{"content-length":[`${s.byteLength}`],"content-type":[inferMimeType(r)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},s)}async#c(t,r){let s;try{s=await this.processManager.acquirePHPInstance()}catch(i){return i instanceof MaxPhpInstancesError?PHPResponse.forHttpCode(502):PHPResponse.forHttpCode(500)}try{return await this.#d(s.php,t,r)}finally{s.reap()}}async#d(t,r,s){let i="GET";const n={host:this.#i,...normalizeHeaders(r.headers||{}),cookie:this.#o.getCookieRequestHeader()};let o=r.body;if(typeof o=="object"&&!(o instanceof Uint8Array)){i="POST";const{bytes:l,contentType:c}=await encodeAsMultipart(o);o=l,n["content-type"]=c}let a;try{a=this.#p(t,decodeURIComponent(s.pathname))}catch{return PHPResponse.forHttpCode(404)}try{const l=await t.run({relativeUri:ensurePathPrefix(toRelativeUrl(s),this.#t),protocol:this.#s,method:r.method||i,$_SERVER:{REMOTE_ADDR:"127.0.0.1",DOCUMENT_ROOT:this.#e,HTTPS:this.#n.startsWith("https://")?"on":""},body:o,scriptPath:a,headers:n});return this.#o.rememberCookiesFromResponseHeaders(l.headers),l}catch(l){const c=l;if(c?.response)return c.response;throw l}}#p(t,r){let s=removePathPrefix(r,this.#t);s=applyRewriteRules(s,this.rewriteRules),s.includes(".php")?s=s.split(".php")[0]+".php":t.isDir(`${this.#e}${s}`)?(s.endsWith("/")||(s=`${s}/`),s=`${s}index.php`):s="/index.php";let i=`${this.#e}${s}`;if(t.fileExists(i)||(i=`${this.#e}/index.php`),t.fileExists(i))return i;throw new Error(`File not found: ${i}`)}}function inferMimeType(e){const t=e.split(".").pop();return mimeTypes[t]||mimeTypes._default}function seemsLikeAPHPRequestHandlerPath(e){return seemsLikeAPHPFile(e)||seemsLikeADirectoryRoot(e)}function seemsLikeAPHPFile(e){return e.endsWith(".php")||e.includes(".php/")}function seemsLikeADirectoryRoot(e){return!e.split("/").pop().includes(".")}function applyRewriteRules(e,t){for(const r of t)if(new RegExp(r.match).test(e))return e.replace(r.match,r.replacement);return e}function rotatePHPRuntime({php:e,cwd:t,recreateRuntime:r,maxRequests:s=400}){let i=0;async function n(){if(++i<s)return;i=0;const o=await e.semaphore.acquire();try{e.hotSwapPHPRuntime(await r(),t)}finally{o()}}return e.addEventListener("request.end",n),function(){e.removeEventListener("request.end",n)}}async function writeFiles(e,t,r,{rmRoot:s=!1}={}){s&&await e.isDir(t)&&await e.rmdir(t,{recursive:!0});for(const[i,n]of Object.entries(r)){const o=joinPaths(t,i);await e.fileExists(dirname(o))||await e.mkdir(dirname(o)),n instanceof Uint8Array||typeof n=="string"?await e.writeFile(o,n):await writeFiles(e,o,n)}}function proxyFileSystem(e,t,r){const s=Object.getOwnPropertySymbols(e)[0];for(const i of r)t.fileExists(i)||t.mkdir(i),e.fileExists(i)||e.mkdir(i),t[s].FS.mount(t[s].PROXYFS,{root:i,fs:e[s].FS},i)}async function bootWordPress(e){async function t(i,n){const o=new PHP(await e.createPhpRuntime());return e.sapiName&&o.setSapiName(e.sapiName),i&&(o.requestHandler=i),e.phpIniEntries&&setPhpIniEntries(o,e.phpIniEntries),n?(await setupPlatformLevelMuPlugins(o),await writeFiles(o,"/",e.createFiles||{}),await preloadPhpInfoRoute(o,joinPaths(new URL(e.siteUrl).pathname,"phpinfo.php"))):proxyFileSystem(await i.getPrimaryPhp(),o,["/tmp",i.documentRoot,"/internal/shared"]),e.spawnHandler&&await o.setSpawnHandler(e.spawnHandler(i.processManager)),rotatePHPRuntime({php:o,cwd:i.documentRoot,recreateRuntime:e.createPhpRuntime,maxRequests:400}),o}const r=new PHPRequestHandler({phpFactory:async({isPrimary:i})=>t(r,i),documentRoot:e.documentRoot||"/wordpress",absoluteUrl:e.siteUrl,rewriteRules:wordPressRewriteRules}),s=await r.getPrimaryPhp();if(e.hooks?.beforeWordPressFiles&&await e.hooks.beforeWordPressFiles(s),e.wordPressZip&&await unzipWordPress(s,await e.wordPressZip),e.constants)for(const i in e.constants)s.defineConstant(i,e.constants[i]);if(s.defineConstant("WP_HOME",e.siteUrl),s.defineConstant("WP_SITEURL",e.siteUrl),e.hooks?.beforeDatabaseSetup&&await e.hooks.beforeDatabaseSetup(s),e.sqliteIntegrationPluginZip&&await preloadSqliteIntegration(s,await e.sqliteIntegrationPluginZip),await isWordPressInstalled(s)||await installWordPress(s),!await isWordPressInstalled(s))throw new Error("WordPress installation has failed.");return r}async function isWordPressInstalled(e){return(await e.run({code:`<?php
1
+ import{joinPaths as s,phpVar as o}from"@php-wasm/util";import{unzipFile as l}from"@wp-playground/common";import{PHPRequestHandler as c,withPHPIniValues as f,PHP as w,setPhpIniEntries as _,writeFiles as g,proxyFileSystem as m,rotatePHPRuntime as h}from"@php-wasm/universal";import{SupportedWordPressVersions as $}from"@wp-playground/wordpress-builds";async function F(e){async function a(i,d){const n=new w(await e.createPhpRuntime());return e.sapiName&&n.setSapiName(e.sapiName),i&&(n.requestHandler=i),e.phpIniEntries&&_(n,e.phpIniEntries),d?(await L(n),await g(n,"/",e.createFiles||{}),await E(n,s(new URL(e.siteUrl).pathname,"phpinfo.php"))):m(await i.getPrimaryPhp(),n,["/tmp",i.documentRoot,"/internal/shared"]),e.spawnHandler&&await n.setSpawnHandler(e.spawnHandler(i.processManager)),h({php:n,cwd:i.documentRoot,recreateRuntime:e.createPhpRuntime,maxRequests:400}),n}const r=new c({phpFactory:async({isPrimary:i})=>a(r,i),documentRoot:e.documentRoot||"/wordpress",absoluteUrl:e.siteUrl,rewriteRules:y}),t=await r.getPrimaryPhp();if(e.hooks?.beforeWordPressFiles&&await e.hooks.beforeWordPressFiles(t),e.wordPressZip&&await R(t,await e.wordPressZip),e.constants)for(const i in e.constants)t.defineConstant(i,e.constants[i]);if(t.defineConstant("WP_HOME",e.siteUrl),t.defineConstant("WP_SITEURL",e.siteUrl),e.hooks?.beforeDatabaseSetup&&await e.hooks.beforeDatabaseSetup(t),e.sqliteIntegrationPluginZip&&await S(t,await e.sqliteIntegrationPluginZip),await u(t)||await P(t),!await u(t))throw new Error("WordPress installation has failed.");return r}async function u(e){return(await e.run({code:`<?php
77
2
  require '${e.documentRoot}/wp-load.php';
78
3
  echo is_blog_installed() ? '1' : '0';
79
- `})).text==="1"}async function installWordPress(e){await withPHPIniValues(e,{disable_functions:"fsockopen",allow_url_fopen:"0"},async()=>await e.request({url:"/wp-admin/install.php?step=2",method:"POST",body:{language:"en",prefix:"wp_",weblog_title:"My WordPress Website",user_name:"admin",admin_password:"password",admin_password2:"password",Submit:"Install WordPress",pw_weak:"1",admin_email:"admin@localhost.com"}}))}const nightly="nightly",beta="6.6-RC2",SupportedWordPressVersions={nightly,beta,"6.5":"6.5.5","6.4":"6.4.5","6.3":"6.3.5","6.2":"6.2.6"},SupportedWordPressVersionsList=Object.keys(SupportedWordPressVersions);SupportedWordPressVersionsList.filter(e=>e.match(/^\d/))[0];async function getLoadedWordPressVersion(e){const s=(await(await e.getPrimaryPhp()).run({code:`<?php
4
+ `})).text==="1"}async function P(e){await f(e,{disable_functions:"fsockopen",allow_url_fopen:"0"},async()=>await e.request({url:"/wp-admin/install.php?step=2",method:"POST",body:{language:"en",prefix:"wp_",weblog_title:"My WordPress Website",user_name:"admin",admin_password:"password",admin_password2:"password",Submit:"Install WordPress",pw_weak:"1",admin_email:"admin@localhost.com"}}))}async function k(e){const t=(await(await e.getPrimaryPhp()).run({code:`<?php
80
5
  require '${e.documentRoot}/wp-includes/version.php';
81
6
  echo $wp_version;
82
- `})).text;if(!s)throw new Error("Unable to read loaded WordPress version.");return versionStringToLoadedWordPressVersion(s)}function versionStringToLoadedWordPressVersion(e){if(/-(alpha|beta|RC)\d*-\d+$/.test(e))return"nightly";if(/-(beta|RC)\d*$/.test(e))return"beta";const s=e.match(/^(\d+\.\d+)(?:\.\d+)?$/);return s!==null?s[1]:e}function isSupportedWordPressVersion(e){return Object.keys(SupportedWordPressVersions).includes(e)}const wordPressRewriteRules=[{match:/^\/(.*?)(\/wp-(content|admin|includes)\/.*)/g,replacement:"$2"}];async function setupPlatformLevelMuPlugins(e){await e.mkdir("/internal/shared/mu-plugins"),await e.writeFile("/internal/shared/preload/env.php",`<?php
7
+ `})).text;if(!t)throw new Error("Unable to read loaded WordPress version.");return b(t)}function b(e){if(/-(alpha|beta|RC)\d*-\d+$/.test(e))return"nightly";if(/-(beta|RC)\d*$/.test(e))return"beta";const t=e.match(/^(\d+\.\d+)(?:\.\d+)?$/);return t!==null?t[1]:e}function q(e){return Object.keys($).includes(e)}const y=[{match:/^\/(.*?)(\/wp-(content|admin|includes)\/.*)/g,replacement:"$2"}];async function L(e){await e.mkdir("/internal/shared/mu-plugins"),await e.writeFile("/internal/shared/preload/env.php",`<?php
83
8
 
84
9
  // Allow adding filters/actions prior to loading WordPress.
85
10
  // $function_to_add MUST be a string.
@@ -183,18 +108,18 @@ ${bold} WASM ERROR${reset}${redBg}`);for(const t of e.split(`
183
108
  }
184
109
  return false;
185
110
  });
186
- })();`)}async function preloadPhpInfoRoute(e,t="/phpinfo.php"){await e.writeFile("/internal/shared/preload/phpinfo.php",`<?php
111
+ })();`)}async function E(e,a="/phpinfo.php"){await e.writeFile("/internal/shared/preload/phpinfo.php",`<?php
187
112
  // Render PHPInfo if the requested page is /phpinfo.php
188
- if ( ${phpVar(t)} === $_SERVER['REQUEST_URI'] ) {
113
+ if ( ${o(a)} === $_SERVER['REQUEST_URI'] ) {
189
114
  phpinfo();
190
115
  exit;
191
116
  }
192
- `)}async function preloadSqliteIntegration(e,t){await e.isDir("/tmp/sqlite-database-integration")&&await e.rmdir("/tmp/sqlite-database-integration",{recursive:!0}),await e.mkdir("/tmp/sqlite-database-integration"),await unzipFile(e,t,"/tmp/sqlite-database-integration");const r="/internal/shared/sqlite-database-integration";await e.mv("/tmp/sqlite-database-integration/sqlite-database-integration-main",r),await e.defineConstant("SQLITE_MAIN_FILE","1");const i=(await e.readFileAsText(joinPaths(r,"db.copy"))).replace("'{SQLITE_IMPLEMENTATION_FOLDER_PATH}'",phpVar(r)).replace("'{SQLITE_PLUGIN}'",phpVar(joinPaths(r,"load.php"))),n=joinPaths(await e.documentRoot,"wp-content/db.php"),o=`<?php
117
+ `)}async function S(e,a){await e.isDir("/tmp/sqlite-database-integration")&&await e.rmdir("/tmp/sqlite-database-integration",{recursive:!0}),await e.mkdir("/tmp/sqlite-database-integration"),await l(e,a,"/tmp/sqlite-database-integration");const r="/internal/shared/sqlite-database-integration";await e.mv("/tmp/sqlite-database-integration/sqlite-database-integration-main",r),await e.defineConstant("SQLITE_MAIN_FILE","1");const i=(await e.readFileAsText(s(r,"db.copy"))).replace("'{SQLITE_IMPLEMENTATION_FOLDER_PATH}'",o(r)).replace("'{SQLITE_PLUGIN}'",o(s(r,"load.php"))),d=s(await e.documentRoot,"wp-content/db.php"),n=`<?php
193
118
  // Do not preload this if WordPress comes with a custom db.php file.
194
- if(file_exists(${phpVar(n)})) {
119
+ if(file_exists(${o(d)})) {
195
120
  return;
196
121
  }
197
- ?>`,a="/internal/shared/mu-plugins/sqlite-database-integration.php";await e.writeFile(a,o+i),await e.writeFile("/internal/shared/preload/0-sqlite.php",o+`<?php
122
+ ?>`,p="/internal/shared/mu-plugins/sqlite-database-integration.php";await e.writeFile(p,n+i),await e.writeFile("/internal/shared/preload/0-sqlite.php",n+`<?php
198
123
 
199
124
  /**
200
125
  * Loads the SQLite integration plugin before WordPress is loaded
@@ -244,7 +169,7 @@ class Playground_SQLite_Integration_Loader {
244
169
  $GLOBALS['wpdb']->$name = $value;
245
170
  }
246
171
  protected function load_sqlite_integration() {
247
- require_once ${phpVar(a)};
172
+ require_once ${o(p)};
248
173
  }
249
174
  }
250
175
  $wpdb = $GLOBALS['wpdb'] = new Playground_SQLite_Integration_Loader();
@@ -266,4 +191,4 @@ if(!function_exists('mysqli_connect')) {
266
191
  var_dump(isset($wpdb));
267
192
  die("SQLite integration not loaded " . get_class($wpdb));
268
193
  }
269
- `)}async function unzipWordPress(e,t){e.mkdir("/tmp/unzipped-wordpress"),await unzipFile(e,t,"/tmp/unzipped-wordpress"),e.fileExists("/tmp/unzipped-wordpress/wordpress.zip")&&await unzipFile(e,"/tmp/unzipped-wordpress/wordpress.zip","/tmp/unzipped-wordpress");const r=e.fileExists("/tmp/unzipped-wordpress/wordpress")?"/tmp/unzipped-wordpress/wordpress":e.fileExists("/tmp/unzipped-wordpress/build")?"/tmp/unzipped-wordpress/build":"/tmp/unzipped-wordpress";e.mv(r,e.documentRoot),!e.fileExists(joinPaths(e.documentRoot,"wp-config.php"))&&e.fileExists(joinPaths(e.documentRoot,"wp-config-sample.php"))&&e.writeFile(joinPaths(e.documentRoot,"wp-config.php"),e.readFileAsText(joinPaths(e.documentRoot,"/wp-config-sample.php")))}export{bootWordPress,getLoadedWordPressVersion,isSupportedWordPressVersion,preloadPhpInfoRoute,preloadSqliteIntegration,setupPlatformLevelMuPlugins,unzipWordPress,wordPressRewriteRules};
194
+ `)}async function R(e,a){e.mkdir("/tmp/unzipped-wordpress"),await l(e,a,"/tmp/unzipped-wordpress"),e.fileExists("/tmp/unzipped-wordpress/wordpress.zip")&&await l(e,"/tmp/unzipped-wordpress/wordpress.zip","/tmp/unzipped-wordpress");const r=e.fileExists("/tmp/unzipped-wordpress/wordpress")?"/tmp/unzipped-wordpress/wordpress":e.fileExists("/tmp/unzipped-wordpress/build")?"/tmp/unzipped-wordpress/build":"/tmp/unzipped-wordpress";e.mv(r,e.documentRoot),!e.fileExists(s(e.documentRoot,"wp-config.php"))&&e.fileExists(s(e.documentRoot,"wp-config-sample.php"))&&e.writeFile(s(e.documentRoot,"wp-config.php"),e.readFileAsText(s(e.documentRoot,"/wp-config-sample.php")))}export{F as bootWordPress,k as getLoadedWordPressVersion,q as isSupportedWordPressVersion,E as preloadPhpInfoRoute,S as preloadSqliteIntegration,L as setupPlatformLevelMuPlugins,R as unzipWordPress,y as wordPressRewriteRules};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wp-playground/wordpress",
3
- "version": "0.9.14",
3
+ "version": "0.9.16",
4
4
  "description": "WordPress-related plumbing for WordPress Playground",
5
5
  "repository": {
6
6
  "type": "git",
@@ -16,6 +16,7 @@
16
16
  }
17
17
  ],
18
18
  "type": "module",
19
+ "types": "index.d.ts",
19
20
  "main": "./index.js",
20
21
  "typings": "./index.d.ts",
21
22
  "license": "GPL-2.0-or-later",
@@ -27,5 +28,5 @@
27
28
  "access": "public",
28
29
  "directory": "../../../dist/packages/playground/wordpress"
29
30
  },
30
- "gitHead": "787eee56fce781d74765e3012786e3f83f58b278"
31
+ "gitHead": "47110de9a9efc876f7b432c88d904ef081d1365c"
31
32
  }
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
package/boot.d.ts DELETED
@@ -1,80 +0,0 @@
1
- import { FileTree, PHP, PHPProcessManager, PHPRequestHandler, SpawnHandler } from '../../../php-wasm/universal/src/index.ts';
2
- export type PhpIniOptions = Record<string, string>;
3
- export type Hook = (php: PHP) => void | Promise<void>;
4
- export interface Hooks {
5
- beforeWordPressFiles?: Hook;
6
- beforeDatabaseSetup?: Hook;
7
- }
8
- export type DatabaseType = 'sqlite' | 'mysql' | 'custom';
9
- export interface BootOptions {
10
- createPhpRuntime: () => Promise<number>;
11
- /**
12
- * Mounting and Copying is handled via hooks for starters.
13
- *
14
- * In the future we could standardize the
15
- * browser-specific and node-specific mounts
16
- * in the future.
17
- */
18
- hooks?: Hooks;
19
- /**
20
- * PHP SAPI name to be returned by get_sapi_name(). Overriding
21
- * it is useful for running programs that check for this value,
22
- * e.g. WP-CLI
23
- */
24
- sapiName?: string;
25
- /**
26
- * URL to use as the site URL. This is used to set the WP_HOME
27
- * and WP_SITEURL constants in WordPress.
28
- */
29
- siteUrl: string;
30
- documentRoot?: string;
31
- /** SQL file to load instead of installing WordPress. */
32
- dataSqlPath?: string;
33
- /** Zip with the WordPress installation to extract in /wordpress. */
34
- wordPressZip?: File | Promise<File> | undefined;
35
- /** Preloaded SQLite integration plugin. */
36
- sqliteIntegrationPluginZip?: File | Promise<File>;
37
- spawnHandler?: (processManager: PHPProcessManager) => SpawnHandler;
38
- /**
39
- * PHP.ini entries to define before running any code. They'll
40
- * be used for all requests.
41
- */
42
- phpIniEntries?: PhpIniOptions;
43
- /**
44
- * PHP constants to define for every request.
45
- */
46
- constants?: Record<string, string | number | boolean | null>;
47
- /**
48
- * Files to create in the filesystem before any mounts are applied.
49
- *
50
- * Example:
51
- *
52
- * ```ts
53
- * {
54
- * createFiles: {
55
- * '/tmp/hello.txt': 'Hello, World!',
56
- * '/internal/preload': {
57
- * '1-custom-mu-plugin.php': '<?php echo "Hello, World!";',
58
- * }
59
- * }
60
- * }
61
- * ```
62
- */
63
- createFiles?: FileTree;
64
- }
65
- /**
66
- * Boots a WordPress instance with the given options.
67
- *
68
- * High-level overview:
69
- *
70
- * * Boot PHP instances and PHPRequestHandler
71
- * * Setup VFS, run beforeWordPressFiles hook
72
- * * Setup WordPress files (if wordPressZip is provided)
73
- * * Run beforeDatabaseSetup hook
74
- * * Setup the database – SQLite, MySQL (@TODO), or rely on a mounted database
75
- * * Run WordPress installer, if the site isn't installed yet
76
- *
77
- * @param options Boot configuration options
78
- * @return PHPRequestHandler instance with WordPress installed.
79
- */
80
- export declare function bootWordPress(options: BootOptions): Promise<PHPRequestHandler>;
@@ -1,5 +0,0 @@
1
- import type { RewriteRule } from '../../../php-wasm/universal/src/index.ts';
2
- /**
3
- * The default rewrite rules for WordPress.
4
- */
5
- export declare const wordPressRewriteRules: RewriteRule[];
@@ -1,4 +0,0 @@
1
- import type { PHPRequestHandler } from '../../../php-wasm/universal/src/index.ts';
2
- export declare function getLoadedWordPressVersion(requestHandler: PHPRequestHandler): Promise<string>;
3
- export declare function versionStringToLoadedWordPressVersion(wpVersionString: string): string;
4
- export declare function isSupportedWordPressVersion(wpVersion: string): boolean;