AbstractOperations.cpp 235 KB

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