AbstractOperations.cpp 242 KB

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