AbstractOperations.cpp 252 KB

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