aboutsummaryrefslogtreecommitdiff
path: root/packages/bun-polyfills/src/global/index.ts
blob: 661a2c3c1660297e9aba4b45104ce5dd76833847 (plain) (blame)
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
import { version } from '../modules/bun.js';
import './console.js';
import './process.js';
import os from 'node:os';

//? NodeJS Blob doesn't implement Blob.json(), so we need to polyfill it.
Blob.prototype.json = async function json<T>(this: Blob): Promise<T> {
    try {
        return JSON.parse(await this.text()) as T;
    } catch (err) {
        Error.captureStackTrace(err as Error, json);
        throw err;
    }
};

//? navigator global object polyfill
Reflect.set(globalThis, 'navigator', {
    userAgent: `Bun/${version}`,
    hardwareConcurrency: os.cpus().length,
});

//? method only available in Bun
// this isn't quite accurate, but it shouldn't break anything and is currently here just for matching bun and node types
const ReadableStreamDefaultReaderPrototype = Object.getPrototypeOf(new ReadableStream().getReader());
Reflect.set(
    ReadableStreamDefaultReaderPrototype, 'readMany',
    function readMany(this: ReadableStreamDefaultReader): Promise<ReadableStreamDefaultReadManyResult<any>> {
        return new Promise((resolve, reject) => {
            const result: ReadableStreamDefaultReadManyResult<any> = {
                value: [],
                size: 0,
                done: true
            };
            this.read().then(({ done, value }) => {
                if (done) resolve(result);
                else {
                    result.value.push(value);
                    result.size = value.length;
                    result.done = false;
                    resolve(result);
                }
            }, reject);
        });
    }
);