AbstractOperations.cpp 149 KB

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