ponyfill.js 196 KB

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