-
Notifications
You must be signed in to change notification settings - Fork 209
/
universal-php.ts
456 lines (409 loc) · 11.1 KB
/
universal-php.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
import { Remote } from 'comlink';
import { PHPResponse } from './php-response';
/**
* Represents an event related to the PHP request.
*/
export interface PHPRequestEndEvent {
type: 'request.end';
}
/**
* Represents an error event related to the PHP request.
*/
export interface PHPRequestErrorEvent {
type: 'request.error';
error: Error;
source?: 'request' | 'php-wasm';
}
/**
* Represents a PHP runtime initialization event.
*/
export interface PHPRuntimeInitializedEvent {
type: 'runtime.initialized';
}
/**
* Represents a PHP runtime destruction event.
*/
export interface PHPRuntimeBeforeDestroyEvent {
type: 'runtime.beforedestroy';
}
/**
* Represents an event related to the PHP instance.
* This is intentionally not an extension of CustomEvent
* to make it isomorphic between different JavaScript runtimes.
*/
export type PHPEvent =
| PHPRequestEndEvent
| PHPRequestErrorEvent
| PHPRuntimeInitializedEvent
| PHPRuntimeBeforeDestroyEvent;
/**
* A callback function that handles PHP events.
*/
export type PHPEventListener = (event: PHPEvent) => void;
export interface IsomorphicLocalPHP {
/** @deprecated Use PHPRequestHandler instead. */
request(request: PHPRequest): Promise<PHPResponse>;
/** @deprecated Use PHPRequestHandler instead. */
pathToInternalUrl(path: string): string;
/** @deprecated Use PHPRequestHandler instead. */
internalUrlToPath(internalUrl: string): string;
/** @deprecated Use PHPRequestHandler instead. */
absoluteUrl: string;
/** @deprecated Use PHPRequestHandler instead. */
documentRoot: string;
/**
* Sets the SAPI name exposed by the PHP module.
* @param newName - The new SAPI name.
*/
setSapiName(newName: string): void;
/**
* Defines a constant in the PHP runtime.
* @param key - The name of the constant.
* @param value - The value of the constant.
*/
defineConstant(key: string, value: boolean | string | number | null): void;
/**
* Adds an event listener for a PHP event.
* @param eventType - The type of event to listen for.
* @param listener - The listener function to be called when the event is triggered.
*/
addEventListener(
eventType: PHPEvent['type'],
listener: PHPEventListener
): void;
/**
* Removes an event listener for a PHP event.
* @param eventType - The type of event to remove the listener from.
* @param listener - The listener function to be removed.
*/
removeEventListener(
eventType: PHPEvent['type'],
listener: PHPEventListener
): void;
/**
* Sets the path to the php.ini file to use for the PHP instance.
*
* @param path - The path to the php.ini file.
*/
setPhpIniPath(path: string): void;
/**
* Sets a value for a specific key in the php.ini file for the PHP instance.
*
* @param key - The key to set the value for.
* @param value - The value to set for the key.
*/
setPhpIniEntry(key: string, value: string): void;
/**
* Recursively creates a directory with the given path in the PHP filesystem.
* For example, if the path is `/root/php/data`, and `/root` already exists,
* it will create the directories `/root/php` and `/root/php/data`.
*
* @param path - The directory path to create.
*/
mkdir(path: string): void;
/**
* @deprecated Use mkdir instead.
*/
mkdirTree(path: string): void;
/**
* Reads a file from the PHP filesystem and returns it as a string.
*
* @throws {@link @php-wasm/universal:ErrnoError} – If the file doesn't exist.
* @param path - The file path to read.
* @returns The file contents.
*/
readFileAsText(path: string): string;
/**
* Reads a file from the PHP filesystem and returns it as an array buffer.
*
* @throws {@link @php-wasm/universal:ErrnoError} – If the file doesn't exist.
* @param path - The file path to read.
* @returns The file contents.
*/
readFileAsBuffer(path: string): Uint8Array;
/**
* Overwrites data in a file in the PHP filesystem.
* Creates a new file if one doesn't exist yet.
*
* @param path - The file path to write to.
* @param data - The data to write to the file.
*/
writeFile(path: string, data: string | Uint8Array): void;
/**
* Removes a file from the PHP filesystem.
*
* @throws {@link @php-wasm/universal:ErrnoError} – If the file doesn't exist.
* @param path - The file path to remove.
*/
unlink(path: string): void;
/**
* Moves a file or directory in the PHP filesystem to a
* new location.
*
* @param oldPath The path to rename.
* @param newPath The new path.
*/
mv(oldPath: string, newPath: string): void;
/**
* Removes a directory from the PHP filesystem.
*
* @param path The directory path to remove.
* @param options Options for the removal.
*/
rmdir(path: string, options?: RmDirOptions): void;
/**
* Lists the files and directories in the given directory.
*
* @param path - The directory path to list.
* @param options - Options for the listing.
* @returns The list of files and directories in the given directory.
*/
listFiles(path: string, options?: ListFilesOptions): string[];
/**
* Checks if a directory exists in the PHP filesystem.
*
* @param path – The path to check.
* @returns True if the path is a directory, false otherwise.
*/
isDir(path: string): boolean;
/**
* Checks if a file (or a directory) exists in the PHP filesystem.
*
* @param path - The file path to check.
* @returns True if the file exists, false otherwise.
*/
fileExists(path: string): boolean;
/**
* Changes the current working directory in the PHP filesystem.
* This is the directory that will be used as the base for relative paths.
* For example, if the current working directory is `/root/php`, and the
* path is `data`, the absolute path will be `/root/php/data`.
*
* @param path - The new working directory.
*/
chdir(path: string): void;
/**
* Runs PHP code.
*
* This low-level method directly interacts with the WebAssembly
* PHP interpreter.
*
* Every time you call run(), it prepares the PHP
* environment and:
*
* * Resets the internal PHP state
* * Populates superglobals ($_SERVER, $_GET, etc.)
* * Handles file uploads
* * Populates input streams (stdin, argv, etc.)
* * Sets the current working directory
*
* You can use run() in two primary modes:
*
* ### Code snippet mode
*
* In this mode, you pass a string containing PHP code to run.
*
* ```ts
* const result = await php.run({
* code: `<?php echo "Hello world!";`
* });
* // result.text === "Hello world!"
* ```
*
* In this mode, information like __DIR__ or __FILE__ isn't very
* useful because the code is not associated with any file.
*
* Under the hood, the PHP snippet is passed to the `zend_eval_string`
* C function.
*
* ### File mode
*
* In the file mode, you pass a scriptPath and PHP executes a file
* found at a that path:
*
* ```ts
* php.writeFile(
* "/www/index.php",
* `<?php echo "Hello world!";"`
* );
* const result = await php.run({
* scriptPath: "/www/index.php"
* });
* // result.text === "Hello world!"
* ```
*
* In this mode, you can rely on path-related information like __DIR__
* or __FILE__.
*
* Under the hood, the PHP file is executed with the `php_execute_script`
* C function.
*
* The `run()` method cannot be used in conjunction with `cli()`.
*
* @example
* ```js
* const result = await php.run(`<?php
* $fp = fopen('php://stderr', 'w');
* fwrite($fp, "Hello, world!");
* `);
* // result.errors === "Hello, world!"
* ```
*
* @param options - PHP runtime options.
*/
run(options: PHPRunOptions): Promise<PHPResponse>;
/**
* Listens to message sent by the PHP code.
*
* To dispatch messages, call:
*
* post_message_to_js(string $data)
*
* Arguments:
* $data (string) – Data to pass to JavaScript.
*
* @example
*
* ```ts
* const php = await PHP.load('8.0');
*
* php.onMessage(
* // The data is always passed as a string
* function (data: string) {
* // Let's decode and log the data:
* console.log(JSON.parse(data));
* }
* );
*
* // Now that we have a listener in place, let's
* // dispatch a message:
* await php.run({
* code: `<?php
* post_message_to_js(
* json_encode([
* 'post_id' => '15',
* 'post_title' => 'This is a blog post!'
* ])
* ));
* `,
* });
* ```
*
* @param listener Callback function to handle the message.
*/
onMessage(listener: MessageListener): void;
}
export type MessageListener = (
data: string
) => Promise<string | Uint8Array | void> | string | void;
interface EventEmitter {
on(event: string, listener: (...args: any[]) => void): this;
emit(event: string, ...args: any[]): boolean;
}
type ChildProcess = EventEmitter & {
stdout: EventEmitter;
stderr: EventEmitter;
};
export type SpawnHandler = (command: string, args: string[]) => ChildProcess;
/**
* The omited methods must either be called synchronously before
* the PHP internal state is initialized, or with a complex argument
* that can't be serialized over a remote connection. Therefeore,
* they don't make sense in a remote PHP instance.
*/
export type IsomorphicRemotePHP = Remote<
Omit<IsomorphicLocalPHP, 'setSapiName' | 'setPhpIniEntry' | 'setPhpIniPath'>
>;
export type UniversalPHP = IsomorphicLocalPHP | IsomorphicRemotePHP;
export type HTTPMethod =
| 'GET'
| 'POST'
| 'HEAD'
| 'OPTIONS'
| 'PATCH'
| 'PUT'
| 'DELETE';
export type PHPRequestHeaders = Record<string, string>;
export interface PHPRequest {
/**
* Request method. Default: `GET`.
*/
method?: HTTPMethod;
/**
* Request path or absolute URL.
*/
url: string;
/**
* Request headers.
*/
headers?: PHPRequestHeaders;
/**
* Request body.
* If an object is given, the request will be encoded as multipart
* and sent with a `multipart/form-data` header.
*/
body?: string | Uint8Array | Record<string, string | Uint8Array | File>;
}
export interface PHPRunOptions {
/**
* Request path following the domain:port part.
*/
relativeUri?: string;
/**
* Path of the .php file to execute.
*/
scriptPath?: string;
/**
* Request protocol.
*/
protocol?: string;
/**
* Request method. Default: `GET`.
*/
method?: HTTPMethod;
/**
* Request headers.
*/
headers?: PHPRequestHeaders;
/**
* Request body.
*/
body?: string | Uint8Array;
/**
* Environment variables to set for this run.
*/
env?: Record<string, string>;
/**
* $_SERVER entries to set for this run.
*/
$_SERVER?: Record<string, string>;
/**
* The code snippet to eval instead of a php file.
*/
code?: string;
}
/**
* Output of the PHP.wasm runtime.
*/
export interface PHPOutput {
/** Exit code of the PHP process. 0 means success, 1 and 2 mean error. */
exitCode: number;
/** Stdout data */
stdout: ArrayBuffer;
/** Stderr lines */
stderr: string[];
}
export interface RmDirOptions {
/**
* If true, recursively removes the directory and all its contents.
* Default: true.
*/
recursive?: boolean;
}
export interface ListFilesOptions {
/**
* If true, prepend given folder path to all file names.
* Default: false.
*/
prependPath: boolean;
}