forked from WordPress/wordpress-playground
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.ts
54 lines (48 loc) · 1.59 KB
/
common.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
import type { UniversalPHP } from '@php-wasm/universal';
export function zipNameToHumanName(zipName: string) {
const mixedCaseName = zipName.split('.').shift()!.replace(/-/g, ' ');
return (
mixedCaseName.charAt(0).toUpperCase() +
mixedCaseName.slice(1).toLowerCase()
);
}
type PatchFileCallback = (contents: string) => string | Uint8Array;
export async function updateFile(
php: UniversalPHP,
path: string,
callback: PatchFileCallback
) {
let contents = '';
if (await php.fileExists(path)) {
contents = await php.readFileAsText(path);
}
await php.writeFile(path, callback(contents));
}
export async function fileToUint8Array(file: File) {
return new Uint8Array(await file.arrayBuffer());
}
/**
* Polyfill the File class in JSDOM which lacks arrayBuffer() method
*
* - [Implement Blob.stream, Blob.text and Blob.arrayBuffer](https://github.com/jsdom/jsdom/issues/2555)
*
* When a Resource (../resources.ts) resolves to an instance of File, the
* resulting object is missing the arrayBuffer() method in JSDOM environment
* during tests.
*
* Import the polyfilled File class below to ensure its buffer is available to
* functions like writeFile (./client-methods.ts) and fileToUint8Array (above).
*/
class FilePolyfill extends File {
buffers: BlobPart[];
constructor(buffers: BlobPart[], name: string) {
super(buffers, name);
this.buffers = buffers;
}
override async arrayBuffer(): Promise<ArrayBuffer> {
return this.buffers[0] as ArrayBuffer;
}
}
const FileWithArrayBuffer =
File.prototype.arrayBuffer instanceof Function ? File : FilePolyfill;
export { FileWithArrayBuffer as File };