AbstractOperations.cpp 228 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046
  1. /*
  2. * Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
  3. * Copyright (c) 2023, Matthew Olsson <mattco@serenityos.org>
  4. * Copyright (c) 2023-2024, 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/Array.h>
  10. #include <LibJS/Runtime/ArrayBuffer.h>
  11. #include <LibJS/Runtime/DataView.h>
  12. #include <LibJS/Runtime/DataViewConstructor.h>
  13. #include <LibJS/Runtime/Intrinsics.h>
  14. #include <LibJS/Runtime/PromiseCapability.h>
  15. #include <LibJS/Runtime/PromiseConstructor.h>
  16. #include <LibJS/Runtime/TypedArray.h>
  17. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  18. #include <LibWeb/DOM/AbortSignal.h>
  19. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  20. #include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
  21. #include <LibWeb/HTML/StructuredSerialize.h>
  22. #include <LibWeb/Streams/AbstractOperations.h>
  23. #include <LibWeb/Streams/QueuingStrategy.h>
  24. #include <LibWeb/Streams/ReadableByteStreamController.h>
  25. #include <LibWeb/Streams/ReadableStream.h>
  26. #include <LibWeb/Streams/ReadableStreamBYOBReader.h>
  27. #include <LibWeb/Streams/ReadableStreamBYOBRequest.h>
  28. #include <LibWeb/Streams/ReadableStreamDefaultController.h>
  29. #include <LibWeb/Streams/ReadableStreamDefaultReader.h>
  30. #include <LibWeb/Streams/ReadableStreamGenericReader.h>
  31. #include <LibWeb/Streams/TransformStream.h>
  32. #include <LibWeb/Streams/TransformStreamDefaultController.h>
  33. #include <LibWeb/Streams/Transformer.h>
  34. #include <LibWeb/Streams/UnderlyingSink.h>
  35. #include <LibWeb/Streams/UnderlyingSource.h>
  36. #include <LibWeb/Streams/WritableStream.h>
  37. #include <LibWeb/Streams/WritableStreamDefaultController.h>
  38. #include <LibWeb/Streams/WritableStreamDefaultWriter.h>
  39. #include <LibWeb/WebIDL/AbstractOperations.h>
  40. #include <LibWeb/WebIDL/Buffers.h>
  41. #include <LibWeb/WebIDL/ExceptionOr.h>
  42. #include <LibWeb/WebIDL/Promise.h>
  43. namespace Web::Streams {
  44. // https://streams.spec.whatwg.org/#acquire-readable-stream-reader
  45. WebIDL::ExceptionOr<JS::NonnullGCPtr<ReadableStreamDefaultReader>> acquire_readable_stream_default_reader(ReadableStream& stream)
  46. {
  47. auto& realm = stream.realm();
  48. // 1. Let reader be a new ReadableStreamDefaultReader.
  49. auto reader = realm.heap().allocate<ReadableStreamDefaultReader>(realm, realm);
  50. // 2. Perform ? SetUpReadableStreamDefaultReader(reader, stream).
  51. TRY(set_up_readable_stream_default_reader(reader, stream));
  52. // 3. Return reader.
  53. return reader;
  54. }
  55. // https://streams.spec.whatwg.org/#acquire-readable-stream-byob-reader
  56. WebIDL::ExceptionOr<JS::NonnullGCPtr<ReadableStreamBYOBReader>> acquire_readable_stream_byob_reader(ReadableStream& stream)
  57. {
  58. auto& realm = stream.realm();
  59. // 1. Let reader be a new ReadableStreamBYOBReader.
  60. auto reader = realm.heap().allocate<ReadableStreamBYOBReader>(realm, realm);
  61. // 2. Perform ? SetUpReadableStreamBYOBReader(reader, stream).
  62. TRY(set_up_readable_stream_byob_reader(reader, stream));
  63. // 3. Return reader.
  64. return reader;
  65. }
  66. // https://streams.spec.whatwg.org/#is-readable-stream-locked
  67. bool is_readable_stream_locked(ReadableStream const& stream)
  68. {
  69. // 1. If stream.[[reader]] is undefined, return false.
  70. if (!stream.reader().has_value())
  71. return false;
  72. // 2. Return true.
  73. return true;
  74. }
  75. // https://streams.spec.whatwg.org/#readable-stream-cancel
  76. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> readable_stream_cancel(ReadableStream& stream, JS::Value reason)
  77. {
  78. auto& realm = stream.realm();
  79. // 1. Set stream.[[disturbed]] to true.
  80. stream.set_disturbed(true);
  81. // 2. If stream.[[state]] is "closed", return a promise resolved with undefined.
  82. if (stream.state() == ReadableStream::State::Closed)
  83. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  84. // 3. If stream.[[state]] is "errored", return a promise rejected with stream.[[storedError]].
  85. if (stream.state() == ReadableStream::State::Errored)
  86. return WebIDL::create_rejected_promise(realm, stream.stored_error());
  87. // 4. Perform ! ReadableStreamClose(stream).
  88. readable_stream_close(stream);
  89. // 5. Let reader be stream.[[reader]].
  90. auto reader = stream.reader();
  91. // 6. If reader is not undefined and reader implements ReadableStreamBYOBReader,
  92. if (reader.has_value() && reader->has<JS::NonnullGCPtr<ReadableStreamBYOBReader>>()) {
  93. // 1. Let readIntoRequests be reader.[[readIntoRequests]].
  94. // 2. Set reader.[[readIntoRequests]] to an empty list.
  95. auto read_into_requests = move(reader->get<JS::NonnullGCPtr<ReadableStreamBYOBReader>>()->read_into_requests());
  96. // 3. For each readIntoRequest of readIntoRequests,
  97. for (auto& read_into_request : read_into_requests) {
  98. // 1. Perform readIntoRequest’s close steps, given undefined.
  99. read_into_request->on_close(JS::js_undefined());
  100. }
  101. }
  102. // 7. Let sourceCancelPromise be ! stream.[[controller]].[[CancelSteps]](reason).
  103. auto source_cancel_promise = TRY(stream.controller()->visit([&](auto const& controller) {
  104. return controller->cancel_steps(reason);
  105. }));
  106. // 8. Return the result of reacting to sourceCancelPromise with a fulfillment step that returns undefined.
  107. auto react_result = WebIDL::react_to_promise(*source_cancel_promise,
  108. [](auto const&) -> WebIDL::ExceptionOr<JS::Value> { return JS::js_undefined(); },
  109. {});
  110. return WebIDL::create_resolved_promise(realm, react_result);
  111. }
  112. // https://streams.spec.whatwg.org/#readable-stream-fulfill-read-into-request
  113. void readable_stream_fulfill_read_into_request(ReadableStream& stream, JS::Value chunk, bool done)
  114. {
  115. // 1. Assert: ! ReadableStreamHasBYOBReader(stream) is true.
  116. VERIFY(readable_stream_has_byob_reader(stream));
  117. // 2. Let reader be stream.[[reader]].
  118. auto reader = stream.reader()->get<JS::NonnullGCPtr<ReadableStreamBYOBReader>>();
  119. // 3. Assert: reader.[[readIntoRequests]] is not empty.
  120. VERIFY(!reader->read_into_requests().is_empty());
  121. // 4. Let readIntoRequest be reader.[[readIntoRequests]][0].
  122. // 5. Remove readIntoRequest from reader.[[readIntoRequests]].
  123. auto read_into_request = reader->read_into_requests().take_first();
  124. // 6. If done is true, perform readIntoRequest’s close steps, given chunk.
  125. if (done) {
  126. read_into_request->on_close(chunk);
  127. }
  128. // 7. Otherwise, perform readIntoRequest’s chunk steps, given chunk.
  129. else {
  130. read_into_request->on_chunk(chunk);
  131. }
  132. }
  133. // https://streams.spec.whatwg.org/#readable-stream-fulfill-read-request
  134. void readable_stream_fulfill_read_request(ReadableStream& stream, JS::Value chunk, bool done)
  135. {
  136. // 1. Assert: ! ReadableStreamHasDefaultReader(stream) is true.
  137. VERIFY(readable_stream_has_default_reader(stream));
  138. // 2. Let reader be stream.[[reader]].
  139. auto reader = stream.reader()->get<JS::NonnullGCPtr<ReadableStreamDefaultReader>>();
  140. // 3. Assert: reader.[[readRequests]] is not empty.
  141. VERIFY(!reader->read_requests().is_empty());
  142. // 4. Let readRequest be reader.[[readRequests]][0].
  143. // 5. Remove readRequest from reader.[[readRequests]].
  144. auto read_request = reader->read_requests().take_first();
  145. // 6. If done is true, perform readRequest’s close steps.
  146. if (done) {
  147. read_request->on_close();
  148. }
  149. // 7. Otherwise, perform readRequest’s chunk steps, given chunk.
  150. else {
  151. read_request->on_chunk(chunk);
  152. }
  153. }
  154. // https://streams.spec.whatwg.org/#readable-stream-get-num-read-into-requests
  155. size_t readable_stream_get_num_read_into_requests(ReadableStream const& stream)
  156. {
  157. // 1. Assert: ! ReadableStreamHasBYOBReader(stream) is true.
  158. VERIFY(readable_stream_has_byob_reader(stream));
  159. // 2. Return stream.[[reader]].[[readIntoRequests]]'s size.
  160. return stream.reader()->get<JS::NonnullGCPtr<ReadableStreamBYOBReader>>()->read_into_requests().size();
  161. }
  162. // https://streams.spec.whatwg.org/#readable-stream-get-num-read-requests
  163. size_t readable_stream_get_num_read_requests(ReadableStream const& stream)
  164. {
  165. // 1. Assert: ! ReadableStreamHasDefaultReader(stream) is true.
  166. VERIFY(readable_stream_has_default_reader(stream));
  167. // 2. Return stream.[[reader]].[[readRequests]]'s size.
  168. return stream.reader()->get<JS::NonnullGCPtr<ReadableStreamDefaultReader>>()->read_requests().size();
  169. }
  170. // https://streams.spec.whatwg.org/#readable-stream-has-byob-reader
  171. bool readable_stream_has_byob_reader(ReadableStream const& stream)
  172. {
  173. // 1. Let reader be stream.[[reader]].
  174. auto reader = stream.reader();
  175. // 2. If reader is undefined, return false.
  176. if (!reader.has_value())
  177. return false;
  178. // 3. If reader implements ReadableStreamBYOBReader, return true.
  179. if (reader->has<JS::NonnullGCPtr<ReadableStreamBYOBReader>>())
  180. return true;
  181. // 4. Return false.
  182. return false;
  183. }
  184. // https://streams.spec.whatwg.org/#readable-stream-has-default-reader
  185. bool readable_stream_has_default_reader(ReadableStream const& stream)
  186. {
  187. // 1. Let reader be stream.[[reader]].
  188. auto reader = stream.reader();
  189. // 2. If reader is undefined, return false.
  190. if (!reader.has_value())
  191. return false;
  192. // 3. If reader implements ReadableStreamDefaultReader, return true.
  193. if (reader->has<JS::NonnullGCPtr<ReadableStreamDefaultReader>>())
  194. return true;
  195. // 4. Return false.
  196. return false;
  197. }
  198. // https://streams.spec.whatwg.org/#readable-stream-tee
  199. WebIDL::ExceptionOr<ReadableStreamPair> readable_stream_tee(JS::Realm& realm, ReadableStream& stream, bool clone_for_branch2)
  200. {
  201. // 1. Assert: stream implements ReadableStream.
  202. // 2. Assert: cloneForBranch2 is a boolean.
  203. // 3. If stream.[[controller]] implements ReadableByteStreamController, return ? ReadableByteStreamTee(stream).
  204. if (stream.controller()->has<JS::NonnullGCPtr<Streams::ReadableByteStreamController>>()) {
  205. return TRY(readable_byte_stream_tee(realm, stream));
  206. }
  207. // 4. Return ? ReadableStreamDefaultTee(stream, cloneForBranch2).
  208. return TRY(readable_stream_default_tee(realm, stream, clone_for_branch2));
  209. }
  210. struct DefaultStreamTeeParams final : JS::Cell {
  211. JS_CELL(TeeParams, JS::Cell);
  212. JS_DECLARE_ALLOCATOR(DefaultStreamTeeParams);
  213. virtual void visit_edges(Visitor& visitor) override
  214. {
  215. Base::visit_edges(visitor);
  216. visitor.visit(reason1);
  217. visitor.visit(reason2);
  218. visitor.visit(branch1);
  219. visitor.visit(branch2);
  220. visitor.visit(pull_algorithm);
  221. }
  222. bool reading { false };
  223. bool read_again { false };
  224. bool canceled1 { false };
  225. bool canceled2 { false };
  226. JS::Value reason1 { JS::js_undefined() };
  227. JS::Value reason2 { JS::js_undefined() };
  228. JS::GCPtr<ReadableStream> branch1;
  229. JS::GCPtr<ReadableStream> branch2;
  230. JS::GCPtr<PullAlgorithm> pull_algorithm;
  231. };
  232. JS_DEFINE_ALLOCATOR(DefaultStreamTeeParams);
  233. // https://streams.spec.whatwg.org/#ref-for-read-request③
  234. class DefaultStreamTeeReadRequest final : public ReadRequest {
  235. JS_CELL(DefaultStreamTeeReadRequest, Cell);
  236. JS_DECLARE_ALLOCATOR(DefaultStreamTeeReadRequest);
  237. public:
  238. DefaultStreamTeeReadRequest(
  239. JS::Realm& realm,
  240. JS::NonnullGCPtr<ReadableStream> stream,
  241. JS::NonnullGCPtr<DefaultStreamTeeParams> params,
  242. JS::NonnullGCPtr<WebIDL::Promise> cancel_promise,
  243. bool clone_for_branch2)
  244. : m_realm(realm)
  245. , m_stream(stream)
  246. , m_params(params)
  247. , m_cancel_promise(cancel_promise)
  248. , m_clone_for_branch2(clone_for_branch2)
  249. {
  250. }
  251. // https://streams.spec.whatwg.org/#ref-for-read-request-chunk-steps③
  252. virtual void on_chunk(JS::Value chunk) override
  253. {
  254. // 1. Queue a microtask to perform the following steps:
  255. HTML::queue_a_microtask(nullptr, [this, chunk]() {
  256. HTML::TemporaryExecutionContext execution_context { Bindings::host_defined_environment_settings_object(m_realm) };
  257. auto controller1 = m_params->branch1->controller()->get<JS::NonnullGCPtr<ReadableStreamDefaultController>>();
  258. auto controller2 = m_params->branch2->controller()->get<JS::NonnullGCPtr<ReadableStreamDefaultController>>();
  259. // 1. Set readAgain to false.
  260. m_params->read_again = false;
  261. // 2. Let chunk1 and chunk2 be chunk.
  262. auto chunk1 = chunk;
  263. auto chunk2 = chunk;
  264. // 3. If canceled2 is false and cloneForBranch2 is true,
  265. if (!m_params->canceled2 && m_clone_for_branch2) {
  266. // 1. Let cloneResult be StructuredClone(chunk2).
  267. auto clone_result = structured_clone(m_realm, chunk2);
  268. // 2. If cloneResult is an abrupt completion,
  269. if (clone_result.is_exception()) {
  270. auto completion = Bindings::dom_exception_to_throw_completion(m_realm->vm(), clone_result.release_error());
  271. // 1. Perform ! ReadableStreamDefaultControllerError(branch1.[[controller]], cloneResult.[[Value]]).
  272. readable_stream_default_controller_error(controller1, completion.value().value());
  273. // 2. Perform ! ReadableStreamDefaultControllerError(branch2.[[controller]], cloneResult.[[Value]]).
  274. readable_stream_default_controller_error(controller2, completion.value().value());
  275. // 3. Resolve cancelPromise with ! ReadableStreamCancel(stream, cloneResult.[[Value]]).
  276. auto cancel_result = MUST(readable_stream_cancel(m_stream, completion.value().value()));
  277. JS::NonnullGCPtr cancel_value = verify_cast<JS::Promise>(*cancel_result->promise().ptr());
  278. WebIDL::resolve_promise(m_realm, m_cancel_promise, cancel_value);
  279. // 4. Return.
  280. return;
  281. }
  282. // 3. Otherwise, set chunk2 to cloneResult.[[Value]].
  283. chunk2 = clone_result.release_value();
  284. }
  285. // 4. If canceled1 is false, perform ! ReadableStreamDefaultControllerEnqueue(branch1.[[controller]], chunk1).
  286. if (!m_params->canceled1) {
  287. MUST(readable_stream_default_controller_enqueue(controller1, chunk1));
  288. }
  289. // 5. If canceled2 is false, perform ! ReadableStreamDefaultControllerEnqueue(branch2.[[controller]], chunk2).
  290. if (!m_params->canceled2) {
  291. MUST(readable_stream_default_controller_enqueue(controller2, chunk2));
  292. }
  293. // 6. Set reading to false.
  294. m_params->reading = false;
  295. // 7. If readAgain is true, perform pullAlgorithm.
  296. if (m_params->read_again) {
  297. MUST(m_params->pull_algorithm->function()());
  298. }
  299. });
  300. // NOTE: The microtask delay here is necessary because it takes at least a microtask to detect errors, when we
  301. // use reader.[[closedPromise]] below. We want errors in stream to error both branches immediately, so we
  302. // cannot let successful synchronously-available reads happen ahead of asynchronously-available errors.
  303. }
  304. // https://streams.spec.whatwg.org/#ref-for-read-request-close-steps②
  305. virtual void on_close() override
  306. {
  307. auto controller1 = m_params->branch1->controller()->get<JS::NonnullGCPtr<ReadableStreamDefaultController>>();
  308. auto controller2 = m_params->branch2->controller()->get<JS::NonnullGCPtr<ReadableStreamDefaultController>>();
  309. // 1. Set reading to false.
  310. m_params->reading = false;
  311. // 2. If canceled1 is false, perform ! ReadableStreamDefaultControllerClose(branch1.[[controller]]).
  312. if (!m_params->canceled1) {
  313. readable_stream_default_controller_close(controller1);
  314. }
  315. // 3. If canceled2 is false, perform ! ReadableStreamDefaultControllerClose(branch2.[[controller]]).
  316. if (!m_params->canceled2) {
  317. readable_stream_default_controller_close(controller2);
  318. }
  319. // 4. If canceled1 is false or canceled2 is false, resolve cancelPromise with undefined.
  320. if (!m_params->canceled1 || !m_params->canceled2) {
  321. WebIDL::resolve_promise(m_realm, m_cancel_promise, JS::js_undefined());
  322. }
  323. }
  324. // https://streams.spec.whatwg.org/#ref-for-read-request-error-steps③
  325. virtual void on_error(JS::Value) override
  326. {
  327. // 1. Set reading to false.
  328. m_params->reading = false;
  329. }
  330. private:
  331. virtual void visit_edges(Visitor& visitor) override
  332. {
  333. Base::visit_edges(visitor);
  334. visitor.visit(m_realm);
  335. visitor.visit(m_stream);
  336. visitor.visit(m_params);
  337. visitor.visit(m_cancel_promise);
  338. }
  339. JS::NonnullGCPtr<JS::Realm> m_realm;
  340. JS::NonnullGCPtr<ReadableStream> m_stream;
  341. JS::NonnullGCPtr<DefaultStreamTeeParams> m_params;
  342. JS::NonnullGCPtr<WebIDL::Promise> m_cancel_promise;
  343. bool m_clone_for_branch2 { false };
  344. };
  345. JS_DEFINE_ALLOCATOR(DefaultStreamTeeReadRequest);
  346. // https://streams.spec.whatwg.org/#abstract-opdef-readablestreamdefaulttee
  347. WebIDL::ExceptionOr<ReadableStreamPair> readable_stream_default_tee(JS::Realm& realm, ReadableStream& stream, bool clone_for_branch2)
  348. {
  349. // 1. Assert: stream implements ReadableStream.
  350. // 2. Assert: cloneForBranch2 is a boolean.
  351. // 3. Let reader be ? AcquireReadableStreamDefaultReader(stream).
  352. auto reader = TRY(acquire_readable_stream_default_reader(stream));
  353. // 4. Let reading be false.
  354. // 5. Let readAgain be false.
  355. // 6. Let canceled1 be false.
  356. // 7. Let canceled2 be false.
  357. // 8. Let reason1 be undefined.
  358. // 9. Let reason2 be undefined.
  359. // 10. Let branch1 be undefined.
  360. // 11. Let branch2 be undefined.
  361. auto params = realm.heap().allocate<DefaultStreamTeeParams>(realm);
  362. // 12. Let cancelPromise be a new promise.
  363. auto cancel_promise = WebIDL::create_promise(realm);
  364. // 13. Let pullAlgorithm be the following steps:
  365. auto pull_algorithm = JS::create_heap_function(realm.heap(), [&realm, &stream, reader, params, cancel_promise, clone_for_branch2]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  366. // 1. If reading is true,
  367. if (params->reading) {
  368. // 1. Set readAgain to true.
  369. params->read_again = true;
  370. // 2. Return a promise resolved with undefined.
  371. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  372. }
  373. // 2. Set reading to true.
  374. params->reading = true;
  375. // 3. Let readRequest be a read request with the following items:
  376. auto read_request = realm.heap().allocate_without_realm<DefaultStreamTeeReadRequest>(realm, stream, params, cancel_promise, clone_for_branch2);
  377. // 4. Perform ! ReadableStreamDefaultReaderRead(reader, readRequest).
  378. MUST(readable_stream_default_reader_read(reader, read_request));
  379. // 5. Return a promise resolved with undefined.
  380. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  381. });
  382. // AD-HOC: The read request within the pull algorithm must be able to re-invoke the pull algorithm, so cache it here.
  383. params->pull_algorithm = pull_algorithm;
  384. // 14. Let cancel1Algorithm be the following steps, taking a reason argument:
  385. auto cancel1_algorithm = JS::create_heap_function(realm.heap(), [&realm, &stream, params, cancel_promise](JS::Value reason) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  386. // 1. Set canceled1 to true.
  387. params->canceled1 = true;
  388. // 2. Set reason1 to reason.
  389. params->reason1 = reason;
  390. // 3. If canceled2 is true,
  391. if (params->canceled2) {
  392. // 1. Let compositeReason be ! CreateArrayFromList(« reason1, reason2 »).
  393. auto composite_reason = JS::Array::create_from(realm, AK::Array { params->reason1, params->reason2 });
  394. // 2. Let cancelResult be ! ReadableStreamCancel(stream, compositeReason).
  395. auto cancel_result = MUST(readable_stream_cancel(stream, composite_reason));
  396. // 3. Resolve cancelPromise with cancelResult.
  397. JS::NonnullGCPtr cancel_value = verify_cast<JS::Promise>(*cancel_result->promise().ptr());
  398. WebIDL::resolve_promise(realm, cancel_promise, cancel_value);
  399. }
  400. // 4. Return cancelPromise.
  401. return cancel_promise;
  402. });
  403. // 15. Let cancel2Algorithm be the following steps, taking a reason argument:
  404. auto cancel2_algorithm = JS::create_heap_function(realm.heap(), [&realm, &stream, params, cancel_promise](JS::Value reason) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  405. // 1. Set canceled2 to true.
  406. params->canceled2 = true;
  407. // 2. Set reason2 to reason.
  408. params->reason2 = reason;
  409. // 3. If canceled1 is true,
  410. if (params->canceled1) {
  411. // 1. Let compositeReason be ! CreateArrayFromList(« reason1, reason2 »).
  412. auto composite_reason = JS::Array::create_from(realm, AK::Array { params->reason1, params->reason2 });
  413. // 2. Let cancelResult be ! ReadableStreamCancel(stream, compositeReason).
  414. auto cancel_result = MUST(readable_stream_cancel(stream, composite_reason));
  415. // 3. Resolve cancelPromise with cancelResult.
  416. JS::NonnullGCPtr cancel_value = verify_cast<JS::Promise>(*cancel_result->promise().ptr());
  417. WebIDL::resolve_promise(realm, cancel_promise, cancel_value);
  418. }
  419. // 4. Return cancelPromise.
  420. return cancel_promise;
  421. });
  422. // 16. Let startAlgorithm be an algorithm that returns undefined.
  423. auto start_algorithm = JS::create_heap_function(realm.heap(), []() -> WebIDL::ExceptionOr<JS::Value> {
  424. return JS::js_undefined();
  425. });
  426. // 17. Set branch1 to ! CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm).
  427. params->branch1 = MUST(create_readable_stream(realm, start_algorithm, pull_algorithm, cancel1_algorithm));
  428. // 18. Set branch2 to ! CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm).
  429. params->branch2 = MUST(create_readable_stream(realm, start_algorithm, pull_algorithm, cancel2_algorithm));
  430. // 19. Upon rejection of reader.[[closedPromise]] with reason r,
  431. WebIDL::upon_rejection(*reader->closed_promise_capability(), [&realm, params, cancel_promise](auto reason) -> WebIDL::ExceptionOr<JS::Value> {
  432. auto controller1 = params->branch1->controller()->get<JS::NonnullGCPtr<ReadableStreamDefaultController>>();
  433. auto controller2 = params->branch2->controller()->get<JS::NonnullGCPtr<ReadableStreamDefaultController>>();
  434. // 1. Perform ! ReadableStreamDefaultControllerError(branch1.[[controller]], r).
  435. readable_stream_default_controller_error(controller1, reason);
  436. // 2. Perform ! ReadableStreamDefaultControllerError(branch2.[[controller]], r).
  437. readable_stream_default_controller_error(controller2, reason);
  438. // 3. If canceled1 is false or canceled2 is false, resolve cancelPromise with undefined.
  439. if (!params->canceled1 || !params->canceled2) {
  440. WebIDL::resolve_promise(realm, cancel_promise, JS::js_undefined());
  441. }
  442. return JS::js_undefined();
  443. });
  444. // 20. Return « branch1, branch2 ».
  445. return ReadableStreamPair { *params->branch1, *params->branch2 };
  446. }
  447. struct ByteStreamTeeParams final : JS::Cell {
  448. JS_CELL(TeeParams, JS::Cell);
  449. JS_DECLARE_ALLOCATOR(ByteStreamTeeParams);
  450. explicit ByteStreamTeeParams(ReadableStreamReader reader)
  451. : reader(move(reader))
  452. {
  453. }
  454. virtual void visit_edges(Visitor& visitor) override
  455. {
  456. Base::visit_edges(visitor);
  457. visitor.visit(reason1);
  458. visitor.visit(reason2);
  459. visitor.visit(branch1);
  460. visitor.visit(branch2);
  461. visitor.visit(pull1_algorithm);
  462. visitor.visit(pull2_algorithm);
  463. reader.visit([&](auto const& underlying_reader) { visitor.visit(underlying_reader); });
  464. }
  465. bool reading { false };
  466. bool read_again_for_branch1 { false };
  467. bool read_again_for_branch2 { false };
  468. bool canceled1 { false };
  469. bool canceled2 { false };
  470. JS::Value reason1 { JS::js_undefined() };
  471. JS::Value reason2 { JS::js_undefined() };
  472. JS::GCPtr<ReadableStream> branch1;
  473. JS::GCPtr<ReadableStream> branch2;
  474. JS::GCPtr<PullAlgorithm> pull1_algorithm;
  475. JS::GCPtr<PullAlgorithm> pull2_algorithm;
  476. ReadableStreamReader reader;
  477. };
  478. JS_DEFINE_ALLOCATOR(ByteStreamTeeParams);
  479. // https://streams.spec.whatwg.org/#ref-for-read-request④
  480. class ByteStreamTeeDefaultReadRequest final : public ReadRequest {
  481. JS_CELL(ByteStreamTeeDefaultReadRequest, Cell);
  482. JS_DECLARE_ALLOCATOR(ByteStreamTeeDefaultReadRequest);
  483. public:
  484. ByteStreamTeeDefaultReadRequest(
  485. JS::Realm& realm,
  486. JS::NonnullGCPtr<ReadableStream> stream,
  487. JS::NonnullGCPtr<ByteStreamTeeParams> params,
  488. JS::NonnullGCPtr<WebIDL::Promise> cancel_promise)
  489. : m_realm(realm)
  490. , m_stream(stream)
  491. , m_params(params)
  492. , m_cancel_promise(cancel_promise)
  493. {
  494. }
  495. // https://streams.spec.whatwg.org/#ref-for-read-request-chunk-steps④
  496. virtual void on_chunk(JS::Value chunk) override
  497. {
  498. // 1. Queue a microtask to perform the following steps:
  499. HTML::queue_a_microtask(nullptr, [this, chunk]() mutable {
  500. HTML::TemporaryExecutionContext execution_context { Bindings::host_defined_environment_settings_object(m_realm) };
  501. auto controller1 = m_params->branch1->controller()->get<JS::NonnullGCPtr<ReadableByteStreamController>>();
  502. auto controller2 = m_params->branch2->controller()->get<JS::NonnullGCPtr<ReadableByteStreamController>>();
  503. // 1. Set readAgainForBranch1 to false.
  504. m_params->read_again_for_branch1 = false;
  505. // 2. Set readAgainForBranch2 to false.
  506. m_params->read_again_for_branch2 = false;
  507. // 3. Let chunk1 and chunk2 be chunk.
  508. auto chunk1 = chunk;
  509. auto chunk2 = chunk;
  510. // 4. If canceled1 is false and canceled2 is false,
  511. if (!m_params->canceled1 && !m_params->canceled2) {
  512. // 1. Let cloneResult be CloneAsUint8Array(chunk).
  513. auto chunk_view = m_realm->vm().heap().allocate<WebIDL::ArrayBufferView>(m_realm, chunk.as_object());
  514. auto clone_result = clone_as_uint8_array(m_realm, chunk_view);
  515. // 2. If cloneResult is an abrupt completion,
  516. if (clone_result.is_exception()) {
  517. auto completion = Bindings::dom_exception_to_throw_completion(m_realm->vm(), clone_result.release_error());
  518. // 1. Perform ! ReadableByteStreamControllerError(branch1.[[controller]], cloneResult.[[Value]]).
  519. readable_byte_stream_controller_error(controller1, completion.value().value());
  520. // 2. Perform ! ReadableByteStreamControllerError(branch2.[[controller]], cloneResult.[[Value]]).
  521. readable_byte_stream_controller_error(controller2, completion.value().value());
  522. // 3. Resolve cancelPromise with ! ReadableStreamCancel(stream, cloneResult.[[Value]]).
  523. auto cancel_result = MUST(readable_stream_cancel(m_stream, completion.value().value()));
  524. JS::NonnullGCPtr cancel_value = verify_cast<JS::Promise>(*cancel_result->promise().ptr());
  525. WebIDL::resolve_promise(m_realm, m_cancel_promise, cancel_value);
  526. // 4. Return.
  527. return;
  528. }
  529. // 3. Otherwise, set chunk2 to cloneResult.[[Value]].
  530. chunk2 = clone_result.release_value();
  531. }
  532. // 5. If canceled1 is false, perform ! ReadableByteStreamControllerEnqueue(branch1.[[controller]], chunk1).
  533. if (!m_params->canceled1) {
  534. MUST(readable_byte_stream_controller_enqueue(controller1, chunk1));
  535. }
  536. // 6. If canceled2 is false, perform ! ReadableByteStreamControllerEnqueue(branch2.[[controller]], chunk2).
  537. if (!m_params->canceled2) {
  538. MUST(readable_byte_stream_controller_enqueue(controller2, chunk2));
  539. }
  540. // 7. Set reading to false.
  541. m_params->reading = false;
  542. // 8. If readAgainForBranch1 is true, perform pull1Algorithm.
  543. if (m_params->read_again_for_branch1) {
  544. MUST(m_params->pull1_algorithm->function()());
  545. }
  546. // 9. Otherwise, if readAgainForBranch2 is true, perform pull2Algorithm.
  547. else if (m_params->read_again_for_branch2) {
  548. MUST(m_params->pull2_algorithm->function()());
  549. }
  550. });
  551. // NOTE: The microtask delay here is necessary because it takes at least a microtask to detect errors, when we
  552. // use reader.[[closedPromise]] below. We want errors in stream to error both branches immediately, so we
  553. // cannot let successful synchronously-available reads happen ahead of asynchronously-available errors.
  554. }
  555. // https://streams.spec.whatwg.org/#ref-for-read-request-close-steps③
  556. virtual void on_close() override
  557. {
  558. auto controller1 = m_params->branch1->controller()->get<JS::NonnullGCPtr<ReadableByteStreamController>>();
  559. auto controller2 = m_params->branch2->controller()->get<JS::NonnullGCPtr<ReadableByteStreamController>>();
  560. // 1. Set reading to false.
  561. m_params->reading = false;
  562. // 2. If canceled1 is false, perform ! ReadableByteStreamControllerClose(branch1.[[controller]]).
  563. if (!m_params->canceled1) {
  564. MUST(readable_byte_stream_controller_close(controller1));
  565. }
  566. // 3. If canceled2 is false, perform ! ReadableByteStreamControllerClose(branch2.[[controller]]).
  567. if (!m_params->canceled2) {
  568. MUST(readable_byte_stream_controller_close(controller2));
  569. }
  570. // 4. If branch1.[[controller]].[[pendingPullIntos]] is not empty, perform ! ReadableByteStreamControllerRespond(branch1.[[controller]], 0).
  571. if (!controller1->pending_pull_intos().is_empty()) {
  572. MUST(readable_byte_stream_controller_respond(controller1, 0));
  573. }
  574. // 5. If branch2.[[controller]].[[pendingPullIntos]] is not empty, perform ! ReadableByteStreamControllerRespond(branch2.[[controller]], 0).
  575. if (!controller2->pending_pull_intos().is_empty()) {
  576. MUST(readable_byte_stream_controller_respond(controller2, 0));
  577. }
  578. // 6. If canceled1 is false or canceled2 is false, resolve cancelPromise with undefined.
  579. if (!m_params->canceled1 || !m_params->canceled2) {
  580. WebIDL::resolve_promise(m_realm, m_cancel_promise, JS::js_undefined());
  581. }
  582. }
  583. // https://streams.spec.whatwg.org/#ref-for-read-request-error-steps④
  584. virtual void on_error(JS::Value) override
  585. {
  586. // 1. Set reading to false.
  587. m_params->reading = false;
  588. }
  589. private:
  590. virtual void visit_edges(Visitor& visitor) override
  591. {
  592. Base::visit_edges(visitor);
  593. visitor.visit(m_realm);
  594. visitor.visit(m_stream);
  595. visitor.visit(m_params);
  596. visitor.visit(m_cancel_promise);
  597. }
  598. JS::NonnullGCPtr<JS::Realm> m_realm;
  599. JS::NonnullGCPtr<ReadableStream> m_stream;
  600. JS::NonnullGCPtr<ByteStreamTeeParams> m_params;
  601. JS::NonnullGCPtr<WebIDL::Promise> m_cancel_promise;
  602. };
  603. JS_DEFINE_ALLOCATOR(ByteStreamTeeDefaultReadRequest);
  604. // https://streams.spec.whatwg.org/#ref-for-read-into-request②
  605. class ByteStreamTeeBYOBReadRequest final : public ReadIntoRequest {
  606. JS_CELL(ByteStreamTeeBYOBReadRequest, Cell);
  607. JS_DECLARE_ALLOCATOR(ByteStreamTeeBYOBReadRequest);
  608. public:
  609. ByteStreamTeeBYOBReadRequest(
  610. JS::Realm& realm,
  611. JS::NonnullGCPtr<ReadableStream> stream,
  612. JS::NonnullGCPtr<ByteStreamTeeParams> params,
  613. JS::NonnullGCPtr<WebIDL::Promise> cancel_promise,
  614. JS::NonnullGCPtr<ReadableStream> byob_branch,
  615. JS::NonnullGCPtr<ReadableStream> other_branch,
  616. bool for_branch2)
  617. : m_realm(realm)
  618. , m_stream(stream)
  619. , m_params(params)
  620. , m_cancel_promise(cancel_promise)
  621. , m_byob_branch(byob_branch)
  622. , m_other_branch(other_branch)
  623. , m_for_branch2(for_branch2)
  624. {
  625. }
  626. // https://streams.spec.whatwg.org/#ref-for-read-into-request-chunk-steps①
  627. virtual void on_chunk(JS::Value chunk) override
  628. {
  629. auto chunk_view = m_realm->vm().heap().allocate<WebIDL::ArrayBufferView>(m_realm, chunk.as_object());
  630. // 1. Queue a microtask to perform the following steps:
  631. HTML::queue_a_microtask(nullptr, [this, chunk = chunk_view]() {
  632. HTML::TemporaryExecutionContext execution_context { Bindings::host_defined_environment_settings_object(m_realm) };
  633. auto byob_controller = m_byob_branch->controller()->get<JS::NonnullGCPtr<ReadableByteStreamController>>();
  634. auto other_controller = m_other_branch->controller()->get<JS::NonnullGCPtr<ReadableByteStreamController>>();
  635. // 1. Set readAgainForBranch1 to false.
  636. m_params->read_again_for_branch1 = false;
  637. // 2. Set readAgainForBranch2 to false.
  638. m_params->read_again_for_branch2 = false;
  639. // 3. Let byobCanceled be canceled2 if forBranch2 is true, and canceled1 otherwise.
  640. auto byob_cancelled = m_for_branch2 ? m_params->canceled2 : m_params->canceled1;
  641. // 4. Let otherCanceled be canceled2 if forBranch2 is false, and canceled1 otherwise.
  642. auto other_cancelled = !m_for_branch2 ? m_params->canceled2 : m_params->canceled1;
  643. // 5. If otherCanceled is false,
  644. if (!other_cancelled) {
  645. // 1. Let cloneResult be CloneAsUint8Array(chunk).
  646. auto clone_result = clone_as_uint8_array(m_realm, chunk);
  647. // 2. If cloneResult is an abrupt completion,
  648. if (clone_result.is_exception()) {
  649. auto completion = Bindings::dom_exception_to_throw_completion(m_realm->vm(), clone_result.release_error());
  650. // 1. Perform ! ReadableByteStreamControllerError(byobBranch.[[controller]], cloneResult.[[Value]]).
  651. readable_byte_stream_controller_error(byob_controller, completion.value().value());
  652. // 2. Perform ! ReadableByteStreamControllerError(otherBranch.[[controller]], cloneResult.[[Value]]).
  653. readable_byte_stream_controller_error(other_controller, completion.value().value());
  654. // 3. Resolve cancelPromise with ! ReadableStreamCancel(stream, cloneResult.[[Value]]).
  655. auto cancel_result = MUST(readable_stream_cancel(m_stream, completion.value().value()));
  656. JS::NonnullGCPtr cancel_value = verify_cast<JS::Promise>(*cancel_result->promise().ptr());
  657. WebIDL::resolve_promise(m_realm, m_cancel_promise, cancel_value);
  658. // 4. Return.
  659. return;
  660. }
  661. // 3. Otherwise, let clonedChunk be cloneResult.[[Value]].
  662. auto cloned_chunk = clone_result.release_value();
  663. // 4. If byobCanceled is false, perform ! ReadableByteStreamControllerRespondWithNewView(byobBranch.[[controller]], chunk).
  664. if (!byob_cancelled) {
  665. MUST(readable_byte_stream_controller_respond_with_new_view(m_realm, byob_controller, chunk));
  666. }
  667. // 5. Perform ! ReadableByteStreamControllerEnqueue(otherBranch.[[controller]], clonedChunk).
  668. MUST(readable_byte_stream_controller_enqueue(other_controller, cloned_chunk));
  669. }
  670. // 6. Otherwise, if byobCanceled is false, perform ! ReadableByteStreamControllerRespondWithNewView(byobBranch.[[controller]], chunk).
  671. else if (!byob_cancelled) {
  672. MUST(readable_byte_stream_controller_respond_with_new_view(m_realm, byob_controller, chunk));
  673. }
  674. // 7. Set reading to false.
  675. m_params->reading = false;
  676. // 8. If readAgainForBranch1 is true, perform pull1Algorithm.
  677. if (m_params->read_again_for_branch1) {
  678. MUST(m_params->pull1_algorithm->function()());
  679. }
  680. // 9. Otherwise, if readAgainForBranch2 is true, perform pull2Algorithm.
  681. else if (m_params->read_again_for_branch2) {
  682. MUST(m_params->pull2_algorithm->function()());
  683. }
  684. });
  685. // NOTE: The microtask delay here is necessary because it takes at least a microtask to detect errors, when we
  686. // use reader.[[closedPromise]] below. We want errors in stream to error both branches immediately, so we
  687. // cannot let successful synchronously-available reads happen ahead of asynchronously-available errors.
  688. }
  689. // https://streams.spec.whatwg.org/#ref-for-read-into-request-close-steps②
  690. virtual void on_close(JS::Value chunk) override
  691. {
  692. auto byob_controller = m_byob_branch->controller()->get<JS::NonnullGCPtr<ReadableByteStreamController>>();
  693. auto other_controller = m_other_branch->controller()->get<JS::NonnullGCPtr<ReadableByteStreamController>>();
  694. // 1. Set reading to false.
  695. m_params->reading = false;
  696. // 2. Let byobCanceled be canceled2 if forBranch2 is true, and canceled1 otherwise.
  697. auto byob_cancelled = m_for_branch2 ? m_params->canceled2 : m_params->canceled1;
  698. // 3. Let otherCanceled be canceled2 if forBranch2 is false, and canceled1 otherwise.
  699. auto other_cancelled = !m_for_branch2 ? m_params->canceled2 : m_params->canceled1;
  700. // 4. If byobCanceled is false, perform ! ReadableByteStreamControllerClose(byobBranch.[[controller]]).
  701. if (!byob_cancelled) {
  702. MUST(readable_byte_stream_controller_close(byob_controller));
  703. }
  704. // 5. If otherCanceled is false, perform ! ReadableByteStreamControllerClose(otherBranch.[[controller]]).
  705. if (!other_cancelled) {
  706. MUST(readable_byte_stream_controller_close(other_controller));
  707. }
  708. // 6. If chunk is not undefined,
  709. if (!chunk.is_undefined()) {
  710. // 1. Assert: chunk.[[ByteLength]] is 0.
  711. // 2. If byobCanceled is false, perform ! ReadableByteStreamControllerRespondWithNewView(byobBranch.[[controller]], chunk).
  712. if (!byob_cancelled) {
  713. auto array_buffer_view = m_realm->vm().heap().allocate<WebIDL::ArrayBufferView>(m_realm, chunk.as_object());
  714. MUST(readable_byte_stream_controller_respond_with_new_view(m_realm, byob_controller, array_buffer_view));
  715. }
  716. // 3. If otherCanceled is false and otherBranch.[[controller]].[[pendingPullIntos]] is not empty,
  717. // perform ! ReadableByteStreamControllerRespond(otherBranch.[[controller]], 0).
  718. if (!other_cancelled && !other_controller->pending_pull_intos().is_empty()) {
  719. MUST(readable_byte_stream_controller_respond(other_controller, 0));
  720. }
  721. }
  722. // 7. If byobCanceled is false or otherCanceled is false, resolve cancelPromise with undefined.
  723. if (!byob_cancelled || !other_cancelled) {
  724. WebIDL::resolve_promise(m_realm, m_cancel_promise, JS::js_undefined());
  725. }
  726. }
  727. // https://streams.spec.whatwg.org/#ref-for-read-into-request-error-steps①
  728. virtual void on_error(JS::Value) override
  729. {
  730. // 1. Set reading to false.
  731. m_params->reading = false;
  732. }
  733. private:
  734. virtual void visit_edges(Visitor& visitor) override
  735. {
  736. Base::visit_edges(visitor);
  737. visitor.visit(m_realm);
  738. visitor.visit(m_stream);
  739. visitor.visit(m_params);
  740. visitor.visit(m_cancel_promise);
  741. visitor.visit(m_byob_branch);
  742. visitor.visit(m_other_branch);
  743. }
  744. JS::NonnullGCPtr<JS::Realm> m_realm;
  745. JS::NonnullGCPtr<ReadableStream> m_stream;
  746. JS::NonnullGCPtr<ByteStreamTeeParams> m_params;
  747. JS::NonnullGCPtr<WebIDL::Promise> m_cancel_promise;
  748. JS::NonnullGCPtr<ReadableStream> m_byob_branch;
  749. JS::NonnullGCPtr<ReadableStream> m_other_branch;
  750. bool m_for_branch2 { false };
  751. };
  752. JS_DEFINE_ALLOCATOR(ByteStreamTeeBYOBReadRequest);
  753. // https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamtee
  754. WebIDL::ExceptionOr<ReadableStreamPair> readable_byte_stream_tee(JS::Realm& realm, ReadableStream& stream)
  755. {
  756. // 1. Assert: stream implements ReadableStream.
  757. // 2. Assert: stream.[[controller]] implements ReadableByteStreamController.
  758. VERIFY(stream.controller().has_value() && stream.controller()->has<JS::NonnullGCPtr<ReadableByteStreamController>>());
  759. // 3. Let reader be ? AcquireReadableStreamDefaultReader(stream).
  760. auto reader = TRY(acquire_readable_stream_default_reader(stream));
  761. // 4. Let reading be false.
  762. // 5. Let readAgainForBranch1 be false.
  763. // 6. Let readAgainForBranch2 be false.
  764. // 7. Let canceled1 be false.
  765. // 8. Let canceled2 be false.
  766. // 9. Let reason1 be undefined.
  767. // 10. Let reason2 be undefined.
  768. // 11. Let branch1 be undefined.
  769. // 12. Let branch2 be undefined.
  770. auto params = realm.heap().allocate<ByteStreamTeeParams>(realm, reader);
  771. // 13. Let cancelPromise be a new promise.
  772. auto cancel_promise = WebIDL::create_promise(realm);
  773. // 14. Let forwardReaderError be the following steps, taking a thisReader argument:
  774. auto forward_reader_error = JS::create_heap_function(realm.heap(), [&realm, params, cancel_promise](ReadableStreamReader const& this_reader) {
  775. // 1. Upon rejection of thisReader.[[closedPromise]] with reason r,
  776. auto closed_promise = this_reader.visit([](auto const& underlying_reader) { return underlying_reader->closed_promise_capability(); });
  777. WebIDL::upon_rejection(*closed_promise, [&realm, this_reader, params, cancel_promise](auto reason) -> WebIDL::ExceptionOr<JS::Value> {
  778. auto controller1 = params->branch1->controller()->get<JS::NonnullGCPtr<ReadableByteStreamController>>();
  779. auto controller2 = params->branch2->controller()->get<JS::NonnullGCPtr<ReadableByteStreamController>>();
  780. // 1. If thisReader is not reader, return.
  781. if (this_reader != params->reader) {
  782. return JS::js_undefined();
  783. }
  784. // 2. Perform ! ReadableByteStreamControllerError(branch1.[[controller]], r).
  785. readable_byte_stream_controller_error(controller1, reason);
  786. // 3. Perform ! ReadableByteStreamControllerError(branch2.[[controller]], r).
  787. readable_byte_stream_controller_error(controller2, reason);
  788. // 4. If canceled1 is false or canceled2 is false, resolve cancelPromise with undefined.
  789. if (!params->canceled1 || !params->canceled2) {
  790. WebIDL::resolve_promise(realm, cancel_promise, JS::js_undefined());
  791. }
  792. return JS::js_undefined();
  793. });
  794. });
  795. // 15. Let pullWithDefaultReader be the following steps:
  796. auto pull_with_default_reader = JS::create_heap_function(realm.heap(), [&realm, &stream, params, cancel_promise, forward_reader_error]() mutable {
  797. // 1. If reader implements ReadableStreamBYOBReader,
  798. if (auto const* byob_reader = params->reader.get_pointer<JS::NonnullGCPtr<ReadableStreamBYOBReader>>()) {
  799. // 1. Assert: reader.[[readIntoRequests]] is empty.
  800. VERIFY((*byob_reader)->read_into_requests().is_empty());
  801. // 2. Perform ! ReadableStreamBYOBReaderRelease(reader).
  802. readable_stream_byob_reader_release(*byob_reader);
  803. // 3. Set reader to ! AcquireReadableStreamDefaultReader(stream).
  804. params->reader = MUST(acquire_readable_stream_default_reader(stream));
  805. // 4. Perform forwardReaderError, given reader.
  806. forward_reader_error->function()(params->reader);
  807. }
  808. // 2. Let readRequest be a read request with the following items:
  809. auto read_request = realm.heap().allocate_without_realm<ByteStreamTeeDefaultReadRequest>(realm, stream, params, cancel_promise);
  810. // 3. Perform ! ReadableStreamDefaultReaderRead(reader, readRequest).
  811. MUST(readable_stream_default_reader_read(params->reader.get<JS::NonnullGCPtr<ReadableStreamDefaultReader>>(), read_request));
  812. });
  813. // 16. Let pullWithBYOBReader be the following steps, given view and forBranch2:
  814. auto pull_with_byob_reader = JS::create_heap_function(realm.heap(), [&realm, &stream, params, cancel_promise, forward_reader_error](JS::NonnullGCPtr<WebIDL::ArrayBufferView> view, bool for_branch2) mutable {
  815. // 1. If reader implements ReadableStreamDefaultReader,
  816. if (auto const* default_reader = params->reader.get_pointer<JS::NonnullGCPtr<ReadableStreamDefaultReader>>()) {
  817. // 2. Assert: reader.[[readRequests]] is empty.
  818. VERIFY((*default_reader)->read_requests().is_empty());
  819. // 3. Perform ! ReadableStreamDefaultReaderRelease(reader).
  820. MUST(readable_stream_default_reader_release(*default_reader));
  821. // 4. Set reader to ! AcquireReadableStreamBYOBReader(stream).
  822. params->reader = MUST(acquire_readable_stream_byob_reader(stream));
  823. // 5. Perform forwardReaderError, given reader.
  824. forward_reader_error->function()(params->reader);
  825. };
  826. // 2. Let byobBranch be branch2 if forBranch2 is true, and branch1 otherwise.
  827. auto byob_branch = for_branch2 ? params->branch2 : params->branch1;
  828. // 3. Let otherBranch be branch2 if forBranch2 is false, and branch1 otherwise.
  829. auto other_branch = !for_branch2 ? params->branch2 : params->branch1;
  830. // 4. Let readIntoRequest be a read-into request with the following items:
  831. auto read_into_request = realm.heap().allocate_without_realm<ByteStreamTeeBYOBReadRequest>(realm, stream, params, cancel_promise, *byob_branch, *other_branch, for_branch2);
  832. // 5. Perform ! ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest).
  833. readable_stream_byob_reader_read(params->reader.get<JS::NonnullGCPtr<ReadableStreamBYOBReader>>(), view, read_into_request);
  834. });
  835. // 17. Let pull1Algorithm be the following steps:
  836. auto pull1_algorithm = JS::create_heap_function(realm.heap(), [&realm, params, pull_with_default_reader, pull_with_byob_reader]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  837. auto controller1 = params->branch1->controller()->get<JS::NonnullGCPtr<ReadableByteStreamController>>();
  838. // 1. If reading is true,
  839. if (params->reading) {
  840. // 1. Set readAgainForBranch1 to true.
  841. params->read_again_for_branch1 = true;
  842. // 2. Return a promise resolved with undefined.
  843. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  844. }
  845. // 2. Set reading to true.
  846. params->reading = true;
  847. // 3. Let byobRequest be ! ReadableByteStreamControllerGetBYOBRequest(branch1.[[controller]]).
  848. auto byob_request = readable_byte_stream_controller_get_byob_request(controller1);
  849. // 4. If byobRequest is null, perform pullWithDefaultReader.
  850. if (!byob_request) {
  851. pull_with_default_reader->function()();
  852. }
  853. // 5. Otherwise, perform pullWithBYOBReader, given byobRequest.[[view]] and false.
  854. else {
  855. pull_with_byob_reader->function()(*byob_request->view(), false);
  856. }
  857. // 6. Return a promise resolved with undefined.
  858. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  859. });
  860. // 18. Let pull2Algorithm be the following steps:
  861. auto pull2_algorithm = JS::create_heap_function(realm.heap(), [&realm, params, pull_with_default_reader, pull_with_byob_reader]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  862. auto controller2 = params->branch2->controller()->get<JS::NonnullGCPtr<ReadableByteStreamController>>();
  863. // 1. If reading is true,
  864. if (params->reading) {
  865. // 1. Set readAgainForBranch2 to true.
  866. params->read_again_for_branch2 = true;
  867. // 2. Return a promise resolved with undefined.
  868. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  869. }
  870. // 2. Set reading to true.
  871. params->reading = true;
  872. // 3. Let byobRequest be ! ReadableByteStreamControllerGetBYOBRequest(branch2.[[controller]]).
  873. auto byob_request = readable_byte_stream_controller_get_byob_request(controller2);
  874. // 4. If byobRequest is null, perform pullWithDefaultReader.
  875. if (!byob_request) {
  876. pull_with_default_reader->function()();
  877. }
  878. // 5. Otherwise, perform pullWithBYOBReader, given byobRequest.[[view]] and true.
  879. else {
  880. pull_with_byob_reader->function()(*byob_request->view(), true);
  881. }
  882. // 6. Return a promise resolved with undefined.
  883. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  884. });
  885. // AD-HOC: The read requests within the pull algorithms must be able to re-invoke the pull algorithms, so cache them here.
  886. params->pull1_algorithm = pull1_algorithm;
  887. params->pull2_algorithm = pull2_algorithm;
  888. // 19. Let cancel1Algorithm be the following steps, taking a reason argument:
  889. auto cancel1_algorithm = JS::create_heap_function(realm.heap(), [&realm, &stream, params, cancel_promise](JS::Value reason) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  890. // 1. Set canceled1 to true.
  891. params->canceled1 = true;
  892. // 2. Set reason1 to reason.
  893. params->reason1 = reason;
  894. // 3. If canceled2 is true,
  895. if (params->canceled2) {
  896. // 1. Let compositeReason be ! CreateArrayFromList(« reason1, reason2 »).
  897. auto composite_reason = JS::Array::create_from(realm, AK::Array { params->reason1, params->reason2 });
  898. // 2. Let cancelResult be ! ReadableStreamCancel(stream, compositeReason).
  899. auto cancel_result = MUST(readable_stream_cancel(stream, composite_reason));
  900. // 3. Resolve cancelPromise with cancelResult.
  901. JS::NonnullGCPtr cancel_value = verify_cast<JS::Promise>(*cancel_result->promise().ptr());
  902. WebIDL::resolve_promise(realm, cancel_promise, cancel_value);
  903. }
  904. // 4. Return cancelPromise.
  905. return cancel_promise;
  906. });
  907. // 20. Let cancel2Algorithm be the following steps, taking a reason argument:
  908. auto cancel2_algorithm = JS::create_heap_function(realm.heap(), [&realm, &stream, params, cancel_promise](JS::Value reason) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  909. // 1. Set canceled2 to true.
  910. params->canceled2 = true;
  911. // 2. Set reason2 to reason.
  912. params->reason2 = reason;
  913. // 3. If canceled1 is true,
  914. if (params->canceled1) {
  915. // 1. Let compositeReason be ! CreateArrayFromList(« reason1, reason2 »).
  916. auto composite_reason = JS::Array::create_from(realm, AK::Array { params->reason1, params->reason2 });
  917. // 2. Let cancelResult be ! ReadableStreamCancel(stream, compositeReason).
  918. auto cancel_result = MUST(readable_stream_cancel(stream, composite_reason));
  919. // 3. Resolve cancelPromise with cancelResult.
  920. JS::NonnullGCPtr cancel_value = verify_cast<JS::Promise>(*cancel_result->promise().ptr());
  921. WebIDL::resolve_promise(realm, cancel_promise, cancel_value);
  922. }
  923. // 4. Return cancelPromise.
  924. return cancel_promise;
  925. });
  926. // 21. Let startAlgorithm be an algorithm that returns undefined.
  927. auto start_algorithm = JS::create_heap_function(realm.heap(), []() -> WebIDL::ExceptionOr<JS::Value> {
  928. return JS::js_undefined();
  929. });
  930. // 22. Set branch1 to ! CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm).
  931. params->branch1 = MUST(create_readable_byte_stream(realm, start_algorithm, pull1_algorithm, cancel1_algorithm));
  932. // 23. Set branch2 to ! CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm).
  933. params->branch2 = MUST(create_readable_byte_stream(realm, start_algorithm, pull2_algorithm, cancel2_algorithm));
  934. // 24. Perform forwardReaderError, given reader.
  935. forward_reader_error->function()(reader);
  936. // 25. Return « branch1, branch2 ».
  937. return ReadableStreamPair { *params->branch1, *params->branch2 };
  938. }
  939. // https://streams.spec.whatwg.org/#make-size-algorithm-from-size-function
  940. JS::NonnullGCPtr<SizeAlgorithm> extract_size_algorithm(JS::VM& vm, QueuingStrategy const& strategy)
  941. {
  942. // 1. If strategy["size"] does not exist, return an algorithm that returns 1.
  943. if (!strategy.size)
  944. return JS::create_heap_function(vm.heap(), [](JS::Value) { return JS::normal_completion(JS::Value(1)); });
  945. // 2. Return an algorithm that performs the following steps, taking a chunk argument:
  946. return JS::create_heap_function(vm.heap(), [size = strategy.size](JS::Value chunk) {
  947. return WebIDL::invoke_callback(*size, JS::js_undefined(), chunk);
  948. });
  949. }
  950. // https://streams.spec.whatwg.org/#validate-and-normalize-high-water-mark
  951. WebIDL::ExceptionOr<double> extract_high_water_mark(QueuingStrategy const& strategy, double default_hwm)
  952. {
  953. // 1. If strategy["highWaterMark"] does not exist, return defaultHWM.
  954. if (!strategy.high_water_mark.has_value())
  955. return default_hwm;
  956. // 2. Let highWaterMark be strategy["highWaterMark"].
  957. auto high_water_mark = strategy.high_water_mark.value();
  958. // 3. If highWaterMark is NaN or highWaterMark < 0, throw a RangeError exception.
  959. if (isnan(high_water_mark) || high_water_mark < 0)
  960. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Invalid value for high water mark"sv };
  961. // 4. Return highWaterMark.
  962. return high_water_mark;
  963. }
  964. // https://streams.spec.whatwg.org/#readable-stream-close
  965. void readable_stream_close(ReadableStream& stream)
  966. {
  967. auto& realm = stream.realm();
  968. // 1. Assert: stream.[[state]] is "readable".
  969. VERIFY(stream.state() == ReadableStream::State::Readable);
  970. // 2. Set stream.[[state]] to "closed".
  971. stream.set_state(ReadableStream::State::Closed);
  972. // 3. Let reader be stream.[[reader]].
  973. auto reader = stream.reader();
  974. // 4. If reader is undefined, return.
  975. if (!reader.has_value())
  976. return;
  977. // 5. Resolve reader.[[closedPromise]] with undefined.
  978. WebIDL::resolve_promise(realm, *reader->visit([](auto& reader) {
  979. return reader->closed_promise_capability();
  980. }));
  981. // 6. If reader implements ReadableStreamDefaultReader,
  982. if (reader->has<JS::NonnullGCPtr<ReadableStreamDefaultReader>>()) {
  983. // 1. Let readRequests be reader.[[readRequests]].
  984. // 2. Set reader.[[readRequests]] to an empty list.
  985. auto read_requests = move(reader->get<JS::NonnullGCPtr<ReadableStreamDefaultReader>>()->read_requests());
  986. // 3. For each readRequest of readRequests,
  987. for (auto& read_request : read_requests) {
  988. // 1. Perform readRequest’s close steps.
  989. read_request->on_close();
  990. }
  991. }
  992. }
  993. // https://streams.spec.whatwg.org/#readable-stream-error
  994. void readable_stream_error(ReadableStream& stream, JS::Value error)
  995. {
  996. auto& realm = stream.realm();
  997. // 1. Assert: stream.[[state]] is "readable".
  998. VERIFY(stream.state() == ReadableStream::State::Readable);
  999. // 2. Set stream.[[state]] to "errored".
  1000. stream.set_state(ReadableStream::State::Errored);
  1001. // 3. Set stream.[[storedError]] to e.
  1002. stream.set_stored_error(error);
  1003. // 4. Let reader be stream.[[reader]].
  1004. auto reader = stream.reader();
  1005. // 5. If reader is undefined, return.
  1006. if (!reader.has_value())
  1007. return;
  1008. auto closed_promise_capability = reader->visit([](auto& reader) { return reader->closed_promise_capability(); });
  1009. // 6. Reject reader.[[closedPromise]] with e.
  1010. WebIDL::reject_promise(realm, *closed_promise_capability, error);
  1011. // 7. Set reader.[[closedPromise]].[[PromiseIsHandled]] to true.
  1012. WebIDL::mark_promise_as_handled(*closed_promise_capability);
  1013. // 8. If reader implements ReadableStreamDefaultReader,
  1014. if (reader->has<JS::NonnullGCPtr<ReadableStreamDefaultReader>>()) {
  1015. // 1. Perform ! ReadableStreamDefaultReaderErrorReadRequests(reader, e).
  1016. readable_stream_default_reader_error_read_requests(*reader->get<JS::NonnullGCPtr<ReadableStreamDefaultReader>>(), error);
  1017. }
  1018. // 9. Otherwise,
  1019. else {
  1020. // 1. Assert: reader implements ReadableStreamBYOBReader.
  1021. VERIFY(reader->has<JS::NonnullGCPtr<ReadableStreamBYOBReader>>());
  1022. // 2. Perform ! ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e).
  1023. readable_stream_byob_reader_error_read_into_requests(*reader->get<JS::NonnullGCPtr<ReadableStreamBYOBReader>>(), error);
  1024. }
  1025. }
  1026. // https://streams.spec.whatwg.org/#readable-stream-add-read-request
  1027. void readable_stream_add_read_request(ReadableStream& stream, JS::NonnullGCPtr<ReadRequest> read_request)
  1028. {
  1029. // 1. Assert: stream.[[reader]] implements ReadableStreamDefaultReader.
  1030. VERIFY(stream.reader().has_value() && stream.reader()->has<JS::NonnullGCPtr<ReadableStreamDefaultReader>>());
  1031. // 2. Assert: stream.[[state]] is "readable".
  1032. VERIFY(stream.state() == ReadableStream::State::Readable);
  1033. // 3. Append readRequest to stream.[[reader]].[[readRequests]].
  1034. stream.reader()->get<JS::NonnullGCPtr<ReadableStreamDefaultReader>>()->read_requests().append(read_request);
  1035. }
  1036. // https://streams.spec.whatwg.org/#readable-stream-add-read-into-request
  1037. void readable_stream_add_read_into_request(ReadableStream& stream, JS::NonnullGCPtr<ReadIntoRequest> read_into_request)
  1038. {
  1039. // 1. Assert: stream.[[reader]] implements ReadableStreamBYOBReader.
  1040. VERIFY(stream.reader().has_value() && stream.reader()->has<JS::NonnullGCPtr<ReadableStreamBYOBReader>>());
  1041. // 2. Assert: stream.[[state]] is "readable" or "closed".
  1042. VERIFY(stream.is_readable() || stream.is_closed());
  1043. // 3. Append readRequest to stream.[[reader]].[[readIntoRequests]].
  1044. stream.reader()->get<JS::NonnullGCPtr<ReadableStreamBYOBReader>>()->read_into_requests().append(read_into_request);
  1045. }
  1046. // https://streams.spec.whatwg.org/#readable-stream-reader-generic-cancel
  1047. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> readable_stream_reader_generic_cancel(ReadableStreamGenericReaderMixin& reader, JS::Value reason)
  1048. {
  1049. // 1. Let stream be reader.[[stream]]
  1050. auto stream = reader.stream();
  1051. // 2. Assert: stream is not undefined
  1052. VERIFY(stream);
  1053. // 3. Return ! ReadableStreamCancel(stream, reason)
  1054. return TRY(readable_stream_cancel(*stream, reason));
  1055. }
  1056. // https://streams.spec.whatwg.org/#readable-stream-reader-generic-initialize
  1057. void readable_stream_reader_generic_initialize(ReadableStreamReader reader, ReadableStream& stream)
  1058. {
  1059. auto& realm = stream.realm();
  1060. // 1. Set reader.[[stream]] to stream.
  1061. reader.visit([&](auto& reader) { reader->set_stream(stream); });
  1062. // 2. Set stream.[[reader]] to reader.
  1063. stream.set_reader(reader);
  1064. // 3. If stream.[[state]] is "readable",
  1065. if (stream.state() == ReadableStream::State::Readable) {
  1066. // 1. Set reader.[[closedPromise]] to a new promise.
  1067. reader.visit([&](auto& reader) { reader->set_closed_promise_capability(WebIDL::create_promise(realm)); });
  1068. }
  1069. // 4. Otherwise, if stream.[[state]] is "closed",
  1070. else if (stream.state() == ReadableStream::State::Closed) {
  1071. // 1. Set reader.[[closedPromise]] to a promise resolved with undefined.
  1072. reader.visit([&](auto& reader) {
  1073. reader->set_closed_promise_capability(WebIDL::create_resolved_promise(realm, JS::js_undefined()));
  1074. });
  1075. }
  1076. // 5. Otherwise,
  1077. else {
  1078. // 1. Assert: stream.[[state]] is "errored".
  1079. VERIFY(stream.state() == ReadableStream::State::Errored);
  1080. // 2. Set reader.[[closedPromise]] to a promise rejected with stream.[[storedError]].
  1081. // 3. Set reader.[[closedPromise]].[[PromiseIsHandled]] to true.
  1082. reader.visit([&](auto& reader) {
  1083. reader->set_closed_promise_capability(WebIDL::create_rejected_promise(realm, stream.stored_error()));
  1084. WebIDL::mark_promise_as_handled(*reader->closed_promise_capability());
  1085. });
  1086. }
  1087. }
  1088. // https://streams.spec.whatwg.org/#readable-stream-reader-generic-release
  1089. WebIDL::ExceptionOr<void> readable_stream_reader_generic_release(ReadableStreamGenericReaderMixin& reader)
  1090. {
  1091. // 1. Let stream be reader.[[stream]].
  1092. auto stream = reader.stream();
  1093. // 2. Assert: stream is not undefined.
  1094. VERIFY(stream);
  1095. // 3. Assert: stream.[[reader]] is reader.
  1096. VERIFY(stream->reader()->visit([](auto& reader) -> ReadableStreamGenericReaderMixin* { return reader.ptr(); }) == &reader);
  1097. auto& realm = stream->realm();
  1098. // 4. If stream.[[state]] is "readable", reject reader.[[closedPromise]] with a TypeError exception.
  1099. auto exception = JS::TypeError::create(realm, "Released readable stream"sv);
  1100. if (stream->is_readable()) {
  1101. WebIDL::reject_promise(realm, *reader.closed_promise_capability(), exception);
  1102. }
  1103. // 5. Otherwise, set reader.[[closedPromise]] to a promise rejected with a TypeError exception.
  1104. else {
  1105. reader.set_closed_promise_capability(WebIDL::create_rejected_promise(realm, exception));
  1106. }
  1107. // 6. Set reader.[[closedPromise]].[[PromiseIsHandled]] to true.
  1108. WebIDL::mark_promise_as_handled(*reader.closed_promise_capability());
  1109. // 7. Perform ! stream.[[controller]].[[ReleaseSteps]]().
  1110. TRY(stream->controller()->visit([](auto const& controller) { return controller->release_steps(); }));
  1111. // 8. Set stream.[[reader]] to undefined.
  1112. stream->set_reader({});
  1113. // 9. Set reader.[[stream]] to undefined.
  1114. reader.set_stream({});
  1115. return {};
  1116. }
  1117. // https://streams.spec.whatwg.org/#abstract-opdef-readablestreamdefaultreadererrorreadrequests
  1118. void readable_stream_default_reader_error_read_requests(ReadableStreamDefaultReader& reader, JS::Value error)
  1119. {
  1120. // 1. Let readRequests be reader.[[readRequests]].
  1121. auto read_requests = move(reader.read_requests());
  1122. // 2. Set reader.[[readRequests]] to a new empty list.
  1123. reader.read_requests().clear();
  1124. // 3. For each readRequest of readRequests,
  1125. for (auto& read_request : read_requests) {
  1126. // 1. Perform readRequest’s error steps, given e.
  1127. read_request->on_error(error);
  1128. }
  1129. }
  1130. // https://streams.spec.whatwg.org/#abstract-opdef-readablestreambyobreadererrorreadintorequests
  1131. void readable_stream_byob_reader_error_read_into_requests(ReadableStreamBYOBReader& reader, JS::Value error)
  1132. {
  1133. // 1. Let readIntoRequests be reader.[[readIntoRequests]].
  1134. auto read_into_requests = move(reader.read_into_requests());
  1135. // 2. Set reader.[[readIntoRequests]] to a new empty list.
  1136. reader.read_into_requests().clear();
  1137. // 3. For each readIntoRequest of readIntoRequests,
  1138. for (auto& read_into_request : read_into_requests) {
  1139. // 1. Perform readIntoRequest’s error steps, given e.
  1140. read_into_request->on_error(error);
  1141. }
  1142. }
  1143. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-fill-head-pull-into-descriptor
  1144. void readable_byte_stream_controller_fill_head_pull_into_descriptor(ReadableByteStreamController const& controller, u64 size, PullIntoDescriptor& pull_into_descriptor)
  1145. {
  1146. // 1. Assert: either controller.[[pendingPullIntos]] is empty, or controller.[[pendingPullIntos]][0] is pullIntoDescriptor.
  1147. VERIFY(controller.pending_pull_intos().is_empty() || &controller.pending_pull_intos().first() == &pull_into_descriptor);
  1148. // 2. Assert: controller.[[byobRequest]] is null.
  1149. VERIFY(!controller.raw_byob_request());
  1150. // 3. Set pullIntoDescriptor’s bytes filled to bytes filled + size.
  1151. pull_into_descriptor.bytes_filled += size;
  1152. }
  1153. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-fill-pull-into-descriptor-from-queue
  1154. bool readable_byte_stream_controller_fill_pull_into_descriptor_from_queue(ReadableByteStreamController& controller, PullIntoDescriptor& pull_into_descriptor)
  1155. {
  1156. // 1. Let elementSize be pullIntoDescriptor.[[elementSize]].
  1157. auto element_size = pull_into_descriptor.element_size;
  1158. // 2. Let currentAlignedBytes be pullIntoDescriptor’s bytes filled − (pullIntoDescriptor’s bytes filled mod elementSize).
  1159. auto current_aligned_bytes = pull_into_descriptor.bytes_filled - (pull_into_descriptor.bytes_filled % pull_into_descriptor.element_size);
  1160. // 3. Let maxBytesToCopy be min(controller.[[queueTotalSize]], pullIntoDescriptor’s byte length − pullIntoDescriptor’s bytes filled).
  1161. auto max_bytes_to_copy = min(controller.queue_total_size(), pull_into_descriptor.byte_length - pull_into_descriptor.bytes_filled);
  1162. // 4. Let maxBytesFilled be pullIntoDescriptor’s bytes filled + maxBytesToCopy.
  1163. u64 max_bytes_filled = pull_into_descriptor.bytes_filled + max_bytes_to_copy;
  1164. // 5. Let maxAlignedBytes be maxBytesFilled − (maxBytesFilled mod elementSize).
  1165. auto max_aligned_bytes = max_bytes_filled - (max_bytes_filled % element_size);
  1166. // 6. Let totalBytesToCopyRemaining be maxBytesToCopy.
  1167. auto total_bytes_to_copy_remaining = max_bytes_to_copy;
  1168. // 7. Let ready be false.
  1169. bool ready = false;
  1170. // 8. If maxAlignedBytes > currentAlignedBytes,
  1171. if (max_aligned_bytes > current_aligned_bytes) {
  1172. // 1. Set totalBytesToCopyRemaining to maxAlignedBytes − pullIntoDescriptor’s bytes filled.
  1173. total_bytes_to_copy_remaining = max_aligned_bytes - pull_into_descriptor.bytes_filled;
  1174. // 2. Set ready to true.
  1175. ready = true;
  1176. }
  1177. // 9. Let queue be controller.[[queue]].
  1178. auto& queue = controller.queue();
  1179. // 10. While totalBytesToCopyRemaining > 0,
  1180. while (total_bytes_to_copy_remaining > 0) {
  1181. // 1. Let headOfQueue be queue[0].
  1182. auto& head_of_queue = queue.first();
  1183. // 2. Let bytesToCopy be min(totalBytesToCopyRemaining, headOfQueue’s byte length).
  1184. auto bytes_to_copy = min(total_bytes_to_copy_remaining, head_of_queue.byte_length);
  1185. // 3. Let destStart be pullIntoDescriptor’s byte offset + pullIntoDescriptor’s bytes filled.
  1186. auto dest_start = pull_into_descriptor.byte_offset + pull_into_descriptor.bytes_filled;
  1187. // 4. Perform ! CopyDataBlockBytes(pullIntoDescriptor’s buffer.[[ArrayBufferData]], destStart, headOfQueue’s buffer.[[ArrayBufferData]], headOfQueue’s byte offset, bytesToCopy).
  1188. JS::copy_data_block_bytes(pull_into_descriptor.buffer->buffer(), dest_start, head_of_queue.buffer->buffer(), head_of_queue.byte_offset, bytes_to_copy);
  1189. // 5. If headOfQueue’s byte length is bytesToCopy,
  1190. if (head_of_queue.byte_length == bytes_to_copy) {
  1191. // 1. Remove queue[0].
  1192. queue.take_first();
  1193. }
  1194. // 6. Otherwise,
  1195. else {
  1196. // 1. Set headOfQueue’s byte offset to headOfQueue’s byte offset + bytesToCopy.
  1197. head_of_queue.byte_offset += bytes_to_copy;
  1198. // 2. Set headOfQueue’s byte length to headOfQueue’s byte length − bytesToCopy.
  1199. head_of_queue.byte_length -= bytes_to_copy;
  1200. }
  1201. // 7. Set controller.[[queueTotalSize]] to controller.[[queueTotalSize]] − bytesToCopy.
  1202. controller.set_queue_total_size(controller.queue_total_size() - bytes_to_copy);
  1203. // 8, Perform ! ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor).
  1204. readable_byte_stream_controller_fill_head_pull_into_descriptor(controller, bytes_to_copy, pull_into_descriptor);
  1205. // 9. Set totalBytesToCopyRemaining to totalBytesToCopyRemaining − bytesToCopy.
  1206. total_bytes_to_copy_remaining -= bytes_to_copy;
  1207. }
  1208. // 11. If ready is false,
  1209. if (!ready) {
  1210. // 1. Assert: controller.[[queueTotalSize]] is 0.
  1211. VERIFY(controller.queue_total_size() == 0);
  1212. // 2. Assert: pullIntoDescriptor’s bytes filled > 0.
  1213. VERIFY(pull_into_descriptor.bytes_filled > 0);
  1214. // 3. Assert: pullIntoDescriptor’s bytes filled < pullIntoDescriptor’s element size.
  1215. VERIFY(pull_into_descriptor.bytes_filled < pull_into_descriptor.element_size);
  1216. }
  1217. // 12. Return ready.
  1218. return ready;
  1219. }
  1220. // https://streams.spec.whatwg.org/#readable-stream-default-reader-read
  1221. WebIDL::ExceptionOr<void> readable_stream_default_reader_read(ReadableStreamDefaultReader& reader, ReadRequest& read_request)
  1222. {
  1223. // 1. Let stream be reader.[[stream]].
  1224. auto stream = reader.stream();
  1225. // 2. Assert: stream is not undefined.
  1226. VERIFY(stream);
  1227. // 3. Set stream.[[disturbed]] to true.
  1228. stream->set_disturbed(true);
  1229. // 4. If stream.[[state]] is "closed", perform readRequest’s close steps.
  1230. if (stream->is_closed()) {
  1231. read_request.on_close();
  1232. }
  1233. // 5. Otherwise, if stream.[[state]] is "errored", perform readRequest’s error steps given stream.[[storedError]].
  1234. else if (stream->is_errored()) {
  1235. read_request.on_error(stream->stored_error());
  1236. }
  1237. // 6. Otherwise,
  1238. else {
  1239. // 1. Assert: stream.[[state]] is "readable".
  1240. VERIFY(stream->is_readable());
  1241. // 2. Perform ! stream.[[controller]].[[PullSteps]](readRequest).
  1242. TRY(stream->controller()->visit([&](auto const& controller) {
  1243. return controller->pull_steps(read_request);
  1244. }));
  1245. }
  1246. return {};
  1247. }
  1248. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-convert-pull-into-descriptor
  1249. JS::Value readable_byte_stream_controller_convert_pull_into_descriptor(JS::Realm& realm, PullIntoDescriptor const& pull_into_descriptor)
  1250. {
  1251. auto& vm = realm.vm();
  1252. // 1. Let bytesFilled be pullIntoDescriptor’s bytes filled.
  1253. auto bytes_filled = pull_into_descriptor.bytes_filled;
  1254. // 2. Let elementSize be pullIntoDescriptor’s element size.
  1255. auto element_size = pull_into_descriptor.element_size;
  1256. // 3. Assert: bytesFilled ≤ pullIntoDescriptor’s byte length.
  1257. VERIFY(bytes_filled <= pull_into_descriptor.byte_length);
  1258. // 4. Assert: bytesFilled mod elementSize is 0.
  1259. VERIFY(bytes_filled % element_size == 0);
  1260. // 5. Let buffer be ! TransferArrayBuffer(pullIntoDescriptor’s buffer).
  1261. auto buffer = MUST(transfer_array_buffer(realm, pull_into_descriptor.buffer));
  1262. // 6. Return ! Construct(pullIntoDescriptor’s view constructor, « buffer, pullIntoDescriptor’s byte offset, bytesFilled ÷ elementSize »).
  1263. return MUST(JS::construct(vm, *pull_into_descriptor.view_constructor, buffer, JS::Value(pull_into_descriptor.byte_offset), JS::Value(bytes_filled / element_size)));
  1264. }
  1265. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-pull-into
  1266. void readable_byte_stream_controller_pull_into(ReadableByteStreamController& controller, WebIDL::ArrayBufferView& view, ReadIntoRequest& read_into_request)
  1267. {
  1268. auto& vm = controller.vm();
  1269. auto& realm = controller.realm();
  1270. // 1. Let stream be controller.[[stream]].
  1271. auto stream = controller.stream();
  1272. // 2. Let elementSize be 1.
  1273. size_t element_size = 1;
  1274. // 3. Let ctor be %DataView%.
  1275. JS::NativeFunction* ctor = realm.intrinsics().data_view_constructor();
  1276. // 4. If view has a [[TypedArrayName]] internal slot (i.e., it is not a DataView),
  1277. if (view.bufferable_object().has<JS::NonnullGCPtr<JS::TypedArrayBase>>()) {
  1278. auto const& typed_array = *view.bufferable_object().get<JS::NonnullGCPtr<JS::TypedArrayBase>>();
  1279. // 1. Set elementSize to the element size specified in the typed array constructors table for view.[[TypedArrayName]].
  1280. element_size = typed_array.element_size();
  1281. // 2. Set ctor to the constructor specified in the typed array constructors table for view.[[TypedArrayName]].
  1282. switch (typed_array.kind()) {
  1283. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, Type) \
  1284. case JS::TypedArrayBase::Kind::ClassName: \
  1285. ctor = realm.intrinsics().snake_name##_constructor(); \
  1286. break;
  1287. JS_ENUMERATE_TYPED_ARRAYS
  1288. #undef __JS_ENUMERATE
  1289. }
  1290. }
  1291. // 5. Let byteOffset be view.[[ByteOffset]].
  1292. auto byte_offset = view.byte_offset();
  1293. // 6. Let byteLength be view.[[ByteLength]].
  1294. auto byte_length = view.byte_length();
  1295. // 7. Let bufferResult be TransferArrayBuffer(view.[[ViewedArrayBuffer]]).
  1296. auto buffer_result = transfer_array_buffer(realm, *view.viewed_array_buffer());
  1297. // 8. If bufferResult is an abrupt completion,
  1298. if (buffer_result.is_exception()) {
  1299. // 1. Perform readIntoRequest’s error steps, given bufferResult.[[Value]].
  1300. auto throw_completion = Bindings::dom_exception_to_throw_completion(vm, buffer_result.exception());
  1301. read_into_request.on_error(*throw_completion.release_value());
  1302. // 2. Return.
  1303. return;
  1304. }
  1305. // 9. Let buffer be bufferResult.[[Value]].
  1306. auto buffer = buffer_result.value();
  1307. // 10. Let pullIntoDescriptor be a new pull-into descriptor with buffer buffer, buffer byte length buffer.[[ArrayBufferByteLength]],
  1308. // byte offset byteOffset, byte length byteLength, bytes filled 0, element size elementSize, view constructor ctor, and reader type "byob".
  1309. PullIntoDescriptor pull_into_descriptor {
  1310. .buffer = buffer,
  1311. .buffer_byte_length = buffer->byte_length(),
  1312. .byte_offset = byte_offset,
  1313. .byte_length = byte_length,
  1314. .bytes_filled = 0,
  1315. .element_size = element_size,
  1316. .view_constructor = *ctor,
  1317. .reader_type = ReaderType::Byob,
  1318. };
  1319. // 11. If controller.[[pendingPullIntos]] is not empty,
  1320. if (!controller.pending_pull_intos().is_empty()) {
  1321. // 1. Append pullIntoDescriptor to controller.[[pendingPullIntos]].
  1322. controller.pending_pull_intos().append(pull_into_descriptor);
  1323. // 2. Perform ! ReadableStreamAddReadIntoRequest(stream, readIntoRequest).
  1324. readable_stream_add_read_into_request(*stream, read_into_request);
  1325. // 3. Return.
  1326. return;
  1327. }
  1328. // 12. If stream.[[state]] is "closed",
  1329. if (stream->is_closed()) {
  1330. // 1. Let emptyView be ! Construct(ctor, « pullIntoDescriptor’s buffer, pullIntoDescriptor’s byte offset, 0 »).
  1331. auto empty_view = MUST(JS::construct(vm, *ctor, pull_into_descriptor.buffer, JS::Value(pull_into_descriptor.byte_offset), JS::Value(0)));
  1332. // 2. Perform readIntoRequest’s close steps, given emptyView.
  1333. read_into_request.on_close(empty_view);
  1334. // 3. Return.
  1335. return;
  1336. }
  1337. // 13. If controller.[[queueTotalSize]] > 0,
  1338. if (controller.queue_total_size() > 0) {
  1339. // 1. If ! ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) is true,
  1340. if (readable_byte_stream_controller_fill_pull_into_descriptor_from_queue(controller, pull_into_descriptor)) {
  1341. // 1. Let filledView be ! ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor).
  1342. auto filled_view = readable_byte_stream_controller_convert_pull_into_descriptor(realm, pull_into_descriptor);
  1343. // 2. Perform ! ReadableByteStreamControllerHandleQueueDrain(controller).
  1344. MUST(readable_byte_stream_controller_handle_queue_drain(controller));
  1345. // 3. Perform readIntoRequest’s chunk steps, given filledView.
  1346. read_into_request.on_chunk(filled_view);
  1347. // 4. Return.
  1348. return;
  1349. }
  1350. // 2. If controller.[[closeRequested]] is true,
  1351. if (controller.close_requested()) {
  1352. // 1. Let e be a TypeError exception.
  1353. auto error = JS::TypeError::create(realm, "Reader has been released"sv);
  1354. // 2. Perform ! ReadableByteStreamControllerError(controller, e).
  1355. readable_byte_stream_controller_error(controller, error);
  1356. // 3. Perform readIntoRequest’s error steps, given e.
  1357. read_into_request.on_error(error);
  1358. // 4. Return.
  1359. return;
  1360. }
  1361. }
  1362. // 14. Append pullIntoDescriptor to controller.[[pendingPullIntos]].
  1363. controller.pending_pull_intos().append(pull_into_descriptor);
  1364. // 15. Perform ! ReadableStreamAddReadIntoRequest(stream, readIntoRequest).
  1365. readable_stream_add_read_into_request(*stream, read_into_request);
  1366. // 16. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
  1367. MUST(readable_byte_stream_controller_call_pull_if_needed(controller));
  1368. }
  1369. // https://streams.spec.whatwg.org/#readable-stream-byob-reader-read
  1370. void readable_stream_byob_reader_read(ReadableStreamBYOBReader& reader, WebIDL::ArrayBufferView& view, ReadIntoRequest& read_into_request)
  1371. {
  1372. // 1. Let stream be reader.[[stream]].
  1373. auto stream = reader.stream();
  1374. // 2. Assert: stream is not undefined.
  1375. VERIFY(stream);
  1376. // 3. Set stream.[[disturbed]] to true.
  1377. stream->set_disturbed(true);
  1378. // 4. If stream.[[state]] is "errored", perform readIntoRequest’s error steps given stream.[[storedError]].
  1379. if (stream->is_errored()) {
  1380. read_into_request.on_error(stream->stored_error());
  1381. }
  1382. // 5. Otherwise, perform ! ReadableByteStreamControllerPullInto(stream.[[controller]], view, readIntoRequest).
  1383. else {
  1384. readable_byte_stream_controller_pull_into(*stream->controller()->get<JS::NonnullGCPtr<ReadableByteStreamController>>(), view, read_into_request);
  1385. }
  1386. }
  1387. // https://streams.spec.whatwg.org/#abstract-opdef-readablestreamdefaultreaderrelease
  1388. WebIDL::ExceptionOr<void> readable_stream_default_reader_release(ReadableStreamDefaultReader& reader)
  1389. {
  1390. auto& realm = reader.realm();
  1391. // 1. Perform ! ReadableStreamReaderGenericRelease(reader).
  1392. TRY(readable_stream_reader_generic_release(reader));
  1393. // 2. Let e be a new TypeError exception.
  1394. auto exception = JS::TypeError::create(realm, "Reader has been released"sv);
  1395. // 3. Perform ! ReadableStreamDefaultReaderErrorReadRequests(reader, e).
  1396. readable_stream_default_reader_error_read_requests(reader, exception);
  1397. return {};
  1398. }
  1399. // https://streams.spec.whatwg.org/#abstract-opdef-readablestreambyobreaderrelease
  1400. void readable_stream_byob_reader_release(ReadableStreamBYOBReader& reader)
  1401. {
  1402. auto& realm = reader.realm();
  1403. // 1. Perform ! ReadableStreamReaderGenericRelease(reader).
  1404. MUST(readable_stream_reader_generic_release(reader));
  1405. // 2. Let e be a new TypeError exception.
  1406. auto exception = JS::TypeError::create(realm, "Reader has been released"sv);
  1407. // 3. Perform ! ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e).
  1408. readable_stream_byob_reader_error_read_into_requests(reader, exception);
  1409. }
  1410. // https://streams.spec.whatwg.org/#set-up-readable-stream-default-reader
  1411. WebIDL::ExceptionOr<void> set_up_readable_stream_default_reader(ReadableStreamDefaultReader& reader, ReadableStream& stream)
  1412. {
  1413. // 1. If ! IsReadableStreamLocked(stream) is true, throw a TypeError exception.
  1414. if (is_readable_stream_locked(stream))
  1415. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot create stream reader for a locked stream"sv };
  1416. // 2. Perform ! ReadableStreamReaderGenericInitialize(reader, stream).
  1417. // 3. Set reader.[[readRequests]] to a new empty list.
  1418. readable_stream_reader_generic_initialize(ReadableStreamReader { reader }, stream);
  1419. return {};
  1420. }
  1421. // https://streams.spec.whatwg.org/#set-up-readable-stream-byob-reader
  1422. WebIDL::ExceptionOr<void> set_up_readable_stream_byob_reader(ReadableStreamBYOBReader& reader, ReadableStream& stream)
  1423. {
  1424. // 1. If ! IsReadableStreamLocked(stream) is true, throw a TypeError exception.
  1425. if (is_readable_stream_locked(stream))
  1426. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot create stream reader for a locked stream"sv };
  1427. // 2. If stream.[[controller]] does not implement ReadableByteStreamController, throw a TypeError exception.
  1428. if (!stream.controller()->has<JS::NonnullGCPtr<ReadableByteStreamController>>())
  1429. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "BYOB reader cannot set up reader from non-byte stream"sv };
  1430. // 3. Perform ! ReadableStreamReaderGenericInitialize(reader, stream).
  1431. readable_stream_reader_generic_initialize(ReadableStreamReader { reader }, stream);
  1432. // 4. Set reader.[[readIntoRequests]] to a new empty list.
  1433. reader.read_into_requests().clear();
  1434. return {};
  1435. }
  1436. // https://streams.spec.whatwg.org/#readable-stream-default-controller-close
  1437. void readable_stream_default_controller_close(ReadableStreamDefaultController& controller)
  1438. {
  1439. // 1. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) is false, return.
  1440. if (!readable_stream_default_controller_can_close_or_enqueue(controller))
  1441. return;
  1442. // 2. Let stream be controller.[[stream]].
  1443. auto stream = controller.stream();
  1444. // 3. Set controller.[[closeRequested]] to true.
  1445. controller.set_close_requested(true);
  1446. // 4. If controller.[[queue]] is empty,
  1447. if (controller.queue().is_empty()) {
  1448. // 1. Perform ! ReadableStreamDefaultControllerClearAlgorithms(controller).
  1449. readable_stream_default_controller_clear_algorithms(controller);
  1450. // 2. Perform ! ReadableStreamClose(stream).
  1451. readable_stream_close(*stream);
  1452. }
  1453. }
  1454. // https://streams.spec.whatwg.org/#rs-default-controller-has-backpressure
  1455. bool readable_stream_default_controller_has_backpressure(ReadableStreamDefaultController& controller)
  1456. {
  1457. // 1. If ! ReadableStreamDefaultControllerShouldCallPull(controller) is true, return false.
  1458. if (readable_stream_default_controller_should_call_pull(controller))
  1459. return false;
  1460. // 2. Otherwise, return true.
  1461. return true;
  1462. }
  1463. // https://streams.spec.whatwg.org/#readable-stream-default-controller-enqueue
  1464. WebIDL::ExceptionOr<void> readable_stream_default_controller_enqueue(ReadableStreamDefaultController& controller, JS::Value chunk)
  1465. {
  1466. auto& vm = controller.vm();
  1467. // 1. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) is false, return.
  1468. if (!readable_stream_default_controller_can_close_or_enqueue(controller))
  1469. return {};
  1470. // 2. Let stream be controller.[[stream]].
  1471. auto stream = controller.stream();
  1472. // 3. If ! IsReadableStreamLocked(stream) is true and ! ReadableStreamGetNumReadRequests(stream) > 0, perform ! ReadableStreamFulfillReadRequest(stream, chunk, false).
  1473. if (is_readable_stream_locked(*stream) && readable_stream_get_num_read_requests(*stream) > 0) {
  1474. readable_stream_fulfill_read_request(*stream, chunk, false);
  1475. }
  1476. // 4. Otherwise,
  1477. else {
  1478. // 1. Let result be the result of performing controller.[[strategySizeAlgorithm]], passing in chunk, and interpreting the result as a completion record.
  1479. auto result = controller.strategy_size_algorithm()->function()(chunk);
  1480. // 2. If result is an abrupt completion,
  1481. if (result.is_abrupt()) {
  1482. // 1. Perform ! ReadableStreamDefaultControllerError(controller, result.[[Value]]).
  1483. readable_stream_default_controller_error(controller, result.value().value());
  1484. // 2. Return result.
  1485. return result;
  1486. }
  1487. // 3. Let chunkSize be result.[[Value]].
  1488. auto chunk_size = result.release_value().release_value();
  1489. // 4. Let enqueueResult be EnqueueValueWithSize(controller, chunk, chunkSize).
  1490. auto enqueue_result = enqueue_value_with_size(controller, chunk, chunk_size);
  1491. // 5. If enqueueResult is an abrupt completion,
  1492. if (enqueue_result.is_error()) {
  1493. auto throw_completion = Bindings::throw_dom_exception_if_needed(vm, [&] { return enqueue_result; }).throw_completion();
  1494. // 1. Perform ! ReadableStreamDefaultControllerError(controller, enqueueResult.[[Value]]).
  1495. readable_stream_default_controller_error(controller, throw_completion.value().value());
  1496. // 2. Return enqueueResult.
  1497. // Note: We need to return the throw_completion object here, as enqueue needs to throw the same object that the controller is errored with
  1498. return throw_completion;
  1499. }
  1500. }
  1501. // 5. Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(controller).
  1502. return readable_stream_default_controller_can_pull_if_needed(controller);
  1503. }
  1504. // https://streams.spec.whatwg.org/#readable-stream-default-controller-call-pull-if-needed
  1505. WebIDL::ExceptionOr<void> readable_stream_default_controller_can_pull_if_needed(ReadableStreamDefaultController& controller)
  1506. {
  1507. // 1. Let shouldPull be ! ReadableStreamDefaultControllerShouldCallPull(controller).
  1508. auto should_pull = readable_stream_default_controller_should_call_pull(controller);
  1509. // 2. If shouldPull is false, return.
  1510. if (!should_pull)
  1511. return {};
  1512. // 3. If controller.[[pulling]] is true,
  1513. if (controller.pulling()) {
  1514. // 1. Set controller.[[pullAgain]] to true.
  1515. controller.set_pull_again(true);
  1516. // 2. Return.
  1517. return {};
  1518. }
  1519. // 4. Assert: controller.[[pullAgain]] is false.
  1520. VERIFY(!controller.pull_again());
  1521. // 5. Set controller.[[pulling]] to true.
  1522. controller.set_pulling(true);
  1523. // 6. Let pullPromise be the result of performing controller.[[pullAlgorithm]].
  1524. auto pull_promise = TRY(controller.pull_algorithm()->function()());
  1525. // 7. Upon fulfillment of pullPromise,
  1526. WebIDL::upon_fulfillment(*pull_promise, [&](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  1527. // 1. Set controller.[[pulling]] to false.
  1528. controller.set_pulling(false);
  1529. // 2. If controller.[[pullAgain]] is true,
  1530. if (controller.pull_again()) {
  1531. // 1. Set controller.[[pullAgain]] to false.
  1532. controller.set_pull_again(false);
  1533. // 2. Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(controller).
  1534. TRY(readable_stream_default_controller_can_pull_if_needed(controller));
  1535. }
  1536. return JS::js_undefined();
  1537. });
  1538. // 8. Upon rejection of pullPromise with reason e,
  1539. WebIDL::upon_rejection(*pull_promise, [&](auto const& e) -> WebIDL::ExceptionOr<JS::Value> {
  1540. // 1. Perform ! ReadableStreamDefaultControllerError(controller, e).
  1541. readable_stream_default_controller_error(controller, e);
  1542. return JS::js_undefined();
  1543. });
  1544. return {};
  1545. }
  1546. // https://streams.spec.whatwg.org/#readable-stream-default-controller-should-call-pull
  1547. bool readable_stream_default_controller_should_call_pull(ReadableStreamDefaultController& controller)
  1548. {
  1549. // 1. Let stream be controller.[[stream]].
  1550. auto stream = controller.stream();
  1551. // 2. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) is false, return false.
  1552. if (!readable_stream_default_controller_can_close_or_enqueue(controller))
  1553. return false;
  1554. // 3. If controller.[[started]] is false, return false.
  1555. if (!controller.started())
  1556. return false;
  1557. // 4. If ! IsReadableStreamLocked(stream) is true and ! ReadableStreamGetNumReadRequests(stream) > 0, return true.
  1558. if (is_readable_stream_locked(*stream) && readable_stream_get_num_read_requests(*stream) > 0)
  1559. return true;
  1560. // 5. Let desiredSize be ! ReadableStreamDefaultControllerGetDesiredSize(controller).
  1561. auto desired_size = readable_stream_default_controller_get_desired_size(controller);
  1562. // 6. Assert: desiredSize is not null.
  1563. VERIFY(desired_size.has_value());
  1564. // 7. If desiredSize > 0, return true.
  1565. if (desired_size.release_value() > 0.0)
  1566. return true;
  1567. // 8. Return false.
  1568. return false;
  1569. }
  1570. // https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollergetbyobrequest
  1571. JS::GCPtr<ReadableStreamBYOBRequest> readable_byte_stream_controller_get_byob_request(JS::NonnullGCPtr<ReadableByteStreamController> controller)
  1572. {
  1573. auto& vm = controller->vm();
  1574. auto& realm = controller->realm();
  1575. // 1. If controller.[[byobRequest]] is null and controller.[[pendingPullIntos]] is not empty,
  1576. if (!controller->raw_byob_request() && !controller->pending_pull_intos().is_empty()) {
  1577. // 1. Let firstDescriptor be controller.[[pendingPullIntos]][0].
  1578. auto const& first_descriptor = controller->pending_pull_intos().first();
  1579. // 2. Let view be ! Construct(%Uint8Array%, « firstDescriptor’s buffer, firstDescriptor’s byte offset + firstDescriptor’s bytes filled, firstDescriptor’s byte length − firstDescriptor’s bytes filled »).
  1580. auto view = MUST(JS::construct(vm, *realm.intrinsics().uint8_array_constructor(), first_descriptor.buffer, JS::Value(first_descriptor.byte_offset + first_descriptor.bytes_filled), JS::Value(first_descriptor.byte_length - first_descriptor.bytes_filled)));
  1581. // 3. Let byobRequest be a new ReadableStreamBYOBRequest.
  1582. auto byob_request = realm.heap().allocate<ReadableStreamBYOBRequest>(realm, realm);
  1583. // 4. Set byobRequest.[[controller]] to controller.
  1584. byob_request->set_controller(controller);
  1585. // 5. Set byobRequest.[[view]] to view.
  1586. auto array_buffer_view = vm.heap().allocate<WebIDL::ArrayBufferView>(realm, view);
  1587. byob_request->set_view(array_buffer_view);
  1588. // 6. Set controller.[[byobRequest]] to byobRequest.
  1589. controller->set_byob_request(byob_request);
  1590. }
  1591. // 2. Return controller.[[byobRequest]].
  1592. return controller->raw_byob_request();
  1593. }
  1594. // https://streams.spec.whatwg.org/#readable-stream-default-controller-clear-algorithms
  1595. void readable_stream_default_controller_clear_algorithms(ReadableStreamDefaultController& controller)
  1596. {
  1597. // 1. Set controller.[[pullAlgorithm]] to undefined.
  1598. controller.set_pull_algorithm({});
  1599. // 2. Set controller.[[cancelAlgorithm]] to undefined.
  1600. controller.set_cancel_algorithm({});
  1601. // 3. Set controller.[[strategySizeAlgorithm]] to undefined.
  1602. controller.set_strategy_size_algorithm({});
  1603. }
  1604. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-respond-in-readable-state
  1605. WebIDL::ExceptionOr<void> readable_byte_stream_controller_respond_in_readable_state(ReadableByteStreamController& controller, u64 bytes_written, PullIntoDescriptor& pull_into_descriptor)
  1606. {
  1607. // 1. Assert: pullIntoDescriptor’s bytes filled + bytesWritten ≤ pullIntoDescriptor’s byte length.
  1608. VERIFY(pull_into_descriptor.bytes_filled + bytes_written <= pull_into_descriptor.byte_length);
  1609. // 2. Perform ! ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor).
  1610. readable_byte_stream_controller_fill_head_pull_into_descriptor(controller, bytes_written, pull_into_descriptor);
  1611. // 3. If pullIntoDescriptor’s reader type is "none",
  1612. if (pull_into_descriptor.reader_type == ReaderType::None) {
  1613. // 1. Perform ? ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor).
  1614. TRY(readable_byte_stream_controller_enqueue_detached_pull_into_queue(controller, pull_into_descriptor));
  1615. // 2. Perform ! ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller).
  1616. readable_byte_stream_controller_process_pull_into_descriptors_using_queue(controller);
  1617. // 3. Return.
  1618. return {};
  1619. }
  1620. // 4. If pullIntoDescriptor’s bytes filled < pullIntoDescriptor’s minimum fill, return.
  1621. // FIXME: Support minimum fill.
  1622. if (pull_into_descriptor.bytes_filled < pull_into_descriptor.element_size)
  1623. return {};
  1624. // NOTE: A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head of the queue, so the underlying source can keep filling it.
  1625. // 5. Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).
  1626. // NOTE: We need to take a copy of pull_into_descriptor here as the shift destroys the pull into descriptor we are given.
  1627. auto pull_into_descriptor_copy = readable_byte_stream_controller_shift_pending_pull_into(controller);
  1628. // 6. Let remainderSize be the remainder after dividing pullIntoDescriptor’s bytes filled by pullIntoDescriptor’s element size.
  1629. auto remainder_size = pull_into_descriptor_copy.bytes_filled % pull_into_descriptor_copy.element_size;
  1630. // 7. If remainderSize > 0,
  1631. if (remainder_size > 0) {
  1632. // 1. Let end be pullIntoDescriptor’s byte offset + pullIntoDescriptor’s bytes filled.
  1633. auto end = pull_into_descriptor_copy.byte_offset + pull_into_descriptor_copy.bytes_filled;
  1634. // 2. Perform ? ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor’s buffer, end − remainderSize, remainderSize).
  1635. TRY(readable_byte_stream_controller_enqueue_cloned_chunk_to_queue(controller, *pull_into_descriptor_copy.buffer, end - remainder_size, remainder_size));
  1636. }
  1637. // 8. Set pullIntoDescriptor’s bytes filled to pullIntoDescriptor’s bytes filled − remainderSize.
  1638. pull_into_descriptor_copy.bytes_filled -= remainder_size;
  1639. // 9. Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(controller.[[stream]], pullIntoDescriptor).
  1640. readable_byte_stream_controller_commit_pull_into_descriptor(*controller.stream(), pull_into_descriptor_copy);
  1641. return {};
  1642. }
  1643. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-respond-in-closed-state
  1644. void readable_byte_stream_controller_respond_in_closed_state(ReadableByteStreamController& controller, PullIntoDescriptor& first_descriptor)
  1645. {
  1646. // 1. Assert: the remainder after dividing firstDescriptor’s bytes filled by firstDescriptor’s element size is 0.
  1647. VERIFY(first_descriptor.bytes_filled % first_descriptor.element_size == 0);
  1648. // 2. If firstDescriptor’s reader type is "none", perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).
  1649. if (first_descriptor.reader_type == ReaderType::None)
  1650. readable_byte_stream_controller_shift_pending_pull_into(controller);
  1651. // 3. Let stream be controller.[[stream]].
  1652. auto& stream = *controller.stream();
  1653. // 4. If ! ReadableStreamHasBYOBReader(stream) is true,
  1654. if (readable_stream_has_byob_reader(stream)) {
  1655. // 1. While ! ReadableStreamGetNumReadIntoRequests(stream) > 0,
  1656. while (readable_stream_get_num_read_into_requests(stream) > 0) {
  1657. // 1. Let pullIntoDescriptor be ! ReadableByteStreamControllerShiftPendingPullInto(controller).
  1658. auto pull_into_descriptor = readable_byte_stream_controller_shift_pending_pull_into(controller);
  1659. // 2. Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor).
  1660. readable_byte_stream_controller_commit_pull_into_descriptor(stream, pull_into_descriptor);
  1661. }
  1662. }
  1663. }
  1664. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-respond-internal
  1665. WebIDL::ExceptionOr<void> readable_byte_stream_controller_respond_internal(ReadableByteStreamController& controller, u64 bytes_written)
  1666. {
  1667. // 1. Let firstDescriptor be controller.[[pendingPullIntos]][0].
  1668. auto& first_descriptor = controller.pending_pull_intos().first();
  1669. // 2. Assert: ! CanTransferArrayBuffer(firstDescriptor’s buffer) is true.
  1670. VERIFY(can_transfer_array_buffer(*first_descriptor.buffer));
  1671. // 3. Perform ! ReadableByteStreamControllerInvalidateBYOBRequest(controller).
  1672. readable_byte_stream_controller_invalidate_byob_request(controller);
  1673. // 4. Let state be controller.[[stream]].[[state]].
  1674. auto state = controller.stream()->state();
  1675. // 5. If state is "closed",
  1676. if (state == ReadableStream::State::Closed) {
  1677. // 1. Assert: bytesWritten is 0.
  1678. VERIFY(bytes_written == 0);
  1679. // 2. Perform ! ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor).
  1680. readable_byte_stream_controller_respond_in_closed_state(controller, first_descriptor);
  1681. }
  1682. // 6. Otherwise,
  1683. else {
  1684. // 1. Assert: state is "readable".
  1685. VERIFY(state == ReadableStream::State::Readable);
  1686. // 2. Assert: bytesWritten > 0.
  1687. VERIFY(bytes_written > 0);
  1688. // 3. Perform ? ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor).
  1689. TRY(readable_byte_stream_controller_respond_in_readable_state(controller, bytes_written, first_descriptor));
  1690. }
  1691. // 7. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
  1692. MUST(readable_byte_stream_controller_call_pull_if_needed(controller));
  1693. return {};
  1694. }
  1695. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-respond
  1696. WebIDL::ExceptionOr<void> readable_byte_stream_controller_respond(ReadableByteStreamController& controller, u64 bytes_written)
  1697. {
  1698. auto& realm = controller.realm();
  1699. // 1. Assert: controller.[[pendingPullIntos]] is not empty.
  1700. VERIFY(!controller.pending_pull_intos().is_empty());
  1701. // 2. Let firstDescriptor be controller.[[pendingPullIntos]][0].
  1702. auto& first_descriptor = controller.pending_pull_intos().first();
  1703. // 3. Let state be controller.[[stream]].[[state]].
  1704. auto state = controller.stream()->state();
  1705. // 4. If state is "closed",
  1706. if (state == ReadableStream::State::Closed) {
  1707. // 1. If bytesWritten is not 0, throw a TypeError exception.
  1708. if (bytes_written != 0)
  1709. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Bytes written is not zero for closed stream"sv };
  1710. }
  1711. // 5. Otherwise,
  1712. else {
  1713. // 1. Assert: state is "readable".
  1714. VERIFY(state == ReadableStream::State::Readable);
  1715. // 2. If bytesWritten is 0, throw a TypeError exception.
  1716. if (bytes_written == 0)
  1717. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Bytes written is zero for stream which is not closed"sv };
  1718. // 3. If firstDescriptor’s bytes filled + bytesWritten > firstDescriptor’s byte length, throw a RangeError exception.
  1719. if (first_descriptor.bytes_filled + bytes_written > first_descriptor.byte_length)
  1720. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Bytes written is greater than the pull requests byte length"sv };
  1721. }
  1722. // 6. Set firstDescriptor’s buffer to ! TransferArrayBuffer(firstDescriptor’s buffer).
  1723. first_descriptor.buffer = MUST(transfer_array_buffer(realm, *first_descriptor.buffer));
  1724. // 7. Perform ? ReadableByteStreamControllerRespondInternal(controller, bytesWritten).
  1725. return readable_byte_stream_controller_respond_internal(controller, bytes_written);
  1726. }
  1727. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-respond-with-new-view
  1728. WebIDL::ExceptionOr<void> readable_byte_stream_controller_respond_with_new_view(JS::Realm& realm, ReadableByteStreamController& controller, WebIDL::ArrayBufferView& view)
  1729. {
  1730. // 1. Assert: controller.[[pendingPullIntos]] is not empty.
  1731. VERIFY(!controller.pending_pull_intos().is_empty());
  1732. // 2. Assert: ! IsDetachedBuffer(view.[[ViewedArrayBuffer]]) is false.
  1733. VERIFY(!view.viewed_array_buffer()->is_detached());
  1734. // 3. Let firstDescriptor be controller.[[pendingPullIntos]][0].
  1735. auto& first_descriptor = controller.pending_pull_intos().first();
  1736. // 4. Let state be controller.[[stream]].[[state]].
  1737. auto state = controller.stream()->state();
  1738. // 5. If state is "closed",
  1739. if (state == ReadableStream::State::Closed) {
  1740. // 1. If view.[[ByteLength]] is not 0, throw a TypeError exception.
  1741. if (view.byte_length() != 0)
  1742. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Byte length is not zero for closed stream"sv };
  1743. }
  1744. // 6. Otherwise,
  1745. else {
  1746. // 1. Assert: state is "readable".
  1747. VERIFY(state == ReadableStream::State::Readable);
  1748. // 2. If view.[[ByteLength]] is 0, throw a TypeError exception.
  1749. if (view.byte_length() == 0)
  1750. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Byte length is zero for stream which is not closed"sv };
  1751. }
  1752. // 7. If firstDescriptor’s byte offset + firstDescriptor’ bytes filled is not view.[[ByteOffset]], throw a RangeError exception.
  1753. if (first_descriptor.byte_offset + first_descriptor.bytes_filled != view.byte_offset())
  1754. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Byte offset is not aligned with the pull request's byte offset"sv };
  1755. // 8. If firstDescriptor’s buffer byte length is not view.[[ViewedArrayBuffer]].[[ByteLength]], throw a RangeError exception.
  1756. if (first_descriptor.buffer_byte_length != view.viewed_array_buffer()->byte_length())
  1757. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Buffer byte length is not aligned with the pull request's byte length"sv };
  1758. // 9. If firstDescriptor’s bytes filled + view.[[ByteLength]] > firstDescriptor’s byte length, throw a RangeError exception.
  1759. if (first_descriptor.bytes_filled + view.byte_length() > first_descriptor.byte_length)
  1760. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Byte length is greater than the pull request's byte length"sv };
  1761. // 10. Let viewByteLength be view.[[ByteLength]].
  1762. auto view_byte_length = view.byte_length();
  1763. // 11. Set firstDescriptor’s buffer to ? TransferArrayBuffer(view.[[ViewedArrayBuffer]]).
  1764. first_descriptor.buffer = TRY(transfer_array_buffer(realm, *view.viewed_array_buffer()));
  1765. // 12. Perform ? ReadableByteStreamControllerRespondInternal(controller, viewByteLength).
  1766. TRY(readable_byte_stream_controller_respond_internal(controller, view_byte_length));
  1767. return {};
  1768. }
  1769. // https://streams.spec.whatwg.org/#readable-stream-default-controller-error
  1770. void readable_stream_default_controller_error(ReadableStreamDefaultController& controller, JS::Value error)
  1771. {
  1772. // 1. Let stream be controller.[[stream]].
  1773. auto stream = controller.stream();
  1774. // 2. If stream.[[state]] is not "readable", return.
  1775. if (!stream->is_readable())
  1776. return;
  1777. // 3. Perform ! ResetQueue(controller).
  1778. reset_queue(controller);
  1779. // 4. Perform ! ReadableStreamDefaultControllerClearAlgorithms(controller).
  1780. readable_stream_default_controller_clear_algorithms(controller);
  1781. // 5. Perform ! ReadableStreamError(stream, e).
  1782. readable_stream_error(*stream, error);
  1783. }
  1784. // https://streams.spec.whatwg.org/#readable-stream-default-controller-get-desired-size
  1785. Optional<double> readable_stream_default_controller_get_desired_size(ReadableStreamDefaultController& controller)
  1786. {
  1787. auto stream = controller.stream();
  1788. // 1. Let state be controller.[[stream]].[[state]].
  1789. // 2. If state is "errored", return null.
  1790. if (stream->is_errored())
  1791. return {};
  1792. // 3. If state is "closed", return 0.
  1793. if (stream->is_closed())
  1794. return 0.0;
  1795. // 4. Return controller.[[strategyHWM]] − controller.[[queueTotalSize]].
  1796. return controller.strategy_hwm() - controller.queue_total_size();
  1797. }
  1798. // https://streams.spec.whatwg.org/#readable-stream-default-controller-can-close-or-enqueue
  1799. bool readable_stream_default_controller_can_close_or_enqueue(ReadableStreamDefaultController& controller)
  1800. {
  1801. // 1. Let state be controller.[[stream]].[[state]].
  1802. // 2. If controller.[[closeRequested]] is false and state is "readable", return true.
  1803. // 3. Otherwise, return false.
  1804. return !controller.close_requested() && controller.stream()->is_readable();
  1805. }
  1806. // https://streams.spec.whatwg.org/#set-up-readable-stream-default-controller
  1807. WebIDL::ExceptionOr<void> set_up_readable_stream_default_controller(ReadableStream& stream, ReadableStreamDefaultController& controller, JS::NonnullGCPtr<StartAlgorithm> start_algorithm, JS::NonnullGCPtr<PullAlgorithm> pull_algorithm, JS::NonnullGCPtr<CancelAlgorithm> cancel_algorithm, double high_water_mark, JS::NonnullGCPtr<SizeAlgorithm> size_algorithm)
  1808. {
  1809. auto& realm = stream.realm();
  1810. // 1. Assert: stream.[[controller]] is undefined.
  1811. VERIFY(!stream.controller().has_value());
  1812. // 2. Set controller.[[stream]] to stream.
  1813. controller.set_stream(stream);
  1814. // 3. Perform ! ResetQueue(controller).
  1815. reset_queue(controller);
  1816. // 4. Set controller.[[started]], controller.[[closeRequested]], controller.[[pullAgain]], and controller.[[pulling]] to false.
  1817. controller.set_started(false);
  1818. controller.set_close_requested(false);
  1819. controller.set_pull_again(false);
  1820. controller.set_pulling(false);
  1821. // 5. Set controller.[[strategySizeAlgorithm]] to sizeAlgorithm and controller.[[strategyHWM]] to highWaterMark.
  1822. controller.set_strategy_size_algorithm(size_algorithm);
  1823. controller.set_strategy_hwm(high_water_mark);
  1824. // 6. Set controller.[[pullAlgorithm]] to pullAlgorithm.
  1825. controller.set_pull_algorithm(pull_algorithm);
  1826. // 7. Set controller.[[cancelAlgorithm]] to cancelAlgorithm.
  1827. controller.set_cancel_algorithm(cancel_algorithm);
  1828. // 8. Set stream.[[controller]] to controller.
  1829. stream.set_controller(ReadableStreamController { controller });
  1830. // 9. Let startResult be the result of performing startAlgorithm. (This might throw an exception.)
  1831. auto start_result = TRY(start_algorithm->function()());
  1832. // 10. Let startPromise be a promise resolved with startResult.
  1833. auto start_promise = WebIDL::create_resolved_promise(realm, start_result);
  1834. // 11. Upon fulfillment of startPromise,
  1835. WebIDL::upon_fulfillment(start_promise, [&](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  1836. // 1. Set controller.[[started]] to true.
  1837. controller.set_started(true);
  1838. // 2. Assert: controller.[[pulling]] is false.
  1839. VERIFY(!controller.pulling());
  1840. // 3. Assert: controller.[[pullAgain]] is false.
  1841. VERIFY(!controller.pull_again());
  1842. // 4. Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(controller).
  1843. TRY(readable_stream_default_controller_can_pull_if_needed(controller));
  1844. return JS::js_undefined();
  1845. });
  1846. // 12. Upon rejection of startPromise with reason r,
  1847. WebIDL::upon_rejection(start_promise, [&](auto const& r) -> WebIDL::ExceptionOr<JS::Value> {
  1848. // 1. Perform ! ReadableStreamDefaultControllerError(controller, r).
  1849. readable_stream_default_controller_error(controller, r);
  1850. return JS::js_undefined();
  1851. });
  1852. return {};
  1853. }
  1854. // https://streams.spec.whatwg.org/#set-up-readable-stream-default-controller-from-underlying-source
  1855. 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, JS::NonnullGCPtr<SizeAlgorithm> size_algorithm)
  1856. {
  1857. auto& realm = stream.realm();
  1858. // 1. Let controller be a new ReadableStreamDefaultController.
  1859. auto controller = stream.heap().allocate<ReadableStreamDefaultController>(realm, realm);
  1860. // 2. Let startAlgorithm be an algorithm that returns undefined.
  1861. auto start_algorithm = JS::create_heap_function(realm.heap(), []() -> WebIDL::ExceptionOr<JS::Value> {
  1862. return JS::js_undefined();
  1863. });
  1864. // 3. Let pullAlgorithm be an algorithm that returns a promise resolved with undefined.
  1865. auto pull_algorithm = JS::create_heap_function(realm.heap(), [&realm]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  1866. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  1867. });
  1868. // 4. Let cancelAlgorithm be an algorithm that returns a promise resolved with undefined.
  1869. auto cancel_algorithm = JS::create_heap_function(realm.heap(), [&realm](JS::Value) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  1870. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  1871. });
  1872. // 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.
  1873. if (underlying_source.start) {
  1874. start_algorithm = JS::create_heap_function(realm.heap(), [controller, underlying_source_value, callback = underlying_source.start]() -> WebIDL::ExceptionOr<JS::Value> {
  1875. // Note: callback does not return a promise, so invoke_callback may return an abrupt completion
  1876. return TRY(WebIDL::invoke_callback(*callback, underlying_source_value, controller)).release_value();
  1877. });
  1878. }
  1879. // 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.
  1880. if (underlying_source.pull) {
  1881. pull_algorithm = JS::create_heap_function(realm.heap(), [&realm, controller, underlying_source_value, callback = underlying_source.pull]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  1882. // Note: callback return a promise, so invoke_callback will never return an abrupt completion
  1883. auto result = MUST_OR_THROW_OOM(WebIDL::invoke_callback(*callback, underlying_source_value, controller)).release_value();
  1884. return WebIDL::create_resolved_promise(realm, result);
  1885. });
  1886. }
  1887. // 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.
  1888. if (underlying_source.cancel) {
  1889. cancel_algorithm = JS::create_heap_function(realm.heap(), [&realm, underlying_source_value, callback = underlying_source.cancel](JS::Value reason) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  1890. // Note: callback return a promise, so invoke_callback will never return an abrupt completion
  1891. auto result = MUST_OR_THROW_OOM(WebIDL::invoke_callback(*callback, underlying_source_value, reason)).release_value();
  1892. return WebIDL::create_resolved_promise(realm, result);
  1893. });
  1894. }
  1895. // 8. Perform ? SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm).
  1896. return set_up_readable_stream_default_controller(stream, controller, start_algorithm, pull_algorithm, cancel_algorithm, high_water_mark, size_algorithm);
  1897. }
  1898. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-call-pull-if-needed
  1899. WebIDL::ExceptionOr<void> readable_byte_stream_controller_call_pull_if_needed(ReadableByteStreamController& controller)
  1900. {
  1901. // 1. Let shouldPull be ! ReadableByteStreamControllerShouldCallPull(controller).
  1902. auto should_pull = readable_byte_stream_controller_should_call_pull(controller);
  1903. // 2. If shouldPull is false, return.
  1904. if (!should_pull)
  1905. return {};
  1906. // 3. If controller.[[pulling]] is true,
  1907. if (controller.pulling()) {
  1908. // 1. Set controller.[[pullAgain]] to true.
  1909. controller.set_pull_again(true);
  1910. // 2. Return.
  1911. return {};
  1912. }
  1913. // 4. Assert: controller.[[pullAgain]] is false.
  1914. VERIFY(!controller.pull_again());
  1915. // 5. Set controller.[[pulling]] to true.
  1916. controller.set_pulling(true);
  1917. // 6. Let pullPromise be the result of performing controller.[[pullAlgorithm]].
  1918. auto pull_promise = TRY(controller.pull_algorithm()->function()());
  1919. // 7. Upon fulfillment of pullPromise,
  1920. WebIDL::upon_fulfillment(*pull_promise, [&](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  1921. // 1. Set controller.[[pulling]] to false.
  1922. controller.set_pulling(false);
  1923. // 2. If controller.[[pullAgain]] is true,
  1924. if (controller.pull_again()) {
  1925. // 1. Set controller.[[pullAgain]] to false.
  1926. controller.set_pull_again(false);
  1927. // 2. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
  1928. TRY(readable_byte_stream_controller_call_pull_if_needed(controller));
  1929. }
  1930. return JS::js_undefined();
  1931. });
  1932. // 8. Upon rejection of pullPromise with reason e,
  1933. WebIDL::upon_rejection(*pull_promise, [&](auto const& error) -> WebIDL::ExceptionOr<JS::Value> {
  1934. // 1. Perform ! ReadableByteStreamControllerError(controller, e).
  1935. readable_byte_stream_controller_error(controller, error);
  1936. return JS::js_undefined();
  1937. });
  1938. return {};
  1939. }
  1940. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-clear-algorithms
  1941. void readable_byte_stream_controller_clear_algorithms(ReadableByteStreamController& controller)
  1942. {
  1943. // 1. Set controller.[[pullAlgorithm]] to undefined.
  1944. controller.set_pull_algorithm({});
  1945. // 2. Set controller.[[cancelAlgorithm]] to undefined.
  1946. controller.set_cancel_algorithm({});
  1947. }
  1948. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-clear-pending-pull-intos
  1949. void readable_byte_stream_controller_clear_pending_pull_intos(ReadableByteStreamController& controller)
  1950. {
  1951. // 1. Perform ! ReadableByteStreamControllerInvalidateBYOBRequest(controller).
  1952. readable_byte_stream_controller_invalidate_byob_request(controller);
  1953. // 2. Set controller.[[pendingPullIntos]] to a new empty list.
  1954. controller.pending_pull_intos().clear();
  1955. }
  1956. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-close
  1957. WebIDL::ExceptionOr<void> readable_byte_stream_controller_close(ReadableByteStreamController& controller)
  1958. {
  1959. auto& realm = controller.realm();
  1960. // 1. Let stream be controller.[[stream]].
  1961. auto stream = controller.stream();
  1962. // 2. If controller.[[closeRequested]] is true or stream.[[state]] is not "readable", return.
  1963. if (controller.close_requested() || stream->state() != ReadableStream::State::Readable)
  1964. return {};
  1965. // 3. If controller.[[queueTotalSize]] > 0,
  1966. if (controller.queue_total_size() > 0.0) {
  1967. // 1. Set controller.[[closeRequested]] to true.
  1968. controller.set_close_requested(true);
  1969. // 2. Return.
  1970. return {};
  1971. }
  1972. // 4. If controller.[[pendingPullIntos]] is not empty,
  1973. if (!controller.pending_pull_intos().is_empty()) {
  1974. // 1. Let firstPendingPullInto be controller.[[pendingPullIntos]][0].
  1975. auto& first_pending_pull_into = controller.pending_pull_intos().first();
  1976. // 2. If firstPendingPullInto’s bytes filled > 0,
  1977. if (first_pending_pull_into.bytes_filled > 0) {
  1978. // 1. Let e be a new TypeError exception.
  1979. auto error = JS::TypeError::create(realm, "Cannot close controller in the middle of processing a write request"sv);
  1980. // 2. Perform ! ReadableByteStreamControllerError(controller, e).
  1981. readable_byte_stream_controller_error(controller, error);
  1982. // 3. Throw e.
  1983. return JS::throw_completion(error);
  1984. }
  1985. }
  1986. // 5. Perform ! ReadableByteStreamControllerClearAlgorithms(controller).
  1987. readable_byte_stream_controller_clear_algorithms(controller);
  1988. // 6. Perform ! ReadableStreamClose(stream).
  1989. readable_stream_close(*stream);
  1990. return {};
  1991. }
  1992. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-error
  1993. void readable_byte_stream_controller_error(ReadableByteStreamController& controller, JS::Value error)
  1994. {
  1995. // 1. Let stream be controller.[[stream]].
  1996. auto stream = controller.stream();
  1997. // 2. If stream.[[state]] is not "readable", return.
  1998. if (stream->state() != ReadableStream::State::Readable)
  1999. return;
  2000. // 3. Perform ! ReadableByteStreamControllerClearPendingPullIntos(controller).
  2001. readable_byte_stream_controller_clear_pending_pull_intos(controller);
  2002. // 4. Perform ! ResetQueue(controller).
  2003. reset_queue(controller);
  2004. // 5. Perform ! ReadableByteStreamControllerClearAlgorithms(controller).
  2005. readable_byte_stream_controller_clear_algorithms(controller);
  2006. // 6. Perform ! ReadableStreamError(stream, e).
  2007. readable_stream_error(*stream, error);
  2008. }
  2009. // https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerfillreadrequestfromqueue
  2010. WebIDL::ExceptionOr<void> readable_byte_stream_controller_fill_read_request_from_queue(ReadableByteStreamController& controller, JS::NonnullGCPtr<ReadRequest> read_request)
  2011. {
  2012. auto& vm = controller.vm();
  2013. auto& realm = controller.realm();
  2014. // 1. Assert: controller.[[queueTotalSize]] > 0.
  2015. VERIFY(controller.queue_total_size() > 0.0);
  2016. // 2. Let entry be controller.[[queue]][0].
  2017. // 3. Remove entry from controller.[[queue]].
  2018. auto entry = controller.queue().take_first();
  2019. // 4. Set controller.[[queueTotalSize]] to controller.[[queueTotalSize]] − entry’s byte length.
  2020. controller.set_queue_total_size(controller.queue_total_size() - entry.byte_length);
  2021. // 5. Perform ! ReadableByteStreamControllerHandleQueueDrain(controller).
  2022. TRY(readable_byte_stream_controller_handle_queue_drain(controller));
  2023. // 6. Let view be ! Construct(%Uint8Array%, « entry’s buffer, entry’s byte offset, entry’s byte length »).
  2024. 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)));
  2025. // 7. Perform readRequest’s chunk steps, given view.
  2026. read_request->on_chunk(view);
  2027. return {};
  2028. }
  2029. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-get-desired-size
  2030. Optional<double> readable_byte_stream_controller_get_desired_size(ReadableByteStreamController const& controller)
  2031. {
  2032. auto stream = controller.stream();
  2033. // 1. Let state be controller.[[stream]].[[state]].
  2034. // 2. If state is "errored", return null.
  2035. if (stream->is_errored())
  2036. return {};
  2037. // 3. If state is "closed", return 0.
  2038. if (stream->is_closed())
  2039. return 0.0;
  2040. // 4. Return controller.[[strategyHWM]] − controller.[[queueTotalSize]].
  2041. return controller.strategy_hwm() - controller.queue_total_size();
  2042. }
  2043. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-handle-queue-drain
  2044. WebIDL::ExceptionOr<void> readable_byte_stream_controller_handle_queue_drain(ReadableByteStreamController& controller)
  2045. {
  2046. // 1. Assert: controller.[[stream]].[[state]] is "readable".
  2047. VERIFY(controller.stream()->state() == ReadableStream::State::Readable);
  2048. // 2. If controller.[[queueTotalSize]] is 0 and controller.[[closeRequested]] is true,
  2049. if (controller.queue_total_size() == 0.0 && controller.close_requested()) {
  2050. // 1. Perform ! ReadableByteStreamControllerClearAlgorithms(controller).
  2051. readable_byte_stream_controller_clear_algorithms(controller);
  2052. // 2. Perform ! ReadableStreamClose(controller.[[stream]]).
  2053. readable_stream_close(*controller.stream());
  2054. }
  2055. // 3. Otherwise,
  2056. else {
  2057. // 1. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
  2058. TRY(readable_byte_stream_controller_call_pull_if_needed(controller));
  2059. }
  2060. return {};
  2061. }
  2062. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-invalidate-byob-request
  2063. void readable_byte_stream_controller_invalidate_byob_request(ReadableByteStreamController& controller)
  2064. {
  2065. // 1. If controller.[[byobRequest]] is null, return.
  2066. if (!controller.byob_request())
  2067. return;
  2068. // 2. Set controller.[[byobRequest]].[[controller]] to undefined.
  2069. controller.byob_request()->set_controller({});
  2070. // 3. Set controller.[[byobRequest]].[[view]] to null.
  2071. controller.byob_request()->set_view({});
  2072. // 4. Set controller.[[byobRequest]] to null.
  2073. controller.set_byob_request({});
  2074. }
  2075. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-error
  2076. bool readable_byte_stream_controller_should_call_pull(ReadableByteStreamController const& controller)
  2077. {
  2078. // 1. Let stream be controller.[[stream]].
  2079. auto stream = controller.stream();
  2080. // 2. If stream.[[state]] is not "readable", return false.
  2081. if (stream->state() != ReadableStream::State::Readable)
  2082. return false;
  2083. // 3. If controller.[[closeRequested]] is true, return false.
  2084. if (controller.close_requested())
  2085. return false;
  2086. // 4. If controller.[[started]] is false, return false.
  2087. if (!controller.started())
  2088. return false;
  2089. // 5. If ! ReadableStreamHasDefaultReader(stream) is true and ! ReadableStreamGetNumReadRequests(stream) > 0, return true.
  2090. if (readable_stream_has_default_reader(*stream) && readable_stream_get_num_read_requests(*stream) > 0)
  2091. return true;
  2092. // 6. If ! ReadableStreamHasBYOBReader(stream) is true and ! ReadableStreamGetNumReadIntoRequests(stream) > 0, return true.
  2093. if (readable_stream_has_byob_reader(*stream) && readable_stream_get_num_read_into_requests(*stream) > 0)
  2094. return true;
  2095. // 7. Let desiredSize be ! ReadableByteStreamControllerGetDesiredSize(controller).
  2096. auto desired_size = readable_byte_stream_controller_get_desired_size(controller);
  2097. // 8. Assert: desiredSize is not null.
  2098. VERIFY(desired_size.has_value());
  2099. // 9. If desiredSize > 0, return true.
  2100. if (*desired_size > 0.0)
  2101. return true;
  2102. // 10. Return false.
  2103. return false;
  2104. }
  2105. // https://streams.spec.whatwg.org/#create-readable-stream
  2106. WebIDL::ExceptionOr<JS::NonnullGCPtr<ReadableStream>> create_readable_stream(JS::Realm& realm, JS::NonnullGCPtr<StartAlgorithm> start_algorithm, JS::NonnullGCPtr<PullAlgorithm> pull_algorithm, JS::NonnullGCPtr<CancelAlgorithm> cancel_algorithm, Optional<double> high_water_mark, JS::GCPtr<SizeAlgorithm> size_algorithm)
  2107. {
  2108. // 1. If highWaterMark was not passed, set it to 1.
  2109. if (!high_water_mark.has_value())
  2110. high_water_mark = 1.0;
  2111. // 2. If sizeAlgorithm was not passed, set it to an algorithm that returns 1.
  2112. if (!size_algorithm)
  2113. size_algorithm = JS::create_heap_function(realm.heap(), [](JS::Value) { return JS::normal_completion(JS::Value(1)); });
  2114. // 3. Assert: ! IsNonNegativeNumber(highWaterMark) is true.
  2115. VERIFY(is_non_negative_number(JS::Value { *high_water_mark }));
  2116. // 4. Let stream be a new ReadableStream.
  2117. auto stream = realm.heap().allocate<ReadableStream>(realm, realm);
  2118. // 5. Perform ! InitializeReadableStream(stream).
  2119. initialize_readable_stream(*stream);
  2120. // 6. Let controller be a new ReadableStreamDefaultController.
  2121. auto controller = realm.heap().allocate<ReadableStreamDefaultController>(realm, realm);
  2122. // 7. Perform ? SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm).
  2123. TRY(set_up_readable_stream_default_controller(*stream, *controller, start_algorithm, pull_algorithm, cancel_algorithm, *high_water_mark, *size_algorithm));
  2124. // 8. Return stream.
  2125. return stream;
  2126. }
  2127. // https://streams.spec.whatwg.org/#abstract-opdef-createreadablebytestream
  2128. WebIDL::ExceptionOr<JS::NonnullGCPtr<ReadableStream>> create_readable_byte_stream(JS::Realm& realm, JS::NonnullGCPtr<StartAlgorithm> start_algorithm, JS::NonnullGCPtr<PullAlgorithm> pull_algorithm, JS::NonnullGCPtr<CancelAlgorithm> cancel_algorithm)
  2129. {
  2130. // 1. Let stream be a new ReadableStream.
  2131. auto stream = realm.heap().allocate<ReadableStream>(realm, realm);
  2132. // 2. Perform ! InitializeReadableStream(stream).
  2133. initialize_readable_stream(*stream);
  2134. // 3. Let controller be a new ReadableByteStreamController.
  2135. auto controller = realm.heap().allocate<ReadableByteStreamController>(realm, realm);
  2136. // 4. Perform ? SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined).
  2137. TRY(set_up_readable_byte_stream_controller(stream, controller, start_algorithm, pull_algorithm, cancel_algorithm, 0, JS::js_undefined()));
  2138. // 5. Return stream.
  2139. return stream;
  2140. }
  2141. // https://streams.spec.whatwg.org/#create-writable-stream
  2142. WebIDL::ExceptionOr<JS::NonnullGCPtr<WritableStream>> create_writable_stream(JS::Realm& realm, JS::NonnullGCPtr<StartAlgorithm> start_algorithm, JS::NonnullGCPtr<WriteAlgorithm> write_algorithm, JS::NonnullGCPtr<CloseAlgorithm> close_algorithm, JS::NonnullGCPtr<AbortAlgorithm> abort_algorithm, double high_water_mark, JS::NonnullGCPtr<SizeAlgorithm> size_algorithm)
  2143. {
  2144. // 1. Assert: ! IsNonNegativeNumber(highWaterMark) is true.
  2145. VERIFY(is_non_negative_number(JS::Value { high_water_mark }));
  2146. // 2. Let stream be a new WritableStream.
  2147. auto stream = realm.heap().allocate<WritableStream>(realm, realm);
  2148. // 3. Perform ! InitializeWritableStream(stream).
  2149. initialize_writable_stream(*stream);
  2150. // 4. Let controller be a new WritableStreamDefaultController.
  2151. auto controller = realm.heap().allocate<WritableStreamDefaultController>(realm, realm);
  2152. // 5. Perform ? SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm).
  2153. 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)));
  2154. // 6. Return stream.
  2155. return stream;
  2156. }
  2157. // https://streams.spec.whatwg.org/#initialize-readable-stream
  2158. void initialize_readable_stream(ReadableStream& stream)
  2159. {
  2160. // 1. Set stream.[[state]] to "readable".
  2161. stream.set_state(ReadableStream::State::Readable);
  2162. // 2. Set stream.[[reader]] and stream.[[storedError]] to undefined.
  2163. stream.set_reader({});
  2164. stream.set_stored_error({});
  2165. // 3. Set stream.[[disturbed]] to false.
  2166. stream.set_disturbed(false);
  2167. }
  2168. // https://streams.spec.whatwg.org/#initialize-writable-stream
  2169. void initialize_writable_stream(WritableStream& stream)
  2170. {
  2171. // 1. Set stream.[[state]] to "writable".
  2172. stream.set_state(WritableStream::State::Writable);
  2173. // 2. Set stream.[[storedError]], stream.[[writer]], stream.[[controller]], stream.[[inFlightWriteRequest]],
  2174. // stream.[[closeRequest]], stream.[[inFlightCloseRequest]], and stream.[[pendingAbortRequest]] to undefined.
  2175. stream.set_stored_error(JS::js_undefined());
  2176. stream.set_writer({});
  2177. stream.set_controller({});
  2178. stream.set_in_flight_write_request({});
  2179. stream.set_close_request({});
  2180. stream.set_in_flight_close_request({});
  2181. stream.set_pending_abort_request({});
  2182. // 3. Set stream.[[writeRequests]] to a new empty list.
  2183. stream.write_requests().clear();
  2184. // 4. Set stream.[[backpressure]] to false.
  2185. stream.set_backpressure(false);
  2186. }
  2187. // https://streams.spec.whatwg.org/#acquire-writable-stream-default-writer
  2188. WebIDL::ExceptionOr<JS::NonnullGCPtr<WritableStreamDefaultWriter>> acquire_writable_stream_default_writer(WritableStream& stream)
  2189. {
  2190. auto& realm = stream.realm();
  2191. // 1. Let writer be a new WritableStreamDefaultWriter.
  2192. auto writer = stream.heap().allocate<WritableStreamDefaultWriter>(realm, realm);
  2193. // 2. Perform ? SetUpWritableStreamDefaultWriter(writer, stream).
  2194. TRY(set_up_writable_stream_default_writer(*writer, stream));
  2195. // 3. Return writer.
  2196. return writer;
  2197. }
  2198. // https://streams.spec.whatwg.org/#is-writable-stream-locked
  2199. bool is_writable_stream_locked(WritableStream const& stream)
  2200. {
  2201. // 1. If stream.[[writer]] is undefined, return false.
  2202. if (!stream.writer())
  2203. return false;
  2204. // 2. Return true.
  2205. return true;
  2206. }
  2207. // https://streams.spec.whatwg.org/#set-up-writable-stream-default-writer
  2208. WebIDL::ExceptionOr<void> set_up_writable_stream_default_writer(WritableStreamDefaultWriter& writer, WritableStream& stream)
  2209. {
  2210. auto& realm = writer.realm();
  2211. // 1. If ! IsWritableStreamLocked(stream) is true, throw a TypeError exception.
  2212. if (is_writable_stream_locked(stream))
  2213. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Stream is locked"sv };
  2214. // 2. Set writer.[[stream]] to stream.
  2215. writer.set_stream(stream);
  2216. // 3. Set stream.[[writer]] to writer.
  2217. stream.set_writer(writer);
  2218. // 4. Let state be stream.[[state]].
  2219. auto state = stream.state();
  2220. // 5. If state is "writable",
  2221. if (state == WritableStream::State::Writable) {
  2222. // 1. If ! WritableStreamCloseQueuedOrInFlight(stream) is false and stream.[[backpressure]] is true, set writer.[[readyPromise]] to a new promise.
  2223. if (!writable_stream_close_queued_or_in_flight(stream) && stream.backpressure()) {
  2224. writer.set_ready_promise(WebIDL::create_promise(realm));
  2225. }
  2226. // 2. Otherwise, set writer.[[readyPromise]] to a promise resolved with undefined.
  2227. else {
  2228. writer.set_ready_promise(WebIDL::create_resolved_promise(realm, JS::js_undefined()));
  2229. }
  2230. // 3. Set writer.[[closedPromise]] to a new promise.
  2231. writer.set_closed_promise(WebIDL::create_promise(realm));
  2232. }
  2233. // 6. Otherwise, if state is "erroring",
  2234. else if (state == WritableStream::State::Erroring) {
  2235. // 1. Set writer.[[readyPromise]] to a promise rejected with stream.[[storedError]].
  2236. writer.set_ready_promise(WebIDL::create_rejected_promise(realm, stream.stored_error()));
  2237. // 2. Set writer.[[readyPromise]].[[PromiseIsHandled]] to true.
  2238. WebIDL::mark_promise_as_handled(*writer.ready_promise());
  2239. // 3. Set writer.[[closedPromise]] to a new promise.
  2240. writer.set_closed_promise(WebIDL::create_promise(realm));
  2241. }
  2242. // 7. Otherwise, if state is "closed",
  2243. else if (state == WritableStream::State::Closed) {
  2244. // 1. Set writer.[[readyPromise]] to a promise resolved with undefined.
  2245. writer.set_ready_promise(WebIDL::create_resolved_promise(realm, JS::js_undefined()));
  2246. // 2. Set writer.[[closedPromise]] to a promise resolved with undefined.
  2247. writer.set_closed_promise(WebIDL::create_resolved_promise(realm, JS::js_undefined()));
  2248. }
  2249. // 8. Otherwise,
  2250. else {
  2251. // 1. Assert: state is "errored".
  2252. VERIFY(state == WritableStream::State::Errored);
  2253. // 2. Let storedError be stream.[[storedError]].
  2254. auto stored_error = stream.stored_error();
  2255. // 3. Set writer.[[readyPromise]] to a promise rejected with storedError.
  2256. writer.set_ready_promise(WebIDL::create_rejected_promise(realm, stored_error));
  2257. // 4. Set writer.[[readyPromise]].[[PromiseIsHandled]] to true.
  2258. WebIDL::mark_promise_as_handled(*writer.ready_promise());
  2259. // 5. Set writer.[[closedPromise]] to a promise rejected with storedError.
  2260. writer.set_closed_promise(WebIDL::create_rejected_promise(realm, stored_error));
  2261. // 6. Set writer.[[closedPromise]].[[PromiseIsHandled]] to true.
  2262. WebIDL::mark_promise_as_handled(*writer.closed_promise());
  2263. }
  2264. return {};
  2265. }
  2266. // https://streams.spec.whatwg.org/#set-up-readable-byte-stream-controller
  2267. WebIDL::ExceptionOr<void> set_up_readable_byte_stream_controller(ReadableStream& stream, ReadableByteStreamController& controller, JS::NonnullGCPtr<StartAlgorithm> start_algorithm, JS::NonnullGCPtr<PullAlgorithm> pull_algorithm, JS::NonnullGCPtr<CancelAlgorithm> cancel_algorithm, double high_water_mark, JS::Value auto_allocate_chunk_size)
  2268. {
  2269. auto& realm = stream.realm();
  2270. // 1. Assert: stream.[[controller]] is undefined.
  2271. VERIFY(!stream.controller().has_value());
  2272. // 2. If autoAllocateChunkSize is not undefined,
  2273. if (!auto_allocate_chunk_size.is_undefined()) {
  2274. // 1. Assert: ! IsInteger(autoAllocateChunkSize) is true.
  2275. VERIFY(auto_allocate_chunk_size.is_integral_number());
  2276. // 2. Assert: autoAllocateChunkSize is positive.
  2277. VERIFY(auto_allocate_chunk_size.as_double() > 0);
  2278. }
  2279. // 3. Set controller.[[stream]] to stream.
  2280. controller.set_stream(stream);
  2281. // 4. Set controller.[[pullAgain]] and controller.[[pulling]] to false.
  2282. controller.set_pull_again(false);
  2283. controller.set_pulling(false);
  2284. // 5. Set controller.[[byobRequest]] to null.
  2285. controller.set_byob_request({});
  2286. // 6. Perform ! ResetQueue(controller).
  2287. reset_queue(controller);
  2288. // 7. Set controller.[[closeRequested]] and controller.[[started]] to false.
  2289. controller.set_close_requested(false);
  2290. controller.set_started(false);
  2291. // 8. Set controller.[[strategyHWM]] to highWaterMark.
  2292. controller.set_strategy_hwm(high_water_mark);
  2293. // 9. Set controller.[[pullAlgorithm]] to pullAlgorithm.
  2294. controller.set_pull_algorithm(pull_algorithm);
  2295. // 10. Set controller.[[cancelAlgorithm]] to cancelAlgorithm.
  2296. controller.set_cancel_algorithm(cancel_algorithm);
  2297. // 11. Set controller.[[autoAllocateChunkSize]] to autoAllocateChunkSize.
  2298. if (auto_allocate_chunk_size.is_integral_number())
  2299. controller.set_auto_allocate_chunk_size(auto_allocate_chunk_size.as_double());
  2300. // 12. Set controller.[[pendingPullIntos]] to a new empty list.
  2301. controller.pending_pull_intos().clear();
  2302. // 13. Set stream.[[controller]] to controller.
  2303. stream.set_controller(ReadableStreamController { controller });
  2304. // 14. Let startResult be the result of performing startAlgorithm.
  2305. auto start_result = TRY(start_algorithm->function()());
  2306. // 15. Let startPromise be a promise resolved with startResult.
  2307. auto start_promise = WebIDL::create_resolved_promise(realm, start_result);
  2308. // 16. Upon fulfillment of startPromise,
  2309. WebIDL::upon_fulfillment(start_promise, [&](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  2310. // 1. Set controller.[[started]] to true.
  2311. controller.set_started(true);
  2312. // 2. Assert: controller.[[pulling]] is false.
  2313. VERIFY(!controller.pulling());
  2314. // 3. Assert: controller.[[pullAgain]] is false.
  2315. VERIFY(!controller.pull_again());
  2316. // 4. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
  2317. TRY(readable_byte_stream_controller_call_pull_if_needed(controller));
  2318. return JS::js_undefined();
  2319. });
  2320. // 17. Upon rejection of startPromise with reason r,
  2321. WebIDL::upon_rejection(start_promise, [&](auto const& r) -> WebIDL::ExceptionOr<JS::Value> {
  2322. // 1. Perform ! ReadableByteStreamControllerError(controller, r).
  2323. readable_byte_stream_controller_error(controller, r);
  2324. return JS::js_undefined();
  2325. });
  2326. return {};
  2327. }
  2328. // https://streams.spec.whatwg.org/#readablestream-enqueue
  2329. WebIDL::ExceptionOr<void> readable_stream_enqueue(ReadableStreamController& controller, JS::Value chunk)
  2330. {
  2331. // 1. If stream.[[controller]] implements ReadableStreamDefaultController,
  2332. if (controller.has<JS::NonnullGCPtr<ReadableStreamDefaultController>>()) {
  2333. // 1. Perform ! ReadableStreamDefaultControllerEnqueue(stream.[[controller]], chunk).
  2334. return readable_stream_default_controller_enqueue(controller.get<JS::NonnullGCPtr<ReadableStreamDefaultController>>(), chunk);
  2335. }
  2336. // 2. Otherwise,
  2337. else {
  2338. // 1. Assert: stream.[[controller]] implements ReadableByteStreamController.
  2339. VERIFY(controller.has<JS::NonnullGCPtr<ReadableByteStreamController>>());
  2340. auto readable_byte_controller = controller.get<JS::NonnullGCPtr<ReadableByteStreamController>>();
  2341. // FIXME: 2. Assert: chunk is an ArrayBufferView.
  2342. // 3. Let byobView be the current BYOB request view for stream.
  2343. // FIXME: This is not what the spec means by 'current BYOB request view'
  2344. auto byob_view = readable_byte_controller->raw_byob_request();
  2345. // 4. If byobView is non-null, and chunk.[[ViewedArrayBuffer]] is byobView.[[ViewedArrayBuffer]], then:
  2346. if (byob_view) {
  2347. // FIXME: 1. Assert: chunk.[[ByteOffset]] is byobView.[[ByteOffset]].
  2348. // FIXME: 2. Assert: chunk.[[ByteLength]] ≤ byobView.[[ByteLength]].
  2349. // FIXME: 3. Perform ? ReadableByteStreamControllerRespond(stream.[[controller]], chunk.[[ByteLength]]).
  2350. TODO();
  2351. }
  2352. // 5. Otherwise, perform ? ReadableByteStreamControllerEnqueue(stream.[[controller]], chunk).
  2353. return readable_byte_stream_controller_enqueue(readable_byte_controller, chunk);
  2354. }
  2355. }
  2356. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-enqueue
  2357. WebIDL::ExceptionOr<void> readable_byte_stream_controller_enqueue(ReadableByteStreamController& controller, JS::Value chunk)
  2358. {
  2359. auto& vm = controller.vm();
  2360. auto& realm = controller.realm();
  2361. // 1. Let stream be controller.[[stream]].
  2362. auto stream = controller.stream();
  2363. // 2. If controller.[[closeRequested]] is true or stream.[[state]] is not "readable", return.
  2364. if (controller.close_requested() || stream->state() != ReadableStream ::State::Readable)
  2365. return {};
  2366. // 3. Let buffer be chunk.[[ViewedArrayBuffer]].
  2367. auto* typed_array = TRY(JS::typed_array_from(vm, chunk));
  2368. auto* buffer = typed_array->viewed_array_buffer();
  2369. // 4. Let byteOffset be chunk.[[ByteOffset]].
  2370. auto byte_offset = typed_array->byte_offset();
  2371. // 6. If ! IsDetachedBuffer(buffer) is true, throw a TypeError exception.
  2372. // FIXME: The streams spec has not been updated for resizable ArrayBuffer objects. We must perform step 6 before
  2373. // invoking TypedArrayByteLength in step 5. We also must check if the array is out-of-bounds, rather than
  2374. // just detached.
  2375. auto typed_array_record = JS::make_typed_array_with_buffer_witness_record(*typed_array, JS::ArrayBuffer::Order::SeqCst);
  2376. if (JS::is_typed_array_out_of_bounds(typed_array_record))
  2377. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BufferOutOfBounds, "TypedArray"sv);
  2378. // 5. Let byteLength be chunk.[[ByteLength]].
  2379. auto byte_length = JS::typed_array_byte_length(typed_array_record);
  2380. // 7. Let transferredBuffer be ? TransferArrayBuffer(buffer).
  2381. auto transferred_buffer = TRY(transfer_array_buffer(realm, *buffer));
  2382. // 8. If controller.[[pendingPullIntos]] is not empty,
  2383. if (!controller.pending_pull_intos().is_empty()) {
  2384. // 1. Let firstPendingPullInto be controller.[[pendingPullIntos]][0].
  2385. auto& first_pending_pull_into = controller.pending_pull_intos().first();
  2386. // 2. If ! IsDetachedBuffer(firstPendingPullInto’s buffer) is true, throw a TypeError exception.
  2387. if (first_pending_pull_into.buffer->is_detached()) {
  2388. auto error = JS::TypeError::create(realm, "Buffer is detached"sv);
  2389. return JS::throw_completion(error);
  2390. }
  2391. // 3. Perform ! ReadableByteStreamControllerInvalidateBYOBRequest(controller).
  2392. readable_byte_stream_controller_invalidate_byob_request(controller);
  2393. // 4. Set firstPendingPullInto’s buffer to ! TransferArrayBuffer(firstPendingPullInto’s buffer).
  2394. first_pending_pull_into.buffer = TRY(transfer_array_buffer(realm, first_pending_pull_into.buffer));
  2395. // 5. If firstPendingPullInto’s reader type is "none", perform ? ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto).
  2396. if (first_pending_pull_into.reader_type == ReaderType::None)
  2397. TRY(readable_byte_stream_controller_enqueue_detached_pull_into_queue(controller, first_pending_pull_into));
  2398. }
  2399. // 9. If ! ReadableStreamHasDefaultReader(stream) is true,
  2400. if (readable_stream_has_default_reader(*stream)) {
  2401. // 1. Perform ! ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller).
  2402. TRY(readable_byte_stream_controller_process_read_requests_using_queue(controller));
  2403. // 2. If ! ReadableStreamGetNumReadRequests(stream) is 0,
  2404. if (readable_stream_get_num_read_requests(*stream) == 0) {
  2405. // 1. Assert: controller.[[pendingPullIntos]] is empty.
  2406. VERIFY(controller.pending_pull_intos().is_empty());
  2407. // 2. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength).
  2408. readable_byte_stream_controller_enqueue_chunk_to_queue(controller, transferred_buffer, byte_offset, byte_length);
  2409. }
  2410. // 3. Otherwise.
  2411. else {
  2412. // 1. Assert: controller.[[queue]] is empty.
  2413. VERIFY(controller.queue().is_empty());
  2414. // 2. If controller.[[pendingPullIntos]] is not empty,
  2415. if (!controller.pending_pull_intos().is_empty()) {
  2416. // 1. Assert: controller.[[pendingPullIntos]][0]'s reader type is "default".
  2417. VERIFY(controller.pending_pull_intos().first().reader_type == ReaderType::Default);
  2418. // 2. Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).
  2419. readable_byte_stream_controller_shift_pending_pull_into(controller);
  2420. }
  2421. // 3. Let transferredView be ! Construct(%Uint8Array%, « transferredBuffer, byteOffset, byteLength »).
  2422. 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)));
  2423. // 4. Perform ! ReadableStreamFulfillReadRequest(stream, transferredView, false).
  2424. readable_stream_fulfill_read_request(*stream, transferred_view, false);
  2425. }
  2426. }
  2427. // 10. Otherwise, if ! ReadableStreamHasBYOBReader(stream) is true,
  2428. else if (readable_stream_has_byob_reader(*stream)) {
  2429. // 1. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength).
  2430. readable_byte_stream_controller_enqueue_chunk_to_queue(controller, transferred_buffer, byte_offset, byte_length);
  2431. // 2. Perform ! ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller).
  2432. readable_byte_stream_controller_process_pull_into_descriptors_using_queue(controller);
  2433. }
  2434. // 11. Otherwise,
  2435. else {
  2436. // 1. Assert: ! IsReadableStreamLocked(stream) is false.
  2437. VERIFY(!is_readable_stream_locked(*stream));
  2438. // 2. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength).
  2439. readable_byte_stream_controller_enqueue_chunk_to_queue(controller, transferred_buffer, byte_offset, byte_length);
  2440. }
  2441. // 12. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
  2442. TRY(readable_byte_stream_controller_call_pull_if_needed(controller));
  2443. return {};
  2444. }
  2445. // https://streams.spec.whatwg.org/#transfer-array-buffer
  2446. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::ArrayBuffer>> transfer_array_buffer(JS::Realm& realm, JS::ArrayBuffer& buffer)
  2447. {
  2448. auto& vm = realm.vm();
  2449. // 1. Assert: ! IsDetachedBuffer(O) is false.
  2450. VERIFY(!buffer.is_detached());
  2451. // 2. Let arrayBufferData be O.[[ArrayBufferData]].
  2452. // 3. Let arrayBufferByteLength be O.[[ArrayBufferByteLength]].
  2453. auto array_buffer = buffer.buffer();
  2454. // 4. Perform ? DetachArrayBuffer(O).
  2455. TRY(JS::detach_array_buffer(vm, buffer));
  2456. // 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.
  2457. return JS::ArrayBuffer::create(realm, move(array_buffer));
  2458. }
  2459. // https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerenqueuedetachedpullintotoqueue
  2460. WebIDL::ExceptionOr<void> readable_byte_stream_controller_enqueue_detached_pull_into_queue(ReadableByteStreamController& controller, PullIntoDescriptor& pull_into_descriptor)
  2461. {
  2462. // 1. Assert: pullIntoDescriptor’s reader type is "none".
  2463. VERIFY(pull_into_descriptor.reader_type == ReaderType::None);
  2464. // 2. If pullIntoDescriptor’s bytes filled > 0, perform ? ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor’s buffer, pullIntoDescriptor’s byte offset, pullIntoDescriptor’s bytes filled).
  2465. if (pull_into_descriptor.bytes_filled > 0)
  2466. 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));
  2467. // 3. Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).
  2468. readable_byte_stream_controller_shift_pending_pull_into(controller);
  2469. return {};
  2470. }
  2471. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-commit-pull-into-descriptor
  2472. void readable_byte_stream_controller_commit_pull_into_descriptor(ReadableStream& stream, PullIntoDescriptor const& pull_into_descriptor)
  2473. {
  2474. // 1. Assert: stream.[[state]] is not "errored".
  2475. VERIFY(!stream.is_errored());
  2476. // 2. Assert: pullIntoDescriptor.reader type is not "none".
  2477. VERIFY(pull_into_descriptor.reader_type != ReaderType::None);
  2478. // 3. Let done be false.
  2479. bool done = false;
  2480. // 4. If stream.[[state]] is "closed",
  2481. if (stream.is_closed()) {
  2482. // 1. Assert: pullIntoDescriptor’s bytes filled is 0.
  2483. VERIFY(pull_into_descriptor.bytes_filled == 0);
  2484. // 2. Set done to true.
  2485. done = true;
  2486. }
  2487. // 5. Let filledView be ! ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor).
  2488. auto filled_view = readable_byte_stream_controller_convert_pull_into_descriptor(stream.realm(), pull_into_descriptor);
  2489. // 6. If pullIntoDescriptor’s reader type is "default",
  2490. if (pull_into_descriptor.reader_type == ReaderType::Default) {
  2491. // 1. Perform ! ReadableStreamFulfillReadRequest(stream, filledView, done).
  2492. readable_stream_fulfill_read_request(stream, filled_view, done);
  2493. }
  2494. // 7. Otherwise,
  2495. else {
  2496. // 1. Assert: pullIntoDescriptor’s reader type is "byob".
  2497. VERIFY(pull_into_descriptor.reader_type == ReaderType::Byob);
  2498. // 2. Perform ! ReadableStreamFulfillReadIntoRequest(stream, filledView, done).
  2499. readable_stream_fulfill_read_into_request(stream, filled_view, done);
  2500. }
  2501. }
  2502. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-process-pull-into-descriptors-using-queue
  2503. void readable_byte_stream_controller_process_pull_into_descriptors_using_queue(ReadableByteStreamController& controller)
  2504. {
  2505. // 1. Assert: controller.[[closeRequested]] is false.
  2506. VERIFY(!controller.close_requested());
  2507. // 2. While controller.[[pendingPullIntos]] is not empty,
  2508. while (!controller.pending_pull_intos().is_empty()) {
  2509. // 1. If controller.[[queueTotalSize]] is 0, return.
  2510. if (controller.queue_total_size() == 0)
  2511. return;
  2512. // 2. Let pullIntoDescriptor be controller.[[pendingPullIntos]][0].
  2513. auto& pull_into_descriptor = controller.pending_pull_intos().first();
  2514. // 3. If ! ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) is true,
  2515. if (readable_byte_stream_controller_fill_pull_into_descriptor_from_queue(controller, pull_into_descriptor)) {
  2516. // NOTE: We store the returned pull into descriptor here as the 'shift pending pull into' will remove
  2517. // the first entry into the list which we have a reference to above.
  2518. // 1. Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).
  2519. auto descriptor = readable_byte_stream_controller_shift_pending_pull_into(controller);
  2520. // 2. Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(controller.[[stream]], pullIntoDescriptor).
  2521. readable_byte_stream_controller_commit_pull_into_descriptor(*controller.stream(), descriptor);
  2522. }
  2523. }
  2524. }
  2525. // https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerprocessreadrequestsusingqueue
  2526. WebIDL::ExceptionOr<void> readable_byte_stream_controller_process_read_requests_using_queue(ReadableByteStreamController& controller)
  2527. {
  2528. // 1. Let reader be controller.[[stream]].[[reader]].
  2529. auto reader = controller.stream()->reader();
  2530. // 2. Assert: reader implements ReadableStreamDefaultReader.
  2531. VERIFY(reader->has<JS::NonnullGCPtr<ReadableStreamDefaultReader>>());
  2532. // 3. While reader.[[readRequests]] is not empty,
  2533. auto readable_stream_default_reader = reader->get<JS::NonnullGCPtr<ReadableStreamDefaultReader>>();
  2534. while (!readable_stream_default_reader->read_requests().is_empty()) {
  2535. // 1. If controller.[[queueTotalSize]] is 0, return.
  2536. if (controller.queue_total_size() == 0.0)
  2537. return {};
  2538. // 2. Let readRequest be reader.[[readRequests]][0].
  2539. // 3. Remove readRequest from reader.[[readRequests]].
  2540. auto read_request = readable_stream_default_reader->read_requests().take_first();
  2541. // 4. Perform ! ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest).
  2542. TRY(readable_byte_stream_controller_fill_read_request_from_queue(controller, read_request));
  2543. }
  2544. return {};
  2545. }
  2546. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-enqueue-chunk-to-queue
  2547. void readable_byte_stream_controller_enqueue_chunk_to_queue(ReadableByteStreamController& controller, JS::NonnullGCPtr<JS::ArrayBuffer> buffer, u32 byte_offset, u32 byte_length)
  2548. {
  2549. // 1. Append a new readable byte stream queue entry with buffer buffer, byte offset byteOffset, and byte length byteLength to controller.[[queue]].
  2550. controller.queue().append(ReadableByteStreamQueueEntry {
  2551. .buffer = buffer,
  2552. .byte_offset = byte_offset,
  2553. .byte_length = byte_length,
  2554. });
  2555. // 2. Set controller.[[queueTotalSize]] to controller.[[queueTotalSize]] + byteLength.
  2556. controller.set_queue_total_size(controller.queue_total_size() + byte_length);
  2557. }
  2558. // https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerenqueueclonedchunktoqueue
  2559. WebIDL::ExceptionOr<void> readable_byte_stream_controller_enqueue_cloned_chunk_to_queue(ReadableByteStreamController& controller, JS::ArrayBuffer& buffer, u64 byte_offset, u64 byte_length)
  2560. {
  2561. auto& vm = controller.vm();
  2562. // 1. Let cloneResult be CloneArrayBuffer(buffer, byteOffset, byteLength, %ArrayBuffer%).
  2563. auto clone_result = JS::clone_array_buffer(vm, buffer, byte_offset, byte_length);
  2564. // 2. If cloneResult is an abrupt completion,
  2565. if (clone_result.is_throw_completion()) {
  2566. auto throw_completion = Bindings::throw_dom_exception_if_needed(vm, [&] { return clone_result; }).throw_completion();
  2567. // 1. Perform ! ReadableByteStreamControllerError(controller, cloneResult.[[Value]]).
  2568. readable_byte_stream_controller_error(controller, throw_completion.value().value());
  2569. // 2. Return cloneResult.
  2570. // Note: We need to return the throw_completion object here, as enqueue needs to throw the same object that the controller is errored with
  2571. return throw_completion;
  2572. }
  2573. // 3. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, cloneResult.[[Value]], 0, byteLength).
  2574. readable_byte_stream_controller_enqueue_chunk_to_queue(controller, *clone_result.release_value(), 0, byte_length);
  2575. return {};
  2576. }
  2577. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-shift-pending-pull-into
  2578. PullIntoDescriptor readable_byte_stream_controller_shift_pending_pull_into(ReadableByteStreamController& controller)
  2579. {
  2580. // 1. Assert: controller.[[byobRequest]] is null.
  2581. VERIFY(!controller.raw_byob_request());
  2582. // 2. Let descriptor be controller.[[pendingPullIntos]][0].
  2583. // 3. Remove descriptor from controller.[[pendingPullIntos]].
  2584. auto descriptor = controller.pending_pull_intos().take_first();
  2585. // 4. Return descriptor.
  2586. return descriptor;
  2587. }
  2588. // https://streams.spec.whatwg.org/#readablestream-set-up-with-byte-reading-support
  2589. WebIDL::ExceptionOr<void> set_up_readable_stream_controller_with_byte_reading_support(ReadableStream& stream, JS::GCPtr<PullAlgorithm> pull_algorithm, JS::GCPtr<CancelAlgorithm> cancel_algorithm, double high_water_mark)
  2590. {
  2591. auto& realm = stream.realm();
  2592. // 1. Let startAlgorithm be an algorithm that returns undefined.
  2593. auto start_algorithm = JS::create_heap_function(realm.heap(), []() -> WebIDL::ExceptionOr<JS::Value> { return JS::js_undefined(); });
  2594. // 2. Let pullAlgorithmWrapper be an algorithm that runs these steps:
  2595. auto pull_algorithm_wrapper = JS::create_heap_function(realm.heap(), [&realm, pull_algorithm]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  2596. // 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.
  2597. JS::GCPtr<JS::PromiseCapability> result = nullptr;
  2598. if (pull_algorithm)
  2599. result = TRY(pull_algorithm->function()());
  2600. // 2. If result is a Promise, then return result.
  2601. if (result != nullptr)
  2602. return JS::NonnullGCPtr(*result);
  2603. // 3. Return a promise resolved with undefined.
  2604. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2605. });
  2606. // 3. Let cancelAlgorithmWrapper be an algorithm that runs these steps:
  2607. auto cancel_algorithm_wrapper = JS::create_heap_function(realm.heap(), [&realm, cancel_algorithm](JS::Value c) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  2608. // 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.
  2609. JS::GCPtr<JS::PromiseCapability> result = nullptr;
  2610. if (cancel_algorithm)
  2611. result = TRY(cancel_algorithm->function()(c));
  2612. // 2. If result is a Promise, then return result.
  2613. if (result != nullptr)
  2614. return JS::NonnullGCPtr(*result);
  2615. // 3. Return a promise resolved with undefined.
  2616. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2617. });
  2618. // 4. Perform ! InitializeReadableStream(stream).
  2619. // 5. Let controller be a new ReadableByteStreamController.
  2620. auto controller = stream.heap().allocate<ReadableByteStreamController>(realm, realm);
  2621. // 6. Perform ! SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithmWrapper, cancelAlgorithmWrapper, highWaterMark, undefined).
  2622. TRY(set_up_readable_byte_stream_controller(stream, controller, start_algorithm, pull_algorithm_wrapper, cancel_algorithm_wrapper, high_water_mark, JS::js_undefined()));
  2623. return {};
  2624. }
  2625. // https://streams.spec.whatwg.org/#writable-stream-abort
  2626. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_abort(WritableStream& stream, JS::Value reason)
  2627. {
  2628. auto& realm = stream.realm();
  2629. // 1. If stream.[[state]] is "closed" or "errored", return a promise resolved with undefined.
  2630. auto state = stream.state();
  2631. if (state == WritableStream::State::Closed || state == WritableStream::State::Errored)
  2632. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2633. // 2. Signal abort on stream.[[controller]].[[signal]] with reason.
  2634. stream.controller()->signal()->signal_abort(reason);
  2635. // 3. Let state be stream.[[state]].
  2636. state = stream.state();
  2637. // 4. If state is "closed" or "errored", return a promise resolved with undefined.
  2638. if (state == WritableStream::State::Closed || state == WritableStream::State::Errored)
  2639. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2640. // 5. If stream.[[pendingAbortRequest]] is not undefined, return stream.[[pendingAbortRequest]]'s promise.
  2641. if (stream.pending_abort_request().has_value())
  2642. return stream.pending_abort_request()->promise;
  2643. // 6. Assert: state is "writable" or "erroring".
  2644. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  2645. // 7. Let wasAlreadyErroring be false.
  2646. auto was_already_erroring = false;
  2647. // 8. If state is "erroring",
  2648. if (state == WritableStream::State::Erroring) {
  2649. // 1. Set wasAlreadyErroring to true.
  2650. was_already_erroring = true;
  2651. // 2. Set reason to undefined.
  2652. reason = JS::js_undefined();
  2653. }
  2654. // 9. Let promise be a new promise.
  2655. auto promise = WebIDL::create_promise(realm);
  2656. // 10. Set stream.[[pendingAbortRequest]] to a new pending abort request whose promise is promise, reason is reason, and was already erroring is wasAlreadyErroring.
  2657. stream.set_pending_abort_request(PendingAbortRequest { promise, reason, was_already_erroring });
  2658. // 11. If wasAlreadyErroring is false, perform ! WritableStreamStartErroring(stream, reason).
  2659. if (!was_already_erroring)
  2660. TRY(writable_stream_start_erroring(stream, reason));
  2661. // 12. Return promise.
  2662. return promise;
  2663. }
  2664. // https://streams.spec.whatwg.org/#writable-stream-close
  2665. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_close(WritableStream& stream)
  2666. {
  2667. auto& realm = stream.realm();
  2668. // 1. Let state be stream.[[state]].
  2669. auto state = stream.state();
  2670. // 2. If state is "closed" or "errored", return a promise rejected with a TypeError exception.
  2671. if (state == WritableStream::State::Closed || state == WritableStream::State::Errored) {
  2672. auto message = state == WritableStream::State::Closed ? "Cannot close a closed stream"sv : "Cannot close an errored stream"sv;
  2673. auto exception = JS::TypeError::create(realm, message);
  2674. return WebIDL::create_rejected_promise(realm, exception);
  2675. }
  2676. // 3. Assert: state is "writable" or "erroring".
  2677. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  2678. // 4. Assert: ! WritableStreamCloseQueuedOrInFlight(stream) is false.
  2679. VERIFY(!writable_stream_close_queued_or_in_flight(stream));
  2680. // 5. Let promise be a new promise.
  2681. auto promise = WebIDL::create_promise(realm);
  2682. // 6. Set stream.[[closeRequest]] to promise.
  2683. stream.set_close_request(promise);
  2684. // 7. Let writer be stream.[[writer]].
  2685. auto writer = stream.writer();
  2686. // 8. If writer is not undefined, and stream.[[backpressure]] is true, and state is "writable", resolve writer.[[readyPromise]] with undefined.
  2687. if (writer && stream.backpressure() && state == WritableStream::State::Writable)
  2688. WebIDL::resolve_promise(realm, *writer->ready_promise(), JS::js_undefined());
  2689. // 9. Perform ! WritableStreamDefaultControllerClose(stream.[[controller]]).
  2690. TRY(writable_stream_default_controller_close(*stream.controller()));
  2691. // 10. Return promise.
  2692. return promise;
  2693. }
  2694. // https://streams.spec.whatwg.org/#writable-stream-add-write-request
  2695. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_add_write_request(WritableStream& stream)
  2696. {
  2697. auto& realm = stream.realm();
  2698. auto& vm = stream.vm();
  2699. // 1. Assert: ! IsWritableStreamLocked(stream) is true.
  2700. VERIFY(is_writable_stream_locked(stream));
  2701. // 2. Assert: stream.[[state]] is "writable".
  2702. VERIFY(stream.state() == WritableStream::State::Writable);
  2703. // 3. Let promise be a new promise.
  2704. auto promise = WebIDL::create_promise(realm);
  2705. // 4. Append promise to stream.[[writeRequests]].
  2706. TRY_OR_THROW_OOM(vm, stream.write_requests().try_append(promise));
  2707. // 5. Return promise.
  2708. return promise;
  2709. }
  2710. // https://streams.spec.whatwg.org/#writable-stream-close-queued-or-in-flight
  2711. bool writable_stream_close_queued_or_in_flight(WritableStream const& stream)
  2712. {
  2713. // 1. If stream.[[closeRequest]] is undefined and stream.[[inFlightCloseRequest]] is undefined, return false.
  2714. if (!stream.close_request() && !stream.in_flight_write_request())
  2715. return false;
  2716. // 2. Return true.
  2717. return true;
  2718. }
  2719. // https://streams.spec.whatwg.org/#writable-stream-deal-with-rejection
  2720. WebIDL::ExceptionOr<void> writable_stream_deal_with_rejection(WritableStream& stream, JS::Value error)
  2721. {
  2722. // 1. Let state be stream.[[state]].
  2723. auto state = stream.state();
  2724. // 2. If state is "writable",
  2725. if (state == WritableStream::State::Writable) {
  2726. // 1. Perform ! WritableStreamStartErroring(stream, error).
  2727. // 2. Return.
  2728. return writable_stream_start_erroring(stream, error);
  2729. }
  2730. // 3. Assert: state is "erroring".
  2731. VERIFY(state == WritableStream::State::Erroring);
  2732. // 4. Perform ! WritableStreamFinishErroring(stream).
  2733. return writable_stream_finish_erroring(stream);
  2734. }
  2735. // https://streams.spec.whatwg.org/#writable-stream-finish-erroring
  2736. WebIDL::ExceptionOr<void> writable_stream_finish_erroring(WritableStream& stream)
  2737. {
  2738. auto& realm = stream.realm();
  2739. // 1. Assert: stream.[[state]] is "erroring".
  2740. VERIFY(stream.state() == WritableStream::State::Erroring);
  2741. // 2. Assert: ! WritableStreamHasOperationMarkedInFlight(stream) is false.
  2742. VERIFY(!writable_stream_has_operation_marked_in_flight(stream));
  2743. // 3. Set stream.[[state]] to "errored".
  2744. stream.set_state(WritableStream::State::Errored);
  2745. // 4. Perform ! stream.[[controller]].[[ErrorSteps]]().
  2746. stream.controller()->error_steps();
  2747. // 5. Let storedError be stream.[[storedError]].
  2748. auto stored_error = stream.stored_error();
  2749. // 6. For each writeRequest of stream.[[writeRequests]]:
  2750. for (auto& write_request : stream.write_requests()) {
  2751. // 1. Reject writeRequest with storedError.
  2752. WebIDL::reject_promise(realm, *write_request, stored_error);
  2753. }
  2754. // 7. Set stream.[[writeRequests]] to an empty list.
  2755. stream.write_requests().clear();
  2756. // 8. If stream.[[pendingAbortRequest]] is undefined,
  2757. if (!stream.pending_abort_request().has_value()) {
  2758. // 1. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).
  2759. writable_stream_reject_close_and_closed_promise_if_needed(stream);
  2760. // 2. Return.
  2761. return {};
  2762. }
  2763. // 9. Let abortRequest be stream.[[pendingAbortRequest]].
  2764. // 10. Set stream.[[pendingAbortRequest]] to undefined.
  2765. auto abort_request = stream.pending_abort_request().release_value();
  2766. // 11. If abortRequest’s was already erroring is true,
  2767. if (abort_request.was_already_erroring) {
  2768. // 1. Reject abortRequest’s promise with storedError.
  2769. WebIDL::reject_promise(realm, abort_request.promise, stored_error);
  2770. // 2. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).
  2771. writable_stream_reject_close_and_closed_promise_if_needed(stream);
  2772. // 3. Return.
  2773. return {};
  2774. }
  2775. // 12. Let promise be ! stream.[[controller]].[[AbortSteps]](abortRequest’s reason).
  2776. auto promise = TRY(stream.controller()->abort_steps(abort_request.reason));
  2777. // 13. Upon fulfillment of promise,
  2778. WebIDL::upon_fulfillment(*promise, [&, abort_promise = abort_request.promise](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  2779. // 1. Resolve abortRequest’s promise with undefined.
  2780. WebIDL::resolve_promise(realm, abort_promise, JS::js_undefined());
  2781. // 2. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).
  2782. writable_stream_reject_close_and_closed_promise_if_needed(stream);
  2783. return JS::js_undefined();
  2784. });
  2785. // 14. Upon rejection of promise with reason reason,
  2786. WebIDL::upon_rejection(*promise, [&, abort_promise = abort_request.promise](auto const& reason) -> WebIDL::ExceptionOr<JS::Value> {
  2787. // 1. Reject abortRequest’s promise with reason.
  2788. WebIDL::reject_promise(realm, abort_promise, reason);
  2789. // 2. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).
  2790. writable_stream_reject_close_and_closed_promise_if_needed(stream);
  2791. return JS::js_undefined();
  2792. });
  2793. return {};
  2794. }
  2795. // https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-close
  2796. void writable_stream_finish_in_flight_close(WritableStream& stream)
  2797. {
  2798. auto& realm = stream.realm();
  2799. // 1. Assert: stream.[[inFlightCloseRequest]] is not undefined.
  2800. VERIFY(stream.in_flight_close_request());
  2801. // 2. Resolve stream.[[inFlightCloseRequest]] with undefined.
  2802. WebIDL::resolve_promise(realm, *stream.in_flight_close_request(), JS::js_undefined());
  2803. // 3. Set stream.[[inFlightCloseRequest]] to undefined.
  2804. stream.set_in_flight_close_request({});
  2805. // 4. Let state be stream.[[state]].
  2806. auto state = stream.state();
  2807. // 5. Assert: stream.[[state]] is "writable" or "erroring".
  2808. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  2809. // 6. If state is "erroring",
  2810. if (state == WritableStream::State::Erroring) {
  2811. // 1. Set stream.[[storedError]] to undefined.
  2812. stream.set_stored_error(JS::js_undefined());
  2813. // 2. If stream.[[pendingAbortRequest]] is not undefined,
  2814. if (stream.pending_abort_request().has_value()) {
  2815. // 1. Resolve stream.[[pendingAbortRequest]]'s promise with undefined.
  2816. // 2. Set stream.[[pendingAbortRequest]] to undefined.
  2817. WebIDL::resolve_promise(realm, stream.pending_abort_request().release_value().promise, JS::js_undefined());
  2818. }
  2819. }
  2820. // 7. Set stream.[[state]] to "closed".
  2821. stream.set_state(WritableStream::State::Closed);
  2822. // 8. Let writer be stream.[[writer]].
  2823. auto writer = stream.writer();
  2824. // 9. If writer is not undefined, resolve writer.[[closedPromise]] with undefined.
  2825. if (writer)
  2826. WebIDL::resolve_promise(realm, *writer->closed_promise(), JS::js_undefined());
  2827. // 10. Assert: stream.[[pendingAbortRequest]] is undefined.
  2828. VERIFY(!stream.pending_abort_request().has_value());
  2829. // 11. Assert: stream.[[storedError]] is undefined.
  2830. VERIFY(stream.stored_error().is_undefined());
  2831. }
  2832. // https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-close-with-error
  2833. WebIDL::ExceptionOr<void> writable_stream_finish_in_flight_close_with_error(WritableStream& stream, JS::Value error)
  2834. {
  2835. auto& realm = stream.realm();
  2836. // 1. Assert: stream.[[inFlightCloseRequest]] is not undefined.
  2837. VERIFY(stream.in_flight_close_request());
  2838. // 2. Reject stream.[[inFlightCloseRequest]] with error.
  2839. WebIDL::reject_promise(realm, *stream.in_flight_close_request(), error);
  2840. // 3. Set stream.[[inFlightCloseRequest]] to undefined.
  2841. stream.set_in_flight_close_request({});
  2842. // 4. Assert: stream.[[state]] is "writable" or "erroring".
  2843. auto state = stream.state();
  2844. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  2845. // 5. If stream.[[pendingAbortRequest]] is not undefined,
  2846. if (stream.pending_abort_request().has_value()) {
  2847. // 1. Reject stream.[[pendingAbortRequest]]'s promise with error.
  2848. // 2. Set stream.[[pendingAbortRequest]] to undefined.
  2849. WebIDL::reject_promise(realm, stream.pending_abort_request().release_value().promise, error);
  2850. }
  2851. // 6. Perform ! WritableStreamDealWithRejection(stream, error).
  2852. return writable_stream_deal_with_rejection(stream, error);
  2853. }
  2854. // https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-write
  2855. void writable_stream_finish_in_flight_write(WritableStream& stream)
  2856. {
  2857. auto& realm = stream.realm();
  2858. // 1. Assert: stream.[[inFlightWriteRequest]] is not undefined.
  2859. VERIFY(stream.in_flight_write_request());
  2860. // 2. Resolve stream.[[inFlightWriteRequest]] with undefined.
  2861. WebIDL::resolve_promise(realm, *stream.in_flight_write_request(), JS::js_undefined());
  2862. // 3. Set stream.[[inFlightWriteRequest]] to undefined.
  2863. stream.set_in_flight_write_request({});
  2864. }
  2865. // https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-write-with-error
  2866. WebIDL::ExceptionOr<void> writable_stream_finish_in_flight_write_with_error(WritableStream& stream, JS::Value error)
  2867. {
  2868. auto& realm = stream.realm();
  2869. // 1. Assert: stream.[[inFlightWriteRequest]] is not undefined.
  2870. VERIFY(stream.in_flight_write_request());
  2871. // 2. Reject stream.[[inFlightWriteRequest]] with error.
  2872. WebIDL::reject_promise(realm, *stream.in_flight_write_request(), error);
  2873. // 3. Set stream.[[inFlightWriteRequest]] to undefined.
  2874. stream.set_in_flight_write_request({});
  2875. // 4. Assert: stream.[[state]] is "writable" or "erroring".
  2876. auto state = stream.state();
  2877. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  2878. // 5. Perform ! WritableStreamDealWithRejection(stream, error).
  2879. return writable_stream_deal_with_rejection(stream, error);
  2880. }
  2881. // https://streams.spec.whatwg.org/#writable-stream-has-operation-marked-in-flight
  2882. bool writable_stream_has_operation_marked_in_flight(WritableStream const& stream)
  2883. {
  2884. // 1. If stream.[[inFlightWriteRequest]] is undefined and stream.[[inFlightCloseRequest]] is undefined, return false.
  2885. if (!stream.in_flight_write_request() && !stream.in_flight_close_request())
  2886. return false;
  2887. // 2. Return true.
  2888. return true;
  2889. }
  2890. // https://streams.spec.whatwg.org/#writable-stream-mark-close-request-in-flight
  2891. void writable_stream_mark_close_request_in_flight(WritableStream& stream)
  2892. {
  2893. // 1. Assert: stream.[[inFlightCloseRequest]] is undefined.
  2894. VERIFY(!stream.in_flight_close_request());
  2895. // 2. Assert: stream.[[closeRequest]] is not undefined.
  2896. VERIFY(stream.close_request());
  2897. // 3. Set stream.[[inFlightCloseRequest]] to stream.[[closeRequest]].
  2898. stream.set_in_flight_close_request(stream.close_request());
  2899. // 4. Set stream.[[closeRequest]] to undefined.
  2900. stream.set_close_request({});
  2901. }
  2902. // https://streams.spec.whatwg.org/#writable-stream-mark-first-write-request-in-flight
  2903. void writable_stream_mark_first_write_request_in_flight(WritableStream& stream)
  2904. {
  2905. // 1. Assert: stream.[[inFlightWriteRequest]] is undefined.
  2906. VERIFY(!stream.in_flight_write_request());
  2907. // 2. Assert: stream.[[writeRequests]] is not empty.
  2908. VERIFY(!stream.write_requests().is_empty());
  2909. // 3. Let writeRequest be stream.[[writeRequests]][0].
  2910. // 4. Remove writeRequest from stream.[[writeRequests]].
  2911. auto write_request = stream.write_requests().take_first();
  2912. // 5. Set stream.[[inFlightWriteRequest]] to writeRequest.
  2913. stream.set_in_flight_write_request(write_request);
  2914. }
  2915. // https://streams.spec.whatwg.org/#writable-stream-reject-close-and-closed-promise-if-needed
  2916. void writable_stream_reject_close_and_closed_promise_if_needed(WritableStream& stream)
  2917. {
  2918. auto& realm = stream.realm();
  2919. // 1. Assert: stream.[[state]] is "errored".
  2920. VERIFY(stream.state() == WritableStream::State::Errored);
  2921. // 2. If stream.[[closeRequest]] is not undefined,
  2922. if (stream.close_request()) {
  2923. // 1. Assert: stream.[[inFlightCloseRequest]] is undefined.
  2924. VERIFY(!stream.in_flight_close_request());
  2925. // 2. Reject stream.[[closeRequest]] with stream.[[storedError]].
  2926. WebIDL::reject_promise(realm, *stream.close_request(), stream.stored_error());
  2927. // 3. Set stream.[[closeRequest]] to undefined.
  2928. stream.set_close_request({});
  2929. }
  2930. // 3. Let writer be stream.[[writer]].
  2931. auto writer = stream.writer();
  2932. // 4. If writer is not undefined,
  2933. if (writer) {
  2934. // 1. Reject writer.[[closedPromise]] with stream.[[storedError]].
  2935. WebIDL::reject_promise(realm, *writer->closed_promise(), stream.stored_error());
  2936. // 2. Set writer.[[closedPromise]].[[PromiseIsHandled]] to true.
  2937. WebIDL::mark_promise_as_handled(*writer->closed_promise());
  2938. }
  2939. }
  2940. // https://streams.spec.whatwg.org/#writable-stream-start-erroring
  2941. WebIDL::ExceptionOr<void> writable_stream_start_erroring(WritableStream& stream, JS::Value reason)
  2942. {
  2943. // 1. Assert: stream.[[storedError]] is undefined.
  2944. VERIFY(stream.stored_error().is_undefined());
  2945. // 2. Assert: stream.[[state]] is "writable".
  2946. VERIFY(stream.state() == WritableStream::State::Writable);
  2947. // 3. Let controller be stream.[[controller]].
  2948. auto controller = stream.controller();
  2949. // 4. Assert: controller is not undefined.
  2950. VERIFY(controller);
  2951. // 5. Set stream.[[state]] to "erroring".
  2952. stream.set_state(WritableStream::State::Erroring);
  2953. // 6. Set stream.[[storedError]] to reason.
  2954. stream.set_stored_error(reason);
  2955. // 7. Let writer be stream.[[writer]].
  2956. auto writer = stream.writer();
  2957. // 8. If writer is not undefined, perform ! WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason).
  2958. if (writer)
  2959. writable_stream_default_writer_ensure_ready_promise_rejected(*writer, reason);
  2960. // 9. If ! WritableStreamHasOperationMarkedInFlight(stream) is false and controller.[[started]] is true, perform ! WritableStreamFinishErroring(stream).
  2961. if (!writable_stream_has_operation_marked_in_flight(stream) && controller->started())
  2962. TRY(writable_stream_finish_erroring(stream));
  2963. return {};
  2964. }
  2965. // https://streams.spec.whatwg.org/#writable-stream-update-backpressure
  2966. void writable_stream_update_backpressure(WritableStream& stream, bool backpressure)
  2967. {
  2968. auto& realm = stream.realm();
  2969. // 1. Assert: stream.[[state]] is "writable".
  2970. VERIFY(stream.state() == WritableStream::State::Writable);
  2971. // 2. Assert: ! WritableStreamCloseQueuedOrInFlight(stream) is false.
  2972. VERIFY(!writable_stream_close_queued_or_in_flight(stream));
  2973. // 3. Let writer be stream.[[writer]].
  2974. auto writer = stream.writer();
  2975. // 4. If writer is not undefined and backpressure is not stream.[[backpressure]],
  2976. if (writer && backpressure != stream.backpressure()) {
  2977. // 1. If backpressure is true, set writer.[[readyPromise]] to a new promise.
  2978. if (backpressure) {
  2979. writer->set_ready_promise(WebIDL::create_promise(realm));
  2980. }
  2981. // 2. Otherwise,
  2982. else {
  2983. // 1. Assert: backpressure is false.
  2984. // 2. Resolve writer.[[readyPromise]] with undefined.
  2985. WebIDL::resolve_promise(realm, *writer->ready_promise(), JS::js_undefined());
  2986. }
  2987. }
  2988. // 5. Set stream.[[backpressure]] to backpressure.
  2989. stream.set_backpressure(backpressure);
  2990. }
  2991. // https://streams.spec.whatwg.org/#writable-stream-default-writer-abort
  2992. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_default_writer_abort(WritableStreamDefaultWriter& writer, JS::Value reason)
  2993. {
  2994. // 1. Let stream be writer.[[stream]].
  2995. auto stream = writer.stream();
  2996. // 2. Assert: stream is not undefined.
  2997. VERIFY(stream);
  2998. // 3. Return ! WritableStreamAbort(stream, reason).
  2999. return writable_stream_abort(*stream, reason);
  3000. }
  3001. // https://streams.spec.whatwg.org/#writable-stream-default-writer-close
  3002. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_default_writer_close(WritableStreamDefaultWriter& writer)
  3003. {
  3004. // 1. Let stream be writer.[[stream]].
  3005. auto stream = writer.stream();
  3006. // 2. Assert: stream is not undefined.
  3007. VERIFY(stream);
  3008. // 3. Return ! WritableStreamClose(stream).
  3009. return writable_stream_close(*stream);
  3010. }
  3011. // https://streams.spec.whatwg.org/#writable-stream-default-writer-ensure-closed-promise-rejected
  3012. void writable_stream_default_writer_ensure_closed_promise_rejected(WritableStreamDefaultWriter& writer, JS::Value error)
  3013. {
  3014. auto& realm = writer.realm();
  3015. // 1. If writer.[[closedPromise]].[[PromiseState]] is "pending", reject writer.[[closedPromise]] with error.
  3016. auto& closed_promise = verify_cast<JS::Promise>(*writer.closed_promise()->promise());
  3017. if (closed_promise.state() == JS::Promise::State::Pending) {
  3018. WebIDL::reject_promise(realm, *writer.closed_promise(), error);
  3019. }
  3020. // 2. Otherwise, set writer.[[closedPromise]] to a promise rejected with error.
  3021. else {
  3022. writer.set_closed_promise(WebIDL::create_rejected_promise(realm, error));
  3023. }
  3024. // 3. Set writer.[[closedPromise]].[[PromiseIsHandled]] to true.
  3025. WebIDL::mark_promise_as_handled(*writer.closed_promise());
  3026. }
  3027. // https://streams.spec.whatwg.org/#writable-stream-default-writer-ensure-ready-promise-rejected
  3028. void writable_stream_default_writer_ensure_ready_promise_rejected(WritableStreamDefaultWriter& writer, JS::Value error)
  3029. {
  3030. auto& realm = writer.realm();
  3031. // 1. If writer.[[readyPromise]].[[PromiseState]] is "pending", reject writer.[[readyPromise]] with error.
  3032. auto& ready_promise = verify_cast<JS::Promise>(*writer.ready_promise()->promise());
  3033. if (ready_promise.state() == JS::Promise::State::Pending) {
  3034. WebIDL::reject_promise(realm, *writer.ready_promise(), error);
  3035. }
  3036. // 2. Otherwise, set writer.[[readyPromise]] to a promise rejected with error.
  3037. else {
  3038. writer.set_ready_promise(WebIDL::create_rejected_promise(realm, error));
  3039. }
  3040. // 3. Set writer.[[readyPromise]].[[PromiseIsHandled]] to true.
  3041. WebIDL::mark_promise_as_handled(*writer.ready_promise());
  3042. }
  3043. // https://streams.spec.whatwg.org/#writable-stream-default-writer-get-desired-size
  3044. Optional<double> writable_stream_default_writer_get_desired_size(WritableStreamDefaultWriter const& writer)
  3045. {
  3046. // 1. Let stream be writer.[[stream]].
  3047. auto stream = writer.stream();
  3048. // 2. Let state be stream.[[state]].
  3049. auto state = stream->state();
  3050. // 3. If state is "errored" or "erroring", return null.
  3051. if (state == WritableStream::State::Errored || state == WritableStream::State::Erroring)
  3052. return {};
  3053. // 4. If state is "closed", return 0.
  3054. if (state == WritableStream::State::Closed)
  3055. return 0.0;
  3056. // 5. Return ! WritableStreamDefaultControllerGetDesiredSize(stream.[[controller]]).
  3057. return writable_stream_default_controller_get_desired_size(*stream->controller());
  3058. }
  3059. // https://streams.spec.whatwg.org/#writable-stream-default-writer-release
  3060. WebIDL::ExceptionOr<void> writable_stream_default_writer_release(WritableStreamDefaultWriter& writer)
  3061. {
  3062. auto& realm = writer.realm();
  3063. // 1. Let stream be writer.[[stream]].
  3064. auto stream = writer.stream();
  3065. // 2. Assert: stream is not undefined.
  3066. VERIFY(stream);
  3067. // 3. Assert: stream.[[writer]] is writer.
  3068. VERIFY(stream->writer().ptr() == &writer);
  3069. // 4. Let releasedError be a new TypeError.
  3070. auto released_error = JS::TypeError::create(realm, "Writer's stream lock has been released"sv);
  3071. // 5. Perform ! WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError).
  3072. writable_stream_default_writer_ensure_ready_promise_rejected(writer, released_error);
  3073. // 6. Perform ! WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError).
  3074. writable_stream_default_writer_ensure_closed_promise_rejected(writer, released_error);
  3075. // 7. Set stream.[[writer]] to undefined.
  3076. stream->set_writer({});
  3077. // 8. Set writer.[[stream]] to undefined.
  3078. writer.set_stream({});
  3079. return {};
  3080. }
  3081. // https://streams.spec.whatwg.org/#writable-stream-default-writer-write
  3082. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_default_writer_write(WritableStreamDefaultWriter& writer, JS::Value chunk)
  3083. {
  3084. auto& realm = writer.realm();
  3085. // 1. Let stream be writer.[[stream]].
  3086. auto stream = writer.stream();
  3087. // 2. Assert: stream is not undefined.
  3088. VERIFY(stream);
  3089. // 3. Let controller be stream.[[controller]].
  3090. auto controller = stream->controller();
  3091. // 4. Let chunkSize be ! WritableStreamDefaultControllerGetChunkSize(controller, chunk).
  3092. auto chunk_size = TRY(writable_stream_default_controller_get_chunk_size(*controller, chunk));
  3093. // 5. If stream is not equal to writer.[[stream]], return a promise rejected with a TypeError exception.
  3094. if (stream.ptr() != writer.stream().ptr()) {
  3095. auto exception = JS::TypeError::create(realm, "Writer's locked stream changed during write"sv);
  3096. return WebIDL::create_rejected_promise(realm, exception);
  3097. }
  3098. // 6. Let state be stream.[[state]].
  3099. auto state = stream->state();
  3100. // 7. If state is "errored", return a promise rejected with stream.[[storedError]].
  3101. if (state == WritableStream::State::Errored)
  3102. return WebIDL::create_rejected_promise(realm, stream->stored_error());
  3103. // 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.
  3104. if (writable_stream_close_queued_or_in_flight(*stream) || state == WritableStream::State::Closed) {
  3105. auto exception = JS::TypeError::create(realm, "Cannot write to a writer whose stream is closing or already closed"sv);
  3106. return WebIDL::create_rejected_promise(realm, exception);
  3107. }
  3108. // 9. If state is "erroring", return a promise rejected with stream.[[storedError]].
  3109. if (state == WritableStream::State::Erroring)
  3110. return WebIDL::create_rejected_promise(realm, stream->stored_error());
  3111. // 10. Assert: state is "writable".
  3112. VERIFY(state == WritableStream::State::Writable);
  3113. // 11. Let promise be ! WritableStreamAddWriteRequest(stream).
  3114. auto promise = writable_stream_add_write_request(*stream);
  3115. // 12. Perform ! WritableStreamDefaultControllerWrite(controller, chunk, chunkSize).
  3116. TRY(writable_stream_default_controller_write(*controller, chunk, chunk_size));
  3117. // 13. Return promise.
  3118. return promise;
  3119. }
  3120. // https://streams.spec.whatwg.org/#set-up-writable-stream-default-controller
  3121. WebIDL::ExceptionOr<void> set_up_writable_stream_default_controller(WritableStream& stream, WritableStreamDefaultController& controller, JS::NonnullGCPtr<StartAlgorithm> start_algorithm, JS::NonnullGCPtr<WriteAlgorithm> write_algorithm, JS::NonnullGCPtr<CloseAlgorithm> close_algorithm, JS::NonnullGCPtr<AbortAlgorithm> abort_algorithm, double high_water_mark, JS::NonnullGCPtr<SizeAlgorithm> size_algorithm)
  3122. {
  3123. auto& realm = stream.realm();
  3124. // 1. Assert: stream implements WritableStream.
  3125. // 2. Assert: stream.[[controller]] is undefined.
  3126. VERIFY(!stream.controller());
  3127. // 3. Set controller.[[stream]] to stream.
  3128. controller.set_stream(stream);
  3129. // 4. Set stream.[[controller]] to controller.
  3130. stream.set_controller(controller);
  3131. // 5. Perform ! ResetQueue(controller).
  3132. reset_queue(controller);
  3133. // 6. Set controller.[[signal]] to a new AbortSignal.
  3134. controller.set_signal(realm.heap().allocate<DOM::AbortSignal>(realm, realm));
  3135. // 7. Set controller.[[started]] to false.
  3136. controller.set_started(false);
  3137. // 8. Set controller.[[strategySizeAlgorithm]] to sizeAlgorithm.
  3138. controller.set_strategy_size_algorithm(size_algorithm);
  3139. // 9. Set controller.[[strategyHWM]] to highWaterMark.
  3140. controller.set_strategy_hwm(high_water_mark);
  3141. // 10. Set controller.[[writeAlgorithm]] to writeAlgorithm.
  3142. controller.set_write_algorithm(write_algorithm);
  3143. // 11. Set controller.[[closeAlgorithm]] to closeAlgorithm.
  3144. controller.set_close_algorithm(close_algorithm);
  3145. // 12. Set controller.[[abortAlgorithm]] to abortAlgorithm.
  3146. controller.set_abort_algorithm(abort_algorithm);
  3147. // 13. Let backpressure be ! WritableStreamDefaultControllerGetBackpressure(controller).
  3148. auto backpressure = writable_stream_default_controller_get_backpressure(controller);
  3149. // 14. Perform ! WritableStreamUpdateBackpressure(stream, backpressure).
  3150. writable_stream_update_backpressure(stream, backpressure);
  3151. // 15. Let startResult be the result of performing startAlgorithm. (This may throw an exception.)
  3152. auto start_result = TRY(start_algorithm->function()());
  3153. // 16. Let startPromise be a promise resolved with startResult.
  3154. auto start_promise = WebIDL::create_resolved_promise(realm, start_result);
  3155. // 17. Upon fulfillment of startPromise,
  3156. WebIDL::upon_fulfillment(*start_promise, [&](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  3157. // 1. Assert: stream.[[state]] is "writable" or "erroring".
  3158. auto state = stream.state();
  3159. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  3160. // 2. Set controller.[[started]] to true.
  3161. controller.set_started(true);
  3162. // 3. Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).
  3163. TRY(writable_stream_default_controller_advance_queue_if_needed(controller));
  3164. return JS::js_undefined();
  3165. });
  3166. // 18. Upon rejection of startPromise with reason r,
  3167. WebIDL::upon_rejection(*start_promise, [&](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {
  3168. // 1. Assert: stream.[[state]] is "writable" or "erroring".
  3169. auto state = stream.state();
  3170. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  3171. // 2. Set controller.[[started]] to true.
  3172. controller.set_started(true);
  3173. // 3. Perform ! WritableStreamDealWithRejection(stream, r).
  3174. TRY(writable_stream_deal_with_rejection(stream, reason));
  3175. return JS::js_undefined();
  3176. });
  3177. return {};
  3178. }
  3179. // https://streams.spec.whatwg.org/#set-up-writable-stream-default-controller-from-underlying-sink
  3180. 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, JS::NonnullGCPtr<SizeAlgorithm> size_algorithm)
  3181. {
  3182. auto& realm = stream.realm();
  3183. // 1. Let controller be a new WritableStreamDefaultController.
  3184. auto controller = realm.heap().allocate<WritableStreamDefaultController>(realm, realm);
  3185. // 2. Let startAlgorithm be an algorithm that returns undefined.
  3186. auto start_algorithm = JS::create_heap_function(realm.heap(), []() -> WebIDL::ExceptionOr<JS::Value> { return JS::js_undefined(); });
  3187. // 3. Let writeAlgorithm be an algorithm that returns a promise resolved with undefined.
  3188. auto write_algorithm = JS::create_heap_function(realm.heap(), [&realm](JS::Value) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  3189. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  3190. });
  3191. // 4. Let closeAlgorithm be an algorithm that returns a promise resolved with undefined.
  3192. auto close_algorithm = JS::create_heap_function(realm.heap(), [&realm]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  3193. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  3194. });
  3195. // 5. Let abortAlgorithm be an algorithm that returns a promise resolved with undefined.
  3196. auto abort_algorithm = JS::create_heap_function(realm.heap(), [&realm](JS::Value) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  3197. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  3198. });
  3199. // 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.
  3200. if (underlying_sink.start) {
  3201. start_algorithm = JS::create_heap_function(realm.heap(), [controller, underlying_sink_value, callback = underlying_sink.start]() -> WebIDL::ExceptionOr<JS::Value> {
  3202. // Note: callback does not return a promise, so invoke_callback may return an abrupt completion
  3203. return TRY(WebIDL::invoke_callback(*callback, underlying_sink_value, controller)).release_value();
  3204. });
  3205. }
  3206. // 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.
  3207. if (underlying_sink.write) {
  3208. write_algorithm = JS::create_heap_function(realm.heap(), [&realm, controller, underlying_sink_value, callback = underlying_sink.write](JS::Value chunk) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  3209. // Note: callback return a promise, so invoke_callback will never return an abrupt completion
  3210. auto result = MUST_OR_THROW_OOM(WebIDL::invoke_callback(*callback, underlying_sink_value, chunk, controller)).release_value();
  3211. return WebIDL::create_resolved_promise(realm, result);
  3212. });
  3213. }
  3214. // 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.
  3215. if (underlying_sink.close) {
  3216. close_algorithm = JS::create_heap_function(realm.heap(), [&realm, underlying_sink_value, callback = underlying_sink.close]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  3217. // Note: callback return a promise, so invoke_callback will never return an abrupt completion
  3218. auto result = MUST_OR_THROW_OOM(WebIDL::invoke_callback(*callback, underlying_sink_value)).release_value();
  3219. return WebIDL::create_resolved_promise(realm, result);
  3220. });
  3221. }
  3222. // 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.
  3223. if (underlying_sink.abort) {
  3224. abort_algorithm = JS::create_heap_function(realm.heap(), [&realm, underlying_sink_value, callback = underlying_sink.abort](JS::Value reason) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  3225. // Note: callback return a promise, so invoke_callback will never return an abrupt completion
  3226. auto result = MUST_OR_THROW_OOM(WebIDL::invoke_callback(*callback, underlying_sink_value, reason)).release_value();
  3227. return WebIDL::create_resolved_promise(realm, result);
  3228. });
  3229. }
  3230. // 10. Perform ? SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm).
  3231. TRY(set_up_writable_stream_default_controller(stream, controller, start_algorithm, write_algorithm, close_algorithm, abort_algorithm, high_water_mark, size_algorithm));
  3232. return {};
  3233. }
  3234. // https://streams.spec.whatwg.org/#writable-stream-default-controller-advance-queue-if-needed
  3235. WebIDL::ExceptionOr<void> writable_stream_default_controller_advance_queue_if_needed(WritableStreamDefaultController& controller)
  3236. {
  3237. // 1. Let stream be controller.[[stream]].
  3238. auto stream = controller.stream();
  3239. // 2. If controller.[[started]] is false, return.
  3240. if (!controller.started())
  3241. return {};
  3242. // 3. If stream.[[inFlightWriteRequest]] is not undefined, return.
  3243. if (stream->in_flight_write_request())
  3244. return {};
  3245. // 4. Let state be stream.[[state]].
  3246. auto state = stream->state();
  3247. // 5. Assert: state is not "closed" or "errored".
  3248. VERIFY(state != WritableStream::State::Closed && state != WritableStream::State::Errored);
  3249. // 6. If state is "erroring",
  3250. if (state == WritableStream::State::Erroring) {
  3251. // 1. Perform ! WritableStreamFinishErroring(stream).
  3252. // 2. Return.
  3253. return writable_stream_finish_erroring(*stream);
  3254. }
  3255. // 7. If controller.[[queue]] is empty, return.
  3256. if (controller.queue().is_empty())
  3257. return {};
  3258. // 8. Let value be ! PeekQueueValue(controller).
  3259. auto value = peek_queue_value(controller);
  3260. // 9. If value is the close sentinel, perform ! WritableStreamDefaultControllerProcessClose(controller).
  3261. if (is_close_sentinel(value)) {
  3262. TRY(writable_stream_default_controller_process_close(controller));
  3263. }
  3264. // 10. Otherwise, perform ! WritableStreamDefaultControllerProcessWrite(controller, value).
  3265. else {
  3266. TRY(writable_stream_default_controller_process_write(controller, value));
  3267. }
  3268. return {};
  3269. }
  3270. // https://streams.spec.whatwg.org/#writable-stream-default-controller-clear-algorithms
  3271. void writable_stream_default_controller_clear_algorithms(WritableStreamDefaultController& controller)
  3272. {
  3273. // 1. Set controller.[[writeAlgorithm]] to undefined.
  3274. controller.set_write_algorithm({});
  3275. // 2. Set controller.[[closeAlgorithm]] to undefined.
  3276. controller.set_close_algorithm({});
  3277. // 3. Set controller.[[abortAlgorithm]] to undefined.
  3278. controller.set_abort_algorithm({});
  3279. // 4. Set controller.[[strategySizeAlgorithm]] to undefined.
  3280. controller.set_strategy_size_algorithm({});
  3281. }
  3282. // https://streams.spec.whatwg.org/#writable-stream-default-controller-close
  3283. WebIDL::ExceptionOr<void> writable_stream_default_controller_close(WritableStreamDefaultController& controller)
  3284. {
  3285. // 1. Perform ! EnqueueValueWithSize(controller, close sentinel, 0).
  3286. TRY(enqueue_value_with_size(controller, create_close_sentinel(), JS::Value(0.0)));
  3287. // 2. Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).
  3288. TRY(writable_stream_default_controller_advance_queue_if_needed(controller));
  3289. return {};
  3290. }
  3291. // https://streams.spec.whatwg.org/#writable-stream-default-controller-error
  3292. WebIDL::ExceptionOr<void> writable_stream_default_controller_error(WritableStreamDefaultController& controller, JS::Value error)
  3293. {
  3294. // 1. Let stream be controller.[[stream]].
  3295. auto stream = controller.stream();
  3296. // 2. Assert: stream.[[state]] is "writable".
  3297. VERIFY(stream->state() == WritableStream::State::Writable);
  3298. // 3. Perform ! WritableStreamDefaultControllerClearAlgorithms(controller).
  3299. writable_stream_default_controller_clear_algorithms(controller);
  3300. // 4. Perform ! WritableStreamStartErroring(stream, error).
  3301. return writable_stream_start_erroring(stream, error);
  3302. }
  3303. // https://streams.spec.whatwg.org/#writable-stream-default-controller-error-if-needed
  3304. WebIDL::ExceptionOr<void> writable_stream_default_controller_error_if_needed(WritableStreamDefaultController& controller, JS::Value error)
  3305. {
  3306. // 1. If controller.[[stream]].[[state]] is "writable", perform ! WritableStreamDefaultControllerError(controller, error).
  3307. if (controller.stream()->state() == WritableStream::State::Writable)
  3308. TRY(writable_stream_default_controller_error(controller, error));
  3309. return {};
  3310. }
  3311. // https://streams.spec.whatwg.org/#writable-stream-default-controller-get-backpressure
  3312. bool writable_stream_default_controller_get_backpressure(WritableStreamDefaultController const& controller)
  3313. {
  3314. // 1. Let desiredSize be ! WritableStreamDefaultControllerGetDesiredSize(controller).
  3315. auto desired_size = writable_stream_default_controller_get_desired_size(controller);
  3316. // 2. Return true if desiredSize ≤ 0, or false otherwise.
  3317. return desired_size <= 0.0;
  3318. }
  3319. // https://streams.spec.whatwg.org/#writable-stream-default-controller-get-chunk-size
  3320. WebIDL::ExceptionOr<JS::Value> writable_stream_default_controller_get_chunk_size(WritableStreamDefaultController& controller, JS::Value chunk)
  3321. {
  3322. // 1. Let returnValue be the result of performing controller.[[strategySizeAlgorithm]], passing in chunk, and interpreting the result as a completion record.
  3323. auto return_value = controller.strategy_size_algorithm()->function()(chunk);
  3324. // 2. If returnValue is an abrupt completion,
  3325. if (return_value.is_abrupt()) {
  3326. // 1. Perform ! WritableStreamDefaultControllerErrorIfNeeded(controller, returnValue.[[Value]]).
  3327. TRY(writable_stream_default_controller_error_if_needed(controller, *return_value.release_value()));
  3328. // 2. Return 1.
  3329. return 1.0;
  3330. }
  3331. // 3. Return returnValue.[[Value]].
  3332. return *return_value.release_value();
  3333. }
  3334. // https://streams.spec.whatwg.org/#writable-stream-default-controller-get-desired-size
  3335. double writable_stream_default_controller_get_desired_size(WritableStreamDefaultController const& controller)
  3336. {
  3337. // 1. Return controller.[[strategyHWM]] − controller.[[queueTotalSize]].
  3338. return controller.strategy_hwm() - controller.queue_total_size();
  3339. }
  3340. // https://streams.spec.whatwg.org/#writable-stream-default-controller-process-close
  3341. WebIDL::ExceptionOr<void> writable_stream_default_controller_process_close(WritableStreamDefaultController& controller)
  3342. {
  3343. // 1. Let stream be controller.[[stream]].
  3344. auto stream = controller.stream();
  3345. // 2. Perform ! WritableStreamMarkCloseRequestInFlight(stream).
  3346. writable_stream_mark_close_request_in_flight(*stream);
  3347. // 3. Perform ! DequeueValue(controller).
  3348. dequeue_value(controller);
  3349. // 4. Assert: controller.[[queue]] is empty.
  3350. VERIFY(controller.queue().is_empty());
  3351. // 5. Let sinkClosePromise be the result of performing controller.[[closeAlgorithm]].
  3352. auto sink_close_promise = TRY(controller.close_algorithm()->function()());
  3353. // 6. Perform ! WritableStreamDefaultControllerClearAlgorithms(controller).
  3354. writable_stream_default_controller_clear_algorithms(controller);
  3355. // 7. Upon fulfillment of sinkClosePromise,
  3356. WebIDL::upon_fulfillment(*sink_close_promise, [&, stream = stream](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  3357. // 1. Perform ! WritableStreamFinishInFlightClose(stream).
  3358. writable_stream_finish_in_flight_close(*stream);
  3359. return JS::js_undefined();
  3360. });
  3361. // 8. Upon rejection of sinkClosePromise with reason reason,
  3362. WebIDL::upon_rejection(*sink_close_promise, [&, stream = stream](auto const& reason) -> WebIDL::ExceptionOr<JS::Value> {
  3363. // 1. Perform ! WritableStreamFinishInFlightCloseWithError(stream, reason).
  3364. TRY(writable_stream_finish_in_flight_close_with_error(*stream, reason));
  3365. return JS::js_undefined();
  3366. });
  3367. return {};
  3368. }
  3369. // https://streams.spec.whatwg.org/#writable-stream-default-controller-process-write
  3370. WebIDL::ExceptionOr<void> writable_stream_default_controller_process_write(WritableStreamDefaultController& controller, JS::Value chunk)
  3371. {
  3372. // 1. Let stream be controller.[[stream]].
  3373. auto stream = controller.stream();
  3374. // 2. Perform ! WritableStreamMarkFirstWriteRequestInFlight(stream).
  3375. writable_stream_mark_first_write_request_in_flight(*stream);
  3376. // 3. Let sinkWritePromise be the result of performing controller.[[writeAlgorithm]], passing in chunk.
  3377. auto sink_write_promise = TRY(controller.write_algorithm()->function()(chunk));
  3378. // 4. Upon fulfillment of sinkWritePromise,
  3379. WebIDL::upon_fulfillment(*sink_write_promise, [&, stream = stream](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  3380. // 1. Perform ! WritableStreamFinishInFlightWrite(stream).
  3381. writable_stream_finish_in_flight_write(*stream);
  3382. // 2. Let state be stream.[[state]].
  3383. auto state = stream->state();
  3384. // 3. Assert: state is "writable" or "erroring".
  3385. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  3386. // 4. Perform ! DequeueValue(controller).
  3387. dequeue_value(controller);
  3388. // 5. If ! WritableStreamCloseQueuedOrInFlight(stream) is false and state is "writable",
  3389. if (!writable_stream_close_queued_or_in_flight(*stream) && state == WritableStream::State::Writable) {
  3390. // 1. Let backpressure be ! WritableStreamDefaultControllerGetBackpressure(controller).
  3391. auto backpressure = writable_stream_default_controller_get_backpressure(controller);
  3392. // 2. Perform ! WritableStreamUpdateBackpressure(stream, backpressure).
  3393. writable_stream_update_backpressure(*stream, backpressure);
  3394. }
  3395. // 6 .Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).
  3396. TRY(writable_stream_default_controller_advance_queue_if_needed(controller));
  3397. return JS::js_undefined();
  3398. });
  3399. // 5. Upon rejection of sinkWritePromise with reason,
  3400. WebIDL::upon_rejection(*sink_write_promise, [&, stream = stream](auto const& reason) -> WebIDL::ExceptionOr<JS::Value> {
  3401. // 1. If stream.[[state]] is "writable", perform ! WritableStreamDefaultControllerClearAlgorithms(controller).
  3402. if (stream->state() == WritableStream::State::Writable)
  3403. writable_stream_default_controller_clear_algorithms(controller);
  3404. // 2. Perform ! WritableStreamFinishInFlightWriteWithError(stream, reason).
  3405. TRY(writable_stream_finish_in_flight_write_with_error(*stream, reason));
  3406. return JS::js_undefined();
  3407. });
  3408. return {};
  3409. }
  3410. // https://streams.spec.whatwg.org/#writable-stream-default-controller-write
  3411. WebIDL::ExceptionOr<void> writable_stream_default_controller_write(WritableStreamDefaultController& controller, JS::Value chunk, JS::Value chunk_size)
  3412. {
  3413. auto& vm = controller.vm();
  3414. // 1. Let enqueueResult be EnqueueValueWithSize(controller, chunk, chunkSize).
  3415. auto enqueue_result = enqueue_value_with_size(controller, chunk, chunk_size);
  3416. // 2. If enqueueResult is an abrupt completion,
  3417. if (enqueue_result.is_exception()) {
  3418. auto throw_completion = Bindings::throw_dom_exception_if_needed(vm, [&] { return enqueue_result; }).throw_completion();
  3419. // 1. Perform ! WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueResult.[[Value]]).
  3420. TRY(writable_stream_default_controller_error_if_needed(controller, *throw_completion.release_value()));
  3421. // 2. Return.
  3422. return {};
  3423. }
  3424. // 3. Let stream be controller.[[stream]].
  3425. auto stream = controller.stream();
  3426. // 4. If ! WritableStreamCloseQueuedOrInFlight(stream) is false and stream.[[state]] is "writable",
  3427. if (!writable_stream_close_queued_or_in_flight(*stream) && stream->state() == WritableStream::State::Writable) {
  3428. // 1. Let backpressure be ! WritableStreamDefaultControllerGetBackpressure(controller).
  3429. auto backpressure = writable_stream_default_controller_get_backpressure(controller);
  3430. // 2. Perform ! WritableStreamUpdateBackpressure(stream, backpressure).
  3431. writable_stream_update_backpressure(*stream, backpressure);
  3432. }
  3433. // 5. Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).
  3434. TRY(writable_stream_default_controller_advance_queue_if_needed(controller));
  3435. return {};
  3436. }
  3437. // https://streams.spec.whatwg.org/#initialize-transform-stream
  3438. WebIDL::ExceptionOr<void> initialize_transform_stream(TransformStream& stream, JS::NonnullGCPtr<JS::PromiseCapability> start_promise, double writable_high_water_mark, JS::NonnullGCPtr<SizeAlgorithm> writable_size_algorithm, double readable_high_water_mark, JS::NonnullGCPtr<SizeAlgorithm> readable_size_algorithm)
  3439. {
  3440. auto& realm = stream.realm();
  3441. // 1. Let startAlgorithm be an algorithm that returns startPromise.
  3442. auto writable_start_algorithm = JS::create_heap_function(realm.heap(), [start_promise]() -> WebIDL::ExceptionOr<JS::Value> {
  3443. return start_promise->promise();
  3444. });
  3445. auto readable_start_algorithm = JS::create_heap_function(realm.heap(), [start_promise]() -> WebIDL::ExceptionOr<JS::Value> {
  3446. return start_promise->promise();
  3447. });
  3448. // 2. Let writeAlgorithm be the following steps, taking a chunk argument:
  3449. auto write_algorithm = JS::create_heap_function(realm.heap(), [&stream](JS::Value chunk) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  3450. // 1. Return ! TransformStreamDefaultSinkWriteAlgorithm(stream, chunk).
  3451. return transform_stream_default_sink_write_algorithm(stream, chunk);
  3452. });
  3453. // 3. Let abortAlgorithm be the following steps, taking a reason argument:
  3454. auto abort_algorithm = JS::create_heap_function(realm.heap(), [&stream](JS::Value reason) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  3455. // 1. Return ! TransformStreamDefaultSinkAbortAlgorithm(stream, reason).
  3456. return transform_stream_default_sink_abort_algorithm(stream, reason);
  3457. });
  3458. // 4. Let closeAlgorithm be the following steps:
  3459. auto close_algorithm = JS::create_heap_function(realm.heap(), [&stream]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  3460. // 1. Return ! TransformStreamDefaultSinkCloseAlgorithm(stream).
  3461. return transform_stream_default_sink_close_algorithm(stream);
  3462. });
  3463. // 5. Set stream.[[writable]] to ! CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm).
  3464. stream.set_writable(TRY(create_writable_stream(realm, writable_start_algorithm, write_algorithm, close_algorithm, abort_algorithm, writable_high_water_mark, writable_size_algorithm)));
  3465. // 6. Let pullAlgorithm be the following steps:
  3466. auto pull_algorithm = JS::create_heap_function(realm.heap(), [&stream]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  3467. // 1. Return ! TransformStreamDefaultSourcePullAlgorithm(stream).
  3468. return transform_stream_default_source_pull_algorithm(stream);
  3469. });
  3470. // 7. Let cancelAlgorithm be the following steps, taking a reason argument:
  3471. auto cancel_algorithm = JS::create_heap_function(realm.heap(), [&stream, &realm](JS::Value reason) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  3472. // 1. Perform ! TransformStreamErrorWritableAndUnblockWrite(stream, reason).
  3473. TRY(transform_stream_error_writable_and_unblock_write(stream, reason));
  3474. // 2. Return a promise resolved with undefined.
  3475. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  3476. });
  3477. // 8. Set stream.[[readable]] to ! CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm).
  3478. stream.set_readable(TRY(create_readable_stream(realm, readable_start_algorithm, pull_algorithm, cancel_algorithm, readable_high_water_mark, readable_size_algorithm)));
  3479. // 9. Set stream.[[backpressure]] and stream.[[backpressureChangePromise]] to undefined.
  3480. stream.set_backpressure({});
  3481. stream.set_backpressure_change_promise({});
  3482. // 10. Perform ! TransformStreamSetBackpressure(stream, true).
  3483. TRY(transform_stream_set_backpressure(stream, true));
  3484. // 11. Set stream.[[controller]] to undefined.
  3485. stream.set_controller({});
  3486. return {};
  3487. }
  3488. // https://streams.spec.whatwg.org/#set-up-transform-stream-default-controller
  3489. void set_up_transform_stream_default_controller(TransformStream& stream, TransformStreamDefaultController& controller, JS::NonnullGCPtr<TransformAlgorithm> transform_algorithm, JS::NonnullGCPtr<FlushAlgorithm> flush_algorithm)
  3490. {
  3491. // 1. Assert: stream implements TransformStream.
  3492. // 2. Assert: stream.[[controller]] is undefined.
  3493. VERIFY(!stream.controller());
  3494. // 3. Set controller.[[stream]] to stream.
  3495. controller.set_stream(stream);
  3496. // 4. Set stream.[[controller]] to controller.
  3497. stream.set_controller(controller);
  3498. // 5. Set controller.[[transformAlgorithm]] to transformAlgorithm.
  3499. controller.set_transform_algorithm(transform_algorithm);
  3500. // 6. Set controller.[[flushAlgorithm]] to flushAlgorithm.
  3501. controller.set_flush_algorithm(flush_algorithm);
  3502. }
  3503. // https://streams.spec.whatwg.org/#set-up-transform-stream-default-controller-from-transformer
  3504. WebIDL::ExceptionOr<void> set_up_transform_stream_default_controller_from_transformer(TransformStream& stream, JS::Value transformer, Transformer& transformer_dict)
  3505. {
  3506. auto& realm = stream.realm();
  3507. auto& vm = realm.vm();
  3508. // 1. Let controller be a new TransformStreamDefaultController.
  3509. auto controller = realm.heap().allocate<TransformStreamDefaultController>(realm, realm);
  3510. // 2. Let transformAlgorithm be the following steps, taking a chunk argument:
  3511. auto transform_algorithm = JS::create_heap_function(realm.heap(), [controller, &realm, &vm](JS::Value chunk) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  3512. // 1. Let result be TransformStreamDefaultControllerEnqueue(controller, chunk).
  3513. auto result = transform_stream_default_controller_enqueue(*controller, chunk);
  3514. // 2. If result is an abrupt completion, return a promise rejected with result.[[Value]].
  3515. if (result.is_error()) {
  3516. auto throw_completion = Bindings::dom_exception_to_throw_completion(vm, result.exception());
  3517. return WebIDL::create_rejected_promise(realm, *throw_completion.release_value());
  3518. }
  3519. // 3. Otherwise, return a promise resolved with undefined.
  3520. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  3521. });
  3522. // 3. Let flushAlgorithm be an algorithm which returns a promise resolved with undefined.
  3523. auto flush_algorithm = JS::create_heap_function(realm.heap(), [&realm]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  3524. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  3525. });
  3526. // 4. If transformerDict["transform"] exists, set transformAlgorithm to an algorithm which takes an argument chunk
  3527. // and returns the result of invoking transformerDict["transform"] with argument list « chunk, controller » and
  3528. // callback this value transformer.
  3529. if (transformer_dict.transform) {
  3530. transform_algorithm = JS::create_heap_function(realm.heap(), [controller, &realm, transformer, callback = transformer_dict.transform](JS::Value chunk) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  3531. // Note: callback does not return a promise, so invoke_callback may return an abrupt completion
  3532. auto result = WebIDL::invoke_callback(*callback, transformer, chunk, controller);
  3533. if (result.is_error())
  3534. return WebIDL::create_rejected_promise(realm, *result.release_value());
  3535. return WebIDL::create_resolved_promise(realm, *result.release_value());
  3536. });
  3537. }
  3538. // 5. If transformerDict["flush"] exists, set flushAlgorithm to an algorithm which returns the result of invoking
  3539. // transformerDict["flush"] with argument list « controller » and callback this value transformer.
  3540. if (transformer_dict.flush) {
  3541. flush_algorithm = JS::create_heap_function(realm.heap(), [&realm, transformer, callback = transformer_dict.flush, controller]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  3542. // Note: callback does not return a promise, so invoke_callback may return an abrupt completion
  3543. auto result = WebIDL::invoke_callback(*callback, transformer, controller);
  3544. if (result.is_error()) {
  3545. return WebIDL::create_rejected_promise(realm, *result.release_value());
  3546. }
  3547. return WebIDL::create_resolved_promise(realm, *result.release_value());
  3548. });
  3549. }
  3550. // 6. Perform ! SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm).
  3551. set_up_transform_stream_default_controller(stream, *controller, transform_algorithm, flush_algorithm);
  3552. return {};
  3553. }
  3554. // https://streams.spec.whatwg.org/#transform-stream-default-controller-clear-algorithms
  3555. void transform_stream_default_controller_clear_algorithms(TransformStreamDefaultController& controller)
  3556. {
  3557. // NOTE: This is observable using weak references. See tc39/proposal-weakrefs#31 for more detail.
  3558. // 1. Set controller.[[transformAlgorithm]] to undefined.
  3559. controller.set_transform_algorithm({});
  3560. // 2. Set controller.[[flushAlgorithm]] to undefined.
  3561. controller.set_flush_algorithm({});
  3562. }
  3563. // https://streams.spec.whatwg.org/#transform-stream-default-controller-enqueue
  3564. WebIDL::ExceptionOr<void> transform_stream_default_controller_enqueue(TransformStreamDefaultController& controller, JS::Value chunk)
  3565. {
  3566. auto& vm = controller.vm();
  3567. // 1. Let stream be controller.[[stream]].
  3568. auto stream = controller.stream();
  3569. // 2. Let readableController be stream.[[readable]].[[controller]].
  3570. VERIFY(stream->readable()->controller().has_value() && stream->readable()->controller()->has<JS::NonnullGCPtr<ReadableStreamDefaultController>>());
  3571. auto& readable_controller = stream->readable()->controller()->get<JS::NonnullGCPtr<ReadableStreamDefaultController>>();
  3572. // 3. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController) is false, throw a TypeError exception.
  3573. if (!readable_stream_default_controller_can_close_or_enqueue(readable_controller))
  3574. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "ReadableController is either closed or not readable."sv };
  3575. // 4. Let enqueueResult be ReadableStreamDefaultControllerEnqueue(readableController, chunk).
  3576. auto enqueue_result = readable_stream_default_controller_enqueue(readable_controller, chunk);
  3577. // 5. If enqueueResult is an abrupt completion,
  3578. if (enqueue_result.is_error()) {
  3579. auto throw_completion = Bindings::dom_exception_to_throw_completion(vm, enqueue_result.exception());
  3580. // 1. Perform ! TransformStreamErrorWritableAndUnblockWrite(stream, enqueueResult.[[Value]]).
  3581. TRY(transform_stream_error_writable_and_unblock_write(*stream, throw_completion.value().value()));
  3582. // 2. Throw stream.[[readable]].[[storedError]].
  3583. return JS::throw_completion(stream->readable()->stored_error());
  3584. }
  3585. // 6. Let backpressure be ! ReadableStreamDefaultControllerHasBackpressure(readableController).
  3586. auto backpressure = readable_stream_default_controller_has_backpressure(readable_controller);
  3587. // 7. If backpressure is not stream.[[backpressure]],
  3588. if (backpressure != stream->backpressure()) {
  3589. // 1. Assert: backpressure is true.
  3590. VERIFY(backpressure);
  3591. // 2. Perform ! TransformStreamSetBackpressure(stream, true).
  3592. TRY(transform_stream_set_backpressure(*stream, true));
  3593. }
  3594. return {};
  3595. }
  3596. // https://streams.spec.whatwg.org/#transform-stream-default-controller-error
  3597. WebIDL::ExceptionOr<void> transform_stream_default_controller_error(TransformStreamDefaultController& controller, JS::Value error)
  3598. {
  3599. // 1. Perform ! TransformStreamError(controller.[[stream]], e).
  3600. TRY(transform_stream_error(*controller.stream(), error));
  3601. return {};
  3602. }
  3603. // https://streams.spec.whatwg.org/#transform-stream-default-controller-terminate
  3604. WebIDL::ExceptionOr<void> transform_stream_default_controller_terminate(TransformStreamDefaultController& controller)
  3605. {
  3606. auto& realm = controller.realm();
  3607. // 1. Let stream be controller.[[stream]].
  3608. auto stream = controller.stream();
  3609. // 2. Let readableController be stream.[[readable]].[[controller]].
  3610. VERIFY(stream->readable()->controller().has_value() && stream->readable()->controller()->has<JS::NonnullGCPtr<ReadableStreamDefaultController>>());
  3611. auto readable_controller = stream->readable()->controller()->get<JS::NonnullGCPtr<ReadableStreamDefaultController>>();
  3612. // 3. Perform ! ReadableStreamDefaultControllerClose(readableController).
  3613. readable_stream_default_controller_close(readable_controller);
  3614. // 4. Let error be a TypeError exception indicating that the stream has been terminated.
  3615. auto error = JS::TypeError::create(realm, "Stream has been terminated."sv);
  3616. // 5. Perform ! TransformStreamErrorWritableAndUnblockWrite(stream, error).
  3617. TRY(transform_stream_error_writable_and_unblock_write(*stream, error));
  3618. return {};
  3619. }
  3620. // https://streams.spec.whatwg.org/#transform-stream-default-controller-perform-transform
  3621. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> transform_stream_default_controller_perform_transform(TransformStreamDefaultController& controller, JS::Value chunk)
  3622. {
  3623. auto& realm = controller.realm();
  3624. // 1. Let transformPromise be the result of performing controller.[[transformAlgorithm]], passing chunk.
  3625. auto transform_promise = TRY(controller.transform_algorithm()->function()(chunk));
  3626. // 2. Return the result of reacting to transformPromise with the following rejection steps given the argument r:
  3627. auto react_result = WebIDL::react_to_promise(*transform_promise,
  3628. {},
  3629. [&](auto const& reason) -> WebIDL::ExceptionOr<JS::Value> {
  3630. // 1. Perform ! TransformStreamError(controller.[[stream]], r).
  3631. TRY(transform_stream_error(*controller.stream(), reason));
  3632. // 2. Throw r.
  3633. return JS::throw_completion(reason);
  3634. });
  3635. return WebIDL::create_resolved_promise(realm, react_result);
  3636. }
  3637. // https://streams.spec.whatwg.org/#transform-stream-default-sink-abort-algorithm
  3638. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> transform_stream_default_sink_abort_algorithm(TransformStream& stream, JS::Value reason)
  3639. {
  3640. auto& realm = stream.realm();
  3641. // 1. Perform ! TransformStreamError(stream, reason).
  3642. TRY(transform_stream_error(stream, reason));
  3643. // 2. Return a promise resolved with undefined.
  3644. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  3645. }
  3646. // https://streams.spec.whatwg.org/#transform-stream-default-sink-close-algorithm
  3647. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> transform_stream_default_sink_close_algorithm(TransformStream& stream)
  3648. {
  3649. auto& realm = stream.realm();
  3650. // 1. Let readable be stream.[[readable]].
  3651. auto readable = stream.readable();
  3652. // 2. Let controller be stream.[[controller]].
  3653. auto controller = stream.controller();
  3654. // 3. Let flushPromise be the result of performing controller.[[flushAlgorithm]].
  3655. auto flush_promise = TRY(controller->flush_algorithm()->function()());
  3656. // 4. Perform ! TransformStreamDefaultControllerClearAlgorithms(controller).
  3657. transform_stream_default_controller_clear_algorithms(*controller);
  3658. // 5. Return the result of reacting to flushPromise:
  3659. auto react_result = WebIDL::react_to_promise(
  3660. *flush_promise,
  3661. // 1. If flushPromise was fulfilled, then:
  3662. [readable](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  3663. // 1. If readable.[[state]] is "errored", throw readable.[[storedError]].
  3664. if (readable->state() == ReadableStream::State::Errored)
  3665. return JS::throw_completion(readable->stored_error());
  3666. VERIFY(readable->controller().has_value() && readable->controller()->has<JS::NonnullGCPtr<ReadableStreamDefaultController>>());
  3667. // 2. Perform ! ReadableStreamDefaultControllerClose(readable.[[controller]]).
  3668. readable_stream_default_controller_close(readable->controller().value().get<JS::NonnullGCPtr<ReadableStreamDefaultController>>());
  3669. return JS::js_undefined();
  3670. },
  3671. // 2. If flushPromise was rejected with reason r, then:
  3672. [&stream, readable](auto const& reason) -> WebIDL::ExceptionOr<JS::Value> {
  3673. // 1. Perform ! TransformStreamError(stream, r).
  3674. TRY(transform_stream_error(stream, reason));
  3675. // 2. Throw readable.[[storedError]].
  3676. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, readable->stored_error().as_string().utf8_string() };
  3677. });
  3678. return WebIDL::create_resolved_promise(realm, react_result);
  3679. }
  3680. // https://streams.spec.whatwg.org/#transform-stream-default-sink-write-algorithm
  3681. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> transform_stream_default_sink_write_algorithm(TransformStream& stream, JS::Value chunk)
  3682. {
  3683. auto& realm = stream.realm();
  3684. // 1. Assert: stream.[[writable]].[[state]] is "writable".
  3685. VERIFY(stream.writable()->state() == WritableStream::State::Writable);
  3686. // 2. Let controller be stream.[[controller]].
  3687. auto controller = stream.controller();
  3688. // 3. If stream.[[backpressure]] is true,
  3689. if (stream.backpressure().has_value() && *stream.backpressure()) {
  3690. // 1. Let backpressureChangePromise be stream.[[backpressureChangePromise]].
  3691. auto backpressure_change_promise = stream.backpressure_change_promise();
  3692. // 2. Assert: backpressureChangePromise is not undefined.
  3693. VERIFY(backpressure_change_promise);
  3694. // 3. Return the result of reacting to backpressureChangePromise with the following fulfillment steps:
  3695. auto react_result = WebIDL::react_to_promise(*backpressure_change_promise,
  3696. [&stream, controller, chunk](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  3697. // 1. Let writable be stream.[[writable]].
  3698. auto writable = stream.writable();
  3699. // 2. Let state be writable.[[state]].
  3700. auto state = writable->state();
  3701. // 3. If state is "erroring", throw writable.[[storedError]].
  3702. if (state == WritableStream::State::Erroring)
  3703. return JS::throw_completion(writable->stored_error());
  3704. // 4. Assert: state is "writable".
  3705. VERIFY(state == WritableStream::State::Writable);
  3706. // 5. Return ! TransformStreamDefaultControllerPerformTransform(controller, chunk).
  3707. return TRY(transform_stream_default_controller_perform_transform(*controller, chunk))->promise();
  3708. },
  3709. {});
  3710. return WebIDL::create_resolved_promise(realm, react_result);
  3711. }
  3712. // 4. Return ! TransformStreamDefaultControllerPerformTransform(controller, chunk).
  3713. return transform_stream_default_controller_perform_transform(*controller, chunk);
  3714. }
  3715. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> transform_stream_default_source_pull_algorithm(TransformStream& stream)
  3716. {
  3717. // 1. Assert: stream.[[backpressure]] is true.
  3718. VERIFY(stream.backpressure().has_value() && *stream.backpressure());
  3719. // 2. Assert: stream.[[backpressureChangePromise]] is not undefined.
  3720. VERIFY(stream.backpressure_change_promise());
  3721. // 3. Perform ! TransformStreamSetBackpressure(stream, false).
  3722. TRY(transform_stream_set_backpressure(stream, false));
  3723. // 4. Return stream.[[backpressureChangePromise]].
  3724. return JS::NonnullGCPtr { *stream.backpressure_change_promise() };
  3725. }
  3726. // https://streams.spec.whatwg.org/#transform-stream-error
  3727. WebIDL::ExceptionOr<void> transform_stream_error(TransformStream& stream, JS::Value error)
  3728. {
  3729. VERIFY(stream.readable()->controller().has_value() && stream.readable()->controller()->has<JS::NonnullGCPtr<ReadableStreamDefaultController>>());
  3730. auto readable_controller = stream.readable()->controller()->get<JS::NonnullGCPtr<ReadableStreamDefaultController>>();
  3731. // 1. Perform ! ReadableStreamDefaultControllerError(stream.[[readable]].[[controller]], e).
  3732. readable_stream_default_controller_error(*readable_controller, error);
  3733. // 2. Perform ! TransformStreamErrorWritableAndUnblockWrite(stream, e).
  3734. TRY(transform_stream_error_writable_and_unblock_write(stream, error));
  3735. return {};
  3736. }
  3737. // https://streams.spec.whatwg.org/#transform-stream-error-writable-and-unblock-write
  3738. WebIDL::ExceptionOr<void> transform_stream_error_writable_and_unblock_write(TransformStream& stream, JS::Value error)
  3739. {
  3740. // 1. Perform ! TransformStreamDefaultControllerClearAlgorithms(stream.[[controller]]).
  3741. transform_stream_default_controller_clear_algorithms(*stream.controller());
  3742. // 2. Perform ! WritableStreamDefaultControllerErrorIfNeeded(stream.[[writable]].[[controller]], e).
  3743. TRY(writable_stream_default_controller_error_if_needed(*stream.writable()->controller(), error));
  3744. // 3. If stream.[[backpressure]] is true, perform ! TransformStreamSetBackpressure(stream, false).
  3745. if (stream.backpressure().has_value() && *stream.backpressure())
  3746. TRY(transform_stream_set_backpressure(stream, false));
  3747. return {};
  3748. }
  3749. // https://streams.spec.whatwg.org/#transform-stream-set-backpressure
  3750. WebIDL::ExceptionOr<void> transform_stream_set_backpressure(TransformStream& stream, bool backpressure)
  3751. {
  3752. auto& realm = stream.realm();
  3753. // 1. Assert: stream.[[backpressure]] is not backpressure.
  3754. VERIFY(stream.backpressure() != backpressure);
  3755. // 2. If stream.[[backpressureChangePromise]] is not undefined, resolve stream.[[backpressureChangePromise]] with undefined.
  3756. if (stream.backpressure_change_promise())
  3757. WebIDL::resolve_promise(realm, *stream.backpressure_change_promise(), JS::js_undefined());
  3758. // 3. Set stream.[[backpressureChangePromise]] to a new promise.
  3759. stream.set_backpressure_change_promise(WebIDL::create_promise(realm));
  3760. // 4. Set stream.[[backpressure]] to backpressure.
  3761. stream.set_backpressure(backpressure);
  3762. return {};
  3763. }
  3764. // https://streams.spec.whatwg.org/#is-non-negative-number
  3765. bool is_non_negative_number(JS::Value value)
  3766. {
  3767. // 1. If Type(v) is not Number, return false.
  3768. if (!value.is_number())
  3769. return false;
  3770. // 2. If v is NaN, return false.
  3771. if (value.is_nan())
  3772. return false;
  3773. // 3. If v < 0, return false.
  3774. if (value.as_double() < 0.0)
  3775. return false;
  3776. // 4. Return true.
  3777. return true;
  3778. }
  3779. // https://streams.spec.whatwg.org/#can-transfer-array-buffer
  3780. bool can_transfer_array_buffer(JS::ArrayBuffer const& array_buffer)
  3781. {
  3782. // 1. Assert: Type(O) is Object.
  3783. // 2. Assert: O has an [[ArrayBufferData]] internal slot.
  3784. // 3. If ! IsDetachedBuffer(O) is true, return false.
  3785. if (array_buffer.is_detached())
  3786. return false;
  3787. // 4. If SameValue(O.[[ArrayBufferDetachKey]], undefined) is false, return false.
  3788. if (!JS::same_value(array_buffer.detach_key(), JS::js_undefined()))
  3789. return false;
  3790. // 5. Return true.
  3791. return true;
  3792. }
  3793. // https://streams.spec.whatwg.org/#abstract-opdef-cloneasuint8array
  3794. WebIDL::ExceptionOr<JS::Value> clone_as_uint8_array(JS::Realm& realm, WebIDL::ArrayBufferView& view)
  3795. {
  3796. auto& vm = realm.vm();
  3797. // 1. Assert: Type(O) is Object.
  3798. // 2. Assert: O has an [[ViewedArrayBuffer]] internal slot.
  3799. // 3. Assert: ! IsDetachedBuffer(O.[[ViewedArrayBuffer]]) is false.
  3800. VERIFY(!view.viewed_array_buffer()->is_detached());
  3801. // 4. Let buffer be ? CloneArrayBuffer(O.[[ViewedArrayBuffer]], O.[[ByteOffset]], O.[[ByteLength]], %ArrayBuffer%).
  3802. auto* buffer = TRY(JS::clone_array_buffer(vm, *view.viewed_array_buffer(), view.byte_offset(), view.byte_length()));
  3803. // 5. Let array be ! Construct(%Uint8Array%, « buffer »).
  3804. auto array = MUST(JS::construct(vm, *realm.intrinsics().uint8_array_constructor(), buffer));
  3805. // 5. Return array.
  3806. return array;
  3807. }
  3808. // https://streams.spec.whatwg.org/#abstract-opdef-structuredclone
  3809. WebIDL::ExceptionOr<JS::Value> structured_clone(JS::Realm& realm, JS::Value value)
  3810. {
  3811. auto& vm = realm.vm();
  3812. // 1. Let serialized be ? StructuredSerialize(v).
  3813. auto serialized = TRY(HTML::structured_serialize(vm, value));
  3814. // 2. Return ? StructuredDeserialize(serialized, the current Realm).
  3815. return TRY(HTML::structured_deserialize(vm, serialized, realm, {}));
  3816. }
  3817. // https://streams.spec.whatwg.org/#close-sentinel
  3818. // Non-standard function that implements the "close sentinel" value.
  3819. JS::Value create_close_sentinel()
  3820. {
  3821. // 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.
  3822. // 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.
  3823. return {};
  3824. }
  3825. // https://streams.spec.whatwg.org/#close-sentinel
  3826. // Non-standard function that implements the "If value is a close sentinel" check.
  3827. bool is_close_sentinel(JS::Value value)
  3828. {
  3829. return value.is_empty();
  3830. }
  3831. // Non-standard function to aid in converting a user-provided function into a WebIDL::Callback. This is essentially
  3832. // what the Bindings generator would do at compile time, but at runtime instead.
  3833. 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)
  3834. {
  3835. auto property = TRY(value.get(vm, property_key));
  3836. if (property.is_undefined())
  3837. return JS::Handle<WebIDL::CallbackType> {};
  3838. if (!property.is_function())
  3839. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAFunction, property.to_string_without_side_effects());
  3840. return vm.heap().allocate_without_realm<WebIDL::CallbackType>(property.as_object(), HTML::incumbent_settings_object(), operation_returns_promise);
  3841. }
  3842. // https://streams.spec.whatwg.org/#set-up-readable-byte-stream-controller-from-underlying-source
  3843. 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)
  3844. {
  3845. auto& realm = stream.realm();
  3846. // 1. Let controller be a new ReadableByteStreamController.
  3847. auto controller = stream.heap().allocate<ReadableByteStreamController>(realm, realm);
  3848. // 2. Let startAlgorithm be an algorithm that returns undefined.
  3849. auto start_algorithm = JS::create_heap_function(realm.heap(), []() -> WebIDL::ExceptionOr<JS::Value> { return JS::js_undefined(); });
  3850. // 3. Let pullAlgorithm be an algorithm that returns a promise resolved with undefined.
  3851. auto pull_algorithm = JS::create_heap_function(realm.heap(), [&realm]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  3852. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  3853. });
  3854. // 4. Let cancelAlgorithm be an algorithm that returns a promise resolved with undefined.
  3855. auto cancel_algorithm = JS::create_heap_function(realm.heap(), [&realm](JS::Value) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  3856. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  3857. });
  3858. // 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.
  3859. if (underlying_source_dict.start) {
  3860. start_algorithm = JS::create_heap_function(realm.heap(), [controller, underlying_source, callback = underlying_source_dict.start]() -> WebIDL::ExceptionOr<JS::Value> {
  3861. // Note: callback does not return a promise, so invoke_callback may return an abrupt completion
  3862. return TRY(WebIDL::invoke_callback(*callback, underlying_source, controller)).release_value();
  3863. });
  3864. }
  3865. // 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.
  3866. if (underlying_source_dict.pull) {
  3867. pull_algorithm = JS::create_heap_function(realm.heap(), [&realm, controller, underlying_source, callback = underlying_source_dict.pull]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  3868. // Note: callback return a promise, so invoke_callback will never return an abrupt completion
  3869. auto result = MUST_OR_THROW_OOM(WebIDL::invoke_callback(*callback, underlying_source, controller)).release_value();
  3870. return WebIDL::create_resolved_promise(realm, result);
  3871. });
  3872. }
  3873. // 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.
  3874. if (underlying_source_dict.cancel) {
  3875. cancel_algorithm = JS::create_heap_function(realm.heap(), [&realm, underlying_source, callback = underlying_source_dict.cancel](JS::Value reason) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  3876. // Note: callback return a promise, so invoke_callback will never return an abrupt completion
  3877. auto result = MUST_OR_THROW_OOM(WebIDL::invoke_callback(*callback, underlying_source, reason)).release_value();
  3878. return WebIDL::create_resolved_promise(realm, result);
  3879. });
  3880. }
  3881. // 8. Let autoAllocateChunkSize be underlyingSourceDict["autoAllocateChunkSize"], if it exists, or undefined otherwise.
  3882. auto auto_allocate_chunk_size = underlying_source_dict.auto_allocate_chunk_size.has_value()
  3883. ? JS::Value(underlying_source_dict.auto_allocate_chunk_size.value())
  3884. : JS::js_undefined();
  3885. // 9. If autoAllocateChunkSize is 0, then throw a TypeError exception.
  3886. if (auto_allocate_chunk_size.is_integral_number() && auto_allocate_chunk_size.as_double() == 0)
  3887. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot use an auto allocate chunk size of 0"sv };
  3888. // 10. Perform ? SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize).
  3889. return set_up_readable_byte_stream_controller(stream, controller, start_algorithm, pull_algorithm, cancel_algorithm, high_water_mark, auto_allocate_chunk_size);
  3890. }
  3891. }