forked from vercel/next.js
/
polyfills.ts
87 lines (75 loc) · 2.11 KB
/
polyfills.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
import { Crypto as WebCrypto } from 'next/dist/compiled/@peculiar/webcrypto'
import { CryptoKey } from 'next/dist/compiled/@peculiar/webcrypto'
import { TransformStream } from 'next/dist/compiled/web-streams-polyfill'
import { v4 as uuid } from 'next/dist/compiled/uuid'
import crypto from 'crypto'
export function atob(b64Encoded: string) {
return Buffer.from(b64Encoded, 'base64').toString('binary')
}
export function btoa(str: string) {
return Buffer.from(str, 'binary').toString('base64')
}
export { CryptoKey }
export class Crypto extends WebCrypto {
// @ts-ignore Remove once types are updated and we deprecate node 12
randomUUID = crypto.randomUUID || uuid
}
export class ReadableStream<T> {
constructor(opts: UnderlyingSource = {}) {
let closed = false
let pullPromise: any
let transformController: TransformStreamDefaultController
const { readable, writable } = new TransformStream(
{
start: (controller: TransformStreamDefaultController) => {
transformController = controller
},
},
undefined,
{
highWaterMark: 1,
}
)
const writer = writable.getWriter()
const encoder = new TextEncoder()
const controller: ReadableStreamController<T> = {
get desiredSize() {
return transformController.desiredSize
},
close: () => {
if (!closed) {
closed = true
writer.close()
}
},
enqueue: (chunk: T) => {
writer.write(typeof chunk === 'string' ? encoder.encode(chunk) : chunk)
pull()
},
error: (reason: any) => {
transformController.error(reason)
},
}
const pull = () => {
if (opts.pull) {
if (!pullPromise) {
pullPromise = Promise.resolve().then(() => {
pullPromise = 0
opts.pull!(controller)
})
}
}
}
if (opts.start) {
opts.start(controller)
}
if (opts.cancel) {
readable.cancel = (reason: any) => {
opts.cancel!(reason)
return readable.cancel(reason)
}
}
pull()
return readable
}
}