@loaders.gl/polyfills 4.0.0-alpha.9 → 4.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/dist.min.js +10 -89
  2. package/dist/es5/index.js +0 -27
  3. package/dist/es5/index.js.map +1 -1
  4. package/dist/es5/node/fetch/fetch.node.js +2 -3
  5. package/dist/es5/node/fetch/fetch.node.js.map +1 -1
  6. package/dist/es5/node/file/install-file-polyfills.js +1 -4
  7. package/dist/es5/node/file/install-file-polyfills.js.map +1 -1
  8. package/dist/esm/index.js +0 -4
  9. package/dist/esm/index.js.map +1 -1
  10. package/dist/esm/node/fetch/fetch.node.js +2 -3
  11. package/dist/esm/node/fetch/fetch.node.js.map +1 -1
  12. package/dist/esm/node/file/install-file-polyfills.js +1 -4
  13. package/dist/esm/node/file/install-file-polyfills.js.map +1 -1
  14. package/dist/index.d.ts +0 -4
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/node/fetch/fetch.node.d.ts +1 -1
  17. package/dist/node/fetch/fetch.node.d.ts.map +1 -1
  18. package/package.json +2 -2
  19. package/src/index.ts +7 -7
  20. package/src/node/fetch/fetch.node.ts +6 -5
  21. package/src/node/file/install-file-polyfills.ts +2 -2
  22. package/dist/bundle.js +0 -5
  23. package/dist/es5/node/fetch/fetch-file.node.js +0 -83
  24. package/dist/es5/node/fetch/fetch-file.node.js.map +0 -1
  25. package/dist/esm/node/fetch/fetch-file.node.js +0 -50
  26. package/dist/esm/node/fetch/fetch-file.node.js.map +0 -1
  27. package/dist/index.js +0 -97
  28. package/dist/lib/encoding-indexes.js +0 -35
  29. package/dist/lib/encoding.js +0 -2779
  30. package/dist/libs/encoding-indexes-asian.js +0 -14
  31. package/dist/node/buffer/btoa.node.js +0 -14
  32. package/dist/node/buffer/to-array-buffer.node.js +0 -12
  33. package/dist/node/fetch/fetch-file.node.d.ts +0 -4
  34. package/dist/node/fetch/fetch-file.node.d.ts.map +0 -1
  35. package/dist/node/fetch/fetch-file.node.js +0 -51
  36. package/dist/node/fetch/fetch.node.js +0 -143
  37. package/dist/node/fetch/headers.node.js +0 -106
  38. package/dist/node/fetch/response.node.js +0 -76
  39. package/dist/node/fetch/utils/decode-data-uri.node.js +0 -65
  40. package/dist/node/fetch/utils/stream-utils.node.js +0 -73
  41. package/dist/node/file/blob-stream-controller.js +0 -63
  42. package/dist/node/file/blob-stream.js +0 -37
  43. package/dist/node/file/blob.js +0 -160
  44. package/dist/node/file/file-reader.js +0 -35
  45. package/dist/node/file/file.js +0 -37
  46. package/dist/node/file/install-file-polyfills.js +0 -27
  47. package/dist/node/file/readable-stream.js +0 -11
  48. package/dist/node/images/encode-image.node.js +0 -41
  49. package/dist/node/images/parse-image.node.js +0 -41
  50. package/dist/promise/all-settled.js +0 -24
  51. package/dist/utils/assert.js +0 -9
  52. package/dist/utils/globals.js +0 -36
  53. package/src/node/fetch/fetch-file.node.ts +0 -51
