ponyfill.es6.js 186 KB

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