AbstractOperations.cpp 168 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814
  1. /*
  2. * Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
  3. * Copyright (c) 2023, Matthew Olsson <mattco@serenityos.org>
  4. * Copyright (c) 2023, Shannon Booth <shannon@serenityos.org>
  5. * Copyright (c) 2023, Kenneth Myhra <kennethmyhra@serenityos.org>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <LibJS/Runtime/ArrayBuffer.h>
  10. #include <LibJS/Runtime/DataView.h>
  11. #include <LibJS/Runtime/DataViewConstructor.h>
  12. #include <LibJS/Runtime/Intrinsics.h>
  13. #include <LibJS/Runtime/PromiseCapability.h>
  14. #include <LibJS/Runtime/PromiseConstructor.h>
  15. #include <LibJS/Runtime/TypedArray.h>
  16. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  17. #include <LibWeb/DOM/AbortSignal.h>
  18. #include <LibWeb/Streams/AbstractOperations.h>
  19. #include <LibWeb/Streams/QueuingStrategy.h>
  20. #include <LibWeb/Streams/ReadableByteStreamController.h>
  21. #include <LibWeb/Streams/ReadableStream.h>
  22. #include <LibWeb/Streams/ReadableStreamBYOBReader.h>
  23. #include <LibWeb/Streams/ReadableStreamBYOBRequest.h>
  24. #include <LibWeb/Streams/ReadableStreamDefaultController.h>
  25. #include <LibWeb/Streams/ReadableStreamDefaultReader.h>
  26. #include <LibWeb/Streams/ReadableStreamGenericReader.h>
  27. #include <LibWeb/Streams/TransformStream.h>
  28. #include <LibWeb/Streams/TransformStreamDefaultController.h>
  29. #include <LibWeb/Streams/Transformer.h>
  30. #include <LibWeb/Streams/UnderlyingSink.h>
  31. #include <LibWeb/Streams/UnderlyingSource.h>
  32. #include <LibWeb/Streams/WritableStream.h>
  33. #include <LibWeb/Streams/WritableStreamDefaultController.h>
  34. #include <LibWeb/Streams/WritableStreamDefaultWriter.h>
  35. #include <LibWeb/WebIDL/AbstractOperations.h>
  36. #include <LibWeb/WebIDL/ExceptionOr.h>
  37. #include <LibWeb/WebIDL/Promise.h>
  38. namespace Web::Streams {
  39. // https://streams.spec.whatwg.org/#acquire-readable-stream-reader
  40. WebIDL::ExceptionOr<JS::NonnullGCPtr<ReadableStreamDefaultReader>> acquire_readable_stream_default_reader(ReadableStream& stream)
  41. {
  42. auto& realm = stream.realm();
  43. // 1. Let reader be a new ReadableStreamDefaultReader.
  44. auto reader = realm.heap().allocate<ReadableStreamDefaultReader>(realm, realm);
  45. // 2. Perform ? SetUpReadableStreamDefaultReader(reader, stream).
  46. TRY(set_up_readable_stream_default_reader(reader, stream));
  47. // 3. Return reader.
  48. return reader;
  49. }
  50. // https://streams.spec.whatwg.org/#acquire-readable-stream-byob-reader
  51. WebIDL::ExceptionOr<JS::NonnullGCPtr<ReadableStreamBYOBReader>> acquire_readable_stream_byob_reader(ReadableStream& stream)
  52. {
  53. auto& realm = stream.realm();
  54. // 1. Let reader be a new ReadableStreamBYOBReader.
  55. auto reader = realm.heap().allocate<ReadableStreamBYOBReader>(realm, realm);
  56. // 2. Perform ? SetUpReadableStreamBYOBReader(reader, stream).
  57. TRY(set_up_readable_stream_byob_reader(reader, stream));
  58. // 3. Return reader.
  59. return reader;
  60. }
  61. // https://streams.spec.whatwg.org/#is-readable-stream-locked
  62. bool is_readable_stream_locked(ReadableStream const& stream)
  63. {
  64. // 1. If stream.[[reader]] is undefined, return false.
  65. if (!stream.reader().has_value())
  66. return false;
  67. // 2. Return true.
  68. return true;
  69. }
  70. // https://streams.spec.whatwg.org/#readable-stream-cancel
  71. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> readable_stream_cancel(ReadableStream& stream, JS::Value reason)
  72. {
  73. auto& realm = stream.realm();
  74. // 1. Set stream.[[disturbed]] to true.
  75. stream.set_disturbed(true);
  76. // 2. If stream.[[state]] is "closed", return a promise resolved with undefined.
  77. if (stream.state() == ReadableStream::State::Closed)
  78. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  79. // 3. If stream.[[state]] is "errored", return a promise rejected with stream.[[storedError]].
  80. if (stream.state() == ReadableStream::State::Errored)
  81. return WebIDL::create_rejected_promise(realm, stream.stored_error());
  82. // 4. Perform ! ReadableStreamClose(stream).
  83. readable_stream_close(stream);
  84. // 5. Let reader be stream.[[reader]].
  85. auto reader = stream.reader();
  86. // 6. If reader is not undefined and reader implements ReadableStreamBYOBReader,
  87. if (reader.has_value() && reader->has<JS::NonnullGCPtr<ReadableStreamBYOBReader>>()) {
  88. // 1. Let readIntoRequests be reader.[[readIntoRequests]].
  89. // 2. Set reader.[[readIntoRequests]] to an empty list.
  90. auto read_into_requests = move(reader->get<JS::NonnullGCPtr<ReadableStreamBYOBReader>>()->read_into_requests());
  91. // 3. For each readIntoRequest of readIntoRequests,
  92. for (auto& read_into_request : read_into_requests) {
  93. // 1. Perform readIntoRequest’s close steps, given undefined.
  94. read_into_request->on_close(JS::js_undefined());
  95. }
  96. }
  97. // 7. Let sourceCancelPromise be ! stream.[[controller]].[[CancelSteps]](reason).
  98. auto source_cancel_promise = TRY(stream.controller()->visit([&](auto const& controller) {
  99. return controller->cancel_steps(reason);
  100. }));
  101. // 8. Return the result of reacting to sourceCancelPromise with a fulfillment step that returns undefined.
  102. auto react_result = WebIDL::react_to_promise(*source_cancel_promise,
  103. [](auto const&) -> WebIDL::ExceptionOr<JS::Value> { return JS::js_undefined(); },
  104. {});
  105. return WebIDL::create_resolved_promise(realm, react_result);
  106. }
  107. // https://streams.spec.whatwg.org/#readable-stream-fulfill-read-into-request
  108. void readable_stream_fulfill_read_into_request(ReadableStream& stream, JS::Value chunk, bool done)
  109. {
  110. // 1. Assert: ! ReadableStreamHasBYOBReader(stream) is true.
  111. VERIFY(readable_stream_has_byob_reader(stream));
  112. // 2. Let reader be stream.[[reader]].
  113. auto reader = stream.reader()->get<JS::NonnullGCPtr<ReadableStreamBYOBReader>>();
  114. // 3. Assert: reader.[[readIntoRequests]] is not empty.
  115. VERIFY(!reader->read_into_requests().is_empty());
  116. // 4. Let readIntoRequest be reader.[[readIntoRequests]][0].
  117. // 5. Remove readIntoRequest from reader.[[readIntoRequests]].
  118. auto read_into_request = reader->read_into_requests().take_first();
  119. // 6. If done is true, perform readIntoRequest’s close steps, given chunk.
  120. if (done) {
  121. read_into_request->on_close(chunk);
  122. }
  123. // 7. Otherwise, perform readIntoRequest’s chunk steps, given chunk.
  124. else {
  125. read_into_request->on_chunk(chunk);
  126. }
  127. }
  128. // https://streams.spec.whatwg.org/#readable-stream-fulfill-read-request
  129. void readable_stream_fulfill_read_request(ReadableStream& stream, JS::Value chunk, bool done)
  130. {
  131. // 1. Assert: ! ReadableStreamHasDefaultReader(stream) is true.
  132. VERIFY(readable_stream_has_default_reader(stream));
  133. // 2. Let reader be stream.[[reader]].
  134. auto reader = stream.reader()->get<JS::NonnullGCPtr<ReadableStreamDefaultReader>>();
  135. // 3. Assert: reader.[[readRequests]] is not empty.
  136. VERIFY(!reader->read_requests().is_empty());
  137. // 4. Let readRequest be reader.[[readRequests]][0].
  138. // 5. Remove readRequest from reader.[[readRequests]].
  139. auto read_request = reader->read_requests().take_first();
  140. // 6. If done is true, perform readRequest’s close steps.
  141. if (done) {
  142. read_request->on_close();
  143. }
  144. // 7. Otherwise, perform readRequest’s chunk steps, given chunk.
  145. else {
  146. read_request->on_chunk(chunk);
  147. }
  148. }
  149. // https://streams.spec.whatwg.org/#readable-stream-get-num-read-into-requests
  150. size_t readable_stream_get_num_read_into_requests(ReadableStream const& stream)
  151. {
  152. // 1. Assert: ! ReadableStreamHasBYOBReader(stream) is true.
  153. VERIFY(readable_stream_has_byob_reader(stream));
  154. // 2. Return stream.[[reader]].[[readIntoRequests]]'s size.
  155. return stream.reader()->get<JS::NonnullGCPtr<ReadableStreamBYOBReader>>()->read_into_requests().size();
  156. }
  157. // https://streams.spec.whatwg.org/#readable-stream-get-num-read-requests
  158. size_t readable_stream_get_num_read_requests(ReadableStream const& stream)
  159. {
  160. // 1. Assert: ! ReadableStreamHasDefaultReader(stream) is true.
  161. VERIFY(readable_stream_has_default_reader(stream));
  162. // 2. Return stream.[[reader]].[[readRequests]]'s size.
  163. return stream.reader()->get<JS::NonnullGCPtr<ReadableStreamDefaultReader>>()->read_requests().size();
  164. }
  165. // https://streams.spec.whatwg.org/#readable-stream-has-byob-reader
  166. bool readable_stream_has_byob_reader(ReadableStream const& stream)
  167. {
  168. // 1. Let reader be stream.[[reader]].
  169. auto reader = stream.reader();
  170. // 2. If reader is undefined, return false.
  171. if (!reader.has_value())
  172. return false;
  173. // 3. If reader implements ReadableStreamBYOBReader, return true.
  174. if (reader->has<JS::NonnullGCPtr<ReadableStreamBYOBReader>>())
  175. return true;
  176. // 4. Return false.
  177. return false;
  178. }
  179. // https://streams.spec.whatwg.org/#readable-stream-has-default-reader
  180. bool readable_stream_has_default_reader(ReadableStream const& stream)
  181. {
  182. // 1. Let reader be stream.[[reader]].
  183. auto reader = stream.reader();
  184. // 2. If reader is undefined, return false.
  185. if (!reader.has_value())
  186. return false;
  187. // 3. If reader implements ReadableStreamDefaultReader, return true.
  188. if (reader->has<JS::NonnullGCPtr<ReadableStreamDefaultReader>>())
  189. return true;
  190. // 4. Return false.
  191. return false;
  192. }
  193. // https://streams.spec.whatwg.org/#make-size-algorithm-from-size-function
  194. SizeAlgorithm extract_size_algorithm(QueuingStrategy const& strategy)
  195. {
  196. // 1. If strategy["size"] does not exist, return an algorithm that returns 1.
  197. if (!strategy.size)
  198. return [](auto const&) { return JS::normal_completion(JS::Value(1)); };
  199. // 2. Return an algorithm that performs the following steps, taking a chunk argument:
  200. return [strategy](auto const& chunk) {
  201. // 1. Return the result of invoking strategy["size"] with argument list « chunk ».
  202. return WebIDL::invoke_callback(*strategy.size, JS::js_undefined(), chunk);
  203. };
  204. }
  205. // https://streams.spec.whatwg.org/#validate-and-normalize-high-water-mark
  206. WebIDL::ExceptionOr<double> extract_high_water_mark(QueuingStrategy const& strategy, double default_hwm)
  207. {
  208. // 1. If strategy["highWaterMark"] does not exist, return defaultHWM.
  209. if (!strategy.high_water_mark.has_value())
  210. return default_hwm;
  211. // 2. Let highWaterMark be strategy["highWaterMark"].
  212. auto high_water_mark = strategy.high_water_mark.value();
  213. // 3. If highWaterMark is NaN or highWaterMark < 0, throw a RangeError exception.
  214. if (isnan(high_water_mark) || high_water_mark < 0)
  215. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Invalid value for high water mark"sv };
  216. // 4. Return highWaterMark.
  217. return high_water_mark;
  218. }
  219. // https://streams.spec.whatwg.org/#readable-stream-close
  220. void readable_stream_close(ReadableStream& stream)
  221. {
  222. auto& realm = stream.realm();
  223. // 1. Assert: stream.[[state]] is "readable".
  224. VERIFY(stream.state() == ReadableStream::State::Readable);
  225. // 2. Set stream.[[state]] to "closed".
  226. stream.set_state(ReadableStream::State::Closed);
  227. // 3. Let reader be stream.[[reader]].
  228. auto reader = stream.reader();
  229. // 4. If reader is undefined, return.
  230. if (!reader.has_value())
  231. return;
  232. // 5. Resolve reader.[[closedPromise]] with undefined.
  233. WebIDL::resolve_promise(realm, *reader->visit([](auto& reader) {
  234. return reader->closed_promise_capability();
  235. }));
  236. // 6. If reader implements ReadableStreamDefaultReader,
  237. if (reader->has<JS::NonnullGCPtr<ReadableStreamDefaultReader>>()) {
  238. // 1. Let readRequests be reader.[[readRequests]].
  239. // 2. Set reader.[[readRequests]] to an empty list.
  240. auto read_requests = move(reader->get<JS::NonnullGCPtr<ReadableStreamDefaultReader>>()->read_requests());
  241. // 3. For each readRequest of readRequests,
  242. for (auto& read_request : read_requests) {
  243. // 1. Perform readRequest’s close steps.
  244. read_request->on_close();
  245. }
  246. }
  247. }
  248. // https://streams.spec.whatwg.org/#readable-stream-error
  249. void readable_stream_error(ReadableStream& stream, JS::Value error)
  250. {
  251. auto& realm = stream.realm();
  252. // 1. Assert: stream.[[state]] is "readable".
  253. VERIFY(stream.state() == ReadableStream::State::Readable);
  254. // 2. Set stream.[[state]] to "errored".
  255. stream.set_state(ReadableStream::State::Errored);
  256. // 3. Set stream.[[storedError]] to e.
  257. stream.set_stored_error(error);
  258. // 4. Let reader be stream.[[reader]].
  259. auto reader = stream.reader();
  260. // 5. If reader is undefined, return.
  261. if (!reader.has_value())
  262. return;
  263. auto closed_promise_capability = reader->visit([](auto& reader) { return reader->closed_promise_capability(); });
  264. // 6. Reject reader.[[closedPromise]] with e.
  265. WebIDL::reject_promise(realm, *closed_promise_capability, error);
  266. // 7. Set reader.[[closedPromise]].[[PromiseIsHandled]] to true.
  267. WebIDL::mark_promise_as_handled(*closed_promise_capability);
  268. // 8. If reader implements ReadableStreamDefaultReader,
  269. if (reader->has<JS::NonnullGCPtr<ReadableStreamDefaultReader>>()) {
  270. // 1. Perform ! ReadableStreamDefaultReaderErrorReadRequests(reader, e).
  271. readable_stream_default_reader_error_read_requests(*reader->get<JS::NonnullGCPtr<ReadableStreamDefaultReader>>(), error);
  272. }
  273. // 9. Otherwise,
  274. else {
  275. // 1. Assert: reader implements ReadableStreamBYOBReader.
  276. VERIFY(reader->has<JS::NonnullGCPtr<ReadableStreamBYOBReader>>());
  277. // 2. Perform ! ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e).
  278. readable_stream_byob_reader_error_read_into_requests(*reader->get<JS::NonnullGCPtr<ReadableStreamBYOBReader>>(), error);
  279. }
  280. }
  281. // https://streams.spec.whatwg.org/#readable-stream-add-read-request
  282. void readable_stream_add_read_request(ReadableStream& stream, JS::NonnullGCPtr<ReadRequest> read_request)
  283. {
  284. // 1. Assert: stream.[[reader]] implements ReadableStreamDefaultReader.
  285. VERIFY(stream.reader().has_value() && stream.reader()->has<JS::NonnullGCPtr<ReadableStreamDefaultReader>>());
  286. // 2. Assert: stream.[[state]] is "readable".
  287. VERIFY(stream.state() == ReadableStream::State::Readable);
  288. // 3. Append readRequest to stream.[[reader]].[[readRequests]].
  289. stream.reader()->get<JS::NonnullGCPtr<ReadableStreamDefaultReader>>()->read_requests().append(read_request);
  290. }
  291. // https://streams.spec.whatwg.org/#readable-stream-add-read-into-request
  292. void readable_stream_add_read_into_request(ReadableStream& stream, JS::NonnullGCPtr<ReadIntoRequest> read_into_request)
  293. {
  294. // 1. Assert: stream.[[reader]] implements ReadableStreamBYOBReader.
  295. VERIFY(stream.reader().has_value() && stream.reader()->has<JS::NonnullGCPtr<ReadableStreamBYOBReader>>());
  296. // 2. Assert: stream.[[state]] is "readable" or "closed".
  297. VERIFY(stream.is_readable() || stream.is_closed());
  298. // 3. Append readRequest to stream.[[reader]].[[readIntoRequests]].
  299. stream.reader()->get<JS::NonnullGCPtr<ReadableStreamBYOBReader>>()->read_into_requests().append(read_into_request);
  300. }
  301. // https://streams.spec.whatwg.org/#readable-stream-reader-generic-cancel
  302. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> readable_stream_reader_generic_cancel(ReadableStreamGenericReaderMixin& reader, JS::Value reason)
  303. {
  304. // 1. Let stream be reader.[[stream]]
  305. auto stream = reader.stream();
  306. // 2. Assert: stream is not undefined
  307. VERIFY(stream);
  308. // 3. Return ! ReadableStreamCancel(stream, reason)
  309. return TRY(readable_stream_cancel(*stream, reason));
  310. }
  311. // https://streams.spec.whatwg.org/#readable-stream-reader-generic-initialize
  312. void readable_stream_reader_generic_initialize(ReadableStreamReader reader, ReadableStream& stream)
  313. {
  314. auto& realm = stream.realm();
  315. // 1. Set reader.[[stream]] to stream.
  316. reader.visit([&](auto& reader) { reader->set_stream(stream); });
  317. // 2. Set stream.[[reader]] to reader.
  318. stream.set_reader(reader);
  319. // 3. If stream.[[state]] is "readable",
  320. if (stream.state() == ReadableStream::State::Readable) {
  321. // 1. Set reader.[[closedPromise]] to a new promise.
  322. reader.visit([&](auto& reader) { reader->set_closed_promise_capability(WebIDL::create_promise(realm)); });
  323. }
  324. // 4. Otherwise, if stream.[[state]] is "closed",
  325. else if (stream.state() == ReadableStream::State::Closed) {
  326. // 1. Set reader.[[closedPromise]] to a promise resolved with undefined.
  327. reader.visit([&](auto& reader) {
  328. reader->set_closed_promise_capability(WebIDL::create_resolved_promise(realm, JS::js_undefined()));
  329. });
  330. }
  331. // 5. Otherwise,
  332. else {
  333. // 1. Assert: stream.[[state]] is "errored".
  334. VERIFY(stream.state() == ReadableStream::State::Errored);
  335. // 2. Set reader.[[closedPromise]] to a promise rejected with stream.[[storedError]].
  336. // 3. Set reader.[[closedPromise]].[[PromiseIsHandled]] to true.
  337. reader.visit([&](auto& reader) {
  338. reader->set_closed_promise_capability(WebIDL::create_rejected_promise(realm, stream.stored_error()));
  339. WebIDL::mark_promise_as_handled(*reader->closed_promise_capability());
  340. });
  341. }
  342. }
  343. // https://streams.spec.whatwg.org/#readable-stream-reader-generic-release
  344. WebIDL::ExceptionOr<void> readable_stream_reader_generic_release(ReadableStreamGenericReaderMixin& reader)
  345. {
  346. // 1. Let stream be reader.[[stream]].
  347. auto stream = reader.stream();
  348. // 2. Assert: stream is not undefined.
  349. VERIFY(stream);
  350. // 3. Assert: stream.[[reader]] is reader.
  351. VERIFY(stream->reader()->visit([](auto& reader) -> ReadableStreamGenericReaderMixin* { return reader.ptr(); }) == &reader);
  352. auto& realm = stream->realm();
  353. // 4. If stream.[[state]] is "readable", reject reader.[[closedPromise]] with a TypeError exception.
  354. auto exception = JS::TypeError::create(realm, "Released readable stream"sv);
  355. if (stream->is_readable()) {
  356. WebIDL::reject_promise(realm, *reader.closed_promise_capability(), exception);
  357. }
  358. // 5. Otherwise, set reader.[[closedPromise]] to a promise rejected with a TypeError exception.
  359. else {
  360. reader.set_closed_promise_capability(WebIDL::create_rejected_promise(realm, exception));
  361. }
  362. // 6. Set reader.[[closedPromise]].[[PromiseIsHandled]] to true.
  363. WebIDL::mark_promise_as_handled(*reader.closed_promise_capability());
  364. // 7. Perform ! stream.[[controller]].[[ReleaseSteps]]().
  365. TRY(stream->controller()->visit([](auto const& controller) { return controller->release_steps(); }));
  366. // 8. Set stream.[[reader]] to undefined.
  367. stream->set_reader({});
  368. // 9. Set reader.[[stream]] to undefined.
  369. reader.set_stream({});
  370. return {};
  371. }
  372. // https://streams.spec.whatwg.org/#abstract-opdef-readablestreamdefaultreadererrorreadrequests
  373. void readable_stream_default_reader_error_read_requests(ReadableStreamDefaultReader& reader, JS::Value error)
  374. {
  375. // 1. Let readRequests be reader.[[readRequests]].
  376. auto read_requests = move(reader.read_requests());
  377. // 2. Set reader.[[readRequests]] to a new empty list.
  378. reader.read_requests().clear();
  379. // 3. For each readRequest of readRequests,
  380. for (auto& read_request : read_requests) {
  381. // 1. Perform readRequest’s error steps, given e.
  382. read_request->on_error(error);
  383. }
  384. }
  385. // https://streams.spec.whatwg.org/#abstract-opdef-readablestreambyobreadererrorreadintorequests
  386. void readable_stream_byob_reader_error_read_into_requests(ReadableStreamBYOBReader& reader, JS::Value error)
  387. {
  388. // 1. Let readIntoRequests be reader.[[readIntoRequests]].
  389. auto read_into_requests = move(reader.read_into_requests());
  390. // 2. Set reader.[[readIntoRequests]] to a new empty list.
  391. reader.read_into_requests().clear();
  392. // 3. For each readIntoRequest of readIntoRequests,
  393. for (auto& read_into_request : read_into_requests) {
  394. // 1. Perform readIntoRequest’s error steps, given e.
  395. read_into_request->on_error(error);
  396. }
  397. }
  398. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-fill-head-pull-into-descriptor
  399. void readable_byte_stream_controller_fill_head_pull_into_descriptor(ReadableByteStreamController const& controller, u64 size, PullIntoDescriptor& pull_into_descriptor)
  400. {
  401. // 1. Assert: either controller.[[pendingPullIntos]] is empty, or controller.[[pendingPullIntos]][0] is pullIntoDescriptor.
  402. VERIFY(controller.pending_pull_intos().is_empty() || &controller.pending_pull_intos().first() == &pull_into_descriptor);
  403. // 2. Assert: controller.[[byobRequest]] is null.
  404. VERIFY(!controller.byob_request());
  405. // 3. Set pullIntoDescriptor’s bytes filled to bytes filled + size.
  406. pull_into_descriptor.bytes_filled += size;
  407. }
  408. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-fill-pull-into-descriptor-from-queue
  409. bool readable_byte_stream_controller_fill_pull_into_descriptor_from_queue(ReadableByteStreamController& controller, PullIntoDescriptor& pull_into_descriptor)
  410. {
  411. // 1. Let elementSize be pullIntoDescriptor.[[elementSize]].
  412. auto element_size = pull_into_descriptor.element_size;
  413. // 2. Let currentAlignedBytes be pullIntoDescriptor’s bytes filled − (pullIntoDescriptor’s bytes filled mod elementSize).
  414. auto current_aligned_bytes = pull_into_descriptor.bytes_filled - (pull_into_descriptor.bytes_filled % pull_into_descriptor.element_size);
  415. // 3. Let maxBytesToCopy be min(controller.[[queueTotalSize]], pullIntoDescriptor’s byte length − pullIntoDescriptor’s bytes filled).
  416. auto max_bytes_to_copy = min(controller.queue_total_size(), pull_into_descriptor.byte_length - pull_into_descriptor.bytes_filled);
  417. // 4. Let maxBytesFilled be pullIntoDescriptor’s bytes filled + maxBytesToCopy.
  418. u64 max_bytes_filled = pull_into_descriptor.bytes_filled + max_bytes_to_copy;
  419. // 5. Let maxAlignedBytes be maxBytesFilled − (maxBytesFilled mod elementSize).
  420. auto max_aligned_bytes = max_bytes_filled - (max_bytes_filled % element_size);
  421. // 6. Let totalBytesToCopyRemaining be maxBytesToCopy.
  422. auto total_bytes_to_copy_remaining = max_bytes_to_copy;
  423. // 7. Let ready be false.
  424. bool ready = false;
  425. // 8. If maxAlignedBytes > currentAlignedBytes,
  426. if (max_aligned_bytes > current_aligned_bytes) {
  427. // 1. Set totalBytesToCopyRemaining to maxAlignedBytes − pullIntoDescriptor’s bytes filled.
  428. total_bytes_to_copy_remaining = max_aligned_bytes - pull_into_descriptor.bytes_filled;
  429. // 2. Set ready to true.
  430. ready = true;
  431. }
  432. // 9. Let queue be controller.[[queue]].
  433. auto& queue = controller.queue();
  434. // 10. While totalBytesToCopyRemaining > 0,
  435. while (total_bytes_to_copy_remaining > 0) {
  436. // 1. Let headOfQueue be queue[0].
  437. auto& head_of_queue = queue.first();
  438. // 2. Let bytesToCopy be min(totalBytesToCopyRemaining, headOfQueue’s byte length).
  439. auto bytes_to_copy = min(total_bytes_to_copy_remaining, head_of_queue.byte_length);
  440. // 3. Let destStart be pullIntoDescriptor’s byte offset + pullIntoDescriptor’s bytes filled.
  441. auto dest_start = pull_into_descriptor.byte_offset + pull_into_descriptor.bytes_filled;
  442. // 4. Perform ! CopyDataBlockBytes(pullIntoDescriptor’s buffer.[[ArrayBufferData]], destStart, headOfQueue’s buffer.[[ArrayBufferData]], headOfQueue’s byte offset, bytesToCopy).
  443. JS::copy_data_block_bytes(pull_into_descriptor.buffer->buffer(), dest_start, head_of_queue.buffer->buffer(), head_of_queue.byte_offset, bytes_to_copy);
  444. // 5. If headOfQueue’s byte length is bytesToCopy,
  445. if (head_of_queue.byte_length == bytes_to_copy) {
  446. // 1. Remove queue[0].
  447. queue.take_first();
  448. }
  449. // 6. Otherwise,
  450. else {
  451. // 1. Set headOfQueue’s byte offset to headOfQueue’s byte offset + bytesToCopy.
  452. head_of_queue.byte_offset += bytes_to_copy;
  453. // 2. Set headOfQueue’s byte length to headOfQueue’s byte length − bytesToCopy.
  454. head_of_queue.byte_length -= bytes_to_copy;
  455. }
  456. // 7. Set controller.[[queueTotalSize]] to controller.[[queueTotalSize]] − bytesToCopy.
  457. controller.set_queue_total_size(controller.queue_total_size() - bytes_to_copy);
  458. // 8, Perform ! ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor).
  459. readable_byte_stream_controller_fill_head_pull_into_descriptor(controller, bytes_to_copy, pull_into_descriptor);
  460. // 9. Set totalBytesToCopyRemaining to totalBytesToCopyRemaining − bytesToCopy.
  461. total_bytes_to_copy_remaining -= bytes_to_copy;
  462. }
  463. // 11. If ready is false,
  464. if (!ready) {
  465. // 1. Assert: controller.[[queueTotalSize]] is 0.
  466. VERIFY(controller.queue_total_size() == 0);
  467. // 2. Assert: pullIntoDescriptor’s bytes filled > 0.
  468. VERIFY(pull_into_descriptor.bytes_filled > 0);
  469. // 3. Assert: pullIntoDescriptor’s bytes filled < pullIntoDescriptor’s element size.
  470. VERIFY(pull_into_descriptor.bytes_filled < pull_into_descriptor.element_size);
  471. }
  472. // 12. Return ready.
  473. return ready;
  474. }
  475. // https://streams.spec.whatwg.org/#readable-stream-default-reader-read
  476. WebIDL::ExceptionOr<void> readable_stream_default_reader_read(ReadableStreamDefaultReader& reader, ReadRequest& read_request)
  477. {
  478. // 1. Let stream be reader.[[stream]].
  479. auto stream = reader.stream();
  480. // 2. Assert: stream is not undefined.
  481. VERIFY(stream);
  482. // 3. Set stream.[[disturbed]] to true.
  483. stream->set_disturbed(true);
  484. // 4. If stream.[[state]] is "closed", perform readRequest’s close steps.
  485. if (stream->is_closed()) {
  486. read_request.on_close();
  487. }
  488. // 5. Otherwise, if stream.[[state]] is "errored", perform readRequest’s error steps given stream.[[storedError]].
  489. else if (stream->is_errored()) {
  490. read_request.on_error(stream->stored_error());
  491. }
  492. // 6. Otherwise,
  493. else {
  494. // 1. Assert: stream.[[state]] is "readable".
  495. VERIFY(stream->is_readable());
  496. // 2. Perform ! stream.[[controller]].[[PullSteps]](readRequest).
  497. TRY(stream->controller()->visit([&](auto const& controller) {
  498. return controller->pull_steps(read_request);
  499. }));
  500. }
  501. return {};
  502. }
  503. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-convert-pull-into-descriptor
  504. JS::Value readable_byte_stream_controller_convert_pull_into_descriptor(JS::Realm& realm, PullIntoDescriptor const& pull_into_descriptor)
  505. {
  506. auto& vm = realm.vm();
  507. // 1. Let bytesFilled be pullIntoDescriptor’s bytes filled.
  508. auto bytes_filled = pull_into_descriptor.bytes_filled;
  509. // 2. Let elementSize be pullIntoDescriptor’s element size.
  510. auto element_size = pull_into_descriptor.element_size;
  511. // 3. Assert: bytesFilled ≤ pullIntoDescriptor’s byte length.
  512. VERIFY(bytes_filled <= pull_into_descriptor.byte_length);
  513. // 4. Assert: bytesFilled mod elementSize is 0.
  514. VERIFY(bytes_filled % element_size == 0);
  515. // 5. Let buffer be ! TransferArrayBuffer(pullIntoDescriptor’s buffer).
  516. auto buffer = MUST(transfer_array_buffer(realm, pull_into_descriptor.buffer));
  517. // 6. Return ! Construct(pullIntoDescriptor’s view constructor, « buffer, pullIntoDescriptor’s byte offset, bytesFilled ÷ elementSize »).
  518. return MUST(JS::construct(vm, *pull_into_descriptor.view_constructor, buffer, JS::Value(pull_into_descriptor.byte_offset), JS::Value(bytes_filled / element_size)));
  519. }
  520. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-pull-into
  521. void readable_byte_stream_controller_pull_into(ReadableByteStreamController& controller, JS::Value view_value, ReadIntoRequest& read_into_request)
  522. {
  523. auto& vm = controller.vm();
  524. auto& realm = controller.realm();
  525. // FIXME: Support DataView
  526. auto& view_object = view_value.as_object();
  527. auto const& view = verify_cast<JS::TypedArrayBase>(view_object);
  528. // 1. Let stream be controller.[[stream]].
  529. auto stream = controller.stream();
  530. // 2. Let elementSize be 1.
  531. size_t element_size = 1;
  532. // 3. Let ctor be %DataView%.
  533. JS::NativeFunction* ctor = realm.intrinsics().data_view_constructor();
  534. // 4. If view has a [[TypedArrayName]] internal slot (i.e., it is not a DataView),
  535. if (!is<JS::DataView>(view_object)) {
  536. // 1. Set elementSize to the element size specified in the typed array constructors table for view.[[TypedArrayName]].
  537. element_size = view.element_size();
  538. // 2. Set ctor to the constructor specified in the typed array constructors table for view.[[TypedArrayName]].
  539. if (is<JS::Int16Array>(view_object))
  540. ctor = realm.intrinsics().int16_array_constructor();
  541. else if (is<JS::Int32Array>(view_object))
  542. ctor = realm.intrinsics().int32_array_constructor();
  543. else if (is<JS::Int8Array>(view_object))
  544. ctor = realm.intrinsics().int8_array_constructor();
  545. else if (is<JS::Uint8Array>(view_object))
  546. ctor = realm.intrinsics().uint8_array_constructor();
  547. else if (is<JS::Uint16Array>(view_object))
  548. ctor = realm.intrinsics().uint16_array_constructor();
  549. else if (is<JS::Uint32Array>(view_object))
  550. ctor = realm.intrinsics().uint32_array_constructor();
  551. else if (is<JS::Uint8ClampedArray>(view_object))
  552. ctor = realm.intrinsics().uint8_clamped_array_constructor();
  553. else if (is<JS::BigInt64Array>(view_object))
  554. ctor = realm.intrinsics().big_int64_array_constructor();
  555. else if (is<JS::BigUint64Array>(view_object))
  556. ctor = realm.intrinsics().big_uint64_array_constructor();
  557. else if (is<JS::Float32Array>(view_object))
  558. ctor = realm.intrinsics().float32_array_constructor();
  559. else if (is<JS::Float64Array>(view_object))
  560. ctor = realm.intrinsics().float64_array_constructor();
  561. else
  562. VERIFY_NOT_REACHED();
  563. }
  564. // 5. Let byteOffset be view.[[ByteOffset]].
  565. auto byte_offset = view.byte_offset();
  566. // 6. Let byteLength be view.[[ByteLength]].
  567. auto byte_length = view.byte_length();
  568. // 7. Let bufferResult be TransferArrayBuffer(view.[[ViewedArrayBuffer]]).
  569. auto buffer_result = transfer_array_buffer(realm, *view.viewed_array_buffer());
  570. // 8. If bufferResult is an abrupt completion,
  571. if (buffer_result.is_exception()) {
  572. // 1. Perform readIntoRequest’s error steps, given bufferResult.[[Value]].
  573. auto throw_completion = Bindings::dom_exception_to_throw_completion(vm, buffer_result.exception());
  574. read_into_request.on_error(*throw_completion.release_value());
  575. // 2. Return.
  576. return;
  577. }
  578. // 9. Let buffer be bufferResult.[[Value]].
  579. auto buffer = buffer_result.value();
  580. // 10. Let pullIntoDescriptor be a new pull-into descriptor with buffer buffer, buffer byte length buffer.[[ArrayBufferByteLength]],
  581. // byte offset byteOffset, byte length byteLength, bytes filled 0, element size elementSize, view constructor ctor, and reader type "byob".
  582. PullIntoDescriptor pull_into_descriptor {
  583. .buffer = buffer,
  584. .buffer_byte_length = buffer->byte_length(),
  585. .byte_offset = byte_offset,
  586. .byte_length = byte_length,
  587. .bytes_filled = 0,
  588. .element_size = element_size,
  589. .view_constructor = *ctor,
  590. .reader_type = ReaderType::Byob,
  591. };
  592. // 11. If controller.[[pendingPullIntos]] is not empty,
  593. if (!controller.pending_pull_intos().is_empty()) {
  594. // 1. Append pullIntoDescriptor to controller.[[pendingPullIntos]].
  595. controller.pending_pull_intos().append(pull_into_descriptor);
  596. // 2. Perform ! ReadableStreamAddReadIntoRequest(stream, readIntoRequest).
  597. readable_stream_add_read_into_request(*stream, read_into_request);
  598. // 3. Return.
  599. return;
  600. }
  601. // 12. If stream.[[state]] is "closed",
  602. if (stream->is_closed()) {
  603. // 1. Let emptyView be ! Construct(ctor, « pullIntoDescriptor’s buffer, pullIntoDescriptor’s byte offset, 0 »).
  604. auto empty_view = MUST(JS::construct(vm, *ctor, pull_into_descriptor.buffer, JS::Value(pull_into_descriptor.byte_offset), JS::Value(0)));
  605. // 2. Perform readIntoRequest’s close steps, given emptyView.
  606. read_into_request.on_close(empty_view);
  607. // 3. Return.
  608. return;
  609. }
  610. // 13. If controller.[[queueTotalSize]] > 0,
  611. if (controller.queue_total_size() > 0) {
  612. // 1. If ! ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) is true,
  613. if (readable_byte_stream_controller_fill_pull_into_descriptor_from_queue(controller, pull_into_descriptor)) {
  614. // 1. Let filledView be ! ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor).
  615. auto filled_view = readable_byte_stream_controller_convert_pull_into_descriptor(realm, pull_into_descriptor);
  616. // 2. Perform ! ReadableByteStreamControllerHandleQueueDrain(controller).
  617. MUST(readable_byte_stream_controller_handle_queue_drain(controller));
  618. // 3. Perform readIntoRequest’s chunk steps, given filledView.
  619. read_into_request.on_chunk(filled_view);
  620. // 4. Return.
  621. return;
  622. }
  623. // 2. If controller.[[closeRequested]] is true,
  624. if (controller.close_requested()) {
  625. // 1. Let e be a TypeError exception.
  626. auto error = JS::TypeError::create(realm, "Reader has been released"sv);
  627. // 2. Perform ! ReadableByteStreamControllerError(controller, e).
  628. readable_byte_stream_controller_error(controller, error);
  629. // 3. Perform readIntoRequest’s error steps, given e.
  630. read_into_request.on_error(error);
  631. // 4. Return.
  632. return;
  633. }
  634. }
  635. // 14. Append pullIntoDescriptor to controller.[[pendingPullIntos]].
  636. controller.pending_pull_intos().append(pull_into_descriptor);
  637. // 15. Perform ! ReadableStreamAddReadIntoRequest(stream, readIntoRequest).
  638. readable_stream_add_read_into_request(*stream, read_into_request);
  639. // 16. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
  640. MUST(readable_byte_stream_controller_call_pull_if_needed(controller));
  641. }
  642. // https://streams.spec.whatwg.org/#readable-stream-byob-reader-read
  643. void readable_stream_byob_reader_read(ReadableStreamBYOBReader& reader, JS::Value view, ReadIntoRequest& read_into_request)
  644. {
  645. // 1. Let stream be reader.[[stream]].
  646. auto stream = reader.stream();
  647. // 2. Assert: stream is not undefined.
  648. VERIFY(stream);
  649. // 3. Set stream.[[disturbed]] to true.
  650. stream->set_disturbed(true);
  651. // 4. If stream.[[state]] is "errored", perform readIntoRequest’s error steps given stream.[[storedError]].
  652. if (stream->is_errored()) {
  653. read_into_request.on_error(stream->stored_error());
  654. }
  655. // 5. Otherwise, perform ! ReadableByteStreamControllerPullInto(stream.[[controller]], view, readIntoRequest).
  656. else {
  657. readable_byte_stream_controller_pull_into(*stream->controller()->get<JS::NonnullGCPtr<ReadableByteStreamController>>(), view, read_into_request);
  658. }
  659. }
  660. // https://streams.spec.whatwg.org/#abstract-opdef-readablestreamdefaultreaderrelease
  661. WebIDL::ExceptionOr<void> readable_stream_default_reader_release(ReadableStreamDefaultReader& reader)
  662. {
  663. auto& realm = reader.realm();
  664. // 1. Perform ! ReadableStreamReaderGenericRelease(reader).
  665. TRY(readable_stream_reader_generic_release(reader));
  666. // 2. Let e be a new TypeError exception.
  667. auto exception = JS::TypeError::create(realm, "Reader has been released"sv);
  668. // 3. Perform ! ReadableStreamDefaultReaderErrorReadRequests(reader, e).
  669. readable_stream_default_reader_error_read_requests(reader, exception);
  670. return {};
  671. }
  672. // https://streams.spec.whatwg.org/#abstract-opdef-readablestreambyobreaderrelease
  673. void readable_stream_byob_reader_release(ReadableStreamBYOBReader& reader)
  674. {
  675. auto& realm = reader.realm();
  676. // 1. Perform ! ReadableStreamReaderGenericRelease(reader).
  677. MUST(readable_stream_reader_generic_release(reader));
  678. // 2. Let e be a new TypeError exception.
  679. auto exception = JS::TypeError::create(realm, "Reader has been released"sv);
  680. // 3. Perform ! ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e).
  681. readable_stream_byob_reader_error_read_into_requests(reader, exception);
  682. }
  683. // https://streams.spec.whatwg.org/#set-up-readable-stream-default-reader
  684. WebIDL::ExceptionOr<void> set_up_readable_stream_default_reader(ReadableStreamDefaultReader& reader, ReadableStream& stream)
  685. {
  686. // 1. If ! IsReadableStreamLocked(stream) is true, throw a TypeError exception.
  687. if (is_readable_stream_locked(stream))
  688. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot create stream reader for a locked stream"sv };
  689. // 2. Perform ! ReadableStreamReaderGenericInitialize(reader, stream).
  690. // 3. Set reader.[[readRequests]] to a new empty list.
  691. readable_stream_reader_generic_initialize(ReadableStreamReader { reader }, stream);
  692. return {};
  693. }
  694. // https://streams.spec.whatwg.org/#set-up-readable-stream-byob-reader
  695. WebIDL::ExceptionOr<void> set_up_readable_stream_byob_reader(ReadableStreamBYOBReader& reader, ReadableStream& stream)
  696. {
  697. // 1. If ! IsReadableStreamLocked(stream) is true, throw a TypeError exception.
  698. if (is_readable_stream_locked(stream))
  699. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot create stream reader for a locked stream"sv };
  700. // 2. If stream.[[controller]] does not implement ReadableByteStreamController, throw a TypeError exception.
  701. if (!stream.controller()->has<JS::NonnullGCPtr<ReadableByteStreamController>>())
  702. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "BYOB reader cannot set up reader from non-byte stream"sv };
  703. // 3. Perform ! ReadableStreamReaderGenericInitialize(reader, stream).
  704. readable_stream_reader_generic_initialize(ReadableStreamReader { reader }, stream);
  705. // 4. Set reader.[[readIntoRequests]] to a new empty list.
  706. reader.read_into_requests().clear();
  707. return {};
  708. }
  709. // https://streams.spec.whatwg.org/#readable-stream-default-controller-close
  710. void readable_stream_default_controller_close(ReadableStreamDefaultController& controller)
  711. {
  712. // 1. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) is false, return.
  713. if (!readable_stream_default_controller_can_close_or_enqueue(controller))
  714. return;
  715. // 2. Let stream be controller.[[stream]].
  716. auto stream = controller.stream();
  717. // 3. Set controller.[[closeRequested]] to true.
  718. controller.set_close_requested(true);
  719. // 4. If controller.[[queue]] is empty,
  720. if (controller.queue().is_empty()) {
  721. // 1. Perform ! ReadableStreamDefaultControllerClearAlgorithms(controller).
  722. readable_stream_default_controller_clear_algorithms(controller);
  723. // 2. Perform ! ReadableStreamClose(stream).
  724. readable_stream_close(*stream);
  725. }
  726. }
  727. // https://streams.spec.whatwg.org/#rs-default-controller-has-backpressure
  728. bool readable_stream_default_controller_has_backpressure(ReadableStreamDefaultController& controller)
  729. {
  730. // 1. If ! ReadableStreamDefaultControllerShouldCallPull(controller) is true, return false.
  731. if (readable_stream_default_controller_should_call_pull(controller))
  732. return false;
  733. // 2. Otherwise, return true.
  734. return true;
  735. }
  736. // https://streams.spec.whatwg.org/#readable-stream-default-controller-enqueue
  737. WebIDL::ExceptionOr<void> readable_stream_default_controller_enqueue(ReadableStreamDefaultController& controller, JS::Value chunk)
  738. {
  739. auto& vm = controller.vm();
  740. // 1. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) is false, return.
  741. if (!readable_stream_default_controller_can_close_or_enqueue(controller))
  742. return {};
  743. // 2. Let stream be controller.[[stream]].
  744. auto stream = controller.stream();
  745. // 3. If ! IsReadableStreamLocked(stream) is true and ! ReadableStreamGetNumReadRequests(stream) > 0, perform ! ReadableStreamFulfillReadRequest(stream, chunk, false).
  746. if (is_readable_stream_locked(*stream) && readable_stream_get_num_read_requests(*stream) > 0) {
  747. readable_stream_fulfill_read_request(*stream, chunk, false);
  748. }
  749. // 4. Otherwise,
  750. else {
  751. // 1. Let result be the result of performing controller.[[strategySizeAlgorithm]], passing in chunk, and interpreting the result as a completion record.
  752. auto result = (*controller.strategy_size_algorithm())(chunk);
  753. // 2. If result is an abrupt completion,
  754. if (result.is_abrupt()) {
  755. // 1. Perform ! ReadableStreamDefaultControllerError(controller, result.[[Value]]).
  756. readable_stream_default_controller_error(controller, result.value().value());
  757. // 2. Return result.
  758. return result;
  759. }
  760. // 3. Let chunkSize be result.[[Value]].
  761. auto chunk_size = result.release_value().release_value();
  762. // 4. Let enqueueResult be EnqueueValueWithSize(controller, chunk, chunkSize).
  763. auto enqueue_result = enqueue_value_with_size(controller, chunk, chunk_size);
  764. // 5. If enqueueResult is an abrupt completion,
  765. if (enqueue_result.is_error()) {
  766. auto throw_completion = Bindings::throw_dom_exception_if_needed(vm, [&] { return enqueue_result; }).throw_completion();
  767. // 1. Perform ! ReadableStreamDefaultControllerError(controller, enqueueResult.[[Value]]).
  768. readable_stream_default_controller_error(controller, throw_completion.value().value());
  769. // 2. Return enqueueResult.
  770. // Note: We need to return the throw_completion object here, as enqueue needs to throw the same object that the controller is errored with
  771. return throw_completion;
  772. }
  773. }
  774. // 5. Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(controller).
  775. return readable_stream_default_controller_can_pull_if_needed(controller);
  776. }
  777. // https://streams.spec.whatwg.org/#readable-stream-default-controller-call-pull-if-needed
  778. WebIDL::ExceptionOr<void> readable_stream_default_controller_can_pull_if_needed(ReadableStreamDefaultController& controller)
  779. {
  780. // 1. Let shouldPull be ! ReadableStreamDefaultControllerShouldCallPull(controller).
  781. auto should_pull = readable_stream_default_controller_should_call_pull(controller);
  782. // 2. If shouldPull is false, return.
  783. if (!should_pull)
  784. return {};
  785. // 3. If controller.[[pulling]] is true,
  786. if (controller.pulling()) {
  787. // 1. Set controller.[[pullAgain]] to true.
  788. controller.set_pull_again(true);
  789. // 2. Return.
  790. return {};
  791. }
  792. // 4. Assert: controller.[[pullAgain]] is false.
  793. VERIFY(!controller.pull_again());
  794. // 5. Set controller.[[pulling]] to true.
  795. controller.set_pulling(true);
  796. // 6. Let pullPromise be the result of performing controller.[[pullAlgorithm]].
  797. auto pull_promise = TRY((*controller.pull_algorithm())());
  798. // 7. Upon fulfillment of pullPromise,
  799. WebIDL::upon_fulfillment(*pull_promise, [&](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  800. // 1. Set controller.[[pulling]] to false.
  801. controller.set_pulling(false);
  802. // 2. If controller.[[pullAgain]] is true,
  803. if (controller.pull_again()) {
  804. // 1. Set controller.[[pullAgain]] to false.
  805. controller.set_pull_again(false);
  806. // 2. Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(controller).
  807. TRY(readable_stream_default_controller_can_pull_if_needed(controller));
  808. }
  809. return JS::js_undefined();
  810. });
  811. // 8. Upon rejection of pullPromise with reason e,
  812. WebIDL::upon_rejection(*pull_promise, [&](auto const& e) -> WebIDL::ExceptionOr<JS::Value> {
  813. // 1. Perform ! ReadableStreamDefaultControllerError(controller, e).
  814. readable_stream_default_controller_error(controller, e);
  815. return JS::js_undefined();
  816. });
  817. return {};
  818. }
  819. // https://streams.spec.whatwg.org/#readable-stream-default-controller-should-call-pull
  820. bool readable_stream_default_controller_should_call_pull(ReadableStreamDefaultController& controller)
  821. {
  822. // 1. Let stream be controller.[[stream]].
  823. auto stream = controller.stream();
  824. // 2. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) is false, return false.
  825. if (!readable_stream_default_controller_can_close_or_enqueue(controller))
  826. return false;
  827. // 3. If controller.[[started]] is false, return false.
  828. if (!controller.started())
  829. return false;
  830. // 4. If ! IsReadableStreamLocked(stream) is true and ! ReadableStreamGetNumReadRequests(stream) > 0, return true.
  831. if (is_readable_stream_locked(*stream) && readable_stream_get_num_read_requests(*stream) > 0)
  832. return true;
  833. // 5. Let desiredSize be ! ReadableStreamDefaultControllerGetDesiredSize(controller).
  834. auto desired_size = readable_stream_default_controller_get_desired_size(controller);
  835. // 6. Assert: desiredSize is not null.
  836. VERIFY(desired_size.has_value());
  837. // 7. If desiredSize > 0, return true.
  838. if (desired_size.release_value() > 0.0)
  839. return true;
  840. // 8. Return false.
  841. return false;
  842. }
  843. // https://streams.spec.whatwg.org/#readable-stream-default-controller-clear-algorithms
  844. void readable_stream_default_controller_clear_algorithms(ReadableStreamDefaultController& controller)
  845. {
  846. // FIXME: This AO can be invoked from within one of the algorithms below. If we clear them, it invokes SafeFunction's
  847. // destructor, which asserts we are not currently invoking the function (as it clears the storage). We need to
  848. // figure out how to delay this, as these algorithms may keep objects alive that can otherwise be GC'd.
  849. (void)controller;
  850. // 1. Set controller.[[pullAlgorithm]] to undefined.
  851. // controller.set_pull_algorithm({});
  852. // 2. Set controller.[[cancelAlgorithm]] to undefined.
  853. // controller.set_cancel_algorithm({});
  854. // 3. Set controller.[[strategySizeAlgorithm]] to undefined.
  855. // controller.set_strategy_size_algorithm({});
  856. }
  857. // https://streams.spec.whatwg.org/#readable-stream-default-controller-error
  858. void readable_stream_default_controller_error(ReadableStreamDefaultController& controller, JS::Value error)
  859. {
  860. // 1. Let stream be controller.[[stream]].
  861. auto stream = controller.stream();
  862. // 2. If stream.[[state]] is not "readable", return.
  863. if (!stream->is_readable())
  864. return;
  865. // 3. Perform ! ResetQueue(controller).
  866. reset_queue(controller);
  867. // 4. Perform ! ReadableStreamDefaultControllerClearAlgorithms(controller).
  868. readable_stream_default_controller_clear_algorithms(controller);
  869. // 5. Perform ! ReadableStreamError(stream, e).
  870. readable_stream_error(*stream, error);
  871. }
  872. // https://streams.spec.whatwg.org/#readable-stream-default-controller-get-desired-size
  873. Optional<double> readable_stream_default_controller_get_desired_size(ReadableStreamDefaultController& controller)
  874. {
  875. auto stream = controller.stream();
  876. // 1. Let state be controller.[[stream]].[[state]].
  877. // 2. If state is "errored", return null.
  878. if (stream->is_errored())
  879. return {};
  880. // 3. If state is "closed", return 0.
  881. if (stream->is_closed())
  882. return 0.0;
  883. // 4. Return controller.[[strategyHWM]] − controller.[[queueTotalSize]].
  884. return controller.strategy_hwm() - controller.queue_total_size();
  885. }
  886. // https://streams.spec.whatwg.org/#readable-stream-default-controller-can-close-or-enqueue
  887. bool readable_stream_default_controller_can_close_or_enqueue(ReadableStreamDefaultController& controller)
  888. {
  889. // 1. Let state be controller.[[stream]].[[state]].
  890. // 2. If controller.[[closeRequested]] is false and state is "readable", return true.
  891. // 3. Otherwise, return false.
  892. return !controller.close_requested() && controller.stream()->is_readable();
  893. }
  894. // https://streams.spec.whatwg.org/#set-up-readable-stream-default-controller
  895. WebIDL::ExceptionOr<void> set_up_readable_stream_default_controller(ReadableStream& stream, ReadableStreamDefaultController& controller, StartAlgorithm&& start_algorithm, PullAlgorithm&& pull_algorithm, CancelAlgorithm&& cancel_algorithm, double high_water_mark, SizeAlgorithm&& size_algorithm)
  896. {
  897. auto& realm = stream.realm();
  898. // 1. Assert: stream.[[controller]] is undefined.
  899. VERIFY(!stream.controller().has_value());
  900. // 2. Set controller.[[stream]] to stream.
  901. controller.set_stream(stream);
  902. // 3. Perform ! ResetQueue(controller).
  903. reset_queue(controller);
  904. // 4. Set controller.[[started]], controller.[[closeRequested]], controller.[[pullAgain]], and controller.[[pulling]] to false.
  905. controller.set_started(false);
  906. controller.set_close_requested(false);
  907. controller.set_pull_again(false);
  908. controller.set_pulling(false);
  909. // 5. Set controller.[[strategySizeAlgorithm]] to sizeAlgorithm and controller.[[strategyHWM]] to highWaterMark.
  910. controller.set_strategy_size_algorithm(move(size_algorithm));
  911. controller.set_strategy_hwm(high_water_mark);
  912. // 6. Set controller.[[pullAlgorithm]] to pullAlgorithm.
  913. controller.set_pull_algorithm(move(pull_algorithm));
  914. // 7. Set controller.[[cancelAlgorithm]] to cancelAlgorithm.
  915. controller.set_cancel_algorithm(move(cancel_algorithm));
  916. // 8. Set stream.[[controller]] to controller.
  917. stream.set_controller(ReadableStreamController { controller });
  918. // 9. Let startResult be the result of performing startAlgorithm. (This might throw an exception.)
  919. auto start_result = TRY(start_algorithm());
  920. // 10. Let startPromise be a promise resolved with startResult.
  921. auto start_promise = WebIDL::create_resolved_promise(realm, start_result);
  922. // 11. Upon fulfillment of startPromise,
  923. WebIDL::upon_fulfillment(start_promise, [&](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  924. // 1. Set controller.[[started]] to true.
  925. controller.set_started(true);
  926. // 2. Assert: controller.[[pulling]] is false.
  927. VERIFY(!controller.pulling());
  928. // 3. Assert: controller.[[pullAgain]] is false.
  929. VERIFY(!controller.pull_again());
  930. // 4. Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(controller).
  931. TRY(readable_stream_default_controller_can_pull_if_needed(controller));
  932. return JS::js_undefined();
  933. });
  934. // 12. Upon rejection of startPromise with reason r,
  935. WebIDL::upon_rejection(start_promise, [&](auto const& r) -> WebIDL::ExceptionOr<JS::Value> {
  936. // 1. Perform ! ReadableStreamDefaultControllerError(controller, r).
  937. readable_stream_default_controller_error(controller, r);
  938. return JS::js_undefined();
  939. });
  940. return {};
  941. }
  942. // https://streams.spec.whatwg.org/#set-up-readable-stream-default-controller-from-underlying-source
  943. WebIDL::ExceptionOr<void> set_up_readable_stream_default_controller_from_underlying_source(ReadableStream& stream, JS::Value underlying_source_value, UnderlyingSource underlying_source, double high_water_mark, SizeAlgorithm&& size_algorithm)
  944. {
  945. auto& realm = stream.realm();
  946. // 1. Let controller be a new ReadableStreamDefaultController.
  947. auto controller = stream.heap().allocate<ReadableStreamDefaultController>(realm, realm);
  948. // 2. Let startAlgorithm be an algorithm that returns undefined.
  949. StartAlgorithm start_algorithm = [] { return JS::js_undefined(); };
  950. // 3. Let pullAlgorithm be an algorithm that returns a promise resolved with undefined.
  951. PullAlgorithm pull_algorithm = [&realm]() {
  952. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  953. };
  954. // 4. Let cancelAlgorithm be an algorithm that returns a promise resolved with undefined.
  955. CancelAlgorithm cancel_algorithm = [&realm](auto const&) {
  956. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  957. };
  958. // 5. If underlyingSourceDict["start"] exists, then set startAlgorithm to an algorithm which returns the result of invoking underlyingSourceDict["start"] with argument list « controller » and callback this value underlyingSource.
  959. if (underlying_source.start) {
  960. start_algorithm = [controller, underlying_source_value, callback = underlying_source.start]() -> WebIDL::ExceptionOr<JS::Value> {
  961. // Note: callback does not return a promise, so invoke_callback may return an abrupt completion
  962. return TRY(WebIDL::invoke_callback(*callback, underlying_source_value, controller)).release_value();
  963. };
  964. }
  965. // 6. If underlyingSourceDict["pull"] exists, then set pullAlgorithm to an algorithm which returns the result of invoking underlyingSourceDict["pull"] with argument list « controller » and callback this value underlyingSource.
  966. if (underlying_source.pull) {
  967. pull_algorithm = [&realm, controller, underlying_source_value, callback = underlying_source.pull]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  968. // Note: callback return a promise, so invoke_callback will never return an abrupt completion
  969. auto result = MUST_OR_THROW_OOM(WebIDL::invoke_callback(*callback, underlying_source_value, controller)).release_value();
  970. return WebIDL::create_resolved_promise(realm, result);
  971. };
  972. }
  973. // 7. If underlyingSourceDict["cancel"] exists, then set cancelAlgorithm to an algorithm which takes an argument reason and returns the result of invoking underlyingSourceDict["cancel"] with argument list « reason » and callback this value underlyingSource.
  974. if (underlying_source.cancel) {
  975. cancel_algorithm = [&realm, underlying_source_value, callback = underlying_source.cancel](auto const& reason) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  976. // Note: callback return a promise, so invoke_callback will never return an abrupt completion
  977. auto result = MUST_OR_THROW_OOM(WebIDL::invoke_callback(*callback, underlying_source_value, reason)).release_value();
  978. return WebIDL::create_resolved_promise(realm, result);
  979. };
  980. }
  981. // 8. Perform ? SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm).
  982. return set_up_readable_stream_default_controller(stream, controller, move(start_algorithm), move(pull_algorithm), move(cancel_algorithm), high_water_mark, move(size_algorithm));
  983. }
  984. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-call-pull-if-needed
  985. WebIDL::ExceptionOr<void> readable_byte_stream_controller_call_pull_if_needed(ReadableByteStreamController& controller)
  986. {
  987. // 1. Let shouldPull be ! ReadableByteStreamControllerShouldCallPull(controller).
  988. auto should_pull = readable_byte_stream_controller_should_call_pull(controller);
  989. // 2. If shouldPull is false, return.
  990. if (!should_pull)
  991. return {};
  992. // 3. If controller.[[pulling]] is true,
  993. if (controller.pulling()) {
  994. // 1. Set controller.[[pullAgain]] to true.
  995. controller.set_pull_again(true);
  996. // 2. Return.
  997. return {};
  998. }
  999. // 4. Assert: controller.[[pullAgain]] is false.
  1000. VERIFY(!controller.pull_again());
  1001. // 5. Set controller.[[pulling]] to true.
  1002. controller.set_pulling(true);
  1003. // 6. Let pullPromise be the result of performing controller.[[pullAlgorithm]].
  1004. auto pull_promise = TRY((*controller.pull_algorithm())());
  1005. // 7. Upon fulfillment of pullPromise,
  1006. WebIDL::upon_fulfillment(*pull_promise, [&](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  1007. // 1. Set controller.[[pulling]] to false.
  1008. controller.set_pulling(false);
  1009. // 2. If controller.[[pullAgain]] is true,
  1010. if (controller.pull_again()) {
  1011. // 1. Set controller.[[pullAgain]] to false.
  1012. controller.set_pull_again(false);
  1013. // 2. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
  1014. TRY(readable_byte_stream_controller_call_pull_if_needed(controller));
  1015. }
  1016. return JS::js_undefined();
  1017. });
  1018. // 8. Upon rejection of pullPromise with reason e,
  1019. WebIDL::upon_rejection(*pull_promise, [&](auto const& error) -> WebIDL::ExceptionOr<JS::Value> {
  1020. // 1. Perform ! ReadableByteStreamControllerError(controller, e).
  1021. readable_byte_stream_controller_error(controller, error);
  1022. return JS::js_undefined();
  1023. });
  1024. return {};
  1025. }
  1026. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-clear-algorithms
  1027. void readable_byte_stream_controller_clear_algorithms(ReadableByteStreamController& controller)
  1028. {
  1029. // FIXME: This AO can be invoked from within one of the algorithms below. If we clear them, it invokes SafeFunction's
  1030. // destructor, which asserts we are not currently invoking the function (as it clears the storage). We need to
  1031. // figure out how to delay this, as these algorithms may keep objects alive that can otherwise be GC'd.
  1032. (void)controller;
  1033. // 1. Set controller.[[pullAlgorithm]] to undefined.
  1034. // controller.set_pull_algorithm({});
  1035. // 2. Set controller.[[cancelAlgorithm]] to undefined.
  1036. // controller.set_cancel_algorithm({});
  1037. }
  1038. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-clear-pending-pull-intos
  1039. void readable_byte_stream_controller_clear_pending_pull_intos(ReadableByteStreamController& controller)
  1040. {
  1041. // 1. Perform ! ReadableByteStreamControllerInvalidateBYOBRequest(controller).
  1042. readable_byte_stream_controller_invalidate_byob_request(controller);
  1043. // 2. Set controller.[[pendingPullIntos]] to a new empty list.
  1044. controller.pending_pull_intos().clear();
  1045. }
  1046. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-close
  1047. WebIDL::ExceptionOr<void> readable_byte_stream_controller_close(ReadableByteStreamController& controller)
  1048. {
  1049. auto& realm = controller.realm();
  1050. // 1. Let stream be controller.[[stream]].
  1051. auto stream = controller.stream();
  1052. // 2. If controller.[[closeRequested]] is true or stream.[[state]] is not "readable", return.
  1053. if (controller.close_requested() || stream->state() != ReadableStream::State::Readable)
  1054. return {};
  1055. // 3. If controller.[[queueTotalSize]] > 0,
  1056. if (controller.queue_total_size() > 0.0) {
  1057. // 1. Set controller.[[closeRequested]] to true.
  1058. controller.set_close_requested(true);
  1059. // 2. Return.
  1060. return {};
  1061. }
  1062. // 4. If controller.[[pendingPullIntos]] is not empty,
  1063. if (!controller.pending_pull_intos().is_empty()) {
  1064. // 1. Let firstPendingPullInto be controller.[[pendingPullIntos]][0].
  1065. auto& first_pending_pull_into = controller.pending_pull_intos().first();
  1066. // 2. If firstPendingPullInto’s bytes filled > 0,
  1067. if (first_pending_pull_into.bytes_filled > 0) {
  1068. // 1. Let e be a new TypeError exception.
  1069. auto error = JS::TypeError::create(realm, "Cannot close controller in the middle of processing a write request"sv);
  1070. // 2. Perform ! ReadableByteStreamControllerError(controller, e).
  1071. readable_byte_stream_controller_error(controller, error);
  1072. // 3. Throw e.
  1073. return JS::throw_completion(error);
  1074. }
  1075. }
  1076. // 5. Perform ! ReadableByteStreamControllerClearAlgorithms(controller).
  1077. readable_byte_stream_controller_clear_algorithms(controller);
  1078. // 6. Perform ! ReadableStreamClose(stream).
  1079. readable_stream_close(*stream);
  1080. return {};
  1081. }
  1082. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-error
  1083. void readable_byte_stream_controller_error(ReadableByteStreamController& controller, JS::Value error)
  1084. {
  1085. // 1. Let stream be controller.[[stream]].
  1086. auto stream = controller.stream();
  1087. // 2. If stream.[[state]] is not "readable", return.
  1088. if (stream->state() != ReadableStream::State::Readable)
  1089. return;
  1090. // 3. Perform ! ReadableByteStreamControllerClearPendingPullIntos(controller).
  1091. readable_byte_stream_controller_clear_pending_pull_intos(controller);
  1092. // 4. Perform ! ResetQueue(controller).
  1093. reset_queue(controller);
  1094. // 5. Perform ! ReadableByteStreamControllerClearAlgorithms(controller).
  1095. readable_byte_stream_controller_clear_algorithms(controller);
  1096. // 6. Perform ! ReadableStreamError(stream, e).
  1097. readable_stream_error(*stream, error);
  1098. }
  1099. // https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerfillreadrequestfromqueue
  1100. WebIDL::ExceptionOr<void> readable_byte_stream_controller_fill_read_request_from_queue(ReadableByteStreamController& controller, JS::NonnullGCPtr<ReadRequest> read_request)
  1101. {
  1102. auto& vm = controller.vm();
  1103. auto& realm = controller.realm();
  1104. // 1. Assert: controller.[[queueTotalSize]] > 0.
  1105. VERIFY(controller.queue_total_size() > 0.0);
  1106. // 2. Let entry be controller.[[queue]][0].
  1107. // 3. Remove entry from controller.[[queue]].
  1108. auto entry = controller.queue().take_first();
  1109. // 4. Set controller.[[queueTotalSize]] to controller.[[queueTotalSize]] − entry’s byte length.
  1110. controller.set_queue_total_size(controller.queue_total_size() - entry.byte_length);
  1111. // 5. Perform ! ReadableByteStreamControllerHandleQueueDrain(controller).
  1112. TRY(readable_byte_stream_controller_handle_queue_drain(controller));
  1113. // 6. Let view be ! Construct(%Uint8Array%, « entry’s buffer, entry’s byte offset, entry’s byte length »).
  1114. auto view = MUST_OR_THROW_OOM(JS::construct(vm, *realm.intrinsics().uint8_array_constructor(), entry.buffer, JS::Value(entry.byte_offset), JS::Value(entry.byte_length)));
  1115. // 7. Perform readRequest’s chunk steps, given view.
  1116. read_request->on_chunk(view);
  1117. return {};
  1118. }
  1119. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-get-desired-size
  1120. Optional<double> readable_byte_stream_controller_get_desired_size(ReadableByteStreamController const& controller)
  1121. {
  1122. auto stream = controller.stream();
  1123. // 1. Let state be controller.[[stream]].[[state]].
  1124. // 2. If state is "errored", return null.
  1125. if (stream->is_errored())
  1126. return {};
  1127. // 3. If state is "closed", return 0.
  1128. if (stream->is_closed())
  1129. return 0.0;
  1130. // 4. Return controller.[[strategyHWM]] − controller.[[queueTotalSize]].
  1131. return controller.strategy_hwm() - controller.queue_total_size();
  1132. }
  1133. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-handle-queue-drain
  1134. WebIDL::ExceptionOr<void> readable_byte_stream_controller_handle_queue_drain(ReadableByteStreamController& controller)
  1135. {
  1136. // 1. Assert: controller.[[stream]].[[state]] is "readable".
  1137. VERIFY(controller.stream()->state() == ReadableStream::State::Readable);
  1138. // 2. If controller.[[queueTotalSize]] is 0 and controller.[[closeRequested]] is true,
  1139. if (controller.queue_total_size() == 0.0 && controller.close_requested()) {
  1140. // 1. Perform ! ReadableByteStreamControllerClearAlgorithms(controller).
  1141. readable_byte_stream_controller_clear_algorithms(controller);
  1142. // 2. Perform ! ReadableStreamClose(controller.[[stream]]).
  1143. readable_stream_close(*controller.stream());
  1144. }
  1145. // 3. Otherwise,
  1146. else {
  1147. // 1. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
  1148. TRY(readable_byte_stream_controller_call_pull_if_needed(controller));
  1149. }
  1150. return {};
  1151. }
  1152. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-invalidate-byob-request
  1153. void readable_byte_stream_controller_invalidate_byob_request(ReadableByteStreamController& controller)
  1154. {
  1155. // 1. If controller.[[byobRequest]] is null, return.
  1156. if (!controller.byob_request())
  1157. return;
  1158. // 2. Set controller.[[byobRequest]].[[controller]] to undefined.
  1159. controller.byob_request()->set_controller({});
  1160. // 3. Set controller.[[byobRequest]].[[view]] to null.
  1161. controller.byob_request()->set_view({});
  1162. // 4. Set controller.[[byobRequest]] to null.
  1163. controller.set_byob_request({});
  1164. }
  1165. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-error
  1166. bool readable_byte_stream_controller_should_call_pull(ReadableByteStreamController const& controller)
  1167. {
  1168. // 1. Let stream be controller.[[stream]].
  1169. auto stream = controller.stream();
  1170. // 2. If stream.[[state]] is not "readable", return false.
  1171. if (stream->state() != ReadableStream::State::Readable)
  1172. return false;
  1173. // 3. If controller.[[closeRequested]] is true, return false.
  1174. if (controller.close_requested())
  1175. return false;
  1176. // 4. If controller.[[started]] is false, return false.
  1177. if (!controller.started())
  1178. return false;
  1179. // 5. If ! ReadableStreamHasDefaultReader(stream) is true and ! ReadableStreamGetNumReadRequests(stream) > 0, return true.
  1180. if (readable_stream_has_default_reader(*stream) && readable_stream_get_num_read_requests(*stream) > 0)
  1181. return true;
  1182. // 6. If ! ReadableStreamHasBYOBReader(stream) is true and ! ReadableStreamGetNumReadIntoRequests(stream) > 0, return true.
  1183. if (readable_stream_has_byob_reader(*stream) && readable_stream_get_num_read_into_requests(*stream) > 0)
  1184. return true;
  1185. // 7. Let desiredSize be ! ReadableByteStreamControllerGetDesiredSize(controller).
  1186. auto desired_size = readable_byte_stream_controller_get_desired_size(controller);
  1187. // 8. Assert: desiredSize is not null.
  1188. VERIFY(desired_size.has_value());
  1189. // 9. If desiredSize > 0, return true.
  1190. if (*desired_size > 0.0)
  1191. return true;
  1192. // 10. Return false.
  1193. return false;
  1194. }
  1195. // https://streams.spec.whatwg.org/#create-readable-stream
  1196. WebIDL::ExceptionOr<JS::NonnullGCPtr<ReadableStream>> create_readable_stream(JS::Realm& realm, StartAlgorithm&& start_algorithm, PullAlgorithm&& pull_algorithm, CancelAlgorithm&& cancel_algorithm, Optional<double> high_water_mark, Optional<SizeAlgorithm>&& size_algorithm)
  1197. {
  1198. // 1. If highWaterMark was not passed, set it to 1.
  1199. if (!high_water_mark.has_value())
  1200. high_water_mark = 1.0;
  1201. // 2. If sizeAlgorithm was not passed, set it to an algorithm that returns 1.
  1202. if (!size_algorithm.has_value())
  1203. size_algorithm = [](auto const&) { return JS::normal_completion(JS::Value(1)); };
  1204. // 3. Assert: ! IsNonNegativeNumber(highWaterMark) is true.
  1205. VERIFY(is_non_negative_number(JS::Value { *high_water_mark }));
  1206. // 4. Let stream be a new ReadableStream.
  1207. auto stream = realm.heap().allocate<ReadableStream>(realm, realm);
  1208. // 5. Perform ! InitializeReadableStream(stream).
  1209. initialize_readable_stream(*stream);
  1210. // 6. Let controller be a new ReadableStreamDefaultController.
  1211. auto controller = realm.heap().allocate<ReadableStreamDefaultController>(realm, realm);
  1212. // 7. Perform ? SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm).
  1213. TRY(set_up_readable_stream_default_controller(*stream, *controller, move(start_algorithm), move(pull_algorithm), move(cancel_algorithm), *high_water_mark, move(*size_algorithm)));
  1214. // 8. Return stream.
  1215. return stream;
  1216. }
  1217. // https://streams.spec.whatwg.org/#create-writable-stream
  1218. WebIDL::ExceptionOr<JS::NonnullGCPtr<WritableStream>> create_writable_stream(JS::Realm& realm, StartAlgorithm&& start_algorithm, WriteAlgorithm&& write_algorithm, CloseAlgorithm&& close_algorithm, AbortAlgorithm&& abort_algorithm, double high_water_mark, SizeAlgorithm&& size_algorithm)
  1219. {
  1220. // 1. Assert: ! IsNonNegativeNumber(highWaterMark) is true.
  1221. VERIFY(is_non_negative_number(JS::Value { high_water_mark }));
  1222. // 2. Let stream be a new WritableStream.
  1223. auto stream = realm.heap().allocate<WritableStream>(realm, realm);
  1224. // 3. Perform ! InitializeWritableStream(stream).
  1225. initialize_writable_stream(*stream);
  1226. // 4. Let controller be a new WritableStreamDefaultController.
  1227. auto controller = realm.heap().allocate<WritableStreamDefaultController>(realm, realm);
  1228. // 5. Perform ? SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm).
  1229. TRY(set_up_writable_stream_default_controller(*stream, *controller, move(start_algorithm), move(write_algorithm), move(close_algorithm), move(abort_algorithm), high_water_mark, move(size_algorithm)));
  1230. // 6. Return stream.
  1231. return stream;
  1232. }
  1233. // https://streams.spec.whatwg.org/#initialize-readable-stream
  1234. void initialize_readable_stream(ReadableStream& stream)
  1235. {
  1236. // 1. Set stream.[[state]] to "readable".
  1237. stream.set_state(ReadableStream::State::Readable);
  1238. // 2. Set stream.[[reader]] and stream.[[storedError]] to undefined.
  1239. stream.set_reader({});
  1240. stream.set_stored_error({});
  1241. // 3. Set stream.[[disturbed]] to false.
  1242. stream.set_disturbed(false);
  1243. }
  1244. // https://streams.spec.whatwg.org/#initialize-writable-stream
  1245. void initialize_writable_stream(WritableStream& stream)
  1246. {
  1247. // 1. Set stream.[[state]] to "writable".
  1248. stream.set_state(WritableStream::State::Writable);
  1249. // 2. Set stream.[[storedError]], stream.[[writer]], stream.[[controller]], stream.[[inFlightWriteRequest]],
  1250. // stream.[[closeRequest]], stream.[[inFlightCloseRequest]], and stream.[[pendingAbortRequest]] to undefined.
  1251. stream.set_stored_error(JS::js_undefined());
  1252. stream.set_writer({});
  1253. stream.set_controller({});
  1254. stream.set_in_flight_write_request({});
  1255. stream.set_close_request({});
  1256. stream.set_in_flight_close_request({});
  1257. stream.set_pending_abort_request({});
  1258. // 3. Set stream.[[writeRequests]] to a new empty list.
  1259. stream.write_requests().clear();
  1260. // 4. Set stream.[[backpressure]] to false.
  1261. stream.set_backpressure(false);
  1262. }
  1263. // https://streams.spec.whatwg.org/#acquire-writable-stream-default-writer
  1264. WebIDL::ExceptionOr<JS::NonnullGCPtr<WritableStreamDefaultWriter>> acquire_writable_stream_default_writer(WritableStream& stream)
  1265. {
  1266. auto& realm = stream.realm();
  1267. // 1. Let writer be a new WritableStreamDefaultWriter.
  1268. auto writer = stream.heap().allocate<WritableStreamDefaultWriter>(realm, realm);
  1269. // 2. Perform ? SetUpWritableStreamDefaultWriter(writer, stream).
  1270. TRY(set_up_writable_stream_default_writer(*writer, stream));
  1271. // 3. Return writer.
  1272. return writer;
  1273. }
  1274. // https://streams.spec.whatwg.org/#is-writable-stream-locked
  1275. bool is_writable_stream_locked(WritableStream const& stream)
  1276. {
  1277. // 1. If stream.[[writer]] is undefined, return false.
  1278. if (!stream.writer())
  1279. return false;
  1280. // 2. Return true.
  1281. return true;
  1282. }
  1283. // https://streams.spec.whatwg.org/#set-up-writable-stream-default-writer
  1284. WebIDL::ExceptionOr<void> set_up_writable_stream_default_writer(WritableStreamDefaultWriter& writer, WritableStream& stream)
  1285. {
  1286. auto& realm = writer.realm();
  1287. // 1. If ! IsWritableStreamLocked(stream) is true, throw a TypeError exception.
  1288. if (is_writable_stream_locked(stream))
  1289. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Stream is locked"sv };
  1290. // 2. Set writer.[[stream]] to stream.
  1291. writer.set_stream(stream);
  1292. // 3. Set stream.[[writer]] to writer.
  1293. stream.set_writer(writer);
  1294. // 4. Let state be stream.[[state]].
  1295. auto state = stream.state();
  1296. // 5. If state is "writable",
  1297. if (state == WritableStream::State::Writable) {
  1298. // 1. If ! WritableStreamCloseQueuedOrInFlight(stream) is false and stream.[[backpressure]] is true, set writer.[[readyPromise]] to a new promise.
  1299. if (!writable_stream_close_queued_or_in_flight(stream) && stream.backpressure()) {
  1300. writer.set_ready_promise(WebIDL::create_promise(realm));
  1301. }
  1302. // 2. Otherwise, set writer.[[readyPromise]] to a promise resolved with undefined.
  1303. else {
  1304. writer.set_ready_promise(WebIDL::create_resolved_promise(realm, JS::js_undefined()));
  1305. }
  1306. // 3. Set writer.[[closedPromise]] to a new promise.
  1307. writer.set_closed_promise(WebIDL::create_promise(realm));
  1308. }
  1309. // 6. Otherwise, if state is "erroring",
  1310. else if (state == WritableStream::State::Erroring) {
  1311. // 1. Set writer.[[readyPromise]] to a promise rejected with stream.[[storedError]].
  1312. writer.set_ready_promise(WebIDL::create_rejected_promise(realm, stream.stored_error()));
  1313. // 2. Set writer.[[readyPromise]].[[PromiseIsHandled]] to true.
  1314. WebIDL::mark_promise_as_handled(*writer.ready_promise());
  1315. // 3. Set writer.[[closedPromise]] to a new promise.
  1316. writer.set_closed_promise(WebIDL::create_promise(realm));
  1317. }
  1318. // 7. Otherwise, if state is "closed",
  1319. else if (state == WritableStream::State::Closed) {
  1320. // 1. Set writer.[[readyPromise]] to a promise resolved with undefined.
  1321. writer.set_ready_promise(WebIDL::create_resolved_promise(realm, JS::js_undefined()));
  1322. // 2. Set writer.[[closedPromise]] to a promise resolved with undefined.
  1323. writer.set_closed_promise(WebIDL::create_resolved_promise(realm, JS::js_undefined()));
  1324. }
  1325. // 8. Otherwise,
  1326. else {
  1327. // 1. Assert: state is "errored".
  1328. VERIFY(state == WritableStream::State::Errored);
  1329. // 2. Let storedError be stream.[[storedError]].
  1330. auto stored_error = stream.stored_error();
  1331. // 3. Set writer.[[readyPromise]] to a promise rejected with storedError.
  1332. writer.set_ready_promise(WebIDL::create_rejected_promise(realm, stored_error));
  1333. // 4. Set writer.[[readyPromise]].[[PromiseIsHandled]] to true.
  1334. WebIDL::mark_promise_as_handled(*writer.ready_promise());
  1335. // 5. Set writer.[[closedPromise]] to a promise rejected with storedError.
  1336. writer.set_closed_promise(WebIDL::create_rejected_promise(realm, stored_error));
  1337. // 6. Set writer.[[closedPromise]].[[PromiseIsHandled]] to true.
  1338. WebIDL::mark_promise_as_handled(*writer.closed_promise());
  1339. }
  1340. return {};
  1341. }
  1342. // https://streams.spec.whatwg.org/#set-up-readable-byte-stream-controller
  1343. WebIDL::ExceptionOr<void> set_up_readable_byte_stream_controller(ReadableStream& stream, ReadableByteStreamController& controller, StartAlgorithm&& start_algorithm, PullAlgorithm&& pull_algorithm, CancelAlgorithm&& cancel_algorithm, double high_water_mark, JS::Value auto_allocate_chunk_size)
  1344. {
  1345. auto& realm = stream.realm();
  1346. // 1. Assert: stream.[[controller]] is undefined.
  1347. VERIFY(!stream.controller().has_value());
  1348. // 2. If autoAllocateChunkSize is not undefined,
  1349. if (!auto_allocate_chunk_size.is_undefined()) {
  1350. // 1. Assert: ! IsInteger(autoAllocateChunkSize) is true.
  1351. VERIFY(auto_allocate_chunk_size.is_integral_number());
  1352. // 2. Assert: autoAllocateChunkSize is positive.
  1353. VERIFY(auto_allocate_chunk_size.as_double() > 0);
  1354. }
  1355. // 3. Set controller.[[stream]] to stream.
  1356. controller.set_stream(stream);
  1357. // 4. Set controller.[[pullAgain]] and controller.[[pulling]] to false.
  1358. controller.set_pull_again(false);
  1359. controller.set_pulling(false);
  1360. // 5. Set controller.[[byobRequest]] to null.
  1361. controller.set_byob_request({});
  1362. // 6. Perform ! ResetQueue(controller).
  1363. reset_queue(controller);
  1364. // 7. Set controller.[[closeRequested]] and controller.[[started]] to false.
  1365. controller.set_close_requested(false);
  1366. controller.set_started(false);
  1367. // 8. Set controller.[[strategyHWM]] to highWaterMark.
  1368. controller.set_strategy_hwm(high_water_mark);
  1369. // 9. Set controller.[[pullAlgorithm]] to pullAlgorithm.
  1370. controller.set_pull_algorithm(move(pull_algorithm));
  1371. // 10. Set controller.[[cancelAlgorithm]] to cancelAlgorithm.
  1372. controller.set_cancel_algorithm(move(cancel_algorithm));
  1373. // 11. Set controller.[[autoAllocateChunkSize]] to autoAllocateChunkSize.
  1374. if (auto_allocate_chunk_size.is_integral_number())
  1375. controller.set_auto_allocate_chunk_size(auto_allocate_chunk_size.as_double());
  1376. // 12. Set controller.[[pendingPullIntos]] to a new empty list.
  1377. controller.pending_pull_intos().clear();
  1378. // 13. Set stream.[[controller]] to controller.
  1379. stream.set_controller(ReadableStreamController { controller });
  1380. // 14. Let startResult be the result of performing startAlgorithm.
  1381. auto start_result = TRY(start_algorithm());
  1382. // 15. Let startPromise be a promise resolved with startResult.
  1383. auto start_promise = WebIDL::create_resolved_promise(realm, start_result);
  1384. // 16. Upon fulfillment of startPromise,
  1385. WebIDL::upon_fulfillment(start_promise, [&](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  1386. // 1. Set controller.[[started]] to true.
  1387. controller.set_started(true);
  1388. // 2. Assert: controller.[[pulling]] is false.
  1389. VERIFY(!controller.pulling());
  1390. // 3. Assert: controller.[[pullAgain]] is false.
  1391. VERIFY(!controller.pull_again());
  1392. // 4. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
  1393. TRY(readable_byte_stream_controller_call_pull_if_needed(controller));
  1394. return JS::js_undefined();
  1395. });
  1396. // 17. Upon rejection of startPromise with reason r,
  1397. WebIDL::upon_rejection(start_promise, [&](auto const& r) -> WebIDL::ExceptionOr<JS::Value> {
  1398. // 1. Perform ! ReadableByteStreamControllerError(controller, r).
  1399. readable_byte_stream_controller_error(controller, r);
  1400. return JS::js_undefined();
  1401. });
  1402. return {};
  1403. }
  1404. // https://streams.spec.whatwg.org/#readablestream-enqueue
  1405. WebIDL::ExceptionOr<void> readable_stream_enqueue(ReadableStreamController& controller, JS::Value chunk)
  1406. {
  1407. // 1. If stream.[[controller]] implements ReadableStreamDefaultController,
  1408. if (controller.has<JS::NonnullGCPtr<ReadableStreamDefaultController>>()) {
  1409. // 1. Perform ! ReadableStreamDefaultControllerEnqueue(stream.[[controller]], chunk).
  1410. return readable_stream_default_controller_enqueue(controller.get<JS::NonnullGCPtr<ReadableStreamDefaultController>>(), chunk);
  1411. }
  1412. // 2. Otherwise,
  1413. else {
  1414. // 1. Assert: stream.[[controller]] implements ReadableByteStreamController.
  1415. VERIFY(controller.has<JS::NonnullGCPtr<ReadableByteStreamController>>());
  1416. auto readable_byte_controller = controller.get<JS::NonnullGCPtr<ReadableByteStreamController>>();
  1417. // FIXME: 2. Assert: chunk is an ArrayBufferView.
  1418. // 3. Let byobView be the current BYOB request view for stream.
  1419. auto byob_view = readable_byte_controller->byob_request();
  1420. // 4. If byobView is non-null, and chunk.[[ViewedArrayBuffer]] is byobView.[[ViewedArrayBuffer]], then:
  1421. if (byob_view) {
  1422. // FIXME: 1. Assert: chunk.[[ByteOffset]] is byobView.[[ByteOffset]].
  1423. // FIXME: 2. Assert: chunk.[[ByteLength]] ≤ byobView.[[ByteLength]].
  1424. // FIXME: 3. Perform ? ReadableByteStreamControllerRespond(stream.[[controller]], chunk.[[ByteLength]]).
  1425. TODO();
  1426. }
  1427. // 5. Otherwise, perform ? ReadableByteStreamControllerEnqueue(stream.[[controller]], chunk).
  1428. return readable_byte_stream_controller_enqueue(readable_byte_controller, chunk);
  1429. }
  1430. }
  1431. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-enqueue
  1432. WebIDL::ExceptionOr<void> readable_byte_stream_controller_enqueue(ReadableByteStreamController& controller, JS::Value chunk)
  1433. {
  1434. auto& vm = controller.vm();
  1435. auto& realm = controller.realm();
  1436. // 1. Let stream be controller.[[stream]].
  1437. auto stream = controller.stream();
  1438. // 2. If controller.[[closeRequested]] is true or stream.[[state]] is not "readable", return.
  1439. if (controller.close_requested() || stream->state() != ReadableStream ::State::Readable)
  1440. return {};
  1441. // 3. Let buffer be chunk.[[ViewedArrayBuffer]].
  1442. auto* typed_array = TRY(JS::typed_array_from(vm, chunk));
  1443. auto* buffer = typed_array->viewed_array_buffer();
  1444. // 4. Let byteOffset be chunk.[[ByteOffset]].
  1445. auto byte_offset = typed_array->byte_offset();
  1446. // 5. Let byteLength be chunk.[[ByteLength]].
  1447. auto byte_length = typed_array->byte_length();
  1448. // 6. If ! IsDetachedBuffer(buffer) is true, throw a TypeError exception.
  1449. if (buffer->is_detached()) {
  1450. auto error = JS::TypeError::create(realm, "Buffer is detached"sv);
  1451. return JS::throw_completion(error);
  1452. }
  1453. // 7. Let transferredBuffer be ? TransferArrayBuffer(buffer).
  1454. auto transferred_buffer = TRY(transfer_array_buffer(realm, *buffer));
  1455. // 8. If controller.[[pendingPullIntos]] is not empty,
  1456. if (!controller.pending_pull_intos().is_empty()) {
  1457. // 1. Let firstPendingPullInto be controller.[[pendingPullIntos]][0].
  1458. auto& first_pending_pull_into = controller.pending_pull_intos().first();
  1459. // 2. If ! IsDetachedBuffer(firstPendingPullInto’s buffer) is true, throw a TypeError exception.
  1460. if (first_pending_pull_into.buffer->is_detached()) {
  1461. auto error = JS::TypeError::create(realm, "Buffer is detached"sv);
  1462. return JS::throw_completion(error);
  1463. }
  1464. // 3. Perform ! ReadableByteStreamControllerInvalidateBYOBRequest(controller).
  1465. readable_byte_stream_controller_invalidate_byob_request(controller);
  1466. // 4. Set firstPendingPullInto’s buffer to ! TransferArrayBuffer(firstPendingPullInto’s buffer).
  1467. first_pending_pull_into.buffer = TRY(transfer_array_buffer(realm, first_pending_pull_into.buffer));
  1468. // 5. If firstPendingPullInto’s reader type is "none", perform ? ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto).
  1469. if (first_pending_pull_into.reader_type == ReaderType::None)
  1470. TRY(readable_byte_stream_controller_enqueue_detached_pull_into_queue(controller, first_pending_pull_into));
  1471. }
  1472. // 9. If ! ReadableStreamHasDefaultReader(stream) is true,
  1473. if (readable_stream_has_default_reader(*stream)) {
  1474. // 1. Perform ! ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller).
  1475. TRY(readable_byte_stream_controller_process_read_requests_using_queue(controller));
  1476. // 2. If ! ReadableStreamGetNumReadRequests(stream) is 0,
  1477. if (readable_stream_get_num_read_requests(*stream) == 0) {
  1478. // 1. Assert: controller.[[pendingPullIntos]] is empty.
  1479. VERIFY(controller.pending_pull_intos().is_empty());
  1480. // 2. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength).
  1481. readable_byte_stream_controller_enqueue_chunk_to_queue(controller, transferred_buffer, byte_offset, byte_length);
  1482. }
  1483. // 3. Otherwise.
  1484. else {
  1485. // 1. Assert: controller.[[queue]] is empty.
  1486. VERIFY(controller.queue().is_empty());
  1487. // 2. If controller.[[pendingPullIntos]] is not empty,
  1488. if (!controller.pending_pull_intos().is_empty()) {
  1489. // 1. Assert: controller.[[pendingPullIntos]][0]'s reader type is "default".
  1490. VERIFY(controller.pending_pull_intos().first().reader_type == ReaderType::Default);
  1491. // 2. Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).
  1492. readable_byte_stream_controller_shift_pending_pull_into(controller);
  1493. }
  1494. // 3. Let transferredView be ! Construct(%Uint8Array%, « transferredBuffer, byteOffset, byteLength »).
  1495. auto transferred_view = MUST_OR_THROW_OOM(JS::construct(vm, *realm.intrinsics().uint8_array_constructor(), transferred_buffer, JS::Value(byte_offset), JS::Value(byte_length)));
  1496. // 4. Perform ! ReadableStreamFulfillReadRequest(stream, transferredView, false).
  1497. readable_stream_fulfill_read_request(*stream, transferred_view, false);
  1498. }
  1499. }
  1500. // 10. Otherwise, if ! ReadableStreamHasBYOBReader(stream) is true,
  1501. else if (readable_stream_has_byob_reader(*stream)) {
  1502. // 1. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength).
  1503. readable_byte_stream_controller_enqueue_chunk_to_queue(controller, transferred_buffer, byte_offset, byte_length);
  1504. // 2. Perform ! ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller).
  1505. readable_byte_stream_controller_process_pull_into_descriptors_using_queue(controller);
  1506. }
  1507. // 11. Otherwise,
  1508. else {
  1509. // 1. Assert: ! IsReadableStreamLocked(stream) is false.
  1510. VERIFY(!is_readable_stream_locked(*stream));
  1511. // 2. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength).
  1512. readable_byte_stream_controller_enqueue_chunk_to_queue(controller, transferred_buffer, byte_offset, byte_length);
  1513. }
  1514. // 12. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
  1515. TRY(readable_byte_stream_controller_call_pull_if_needed(controller));
  1516. return {};
  1517. }
  1518. // https://streams.spec.whatwg.org/#transfer-array-buffer
  1519. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::ArrayBuffer>> transfer_array_buffer(JS::Realm& realm, JS::ArrayBuffer& buffer)
  1520. {
  1521. auto& vm = realm.vm();
  1522. // 1. Assert: ! IsDetachedBuffer(O) is false.
  1523. VERIFY(!buffer.is_detached());
  1524. // 2. Let arrayBufferData be O.[[ArrayBufferData]].
  1525. // 3. Let arrayBufferByteLength be O.[[ArrayBufferByteLength]].
  1526. auto array_buffer = buffer.buffer();
  1527. // 4. Perform ? DetachArrayBuffer(O).
  1528. TRY(JS::detach_array_buffer(vm, buffer));
  1529. // 5. Return a new ArrayBuffer object, created in the current Realm, whose [[ArrayBufferData]] internal slot value is arrayBufferData and whose [[ArrayBufferByteLength]] internal slot value is arrayBufferByteLength.
  1530. return JS::ArrayBuffer::create(realm, move(array_buffer));
  1531. }
  1532. // https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerenqueuedetachedpullintotoqueue
  1533. WebIDL::ExceptionOr<void> readable_byte_stream_controller_enqueue_detached_pull_into_queue(ReadableByteStreamController& controller, PullIntoDescriptor& pull_into_descriptor)
  1534. {
  1535. // 1. Assert: pullIntoDescriptor’s reader type is "none".
  1536. VERIFY(pull_into_descriptor.reader_type == ReaderType::None);
  1537. // 2. If pullIntoDescriptor’s bytes filled > 0, perform ? ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor’s buffer, pullIntoDescriptor’s byte offset, pullIntoDescriptor’s bytes filled).
  1538. if (pull_into_descriptor.bytes_filled > 0)
  1539. TRY(readable_byte_stream_controller_enqueue_cloned_chunk_to_queue(controller, pull_into_descriptor.buffer, pull_into_descriptor.byte_offset, pull_into_descriptor.bytes_filled));
  1540. // 3. Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).
  1541. readable_byte_stream_controller_shift_pending_pull_into(controller);
  1542. return {};
  1543. }
  1544. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-commit-pull-into-descriptor
  1545. void readable_byte_stream_controller_commit_pull_into_descriptor(ReadableStream& stream, PullIntoDescriptor const& pull_into_descriptor)
  1546. {
  1547. // 1. Assert: stream.[[state]] is not "errored".
  1548. VERIFY(!stream.is_errored());
  1549. // 2. Assert: pullIntoDescriptor.reader type is not "none".
  1550. VERIFY(pull_into_descriptor.reader_type != ReaderType::None);
  1551. // 3. Let done be false.
  1552. bool done = false;
  1553. // 4. If stream.[[state]] is "closed",
  1554. if (stream.is_closed()) {
  1555. // 1. Assert: pullIntoDescriptor’s bytes filled is 0.
  1556. VERIFY(pull_into_descriptor.bytes_filled == 0);
  1557. // 2. Set done to true.
  1558. done = true;
  1559. }
  1560. // 5. Let filledView be ! ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor).
  1561. auto filled_view = readable_byte_stream_controller_convert_pull_into_descriptor(stream.realm(), pull_into_descriptor);
  1562. // 6. If pullIntoDescriptor’s reader type is "default",
  1563. if (pull_into_descriptor.reader_type == ReaderType::Default) {
  1564. // 1. Perform ! ReadableStreamFulfillReadRequest(stream, filledView, done).
  1565. readable_stream_fulfill_read_request(stream, filled_view, done);
  1566. }
  1567. // 7. Otherwise,
  1568. else {
  1569. // 1. Assert: pullIntoDescriptor’s reader type is "byob".
  1570. VERIFY(pull_into_descriptor.reader_type == ReaderType::Byob);
  1571. // 2. Perform ! ReadableStreamFulfillReadIntoRequest(stream, filledView, done).
  1572. readable_stream_fulfill_read_into_request(stream, filled_view, done);
  1573. }
  1574. }
  1575. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-process-pull-into-descriptors-using-queue
  1576. void readable_byte_stream_controller_process_pull_into_descriptors_using_queue(ReadableByteStreamController& controller)
  1577. {
  1578. // 1. Assert: controller.[[closeRequested]] is false.
  1579. VERIFY(!controller.close_requested());
  1580. // 2. While controller.[[pendingPullIntos]] is not empty,
  1581. while (!controller.pending_pull_intos().is_empty()) {
  1582. // 1. If controller.[[queueTotalSize]] is 0, return.
  1583. if (controller.queue_total_size() == 0)
  1584. return;
  1585. // 2. Let pullIntoDescriptor be controller.[[pendingPullIntos]][0].
  1586. auto& pull_into_descriptor = controller.pending_pull_intos().first();
  1587. // 3. If ! ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) is true,
  1588. if (readable_byte_stream_controller_fill_pull_into_descriptor_from_queue(controller, pull_into_descriptor)) {
  1589. // NOTE: We store the returned pull into descriptor here as the 'shift pending pull into' will remove
  1590. // the first entry into the list which we have a reference to above.
  1591. // 1. Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).
  1592. auto descriptor = readable_byte_stream_controller_shift_pending_pull_into(controller);
  1593. // 2. Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(controller.[[stream]], pullIntoDescriptor).
  1594. readable_byte_stream_controller_commit_pull_into_descriptor(*controller.stream(), descriptor);
  1595. }
  1596. }
  1597. }
  1598. // https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerprocessreadrequestsusingqueue
  1599. WebIDL::ExceptionOr<void> readable_byte_stream_controller_process_read_requests_using_queue(ReadableByteStreamController& controller)
  1600. {
  1601. // 1. Let reader be controller.[[stream]].[[reader]].
  1602. auto reader = controller.stream()->reader();
  1603. // 2. Assert: reader implements ReadableStreamDefaultReader.
  1604. VERIFY(reader->has<JS::NonnullGCPtr<ReadableStreamDefaultReader>>());
  1605. // 3. While reader.[[readRequests]] is not empty,
  1606. auto readable_stream_default_reader = reader->get<JS::NonnullGCPtr<ReadableStreamDefaultReader>>();
  1607. while (!readable_stream_default_reader->read_requests().is_empty()) {
  1608. // 1. If controller.[[queueTotalSize]] is 0, return.
  1609. if (controller.queue_total_size() == 0.0)
  1610. return {};
  1611. // 2. Let readRequest be reader.[[readRequests]][0].
  1612. // 3. Remove readRequest from reader.[[readRequests]].
  1613. auto read_request = readable_stream_default_reader->read_requests().take_first();
  1614. // 4. Perform ! ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest).
  1615. TRY(readable_byte_stream_controller_fill_read_request_from_queue(controller, read_request));
  1616. }
  1617. return {};
  1618. }
  1619. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-enqueue-chunk-to-queue
  1620. void readable_byte_stream_controller_enqueue_chunk_to_queue(ReadableByteStreamController& controller, JS::NonnullGCPtr<JS::ArrayBuffer> buffer, u32 byte_offset, u32 byte_length)
  1621. {
  1622. // 1. Append a new readable byte stream queue entry with buffer buffer, byte offset byteOffset, and byte length byteLength to controller.[[queue]].
  1623. controller.queue().append(ReadableByteStreamQueueEntry {
  1624. .buffer = buffer,
  1625. .byte_offset = byte_offset,
  1626. .byte_length = byte_length,
  1627. });
  1628. // 2. Set controller.[[queueTotalSize]] to controller.[[queueTotalSize]] + byteLength.
  1629. controller.set_queue_total_size(controller.queue_total_size() + byte_length);
  1630. }
  1631. // https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerenqueueclonedchunktoqueue
  1632. WebIDL::ExceptionOr<void> readable_byte_stream_controller_enqueue_cloned_chunk_to_queue(ReadableByteStreamController& controller, JS::ArrayBuffer& buffer, u64 byte_offset, u64 byte_length)
  1633. {
  1634. auto& vm = controller.vm();
  1635. // 1. Let cloneResult be CloneArrayBuffer(buffer, byteOffset, byteLength, %ArrayBuffer%).
  1636. auto clone_result = JS::clone_array_buffer(vm, buffer, byte_offset, byte_length);
  1637. // 2. If cloneResult is an abrupt completion,
  1638. if (clone_result.is_throw_completion()) {
  1639. auto throw_completion = Bindings::throw_dom_exception_if_needed(vm, [&] { return clone_result; }).throw_completion();
  1640. // 1. Perform ! ReadableByteStreamControllerError(controller, cloneResult.[[Value]]).
  1641. readable_byte_stream_controller_error(controller, throw_completion.value().value());
  1642. // 2. Return cloneResult.
  1643. // Note: We need to return the throw_completion object here, as enqueue needs to throw the same object that the controller is errored with
  1644. return throw_completion;
  1645. }
  1646. // 3. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, cloneResult.[[Value]], 0, byteLength).
  1647. readable_byte_stream_controller_enqueue_chunk_to_queue(controller, *clone_result.release_value(), 0, byte_length);
  1648. return {};
  1649. }
  1650. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-shift-pending-pull-into
  1651. PullIntoDescriptor readable_byte_stream_controller_shift_pending_pull_into(ReadableByteStreamController& controller)
  1652. {
  1653. // 1. Assert: controller.[[byobRequest]] is null.
  1654. VERIFY(!controller.byob_request());
  1655. // 2. Let descriptor be controller.[[pendingPullIntos]][0].
  1656. // 3. Remove descriptor from controller.[[pendingPullIntos]].
  1657. auto descriptor = controller.pending_pull_intos().take_first();
  1658. // 4. Return descriptor.
  1659. return descriptor;
  1660. }
  1661. // https://streams.spec.whatwg.org/#readablestream-set-up-with-byte-reading-support
  1662. WebIDL::ExceptionOr<void> set_up_readable_stream_controller_with_byte_reading_support(ReadableStream& stream, Optional<PullAlgorithm>&& pull_algorithm, Optional<CancelAlgorithm>&& cancel_algorithm, double high_water_mark)
  1663. {
  1664. auto& realm = stream.realm();
  1665. // 1. Let startAlgorithm be an algorithm that returns undefined.
  1666. StartAlgorithm start_algorithm = [] { return JS::js_undefined(); };
  1667. // 2. Let pullAlgorithmWrapper be an algorithm that runs these steps:
  1668. PullAlgorithm pull_algorithm_wrapper = [&realm, pull_algorithm = move(pull_algorithm)]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  1669. // 1. Let result be the result of running pullAlgorithm, if pullAlgorithm was given, or null otherwise. If this throws an exception e, return a promise rejected with e.
  1670. JS::GCPtr<JS::PromiseCapability> result = nullptr;
  1671. if (pull_algorithm.has_value())
  1672. result = TRY(pull_algorithm.value()());
  1673. // 2. If result is a Promise, then return result.
  1674. if (result != nullptr)
  1675. return JS::NonnullGCPtr(*result);
  1676. // 3. Return a promise resolved with undefined.
  1677. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  1678. };
  1679. // 3. Let cancelAlgorithmWrapper be an algorithm that runs these steps:
  1680. CancelAlgorithm cancel_algorithm_wrapper = [&realm, cancel_algorithm = move(cancel_algorithm)](auto const& c) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  1681. // 1. Let result be the result of running cancelAlgorithm, if cancelAlgorithm was given, or null otherwise. If this throws an exception e, return a promise rejected with e.
  1682. JS::GCPtr<JS::PromiseCapability> result = nullptr;
  1683. if (cancel_algorithm.has_value())
  1684. result = TRY(cancel_algorithm.value()(c));
  1685. // 2. If result is a Promise, then return result.
  1686. if (result != nullptr)
  1687. return JS::NonnullGCPtr(*result);
  1688. // 3. Return a promise resolved with undefined.
  1689. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  1690. };
  1691. // 4. Perform ! InitializeReadableStream(stream).
  1692. // 5. Let controller be a new ReadableByteStreamController.
  1693. auto controller = stream.heap().allocate<ReadableByteStreamController>(realm, realm);
  1694. // 6. Perform ! SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithmWrapper, cancelAlgorithmWrapper, highWaterMark, undefined).
  1695. TRY(set_up_readable_byte_stream_controller(stream, controller, move(start_algorithm), move(pull_algorithm_wrapper), move(cancel_algorithm_wrapper), high_water_mark, JS::js_undefined()));
  1696. return {};
  1697. }
  1698. // https://streams.spec.whatwg.org/#writable-stream-abort
  1699. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_abort(WritableStream& stream, JS::Value reason)
  1700. {
  1701. auto& realm = stream.realm();
  1702. // 1. If stream.[[state]] is "closed" or "errored", return a promise resolved with undefined.
  1703. auto state = stream.state();
  1704. if (state == WritableStream::State::Closed || state == WritableStream::State::Errored)
  1705. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  1706. // 2. Signal abort on stream.[[controller]].[[signal]] with reason.
  1707. stream.controller()->signal()->signal_abort(reason);
  1708. // 3. Let state be stream.[[state]].
  1709. state = stream.state();
  1710. // 4. If state is "closed" or "errored", return a promise resolved with undefined.
  1711. if (state == WritableStream::State::Closed || state == WritableStream::State::Errored)
  1712. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  1713. // 5. If stream.[[pendingAbortRequest]] is not undefined, return stream.[[pendingAbortRequest]]'s promise.
  1714. if (stream.pending_abort_request().has_value())
  1715. return stream.pending_abort_request()->promise;
  1716. // 6. Assert: state is "writable" or "erroring".
  1717. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  1718. // 7. Let wasAlreadyErroring be false.
  1719. auto was_already_erroring = false;
  1720. // 8. If state is "erroring",
  1721. if (state == WritableStream::State::Erroring) {
  1722. // 1. Set wasAlreadyErroring to true.
  1723. was_already_erroring = true;
  1724. // 2. Set reason to undefined.
  1725. reason = JS::js_undefined();
  1726. }
  1727. // 9. Let promise be a new promise.
  1728. auto promise = WebIDL::create_promise(realm);
  1729. // 10. Set stream.[[pendingAbortRequest]] to a new pending abort request whose promise is promise, reason is reason, and was already erroring is wasAlreadyErroring.
  1730. stream.set_pending_abort_request(PendingAbortRequest { promise, reason, was_already_erroring });
  1731. // 11. If wasAlreadyErroring is false, perform ! WritableStreamStartErroring(stream, reason).
  1732. if (!was_already_erroring)
  1733. TRY(writable_stream_start_erroring(stream, reason));
  1734. // 12. Return promise.
  1735. return promise;
  1736. }
  1737. // https://streams.spec.whatwg.org/#writable-stream-close
  1738. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_close(WritableStream& stream)
  1739. {
  1740. auto& realm = stream.realm();
  1741. // 1. Let state be stream.[[state]].
  1742. auto state = stream.state();
  1743. // 2. If state is "closed" or "errored", return a promise rejected with a TypeError exception.
  1744. if (state == WritableStream::State::Closed || state == WritableStream::State::Errored) {
  1745. auto message = state == WritableStream::State::Closed ? "Cannot close a closed stream"sv : "Cannot close an errored stream"sv;
  1746. auto exception = JS::TypeError::create(realm, message);
  1747. return WebIDL::create_rejected_promise(realm, exception);
  1748. }
  1749. // 3. Assert: state is "writable" or "erroring".
  1750. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  1751. // 4. Assert: ! WritableStreamCloseQueuedOrInFlight(stream) is false.
  1752. VERIFY(!writable_stream_close_queued_or_in_flight(stream));
  1753. // 5. Let promise be a new promise.
  1754. auto promise = WebIDL::create_promise(realm);
  1755. // 6. Set stream.[[closeRequest]] to promise.
  1756. stream.set_close_request(promise);
  1757. // 7. Let writer be stream.[[writer]].
  1758. auto writer = stream.writer();
  1759. // 8. If writer is not undefined, and stream.[[backpressure]] is true, and state is "writable", resolve writer.[[readyPromise]] with undefined.
  1760. if (writer && stream.backpressure() && state == WritableStream::State::Writable)
  1761. WebIDL::resolve_promise(realm, *writer->ready_promise(), JS::js_undefined());
  1762. // 9. Perform ! WritableStreamDefaultControllerClose(stream.[[controller]]).
  1763. TRY(writable_stream_default_controller_close(*stream.controller()));
  1764. // 10. Return promise.
  1765. return promise;
  1766. }
  1767. // https://streams.spec.whatwg.org/#writable-stream-add-write-request
  1768. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_add_write_request(WritableStream& stream)
  1769. {
  1770. auto& realm = stream.realm();
  1771. auto& vm = stream.vm();
  1772. // 1. Assert: ! IsWritableStreamLocked(stream) is true.
  1773. VERIFY(is_writable_stream_locked(stream));
  1774. // 2. Assert: stream.[[state]] is "writable".
  1775. VERIFY(stream.state() == WritableStream::State::Writable);
  1776. // 3. Let promise be a new promise.
  1777. auto promise = WebIDL::create_promise(realm);
  1778. // 4. Append promise to stream.[[writeRequests]].
  1779. TRY_OR_THROW_OOM(vm, stream.write_requests().try_append(promise));
  1780. // 5. Return promise.
  1781. return promise;
  1782. }
  1783. // https://streams.spec.whatwg.org/#writable-stream-close-queued-or-in-flight
  1784. bool writable_stream_close_queued_or_in_flight(WritableStream const& stream)
  1785. {
  1786. // 1. If stream.[[closeRequest]] is undefined and stream.[[inFlightCloseRequest]] is undefined, return false.
  1787. if (!stream.close_request() && !stream.in_flight_write_request())
  1788. return false;
  1789. // 2. Return true.
  1790. return true;
  1791. }
  1792. // https://streams.spec.whatwg.org/#writable-stream-deal-with-rejection
  1793. WebIDL::ExceptionOr<void> writable_stream_deal_with_rejection(WritableStream& stream, JS::Value error)
  1794. {
  1795. // 1. Let state be stream.[[state]].
  1796. auto state = stream.state();
  1797. // 2. If state is "writable",
  1798. if (state == WritableStream::State::Writable) {
  1799. // 1. Perform ! WritableStreamStartErroring(stream, error).
  1800. // 2. Return.
  1801. return writable_stream_start_erroring(stream, error);
  1802. }
  1803. // 3. Assert: state is "erroring".
  1804. VERIFY(state == WritableStream::State::Erroring);
  1805. // 4. Perform ! WritableStreamFinishErroring(stream).
  1806. return writable_stream_finish_erroring(stream);
  1807. }
  1808. // https://streams.spec.whatwg.org/#writable-stream-finish-erroring
  1809. WebIDL::ExceptionOr<void> writable_stream_finish_erroring(WritableStream& stream)
  1810. {
  1811. auto& realm = stream.realm();
  1812. // 1. Assert: stream.[[state]] is "erroring".
  1813. VERIFY(stream.state() == WritableStream::State::Erroring);
  1814. // 2. Assert: ! WritableStreamHasOperationMarkedInFlight(stream) is false.
  1815. VERIFY(!writable_stream_has_operation_marked_in_flight(stream));
  1816. // 3. Set stream.[[state]] to "errored".
  1817. stream.set_state(WritableStream::State::Errored);
  1818. // 4. Perform ! stream.[[controller]].[[ErrorSteps]]().
  1819. stream.controller()->error_steps();
  1820. // 5. Let storedError be stream.[[storedError]].
  1821. auto stored_error = stream.stored_error();
  1822. // 6. For each writeRequest of stream.[[writeRequests]]:
  1823. for (auto& write_request : stream.write_requests()) {
  1824. // 1. Reject writeRequest with storedError.
  1825. WebIDL::reject_promise(realm, *write_request, stored_error);
  1826. }
  1827. // 7. Set stream.[[writeRequests]] to an empty list.
  1828. stream.write_requests().clear();
  1829. // 8. If stream.[[pendingAbortRequest]] is undefined,
  1830. if (!stream.pending_abort_request().has_value()) {
  1831. // 1. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).
  1832. writable_stream_reject_close_and_closed_promise_if_needed(stream);
  1833. // 2. Return.
  1834. return {};
  1835. }
  1836. // 9. Let abortRequest be stream.[[pendingAbortRequest]].
  1837. // 10. Set stream.[[pendingAbortRequest]] to undefined.
  1838. auto abort_request = stream.pending_abort_request().release_value();
  1839. // 11. If abortRequest’s was already erroring is true,
  1840. if (abort_request.was_already_erroring) {
  1841. // 1. Reject abortRequest’s promise with storedError.
  1842. WebIDL::reject_promise(realm, abort_request.promise, stored_error);
  1843. // 2. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).
  1844. writable_stream_reject_close_and_closed_promise_if_needed(stream);
  1845. // 3. Return.
  1846. return {};
  1847. }
  1848. // 12. Let promise be ! stream.[[controller]].[[AbortSteps]](abortRequest’s reason).
  1849. auto promise = TRY(stream.controller()->abort_steps(abort_request.reason));
  1850. // 13. Upon fulfillment of promise,
  1851. WebIDL::upon_fulfillment(*promise, [&, abort_promise = abort_request.promise](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  1852. // 1. Resolve abortRequest’s promise with undefined.
  1853. WebIDL::resolve_promise(realm, abort_promise, JS::js_undefined());
  1854. // 2. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).
  1855. writable_stream_reject_close_and_closed_promise_if_needed(stream);
  1856. return JS::js_undefined();
  1857. });
  1858. // 14. Upon rejection of promise with reason reason,
  1859. WebIDL::upon_rejection(*promise, [&, abort_promise = abort_request.promise](auto const& reason) -> WebIDL::ExceptionOr<JS::Value> {
  1860. // 1. Reject abortRequest’s promise with reason.
  1861. WebIDL::reject_promise(realm, abort_promise, reason);
  1862. // 2. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).
  1863. writable_stream_reject_close_and_closed_promise_if_needed(stream);
  1864. return JS::js_undefined();
  1865. });
  1866. return {};
  1867. }
  1868. // https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-close
  1869. void writable_stream_finish_in_flight_close(WritableStream& stream)
  1870. {
  1871. auto& realm = stream.realm();
  1872. // 1. Assert: stream.[[inFlightCloseRequest]] is not undefined.
  1873. VERIFY(stream.in_flight_close_request());
  1874. // 2. Resolve stream.[[inFlightCloseRequest]] with undefined.
  1875. WebIDL::resolve_promise(realm, *stream.in_flight_close_request(), JS::js_undefined());
  1876. // 3. Set stream.[[inFlightCloseRequest]] to undefined.
  1877. stream.set_in_flight_close_request({});
  1878. // 4. Let state be stream.[[state]].
  1879. auto state = stream.state();
  1880. // 5. Assert: stream.[[state]] is "writable" or "erroring".
  1881. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  1882. // 6. If state is "erroring",
  1883. if (state == WritableStream::State::Erroring) {
  1884. // 1. Set stream.[[storedError]] to undefined.
  1885. stream.set_stored_error(JS::js_undefined());
  1886. // 2. If stream.[[pendingAbortRequest]] is not undefined,
  1887. if (stream.pending_abort_request().has_value()) {
  1888. // 1. Resolve stream.[[pendingAbortRequest]]'s promise with undefined.
  1889. // 2. Set stream.[[pendingAbortRequest]] to undefined.
  1890. WebIDL::resolve_promise(realm, stream.pending_abort_request().release_value().promise, JS::js_undefined());
  1891. }
  1892. }
  1893. // 7. Set stream.[[state]] to "closed".
  1894. stream.set_state(WritableStream::State::Closed);
  1895. // 8. Let writer be stream.[[writer]].
  1896. auto writer = stream.writer();
  1897. // 9. If writer is not undefined, resolve writer.[[closedPromise]] with undefined.
  1898. if (writer)
  1899. WebIDL::resolve_promise(realm, *writer->closed_promise(), JS::js_undefined());
  1900. // 10. Assert: stream.[[pendingAbortRequest]] is undefined.
  1901. VERIFY(!stream.pending_abort_request().has_value());
  1902. // 11. Assert: stream.[[storedError]] is undefined.
  1903. VERIFY(stream.stored_error().is_undefined());
  1904. }
  1905. // https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-close-with-error
  1906. WebIDL::ExceptionOr<void> writable_stream_finish_in_flight_close_with_error(WritableStream& stream, JS::Value error)
  1907. {
  1908. auto& realm = stream.realm();
  1909. // 1. Assert: stream.[[inFlightCloseRequest]] is not undefined.
  1910. VERIFY(stream.in_flight_close_request());
  1911. // 2. Reject stream.[[inFlightCloseRequest]] with error.
  1912. WebIDL::reject_promise(realm, *stream.in_flight_close_request(), error);
  1913. // 3. Set stream.[[inFlightCloseRequest]] to undefined.
  1914. stream.set_in_flight_close_request({});
  1915. // 4. Assert: stream.[[state]] is "writable" or "erroring".
  1916. auto state = stream.state();
  1917. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  1918. // 5. If stream.[[pendingAbortRequest]] is not undefined,
  1919. if (stream.pending_abort_request().has_value()) {
  1920. // 1. Reject stream.[[pendingAbortRequest]]'s promise with error.
  1921. // 2. Set stream.[[pendingAbortRequest]] to undefined.
  1922. WebIDL::reject_promise(realm, stream.pending_abort_request().release_value().promise, error);
  1923. }
  1924. // 6. Perform ! WritableStreamDealWithRejection(stream, error).
  1925. return writable_stream_deal_with_rejection(stream, error);
  1926. }
  1927. // https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-write
  1928. void writable_stream_finish_in_flight_write(WritableStream& stream)
  1929. {
  1930. auto& realm = stream.realm();
  1931. // 1. Assert: stream.[[inFlightWriteRequest]] is not undefined.
  1932. VERIFY(stream.in_flight_write_request());
  1933. // 2. Resolve stream.[[inFlightWriteRequest]] with undefined.
  1934. WebIDL::resolve_promise(realm, *stream.in_flight_write_request(), JS::js_undefined());
  1935. // 3. Set stream.[[inFlightWriteRequest]] to undefined.
  1936. stream.set_in_flight_write_request({});
  1937. }
  1938. // https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-write-with-error
  1939. WebIDL::ExceptionOr<void> writable_stream_finish_in_flight_write_with_error(WritableStream& stream, JS::Value error)
  1940. {
  1941. auto& realm = stream.realm();
  1942. // 1. Assert: stream.[[inFlightWriteRequest]] is not undefined.
  1943. VERIFY(stream.in_flight_write_request());
  1944. // 2. Reject stream.[[inFlightWriteRequest]] with error.
  1945. WebIDL::reject_promise(realm, *stream.in_flight_write_request(), error);
  1946. // 3. Set stream.[[inFlightWriteRequest]] to undefined.
  1947. stream.set_in_flight_write_request({});
  1948. // 4. Assert: stream.[[state]] is "writable" or "erroring".
  1949. auto state = stream.state();
  1950. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  1951. // 5. Perform ! WritableStreamDealWithRejection(stream, error).
  1952. return writable_stream_deal_with_rejection(stream, error);
  1953. }
  1954. // https://streams.spec.whatwg.org/#writable-stream-has-operation-marked-in-flight
  1955. bool writable_stream_has_operation_marked_in_flight(WritableStream const& stream)
  1956. {
  1957. // 1. If stream.[[inFlightWriteRequest]] is undefined and stream.[[inFlightCloseRequest]] is undefined, return false.
  1958. if (!stream.in_flight_write_request() && !stream.in_flight_close_request())
  1959. return false;
  1960. // 2. Return true.
  1961. return true;
  1962. }
  1963. // https://streams.spec.whatwg.org/#writable-stream-mark-close-request-in-flight
  1964. void writable_stream_mark_close_request_in_flight(WritableStream& stream)
  1965. {
  1966. // 1. Assert: stream.[[inFlightCloseRequest]] is undefined.
  1967. VERIFY(!stream.in_flight_close_request());
  1968. // 2. Assert: stream.[[closeRequest]] is not undefined.
  1969. VERIFY(stream.close_request());
  1970. // 3. Set stream.[[inFlightCloseRequest]] to stream.[[closeRequest]].
  1971. stream.set_in_flight_close_request(stream.close_request());
  1972. // 4. Set stream.[[closeRequest]] to undefined.
  1973. stream.set_close_request({});
  1974. }
  1975. // https://streams.spec.whatwg.org/#writable-stream-mark-first-write-request-in-flight
  1976. void writable_stream_mark_first_write_request_in_flight(WritableStream& stream)
  1977. {
  1978. // 1. Assert: stream.[[inFlightWriteRequest]] is undefined.
  1979. VERIFY(!stream.in_flight_write_request());
  1980. // 2. Assert: stream.[[writeRequests]] is not empty.
  1981. VERIFY(!stream.write_requests().is_empty());
  1982. // 3. Let writeRequest be stream.[[writeRequests]][0].
  1983. // 4. Remove writeRequest from stream.[[writeRequests]].
  1984. auto write_request = stream.write_requests().take_first();
  1985. // 5. Set stream.[[inFlightWriteRequest]] to writeRequest.
  1986. stream.set_in_flight_write_request(write_request);
  1987. }
  1988. // https://streams.spec.whatwg.org/#writable-stream-reject-close-and-closed-promise-if-needed
  1989. void writable_stream_reject_close_and_closed_promise_if_needed(WritableStream& stream)
  1990. {
  1991. auto& realm = stream.realm();
  1992. // 1. Assert: stream.[[state]] is "errored".
  1993. VERIFY(stream.state() == WritableStream::State::Errored);
  1994. // 2. If stream.[[closeRequest]] is not undefined,
  1995. if (stream.close_request()) {
  1996. // 1. Assert: stream.[[inFlightCloseRequest]] is undefined.
  1997. VERIFY(!stream.in_flight_close_request());
  1998. // 2. Reject stream.[[closeRequest]] with stream.[[storedError]].
  1999. WebIDL::reject_promise(realm, *stream.close_request(), stream.stored_error());
  2000. // 3. Set stream.[[closeRequest]] to undefined.
  2001. stream.set_close_request({});
  2002. }
  2003. // 3. Let writer be stream.[[writer]].
  2004. auto writer = stream.writer();
  2005. // 4. If writer is not undefined,
  2006. if (writer) {
  2007. // 1. Reject writer.[[closedPromise]] with stream.[[storedError]].
  2008. WebIDL::reject_promise(realm, *writer->closed_promise(), stream.stored_error());
  2009. // 2. Set writer.[[closedPromise]].[[PromiseIsHandled]] to true.
  2010. WebIDL::mark_promise_as_handled(*writer->closed_promise());
  2011. }
  2012. }
  2013. // https://streams.spec.whatwg.org/#writable-stream-start-erroring
  2014. WebIDL::ExceptionOr<void> writable_stream_start_erroring(WritableStream& stream, JS::Value reason)
  2015. {
  2016. // 1. Assert: stream.[[storedError]] is undefined.
  2017. VERIFY(stream.stored_error().is_undefined());
  2018. // 2. Assert: stream.[[state]] is "writable".
  2019. VERIFY(stream.state() == WritableStream::State::Writable);
  2020. // 3. Let controller be stream.[[controller]].
  2021. auto controller = stream.controller();
  2022. // 4. Assert: controller is not undefined.
  2023. VERIFY(controller);
  2024. // 5. Set stream.[[state]] to "erroring".
  2025. stream.set_state(WritableStream::State::Erroring);
  2026. // 6. Set stream.[[storedError]] to reason.
  2027. stream.set_stored_error(reason);
  2028. // 7. Let writer be stream.[[writer]].
  2029. auto writer = stream.writer();
  2030. // 8. If writer is not undefined, perform ! WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason).
  2031. if (writer)
  2032. writable_stream_default_writer_ensure_ready_promise_rejected(*writer, reason);
  2033. // 9. If ! WritableStreamHasOperationMarkedInFlight(stream) is false and controller.[[started]] is true, perform ! WritableStreamFinishErroring(stream).
  2034. if (!writable_stream_has_operation_marked_in_flight(stream) && controller->started())
  2035. TRY(writable_stream_finish_erroring(stream));
  2036. return {};
  2037. }
  2038. // https://streams.spec.whatwg.org/#writable-stream-update-backpressure
  2039. void writable_stream_update_backpressure(WritableStream& stream, bool backpressure)
  2040. {
  2041. auto& realm = stream.realm();
  2042. // 1. Assert: stream.[[state]] is "writable".
  2043. VERIFY(stream.state() == WritableStream::State::Writable);
  2044. // 2. Assert: ! WritableStreamCloseQueuedOrInFlight(stream) is false.
  2045. VERIFY(!writable_stream_close_queued_or_in_flight(stream));
  2046. // 3. Let writer be stream.[[writer]].
  2047. auto writer = stream.writer();
  2048. // 4. If writer is not undefined and backpressure is not stream.[[backpressure]],
  2049. if (writer && backpressure != stream.backpressure()) {
  2050. // 1. If backpressure is true, set writer.[[readyPromise]] to a new promise.
  2051. if (backpressure) {
  2052. writer->set_ready_promise(WebIDL::create_promise(realm));
  2053. }
  2054. // 2. Otherwise,
  2055. else {
  2056. // 1. Assert: backpressure is false.
  2057. // 2. Resolve writer.[[readyPromise]] with undefined.
  2058. WebIDL::resolve_promise(realm, *writer->ready_promise(), JS::js_undefined());
  2059. }
  2060. }
  2061. // 5. Set stream.[[backpressure]] to backpressure.
  2062. stream.set_backpressure(backpressure);
  2063. }
  2064. // https://streams.spec.whatwg.org/#writable-stream-default-writer-abort
  2065. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_default_writer_abort(WritableStreamDefaultWriter& writer, JS::Value reason)
  2066. {
  2067. // 1. Let stream be writer.[[stream]].
  2068. auto stream = writer.stream();
  2069. // 2. Assert: stream is not undefined.
  2070. VERIFY(stream);
  2071. // 3. Return ! WritableStreamAbort(stream, reason).
  2072. return writable_stream_abort(*stream, reason);
  2073. }
  2074. // https://streams.spec.whatwg.org/#writable-stream-default-writer-close
  2075. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_default_writer_close(WritableStreamDefaultWriter& writer)
  2076. {
  2077. // 1. Let stream be writer.[[stream]].
  2078. auto stream = writer.stream();
  2079. // 2. Assert: stream is not undefined.
  2080. VERIFY(stream);
  2081. // 3. Return ! WritableStreamClose(stream).
  2082. return writable_stream_close(*stream);
  2083. }
  2084. // https://streams.spec.whatwg.org/#writable-stream-default-writer-ensure-closed-promise-rejected
  2085. void writable_stream_default_writer_ensure_closed_promise_rejected(WritableStreamDefaultWriter& writer, JS::Value error)
  2086. {
  2087. auto& realm = writer.realm();
  2088. // 1. If writer.[[closedPromise]].[[PromiseState]] is "pending", reject writer.[[closedPromise]] with error.
  2089. auto& closed_promise = verify_cast<JS::Promise>(*writer.closed_promise()->promise());
  2090. if (closed_promise.state() == JS::Promise::State::Pending) {
  2091. WebIDL::reject_promise(realm, *writer.closed_promise(), error);
  2092. }
  2093. // 2. Otherwise, set writer.[[closedPromise]] to a promise rejected with error.
  2094. else {
  2095. writer.set_closed_promise(WebIDL::create_rejected_promise(realm, error));
  2096. }
  2097. // 3. Set writer.[[closedPromise]].[[PromiseIsHandled]] to true.
  2098. WebIDL::mark_promise_as_handled(*writer.closed_promise());
  2099. }
  2100. // https://streams.spec.whatwg.org/#writable-stream-default-writer-ensure-ready-promise-rejected
  2101. void writable_stream_default_writer_ensure_ready_promise_rejected(WritableStreamDefaultWriter& writer, JS::Value error)
  2102. {
  2103. auto& realm = writer.realm();
  2104. // 1. If writer.[[readyPromise]].[[PromiseState]] is "pending", reject writer.[[readyPromise]] with error.
  2105. auto& ready_promise = verify_cast<JS::Promise>(*writer.ready_promise()->promise());
  2106. if (ready_promise.state() == JS::Promise::State::Pending) {
  2107. WebIDL::reject_promise(realm, *writer.ready_promise(), error);
  2108. }
  2109. // 2. Otherwise, set writer.[[readyPromise]] to a promise rejected with error.
  2110. else {
  2111. writer.set_ready_promise(WebIDL::create_rejected_promise(realm, error));
  2112. }
  2113. // 3. Set writer.[[readyPromise]].[[PromiseIsHandled]] to true.
  2114. WebIDL::mark_promise_as_handled(*writer.ready_promise());
  2115. }
  2116. // https://streams.spec.whatwg.org/#writable-stream-default-writer-get-desired-size
  2117. Optional<double> writable_stream_default_writer_get_desired_size(WritableStreamDefaultWriter const& writer)
  2118. {
  2119. // 1. Let stream be writer.[[stream]].
  2120. auto stream = writer.stream();
  2121. // 2. Let state be stream.[[state]].
  2122. auto state = stream->state();
  2123. // 3. If state is "errored" or "erroring", return null.
  2124. if (state == WritableStream::State::Errored || state == WritableStream::State::Erroring)
  2125. return {};
  2126. // 4. If state is "closed", return 0.
  2127. if (state == WritableStream::State::Closed)
  2128. return 0.0;
  2129. // 5. Return ! WritableStreamDefaultControllerGetDesiredSize(stream.[[controller]]).
  2130. return writable_stream_default_controller_get_desired_size(*stream->controller());
  2131. }
  2132. // https://streams.spec.whatwg.org/#writable-stream-default-writer-release
  2133. WebIDL::ExceptionOr<void> writable_stream_default_writer_release(WritableStreamDefaultWriter& writer)
  2134. {
  2135. auto& realm = writer.realm();
  2136. // 1. Let stream be writer.[[stream]].
  2137. auto stream = writer.stream();
  2138. // 2. Assert: stream is not undefined.
  2139. VERIFY(stream);
  2140. // 3. Assert: stream.[[writer]] is writer.
  2141. VERIFY(stream->writer().ptr() == &writer);
  2142. // 4. Let releasedError be a new TypeError.
  2143. auto released_error = JS::TypeError::create(realm, "Writer's stream lock has been released"sv);
  2144. // 5. Perform ! WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError).
  2145. writable_stream_default_writer_ensure_ready_promise_rejected(writer, released_error);
  2146. // 6. Perform ! WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError).
  2147. writable_stream_default_writer_ensure_closed_promise_rejected(writer, released_error);
  2148. // 7. Set stream.[[writer]] to undefined.
  2149. stream->set_writer({});
  2150. // 8. Set writer.[[stream]] to undefined.
  2151. writer.set_stream({});
  2152. return {};
  2153. }
  2154. // https://streams.spec.whatwg.org/#writable-stream-default-writer-write
  2155. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_default_writer_write(WritableStreamDefaultWriter& writer, JS::Value chunk)
  2156. {
  2157. auto& realm = writer.realm();
  2158. // 1. Let stream be writer.[[stream]].
  2159. auto stream = writer.stream();
  2160. // 2. Assert: stream is not undefined.
  2161. VERIFY(stream);
  2162. // 3. Let controller be stream.[[controller]].
  2163. auto controller = stream->controller();
  2164. // 4. Let chunkSize be ! WritableStreamDefaultControllerGetChunkSize(controller, chunk).
  2165. auto chunk_size = TRY(writable_stream_default_controller_get_chunk_size(*controller, chunk));
  2166. // 5. If stream is not equal to writer.[[stream]], return a promise rejected with a TypeError exception.
  2167. if (stream.ptr() != writer.stream().ptr()) {
  2168. auto exception = JS::TypeError::create(realm, "Writer's locked stream changed during write"sv);
  2169. return WebIDL::create_rejected_promise(realm, exception);
  2170. }
  2171. // 6. Let state be stream.[[state]].
  2172. auto state = stream->state();
  2173. // 7. If state is "errored", return a promise rejected with stream.[[storedError]].
  2174. if (state == WritableStream::State::Errored)
  2175. return WebIDL::create_rejected_promise(realm, stream->stored_error());
  2176. // 8. If ! WritableStreamCloseQueuedOrInFlight(stream) is true or state is "closed", return a promise rejected with a TypeError exception indicating that the stream is closing or closed.
  2177. if (writable_stream_close_queued_or_in_flight(*stream) || state == WritableStream::State::Closed) {
  2178. auto exception = JS::TypeError::create(realm, "Cannot write to a writer whose stream is closing or already closed"sv);
  2179. return WebIDL::create_rejected_promise(realm, exception);
  2180. }
  2181. // 9. If state is "erroring", return a promise rejected with stream.[[storedError]].
  2182. if (state == WritableStream::State::Erroring)
  2183. return WebIDL::create_rejected_promise(realm, stream->stored_error());
  2184. // 10. Assert: state is "writable".
  2185. VERIFY(state == WritableStream::State::Writable);
  2186. // 11. Let promise be ! WritableStreamAddWriteRequest(stream).
  2187. auto promise = writable_stream_add_write_request(*stream);
  2188. // 12. Perform ! WritableStreamDefaultControllerWrite(controller, chunk, chunkSize).
  2189. TRY(writable_stream_default_controller_write(*controller, chunk, chunk_size));
  2190. // 13. Return promise.
  2191. return promise;
  2192. }
  2193. // https://streams.spec.whatwg.org/#set-up-writable-stream-default-controller
  2194. WebIDL::ExceptionOr<void> set_up_writable_stream_default_controller(WritableStream& stream, WritableStreamDefaultController& controller, StartAlgorithm&& start_algorithm, WriteAlgorithm&& write_algorithm, CloseAlgorithm&& close_algorithm, AbortAlgorithm&& abort_algorithm, double high_water_mark, SizeAlgorithm&& size_algorithm)
  2195. {
  2196. auto& realm = stream.realm();
  2197. // 1. Assert: stream implements WritableStream.
  2198. // 2. Assert: stream.[[controller]] is undefined.
  2199. VERIFY(!stream.controller());
  2200. // 3. Set controller.[[stream]] to stream.
  2201. controller.set_stream(stream);
  2202. // 4. Set stream.[[controller]] to controller.
  2203. stream.set_controller(controller);
  2204. // 5. Perform ! ResetQueue(controller).
  2205. reset_queue(controller);
  2206. // 6. Set controller.[[signal]] to a new AbortSignal.
  2207. controller.set_signal(realm.heap().allocate<DOM::AbortSignal>(realm, realm));
  2208. // 7. Set controller.[[started]] to false.
  2209. controller.set_started(false);
  2210. // 8. Set controller.[[strategySizeAlgorithm]] to sizeAlgorithm.
  2211. controller.set_strategy_size_algorithm(move(size_algorithm));
  2212. // 9. Set controller.[[strategyHWM]] to highWaterMark.
  2213. controller.set_strategy_hwm(high_water_mark);
  2214. // 10. Set controller.[[writeAlgorithm]] to writeAlgorithm.
  2215. controller.set_write_algorithm(move(write_algorithm));
  2216. // 11. Set controller.[[closeAlgorithm]] to closeAlgorithm.
  2217. controller.set_close_algorithm(move(close_algorithm));
  2218. // 12. Set controller.[[abortAlgorithm]] to abortAlgorithm.
  2219. controller.set_abort_algorithm(move(abort_algorithm));
  2220. // 13. Let backpressure be ! WritableStreamDefaultControllerGetBackpressure(controller).
  2221. auto backpressure = writable_stream_default_controller_get_backpressure(controller);
  2222. // 14. Perform ! WritableStreamUpdateBackpressure(stream, backpressure).
  2223. writable_stream_update_backpressure(stream, backpressure);
  2224. // 15. Let startResult be the result of performing startAlgorithm. (This may throw an exception.)
  2225. auto start_result = TRY(start_algorithm());
  2226. // 16. Let startPromise be a promise resolved with startResult.
  2227. auto start_promise = WebIDL::create_resolved_promise(realm, start_result);
  2228. // 17. Upon fulfillment of startPromise,
  2229. WebIDL::upon_fulfillment(*start_promise, [&](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  2230. // 1. Assert: stream.[[state]] is "writable" or "erroring".
  2231. auto state = stream.state();
  2232. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  2233. // 2. Set controller.[[started]] to true.
  2234. controller.set_started(true);
  2235. // 3. Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).
  2236. TRY(writable_stream_default_controller_advance_queue_if_needed(controller));
  2237. return JS::js_undefined();
  2238. });
  2239. // 18. Upon rejection of startPromise with reason r,
  2240. WebIDL::upon_rejection(*start_promise, [&](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {
  2241. // 1. Assert: stream.[[state]] is "writable" or "erroring".
  2242. auto state = stream.state();
  2243. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  2244. // 2. Set controller.[[started]] to true.
  2245. controller.set_started(true);
  2246. // 3. Perform ! WritableStreamDealWithRejection(stream, r).
  2247. TRY(writable_stream_deal_with_rejection(stream, reason));
  2248. return JS::js_undefined();
  2249. });
  2250. return {};
  2251. }
  2252. // https://streams.spec.whatwg.org/#set-up-writable-stream-default-controller-from-underlying-sink
  2253. WebIDL::ExceptionOr<void> set_up_writable_stream_default_controller_from_underlying_sink(WritableStream& stream, JS::Value underlying_sink_value, UnderlyingSink& underlying_sink, double high_water_mark, SizeAlgorithm&& size_algorithm)
  2254. {
  2255. auto& realm = stream.realm();
  2256. // 1. Let controller be a new WritableStreamDefaultController.
  2257. auto controller = realm.heap().allocate<WritableStreamDefaultController>(realm, realm);
  2258. // 2. Let startAlgorithm be an algorithm that returns undefined.
  2259. StartAlgorithm start_algorithm = [] { return JS::js_undefined(); };
  2260. // 3. Let writeAlgorithm be an algorithm that returns a promise resolved with undefined.
  2261. WriteAlgorithm write_algorithm = [&realm](auto const&) {
  2262. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2263. };
  2264. // 4. Let closeAlgorithm be an algorithm that returns a promise resolved with undefined.
  2265. CloseAlgorithm close_algorithm = [&realm] {
  2266. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2267. };
  2268. // 5. Let abortAlgorithm be an algorithm that returns a promise resolved with undefined.
  2269. AbortAlgorithm abort_algorithm = [&realm](auto const&) {
  2270. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2271. };
  2272. // 6. If underlyingSinkDict["start"] exists, then set startAlgorithm to an algorithm which returns the result of invoking underlyingSinkDict["start"] with argument list « controller » and callback this value underlyingSink.
  2273. if (underlying_sink.start) {
  2274. start_algorithm = [controller, underlying_sink_value, callback = underlying_sink.start]() -> WebIDL::ExceptionOr<JS::Value> {
  2275. // Note: callback does not return a promise, so invoke_callback may return an abrupt completion
  2276. return TRY(WebIDL::invoke_callback(*callback, underlying_sink_value, controller)).release_value();
  2277. };
  2278. }
  2279. // 7. If underlyingSinkDict["write"] exists, then set writeAlgorithm to an algorithm which takes an argument chunk and returns the result of invoking underlyingSinkDict["write"] with argument list « chunk, controller » and callback this value underlyingSink.
  2280. if (underlying_sink.write) {
  2281. write_algorithm = [&realm, controller, underlying_sink_value, callback = underlying_sink.write](JS::Value chunk) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  2282. // Note: callback return a promise, so invoke_callback will never return an abrupt completion
  2283. auto result = MUST_OR_THROW_OOM(WebIDL::invoke_callback(*callback, underlying_sink_value, chunk, controller)).release_value();
  2284. return WebIDL::create_resolved_promise(realm, result);
  2285. };
  2286. }
  2287. // 8. If underlyingSinkDict["close"] exists, then set closeAlgorithm to an algorithm which returns the result of invoking underlyingSinkDict["close"] with argument list «» and callback this value underlyingSink.
  2288. if (underlying_sink.close) {
  2289. close_algorithm = [&realm, underlying_sink_value, callback = underlying_sink.close]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  2290. // Note: callback return a promise, so invoke_callback will never return an abrupt completion
  2291. auto result = MUST_OR_THROW_OOM(WebIDL::invoke_callback(*callback, underlying_sink_value)).release_value();
  2292. return WebIDL::create_resolved_promise(realm, result);
  2293. };
  2294. }
  2295. // 9. If underlyingSinkDict["abort"] exists, then set abortAlgorithm to an algorithm which takes an argument reason and returns the result of invoking underlyingSinkDict["abort"] with argument list « reason » and callback this value underlyingSink.
  2296. if (underlying_sink.abort) {
  2297. abort_algorithm = [&realm, underlying_sink_value, callback = underlying_sink.abort](JS::Value reason) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  2298. // Note: callback return a promise, so invoke_callback will never return an abrupt completion
  2299. auto result = MUST_OR_THROW_OOM(WebIDL::invoke_callback(*callback, underlying_sink_value, reason)).release_value();
  2300. return WebIDL::create_resolved_promise(realm, result);
  2301. };
  2302. }
  2303. // 10. Perform ? SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm).
  2304. TRY(set_up_writable_stream_default_controller(stream, controller, move(start_algorithm), move(write_algorithm), move(close_algorithm), move(abort_algorithm), high_water_mark, move(size_algorithm)));
  2305. return {};
  2306. }
  2307. // https://streams.spec.whatwg.org/#writable-stream-default-controller-advance-queue-if-needed
  2308. WebIDL::ExceptionOr<void> writable_stream_default_controller_advance_queue_if_needed(WritableStreamDefaultController& controller)
  2309. {
  2310. // 1. Let stream be controller.[[stream]].
  2311. auto stream = controller.stream();
  2312. // 2. If controller.[[started]] is false, return.
  2313. if (!controller.started())
  2314. return {};
  2315. // 3. If stream.[[inFlightWriteRequest]] is not undefined, return.
  2316. if (stream->in_flight_write_request())
  2317. return {};
  2318. // 4. Let state be stream.[[state]].
  2319. auto state = stream->state();
  2320. // 5. Assert: state is not "closed" or "errored".
  2321. VERIFY(state != WritableStream::State::Closed && state != WritableStream::State::Errored);
  2322. // 6. If state is "erroring",
  2323. if (state == WritableStream::State::Erroring) {
  2324. // 1. Perform ! WritableStreamFinishErroring(stream).
  2325. // 2. Return.
  2326. return writable_stream_finish_erroring(*stream);
  2327. }
  2328. // 7. If controller.[[queue]] is empty, return.
  2329. if (controller.queue().is_empty())
  2330. return {};
  2331. // 8. Let value be ! PeekQueueValue(controller).
  2332. auto value = peek_queue_value(controller);
  2333. // 9. If value is the close sentinel, perform ! WritableStreamDefaultControllerProcessClose(controller).
  2334. if (is_close_sentinel(value)) {
  2335. TRY(writable_stream_default_controller_process_close(controller));
  2336. }
  2337. // 10. Otherwise, perform ! WritableStreamDefaultControllerProcessWrite(controller, value).
  2338. else {
  2339. TRY(writable_stream_default_controller_process_write(controller, value));
  2340. }
  2341. return {};
  2342. }
  2343. // https://streams.spec.whatwg.org/#writable-stream-default-controller-clear-algorithms
  2344. void writable_stream_default_controller_clear_algorithms(WritableStreamDefaultController& controller)
  2345. {
  2346. // FIXME: This AO can be invoked from within one of the algorithms below. If we clear them, it invokes SafeFunction's
  2347. // destructor, which asserts we are not currently invoking the function (as it clears the storage). We need to
  2348. // figure out how to delay this, as these algorithms may keep objects alive that can otherwise be GC'd.
  2349. (void)controller;
  2350. // 1. Set controller.[[writeAlgorithm]] to undefined.
  2351. // controller.set_write_algorithm({});
  2352. // 2. Set controller.[[closeAlgorithm]] to undefined.
  2353. // controller.set_close_algorithm({});
  2354. // 3. Set controller.[[abortAlgorithm]] to undefined.
  2355. // controller.set_abort_algorithm({});
  2356. // 4. Set controller.[[strategySizeAlgorithm]] to undefined.
  2357. // controller.set_strategy_size_algorithm({});
  2358. }
  2359. // https://streams.spec.whatwg.org/#writable-stream-default-controller-close
  2360. WebIDL::ExceptionOr<void> writable_stream_default_controller_close(WritableStreamDefaultController& controller)
  2361. {
  2362. // 1. Perform ! EnqueueValueWithSize(controller, close sentinel, 0).
  2363. TRY(enqueue_value_with_size(controller, create_close_sentinel(), JS::Value(0.0)));
  2364. // 2. Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).
  2365. TRY(writable_stream_default_controller_advance_queue_if_needed(controller));
  2366. return {};
  2367. }
  2368. // https://streams.spec.whatwg.org/#writable-stream-default-controller-error
  2369. WebIDL::ExceptionOr<void> writable_stream_default_controller_error(WritableStreamDefaultController& controller, JS::Value error)
  2370. {
  2371. // 1. Let stream be controller.[[stream]].
  2372. auto stream = controller.stream();
  2373. // 2. Assert: stream.[[state]] is "writable".
  2374. VERIFY(stream->state() == WritableStream::State::Writable);
  2375. // 3. Perform ! WritableStreamDefaultControllerClearAlgorithms(controller).
  2376. writable_stream_default_controller_clear_algorithms(controller);
  2377. // 4. Perform ! WritableStreamStartErroring(stream, error).
  2378. return writable_stream_start_erroring(stream, error);
  2379. }
  2380. // https://streams.spec.whatwg.org/#writable-stream-default-controller-error-if-needed
  2381. WebIDL::ExceptionOr<void> writable_stream_default_controller_error_if_needed(WritableStreamDefaultController& controller, JS::Value error)
  2382. {
  2383. // 1. If controller.[[stream]].[[state]] is "writable", perform ! WritableStreamDefaultControllerError(controller, error).
  2384. if (controller.stream()->state() == WritableStream::State::Writable)
  2385. TRY(writable_stream_default_controller_error(controller, error));
  2386. return {};
  2387. }
  2388. // https://streams.spec.whatwg.org/#writable-stream-default-controller-get-backpressure
  2389. bool writable_stream_default_controller_get_backpressure(WritableStreamDefaultController const& controller)
  2390. {
  2391. // 1. Let desiredSize be ! WritableStreamDefaultControllerGetDesiredSize(controller).
  2392. auto desired_size = writable_stream_default_controller_get_desired_size(controller);
  2393. // 2. Return true if desiredSize ≤ 0, or false otherwise.
  2394. return desired_size <= 0.0;
  2395. }
  2396. // https://streams.spec.whatwg.org/#writable-stream-default-controller-get-chunk-size
  2397. WebIDL::ExceptionOr<JS::Value> writable_stream_default_controller_get_chunk_size(WritableStreamDefaultController& controller, JS::Value chunk)
  2398. {
  2399. // 1. Let returnValue be the result of performing controller.[[strategySizeAlgorithm]], passing in chunk, and interpreting the result as a completion record.
  2400. auto return_value = (*controller.strategy_size_algorithm())(chunk);
  2401. // 2. If returnValue is an abrupt completion,
  2402. if (return_value.is_abrupt()) {
  2403. // 1. Perform ! WritableStreamDefaultControllerErrorIfNeeded(controller, returnValue.[[Value]]).
  2404. TRY(writable_stream_default_controller_error_if_needed(controller, *return_value.release_value()));
  2405. // 2. Return 1.
  2406. return 1.0;
  2407. }
  2408. // 3. Return returnValue.[[Value]].
  2409. return *return_value.release_value();
  2410. }
  2411. // https://streams.spec.whatwg.org/#writable-stream-default-controller-get-desired-size
  2412. double writable_stream_default_controller_get_desired_size(WritableStreamDefaultController const& controller)
  2413. {
  2414. // 1. Return controller.[[strategyHWM]] − controller.[[queueTotalSize]].
  2415. return controller.strategy_hwm() - controller.queue_total_size();
  2416. }
  2417. // https://streams.spec.whatwg.org/#writable-stream-default-controller-process-close
  2418. WebIDL::ExceptionOr<void> writable_stream_default_controller_process_close(WritableStreamDefaultController& controller)
  2419. {
  2420. // 1. Let stream be controller.[[stream]].
  2421. auto stream = controller.stream();
  2422. // 2. Perform ! WritableStreamMarkCloseRequestInFlight(stream).
  2423. writable_stream_mark_close_request_in_flight(*stream);
  2424. // 3. Perform ! DequeueValue(controller).
  2425. dequeue_value(controller);
  2426. // 4. Assert: controller.[[queue]] is empty.
  2427. VERIFY(controller.queue().is_empty());
  2428. // 5. Let sinkClosePromise be the result of performing controller.[[closeAlgorithm]].
  2429. auto sink_close_promise = TRY((*controller.close_algorithm())());
  2430. // 6. Perform ! WritableStreamDefaultControllerClearAlgorithms(controller).
  2431. writable_stream_default_controller_clear_algorithms(controller);
  2432. // 7. Upon fulfillment of sinkClosePromise,
  2433. WebIDL::upon_fulfillment(*sink_close_promise, [&, stream = stream](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  2434. // 1. Perform ! WritableStreamFinishInFlightClose(stream).
  2435. writable_stream_finish_in_flight_close(*stream);
  2436. return JS::js_undefined();
  2437. });
  2438. // 8. Upon rejection of sinkClosePromise with reason reason,
  2439. WebIDL::upon_rejection(*sink_close_promise, [&, stream = stream](auto const& reason) -> WebIDL::ExceptionOr<JS::Value> {
  2440. // 1. Perform ! WritableStreamFinishInFlightCloseWithError(stream, reason).
  2441. TRY(writable_stream_finish_in_flight_close_with_error(*stream, reason));
  2442. return JS::js_undefined();
  2443. });
  2444. return {};
  2445. }
  2446. // https://streams.spec.whatwg.org/#writable-stream-default-controller-process-write
  2447. WebIDL::ExceptionOr<void> writable_stream_default_controller_process_write(WritableStreamDefaultController& controller, JS::Value chunk)
  2448. {
  2449. // 1. Let stream be controller.[[stream]].
  2450. auto stream = controller.stream();
  2451. // 2. Perform ! WritableStreamMarkFirstWriteRequestInFlight(stream).
  2452. writable_stream_mark_first_write_request_in_flight(*stream);
  2453. // 3. Let sinkWritePromise be the result of performing controller.[[writeAlgorithm]], passing in chunk.
  2454. auto sink_write_promise = TRY((*controller.write_algorithm())(chunk));
  2455. // 4. Upon fulfillment of sinkWritePromise,
  2456. WebIDL::upon_fulfillment(*sink_write_promise, [&, stream = stream](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  2457. // 1. Perform ! WritableStreamFinishInFlightWrite(stream).
  2458. writable_stream_finish_in_flight_write(*stream);
  2459. // 2. Let state be stream.[[state]].
  2460. auto state = stream->state();
  2461. // 3. Assert: state is "writable" or "erroring".
  2462. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  2463. // 4. Perform ! DequeueValue(controller).
  2464. dequeue_value(controller);
  2465. // 5. If ! WritableStreamCloseQueuedOrInFlight(stream) is false and state is "writable",
  2466. if (!writable_stream_close_queued_or_in_flight(*stream) && state == WritableStream::State::Writable) {
  2467. // 1. Let backpressure be ! WritableStreamDefaultControllerGetBackpressure(controller).
  2468. auto backpressure = writable_stream_default_controller_get_backpressure(controller);
  2469. // 2. Perform ! WritableStreamUpdateBackpressure(stream, backpressure).
  2470. writable_stream_update_backpressure(*stream, backpressure);
  2471. }
  2472. // 6 .Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).
  2473. TRY(writable_stream_default_controller_advance_queue_if_needed(controller));
  2474. return JS::js_undefined();
  2475. });
  2476. // 5. Upon rejection of sinkWritePromise with reason,
  2477. WebIDL::upon_rejection(*sink_write_promise, [&, stream = stream](auto const& reason) -> WebIDL::ExceptionOr<JS::Value> {
  2478. // 1. If stream.[[state]] is "writable", perform ! WritableStreamDefaultControllerClearAlgorithms(controller).
  2479. if (stream->state() == WritableStream::State::Writable)
  2480. writable_stream_default_controller_clear_algorithms(controller);
  2481. // 2. Perform ! WritableStreamFinishInFlightWriteWithError(stream, reason).
  2482. TRY(writable_stream_finish_in_flight_write_with_error(*stream, reason));
  2483. return JS::js_undefined();
  2484. });
  2485. return {};
  2486. }
  2487. // https://streams.spec.whatwg.org/#writable-stream-default-controller-write
  2488. WebIDL::ExceptionOr<void> writable_stream_default_controller_write(WritableStreamDefaultController& controller, JS::Value chunk, JS::Value chunk_size)
  2489. {
  2490. auto& vm = controller.vm();
  2491. // 1. Let enqueueResult be EnqueueValueWithSize(controller, chunk, chunkSize).
  2492. auto enqueue_result = enqueue_value_with_size(controller, chunk, chunk_size);
  2493. // 2. If enqueueResult is an abrupt completion,
  2494. if (enqueue_result.is_exception()) {
  2495. auto throw_completion = Bindings::throw_dom_exception_if_needed(vm, [&] { return enqueue_result; }).throw_completion();
  2496. // 1. Perform ! WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueResult.[[Value]]).
  2497. TRY(writable_stream_default_controller_error_if_needed(controller, *throw_completion.release_value()));
  2498. // 2. Return.
  2499. return {};
  2500. }
  2501. // 3. Let stream be controller.[[stream]].
  2502. auto stream = controller.stream();
  2503. // 4. If ! WritableStreamCloseQueuedOrInFlight(stream) is false and stream.[[state]] is "writable",
  2504. if (!writable_stream_close_queued_or_in_flight(*stream) && stream->state() == WritableStream::State::Writable) {
  2505. // 1. Let backpressure be ! WritableStreamDefaultControllerGetBackpressure(controller).
  2506. auto backpressure = writable_stream_default_controller_get_backpressure(controller);
  2507. // 2. Perform ! WritableStreamUpdateBackpressure(stream, backpressure).
  2508. writable_stream_update_backpressure(*stream, backpressure);
  2509. }
  2510. // 5. Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).
  2511. TRY(writable_stream_default_controller_advance_queue_if_needed(controller));
  2512. return {};
  2513. }
  2514. // https://streams.spec.whatwg.org/#initialize-transform-stream
  2515. WebIDL::ExceptionOr<void> initialize_transform_stream(TransformStream& stream, JS::NonnullGCPtr<JS::PromiseCapability> start_promise, double writable_high_water_mark, SizeAlgorithm&& writable_size_algorithm, double readable_high_water_mark, SizeAlgorithm&& readable_size_algorithm)
  2516. {
  2517. auto& realm = stream.realm();
  2518. // 1. Let startAlgorithm be an algorithm that returns startPromise.
  2519. StartAlgorithm writable_start_algorithm = [start_promise] {
  2520. return start_promise->promise();
  2521. };
  2522. StartAlgorithm readable_start_algorithm = [start_promise] {
  2523. return start_promise->promise();
  2524. };
  2525. // 2. Let writeAlgorithm be the following steps, taking a chunk argument:
  2526. WriteAlgorithm write_algorithm = [&stream](JS::Value chunk) {
  2527. // 1. Return ! TransformStreamDefaultSinkWriteAlgorithm(stream, chunk).
  2528. return transform_stream_default_sink_write_algorithm(stream, chunk);
  2529. };
  2530. // 3. Let abortAlgorithm be the following steps, taking a reason argument:
  2531. AbortAlgorithm abort_algorithm = [&stream](JS::Value reason) {
  2532. // 1. Return ! TransformStreamDefaultSinkAbortAlgorithm(stream, reason).
  2533. return transform_stream_default_sink_abort_algorithm(stream, reason);
  2534. };
  2535. // 4. Let closeAlgorithm be the following steps:
  2536. CloseAlgorithm close_algorithm = [&stream] {
  2537. // 1. Return ! TransformStreamDefaultSinkCloseAlgorithm(stream).
  2538. return transform_stream_default_sink_close_algorithm(stream);
  2539. };
  2540. // 5. Set stream.[[writable]] to ! CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm).
  2541. stream.set_writable(TRY(create_writable_stream(realm, move(writable_start_algorithm), move(write_algorithm), move(close_algorithm), move(abort_algorithm), writable_high_water_mark, move(writable_size_algorithm))));
  2542. // 6. Let pullAlgorithm be the following steps:
  2543. PullAlgorithm pull_algorithm = [&stream] {
  2544. // 1. Return ! TransformStreamDefaultSourcePullAlgorithm(stream).
  2545. return transform_stream_default_source_pull_algorithm(stream);
  2546. };
  2547. // 7. Let cancelAlgorithm be the following steps, taking a reason argument:
  2548. CancelAlgorithm cancel_algorithm = [&stream, &realm](JS::Value reason) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  2549. // 1. Perform ! TransformStreamErrorWritableAndUnblockWrite(stream, reason).
  2550. TRY(transform_stream_error_writable_and_unblock_write(stream, reason));
  2551. // 2. Return a promise resolved with undefined.
  2552. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2553. };
  2554. // 8. Set stream.[[readable]] to ! CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm).
  2555. stream.set_readable(TRY(create_readable_stream(realm, move(readable_start_algorithm), move(pull_algorithm), move(cancel_algorithm), readable_high_water_mark, move(readable_size_algorithm))));
  2556. // 9. Set stream.[[backpressure]] and stream.[[backpressureChangePromise]] to undefined.
  2557. stream.set_backpressure({});
  2558. stream.set_backpressure_change_promise({});
  2559. // 10. Perform ! TransformStreamSetBackpressure(stream, true).
  2560. TRY(transform_stream_set_backpressure(stream, true));
  2561. // 11. Set stream.[[controller]] to undefined.
  2562. stream.set_controller({});
  2563. return {};
  2564. }
  2565. // https://streams.spec.whatwg.org/#set-up-transform-stream-default-controller
  2566. void set_up_transform_stream_default_controller(TransformStream& stream, TransformStreamDefaultController& controller, TransformAlgorithm&& transform_algorithm, FlushAlgorithm&& flush_algorithm)
  2567. {
  2568. // 1. Assert: stream implements TransformStream.
  2569. // 2. Assert: stream.[[controller]] is undefined.
  2570. VERIFY(!stream.controller());
  2571. // 3. Set controller.[[stream]] to stream.
  2572. controller.set_stream(stream);
  2573. // 4. Set stream.[[controller]] to controller.
  2574. stream.set_controller(controller);
  2575. // 5. Set controller.[[transformAlgorithm]] to transformAlgorithm.
  2576. controller.set_transform_algorithm(move(transform_algorithm));
  2577. // 6. Set controller.[[flushAlgorithm]] to flushAlgorithm.
  2578. controller.set_flush_algorithm(move(flush_algorithm));
  2579. }
  2580. // https://streams.spec.whatwg.org/#set-up-transform-stream-default-controller-from-transformer
  2581. WebIDL::ExceptionOr<void> set_up_transform_stream_default_controller_from_transformer(TransformStream& stream, JS::Value transformer, Transformer& transformer_dict)
  2582. {
  2583. auto& realm = stream.realm();
  2584. auto& vm = realm.vm();
  2585. // 1. Let controller be a new TransformStreamDefaultController.
  2586. auto controller = realm.heap().allocate<TransformStreamDefaultController>(realm, realm);
  2587. // 2. Let transformAlgorithm be the following steps, taking a chunk argument:
  2588. TransformAlgorithm transform_algorithm = [controller, &realm, &vm](JS::Value chunk) {
  2589. // 1. Let result be TransformStreamDefaultControllerEnqueue(controller, chunk).
  2590. auto result = transform_stream_default_controller_enqueue(*controller, chunk);
  2591. // 2. If result is an abrupt completion, return a promise rejected with result.[[Value]].
  2592. if (result.is_error()) {
  2593. auto throw_completion = Bindings::dom_exception_to_throw_completion(vm, result.exception());
  2594. return WebIDL::create_rejected_promise(realm, *throw_completion.release_value());
  2595. }
  2596. // 3. Otherwise, return a promise resolved with undefined.
  2597. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2598. };
  2599. // 3. Let flushAlgorithm be an algorithm which returns a promise resolved with undefined.
  2600. FlushAlgorithm flush_algorithm = [&realm] {
  2601. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2602. };
  2603. // 4. If transformerDict["transform"] exists, set transformAlgorithm to an algorithm which takes an argument chunk
  2604. // and returns the result of invoking transformerDict["transform"] with argument list « chunk, controller » and
  2605. // callback this value transformer.
  2606. if (transformer_dict.transform) {
  2607. transform_algorithm = [controller, &realm, transformer, callback = transformer_dict.transform](JS::Value chunk) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  2608. // Note: callback does not return a promise, so invoke_callback may return an abrupt completion
  2609. auto result = WebIDL::invoke_callback(*callback, transformer, chunk, controller);
  2610. if (result.is_error())
  2611. return WebIDL::create_rejected_promise(realm, *result.release_value());
  2612. return WebIDL::create_resolved_promise(realm, *result.release_value());
  2613. };
  2614. }
  2615. // 5. If transformerDict["flush"] exists, set flushAlgorithm to an algorithm which returns the result of invoking
  2616. // transformerDict["flush"] with argument list « controller » and callback this value transformer.
  2617. if (transformer_dict.flush) {
  2618. flush_algorithm = [&realm, transformer, callback = transformer_dict.flush, controller]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  2619. // Note: callback does not return a promise, so invoke_callback may return an abrupt completion
  2620. auto result = WebIDL::invoke_callback(*callback, transformer, controller);
  2621. if (result.is_error()) {
  2622. return WebIDL::create_rejected_promise(realm, *result.release_value());
  2623. }
  2624. return WebIDL::create_resolved_promise(realm, *result.release_value());
  2625. };
  2626. }
  2627. // 6. Perform ! SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm).
  2628. set_up_transform_stream_default_controller(stream, *controller, move(transform_algorithm), move(flush_algorithm));
  2629. return {};
  2630. }
  2631. // https://streams.spec.whatwg.org/#transform-stream-default-controller-clear-algorithms
  2632. void transform_stream_default_controller_clear_algorithms(TransformStreamDefaultController& controller)
  2633. {
  2634. // NOTE: This is observable using weak references. See tc39/proposal-weakrefs#31 for more detail.
  2635. // 1. Set controller.[[transformAlgorithm]] to undefined.
  2636. controller.set_transform_algorithm({});
  2637. // 2. Set controller.[[flushAlgorithm]] to undefined.
  2638. controller.set_flush_algorithm({});
  2639. }
  2640. // https://streams.spec.whatwg.org/#transform-stream-default-controller-enqueue
  2641. WebIDL::ExceptionOr<void> transform_stream_default_controller_enqueue(TransformStreamDefaultController& controller, JS::Value chunk)
  2642. {
  2643. auto& vm = controller.vm();
  2644. // 1. Let stream be controller.[[stream]].
  2645. auto stream = controller.stream();
  2646. // 2. Let readableController be stream.[[readable]].[[controller]].
  2647. VERIFY(stream->readable()->controller().has_value() && stream->readable()->controller()->has<JS::NonnullGCPtr<ReadableStreamDefaultController>>());
  2648. auto& readable_controller = stream->readable()->controller()->get<JS::NonnullGCPtr<ReadableStreamDefaultController>>();
  2649. // 3. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController) is false, throw a TypeError exception.
  2650. if (!readable_stream_default_controller_can_close_or_enqueue(readable_controller))
  2651. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "ReadableController is either closed or not readable."sv };
  2652. // 4. Let enqueueResult be ReadableStreamDefaultControllerEnqueue(readableController, chunk).
  2653. auto enqueue_result = readable_stream_default_controller_enqueue(readable_controller, chunk);
  2654. // 5. If enqueueResult is an abrupt completion,
  2655. if (enqueue_result.is_error()) {
  2656. auto throw_completion = Bindings::dom_exception_to_throw_completion(vm, enqueue_result.exception());
  2657. // 1. Perform ! TransformStreamErrorWritableAndUnblockWrite(stream, enqueueResult.[[Value]]).
  2658. TRY(transform_stream_error_writable_and_unblock_write(*stream, throw_completion.value().value()));
  2659. // 2. Throw stream.[[readable]].[[storedError]].
  2660. return JS::throw_completion(stream->readable()->stored_error());
  2661. }
  2662. // 6. Let backpressure be ! ReadableStreamDefaultControllerHasBackpressure(readableController).
  2663. auto backpressure = readable_stream_default_controller_has_backpressure(readable_controller);
  2664. // 7. If backpressure is not stream.[[backpressure]],
  2665. if (backpressure != stream->backpressure()) {
  2666. // 1. Assert: backpressure is true.
  2667. VERIFY(backpressure);
  2668. // 2. Perform ! TransformStreamSetBackpressure(stream, true).
  2669. TRY(transform_stream_set_backpressure(*stream, true));
  2670. }
  2671. return {};
  2672. }
  2673. // https://streams.spec.whatwg.org/#transform-stream-default-controller-error
  2674. WebIDL::ExceptionOr<void> transform_stream_default_controller_error(TransformStreamDefaultController& controller, JS::Value error)
  2675. {
  2676. // 1. Perform ! TransformStreamError(controller.[[stream]], e).
  2677. TRY(transform_stream_error(*controller.stream(), error));
  2678. return {};
  2679. }
  2680. // https://streams.spec.whatwg.org/#transform-stream-default-controller-terminate
  2681. WebIDL::ExceptionOr<void> transform_stream_default_controller_terminate(TransformStreamDefaultController& controller)
  2682. {
  2683. auto& realm = controller.realm();
  2684. // 1. Let stream be controller.[[stream]].
  2685. auto stream = controller.stream();
  2686. // 2. Let readableController be stream.[[readable]].[[controller]].
  2687. VERIFY(stream->readable()->controller().has_value() && stream->readable()->controller()->has<JS::NonnullGCPtr<ReadableStreamDefaultController>>());
  2688. auto readable_controller = stream->readable()->controller()->get<JS::NonnullGCPtr<ReadableStreamDefaultController>>();
  2689. // 3. Perform ! ReadableStreamDefaultControllerClose(readableController).
  2690. readable_stream_default_controller_close(readable_controller);
  2691. // 4. Let error be a TypeError exception indicating that the stream has been terminated.
  2692. auto error = JS::TypeError::create(realm, "Stream has been terminated."sv);
  2693. // 5. Perform ! TransformStreamErrorWritableAndUnblockWrite(stream, error).
  2694. TRY(transform_stream_error_writable_and_unblock_write(*stream, error));
  2695. return {};
  2696. }
  2697. // https://streams.spec.whatwg.org/#transform-stream-default-controller-perform-transform
  2698. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> transform_stream_default_controller_perform_transform(TransformStreamDefaultController& controller, JS::Value chunk)
  2699. {
  2700. auto& realm = controller.realm();
  2701. // 1. Let transformPromise be the result of performing controller.[[transformAlgorithm]], passing chunk.
  2702. auto transform_promise = TRY((*controller.transform_algorithm())(chunk));
  2703. // 2. Return the result of reacting to transformPromise with the following rejection steps given the argument r:
  2704. auto react_result = WebIDL::react_to_promise(*transform_promise,
  2705. {},
  2706. [&](auto const& reason) -> WebIDL::ExceptionOr<JS::Value> {
  2707. // 1. Perform ! TransformStreamError(controller.[[stream]], r).
  2708. TRY(transform_stream_error(*controller.stream(), reason));
  2709. // 2. Throw r.
  2710. return JS::throw_completion(reason);
  2711. });
  2712. return WebIDL::create_resolved_promise(realm, react_result);
  2713. }
  2714. // https://streams.spec.whatwg.org/#transform-stream-default-sink-abort-algorithm
  2715. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> transform_stream_default_sink_abort_algorithm(TransformStream& stream, JS::Value reason)
  2716. {
  2717. auto& realm = stream.realm();
  2718. // 1. Perform ! TransformStreamError(stream, reason).
  2719. TRY(transform_stream_error(stream, reason));
  2720. // 2. Return a promise resolved with undefined.
  2721. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2722. }
  2723. // https://streams.spec.whatwg.org/#transform-stream-default-sink-close-algorithm
  2724. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> transform_stream_default_sink_close_algorithm(TransformStream& stream)
  2725. {
  2726. auto& realm = stream.realm();
  2727. // 1. Let readable be stream.[[readable]].
  2728. auto readable = stream.readable();
  2729. // 2. Let controller be stream.[[controller]].
  2730. auto controller = stream.controller();
  2731. // 3. Let flushPromise be the result of performing controller.[[flushAlgorithm]].
  2732. auto flush_promise = TRY((*controller->flush_algorithm())());
  2733. // 4. Perform ! TransformStreamDefaultControllerClearAlgorithms(controller).
  2734. transform_stream_default_controller_clear_algorithms(*controller);
  2735. // 5. Return the result of reacting to flushPromise:
  2736. auto react_result = WebIDL::react_to_promise(
  2737. *flush_promise,
  2738. // 1. If flushPromise was fulfilled, then:
  2739. [readable](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  2740. // 1. If readable.[[state]] is "errored", throw readable.[[storedError]].
  2741. if (readable->state() == ReadableStream::State::Errored)
  2742. return JS::throw_completion(readable->stored_error());
  2743. VERIFY(readable->controller().has_value() && readable->controller()->has<JS::NonnullGCPtr<ReadableStreamDefaultController>>());
  2744. // 2. Perform ! ReadableStreamDefaultControllerClose(readable.[[controller]]).
  2745. readable_stream_default_controller_close(readable->controller().value().get<JS::NonnullGCPtr<ReadableStreamDefaultController>>());
  2746. return JS::js_undefined();
  2747. },
  2748. // 2. If flushPromise was rejected with reason r, then:
  2749. [&stream, readable](auto const& reason) -> WebIDL::ExceptionOr<JS::Value> {
  2750. // 1. Perform ! TransformStreamError(stream, r).
  2751. TRY(transform_stream_error(stream, reason));
  2752. // 2. Throw readable.[[storedError]].
  2753. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, readable->stored_error().as_string().utf8_string() };
  2754. });
  2755. return WebIDL::create_resolved_promise(realm, react_result);
  2756. }
  2757. // https://streams.spec.whatwg.org/#transform-stream-default-sink-write-algorithm
  2758. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> transform_stream_default_sink_write_algorithm(TransformStream& stream, JS::Value chunk)
  2759. {
  2760. auto& realm = stream.realm();
  2761. // 1. Assert: stream.[[writable]].[[state]] is "writable".
  2762. VERIFY(stream.writable()->state() == WritableStream::State::Writable);
  2763. // 2. Let controller be stream.[[controller]].
  2764. auto controller = stream.controller();
  2765. // 3. If stream.[[backpressure]] is true,
  2766. if (stream.backpressure().has_value() && *stream.backpressure()) {
  2767. // 1. Let backpressureChangePromise be stream.[[backpressureChangePromise]].
  2768. auto backpressure_change_promise = stream.backpressure_change_promise();
  2769. // 2. Assert: backpressureChangePromise is not undefined.
  2770. VERIFY(backpressure_change_promise);
  2771. // 3. Return the result of reacting to backpressureChangePromise with the following fulfillment steps:
  2772. auto react_result = WebIDL::react_to_promise(*backpressure_change_promise,
  2773. [&stream, controller, chunk](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  2774. // 1. Let writable be stream.[[writable]].
  2775. auto writable = stream.writable();
  2776. // 2. Let state be writable.[[state]].
  2777. auto state = writable->state();
  2778. // 3. If state is "erroring", throw writable.[[storedError]].
  2779. if (state == WritableStream::State::Erroring)
  2780. return JS::throw_completion(writable->stored_error());
  2781. // 4. Assert: state is "writable".
  2782. VERIFY(state == WritableStream::State::Writable);
  2783. // 5. Return ! TransformStreamDefaultControllerPerformTransform(controller, chunk).
  2784. return TRY(transform_stream_default_controller_perform_transform(*controller, chunk))->promise();
  2785. },
  2786. {});
  2787. return WebIDL::create_resolved_promise(realm, react_result);
  2788. }
  2789. // 4. Return ! TransformStreamDefaultControllerPerformTransform(controller, chunk).
  2790. return transform_stream_default_controller_perform_transform(*controller, chunk);
  2791. }
  2792. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> transform_stream_default_source_pull_algorithm(TransformStream& stream)
  2793. {
  2794. // 1. Assert: stream.[[backpressure]] is true.
  2795. VERIFY(stream.backpressure().has_value() && *stream.backpressure());
  2796. // 2. Assert: stream.[[backpressureChangePromise]] is not undefined.
  2797. VERIFY(stream.backpressure_change_promise());
  2798. // 3. Perform ! TransformStreamSetBackpressure(stream, false).
  2799. TRY(transform_stream_set_backpressure(stream, false));
  2800. // 4. Return stream.[[backpressureChangePromise]].
  2801. return JS::NonnullGCPtr { *stream.backpressure_change_promise() };
  2802. }
  2803. // https://streams.spec.whatwg.org/#transform-stream-error
  2804. WebIDL::ExceptionOr<void> transform_stream_error(TransformStream& stream, JS::Value error)
  2805. {
  2806. VERIFY(stream.readable()->controller().has_value() && stream.readable()->controller()->has<JS::NonnullGCPtr<ReadableStreamDefaultController>>());
  2807. auto readable_controller = stream.readable()->controller()->get<JS::NonnullGCPtr<ReadableStreamDefaultController>>();
  2808. // 1. Perform ! ReadableStreamDefaultControllerError(stream.[[readable]].[[controller]], e).
  2809. readable_stream_default_controller_error(*readable_controller, error);
  2810. // 2. Perform ! TransformStreamErrorWritableAndUnblockWrite(stream, e).
  2811. TRY(transform_stream_error_writable_and_unblock_write(stream, error));
  2812. return {};
  2813. }
  2814. // https://streams.spec.whatwg.org/#transform-stream-error-writable-and-unblock-write
  2815. WebIDL::ExceptionOr<void> transform_stream_error_writable_and_unblock_write(TransformStream& stream, JS::Value error)
  2816. {
  2817. // 1. Perform ! TransformStreamDefaultControllerClearAlgorithms(stream.[[controller]]).
  2818. transform_stream_default_controller_clear_algorithms(*stream.controller());
  2819. // 2. Perform ! WritableStreamDefaultControllerErrorIfNeeded(stream.[[writable]].[[controller]], e).
  2820. TRY(writable_stream_default_controller_error_if_needed(*stream.writable()->controller(), error));
  2821. // 3. If stream.[[backpressure]] is true, perform ! TransformStreamSetBackpressure(stream, false).
  2822. if (stream.backpressure().has_value() && *stream.backpressure())
  2823. TRY(transform_stream_set_backpressure(stream, false));
  2824. return {};
  2825. }
  2826. // https://streams.spec.whatwg.org/#transform-stream-set-backpressure
  2827. WebIDL::ExceptionOr<void> transform_stream_set_backpressure(TransformStream& stream, bool backpressure)
  2828. {
  2829. auto& realm = stream.realm();
  2830. // 1. Assert: stream.[[backpressure]] is not backpressure.
  2831. VERIFY(stream.backpressure() != backpressure);
  2832. // 2. If stream.[[backpressureChangePromise]] is not undefined, resolve stream.[[backpressureChangePromise]] with undefined.
  2833. if (stream.backpressure_change_promise())
  2834. WebIDL::resolve_promise(realm, *stream.backpressure_change_promise(), JS::js_undefined());
  2835. // 3. Set stream.[[backpressureChangePromise]] to a new promise.
  2836. stream.set_backpressure_change_promise(WebIDL::create_promise(realm));
  2837. // 4. Set stream.[[backpressure]] to backpressure.
  2838. stream.set_backpressure(backpressure);
  2839. return {};
  2840. }
  2841. // https://streams.spec.whatwg.org/#is-non-negative-number
  2842. bool is_non_negative_number(JS::Value value)
  2843. {
  2844. // 1. If Type(v) is not Number, return false.
  2845. if (!value.is_number())
  2846. return false;
  2847. // 2. If v is NaN, return false.
  2848. if (value.is_nan())
  2849. return false;
  2850. // 3. If v < 0, return false.
  2851. if (value.as_double() < 0.0)
  2852. return false;
  2853. // 4. Return true.
  2854. return true;
  2855. }
  2856. // https://streams.spec.whatwg.org/#close-sentinel
  2857. // Non-standard function that implements the "close sentinel" value.
  2858. JS::Value create_close_sentinel()
  2859. {
  2860. // The close sentinel is a unique value enqueued into [[queue]], in lieu of a chunk, to signal that the stream is closed. It is only used internally, and is never exposed to web developers.
  2861. // Note: We use the empty Value to signal this as, similarly to the note above, the empty value is not exposed to nor creatable by web developers.
  2862. return {};
  2863. }
  2864. // https://streams.spec.whatwg.org/#close-sentinel
  2865. // Non-standard function that implements the "If value is a close sentinel" check.
  2866. bool is_close_sentinel(JS::Value value)
  2867. {
  2868. return value.is_empty();
  2869. }
  2870. // Non-standard function to aid in converting a user-provided function into a WebIDL::Callback. This is essentially
  2871. // what the Bindings generator would do at compile time, but at runtime instead.
  2872. JS::ThrowCompletionOr<JS::Handle<WebIDL::CallbackType>> property_to_callback(JS::VM& vm, JS::Value value, JS::PropertyKey const& property_key, WebIDL::OperationReturnsPromise operation_returns_promise)
  2873. {
  2874. auto property = TRY(value.get(vm, property_key));
  2875. if (property.is_undefined())
  2876. return JS::Handle<WebIDL::CallbackType> {};
  2877. if (!property.is_function())
  2878. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAFunction, property.to_string_without_side_effects());
  2879. return vm.heap().allocate_without_realm<WebIDL::CallbackType>(property.as_object(), HTML::incumbent_settings_object(), operation_returns_promise);
  2880. }
  2881. // https://streams.spec.whatwg.org/#set-up-readable-byte-stream-controller-from-underlying-source
  2882. WebIDL::ExceptionOr<void> set_up_readable_byte_stream_controller_from_underlying_source(ReadableStream& stream, JS::Value underlying_source, UnderlyingSource const& underlying_source_dict, double high_water_mark)
  2883. {
  2884. auto& realm = stream.realm();
  2885. // 1. Let controller be a new ReadableByteStreamController.
  2886. auto controller = stream.heap().allocate<ReadableByteStreamController>(realm, realm);
  2887. // 2. Let startAlgorithm be an algorithm that returns undefined.
  2888. StartAlgorithm start_algorithm = [] { return JS::js_undefined(); };
  2889. // 3. Let pullAlgorithm be an algorithm that returns a promise resolved with undefined.
  2890. PullAlgorithm pull_algorithm = [&realm]() {
  2891. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2892. };
  2893. // 4. Let cancelAlgorithm be an algorithm that returns a promise resolved with undefined.
  2894. CancelAlgorithm cancel_algorithm = [&realm](auto const&) {
  2895. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2896. };
  2897. // 5. If underlyingSourceDict["start"] exists, then set startAlgorithm to an algorithm which returns the result of invoking underlyingSourceDict["start"] with argument list « controller » and callback this value underlyingSource.
  2898. if (underlying_source_dict.start) {
  2899. start_algorithm = [controller, underlying_source, callback = underlying_source_dict.start]() -> WebIDL::ExceptionOr<JS::Value> {
  2900. // Note: callback does not return a promise, so invoke_callback may return an abrupt completion
  2901. return TRY(WebIDL::invoke_callback(*callback, underlying_source, controller)).release_value();
  2902. };
  2903. }
  2904. // 6. If underlyingSourceDict["pull"] exists, then set pullAlgorithm to an algorithm which returns the result of invoking underlyingSourceDict["pull"] with argument list « controller » and callback this value underlyingSource.
  2905. if (underlying_source_dict.pull) {
  2906. pull_algorithm = [&realm, controller, underlying_source, callback = underlying_source_dict.pull]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  2907. // Note: callback return a promise, so invoke_callback will never return an abrupt completion
  2908. auto result = MUST_OR_THROW_OOM(WebIDL::invoke_callback(*callback, underlying_source, controller)).release_value();
  2909. return WebIDL::create_resolved_promise(realm, result);
  2910. };
  2911. }
  2912. // 7. If underlyingSourceDict["cancel"] exists, then set cancelAlgorithm to an algorithm which takes an argument reason and returns the result of invoking underlyingSourceDict["cancel"] with argument list « reason » and callback this value underlyingSource.
  2913. if (underlying_source_dict.cancel) {
  2914. cancel_algorithm = [&realm, underlying_source, callback = underlying_source_dict.cancel](auto const& reason) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  2915. // Note: callback return a promise, so invoke_callback will never return an abrupt completion
  2916. auto result = MUST_OR_THROW_OOM(WebIDL::invoke_callback(*callback, underlying_source, reason)).release_value();
  2917. return WebIDL::create_resolved_promise(realm, result);
  2918. };
  2919. }
  2920. // 8. Let autoAllocateChunkSize be underlyingSourceDict["autoAllocateChunkSize"], if it exists, or undefined otherwise.
  2921. auto auto_allocate_chunk_size = underlying_source_dict.auto_allocate_chunk_size.has_value()
  2922. ? JS::Value(underlying_source_dict.auto_allocate_chunk_size.value())
  2923. : JS::js_undefined();
  2924. // 9. If autoAllocateChunkSize is 0, then throw a TypeError exception.
  2925. if (auto_allocate_chunk_size.is_integral_number() && auto_allocate_chunk_size.as_double() == 0)
  2926. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot use an auto allocate chunk size of 0"sv };
  2927. // 10. Perform ? SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize).
  2928. return set_up_readable_byte_stream_controller(stream, controller, move(start_algorithm), move(pull_algorithm), move(cancel_algorithm), high_water_mark, auto_allocate_chunk_size);
  2929. }
  2930. }