polyfill.es6.js 187 KB

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