-
Notifications
You must be signed in to change notification settings - Fork 513
/
io.js
730 lines (644 loc) · 18.4 KB
/
io.js
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
/*
Copyright (c) 2022 Gildas Lormeau. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* global Blob, atob, btoa, XMLHttpRequest, URL, fetch, ReadableStream, WritableStream, FileReader, TransformStream, Response */
// deno-lint-ignore-file no-this-alias
import {
UNDEFINED_VALUE,
FUNCTION_TYPE
} from "./constants.js";
import { getConfiguration } from "./configuration.js";
const ERR_HTTP_STATUS = "HTTP error ";
const ERR_HTTP_RANGE = "HTTP Range not supported";
const ERR_ITERATOR_COMPLETED_TOO_SOON = "Writer iterator completed too soon";
const CONTENT_TYPE_TEXT_PLAIN = "text/plain";
const HTTP_HEADER_CONTENT_LENGTH = "Content-Length";
const HTTP_HEADER_CONTENT_RANGE = "Content-Range";
const HTTP_HEADER_ACCEPT_RANGES = "Accept-Ranges";
const HTTP_HEADER_RANGE = "Range";
const HTTP_HEADER_CONTENT_TYPE = "Content-Type";
const HTTP_METHOD_HEAD = "HEAD";
const HTTP_METHOD_GET = "GET";
const HTTP_RANGE_UNIT = "bytes";
const DEFAULT_CHUNK_SIZE = 64 * 1024;
const PROPERTY_NAME_WRITABLE = "writable";
class Stream {
constructor() {
this.size = 0;
}
init() {
this.initialized = true;
}
}
class Reader extends Stream {
get readable() {
const reader = this;
const { chunkSize = DEFAULT_CHUNK_SIZE } = reader;
const readable = new ReadableStream({
start() {
this.chunkOffset = 0;
},
async pull(controller) {
const { offset = 0, size, diskNumberStart } = readable;
const { chunkOffset } = this;
controller.enqueue(await readUint8Array(reader, offset + chunkOffset, Math.min(chunkSize, size - chunkOffset), diskNumberStart));
if (chunkOffset + chunkSize > size) {
controller.close();
} else {
this.chunkOffset += chunkSize;
}
}
});
return readable;
}
}
class Writer extends Stream {
constructor() {
super();
const writer = this;
const writable = new WritableStream({
write(chunk) {
return writer.writeUint8Array(chunk);
}
});
Object.defineProperty(writer, PROPERTY_NAME_WRITABLE, {
get() {
return writable;
}
});
}
writeUint8Array() {
// abstract
}
}
class Data64URIReader extends Reader {
constructor(dataURI) {
super();
let dataEnd = dataURI.length;
while (dataURI.charAt(dataEnd - 1) == "=") {
dataEnd--;
}
const dataStart = dataURI.indexOf(",") + 1;
Object.assign(this, {
dataURI,
dataStart,
size: Math.floor((dataEnd - dataStart) * 0.75)
});
}
readUint8Array(offset, length) {
const {
dataStart,
dataURI
} = this;
const dataArray = new Uint8Array(length);
const start = Math.floor(offset / 3) * 4;
const bytes = atob(dataURI.substring(start + dataStart, Math.ceil((offset + length) / 3) * 4 + dataStart));
const delta = offset - Math.floor(start / 4) * 3;
for (let indexByte = delta; indexByte < delta + length; indexByte++) {
dataArray[indexByte - delta] = bytes.charCodeAt(indexByte);
}
return dataArray;
}
}
class Data64URIWriter extends Writer {
constructor(contentType) {
super();
Object.assign(this, {
data: "data:" + (contentType || "") + ";base64,",
pending: []
});
}
writeUint8Array(array) {
const writer = this;
let indexArray = 0;
let dataString = writer.pending;
const delta = writer.pending.length;
writer.pending = "";
for (indexArray = 0; indexArray < (Math.floor((delta + array.length) / 3) * 3) - delta; indexArray++) {
dataString += String.fromCharCode(array[indexArray]);
}
for (; indexArray < array.length; indexArray++) {
writer.pending += String.fromCharCode(array[indexArray]);
}
if (dataString.length > 2) {
writer.data += btoa(dataString);
} else {
writer.pending = dataString;
}
}
getData() {
return this.data + btoa(this.pending);
}
}
class BlobReader extends Reader {
constructor(blob) {
super();
Object.assign(this, {
blob,
size: blob.size
});
}
async readUint8Array(offset, length) {
const reader = this;
const offsetEnd = offset + length;
const blob = offset || offsetEnd < reader.size ? reader.blob.slice(offset, offsetEnd) : reader.blob;
return new Uint8Array(await blob.arrayBuffer());
}
}
class BlobWriter extends Stream {
constructor(contentType) {
super();
const writer = this;
const transformStream = new TransformStream();
const headers = [];
if (contentType) {
headers.push([HTTP_HEADER_CONTENT_TYPE, contentType]);
}
Object.defineProperty(writer, PROPERTY_NAME_WRITABLE, {
get() {
return transformStream.writable;
}
});
writer.blob = new Response(transformStream.readable, { headers }).blob();
}
getData() {
return this.blob;
}
}
class TextReader extends BlobReader {
constructor(text) {
super(new Blob([text], { type: CONTENT_TYPE_TEXT_PLAIN }));
}
}
class TextWriter extends BlobWriter {
constructor(encoding) {
super(encoding);
Object.assign(this, {
encoding,
utf8: !encoding || encoding.toLowerCase() == "utf-8"
});
}
async getData() {
const {
encoding,
utf8
} = this;
const blob = await super.getData();
if (blob.text && utf8) {
return blob.text();
} else {
const reader = new FileReader();
return new Promise((resolve, reject) => {
Object.assign(reader, {
onload: ({ target }) => resolve(target.result),
onerror: () => reject(reader.error)
});
reader.readAsText(blob, encoding);
});
}
}
}
class FetchReader extends Reader {
constructor(url, options) {
super();
createHtpReader(this, url, options);
}
async init() {
await initHttpReader(this, sendFetchRequest, getFetchRequestData);
super.init();
}
readUint8Array(index, length) {
return readUint8ArrayHttpReader(this, index, length, sendFetchRequest, getFetchRequestData);
}
}
class XHRReader extends Reader {
constructor(url, options) {
super();
createHtpReader(this, url, options);
}
async init() {
await initHttpReader(this, sendXMLHttpRequest, getXMLHttpRequestData);
super.init();
}
readUint8Array(index, length) {
return readUint8ArrayHttpReader(this, index, length, sendXMLHttpRequest, getXMLHttpRequestData);
}
}
function createHtpReader(httpReader, url, options) {
const {
preventHeadRequest,
useRangeHeader,
forceRangeRequests
} = options;
options = Object.assign({}, options);
delete options.preventHeadRequest;
delete options.useRangeHeader;
delete options.forceRangeRequests;
delete options.useXHR;
Object.assign(httpReader, {
url,
options,
preventHeadRequest,
useRangeHeader,
forceRangeRequests
});
}
async function initHttpReader(httpReader, sendRequest, getRequestData) {
const {
url,
useRangeHeader,
forceRangeRequests
} = httpReader;
if (isHttpFamily(url) && (useRangeHeader || forceRangeRequests)) {
const { headers } = await sendRequest(HTTP_METHOD_GET, httpReader, getRangeHeaders(httpReader));
if (!forceRangeRequests && headers.get(HTTP_HEADER_ACCEPT_RANGES) != HTTP_RANGE_UNIT) {
throw new Error(ERR_HTTP_RANGE);
} else {
let contentSize;
const contentRangeHeader = headers.get(HTTP_HEADER_CONTENT_RANGE);
if (contentRangeHeader) {
const splitHeader = contentRangeHeader.trim().split(/\s*\/\s*/);
if (splitHeader.length) {
const headerValue = splitHeader[1];
if (headerValue && headerValue != "*") {
contentSize = Number(headerValue);
}
}
}
if (contentSize === UNDEFINED_VALUE) {
await getContentLength(httpReader, sendRequest, getRequestData);
} else {
httpReader.size = contentSize;
}
}
} else {
await getContentLength(httpReader, sendRequest, getRequestData);
}
}
async function readUint8ArrayHttpReader(httpReader, index, length, sendRequest, getRequestData) {
const {
useRangeHeader,
forceRangeRequests,
options
} = httpReader;
if (useRangeHeader || forceRangeRequests) {
const response = await sendRequest(HTTP_METHOD_GET, httpReader, getRangeHeaders(httpReader, index, length));
if (response.status != 206) {
throw new Error(ERR_HTTP_RANGE);
}
return new Uint8Array(await response.arrayBuffer());
} else {
const { data } = httpReader;
if (!data) {
await getRequestData(httpReader, options);
}
return new Uint8Array(httpReader.data.subarray(index, index + length));
}
}
function getRangeHeaders(httpReader, index = 0, length = 1) {
return Object.assign({}, getHeaders(httpReader), { [HTTP_HEADER_RANGE]: HTTP_RANGE_UNIT + "=" + index + "-" + (index + length - 1) });
}
function getHeaders({ options }) {
const { headers } = options;
if (headers) {
if (Symbol.iterator in headers) {
return Object.fromEntries(headers);
} else {
return headers;
}
}
}
async function getFetchRequestData(httpReader) {
await getRequestData(httpReader, sendFetchRequest);
}
async function getXMLHttpRequestData(httpReader) {
await getRequestData(httpReader, sendXMLHttpRequest);
}
async function getRequestData(httpReader, sendRequest) {
const response = await sendRequest(HTTP_METHOD_GET, httpReader, getHeaders(httpReader));
httpReader.data = new Uint8Array(await response.arrayBuffer());
if (!httpReader.size) {
httpReader.size = httpReader.data.length;
}
}
async function getContentLength(httpReader, sendRequest, getRequestData) {
if (httpReader.preventHeadRequest) {
await getRequestData(httpReader, httpReader.options);
} else {
const response = await sendRequest(HTTP_METHOD_HEAD, httpReader, getHeaders(httpReader));
const contentLength = response.headers.get(HTTP_HEADER_CONTENT_LENGTH);
if (contentLength) {
httpReader.size = Number(contentLength);
} else {
await getRequestData(httpReader, httpReader.options);
}
}
}
async function sendFetchRequest(method, { options, url }, headers) {
const response = await fetch(url, Object.assign({}, options, { method, headers }));
if (response.status < 400) {
return response;
} else {
throw response.status == 416 ? new Error(ERR_HTTP_RANGE) : new Error(ERR_HTTP_STATUS + (response.statusText || response.status));
}
}
function sendXMLHttpRequest(method, { url }, headers) {
return new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
request.addEventListener("load", () => {
if (request.status < 400) {
const headers = [];
request.getAllResponseHeaders().trim().split(/[\r\n]+/).forEach(header => {
const splitHeader = header.trim().split(/\s*:\s*/);
splitHeader[0] = splitHeader[0].trim().replace(/^[a-z]|-[a-z]/g, value => value.toUpperCase());
headers.push(splitHeader);
});
resolve({
status: request.status,
arrayBuffer: () => request.response,
headers: new Map(headers)
});
} else {
reject(request.status == 416 ? new Error(ERR_HTTP_RANGE) : new Error(ERR_HTTP_STATUS + (request.statusText || request.status)));
}
}, false);
request.addEventListener("error", event => reject(event.detail.error), false);
request.open(method, url);
if (headers) {
for (const entry of Object.entries(headers)) {
request.setRequestHeader(entry[0], entry[1]);
}
}
request.responseType = "arraybuffer";
request.send();
});
}
class HttpReader extends Reader {
constructor(url, options = {}) {
super();
Object.assign(this, {
url,
reader: options.useXHR ? new XHRReader(url, options) : new FetchReader(url, options)
});
}
set size(value) {
// ignored
}
get size() {
return this.reader.size;
}
async init() {
await this.reader.init();
super.init();
}
readUint8Array(index, length) {
return this.reader.readUint8Array(index, length);
}
}
class HttpRangeReader extends HttpReader {
constructor(url, options = {}) {
options.useRangeHeader = true;
super(url, options);
}
}
class Uint8ArrayReader extends Reader {
constructor(array) {
super();
Object.assign(this, {
array,
size: array.length
});
}
readUint8Array(index, length) {
return this.array.slice(index, index + length);
}
}
class Uint8ArrayWriter extends Writer {
init(initSize = 0) {
Object.assign(this, {
offset: 0,
array: new Uint8Array(initSize)
});
super.init();
}
writeUint8Array(array) {
const writer = this;
if (writer.offset + array.length > writer.array.length) {
const previousArray = writer.array;
writer.array = new Uint8Array(previousArray.length + array.length);
writer.array.set(previousArray);
}
writer.array.set(array, writer.offset);
writer.offset += array.length;
}
getData() {
return this.array;
}
}
class SplitDataReader extends Reader {
constructor(readers) {
super();
this.readers = readers;
}
async init() {
const reader = this;
const { readers } = reader;
reader.lastDiskNumber = 0;
reader.lastDiskOffset = 0;
await Promise.all(readers.map(async (diskReader, indexDiskReader) => {
await diskReader.init();
if (indexDiskReader != readers.length - 1) {
reader.lastDiskOffset += diskReader.size;
}
reader.size += diskReader.size;
}));
super.init();
}
async readUint8Array(offset, length, diskNumber = 0) {
const reader = this;
const { readers } = this;
let result;
let currentDiskNumber = diskNumber;
if (currentDiskNumber == -1) {
currentDiskNumber = readers.length - 1;
}
let currentReaderOffset = offset;
while (currentReaderOffset >= readers[currentDiskNumber].size) {
currentReaderOffset -= readers[currentDiskNumber].size;
currentDiskNumber++;
}
const currentReader = readers[currentDiskNumber];
const currentReaderSize = currentReader.size;
if (currentReaderOffset + length <= currentReaderSize) {
result = await readUint8Array(currentReader, currentReaderOffset, length);
} else {
const chunkLength = currentReaderSize - currentReaderOffset;
result = new Uint8Array(length);
result.set(await readUint8Array(currentReader, currentReaderOffset, chunkLength));
result.set(await reader.readUint8Array(offset + chunkLength, length - chunkLength, diskNumber), chunkLength);
}
reader.lastDiskNumber = Math.max(currentDiskNumber, reader.lastDiskNumber);
return result;
}
}
class SplitDataWriter extends Stream {
constructor(writerGenerator, maxSize = 4294967295) {
super();
const zipWriter = this;
Object.assign(zipWriter, {
diskNumber: 0,
diskOffset: 0,
size: 0,
maxSize,
availableSize: maxSize
});
let diskSourceWriter, diskWritable, diskWriter;
const writable = new WritableStream({
async write(chunk) {
const { availableSize } = zipWriter;
if (!diskWriter) {
const { value, done } = await writerGenerator.next();
if (done && !value) {
throw new Error(ERR_ITERATOR_COMPLETED_TOO_SOON);
} else {
diskSourceWriter = value;
diskSourceWriter.size = 0;
if (diskSourceWriter.maxSize) {
zipWriter.maxSize = diskSourceWriter.maxSize;
}
zipWriter.availableSize = zipWriter.maxSize;
await initStream(diskSourceWriter);
diskWritable = value.writable;
diskWriter = diskWritable.getWriter();
}
await this.write(chunk);
} else if (chunk.length >= availableSize) {
await writeChunk(chunk.slice(0, availableSize));
await closeDisk();
zipWriter.diskOffset += diskSourceWriter.size;
zipWriter.diskNumber++;
diskWriter = null;
await this.write(chunk.slice(availableSize));
} else {
await writeChunk(chunk);
}
},
async close() {
await diskWriter.ready;
await closeDisk();
}
});
Object.defineProperty(zipWriter, PROPERTY_NAME_WRITABLE, {
get() {
return writable;
}
});
async function writeChunk(chunk) {
const chunkLength = chunk.length;
if (chunkLength) {
await diskWriter.ready;
await diskWriter.write(chunk);
diskSourceWriter.size += chunkLength;
zipWriter.size += chunkLength;
zipWriter.availableSize -= chunkLength;
}
}
async function closeDisk() {
diskWritable.size = diskSourceWriter.size;
await diskWriter.close();
}
}
}
function isHttpFamily(url) {
const { baseURL } = getConfiguration();
const { protocol } = new URL(url, baseURL);
return protocol == "http:" || protocol == "https:";
}
async function initStream(stream, initSize) {
if (stream.init && !stream.initialized) {
await stream.init(initSize);
}
}
function initReader(reader) {
if (Array.isArray(reader)) {
reader = new SplitDataReader(reader);
}
if (reader instanceof ReadableStream) {
reader = {
readable: reader
};
}
return reader;
}
function initWriter(writer) {
if (writer.writable === UNDEFINED_VALUE && typeof writer.next == FUNCTION_TYPE) {
writer = new SplitDataWriter(writer);
}
if (writer instanceof WritableStream) {
writer = {
writable: writer
};
}
const { writable } = writer;
if (writable.size === UNDEFINED_VALUE) {
writable.size = 0;
}
const splitZipFile = writer instanceof SplitDataWriter;
if (!splitZipFile) {
Object.assign(writer, {
diskNumber: 0,
diskOffset: 0,
availableSize: Infinity,
maxSize: Infinity
});
}
return writer;
}
function readUint8Array(reader, offset, size, diskNumber) {
return reader.readUint8Array(offset, size, diskNumber);
}
const SplitZipReader = SplitDataReader;
const SplitZipWriter = SplitDataWriter;
export {
initStream,
initReader,
initWriter,
readUint8Array,
Reader,
Writer,
TextReader,
TextWriter,
Data64URIReader,
Data64URIWriter,
BlobReader,
BlobWriter,
Uint8ArrayReader,
Uint8ArrayWriter,
HttpReader,
HttpRangeReader,
SplitZipReader,
SplitZipWriter,
SplitDataReader,
SplitDataWriter,
ERR_HTTP_RANGE,
ERR_ITERATOR_COMPLETED_TOO_SOON
};