@wp-playground/storage 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.d.ts ADDED
@@ -0,0 +1,1084 @@
1
+ // Generated by dts-bundle-generator v7.2.0
2
+
3
+ import { Remote } from 'comlink';
4
+ import { Octokit } from 'octokit';
5
+
6
+ export interface PHPResponseData {
7
+ /**
8
+ * Response headers.
9
+ */
10
+ readonly headers: Record<string, string[]>;
11
+ /**
12
+ * Response body. Contains the output from `echo`,
13
+ * `print`, inline HTML etc.
14
+ */
15
+ readonly bytes: ArrayBuffer;
16
+ /**
17
+ * Stderr contents, if any.
18
+ */
19
+ readonly errors: string;
20
+ /**
21
+ * The exit code of the script. `0` is a success, while
22
+ * `1` and `2` indicate an error.
23
+ */
24
+ readonly exitCode: number;
25
+ /**
26
+ * Response HTTP status code, e.g. 200.
27
+ */
28
+ readonly httpStatusCode: number;
29
+ }
30
+ declare class PHPResponse implements PHPResponseData {
31
+ /** @inheritDoc */
32
+ readonly headers: Record<string, string[]>;
33
+ /** @inheritDoc */
34
+ readonly bytes: ArrayBuffer;
35
+ /** @inheritDoc */
36
+ readonly errors: string;
37
+ /** @inheritDoc */
38
+ readonly exitCode: number;
39
+ /** @inheritDoc */
40
+ readonly httpStatusCode: number;
41
+ constructor(httpStatusCode: number, headers: Record<string, string[]>, body: ArrayBuffer, errors?: string, exitCode?: number);
42
+ static forHttpCode(httpStatusCode: number, text?: string): PHPResponse;
43
+ static fromRawData(data: PHPResponseData): PHPResponse;
44
+ toRawData(): PHPResponseData;
45
+ /**
46
+ * Response body as JSON.
47
+ */
48
+ get json(): any;
49
+ /**
50
+ * Response body as text.
51
+ */
52
+ get text(): string;
53
+ }
54
+ export type PHPRuntimeId = number;
55
+ /** Other WebAssembly declarations, for compatibility with older versions of Typescript */
56
+ export declare namespace Emscripten {
57
+ export interface RootFS extends Emscripten.FileSystemInstance {
58
+ filesystems: Record<string, Emscripten.FileSystemType>;
59
+ }
60
+ export interface FileSystemType {
61
+ mount(mount: FS.Mount): FS.FSNode;
62
+ syncfs(mount: FS.Mount, populate: () => unknown, done: (err?: number | null) => unknown): void;
63
+ }
64
+ export type EnvironmentType = "WEB" | "NODE" | "SHELL" | "WORKER";
65
+ export type JSType = "number" | "string" | "array" | "boolean";
66
+ export type TypeCompatibleWithC = number | string | any[] | boolean;
67
+ export type CIntType = "i8" | "i16" | "i32" | "i64";
68
+ export type CFloatType = "float" | "double";
69
+ export type CPointerType = "i8*" | "i16*" | "i32*" | "i64*" | "float*" | "double*" | "*";
70
+ export type CType = CIntType | CFloatType | CPointerType;
71
+ export interface CCallOpts {
72
+ async?: boolean | undefined;
73
+ }
74
+ type NamespaceToInstance<T> = {
75
+ [K in keyof T]: T[K] extends (...args: any[]) => any ? T[K] : never;
76
+ };
77
+ export type FileSystemInstance = NamespaceToInstance<typeof FS> & {
78
+ mkdirTree(path: string): void;
79
+ lookupPath(path: string, opts?: any): FS.Lookup;
80
+ };
81
+ export interface EmscriptenModule {
82
+ print(str: string): void;
83
+ printErr(str: string): void;
84
+ arguments: string[];
85
+ environment: Emscripten.EnvironmentType;
86
+ preInit: Array<{
87
+ (): void;
88
+ }>;
89
+ preRun: Array<{
90
+ (): void;
91
+ }>;
92
+ postRun: Array<{
93
+ (): void;
94
+ }>;
95
+ onAbort: {
96
+ (what: any): void;
97
+ };
98
+ onRuntimeInitialized: {
99
+ (): void;
100
+ };
101
+ preinitializedWebGLContext: WebGLRenderingContext;
102
+ noInitialRun: boolean;
103
+ noExitRuntime: boolean;
104
+ logReadFiles: boolean;
105
+ filePackagePrefixURL: string;
106
+ wasmBinary: ArrayBuffer;
107
+ destroy(object: object): void;
108
+ getPreloadedPackage(remotePackageName: string, remotePackageSize: number): ArrayBuffer;
109
+ instantiateWasm(imports: WebAssembly.Imports, successCallback: (module: WebAssembly.Instance) => void): WebAssembly.Exports | undefined;
110
+ locateFile(url: string, scriptDirectory: string): string;
111
+ onCustomMessage(event: MessageEvent): void;
112
+ HEAP: Int32Array;
113
+ IHEAP: Int32Array;
114
+ FHEAP: Float64Array;
115
+ HEAP8: Int8Array;
116
+ HEAP16: Int16Array;
117
+ HEAP32: Int32Array;
118
+ HEAPU8: Uint8Array;
119
+ HEAPU16: Uint16Array;
120
+ HEAPU32: Uint32Array;
121
+ HEAPF32: Float32Array;
122
+ HEAPF64: Float64Array;
123
+ HEAP64: BigInt64Array;
124
+ HEAPU64: BigUint64Array;
125
+ TOTAL_STACK: number;
126
+ TOTAL_MEMORY: number;
127
+ FAST_MEMORY: number;
128
+ addOnPreRun(cb: () => any): void;
129
+ addOnInit(cb: () => any): void;
130
+ addOnPreMain(cb: () => any): void;
131
+ addOnExit(cb: () => any): void;
132
+ addOnPostRun(cb: () => any): void;
133
+ preloadedImages: any;
134
+ preloadedAudios: any;
135
+ _malloc(size: number): number;
136
+ _free(ptr: number): void;
137
+ }
138
+ /**
139
+ * A factory function is generated when setting the `MODULARIZE` build option
140
+ * to `1` in your Emscripten build. It return a Promise that resolves to an
141
+ * initialized, ready-to-call `EmscriptenModule` instance.
142
+ *
143
+ * By default, the factory function will be named `Module`. It's recommended to
144
+ * use the `EXPORT_ES6` option, in which the factory function will be the
145
+ * default export. If used without `EXPORT_ES6`, the factory function will be a
146
+ * global variable. You can rename the variable using the `EXPORT_NAME` build
147
+ * option. It's left to you to export any global variables as needed in your
148
+ * application's types.
149
+ * @param moduleOverrides Default properties for the initialized module.
150
+ */
151
+ export type EmscriptenModuleFactory<T extends EmscriptenModule = EmscriptenModule> = (moduleOverrides?: Partial<T>) => Promise<T>;
152
+ export namespace FS {
153
+ interface Lookup {
154
+ path: string;
155
+ node: FSNode;
156
+ }
157
+ interface Analyze {
158
+ isRoot: boolean;
159
+ exists: boolean;
160
+ error: Error;
161
+ name: string;
162
+ path: Lookup["path"];
163
+ object: Lookup["node"];
164
+ parentExists: boolean;
165
+ parentPath: Lookup["path"];
166
+ parentObject: Lookup["node"];
167
+ }
168
+ interface Mount {
169
+ type: Emscripten.FileSystemType;
170
+ opts: object;
171
+ mountpoint: string;
172
+ mounts: Mount[];
173
+ root: FSNode;
174
+ }
175
+ class FSStream {
176
+ constructor();
177
+ object: FSNode;
178
+ readonly isRead: boolean;
179
+ readonly isWrite: boolean;
180
+ readonly isAppend: boolean;
181
+ flags: number;
182
+ position: number;
183
+ }
184
+ class FSNode {
185
+ parent: FSNode;
186
+ mount: Mount;
187
+ mounted?: Mount;
188
+ id: number;
189
+ name: string;
190
+ mode: number;
191
+ rdev: number;
192
+ readMode: number;
193
+ writeMode: number;
194
+ constructor(parent: FSNode, name: string, mode: number, rdev: number);
195
+ read: boolean;
196
+ write: boolean;
197
+ readonly isFolder: boolean;
198
+ readonly isDevice: boolean;
199
+ }
200
+ interface ErrnoError extends Error {
201
+ name: "ErronoError";
202
+ errno: number;
203
+ code: string;
204
+ }
205
+ function lookupPath(path: string, opts: any): Lookup;
206
+ function getPath(node: FSNode): string;
207
+ function analyzePath(path: string, dontResolveLastLink?: boolean): Analyze;
208
+ function isFile(mode: number): boolean;
209
+ function isDir(mode: number): boolean;
210
+ function isLink(mode: number): boolean;
211
+ function isChrdev(mode: number): boolean;
212
+ function isBlkdev(mode: number): boolean;
213
+ function isFIFO(mode: number): boolean;
214
+ function isSocket(mode: number): boolean;
215
+ function major(dev: number): number;
216
+ function minor(dev: number): number;
217
+ function makedev(ma: number, mi: number): number;
218
+ function registerDevice(dev: number, ops: any): void;
219
+ function syncfs(populate: boolean, callback: (e: any) => any): void;
220
+ function syncfs(callback: (e: any) => any, populate?: boolean): void;
221
+ function mount(type: Emscripten.FileSystemType, opts: any, mountpoint: string): any;
222
+ function unmount(mountpoint: string): void;
223
+ function mkdir(path: string, mode?: number): any;
224
+ function mkdev(path: string, mode?: number, dev?: number): any;
225
+ function symlink(oldpath: string, newpath: string): any;
226
+ function rename(old_path: string, new_path: string): void;
227
+ function rmdir(path: string): void;
228
+ function readdir(path: string): any;
229
+ function unlink(path: string): void;
230
+ function readlink(path: string): string;
231
+ function stat(path: string, dontFollow?: boolean): any;
232
+ function lstat(path: string): any;
233
+ function chmod(path: string, mode: number, dontFollow?: boolean): void;
234
+ function lchmod(path: string, mode: number): void;
235
+ function fchmod(fd: number, mode: number): void;
236
+ function chown(path: string, uid: number, gid: number, dontFollow?: boolean): void;
237
+ function lchown(path: string, uid: number, gid: number): void;
238
+ function fchown(fd: number, uid: number, gid: number): void;
239
+ function truncate(path: string, len: number): void;
240
+ function ftruncate(fd: number, len: number): void;
241
+ function utime(path: string, atime: number, mtime: number): void;
242
+ function open(path: string, flags: string, mode?: number, fd_start?: number, fd_end?: number): FSStream;
243
+ function close(stream: FSStream): void;
244
+ function llseek(stream: FSStream, offset: number, whence: number): any;
245
+ function read(stream: FSStream, buffer: ArrayBufferView, offset: number, length: number, position?: number): number;
246
+ function write(stream: FSStream, buffer: ArrayBufferView, offset: number, length: number, position?: number, canOwn?: boolean): number;
247
+ function allocate(stream: FSStream, offset: number, length: number): void;
248
+ function mmap(stream: FSStream, buffer: ArrayBufferView, offset: number, length: number, position: number, prot: number, flags: number): any;
249
+ function ioctl(stream: FSStream, cmd: any, arg: any): any;
250
+ function readFile(path: string, opts: {
251
+ encoding: "binary";
252
+ flags?: string | undefined;
253
+ }): Uint8Array;
254
+ function readFile(path: string, opts: {
255
+ encoding: "utf8";
256
+ flags?: string | undefined;
257
+ }): string;
258
+ function readFile(path: string, opts?: {
259
+ flags?: string | undefined;
260
+ }): Uint8Array;
261
+ function writeFile(path: string, data: string | ArrayBufferView, opts?: {
262
+ flags?: string | undefined;
263
+ }): void;
264
+ function cwd(): string;
265
+ function chdir(path: string): void;
266
+ function init(input: null | (() => number | null), output: null | ((c: number) => any), error: null | ((c: number) => any)): void;
267
+ function createLazyFile(parent: string | FSNode, name: string, url: string, canRead: boolean, canWrite: boolean): FSNode;
268
+ function createPreloadedFile(parent: string | FSNode, name: string, url: string, canRead: boolean, canWrite: boolean, onload?: () => void, onerror?: () => void, dontCreateFile?: boolean, canOwn?: boolean): void;
269
+ function createDataFile(parent: string | FSNode, name: string, data: ArrayBufferView, canRead: boolean, canWrite: boolean, canOwn: boolean): FSNode;
270
+ }
271
+ export const MEMFS: Emscripten.FileSystemType;
272
+ export const NODEFS: Emscripten.FileSystemType;
273
+ export const IDBFS: Emscripten.FileSystemType;
274
+ type StringToType<R> = R extends Emscripten.JSType ? {
275
+ number: number;
276
+ string: string;
277
+ array: number[] | string[] | boolean[] | Uint8Array | Int8Array;
278
+ boolean: boolean;
279
+ null: null;
280
+ }[R] : never;
281
+ type ArgsToType<T extends Array<Emscripten.JSType | null>> = Extract<{
282
+ [P in keyof T]: StringToType<T[P]>;
283
+ }, any[]>;
284
+ type ReturnToType<R extends Emscripten.JSType | null> = R extends null ? null : StringToType<Exclude<R, null>>;
285
+ export function cwrap<I extends Array<Emscripten.JSType | null> | [
286
+ ], R extends Emscripten.JSType | null>(ident: string, returnType: R, argTypes: I, opts?: Emscripten.CCallOpts): (...arg: ArgsToType<I>) => ReturnToType<R>;
287
+ export function ccall<I extends Array<Emscripten.JSType | null> | [
288
+ ], R extends Emscripten.JSType | null>(ident: string, returnType: R, argTypes: I, args: ArgsToType<I>, opts?: Emscripten.CCallOpts): ReturnToType<R>;
289
+ export function setValue(ptr: number, value: any, type: Emscripten.CType, noSafe?: boolean): void;
290
+ export function getValue(ptr: number, type: Emscripten.CType, noSafe?: boolean): number;
291
+ export function allocate(slab: number[] | ArrayBufferView | number, types: Emscripten.CType | Emscripten.CType[], allocator: number, ptr?: number): number;
292
+ export function stackAlloc(size: number): number;
293
+ export function stackSave(): number;
294
+ export function stackRestore(ptr: number): void;
295
+ export function UTF8ToString(ptr: number, maxBytesToRead?: number): string;
296
+ export function stringToUTF8(str: string, outPtr: number, maxBytesToRead?: number): void;
297
+ export function lengthBytesUTF8(str: string): number;
298
+ export function allocateUTF8(str: string): number;
299
+ export function allocateUTF8OnStack(str: string): number;
300
+ export function UTF16ToString(ptr: number): string;
301
+ export function stringToUTF16(str: string, outPtr: number, maxBytesToRead?: number): void;
302
+ export function lengthBytesUTF16(str: string): number;
303
+ export function UTF32ToString(ptr: number): string;
304
+ export function stringToUTF32(str: string, outPtr: number, maxBytesToRead?: number): void;
305
+ export function lengthBytesUTF32(str: string): number;
306
+ export function intArrayFromString(stringy: string, dontAddNull?: boolean, length?: number): number[];
307
+ export function intArrayToString(array: number[]): string;
308
+ export function writeStringToMemory(str: string, buffer: number, dontAddNull: boolean): void;
309
+ export function writeArrayToMemory(array: number[], buffer: number): void;
310
+ export function writeAsciiToMemory(str: string, buffer: number, dontAddNull: boolean): void;
311
+ export function addRunDependency(id: any): void;
312
+ export function removeRunDependency(id: any): void;
313
+ export function addFunction(func: (...args: any[]) => any, signature?: string): number;
314
+ export function removeFunction(funcPtr: number): void;
315
+ export const ALLOC_NORMAL: number;
316
+ export const ALLOC_STACK: number;
317
+ export const ALLOC_STATIC: number;
318
+ export const ALLOC_DYNAMIC: number;
319
+ export const ALLOC_NONE: number;
320
+ export {};
321
+ }
322
+ export interface RmDirOptions {
323
+ /**
324
+ * If true, recursively removes the directory and all its contents.
325
+ * Default: true.
326
+ */
327
+ recursive?: boolean;
328
+ }
329
+ export interface ListFilesOptions {
330
+ /**
331
+ * If true, prepend given folder path to all file names.
332
+ * Default: false.
333
+ */
334
+ prependPath: boolean;
335
+ }
336
+ export interface SemaphoreOptions {
337
+ /**
338
+ * The maximum number of concurrent locks.
339
+ */
340
+ concurrency: number;
341
+ /**
342
+ * The maximum time to wait for a lock to become available.
343
+ */
344
+ timeout?: number;
345
+ }
346
+ declare class Semaphore {
347
+ private _running;
348
+ private concurrency;
349
+ private timeout?;
350
+ private queue;
351
+ constructor({ concurrency, timeout }: SemaphoreOptions);
352
+ get remaining(): number;
353
+ get running(): number;
354
+ acquire(): Promise<() => void>;
355
+ run<T>(fn: () => T | Promise<T>): Promise<T>;
356
+ }
357
+ export type PHPFactoryOptions = {
358
+ isPrimary: boolean;
359
+ };
360
+ export type PHPFactory = (options: PHPFactoryOptions) => Promise<PHP>;
361
+ export interface ProcessManagerOptions {
362
+ /**
363
+ * The maximum number of PHP instances that can exist at
364
+ * the same time.
365
+ */
366
+ maxPhpInstances?: number;
367
+ /**
368
+ * The number of milliseconds to wait for a PHP instance when
369
+ * we have reached the maximum number of PHP instances and
370
+ * cannot spawn a new one. If the timeout is reached, we assume
371
+ * all the PHP instances are deadlocked and a throw MaxPhpInstancesError.
372
+ *
373
+ * Default: 5000
374
+ */
375
+ timeout?: number;
376
+ /**
377
+ * The primary PHP instance that's never killed. This instance
378
+ * contains the reference filesystem used by all other PHP instances.
379
+ */
380
+ primaryPhp?: PHP;
381
+ /**
382
+ * A factory function used for spawning new PHP instances.
383
+ */
384
+ phpFactory?: PHPFactory;
385
+ }
386
+ export interface SpawnedPHP {
387
+ php: PHP;
388
+ reap: () => void;
389
+ }
390
+ declare class PHPProcessManager implements AsyncDisposable {
391
+ private primaryPhp?;
392
+ private primaryIdle;
393
+ private nextInstance;
394
+ /**
395
+ * All spawned PHP instances, including the primary PHP instance.
396
+ * Used for bookkeeping and reaping all instances on dispose.
397
+ */
398
+ private allInstances;
399
+ private phpFactory?;
400
+ private maxPhpInstances;
401
+ private semaphore;
402
+ constructor(options?: ProcessManagerOptions);
403
+ /**
404
+ * Get the primary PHP instance.
405
+ *
406
+ * If the primary PHP instance is not set, it will be spawned
407
+ * using the provided phpFactory.
408
+ *
409
+ * @throws {Error} when called twice before the first call is resolved.
410
+ */
411
+ getPrimaryPhp(): Promise<PHP>;
412
+ /**
413
+ * Get a PHP instance.
414
+ *
415
+ * It could be either the primary PHP instance, an idle disposable PHP instance,
416
+ * or a newly spawned PHP instance – depending on the resource availability.
417
+ *
418
+ * @throws {MaxPhpInstancesError} when the maximum number of PHP instances is reached
419
+ * and the waiting timeout is exceeded.
420
+ */
421
+ acquirePHPInstance(): Promise<SpawnedPHP>;
422
+ /**
423
+ * Initiated spawning of a new PHP instance.
424
+ * This function is synchronous on purpose – it needs to synchronously
425
+ * add the spawn promise to the allInstances array without waiting
426
+ * for PHP to spawn.
427
+ */
428
+ private spawn;
429
+ /**
430
+ * Actually acquires the lock and spawns a new PHP instance.
431
+ */
432
+ private doSpawn;
433
+ [Symbol.asyncDispose](): Promise<void>;
434
+ }
435
+ export type RewriteRule = {
436
+ match: RegExp;
437
+ replacement: string;
438
+ };
439
+ export interface BaseConfiguration {
440
+ /**
441
+ * The directory in the PHP filesystem where the server will look
442
+ * for the files to serve. Default: `/var/www`.
443
+ */
444
+ documentRoot?: string;
445
+ /**
446
+ * Request Handler URL. Used to populate $_SERVER details like HTTP_HOST.
447
+ */
448
+ absoluteUrl?: string;
449
+ /**
450
+ * Rewrite rules
451
+ */
452
+ rewriteRules?: RewriteRule[];
453
+ }
454
+ export type PHPRequestHandlerFactoryArgs = PHPFactoryOptions & {
455
+ requestHandler: PHPRequestHandler;
456
+ };
457
+ export type PHPRequestHandlerConfiguration = BaseConfiguration & ({
458
+ /**
459
+ * PHPProcessManager is required because the request handler needs
460
+ * to make a decision for each request.
461
+ *
462
+ * Static assets are served using the primary PHP's filesystem, even
463
+ * when serving 100 static files concurrently. No new PHP interpreter
464
+ * is ever created as there's no need for it.
465
+ *
466
+ * Dynamic PHP requests, however, require grabbing an available PHP
467
+ * interpreter, and that's where the PHPProcessManager comes in.
468
+ */
469
+ processManager: PHPProcessManager;
470
+ } | {
471
+ phpFactory: (requestHandler: PHPRequestHandlerFactoryArgs) => Promise<PHP>;
472
+ /**
473
+ * The maximum number of PHP instances that can exist at
474
+ * the same time.
475
+ */
476
+ maxPhpInstances?: number;
477
+ });
478
+ declare class PHPRequestHandler {
479
+ #private;
480
+ rewriteRules: RewriteRule[];
481
+ processManager: PHPProcessManager;
482
+ /**
483
+ * The request handler needs to decide whether to serve a static asset or
484
+ * run the PHP interpreter. For static assets it should just reuse the primary
485
+ * PHP even if there's 50 concurrent requests to serve. However, for
486
+ * dynamic PHP requests, it needs to grab an available interpreter.
487
+ * Therefore, it cannot just accept PHP as an argument as serving requests
488
+ * requires access to ProcessManager.
489
+ *
490
+ * @param php - The PHP instance.
491
+ * @param config - Request Handler configuration.
492
+ */
493
+ constructor(config: PHPRequestHandlerConfiguration);
494
+ getPrimaryPhp(): Promise<PHP>;
495
+ /**
496
+ * Converts a path to an absolute URL based at the PHPRequestHandler
497
+ * root.
498
+ *
499
+ * @param path The server path to convert to an absolute URL.
500
+ * @returns The absolute URL.
501
+ */
502
+ pathToInternalUrl(path: string): string;
503
+ /**
504
+ * Converts an absolute URL based at the PHPRequestHandler to a relative path
505
+ * without the server pathname and scope.
506
+ *
507
+ * @param internalUrl An absolute URL based at the PHPRequestHandler root.
508
+ * @returns The relative path.
509
+ */
510
+ internalUrlToPath(internalUrl: string): string;
511
+ /**
512
+ * The absolute URL of this PHPRequestHandler instance.
513
+ */
514
+ get absoluteUrl(): string;
515
+ /**
516
+ * The directory in the PHP filesystem where the server will look
517
+ * for the files to serve. Default: `/var/www`.
518
+ */
519
+ get documentRoot(): string;
520
+ /**
521
+ * Serves the request – either by serving a static file, or by
522
+ * dispatching it to the PHP runtime.
523
+ *
524
+ * The request() method mode behaves like a web server and only works if
525
+ * the PHP was initialized with a `requestHandler` option (which the online version
526
+ * of WordPress Playground does by default).
527
+ *
528
+ * In the request mode, you pass an object containing the request information
529
+ * (method, headers, body, etc.) and the path to the PHP file to run:
530
+ *
531
+ * ```ts
532
+ * const php = PHP.load('7.4', {
533
+ * requestHandler: {
534
+ * documentRoot: "/www"
535
+ * }
536
+ * })
537
+ * php.writeFile("/www/index.php", `<?php echo file_get_contents("php://input");`);
538
+ * const result = await php.request({
539
+ * method: "GET",
540
+ * headers: {
541
+ * "Content-Type": "text/plain"
542
+ * },
543
+ * body: "Hello world!",
544
+ * path: "/www/index.php"
545
+ * });
546
+ * // result.text === "Hello world!"
547
+ * ```
548
+ *
549
+ * The `request()` method cannot be used in conjunction with `cli()`.
550
+ *
551
+ * @example
552
+ * ```js
553
+ * const output = await php.request({
554
+ * method: 'GET',
555
+ * url: '/index.php',
556
+ * headers: {
557
+ * 'X-foo': 'bar',
558
+ * },
559
+ * body: {
560
+ * foo: 'bar',
561
+ * },
562
+ * });
563
+ * console.log(output.stdout); // "Hello world!"
564
+ * ```
565
+ *
566
+ * @param request - PHP Request data.
567
+ */
568
+ request(request: PHPRequest): Promise<PHPResponse>;
569
+ }
570
+ declare const __private__dont__use: unique symbol;
571
+ export type UnmountFunction = (() => Promise<any>) | (() => any);
572
+ export type MountHandler = (php: PHP, FS: Emscripten.RootFS, vfsMountPoint: string) => UnmountFunction | Promise<UnmountFunction>;
573
+ declare class PHP implements Disposable {
574
+ #private;
575
+ protected [__private__dont__use]: any;
576
+ requestHandler?: PHPRequestHandler;
577
+ /**
578
+ * An exclusive lock that prevent multiple requests from running at
579
+ * the same time.
580
+ */
581
+ semaphore: Semaphore;
582
+ /**
583
+ * Initializes a PHP runtime.
584
+ *
585
+ * @internal
586
+ * @param PHPRuntime - Optional. PHP Runtime ID as initialized by loadPHPRuntime.
587
+ * @param requestHandlerOptions - Optional. Options for the PHPRequestHandler. If undefined, no request handler will be initialized.
588
+ */
589
+ constructor(PHPRuntimeId?: PHPRuntimeId);
590
+ /**
591
+ * Adds an event listener for a PHP event.
592
+ * @param eventType - The type of event to listen for.
593
+ * @param listener - The listener function to be called when the event is triggered.
594
+ */
595
+ addEventListener(eventType: PHPEvent["type"], listener: PHPEventListener): void;
596
+ /**
597
+ * Removes an event listener for a PHP event.
598
+ * @param eventType - The type of event to remove the listener from.
599
+ * @param listener - The listener function to be removed.
600
+ */
601
+ removeEventListener(eventType: PHPEvent["type"], listener: PHPEventListener): void;
602
+ dispatchEvent<Event extends PHPEvent>(event: Event): void;
603
+ /**
604
+ * Listens to message sent by the PHP code.
605
+ *
606
+ * To dispatch messages, call:
607
+ *
608
+ * post_message_to_js(string $data)
609
+ *
610
+ * Arguments:
611
+ * $data (string) – Data to pass to JavaScript.
612
+ *
613
+ * @example
614
+ *
615
+ * ```ts
616
+ * const php = await PHP.load('8.0');
617
+ *
618
+ * php.onMessage(
619
+ * // The data is always passed as a string
620
+ * function (data: string) {
621
+ * // Let's decode and log the data:
622
+ * console.log(JSON.parse(data));
623
+ * }
624
+ * );
625
+ *
626
+ * // Now that we have a listener in place, let's
627
+ * // dispatch a message:
628
+ * await php.run({
629
+ * code: `<?php
630
+ * post_message_to_js(
631
+ * json_encode([
632
+ * 'post_id' => '15',
633
+ * 'post_title' => 'This is a blog post!'
634
+ * ])
635
+ * ));
636
+ * `,
637
+ * });
638
+ * ```
639
+ *
640
+ * @param listener Callback function to handle the message.
641
+ */
642
+ onMessage(listener: MessageListener): void;
643
+ setSpawnHandler(handler: SpawnHandler | string): Promise<void>;
644
+ /** @deprecated Use PHPRequestHandler instead. */
645
+ get absoluteUrl(): string;
646
+ /** @deprecated Use PHPRequestHandler instead. */
647
+ get documentRoot(): string;
648
+ /** @deprecated Use PHPRequestHandler instead. */
649
+ pathToInternalUrl(path: string): string;
650
+ /** @deprecated Use PHPRequestHandler instead. */
651
+ internalUrlToPath(internalUrl: string): string;
652
+ initializeRuntime(runtimeId: PHPRuntimeId): void;
653
+ /** @inheritDoc */
654
+ setSapiName(newName: string): Promise<void>;
655
+ /**
656
+ * Changes the current working directory in the PHP filesystem.
657
+ * This is the directory that will be used as the base for relative paths.
658
+ * For example, if the current working directory is `/root/php`, and the
659
+ * path is `data`, the absolute path will be `/root/php/data`.
660
+ *
661
+ * @param path - The new working directory.
662
+ */
663
+ chdir(path: string): void;
664
+ /**
665
+ * Do not use. Use new PHPRequestHandler() instead.
666
+ * @deprecated
667
+ */
668
+ request(request: PHPRequest): Promise<PHPResponse>;
669
+ /**
670
+ * Runs PHP code.
671
+ *
672
+ * This low-level method directly interacts with the WebAssembly
673
+ * PHP interpreter.
674
+ *
675
+ * Every time you call run(), it prepares the PHP
676
+ * environment and:
677
+ *
678
+ * * Resets the internal PHP state
679
+ * * Populates superglobals ($_SERVER, $_GET, etc.)
680
+ * * Handles file uploads
681
+ * * Populates input streams (stdin, argv, etc.)
682
+ * * Sets the current working directory
683
+ *
684
+ * You can use run() in two primary modes:
685
+ *
686
+ * ### Code snippet mode
687
+ *
688
+ * In this mode, you pass a string containing PHP code to run.
689
+ *
690
+ * ```ts
691
+ * const result = await php.run({
692
+ * code: `<?php echo "Hello world!";`
693
+ * });
694
+ * // result.text === "Hello world!"
695
+ * ```
696
+ *
697
+ * In this mode, information like __DIR__ or __FILE__ isn't very
698
+ * useful because the code is not associated with any file.
699
+ *
700
+ * Under the hood, the PHP snippet is passed to the `zend_eval_string`
701
+ * C function.
702
+ *
703
+ * ### File mode
704
+ *
705
+ * In the file mode, you pass a scriptPath and PHP executes a file
706
+ * found at a that path:
707
+ *
708
+ * ```ts
709
+ * php.writeFile(
710
+ * "/www/index.php",
711
+ * `<?php echo "Hello world!";"`
712
+ * );
713
+ * const result = await php.run({
714
+ * scriptPath: "/www/index.php"
715
+ * });
716
+ * // result.text === "Hello world!"
717
+ * ```
718
+ *
719
+ * In this mode, you can rely on path-related information like __DIR__
720
+ * or __FILE__.
721
+ *
722
+ * Under the hood, the PHP file is executed with the `php_execute_script`
723
+ * C function.
724
+ *
725
+ * The `run()` method cannot be used in conjunction with `cli()`.
726
+ *
727
+ * @example
728
+ * ```js
729
+ * const result = await php.run(`<?php
730
+ * $fp = fopen('php://stderr', 'w');
731
+ * fwrite($fp, "Hello, world!");
732
+ * `);
733
+ * // result.errors === "Hello, world!"
734
+ * ```
735
+ *
736
+ * @param options - PHP runtime options.
737
+ */
738
+ run(request: PHPRunOptions): Promise<PHPResponse>;
739
+ /**
740
+ * Defines a constant in the PHP runtime.
741
+ * @param key - The name of the constant.
742
+ * @param value - The value of the constant.
743
+ */
744
+ defineConstant(key: string, value: string | boolean | number | null): void;
745
+ /**
746
+ * Recursively creates a directory with the given path in the PHP filesystem.
747
+ * For example, if the path is `/root/php/data`, and `/root` already exists,
748
+ * it will create the directories `/root/php` and `/root/php/data`.
749
+ *
750
+ * @param path - The directory path to create.
751
+ */
752
+ mkdir(path: string): void;
753
+ /**
754
+ * @deprecated Use mkdir instead.
755
+ */
756
+ mkdirTree(path: string): void;
757
+ /**
758
+ * Reads a file from the PHP filesystem and returns it as a string.
759
+ *
760
+ * @throws {@link @php-wasm/universal:ErrnoError} – If the file doesn't exist.
761
+ * @param path - The file path to read.
762
+ * @returns The file contents.
763
+ */
764
+ readFileAsText(path: string): string;
765
+ /**
766
+ * Reads a file from the PHP filesystem and returns it as an array buffer.
767
+ *
768
+ * @throws {@link @php-wasm/universal:ErrnoError} – If the file doesn't exist.
769
+ * @param path - The file path to read.
770
+ * @returns The file contents.
771
+ */
772
+ readFileAsBuffer(path: string): Uint8Array;
773
+ /**
774
+ * Overwrites data in a file in the PHP filesystem.
775
+ * Creates a new file if one doesn't exist yet.
776
+ *
777
+ * @param path - The file path to write to.
778
+ * @param data - The data to write to the file.
779
+ */
780
+ writeFile(path: string, data: string | Uint8Array): void;
781
+ /**
782
+ * Removes a file from the PHP filesystem.
783
+ *
784
+ * @throws {@link @php-wasm/universal:ErrnoError} – If the file doesn't exist.
785
+ * @param path - The file path to remove.
786
+ */
787
+ unlink(path: string): void;
788
+ /**
789
+ * Moves a file or directory in the PHP filesystem to a
790
+ * new location.
791
+ *
792
+ * @param oldPath The path to rename.
793
+ * @param newPath The new path.
794
+ */
795
+ mv(fromPath: string, toPath: string): void;
796
+ /**
797
+ * Removes a directory from the PHP filesystem.
798
+ *
799
+ * @param path The directory path to remove.
800
+ * @param options Options for the removal.
801
+ */
802
+ rmdir(path: string, options?: RmDirOptions): void;
803
+ /**
804
+ * Lists the files and directories in the given directory.
805
+ *
806
+ * @param path - The directory path to list.
807
+ * @param options - Options for the listing.
808
+ * @returns The list of files and directories in the given directory.
809
+ */
810
+ listFiles(path: string, options?: ListFilesOptions): string[];
811
+ /**
812
+ * Checks if a directory exists in the PHP filesystem.
813
+ *
814
+ * @param path – The path to check.
815
+ * @returns True if the path is a directory, false otherwise.
816
+ */
817
+ isDir(path: string): boolean;
818
+ /**
819
+ * Checks if a file (or a directory) exists in the PHP filesystem.
820
+ *
821
+ * @param path - The file path to check.
822
+ * @returns True if the file exists, false otherwise.
823
+ */
824
+ fileExists(path: string): boolean;
825
+ /**
826
+ * Hot-swaps the PHP runtime for a new one without
827
+ * interrupting the operations of this PHP instance.
828
+ *
829
+ * @param runtime
830
+ * @param cwd. Internal, the VFS path to recreate in the new runtime.
831
+ * This arg is temporary and will be removed once BasePHP
832
+ * is fully decoupled from the request handler and
833
+ * accepts a constructor-level cwd argument.
834
+ */
835
+ hotSwapPHPRuntime(runtime: number, cwd?: string): void;
836
+ /**
837
+ * Mounts a filesystem to a given path in the PHP filesystem.
838
+ *
839
+ * @param virtualFSPath - Where to mount it in the PHP virtual filesystem.
840
+ * @param mountHandler - The mount handler to use.
841
+ * @return Unmount function to unmount the filesystem.
842
+ */
843
+ mount(virtualFSPath: string, mountHandler: MountHandler): Promise<UnmountFunction>;
844
+ /**
845
+ * Starts a PHP CLI session with given arguments.
846
+ *
847
+ * This method can only be used when PHP was compiled with the CLI SAPI
848
+ * and it cannot be used in conjunction with `run()`.
849
+ *
850
+ * Once this method finishes running, the PHP instance is no
851
+ * longer usable and should be discarded. This is because PHP
852
+ * internally cleans up all the resources and calls exit().
853
+ *
854
+ * @param argv - The arguments to pass to the CLI.
855
+ * @returns The exit code of the CLI session.
856
+ */
857
+ cli(argv: string[]): Promise<number>;
858
+ setSkipShebang(shouldSkip: boolean): void;
859
+ exit(code?: number): void;
860
+ [Symbol.dispose](): void;
861
+ }
862
+ export type LimitedPHPApi = Pick<PHP, "request" | "defineConstant" | "addEventListener" | "removeEventListener" | "mkdir" | "mkdirTree" | "readFileAsText" | "readFileAsBuffer" | "writeFile" | "unlink" | "mv" | "rmdir" | "listFiles" | "isDir" | "fileExists" | "chdir" | "run" | "onMessage"> & {
863
+ documentRoot: PHP["documentRoot"];
864
+ absoluteUrl: PHP["absoluteUrl"];
865
+ };
866
+ /**
867
+ * Represents an event related to the PHP request.
868
+ */
869
+ export interface PHPRequestEndEvent {
870
+ type: "request.end";
871
+ }
872
+ /**
873
+ * Represents an error event related to the PHP request.
874
+ */
875
+ export interface PHPRequestErrorEvent {
876
+ type: "request.error";
877
+ error: Error;
878
+ source?: "request" | "php-wasm";
879
+ }
880
+ /**
881
+ * Represents a PHP runtime initialization event.
882
+ */
883
+ export interface PHPRuntimeInitializedEvent {
884
+ type: "runtime.initialized";
885
+ }
886
+ /**
887
+ * Represents a PHP runtime destruction event.
888
+ */
889
+ export interface PHPRuntimeBeforeDestroyEvent {
890
+ type: "runtime.beforedestroy";
891
+ }
892
+ /**
893
+ * Represents an event related to the PHP instance.
894
+ * This is intentionally not an extension of CustomEvent
895
+ * to make it isomorphic between different JavaScript runtimes.
896
+ */
897
+ export type PHPEvent = PHPRequestEndEvent | PHPRequestErrorEvent | PHPRuntimeInitializedEvent | PHPRuntimeBeforeDestroyEvent;
898
+ /**
899
+ * A callback function that handles PHP events.
900
+ */
901
+ export type PHPEventListener = (event: PHPEvent) => void;
902
+ export type UniversalPHP = LimitedPHPApi | Remote<LimitedPHPApi>;
903
+ export type MessageListener = (data: string) => Promise<string | Uint8Array | void> | string | void;
904
+ export interface EventEmitter {
905
+ on(event: string, listener: (...args: any[]) => void): this;
906
+ emit(event: string, ...args: any[]): boolean;
907
+ }
908
+ export type ChildProcess = EventEmitter & {
909
+ stdout: EventEmitter;
910
+ stderr: EventEmitter;
911
+ };
912
+ export type SpawnHandler = (command: string, args: string[]) => ChildProcess;
913
+ export type HTTPMethod = "GET" | "POST" | "HEAD" | "OPTIONS" | "PATCH" | "PUT" | "DELETE";
914
+ export type PHPRequestHeaders = Record<string, string>;
915
+ export interface PHPRequest {
916
+ /**
917
+ * Request method. Default: `GET`.
918
+ */
919
+ method?: HTTPMethod;
920
+ /**
921
+ * Request path or absolute URL.
922
+ */
923
+ url: string;
924
+ /**
925
+ * Request headers.
926
+ */
927
+ headers?: PHPRequestHeaders;
928
+ /**
929
+ * Request body.
930
+ * If an object is given, the request will be encoded as multipart
931
+ * and sent with a `multipart/form-data` header.
932
+ */
933
+ body?: string | Uint8Array | Record<string, string | Uint8Array | File>;
934
+ }
935
+ export interface PHPRunOptions {
936
+ /**
937
+ * Request path following the domain:port part.
938
+ */
939
+ relativeUri?: string;
940
+ /**
941
+ * Path of the .php file to execute.
942
+ */
943
+ scriptPath?: string;
944
+ /**
945
+ * Request protocol.
946
+ */
947
+ protocol?: string;
948
+ /**
949
+ * Request method. Default: `GET`.
950
+ */
951
+ method?: HTTPMethod;
952
+ /**
953
+ * Request headers.
954
+ */
955
+ headers?: PHPRequestHeaders;
956
+ /**
957
+ * Request body.
958
+ */
959
+ body?: string | Uint8Array;
960
+ /**
961
+ * Environment variables to set for this run.
962
+ */
963
+ env?: Record<string, string>;
964
+ /**
965
+ * $_SERVER entries to set for this run.
966
+ */
967
+ $_SERVER?: Record<string, string>;
968
+ /**
969
+ * The code snippet to eval instead of a php file.
970
+ */
971
+ code?: string;
972
+ }
973
+ export type IterateFilesOptions = {
974
+ /**
975
+ * Should yield paths relative to the root directory?
976
+ * If false, all paths will be absolute.
977
+ */
978
+ relativePaths?: boolean;
979
+ /**
980
+ * The root directory that Playground paths start from.
981
+ */
982
+ playgroundRoot?: string;
983
+ /**
984
+ * A prefix to add to all paths.
985
+ * Only used if `relativePaths` is true.
986
+ */
987
+ pathPrefix?: string;
988
+ /**
989
+ * A list of paths to exclude from the results.
990
+ */
991
+ exceptPaths?: string[];
992
+ };
993
+ /**
994
+ * Iterates over all files in a Playground directory and its subdirectories.
995
+ *
996
+ * @param playground - The Playground/PHP instance.
997
+ * @param root - The root directory to start iterating from.
998
+ * @param options - Optional configuration.
999
+ * @returns All files found in the tree.
1000
+ */
1001
+ export declare function iterateFiles(playground: UniversalPHP, root: string, { exceptPaths }?: IterateFilesOptions): AsyncGenerator<FileEntry>;
1002
+ export type FileEntry = {
1003
+ path: string;
1004
+ read: () => Promise<Uint8Array>;
1005
+ };
1006
+ /**
1007
+ * Represents a set of changes to be applied to a data store.
1008
+ */
1009
+ export type Changeset = {
1010
+ /**
1011
+ * Created files.
1012
+ */
1013
+ create: Map<string, Uint8Array>;
1014
+ /**
1015
+ * Updated files.
1016
+ */
1017
+ update: Map<string, Uint8Array>;
1018
+ /**
1019
+ * Deleted files.
1020
+ */
1021
+ delete: Set<string>;
1022
+ };
1023
+ /**
1024
+ * Compares two sets of files and returns a changeset object that describes
1025
+ * the differences between them.
1026
+ *
1027
+ * @param filesBefore - A map of file paths to Uint8Array objects representing the contents
1028
+ * of the files before the changes.
1029
+ * @param filesAfter - An async generator that yields FileEntry objects representing the files
1030
+ * after the changes.
1031
+ * @returns A changeset object that describes the differences between the two sets of files.
1032
+ */
1033
+ export declare function changeset(filesBefore: Map<string, Uint8Array>, filesAfter: AsyncGenerator<FileEntry> | Iterable<FileEntry>): Promise<Changeset>;
1034
+ export type GithubClient = ReturnType<typeof createClient>;
1035
+ export declare function createClient(githubToken: string): Octokit;
1036
+ export type Files = Record<string, Uint8Array>;
1037
+ export declare function filesListToObject(files: any[], root?: string): Files;
1038
+ export interface GetFilesProgress {
1039
+ foundFiles: number;
1040
+ downloadedFiles: number;
1041
+ }
1042
+ export interface GetFilesOptions {
1043
+ onProgress?: ({ foundFiles, downloadedFiles }: GetFilesProgress) => void;
1044
+ progress?: GetFilesProgress;
1045
+ }
1046
+ export declare function getFilesFromDirectory(octokit: GithubClient, owner: string, repo: string, ref: string, path: string, options?: GetFilesOptions): Promise<any[]>;
1047
+ /**
1048
+ * Usage:
1049
+ * > await getArtifact('wordpress', 'wordpress-develop', 5511, 'build.yml')
1050
+ *
1051
+ * To get the first artifact produced by the "build.yml" workflow running
1052
+ * as a part of the PR 5511
1053
+ *
1054
+ * @returns
1055
+ */
1056
+ export declare function getArtifact(octokit: GithubClient, owner: string, repo: string, pull_number: number, workflow_id: string): Promise<unknown>;
1057
+ export declare function mayPush(octokit: Octokit, owner: string, repo: string): Promise<boolean>;
1058
+ export declare function createOrUpdateBranch(octokit: Octokit, owner: string, repo: string, branch: string, newHead: string): Promise<void>;
1059
+ /**
1060
+ * @param octokit
1061
+ * @param owner
1062
+ * @param repo
1063
+ * @returns The owner of the forked repository
1064
+ */
1065
+ export declare function fork(octokit: Octokit, owner: string, repo: string): Promise<string>;
1066
+ export declare function createCommit(octokit: Octokit, owner: string, repo: string, message: string, parentSha: string, treeSha: string): Promise<string>;
1067
+ export declare function createTree(octokit: Octokit, owner: string, repo: string, parentSha: string, changeset: Changeset): Promise<string | null>;
1068
+ export type GitHubTreeNode = {
1069
+ path: string;
1070
+ mode: "100644";
1071
+ } & ({
1072
+ sha: string | null;
1073
+ } | {
1074
+ content: string;
1075
+ });
1076
+ export declare function createTreeNodes(octokit: Octokit, owner: string, repo: string, parentSha: string, changeset: Changeset): Promise<GitHubTreeNode[]>;
1077
+ export declare function createTreeNode(octokit: Octokit, owner: string, repo: string, path: string, content: string | Uint8Array): Promise<GitHubTreeNode>;
1078
+ export declare function deleteFile(octokit: Octokit, owner: string, repo: string, parentSha: string, path: string): Promise<GitHubTreeNode | undefined>;
1079
+ export type GitHubFile = {
1080
+ path: string;
1081
+ content: Uint8Array;
1082
+ };
1083
+
1084
+ export {};