AbstractOperations.cpp 126 KB

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