@protontech/openpgp 4.10.5 → 5.3.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 (173) hide show
  1. package/README.md +311 -239
  2. package/dist/lightweight/bn.interface.min.mjs +3 -0
  3. package/dist/lightweight/bn.interface.min.mjs.map +1 -0
  4. package/dist/lightweight/bn.interface.mjs +340 -0
  5. package/dist/lightweight/bn.min.mjs +3 -0
  6. package/dist/lightweight/bn.min.mjs.map +1 -0
  7. package/dist/lightweight/bn.mjs +3434 -0
  8. package/dist/lightweight/elliptic.min.mjs +3 -0
  9. package/dist/lightweight/elliptic.min.mjs.map +1 -0
  10. package/dist/lightweight/elliptic.mjs +4313 -0
  11. package/dist/lightweight/openpgp.min.mjs +3 -0
  12. package/dist/lightweight/openpgp.min.mjs.map +1 -0
  13. package/dist/lightweight/openpgp.mjs +31375 -0
  14. package/dist/lightweight/ponyfill.es6.min.mjs +3 -0
  15. package/dist/lightweight/ponyfill.es6.min.mjs.map +1 -0
  16. package/dist/lightweight/ponyfill.es6.mjs +3831 -0
  17. package/dist/lightweight/web-streams-adapter.min.mjs +17 -0
  18. package/dist/lightweight/web-streams-adapter.min.mjs.map +1 -0
  19. package/dist/lightweight/web-streams-adapter.mjs +561 -0
  20. package/dist/node/openpgp.js +43943 -0
  21. package/dist/node/openpgp.min.js +17 -0
  22. package/dist/node/openpgp.min.js.map +1 -0
  23. package/dist/node/openpgp.min.mjs +17 -0
  24. package/dist/node/openpgp.min.mjs.map +1 -0
  25. package/dist/node/openpgp.mjs +43880 -0
  26. package/dist/openpgp.js +41080 -41565
  27. package/dist/openpgp.min.js +17 -2
  28. package/dist/openpgp.min.js.map +1 -0
  29. package/dist/openpgp.min.mjs +17 -0
  30. package/dist/openpgp.min.mjs.map +1 -0
  31. package/dist/openpgp.mjs +43868 -0
  32. package/lightweight/package.json +5 -0
  33. package/openpgp.d.ts +889 -0
  34. package/package.json +63 -57
  35. package/dist/compat/openpgp.js +0 -61067
  36. package/dist/compat/openpgp.min.js +0 -2
  37. package/dist/compat/openpgp.worker.js +0 -173
  38. package/dist/compat/openpgp.worker.min.js +0 -2
  39. package/dist/lightweight/elliptic.min.js +0 -5
  40. package/dist/lightweight/openpgp.js +0 -40024
  41. package/dist/lightweight/openpgp.min.js +0 -2
  42. package/dist/lightweight/openpgp.worker.js +0 -173
  43. package/dist/lightweight/openpgp.worker.min.js +0 -2
  44. package/dist/openpgp.worker.js +0 -173
  45. package/dist/openpgp.worker.min.js +0 -2
  46. package/src/cleartext.js +0 -220
  47. package/src/config/config.js +0 -224
  48. package/src/config/index.js +0 -7
  49. package/src/config/localStorage.js +0 -35
  50. package/src/crypto/aes_kw.js +0 -153
  51. package/src/crypto/cfb.js +0 -169
  52. package/src/crypto/cipher/aes.js +0 -27
  53. package/src/crypto/cipher/blowfish.js +0 -398
  54. package/src/crypto/cipher/cast5.js +0 -610
  55. package/src/crypto/cipher/des.js +0 -476
  56. package/src/crypto/cipher/index.js +0 -91
  57. package/src/crypto/cipher/twofish.js +0 -346
  58. package/src/crypto/cmac.js +0 -98
  59. package/src/crypto/crypto.js +0 -394
  60. package/src/crypto/eax.js +0 -172
  61. package/src/crypto/gcm.js +0 -141
  62. package/src/crypto/hash/index.js +0 -163
  63. package/src/crypto/hash/md5.js +0 -205
  64. package/src/crypto/index.js +0 -57
  65. package/src/crypto/ocb.js +0 -274
  66. package/src/crypto/pkcs1.js +0 -170
  67. package/src/crypto/pkcs5.js +0 -55
  68. package/src/crypto/public_key/dsa.js +0 -188
  69. package/src/crypto/public_key/elgamal.js +0 -137
  70. package/src/crypto/public_key/elliptic/curves.js +0 -385
  71. package/src/crypto/public_key/elliptic/ecdh.js +0 -414
  72. package/src/crypto/public_key/elliptic/ecdsa.js +0 -348
  73. package/src/crypto/public_key/elliptic/eddsa.js +0 -119
  74. package/src/crypto/public_key/elliptic/index.js +0 -34
  75. package/src/crypto/public_key/elliptic/indutnyKey.js +0 -85
  76. package/src/crypto/public_key/index.js +0 -28
  77. package/src/crypto/public_key/prime.js +0 -275
  78. package/src/crypto/public_key/rsa.js +0 -597
  79. package/src/crypto/random.js +0 -145
  80. package/src/crypto/signature.js +0 -137
  81. package/src/encoding/armor.js +0 -433
  82. package/src/encoding/base64.js +0 -96
  83. package/src/enums.js +0 -493
  84. package/src/hkp.js +0 -89
  85. package/src/index.js +0 -161
  86. package/src/key/factory.js +0 -326
  87. package/src/key/helper.js +0 -363
  88. package/src/key/index.js +0 -32
  89. package/src/key/key.js +0 -890
  90. package/src/key/subkey.js +0 -187
  91. package/src/key/user.js +0 -230
  92. package/src/keyring/index.js +0 -12
  93. package/src/keyring/keyring.js +0 -229
  94. package/src/keyring/localstore.js +0 -119
  95. package/src/lightweight_helper.js +0 -26
  96. package/src/message.js +0 -825
  97. package/src/openpgp.js +0 -717
  98. package/src/packet/all_packets.js +0 -116
  99. package/src/packet/clone.js +0 -189
  100. package/src/packet/compressed.js +0 -194
  101. package/src/packet/index.js +0 -20
  102. package/src/packet/literal.js +0 -168
  103. package/src/packet/marker.js +0 -62
  104. package/src/packet/one_pass_signature.js +0 -156
  105. package/src/packet/packet.js +0 -300
  106. package/src/packet/packetlist.js +0 -232
  107. package/src/packet/public_key.js +0 -280
  108. package/src/packet/public_key_encrypted_session_key.js +0 -156
  109. package/src/packet/public_subkey.js +0 -44
  110. package/src/packet/secret_key.js +0 -448
  111. package/src/packet/secret_subkey.js +0 -41
  112. package/src/packet/signature.js +0 -782
  113. package/src/packet/sym_encrypted_aead_protected.js +0 -189
  114. package/src/packet/sym_encrypted_integrity_protected.js +0 -139
  115. package/src/packet/sym_encrypted_session_key.js +0 -204
  116. package/src/packet/symmetrically_encrypted.js +0 -118
  117. package/src/packet/trust.js +0 -35
  118. package/src/packet/user_attribute.js +0 -94
  119. package/src/packet/userid.js +0 -87
  120. package/src/polyfills.js +0 -64
  121. package/src/signature.js +0 -73
  122. package/src/type/ecdh_symkey.js +0 -69
  123. package/src/type/kdf_params.js +0 -114
  124. package/src/type/keyid.js +0 -110
  125. package/src/type/mpi.js +0 -138
  126. package/src/type/oid.js +0 -110
  127. package/src/type/s2k.js +0 -203
  128. package/src/util.js +0 -836
  129. package/src/wkd.js +0 -88
  130. package/src/worker/async_proxy.js +0 -190
  131. package/src/worker/worker.js +0 -167
  132. package/test/crypto/aes_kw.js +0 -57
  133. package/test/crypto/cipher/aes.js +0 -86
  134. package/test/crypto/cipher/blowfish.js +0 -58
  135. package/test/crypto/cipher/cast5.js +0 -25
  136. package/test/crypto/cipher/des.js +0 -143
  137. package/test/crypto/cipher/index.js +0 -7
  138. package/test/crypto/cipher/twofish.js +0 -71
  139. package/test/crypto/crypto.js +0 -383
  140. package/test/crypto/eax.js +0 -150
  141. package/test/crypto/ecdh.js +0 -359
  142. package/test/crypto/elliptic.js +0 -251
  143. package/test/crypto/elliptic_data.js +0 -102
  144. package/test/crypto/hash/index.js +0 -5
  145. package/test/crypto/hash/md5.js +0 -16
  146. package/test/crypto/hash/ripemd.js +0 -14
  147. package/test/crypto/hash/sha.js +0 -20
  148. package/test/crypto/index.js +0 -14
  149. package/test/crypto/ocb.js +0 -183
  150. package/test/crypto/pkcs5.js +0 -39
  151. package/test/crypto/random.js +0 -79
  152. package/test/crypto/rsa.js +0 -180
  153. package/test/crypto/validate.js +0 -387
  154. package/test/general/armor.js +0 -408
  155. package/test/general/brainpool.js +0 -360
  156. package/test/general/decompression.js +0 -60
  157. package/test/general/ecc_nist.js +0 -115
  158. package/test/general/ecc_secp256k1.js +0 -242
  159. package/test/general/forwarding.js +0 -43
  160. package/test/general/hkp.js +0 -165
  161. package/test/general/index.js +0 -20
  162. package/test/general/key.js +0 -3402
  163. package/test/general/keyring.js +0 -336
  164. package/test/general/oid.js +0 -39
  165. package/test/general/openpgp.js +0 -2542
  166. package/test/general/packet.js +0 -937
  167. package/test/general/signature.js +0 -1665
  168. package/test/general/streaming.js +0 -944
  169. package/test/general/testInputs.js +0 -18
  170. package/test/general/util.js +0 -183
  171. package/test/general/wkd.js +0 -48
  172. package/test/general/x25519.js +0 -556
  173. package/test/unittests.js +0 -64
