polyfill.es6.mjs 169 KB

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