-
Notifications
You must be signed in to change notification settings - Fork 8
/
polyfill-core.mjs
294 lines (265 loc) · 8.52 KB
/
polyfill-core.mjs
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
let base64Characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
let base64UrlCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
let tag = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get;
export function checkUint8Array(arg) {
let kind;
try {
kind = tag.call(arg);
} catch {
throw new TypeError('not a Uint8Array');
}
if (kind !== 'Uint8Array') {
throw new TypeError('not a Uint8Array');
}
}
function assert(condition, message) {
if (!condition) {
throw new Error(`Assert failed: ${message}`);
}
}
function getOptions(options) {
if (typeof options === 'undefined') {
return Object.create(null);
}
if (options && typeof options === 'object') {
return options;
}
throw new TypeError('options is not object');
}
export function uint8ArrayToBase64(arr, options) {
checkUint8Array(arr);
let opts = getOptions(options);
let alphabet = opts.alphabet;
if (typeof alphabet === 'undefined') {
alphabet = 'base64';
}
if (alphabet !== 'base64' && alphabet !== 'base64url') {
throw new TypeError('expected alphabet to be either "base64" or "base64url"');
}
if ('detached' in arr.buffer && arr.buffer.detached) {
throw new TypeError('toBase64 called on array backed by detached buffer');
}
let lookup = alphabet === 'base64' ? base64Characters : base64UrlCharacters;
let result = '';
let i = 0;
for (; i + 2 < arr.length; i += 3) {
let triplet = (arr[i] << 16) + (arr[i + 1] << 8) + arr[i + 2];
result +=
lookup[(triplet >> 18) & 63] +
lookup[(triplet >> 12) & 63] +
lookup[(triplet >> 6) & 63] +
lookup[triplet & 63];
}
if (i + 2 === arr.length) {
let triplet = (arr[i] << 16) + (arr[i + 1] << 8);
result +=
lookup[(triplet >> 18) & 63] +
lookup[(triplet >> 12) & 63] +
lookup[(triplet >> 6) & 63] +
'=';
} else if (i + 1 === arr.length) {
let triplet = arr[i] << 16;
result +=
lookup[(triplet >> 18) & 63] +
lookup[(triplet >> 12) & 63] +
'==';
}
return result;
}
function decodeBase64Chunk(chunk, throwOnExtraBits) {
let actualChunkLength = chunk.length;
if (actualChunkLength < 4) {
chunk += actualChunkLength === 2 ? 'AA' : 'A';
}
let map = new Map(base64Characters.split('').map((c, i) => [c, i]));
let c1 = chunk[0];
let c2 = chunk[1];
let c3 = chunk[2];
let c4 = chunk[3];
let triplet =
(map.get(c1) << 18) +
(map.get(c2) << 12) +
(map.get(c3) << 6) +
map.get(c4);
let chunkBytes = [
(triplet >> 16) & 255,
(triplet >> 8) & 255,
triplet & 255
];
if (actualChunkLength === 2) {
if (throwOnExtraBits && chunkBytes[1] !== 0) {
throw new SyntaxError('extra bits');
}
return [chunkBytes[0]];
} else if (actualChunkLength === 3) {
if (throwOnExtraBits && chunkBytes[2] !== 0) {
throw new SyntaxError('extra bits');
}
return [chunkBytes[0], chunkBytes[1]];
}
return chunkBytes;
}
function skipAsciiWhitespace(string, index) {
for (; index < string.length; ++index) {
if (!/[\u0009\u000A\u000C\u000D\u0020]/.test(string[index])) {
break;
}
}
return index;
}
function fromBase64(string, alphabet, lastChunkHandling, maxLength) {
if (maxLength === 0) {
return { read: 0, bytes: [] };
}
let read = 0;
let bytes = [];
let chunk = '';
let index = 0
while (true) {
index = skipAsciiWhitespace(string, index);
if (index === string.length) {
if (chunk.length > 0) {
if (lastChunkHandling === 'stop-before-partial') {
return { bytes, read };
} else if (lastChunkHandling === 'loose') {
if (chunk.length === 1) {
throw new SyntaxError('malformed padding: exactly one additional character');
}
bytes.push(...decodeBase64Chunk(chunk, false));
} else {
assert(lastChunkHandling === 'strict');
throw new SyntaxError('missing padding');
}
}
return { bytes, read: string.length };
}
let char = string[index];
++index;
if (char === '=') {
if (chunk.length < 2) {
throw new SyntaxError('padding is too early');
}
index = skipAsciiWhitespace(string, index);
if (chunk.length === 2) {
if (index === string.length) {
if (lastChunkHandling === 'stop-before-partial') {
// two characters then `=` then EOS: this is, technically, a partial chunk
return { bytes, read };
}
throw new SyntaxError('malformed padding - only one =');
}
if (string[index] === '=') {
++index;
index = skipAsciiWhitespace(string, index);
}
}
if (index < string.length) {
throw new SyntaxError('unexpected character after padding');
}
bytes.push(...decodeBase64Chunk(chunk, lastChunkHandling === 'strict'));
assert(bytes.length <= maxLength);
return { bytes, read: string.length };
}
if (alphabet === 'base64url') {
if (char === '+' || char === '/') {
throw new SyntaxError(`unexpected character ${JSON.stringify(char)}`);
} else if (char === '-') {
char = '+';
} else if (char === '_') {
char = '/';
}
}
if (!base64Characters.includes(char)) {
throw new SyntaxError(`unexpected character ${JSON.stringify(char)}`);
}
let remainingBytes = maxLength - bytes.length;
if (remainingBytes === 1 && chunk.length === 2 || remainingBytes === 2 && chunk.length === 3) {
// special case: we can fit exactly the number of bytes currently represented by chunk, so we were just checking for `=`
return { bytes, read };
}
chunk += char;
if (chunk.length === 4) {
bytes.push(...decodeBase64Chunk(chunk, false));
chunk = '';
read = index;
assert(bytes.length <= maxLength);
if (bytes.length === maxLength) {
return { bytes, read };
}
}
}
}
export function base64ToUint8Array(string, options, into) {
let opts = getOptions(options);
let alphabet = opts.alphabet;
if (typeof alphabet === 'undefined') {
alphabet = 'base64';
}
if (alphabet !== 'base64' && alphabet !== 'base64url') {
throw new TypeError('expected alphabet to be either "base64" or "base64url"');
}
let lastChunkHandling = opts.lastChunkHandling;
if (typeof lastChunkHandling === 'undefined') {
lastChunkHandling = 'loose';
}
if (!['loose', 'strict', 'stop-before-partial'].includes(lastChunkHandling)) {
throw new TypeError('expected lastChunkHandling to be either "loose", "strict", or "stop-before-partial"');
}
if (into && 'detached' in into.buffer && into.buffer.detached) {
throw new TypeError('toBase64Into called on array backed by detached buffer');
}
let maxLength = into ? into.length : 2 ** 53 - 1;
let { bytes, read } = fromBase64(string, alphabet, lastChunkHandling, maxLength);
bytes = new Uint8Array(bytes);
if (into && bytes.length > 0) {
assert(bytes.length <= into.length);
into.set(bytes);
}
return { read, bytes };
}
export function uint8ArrayToHex(arr) {
checkUint8Array(arr);
if ('detached' in arr.buffer && arr.buffer.detached) {
throw new TypeError('toHex called on array backed by detached buffer');
}
let out = '';
for (let i = 0; i < arr.length; ++i) {
out += arr[i].toString(16).padStart(2, '0');
}
return out;
}
export function hexToUint8Array(string, into) {
if (typeof string !== 'string') {
throw new TypeError('expected string to be a string');
}
if (into && 'detached' in into.buffer && into.buffer.detached) {
throw new TypeError('fromHexInto called on array backed by detached buffer');
}
if (string.length % 2 !== 0) {
throw new SyntaxError('string should be an even number of characters');
}
let maxLength = into ? into.length : 2 ** 53 - 1;
// TODO should hex allow whitespace?
// TODO should hex support lastChunkHandling? (only 'strict' or 'stop-before-partial')
let bytes = [];
let index = 0;
if (maxLength > 0) {
while (index < string.length) {
let hexits = string.slice(index, index + 2);
if (/[^0-9a-fA-F]/.test(hexits)) {
throw new SyntaxError('string should only contain hex characters');
}
bytes.push(parseInt(hexits, 16));
index += 2;
if (bytes.length === maxLength) {
break;
}
}
}
bytes = new Uint8Array(bytes);
if (into && bytes.length > 0) {
assert(bytes.length <= into.length);
into.set(bytes);
}
return { read: index, bytes };
}