@@ -1,14 +0,0 @@
1
- "use strict";
2
- // btoa, atob polyfills for Node.js
3
- // Note: The atob and btoa functions (not just the polyfills!) are not unicode safe
4
- // But still useful for unit testing
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.btoa = exports.atob = void 0;
7
- function atob(string) {
8
- return Buffer.from(string).toString('base64');
9
- }
10
- exports.atob = atob;
11
- function btoa(base64) {
12
- return Buffer.from(base64, 'base64').toString('ascii');
13
- }
14
- exports.btoa = btoa;
@@ -1,12 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.bufferToArrayBuffer = void 0;
4
- function bufferToArrayBuffer(buffer) {
5
- // TODO - per docs we should just be able to call buffer.buffer, but there are issues
6
- if (Buffer.isBuffer(buffer)) {
7
- const typedArray = new Uint8Array(buffer);
8
- return typedArray.buffer;
9
- }
10
- return buffer;
11
- }
12
- exports.bufferToArrayBuffer = bufferToArrayBuffer;
@@ -1,4 +0,0 @@
1
- import { Response } from './response.node';
2
- export declare function isRequestURL(url: string): boolean;
3
- export declare function fetchFileNode(url: string, options: any): Promise<Response>;
4
- //# sourceMappingURL=fetch-file.node.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"fetch-file.node.d.ts","sourceRoot":"","sources":["../../../src/node/fetch/fetch-file.node.ts"],"names":[],"mappings":"AAGA,OAAO,EAAC,QAAQ,EAAC,MAAM,iBAAiB,CAAC;AAGzC,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAEjD;AAED,wBAAsB,aAAa,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,KAAA,GAAG,OAAO,CAAC,QAAQ,CAAC,CAsB3E"}
@@ -1,51 +0,0 @@
1
- "use strict";
2
- // loaders.gl, MIT license
3
- var __importDefault = (this && this.__importDefault) || function (mod) {
4
- return (mod && mod.__esModule) ? mod : { "default": mod };
5
- };
6
- Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.fetchFileNode = exports.isRequestURL = void 0;
8
- const fs_1 = __importDefault(require("fs")); // `fs` will be empty object in browsers (see package.json "browser" field).
9
- const response_node_1 = require("./response.node");
10
- const headers_node_1 = require("./headers.node");
11
- function isRequestURL(url) {
12
- return url.startsWith('http:') || url.startsWith('https:');
13
- }
14
- exports.isRequestURL = isRequestURL;
15
- async function fetchFileNode(url, options) {
16
- const noqueryUrl = url.split('?')[0];
17
- try {
18
- // Now open the stream
19
- const body = await new Promise((resolve, reject) => {
20
- // @ts-ignore
21
- const stream = fs_1.default.createReadStream(noqueryUrl, { encoding: null });
22
- stream.once('readable', () => resolve(stream));
23
- stream.on('error', (error) => reject(error));
24
- });
25
- const status = 200;
26
- const statusText = 'OK';
27
- const headers = getHeadersForFile(noqueryUrl);
28
- return new response_node_1.Response(body, { headers, status, statusText, url });
29
- }
30
- catch (error) {
31
- const status = 400;
32
- const statusText = error.message;
33
- const headers = {};
34
- return new response_node_1.Response(error.message, { headers, status, statusText, url });
35
- }
36
- }
37
- exports.fetchFileNode = fetchFileNode;
38
- function getHeadersForFile(noqueryUrl) {
39
- const headers = {};
40
- // Fix up content length if we can for best progress experience
41
- if (!headers['content-length']) {
42
- const stats = fs_1.default.statSync(noqueryUrl);
43
- headers['content-length'] = stats.size;
44
- }
45
- // Automatically decompress gzipped files with .gz extension
46
- if (noqueryUrl.endsWith('.gz')) {
47
- noqueryUrl = noqueryUrl.slice(0, -3);
48
- headers['content-encoding'] = 'gzip';
49
- }
50
- return new headers_node_1.Headers(headers);
51
- }
@@ -1,143 +0,0 @@
1
- "use strict";
2
- // loaders.gl, MIT license
3
- var __importDefault = (this && this.__importDefault) || function (mod) {
4
- return (mod && mod.__esModule) ? mod : { "default": mod };
5
- };
6
- Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.createHTTPRequestReadStream = exports.fetchNode = void 0;
8
- const http_1 = __importDefault(require("http"));
9
- const https_1 = __importDefault(require("https"));
10
- const response_node_1 = require("./response.node");
11
- const headers_node_1 = require("./headers.node");
12
- const decode_data_uri_node_1 = require("./utils/decode-data-uri.node");
13
- const fetch_file_node_1 = require("./fetch-file.node");
14
- const isDataURL = (url) => url.startsWith('data:');
15
- const isRequestURL = (url) => url.startsWith('http:') || url.startsWith('https:');
16
- /**
17
- * Emulation of Browser fetch for Node.js
18
- * @param url
19
- * @param options
20
- */
21
- // eslint-disable-next-line complexity
22
- async function fetchNode(url, options) {
23
- try {
24
- // Handle file streams in node
25
- if (!isRequestURL(url) && !isDataURL(url)) {
26
- return await (0, fetch_file_node_1.fetchFileNode)(url, options);
27
- }
28
- // Handle data urls in node, to match `fetch``
29
- // Note - this loses the MIME type, data URIs are handled directly in fetch
30
- if (isDataURL(url)) {
31
- const { arrayBuffer, mimeType } = (0, decode_data_uri_node_1.decodeDataUri)(url);
32
- const response = new response_node_1.Response(arrayBuffer, {
33
- headers: { 'content-type': mimeType },
34
- url
35
- });
36
- return response;
37
- }
38
- // Automatically decompress gzipped files with .gz extension
39
- const syntheticResponseHeaders = {};
40
- const originalUrl = url;
41
- if (url.endsWith('.gz')) {
42
- url = url.slice(0, -3);
43
- syntheticResponseHeaders['content-encoding'] = 'gzip';
44
- }
45
- // Need to create the stream in advance since Response constructor needs to be sync
46
- const body = await createHTTPRequestReadStream(originalUrl, options);
47
- const headers = getHeaders(url, body, syntheticResponseHeaders);
48
- const { status, statusText } = getStatus(body);
49
- const followRedirect = !options || options.followRedirect || options.followRedirect === undefined;
50
- if (status >= 300 && status < 400 && headers.has('location') && followRedirect) {
51
- const redirectUrl = generateRedirectUrl(url, headers.get('location'));
52
- // Redirect
53
- return await fetchNode(redirectUrl, options);
54
- }
55
- return new response_node_1.Response(body, { headers, status, statusText, url });
56
- }
57
- catch (error) {
58
- // TODO - what error code to use here?
59
- return new response_node_1.Response(null, { status: 400, statusText: String(error), url });
60
- }
61
- }
62
- exports.fetchNode = fetchNode;
63
- /** Returns a promise that resolves to a readable stream */
64
- async function createHTTPRequestReadStream(url, options) {
65
- // HANDLE HTTP/HTTPS REQUESTS IN NODE
66
- // TODO: THIS IS BAD SINCE WE RETURN A PROMISE INSTEAD OF A STREAM
67
- return await new Promise((resolve, reject) => {
68
- const requestOptions = getRequestOptions(url, options);
69
- const req = url.startsWith('https:')
70
- ? https_1.default.request(requestOptions, (res) => resolve(res))
71
- : http_1.default.request(requestOptions, (res) => resolve(res));
72
- req.on('error', (error) => reject(error));
73
- req.end();
74
- });
75
- }
76
- exports.createHTTPRequestReadStream = createHTTPRequestReadStream;
77
- /**
78
- * Generate redirect url from location without origin and protocol.
79
- * @param originalUrl
80
- * @param redirectUrl
81
- */
82
- function generateRedirectUrl(originalUrl, location) {
83
- if (location.startsWith('http')) {
84
- return location;
85
- }
86
- // If url doesn't have origin and protocol just extend current url origin with location.
87
- const url = new URL(originalUrl);
88
- url.pathname = location;
89
- return url.href;
90
- }
91
- // HELPER FUNCTIONS
92
- function getRequestOptions(url, options) {
93
- // Ensure header keys are lower case so that we can merge without duplicates
94
- const originalHeaders = options?.headers || {};
95
- const headers = {};
96
- for (const key of Object.keys(originalHeaders)) {
97
- headers[key.toLowerCase()] = originalHeaders[key];
98
- }
99
- // Add default accept-encoding to headers
100
- headers['accept-encoding'] = headers['accept-encoding'] || 'gzip,br,deflate';
101
- const urlObject = new URL(url);
102
- return {
103
- hostname: urlObject.hostname,
104
- path: urlObject.pathname,
105
- method: 'GET',
106
- // Add options and user provided 'options.fetch' overrides if available
107
- ...options,
108
- ...options?.fetch,
109
- // Override with updated headers with accepted encodings:
110
- headers,
111
- port: urlObject.port
112
- };
113
- }
114
- function getStatus(httpResponse) {
115
- if (httpResponse.statusCode) {
116
- return { status: httpResponse.statusCode, statusText: httpResponse.statusMessage || 'NA' };
117
- }
118
- return { status: 200, statusText: 'OK' };
119
- }
120
- function getHeaders(url, httpResponse, additionalHeaders = {}) {
121
- const headers = {};
122
- if (httpResponse && httpResponse.headers) {
123
- const httpHeaders = httpResponse.headers;
124
- for (const key in httpHeaders) {
125
- const header = httpHeaders[key];
126
- headers[key.toLowerCase()] = String(header);
127
- }
128
- }
129
- // Fix up content length if we can for best progress experience
130
- if (!headers['content-length']) {
131
- const contentLength = getContentLength(url);
132
- if (Number.isFinite(contentLength)) {
133
- headers['content-length'] = contentLength;
134
- }
135
- }
136
- Object.assign(headers, additionalHeaders);
137
- return new headers_node_1.Headers(headers);
138
- }
139
- /** Needs to be read from actual headers */
140
- function getContentLength(url) {
141
- // TODO - remove media type etc
142
- return isDataURL(url) ? url.length - 'data:'.length : null;
143
- }
@@ -1,106 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Headers = void 0;
4
- /**
5
- * Polyfill for Browser Headers
6
- * Based on https://github.com/github/fetch under MIT license
7
- */
8
- class Headers {
9
- constructor(headers) {
10
- this.map = {};
11
- if (headers instanceof Headers) {
12
- headers.forEach((value, name) => this.append(name, value));
13
- }
14
- else if (Array.isArray(headers)) {
15
- headers.forEach((header) => this.append(header[0], header[1]));
16
- }
17
- else if (headers) {
18
- Object.getOwnPropertyNames(headers).forEach((name) => this.append(name, headers[name]));
19
- }
20
- }
21
- append(name, value) {
22
- name = normalizeName(name);
23
- value = normalizeValue(value);
24
- const oldValue = this.map[name];
25
- this.map[name] = oldValue ? `${oldValue}, ${value}` : value;
26
- }
27
- delete(name) {
28
- delete this.map[normalizeName(name)];
29
- }
30
- get(name) {
31
- name = normalizeName(name);
32
- return this.has(name) ? this.map[name] : null;
33
- }
34
- has(name) {
35
- return this.map.hasOwnProperty(normalizeName(name));
36
- }
37
- set(name, value) {
38
- this.map[normalizeName(name)] = normalizeValue(value);
39
- }
40
- forEach(visitor, thisArg = null) {
41
- for (const name in this.map) {
42
- if (this.map.hasOwnProperty(name)) {
43
- if (thisArg) {
44
- visitor.call(thisArg, this.map[name], name, this);
45
- }
46
- else {
47
- visitor(this.map[name], name, this);
48
- }
49
- }
50
- }
51
- }
52
- keys() {
53
- const items = [];
54
- this.forEach(function (value, name) {
55
- items.push(name);
56
- });
57
- return iteratorFor(items);
58
- }
59
- values() {
60
- const items = [];
61
- this.forEach(function (value) {
62
- items.push(value);
63
- });
64
- return iteratorFor(items);
65
- }
66
- entries() {
67
- const items = [];
68
- this.forEach(function (value, name) {
69
- items.push([name, value]);
70
- });
71
- return iteratorFor(items);
72
- }
73
- *[Symbol.iterator]() {
74
- // @ts-ignore must have a '[Symbol.iterator]()' method that returns an iterator.
75
- yield* this.entries();
76
- }
77
- }
78
- exports.Headers = Headers;
79
- function normalizeName(name) {
80
- if (typeof name !== 'string') {
81
- name = String(name);
82
- }
83
- if (/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(name) || name === '') {
84
- throw new TypeError('Invalid character in header field name');
85
- }
86
- return name.toLowerCase();
87
- }
88
- function normalizeValue(value) {
89
- if (typeof value !== 'string') {
90
- value = String(value);
91
- }
92
- return value;
93
- }
94
- // Build a destructive iterator for the value list
95
- function iteratorFor(items) {
96
- const iterator = {
97
- next() {
98
- const value = items.shift();
99
- return { done: value === undefined, value };
100
- }
101
- };
102
- iterator[Symbol.iterator] = function () {
103
- return iterator;
104
- };
105
- return iterator;
106
- }
@@ -1,76 +0,0 @@
1
- "use strict";
2
- // loaders.gl, MIT license
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.Response = void 0;
5
- const assert_1 = require("../../utils/assert");
6
- const stream_utils_node_1 = require("./utils/stream-utils.node");
7
- const headers_node_1 = require("./headers.node");
8
- const isBoolean = (x) => typeof x === 'boolean';
9
- const isFunction = (x) => typeof x === 'function';
10
- const isObject = (x) => x !== null && typeof x === 'object';
11
- const isReadableNodeStream = (x) => isObject(x) && isFunction(x.read) && isFunction(x.pipe) && isBoolean(x.readable);
12
- /**
13
- * Polyfill for Browser Response
14
- *
15
- * Under Node.js we return a mock "fetch response object"
16
- * so that apps can use the same API as in the browser.
17
- *
18
- * Note: This is intended to be a "lightweight" implementation and will have limitations.
19
- *
20
- * See https://developer.mozilla.org/en-US/docs/Web/API/Response
21
- */
22
- const stream_1 = require("stream");
23
- class Response {
24
- // TODO - handle ArrayBuffer, ArrayBufferView, Buffer
25
- constructor(body, options) {
26
- this.bodyUsed = false;
27
- const { headers, status = 200, statusText = 'OK', url } = options || {};
28
- this.url = url;
29
- this.ok = status === 200;
30
- this.status = status; // TODO - handle errors and set status
31
- this.statusText = statusText;
32
- this.headers = new headers_node_1.Headers(options?.headers || {});
33
- // Check for content-encoding and create a decompression stream
34
- if (isReadableNodeStream(body)) {
35
- this._body = (0, stream_utils_node_1.decompressReadStream)(body, headers);
36
- }
37
- else if (typeof body === 'string') {
38
- this._body = stream_1.Readable.from([new TextEncoder().encode(body)]);
39
- }
40
- else {
41
- this._body = stream_1.Readable.from([body || new ArrayBuffer(0)]);
42
- }
43
- }
44
- // Subset of Properties
45
- // Returns a readable stream to the "body" of the response (or file)
46
- get body() {
47
- (0, assert_1.assert)(!this.bodyUsed);
48
- (0, assert_1.assert)(isReadableNodeStream(this._body)); // Not implemented: conversion of ArrayBuffer etc to stream
49
- this.bodyUsed = true;
50
- return this._body;
51
- }
52
- // Subset of Methods
53
- async arrayBuffer() {
54
- if (!isReadableNodeStream(this._body)) {
55
- return this._body || new ArrayBuffer(0);
56
- }
57
- const data = await (0, stream_utils_node_1.concatenateReadStream)(this._body);
58
- return data;
59
- }
60
- async text() {
61
- const arrayBuffer = await this.arrayBuffer();
62
- const textDecoder = new TextDecoder();
63
- return textDecoder.decode(arrayBuffer);
64
- }
65
- async json() {
66
- const text = await this.text();
67
- return JSON.parse(text);
68
- }
69
- async blob() {
70
- if (typeof Blob === 'undefined') {
71
- throw new Error('Blob polyfill not installed');
72
- }
73
- return new Blob([await this.arrayBuffer()]);
74
- }
75
- }
76
- exports.Response = Response;
@@ -1,65 +0,0 @@
1
- "use strict";
2
- // Based on binary-gltf-utils under MIT license: Copyright (c) 2016-17 Karl Cheng
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.toArrayBuffer = exports.decodeDataUri = void 0;
5
- const isArrayBuffer = (x) => x && x instanceof ArrayBuffer;
6
- const isBuffer = (x) => x && x instanceof Buffer;
7
- /**
8
- * Parses a data URI into a buffer, as well as retrieving its declared MIME type.
9
- *
10
- * @param {string} uri - a data URI (assumed to be valid)
11
- * @returns {Object} { buffer, mimeType }
12
- */
13
- function decodeDataUri(uri) {
14
- const dataIndex = uri.indexOf(',');
15
- let buffer;
16
- let mimeType;
17
- if (uri.slice(dataIndex - 7, dataIndex) === ';base64') {
18
- buffer = Buffer.from(uri.slice(dataIndex + 1), 'base64');
19
- mimeType = uri.slice(5, dataIndex - 7).trim();
20
- }
21
- else {
22
- buffer = Buffer.from(decodeURIComponent(uri.slice(dataIndex + 1)));
23
- mimeType = uri.slice(5, dataIndex).trim();
24
- }
25
- if (!mimeType) {
26
- mimeType = 'text/plain;charset=US-ASCII';
27
- }
28
- else if (mimeType.startsWith(';')) {
29
- mimeType = `text/plain${mimeType}`;
30
- }
31
- return { arrayBuffer: toArrayBuffer(buffer), mimeType };
32
- }
33
- exports.decodeDataUri = decodeDataUri;
34
- /**
35
- * @param data
36
- * @todo Duplicate of core
37
- */
38
- function toArrayBuffer(data) {
39
- if (isArrayBuffer(data)) {
40
- return data;
41
- }
42
- // TODO - per docs we should just be able to call buffer.buffer, but there are issues
43
- if (isBuffer(data)) {
44
- // @ts-expect-error
45
- const typedArray = new Uint8Array(data);
46
- return typedArray.buffer;
47
- }
48
- // Careful - Node Buffers will look like ArrayBuffers (keep after isBuffer)
49
- if (ArrayBuffer.isView(data)) {
50
- return data.buffer;
51
- }
52
- if (typeof data === 'string') {
53
- const text = data;
54
- const uint8Array = new TextEncoder().encode(text);
55
- return uint8Array.buffer;
56
- }
57
- // HACK to support Blob polyfill
58
- // @ts-expect-error
59
- if (data && typeof data === 'object' && data._toArrayBuffer) {
60
- // @ts-expect-error
61
- return data._toArrayBuffer();
62
- }
63
- throw new Error(`toArrayBuffer(${JSON.stringify(data, null, 2).slice(10)})`);
64
- }
65
- exports.toArrayBuffer = toArrayBuffer;
@@ -1,73 +0,0 @@
1
- "use strict";
2
- // loaders.gl, MIT license
3
- var __importDefault = (this && this.__importDefault) || function (mod) {
4
- return (mod && mod.__esModule) ? mod : { "default": mod };
5
- };
6
- Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.concatenateArrayBuffers = exports.concatenateReadStream = exports.decompressReadStream = void 0;
8
- const zlib_1 = __importDefault(require("zlib"));
9
- const decode_data_uri_node_1 = require("./decode-data-uri.node");
10
- /**
11
- *
12
- */
13
- function decompressReadStream(readStream, headers) {
14
- switch (headers.get('content-encoding')) {
15
- case 'br':
16
- return readStream.pipe(zlib_1.default.createBrotliDecompress());
17
- case 'gzip':
18
- return readStream.pipe(zlib_1.default.createGunzip());
19
- case 'deflate':
20
- return readStream.pipe(zlib_1.default.createDeflate());
21
- default:
22
- // No compression or an unknown one, just return it as is
23
- return readStream;
24
- }
25
- }
26
- exports.decompressReadStream = decompressReadStream;
27
- /**
28
- *
29
- * @param readStream
30
- * @returns
31
- */
32
- async function concatenateReadStream(readStream) {
33
- const arrayBufferChunks = [];
34
- return await new Promise((resolve, reject) => {
35
- readStream.on('error', (error) => reject(error));
36
- // Once the readable callback has been added, stream switches to "flowing mode"
37
- // In Node 10 (but not 12 and 14) this causes `data` and `end` to never be called unless we read data here
38
- readStream.on('readable', () => readStream.read());
39
- readStream.on('data', (chunk) => {
40
- if (typeof chunk === 'string') {
41
- reject(new Error('Read stream not binary'));
42
- }
43
- arrayBufferChunks.push((0, decode_data_uri_node_1.toArrayBuffer)(chunk));
44
- });
45
- readStream.on('end', () => {
46
- const arrayBuffer = concatenateArrayBuffers(arrayBufferChunks);
47
- resolve(arrayBuffer);
48
- });
49
- });
50
- }
51
- exports.concatenateReadStream = concatenateReadStream;
52
- /**
53
- * Concatenate a sequence of ArrayBuffers
54
- * @return A concatenated ArrayBuffer
55
- * @note duplicates loader-utils since polyfills should be independent
56
- */
57
- function concatenateArrayBuffers(sources) {
58
- // Make sure all inputs are wrapped in typed arrays
59
- const sourceArrays = sources.map((source2) => source2 instanceof ArrayBuffer ? new Uint8Array(source2) : source2);
60
- // Get length of all inputs
61
- const byteLength = sourceArrays.reduce((length, typedArray) => length + typedArray.byteLength, 0);
62
- // Allocate array with space for all inputs
63
- const result = new Uint8Array(byteLength);
64
- // Copy the subarrays
65
- let offset = 0;
66
- for (const sourceArray of sourceArrays) {
67
- result.set(sourceArray, offset);
68
- offset += sourceArray.byteLength;
69
- }
70
- // We work with ArrayBuffers, discard the typed array wrapper
71
- return result.buffer;
72
- }
73
- exports.concatenateArrayBuffers = concatenateArrayBuffers;
@@ -1,63 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.BlobStreamController = void 0;
4
- /**
5
- * Forked from @gozala's web-blob under MIT license
6
- * @see https://github.com/Gozala/web-blob
7
- */
8
- class BlobStreamController {
9
- /**
10
- * @param chunks
11
- */
12
- constructor(chunks) {
13
- this.isWorking = false;
14
- this.isCancelled = false;
15
- this.chunks = chunks;
16
- }
17
- /**
18
- * @param controller
19
- */
20
- start(controller) {
21
- this.work(controller); // eslint-disable-line @typescript-eslint/no-floating-promises
22
- }
23
- /**
24
- *
25
- * @param controller
26
- */
27
- async work(controller) {
28
- const { chunks } = this;
29
- this.isWorking = true;
30
- while (!this.isCancelled && (controller.desiredSize || 0) > 0) {
31
- let next;
32
- try {
33
- next = chunks.next();
34
- }
35
- catch (error) {
36
- controller.error(error);
37
- break;
38
- }
39
- if (next) {
40
- if (!next.done && !this.isCancelled) {
41
- controller.enqueue(next.value);
42
- }
43
- else {
44
- controller.close();
45
- }
46
- }
47
- }
48
- this.isWorking = false;
49
- }
50
- /**
51
- *
52
- * @param {ReadableStreamDefaultController} controller
53
- */
54
- pull(controller) {
55
- if (!this.isWorking) {
56
- this.work(controller); // eslint-disable-line @typescript-eslint/no-floating-promises
57
- }
58
- }
59
- cancel() {
60
- this.isCancelled = true;
61
- }
62
- }
63
- exports.BlobStreamController = BlobStreamController;
@@ -1,37 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.BlobStream = void 0;
4
- /**
5
- * Forked from @gozala's web-blob under MIT license
6
- * @see https://github.com/Gozala/web-blob
7
- */
8
- const readable_stream_1 = require("./readable-stream");
9
- const blob_stream_controller_1 = require("./blob-stream-controller");
10
- /**
11
- * Blob stream is a `ReadableStream` extension optimized to have minimal
12
- * overhead when consumed as `AsyncIterable<Uint8Array>`.
13
- * extends {ReadableStream<Uint8Array>}
14
- * implements {AsyncIterable<Uint8Array>}
15
- */
16
- // @ts-ignore
17
- class BlobStream extends readable_stream_1.ReadableStreamPolyfill {
18
- /**
19
- * @param chunks
20
- */
21
- constructor(chunks) {
22
- // @ts-ignore
23
- super(new blob_stream_controller_1.BlobStreamController(chunks.values()), { type: 'bytes' });
24
- /** @private */
25
- this._chunks = chunks;
26
- }
27
- /**
28
- * @property [_options.preventCancel]
29
- */
30
- // @ts-ignore
31
- async *[Symbol.asyncIterator](_options) {
32
- const reader = this.getReader();
33
- yield* this._chunks;
34
- reader.releaseLock();
35
- }
36
- }
37
- exports.BlobStream = BlobStream;