AbstractOperations.cpp 179 KB

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