@php-wasm/universal 0.9.18 → 0.9.20

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.d.ts CHANGED
@@ -1,1605 +1 @@
1
- // Generated by dts-bundle-generator v7.2.0
2
-
3
- import { Remote } from 'comlink';
4
-
5
- declare class EmscriptenDownloadMonitor extends EventTarget {
6
- #private;
7
- expectAssets(assets: Record<string, number>): void;
8
- monitorFetch(fetchPromise: Promise<Response>): Promise<Response>;
9
- }
10
- export interface PHPResponseData {
11
- /**
12
- * Response headers.
13
- */
14
- readonly headers: Record<string, string[]>;
15
- /**
16
- * Response body. Contains the output from `echo`,
17
- * `print`, inline HTML etc.
18
- */
19
- readonly bytes: ArrayBuffer;
20
- /**
21
- * Stderr contents, if any.
22
- */
23
- readonly errors: string;
24
- /**
25
- * The exit code of the script. `0` is a success, while
26
- * `1` and `2` indicate an error.
27
- */
28
- readonly exitCode: number;
29
- /**
30
- * Response HTTP status code, e.g. 200.
31
- */
32
- readonly httpStatusCode: number;
33
- }
34
- /**
35
- * PHP response. Body is an `ArrayBuffer` because it can
36
- * contain binary data.
37
- *
38
- * This type is used in Comlink.transferHandlers.set('PHPResponse', \{ ... \})
39
- * so be sure to update that if you change this type.
40
- */
41
- export declare class PHPResponse implements PHPResponseData {
42
- /** @inheritDoc */
43
- readonly headers: Record<string, string[]>;
44
- /** @inheritDoc */
45
- readonly bytes: ArrayBuffer;
46
- /** @inheritDoc */
47
- readonly errors: string;
48
- /** @inheritDoc */
49
- readonly exitCode: number;
50
- /** @inheritDoc */
51
- readonly httpStatusCode: number;
52
- constructor(httpStatusCode: number, headers: Record<string, string[]>, body: ArrayBuffer, errors?: string, exitCode?: number);
53
- static forHttpCode(httpStatusCode: number, text?: string): PHPResponse;
54
- static fromRawData(data: PHPResponseData): PHPResponse;
55
- toRawData(): PHPResponseData;
56
- /**
57
- * Response body as JSON.
58
- */
59
- get json(): any;
60
- /**
61
- * Response body as text.
62
- */
63
- get text(): string;
64
- }
65
- /**
66
- * Loads the PHP runtime with the given arguments and data dependencies.
67
- *
68
- * This function handles the entire PHP initialization pipeline. In particular, it:
69
- *
70
- * * Instantiates the Emscripten PHP module
71
- * * Wires it together with the data dependencies and loads them
72
- * * Ensures is all happens in a correct order
73
- * * Waits until the entire loading sequence is finished
74
- *
75
- * Basic usage:
76
- *
77
- * ```js
78
- * const phpLoaderModule = await getPHPLoaderModule("7.4");
79
- * const php = await loadPHPRuntime( phpLoaderModule );
80
- * console.log(php.run(`<?php echo "Hello, world!"; `));
81
- * // { stdout: ArrayBuffer containing the string "Hello, world!", stderr: [''], exitCode: 0 }
82
- * ```
83
- *
84
- * **The PHP loader module:**
85
- *
86
- * In the basic usage example, `phpLoaderModule` is **not** a vanilla Emscripten module. Instead,
87
- * it's an ESM module that wraps the regular Emscripten output and adds some
88
- * extra functionality. It's generated by the Dockerfile shipped with this repo.
89
- * Here's the API it provides:
90
- *
91
- * ```js
92
- * // php.wasm size in bytes:
93
- * export const dependenciesTotalSize = 5644199;
94
- *
95
- * // php.wasm filename:
96
- * export const dependencyFilename = 'php.wasm';
97
- *
98
- * // Run Emscripten's generated module:
99
- * export default function(jsEnv, emscriptenModuleArgs) {}
100
- * ```
101
- *
102
- * **PHP Filesystem:**
103
- *
104
- * Once initialized, the PHP has its own filesystem separate from the project
105
- * files. It's provided by [Emscripten and uses its FS library](https://emscripten.org/docs/api_reference/Filesystem-API.html).
106
- *
107
- * The API exposed to you via the PHP class is succinct and abstracts
108
- * certain unintuitive parts of low-level filesystem interactions.
109
- *
110
- * Here's how to use it:
111
- *
112
- * ```js
113
- * // Recursively create a /var/www directory
114
- * php.mkdirTree('/var/www');
115
- *
116
- * console.log(php.fileExists('/var/www/file.txt'));
117
- * // false
118
- *
119
- * php.writeFile('/var/www/file.txt', 'Hello from the filesystem!');
120
- *
121
- * console.log(php.fileExists('/var/www/file.txt'));
122
- * // true
123
- *
124
- * console.log(php.readFile('/var/www/file.txt'));
125
- * // "Hello from the filesystem!
126
- *
127
- * // Delete the file:
128
- * php.unlink('/var/www/file.txt');
129
- * ```
130
- *
131
- * For more details consult the PHP class directly.
132
- *
133
- * **Data dependencies:**
134
- *
135
- * Using existing PHP packages by manually recreating them file-by-file would
136
- * be quite inconvenient. Fortunately, Emscripten provides a "data dependencies"
137
- * feature.
138
- *
139
- * Data dependencies consist of a `dependency.data` file and a `dependency.js` loader and
140
- * can be packaged with the [file_packager.py tool]( https://emscripten.org/docs/porting/files/packaging_files.html#packaging-using-the-file-packager-tool).
141
- * This project requires wrapping the Emscripten-generated `dependency.js` file in an ES
142
- * module as follows:
143
- *
144
- * 1. Prepend `export default function(emscriptenPHPModule) {'; `
145
- * 2. Prepend `export const dependencyFilename = '<DATA FILE NAME>'; `
146
- * 3. Prepend `export const dependenciesTotalSize = <DATA FILE SIZE>;`
147
- * 4. Append `}`
148
- *
149
- * Be sure to use the `--export-name="emscriptenPHPModule"` file_packager.py option.
150
- *
151
- * You want the final output to look as follows:
152
- *
153
- * ```js
154
- * export const dependenciesTotalSize = 5644199;
155
- * export const dependencyFilename = 'dependency.data';
156
- * export default function(emscriptenPHPModule) {
157
- * // Emscripten-generated code:
158
- * var Module = typeof emscriptenPHPModule !== 'undefined' ? emscriptenPHPModule : {};
159
- * // ... the rest of it ...
160
- * }
161
- * ```
162
- *
163
- * Such a constructions enables loading the `dependency.js` as an ES Module using
164
- * `import("/dependency.js")`.
165
- *
166
- * Once it's ready, you can load PHP and your data dependencies as follows:
167
- *
168
- * ```js
169
- * const [phpLoaderModule, wordPressLoaderModule] = await Promise.all([
170
- * getPHPLoaderModule("7.4"),
171
- * import("/wp.js")
172
- * ]);
173
- * const php = await loadPHPRuntime(phpLoaderModule, {}, [wordPressLoaderModule]);
174
- * ```
175
- *
176
- * @public
177
- * @param phpLoaderModule - The ESM-wrapped Emscripten module. Consult the Dockerfile for the build process.
178
- * @param phpModuleArgs - The Emscripten module arguments, see https://emscripten.org/docs/api_reference/module.html#affecting-execution.
179
- * @returns Loaded runtime id.
180
- */
181
- export declare function loadPHPRuntime(phpLoaderModule: PHPLoaderModule, phpModuleArgs?: EmscriptenOptions): Promise<number>;
182
- export type RuntimeType = "NODE" | "WEB" | "WORKER";
183
- export type PHPRuntimeId = number;
184
- export type PHPRuntime = any;
185
- export type PHPLoaderModule = {
186
- dependencyFilename: string;
187
- dependenciesTotalSize: number;
188
- init: (jsRuntime: string, options: EmscriptenOptions) => PHPRuntime;
189
- };
190
- export type DataModule = {
191
- dependencyFilename: string;
192
- dependenciesTotalSize: number;
193
- default: (phpRuntime: PHPRuntime) => void;
194
- };
195
- export type EmscriptenOptions = {
196
- onAbort?: (message: string) => void;
197
- /**
198
- * Set to true for debugging tricky WebAssembly errors.
199
- */
200
- debug?: boolean;
201
- ENV?: Record<string, string>;
202
- locateFile?: (path: string) => string;
203
- noInitialRun?: boolean;
204
- print?: (message: string) => void;
205
- printErr?: (message: string) => void;
206
- quit?: (status: number, toThrow: any) => void;
207
- onRuntimeInitialized?: () => void;
208
- monitorRunDependencies?: (left: number) => void;
209
- onMessage?: (listener: EmscriptenMessageListener) => void;
210
- instantiateWasm?: (info: WebAssembly.Imports, receiveInstance: (instance: WebAssembly.Instance, module: WebAssembly.Module) => void) => void;
211
- } & Record<string, any>;
212
- export type EmscriptenMessageListener = (type: string, data: string) => void;
213
- /** Other WebAssembly declarations, for compatibility with older versions of Typescript */
214
- export declare namespace Emscripten {
215
- export interface RootFS extends Emscripten.FileSystemInstance {
216
- filesystems: Record<string, Emscripten.FileSystemType>;
217
- }
218
- export interface FileSystemType {
219
- mount(mount: FS.Mount): FS.FSNode;
220
- syncfs(mount: FS.Mount, populate: () => unknown, done: (err?: number | null) => unknown): void;
221
- }
222
- export type EnvironmentType = "WEB" | "NODE" | "SHELL" | "WORKER";
223
- export type JSType = "number" | "string" | "array" | "boolean";
224
- export type TypeCompatibleWithC = number | string | any[] | boolean;
225
- export type CIntType = "i8" | "i16" | "i32" | "i64";
226
- export type CFloatType = "float" | "double";
227
- export type CPointerType = "i8*" | "i16*" | "i32*" | "i64*" | "float*" | "double*" | "*";
228
- export type CType = CIntType | CFloatType | CPointerType;
229
- export interface CCallOpts {
230
- async?: boolean | undefined;
231
- }
232
- type NamespaceToInstance<T> = {
233
- [K in keyof T]: T[K] extends (...args: any[]) => any ? T[K] : never;
234
- };
235
- export type FileSystemInstance = NamespaceToInstance<typeof FS> & {
236
- mkdirTree(path: string): void;
237
- lookupPath(path: string, opts?: any): FS.Lookup;
238
- };
239
- export interface EmscriptenModule {
240
- print(str: string): void;
241
- printErr(str: string): void;
242
- arguments: string[];
243
- environment: Emscripten.EnvironmentType;
244
- preInit: Array<{
245
- (): void;
246
- }>;
247
- preRun: Array<{
248
- (): void;
249
- }>;
250
- postRun: Array<{
251
- (): void;
252
- }>;
253
- onAbort: {
254
- (what: any): void;
255
- };
256
- onRuntimeInitialized: {
257
- (): void;
258
- };
259
- preinitializedWebGLContext: WebGLRenderingContext;
260
- noInitialRun: boolean;
261
- noExitRuntime: boolean;
262
- logReadFiles: boolean;
263
- filePackagePrefixURL: string;
264
- wasmBinary: ArrayBuffer;
265
- destroy(object: object): void;
266
- getPreloadedPackage(remotePackageName: string, remotePackageSize: number): ArrayBuffer;
267
- instantiateWasm(imports: WebAssembly.Imports, successCallback: (module: WebAssembly.Instance) => void): WebAssembly.Exports | undefined;
268
- locateFile(url: string, scriptDirectory: string): string;
269
- onCustomMessage(event: MessageEvent): void;
270
- HEAP: Int32Array;
271
- IHEAP: Int32Array;
272
- FHEAP: Float64Array;
273
- HEAP8: Int8Array;
274
- HEAP16: Int16Array;
275
- HEAP32: Int32Array;
276
- HEAPU8: Uint8Array;
277
- HEAPU16: Uint16Array;
278
- HEAPU32: Uint32Array;
279
- HEAPF32: Float32Array;
280
- HEAPF64: Float64Array;
281
- HEAP64: BigInt64Array;
282
- HEAPU64: BigUint64Array;
283
- TOTAL_STACK: number;
284
- TOTAL_MEMORY: number;
285
- FAST_MEMORY: number;
286
- addOnPreRun(cb: () => any): void;
287
- addOnInit(cb: () => any): void;
288
- addOnPreMain(cb: () => any): void;
289
- addOnExit(cb: () => any): void;
290
- addOnPostRun(cb: () => any): void;
291
- preloadedImages: any;
292
- preloadedAudios: any;
293
- _malloc(size: number): number;
294
- _free(ptr: number): void;
295
- }
296
- /**
297
- * A factory function is generated when setting the `MODULARIZE` build option
298
- * to `1` in your Emscripten build. It return a Promise that resolves to an
299
- * initialized, ready-to-call `EmscriptenModule` instance.
300
- *
301
- * By default, the factory function will be named `Module`. It's recommended to
302
- * use the `EXPORT_ES6` option, in which the factory function will be the
303
- * default export. If used without `EXPORT_ES6`, the factory function will be a
304
- * global variable. You can rename the variable using the `EXPORT_NAME` build
305
- * option. It's left to you to export any global variables as needed in your
306
- * application's types.
307
- * @param moduleOverrides Default properties for the initialized module.
308
- */
309
- export type EmscriptenModuleFactory<T extends EmscriptenModule = EmscriptenModule> = (moduleOverrides?: Partial<T>) => Promise<T>;
310
- export namespace FS {
311
- interface Lookup {
312
- path: string;
313
- node: FSNode;
314
- }
315
- interface Analyze {
316
- isRoot: boolean;
317
- exists: boolean;
318
- error: Error;
319
- name: string;
320
- path: Lookup["path"];
321
- object: Lookup["node"];
322
- parentExists: boolean;
323
- parentPath: Lookup["path"];
324
- parentObject: Lookup["node"];
325
- }
326
- interface Mount {
327
- type: Emscripten.FileSystemType;
328
- opts: object;
329
- mountpoint: string;
330
- mounts: Mount[];
331
- root: FSNode;
332
- }
333
- class FSStream {
334
- constructor();
335
- object: FSNode;
336
- readonly isRead: boolean;
337
- readonly isWrite: boolean;
338
- readonly isAppend: boolean;
339
- flags: number;
340
- position: number;
341
- }
342
- class FSNode {
343
- parent: FSNode;
344
- mount: Mount;
345
- mounted?: Mount;
346
- id: number;
347
- name: string;
348
- mode: number;
349
- rdev: number;
350
- readMode: number;
351
- writeMode: number;
352
- constructor(parent: FSNode, name: string, mode: number, rdev: number);
353
- read: boolean;
354
- write: boolean;
355
- readonly isFolder: boolean;
356
- readonly isDevice: boolean;
357
- }
358
- interface ErrnoError extends Error {
359
- name: "ErronoError";
360
- errno: number;
361
- code: string;
362
- }
363
- function lookupPath(path: string, opts: any): Lookup;
364
- function getPath(node: FSNode): string;
365
- function analyzePath(path: string, dontResolveLastLink?: boolean): Analyze;
366
- function isFile(mode: number): boolean;
367
- function isDir(mode: number): boolean;
368
- function isLink(mode: number): boolean;
369
- function isChrdev(mode: number): boolean;
370
- function isBlkdev(mode: number): boolean;
371
- function isFIFO(mode: number): boolean;
372
- function isSocket(mode: number): boolean;
373
- function major(dev: number): number;
374
- function minor(dev: number): number;
375
- function makedev(ma: number, mi: number): number;
376
- function registerDevice(dev: number, ops: any): void;
377
- function syncfs(populate: boolean, callback: (e: any) => any): void;
378
- function syncfs(callback: (e: any) => any, populate?: boolean): void;
379
- function mount(type: Emscripten.FileSystemType, opts: any, mountpoint: string): any;
380
- function unmount(mountpoint: string): void;
381
- function mkdir(path: string, mode?: number): any;
382
- function mkdev(path: string, mode?: number, dev?: number): any;
383
- function symlink(oldpath: string, newpath: string): any;
384
- function rename(old_path: string, new_path: string): void;
385
- function rmdir(path: string): void;
386
- function readdir(path: string): any;
387
- function unlink(path: string): void;
388
- function readlink(path: string): string;
389
- function stat(path: string, dontFollow?: boolean): any;
390
- function lstat(path: string): any;
391
- function chmod(path: string, mode: number, dontFollow?: boolean): void;
392
- function lchmod(path: string, mode: number): void;
393
- function fchmod(fd: number, mode: number): void;
394
- function chown(path: string, uid: number, gid: number, dontFollow?: boolean): void;
395
- function lchown(path: string, uid: number, gid: number): void;
396
- function fchown(fd: number, uid: number, gid: number): void;
397
- function truncate(path: string, len: number): void;
398
- function ftruncate(fd: number, len: number): void;
399
- function utime(path: string, atime: number, mtime: number): void;
400
- function open(path: string, flags: string, mode?: number, fd_start?: number, fd_end?: number): FSStream;
401
- function close(stream: FSStream): void;
402
- function llseek(stream: FSStream, offset: number, whence: number): any;
403
- function read(stream: FSStream, buffer: ArrayBufferView, offset: number, length: number, position?: number): number;
404
- function write(stream: FSStream, buffer: ArrayBufferView, offset: number, length: number, position?: number, canOwn?: boolean): number;
405
- function allocate(stream: FSStream, offset: number, length: number): void;
406
- function mmap(stream: FSStream, buffer: ArrayBufferView, offset: number, length: number, position: number, prot: number, flags: number): any;
407
- function ioctl(stream: FSStream, cmd: any, arg: any): any;
408
- function readFile(path: string, opts: {
409
- encoding: "binary";
410
- flags?: string | undefined;
411
- }): Uint8Array;
412
- function readFile(path: string, opts: {
413
- encoding: "utf8";
414
- flags?: string | undefined;
415
- }): string;
416
- function readFile(path: string, opts?: {
417
- flags?: string | undefined;
418
- }): Uint8Array;
419
- function writeFile(path: string, data: string | ArrayBufferView, opts?: {
420
- flags?: string | undefined;
421
- }): void;
422
- function cwd(): string;
423
- function chdir(path: string): void;
424
- function init(input: null | (() => number | null), output: null | ((c: number) => any), error: null | ((c: number) => any)): void;
425
- function createLazyFile(parent: string | FSNode, name: string, url: string, canRead: boolean, canWrite: boolean): FSNode;
426
- function createPreloadedFile(parent: string | FSNode, name: string, url: string, canRead: boolean, canWrite: boolean, onload?: () => void, onerror?: () => void, dontCreateFile?: boolean, canOwn?: boolean): void;
427
- function createDataFile(parent: string | FSNode, name: string, data: ArrayBufferView, canRead: boolean, canWrite: boolean, canOwn: boolean): FSNode;
428
- }
429
- export const MEMFS: Emscripten.FileSystemType;
430
- export const NODEFS: Emscripten.FileSystemType;
431
- export const IDBFS: Emscripten.FileSystemType;
432
- type StringToType<R> = R extends Emscripten.JSType ? {
433
- number: number;
434
- string: string;
435
- array: number[] | string[] | boolean[] | Uint8Array | Int8Array;
436
- boolean: boolean;
437
- null: null;
438
- }[R] : never;
439
- type ArgsToType<T extends Array<Emscripten.JSType | null>> = Extract<{
440
- [P in keyof T]: StringToType<T[P]>;
441
- }, any[]>;
442
- type ReturnToType<R extends Emscripten.JSType | null> = R extends null ? null : StringToType<Exclude<R, null>>;
443
- export function cwrap<I extends Array<Emscripten.JSType | null> | [
444
- ], R extends Emscripten.JSType | null>(ident: string, returnType: R, argTypes: I, opts?: Emscripten.CCallOpts): (...arg: ArgsToType<I>) => ReturnToType<R>;
445
- export function ccall<I extends Array<Emscripten.JSType | null> | [
446
- ], R extends Emscripten.JSType | null>(ident: string, returnType: R, argTypes: I, args: ArgsToType<I>, opts?: Emscripten.CCallOpts): ReturnToType<R>;
447
- export function setValue(ptr: number, value: any, type: Emscripten.CType, noSafe?: boolean): void;
448
- export function getValue(ptr: number, type: Emscripten.CType, noSafe?: boolean): number;
449
- export function allocate(slab: number[] | ArrayBufferView | number, types: Emscripten.CType | Emscripten.CType[], allocator: number, ptr?: number): number;
450
- export function stackAlloc(size: number): number;
451
- export function stackSave(): number;
452
- export function stackRestore(ptr: number): void;
453
- export function UTF8ToString(ptr: number, maxBytesToRead?: number): string;
454
- export function stringToUTF8(str: string, outPtr: number, maxBytesToRead?: number): void;
455
- export function lengthBytesUTF8(str: string): number;
456
- export function allocateUTF8(str: string): number;
457
- export function allocateUTF8OnStack(str: string): number;
458
- export function UTF16ToString(ptr: number): string;
459
- export function stringToUTF16(str: string, outPtr: number, maxBytesToRead?: number): void;
460
- export function lengthBytesUTF16(str: string): number;
461
- export function UTF32ToString(ptr: number): string;
462
- export function stringToUTF32(str: string, outPtr: number, maxBytesToRead?: number): void;
463
- export function lengthBytesUTF32(str: string): number;
464
- export function intArrayFromString(stringy: string, dontAddNull?: boolean, length?: number): number[];
465
- export function intArrayToString(array: number[]): string;
466
- export function writeStringToMemory(str: string, buffer: number, dontAddNull: boolean): void;
467
- export function writeArrayToMemory(array: number[], buffer: number): void;
468
- export function writeAsciiToMemory(str: string, buffer: number, dontAddNull: boolean): void;
469
- export function addRunDependency(id: any): void;
470
- export function removeRunDependency(id: any): void;
471
- export function addFunction(func: (...args: any[]) => any, signature?: string): number;
472
- export function removeFunction(funcPtr: number): void;
473
- export const ALLOC_NORMAL: number;
474
- export const ALLOC_STACK: number;
475
- export const ALLOC_STATIC: number;
476
- export const ALLOC_DYNAMIC: number;
477
- export const ALLOC_NONE: number;
478
- export {};
479
- }
480
- export interface RmDirOptions {
481
- /**
482
- * If true, recursively removes the directory and all its contents.
483
- * Default: true.
484
- */
485
- recursive?: boolean;
486
- }
487
- export interface ListFilesOptions {
488
- /**
489
- * If true, prepend given folder path to all file names.
490
- * Default: false.
491
- */
492
- prependPath: boolean;
493
- }
494
- export declare class FSHelpers {
495
- /**
496
- * Reads a file from the PHP filesystem and returns it as a string.
497
- *
498
- * @throws {@link @php-wasm/universal:ErrnoError} – If the file doesn't exist.
499
- * @param path - The file path to read.
500
- * @returns The file contents.
501
- */
502
- static readFileAsText(FS: Emscripten.RootFS, path: string): string;
503
- /**
504
- * Reads a file from the PHP filesystem and returns it as an array buffer.
505
- *
506
- * @throws {@link @php-wasm/universal:ErrnoError} – If the file doesn't exist.
507
- * @param path - The file path to read.
508
- * @returns The file contents.
509
- */
510
- static readFileAsBuffer(FS: Emscripten.RootFS, path: string): Uint8Array;
511
- /**
512
- * Overwrites data in a file in the PHP filesystem.
513
- * Creates a new file if one doesn't exist yet.
514
- *
515
- * @param path - The file path to write to.
516
- * @param data - The data to write to the file.
517
- */
518
- static writeFile(FS: Emscripten.RootFS, path: string, data: string | Uint8Array): void;
519
- /**
520
- * Removes a file from the PHP filesystem.
521
- *
522
- * @throws {@link @php-wasm/universal:ErrnoError} – If the file doesn't exist.
523
- * @param path - The file path to remove.
524
- */
525
- static unlink(FS: Emscripten.RootFS, path: string): void;
526
- /**
527
- * Moves a file or directory in the PHP filesystem to a
528
- * new location.
529
- *
530
- * @param oldPath The path to rename.
531
- * @param newPath The new path.
532
- */
533
- static mv(FS: Emscripten.RootFS, fromPath: string, toPath: string): void;
534
- /**
535
- * Removes a directory from the PHP filesystem.
536
- *
537
- * @param path The directory path to remove.
538
- * @param options Options for the removal.
539
- */
540
- static rmdir(FS: Emscripten.RootFS, path: string, options?: RmDirOptions): void;
541
- /**
542
- * Lists the files and directories in the given directory.
543
- *
544
- * @param path - The directory path to list.
545
- * @param options - Options for the listing.
546
- * @returns The list of files and directories in the given directory.
547
- */
548
- static listFiles(FS: Emscripten.RootFS, path: string, options?: ListFilesOptions): string[];
549
- /**
550
- * Checks if a directory exists in the PHP filesystem.
551
- *
552
- * @param path – The path to check.
553
- * @returns True if the path is a directory, false otherwise.
554
- */
555
- static isDir(FS: Emscripten.RootFS, path: string): boolean;
556
- /**
557
- * Checks if a file (or a directory) exists in the PHP filesystem.
558
- *
559
- * @param path - The file path to check.
560
- * @returns True if the file exists, false otherwise.
561
- */
562
- static fileExists(FS: Emscripten.RootFS, path: string): boolean;
563
- /**
564
- * Recursively creates a directory with the given path in the PHP filesystem.
565
- * For example, if the path is `/root/php/data`, and `/root` already exists,
566
- * it will create the directories `/root/php` and `/root/php/data`.
567
- *
568
- * @param path - The directory path to create.
569
- */
570
- static mkdir(FS: Emscripten.RootFS, path: string): void;
571
- static copyRecursive(FS: Emscripten.FileSystemInstance, fromPath: string, toPath: string): void;
572
- }
573
- export interface SemaphoreOptions {
574
- /**
575
- * The maximum number of concurrent locks.
576
- */
577
- concurrency: number;
578
- /**
579
- * The maximum time to wait for a lock to become available.
580
- */
581
- timeout?: number;
582
- }
583
- declare class Semaphore {
584
- private _running;
585
- private concurrency;
586
- private timeout?;
587
- private queue;
588
- constructor({ concurrency, timeout }: SemaphoreOptions);
589
- get remaining(): number;
590
- get running(): number;
591
- acquire(): Promise<() => void>;
592
- run<T>(fn: () => T | Promise<T>): Promise<T>;
593
- }
594
- export type PHPFactoryOptions = {
595
- isPrimary: boolean;
596
- };
597
- export type PHPFactory = (options: PHPFactoryOptions) => Promise<PHP>;
598
- export interface ProcessManagerOptions {
599
- /**
600
- * The maximum number of PHP instances that can exist at
601
- * the same time.
602
- */
603
- maxPhpInstances?: number;
604
- /**
605
- * The number of milliseconds to wait for a PHP instance when
606
- * we have reached the maximum number of PHP instances and
607
- * cannot spawn a new one. If the timeout is reached, we assume
608
- * all the PHP instances are deadlocked and a throw MaxPhpInstancesError.
609
- *
610
- * Default: 5000
611
- */
612
- timeout?: number;
613
- /**
614
- * The primary PHP instance that's never killed. This instance
615
- * contains the reference filesystem used by all other PHP instances.
616
- */
617
- primaryPhp?: PHP;
618
- /**
619
- * A factory function used for spawning new PHP instances.
620
- */
621
- phpFactory?: PHPFactory;
622
- }
623
- export interface SpawnedPHP {
624
- php: PHP;
625
- reap: () => void;
626
- }
627
- export declare class MaxPhpInstancesError extends Error {
628
- constructor(limit: number);
629
- }
630
- /**
631
- * A PHP Process manager.
632
- *
633
- * Maintains:
634
- * * A single "primary" PHP instance that's never killed – it contains the
635
- * reference filesystem used by all other PHP instances.
636
- * * A pool of disposable PHP instances that are spawned to handle a single
637
- * request and reaped immediately after.
638
- *
639
- * When a new request comes in, PHPProcessManager yields the idle instance to handle it,
640
- * and immediately starts initializing a new idle instance. In other words, for n concurrent
641
- * requests, there are at most n+1 PHP instances running at the same time.
642
- *
643
- * A slight nuance is that the first idle instance is not initialized until the first
644
- * concurrent request comes in. This is because many use-cases won't involve parallel
645
- * requests and, for those, we can avoid eagerly spinning up a second PHP instance.
646
- *
647
- * This strategy is inspired by Cowboy, an Erlang HTTP server. Handling a single extra
648
- * request can happen immediately, while handling multiple extra requests requires
649
- * extra time to spin up a few PHP instances. This is a more resource-friendly tradeoff
650
- * than keeping 5 idle instances at all times.
651
- */
652
- export declare class PHPProcessManager implements AsyncDisposable {
653
- private primaryPhp?;
654
- private primaryIdle;
655
- private nextInstance;
656
- /**
657
- * All spawned PHP instances, including the primary PHP instance.
658
- * Used for bookkeeping and reaping all instances on dispose.
659
- */
660
- private allInstances;
661
- private phpFactory?;
662
- private maxPhpInstances;
663
- private semaphore;
664
- constructor(options?: ProcessManagerOptions);
665
- /**
666
- * Get the primary PHP instance.
667
- *
668
- * If the primary PHP instance is not set, it will be spawned
669
- * using the provided phpFactory.
670
- *
671
- * @throws {Error} when called twice before the first call is resolved.
672
- */
673
- getPrimaryPhp(): Promise<PHP>;
674
- /**
675
- * Get a PHP instance.
676
- *
677
- * It could be either the primary PHP instance, an idle disposable PHP instance,
678
- * or a newly spawned PHP instance – depending on the resource availability.
679
- *
680
- * @throws {MaxPhpInstancesError} when the maximum number of PHP instances is reached
681
- * and the waiting timeout is exceeded.
682
- */
683
- acquirePHPInstance(): Promise<SpawnedPHP>;
684
- /**
685
- * Initiated spawning of a new PHP instance.
686
- * This function is synchronous on purpose – it needs to synchronously
687
- * add the spawn promise to the allInstances array without waiting
688
- * for PHP to spawn.
689
- */
690
- private spawn;
691
- /**
692
- * Actually acquires the lock and spawns a new PHP instance.
693
- */
694
- private doSpawn;
695
- [Symbol.asyncDispose](): Promise<void>;
696
- }
697
- export type RewriteRule = {
698
- match: RegExp;
699
- replacement: string;
700
- };
701
- export interface BaseConfiguration {
702
- /**
703
- * The directory in the PHP filesystem where the server will look
704
- * for the files to serve. Default: `/var/www`.
705
- */
706
- documentRoot?: string;
707
- /**
708
- * Request Handler URL. Used to populate $_SERVER details like HTTP_HOST.
709
- */
710
- absoluteUrl?: string;
711
- /**
712
- * Rewrite rules
713
- */
714
- rewriteRules?: RewriteRule[];
715
- }
716
- export type PHPRequestHandlerFactoryArgs = PHPFactoryOptions & {
717
- requestHandler: PHPRequestHandler;
718
- };
719
- export type PHPRequestHandlerConfiguration = BaseConfiguration & ({
720
- /**
721
- * PHPProcessManager is required because the request handler needs
722
- * to make a decision for each request.
723
- *
724
- * Static assets are served using the primary PHP's filesystem, even
725
- * when serving 100 static files concurrently. No new PHP interpreter
726
- * is ever created as there's no need for it.
727
- *
728
- * Dynamic PHP requests, however, require grabbing an available PHP
729
- * interpreter, and that's where the PHPProcessManager comes in.
730
- */
731
- processManager: PHPProcessManager;
732
- } | {
733
- phpFactory: (requestHandler: PHPRequestHandlerFactoryArgs) => Promise<PHP>;
734
- /**
735
- * The maximum number of PHP instances that can exist at
736
- * the same time.
737
- */
738
- maxPhpInstances?: number;
739
- });
740
- /**
741
- * Handles HTTP requests using PHP runtime as a backend.
742
- *
743
- * @public
744
- * @example Use PHPRequestHandler implicitly with a new PHP instance:
745
- * ```js
746
- * import { PHP } from '@php-wasm/web';
747
- *
748
- * const php = await PHP.load( '7.4', {
749
- * requestHandler: {
750
- * // PHP FS path to serve the files from:
751
- * documentRoot: '/www',
752
- *
753
- * // Used to populate $_SERVER['SERVER_NAME'] etc.:
754
- * absoluteUrl: 'http://127.0.0.1'
755
- * }
756
- * } );
757
- *
758
- * php.mkdirTree('/www');
759
- * php.writeFile('/www/index.php', '<?php echo "Hi from PHP!"; ');
760
- *
761
- * const response = await php.request({ path: '/index.php' });
762
- * console.log(response.text);
763
- * // "Hi from PHP!"
764
- * ```
765
- *
766
- * @example Explicitly create a PHPRequestHandler instance and run a PHP script:
767
- * ```js
768
- * import {
769
- * loadPHPRuntime,
770
- * PHP,
771
- * PHPRequestHandler,
772
- * getPHPLoaderModule,
773
- * } from '@php-wasm/web';
774
- *
775
- * const runtime = await loadPHPRuntime( await getPHPLoaderModule('7.4') );
776
- * const php = new PHP( runtime );
777
- *
778
- * php.mkdirTree('/www');
779
- * php.writeFile('/www/index.php', '<?php echo "Hi from PHP!"; ');
780
- *
781
- * const server = new PHPRequestHandler(php, {
782
- * // PHP FS path to serve the files from:
783
- * documentRoot: '/www',
784
- *
785
- * // Used to populate $_SERVER['SERVER_NAME'] etc.:
786
- * absoluteUrl: 'http://127.0.0.1'
787
- * });
788
- *
789
- * const response = server.request({ path: '/index.php' });
790
- * console.log(response.text);
791
- * // "Hi from PHP!"
792
- * ```
793
- */
794
- export declare class PHPRequestHandler {
795
- #private;
796
- rewriteRules: RewriteRule[];
797
- processManager: PHPProcessManager;
798
- /**
799
- * The request handler needs to decide whether to serve a static asset or
800
- * run the PHP interpreter. For static assets it should just reuse the primary
801
- * PHP even if there's 50 concurrent requests to serve. However, for
802
- * dynamic PHP requests, it needs to grab an available interpreter.
803
- * Therefore, it cannot just accept PHP as an argument as serving requests
804
- * requires access to ProcessManager.
805
- *
806
- * @param php - The PHP instance.
807
- * @param config - Request Handler configuration.
808
- */
809
- constructor(config: PHPRequestHandlerConfiguration);
810
- getPrimaryPhp(): Promise<PHP>;
811
- /**
812
- * Converts a path to an absolute URL based at the PHPRequestHandler
813
- * root.
814
- *
815
- * @param path The server path to convert to an absolute URL.
816
- * @returns The absolute URL.
817
- */
818
- pathToInternalUrl(path: string): string;
819
- /**
820
- * Converts an absolute URL based at the PHPRequestHandler to a relative path
821
- * without the server pathname and scope.
822
- *
823
- * @param internalUrl An absolute URL based at the PHPRequestHandler root.
824
- * @returns The relative path.
825
- */
826
- internalUrlToPath(internalUrl: string): string;
827
- /**
828
- * The absolute URL of this PHPRequestHandler instance.
829
- */
830
- get absoluteUrl(): string;
831
- /**
832
- * The directory in the PHP filesystem where the server will look
833
- * for the files to serve. Default: `/var/www`.
834
- */
835
- get documentRoot(): string;
836
- /**
837
- * Serves the request – either by serving a static file, or by
838
- * dispatching it to the PHP runtime.
839
- *
840
- * The request() method mode behaves like a web server and only works if
841
- * the PHP was initialized with a `requestHandler` option (which the online version
842
- * of WordPress Playground does by default).
843
- *
844
- * In the request mode, you pass an object containing the request information
845
- * (method, headers, body, etc.) and the path to the PHP file to run:
846
- *
847
- * ```ts
848
- * const php = PHP.load('7.4', {
849
- * requestHandler: {
850
- * documentRoot: "/www"
851
- * }
852
- * })
853
- * php.writeFile("/www/index.php", `<?php echo file_get_contents("php://input");`);
854
- * const result = await php.request({
855
- * method: "GET",
856
- * headers: {
857
- * "Content-Type": "text/plain"
858
- * },
859
- * body: "Hello world!",
860
- * path: "/www/index.php"
861
- * });
862
- * // result.text === "Hello world!"
863
- * ```
864
- *
865
- * The `request()` method cannot be used in conjunction with `cli()`.
866
- *
867
- * @example
868
- * ```js
869
- * const output = await php.request({
870
- * method: 'GET',
871
- * url: '/index.php',
872
- * headers: {
873
- * 'X-foo': 'bar',
874
- * },
875
- * body: {
876
- * foo: 'bar',
877
- * },
878
- * });
879
- * console.log(output.stdout); // "Hello world!"
880
- * ```
881
- *
882
- * @param request - PHP Request data.
883
- */
884
- request(request: PHPRequest): Promise<PHPResponse>;
885
- }
886
- /**
887
- * Applies the given rewrite rules to the given path.
888
- *
889
- * @param path The path to apply the rules to.
890
- * @param rules The rules to apply.
891
- * @returns The path with the rules applied.
892
- */
893
- export declare function applyRewriteRules(path: string, rules: RewriteRule[]): string;
894
- declare const __private__dont__use: unique symbol;
895
- export type UnmountFunction = (() => Promise<any>) | (() => any);
896
- export type MountHandler = (php: PHP, FS: Emscripten.RootFS, vfsMountPoint: string) => UnmountFunction | Promise<UnmountFunction>;
897
- /**
898
- * An environment-agnostic wrapper around the Emscripten PHP runtime
899
- * that universals the super low-level API and provides a more convenient
900
- * higher-level API.
901
- *
902
- * It exposes a minimal set of methods to run PHP scripts and to
903
- * interact with the PHP filesystem.
904
- */
905
- export declare class PHP implements Disposable {
906
- #private;
907
- protected [__private__dont__use]: any;
908
- requestHandler?: PHPRequestHandler;
909
- /**
910
- * An exclusive lock that prevent multiple requests from running at
911
- * the same time.
912
- */
913
- semaphore: Semaphore;
914
- /**
915
- * Initializes a PHP runtime.
916
- *
917
- * @internal
918
- * @param PHPRuntime - Optional. PHP Runtime ID as initialized by loadPHPRuntime.
919
- * @param requestHandlerOptions - Optional. Options for the PHPRequestHandler. If undefined, no request handler will be initialized.
920
- */
921
- constructor(PHPRuntimeId?: PHPRuntimeId);
922
- /**
923
- * Adds an event listener for a PHP event.
924
- * @param eventType - The type of event to listen for.
925
- * @param listener - The listener function to be called when the event is triggered.
926
- */
927
- addEventListener(eventType: PHPEvent["type"], listener: PHPEventListener): void;
928
- /**
929
- * Removes an event listener for a PHP event.
930
- * @param eventType - The type of event to remove the listener from.
931
- * @param listener - The listener function to be removed.
932
- */
933
- removeEventListener(eventType: PHPEvent["type"], listener: PHPEventListener): void;
934
- dispatchEvent<Event extends PHPEvent>(event: Event): void;
935
- /**
936
- * Listens to message sent by the PHP code.
937
- *
938
- * To dispatch messages, call:
939
- *
940
- * post_message_to_js(string $data)
941
- *
942
- * Arguments:
943
- * $data (string) – Data to pass to JavaScript.
944
- *
945
- * @example
946
- *
947
- * ```ts
948
- * const php = await PHP.load('8.0');
949
- *
950
- * php.onMessage(
951
- * // The data is always passed as a string
952
- * function (data: string) {
953
- * // Let's decode and log the data:
954
- * console.log(JSON.parse(data));
955
- * }
956
- * );
957
- *
958
- * // Now that we have a listener in place, let's
959
- * // dispatch a message:
960
- * await php.run({
961
- * code: `<?php
962
- * post_message_to_js(
963
- * json_encode([
964
- * 'post_id' => '15',
965
- * 'post_title' => 'This is a blog post!'
966
- * ])
967
- * ));
968
- * `,
969
- * });
970
- * ```
971
- *
972
- * @param listener Callback function to handle the message.
973
- */
974
- onMessage(listener: MessageListener): void;
975
- setSpawnHandler(handler: SpawnHandler | string): Promise<void>;
976
- /** @deprecated Use PHPRequestHandler instead. */
977
- get absoluteUrl(): string;
978
- /** @deprecated Use PHPRequestHandler instead. */
979
- get documentRoot(): string;
980
- /** @deprecated Use PHPRequestHandler instead. */
981
- pathToInternalUrl(path: string): string;
982
- /** @deprecated Use PHPRequestHandler instead. */
983
- internalUrlToPath(internalUrl: string): string;
984
- initializeRuntime(runtimeId: PHPRuntimeId): void;
985
- /** @inheritDoc */
986
- setSapiName(newName: string): Promise<void>;
987
- /**
988
- * Changes the current working directory in the PHP filesystem.
989
- * This is the directory that will be used as the base for relative paths.
990
- * For example, if the current working directory is `/root/php`, and the
991
- * path is `data`, the absolute path will be `/root/php/data`.
992
- *
993
- * @param path - The new working directory.
994
- */
995
- chdir(path: string): void;
996
- /**
997
- * Do not use. Use new PHPRequestHandler() instead.
998
- * @deprecated
999
- */
1000
- request(request: PHPRequest): Promise<PHPResponse>;
1001
- /**
1002
- * Runs PHP code.
1003
- *
1004
- * This low-level method directly interacts with the WebAssembly
1005
- * PHP interpreter.
1006
- *
1007
- * Every time you call run(), it prepares the PHP
1008
- * environment and:
1009
- *
1010
- * * Resets the internal PHP state
1011
- * * Populates superglobals ($_SERVER, $_GET, etc.)
1012
- * * Handles file uploads
1013
- * * Populates input streams (stdin, argv, etc.)
1014
- * * Sets the current working directory
1015
- *
1016
- * You can use run() in two primary modes:
1017
- *
1018
- * ### Code snippet mode
1019
- *
1020
- * In this mode, you pass a string containing PHP code to run.
1021
- *
1022
- * ```ts
1023
- * const result = await php.run({
1024
- * code: `<?php echo "Hello world!";`
1025
- * });
1026
- * // result.text === "Hello world!"
1027
- * ```
1028
- *
1029
- * In this mode, information like __DIR__ or __FILE__ isn't very
1030
- * useful because the code is not associated with any file.
1031
- *
1032
- * Under the hood, the PHP snippet is passed to the `zend_eval_string`
1033
- * C function.
1034
- *
1035
- * ### File mode
1036
- *
1037
- * In the file mode, you pass a scriptPath and PHP executes a file
1038
- * found at a that path:
1039
- *
1040
- * ```ts
1041
- * php.writeFile(
1042
- * "/www/index.php",
1043
- * `<?php echo "Hello world!";"`
1044
- * );
1045
- * const result = await php.run({
1046
- * scriptPath: "/www/index.php"
1047
- * });
1048
- * // result.text === "Hello world!"
1049
- * ```
1050
- *
1051
- * In this mode, you can rely on path-related information like __DIR__
1052
- * or __FILE__.
1053
- *
1054
- * Under the hood, the PHP file is executed with the `php_execute_script`
1055
- * C function.
1056
- *
1057
- * The `run()` method cannot be used in conjunction with `cli()`.
1058
- *
1059
- * @example
1060
- * ```js
1061
- * const result = await php.run(`<?php
1062
- * $fp = fopen('php://stderr', 'w');
1063
- * fwrite($fp, "Hello, world!");
1064
- * `);
1065
- * // result.errors === "Hello, world!"
1066
- * ```
1067
- *
1068
- * @param options - PHP runtime options.
1069
- */
1070
- run(request: PHPRunOptions): Promise<PHPResponse>;
1071
- /**
1072
- * Defines a constant in the PHP runtime.
1073
- * @param key - The name of the constant.
1074
- * @param value - The value of the constant.
1075
- */
1076
- defineConstant(key: string, value: string | boolean | number | null): void;
1077
- /**
1078
- * Recursively creates a directory with the given path in the PHP filesystem.
1079
- * For example, if the path is `/root/php/data`, and `/root` already exists,
1080
- * it will create the directories `/root/php` and `/root/php/data`.
1081
- *
1082
- * @param path - The directory path to create.
1083
- */
1084
- mkdir(path: string): void;
1085
- /**
1086
- * @deprecated Use mkdir instead.
1087
- */
1088
- mkdirTree(path: string): void;
1089
- /**
1090
- * Reads a file from the PHP filesystem and returns it as a string.
1091
- *
1092
- * @throws {@link @php-wasm/universal:ErrnoError} – If the file doesn't exist.
1093
- * @param path - The file path to read.
1094
- * @returns The file contents.
1095
- */
1096
- readFileAsText(path: string): string;
1097
- /**
1098
- * Reads a file from the PHP filesystem and returns it as an array buffer.
1099
- *
1100
- * @throws {@link @php-wasm/universal:ErrnoError} – If the file doesn't exist.
1101
- * @param path - The file path to read.
1102
- * @returns The file contents.
1103
- */
1104
- readFileAsBuffer(path: string): Uint8Array;
1105
- /**
1106
- * Overwrites data in a file in the PHP filesystem.
1107
- * Creates a new file if one doesn't exist yet.
1108
- *
1109
- * @param path - The file path to write to.
1110
- * @param data - The data to write to the file.
1111
- */
1112
- writeFile(path: string, data: string | Uint8Array): void;
1113
- /**
1114
- * Removes a file from the PHP filesystem.
1115
- *
1116
- * @throws {@link @php-wasm/universal:ErrnoError} – If the file doesn't exist.
1117
- * @param path - The file path to remove.
1118
- */
1119
- unlink(path: string): void;
1120
- /**
1121
- * Moves a file or directory in the PHP filesystem to a
1122
- * new location.
1123
- *
1124
- * @param oldPath The path to rename.
1125
- * @param newPath The new path.
1126
- */
1127
- mv(fromPath: string, toPath: string): void;
1128
- /**
1129
- * Removes a directory from the PHP filesystem.
1130
- *
1131
- * @param path The directory path to remove.
1132
- * @param options Options for the removal.
1133
- */
1134
- rmdir(path: string, options?: RmDirOptions): void;
1135
- /**
1136
- * Lists the files and directories in the given directory.
1137
- *
1138
- * @param path - The directory path to list.
1139
- * @param options - Options for the listing.
1140
- * @returns The list of files and directories in the given directory.
1141
- */
1142
- listFiles(path: string, options?: ListFilesOptions): string[];
1143
- /**
1144
- * Checks if a directory exists in the PHP filesystem.
1145
- *
1146
- * @param path – The path to check.
1147
- * @returns True if the path is a directory, false otherwise.
1148
- */
1149
- isDir(path: string): boolean;
1150
- /**
1151
- * Checks if a file (or a directory) exists in the PHP filesystem.
1152
- *
1153
- * @param path - The file path to check.
1154
- * @returns True if the file exists, false otherwise.
1155
- */
1156
- fileExists(path: string): boolean;
1157
- /**
1158
- * Hot-swaps the PHP runtime for a new one without
1159
- * interrupting the operations of this PHP instance.
1160
- *
1161
- * @param runtime
1162
- * @param cwd. Internal, the VFS path to recreate in the new runtime.
1163
- * This arg is temporary and will be removed once BasePHP
1164
- * is fully decoupled from the request handler and
1165
- * accepts a constructor-level cwd argument.
1166
- */
1167
- hotSwapPHPRuntime(runtime: number, cwd?: string): void;
1168
- /**
1169
- * Mounts a filesystem to a given path in the PHP filesystem.
1170
- *
1171
- * @param virtualFSPath - Where to mount it in the PHP virtual filesystem.
1172
- * @param mountHandler - The mount handler to use.
1173
- * @return Unmount function to unmount the filesystem.
1174
- */
1175
- mount(virtualFSPath: string, mountHandler: MountHandler): Promise<UnmountFunction>;
1176
- /**
1177
- * Starts a PHP CLI session with given arguments.
1178
- *
1179
- * This method can only be used when PHP was compiled with the CLI SAPI
1180
- * and it cannot be used in conjunction with `run()`.
1181
- *
1182
- * Once this method finishes running, the PHP instance is no
1183
- * longer usable and should be discarded. This is because PHP
1184
- * internally cleans up all the resources and calls exit().
1185
- *
1186
- * @param argv - The arguments to pass to the CLI.
1187
- * @returns The exit code of the CLI session.
1188
- */
1189
- cli(argv: string[]): Promise<number>;
1190
- setSkipShebang(shouldSkip: boolean): void;
1191
- exit(code?: number): void;
1192
- [Symbol.dispose](): void;
1193
- }
1194
- export type LimitedPHPApi = Pick<PHP, "request" | "defineConstant" | "addEventListener" | "removeEventListener" | "mkdir" | "mkdirTree" | "readFileAsText" | "readFileAsBuffer" | "writeFile" | "unlink" | "mv" | "rmdir" | "listFiles" | "isDir" | "fileExists" | "chdir" | "run" | "onMessage"> & {
1195
- documentRoot: PHP["documentRoot"];
1196
- absoluteUrl: PHP["absoluteUrl"];
1197
- };
1198
- /**
1199
- * A PHP client that can be used to run PHP code in the browser.
1200
- */
1201
- export declare class PHPWorker implements LimitedPHPApi {
1202
- /** @inheritDoc @php-wasm/universal!RequestHandler.absoluteUrl */
1203
- absoluteUrl: string;
1204
- /** @inheritDoc @php-wasm/universal!RequestHandler.documentRoot */
1205
- documentRoot: string;
1206
- /** @inheritDoc */
1207
- constructor(requestHandler?: PHPRequestHandler, monitor?: EmscriptenDownloadMonitor);
1208
- __internal_setRequestHandler(requestHandler: PHPRequestHandler): void;
1209
- /**
1210
- * @internal
1211
- * @deprecated
1212
- * Do not use this method directly in the code consuming
1213
- * the web API. It will change or even be removed without
1214
- * a warning.
1215
- */
1216
- protected __internal_getPHP(): PHP | undefined;
1217
- setPrimaryPHP(php: PHP): Promise<void>;
1218
- /** @inheritDoc @php-wasm/universal!PHPRequestHandler.pathToInternalUrl */
1219
- pathToInternalUrl(path: string): string;
1220
- /** @inheritDoc @php-wasm/universal!PHPRequestHandler.internalUrlToPath */
1221
- internalUrlToPath(internalUrl: string): string;
1222
- /**
1223
- * The onDownloadProgress event listener.
1224
- */
1225
- onDownloadProgress(callback: (progress: CustomEvent<ProgressEvent>) => void): Promise<void>;
1226
- /** @inheritDoc @php-wasm/universal!PHP.mv */
1227
- mv(fromPath: string, toPath: string): Promise<void>;
1228
- /** @inheritDoc @php-wasm/universal!PHP.rmdir */
1229
- rmdir(path: string, options?: RmDirOptions): Promise<void>;
1230
- /** @inheritDoc @php-wasm/universal!PHPRequestHandler.request */
1231
- request(request: PHPRequest): Promise<PHPResponse>;
1232
- /** @inheritDoc @php-wasm/universal!/PHP.run */
1233
- run(request: PHPRunOptions): Promise<PHPResponse>;
1234
- /** @inheritDoc @php-wasm/universal!/PHP.chdir */
1235
- chdir(path: string): void;
1236
- /** @inheritDoc @php-wasm/universal!/PHP.setSapiName */
1237
- setSapiName(newName: string): void;
1238
- /** @inheritDoc @php-wasm/universal!/PHP.mkdir */
1239
- mkdir(path: string): void;
1240
- /** @inheritDoc @php-wasm/universal!/PHP.mkdirTree */
1241
- mkdirTree(path: string): void;
1242
- /** @inheritDoc @php-wasm/universal!/PHP.readFileAsText */
1243
- readFileAsText(path: string): string;
1244
- /** @inheritDoc @php-wasm/universal!/PHP.readFileAsBuffer */
1245
- readFileAsBuffer(path: string): Uint8Array;
1246
- /** @inheritDoc @php-wasm/universal!/PHP.writeFile */
1247
- writeFile(path: string, data: string | Uint8Array): void;
1248
- /** @inheritDoc @php-wasm/universal!/PHP.unlink */
1249
- unlink(path: string): void;
1250
- /** @inheritDoc @php-wasm/universal!/PHP.listFiles */
1251
- listFiles(path: string, options?: ListFilesOptions): string[];
1252
- /** @inheritDoc @php-wasm/universal!/PHP.isDir */
1253
- isDir(path: string): boolean;
1254
- /** @inheritDoc @php-wasm/universal!/PHP.fileExists */
1255
- fileExists(path: string): boolean;
1256
- /** @inheritDoc @php-wasm/universal!/PHP.onMessage */
1257
- onMessage(listener: MessageListener): void;
1258
- /** @inheritDoc @php-wasm/universal!/PHP.defineConstant */
1259
- defineConstant(key: string, value: string | boolean | number | null): void;
1260
- /** @inheritDoc @php-wasm/universal!/PHP.addEventListener */
1261
- addEventListener(eventType: PHPEvent["type"], listener: PHPEventListener): void;
1262
- /** @inheritDoc @php-wasm/universal!/PHP.removeEventListener */
1263
- removeEventListener(eventType: PHPEvent["type"], listener: PHPEventListener): void;
1264
- }
1265
- /**
1266
- * Represents an event related to the PHP request.
1267
- */
1268
- export interface PHPRequestEndEvent {
1269
- type: "request.end";
1270
- }
1271
- /**
1272
- * Represents an error event related to the PHP request.
1273
- */
1274
- export interface PHPRequestErrorEvent {
1275
- type: "request.error";
1276
- error: Error;
1277
- source?: "request" | "php-wasm";
1278
- }
1279
- /**
1280
- * Represents a PHP runtime initialization event.
1281
- */
1282
- export interface PHPRuntimeInitializedEvent {
1283
- type: "runtime.initialized";
1284
- }
1285
- /**
1286
- * Represents a PHP runtime destruction event.
1287
- */
1288
- export interface PHPRuntimeBeforeDestroyEvent {
1289
- type: "runtime.beforedestroy";
1290
- }
1291
- /**
1292
- * Represents an event related to the PHP instance.
1293
- * This is intentionally not an extension of CustomEvent
1294
- * to make it isomorphic between different JavaScript runtimes.
1295
- */
1296
- export type PHPEvent = PHPRequestEndEvent | PHPRequestErrorEvent | PHPRuntimeInitializedEvent | PHPRuntimeBeforeDestroyEvent;
1297
- /**
1298
- * A callback function that handles PHP events.
1299
- */
1300
- export type PHPEventListener = (event: PHPEvent) => void;
1301
- export type UniversalPHP = LimitedPHPApi | Remote<LimitedPHPApi>;
1302
- export type MessageListener = (data: string) => Promise<string | Uint8Array | void> | string | void;
1303
- export interface EventEmitter {
1304
- on(event: string, listener: (...args: any[]) => void): this;
1305
- emit(event: string, ...args: any[]): boolean;
1306
- }
1307
- export type ChildProcess = EventEmitter & {
1308
- stdout: EventEmitter;
1309
- stderr: EventEmitter;
1310
- };
1311
- export type SpawnHandler = (command: string, args: string[]) => ChildProcess;
1312
- export type HTTPMethod = "GET" | "POST" | "HEAD" | "OPTIONS" | "PATCH" | "PUT" | "DELETE";
1313
- export type PHPRequestHeaders = Record<string, string>;
1314
- export interface PHPRequest {
1315
- /**
1316
- * Request method. Default: `GET`.
1317
- */
1318
- method?: HTTPMethod;
1319
- /**
1320
- * Request path or absolute URL.
1321
- */
1322
- url: string;
1323
- /**
1324
- * Request headers.
1325
- */
1326
- headers?: PHPRequestHeaders;
1327
- /**
1328
- * Request body.
1329
- * If an object is given, the request will be encoded as multipart
1330
- * and sent with a `multipart/form-data` header.
1331
- */
1332
- body?: string | Uint8Array | Record<string, string | Uint8Array | File>;
1333
- }
1334
- export interface PHPRunOptions {
1335
- /**
1336
- * Request path following the domain:port part.
1337
- */
1338
- relativeUri?: string;
1339
- /**
1340
- * Path of the .php file to execute.
1341
- */
1342
- scriptPath?: string;
1343
- /**
1344
- * Request protocol.
1345
- */
1346
- protocol?: string;
1347
- /**
1348
- * Request method. Default: `GET`.
1349
- */
1350
- method?: HTTPMethod;
1351
- /**
1352
- * Request headers.
1353
- */
1354
- headers?: PHPRequestHeaders;
1355
- /**
1356
- * Request body.
1357
- */
1358
- body?: string | Uint8Array;
1359
- /**
1360
- * Environment variables to set for this run.
1361
- */
1362
- env?: Record<string, string>;
1363
- /**
1364
- * $_SERVER entries to set for this run.
1365
- */
1366
- $_SERVER?: Record<string, string>;
1367
- /**
1368
- * The code snippet to eval instead of a php file.
1369
- */
1370
- code?: string;
1371
- }
1372
- /**
1373
- * Output of the PHP.wasm runtime.
1374
- */
1375
- export interface PHPOutput {
1376
- /** Exit code of the PHP process. 0 means success, 1 and 2 mean error. */
1377
- exitCode: number;
1378
- /** Stdout data */
1379
- stdout: ArrayBuffer;
1380
- /** Stderr lines */
1381
- stderr: string[];
1382
- }
1383
- /**
1384
- * Reads the php.ini file and returns its entries.
1385
- *
1386
- * @param php The PHP instance.
1387
- * @param entries Optional. If provided, only the specified entries will be returned.
1388
- * @returns The php.ini entries.
1389
- */
1390
- export declare function getPhpIniEntries(php: UniversalPHP, entries?: string[]): Promise<{
1391
- [key: string]: any;
1392
- }>;
1393
- /**
1394
- * Rewrites the php.ini file with the given entries.
1395
- *
1396
- * @param php The PHP instance.
1397
- * @param entries The entries to write to the php.ini file.
1398
- */
1399
- export declare function setPhpIniEntries(php: UniversalPHP, entries: Record<string, unknown>): Promise<void>;
1400
- /**
1401
- * Sets php.ini values to the given values, executes a callback,
1402
- * and restores the original php.ini values. This is useful for
1403
- * running code with temporary php.ini values, such as when
1404
- * disabling network-related PHP functions just to run WordPress
1405
- * installer.
1406
- *
1407
- * @example
1408
- * ```ts
1409
- * await withPHPIniValues(
1410
- * php,
1411
- * {
1412
- * disable_functions: 'fsockopen',
1413
- * allow_url_fopen: '0',
1414
- * },
1415
- * async () => await runWpInstallationWizard(php, {
1416
- * options: {},
1417
- * })
1418
- * );
1419
- * ```
1420
- *
1421
- * @param php The PHP instance.
1422
- * @param phpIniValues The php.ini values to set.
1423
- * @param callback The callback to execute.
1424
- * @returns The result of the callback.
1425
- */
1426
- export declare function withPHPIniValues(php: UniversalPHP, phpIniValues: Record<string, string>, callback: () => Promise<any>): Promise<any>;
1427
- export declare class UnhandledRejectionsTarget extends EventTarget {
1428
- listenersCount: number;
1429
- addEventListener(type: unknown, callback: unknown): void;
1430
- removeEventListener(type: unknown, callback: unknown): void;
1431
- hasListeners(): boolean;
1432
- }
1433
- /**
1434
- * @public
1435
- */
1436
- export declare class HttpCookieStore {
1437
- cookies: Record<string, string>;
1438
- rememberCookiesFromResponseHeaders(headers: Record<string, string[]>): void;
1439
- getCookieRequestHeader(): string;
1440
- }
1441
- type IteratePhpFilesOptions = {
1442
- /**
1443
- * Should yield paths relative to the root directory?
1444
- * If false, all paths will be absolute.
1445
- */
1446
- relativePaths?: boolean;
1447
- /**
1448
- * A prefix to add to all paths.
1449
- * Only used if `relativePaths` is true.
1450
- */
1451
- pathPrefix?: string;
1452
- /**
1453
- * A list of paths to exclude from the results.
1454
- */
1455
- exceptPaths?: string[];
1456
- };
1457
- declare function iteratePhpFiles(php: UniversalPHP, root: string, { relativePaths, pathPrefix, exceptPaths, }?: IteratePhpFilesOptions): AsyncGenerator<File>;
1458
- /**
1459
- * Writes streamed files to PHP filesystem.
1460
- */
1461
- export declare function writeFilesStreamToPhp(php: UniversalPHP, root: string): WritableStream<File>;
1462
- /**
1463
- * Emscripten's filesystem-related Exception.
1464
- *
1465
- * @see https://emscripten.org/docs/api_reference/Filesystem-API.html
1466
- * @see https://github.com/emscripten-core/emscripten/blob/main/system/lib/libc/musl/arch/emscripten/bits/errno.h
1467
- * @see https://github.com/emscripten-core/emscripten/blob/38eedc630f17094b3202fd48ac0c2c585dbea31e/system/include/wasi/api.h#L336
1468
- */
1469
- export interface ErrnoError extends Error {
1470
- node?: any;
1471
- errno: number;
1472
- message: string;
1473
- }
1474
- export declare const SupportedPHPVersions: readonly [
1475
- "8.3",
1476
- "8.2",
1477
- "8.1",
1478
- "8.0",
1479
- "7.4",
1480
- "7.3",
1481
- "7.2",
1482
- "7.1",
1483
- "7.0"
1484
- ];
1485
- export declare const LatestSupportedPHPVersion: "8.3";
1486
- export declare const SupportedPHPVersionsList: string[];
1487
- export type SupportedPHPVersion = (typeof SupportedPHPVersions)[number];
1488
- export type SupportedPHPExtension = "iconv" | "mbstring" | "xml-bundle" | "gd";
1489
- export declare const SupportedPHPExtensionsList: string[];
1490
- export declare const SupportedPHPExtensionBundles: {
1491
- "kitchen-sink": string[];
1492
- light: never[];
1493
- };
1494
- export type SupportedPHPExtensionBundle = "kitchen-sink" | "light";
1495
- export interface RotateOptions {
1496
- php: PHP;
1497
- cwd: string;
1498
- recreateRuntime: () => Promise<number> | number;
1499
- maxRequests: number;
1500
- }
1501
- /**
1502
- * Listens to PHP events and swaps the internal PHP Runtime for a fresh one
1503
- * after a certain number of run() calls (which are responsible for handling
1504
- * HTTP requests).
1505
- *
1506
- * Why? Because PHP and PHP extension have a memory leak. Each request leaves
1507
- * the memory a bit more fragmented and with a bit less available space than
1508
- * before. Eventually, new allocations start failing.
1509
- *
1510
- * Rotating the PHP instance may seem like a workaround, but it's actually
1511
- * what PHP-FPM does natively:
1512
- *
1513
- * https://www.php.net/manual/en/install.fpm.configuration.php#pm.max-tasks
1514
- *
1515
- * @return cleanup function to restore
1516
- */
1517
- export declare function rotatePHPRuntime({ php, cwd, recreateRuntime, maxRequests, }: RotateOptions): () => void;
1518
- export interface WriteFilesOptions {
1519
- /**
1520
- * Whether to wipe out the contents of the
1521
- * root directory before writing the new files.
1522
- */
1523
- rmRoot?: boolean;
1524
- }
1525
- export interface FileTree extends Record<string, Uint8Array | string | FileTree> {
1526
- }
1527
- /**
1528
- * Writes multiple files to a specified directory in the Playground
1529
- * filesystem.
1530
- *
1531
- * @example ```ts
1532
- * await writeFiles(php, '/test', {
1533
- * 'file.txt': 'file',
1534
- * 'sub/file.txt': 'file',
1535
- * 'sub1/sub2/file.txt': 'file',
1536
- * });
1537
- * ```
1538
- *
1539
- * @param php
1540
- * @param root
1541
- * @param newFiles
1542
- * @param options
1543
- */
1544
- export declare function writeFiles(php: UniversalPHP, root: string, newFiles: FileTree, { rmRoot }?: WriteFilesOptions): Promise<void>;
1545
- /**
1546
- * The default base used to convert a path into the URL object.
1547
- */
1548
- export declare const DEFAULT_BASE_URL = "http://example.com";
1549
- /**
1550
- * Returns a string representing the path, query, and
1551
- * fragment of the given URL.
1552
- *
1553
- * @example
1554
- * ```js
1555
- * const url = new URL('http://example.com/foo/bar?baz=qux#quux');
1556
- * toRelativeUrl(url); // '/foo/bar?baz=qux#quux'
1557
- * ```
1558
- *
1559
- * @param url The URL.
1560
- * @returns The path, query, and fragment.
1561
- */
1562
- export declare function toRelativeUrl(url: URL): string;
1563
- /**
1564
- * Removes the given prefix from the given path.
1565
- *
1566
- * @example
1567
- * ```js
1568
- * removePathPrefix('/foo/bar', '/foo'); // '/bar'
1569
- * removePathPrefix('/bar', '/foo'); // '/bar'
1570
- * ```
1571
- *
1572
- * @param path The path to remove the prefix from.
1573
- * @param prefix The prefix to remove.
1574
- * @returns Path with the prefix removed.
1575
- */
1576
- export declare function removePathPrefix(path: string, prefix: string): string;
1577
- /**
1578
- * Ensures the given path has the given prefix.
1579
- *
1580
- * @example
1581
- * ```js
1582
- * ensurePathPrefix('/bar', '/foo'); // '/foo/bar'
1583
- * ensurePathPrefix('/foo/bar', '/foo'); // '/foo/bar'
1584
- * ```
1585
- *
1586
- * @param path
1587
- * @param prefix
1588
- * @returns Path with the prefix added.
1589
- */
1590
- export declare function ensurePathPrefix(path: string, prefix: string): string;
1591
- /**
1592
- * Check if the Emscripten-thrown error is an exit code 0 error.
1593
- *
1594
- * @param e The error to check
1595
- * @returns True if the error is an exit code 0 error
1596
- */
1597
- export declare function isExitCodeZero(e: any): boolean;
1598
- /**
1599
- * Proxy specific paths to the parent's MEMFS instance.
1600
- * This is useful for sharing the WordPress installation
1601
- * between the parent and child processes.
1602
- */
1603
- export declare function proxyFileSystem(sourceOfTruth: PHP, replica: PHP, paths: string[]): void;
1604
-
1605
- export {};
1
+ export * from './lib';