AbstractOperations.cpp 102 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448
  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. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <LibJS/Runtime/PromiseCapability.h>
  9. #include <LibJS/Runtime/PromiseConstructor.h>
  10. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  11. #include <LibWeb/DOM/AbortSignal.h>
  12. #include <LibWeb/Streams/AbstractOperations.h>
  13. #include <LibWeb/Streams/ReadableByteStreamController.h>
  14. #include <LibWeb/Streams/ReadableStream.h>
  15. #include <LibWeb/Streams/ReadableStreamBYOBReader.h>
  16. #include <LibWeb/Streams/ReadableStreamBYOBRequest.h>
  17. #include <LibWeb/Streams/ReadableStreamDefaultController.h>
  18. #include <LibWeb/Streams/ReadableStreamDefaultReader.h>
  19. #include <LibWeb/Streams/ReadableStreamGenericReader.h>
  20. #include <LibWeb/Streams/UnderlyingSink.h>
  21. #include <LibWeb/Streams/UnderlyingSource.h>
  22. #include <LibWeb/Streams/WritableStream.h>
  23. #include <LibWeb/Streams/WritableStreamDefaultController.h>
  24. #include <LibWeb/Streams/WritableStreamDefaultWriter.h>
  25. #include <LibWeb/WebIDL/AbstractOperations.h>
  26. #include <LibWeb/WebIDL/ExceptionOr.h>
  27. #include <LibWeb/WebIDL/Promise.h>
  28. namespace Web::Streams {
  29. // https://streams.spec.whatwg.org/#acquire-readable-stream-reader
  30. WebIDL::ExceptionOr<JS::NonnullGCPtr<ReadableStreamDefaultReader>> acquire_readable_stream_default_reader(ReadableStream& stream)
  31. {
  32. auto& realm = stream.realm();
  33. // 1. Let reader be a new ReadableStreamDefaultReader.
  34. auto reader = TRY(realm.heap().allocate<ReadableStreamDefaultReader>(realm, realm));
  35. // 2. Perform ? SetUpReadableStreamDefaultReader(reader, stream).
  36. TRY(set_up_readable_stream_default_reader(reader, stream));
  37. // 3. Return reader.
  38. return reader;
  39. }
  40. // https://streams.spec.whatwg.org/#is-readable-stream-locked
  41. bool is_readable_stream_locked(ReadableStream const& stream)
  42. {
  43. // 1. If stream.[[reader]] is undefined, return false.
  44. if (!stream.reader().has_value())
  45. return false;
  46. // 2. Return true.
  47. return true;
  48. }
  49. // https://streams.spec.whatwg.org/#readable-stream-cancel
  50. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> readable_stream_cancel(ReadableStream& stream, JS::Value reason)
  51. {
  52. auto& realm = stream.realm();
  53. // 1. Set stream.[[disturbed]] to true.
  54. stream.set_disturbed(true);
  55. // 2. If stream.[[state]] is "closed", return a promise resolved with undefined.
  56. if (stream.state() == ReadableStream::State::Closed)
  57. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  58. // 3. If stream.[[state]] is "errored", return a promise rejected with stream.[[storedError]].
  59. if (stream.state() == ReadableStream::State::Errored)
  60. return WebIDL::create_rejected_promise(realm, stream.stored_error());
  61. // 4. Perform ! ReadableStreamClose(stream).
  62. readable_stream_close(stream);
  63. // 5. Let reader be stream.[[reader]].
  64. auto reader = stream.reader();
  65. // 6. If reader is not undefined and reader implements ReadableStreamBYOBReader,
  66. if (reader.has_value() && reader->has<JS::NonnullGCPtr<ReadableStreamBYOBReader>>()) {
  67. // 1. Let readIntoRequests be reader.[[readIntoRequests]].
  68. // 2. Set reader.[[readIntoRequests]] to an empty list.
  69. auto read_into_requests = move(reader->get<JS::NonnullGCPtr<ReadableStreamBYOBReader>>()->read_into_requests());
  70. // 3. For each readIntoRequest of readIntoRequests,
  71. for (auto& read_into_request : read_into_requests) {
  72. // 1. Perform readIntoRequest’s close steps, given undefined.
  73. read_into_request->on_close(JS::js_undefined());
  74. }
  75. }
  76. // 7. Let sourceCancelPromise be ! stream.[[controller]].[[CancelSteps]](reason).
  77. auto source_cancel_promise = TRY(stream.controller()->visit([&](auto const& controller) {
  78. return controller->cancel_steps(reason);
  79. }));
  80. // 8. Return the result of reacting to sourceCancelPromise with a fulfillment step that returns undefined.
  81. auto react_result = WebIDL::react_to_promise(*source_cancel_promise,
  82. [](auto const&) -> WebIDL::ExceptionOr<JS::Value> { return JS::js_undefined(); },
  83. {});
  84. return WebIDL::create_resolved_promise(realm, react_result);
  85. }
  86. // https://streams.spec.whatwg.org/#readable-stream-fulfill-read-request
  87. void readable_stream_fulfill_read_request(ReadableStream& stream, JS::Value chunk, bool done)
  88. {
  89. // 1. Assert: ! ReadableStreamHasDefaultReader(stream) is true.
  90. VERIFY(readable_stream_has_default_reader(stream));
  91. // 2. Let reader be stream.[[reader]].
  92. auto reader = stream.reader()->get<JS::NonnullGCPtr<ReadableStreamDefaultReader>>();
  93. // 3. Assert: reader.[[readRequests]] is not empty.
  94. VERIFY(!reader->read_requests().is_empty());
  95. // 4. Let readRequest be reader.[[readRequests]][0].
  96. // 5. Remove readRequest from reader.[[readRequests]].
  97. auto read_request = reader->read_requests().take_first();
  98. // 6. If done is true, perform readRequest’s close steps.
  99. if (done) {
  100. read_request->on_close();
  101. }
  102. // 7. Otherwise, perform readRequest’s chunk steps, given chunk.
  103. else {
  104. read_request->on_chunk(chunk);
  105. }
  106. }
  107. // https://streams.spec.whatwg.org/#readable-stream-get-num-read-into-requests
  108. size_t readable_stream_get_num_read_into_requests(ReadableStream const& stream)
  109. {
  110. // 1. Assert: ! ReadableStreamHasBYOBReader(stream) is true.
  111. VERIFY(readable_stream_has_byob_reader(stream));
  112. // 2. Return stream.[[reader]].[[readIntoRequests]]'s size.
  113. return stream.reader()->get<JS::NonnullGCPtr<ReadableStreamBYOBReader>>()->read_into_requests().size();
  114. }
  115. // https://streams.spec.whatwg.org/#readable-stream-get-num-read-requests
  116. size_t readable_stream_get_num_read_requests(ReadableStream const& stream)
  117. {
  118. // 1. Assert: ! ReadableStreamHasDefaultReader(stream) is true.
  119. VERIFY(readable_stream_has_default_reader(stream));
  120. // 2. Return stream.[[reader]].[[readRequests]]'s size.
  121. return stream.reader()->get<JS::NonnullGCPtr<ReadableStreamDefaultReader>>()->read_requests().size();
  122. }
  123. // https://streams.spec.whatwg.org/#readable-stream-has-byob-reader
  124. bool readable_stream_has_byob_reader(ReadableStream const& stream)
  125. {
  126. // 1. Let reader be stream.[[reader]].
  127. auto reader = stream.reader();
  128. // 2. If reader is undefined, return false.
  129. if (!reader.has_value())
  130. return false;
  131. // 3. If reader implements ReadableStreamBYOBReader, return true.
  132. if (reader->has<JS::NonnullGCPtr<ReadableStreamBYOBReader>>())
  133. return true;
  134. // 4. Return false.
  135. return false;
  136. }
  137. // https://streams.spec.whatwg.org/#readable-stream-has-default-reader
  138. bool readable_stream_has_default_reader(ReadableStream const& stream)
  139. {
  140. // 1. Let reader be stream.[[reader]].
  141. auto reader = stream.reader();
  142. // 2. If reader is undefined, return false.
  143. if (!reader.has_value())
  144. return false;
  145. // 3. If reader implements ReadableStreamDefaultReader, return true.
  146. if (reader->has<JS::NonnullGCPtr<ReadableStreamDefaultReader>>())
  147. return true;
  148. // 4. Return false.
  149. return false;
  150. }
  151. // https://streams.spec.whatwg.org/#readable-stream-close
  152. void readable_stream_close(ReadableStream& stream)
  153. {
  154. auto& realm = stream.realm();
  155. // 1. Assert: stream.[[state]] is "readable".
  156. VERIFY(stream.state() == ReadableStream::State::Readable);
  157. // 2. Set stream.[[state]] to "closed".
  158. stream.set_state(ReadableStream::State::Closed);
  159. // 3. Let reader be stream.[[reader]].
  160. auto reader = stream.reader();
  161. // 4. If reader is undefined, return.
  162. if (!reader.has_value())
  163. return;
  164. // 5. Resolve reader.[[closedPromise]] with undefined.
  165. WebIDL::resolve_promise(realm, *reader->visit([](auto& reader) {
  166. return reader->closed_promise_capability();
  167. }));
  168. // 6. If reader implements ReadableStreamDefaultReader,
  169. if (reader->has<JS::NonnullGCPtr<ReadableStreamDefaultReader>>()) {
  170. // 1. Let readRequests be reader.[[readRequests]].
  171. // 2. Set reader.[[readRequests]] to an empty list.
  172. auto read_requests = move(reader->get<JS::NonnullGCPtr<ReadableStreamDefaultReader>>()->read_requests());
  173. // 3. For each readRequest of readRequests,
  174. for (auto& read_request : read_requests) {
  175. // 1. Perform readRequest’s close steps.
  176. read_request->on_close();
  177. }
  178. }
  179. }
  180. // https://streams.spec.whatwg.org/#readable-stream-error
  181. void readable_stream_error(ReadableStream& stream, JS::Value error)
  182. {
  183. auto& realm = stream.realm();
  184. // 1. Assert: stream.[[state]] is "readable".
  185. VERIFY(stream.state() == ReadableStream::State::Readable);
  186. // 2. Set stream.[[state]] to "errored".
  187. stream.set_state(ReadableStream::State::Errored);
  188. // 3. Set stream.[[storedError]] to e.
  189. stream.set_stored_error(error);
  190. // 4. Let reader be stream.[[reader]].
  191. auto reader = stream.reader();
  192. // 5. If reader is undefined, return.
  193. if (!reader.has_value())
  194. return;
  195. auto closed_promise_capability = reader->visit([](auto& reader) { return reader->closed_promise_capability(); });
  196. // 6. Reject reader.[[closedPromise]] with e.
  197. WebIDL::reject_promise(realm, *closed_promise_capability, error);
  198. // 7. Set reader.[[closedPromise]].[[PromiseIsHandled]] to true.
  199. WebIDL::mark_promise_as_handled(*closed_promise_capability);
  200. // 8. If reader implements ReadableStreamDefaultReader,
  201. if (reader->has<JS::NonnullGCPtr<ReadableStreamDefaultReader>>()) {
  202. // 1. Perform ! ReadableStreamDefaultReaderErrorReadRequests(reader, e).
  203. readable_stream_default_reader_error_read_requests(*reader->get<JS::NonnullGCPtr<ReadableStreamDefaultReader>>(), error);
  204. }
  205. // 9. Otherwise,
  206. else {
  207. // 1. Assert: reader implements ReadableStreamBYOBReader.
  208. // 2. Perform ! ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e).
  209. // FIXME: Handle BYOBReader
  210. TODO();
  211. }
  212. }
  213. // https://streams.spec.whatwg.org/#readable-stream-add-read-request
  214. void readable_stream_add_read_request(ReadableStream& stream, ReadRequest const& read_request)
  215. {
  216. // 1. Assert: stream.[[reader]] implements ReadableStreamDefaultReader.
  217. VERIFY(stream.reader().has_value() && stream.reader()->has<JS::NonnullGCPtr<ReadableStreamDefaultReader>>());
  218. // 2. Assert: stream.[[state]] is "readable".
  219. VERIFY(stream.state() == ReadableStream::State::Readable);
  220. // 3. Append readRequest to stream.[[reader]].[[readRequests]].
  221. stream.reader()->get<JS::NonnullGCPtr<ReadableStreamDefaultReader>>()->read_requests().append(read_request);
  222. }
  223. // https://streams.spec.whatwg.org/#readable-stream-reader-generic-cancel
  224. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> readable_stream_reader_generic_cancel(ReadableStreamGenericReaderMixin& reader, JS::Value reason)
  225. {
  226. // 1. Let stream be reader.[[stream]]
  227. auto stream = reader.stream();
  228. // 2. Assert: stream is not undefined
  229. VERIFY(stream);
  230. // 3. Return ! ReadableStreamCancel(stream, reason)
  231. return TRY(readable_stream_cancel(*stream, reason));
  232. }
  233. // https://streams.spec.whatwg.org/#readable-stream-reader-generic-initialize
  234. void readable_stream_reader_generic_initialize(ReadableStreamReader reader, ReadableStream& stream)
  235. {
  236. auto& realm = stream.realm();
  237. // 1. Set reader.[[stream]] to stream.
  238. reader.visit([&](auto& reader) { reader->set_stream(stream); });
  239. // 2. Set stream.[[reader]] to reader.
  240. stream.set_reader(reader);
  241. // 3. If stream.[[state]] is "readable",
  242. if (stream.state() == ReadableStream::State::Readable) {
  243. // 1. Set reader.[[closedPromise]] to a new promise.
  244. reader.visit([&](auto& reader) { reader->set_closed_promise_capability(WebIDL::create_promise(realm)); });
  245. }
  246. // 4. Otherwise, if stream.[[state]] is "closed",
  247. else if (stream.state() == ReadableStream::State::Closed) {
  248. // 1. Set reader.[[closedPromise]] to a promise resolved with undefined.
  249. reader.visit([&](auto& reader) {
  250. reader->set_closed_promise_capability(WebIDL::create_resolved_promise(realm, JS::js_undefined()));
  251. });
  252. }
  253. // 5. Otherwise,
  254. else {
  255. // 1. Assert: stream.[[state]] is "errored".
  256. VERIFY(stream.state() == ReadableStream::State::Errored);
  257. // 2. Set reader.[[closedPromise]] to a promise rejected with stream.[[storedError]].
  258. // 3. Set reader.[[closedPromise]].[[PromiseIsHandled]] to true.
  259. reader.visit([&](auto& reader) {
  260. reader->set_closed_promise_capability(WebIDL::create_rejected_promise(realm, stream.stored_error()));
  261. WebIDL::mark_promise_as_handled(*reader->closed_promise_capability());
  262. });
  263. }
  264. }
  265. // https://streams.spec.whatwg.org/#readable-stream-reader-generic-release
  266. WebIDL::ExceptionOr<void> readable_stream_reader_generic_release(ReadableStreamGenericReaderMixin& reader)
  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. Assert: stream.[[reader]] is reader.
  273. VERIFY(stream->reader()->visit([](auto& reader) -> ReadableStreamGenericReaderMixin* { return reader.ptr(); }) == &reader);
  274. auto& realm = stream->realm();
  275. // 4. If stream.[[state]] is "readable", reject reader.[[closedPromise]] with a TypeError exception.
  276. auto exception = MUST_OR_THROW_OOM(JS::TypeError::create(realm, "Released readable stream"sv));
  277. if (stream->is_readable()) {
  278. WebIDL::reject_promise(realm, *reader.closed_promise_capability(), exception);
  279. }
  280. // 5. Otherwise, set reader.[[closedPromise]] to a promise rejected with a TypeError exception.
  281. else {
  282. reader.set_closed_promise_capability(WebIDL::create_rejected_promise(realm, exception));
  283. }
  284. // 6. Set reader.[[closedPromise]].[[PromiseIsHandled]] to true.
  285. WebIDL::mark_promise_as_handled(*reader.closed_promise_capability());
  286. // 7. Perform ! stream.[[controller]].[[ReleaseSteps]]().
  287. TRY(stream->controller()->visit([](auto const& controller) { return controller->release_steps(); }));
  288. // 8. Set stream.[[reader]] to undefined.
  289. stream->set_reader({});
  290. // 9. Set reader.[[stream]] to undefined.
  291. reader.set_stream({});
  292. return {};
  293. }
  294. // https://streams.spec.whatwg.org/#abstract-opdef-readablestreamdefaultreadererrorreadrequests
  295. void readable_stream_default_reader_error_read_requests(ReadableStreamDefaultReader& reader, JS::Value error)
  296. {
  297. // 1. Let readRequests be reader.[[readRequests]].
  298. // 2. Set reader.[[readRequests]] to a new empty list.
  299. auto read_requests = move(reader.read_requests());
  300. // 3. For each readRequest of readRequests,
  301. for (auto& read_request : read_requests) {
  302. // 1. Perform readRequest’s error steps, given e.
  303. read_request->on_error(error);
  304. }
  305. }
  306. // https://streams.spec.whatwg.org/#readable-stream-default-reader-read
  307. WebIDL::ExceptionOr<void> readable_stream_default_reader_read(ReadableStreamDefaultReader& reader, ReadRequest& read_request)
  308. {
  309. // 1. Let stream be reader.[[stream]].
  310. auto stream = reader.stream();
  311. // 2. Assert: stream is not undefined.
  312. VERIFY(stream);
  313. // 3. Set stream.[[disturbed]] to true.
  314. stream->set_disturbed(true);
  315. // 4. If stream.[[state]] is "closed", perform readRequest’s close steps.
  316. if (stream->is_closed()) {
  317. read_request.on_close();
  318. }
  319. // 5. Otherwise, if stream.[[state]] is "errored", perform readRequest’s error steps given stream.[[storedError]].
  320. else if (stream->is_errored()) {
  321. read_request.on_error(stream->stored_error());
  322. }
  323. // 6. Otherwise,
  324. else {
  325. // 1. Assert: stream.[[state]] is "readable".
  326. VERIFY(stream->is_readable());
  327. // 2. Perform ! stream.[[controller]].[[PullSteps]](readRequest).
  328. TRY(stream->controller()->visit([&](auto const& controller) {
  329. return controller->pull_steps(read_request);
  330. }));
  331. }
  332. return {};
  333. }
  334. // https://streams.spec.whatwg.org/#abstract-opdef-readablestreamdefaultreaderrelease
  335. WebIDL::ExceptionOr<void> readable_stream_default_reader_release(ReadableStreamDefaultReader& reader)
  336. {
  337. auto& realm = reader.realm();
  338. // 1. Perform ! ReadableStreamReaderGenericRelease(reader).
  339. TRY(readable_stream_reader_generic_release(reader));
  340. // 2. Let e be a new TypeError exception.
  341. auto exception = MUST_OR_THROW_OOM(JS::TypeError::create(realm, "Reader has been released"sv));
  342. // 3. Perform ! ReadableStreamDefaultReaderErrorReadRequests(reader, e).
  343. readable_stream_default_reader_error_read_requests(reader, exception);
  344. return {};
  345. }
  346. // https://streams.spec.whatwg.org/#set-up-readable-stream-default-reader
  347. WebIDL::ExceptionOr<void> set_up_readable_stream_default_reader(ReadableStreamDefaultReader& reader, ReadableStream& stream)
  348. {
  349. // 1. If ! IsReadableStreamLocked(stream) is true, throw a TypeError exception.
  350. if (is_readable_stream_locked(stream))
  351. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot create stream reader for a locked stream"sv };
  352. // 2. Perform ! ReadableStreamReaderGenericInitialize(reader, stream).
  353. // 3. Set reader.[[readRequests]] to a new empty list.
  354. readable_stream_reader_generic_initialize(ReadableStreamReader { reader }, stream);
  355. return {};
  356. }
  357. // https://streams.spec.whatwg.org/#readable-stream-default-controller-close
  358. void readable_stream_default_controller_close(ReadableStreamDefaultController& controller)
  359. {
  360. // 1. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) is false, return.
  361. if (!readable_stream_default_controller_can_close_or_enqueue(controller))
  362. return;
  363. // 2. Let stream be controller.[[stream]].
  364. auto stream = controller.stream();
  365. // 3. Set controller.[[closeRequested]] to true.
  366. controller.set_close_requested(true);
  367. // 4. If controller.[[queue]] is empty,
  368. if (controller.queue().is_empty()) {
  369. // 1. Perform ! ReadableStreamDefaultControllerClearAlgorithms(controller).
  370. readable_stream_default_controller_clear_algorithms(controller);
  371. // 2. Perform ! ReadableStreamClose(stream).
  372. readable_stream_close(*stream);
  373. }
  374. }
  375. // https://streams.spec.whatwg.org/#readable-stream-default-controller-enqueue
  376. WebIDL::ExceptionOr<void> readable_stream_default_controller_enqueue(ReadableStreamDefaultController& controller, JS::Value chunk)
  377. {
  378. auto& vm = controller.vm();
  379. // 1. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) is false, return.
  380. if (!readable_stream_default_controller_can_close_or_enqueue(controller))
  381. return {};
  382. // 2. Let stream be controller.[[stream]].
  383. auto stream = controller.stream();
  384. // 3. If ! IsReadableStreamLocked(stream) is true and ! ReadableStreamGetNumReadRequests(stream) > 0, perform ! ReadableStreamFulfillReadRequest(stream, chunk, false).
  385. if (is_readable_stream_locked(*stream) && readable_stream_get_num_read_requests(*stream) > 0) {
  386. readable_stream_fulfill_read_request(*stream, chunk, false);
  387. }
  388. // 4. Otherwise,
  389. else {
  390. // 1. Let result be the result of performing controller.[[strategySizeAlgorithm]], passing in chunk, and interpreting the result as a completion record.
  391. auto result = (*controller.strategy_size_algorithm())(chunk);
  392. // 2. If result is an abrupt completion,
  393. if (result.is_abrupt()) {
  394. // 1. Perform ! ReadableStreamDefaultControllerError(controller, result.[[Value]]).
  395. readable_stream_default_controller_error(controller, result.value().value());
  396. // 2. Return result.
  397. return result;
  398. }
  399. // 3. Let chunkSize be result.[[Value]].
  400. auto chunk_size = result.release_value().release_value();
  401. // 4. Let enqueueResult be EnqueueValueWithSize(controller, chunk, chunkSize).
  402. auto enqueue_result = enqueue_value_with_size(controller, chunk, chunk_size);
  403. // 5. If enqueueResult is an abrupt completion,
  404. if (enqueue_result.is_error()) {
  405. auto throw_completion = Bindings::throw_dom_exception_if_needed(vm, [&] { return enqueue_result; }).throw_completion();
  406. // 1. Perform ! ReadableStreamDefaultControllerError(controller, enqueueResult.[[Value]]).
  407. readable_stream_default_controller_error(controller, throw_completion.value().value());
  408. // 2. Return enqueueResult.
  409. // Note: We need to return the throw_completion object here, as enqueue needs to throw the same object that the controller is errored with
  410. return throw_completion;
  411. }
  412. }
  413. // 5. Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(controller).
  414. return readable_stream_default_controller_can_pull_if_needed(controller);
  415. }
  416. // https://streams.spec.whatwg.org/#readable-stream-default-controller-call-pull-if-needed
  417. WebIDL::ExceptionOr<void> readable_stream_default_controller_can_pull_if_needed(ReadableStreamDefaultController& controller)
  418. {
  419. // 1. Let shouldPull be ! ReadableStreamDefaultControllerShouldCallPull(controller).
  420. auto should_pull = readable_stream_default_controller_should_call_pull(controller);
  421. // 2. If shouldPull is false, return.
  422. if (!should_pull)
  423. return {};
  424. // 3. If controller.[[pulling]] is true,
  425. if (controller.pulling()) {
  426. // 1. Set controller.[[pullAgain]] to true.
  427. controller.set_pull_again(true);
  428. // 2. Return.
  429. return {};
  430. }
  431. // 4. Assert: controller.[[pullAgain]] is false.
  432. VERIFY(!controller.pull_again());
  433. // 5. Set controller.[[pulling]] to true.
  434. controller.set_pulling(true);
  435. // 6. Let pullPromise be the result of performing controller.[[pullAlgorithm]].
  436. auto pull_promise = TRY((*controller.pull_algorithm())());
  437. // 7. Upon fulfillment of pullPromise,
  438. WebIDL::upon_fulfillment(*pull_promise, [&](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  439. // 1. Set controller.[[pulling]] to false.
  440. controller.set_pulling(false);
  441. // 2. If controller.[[pullAgain]] is true,
  442. if (controller.pull_again()) {
  443. // 1. Set controller.[[pullAgain]] to false.
  444. controller.set_pull_again(false);
  445. // 2. Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(controller).
  446. TRY(readable_stream_default_controller_can_pull_if_needed(controller));
  447. }
  448. return JS::js_undefined();
  449. });
  450. // 8. Upon rejection of pullPromise with reason e,
  451. WebIDL::upon_rejection(*pull_promise, [&](auto const& e) -> WebIDL::ExceptionOr<JS::Value> {
  452. // 1. Perform ! ReadableStreamDefaultControllerError(controller, e).
  453. readable_stream_default_controller_error(controller, e);
  454. return JS::js_undefined();
  455. });
  456. return {};
  457. }
  458. // https://streams.spec.whatwg.org/#readable-stream-default-controller-should-call-pull
  459. bool readable_stream_default_controller_should_call_pull(ReadableStreamDefaultController& controller)
  460. {
  461. // 1. Let stream be controller.[[stream]].
  462. auto stream = controller.stream();
  463. // 2. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) is false, return false.
  464. if (!readable_stream_default_controller_can_close_or_enqueue(controller))
  465. return false;
  466. // 3. If controller.[[started]] is false, return false.
  467. if (!controller.started())
  468. return false;
  469. // 4. If ! IsReadableStreamLocked(stream) is true and ! ReadableStreamGetNumReadRequests(stream) > 0, return true.
  470. if (is_readable_stream_locked(*stream) && readable_stream_get_num_read_requests(*stream) > 0)
  471. return true;
  472. // 5. Let desiredSize be ! ReadableStreamDefaultControllerGetDesiredSize(controller).
  473. auto desired_size = readable_stream_default_controller_get_desired_size(controller);
  474. // 6. Assert: desiredSize is not null.
  475. VERIFY(desired_size.has_value());
  476. // 7. If desiredSize > 0, return true.
  477. if (desired_size.release_value() > 0.0)
  478. return true;
  479. // 8. Return false.
  480. return false;
  481. }
  482. // https://streams.spec.whatwg.org/#readable-stream-default-controller-clear-algorithms
  483. void readable_stream_default_controller_clear_algorithms(ReadableStreamDefaultController& controller)
  484. {
  485. // FIXME: This AO can be invoked from within one of the algorithms below. If we clear them, it invokes SafeFunction's
  486. // destructor, which asserts we are not currently invoking the function (as it clears the storage). We need to
  487. // figure out how to delay this, as these algorithms may keep objects alive that can otherwise be GC'd.
  488. (void)controller;
  489. // 1. Set controller.[[pullAlgorithm]] to undefined.
  490. // controller.set_pull_algorithm({});
  491. // 2. Set controller.[[cancelAlgorithm]] to undefined.
  492. // controller.set_cancel_algorithm({});
  493. // 3. Set controller.[[strategySizeAlgorithm]] to undefined.
  494. // controller.set_strategy_size_algorithm({});
  495. }
  496. // https://streams.spec.whatwg.org/#readable-stream-default-controller-error
  497. void readable_stream_default_controller_error(ReadableStreamDefaultController& controller, JS::Value error)
  498. {
  499. // 1. Let stream be controller.[[stream]].
  500. auto stream = controller.stream();
  501. // 2. If stream.[[state]] is not "readable", return.
  502. if (!stream->is_readable())
  503. return;
  504. // 3. Perform ! ResetQueue(controller).
  505. reset_queue(controller);
  506. // 4. Perform ! ReadableStreamDefaultControllerClearAlgorithms(controller).
  507. readable_stream_default_controller_clear_algorithms(controller);
  508. // 5. Perform ! ReadableStreamError(stream, e).
  509. readable_stream_error(*stream, error);
  510. }
  511. // https://streams.spec.whatwg.org/#readable-stream-default-controller-get-desired-size
  512. Optional<double> readable_stream_default_controller_get_desired_size(ReadableStreamDefaultController& controller)
  513. {
  514. auto stream = controller.stream();
  515. // 1. Let state be controller.[[stream]].[[state]].
  516. // 2. If state is "errored", return null.
  517. if (stream->is_errored())
  518. return {};
  519. // 3. If state is "closed", return 0.
  520. if (stream->is_closed())
  521. return 0.0;
  522. // 4. Return controller.[[strategyHWM]] − controller.[[queueTotalSize]].
  523. return controller.strategy_hwm() - controller.queue_total_size();
  524. }
  525. // https://streams.spec.whatwg.org/#readable-stream-default-controller-can-close-or-enqueue
  526. bool readable_stream_default_controller_can_close_or_enqueue(ReadableStreamDefaultController& controller)
  527. {
  528. // 1. Let state be controller.[[stream]].[[state]].
  529. // 2. If controller.[[closeRequested]] is false and state is "readable", return true.
  530. // 3. Otherwise, return false.
  531. return !controller.close_requested() && controller.stream()->is_readable();
  532. }
  533. // https://streams.spec.whatwg.org/#set-up-readable-stream-default-controller
  534. 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)
  535. {
  536. auto& realm = stream.realm();
  537. // 1. Assert: stream.[[controller]] is undefined.
  538. VERIFY(!stream.controller().has_value());
  539. // 2. Set controller.[[stream]] to stream.
  540. controller.set_stream(stream);
  541. // 3. Perform ! ResetQueue(controller).
  542. reset_queue(controller);
  543. // 4. Set controller.[[started]], controller.[[closeRequested]], controller.[[pullAgain]], and controller.[[pulling]] to false.
  544. controller.set_started(false);
  545. controller.set_close_requested(false);
  546. controller.set_pull_again(false);
  547. controller.set_pulling(false);
  548. // 5. Set controller.[[strategySizeAlgorithm]] to sizeAlgorithm and controller.[[strategyHWM]] to highWaterMark.
  549. controller.set_strategy_size_algorithm(move(size_algorithm));
  550. controller.set_strategy_hwm(high_water_mark);
  551. // 6. Set controller.[[pullAlgorithm]] to pullAlgorithm.
  552. controller.set_pull_algorithm(move(pull_algorithm));
  553. // 7. Set controller.[[cancelAlgorithm]] to cancelAlgorithm.
  554. controller.set_cancel_algorithm(move(cancel_algorithm));
  555. // 8. Set stream.[[controller]] to controller.
  556. stream.set_controller(ReadableStreamController { controller });
  557. // 9. Let startResult be the result of performing startAlgorithm. (This might throw an exception.)
  558. auto start_result = TRY(start_algorithm());
  559. // 10. Let startPromise be a promise resolved with startResult.
  560. auto start_promise = WebIDL::create_resolved_promise(realm, start_result);
  561. // 11. Upon fulfillment of startPromise,
  562. WebIDL::upon_fulfillment(start_promise, [&](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  563. // 1. Set controller.[[started]] to true.
  564. controller.set_started(true);
  565. // 2. Assert: controller.[[pulling]] is false.
  566. VERIFY(!controller.pulling());
  567. // 3. Assert: controller.[[pullAgain]] is false.
  568. VERIFY(!controller.pull_again());
  569. // 4. Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(controller).
  570. TRY(readable_stream_default_controller_can_pull_if_needed(controller));
  571. return JS::js_undefined();
  572. });
  573. // 12. Upon rejection of startPromise with reason r,
  574. WebIDL::upon_rejection(start_promise, [&](auto const& r) -> WebIDL::ExceptionOr<JS::Value> {
  575. // 1. Perform ! ReadableStreamDefaultControllerError(controller, r).
  576. readable_stream_default_controller_error(controller, r);
  577. return JS::js_undefined();
  578. });
  579. return {};
  580. }
  581. // https://streams.spec.whatwg.org/#set-up-readable-stream-default-controller-from-underlying-source
  582. 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)
  583. {
  584. auto& realm = stream.realm();
  585. // 1. Let controller be a new ReadableStreamDefaultController.
  586. auto controller = MUST_OR_THROW_OOM(stream.heap().allocate<ReadableStreamDefaultController>(realm, realm));
  587. // 2. Let startAlgorithm be an algorithm that returns undefined.
  588. StartAlgorithm start_algorithm = [] { return JS::js_undefined(); };
  589. // 3. Let pullAlgorithm be an algorithm that returns a promise resolved with undefined.
  590. PullAlgorithm pull_algorithm = [&realm]() {
  591. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  592. };
  593. // 4. Let cancelAlgorithm be an algorithm that returns a promise resolved with undefined.
  594. CancelAlgorithm cancel_algorithm = [&realm](auto const&) {
  595. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  596. };
  597. // 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.
  598. if (underlying_source.start) {
  599. start_algorithm = [controller, underlying_source_value, callback = underlying_source.start]() -> WebIDL::ExceptionOr<JS::Value> {
  600. // Note: callback does not return a promise, so invoke_callback may return an abrupt completion
  601. return TRY(WebIDL::invoke_callback(*callback, underlying_source_value, controller)).release_value();
  602. };
  603. }
  604. // 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.
  605. if (underlying_source.pull) {
  606. pull_algorithm = [&realm, controller, underlying_source_value, callback = underlying_source.pull]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  607. // Note: callback return a promise, so invoke_callback will never return an abrupt completion
  608. auto result = MUST_OR_THROW_OOM(WebIDL::invoke_callback(*callback, underlying_source_value, controller)).release_value();
  609. return WebIDL::create_resolved_promise(realm, result);
  610. };
  611. }
  612. // 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.
  613. if (underlying_source.cancel) {
  614. cancel_algorithm = [&realm, controller, underlying_source_value, callback = underlying_source.cancel](auto const& reason) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  615. // Note: callback return a promise, so invoke_callback will never return an abrupt completion
  616. auto result = MUST_OR_THROW_OOM(WebIDL::invoke_callback(*callback, underlying_source_value, reason)).release_value();
  617. return WebIDL::create_resolved_promise(realm, result);
  618. };
  619. }
  620. // 8. Perform ? SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm).
  621. return set_up_readable_stream_default_controller(stream, controller, move(start_algorithm), move(pull_algorithm), move(cancel_algorithm), high_water_mark, move(size_algorithm));
  622. }
  623. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-call-pull-if-needed
  624. WebIDL::ExceptionOr<void> readable_byte_stream_controller_call_pull_if_needed(ReadableByteStreamController& controller)
  625. {
  626. // 1. Let shouldPull be ! ReadableByteStreamControllerShouldCallPull(controller).
  627. auto should_pull = readable_byte_stream_controller_should_call_pull(controller);
  628. // 2. If shouldPull is false, return.
  629. if (!should_pull)
  630. return {};
  631. // 3. If controller.[[pulling]] is true,
  632. if (controller.pulling()) {
  633. // 1. Set controller.[[pullAgain]] to true.
  634. controller.set_pull_again(true);
  635. // 2. Return.
  636. return {};
  637. }
  638. // 4. Assert: controller.[[pullAgain]] is false.
  639. VERIFY(!controller.pull_again());
  640. // 5. Set controller.[[pulling]] to true.
  641. controller.set_pulling(true);
  642. // 6. Let pullPromise be the result of performing controller.[[pullAlgorithm]].
  643. auto pull_promise = TRY((*controller.pull_algorithm())());
  644. // 7. Upon fulfillment of pullPromise,
  645. WebIDL::upon_fulfillment(*pull_promise, [&](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  646. // 1. Set controller.[[pulling]] to false.
  647. controller.set_pulling(false);
  648. // 2. If controller.[[pullAgain]] is true,
  649. if (controller.pull_again()) {
  650. // 1. Set controller.[[pullAgain]] to false.
  651. controller.set_pull_again(false);
  652. // 2. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
  653. TRY(readable_byte_stream_controller_call_pull_if_needed(controller));
  654. }
  655. return JS::js_undefined();
  656. });
  657. // 8. Upon rejection of pullPromise with reason e,
  658. WebIDL::upon_rejection(*pull_promise, [&](auto const& error) -> WebIDL::ExceptionOr<JS::Value> {
  659. // 1. Perform ! ReadableByteStreamControllerError(controller, e).
  660. readable_byte_stream_controller_error(controller, error);
  661. return JS::js_undefined();
  662. });
  663. return {};
  664. }
  665. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-clear-algorithms
  666. void readable_byte_stream_controller_clear_algorithms(ReadableByteStreamController& controller)
  667. {
  668. // FIXME: This AO can be invoked from within one of the algorithms below. If we clear them, it invokes SafeFunction's
  669. // destructor, which asserts we are not currently invoking the function (as it clears the storage). We need to
  670. // figure out how to delay this, as these algorithms may keep objects alive that can otherwise be GC'd.
  671. (void)controller;
  672. // 1. Set controller.[[pullAlgorithm]] to undefined.
  673. // controller.set_pull_algorithm({});
  674. // 2. Set controller.[[cancelAlgorithm]] to undefined.
  675. // controller.set_cancel_algorithm({});
  676. }
  677. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-clear-pending-pull-intos
  678. void readable_byte_stream_controller_clear_pending_pull_intos(ReadableByteStreamController& controller)
  679. {
  680. // 1. Perform ! ReadableByteStreamControllerInvalidateBYOBRequest(controller).
  681. readable_byte_stream_controller_invalidate_byob_request(controller);
  682. // 2. Set controller.[[pendingPullIntos]] to a new empty list.
  683. controller.pending_pull_intos().clear();
  684. }
  685. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-close
  686. WebIDL::ExceptionOr<void> readable_byte_stream_controller_close(ReadableByteStreamController& controller)
  687. {
  688. auto& realm = controller.realm();
  689. // 1. Let stream be controller.[[stream]].
  690. auto stream = controller.stream();
  691. // 2. If controller.[[closeRequested]] is true or stream.[[state]] is not "readable", return.
  692. if (controller.close_requested() || stream->state() != ReadableStream::State::Readable)
  693. return {};
  694. // 3. If controller.[[queueTotalSize]] > 0,
  695. if (controller.queue_total_size() > 0.0) {
  696. // 1. Set controller.[[closeRequested]] to true.
  697. controller.set_close_requested(true);
  698. // 2. Return.
  699. return {};
  700. }
  701. // 4. If controller.[[pendingPullIntos]] is not empty,
  702. if (!controller.pending_pull_intos().is_empty()) {
  703. // 1. Let firstPendingPullInto be controller.[[pendingPullIntos]][0].
  704. auto& first_pending_pull_into = controller.pending_pull_intos().first();
  705. // 2. If firstPendingPullInto’s bytes filled > 0,
  706. if (first_pending_pull_into.bytes_filled > 0) {
  707. // 1. Let e be a new TypeError exception.
  708. auto error = MUST_OR_THROW_OOM(JS::TypeError::create(realm, "Cannot close controller in the middle of processing a write request"sv));
  709. // 2. Perform ! ReadableByteStreamControllerError(controller, e).
  710. readable_byte_stream_controller_error(controller, error);
  711. // 3. Throw e.
  712. return JS::throw_completion(error);
  713. }
  714. }
  715. // 5. Perform ! ReadableByteStreamControllerClearAlgorithms(controller).
  716. readable_byte_stream_controller_clear_algorithms(controller);
  717. // 6. Perform ! ReadableStreamClose(stream).
  718. readable_stream_close(*stream);
  719. return {};
  720. }
  721. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-error
  722. void readable_byte_stream_controller_error(ReadableByteStreamController& controller, JS::Value error)
  723. {
  724. // 1. Let stream be controller.[[stream]].
  725. auto stream = controller.stream();
  726. // 2. If stream.[[state]] is not "readable", return.
  727. if (stream->state() != ReadableStream::State::Readable)
  728. return;
  729. // 3. Perform ! ReadableByteStreamControllerClearPendingPullIntos(controller).
  730. readable_byte_stream_controller_clear_pending_pull_intos(controller);
  731. // 4. Perform ! ResetQueue(controller).
  732. reset_queue(controller);
  733. // 5. Perform ! ReadableByteStreamControllerClearAlgorithms(controller).
  734. readable_byte_stream_controller_clear_algorithms(controller);
  735. // 6. Perform ! ReadableStreamError(stream, e).
  736. readable_stream_error(*stream, error);
  737. }
  738. // https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerfillreadrequestfromqueue
  739. WebIDL::ExceptionOr<void> readable_byte_stream_controller_fill_read_request_from_queue(ReadableByteStreamController& controller, NonnullRefPtr<ReadRequest> read_request)
  740. {
  741. auto& vm = controller.vm();
  742. auto& realm = controller.realm();
  743. // 1. Assert: controller.[[queueTotalSize]] > 0.
  744. VERIFY(controller.queue_total_size() > 0.0);
  745. // 2. Let entry be controller.[[queue]][0].
  746. // 3. Remove entry from controller.[[queue]].
  747. auto entry = controller.queue().take_first();
  748. // 4. Set controller.[[queueTotalSize]] to controller.[[queueTotalSize]] − entry’s byte length.
  749. controller.set_queue_total_size(controller.queue_total_size() - entry.byte_length);
  750. // 5. Perform ! ReadableByteStreamControllerHandleQueueDrain(controller).
  751. TRY(readable_byte_stream_controller_handle_queue_drain(controller));
  752. // 6. Let view be ! Construct(%Uint8Array%, « entry’s buffer, entry’s byte offset, entry’s byte length »).
  753. 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)));
  754. // 7. Perform readRequest’s chunk steps, given view.
  755. read_request->on_chunk(view);
  756. return {};
  757. }
  758. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-get-desired-size
  759. Optional<double> readable_byte_stream_controller_get_desired_size(ReadableByteStreamController const& controller)
  760. {
  761. auto stream = controller.stream();
  762. // 1. Let state be controller.[[stream]].[[state]].
  763. // 2. If state is "errored", return null.
  764. if (stream->is_errored())
  765. return {};
  766. // 3. If state is "closed", return 0.
  767. if (stream->is_closed())
  768. return 0.0;
  769. // 4. Return controller.[[strategyHWM]] − controller.[[queueTotalSize]].
  770. return controller.strategy_hwm() - controller.queue_total_size();
  771. }
  772. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-handle-queue-drain
  773. WebIDL::ExceptionOr<void> readable_byte_stream_controller_handle_queue_drain(ReadableByteStreamController& controller)
  774. {
  775. // 1. Assert: controller.[[stream]].[[state]] is "readable".
  776. VERIFY(controller.stream()->state() == ReadableStream::State::Readable);
  777. // 2. If controller.[[queueTotalSize]] is 0 and controller.[[closeRequested]] is true,
  778. if (controller.queue_total_size() == 0.0 && controller.close_requested()) {
  779. // 1. Perform ! ReadableByteStreamControllerClearAlgorithms(controller).
  780. readable_byte_stream_controller_clear_algorithms(controller);
  781. // 2. Perform ! ReadableStreamClose(controller.[[stream]]).
  782. readable_stream_close(*controller.stream());
  783. }
  784. // 3. Otherwise,
  785. else {
  786. // 1. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
  787. TRY(readable_byte_stream_controller_call_pull_if_needed(controller));
  788. }
  789. return {};
  790. }
  791. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-invalidate-byob-request
  792. void readable_byte_stream_controller_invalidate_byob_request(ReadableByteStreamController& controller)
  793. {
  794. // 1. If controller.[[byobRequest]] is null, return.
  795. if (!controller.byob_request())
  796. return;
  797. // 2. Set controller.[[byobRequest]].[[controller]] to undefined.
  798. controller.byob_request()->set_controller({});
  799. // 3. Set controller.[[byobRequest]].[[view]] to null.
  800. controller.byob_request()->set_view({});
  801. // 4. Set controller.[[byobRequest]] to null.
  802. controller.set_byob_request({});
  803. }
  804. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-error
  805. bool readable_byte_stream_controller_should_call_pull(ReadableByteStreamController const& controller)
  806. {
  807. // 1. Let stream be controller.[[stream]].
  808. auto stream = controller.stream();
  809. // 2. If stream.[[state]] is not "readable", return false.
  810. if (stream->state() != ReadableStream::State::Readable)
  811. return false;
  812. // 3. If controller.[[closeRequested]] is true, return false.
  813. if (controller.close_requested())
  814. return false;
  815. // 4. If controller.[[started]] is false, return false.
  816. if (!controller.started())
  817. return false;
  818. // 5. If ! ReadableStreamHasDefaultReader(stream) is true and ! ReadableStreamGetNumReadRequests(stream) > 0, return true.
  819. if (readable_stream_has_default_reader(*stream) && readable_stream_get_num_read_requests(*stream) > 0)
  820. return true;
  821. // 6. If ! ReadableStreamHasBYOBReader(stream) is true and ! ReadableStreamGetNumReadIntoRequests(stream) > 0, return true.
  822. if (readable_stream_has_byob_reader(*stream) && readable_stream_get_num_read_into_requests(*stream) > 0)
  823. return true;
  824. // 7. Let desiredSize be ! ReadableByteStreamControllerGetDesiredSize(controller).
  825. auto desired_size = readable_byte_stream_controller_get_desired_size(controller);
  826. // 8. Assert: desiredSize is not null.
  827. VERIFY(desired_size.has_value());
  828. // 9. If desiredSize > 0, return true.
  829. if (*desired_size > 0.0)
  830. return true;
  831. // 10. Return false.
  832. return false;
  833. }
  834. // https://streams.spec.whatwg.org/#acquire-writable-stream-default-writer
  835. WebIDL::ExceptionOr<JS::NonnullGCPtr<WritableStreamDefaultWriter>> acquire_writable_stream_default_writer(WritableStream& stream)
  836. {
  837. auto& realm = stream.realm();
  838. // 1. Let writer be a new WritableStreamDefaultWriter.
  839. auto writer = MUST_OR_THROW_OOM(stream.heap().allocate<WritableStreamDefaultWriter>(realm, realm));
  840. // 2. Perform ? SetUpWritableStreamDefaultWriter(writer, stream).
  841. TRY(set_up_writable_stream_default_writer(*writer, stream));
  842. // 3. Return writer.
  843. return writer;
  844. }
  845. // https://streams.spec.whatwg.org/#is-writable-stream-locked
  846. bool is_writable_stream_locked(WritableStream const& stream)
  847. {
  848. // 1. If stream.[[writer]] is undefined, return false.
  849. if (!stream.writer())
  850. return false;
  851. // 2. Return true.
  852. return true;
  853. }
  854. // https://streams.spec.whatwg.org/#set-up-writable-stream-default-writer
  855. WebIDL::ExceptionOr<void> set_up_writable_stream_default_writer(WritableStreamDefaultWriter& writer, WritableStream& stream)
  856. {
  857. auto& realm = writer.realm();
  858. // 1. If ! IsWritableStreamLocked(stream) is true, throw a TypeError exception.
  859. if (is_writable_stream_locked(stream))
  860. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Stream is locked"sv };
  861. // 2. Set writer.[[stream]] to stream.
  862. writer.set_stream(stream);
  863. // 3. Set stream.[[writer]] to writer.
  864. stream.set_writer(writer);
  865. // 4. Let state be stream.[[state]].
  866. auto state = stream.state();
  867. // 5. If state is "writable",
  868. if (state == WritableStream::State::Writable) {
  869. // 1. If ! WritableStreamCloseQueuedOrInFlight(stream) is false and stream.[[backpressure]] is true, set writer.[[readyPromise]] to a new promise.
  870. if (!writable_stream_close_queued_or_in_flight(stream) && stream.backpressure()) {
  871. writer.set_ready_promise(WebIDL::create_promise(realm));
  872. }
  873. // 2. Otherwise, set writer.[[readyPromise]] to a promise resolved with undefined.
  874. else {
  875. writer.set_ready_promise(WebIDL::create_resolved_promise(realm, JS::js_undefined()));
  876. }
  877. // 3. Set writer.[[closedPromise]] to a new promise.
  878. writer.set_closed_promise(WebIDL::create_promise(realm));
  879. }
  880. // 6. Otherwise, if state is "erroring",
  881. else if (state == WritableStream::State::Erroring) {
  882. // 1. Set writer.[[readyPromise]] to a promise rejected with stream.[[storedError]].
  883. writer.set_ready_promise(WebIDL::create_rejected_promise(realm, stream.stored_error()));
  884. // 2. Set writer.[[readyPromise]].[[PromiseIsHandled]] to true.
  885. WebIDL::mark_promise_as_handled(*writer.ready_promise());
  886. // 3. Set writer.[[closedPromise]] to a new promise.
  887. writer.set_closed_promise(WebIDL::create_promise(realm));
  888. }
  889. // 7. Otherwise, if state is "closed",
  890. else if (state == WritableStream::State::Closed) {
  891. // 1. Set writer.[[readyPromise]] to a promise resolved with undefined.
  892. writer.set_ready_promise(WebIDL::create_resolved_promise(realm, JS::js_undefined()));
  893. // 2. Set writer.[[closedPromise]] to a promise resolved with undefined.
  894. writer.set_closed_promise(WebIDL::create_resolved_promise(realm, JS::js_undefined()));
  895. }
  896. // 8. Otherwise,
  897. else {
  898. // 1. Assert: state is "errored".
  899. VERIFY(state == WritableStream::State::Errored);
  900. // 2. Let storedError be stream.[[storedError]].
  901. auto stored_error = stream.stored_error();
  902. // 3. Set writer.[[readyPromise]] to a promise rejected with storedError.
  903. writer.set_ready_promise(WebIDL::create_rejected_promise(realm, stored_error));
  904. // 4. Set writer.[[readyPromise]].[[PromiseIsHandled]] to true.
  905. WebIDL::mark_promise_as_handled(*writer.ready_promise());
  906. // 5. Set writer.[[closedPromise]] to a promise rejected with storedError.
  907. writer.set_closed_promise(WebIDL::create_rejected_promise(realm, stored_error));
  908. // 6. Set writer.[[closedPromise]].[[PromiseIsHandled]] to true.
  909. WebIDL::mark_promise_as_handled(*writer.closed_promise());
  910. }
  911. return {};
  912. }
  913. // https://streams.spec.whatwg.org/#set-up-readable-byte-stream-controller
  914. 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)
  915. {
  916. auto& realm = stream.realm();
  917. // 1. Assert: stream.[[controller]] is undefined.
  918. VERIFY(!stream.controller().has_value());
  919. // 2. If autoAllocateChunkSize is not undefined,
  920. if (!auto_allocate_chunk_size.is_undefined()) {
  921. // 1. Assert: ! IsInteger(autoAllocateChunkSize) is true.
  922. VERIFY(auto_allocate_chunk_size.is_integral_number());
  923. // 2. Assert: autoAllocateChunkSize is positive.
  924. VERIFY(auto_allocate_chunk_size.as_double() > 0);
  925. }
  926. // 3. Set controller.[[stream]] to stream.
  927. controller.set_stream(stream);
  928. // 4. Set controller.[[pullAgain]] and controller.[[pulling]] to false.
  929. controller.set_pull_again(false);
  930. controller.set_pulling(false);
  931. // 5. Set controller.[[byobRequest]] to null.
  932. controller.set_byob_request({});
  933. // 6. Perform ! ResetQueue(controller).
  934. reset_queue(controller);
  935. // 7. Set controller.[[closeRequested]] and controller.[[started]] to false.
  936. controller.set_close_requested(false);
  937. controller.set_started(false);
  938. // 8. Set controller.[[strategyHWM]] to highWaterMark.
  939. controller.set_strategy_hwm(high_water_mark);
  940. // 9. Set controller.[[pullAlgorithm]] to pullAlgorithm.
  941. controller.set_pull_algorithm(move(pull_algorithm));
  942. // 10. Set controller.[[cancelAlgorithm]] to cancelAlgorithm.
  943. controller.set_cancel_algorithm(move(cancel_algorithm));
  944. // 11. Set controller.[[autoAllocateChunkSize]] to autoAllocateChunkSize.
  945. if (auto_allocate_chunk_size.is_integral_number())
  946. controller.set_auto_allocate_chunk_size(auto_allocate_chunk_size.as_double());
  947. // 12. Set controller.[[pendingPullIntos]] to a new empty list.
  948. controller.pending_pull_intos().clear();
  949. // 13. Set stream.[[controller]] to controller.
  950. stream.set_controller(ReadableStreamController { controller });
  951. // 14. Let startResult be the result of performing startAlgorithm.
  952. auto start_result = TRY(start_algorithm());
  953. // 15. Let startPromise be a promise resolved with startResult.
  954. auto start_promise = WebIDL::create_resolved_promise(realm, start_result);
  955. // 16. Upon fulfillment of startPromise,
  956. WebIDL::upon_fulfillment(start_promise, [&](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  957. // 1. Set controller.[[started]] to true.
  958. controller.set_started(true);
  959. // 2. Assert: controller.[[pulling]] is false.
  960. VERIFY(!controller.pulling());
  961. // 3. Assert: controller.[[pullAgain]] is false.
  962. VERIFY(!controller.pull_again());
  963. // 4. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
  964. TRY(readable_byte_stream_controller_call_pull_if_needed(controller));
  965. return JS::js_undefined();
  966. });
  967. // 17. Upon rejection of startPromise with reason r,
  968. WebIDL::upon_rejection(start_promise, [&](auto const& r) -> WebIDL::ExceptionOr<JS::Value> {
  969. // 1. Perform ! ReadableByteStreamControllerError(controller, r).
  970. readable_byte_stream_controller_error(controller, r);
  971. return JS::js_undefined();
  972. });
  973. return {};
  974. }
  975. // https://streams.spec.whatwg.org/#readablestream-set-up-with-byte-reading-support
  976. 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)
  977. {
  978. auto& realm = stream.realm();
  979. // 1. Let startAlgorithm be an algorithm that returns undefined.
  980. StartAlgorithm start_algorithm = [] { return JS::js_undefined(); };
  981. // 2. Let pullAlgorithmWrapper be an algorithm that runs these steps:
  982. PullAlgorithm pull_algorithm_wrapper = [&realm, pull_algorithm = move(pull_algorithm)]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  983. // 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.
  984. JS::GCPtr<JS::PromiseCapability> result = nullptr;
  985. if (pull_algorithm.has_value())
  986. result = TRY(pull_algorithm.value()());
  987. // 2. If result is a Promise, then return result.
  988. if (result != nullptr)
  989. return JS::NonnullGCPtr(*result);
  990. // 3. Return a promise resolved with undefined.
  991. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  992. };
  993. // 3. Let cancelAlgorithmWrapper be an algorithm that runs these steps:
  994. CancelAlgorithm cancel_algorithm_wrapper = [&realm, cancel_algorithm = move(cancel_algorithm)](auto const& c) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  995. // 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.
  996. JS::GCPtr<JS::PromiseCapability> result = nullptr;
  997. if (cancel_algorithm.has_value())
  998. result = TRY(cancel_algorithm.value()(c));
  999. // 2. If result is a Promise, then return result.
  1000. if (result != nullptr)
  1001. return JS::NonnullGCPtr(*result);
  1002. // 3. Return a promise resolved with undefined.
  1003. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  1004. };
  1005. // 4. Perform ! InitializeReadableStream(stream).
  1006. // 5. Let controller be a new ReadableByteStreamController.
  1007. auto controller = MUST_OR_THROW_OOM(stream.heap().allocate<ReadableByteStreamController>(realm, realm));
  1008. // 6. Perform ! SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithmWrapper, cancelAlgorithmWrapper, highWaterMark, undefined).
  1009. 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()));
  1010. return {};
  1011. }
  1012. // https://streams.spec.whatwg.org/#writable-stream-abort
  1013. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_abort(WritableStream& stream, JS::Value reason)
  1014. {
  1015. auto& realm = stream.realm();
  1016. // 1. If stream.[[state]] is "closed" or "errored", return a promise resolved with undefined.
  1017. auto state = stream.state();
  1018. if (state == WritableStream::State::Closed || state == WritableStream::State::Errored)
  1019. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  1020. // 2. Signal abort on stream.[[controller]].[[signal]] with reason.
  1021. stream.controller()->signal()->signal_abort(reason);
  1022. // 3. Let state be stream.[[state]].
  1023. state = stream.state();
  1024. // 4. If state is "closed" or "errored", return a promise resolved with undefined.
  1025. if (state == WritableStream::State::Closed || state == WritableStream::State::Errored)
  1026. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  1027. // 5. If stream.[[pendingAbortRequest]] is not undefined, return stream.[[pendingAbortRequest]]'s promise.
  1028. if (stream.pending_abort_request().has_value())
  1029. return stream.pending_abort_request()->promise;
  1030. // 6. Assert: state is "writable" or "erroring".
  1031. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  1032. // 7. Let wasAlreadyErroring be false.
  1033. auto was_already_erroring = false;
  1034. // 8. If state is "erroring",
  1035. if (state == WritableStream::State::Erroring) {
  1036. // 1. Set wasAlreadyErroring to true.
  1037. was_already_erroring = true;
  1038. // 2. Set reason to undefined.
  1039. reason = JS::js_undefined();
  1040. }
  1041. // 9. Let promise be a new promise.
  1042. auto promise = WebIDL::create_promise(realm);
  1043. // 10. Set stream.[[pendingAbortRequest]] to a new pending abort request whose promise is promise, reason is reason, and was already erroring is wasAlreadyErroring.
  1044. stream.set_pending_abort_request(PendingAbortRequest { promise, reason, was_already_erroring });
  1045. // 11. If wasAlreadyErroring is false, perform ! WritableStreamStartErroring(stream, reason).
  1046. if (!was_already_erroring)
  1047. TRY(writable_stream_start_erroring(stream, reason));
  1048. // 12. Return promise.
  1049. return promise;
  1050. }
  1051. // https://streams.spec.whatwg.org/#writable-stream-close
  1052. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_close(WritableStream& stream)
  1053. {
  1054. auto& realm = stream.realm();
  1055. // 1. Let state be stream.[[state]].
  1056. auto state = stream.state();
  1057. // 2. If state is "closed" or "errored", return a promise rejected with a TypeError exception.
  1058. if (state == WritableStream::State::Closed || state == WritableStream::State::Errored) {
  1059. auto message = state == WritableStream::State::Closed ? "Cannot close a closed stream"sv : "Cannot close an errored stream"sv;
  1060. auto exception = MUST_OR_THROW_OOM(JS::TypeError::create(realm, message));
  1061. return WebIDL::create_rejected_promise(realm, exception);
  1062. }
  1063. // 3. Assert: state is "writable" or "erroring".
  1064. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  1065. // 4. Assert: ! WritableStreamCloseQueuedOrInFlight(stream) is false.
  1066. VERIFY(!writable_stream_close_queued_or_in_flight(stream));
  1067. // 5. Let promise be a new promise.
  1068. auto promise = WebIDL::create_promise(realm);
  1069. // 6. Set stream.[[closeRequest]] to promise.
  1070. stream.set_close_request(promise);
  1071. // 7. Let writer be stream.[[writer]].
  1072. auto writer = stream.writer();
  1073. // 8. If writer is not undefined, and stream.[[backpressure]] is true, and state is "writable", resolve writer.[[readyPromise]] with undefined.
  1074. if (writer && stream.backpressure() && state == WritableStream::State::Writable)
  1075. WebIDL::resolve_promise(realm, *writer->ready_promise(), JS::js_undefined());
  1076. // 9. Perform ! WritableStreamDefaultControllerClose(stream.[[controller]]).
  1077. TRY(writable_stream_default_controller_close(*stream.controller()));
  1078. // 10. Return promise.
  1079. return promise;
  1080. }
  1081. // https://streams.spec.whatwg.org/#writable-stream-add-write-request
  1082. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_add_write_request(WritableStream& stream)
  1083. {
  1084. auto& realm = stream.realm();
  1085. auto& vm = stream.vm();
  1086. // 1. Assert: ! IsWritableStreamLocked(stream) is true.
  1087. VERIFY(is_writable_stream_locked(stream));
  1088. // 2. Assert: stream.[[state]] is "writable".
  1089. VERIFY(stream.state() == WritableStream::State::Writable);
  1090. // 3. Let promise be a new promise.
  1091. auto promise = WebIDL::create_promise(realm);
  1092. // 4. Append promise to stream.[[writeRequests]].
  1093. TRY_OR_THROW_OOM(vm, stream.write_requests().try_append(promise));
  1094. // 5. Return promise.
  1095. return promise;
  1096. }
  1097. // https://streams.spec.whatwg.org/#writable-stream-close-queued-or-in-flight
  1098. bool writable_stream_close_queued_or_in_flight(WritableStream const& stream)
  1099. {
  1100. // 1. If stream.[[closeRequest]] is undefined and stream.[[inFlightCloseRequest]] is undefined, return false.
  1101. if (!stream.close_request() && !stream.in_flight_write_request())
  1102. return false;
  1103. // 2. Return true.
  1104. return true;
  1105. }
  1106. // https://streams.spec.whatwg.org/#writable-stream-deal-with-rejection
  1107. WebIDL::ExceptionOr<void> writable_stream_deal_with_rejection(WritableStream& stream, JS::Value error)
  1108. {
  1109. // 1. Let state be stream.[[state]].
  1110. auto state = stream.state();
  1111. // 2. If state is "writable",
  1112. if (state == WritableStream::State::Writable) {
  1113. // 1. Perform ! WritableStreamStartErroring(stream, error).
  1114. // 2. Return.
  1115. return writable_stream_start_erroring(stream, error);
  1116. }
  1117. // 3. Assert: state is "erroring".
  1118. VERIFY(state == WritableStream::State::Erroring);
  1119. // 4. Perform ! WritableStreamFinishErroring(stream).
  1120. return writable_stream_finish_erroring(stream);
  1121. }
  1122. // https://streams.spec.whatwg.org/#writable-stream-finish-erroring
  1123. WebIDL::ExceptionOr<void> writable_stream_finish_erroring(WritableStream& stream)
  1124. {
  1125. auto& realm = stream.realm();
  1126. // 1. Assert: stream.[[state]] is "erroring".
  1127. VERIFY(stream.state() == WritableStream::State::Erroring);
  1128. // 2. Assert: ! WritableStreamHasOperationMarkedInFlight(stream) is false.
  1129. VERIFY(!writable_stream_has_operation_marked_in_flight(stream));
  1130. // 3. Set stream.[[state]] to "errored".
  1131. stream.set_state(WritableStream::State::Errored);
  1132. // 4. Perform ! stream.[[controller]].[[ErrorSteps]]().
  1133. stream.controller()->error_steps();
  1134. // 5. Let storedError be stream.[[storedError]].
  1135. auto stored_error = stream.stored_error();
  1136. // 6. For each writeRequest of stream.[[writeRequests]]:
  1137. for (auto& write_request : stream.write_requests()) {
  1138. // 1. Reject writeRequest with storedError.
  1139. WebIDL::reject_promise(realm, *write_request, stored_error);
  1140. }
  1141. // 7. Set stream.[[writeRequests]] to an empty list.
  1142. stream.write_requests().clear();
  1143. // 8. If stream.[[pendingAbortRequest]] is undefined,
  1144. if (!stream.pending_abort_request().has_value()) {
  1145. // 1. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).
  1146. writable_stream_reject_close_and_closed_promise_if_needed(stream);
  1147. // 2. Return.
  1148. return {};
  1149. }
  1150. // 9. Let abortRequest be stream.[[pendingAbortRequest]].
  1151. // 10. Set stream.[[pendingAbortRequest]] to undefined.
  1152. auto abort_request = stream.pending_abort_request().release_value();
  1153. // 11. If abortRequest’s was already erroring is true,
  1154. if (abort_request.was_already_erroring) {
  1155. // 1. Reject abortRequest’s promise with storedError.
  1156. WebIDL::reject_promise(realm, abort_request.promise, stored_error);
  1157. // 2. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).
  1158. writable_stream_reject_close_and_closed_promise_if_needed(stream);
  1159. // 3. Return.
  1160. return {};
  1161. }
  1162. // 12. Let promise be ! stream.[[controller]].[[AbortSteps]](abortRequest’s reason).
  1163. auto promise = TRY(stream.controller()->abort_steps(abort_request.reason));
  1164. // 13. Upon fulfillment of promise,
  1165. WebIDL::upon_fulfillment(*promise, [&, abort_promise = abort_request.promise](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  1166. // 1. Resolve abortRequest’s promise with undefined.
  1167. WebIDL::resolve_promise(realm, abort_promise, JS::js_undefined());
  1168. // 2. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).
  1169. writable_stream_reject_close_and_closed_promise_if_needed(stream);
  1170. return JS::js_undefined();
  1171. });
  1172. // 14. Upon rejection of promise with reason reason,
  1173. WebIDL::upon_rejection(*promise, [&, abort_promise = abort_request.promise](auto const& reason) -> WebIDL::ExceptionOr<JS::Value> {
  1174. // 1. Reject abortRequest’s promise with reason.
  1175. WebIDL::reject_promise(realm, abort_promise, reason);
  1176. // 2. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).
  1177. writable_stream_reject_close_and_closed_promise_if_needed(stream);
  1178. return JS::js_undefined();
  1179. });
  1180. return {};
  1181. }
  1182. // https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-close
  1183. void writable_stream_finish_in_flight_close(WritableStream& stream)
  1184. {
  1185. auto& realm = stream.realm();
  1186. // 1. Assert: stream.[[inFlightCloseRequest]] is not undefined.
  1187. VERIFY(stream.in_flight_close_request());
  1188. // 2. Resolve stream.[[inFlightCloseRequest]] with undefined.
  1189. WebIDL::resolve_promise(realm, *stream.in_flight_close_request(), JS::js_undefined());
  1190. // 3. Set stream.[[inFlightCloseRequest]] to undefined.
  1191. stream.set_in_flight_close_request({});
  1192. // 4. Let state be stream.[[state]].
  1193. auto state = stream.state();
  1194. // 5. Assert: stream.[[state]] is "writable" or "erroring".
  1195. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  1196. // 6. If state is "erroring",
  1197. if (state == WritableStream::State::Erroring) {
  1198. // 1. Set stream.[[storedError]] to undefined.
  1199. stream.set_stored_error(JS::js_undefined());
  1200. // 2. If stream.[[pendingAbortRequest]] is not undefined,
  1201. if (stream.pending_abort_request().has_value()) {
  1202. // 1. Resolve stream.[[pendingAbortRequest]]'s promise with undefined.
  1203. // 2. Set stream.[[pendingAbortRequest]] to undefined.
  1204. WebIDL::resolve_promise(realm, stream.pending_abort_request().release_value().promise, JS::js_undefined());
  1205. }
  1206. }
  1207. // 7. Set stream.[[state]] to "closed".
  1208. stream.set_state(WritableStream::State::Closed);
  1209. // 8. Let writer be stream.[[writer]].
  1210. auto writer = stream.writer();
  1211. // 9. If writer is not undefined, resolve writer.[[closedPromise]] with undefined.
  1212. if (writer)
  1213. WebIDL::resolve_promise(realm, *writer->closed_promise(), JS::js_undefined());
  1214. // 10. Assert: stream.[[pendingAbortRequest]] is undefined.
  1215. VERIFY(!stream.pending_abort_request().has_value());
  1216. // 11. Assert: stream.[[storedError]] is undefined.
  1217. VERIFY(stream.stored_error().is_undefined());
  1218. }
  1219. // https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-close-with-error
  1220. WebIDL::ExceptionOr<void> writable_stream_finish_in_flight_close_with_error(WritableStream& stream, JS::Value error)
  1221. {
  1222. auto& realm = stream.realm();
  1223. // 1. Assert: stream.[[inFlightCloseRequest]] is not undefined.
  1224. VERIFY(stream.in_flight_close_request());
  1225. // 2. Reject stream.[[inFlightCloseRequest]] with error.
  1226. WebIDL::reject_promise(realm, *stream.in_flight_close_request(), error);
  1227. // 3. Set stream.[[inFlightCloseRequest]] to undefined.
  1228. stream.set_in_flight_close_request({});
  1229. // 4. Assert: stream.[[state]] is "writable" or "erroring".
  1230. auto state = stream.state();
  1231. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  1232. // 5. If stream.[[pendingAbortRequest]] is not undefined,
  1233. if (stream.pending_abort_request().has_value()) {
  1234. // 1. Reject stream.[[pendingAbortRequest]]'s promise with error.
  1235. // 2. Set stream.[[pendingAbortRequest]] to undefined.
  1236. WebIDL::reject_promise(realm, stream.pending_abort_request().release_value().promise, error);
  1237. }
  1238. // 6. Perform ! WritableStreamDealWithRejection(stream, error).
  1239. return writable_stream_deal_with_rejection(stream, error);
  1240. }
  1241. // https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-write
  1242. void writable_stream_finish_in_flight_write(WritableStream& stream)
  1243. {
  1244. auto& realm = stream.realm();
  1245. // 1. Assert: stream.[[inFlightWriteRequest]] is not undefined.
  1246. VERIFY(stream.in_flight_write_request());
  1247. // 2. Resolve stream.[[inFlightWriteRequest]] with undefined.
  1248. WebIDL::resolve_promise(realm, *stream.in_flight_write_request(), JS::js_undefined());
  1249. // 3. Set stream.[[inFlightWriteRequest]] to undefined.
  1250. stream.set_in_flight_write_request({});
  1251. }
  1252. // https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-write-with-error
  1253. WebIDL::ExceptionOr<void> writable_stream_finish_in_flight_write_with_error(WritableStream& stream, JS::Value error)
  1254. {
  1255. auto& realm = stream.realm();
  1256. // 1. Assert: stream.[[inFlightWriteRequest]] is not undefined.
  1257. VERIFY(stream.in_flight_write_request());
  1258. // 2. Reject stream.[[inFlightWriteRequest]] with error.
  1259. WebIDL::reject_promise(realm, *stream.in_flight_write_request(), error);
  1260. // 3. Set stream.[[inFlightWriteRequest]] to undefined.
  1261. stream.set_in_flight_write_request({});
  1262. // 4. Assert: stream.[[state]] is "writable" or "erroring".
  1263. auto state = stream.state();
  1264. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  1265. // 5. Perform ! WritableStreamDealWithRejection(stream, error).
  1266. return writable_stream_deal_with_rejection(stream, error);
  1267. }
  1268. // https://streams.spec.whatwg.org/#writable-stream-has-operation-marked-in-flight
  1269. bool writable_stream_has_operation_marked_in_flight(WritableStream const& stream)
  1270. {
  1271. // 1. If stream.[[inFlightWriteRequest]] is undefined and stream.[[inFlightCloseRequest]] is undefined, return false.
  1272. if (!stream.in_flight_write_request() && !stream.in_flight_close_request())
  1273. return false;
  1274. // 2. Return true.
  1275. return true;
  1276. }
  1277. // https://streams.spec.whatwg.org/#writable-stream-mark-close-request-in-flight
  1278. void writable_stream_mark_close_request_in_flight(WritableStream& stream)
  1279. {
  1280. // 1. Assert: stream.[[inFlightCloseRequest]] is undefined.
  1281. VERIFY(!stream.in_flight_close_request());
  1282. // 2. Assert: stream.[[closeRequest]] is not undefined.
  1283. VERIFY(stream.close_request());
  1284. // 3. Set stream.[[inFlightCloseRequest]] to stream.[[closeRequest]].
  1285. stream.set_in_flight_close_request(stream.close_request());
  1286. // 4. Set stream.[[closeRequest]] to undefined.
  1287. stream.set_close_request({});
  1288. }
  1289. // https://streams.spec.whatwg.org/#writable-stream-mark-first-write-request-in-flight
  1290. void writable_stream_mark_first_write_request_in_flight(WritableStream& stream)
  1291. {
  1292. // 1. Assert: stream.[[inFlightWriteRequest]] is undefined.
  1293. VERIFY(!stream.in_flight_write_request());
  1294. // 2. Assert: stream.[[writeRequests]] is not empty.
  1295. VERIFY(!stream.write_requests().is_empty());
  1296. // 3. Let writeRequest be stream.[[writeRequests]][0].
  1297. // 4. Remove writeRequest from stream.[[writeRequests]].
  1298. auto write_request = stream.write_requests().take_first();
  1299. // 5. Set stream.[[inFlightWriteRequest]] to writeRequest.
  1300. stream.set_in_flight_write_request(write_request);
  1301. }
  1302. // https://streams.spec.whatwg.org/#writable-stream-reject-close-and-closed-promise-if-needed
  1303. void writable_stream_reject_close_and_closed_promise_if_needed(WritableStream& stream)
  1304. {
  1305. auto& realm = stream.realm();
  1306. // 1. Assert: stream.[[state]] is "errored".
  1307. VERIFY(stream.state() == WritableStream::State::Errored);
  1308. // 2. If stream.[[closeRequest]] is not undefined,
  1309. if (stream.close_request()) {
  1310. // 1. Assert: stream.[[inFlightCloseRequest]] is undefined.
  1311. VERIFY(!stream.in_flight_close_request());
  1312. // 2. Reject stream.[[closeRequest]] with stream.[[storedError]].
  1313. WebIDL::reject_promise(realm, *stream.close_request(), stream.stored_error());
  1314. // 3. Set stream.[[closeRequest]] to undefined.
  1315. stream.set_close_request({});
  1316. }
  1317. // 3. Let writer be stream.[[writer]].
  1318. auto writer = stream.writer();
  1319. // 4. If writer is not undefined,
  1320. if (writer) {
  1321. // 1. Reject writer.[[closedPromise]] with stream.[[storedError]].
  1322. WebIDL::reject_promise(realm, *writer->closed_promise(), stream.stored_error());
  1323. // 2. Set writer.[[closedPromise]].[[PromiseIsHandled]] to true.
  1324. WebIDL::mark_promise_as_handled(*writer->closed_promise());
  1325. }
  1326. }
  1327. // https://streams.spec.whatwg.org/#writable-stream-start-erroring
  1328. WebIDL::ExceptionOr<void> writable_stream_start_erroring(WritableStream& stream, JS::Value reason)
  1329. {
  1330. // 1. Assert: stream.[[storedError]] is undefined.
  1331. VERIFY(stream.stored_error().is_undefined());
  1332. // 2. Assert: stream.[[state]] is "writable".
  1333. VERIFY(stream.state() == WritableStream::State::Writable);
  1334. // 3. Let controller be stream.[[controller]].
  1335. auto controller = stream.controller();
  1336. // 4. Assert: controller is not undefined.
  1337. VERIFY(controller);
  1338. // 5. Set stream.[[state]] to "erroring".
  1339. stream.set_state(WritableStream::State::Erroring);
  1340. // 6. Set stream.[[storedError]] to reason.
  1341. stream.set_stored_error(reason);
  1342. // 7. Let writer be stream.[[writer]].
  1343. auto writer = stream.writer();
  1344. // 8. If writer is not undefined, perform ! WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason).
  1345. if (writer)
  1346. writable_stream_default_writer_ensure_ready_promise_rejected(*writer, reason);
  1347. // 9. If ! WritableStreamHasOperationMarkedInFlight(stream) is false and controller.[[started]] is true, perform ! WritableStreamFinishErroring(stream).
  1348. if (!writable_stream_has_operation_marked_in_flight(stream) && controller->started())
  1349. TRY(writable_stream_finish_erroring(stream));
  1350. return {};
  1351. }
  1352. // https://streams.spec.whatwg.org/#writable-stream-update-backpressure
  1353. void writable_stream_update_backpressure(WritableStream& stream, bool backpressure)
  1354. {
  1355. auto& realm = stream.realm();
  1356. // 1. Assert: stream.[[state]] is "writable".
  1357. VERIFY(stream.state() == WritableStream::State::Writable);
  1358. // 2. Assert: ! WritableStreamCloseQueuedOrInFlight(stream) is false.
  1359. VERIFY(!writable_stream_close_queued_or_in_flight(stream));
  1360. // 3. Let writer be stream.[[writer]].
  1361. auto writer = stream.writer();
  1362. // 4. If writer is not undefined and backpressure is not stream.[[backpressure]],
  1363. if (writer && backpressure != stream.backpressure()) {
  1364. // 1. If backpressure is true, set writer.[[readyPromise]] to a new promise.
  1365. if (backpressure) {
  1366. writer->set_ready_promise(WebIDL::create_promise(realm));
  1367. }
  1368. // 2. Otherwise,
  1369. else {
  1370. // 1. Assert: backpressure is false.
  1371. // 2. Resolve writer.[[readyPromise]] with undefined.
  1372. WebIDL::resolve_promise(realm, *writer->ready_promise(), JS::js_undefined());
  1373. }
  1374. }
  1375. // 5. Set stream.[[backpressure]] to backpressure.
  1376. stream.set_backpressure(backpressure);
  1377. }
  1378. // https://streams.spec.whatwg.org/#writable-stream-default-writer-abort
  1379. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_default_writer_abort(WritableStreamDefaultWriter& writer, JS::Value reason)
  1380. {
  1381. // 1. Let stream be writer.[[stream]].
  1382. auto stream = writer.stream();
  1383. // 2. Assert: stream is not undefined.
  1384. VERIFY(stream);
  1385. // 3. Return ! WritableStreamAbort(stream, reason).
  1386. return writable_stream_abort(*stream, reason);
  1387. }
  1388. // https://streams.spec.whatwg.org/#writable-stream-default-writer-close
  1389. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_default_writer_close(WritableStreamDefaultWriter& writer)
  1390. {
  1391. // 1. Let stream be writer.[[stream]].
  1392. auto stream = writer.stream();
  1393. // 2. Assert: stream is not undefined.
  1394. VERIFY(stream);
  1395. // 3. Return ! WritableStreamClose(stream).
  1396. return writable_stream_close(*stream);
  1397. }
  1398. // https://streams.spec.whatwg.org/#writable-stream-default-writer-ensure-closed-promise-rejected
  1399. void writable_stream_default_writer_ensure_closed_promise_rejected(WritableStreamDefaultWriter& writer, JS::Value error)
  1400. {
  1401. auto& realm = writer.realm();
  1402. // 1. If writer.[[closedPromise]].[[PromiseState]] is "pending", reject writer.[[closedPromise]] with error.
  1403. auto& closed_promise = verify_cast<JS::Promise>(*writer.closed_promise()->promise());
  1404. if (closed_promise.state() == JS::Promise::State::Pending) {
  1405. WebIDL::reject_promise(realm, *writer.closed_promise(), error);
  1406. }
  1407. // 2. Otherwise, set writer.[[closedPromise]] to a promise rejected with error.
  1408. else {
  1409. writer.set_closed_promise(WebIDL::create_rejected_promise(realm, error));
  1410. }
  1411. // 3. Set writer.[[closedPromise]].[[PromiseIsHandled]] to true.
  1412. WebIDL::mark_promise_as_handled(*writer.closed_promise());
  1413. }
  1414. // https://streams.spec.whatwg.org/#writable-stream-default-writer-ensure-ready-promise-rejected
  1415. void writable_stream_default_writer_ensure_ready_promise_rejected(WritableStreamDefaultWriter& writer, JS::Value error)
  1416. {
  1417. auto& realm = writer.realm();
  1418. // 1. If writer.[[readyPromise]].[[PromiseState]] is "pending", reject writer.[[readyPromise]] with error.
  1419. auto& ready_promise = verify_cast<JS::Promise>(*writer.ready_promise()->promise());
  1420. if (ready_promise.state() == JS::Promise::State::Pending) {
  1421. WebIDL::reject_promise(realm, *writer.ready_promise(), error);
  1422. }
  1423. // 2. Otherwise, set writer.[[readyPromise]] to a promise rejected with error.
  1424. else {
  1425. writer.set_ready_promise(WebIDL::create_rejected_promise(realm, error));
  1426. }
  1427. // 3. Set writer.[[readyPromise]].[[PromiseIsHandled]] to true.
  1428. WebIDL::mark_promise_as_handled(*writer.ready_promise());
  1429. }
  1430. // https://streams.spec.whatwg.org/#writable-stream-default-writer-get-desired-size
  1431. Optional<double> writable_stream_default_writer_get_desired_size(WritableStreamDefaultWriter const& writer)
  1432. {
  1433. // 1. Let stream be writer.[[stream]].
  1434. auto stream = writer.stream();
  1435. // 2. Let state be stream.[[state]].
  1436. auto state = stream->state();
  1437. // 3. If state is "errored" or "erroring", return null.
  1438. if (state == WritableStream::State::Errored || state == WritableStream::State::Erroring)
  1439. return {};
  1440. // 4. If state is "closed", return 0.
  1441. if (state == WritableStream::State::Closed)
  1442. return 0.0;
  1443. // 5. Return ! WritableStreamDefaultControllerGetDesiredSize(stream.[[controller]]).
  1444. return writable_stream_default_controller_get_desired_size(*stream->controller());
  1445. }
  1446. // https://streams.spec.whatwg.org/#writable-stream-default-writer-release
  1447. WebIDL::ExceptionOr<void> writable_stream_default_writer_release(WritableStreamDefaultWriter& writer)
  1448. {
  1449. auto& realm = writer.realm();
  1450. // 1. Let stream be writer.[[stream]].
  1451. auto stream = writer.stream();
  1452. // 2. Assert: stream is not undefined.
  1453. VERIFY(stream);
  1454. // 3. Assert: stream.[[writer]] is writer.
  1455. VERIFY(stream->writer().ptr() == &writer);
  1456. // 4. Let releasedError be a new TypeError.
  1457. auto released_error = MUST_OR_THROW_OOM(JS::TypeError::create(realm, "Writer's stream lock has been released"sv));
  1458. // 5. Perform ! WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError).
  1459. writable_stream_default_writer_ensure_ready_promise_rejected(writer, released_error);
  1460. // 6. Perform ! WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError).
  1461. writable_stream_default_writer_ensure_closed_promise_rejected(writer, released_error);
  1462. // 7. Set stream.[[writer]] to undefined.
  1463. stream->set_writer({});
  1464. // 8. Set writer.[[stream]] to undefined.
  1465. writer.set_stream({});
  1466. return {};
  1467. }
  1468. // https://streams.spec.whatwg.org/#writable-stream-default-writer-write
  1469. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_default_writer_write(WritableStreamDefaultWriter& writer, JS::Value chunk)
  1470. {
  1471. auto& realm = writer.realm();
  1472. // 1. Let stream be writer.[[stream]].
  1473. auto stream = writer.stream();
  1474. // 2. Assert: stream is not undefined.
  1475. VERIFY(stream);
  1476. // 3. Let controller be stream.[[controller]].
  1477. auto controller = stream->controller();
  1478. // 4. Let chunkSize be ! WritableStreamDefaultControllerGetChunkSize(controller, chunk).
  1479. auto chunk_size = TRY(writable_stream_default_controller_get_chunk_size(*controller, chunk));
  1480. // 5. If stream is not equal to writer.[[stream]], return a promise rejected with a TypeError exception.
  1481. if (stream.ptr() != writer.stream().ptr()) {
  1482. auto exception = MUST_OR_THROW_OOM(JS::TypeError::create(realm, "Writer's locked stream changed during write"sv));
  1483. return WebIDL::create_rejected_promise(realm, exception);
  1484. }
  1485. // 6. Let state be stream.[[state]].
  1486. auto state = stream->state();
  1487. // 7. If state is "errored", return a promise rejected with stream.[[storedError]].
  1488. if (state == WritableStream::State::Errored)
  1489. return WebIDL::create_rejected_promise(realm, stream->stored_error());
  1490. // 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.
  1491. if (writable_stream_close_queued_or_in_flight(*stream) || state == WritableStream::State::Closed) {
  1492. auto exception = MUST_OR_THROW_OOM(JS::TypeError::create(realm, "Cannot write to a writer whose stream is closing or already closed"sv));
  1493. return WebIDL::create_rejected_promise(realm, exception);
  1494. }
  1495. // 9. If state is "erroring", return a promise rejected with stream.[[storedError]].
  1496. if (state == WritableStream::State::Erroring)
  1497. return WebIDL::create_rejected_promise(realm, stream->stored_error());
  1498. // 10. Assert: state is "writable".
  1499. VERIFY(state == WritableStream::State::Writable);
  1500. // 11. Let promise be ! WritableStreamAddWriteRequest(stream).
  1501. auto promise = writable_stream_add_write_request(*stream);
  1502. // 12. Perform ! WritableStreamDefaultControllerWrite(controller, chunk, chunkSize).
  1503. TRY(writable_stream_default_controller_write(*controller, chunk, chunk_size));
  1504. // 13. Return promise.
  1505. return promise;
  1506. }
  1507. // https://streams.spec.whatwg.org/#set-up-writable-stream-default-controller
  1508. 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)
  1509. {
  1510. auto& realm = stream.realm();
  1511. // 1. Assert: stream implements WritableStream.
  1512. // 2. Assert: stream.[[controller]] is undefined.
  1513. VERIFY(!stream.controller());
  1514. // 3. Set controller.[[stream]] to stream.
  1515. controller.set_stream(stream);
  1516. // 4. Set stream.[[controller]] to controller.
  1517. stream.set_controller(controller);
  1518. // 5. Perform ! ResetQueue(controller).
  1519. reset_queue(controller);
  1520. // 6. Set controller.[[signal]] to a new AbortSignal.
  1521. controller.set_signal(MUST_OR_THROW_OOM(realm.heap().allocate<DOM::AbortSignal>(realm, realm)));
  1522. // 7. Set controller.[[started]] to false.
  1523. controller.set_started(false);
  1524. // 8. Set controller.[[strategySizeAlgorithm]] to sizeAlgorithm.
  1525. controller.set_strategy_size_algorithm(move(size_algorithm));
  1526. // 9. Set controller.[[strategyHWM]] to highWaterMark.
  1527. controller.set_strategy_hwm(high_water_mark);
  1528. // 10. Set controller.[[writeAlgorithm]] to writeAlgorithm.
  1529. controller.set_write_algorithm(move(write_algorithm));
  1530. // 11. Set controller.[[closeAlgorithm]] to closeAlgorithm.
  1531. controller.set_close_algorithm(move(close_algorithm));
  1532. // 12. Set controller.[[abortAlgorithm]] to abortAlgorithm.
  1533. controller.set_abort_algorithm(move(abort_algorithm));
  1534. // 13. Let backpressure be ! WritableStreamDefaultControllerGetBackpressure(controller).
  1535. auto backpressure = writable_stream_default_controller_get_backpressure(controller);
  1536. // 14. Perform ! WritableStreamUpdateBackpressure(stream, backpressure).
  1537. writable_stream_update_backpressure(stream, backpressure);
  1538. // 15. Let startResult be the result of performing startAlgorithm. (This may throw an exception.)
  1539. auto start_result = TRY(start_algorithm());
  1540. // 16. Let startPromise be a promise resolved with startResult.
  1541. auto start_promise = WebIDL::create_resolved_promise(realm, start_result);
  1542. // 17. Upon fulfillment of startPromise,
  1543. WebIDL::upon_fulfillment(*start_promise, [&](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  1544. // 1. Assert: stream.[[state]] is "writable" or "erroring".
  1545. auto state = stream.state();
  1546. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  1547. // 2. Set controller.[[started]] to true.
  1548. controller.set_started(true);
  1549. // 3. Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).
  1550. TRY(writable_stream_default_controller_advance_queue_if_needed(controller));
  1551. return JS::js_undefined();
  1552. });
  1553. // 18. Upon rejection of startPromise with reason r,
  1554. WebIDL::upon_rejection(*start_promise, [&](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {
  1555. // 1. Assert: stream.[[state]] is "writable" or "erroring".
  1556. auto state = stream.state();
  1557. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  1558. // 2. Set controller.[[started]] to true.
  1559. controller.set_started(true);
  1560. // 3. Perform ! WritableStreamDealWithRejection(stream, r).
  1561. TRY(writable_stream_deal_with_rejection(stream, reason));
  1562. return JS::js_undefined();
  1563. });
  1564. return {};
  1565. }
  1566. // https://streams.spec.whatwg.org/#set-up-writable-stream-default-controller-from-underlying-sink
  1567. 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)
  1568. {
  1569. auto& realm = stream.realm();
  1570. // 1. Let controller be a new WritableStreamDefaultController.
  1571. auto controller = MUST_OR_THROW_OOM(realm.heap().allocate<WritableStreamDefaultController>(realm, realm));
  1572. // 2. Let startAlgorithm be an algorithm that returns undefined.
  1573. StartAlgorithm start_algorithm = [] { return JS::js_undefined(); };
  1574. // 3. Let writeAlgorithm be an algorithm that returns a promise resolved with undefined.
  1575. WriteAlgorithm write_algorithm = [&realm](auto const&) {
  1576. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  1577. };
  1578. // 4. Let closeAlgorithm be an algorithm that returns a promise resolved with undefined.
  1579. CloseAlgorithm close_algorithm = [&realm] {
  1580. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  1581. };
  1582. // 5. Let abortAlgorithm be an algorithm that returns a promise resolved with undefined.
  1583. AbortAlgorithm abort_algorithm = [&realm](auto const&) {
  1584. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  1585. };
  1586. // 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.
  1587. if (underlying_sink.start) {
  1588. start_algorithm = [controller, underlying_sink_value, callback = underlying_sink.start]() -> WebIDL::ExceptionOr<JS::Value> {
  1589. // Note: callback does not return a promise, so invoke_callback may return an abrupt completion
  1590. return TRY(WebIDL::invoke_callback(*callback, underlying_sink_value, controller)).release_value();
  1591. };
  1592. }
  1593. // 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.
  1594. if (underlying_sink.write) {
  1595. write_algorithm = [&realm, controller, underlying_sink_value, callback = underlying_sink.write](JS::Value chunk) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  1596. // Note: callback return a promise, so invoke_callback will never return an abrupt completion
  1597. auto result = MUST_OR_THROW_OOM(WebIDL::invoke_callback(*callback, underlying_sink_value, chunk, controller)).release_value();
  1598. return WebIDL::create_resolved_promise(realm, result);
  1599. };
  1600. }
  1601. // 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.
  1602. if (underlying_sink.close) {
  1603. close_algorithm = [&realm, controller, underlying_sink_value, callback = underlying_sink.close]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  1604. // Note: callback return a promise, so invoke_callback will never return an abrupt completion
  1605. auto result = MUST_OR_THROW_OOM(WebIDL::invoke_callback(*callback, underlying_sink_value)).release_value();
  1606. return WebIDL::create_resolved_promise(realm, result);
  1607. };
  1608. }
  1609. // 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.
  1610. if (underlying_sink.abort) {
  1611. abort_algorithm = [&realm, controller, underlying_sink_value, callback = underlying_sink.abort](JS::Value reason) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  1612. // Note: callback return a promise, so invoke_callback will never return an abrupt completion
  1613. auto result = MUST_OR_THROW_OOM(WebIDL::invoke_callback(*callback, underlying_sink_value, reason)).release_value();
  1614. return WebIDL::create_resolved_promise(realm, result);
  1615. };
  1616. }
  1617. // 10. Perform ? SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm).
  1618. 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)));
  1619. return {};
  1620. }
  1621. // https://streams.spec.whatwg.org/#writable-stream-default-controller-advance-queue-if-needed
  1622. WebIDL::ExceptionOr<void> writable_stream_default_controller_advance_queue_if_needed(WritableStreamDefaultController& controller)
  1623. {
  1624. // 1. Let stream be controller.[[stream]].
  1625. auto stream = controller.stream();
  1626. // 2. If controller.[[started]] is false, return.
  1627. if (!controller.started())
  1628. return {};
  1629. // 3. If stream.[[inFlightWriteRequest]] is not undefined, return.
  1630. if (stream->in_flight_write_request())
  1631. return {};
  1632. // 4. Let state be stream.[[state]].
  1633. auto state = stream->state();
  1634. // 5. Assert: state is not "closed" or "errored".
  1635. VERIFY(state != WritableStream::State::Closed && state != WritableStream::State::Errored);
  1636. // 6. If state is "erroring",
  1637. if (state == WritableStream::State::Erroring) {
  1638. // 1. Perform ! WritableStreamFinishErroring(stream).
  1639. // 2. Return.
  1640. return writable_stream_finish_erroring(*stream);
  1641. }
  1642. // 7. If controller.[[queue]] is empty, return.
  1643. if (controller.queue().is_empty())
  1644. return {};
  1645. // 8. Let value be ! PeekQueueValue(controller).
  1646. auto value = peek_queue_value(controller);
  1647. // 9. If value is the close sentinel, perform ! WritableStreamDefaultControllerProcessClose(controller).
  1648. if (is_close_sentinel(value)) {
  1649. TRY(writable_stream_default_controller_process_close(controller));
  1650. }
  1651. // 10. Otherwise, perform ! WritableStreamDefaultControllerProcessWrite(controller, value).
  1652. else {
  1653. TRY(writable_stream_default_controller_process_write(controller, value));
  1654. }
  1655. return {};
  1656. }
  1657. // https://streams.spec.whatwg.org/#writable-stream-default-controller-clear-algorithms
  1658. void writable_stream_default_controller_clear_algorithms(WritableStreamDefaultController& controller)
  1659. {
  1660. // FIXME: This AO can be invoked from within one of the algorithms below. If we clear them, it invokes SafeFunction's
  1661. // destructor, which asserts we are not currently invoking the function (as it clears the storage). We need to
  1662. // figure out how to delay this, as these algorithms may keep objects alive that can otherwise be GC'd.
  1663. (void)controller;
  1664. // 1. Set controller.[[writeAlgorithm]] to undefined.
  1665. // controller.set_write_algorithm({});
  1666. // 2. Set controller.[[closeAlgorithm]] to undefined.
  1667. // controller.set_close_algorithm({});
  1668. // 3. Set controller.[[abortAlgorithm]] to undefined.
  1669. // controller.set_abort_algorithm({});
  1670. // 4. Set controller.[[strategySizeAlgorithm]] to undefined.
  1671. // controller.set_strategy_size_algorithm({});
  1672. }
  1673. // https://streams.spec.whatwg.org/#writable-stream-default-controller-close
  1674. WebIDL::ExceptionOr<void> writable_stream_default_controller_close(WritableStreamDefaultController& controller)
  1675. {
  1676. // 1. Perform ! EnqueueValueWithSize(controller, close sentinel, 0).
  1677. TRY(enqueue_value_with_size(controller, create_close_sentinel(), JS::Value(0.0)));
  1678. // 2. Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).
  1679. TRY(writable_stream_default_controller_advance_queue_if_needed(controller));
  1680. return {};
  1681. }
  1682. // https://streams.spec.whatwg.org/#writable-stream-default-controller-error
  1683. WebIDL::ExceptionOr<void> writable_stream_default_controller_error(WritableStreamDefaultController& controller, JS::Value error)
  1684. {
  1685. // 1. Let stream be controller.[[stream]].
  1686. auto stream = controller.stream();
  1687. // 2. Assert: stream.[[state]] is "writable".
  1688. VERIFY(stream->state() == WritableStream::State::Writable);
  1689. // 3. Perform ! WritableStreamDefaultControllerClearAlgorithms(controller).
  1690. writable_stream_default_controller_clear_algorithms(controller);
  1691. // 4. Perform ! WritableStreamStartErroring(stream, error).
  1692. return writable_stream_start_erroring(stream, error);
  1693. }
  1694. // https://streams.spec.whatwg.org/#writable-stream-default-controller-error-if-needed
  1695. WebIDL::ExceptionOr<void> writable_stream_default_controller_error_if_needed(WritableStreamDefaultController& controller, JS::Value error)
  1696. {
  1697. // 1. If controller.[[stream]].[[state]] is "writable", perform ! WritableStreamDefaultControllerError(controller, error).
  1698. if (controller.stream()->state() == WritableStream::State::Writable)
  1699. TRY(writable_stream_default_controller_error(controller, error));
  1700. return {};
  1701. }
  1702. // https://streams.spec.whatwg.org/#writable-stream-default-controller-get-backpressure
  1703. bool writable_stream_default_controller_get_backpressure(WritableStreamDefaultController const& controller)
  1704. {
  1705. // 1. Let desiredSize be ! WritableStreamDefaultControllerGetDesiredSize(controller).
  1706. auto desired_size = writable_stream_default_controller_get_desired_size(controller);
  1707. // 2. Return true if desiredSize ≤ 0, or false otherwise.
  1708. return desired_size <= 0.0;
  1709. }
  1710. // https://streams.spec.whatwg.org/#writable-stream-default-controller-get-chunk-size
  1711. WebIDL::ExceptionOr<JS::Value> writable_stream_default_controller_get_chunk_size(WritableStreamDefaultController& controller, JS::Value chunk)
  1712. {
  1713. // 1. Let returnValue be the result of performing controller.[[strategySizeAlgorithm]], passing in chunk, and interpreting the result as a completion record.
  1714. auto return_value = (*controller.strategy_size_algorithm())(chunk);
  1715. // 2. If returnValue is an abrupt completion,
  1716. if (return_value.is_abrupt()) {
  1717. // 1. Perform ! WritableStreamDefaultControllerErrorIfNeeded(controller, returnValue.[[Value]]).
  1718. TRY(writable_stream_default_controller_error_if_needed(controller, *return_value.release_value()));
  1719. // 2. Return 1.
  1720. return 1.0;
  1721. }
  1722. // 3. Return returnValue.[[Value]].
  1723. return *return_value.release_value();
  1724. }
  1725. // https://streams.spec.whatwg.org/#writable-stream-default-controller-get-desired-size
  1726. double writable_stream_default_controller_get_desired_size(WritableStreamDefaultController const& controller)
  1727. {
  1728. // 1. Return controller.[[strategyHWM]] − controller.[[queueTotalSize]].
  1729. return controller.strategy_hwm() - controller.queue_total_size();
  1730. }
  1731. // https://streams.spec.whatwg.org/#writable-stream-default-controller-process-close
  1732. WebIDL::ExceptionOr<void> writable_stream_default_controller_process_close(WritableStreamDefaultController& controller)
  1733. {
  1734. // 1. Let stream be controller.[[stream]].
  1735. auto stream = controller.stream();
  1736. // 2. Perform ! WritableStreamMarkCloseRequestInFlight(stream).
  1737. writable_stream_mark_close_request_in_flight(*stream);
  1738. // 3. Perform ! DequeueValue(controller).
  1739. dequeue_value(controller);
  1740. // 4. Assert: controller.[[queue]] is empty.
  1741. VERIFY(controller.queue().is_empty());
  1742. // 5. Let sinkClosePromise be the result of performing controller.[[closeAlgorithm]].
  1743. auto sink_close_promise = TRY((*controller.close_algorithm())());
  1744. // 6. Perform ! WritableStreamDefaultControllerClearAlgorithms(controller).
  1745. writable_stream_default_controller_clear_algorithms(controller);
  1746. // 7. Upon fulfillment of sinkClosePromise,
  1747. WebIDL::upon_fulfillment(*sink_close_promise, [&, stream = stream](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  1748. // 1. Perform ! WritableStreamFinishInFlightClose(stream).
  1749. writable_stream_finish_in_flight_close(*stream);
  1750. return JS::js_undefined();
  1751. });
  1752. // 8. Upon rejection of sinkClosePromise with reason reason,
  1753. WebIDL::upon_rejection(*sink_close_promise, [&, stream = stream](auto const& reason) -> WebIDL::ExceptionOr<JS::Value> {
  1754. // 1. Perform ! WritableStreamFinishInFlightCloseWithError(stream, reason).
  1755. TRY(writable_stream_finish_in_flight_close_with_error(*stream, reason));
  1756. return JS::js_undefined();
  1757. });
  1758. return {};
  1759. }
  1760. // https://streams.spec.whatwg.org/#writable-stream-default-controller-process-write
  1761. WebIDL::ExceptionOr<void> writable_stream_default_controller_process_write(WritableStreamDefaultController& controller, JS::Value chunk)
  1762. {
  1763. // 1. Let stream be controller.[[stream]].
  1764. auto stream = controller.stream();
  1765. // 2. Perform ! WritableStreamMarkFirstWriteRequestInFlight(stream).
  1766. writable_stream_mark_first_write_request_in_flight(*stream);
  1767. // 3. Let sinkWritePromise be the result of performing controller.[[writeAlgorithm]], passing in chunk.
  1768. auto sink_write_promise = TRY((*controller.write_algorithm())(chunk));
  1769. // 4. Upon fulfillment of sinkWritePromise,
  1770. WebIDL::upon_fulfillment(*sink_write_promise, [&, stream = stream](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  1771. // 1. Perform ! WritableStreamFinishInFlightWrite(stream).
  1772. writable_stream_finish_in_flight_write(*stream);
  1773. // 2. Let state be stream.[[state]].
  1774. auto state = stream->state();
  1775. // 3. Assert: state is "writable" or "erroring".
  1776. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  1777. // 4. Perform ! DequeueValue(controller).
  1778. dequeue_value(controller);
  1779. // 5. If ! WritableStreamCloseQueuedOrInFlight(stream) is false and state is "writable",
  1780. if (!writable_stream_close_queued_or_in_flight(*stream) && state == WritableStream::State::Writable) {
  1781. // 1. Let backpressure be ! WritableStreamDefaultControllerGetBackpressure(controller).
  1782. auto backpressure = writable_stream_default_controller_get_backpressure(controller);
  1783. // 2. Perform ! WritableStreamUpdateBackpressure(stream, backpressure).
  1784. writable_stream_update_backpressure(*stream, backpressure);
  1785. }
  1786. // 6 .Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).
  1787. TRY(writable_stream_default_controller_advance_queue_if_needed(controller));
  1788. return JS::js_undefined();
  1789. });
  1790. // 5. Upon rejection of sinkWritePromise with reason,
  1791. WebIDL::upon_rejection(*sink_write_promise, [&, stream = stream](auto const& reason) -> WebIDL::ExceptionOr<JS::Value> {
  1792. // 1. If stream.[[state]] is "writable", perform ! WritableStreamDefaultControllerClearAlgorithms(controller).
  1793. if (stream->state() == WritableStream::State::Writable)
  1794. writable_stream_default_controller_clear_algorithms(controller);
  1795. // 2. Perform ! WritableStreamFinishInFlightWriteWithError(stream, reason).
  1796. TRY(writable_stream_finish_in_flight_write_with_error(*stream, reason));
  1797. return JS::js_undefined();
  1798. });
  1799. return {};
  1800. }
  1801. // https://streams.spec.whatwg.org/#writable-stream-default-controller-write
  1802. WebIDL::ExceptionOr<void> writable_stream_default_controller_write(WritableStreamDefaultController& controller, JS::Value chunk, JS::Value chunk_size)
  1803. {
  1804. auto& vm = controller.vm();
  1805. // 1. Let enqueueResult be EnqueueValueWithSize(controller, chunk, chunkSize).
  1806. auto enqueue_result = enqueue_value_with_size(controller, chunk, chunk_size);
  1807. // 2. If enqueueResult is an abrupt completion,
  1808. if (enqueue_result.is_exception()) {
  1809. auto throw_completion = Bindings::throw_dom_exception_if_needed(vm, [&] { return enqueue_result; }).throw_completion();
  1810. // 1. Perform ! WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueResult.[[Value]]).
  1811. TRY(writable_stream_default_controller_error_if_needed(controller, *throw_completion.release_value()));
  1812. // 2. Return.
  1813. return {};
  1814. }
  1815. // 3. Let stream be controller.[[stream]].
  1816. auto stream = controller.stream();
  1817. // 4. If ! WritableStreamCloseQueuedOrInFlight(stream) is false and stream.[[state]] is "writable",
  1818. if (!writable_stream_close_queued_or_in_flight(*stream) && stream->state() == WritableStream::State::Writable) {
  1819. // 1. Let backpressure be ! WritableStreamDefaultControllerGetBackpressure(controller).
  1820. auto backpressure = writable_stream_default_controller_get_backpressure(controller);
  1821. // 2. Perform ! WritableStreamUpdateBackpressure(stream, backpressure).
  1822. writable_stream_update_backpressure(*stream, backpressure);
  1823. }
  1824. // 5. Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).
  1825. TRY(writable_stream_default_controller_advance_queue_if_needed(controller));
  1826. return {};
  1827. }
  1828. // https://streams.spec.whatwg.org/#is-non-negative-number
  1829. bool is_non_negative_number(JS::Value value)
  1830. {
  1831. // 1. If Type(v) is not Number, return false.
  1832. if (!value.is_number())
  1833. return false;
  1834. // 2. If v is NaN, return false.
  1835. if (value.is_nan())
  1836. return false;
  1837. // 3. If v < 0, return false.
  1838. if (value.as_double() < 0.0)
  1839. return false;
  1840. // 4. Return true.
  1841. return true;
  1842. }
  1843. // https://streams.spec.whatwg.org/#close-sentinel
  1844. // Non-standard function that implements the "close sentinel" value.
  1845. JS::Value create_close_sentinel()
  1846. {
  1847. // 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.
  1848. // 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.
  1849. return {};
  1850. }
  1851. // https://streams.spec.whatwg.org/#close-sentinel
  1852. // Non-standard function that implements the "If value is a close sentinel" check.
  1853. bool is_close_sentinel(JS::Value value)
  1854. {
  1855. return value.is_empty();
  1856. }
  1857. // Non-standard function to aid in converting a user-provided function into a WebIDL::Callback. This is essentially
  1858. // what the Bindings generator would do at compile time, but at runtime instead.
  1859. 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)
  1860. {
  1861. auto property = TRY(value.get(vm, property_key));
  1862. if (property.is_undefined())
  1863. return JS::Handle<WebIDL::CallbackType> {};
  1864. if (!property.is_function())
  1865. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAFunction, TRY_OR_THROW_OOM(vm, property.to_string_without_side_effects()));
  1866. return vm.heap().allocate_without_realm<WebIDL::CallbackType>(property.as_object(), HTML::incumbent_settings_object(), operation_returns_promise);
  1867. }
  1868. }