@@ -0,0 +1,3831 @@
1
+ /*! OpenPGP.js v5.3.1 - 2022-07-12 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */
2
+ const globalThis = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
3
+
4
+ /**
5
+ * web-streams-polyfill v3.0.3
6
+ */
7
+ /// <reference lib="es2015.symbol" />
8
+ const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?
9
+ Symbol :
10
+ description => `Symbol(${description})`;
11
+
12
+ /// <reference lib="dom" />
13
+ function noop() {
14
+ return undefined;
15
+ }
16
+ function getGlobals() {
17
+ if (typeof self !== 'undefined') {
18
+ return self;
19
+ }
20
+ else if (typeof window !== 'undefined') {
21
+ return window;
22
+ }
23
+ else if (typeof global !== 'undefined') {
24
+ return global;
25
+ }
26
+ return undefined;
27
+ }
28
+ const globals = getGlobals();
29
+
30
+ function typeIsObject(x) {
31
+ return (typeof x === 'object' && x !== null) || typeof x === 'function';
32
+ }
33
+ const rethrowAssertionErrorRejection = noop;
34
+
35
+ const originalPromise = Promise;
36
+ const originalPromiseThen = Promise.prototype.then;
37
+ const originalPromiseResolve = Promise.resolve.bind(originalPromise);
38
+ const originalPromiseReject = Promise.reject.bind(originalPromise);
39
+ function newPromise(executor) {
40
+ return new originalPromise(executor);
41
+ }
42
+ function promiseResolvedWith(value) {
43
+ return originalPromiseResolve(value);
44
+ }
45
+ function promiseRejectedWith(reason) {
46
+ return originalPromiseReject(reason);
47
+ }
48
+ function PerformPromiseThen(promise, onFulfilled, onRejected) {
49
+ // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an
50
+ // approximation.
51
+ return originalPromiseThen.call(promise, onFulfilled, onRejected);
52
+ }
53
+ function uponPromise(promise, onFulfilled, onRejected) {
54
+ PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection);
55
+ }
56
+ function uponFulfillment(promise, onFulfilled) {
57
+ uponPromise(promise, onFulfilled);
58
+ }
59
+ function uponRejection(promise, onRejected) {
60
+ uponPromise(promise, undefined, onRejected);
61
+ }
62
+ function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) {
63
+ return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);
64
+ }
65
+ function setPromiseIsHandledToTrue(promise) {
66
+ PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);
67
+ }
68
+ const queueMicrotask = (() => {
69
+ const globalQueueMicrotask = globals && globals.queueMicrotask;
70
+ if (typeof globalQueueMicrotask === 'function') {
71
+ return globalQueueMicrotask;
72
+ }
73
+ const resolvedPromise = promiseResolvedWith(undefined);
74
+ return (fn) => PerformPromiseThen(resolvedPromise, fn);
75
+ })();
76
+ function reflectCall(F, V, args) {
77
+ if (typeof F !== 'function') {
78
+ throw new TypeError('Argument is not a function');
79
+ }
80
+ return Function.prototype.apply.call(F, V, args);
81
+ }
82
+ function promiseCall(F, V, args) {
83
+ try {
84
+ return promiseResolvedWith(reflectCall(F, V, args));
85
+ }
86
+ catch (value) {
87
+ return promiseRejectedWith(value);
88
+ }
89
+ }
90
+
91
+ // Original from Chromium
92
+ // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js
93
+ const QUEUE_MAX_ARRAY_SIZE = 16384;
94
+ /**
95
+ * Simple queue structure.
96
+ *
97
+ * Avoids scalability issues with using a packed array directly by using
98
+ * multiple arrays in a linked list and keeping the array size bounded.
99
+ */
100
+ class SimpleQueue {
101
+ constructor() {
102
+ this._cursor = 0;
103
+ this._size = 0;
104
+ // _front and _back are always defined.
105
+ this._front = {
106
+ _elements: [],
107
+ _next: undefined
108
+ };
109
+ this._back = this._front;
110
+ // The cursor is used to avoid calling Array.shift().
111
+ // It contains the index of the front element of the array inside the
112
+ // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).
113
+ this._cursor = 0;
114
+ // When there is only one node, size === elements.length - cursor.
115
+ this._size = 0;
116
+ }
117
+ get length() {
118
+ return this._size;
119
+ }
120
+ // For exception safety, this method is structured in order:
121
+ // 1. Read state
122
+ // 2. Calculate required state mutations
123
+ // 3. Perform state mutations
124
+ push(element) {
125
+ const oldBack = this._back;
126
+ let newBack = oldBack;
127
+ if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {
128
+ newBack = {
129
+ _elements: [],
130
+ _next: undefined
131
+ };
132
+ }
133
+ // push() is the mutation most likely to throw an exception, so it
134
+ // goes first.
135
+ oldBack._elements.push(element);
136
+ if (newBack !== oldBack) {
137
+ this._back = newBack;
138
+ oldBack._next = newBack;
139
+ }
140
+ ++this._size;
141
+ }
142
+ // Like push(), shift() follows the read -> calculate -> mutate pattern for
143
+ // exception safety.
144
+ shift() { // must not be called on an empty queue
145
+ const oldFront = this._front;
146
+ let newFront = oldFront;
147
+ const oldCursor = this._cursor;
148
+ let newCursor = oldCursor + 1;
149
+ const elements = oldFront._elements;
150
+ const element = elements[oldCursor];
151
+ if (newCursor === QUEUE_MAX_ARRAY_SIZE) {
152
+ newFront = oldFront._next;
153
+ newCursor = 0;
154
+ }
155
+ // No mutations before this point.
156
+ --this._size;
157
+ this._cursor = newCursor;
158
+ if (oldFront !== newFront) {
159
+ this._front = newFront;
160
+ }
161
+ // Permit shifted element to be garbage collected.
162
+ elements[oldCursor] = undefined;
163
+ return element;
164
+ }
165
+ // The tricky thing about forEach() is that it can be called
166
+ // re-entrantly. The queue may be mutated inside the callback. It is easy to
167
+ // see that push() within the callback has no negative effects since the end
168
+ // of the queue is checked for on every iteration. If shift() is called
169
+ // repeatedly within the callback then the next iteration may return an
170
+ // element that has been removed. In this case the callback will be called
171
+ // with undefined values until we either "catch up" with elements that still
172
+ // exist or reach the back of the queue.
173
+ forEach(callback) {
174
+ let i = this._cursor;
175
+ let node = this._front;
176
+ let elements = node._elements;
177
+ while (i !== elements.length || node._next !== undefined) {
178
+ if (i === elements.length) {
179
+ node = node._next;
180
+ elements = node._elements;
181
+ i = 0;
182
+ if (elements.length === 0) {
183
+ break;
184
+ }
185
+ }
186
+ callback(elements[i]);
187
+ ++i;
188
+ }
189
+ }
190
+ // Return the element that would be returned if shift() was called now,
191
+ // without modifying the queue.
192
+ peek() { // must not be called on an empty queue
193
+ const front = this._front;
194
+ const cursor = this._cursor;
195
+ return front._elements[cursor];
196
+ }
197
+ }
198
+
199
+ function ReadableStreamReaderGenericInitialize(reader, stream) {
200
+ reader._ownerReadableStream = stream;
201
+ stream._reader = reader;
202
+ if (stream._state === 'readable') {
203
+ defaultReaderClosedPromiseInitialize(reader);
204
+ }
205
+ else if (stream._state === 'closed') {
206
+ defaultReaderClosedPromiseInitializeAsResolved(reader);
207
+ }
208
+ else {
209
+ defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);
210
+ }
211
+ }
212
+ // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state
213
+ // check.
214
+ function ReadableStreamReaderGenericCancel(reader, reason) {
215
+ const stream = reader._ownerReadableStream;
216
+ return ReadableStreamCancel(stream, reason);
217
+ }
218
+ function ReadableStreamReaderGenericRelease(reader) {
219
+ if (reader._ownerReadableStream._state === 'readable') {
220
+ defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
221
+ }
222
+ else {
223
+ defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
224
+ }
225
+ reader._ownerReadableStream._reader = undefined;
226
+ reader._ownerReadableStream = undefined;
227
+ }
228
+ // Helper functions for the readers.
229
+ function readerLockException(name) {
230
+ return new TypeError('Cannot ' + name + ' a stream using a released reader');
231
+ }
232
+ // Helper functions for the ReadableStreamDefaultReader.
233
+ function defaultReaderClosedPromiseInitialize(reader) {
234
+ reader._closedPromise = newPromise((resolve, reject) => {
235
+ reader._closedPromise_resolve = resolve;
236
+ reader._closedPromise_reject = reject;
237
+ });
238
+ }
239
+ function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) {
240
+ defaultReaderClosedPromiseInitialize(reader);
241
+ defaultReaderClosedPromiseReject(reader, reason);
242
+ }
243
+ function defaultReaderClosedPromiseInitializeAsResolved(reader) {
244
+ defaultReaderClosedPromiseInitialize(reader);
245
+ defaultReaderClosedPromiseResolve(reader);
246
+ }
247
+ function defaultReaderClosedPromiseReject(reader, reason) {
248
+ if (reader._closedPromise_reject === undefined) {
249
+ return;
250
+ }
251
+ setPromiseIsHandledToTrue(reader._closedPromise);
252
+ reader._closedPromise_reject(reason);
253
+ reader._closedPromise_resolve = undefined;
254
+ reader._closedPromise_reject = undefined;
255
+ }
256
+ function defaultReaderClosedPromiseResetToRejected(reader, reason) {
257
+ defaultReaderClosedPromiseInitializeAsRejected(reader, reason);
258
+ }
259
+ function defaultReaderClosedPromiseResolve(reader) {
260
+ if (reader._closedPromise_resolve === undefined) {
261
+ return;
262
+ }
263
+ reader._closedPromise_resolve(undefined);
264
+ reader._closedPromise_resolve = undefined;
265
+ reader._closedPromise_reject = undefined;
266
+ }
267
+
268
+ const AbortSteps = SymbolPolyfill('[[AbortSteps]]');
269
+ const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]');
270
+ const CancelSteps = SymbolPolyfill('[[CancelSteps]]');
271
+ const PullSteps = SymbolPolyfill('[[PullSteps]]');
272
+
273
+ /// <reference lib="es2015.core" />
274
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill
275
+ const NumberIsFinite = Number.isFinite || function (x) {
276
+ return typeof x === 'number' && isFinite(x);
277
+ };
278
+
279
+ /// <reference lib="es2015.core" />
280
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill
281
+ const MathTrunc = Math.trunc || function (v) {
282
+ return v < 0 ? Math.ceil(v) : Math.floor(v);
283
+ };
284
+
285
+ // https://heycam.github.io/webidl/#idl-dictionaries
286
+ function isDictionary(x) {
287
+ return typeof x === 'object' || typeof x === 'function';
288
+ }
289
+ function assertDictionary(obj, context) {
290
+ if (obj !== undefined && !isDictionary(obj)) {
291
+ throw new TypeError(`${context} is not an object.`);
292
+ }
293
+ }
294
+ // https://heycam.github.io/webidl/#idl-callback-functions
295
+ function assertFunction(x, context) {
296
+ if (typeof x !== 'function') {
297
+ throw new TypeError(`${context} is not a function.`);
298
+ }
299
+ }
300
+ // https://heycam.github.io/webidl/#idl-object
301
+ function isObject(x) {
302
+ return (typeof x === 'object' && x !== null) || typeof x === 'function';
303
+ }
304
+ function assertObject(x, context) {
305
+ if (!isObject(x)) {
306
+ throw new TypeError(`${context} is not an object.`);
307
+ }
308
+ }
309
+ function assertRequiredArgument(x, position, context) {
310
+ if (x === undefined) {
311
+ throw new TypeError(`Parameter ${position} is required in '${context}'.`);
312
+ }
313
+ }
314
+ function assertRequiredField(x, field, context) {
315
+ if (x === undefined) {
316
+ throw new TypeError(`${field} is required in '${context}'.`);
317
+ }
318
+ }
319
+ // https://heycam.github.io/webidl/#idl-unrestricted-double
320
+ function convertUnrestrictedDouble(value) {
321
+ return Number(value);
322
+ }
323
+ function censorNegativeZero(x) {
324
+ return x === 0 ? 0 : x;
325
+ }
326
+ function integerPart(x) {
327
+ return censorNegativeZero(MathTrunc(x));
328
+ }
329
+ // https://heycam.github.io/webidl/#idl-unsigned-long-long
330
+ function convertUnsignedLongLongWithEnforceRange(value, context) {
331
+ const lowerBound = 0;
332
+ const upperBound = Number.MAX_SAFE_INTEGER;
333
+ let x = Number(value);
334
+ x = censorNegativeZero(x);
335
+ if (!NumberIsFinite(x)) {
336
+ throw new TypeError(`${context} is not a finite number`);
337
+ }
338
+ x = integerPart(x);
339
+ if (x < lowerBound || x > upperBound) {
340
+ throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);
341
+ }
342
+ if (!NumberIsFinite(x) || x === 0) {
343
+ return 0;
344
+ }
345
+ // TODO Use BigInt if supported?
346
+ // let xBigInt = BigInt(integerPart(x));
347
+ // xBigInt = BigInt.asUintN(64, xBigInt);
348
+ // return Number(xBigInt);
349
+ return x;
350
+ }
351
+
352
+ function assertReadableStream(x, context) {
353
+ if (!IsReadableStream(x)) {
354
+ throw new TypeError(`${context} is not a ReadableStream.`);
355
+ }
356
+ }
357
+
358
+ // Abstract operations for the ReadableStream.
359
+ function AcquireReadableStreamDefaultReader(stream) {
360
+ return new ReadableStreamDefaultReader(stream);
361
+ }
362
+ // ReadableStream API exposed for controllers.
363
+ function ReadableStreamAddReadRequest(stream, readRequest) {
364
+ stream._reader._readRequests.push(readRequest);
365
+ }
366
+ function ReadableStreamFulfillReadRequest(stream, chunk, done) {
367
+ const reader = stream._reader;
368
+ const readRequest = reader._readRequests.shift();
369
+ if (done) {
370
+ readRequest._closeSteps();
371
+ }
372
+ else {
373
+ readRequest._chunkSteps(chunk);
374
+ }
375
+ }
376
+ function ReadableStreamGetNumReadRequests(stream) {
377
+ return stream._reader._readRequests.length;
378
+ }
379
+ function ReadableStreamHasDefaultReader(stream) {
380
+ const reader = stream._reader;
381
+ if (reader === undefined) {
382
+ return false;
383
+ }
384
+ if (!IsReadableStreamDefaultReader(reader)) {
385
+ return false;
386
+ }
387
+ return true;
388
+ }
389
+ /**
390
+ * A default reader vended by a {@link ReadableStream}.
391
+ *
392
+ * @public
393
+ */
394
+ class ReadableStreamDefaultReader {
395
+ constructor(stream) {
396
+ assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');
397
+ assertReadableStream(stream, 'First parameter');
398
+ if (IsReadableStreamLocked(stream)) {
399
+ throw new TypeError('This stream has already been locked for exclusive reading by another reader');
400
+ }
401
+ ReadableStreamReaderGenericInitialize(this, stream);
402
+ this._readRequests = new SimpleQueue();
403
+ }
404
+ /**
405
+ * Returns a promise that will be fulfilled when the stream becomes closed,
406
+ * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.
407
+ */
408
+ get closed() {
409
+ if (!IsReadableStreamDefaultReader(this)) {
410
+ return promiseRejectedWith(defaultReaderBrandCheckException('closed'));
411
+ }
412
+ return this._closedPromise;
413
+ }
414
+ /**
415
+ * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
416
+ */
417
+ cancel(reason = undefined) {
418
+ if (!IsReadableStreamDefaultReader(this)) {
419
+ return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));
420
+ }
421
+ if (this._ownerReadableStream === undefined) {
422
+ return promiseRejectedWith(readerLockException('cancel'));
423
+ }
424
+ return ReadableStreamReaderGenericCancel(this, reason);
425
+ }
426
+ /**
427
+ * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.
428
+ *
429
+ * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
430
+ */
431
+ read() {
432
+ if (!IsReadableStreamDefaultReader(this)) {
433
+ return promiseRejectedWith(defaultReaderBrandCheckException('read'));
434
+ }
435
+ if (this._ownerReadableStream === undefined) {
436
+ return promiseRejectedWith(readerLockException('read from'));
437
+ }
438
+ let resolvePromise;
439
+ let rejectPromise;
440
+ const promise = newPromise((resolve, reject) => {
441
+ resolvePromise = resolve;
442
+ rejectPromise = reject;
443
+ });
444
+ const readRequest = {
445
+ _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),
446
+ _closeSteps: () => resolvePromise({ value: undefined, done: true }),
447
+ _errorSteps: e => rejectPromise(e)
448
+ };
449
+ ReadableStreamDefaultReaderRead(this, readRequest);
450
+ return promise;
451
+ }
452
+ /**
453
+ * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
454
+ * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
455
+ * from now on; otherwise, the reader will appear closed.
456
+ *
457
+ * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
458
+ * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to
459
+ * do so will throw a `TypeError` and leave the reader locked to the stream.
460
+ */
461
+ releaseLock() {
462
+ if (!IsReadableStreamDefaultReader(this)) {
463
+ throw defaultReaderBrandCheckException('releaseLock');
464
+ }
465
+ if (this._ownerReadableStream === undefined) {
466
+ return;
467
+ }
468
+ if (this._readRequests.length > 0) {
469
+ throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');
470
+ }
471
+ ReadableStreamReaderGenericRelease(this);
472
+ }
473
+ }
474
+ Object.defineProperties(ReadableStreamDefaultReader.prototype, {
475
+ cancel: { enumerable: true },
476
+ read: { enumerable: true },
477
+ releaseLock: { enumerable: true },
478
+ closed: { enumerable: true }
479
+ });
480
+ if (typeof SymbolPolyfill.toStringTag === 'symbol') {
481
+ Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, {
482
+ value: 'ReadableStreamDefaultReader',
483
+ configurable: true
484
+ });
485
+ }
486
+ // Abstract operations for the readers.
487
+ function IsReadableStreamDefaultReader(x) {
488
+ if (!typeIsObject(x)) {
489
+ return false;
490
+ }
491
+ if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {
492
+ return false;
493
+ }
494
+ return true;
495
+ }
496
+ function ReadableStreamDefaultReaderRead(reader, readRequest) {
497
+ const stream = reader._ownerReadableStream;
498
+ stream._disturbed = true;
499
+ if (stream._state === 'closed') {
500
+ readRequest._closeSteps();
501
+ }
502
+ else if (stream._state === 'errored') {
503
+ readRequest._errorSteps(stream._storedError);
504
+ }
505
+ else {
506
+ stream._readableStreamController[PullSteps](readRequest);
507
+ }
508
+ }
509
+ // Helper functions for the ReadableStreamDefaultReader.
510
+ function defaultReaderBrandCheckException(name) {
511
+ return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);
512
+ }
513
+
514
+ /// <reference lib="es2018.asynciterable" />
515
+ let AsyncIteratorPrototype;
516
+ if (typeof SymbolPolyfill.asyncIterator === 'symbol') {
517
+ // We're running inside a ES2018+ environment, but we're compiling to an older syntax.
518
+ // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.
519
+ AsyncIteratorPrototype = {
520
+ // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )
521
+ // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator
522
+ [SymbolPolyfill.asyncIterator]() {
523
+ return this;
524
+ }
525
+ };
526
+ Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false });
527
+ }
528
+
529
+ /// <reference lib="es2018.asynciterable" />
530
+ class ReadableStreamAsyncIteratorImpl {
531
+ constructor(reader, preventCancel) {
532
+ this._ongoingPromise = undefined;
533
+ this._isFinished = false;
534
+ this._reader = reader;
535
+ this._preventCancel = preventCancel;
536
+ }
537
+ next() {
538
+ const nextSteps = () => this._nextSteps();
539
+ this._ongoingPromise = this._ongoingPromise ?
540
+ transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :
541
+ nextSteps();
542
+ return this._ongoingPromise;
543
+ }
544
+ return(value) {
545
+ const returnSteps = () => this._returnSteps(value);
546
+ return this._ongoingPromise ?
547
+ transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :
548
+ returnSteps();
549
+ }
550
+ _nextSteps() {
551
+ if (this._isFinished) {
552
+ return Promise.resolve({ value: undefined, done: true });
553
+ }
554
+ const reader = this._reader;
555
+ if (reader._ownerReadableStream === undefined) {
556
+ return promiseRejectedWith(readerLockException('iterate'));
557
+ }
558
+ let resolvePromise;
559
+ let rejectPromise;
560
+ const promise = newPromise((resolve, reject) => {
561
+ resolvePromise = resolve;
562
+ rejectPromise = reject;
563
+ });
564
+ const readRequest = {
565
+ _chunkSteps: chunk => {
566
+ this._ongoingPromise = undefined;
567
+ // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.
568
+ // FIXME Is this a bug in the specification, or in the test?
569
+ queueMicrotask(() => resolvePromise({ value: chunk, done: false }));
570
+ },
571
+ _closeSteps: () => {
572
+ this._ongoingPromise = undefined;
573
+ this._isFinished = true;
574
+ ReadableStreamReaderGenericRelease(reader);
575
+ resolvePromise({ value: undefined, done: true });
576
+ },
577
+ _errorSteps: reason => {
578
+ this._ongoingPromise = undefined;
579
+ this._isFinished = true;
580
+ ReadableStreamReaderGenericRelease(reader);
581
+ rejectPromise(reason);
582
+ }
583
+ };
584
+ ReadableStreamDefaultReaderRead(reader, readRequest);
585
+ return promise;
586
+ }
587
+ _returnSteps(value) {
588
+ if (this._isFinished) {
589
+ return Promise.resolve({ value, done: true });
590
+ }
591
+ this._isFinished = true;
592
+ const reader = this._reader;
593
+ if (reader._ownerReadableStream === undefined) {
594
+ return promiseRejectedWith(readerLockException('finish iterating'));
595
+ }
596
+ if (!this._preventCancel) {
597
+ const result = ReadableStreamReaderGenericCancel(reader, value);
598
+ ReadableStreamReaderGenericRelease(reader);
599
+ return transformPromiseWith(result, () => ({ value, done: true }));
600
+ }
601
+ ReadableStreamReaderGenericRelease(reader);
602
+ return promiseResolvedWith({ value, done: true });
603
+ }
604
+ }
605
+ const ReadableStreamAsyncIteratorPrototype = {
606
+ next() {
607
+ if (!IsReadableStreamAsyncIterator(this)) {
608
+ return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));
609
+ }
610
+ return this._asyncIteratorImpl.next();
611
+ },
612
+ return(value) {
613
+ if (!IsReadableStreamAsyncIterator(this)) {
614
+ return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));
615
+ }
616
+ return this._asyncIteratorImpl.return(value);
617
+ }
618
+ };
619
+ if (AsyncIteratorPrototype !== undefined) {
620
+ Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);
621
+ }
622
+ // Abstract operations for the ReadableStream.
623
+ function AcquireReadableStreamAsyncIterator(stream, preventCancel) {
624
+ const reader = AcquireReadableStreamDefaultReader(stream);
625
+ const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);
626
+ const iterator = Object.create(ReadableStreamAsyncIteratorPrototype);
627
+ iterator._asyncIteratorImpl = impl;
628
+ return iterator;
629
+ }
630
+ function IsReadableStreamAsyncIterator(x) {
631
+ if (!typeIsObject(x)) {
632
+ return false;
633
+ }
634
+ if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {
635
+ return false;
636
+ }
637
+ return true;
638
+ }
639
+ // Helper functions for the ReadableStream.
640
+ function streamAsyncIteratorBrandCheckException(name) {
641
+ return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);
642
+ }
643
+
644
+ /// <reference lib="es2015.core" />
645
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill
646
+ const NumberIsNaN = Number.isNaN || function (x) {
647
+ // eslint-disable-next-line no-self-compare
648
+ return x !== x;
649
+ };
650
+
651
+ function IsFiniteNonNegativeNumber(v) {
652
+ if (!IsNonNegativeNumber(v)) {
653
+ return false;
654
+ }
655
+ if (v === Infinity) {
656
+ return false;
657
+ }
658
+ return true;
659
+ }
660
+ function IsNonNegativeNumber(v) {
661
+ if (typeof v !== 'number') {
662
+ return false;
663
+ }
664
+ if (NumberIsNaN(v)) {
665
+ return false;
666
+ }
667
+ if (v < 0) {
668
+ return false;
669
+ }
670
+ return true;
671
+ }
672
+
673
+ function DequeueValue(container) {
674
+ const pair = container._queue.shift();
675
+ container._queueTotalSize -= pair.size;
676
+ if (container._queueTotalSize < 0) {
677
+ container._queueTotalSize = 0;
678
+ }
679
+ return pair.value;
680
+ }
681
+ function EnqueueValueWithSize(container, value, size) {
682
+ size = Number(size);
683
+ if (!IsFiniteNonNegativeNumber(size)) {
684
+ throw new RangeError('Size must be a finite, non-NaN, non-negative number.');
685
+ }
686
+ container._queue.push({ value, size });
687
+ container._queueTotalSize += size;
688
+ }
689
+ function PeekQueueValue(container) {
690
+ const pair = container._queue.peek();
691
+ return pair.value;
692
+ }
693
+ function ResetQueue(container) {
694
+ container._queue = new SimpleQueue();
695
+ container._queueTotalSize = 0;
696
+ }
697
+
698
+ function CreateArrayFromList(elements) {
699
+ // We use arrays to represent lists, so this is basically a no-op.
700
+ // Do a slice though just in case we happen to depend on the unique-ness.
701
+ return elements.slice();
702
+ }
703
+ function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) {
704
+ new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);
705
+ }
706
+ // Not implemented correctly
707
+ function TransferArrayBuffer(O) {
708
+ return O;
709
+ }
710
+ // Not implemented correctly
711
+ function IsDetachedBuffer(O) {
712
+ return false;
713
+ }
714
+
715
+ /**
716
+ * A pull-into request in a {@link ReadableByteStreamController}.
717
+ *
718
+ * @public
719
+ */
720
+ class ReadableStreamBYOBRequest {
721
+ constructor() {
722
+ throw new TypeError('Illegal constructor');
723
+ }
724
+ /**
725
+ * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.
726
+ */
727
+ get view() {
728
+ if (!IsReadableStreamBYOBRequest(this)) {
729
+ throw byobRequestBrandCheckException('view');
730
+ }
731
+ return this._view;
732
+ }
733
+ respond(bytesWritten) {
734
+ if (!IsReadableStreamBYOBRequest(this)) {
735
+ throw byobRequestBrandCheckException('respond');
736
+ }
737
+ assertRequiredArgument(bytesWritten, 1, 'respond');
738
+ bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');
739
+ if (this._associatedReadableByteStreamController === undefined) {
740
+ throw new TypeError('This BYOB request has been invalidated');
741
+ }
742
+ if (IsDetachedBuffer(this._view.buffer)) ;
743
+ ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);
744
+ }
745
+ respondWithNewView(view) {
746
+ if (!IsReadableStreamBYOBRequest(this)) {
747
+ throw byobRequestBrandCheckException('respondWithNewView');
748
+ }
749
+ assertRequiredArgument(view, 1, 'respondWithNewView');
750
+ if (!ArrayBuffer.isView(view)) {
751
+ throw new TypeError('You can only respond with array buffer views');
752
+ }
753
+ if (view.byteLength === 0) {
754
+ throw new TypeError('chunk must have non-zero byteLength');
755
+ }
756
+ if (view.buffer.byteLength === 0) {
757
+ throw new TypeError(`chunk's buffer must have non-zero byteLength`);
758
+ }
759
+ if (this._associatedReadableByteStreamController === undefined) {
760
+ throw new TypeError('This BYOB request has been invalidated');
761
+ }
762
+ ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);
763
+ }
764
+ }
765
+ Object.defineProperties(ReadableStreamBYOBRequest.prototype, {
766
+ respond: { enumerable: true },
767
+ respondWithNewView: { enumerable: true },
768
+ view: { enumerable: true }
769
+ });
770
+ if (typeof SymbolPolyfill.toStringTag === 'symbol') {
771
+ Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, {
772
+ value: 'ReadableStreamBYOBRequest',
773
+ configurable: true
774
+ });
775
+ }
776
+ /**
777
+ * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.
778
+ *
779
+ * @public
780
+ */
781
+ class ReadableByteStreamController {
782
+ constructor() {
783
+ throw new TypeError('Illegal constructor');
784
+ }
785
+ /**
786
+ * Returns the current BYOB pull request, or `null` if there isn't one.
787
+ */
788
+ get byobRequest() {
789
+ if (!IsReadableByteStreamController(this)) {
790
+ throw byteStreamControllerBrandCheckException('byobRequest');
791
+ }
792
+ if (this._byobRequest === null && this._pendingPullIntos.length > 0) {
793
+ const firstDescriptor = this._pendingPullIntos.peek();
794
+ const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled);
795
+ const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype);
796
+ SetUpReadableStreamBYOBRequest(byobRequest, this, view);
797
+ this._byobRequest = byobRequest;
798
+ }
799
+ return this._byobRequest;
800
+ }
801
+ /**
802
+ * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
803
+ * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.
804
+ */
805
+ get desiredSize() {
806
+ if (!IsReadableByteStreamController(this)) {
807
+ throw byteStreamControllerBrandCheckException('desiredSize');
808
+ }
809
+ return ReadableByteStreamControllerGetDesiredSize(this);
810
+ }
811
+ /**
812
+ * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
813
+ * the stream, but once those are read, the stream will become closed.
814
+ */
815
+ close() {
816
+ if (!IsReadableByteStreamController(this)) {
817
+ throw byteStreamControllerBrandCheckException('close');
818
+ }
819
+ if (this._closeRequested) {
820
+ throw new TypeError('The stream has already been closed; do not close it again!');
821
+ }
822
+ const state = this._controlledReadableByteStream._state;
823
+ if (state !== 'readable') {
824
+ throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);
825
+ }
826
+ ReadableByteStreamControllerClose(this);
827
+ }
828
+ enqueue(chunk) {
829
+ if (!IsReadableByteStreamController(this)) {
830
+ throw byteStreamControllerBrandCheckException('enqueue');
831
+ }
832
+ assertRequiredArgument(chunk, 1, 'enqueue');
833
+ if (!ArrayBuffer.isView(chunk)) {
834
+ throw new TypeError('chunk must be an array buffer view');
835
+ }
836
+ if (chunk.byteLength === 0) {
837
+ throw new TypeError('chunk must have non-zero byteLength');
838
+ }
839
+ if (chunk.buffer.byteLength === 0) {
840
+ throw new TypeError(`chunk's buffer must have non-zero byteLength`);
841
+ }
842
+ if (this._closeRequested) {
843
+ throw new TypeError('stream is closed or draining');
844
+ }
845
+ const state = this._controlledReadableByteStream._state;
846
+ if (state !== 'readable') {
847
+ throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);
848
+ }
849
+ ReadableByteStreamControllerEnqueue(this, chunk);
850
+ }
851
+ /**
852
+ * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
853
+ */
854
+ error(e = undefined) {
855
+ if (!IsReadableByteStreamController(this)) {
856
+ throw byteStreamControllerBrandCheckException('error');
857
+ }
858
+ ReadableByteStreamControllerError(this, e);
859
+ }
860
+ /** @internal */
861
+ [CancelSteps](reason) {
862
+ if (this._pendingPullIntos.length > 0) {
863
+ const firstDescriptor = this._pendingPullIntos.peek();
864
+ firstDescriptor.bytesFilled = 0;
865
+ }
866
+ ResetQueue(this);
867
+ const result = this._cancelAlgorithm(reason);
868
+ ReadableByteStreamControllerClearAlgorithms(this);
869
+ return result;
870
+ }
871
+ /** @internal */
872
+ [PullSteps](readRequest) {
873
+ const stream = this._controlledReadableByteStream;
874
+ if (this._queueTotalSize > 0) {
875
+ const entry = this._queue.shift();
876
+ this._queueTotalSize -= entry.byteLength;
877
+ ReadableByteStreamControllerHandleQueueDrain(this);
878
+ const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);
879
+ readRequest._chunkSteps(view);
880
+ return;
881
+ }
882
+ const autoAllocateChunkSize = this._autoAllocateChunkSize;
883
+ if (autoAllocateChunkSize !== undefined) {
884
+ let buffer;
885
+ try {
886
+ buffer = new ArrayBuffer(autoAllocateChunkSize);
887
+ }
888
+ catch (bufferE) {
889
+ readRequest._errorSteps(bufferE);
890
+ return;
891
+ }
892
+ const pullIntoDescriptor = {
893
+ buffer,
894
+ byteOffset: 0,
895
+ byteLength: autoAllocateChunkSize,
896
+ bytesFilled: 0,
897
+ elementSize: 1,
898
+ viewConstructor: Uint8Array,
899
+ readerType: 'default'
900
+ };
901
+ this._pendingPullIntos.push(pullIntoDescriptor);
902
+ }
903
+ ReadableStreamAddReadRequest(stream, readRequest);
904
+ ReadableByteStreamControllerCallPullIfNeeded(this);
905
+ }
906
+ }
907
+ Object.defineProperties(ReadableByteStreamController.prototype, {
908
+ close: { enumerable: true },
909
+ enqueue: { enumerable: true },
910
+ error: { enumerable: true },
911
+ byobRequest: { enumerable: true },
912
+ desiredSize: { enumerable: true }
913
+ });
914
+ if (typeof SymbolPolyfill.toStringTag === 'symbol') {
915
+ Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, {
916
+ value: 'ReadableByteStreamController',
917
+ configurable: true
918
+ });
919
+ }
920
+ // Abstract operations for the ReadableByteStreamController.
921
+ function IsReadableByteStreamController(x) {
922
+ if (!typeIsObject(x)) {
923
+ return false;
924
+ }
925
+ if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {
926
+ return false;
927
+ }
928
+ return true;
929
+ }
930
+ function IsReadableStreamBYOBRequest(x) {
931
+ if (!typeIsObject(x)) {
932
+ return false;
933
+ }
934
+ if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {
935
+ return false;
936
+ }
937
+ return true;
938
+ }
939
+ function ReadableByteStreamControllerCallPullIfNeeded(controller) {
940
+ const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);
941
+ if (!shouldPull) {
942
+ return;
943
+ }
944
+ if (controller._pulling) {
945
+ controller._pullAgain = true;
946
+ return;
947
+ }
948
+ controller._pulling = true;
949
+ // TODO: Test controller argument
950
+ const pullPromise = controller._pullAlgorithm();
951
+ uponPromise(pullPromise, () => {
952
+ controller._pulling = false;
953
+ if (controller._pullAgain) {
954
+ controller._pullAgain = false;
955
+ ReadableByteStreamControllerCallPullIfNeeded(controller);
956
+ }
957
+ }, e => {
958
+ ReadableByteStreamControllerError(controller, e);
959
+ });
960
+ }
961
+ function ReadableByteStreamControllerClearPendingPullIntos(controller) {
962
+ ReadableByteStreamControllerInvalidateBYOBRequest(controller);
963
+ controller._pendingPullIntos = new SimpleQueue();
964
+ }
965
+ function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) {
966
+ let done = false;
967
+ if (stream._state === 'closed') {
968
+ done = true;
969
+ }
970
+ const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
971
+ if (pullIntoDescriptor.readerType === 'default') {
972
+ ReadableStreamFulfillReadRequest(stream, filledView, done);
973
+ }
974
+ else {
975
+ ReadableStreamFulfillReadIntoRequest(stream, filledView, done);
976
+ }
977
+ }
978
+ function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) {
979
+ const bytesFilled = pullIntoDescriptor.bytesFilled;
980
+ const elementSize = pullIntoDescriptor.elementSize;
981
+ return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize);
982
+ }
983
+ function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) {
984
+ controller._queue.push({ buffer, byteOffset, byteLength });
985
+ controller._queueTotalSize += byteLength;
986
+ }
987
+ function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) {
988
+ const elementSize = pullIntoDescriptor.elementSize;
989
+ const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;
990
+ const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);
991
+ const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;
992
+ const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;
993
+ let totalBytesToCopyRemaining = maxBytesToCopy;
994
+ let ready = false;
995
+ if (maxAlignedBytes > currentAlignedBytes) {
996
+ totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;
997
+ ready = true;
998
+ }
999
+ const queue = controller._queue;
1000
+ while (totalBytesToCopyRemaining > 0) {
1001
+ const headOfQueue = queue.peek();
1002
+ const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);
1003
+ const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
1004
+ CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);
1005
+ if (headOfQueue.byteLength === bytesToCopy) {
1006
+ queue.shift();
1007
+ }
1008
+ else {
1009
+ headOfQueue.byteOffset += bytesToCopy;
1010
+ headOfQueue.byteLength -= bytesToCopy;
1011
+ }
1012
+ controller._queueTotalSize -= bytesToCopy;
1013
+ ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);
1014
+ totalBytesToCopyRemaining -= bytesToCopy;
1015
+ }
1016
+ return ready;
1017
+ }
1018
+ function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) {
1019
+ ReadableByteStreamControllerInvalidateBYOBRequest(controller);
1020
+ pullIntoDescriptor.bytesFilled += size;
1021
+ }
1022
+ function ReadableByteStreamControllerHandleQueueDrain(controller) {
1023
+ if (controller._queueTotalSize === 0 && controller._closeRequested) {
1024
+ ReadableByteStreamControllerClearAlgorithms(controller);
1025
+ ReadableStreamClose(controller._controlledReadableByteStream);
1026
+ }
1027
+ else {
1028
+ ReadableByteStreamControllerCallPullIfNeeded(controller);
1029
+ }
1030
+ }
1031
+ function ReadableByteStreamControllerInvalidateBYOBRequest(controller) {
1032
+ if (controller._byobRequest === null) {
1033
+ return;
1034
+ }
1035
+ controller._byobRequest._associatedReadableByteStreamController = undefined;
1036
+ controller._byobRequest._view = null;
1037
+ controller._byobRequest = null;
1038
+ }
1039
+ function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) {
1040
+ while (controller._pendingPullIntos.length > 0) {
1041
+ if (controller._queueTotalSize === 0) {
1042
+ return;
1043
+ }
1044
+ const pullIntoDescriptor = controller._pendingPullIntos.peek();
1045
+ if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {
1046
+ ReadableByteStreamControllerShiftPendingPullInto(controller);
1047
+ ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
1048
+ }
1049
+ }
1050
+ }
1051
+ function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) {
1052
+ const stream = controller._controlledReadableByteStream;
1053
+ let elementSize = 1;
1054
+ if (view.constructor !== DataView) {
1055
+ elementSize = view.constructor.BYTES_PER_ELEMENT;
1056
+ }
1057
+ const ctor = view.constructor;
1058
+ const buffer = TransferArrayBuffer(view.buffer);
1059
+ const pullIntoDescriptor = {
1060
+ buffer,
1061
+ byteOffset: view.byteOffset,
1062
+ byteLength: view.byteLength,
1063
+ bytesFilled: 0,
1064
+ elementSize,
1065
+ viewConstructor: ctor,
1066
+ readerType: 'byob'
1067
+ };
1068
+ if (controller._pendingPullIntos.length > 0) {
1069
+ controller._pendingPullIntos.push(pullIntoDescriptor);
1070
+ // No ReadableByteStreamControllerCallPullIfNeeded() call since:
1071
+ // - No change happens on desiredSize
1072
+ // - The source has already been notified of that there's at least 1 pending read(view)
1073
+ ReadableStreamAddReadIntoRequest(stream, readIntoRequest);
1074
+ return;
1075
+ }
1076
+ if (stream._state === 'closed') {
1077
+ const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);
1078
+ readIntoRequest._closeSteps(emptyView);
1079
+ return;
1080
+ }
1081
+ if (controller._queueTotalSize > 0) {
1082
+ if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {
1083
+ const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
1084
+ ReadableByteStreamControllerHandleQueueDrain(controller);
1085
+ readIntoRequest._chunkSteps(filledView);
1086
+ return;
1087
+ }
1088
+ if (controller._closeRequested) {
1089
+ const e = new TypeError('Insufficient bytes to fill elements in the given buffer');
1090
+ ReadableByteStreamControllerError(controller, e);
1091
+ readIntoRequest._errorSteps(e);
1092
+ return;
1093
+ }
1094
+ }
1095
+ controller._pendingPullIntos.push(pullIntoDescriptor);
1096
+ ReadableStreamAddReadIntoRequest(stream, readIntoRequest);
1097
+ ReadableByteStreamControllerCallPullIfNeeded(controller);
1098
+ }
1099
+ function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {
1100
+ firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);
1101
+ const stream = controller._controlledReadableByteStream;
1102
+ if (ReadableStreamHasBYOBReader(stream)) {
1103
+ while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {
1104
+ const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);
1105
+ ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);
1106
+ }
1107
+ }
1108
+ }
1109
+ function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) {
1110
+ if (pullIntoDescriptor.bytesFilled + bytesWritten > pullIntoDescriptor.byteLength) {
1111
+ throw new RangeError('bytesWritten out of range');
1112
+ }
1113
+ ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);
1114
+ if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {
1115
+ // TODO: Figure out whether we should detach the buffer or not here.
1116
+ return;
1117
+ }
1118
+ ReadableByteStreamControllerShiftPendingPullInto(controller);
1119
+ const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;
1120
+ if (remainderSize > 0) {
1121
+ const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
1122
+ const remainder = pullIntoDescriptor.buffer.slice(end - remainderSize, end);
1123
+ ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);
1124
+ }
1125
+ pullIntoDescriptor.buffer = TransferArrayBuffer(pullIntoDescriptor.buffer);
1126
+ pullIntoDescriptor.bytesFilled -= remainderSize;
1127
+ ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
1128
+ ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
1129
+ }
1130
+ function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) {
1131
+ const firstDescriptor = controller._pendingPullIntos.peek();
1132
+ const state = controller._controlledReadableByteStream._state;
1133
+ if (state === 'closed') {
1134
+ if (bytesWritten !== 0) {
1135
+ throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');
1136
+ }
1137
+ ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);
1138
+ }
1139
+ else {
1140
+ ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);
1141
+ }
1142
+ ReadableByteStreamControllerCallPullIfNeeded(controller);
1143
+ }
1144
+ function ReadableByteStreamControllerShiftPendingPullInto(controller) {
1145
+ const descriptor = controller._pendingPullIntos.shift();
1146
+ ReadableByteStreamControllerInvalidateBYOBRequest(controller);
1147
+ return descriptor;
1148
+ }
1149
+ function ReadableByteStreamControllerShouldCallPull(controller) {
1150
+ const stream = controller._controlledReadableByteStream;
1151
+ if (stream._state !== 'readable') {
1152
+ return false;
1153
+ }
1154
+ if (controller._closeRequested) {
1155
+ return false;
1156
+ }
1157
+ if (!controller._started) {
1158
+ return false;
1159
+ }
1160
+ if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
1161
+ return true;
1162
+ }
1163
+ if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {
1164
+ return true;
1165
+ }
1166
+ const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);
1167
+ if (desiredSize > 0) {
1168
+ return true;
1169
+ }
1170
+ return false;
1171
+ }
1172
+ function ReadableByteStreamControllerClearAlgorithms(controller) {
1173
+ controller._pullAlgorithm = undefined;
1174
+ controller._cancelAlgorithm = undefined;
1175
+ }
1176
+ // A client of ReadableByteStreamController may use these functions directly to bypass state check.
1177
+ function ReadableByteStreamControllerClose(controller) {
1178
+ const stream = controller._controlledReadableByteStream;
1179
+ if (controller._closeRequested || stream._state !== 'readable') {
1180
+ return;
1181
+ }
1182
+ if (controller._queueTotalSize > 0) {
1183
+ controller._closeRequested = true;
1184
+ return;
1185
+ }
1186
+ if (controller._pendingPullIntos.length > 0) {
1187
+ const firstPendingPullInto = controller._pendingPullIntos.peek();
1188
+ if (firstPendingPullInto.bytesFilled > 0) {
1189
+ const e = new TypeError('Insufficient bytes to fill elements in the given buffer');
1190
+ ReadableByteStreamControllerError(controller, e);
1191
+ throw e;
1192
+ }
1193
+ }
1194
+ ReadableByteStreamControllerClearAlgorithms(controller);
1195
+ ReadableStreamClose(stream);
1196
+ }
1197
+ function ReadableByteStreamControllerEnqueue(controller, chunk) {
1198
+ const stream = controller._controlledReadableByteStream;
1199
+ if (controller._closeRequested || stream._state !== 'readable') {
1200
+ return;
1201
+ }
1202
+ const buffer = chunk.buffer;
1203
+ const byteOffset = chunk.byteOffset;
1204
+ const byteLength = chunk.byteLength;
1205
+ const transferredBuffer = TransferArrayBuffer(buffer);
1206
+ if (ReadableStreamHasDefaultReader(stream)) {
1207
+ if (ReadableStreamGetNumReadRequests(stream) === 0) {
1208
+ ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
1209
+ }
1210
+ else {
1211
+ const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);
1212
+ ReadableStreamFulfillReadRequest(stream, transferredView, false);
1213
+ }
1214
+ }
1215
+ else if (ReadableStreamHasBYOBReader(stream)) {
1216
+ // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.
1217
+ ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
1218
+ ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
1219
+ }
1220
+ else {
1221
+ ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
1222
+ }
1223
+ ReadableByteStreamControllerCallPullIfNeeded(controller);
1224
+ }
1225
+ function ReadableByteStreamControllerError(controller, e) {
1226
+ const stream = controller._controlledReadableByteStream;
1227
+ if (stream._state !== 'readable') {
1228
+ return;
1229
+ }
1230
+ ReadableByteStreamControllerClearPendingPullIntos(controller);
1231
+ ResetQueue(controller);
1232
+ ReadableByteStreamControllerClearAlgorithms(controller);
1233
+ ReadableStreamError(stream, e);
1234
+ }
1235
+ function ReadableByteStreamControllerGetDesiredSize(controller) {
1236
+ const state = controller._controlledReadableByteStream._state;
1237
+ if (state === 'errored') {
1238
+ return null;
1239
+ }
1240
+ if (state === 'closed') {
1241
+ return 0;
1242
+ }
1243
+ return controller._strategyHWM - controller._queueTotalSize;
1244
+ }
1245
+ function ReadableByteStreamControllerRespond(controller, bytesWritten) {
1246
+ bytesWritten = Number(bytesWritten);
1247
+ if (!IsFiniteNonNegativeNumber(bytesWritten)) {
1248
+ throw new RangeError('bytesWritten must be a finite');
1249
+ }
1250
+ ReadableByteStreamControllerRespondInternal(controller, bytesWritten);
1251
+ }
1252
+ function ReadableByteStreamControllerRespondWithNewView(controller, view) {
1253
+ const firstDescriptor = controller._pendingPullIntos.peek();
1254
+ if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {
1255
+ throw new RangeError('The region specified by view does not match byobRequest');
1256
+ }
1257
+ if (firstDescriptor.byteLength !== view.byteLength) {
1258
+ throw new RangeError('The buffer of view has different capacity than byobRequest');
1259
+ }
1260
+ firstDescriptor.buffer = view.buffer;
1261
+ ReadableByteStreamControllerRespondInternal(controller, view.byteLength);
1262
+ }
1263
+ function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) {
1264
+ controller._controlledReadableByteStream = stream;
1265
+ controller._pullAgain = false;
1266
+ controller._pulling = false;
1267
+ controller._byobRequest = null;
1268
+ // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.
1269
+ controller._queue = controller._queueTotalSize = undefined;
1270
+ ResetQueue(controller);
1271
+ controller._closeRequested = false;
1272
+ controller._started = false;
1273
+ controller._strategyHWM = highWaterMark;
1274
+ controller._pullAlgorithm = pullAlgorithm;
1275
+ controller._cancelAlgorithm = cancelAlgorithm;
1276
+ controller._autoAllocateChunkSize = autoAllocateChunkSize;
1277
+ controller._pendingPullIntos = new SimpleQueue();
1278
+ stream._readableStreamController = controller;
1279
+ const startResult = startAlgorithm();
1280
+ uponPromise(promiseResolvedWith(startResult), () => {
1281
+ controller._started = true;
1282
+ ReadableByteStreamControllerCallPullIfNeeded(controller);
1283
+ }, r => {
1284
+ ReadableByteStreamControllerError(controller, r);
1285
+ });
1286
+ }
1287
+ function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) {
1288
+ const controller = Object.create(ReadableByteStreamController.prototype);
1289
+ let startAlgorithm = () => undefined;
1290
+ let pullAlgorithm = () => promiseResolvedWith(undefined);
1291
+ let cancelAlgorithm = () => promiseResolvedWith(undefined);
1292
+ if (underlyingByteSource.start !== undefined) {
1293
+ startAlgorithm = () => underlyingByteSource.start(controller);
1294
+ }
1295
+ if (underlyingByteSource.pull !== undefined) {
1296
+ pullAlgorithm = () => underlyingByteSource.pull(controller);
1297
+ }
1298
+ if (underlyingByteSource.cancel !== undefined) {
1299
+ cancelAlgorithm = reason => underlyingByteSource.cancel(reason);
1300
+ }
1301
+ const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;
1302
+ if (autoAllocateChunkSize === 0) {
1303
+ throw new TypeError('autoAllocateChunkSize must be greater than 0');
1304
+ }
1305
+ SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize);
1306
+ }
1307
+ function SetUpReadableStreamBYOBRequest(request, controller, view) {
1308
+ request._associatedReadableByteStreamController = controller;
1309
+ request._view = view;
1310
+ }
1311
+ // Helper functions for the ReadableStreamBYOBRequest.
1312
+ function byobRequestBrandCheckException(name) {
1313
+ return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);
1314
+ }
1315
+ // Helper functions for the ReadableByteStreamController.
1316
+ function byteStreamControllerBrandCheckException(name) {
1317
+ return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);
1318
+ }
1319
+
1320
+ // Abstract operations for the ReadableStream.
1321
+ function AcquireReadableStreamBYOBReader(stream) {
1322
+ return new ReadableStreamBYOBReader(stream);
1323
+ }
1324
+ // ReadableStream API exposed for controllers.
1325
+ function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) {
1326
+ stream._reader._readIntoRequests.push(readIntoRequest);
1327
+ }
1328
+ function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) {
1329
+ const reader = stream._reader;
1330
+ const readIntoRequest = reader._readIntoRequests.shift();
1331
+ if (done) {
1332
+ readIntoRequest._closeSteps(chunk);
1333
+ }
1334
+ else {
1335
+ readIntoRequest._chunkSteps(chunk);
1336
+ }
1337
+ }
1338
+ function ReadableStreamGetNumReadIntoRequests(stream) {
1339
+ return stream._reader._readIntoRequests.length;
1340
+ }
1341
+ function ReadableStreamHasBYOBReader(stream) {
1342
+ const reader = stream._reader;
1343
+ if (reader === undefined) {
1344
+ return false;
1345
+ }
1346
+ if (!IsReadableStreamBYOBReader(reader)) {
1347
+ return false;
1348
+ }
1349
+ return true;
1350
+ }
1351
+ /**
1352
+ * A BYOB reader vended by a {@link ReadableStream}.
1353
+ *
1354
+ * @public
1355
+ */
1356
+ class ReadableStreamBYOBReader {
1357
+ constructor(stream) {
1358
+ assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');
1359
+ assertReadableStream(stream, 'First parameter');
1360
+ if (IsReadableStreamLocked(stream)) {
1361
+ throw new TypeError('This stream has already been locked for exclusive reading by another reader');
1362
+ }
1363
+ if (!IsReadableByteStreamController(stream._readableStreamController)) {
1364
+ throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +
1365
+ 'source');
1366
+ }
1367
+ ReadableStreamReaderGenericInitialize(this, stream);
1368
+ this._readIntoRequests = new SimpleQueue();
1369
+ }
1370
+ /**
1371
+ * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
1372
+ * the reader's lock is released before the stream finishes closing.
1373
+ */
1374
+ get closed() {
1375
+ if (!IsReadableStreamBYOBReader(this)) {
1376
+ return promiseRejectedWith(byobReaderBrandCheckException('closed'));
1377
+ }
1378
+ return this._closedPromise;
1379
+ }
1380
+ /**
1381
+ * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
1382
+ */
1383
+ cancel(reason = undefined) {
1384
+ if (!IsReadableStreamBYOBReader(this)) {
1385
+ return promiseRejectedWith(byobReaderBrandCheckException('cancel'));
1386
+ }
1387
+ if (this._ownerReadableStream === undefined) {
1388
+ return promiseRejectedWith(readerLockException('cancel'));
1389
+ }
1390
+ return ReadableStreamReaderGenericCancel(this, reason);
1391
+ }
1392
+ /**
1393
+ * Attempts to reads bytes into view, and returns a promise resolved with the result.
1394
+ *
1395
+ * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
1396
+ */
1397
+ read(view) {
1398
+ if (!IsReadableStreamBYOBReader(this)) {
1399
+ return promiseRejectedWith(byobReaderBrandCheckException('read'));
1400
+ }
1401
+ if (!ArrayBuffer.isView(view)) {
1402
+ return promiseRejectedWith(new TypeError('view must be an array buffer view'));
1403
+ }
1404
+ if (view.byteLength === 0) {
1405
+ return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));
1406
+ }
1407
+ if (view.buffer.byteLength === 0) {
1408
+ return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));
1409
+ }
1410
+ if (this._ownerReadableStream === undefined) {
1411
+ return promiseRejectedWith(readerLockException('read from'));
1412
+ }
1413
+ let resolvePromise;
1414
+ let rejectPromise;
1415
+ const promise = newPromise((resolve, reject) => {
1416
+ resolvePromise = resolve;
1417
+ rejectPromise = reject;
1418
+ });
1419
+ const readIntoRequest = {
1420
+ _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),
1421
+ _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),
1422
+ _errorSteps: e => rejectPromise(e)
1423
+ };
1424
+ ReadableStreamBYOBReaderRead(this, view, readIntoRequest);
1425
+ return promise;
1426
+ }
1427
+ /**
1428
+ * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
1429
+ * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
1430
+ * from now on; otherwise, the reader will appear closed.
1431
+ *
1432
+ * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
1433
+ * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to
1434
+ * do so will throw a `TypeError` and leave the reader locked to the stream.
1435
+ */
1436
+ releaseLock() {
1437
+ if (!IsReadableStreamBYOBReader(this)) {
1438
+ throw byobReaderBrandCheckException('releaseLock');
1439
+ }
1440
+ if (this._ownerReadableStream === undefined) {
1441
+ return;
1442
+ }
1443
+ if (this._readIntoRequests.length > 0) {
1444
+ throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');
1445
+ }
1446
+ ReadableStreamReaderGenericRelease(this);
1447
+ }
1448
+ }
1449
+ Object.defineProperties(ReadableStreamBYOBReader.prototype, {
1450
+ cancel: { enumerable: true },
1451
+ read: { enumerable: true },
1452
+ releaseLock: { enumerable: true },
1453
+ closed: { enumerable: true }
1454
+ });
1455
+ if (typeof SymbolPolyfill.toStringTag === 'symbol') {
1456
+ Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, {
1457
+ value: 'ReadableStreamBYOBReader',
1458
+ configurable: true
1459
+ });
1460
+ }
1461
+ // Abstract operations for the readers.
1462
+ function IsReadableStreamBYOBReader(x) {
1463
+ if (!typeIsObject(x)) {
1464
+ return false;
1465
+ }
1466
+ if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {
1467
+ return false;
1468
+ }
1469
+ return true;
1470
+ }
1471
+ function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) {
1472
+ const stream = reader._ownerReadableStream;
1473
+ stream._disturbed = true;
1474
+ if (stream._state === 'errored') {
1475
+ readIntoRequest._errorSteps(stream._storedError);
1476
+ }
1477
+ else {
1478
+ ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest);
1479
+ }
1480
+ }
1481
+ // Helper functions for the ReadableStreamBYOBReader.
1482
+ function byobReaderBrandCheckException(name) {
1483
+ return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);
1484
+ }
1485
+
1486
+ function ExtractHighWaterMark(strategy, defaultHWM) {
1487
+ const { highWaterMark } = strategy;
1488
+ if (highWaterMark === undefined) {
1489
+ return defaultHWM;
1490
+ }
1491
+ if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {
1492
+ throw new RangeError('Invalid highWaterMark');
1493
+ }
1494
+ return highWaterMark;
1495
+ }
1496
+ function ExtractSizeAlgorithm(strategy) {
1497
+ const { size } = strategy;
1498
+ if (!size) {
1499
+ return () => 1;
1500
+ }
1501
+ return size;
1502
+ }
1503
+
1504
+ function convertQueuingStrategy(init, context) {
1505
+ assertDictionary(init, context);
1506
+ const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;
1507
+ const size = init === null || init === void 0 ? void 0 : init.size;
1508
+ return {
1509
+ highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),
1510
+ size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)
1511
+ };
1512
+ }
1513
+ function convertQueuingStrategySize(fn, context) {
1514
+ assertFunction(fn, context);
1515
+ return chunk => convertUnrestrictedDouble(fn(chunk));
1516
+ }
1517
+
1518
+ function convertUnderlyingSink(original, context) {
1519
+ assertDictionary(original, context);
1520
+ const abort = original === null || original === void 0 ? void 0 : original.abort;
1521
+ const close = original === null || original === void 0 ? void 0 : original.close;
1522
+ const start = original === null || original === void 0 ? void 0 : original.start;
1523
+ const type = original === null || original === void 0 ? void 0 : original.type;
1524
+ const write = original === null || original === void 0 ? void 0 : original.write;
1525
+ return {
1526
+ abort: abort === undefined ?
1527
+ undefined :
1528
+ convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`),
1529
+ close: close === undefined ?
1530
+ undefined :
1531
+ convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`),
1532
+ start: start === undefined ?
1533
+ undefined :
1534
+ convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`),
1535
+ write: write === undefined ?
1536
+ undefined :
1537
+ convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`),
1538
+ type
1539
+ };
1540
+ }
1541
+ function convertUnderlyingSinkAbortCallback(fn, original, context) {
1542
+ assertFunction(fn, context);
1543
+ return (reason) => promiseCall(fn, original, [reason]);
1544
+ }
1545
+ function convertUnderlyingSinkCloseCallback(fn, original, context) {
1546
+ assertFunction(fn, context);
1547
+ return () => promiseCall(fn, original, []);
1548
+ }
1549
+ function convertUnderlyingSinkStartCallback(fn, original, context) {
1550
+ assertFunction(fn, context);
1551
+ return (controller) => reflectCall(fn, original, [controller]);
1552
+ }
1553
+ function convertUnderlyingSinkWriteCallback(fn, original, context) {
1554
+ assertFunction(fn, context);
1555
+ return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
1556
+ }
1557
+
1558
+ function assertWritableStream(x, context) {
1559
+ if (!IsWritableStream(x)) {
1560
+ throw new TypeError(`${context} is not a WritableStream.`);
1561
+ }
1562
+ }
1563
+
1564
+ /**
1565
+ * A writable stream represents a destination for data, into which you can write.
1566
+ *
1567
+ * @public
1568
+ */
1569
+ class WritableStream {
1570
+ constructor(rawUnderlyingSink = {}, rawStrategy = {}) {
1571
+ if (rawUnderlyingSink === undefined) {
1572
+ rawUnderlyingSink = null;
1573
+ }
1574
+ else {
1575
+ assertObject(rawUnderlyingSink, 'First parameter');
1576
+ }
1577
+ const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');
1578
+ const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');
1579
+ InitializeWritableStream(this);
1580
+ const type = underlyingSink.type;
1581
+ if (type !== undefined) {
1582
+ throw new RangeError('Invalid type is specified');
1583
+ }
1584
+ const sizeAlgorithm = ExtractSizeAlgorithm(strategy);
1585
+ const highWaterMark = ExtractHighWaterMark(strategy, 1);
1586
+ SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);
1587
+ }
1588
+ /**
1589
+ * Returns whether or not the writable stream is locked to a writer.
1590
+ */
1591
+ get locked() {
1592
+ if (!IsWritableStream(this)) {
1593
+ throw streamBrandCheckException$2('locked');
1594
+ }
1595
+ return IsWritableStreamLocked(this);
1596
+ }
1597
+ /**
1598
+ * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be
1599
+ * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort
1600
+ * mechanism of the underlying sink.
1601
+ *
1602
+ * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled
1603
+ * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel
1604
+ * the stream) if the stream is currently locked.
1605
+ */
1606
+ abort(reason = undefined) {
1607
+ if (!IsWritableStream(this)) {
1608
+ return promiseRejectedWith(streamBrandCheckException$2('abort'));
1609
+ }
1610
+ if (IsWritableStreamLocked(this)) {
1611
+ return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));
1612
+ }
1613
+ return WritableStreamAbort(this, reason);
1614
+ }
1615
+ /**
1616
+ * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its
1617
+ * close behavior. During this time any further attempts to write will fail (without erroring the stream).
1618
+ *
1619
+ * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream
1620
+ * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with
1621
+ * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.
1622
+ */
1623
+ close() {
1624
+ if (!IsWritableStream(this)) {
1625
+ return promiseRejectedWith(streamBrandCheckException$2('close'));
1626
+ }
1627
+ if (IsWritableStreamLocked(this)) {
1628
+ return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));
1629
+ }
1630
+ if (WritableStreamCloseQueuedOrInFlight(this)) {
1631
+ return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));
1632
+ }
1633
+ return WritableStreamClose(this);
1634
+ }
1635
+ /**
1636
+ * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream
1637
+ * is locked, no other writer can be acquired until this one is released.
1638
+ *
1639
+ * This functionality is especially useful for creating abstractions that desire the ability to write to a stream
1640
+ * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at
1641
+ * the same time, which would cause the resulting written data to be unpredictable and probably useless.
1642
+ */
1643
+ getWriter() {
1644
+ if (!IsWritableStream(this)) {
1645
+ throw streamBrandCheckException$2('getWriter');
1646
+ }
1647
+ return AcquireWritableStreamDefaultWriter(this);
1648
+ }
1649
+ }
1650
+ Object.defineProperties(WritableStream.prototype, {
1651
+ abort: { enumerable: true },
1652
+ close: { enumerable: true },
1653
+ getWriter: { enumerable: true },
1654
+ locked: { enumerable: true }
1655
+ });
1656
+ if (typeof SymbolPolyfill.toStringTag === 'symbol') {
1657
+ Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, {
1658
+ value: 'WritableStream',
1659
+ configurable: true
1660
+ });
1661
+ }
1662
+ // Abstract operations for the WritableStream.
1663
+ function AcquireWritableStreamDefaultWriter(stream) {
1664
+ return new WritableStreamDefaultWriter(stream);
1665
+ }
1666
+ // Throws if and only if startAlgorithm throws.
1667
+ function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
1668
+ const stream = Object.create(WritableStream.prototype);
1669
+ InitializeWritableStream(stream);
1670
+ const controller = Object.create(WritableStreamDefaultController.prototype);
1671
+ SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
1672
+ return stream;
1673
+ }
1674
+ function InitializeWritableStream(stream) {
1675
+ stream._state = 'writable';
1676
+ // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is
1677
+ // 'erroring' or 'errored'. May be set to an undefined value.
1678
+ stream._storedError = undefined;
1679
+ stream._writer = undefined;
1680
+ // Initialize to undefined first because the constructor of the controller checks this
1681
+ // variable to validate the caller.
1682
+ stream._writableStreamController = undefined;
1683
+ // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data
1684
+ // producer without waiting for the queued writes to finish.
1685
+ stream._writeRequests = new SimpleQueue();
1686
+ // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents
1687
+ // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.
1688
+ stream._inFlightWriteRequest = undefined;
1689
+ // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer
1690
+ // has been detached.
1691
+ stream._closeRequest = undefined;
1692
+ // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it
1693
+ // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.
1694
+ stream._inFlightCloseRequest = undefined;
1695
+ // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.
1696
+ stream._pendingAbortRequest = undefined;
1697
+ // The backpressure signal set by the controller.
1698
+ stream._backpressure = false;
1699
+ }
1700
+ function IsWritableStream(x) {
1701
+ if (!typeIsObject(x)) {
1702
+ return false;
1703
+ }
1704
+ if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {
1705
+ return false;
1706
+ }
1707
+ return true;
1708
+ }
1709
+ function IsWritableStreamLocked(stream) {
1710
+ if (stream._writer === undefined) {
1711
+ return false;
1712
+ }
1713
+ return true;
1714
+ }
1715
+ function WritableStreamAbort(stream, reason) {
1716
+ const state = stream._state;
1717
+ if (state === 'closed' || state === 'errored') {
1718
+ return promiseResolvedWith(undefined);
1719
+ }
1720
+ if (stream._pendingAbortRequest !== undefined) {
1721
+ return stream._pendingAbortRequest._promise;
1722
+ }
1723
+ let wasAlreadyErroring = false;
1724
+ if (state === 'erroring') {
1725
+ wasAlreadyErroring = true;
1726
+ // reason will not be used, so don't keep a reference to it.
1727
+ reason = undefined;
1728
+ }
1729
+ const promise = newPromise((resolve, reject) => {
1730
+ stream._pendingAbortRequest = {
1731
+ _promise: undefined,
1732
+ _resolve: resolve,
1733
+ _reject: reject,
1734
+ _reason: reason,
1735
+ _wasAlreadyErroring: wasAlreadyErroring
1736
+ };
1737
+ });
1738
+ stream._pendingAbortRequest._promise = promise;
1739
+ if (!wasAlreadyErroring) {
1740
+ WritableStreamStartErroring(stream, reason);
1741
+ }
1742
+ return promise;
1743
+ }
1744
+ function WritableStreamClose(stream) {
1745
+ const state = stream._state;
1746
+ if (state === 'closed' || state === 'errored') {
1747
+ return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`));
1748
+ }
1749
+ const promise = newPromise((resolve, reject) => {
1750
+ const closeRequest = {
1751
+ _resolve: resolve,
1752
+ _reject: reject
1753
+ };
1754
+ stream._closeRequest = closeRequest;
1755
+ });
1756
+ const writer = stream._writer;
1757
+ if (writer !== undefined && stream._backpressure && state === 'writable') {
1758
+ defaultWriterReadyPromiseResolve(writer);
1759
+ }
1760
+ WritableStreamDefaultControllerClose(stream._writableStreamController);
1761
+ return promise;
1762
+ }
1763
+ // WritableStream API exposed for controllers.
1764
+ function WritableStreamAddWriteRequest(stream) {
1765
+ const promise = newPromise((resolve, reject) => {
1766
+ const writeRequest = {
1767
+ _resolve: resolve,
1768
+ _reject: reject
1769
+ };
1770
+ stream._writeRequests.push(writeRequest);
1771
+ });
1772
+ return promise;
1773
+ }
1774
+ function WritableStreamDealWithRejection(stream, error) {
1775
+ const state = stream._state;
1776
+ if (state === 'writable') {
1777
+ WritableStreamStartErroring(stream, error);
1778
+ return;
1779
+ }
1780
+ WritableStreamFinishErroring(stream);
1781
+ }
1782
+ function WritableStreamStartErroring(stream, reason) {
1783
+ const controller = stream._writableStreamController;
1784
+ stream._state = 'erroring';
1785
+ stream._storedError = reason;
1786
+ const writer = stream._writer;
1787
+ if (writer !== undefined) {
1788
+ WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);
1789
+ }
1790
+ if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {
1791
+ WritableStreamFinishErroring(stream);
1792
+ }
1793
+ }
1794
+ function WritableStreamFinishErroring(stream) {
1795
+ stream._state = 'errored';
1796
+ stream._writableStreamController[ErrorSteps]();
1797
+ const storedError = stream._storedError;
1798
+ stream._writeRequests.forEach(writeRequest => {
1799
+ writeRequest._reject(storedError);
1800
+ });
1801
+ stream._writeRequests = new SimpleQueue();
1802
+ if (stream._pendingAbortRequest === undefined) {
1803
+ WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
1804
+ return;
1805
+ }
1806
+ const abortRequest = stream._pendingAbortRequest;
1807
+ stream._pendingAbortRequest = undefined;
1808
+ if (abortRequest._wasAlreadyErroring) {
1809
+ abortRequest._reject(storedError);
1810
+ WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
1811
+ return;
1812
+ }
1813
+ const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);
1814
+ uponPromise(promise, () => {
1815
+ abortRequest._resolve();
1816
+ WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
1817
+ }, (reason) => {
1818
+ abortRequest._reject(reason);
1819
+ WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
1820
+ });
1821
+ }
1822
+ function WritableStreamFinishInFlightWrite(stream) {
1823
+ stream._inFlightWriteRequest._resolve(undefined);
1824
+ stream._inFlightWriteRequest = undefined;
1825
+ }
1826
+ function WritableStreamFinishInFlightWriteWithError(stream, error) {
1827
+ stream._inFlightWriteRequest._reject(error);
1828
+ stream._inFlightWriteRequest = undefined;
1829
+ WritableStreamDealWithRejection(stream, error);
1830
+ }
1831
+ function WritableStreamFinishInFlightClose(stream) {
1832
+ stream._inFlightCloseRequest._resolve(undefined);
1833
+ stream._inFlightCloseRequest = undefined;
1834
+ const state = stream._state;
1835
+ if (state === 'erroring') {
1836
+ // The error was too late to do anything, so it is ignored.
1837
+ stream._storedError = undefined;
1838
+ if (stream._pendingAbortRequest !== undefined) {
1839
+ stream._pendingAbortRequest._resolve();
1840
+ stream._pendingAbortRequest = undefined;
1841
+ }
1842
+ }
1843
+ stream._state = 'closed';
1844
+ const writer = stream._writer;
1845
+ if (writer !== undefined) {
1846
+ defaultWriterClosedPromiseResolve(writer);
1847
+ }
1848
+ }
1849
+ function WritableStreamFinishInFlightCloseWithError(stream, error) {
1850
+ stream._inFlightCloseRequest._reject(error);
1851
+ stream._inFlightCloseRequest = undefined;
1852
+ // Never execute sink abort() after sink close().
1853
+ if (stream._pendingAbortRequest !== undefined) {
1854
+ stream._pendingAbortRequest._reject(error);
1855
+ stream._pendingAbortRequest = undefined;
1856
+ }
1857
+ WritableStreamDealWithRejection(stream, error);
1858
+ }
1859
+ // TODO(ricea): Fix alphabetical order.
1860
+ function WritableStreamCloseQueuedOrInFlight(stream) {
1861
+ if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {
1862
+ return false;
1863
+ }
1864
+ return true;
1865
+ }
1866
+ function WritableStreamHasOperationMarkedInFlight(stream) {
1867
+ if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {
1868
+ return false;
1869
+ }
1870
+ return true;
1871
+ }
1872
+ function WritableStreamMarkCloseRequestInFlight(stream) {
1873
+ stream._inFlightCloseRequest = stream._closeRequest;
1874
+ stream._closeRequest = undefined;
1875
+ }
1876
+ function WritableStreamMarkFirstWriteRequestInFlight(stream) {
1877
+ stream._inFlightWriteRequest = stream._writeRequests.shift();
1878
+ }
1879
+ function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) {
1880
+ if (stream._closeRequest !== undefined) {
1881
+ stream._closeRequest._reject(stream._storedError);
1882
+ stream._closeRequest = undefined;
1883
+ }
1884
+ const writer = stream._writer;
1885
+ if (writer !== undefined) {
1886
+ defaultWriterClosedPromiseReject(writer, stream._storedError);
1887
+ }
1888
+ }
1889
+ function WritableStreamUpdateBackpressure(stream, backpressure) {
1890
+ const writer = stream._writer;
1891
+ if (writer !== undefined && backpressure !== stream._backpressure) {
1892
+ if (backpressure) {
1893
+ defaultWriterReadyPromiseReset(writer);
1894
+ }
1895
+ else {
1896
+ defaultWriterReadyPromiseResolve(writer);
1897
+ }
1898
+ }
1899
+ stream._backpressure = backpressure;
1900
+ }
1901
+ /**
1902
+ * A default writer vended by a {@link WritableStream}.
1903
+ *
1904
+ * @public
1905
+ */
1906
+ class WritableStreamDefaultWriter {
1907
+ constructor(stream) {
1908
+ assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');
1909
+ assertWritableStream(stream, 'First parameter');
1910
+ if (IsWritableStreamLocked(stream)) {
1911
+ throw new TypeError('This stream has already been locked for exclusive writing by another writer');
1912
+ }
1913
+ this._ownerWritableStream = stream;
1914
+ stream._writer = this;
1915
+ const state = stream._state;
1916
+ if (state === 'writable') {
1917
+ if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {
1918
+ defaultWriterReadyPromiseInitialize(this);
1919
+ }
1920
+ else {
1921
+ defaultWriterReadyPromiseInitializeAsResolved(this);
1922
+ }
1923
+ defaultWriterClosedPromiseInitialize(this);
1924
+ }
1925
+ else if (state === 'erroring') {
1926
+ defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);
1927
+ defaultWriterClosedPromiseInitialize(this);
1928
+ }
1929
+ else if (state === 'closed') {
1930
+ defaultWriterReadyPromiseInitializeAsResolved(this);
1931
+ defaultWriterClosedPromiseInitializeAsResolved(this);
1932
+ }
1933
+ else {
1934
+ const storedError = stream._storedError;
1935
+ defaultWriterReadyPromiseInitializeAsRejected(this, storedError);
1936
+ defaultWriterClosedPromiseInitializeAsRejected(this, storedError);
1937
+ }
1938
+ }
1939
+ /**
1940
+ * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
1941
+ * the writer’s lock is released before the stream finishes closing.
1942
+ */
1943
+ get closed() {
1944
+ if (!IsWritableStreamDefaultWriter(this)) {
1945
+ return promiseRejectedWith(defaultWriterBrandCheckException('closed'));
1946
+ }
1947
+ return this._closedPromise;
1948
+ }
1949
+ /**
1950
+ * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.
1951
+ * A producer can use this information to determine the right amount of data to write.
1952
+ *
1953
+ * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort
1954
+ * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when
1955
+ * the writer’s lock is released.
1956
+ */
1957
+ get desiredSize() {
1958
+ if (!IsWritableStreamDefaultWriter(this)) {
1959
+ throw defaultWriterBrandCheckException('desiredSize');
1960
+ }
1961
+ if (this._ownerWritableStream === undefined) {
1962
+ throw defaultWriterLockException('desiredSize');
1963
+ }
1964
+ return WritableStreamDefaultWriterGetDesiredSize(this);
1965
+ }
1966
+ /**
1967
+ * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions
1968
+ * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips
1969
+ * back to zero or below, the getter will return a new promise that stays pending until the next transition.
1970
+ *
1971
+ * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become
1972
+ * rejected.
1973
+ */
1974
+ get ready() {
1975
+ if (!IsWritableStreamDefaultWriter(this)) {
1976
+ return promiseRejectedWith(defaultWriterBrandCheckException('ready'));
1977
+ }
1978
+ return this._readyPromise;
1979
+ }
1980
+ /**
1981
+ * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.
1982
+ */
1983
+ abort(reason = undefined) {
1984
+ if (!IsWritableStreamDefaultWriter(this)) {
1985
+ return promiseRejectedWith(defaultWriterBrandCheckException('abort'));
1986
+ }
1987
+ if (this._ownerWritableStream === undefined) {
1988
+ return promiseRejectedWith(defaultWriterLockException('abort'));
1989
+ }
1990
+ return WritableStreamDefaultWriterAbort(this, reason);
1991
+ }
1992
+ /**
1993
+ * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.
1994
+ */
1995
+ close() {
1996
+ if (!IsWritableStreamDefaultWriter(this)) {
1997
+ return promiseRejectedWith(defaultWriterBrandCheckException('close'));
1998
+ }
1999
+ const stream = this._ownerWritableStream;
2000
+ if (stream === undefined) {
2001
+ return promiseRejectedWith(defaultWriterLockException('close'));
2002
+ }
2003
+ if (WritableStreamCloseQueuedOrInFlight(stream)) {
2004
+ return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));
2005
+ }
2006
+ return WritableStreamDefaultWriterClose(this);
2007
+ }
2008
+ /**
2009
+ * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.
2010
+ * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from
2011
+ * now on; otherwise, the writer will appear closed.
2012
+ *
2013
+ * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the
2014
+ * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).
2015
+ * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents
2016
+ * other producers from writing in an interleaved manner.
2017
+ */
2018
+ releaseLock() {
2019
+ if (!IsWritableStreamDefaultWriter(this)) {
2020
+ throw defaultWriterBrandCheckException('releaseLock');
2021
+ }
2022
+ const stream = this._ownerWritableStream;
2023
+ if (stream === undefined) {
2024
+ return;
2025
+ }
2026
+ WritableStreamDefaultWriterRelease(this);
2027
+ }
2028
+ write(chunk = undefined) {
2029
+ if (!IsWritableStreamDefaultWriter(this)) {
2030
+ return promiseRejectedWith(defaultWriterBrandCheckException('write'));
2031
+ }
2032
+ if (this._ownerWritableStream === undefined) {
2033
+ return promiseRejectedWith(defaultWriterLockException('write to'));
2034
+ }
2035
+ return WritableStreamDefaultWriterWrite(this, chunk);
2036
+ }
2037
+ }
2038
+ Object.defineProperties(WritableStreamDefaultWriter.prototype, {
2039
+ abort: { enumerable: true },
2040
+ close: { enumerable: true },
2041
+ releaseLock: { enumerable: true },
2042
+ write: { enumerable: true },
2043
+ closed: { enumerable: true },
2044
+ desiredSize: { enumerable: true },
2045
+ ready: { enumerable: true }
2046
+ });
2047
+ if (typeof SymbolPolyfill.toStringTag === 'symbol') {
2048
+ Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, {
2049
+ value: 'WritableStreamDefaultWriter',
2050
+ configurable: true
2051
+ });
2052
+ }
2053
+ // Abstract operations for the WritableStreamDefaultWriter.
2054
+ function IsWritableStreamDefaultWriter(x) {
2055
+ if (!typeIsObject(x)) {
2056
+ return false;
2057
+ }
2058
+ if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {
2059
+ return false;
2060
+ }
2061
+ return true;
2062
+ }
2063
+ // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.
2064
+ function WritableStreamDefaultWriterAbort(writer, reason) {
2065
+ const stream = writer._ownerWritableStream;
2066
+ return WritableStreamAbort(stream, reason);
2067
+ }
2068
+ function WritableStreamDefaultWriterClose(writer) {
2069
+ const stream = writer._ownerWritableStream;
2070
+ return WritableStreamClose(stream);
2071
+ }
2072
+ function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) {
2073
+ const stream = writer._ownerWritableStream;
2074
+ const state = stream._state;
2075
+ if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {
2076
+ return promiseResolvedWith(undefined);
2077
+ }
2078
+ if (state === 'errored') {
2079
+ return promiseRejectedWith(stream._storedError);
2080
+ }
2081
+ return WritableStreamDefaultWriterClose(writer);
2082
+ }
2083
+ function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) {
2084
+ if (writer._closedPromiseState === 'pending') {
2085
+ defaultWriterClosedPromiseReject(writer, error);
2086
+ }
2087
+ else {
2088
+ defaultWriterClosedPromiseResetToRejected(writer, error);
2089
+ }
2090
+ }
2091
+ function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) {
2092
+ if (writer._readyPromiseState === 'pending') {
2093
+ defaultWriterReadyPromiseReject(writer, error);
2094
+ }
2095
+ else {
2096
+ defaultWriterReadyPromiseResetToRejected(writer, error);
2097
+ }
2098
+ }
2099
+ function WritableStreamDefaultWriterGetDesiredSize(writer) {
2100
+ const stream = writer._ownerWritableStream;
2101
+ const state = stream._state;
2102
+ if (state === 'errored' || state === 'erroring') {
2103
+ return null;
2104
+ }
2105
+ if (state === 'closed') {
2106
+ return 0;
2107
+ }
2108
+ return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);
2109
+ }
2110
+ function WritableStreamDefaultWriterRelease(writer) {
2111
+ const stream = writer._ownerWritableStream;
2112
+ const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`);
2113
+ WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);
2114
+ // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not
2115
+ // rejected until afterwards. This means that simply testing state will not work.
2116
+ WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);
2117
+ stream._writer = undefined;
2118
+ writer._ownerWritableStream = undefined;
2119
+ }
2120
+ function WritableStreamDefaultWriterWrite(writer, chunk) {
2121
+ const stream = writer._ownerWritableStream;
2122
+ const controller = stream._writableStreamController;
2123
+ const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);
2124
+ if (stream !== writer._ownerWritableStream) {
2125
+ return promiseRejectedWith(defaultWriterLockException('write to'));
2126
+ }
2127
+ const state = stream._state;
2128
+ if (state === 'errored') {
2129
+ return promiseRejectedWith(stream._storedError);
2130
+ }
2131
+ if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {
2132
+ return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));
2133
+ }
2134
+ if (state === 'erroring') {
2135
+ return promiseRejectedWith(stream._storedError);
2136
+ }
2137
+ const promise = WritableStreamAddWriteRequest(stream);
2138
+ WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);
2139
+ return promise;
2140
+ }
2141
+ const closeSentinel = {};
2142
+ /**
2143
+ * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.
2144
+ *
2145
+ * @public
2146
+ */
2147
+ class WritableStreamDefaultController {
2148
+ constructor() {
2149
+ throw new TypeError('Illegal constructor');
2150
+ }
2151
+ /**
2152
+ * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.
2153
+ *
2154
+ * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying
2155
+ * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the
2156
+ * normal lifecycle of interactions with the underlying sink.
2157
+ */
2158
+ error(e = undefined) {
2159
+ if (!IsWritableStreamDefaultController(this)) {
2160
+ throw new TypeError('WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController');
2161
+ }
2162
+ const state = this._controlledWritableStream._state;
2163
+ if (state !== 'writable') {
2164
+ // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so
2165
+ // just treat it as a no-op.
2166
+ return;
2167
+ }
2168
+ WritableStreamDefaultControllerError(this, e);
2169
+ }
2170
+ /** @internal */
2171
+ [AbortSteps](reason) {
2172
+ const result = this._abortAlgorithm(reason);
2173
+ WritableStreamDefaultControllerClearAlgorithms(this);
2174
+ return result;
2175
+ }
2176
+ /** @internal */
2177
+ [ErrorSteps]() {
2178
+ ResetQueue(this);
2179
+ }
2180
+ }
2181
+ Object.defineProperties(WritableStreamDefaultController.prototype, {
2182
+ error: { enumerable: true }
2183
+ });
2184
+ if (typeof SymbolPolyfill.toStringTag === 'symbol') {
2185
+ Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
2186
+ value: 'WritableStreamDefaultController',
2187
+ configurable: true
2188
+ });
2189
+ }
2190
+ // Abstract operations implementing interface required by the WritableStream.
2191
+ function IsWritableStreamDefaultController(x) {
2192
+ if (!typeIsObject(x)) {
2193
+ return false;
2194
+ }
2195
+ if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {
2196
+ return false;
2197
+ }
2198
+ return true;
2199
+ }
2200
+ function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) {
2201
+ controller._controlledWritableStream = stream;
2202
+ stream._writableStreamController = controller;
2203
+ // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.
2204
+ controller._queue = undefined;
2205
+ controller._queueTotalSize = undefined;
2206
+ ResetQueue(controller);
2207
+ controller._started = false;
2208
+ controller._strategySizeAlgorithm = sizeAlgorithm;
2209
+ controller._strategyHWM = highWaterMark;
2210
+ controller._writeAlgorithm = writeAlgorithm;
2211
+ controller._closeAlgorithm = closeAlgorithm;
2212
+ controller._abortAlgorithm = abortAlgorithm;
2213
+ const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
2214
+ WritableStreamUpdateBackpressure(stream, backpressure);
2215
+ const startResult = startAlgorithm();
2216
+ const startPromise = promiseResolvedWith(startResult);
2217
+ uponPromise(startPromise, () => {
2218
+ controller._started = true;
2219
+ WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
2220
+ }, r => {
2221
+ controller._started = true;
2222
+ WritableStreamDealWithRejection(stream, r);
2223
+ });
2224
+ }
2225
+ function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) {
2226
+ const controller = Object.create(WritableStreamDefaultController.prototype);
2227
+ let startAlgorithm = () => undefined;
2228
+ let writeAlgorithm = () => promiseResolvedWith(undefined);
2229
+ let closeAlgorithm = () => promiseResolvedWith(undefined);
2230
+ let abortAlgorithm = () => promiseResolvedWith(undefined);
2231
+ if (underlyingSink.start !== undefined) {
2232
+ startAlgorithm = () => underlyingSink.start(controller);
2233
+ }
2234
+ if (underlyingSink.write !== undefined) {
2235
+ writeAlgorithm = chunk => underlyingSink.write(chunk, controller);
2236
+ }
2237
+ if (underlyingSink.close !== undefined) {
2238
+ closeAlgorithm = () => underlyingSink.close();
2239
+ }
2240
+ if (underlyingSink.abort !== undefined) {
2241
+ abortAlgorithm = reason => underlyingSink.abort(reason);
2242
+ }
2243
+ SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
2244
+ }
2245
+ // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.
2246
+ function WritableStreamDefaultControllerClearAlgorithms(controller) {
2247
+ controller._writeAlgorithm = undefined;
2248
+ controller._closeAlgorithm = undefined;
2249
+ controller._abortAlgorithm = undefined;
2250
+ controller._strategySizeAlgorithm = undefined;
2251
+ }
2252
+ function WritableStreamDefaultControllerClose(controller) {
2253
+ EnqueueValueWithSize(controller, closeSentinel, 0);
2254
+ WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
2255
+ }
2256
+ function WritableStreamDefaultControllerGetChunkSize(controller, chunk) {
2257
+ try {
2258
+ return controller._strategySizeAlgorithm(chunk);
2259
+ }
2260
+ catch (chunkSizeE) {
2261
+ WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);
2262
+ return 1;
2263
+ }
2264
+ }
2265
+ function WritableStreamDefaultControllerGetDesiredSize(controller) {
2266
+ return controller._strategyHWM - controller._queueTotalSize;
2267
+ }
2268
+ function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) {
2269
+ try {
2270
+ EnqueueValueWithSize(controller, chunk, chunkSize);
2271
+ }
2272
+ catch (enqueueE) {
2273
+ WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);
2274
+ return;
2275
+ }
2276
+ const stream = controller._controlledWritableStream;
2277
+ if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {
2278
+ const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
2279
+ WritableStreamUpdateBackpressure(stream, backpressure);
2280
+ }
2281
+ WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
2282
+ }
2283
+ // Abstract operations for the WritableStreamDefaultController.
2284
+ function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) {
2285
+ const stream = controller._controlledWritableStream;
2286
+ if (!controller._started) {
2287
+ return;
2288
+ }
2289
+ if (stream._inFlightWriteRequest !== undefined) {
2290
+ return;
2291
+ }
2292
+ const state = stream._state;
2293
+ if (state === 'erroring') {
2294
+ WritableStreamFinishErroring(stream);
2295
+ return;
2296
+ }
2297
+ if (controller._queue.length === 0) {
2298
+ return;
2299
+ }
2300
+ const value = PeekQueueValue(controller);
2301
+ if (value === closeSentinel) {
2302
+ WritableStreamDefaultControllerProcessClose(controller);
2303
+ }
2304
+ else {
2305
+ WritableStreamDefaultControllerProcessWrite(controller, value);
2306
+ }
2307
+ }
2308
+ function WritableStreamDefaultControllerErrorIfNeeded(controller, error) {
2309
+ if (controller._controlledWritableStream._state === 'writable') {
2310
+ WritableStreamDefaultControllerError(controller, error);
2311
+ }
2312
+ }
2313
+ function WritableStreamDefaultControllerProcessClose(controller) {
2314
+ const stream = controller._controlledWritableStream;
2315
+ WritableStreamMarkCloseRequestInFlight(stream);
2316
+ DequeueValue(controller);
2317
+ const sinkClosePromise = controller._closeAlgorithm();
2318
+ WritableStreamDefaultControllerClearAlgorithms(controller);
2319
+ uponPromise(sinkClosePromise, () => {
2320
+ WritableStreamFinishInFlightClose(stream);
2321
+ }, reason => {
2322
+ WritableStreamFinishInFlightCloseWithError(stream, reason);
2323
+ });
2324
+ }
2325
+ function WritableStreamDefaultControllerProcessWrite(controller, chunk) {
2326
+ const stream = controller._controlledWritableStream;
2327
+ WritableStreamMarkFirstWriteRequestInFlight(stream);
2328
+ const sinkWritePromise = controller._writeAlgorithm(chunk);
2329
+ uponPromise(sinkWritePromise, () => {
2330
+ WritableStreamFinishInFlightWrite(stream);
2331
+ const state = stream._state;
2332
+ DequeueValue(controller);
2333
+ if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {
2334
+ const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
2335
+ WritableStreamUpdateBackpressure(stream, backpressure);
2336
+ }
2337
+ WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
2338
+ }, reason => {
2339
+ if (stream._state === 'writable') {
2340
+ WritableStreamDefaultControllerClearAlgorithms(controller);
2341
+ }
2342
+ WritableStreamFinishInFlightWriteWithError(stream, reason);
2343
+ });
2344
+ }
2345
+ function WritableStreamDefaultControllerGetBackpressure(controller) {
2346
+ const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);
2347
+ return desiredSize <= 0;
2348
+ }
2349
+ // A client of WritableStreamDefaultController may use these functions directly to bypass state check.
2350
+ function WritableStreamDefaultControllerError(controller, error) {
2351
+ const stream = controller._controlledWritableStream;
2352
+ WritableStreamDefaultControllerClearAlgorithms(controller);
2353
+ WritableStreamStartErroring(stream, error);
2354
+ }
2355
+ // Helper functions for the WritableStream.
2356
+ function streamBrandCheckException$2(name) {
2357
+ return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);
2358
+ }
2359
+ // Helper functions for the WritableStreamDefaultWriter.
2360
+ function defaultWriterBrandCheckException(name) {
2361
+ return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);
2362
+ }
2363
+ function defaultWriterLockException(name) {
2364
+ return new TypeError('Cannot ' + name + ' a stream using a released writer');
2365
+ }
2366
+ function defaultWriterClosedPromiseInitialize(writer) {
2367
+ writer._closedPromise = newPromise((resolve, reject) => {
2368
+ writer._closedPromise_resolve = resolve;
2369
+ writer._closedPromise_reject = reject;
2370
+ writer._closedPromiseState = 'pending';
2371
+ });
2372
+ }
2373
+ function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) {
2374
+ defaultWriterClosedPromiseInitialize(writer);
2375
+ defaultWriterClosedPromiseReject(writer, reason);
2376
+ }
2377
+ function defaultWriterClosedPromiseInitializeAsResolved(writer) {
2378
+ defaultWriterClosedPromiseInitialize(writer);
2379
+ defaultWriterClosedPromiseResolve(writer);
2380
+ }
2381
+ function defaultWriterClosedPromiseReject(writer, reason) {
2382
+ if (writer._closedPromise_reject === undefined) {
2383
+ return;
2384
+ }
2385
+ setPromiseIsHandledToTrue(writer._closedPromise);
2386
+ writer._closedPromise_reject(reason);
2387
+ writer._closedPromise_resolve = undefined;
2388
+ writer._closedPromise_reject = undefined;
2389
+ writer._closedPromiseState = 'rejected';
2390
+ }
2391
+ function defaultWriterClosedPromiseResetToRejected(writer, reason) {
2392
+ defaultWriterClosedPromiseInitializeAsRejected(writer, reason);
2393
+ }
2394
+ function defaultWriterClosedPromiseResolve(writer) {
2395
+ if (writer._closedPromise_resolve === undefined) {
2396
+ return;
2397
+ }
2398
+ writer._closedPromise_resolve(undefined);
2399
+ writer._closedPromise_resolve = undefined;
2400
+ writer._closedPromise_reject = undefined;
2401
+ writer._closedPromiseState = 'resolved';
2402
+ }
2403
+ function defaultWriterReadyPromiseInitialize(writer) {
2404
+ writer._readyPromise = newPromise((resolve, reject) => {
2405
+ writer._readyPromise_resolve = resolve;
2406
+ writer._readyPromise_reject = reject;
2407
+ });
2408
+ writer._readyPromiseState = 'pending';
2409
+ }
2410
+ function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) {
2411
+ defaultWriterReadyPromiseInitialize(writer);
2412
+ defaultWriterReadyPromiseReject(writer, reason);
2413
+ }
2414
+ function defaultWriterReadyPromiseInitializeAsResolved(writer) {
2415
+ defaultWriterReadyPromiseInitialize(writer);
2416
+ defaultWriterReadyPromiseResolve(writer);
2417
+ }
2418
+ function defaultWriterReadyPromiseReject(writer, reason) {
2419
+ if (writer._readyPromise_reject === undefined) {
2420
+ return;
2421
+ }
2422
+ setPromiseIsHandledToTrue(writer._readyPromise);
2423
+ writer._readyPromise_reject(reason);
2424
+ writer._readyPromise_resolve = undefined;
2425
+ writer._readyPromise_reject = undefined;
2426
+ writer._readyPromiseState = 'rejected';
2427
+ }
2428
+ function defaultWriterReadyPromiseReset(writer) {
2429
+ defaultWriterReadyPromiseInitialize(writer);
2430
+ }
2431
+ function defaultWriterReadyPromiseResetToRejected(writer, reason) {
2432
+ defaultWriterReadyPromiseInitializeAsRejected(writer, reason);
2433
+ }
2434
+ function defaultWriterReadyPromiseResolve(writer) {
2435
+ if (writer._readyPromise_resolve === undefined) {
2436
+ return;
2437
+ }
2438
+ writer._readyPromise_resolve(undefined);
2439
+ writer._readyPromise_resolve = undefined;
2440
+ writer._readyPromise_reject = undefined;
2441
+ writer._readyPromiseState = 'fulfilled';
2442
+ }
2443
+
2444
+ function isAbortSignal(value) {
2445
+ if (typeof value !== 'object' || value === null) {
2446
+ return false;
2447
+ }
2448
+ try {
2449
+ return typeof value.aborted === 'boolean';
2450
+ }
2451
+ catch (_a) {
2452
+ // AbortSignal.prototype.aborted throws if its brand check fails
2453
+ return false;
2454
+ }
2455
+ }
2456
+
2457
+ /// <reference lib="dom" />
2458
+ const NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined;
2459
+
2460
+ /// <reference types="node" />
2461
+ function isDOMExceptionConstructor(ctor) {
2462
+ if (!(typeof ctor === 'function' || typeof ctor === 'object')) {
2463
+ return false;
2464
+ }
2465
+ try {
2466
+ new ctor();
2467
+ return true;
2468
+ }
2469
+ catch (_a) {
2470
+ return false;
2471
+ }
2472
+ }
2473
+ function createDOMExceptionPolyfill() {
2474
+ // eslint-disable-next-line no-shadow
2475
+ const ctor = function DOMException(message, name) {
2476
+ this.message = message || '';
2477
+ this.name = name || 'Error';
2478
+ if (Error.captureStackTrace) {
2479
+ Error.captureStackTrace(this, this.constructor);
2480
+ }
2481
+ };
2482
+ ctor.prototype = Object.create(Error.prototype);
2483
+ Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });
2484
+ return ctor;
2485
+ }
2486
+ // eslint-disable-next-line no-redeclare
2487
+ const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();
2488
+
2489
+ function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) {
2490
+ const reader = AcquireReadableStreamDefaultReader(source);
2491
+ const writer = AcquireWritableStreamDefaultWriter(dest);
2492
+ source._disturbed = true;
2493
+ let shuttingDown = false;
2494
+ // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.
2495
+ let currentWrite = promiseResolvedWith(undefined);
2496
+ return newPromise((resolve, reject) => {
2497
+ let abortAlgorithm;
2498
+ if (signal !== undefined) {
2499
+ abortAlgorithm = () => {
2500
+ const error = new DOMException$1('Aborted', 'AbortError');
2501
+ const actions = [];
2502
+ if (!preventAbort) {
2503
+ actions.push(() => {
2504
+ if (dest._state === 'writable') {
2505
+ return WritableStreamAbort(dest, error);
2506
+ }
2507
+ return promiseResolvedWith(undefined);
2508
+ });
2509
+ }
2510
+ if (!preventCancel) {
2511
+ actions.push(() => {
2512
+ if (source._state === 'readable') {
2513
+ return ReadableStreamCancel(source, error);
2514
+ }
2515
+ return promiseResolvedWith(undefined);
2516
+ });
2517
+ }
2518
+ shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);
2519
+ };
2520
+ if (signal.aborted) {
2521
+ abortAlgorithm();
2522
+ return;
2523
+ }
2524
+ signal.addEventListener('abort', abortAlgorithm);
2525
+ }
2526
+ // Using reader and writer, read all chunks from this and write them to dest
2527
+ // - Backpressure must be enforced
2528
+ // - Shutdown must stop all activity
2529
+ function pipeLoop() {
2530
+ return newPromise((resolveLoop, rejectLoop) => {
2531
+ function next(done) {
2532
+ if (done) {
2533
+ resolveLoop();
2534
+ }
2535
+ else {
2536
+ // Use `PerformPromiseThen` instead of `uponPromise` to avoid
2537
+ // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers
2538
+ PerformPromiseThen(pipeStep(), next, rejectLoop);
2539
+ }
2540
+ }
2541
+ next(false);
2542
+ });
2543
+ }
2544
+ function pipeStep() {
2545
+ if (shuttingDown) {
2546
+ return promiseResolvedWith(true);
2547
+ }
2548
+ return PerformPromiseThen(writer._readyPromise, () => {
2549
+ return newPromise((resolveRead, rejectRead) => {
2550
+ ReadableStreamDefaultReaderRead(reader, {
2551
+ _chunkSteps: chunk => {
2552
+ currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);
2553
+ resolveRead(false);
2554
+ },
2555
+ _closeSteps: () => resolveRead(true),
2556
+ _errorSteps: rejectRead
2557
+ });
2558
+ });
2559
+ });
2560
+ }
2561
+ // Errors must be propagated forward
2562
+ isOrBecomesErrored(source, reader._closedPromise, storedError => {
2563
+ if (!preventAbort) {
2564
+ shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);
2565
+ }
2566
+ else {
2567
+ shutdown(true, storedError);
2568
+ }
2569
+ });
2570
+ // Errors must be propagated backward
2571
+ isOrBecomesErrored(dest, writer._closedPromise, storedError => {
2572
+ if (!preventCancel) {
2573
+ shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);
2574
+ }
2575
+ else {
2576
+ shutdown(true, storedError);
2577
+ }
2578
+ });
2579
+ // Closing must be propagated forward
2580
+ isOrBecomesClosed(source, reader._closedPromise, () => {
2581
+ if (!preventClose) {
2582
+ shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));
2583
+ }
2584
+ else {
2585
+ shutdown();
2586
+ }
2587
+ });
2588
+ // Closing must be propagated backward
2589
+ if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {
2590
+ const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');
2591
+ if (!preventCancel) {
2592
+ shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);
2593
+ }
2594
+ else {
2595
+ shutdown(true, destClosed);
2596
+ }
2597
+ }
2598
+ setPromiseIsHandledToTrue(pipeLoop());
2599
+ function waitForWritesToFinish() {
2600
+ // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait
2601
+ // for that too.
2602
+ const oldCurrentWrite = currentWrite;
2603
+ return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined);
2604
+ }
2605
+ function isOrBecomesErrored(stream, promise, action) {
2606
+ if (stream._state === 'errored') {
2607
+ action(stream._storedError);
2608
+ }
2609
+ else {
2610
+ uponRejection(promise, action);
2611
+ }
2612
+ }
2613
+ function isOrBecomesClosed(stream, promise, action) {
2614
+ if (stream._state === 'closed') {
2615
+ action();
2616
+ }
2617
+ else {
2618
+ uponFulfillment(promise, action);
2619
+ }
2620
+ }
2621
+ function shutdownWithAction(action, originalIsError, originalError) {
2622
+ if (shuttingDown) {
2623
+ return;
2624
+ }
2625
+ shuttingDown = true;
2626
+ if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {
2627
+ uponFulfillment(waitForWritesToFinish(), doTheRest);
2628
+ }
2629
+ else {
2630
+ doTheRest();
2631
+ }
2632
+ function doTheRest() {
2633
+ uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError));
2634
+ }
2635
+ }
2636
+ function shutdown(isError, error) {
2637
+ if (shuttingDown) {
2638
+ return;
2639
+ }
2640
+ shuttingDown = true;
2641
+ if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {
2642
+ uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));
2643
+ }
2644
+ else {
2645
+ finalize(isError, error);
2646
+ }
2647
+ }
2648
+ function finalize(isError, error) {
2649
+ WritableStreamDefaultWriterRelease(writer);
2650
+ ReadableStreamReaderGenericRelease(reader);
2651
+ if (signal !== undefined) {
2652
+ signal.removeEventListener('abort', abortAlgorithm);
2653
+ }
2654
+ if (isError) {
2655
+ reject(error);
2656
+ }
2657
+ else {
2658
+ resolve(undefined);
2659
+ }
2660
+ }
2661
+ });
2662
+ }
2663
+
2664
+ /**
2665
+ * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.
2666
+ *
2667
+ * @public
2668
+ */
2669
+ class ReadableStreamDefaultController {
2670
+ constructor() {
2671
+ throw new TypeError('Illegal constructor');
2672
+ }
2673
+ /**
2674
+ * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
2675
+ * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.
2676
+ */
2677
+ get desiredSize() {
2678
+ if (!IsReadableStreamDefaultController(this)) {
2679
+ throw defaultControllerBrandCheckException$1('desiredSize');
2680
+ }
2681
+ return ReadableStreamDefaultControllerGetDesiredSize(this);
2682
+ }
2683
+ /**
2684
+ * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
2685
+ * the stream, but once those are read, the stream will become closed.
2686
+ */
2687
+ close() {
2688
+ if (!IsReadableStreamDefaultController(this)) {
2689
+ throw defaultControllerBrandCheckException$1('close');
2690
+ }
2691
+ if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {
2692
+ throw new TypeError('The stream is not in a state that permits close');
2693
+ }
2694
+ ReadableStreamDefaultControllerClose(this);
2695
+ }
2696
+ enqueue(chunk = undefined) {
2697
+ if (!IsReadableStreamDefaultController(this)) {
2698
+ throw defaultControllerBrandCheckException$1('enqueue');
2699
+ }
2700
+ if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {
2701
+ throw new TypeError('The stream is not in a state that permits enqueue');
2702
+ }
2703
+ return ReadableStreamDefaultControllerEnqueue(this, chunk);
2704
+ }
2705
+ /**
2706
+ * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
2707
+ */
2708
+ error(e = undefined) {
2709
+ if (!IsReadableStreamDefaultController(this)) {
2710
+ throw defaultControllerBrandCheckException$1('error');
2711
+ }
2712
+ ReadableStreamDefaultControllerError(this, e);
2713
+ }
2714
+ /** @internal */
2715
+ [CancelSteps](reason) {
2716
+ ResetQueue(this);
2717
+ const result = this._cancelAlgorithm(reason);
2718
+ ReadableStreamDefaultControllerClearAlgorithms(this);
2719
+ return result;
2720
+ }
2721
+ /** @internal */
2722
+ [PullSteps](readRequest) {
2723
+ const stream = this._controlledReadableStream;
2724
+ if (this._queue.length > 0) {
2725
+ const chunk = DequeueValue(this);
2726
+ if (this._closeRequested && this._queue.length === 0) {
2727
+ ReadableStreamDefaultControllerClearAlgorithms(this);
2728
+ ReadableStreamClose(stream);
2729
+ }
2730
+ else {
2731
+ ReadableStreamDefaultControllerCallPullIfNeeded(this);
2732
+ }
2733
+ readRequest._chunkSteps(chunk);
2734
+ }
2735
+ else {
2736
+ ReadableStreamAddReadRequest(stream, readRequest);
2737
+ ReadableStreamDefaultControllerCallPullIfNeeded(this);
2738
+ }
2739
+ }
2740
+ }
2741
+ Object.defineProperties(ReadableStreamDefaultController.prototype, {
2742
+ close: { enumerable: true },
2743
+ enqueue: { enumerable: true },
2744
+ error: { enumerable: true },
2745
+ desiredSize: { enumerable: true }
2746
+ });
2747
+ if (typeof SymbolPolyfill.toStringTag === 'symbol') {
2748
+ Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
2749
+ value: 'ReadableStreamDefaultController',
2750
+ configurable: true
2751
+ });
2752
+ }
2753
+ // Abstract operations for the ReadableStreamDefaultController.
2754
+ function IsReadableStreamDefaultController(x) {
2755
+ if (!typeIsObject(x)) {
2756
+ return false;
2757
+ }
2758
+ if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {
2759
+ return false;
2760
+ }
2761
+ return true;
2762
+ }
2763
+ function ReadableStreamDefaultControllerCallPullIfNeeded(controller) {
2764
+ const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);
2765
+ if (!shouldPull) {
2766
+ return;
2767
+ }
2768
+ if (controller._pulling) {
2769
+ controller._pullAgain = true;
2770
+ return;
2771
+ }
2772
+ controller._pulling = true;
2773
+ const pullPromise = controller._pullAlgorithm();
2774
+ uponPromise(pullPromise, () => {
2775
+ controller._pulling = false;
2776
+ if (controller._pullAgain) {
2777
+ controller._pullAgain = false;
2778
+ ReadableStreamDefaultControllerCallPullIfNeeded(controller);
2779
+ }
2780
+ }, e => {
2781
+ ReadableStreamDefaultControllerError(controller, e);
2782
+ });
2783
+ }
2784
+ function ReadableStreamDefaultControllerShouldCallPull(controller) {
2785
+ const stream = controller._controlledReadableStream;
2786
+ if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
2787
+ return false;
2788
+ }
2789
+ if (!controller._started) {
2790
+ return false;
2791
+ }
2792
+ if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
2793
+ return true;
2794
+ }
2795
+ const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);
2796
+ if (desiredSize > 0) {
2797
+ return true;
2798
+ }
2799
+ return false;
2800
+ }
2801
+ function ReadableStreamDefaultControllerClearAlgorithms(controller) {
2802
+ controller._pullAlgorithm = undefined;
2803
+ controller._cancelAlgorithm = undefined;
2804
+ controller._strategySizeAlgorithm = undefined;
2805
+ }
2806
+ // A client of ReadableStreamDefaultController may use these functions directly to bypass state check.
2807
+ function ReadableStreamDefaultControllerClose(controller) {
2808
+ if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
2809
+ return;
2810
+ }
2811
+ const stream = controller._controlledReadableStream;
2812
+ controller._closeRequested = true;
2813
+ if (controller._queue.length === 0) {
2814
+ ReadableStreamDefaultControllerClearAlgorithms(controller);
2815
+ ReadableStreamClose(stream);
2816
+ }
2817
+ }
2818
+ function ReadableStreamDefaultControllerEnqueue(controller, chunk) {
2819
+ if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
2820
+ return;
2821
+ }
2822
+ const stream = controller._controlledReadableStream;
2823
+ if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
2824
+ ReadableStreamFulfillReadRequest(stream, chunk, false);
2825
+ }
2826
+ else {
2827
+ let chunkSize;
2828
+ try {
2829
+ chunkSize = controller._strategySizeAlgorithm(chunk);
2830
+ }
2831
+ catch (chunkSizeE) {
2832
+ ReadableStreamDefaultControllerError(controller, chunkSizeE);
2833
+ throw chunkSizeE;
2834
+ }
2835
+ try {
2836
+ EnqueueValueWithSize(controller, chunk, chunkSize);
2837
+ }
2838
+ catch (enqueueE) {
2839
+ ReadableStreamDefaultControllerError(controller, enqueueE);
2840
+ throw enqueueE;
2841
+ }
2842
+ }
2843
+ ReadableStreamDefaultControllerCallPullIfNeeded(controller);
2844
+ }
2845
+ function ReadableStreamDefaultControllerError(controller, e) {
2846
+ const stream = controller._controlledReadableStream;
2847
+ if (stream._state !== 'readable') {
2848
+ return;
2849
+ }
2850
+ ResetQueue(controller);
2851
+ ReadableStreamDefaultControllerClearAlgorithms(controller);
2852
+ ReadableStreamError(stream, e);
2853
+ }
2854
+ function ReadableStreamDefaultControllerGetDesiredSize(controller) {
2855
+ const state = controller._controlledReadableStream._state;
2856
+ if (state === 'errored') {
2857
+ return null;
2858
+ }
2859
+ if (state === 'closed') {
2860
+ return 0;
2861
+ }
2862
+ return controller._strategyHWM - controller._queueTotalSize;
2863
+ }
2864
+ // This is used in the implementation of TransformStream.
2865
+ function ReadableStreamDefaultControllerHasBackpressure(controller) {
2866
+ if (ReadableStreamDefaultControllerShouldCallPull(controller)) {
2867
+ return false;
2868
+ }
2869
+ return true;
2870
+ }
2871
+ function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) {
2872
+ const state = controller._controlledReadableStream._state;
2873
+ if (!controller._closeRequested && state === 'readable') {
2874
+ return true;
2875
+ }
2876
+ return false;
2877
+ }
2878
+ function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) {
2879
+ controller._controlledReadableStream = stream;
2880
+ controller._queue = undefined;
2881
+ controller._queueTotalSize = undefined;
2882
+ ResetQueue(controller);
2883
+ controller._started = false;
2884
+ controller._closeRequested = false;
2885
+ controller._pullAgain = false;
2886
+ controller._pulling = false;
2887
+ controller._strategySizeAlgorithm = sizeAlgorithm;
2888
+ controller._strategyHWM = highWaterMark;
2889
+ controller._pullAlgorithm = pullAlgorithm;
2890
+ controller._cancelAlgorithm = cancelAlgorithm;
2891
+ stream._readableStreamController = controller;
2892
+ const startResult = startAlgorithm();
2893
+ uponPromise(promiseResolvedWith(startResult), () => {
2894
+ controller._started = true;
2895
+ ReadableStreamDefaultControllerCallPullIfNeeded(controller);
2896
+ }, r => {
2897
+ ReadableStreamDefaultControllerError(controller, r);
2898
+ });
2899
+ }
2900
+ function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) {
2901
+ const controller = Object.create(ReadableStreamDefaultController.prototype);
2902
+ let startAlgorithm = () => undefined;
2903
+ let pullAlgorithm = () => promiseResolvedWith(undefined);
2904
+ let cancelAlgorithm = () => promiseResolvedWith(undefined);
2905
+ if (underlyingSource.start !== undefined) {
2906
+ startAlgorithm = () => underlyingSource.start(controller);
2907
+ }
2908
+ if (underlyingSource.pull !== undefined) {
2909
+ pullAlgorithm = () => underlyingSource.pull(controller);
2910
+ }
2911
+ if (underlyingSource.cancel !== undefined) {
2912
+ cancelAlgorithm = reason => underlyingSource.cancel(reason);
2913
+ }
2914
+ SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
2915
+ }
2916
+ // Helper functions for the ReadableStreamDefaultController.
2917
+ function defaultControllerBrandCheckException$1(name) {
2918
+ return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);
2919
+ }
2920
+
2921
+ function ReadableStreamTee(stream, cloneForBranch2) {
2922
+ const reader = AcquireReadableStreamDefaultReader(stream);
2923
+ let reading = false;
2924
+ let canceled1 = false;
2925
+ let canceled2 = false;
2926
+ let reason1;
2927
+ let reason2;
2928
+ let branch1;
2929
+ let branch2;
2930
+ let resolveCancelPromise;
2931
+ const cancelPromise = newPromise(resolve => {
2932
+ resolveCancelPromise = resolve;
2933
+ });
2934
+ function pullAlgorithm() {
2935
+ if (reading) {
2936
+ return promiseResolvedWith(undefined);
2937
+ }
2938
+ reading = true;
2939
+ const readRequest = {
2940
+ _chunkSteps: value => {
2941
+ // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
2942
+ // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
2943
+ // successful synchronously-available reads get ahead of asynchronously-available errors.
2944
+ queueMicrotask(() => {
2945
+ reading = false;
2946
+ const value1 = value;
2947
+ const value2 = value;
2948
+ // There is no way to access the cloning code right now in the reference implementation.
2949
+ // If we add one then we'll need an implementation for serializable objects.
2950
+ // if (!canceled2 && cloneForBranch2) {
2951
+ // value2 = StructuredDeserialize(StructuredSerialize(value2));
2952
+ // }
2953
+ if (!canceled1) {
2954
+ ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, value1);
2955
+ }
2956
+ if (!canceled2) {
2957
+ ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, value2);
2958
+ }
2959
+ });
2960
+ },
2961
+ _closeSteps: () => {
2962
+ reading = false;
2963
+ if (!canceled1) {
2964
+ ReadableStreamDefaultControllerClose(branch1._readableStreamController);
2965
+ }
2966
+ if (!canceled2) {
2967
+ ReadableStreamDefaultControllerClose(branch2._readableStreamController);
2968
+ }
2969
+ if (!canceled1 || !canceled2) {
2970
+ resolveCancelPromise(undefined);
2971
+ }
2972
+ },
2973
+ _errorSteps: () => {
2974
+ reading = false;
2975
+ }
2976
+ };
2977
+ ReadableStreamDefaultReaderRead(reader, readRequest);
2978
+ return promiseResolvedWith(undefined);
2979
+ }
2980
+ function cancel1Algorithm(reason) {
2981
+ canceled1 = true;
2982
+ reason1 = reason;
2983
+ if (canceled2) {
2984
+ const compositeReason = CreateArrayFromList([reason1, reason2]);
2985
+ const cancelResult = ReadableStreamCancel(stream, compositeReason);
2986
+ resolveCancelPromise(cancelResult);
2987
+ }
2988
+ return cancelPromise;
2989
+ }
2990
+ function cancel2Algorithm(reason) {
2991
+ canceled2 = true;
2992
+ reason2 = reason;
2993
+ if (canceled1) {
2994
+ const compositeReason = CreateArrayFromList([reason1, reason2]);
2995
+ const cancelResult = ReadableStreamCancel(stream, compositeReason);
2996
+ resolveCancelPromise(cancelResult);
2997
+ }
2998
+ return cancelPromise;
2999
+ }
3000
+ function startAlgorithm() {
3001
+ // do nothing
3002
+ }
3003
+ branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);
3004
+ branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);
3005
+ uponRejection(reader._closedPromise, (r) => {
3006
+ ReadableStreamDefaultControllerError(branch1._readableStreamController, r);
3007
+ ReadableStreamDefaultControllerError(branch2._readableStreamController, r);
3008
+ if (!canceled1 || !canceled2) {
3009
+ resolveCancelPromise(undefined);
3010
+ }
3011
+ });
3012
+ return [branch1, branch2];
3013
+ }
3014
+
3015
+ function convertUnderlyingDefaultOrByteSource(source, context) {
3016
+ assertDictionary(source, context);
3017
+ const original = source;
3018
+ const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize;
3019
+ const cancel = original === null || original === void 0 ? void 0 : original.cancel;
3020
+ const pull = original === null || original === void 0 ? void 0 : original.pull;
3021
+ const start = original === null || original === void 0 ? void 0 : original.start;
3022
+ const type = original === null || original === void 0 ? void 0 : original.type;
3023
+ return {
3024
+ autoAllocateChunkSize: autoAllocateChunkSize === undefined ?
3025
+ undefined :
3026
+ convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`),
3027
+ cancel: cancel === undefined ?
3028
+ undefined :
3029
+ convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`),
3030
+ pull: pull === undefined ?
3031
+ undefined :
3032
+ convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`),
3033
+ start: start === undefined ?
3034
+ undefined :
3035
+ convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`),
3036
+ type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)
3037
+ };
3038
+ }
3039
+ function convertUnderlyingSourceCancelCallback(fn, original, context) {
3040
+ assertFunction(fn, context);
3041
+ return (reason) => promiseCall(fn, original, [reason]);
3042
+ }
3043
+ function convertUnderlyingSourcePullCallback(fn, original, context) {
3044
+ assertFunction(fn, context);
3045
+ return (controller) => promiseCall(fn, original, [controller]);
3046
+ }
3047
+ function convertUnderlyingSourceStartCallback(fn, original, context) {
3048
+ assertFunction(fn, context);
3049
+ return (controller) => reflectCall(fn, original, [controller]);
3050
+ }
3051
+ function convertReadableStreamType(type, context) {
3052
+ type = `${type}`;
3053
+ if (type !== 'bytes') {
3054
+ throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);
3055
+ }
3056
+ return type;
3057
+ }
3058
+
3059
+ function convertReaderOptions(options, context) {
3060
+ assertDictionary(options, context);
3061
+ const mode = options === null || options === void 0 ? void 0 : options.mode;
3062
+ return {
3063
+ mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)
3064
+ };
3065
+ }
3066
+ function convertReadableStreamReaderMode(mode, context) {
3067
+ mode = `${mode}`;
3068
+ if (mode !== 'byob') {
3069
+ throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);
3070
+ }
3071
+ return mode;
3072
+ }
3073
+
3074
+ function convertIteratorOptions(options, context) {
3075
+ assertDictionary(options, context);
3076
+ const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
3077
+ return { preventCancel: Boolean(preventCancel) };
3078
+ }
3079
+
3080
+ function convertPipeOptions(options, context) {
3081
+ assertDictionary(options, context);
3082
+ const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort;
3083
+ const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
3084
+ const preventClose = options === null || options === void 0 ? void 0 : options.preventClose;
3085
+ const signal = options === null || options === void 0 ? void 0 : options.signal;
3086
+ if (signal !== undefined) {
3087
+ assertAbortSignal(signal, `${context} has member 'signal' that`);
3088
+ }
3089
+ return {
3090
+ preventAbort: Boolean(preventAbort),
3091
+ preventCancel: Boolean(preventCancel),
3092
+ preventClose: Boolean(preventClose),
3093
+ signal
3094
+ };
3095
+ }
3096
+ function assertAbortSignal(signal, context) {
3097
+ if (!isAbortSignal(signal)) {
3098
+ throw new TypeError(`${context} is not an AbortSignal.`);
3099
+ }
3100
+ }
3101
+
3102
+ function convertReadableWritablePair(pair, context) {
3103
+ assertDictionary(pair, context);
3104
+ const readable = pair === null || pair === void 0 ? void 0 : pair.readable;
3105
+ assertRequiredField(readable, 'readable', 'ReadableWritablePair');
3106
+ assertReadableStream(readable, `${context} has member 'readable' that`);
3107
+ const writable = pair === null || pair === void 0 ? void 0 : pair.writable;
3108
+ assertRequiredField(writable, 'writable', 'ReadableWritablePair');
3109
+ assertWritableStream(writable, `${context} has member 'writable' that`);
3110
+ return { readable, writable };
3111
+ }
3112
+
3113
+ /**
3114
+ * A readable stream represents a source of data, from which you can read.
3115
+ *
3116
+ * @public
3117
+ */
3118
+ class ReadableStream {
3119
+ constructor(rawUnderlyingSource = {}, rawStrategy = {}) {
3120
+ if (rawUnderlyingSource === undefined) {
3121
+ rawUnderlyingSource = null;
3122
+ }
3123
+ else {
3124
+ assertObject(rawUnderlyingSource, 'First parameter');
3125
+ }
3126
+ const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');
3127
+ const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');
3128
+ InitializeReadableStream(this);
3129
+ if (underlyingSource.type === 'bytes') {
3130
+ if (strategy.size !== undefined) {
3131
+ throw new RangeError('The strategy for a byte stream cannot have a size function');
3132
+ }
3133
+ const highWaterMark = ExtractHighWaterMark(strategy, 0);
3134
+ SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark);
3135
+ }
3136
+ else {
3137
+ const sizeAlgorithm = ExtractSizeAlgorithm(strategy);
3138
+ const highWaterMark = ExtractHighWaterMark(strategy, 1);
3139
+ SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm);
3140
+ }
3141
+ }
3142
+ /**
3143
+ * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.
3144
+ */
3145
+ get locked() {
3146
+ if (!IsReadableStream(this)) {
3147
+ throw streamBrandCheckException$1('locked');
3148
+ }
3149
+ return IsReadableStreamLocked(this);
3150
+ }
3151
+ /**
3152
+ * Cancels the stream, signaling a loss of interest in the stream by a consumer.
3153
+ *
3154
+ * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}
3155
+ * method, which might or might not use it.
3156
+ */
3157
+ cancel(reason = undefined) {
3158
+ if (!IsReadableStream(this)) {
3159
+ return promiseRejectedWith(streamBrandCheckException$1('cancel'));
3160
+ }
3161
+ if (IsReadableStreamLocked(this)) {
3162
+ return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));
3163
+ }
3164
+ return ReadableStreamCancel(this, reason);
3165
+ }
3166
+ getReader(rawOptions = undefined) {
3167
+ if (!IsReadableStream(this)) {
3168
+ throw streamBrandCheckException$1('getReader');
3169
+ }
3170
+ const options = convertReaderOptions(rawOptions, 'First parameter');
3171
+ if (options.mode === undefined) {
3172
+ return AcquireReadableStreamDefaultReader(this);
3173
+ }
3174
+ return AcquireReadableStreamBYOBReader(this);
3175
+ }
3176
+ pipeThrough(rawTransform, rawOptions = {}) {
3177
+ if (!IsReadableStream(this)) {
3178
+ throw streamBrandCheckException$1('pipeThrough');
3179
+ }
3180
+ assertRequiredArgument(rawTransform, 1, 'pipeThrough');
3181
+ const transform = convertReadableWritablePair(rawTransform, 'First parameter');
3182
+ const options = convertPipeOptions(rawOptions, 'Second parameter');
3183
+ if (IsReadableStreamLocked(this)) {
3184
+ throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');
3185
+ }
3186
+ if (IsWritableStreamLocked(transform.writable)) {
3187
+ throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');
3188
+ }
3189
+ const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal);
3190
+ setPromiseIsHandledToTrue(promise);
3191
+ return transform.readable;
3192
+ }
3193
+ pipeTo(destination, rawOptions = {}) {
3194
+ if (!IsReadableStream(this)) {
3195
+ return promiseRejectedWith(streamBrandCheckException$1('pipeTo'));
3196
+ }
3197
+ if (destination === undefined) {
3198
+ return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);
3199
+ }
3200
+ if (!IsWritableStream(destination)) {
3201
+ return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`));
3202
+ }
3203
+ let options;
3204
+ try {
3205
+ options = convertPipeOptions(rawOptions, 'Second parameter');
3206
+ }
3207
+ catch (e) {
3208
+ return promiseRejectedWith(e);
3209
+ }
3210
+ if (IsReadableStreamLocked(this)) {
3211
+ return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream'));
3212
+ }
3213
+ if (IsWritableStreamLocked(destination)) {
3214
+ return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream'));
3215
+ }
3216
+ return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal);
3217
+ }
3218
+ /**
3219
+ * Tees this readable stream, returning a two-element array containing the two resulting branches as
3220
+ * new {@link ReadableStream} instances.
3221
+ *
3222
+ * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.
3223
+ * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be
3224
+ * propagated to the stream's underlying source.
3225
+ *
3226
+ * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,
3227
+ * this could allow interference between the two branches.
3228
+ */
3229
+ tee() {
3230
+ if (!IsReadableStream(this)) {
3231
+ throw streamBrandCheckException$1('tee');
3232
+ }
3233
+ const branches = ReadableStreamTee(this);
3234
+ return CreateArrayFromList(branches);
3235
+ }
3236
+ values(rawOptions = undefined) {
3237
+ if (!IsReadableStream(this)) {
3238
+ throw streamBrandCheckException$1('values');
3239
+ }
3240
+ const options = convertIteratorOptions(rawOptions, 'First parameter');
3241
+ return AcquireReadableStreamAsyncIterator(this, options.preventCancel);
3242
+ }
3243
+ }
3244
+ Object.defineProperties(ReadableStream.prototype, {
3245
+ cancel: { enumerable: true },
3246
+ getReader: { enumerable: true },
3247
+ pipeThrough: { enumerable: true },
3248
+ pipeTo: { enumerable: true },
3249
+ tee: { enumerable: true },
3250
+ values: { enumerable: true },
3251
+ locked: { enumerable: true }
3252
+ });
3253
+ if (typeof SymbolPolyfill.toStringTag === 'symbol') {
3254
+ Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, {
3255
+ value: 'ReadableStream',
3256
+ configurable: true
3257
+ });
3258
+ }
3259
+ if (typeof SymbolPolyfill.asyncIterator === 'symbol') {
3260
+ Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, {
3261
+ value: ReadableStream.prototype.values,
3262
+ writable: true,
3263
+ configurable: true
3264
+ });
3265
+ }
3266
+ // Abstract operations for the ReadableStream.
3267
+ // Throws if and only if startAlgorithm throws.
3268
+ function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
3269
+ const stream = Object.create(ReadableStream.prototype);
3270
+ InitializeReadableStream(stream);
3271
+ const controller = Object.create(ReadableStreamDefaultController.prototype);
3272
+ SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
3273
+ return stream;
3274
+ }
3275
+ function InitializeReadableStream(stream) {
3276
+ stream._state = 'readable';
3277
+ stream._reader = undefined;
3278
+ stream._storedError = undefined;
3279
+ stream._disturbed = false;
3280
+ }
3281
+ function IsReadableStream(x) {
3282
+ if (!typeIsObject(x)) {
3283
+ return false;
3284
+ }
3285
+ if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {
3286
+ return false;
3287
+ }
3288
+ return true;
3289
+ }
3290
+ function IsReadableStreamLocked(stream) {
3291
+ if (stream._reader === undefined) {
3292
+ return false;
3293
+ }
3294
+ return true;
3295
+ }
3296
+ // ReadableStream API exposed for controllers.
3297
+ function ReadableStreamCancel(stream, reason) {
3298
+ stream._disturbed = true;
3299
+ if (stream._state === 'closed') {
3300
+ return promiseResolvedWith(undefined);
3301
+ }
3302
+ if (stream._state === 'errored') {
3303
+ return promiseRejectedWith(stream._storedError);
3304
+ }
3305
+ ReadableStreamClose(stream);
3306
+ const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);
3307
+ return transformPromiseWith(sourceCancelPromise, noop);
3308
+ }
3309
+ function ReadableStreamClose(stream) {
3310
+ stream._state = 'closed';
3311
+ const reader = stream._reader;
3312
+ if (reader === undefined) {
3313
+ return;
3314
+ }
3315
+ defaultReaderClosedPromiseResolve(reader);
3316
+ if (IsReadableStreamDefaultReader(reader)) {
3317
+ reader._readRequests.forEach(readRequest => {
3318
+ readRequest._closeSteps();
3319
+ });
3320
+ reader._readRequests = new SimpleQueue();
3321
+ }
3322
+ }
3323
+ function ReadableStreamError(stream, e) {
3324
+ stream._state = 'errored';
3325
+ stream._storedError = e;
3326
+ const reader = stream._reader;
3327
+ if (reader === undefined) {
3328
+ return;
3329
+ }
3330
+ defaultReaderClosedPromiseReject(reader, e);
3331
+ if (IsReadableStreamDefaultReader(reader)) {
3332
+ reader._readRequests.forEach(readRequest => {
3333
+ readRequest._errorSteps(e);
3334
+ });
3335
+ reader._readRequests = new SimpleQueue();
3336
+ }
3337
+ else {
3338
+ reader._readIntoRequests.forEach(readIntoRequest => {
3339
+ readIntoRequest._errorSteps(e);
3340
+ });
3341
+ reader._readIntoRequests = new SimpleQueue();
3342
+ }
3343
+ }
3344
+ // Helper functions for the ReadableStream.
3345
+ function streamBrandCheckException$1(name) {
3346
+ return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);
3347
+ }
3348
+
3349
+ function convertQueuingStrategyInit(init, context) {
3350
+ assertDictionary(init, context);
3351
+ const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;
3352
+ assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');
3353
+ return {
3354
+ highWaterMark: convertUnrestrictedDouble(highWaterMark)
3355
+ };
3356
+ }
3357
+
3358
+ const byteLengthSizeFunction = function size(chunk) {
3359
+ return chunk.byteLength;
3360
+ };
3361
+ /**
3362
+ * A queuing strategy that counts the number of bytes in each chunk.
3363
+ *
3364
+ * @public
3365
+ */
3366
+ class ByteLengthQueuingStrategy {
3367
+ constructor(options) {
3368
+ assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');
3369
+ options = convertQueuingStrategyInit(options, 'First parameter');
3370
+ this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;
3371
+ }
3372
+ /**
3373
+ * Returns the high water mark provided to the constructor.
3374
+ */
3375
+ get highWaterMark() {
3376
+ if (!IsByteLengthQueuingStrategy(this)) {
3377
+ throw byteLengthBrandCheckException('highWaterMark');
3378
+ }
3379
+ return this._byteLengthQueuingStrategyHighWaterMark;
3380
+ }
3381
+ /**
3382
+ * Measures the size of `chunk` by returning the value of its `byteLength` property.
3383
+ */
3384
+ get size() {
3385
+ if (!IsByteLengthQueuingStrategy(this)) {
3386
+ throw byteLengthBrandCheckException('size');
3387
+ }
3388
+ return byteLengthSizeFunction;
3389
+ }
3390
+ }
3391
+ Object.defineProperties(ByteLengthQueuingStrategy.prototype, {
3392
+ highWaterMark: { enumerable: true },
3393
+ size: { enumerable: true }
3394
+ });
3395
+ if (typeof SymbolPolyfill.toStringTag === 'symbol') {
3396
+ Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {
3397
+ value: 'ByteLengthQueuingStrategy',
3398
+ configurable: true
3399
+ });
3400
+ }
3401
+ // Helper functions for the ByteLengthQueuingStrategy.
3402
+ function byteLengthBrandCheckException(name) {
3403
+ return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);
3404
+ }
3405
+ function IsByteLengthQueuingStrategy(x) {
3406
+ if (!typeIsObject(x)) {
3407
+ return false;
3408
+ }
3409
+ if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {
3410
+ return false;
3411
+ }
3412
+ return true;
3413
+ }
3414
+
3415
+ const countSizeFunction = function size() {
3416
+ return 1;
3417
+ };
3418
+ /**
3419
+ * A queuing strategy that counts the number of chunks.
3420
+ *
3421
+ * @public
3422
+ */
3423
+ class CountQueuingStrategy {
3424
+ constructor(options) {
3425
+ assertRequiredArgument(options, 1, 'CountQueuingStrategy');
3426
+ options = convertQueuingStrategyInit(options, 'First parameter');
3427
+ this._countQueuingStrategyHighWaterMark = options.highWaterMark;
3428
+ }
3429
+ /**
3430
+ * Returns the high water mark provided to the constructor.
3431
+ */
3432
+ get highWaterMark() {
3433
+ if (!IsCountQueuingStrategy(this)) {
3434
+ throw countBrandCheckException('highWaterMark');
3435
+ }
3436
+ return this._countQueuingStrategyHighWaterMark;
3437
+ }
3438
+ /**
3439
+ * Measures the size of `chunk` by always returning 1.
3440
+ * This ensures that the total queue size is a count of the number of chunks in the queue.
3441
+ */
3442
+ get size() {
3443
+ if (!IsCountQueuingStrategy(this)) {
3444
+ throw countBrandCheckException('size');
3445
+ }
3446
+ return countSizeFunction;
3447
+ }
3448
+ }
3449
+ Object.defineProperties(CountQueuingStrategy.prototype, {
3450
+ highWaterMark: { enumerable: true },
3451
+ size: { enumerable: true }
3452
+ });
3453
+ if (typeof SymbolPolyfill.toStringTag === 'symbol') {
3454
+ Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {
3455
+ value: 'CountQueuingStrategy',
3456
+ configurable: true
3457
+ });
3458
+ }
3459
+ // Helper functions for the CountQueuingStrategy.
3460
+ function countBrandCheckException(name) {
3461
+ return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);
3462
+ }
3463
+ function IsCountQueuingStrategy(x) {
3464
+ if (!typeIsObject(x)) {
3465
+ return false;
3466
+ }
3467
+ if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {
3468
+ return false;
3469
+ }
3470
+ return true;
3471
+ }
3472
+
3473
+ function convertTransformer(original, context) {
3474
+ assertDictionary(original, context);
3475
+ const flush = original === null || original === void 0 ? void 0 : original.flush;
3476
+ const readableType = original === null || original === void 0 ? void 0 : original.readableType;
3477
+ const start = original === null || original === void 0 ? void 0 : original.start;
3478
+ const transform = original === null || original === void 0 ? void 0 : original.transform;
3479
+ const writableType = original === null || original === void 0 ? void 0 : original.writableType;
3480
+ return {
3481
+ flush: flush === undefined ?
3482
+ undefined :
3483
+ convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`),
3484
+ readableType,
3485
+ start: start === undefined ?
3486
+ undefined :
3487
+ convertTransformerStartCallback(start, original, `${context} has member 'start' that`),
3488
+ transform: transform === undefined ?
3489
+ undefined :
3490
+ convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`),
3491
+ writableType
3492
+ };
3493
+ }
3494
+ function convertTransformerFlushCallback(fn, original, context) {
3495
+ assertFunction(fn, context);
3496
+ return (controller) => promiseCall(fn, original, [controller]);
3497
+ }
3498
+ function convertTransformerStartCallback(fn, original, context) {
3499
+ assertFunction(fn, context);
3500
+ return (controller) => reflectCall(fn, original, [controller]);
3501
+ }
3502
+ function convertTransformerTransformCallback(fn, original, context) {
3503
+ assertFunction(fn, context);
3504
+ return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
3505
+ }
3506
+
3507
+ // Class TransformStream
3508
+ /**
3509
+ * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},
3510
+ * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.
3511
+ * In a manner specific to the transform stream in question, writes to the writable side result in new data being
3512
+ * made available for reading from the readable side.
3513
+ *
3514
+ * @public
3515
+ */
3516
+ class TransformStream {
3517
+ constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) {
3518
+ if (rawTransformer === undefined) {
3519
+ rawTransformer = null;
3520
+ }
3521
+ const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');
3522
+ const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');
3523
+ const transformer = convertTransformer(rawTransformer, 'First parameter');
3524
+ if (transformer.readableType !== undefined) {
3525
+ throw new RangeError('Invalid readableType specified');
3526
+ }
3527
+ if (transformer.writableType !== undefined) {
3528
+ throw new RangeError('Invalid writableType specified');
3529
+ }
3530
+ const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);
3531
+ const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);
3532
+ const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);
3533
+ const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);
3534
+ let startPromise_resolve;
3535
+ const startPromise = newPromise(resolve => {
3536
+ startPromise_resolve = resolve;
3537
+ });
3538
+ InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
3539
+ SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);
3540
+ if (transformer.start !== undefined) {
3541
+ startPromise_resolve(transformer.start(this._transformStreamController));
3542
+ }
3543
+ else {
3544
+ startPromise_resolve(undefined);
3545
+ }
3546
+ }
3547
+ /**
3548
+ * The readable side of the transform stream.
3549
+ */
3550
+ get readable() {
3551
+ if (!IsTransformStream(this)) {
3552
+ throw streamBrandCheckException('readable');
3553
+ }
3554
+ return this._readable;
3555
+ }
3556
+ /**
3557
+ * The writable side of the transform stream.
3558
+ */
3559
+ get writable() {
3560
+ if (!IsTransformStream(this)) {
3561
+ throw streamBrandCheckException('writable');
3562
+ }
3563
+ return this._writable;
3564
+ }
3565
+ }
3566
+ Object.defineProperties(TransformStream.prototype, {
3567
+ readable: { enumerable: true },
3568
+ writable: { enumerable: true }
3569
+ });
3570
+ if (typeof SymbolPolyfill.toStringTag === 'symbol') {
3571
+ Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, {
3572
+ value: 'TransformStream',
3573
+ configurable: true
3574
+ });
3575
+ }
3576
+ function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) {
3577
+ function startAlgorithm() {
3578
+ return startPromise;
3579
+ }
3580
+ function writeAlgorithm(chunk) {
3581
+ return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);
3582
+ }
3583
+ function abortAlgorithm(reason) {
3584
+ return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);
3585
+ }
3586
+ function closeAlgorithm() {
3587
+ return TransformStreamDefaultSinkCloseAlgorithm(stream);
3588
+ }
3589
+ stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm);
3590
+ function pullAlgorithm() {
3591
+ return TransformStreamDefaultSourcePullAlgorithm(stream);
3592
+ }
3593
+ function cancelAlgorithm(reason) {
3594
+ TransformStreamErrorWritableAndUnblockWrite(stream, reason);
3595
+ return promiseResolvedWith(undefined);
3596
+ }
3597
+ stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
3598
+ // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.
3599
+ stream._backpressure = undefined;
3600
+ stream._backpressureChangePromise = undefined;
3601
+ stream._backpressureChangePromise_resolve = undefined;
3602
+ TransformStreamSetBackpressure(stream, true);
3603
+ stream._transformStreamController = undefined;
3604
+ }
3605
+ function IsTransformStream(x) {
3606
+ if (!typeIsObject(x)) {
3607
+ return false;
3608
+ }
3609
+ if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {
3610
+ return false;
3611
+ }
3612
+ return true;
3613
+ }
3614
+ // This is a no-op if both sides are already errored.
3615
+ function TransformStreamError(stream, e) {
3616
+ ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);
3617
+ TransformStreamErrorWritableAndUnblockWrite(stream, e);
3618
+ }
3619
+ function TransformStreamErrorWritableAndUnblockWrite(stream, e) {
3620
+ TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);
3621
+ WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);
3622
+ if (stream._backpressure) {
3623
+ // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()
3624
+ // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time
3625
+ // _backpressure is set.
3626
+ TransformStreamSetBackpressure(stream, false);
3627
+ }
3628
+ }
3629
+ function TransformStreamSetBackpressure(stream, backpressure) {
3630
+ // Passes also when called during construction.
3631
+ if (stream._backpressureChangePromise !== undefined) {
3632
+ stream._backpressureChangePromise_resolve();
3633
+ }
3634
+ stream._backpressureChangePromise = newPromise(resolve => {
3635
+ stream._backpressureChangePromise_resolve = resolve;
3636
+ });
3637
+ stream._backpressure = backpressure;
3638
+ }
3639
+ // Class TransformStreamDefaultController
3640
+ /**
3641
+ * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.
3642
+ *
3643
+ * @public
3644
+ */
3645
+ class TransformStreamDefaultController {
3646
+ constructor() {
3647
+ throw new TypeError('Illegal constructor');
3648
+ }
3649
+ /**
3650
+ * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.
3651
+ */
3652
+ get desiredSize() {
3653
+ if (!IsTransformStreamDefaultController(this)) {
3654
+ throw defaultControllerBrandCheckException('desiredSize');
3655
+ }
3656
+ const readableController = this._controlledTransformStream._readable._readableStreamController;
3657
+ return ReadableStreamDefaultControllerGetDesiredSize(readableController);
3658
+ }
3659
+ enqueue(chunk = undefined) {
3660
+ if (!IsTransformStreamDefaultController(this)) {
3661
+ throw defaultControllerBrandCheckException('enqueue');
3662
+ }
3663
+ TransformStreamDefaultControllerEnqueue(this, chunk);
3664
+ }
3665
+ /**
3666
+ * Errors both the readable side and the writable side of the controlled transform stream, making all future
3667
+ * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.
3668
+ */
3669
+ error(reason = undefined) {
3670
+ if (!IsTransformStreamDefaultController(this)) {
3671
+ throw defaultControllerBrandCheckException('error');
3672
+ }
3673
+ TransformStreamDefaultControllerError(this, reason);
3674
+ }
3675
+ /**
3676
+ * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the
3677
+ * transformer only needs to consume a portion of the chunks written to the writable side.
3678
+ */
3679
+ terminate() {
3680
+ if (!IsTransformStreamDefaultController(this)) {
3681
+ throw defaultControllerBrandCheckException('terminate');
3682
+ }
3683
+ TransformStreamDefaultControllerTerminate(this);
3684
+ }
3685
+ }
3686
+ Object.defineProperties(TransformStreamDefaultController.prototype, {
3687
+ enqueue: { enumerable: true },
3688
+ error: { enumerable: true },
3689
+ terminate: { enumerable: true },
3690
+ desiredSize: { enumerable: true }
3691
+ });
3692
+ if (typeof SymbolPolyfill.toStringTag === 'symbol') {
3693
+ Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
3694
+ value: 'TransformStreamDefaultController',
3695
+ configurable: true
3696
+ });
3697
+ }
3698
+ // Transform Stream Default Controller Abstract Operations
3699
+ function IsTransformStreamDefaultController(x) {
3700
+ if (!typeIsObject(x)) {
3701
+ return false;
3702
+ }
3703
+ if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {
3704
+ return false;
3705
+ }
3706
+ return true;
3707
+ }
3708
+ function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) {
3709
+ controller._controlledTransformStream = stream;
3710
+ stream._transformStreamController = controller;
3711
+ controller._transformAlgorithm = transformAlgorithm;
3712
+ controller._flushAlgorithm = flushAlgorithm;
3713
+ }
3714
+ function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) {
3715
+ const controller = Object.create(TransformStreamDefaultController.prototype);
3716
+ let transformAlgorithm = (chunk) => {
3717
+ try {
3718
+ TransformStreamDefaultControllerEnqueue(controller, chunk);
3719
+ return promiseResolvedWith(undefined);
3720
+ }
3721
+ catch (transformResultE) {
3722
+ return promiseRejectedWith(transformResultE);
3723
+ }
3724
+ };
3725
+ let flushAlgorithm = () => promiseResolvedWith(undefined);
3726
+ if (transformer.transform !== undefined) {
3727
+ transformAlgorithm = chunk => transformer.transform(chunk, controller);
3728
+ }
3729
+ if (transformer.flush !== undefined) {
3730
+ flushAlgorithm = () => transformer.flush(controller);
3731
+ }
3732
+ SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);
3733
+ }
3734
+ function TransformStreamDefaultControllerClearAlgorithms(controller) {
3735
+ controller._transformAlgorithm = undefined;
3736
+ controller._flushAlgorithm = undefined;
3737
+ }
3738
+ function TransformStreamDefaultControllerEnqueue(controller, chunk) {
3739
+ const stream = controller._controlledTransformStream;
3740
+ const readableController = stream._readable._readableStreamController;
3741
+ if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {
3742
+ throw new TypeError('Readable side is not in a state that permits enqueue');
3743
+ }
3744
+ // We throttle transform invocations based on the backpressure of the ReadableStream, but we still
3745
+ // accept TransformStreamDefaultControllerEnqueue() calls.
3746
+ try {
3747
+ ReadableStreamDefaultControllerEnqueue(readableController, chunk);
3748
+ }
3749
+ catch (e) {
3750
+ // This happens when readableStrategy.size() throws.
3751
+ TransformStreamErrorWritableAndUnblockWrite(stream, e);
3752
+ throw stream._readable._storedError;
3753
+ }
3754
+ const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);
3755
+ if (backpressure !== stream._backpressure) {
3756
+ TransformStreamSetBackpressure(stream, true);
3757
+ }
3758
+ }
3759
+ function TransformStreamDefaultControllerError(controller, e) {
3760
+ TransformStreamError(controller._controlledTransformStream, e);
3761
+ }
3762
+ function TransformStreamDefaultControllerPerformTransform(controller, chunk) {
3763
+ const transformPromise = controller._transformAlgorithm(chunk);
3764
+ return transformPromiseWith(transformPromise, undefined, r => {
3765
+ TransformStreamError(controller._controlledTransformStream, r);
3766
+ throw r;
3767
+ });
3768
+ }
3769
+ function TransformStreamDefaultControllerTerminate(controller) {
3770
+ const stream = controller._controlledTransformStream;
3771
+ const readableController = stream._readable._readableStreamController;
3772
+ ReadableStreamDefaultControllerClose(readableController);
3773
+ const error = new TypeError('TransformStream terminated');
3774
+ TransformStreamErrorWritableAndUnblockWrite(stream, error);
3775
+ }
3776
+ // TransformStreamDefaultSink Algorithms
3777
+ function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) {
3778
+ const controller = stream._transformStreamController;
3779
+ if (stream._backpressure) {
3780
+ const backpressureChangePromise = stream._backpressureChangePromise;
3781
+ return transformPromiseWith(backpressureChangePromise, () => {
3782
+ const writable = stream._writable;
3783
+ const state = writable._state;
3784
+ if (state === 'erroring') {
3785
+ throw writable._storedError;
3786
+ }
3787
+ return TransformStreamDefaultControllerPerformTransform(controller, chunk);
3788
+ });
3789
+ }
3790
+ return TransformStreamDefaultControllerPerformTransform(controller, chunk);
3791
+ }
3792
+ function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) {
3793
+ // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already
3794
+ // errored.
3795
+ TransformStreamError(stream, reason);
3796
+ return promiseResolvedWith(undefined);
3797
+ }
3798
+ function TransformStreamDefaultSinkCloseAlgorithm(stream) {
3799
+ // stream._readable cannot change after construction, so caching it across a call to user code is safe.
3800
+ const readable = stream._readable;
3801
+ const controller = stream._transformStreamController;
3802
+ const flushPromise = controller._flushAlgorithm();
3803
+ TransformStreamDefaultControllerClearAlgorithms(controller);
3804
+ // Return a promise that is fulfilled with undefined on success.
3805
+ return transformPromiseWith(flushPromise, () => {
3806
+ if (readable._state === 'errored') {
3807
+ throw readable._storedError;
3808
+ }
3809
+ ReadableStreamDefaultControllerClose(readable._readableStreamController);
3810
+ }, r => {
3811
+ TransformStreamError(stream, r);
3812
+ throw readable._storedError;
3813
+ });
3814
+ }
3815
+ // TransformStreamDefaultSource Algorithms
3816
+ function TransformStreamDefaultSourcePullAlgorithm(stream) {
3817
+ // Invariant. Enforced by the promises returned by start() and pull().
3818
+ TransformStreamSetBackpressure(stream, false);
3819
+ // Prevent the next pull() call until there is backpressure.
3820
+ return stream._backpressureChangePromise;
3821
+ }
3822
+ // Helper functions for the TransformStreamDefaultController.
3823
+ function defaultControllerBrandCheckException(name) {
3824
+ return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);
3825
+ }
3826
+ // Helper functions for the TransformStream.
3827
+ function streamBrandCheckException(name) {
3828
+ return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`);
3829
+ }
3830
+
3831
+ export { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter };