AbstractOperations.cpp 151 KB

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