AbstractOperations.cpp 149 KB

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