AbstractOperations.cpp 138 KB

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