polyfill.mjs 180 KB

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