AbstractOperations.cpp 148 KB

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