AbstractOperations.cpp 251 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485
  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 = [&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 = [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 = [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(move(chunk_steps), move(success_steps), move(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, 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 elementSize be pullIntoDescriptor.[[elementSize]].
  1314. auto element_size = pull_into_descriptor.element_size;
  1315. // 2. Let currentAlignedBytes be pullIntoDescriptor’s bytes filled − (pullIntoDescriptor’s bytes filled mod elementSize).
  1316. auto current_aligned_bytes = pull_into_descriptor.bytes_filled - (pull_into_descriptor.bytes_filled % pull_into_descriptor.element_size);
  1317. // 3. Let maxBytesToCopy be min(controller.[[queueTotalSize]], pullIntoDescriptor’s byte length − pullIntoDescriptor’s bytes filled).
  1318. auto max_bytes_to_copy = min(controller.queue_total_size(), pull_into_descriptor.byte_length - pull_into_descriptor.bytes_filled);
  1319. // 4. Let maxBytesFilled be pullIntoDescriptor’s bytes filled + maxBytesToCopy.
  1320. u64 max_bytes_filled = pull_into_descriptor.bytes_filled + max_bytes_to_copy;
  1321. // 5. Let maxAlignedBytes be maxBytesFilled − (maxBytesFilled mod elementSize).
  1322. auto max_aligned_bytes = max_bytes_filled - (max_bytes_filled % element_size);
  1323. // 6. Let totalBytesToCopyRemaining be maxBytesToCopy.
  1324. auto total_bytes_to_copy_remaining = max_bytes_to_copy;
  1325. // 7. Let ready be false.
  1326. bool ready = false;
  1327. // 8. If maxAlignedBytes > currentAlignedBytes,
  1328. if (max_aligned_bytes > current_aligned_bytes) {
  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. }
  1334. // 9. Let queue be controller.[[queue]].
  1335. auto& queue = controller.queue();
  1336. // 10. While totalBytesToCopyRemaining > 0,
  1337. while (total_bytes_to_copy_remaining > 0) {
  1338. // 1. Let headOfQueue be queue[0].
  1339. auto& head_of_queue = queue.first();
  1340. // 2. Let bytesToCopy be min(totalBytesToCopyRemaining, headOfQueue’s byte length).
  1341. auto bytes_to_copy = min(total_bytes_to_copy_remaining, head_of_queue.byte_length);
  1342. // 3. Let destStart be pullIntoDescriptor’s byte offset + pullIntoDescriptor’s bytes filled.
  1343. auto dest_start = pull_into_descriptor.byte_offset + pull_into_descriptor.bytes_filled;
  1344. // 4. Perform ! CopyDataBlockBytes(pullIntoDescriptor’s buffer.[[ArrayBufferData]], destStart, headOfQueue’s buffer.[[ArrayBufferData]], headOfQueue’s byte offset, bytesToCopy).
  1345. 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);
  1346. // 5. If headOfQueue’s byte length is bytesToCopy,
  1347. if (head_of_queue.byte_length == bytes_to_copy) {
  1348. // 1. Remove queue[0].
  1349. queue.take_first();
  1350. }
  1351. // 6. Otherwise,
  1352. else {
  1353. // 1. Set headOfQueue’s byte offset to headOfQueue’s byte offset + bytesToCopy.
  1354. head_of_queue.byte_offset += bytes_to_copy;
  1355. // 2. Set headOfQueue’s byte length to headOfQueue’s byte length − bytesToCopy.
  1356. head_of_queue.byte_length -= bytes_to_copy;
  1357. }
  1358. // 7. Set controller.[[queueTotalSize]] to controller.[[queueTotalSize]] − bytesToCopy.
  1359. controller.set_queue_total_size(controller.queue_total_size() - bytes_to_copy);
  1360. // 8, Perform ! ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor).
  1361. readable_byte_stream_controller_fill_head_pull_into_descriptor(controller, bytes_to_copy, pull_into_descriptor);
  1362. // 9. Set totalBytesToCopyRemaining to totalBytesToCopyRemaining − bytesToCopy.
  1363. total_bytes_to_copy_remaining -= bytes_to_copy;
  1364. }
  1365. // 11. If ready is false,
  1366. if (!ready) {
  1367. // 1. Assert: controller.[[queueTotalSize]] is 0.
  1368. VERIFY(controller.queue_total_size() == 0);
  1369. // 2. Assert: pullIntoDescriptor’s bytes filled > 0.
  1370. VERIFY(pull_into_descriptor.bytes_filled > 0);
  1371. // 3. Assert: pullIntoDescriptor’s bytes filled < pullIntoDescriptor’s element size.
  1372. VERIFY(pull_into_descriptor.bytes_filled < pull_into_descriptor.element_size);
  1373. }
  1374. // 12. Return ready.
  1375. return ready;
  1376. }
  1377. // https://streams.spec.whatwg.org/#readable-stream-default-reader-read
  1378. void readable_stream_default_reader_read(ReadableStreamDefaultReader& reader, ReadRequest& read_request)
  1379. {
  1380. // 1. Let stream be reader.[[stream]].
  1381. auto stream = reader.stream();
  1382. // 2. Assert: stream is not undefined.
  1383. VERIFY(stream);
  1384. // 3. Set stream.[[disturbed]] to true.
  1385. stream->set_disturbed(true);
  1386. // 4. If stream.[[state]] is "closed", perform readRequest’s close steps.
  1387. if (stream->is_closed()) {
  1388. read_request.on_close();
  1389. }
  1390. // 5. Otherwise, if stream.[[state]] is "errored", perform readRequest’s error steps given stream.[[storedError]].
  1391. else if (stream->is_errored()) {
  1392. read_request.on_error(stream->stored_error());
  1393. }
  1394. // 6. Otherwise,
  1395. else {
  1396. // 1. Assert: stream.[[state]] is "readable".
  1397. VERIFY(stream->is_readable());
  1398. // 2. Perform ! stream.[[controller]].[[PullSteps]](readRequest).
  1399. stream->controller()->visit([&](auto const& controller) {
  1400. return controller->pull_steps(read_request);
  1401. });
  1402. }
  1403. }
  1404. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-convert-pull-into-descriptor
  1405. JS::Value readable_byte_stream_controller_convert_pull_into_descriptor(JS::Realm& realm, PullIntoDescriptor const& pull_into_descriptor)
  1406. {
  1407. auto& vm = realm.vm();
  1408. // 1. Let bytesFilled be pullIntoDescriptor’s bytes filled.
  1409. auto bytes_filled = pull_into_descriptor.bytes_filled;
  1410. // 2. Let elementSize be pullIntoDescriptor’s element size.
  1411. auto element_size = pull_into_descriptor.element_size;
  1412. // 3. Assert: bytesFilled ≤ pullIntoDescriptor’s byte length.
  1413. VERIFY(bytes_filled <= pull_into_descriptor.byte_length);
  1414. // 4. Assert: bytesFilled mod elementSize is 0.
  1415. VERIFY(bytes_filled % element_size == 0);
  1416. // 5. Let buffer be ! TransferArrayBuffer(pullIntoDescriptor’s buffer).
  1417. auto buffer = MUST(transfer_array_buffer(realm, pull_into_descriptor.buffer));
  1418. // 6. Return ! Construct(pullIntoDescriptor’s view constructor, « buffer, pullIntoDescriptor’s byte offset, bytesFilled ÷ elementSize »).
  1419. return MUST(JS::construct(vm, *pull_into_descriptor.view_constructor, buffer, JS::Value(pull_into_descriptor.byte_offset), JS::Value(bytes_filled / element_size)));
  1420. }
  1421. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-pull-into
  1422. void readable_byte_stream_controller_pull_into(ReadableByteStreamController& controller, WebIDL::ArrayBufferView& view, ReadIntoRequest& read_into_request)
  1423. {
  1424. auto& vm = controller.vm();
  1425. auto& realm = controller.realm();
  1426. // 1. Let stream be controller.[[stream]].
  1427. auto stream = controller.stream();
  1428. // 2. Let elementSize be 1.
  1429. size_t element_size = 1;
  1430. // 3. Let ctor be %DataView%.
  1431. JS::NativeFunction* ctor = realm.intrinsics().data_view_constructor();
  1432. // 4. If view has a [[TypedArrayName]] internal slot (i.e., it is not a DataView),
  1433. if (view.bufferable_object().has<JS::NonnullGCPtr<JS::TypedArrayBase>>()) {
  1434. auto const& typed_array = *view.bufferable_object().get<JS::NonnullGCPtr<JS::TypedArrayBase>>();
  1435. // 1. Set elementSize to the element size specified in the typed array constructors table for view.[[TypedArrayName]].
  1436. element_size = typed_array.element_size();
  1437. // 2. Set ctor to the constructor specified in the typed array constructors table for view.[[TypedArrayName]].
  1438. switch (typed_array.kind()) {
  1439. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, Type) \
  1440. case JS::TypedArrayBase::Kind::ClassName: \
  1441. ctor = realm.intrinsics().snake_name##_constructor(); \
  1442. break;
  1443. JS_ENUMERATE_TYPED_ARRAYS
  1444. #undef __JS_ENUMERATE
  1445. }
  1446. }
  1447. // 5. Let byteOffset be view.[[ByteOffset]].
  1448. auto byte_offset = view.byte_offset();
  1449. // 6. Let byteLength be view.[[ByteLength]].
  1450. auto byte_length = view.byte_length();
  1451. // 7. Let bufferResult be TransferArrayBuffer(view.[[ViewedArrayBuffer]]).
  1452. auto buffer_result = transfer_array_buffer(realm, *view.viewed_array_buffer());
  1453. // 8. If bufferResult is an abrupt completion,
  1454. if (buffer_result.is_exception()) {
  1455. // 1. Perform readIntoRequest’s error steps, given bufferResult.[[Value]].
  1456. auto throw_completion = Bindings::dom_exception_to_throw_completion(vm, buffer_result.exception());
  1457. read_into_request.on_error(*throw_completion.release_value());
  1458. // 2. Return.
  1459. return;
  1460. }
  1461. // 9. Let buffer be bufferResult.[[Value]].
  1462. auto buffer = buffer_result.value();
  1463. // 10. Let pullIntoDescriptor be a new pull-into descriptor with buffer buffer, buffer byte length buffer.[[ArrayBufferByteLength]],
  1464. // byte offset byteOffset, byte length byteLength, bytes filled 0, element size elementSize, view constructor ctor, and reader type "byob".
  1465. PullIntoDescriptor pull_into_descriptor {
  1466. .buffer = buffer,
  1467. .buffer_byte_length = buffer->byte_length(),
  1468. .byte_offset = byte_offset,
  1469. .byte_length = byte_length,
  1470. .bytes_filled = 0,
  1471. .element_size = element_size,
  1472. .view_constructor = *ctor,
  1473. .reader_type = ReaderType::Byob,
  1474. };
  1475. // 11. If controller.[[pendingPullIntos]] is not empty,
  1476. if (!controller.pending_pull_intos().is_empty()) {
  1477. // 1. Append pullIntoDescriptor to controller.[[pendingPullIntos]].
  1478. controller.pending_pull_intos().append(pull_into_descriptor);
  1479. // 2. Perform ! ReadableStreamAddReadIntoRequest(stream, readIntoRequest).
  1480. readable_stream_add_read_into_request(*stream, read_into_request);
  1481. // 3. Return.
  1482. return;
  1483. }
  1484. // 12. If stream.[[state]] is "closed",
  1485. if (stream->is_closed()) {
  1486. // 1. Let emptyView be ! Construct(ctor, « pullIntoDescriptor’s buffer, pullIntoDescriptor’s byte offset, 0 »).
  1487. auto empty_view = MUST(JS::construct(vm, *ctor, pull_into_descriptor.buffer, JS::Value(pull_into_descriptor.byte_offset), JS::Value(0)));
  1488. // 2. Perform readIntoRequest’s close steps, given emptyView.
  1489. read_into_request.on_close(empty_view);
  1490. // 3. Return.
  1491. return;
  1492. }
  1493. // 13. If controller.[[queueTotalSize]] > 0,
  1494. if (controller.queue_total_size() > 0) {
  1495. // 1. If ! ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) is true,
  1496. if (readable_byte_stream_controller_fill_pull_into_descriptor_from_queue(controller, pull_into_descriptor)) {
  1497. // 1. Let filledView be ! ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor).
  1498. auto filled_view = readable_byte_stream_controller_convert_pull_into_descriptor(realm, pull_into_descriptor);
  1499. // 2. Perform ! ReadableByteStreamControllerHandleQueueDrain(controller).
  1500. readable_byte_stream_controller_handle_queue_drain(controller);
  1501. // 3. Perform readIntoRequest’s chunk steps, given filledView.
  1502. read_into_request.on_chunk(filled_view);
  1503. // 4. Return.
  1504. return;
  1505. }
  1506. // 2. If controller.[[closeRequested]] is true,
  1507. if (controller.close_requested()) {
  1508. // 1. Let e be a TypeError exception.
  1509. auto error = JS::TypeError::create(realm, "Reader has been released"sv);
  1510. // 2. Perform ! ReadableByteStreamControllerError(controller, e).
  1511. readable_byte_stream_controller_error(controller, error);
  1512. // 3. Perform readIntoRequest’s error steps, given e.
  1513. read_into_request.on_error(error);
  1514. // 4. Return.
  1515. return;
  1516. }
  1517. }
  1518. // 14. Append pullIntoDescriptor to controller.[[pendingPullIntos]].
  1519. controller.pending_pull_intos().append(pull_into_descriptor);
  1520. // 15. Perform ! ReadableStreamAddReadIntoRequest(stream, readIntoRequest).
  1521. readable_stream_add_read_into_request(*stream, read_into_request);
  1522. // 16. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
  1523. readable_byte_stream_controller_call_pull_if_needed(controller);
  1524. }
  1525. // https://streams.spec.whatwg.org/#readable-stream-byob-reader-read
  1526. void readable_stream_byob_reader_read(ReadableStreamBYOBReader& reader, WebIDL::ArrayBufferView& view, ReadIntoRequest& read_into_request)
  1527. {
  1528. // 1. Let stream be reader.[[stream]].
  1529. auto stream = reader.stream();
  1530. // 2. Assert: stream is not undefined.
  1531. VERIFY(stream);
  1532. // 3. Set stream.[[disturbed]] to true.
  1533. stream->set_disturbed(true);
  1534. // 4. If stream.[[state]] is "errored", perform readIntoRequest’s error steps given stream.[[storedError]].
  1535. if (stream->is_errored()) {
  1536. read_into_request.on_error(stream->stored_error());
  1537. }
  1538. // 5. Otherwise, perform ! ReadableByteStreamControllerPullInto(stream.[[controller]], view, readIntoRequest).
  1539. else {
  1540. readable_byte_stream_controller_pull_into(*stream->controller()->get<JS::NonnullGCPtr<ReadableByteStreamController>>(), view, read_into_request);
  1541. }
  1542. }
  1543. // https://streams.spec.whatwg.org/#abstract-opdef-readablestreamdefaultreaderrelease
  1544. void readable_stream_default_reader_release(ReadableStreamDefaultReader& reader)
  1545. {
  1546. auto& realm = reader.realm();
  1547. // 1. Perform ! ReadableStreamReaderGenericRelease(reader).
  1548. readable_stream_reader_generic_release(reader);
  1549. // 2. Let e be a new TypeError exception.
  1550. auto exception = JS::TypeError::create(realm, "Reader has been released"sv);
  1551. // 3. Perform ! ReadableStreamDefaultReaderErrorReadRequests(reader, e).
  1552. readable_stream_default_reader_error_read_requests(reader, exception);
  1553. }
  1554. // https://streams.spec.whatwg.org/#abstract-opdef-readablestreambyobreaderrelease
  1555. void readable_stream_byob_reader_release(ReadableStreamBYOBReader& reader)
  1556. {
  1557. auto& realm = reader.realm();
  1558. // 1. Perform ! ReadableStreamReaderGenericRelease(reader).
  1559. readable_stream_reader_generic_release(reader);
  1560. // 2. Let e be a new TypeError exception.
  1561. auto exception = JS::TypeError::create(realm, "Reader has been released"sv);
  1562. // 3. Perform ! ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e).
  1563. readable_stream_byob_reader_error_read_into_requests(reader, exception);
  1564. }
  1565. // https://streams.spec.whatwg.org/#set-up-readable-stream-default-reader
  1566. WebIDL::ExceptionOr<void> set_up_readable_stream_default_reader(ReadableStreamDefaultReader& reader, ReadableStream& stream)
  1567. {
  1568. // 1. If ! IsReadableStreamLocked(stream) is true, throw a TypeError exception.
  1569. if (is_readable_stream_locked(stream))
  1570. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot create stream reader for a locked stream"sv };
  1571. // 2. Perform ! ReadableStreamReaderGenericInitialize(reader, stream).
  1572. // 3. Set reader.[[readRequests]] to a new empty list.
  1573. readable_stream_reader_generic_initialize(ReadableStreamReader { reader }, stream);
  1574. return {};
  1575. }
  1576. // https://streams.spec.whatwg.org/#set-up-readable-stream-byob-reader
  1577. WebIDL::ExceptionOr<void> set_up_readable_stream_byob_reader(ReadableStreamBYOBReader& reader, ReadableStream& stream)
  1578. {
  1579. // 1. If ! IsReadableStreamLocked(stream) is true, throw a TypeError exception.
  1580. if (is_readable_stream_locked(stream))
  1581. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot create stream reader for a locked stream"sv };
  1582. // 2. If stream.[[controller]] does not implement ReadableByteStreamController, throw a TypeError exception.
  1583. if (!stream.controller()->has<JS::NonnullGCPtr<ReadableByteStreamController>>())
  1584. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "BYOB reader cannot set up reader from non-byte stream"sv };
  1585. // 3. Perform ! ReadableStreamReaderGenericInitialize(reader, stream).
  1586. readable_stream_reader_generic_initialize(ReadableStreamReader { reader }, stream);
  1587. // 4. Set reader.[[readIntoRequests]] to a new empty list.
  1588. reader.read_into_requests().clear();
  1589. return {};
  1590. }
  1591. // https://streams.spec.whatwg.org/#readable-stream-default-controller-close
  1592. void readable_stream_default_controller_close(ReadableStreamDefaultController& controller)
  1593. {
  1594. // 1. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) is false, return.
  1595. if (!readable_stream_default_controller_can_close_or_enqueue(controller))
  1596. return;
  1597. // 2. Let stream be controller.[[stream]].
  1598. auto stream = controller.stream();
  1599. // 3. Set controller.[[closeRequested]] to true.
  1600. controller.set_close_requested(true);
  1601. // 4. If controller.[[queue]] is empty,
  1602. if (controller.queue().is_empty()) {
  1603. // 1. Perform ! ReadableStreamDefaultControllerClearAlgorithms(controller).
  1604. readable_stream_default_controller_clear_algorithms(controller);
  1605. // 2. Perform ! ReadableStreamClose(stream).
  1606. readable_stream_close(*stream);
  1607. }
  1608. }
  1609. // https://streams.spec.whatwg.org/#rs-default-controller-has-backpressure
  1610. bool readable_stream_default_controller_has_backpressure(ReadableStreamDefaultController& controller)
  1611. {
  1612. // 1. If ! ReadableStreamDefaultControllerShouldCallPull(controller) is true, return false.
  1613. if (readable_stream_default_controller_should_call_pull(controller))
  1614. return false;
  1615. // 2. Otherwise, return true.
  1616. return true;
  1617. }
  1618. // https://streams.spec.whatwg.org/#readable-stream-default-controller-enqueue
  1619. WebIDL::ExceptionOr<void> readable_stream_default_controller_enqueue(ReadableStreamDefaultController& controller, JS::Value chunk)
  1620. {
  1621. auto& vm = controller.vm();
  1622. // 1. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) is false, return.
  1623. if (!readable_stream_default_controller_can_close_or_enqueue(controller))
  1624. return {};
  1625. // 2. Let stream be controller.[[stream]].
  1626. auto stream = controller.stream();
  1627. // 3. If ! IsReadableStreamLocked(stream) is true and ! ReadableStreamGetNumReadRequests(stream) > 0, perform ! ReadableStreamFulfillReadRequest(stream, chunk, false).
  1628. if (is_readable_stream_locked(*stream) && readable_stream_get_num_read_requests(*stream) > 0) {
  1629. readable_stream_fulfill_read_request(*stream, chunk, false);
  1630. }
  1631. // 4. Otherwise,
  1632. else {
  1633. // 1. Let result be the result of performing controller.[[strategySizeAlgorithm]], passing in chunk, and interpreting the result as a completion record.
  1634. auto result = controller.strategy_size_algorithm()->function()(chunk);
  1635. // 2. If result is an abrupt completion,
  1636. if (result.is_abrupt()) {
  1637. // 1. Perform ! ReadableStreamDefaultControllerError(controller, result.[[Value]]).
  1638. readable_stream_default_controller_error(controller, result.value().value());
  1639. // 2. Return result.
  1640. return result;
  1641. }
  1642. // 3. Let chunkSize be result.[[Value]].
  1643. auto chunk_size = result.release_value().release_value();
  1644. // 4. Let enqueueResult be EnqueueValueWithSize(controller, chunk, chunkSize).
  1645. auto enqueue_result = enqueue_value_with_size(controller, chunk, chunk_size);
  1646. // 5. If enqueueResult is an abrupt completion,
  1647. if (enqueue_result.is_error()) {
  1648. auto throw_completion = Bindings::throw_dom_exception_if_needed(vm, [&] { return enqueue_result; }).throw_completion();
  1649. // 1. Perform ! ReadableStreamDefaultControllerError(controller, enqueueResult.[[Value]]).
  1650. readable_stream_default_controller_error(controller, throw_completion.value().value());
  1651. // 2. Return enqueueResult.
  1652. // Note: We need to return the throw_completion object here, as enqueue needs to throw the same object that the controller is errored with
  1653. return throw_completion;
  1654. }
  1655. }
  1656. // 5. Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(controller).
  1657. readable_stream_default_controller_can_pull_if_needed(controller);
  1658. return {};
  1659. }
  1660. // https://streams.spec.whatwg.org/#readable-stream-default-controller-call-pull-if-needed
  1661. void readable_stream_default_controller_can_pull_if_needed(ReadableStreamDefaultController& controller)
  1662. {
  1663. // 1. Let shouldPull be ! ReadableStreamDefaultControllerShouldCallPull(controller).
  1664. auto should_pull = readable_stream_default_controller_should_call_pull(controller);
  1665. // 2. If shouldPull is false, return.
  1666. if (!should_pull)
  1667. return;
  1668. // 3. If controller.[[pulling]] is true,
  1669. if (controller.pulling()) {
  1670. // 1. Set controller.[[pullAgain]] to true.
  1671. controller.set_pull_again(true);
  1672. // 2. Return.
  1673. return;
  1674. }
  1675. // 4. Assert: controller.[[pullAgain]] is false.
  1676. VERIFY(!controller.pull_again());
  1677. // 5. Set controller.[[pulling]] to true.
  1678. controller.set_pulling(true);
  1679. // 6. Let pullPromise be the result of performing controller.[[pullAlgorithm]].
  1680. auto pull_promise = controller.pull_algorithm()->function()();
  1681. // 7. Upon fulfillment of pullPromise,
  1682. WebIDL::upon_fulfillment(*pull_promise, JS::create_heap_function(controller.heap(), [&controller](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {
  1683. // 1. Set controller.[[pulling]] to false.
  1684. controller.set_pulling(false);
  1685. // 2. If controller.[[pullAgain]] is true,
  1686. if (controller.pull_again()) {
  1687. // 1. Set controller.[[pullAgain]] to false.
  1688. controller.set_pull_again(false);
  1689. // 2. Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(controller).
  1690. readable_stream_default_controller_can_pull_if_needed(controller);
  1691. }
  1692. return JS::js_undefined();
  1693. }));
  1694. // 8. Upon rejection of pullPromise with reason e,
  1695. WebIDL::upon_rejection(*pull_promise, JS::create_heap_function(controller.heap(), [&controller](JS::Value e) -> WebIDL::ExceptionOr<JS::Value> {
  1696. // 1. Perform ! ReadableStreamDefaultControllerError(controller, e).
  1697. readable_stream_default_controller_error(controller, e);
  1698. return JS::js_undefined();
  1699. }));
  1700. }
  1701. // https://streams.spec.whatwg.org/#readable-stream-default-controller-should-call-pull
  1702. bool readable_stream_default_controller_should_call_pull(ReadableStreamDefaultController& controller)
  1703. {
  1704. // 1. Let stream be controller.[[stream]].
  1705. auto stream = controller.stream();
  1706. // 2. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) is false, return false.
  1707. if (!readable_stream_default_controller_can_close_or_enqueue(controller))
  1708. return false;
  1709. // 3. If controller.[[started]] is false, return false.
  1710. if (!controller.started())
  1711. return false;
  1712. // 4. If ! IsReadableStreamLocked(stream) is true and ! ReadableStreamGetNumReadRequests(stream) > 0, return true.
  1713. if (is_readable_stream_locked(*stream) && readable_stream_get_num_read_requests(*stream) > 0)
  1714. return true;
  1715. // 5. Let desiredSize be ! ReadableStreamDefaultControllerGetDesiredSize(controller).
  1716. auto desired_size = readable_stream_default_controller_get_desired_size(controller);
  1717. // 6. Assert: desiredSize is not null.
  1718. VERIFY(desired_size.has_value());
  1719. // 7. If desiredSize > 0, return true.
  1720. if (desired_size.release_value() > 0.0)
  1721. return true;
  1722. // 8. Return false.
  1723. return false;
  1724. }
  1725. // https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollergetbyobrequest
  1726. JS::GCPtr<ReadableStreamBYOBRequest> readable_byte_stream_controller_get_byob_request(JS::NonnullGCPtr<ReadableByteStreamController> controller)
  1727. {
  1728. auto& vm = controller->vm();
  1729. auto& realm = controller->realm();
  1730. // 1. If controller.[[byobRequest]] is null and controller.[[pendingPullIntos]] is not empty,
  1731. if (!controller->raw_byob_request() && !controller->pending_pull_intos().is_empty()) {
  1732. // 1. Let firstDescriptor be controller.[[pendingPullIntos]][0].
  1733. auto const& first_descriptor = controller->pending_pull_intos().first();
  1734. // 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 »).
  1735. 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)));
  1736. // 3. Let byobRequest be a new ReadableStreamBYOBRequest.
  1737. auto byob_request = realm.heap().allocate<ReadableStreamBYOBRequest>(realm, realm);
  1738. // 4. Set byobRequest.[[controller]] to controller.
  1739. byob_request->set_controller(controller);
  1740. // 5. Set byobRequest.[[view]] to view.
  1741. auto array_buffer_view = vm.heap().allocate<WebIDL::ArrayBufferView>(realm, view);
  1742. byob_request->set_view(array_buffer_view);
  1743. // 6. Set controller.[[byobRequest]] to byobRequest.
  1744. controller->set_byob_request(byob_request);
  1745. }
  1746. // 2. Return controller.[[byobRequest]].
  1747. return controller->raw_byob_request();
  1748. }
  1749. // https://streams.spec.whatwg.org/#readable-stream-default-controller-clear-algorithms
  1750. void readable_stream_default_controller_clear_algorithms(ReadableStreamDefaultController& controller)
  1751. {
  1752. // 1. Set controller.[[pullAlgorithm]] to undefined.
  1753. controller.set_pull_algorithm({});
  1754. // 2. Set controller.[[cancelAlgorithm]] to undefined.
  1755. controller.set_cancel_algorithm({});
  1756. // 3. Set controller.[[strategySizeAlgorithm]] to undefined.
  1757. controller.set_strategy_size_algorithm({});
  1758. }
  1759. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-respond-in-readable-state
  1760. WebIDL::ExceptionOr<void> readable_byte_stream_controller_respond_in_readable_state(ReadableByteStreamController& controller, u64 bytes_written, PullIntoDescriptor& pull_into_descriptor)
  1761. {
  1762. // 1. Assert: pullIntoDescriptor’s bytes filled + bytesWritten ≤ pullIntoDescriptor’s byte length.
  1763. VERIFY(pull_into_descriptor.bytes_filled + bytes_written <= pull_into_descriptor.byte_length);
  1764. // 2. Perform ! ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor).
  1765. readable_byte_stream_controller_fill_head_pull_into_descriptor(controller, bytes_written, pull_into_descriptor);
  1766. // 3. If pullIntoDescriptor’s reader type is "none",
  1767. if (pull_into_descriptor.reader_type == ReaderType::None) {
  1768. // 1. Perform ? ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor).
  1769. TRY(readable_byte_stream_controller_enqueue_detached_pull_into_queue(controller, pull_into_descriptor));
  1770. // 2. Perform ! ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller).
  1771. readable_byte_stream_controller_process_pull_into_descriptors_using_queue(controller);
  1772. // 3. Return.
  1773. return {};
  1774. }
  1775. // 4. If pullIntoDescriptor’s bytes filled < pullIntoDescriptor’s minimum fill, return.
  1776. // FIXME: Support minimum fill.
  1777. if (pull_into_descriptor.bytes_filled < pull_into_descriptor.element_size)
  1778. return {};
  1779. // 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.
  1780. // 5. Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).
  1781. // NOTE: We need to take a copy of pull_into_descriptor here as the shift destroys the pull into descriptor we are given.
  1782. auto pull_into_descriptor_copy = readable_byte_stream_controller_shift_pending_pull_into(controller);
  1783. // 6. Let remainderSize be the remainder after dividing pullIntoDescriptor’s bytes filled by pullIntoDescriptor’s element size.
  1784. auto remainder_size = pull_into_descriptor_copy.bytes_filled % pull_into_descriptor_copy.element_size;
  1785. // 7. If remainderSize > 0,
  1786. if (remainder_size > 0) {
  1787. // 1. Let end be pullIntoDescriptor’s byte offset + pullIntoDescriptor’s bytes filled.
  1788. auto end = pull_into_descriptor_copy.byte_offset + pull_into_descriptor_copy.bytes_filled;
  1789. // 2. Perform ? ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor’s buffer, end − remainderSize, remainderSize).
  1790. TRY(readable_byte_stream_controller_enqueue_cloned_chunk_to_queue(controller, *pull_into_descriptor_copy.buffer, end - remainder_size, remainder_size));
  1791. }
  1792. // 8. Set pullIntoDescriptor’s bytes filled to pullIntoDescriptor’s bytes filled − remainderSize.
  1793. pull_into_descriptor_copy.bytes_filled -= remainder_size;
  1794. // 9. Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(controller.[[stream]], pullIntoDescriptor).
  1795. readable_byte_stream_controller_commit_pull_into_descriptor(*controller.stream(), pull_into_descriptor_copy);
  1796. return {};
  1797. }
  1798. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-respond-in-closed-state
  1799. void readable_byte_stream_controller_respond_in_closed_state(ReadableByteStreamController& controller, PullIntoDescriptor& first_descriptor)
  1800. {
  1801. // 1. Assert: the remainder after dividing firstDescriptor’s bytes filled by firstDescriptor’s element size is 0.
  1802. VERIFY(first_descriptor.bytes_filled % first_descriptor.element_size == 0);
  1803. // 2. If firstDescriptor’s reader type is "none", perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).
  1804. if (first_descriptor.reader_type == ReaderType::None)
  1805. readable_byte_stream_controller_shift_pending_pull_into(controller);
  1806. // 3. Let stream be controller.[[stream]].
  1807. auto& stream = *controller.stream();
  1808. // 4. If ! ReadableStreamHasBYOBReader(stream) is true,
  1809. if (readable_stream_has_byob_reader(stream)) {
  1810. // 1. While ! ReadableStreamGetNumReadIntoRequests(stream) > 0,
  1811. while (readable_stream_get_num_read_into_requests(stream) > 0) {
  1812. // 1. Let pullIntoDescriptor be ! ReadableByteStreamControllerShiftPendingPullInto(controller).
  1813. auto pull_into_descriptor = readable_byte_stream_controller_shift_pending_pull_into(controller);
  1814. // 2. Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor).
  1815. readable_byte_stream_controller_commit_pull_into_descriptor(stream, pull_into_descriptor);
  1816. }
  1817. }
  1818. }
  1819. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-respond-internal
  1820. WebIDL::ExceptionOr<void> readable_byte_stream_controller_respond_internal(ReadableByteStreamController& controller, u64 bytes_written)
  1821. {
  1822. // 1. Let firstDescriptor be controller.[[pendingPullIntos]][0].
  1823. auto& first_descriptor = controller.pending_pull_intos().first();
  1824. // 2. Assert: ! CanTransferArrayBuffer(firstDescriptor’s buffer) is true.
  1825. VERIFY(can_transfer_array_buffer(*first_descriptor.buffer));
  1826. // 3. Perform ! ReadableByteStreamControllerInvalidateBYOBRequest(controller).
  1827. readable_byte_stream_controller_invalidate_byob_request(controller);
  1828. // 4. Let state be controller.[[stream]].[[state]].
  1829. auto state = controller.stream()->state();
  1830. // 5. If state is "closed",
  1831. if (state == ReadableStream::State::Closed) {
  1832. // 1. Assert: bytesWritten is 0.
  1833. VERIFY(bytes_written == 0);
  1834. // 2. Perform ! ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor).
  1835. readable_byte_stream_controller_respond_in_closed_state(controller, first_descriptor);
  1836. }
  1837. // 6. Otherwise,
  1838. else {
  1839. // 1. Assert: state is "readable".
  1840. VERIFY(state == ReadableStream::State::Readable);
  1841. // 2. Assert: bytesWritten > 0.
  1842. VERIFY(bytes_written > 0);
  1843. // 3. Perform ? ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor).
  1844. TRY(readable_byte_stream_controller_respond_in_readable_state(controller, bytes_written, first_descriptor));
  1845. }
  1846. // 7. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
  1847. readable_byte_stream_controller_call_pull_if_needed(controller);
  1848. return {};
  1849. }
  1850. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-respond
  1851. WebIDL::ExceptionOr<void> readable_byte_stream_controller_respond(ReadableByteStreamController& controller, u64 bytes_written)
  1852. {
  1853. auto& realm = controller.realm();
  1854. // 1. Assert: controller.[[pendingPullIntos]] is not empty.
  1855. VERIFY(!controller.pending_pull_intos().is_empty());
  1856. // 2. Let firstDescriptor be controller.[[pendingPullIntos]][0].
  1857. auto& first_descriptor = controller.pending_pull_intos().first();
  1858. // 3. Let state be controller.[[stream]].[[state]].
  1859. auto state = controller.stream()->state();
  1860. // 4. If state is "closed",
  1861. if (state == ReadableStream::State::Closed) {
  1862. // 1. If bytesWritten is not 0, throw a TypeError exception.
  1863. if (bytes_written != 0)
  1864. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Bytes written is not zero for closed stream"sv };
  1865. }
  1866. // 5. Otherwise,
  1867. else {
  1868. // 1. Assert: state is "readable".
  1869. VERIFY(state == ReadableStream::State::Readable);
  1870. // 2. If bytesWritten is 0, throw a TypeError exception.
  1871. if (bytes_written == 0)
  1872. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Bytes written is zero for stream which is not closed"sv };
  1873. // 3. If firstDescriptor’s bytes filled + bytesWritten > firstDescriptor’s byte length, throw a RangeError exception.
  1874. if (first_descriptor.bytes_filled + bytes_written > first_descriptor.byte_length)
  1875. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Bytes written is greater than the pull requests byte length"sv };
  1876. }
  1877. // 6. Set firstDescriptor’s buffer to ! TransferArrayBuffer(firstDescriptor’s buffer).
  1878. first_descriptor.buffer = MUST(transfer_array_buffer(realm, *first_descriptor.buffer));
  1879. // 7. Perform ? ReadableByteStreamControllerRespondInternal(controller, bytesWritten).
  1880. return readable_byte_stream_controller_respond_internal(controller, bytes_written);
  1881. }
  1882. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-respond-with-new-view
  1883. WebIDL::ExceptionOr<void> readable_byte_stream_controller_respond_with_new_view(JS::Realm& realm, ReadableByteStreamController& controller, WebIDL::ArrayBufferView& view)
  1884. {
  1885. // 1. Assert: controller.[[pendingPullIntos]] is not empty.
  1886. VERIFY(!controller.pending_pull_intos().is_empty());
  1887. // 2. Assert: ! IsDetachedBuffer(view.[[ViewedArrayBuffer]]) is false.
  1888. VERIFY(!view.viewed_array_buffer()->is_detached());
  1889. // 3. Let firstDescriptor be controller.[[pendingPullIntos]][0].
  1890. auto& first_descriptor = controller.pending_pull_intos().first();
  1891. // 4. Let state be controller.[[stream]].[[state]].
  1892. auto state = controller.stream()->state();
  1893. // 5. If state is "closed",
  1894. if (state == ReadableStream::State::Closed) {
  1895. // 1. If view.[[ByteLength]] is not 0, throw a TypeError exception.
  1896. if (view.byte_length() != 0)
  1897. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Byte length is not zero for closed stream"sv };
  1898. }
  1899. // 6. Otherwise,
  1900. else {
  1901. // 1. Assert: state is "readable".
  1902. VERIFY(state == ReadableStream::State::Readable);
  1903. // 2. If view.[[ByteLength]] is 0, throw a TypeError exception.
  1904. if (view.byte_length() == 0)
  1905. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Byte length is zero for stream which is not closed"sv };
  1906. }
  1907. // 7. If firstDescriptor’s byte offset + firstDescriptor’ bytes filled is not view.[[ByteOffset]], throw a RangeError exception.
  1908. if (first_descriptor.byte_offset + first_descriptor.bytes_filled != view.byte_offset())
  1909. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Byte offset is not aligned with the pull request's byte offset"sv };
  1910. // 8. If firstDescriptor’s buffer byte length is not view.[[ViewedArrayBuffer]].[[ByteLength]], throw a RangeError exception.
  1911. if (first_descriptor.buffer_byte_length != view.viewed_array_buffer()->byte_length())
  1912. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Buffer byte length is not aligned with the pull request's byte length"sv };
  1913. // 9. If firstDescriptor’s bytes filled + view.[[ByteLength]] > firstDescriptor’s byte length, throw a RangeError exception.
  1914. if (first_descriptor.bytes_filled + view.byte_length() > first_descriptor.byte_length)
  1915. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Byte length is greater than the pull request's byte length"sv };
  1916. // 10. Let viewByteLength be view.[[ByteLength]].
  1917. auto view_byte_length = view.byte_length();
  1918. // 11. Set firstDescriptor’s buffer to ? TransferArrayBuffer(view.[[ViewedArrayBuffer]]).
  1919. first_descriptor.buffer = TRY(transfer_array_buffer(realm, *view.viewed_array_buffer()));
  1920. // 12. Perform ? ReadableByteStreamControllerRespondInternal(controller, viewByteLength).
  1921. TRY(readable_byte_stream_controller_respond_internal(controller, view_byte_length));
  1922. return {};
  1923. }
  1924. // https://streams.spec.whatwg.org/#readable-stream-default-controller-error
  1925. void readable_stream_default_controller_error(ReadableStreamDefaultController& controller, JS::Value error)
  1926. {
  1927. // 1. Let stream be controller.[[stream]].
  1928. auto stream = controller.stream();
  1929. // 2. If stream.[[state]] is not "readable", return.
  1930. if (!stream->is_readable())
  1931. return;
  1932. // 3. Perform ! ResetQueue(controller).
  1933. reset_queue(controller);
  1934. // 4. Perform ! ReadableStreamDefaultControllerClearAlgorithms(controller).
  1935. readable_stream_default_controller_clear_algorithms(controller);
  1936. // 5. Perform ! ReadableStreamError(stream, e).
  1937. readable_stream_error(*stream, error);
  1938. }
  1939. // https://streams.spec.whatwg.org/#readable-stream-default-controller-get-desired-size
  1940. Optional<double> readable_stream_default_controller_get_desired_size(ReadableStreamDefaultController& controller)
  1941. {
  1942. auto stream = controller.stream();
  1943. // 1. Let state be controller.[[stream]].[[state]].
  1944. // 2. If state is "errored", return null.
  1945. if (stream->is_errored())
  1946. return {};
  1947. // 3. If state is "closed", return 0.
  1948. if (stream->is_closed())
  1949. return 0.0;
  1950. // 4. Return controller.[[strategyHWM]] − controller.[[queueTotalSize]].
  1951. return controller.strategy_hwm() - controller.queue_total_size();
  1952. }
  1953. // https://streams.spec.whatwg.org/#readable-stream-default-controller-can-close-or-enqueue
  1954. bool readable_stream_default_controller_can_close_or_enqueue(ReadableStreamDefaultController& controller)
  1955. {
  1956. // 1. Let state be controller.[[stream]].[[state]].
  1957. // 2. If controller.[[closeRequested]] is false and state is "readable", return true.
  1958. // 3. Otherwise, return false.
  1959. return !controller.close_requested() && controller.stream()->is_readable();
  1960. }
  1961. // https://streams.spec.whatwg.org/#set-up-readable-stream-default-controller
  1962. 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)
  1963. {
  1964. auto& realm = stream.realm();
  1965. // 1. Assert: stream.[[controller]] is undefined.
  1966. VERIFY(!stream.controller().has_value());
  1967. // 2. Set controller.[[stream]] to stream.
  1968. controller.set_stream(stream);
  1969. // 3. Perform ! ResetQueue(controller).
  1970. reset_queue(controller);
  1971. // 4. Set controller.[[started]], controller.[[closeRequested]], controller.[[pullAgain]], and controller.[[pulling]] to false.
  1972. controller.set_started(false);
  1973. controller.set_close_requested(false);
  1974. controller.set_pull_again(false);
  1975. controller.set_pulling(false);
  1976. // 5. Set controller.[[strategySizeAlgorithm]] to sizeAlgorithm and controller.[[strategyHWM]] to highWaterMark.
  1977. controller.set_strategy_size_algorithm(size_algorithm);
  1978. controller.set_strategy_hwm(high_water_mark);
  1979. // 6. Set controller.[[pullAlgorithm]] to pullAlgorithm.
  1980. controller.set_pull_algorithm(pull_algorithm);
  1981. // 7. Set controller.[[cancelAlgorithm]] to cancelAlgorithm.
  1982. controller.set_cancel_algorithm(cancel_algorithm);
  1983. // 8. Set stream.[[controller]] to controller.
  1984. stream.set_controller(ReadableStreamController { controller });
  1985. // 9. Let startResult be the result of performing startAlgorithm. (This might throw an exception.)
  1986. auto start_result = TRY(start_algorithm->function()());
  1987. // 10. Let startPromise be a promise resolved with startResult.
  1988. auto start_promise = WebIDL::create_resolved_promise(realm, start_result);
  1989. // 11. Upon fulfillment of startPromise,
  1990. WebIDL::upon_fulfillment(start_promise, JS::create_heap_function(controller.heap(), [&controller](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {
  1991. // 1. Set controller.[[started]] to true.
  1992. controller.set_started(true);
  1993. // 2. Assert: controller.[[pulling]] is false.
  1994. VERIFY(!controller.pulling());
  1995. // 3. Assert: controller.[[pullAgain]] is false.
  1996. VERIFY(!controller.pull_again());
  1997. // 4. Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(controller).
  1998. readable_stream_default_controller_can_pull_if_needed(controller);
  1999. return JS::js_undefined();
  2000. }));
  2001. // 12. Upon rejection of startPromise with reason r,
  2002. WebIDL::upon_rejection(start_promise, JS::create_heap_function(controller.heap(), [&controller](JS::Value r) -> WebIDL::ExceptionOr<JS::Value> {
  2003. // 1. Perform ! ReadableStreamDefaultControllerError(controller, r).
  2004. readable_stream_default_controller_error(controller, r);
  2005. return JS::js_undefined();
  2006. }));
  2007. return {};
  2008. }
  2009. // https://streams.spec.whatwg.org/#set-up-readable-stream-default-controller-from-underlying-source
  2010. 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)
  2011. {
  2012. auto& realm = stream.realm();
  2013. // 1. Let controller be a new ReadableStreamDefaultController.
  2014. auto controller = stream.heap().allocate<ReadableStreamDefaultController>(realm, realm);
  2015. // 2. Let startAlgorithm be an algorithm that returns undefined.
  2016. auto start_algorithm = JS::create_heap_function(realm.heap(), []() -> WebIDL::ExceptionOr<JS::Value> {
  2017. return JS::js_undefined();
  2018. });
  2019. // 3. Let pullAlgorithm be an algorithm that returns a promise resolved with undefined.
  2020. auto pull_algorithm = JS::create_heap_function(realm.heap(), [&realm]() {
  2021. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2022. });
  2023. // 4. Let cancelAlgorithm be an algorithm that returns a promise resolved with undefined.
  2024. auto cancel_algorithm = JS::create_heap_function(realm.heap(), [&realm](JS::Value) {
  2025. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2026. });
  2027. // 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.
  2028. if (underlying_source.start) {
  2029. start_algorithm = JS::create_heap_function(realm.heap(), [controller, underlying_source_value, callback = underlying_source.start]() -> WebIDL::ExceptionOr<JS::Value> {
  2030. // Note: callback does not return a promise, so invoke_callback may return an abrupt completion
  2031. return TRY(WebIDL::invoke_callback(*callback, underlying_source_value, controller)).release_value();
  2032. });
  2033. }
  2034. // 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.
  2035. if (underlying_source.pull) {
  2036. pull_algorithm = JS::create_heap_function(realm.heap(), [&realm, controller, underlying_source_value, callback = underlying_source.pull]() {
  2037. // Note: callback returns a promise, so invoke_callback will never return an abrupt completion
  2038. auto result = MUST(WebIDL::invoke_callback(*callback, underlying_source_value, controller)).release_value();
  2039. return WebIDL::create_resolved_promise(realm, result);
  2040. });
  2041. }
  2042. // 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.
  2043. if (underlying_source.cancel) {
  2044. cancel_algorithm = JS::create_heap_function(realm.heap(), [&realm, underlying_source_value, callback = underlying_source.cancel](JS::Value reason) {
  2045. // Note: callback returns a promise, so invoke_callback will never return an abrupt completion
  2046. auto result = MUST(WebIDL::invoke_callback(*callback, underlying_source_value, reason)).release_value();
  2047. return WebIDL::create_resolved_promise(realm, result);
  2048. });
  2049. }
  2050. // 8. Perform ? SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm).
  2051. return set_up_readable_stream_default_controller(stream, controller, start_algorithm, pull_algorithm, cancel_algorithm, high_water_mark, size_algorithm);
  2052. }
  2053. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-call-pull-if-needed
  2054. void readable_byte_stream_controller_call_pull_if_needed(ReadableByteStreamController& controller)
  2055. {
  2056. // 1. Let shouldPull be ! ReadableByteStreamControllerShouldCallPull(controller).
  2057. auto should_pull = readable_byte_stream_controller_should_call_pull(controller);
  2058. // 2. If shouldPull is false, return.
  2059. if (!should_pull)
  2060. return;
  2061. // 3. If controller.[[pulling]] is true,
  2062. if (controller.pulling()) {
  2063. // 1. Set controller.[[pullAgain]] to true.
  2064. controller.set_pull_again(true);
  2065. // 2. Return.
  2066. return;
  2067. }
  2068. // 4. Assert: controller.[[pullAgain]] is false.
  2069. VERIFY(!controller.pull_again());
  2070. // 5. Set controller.[[pulling]] to true.
  2071. controller.set_pulling(true);
  2072. // 6. Let pullPromise be the result of performing controller.[[pullAlgorithm]].
  2073. auto pull_promise = controller.pull_algorithm()->function()();
  2074. // 7. Upon fulfillment of pullPromise,
  2075. WebIDL::upon_fulfillment(*pull_promise, JS::create_heap_function(controller.heap(), [&controller](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {
  2076. // 1. Set controller.[[pulling]] to false.
  2077. controller.set_pulling(false);
  2078. // 2. If controller.[[pullAgain]] is true,
  2079. if (controller.pull_again()) {
  2080. // 1. Set controller.[[pullAgain]] to false.
  2081. controller.set_pull_again(false);
  2082. // 2. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
  2083. readable_byte_stream_controller_call_pull_if_needed(controller);
  2084. }
  2085. return JS::js_undefined();
  2086. }));
  2087. // 8. Upon rejection of pullPromise with reason e,
  2088. WebIDL::upon_rejection(*pull_promise, JS::create_heap_function(controller.heap(), [&controller](JS::Value error) -> WebIDL::ExceptionOr<JS::Value> {
  2089. // 1. Perform ! ReadableByteStreamControllerError(controller, e).
  2090. readable_byte_stream_controller_error(controller, error);
  2091. return JS::js_undefined();
  2092. }));
  2093. }
  2094. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-clear-algorithms
  2095. void readable_byte_stream_controller_clear_algorithms(ReadableByteStreamController& controller)
  2096. {
  2097. // 1. Set controller.[[pullAlgorithm]] to undefined.
  2098. controller.set_pull_algorithm({});
  2099. // 2. Set controller.[[cancelAlgorithm]] to undefined.
  2100. controller.set_cancel_algorithm({});
  2101. }
  2102. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-clear-pending-pull-intos
  2103. void readable_byte_stream_controller_clear_pending_pull_intos(ReadableByteStreamController& controller)
  2104. {
  2105. // 1. Perform ! ReadableByteStreamControllerInvalidateBYOBRequest(controller).
  2106. readable_byte_stream_controller_invalidate_byob_request(controller);
  2107. // 2. Set controller.[[pendingPullIntos]] to a new empty list.
  2108. controller.pending_pull_intos().clear();
  2109. }
  2110. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-close
  2111. WebIDL::ExceptionOr<void> readable_byte_stream_controller_close(ReadableByteStreamController& controller)
  2112. {
  2113. auto& realm = controller.realm();
  2114. // 1. Let stream be controller.[[stream]].
  2115. auto stream = controller.stream();
  2116. // 2. If controller.[[closeRequested]] is true or stream.[[state]] is not "readable", return.
  2117. if (controller.close_requested() || stream->state() != ReadableStream::State::Readable)
  2118. return {};
  2119. // 3. If controller.[[queueTotalSize]] > 0,
  2120. if (controller.queue_total_size() > 0.0) {
  2121. // 1. Set controller.[[closeRequested]] to true.
  2122. controller.set_close_requested(true);
  2123. // 2. Return.
  2124. return {};
  2125. }
  2126. // 4. If controller.[[pendingPullIntos]] is not empty,
  2127. if (!controller.pending_pull_intos().is_empty()) {
  2128. // 1. Let firstPendingPullInto be controller.[[pendingPullIntos]][0].
  2129. auto& first_pending_pull_into = controller.pending_pull_intos().first();
  2130. // 2. If firstPendingPullInto’s bytes filled > 0,
  2131. if (first_pending_pull_into.bytes_filled > 0) {
  2132. // 1. Let e be a new TypeError exception.
  2133. auto error = JS::TypeError::create(realm, "Cannot close controller in the middle of processing a write request"sv);
  2134. // 2. Perform ! ReadableByteStreamControllerError(controller, e).
  2135. readable_byte_stream_controller_error(controller, error);
  2136. // 3. Throw e.
  2137. return JS::throw_completion(error);
  2138. }
  2139. }
  2140. // 5. Perform ! ReadableByteStreamControllerClearAlgorithms(controller).
  2141. readable_byte_stream_controller_clear_algorithms(controller);
  2142. // 6. Perform ! ReadableStreamClose(stream).
  2143. readable_stream_close(*stream);
  2144. return {};
  2145. }
  2146. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-error
  2147. void readable_byte_stream_controller_error(ReadableByteStreamController& controller, JS::Value error)
  2148. {
  2149. // 1. Let stream be controller.[[stream]].
  2150. auto stream = controller.stream();
  2151. // 2. If stream.[[state]] is not "readable", return.
  2152. if (stream->state() != ReadableStream::State::Readable)
  2153. return;
  2154. // 3. Perform ! ReadableByteStreamControllerClearPendingPullIntos(controller).
  2155. readable_byte_stream_controller_clear_pending_pull_intos(controller);
  2156. // 4. Perform ! ResetQueue(controller).
  2157. reset_queue(controller);
  2158. // 5. Perform ! ReadableByteStreamControllerClearAlgorithms(controller).
  2159. readable_byte_stream_controller_clear_algorithms(controller);
  2160. // 6. Perform ! ReadableStreamError(stream, e).
  2161. readable_stream_error(*stream, error);
  2162. }
  2163. // https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerfillreadrequestfromqueue
  2164. void readable_byte_stream_controller_fill_read_request_from_queue(ReadableByteStreamController& controller, JS::NonnullGCPtr<ReadRequest> read_request)
  2165. {
  2166. auto& vm = controller.vm();
  2167. auto& realm = controller.realm();
  2168. // 1. Assert: controller.[[queueTotalSize]] > 0.
  2169. VERIFY(controller.queue_total_size() > 0.0);
  2170. // 2. Let entry be controller.[[queue]][0].
  2171. // 3. Remove entry from controller.[[queue]].
  2172. auto entry = controller.queue().take_first();
  2173. // 4. Set controller.[[queueTotalSize]] to controller.[[queueTotalSize]] − entry’s byte length.
  2174. controller.set_queue_total_size(controller.queue_total_size() - entry.byte_length);
  2175. // 5. Perform ! ReadableByteStreamControllerHandleQueueDrain(controller).
  2176. readable_byte_stream_controller_handle_queue_drain(controller);
  2177. // 6. Let view be ! Construct(%Uint8Array%, « entry’s buffer, entry’s byte offset, entry’s byte length »).
  2178. auto view = MUST(JS::construct(vm, *realm.intrinsics().uint8_array_constructor(), entry.buffer, JS::Value(entry.byte_offset), JS::Value(entry.byte_length)));
  2179. // 7. Perform readRequest’s chunk steps, given view.
  2180. read_request->on_chunk(view);
  2181. }
  2182. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-get-desired-size
  2183. Optional<double> readable_byte_stream_controller_get_desired_size(ReadableByteStreamController const& controller)
  2184. {
  2185. auto stream = controller.stream();
  2186. // 1. Let state be controller.[[stream]].[[state]].
  2187. // 2. If state is "errored", return null.
  2188. if (stream->is_errored())
  2189. return {};
  2190. // 3. If state is "closed", return 0.
  2191. if (stream->is_closed())
  2192. return 0.0;
  2193. // 4. Return controller.[[strategyHWM]] − controller.[[queueTotalSize]].
  2194. return controller.strategy_hwm() - controller.queue_total_size();
  2195. }
  2196. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-handle-queue-drain
  2197. void readable_byte_stream_controller_handle_queue_drain(ReadableByteStreamController& controller)
  2198. {
  2199. // 1. Assert: controller.[[stream]].[[state]] is "readable".
  2200. VERIFY(controller.stream()->state() == ReadableStream::State::Readable);
  2201. // 2. If controller.[[queueTotalSize]] is 0 and controller.[[closeRequested]] is true,
  2202. if (controller.queue_total_size() == 0.0 && controller.close_requested()) {
  2203. // 1. Perform ! ReadableByteStreamControllerClearAlgorithms(controller).
  2204. readable_byte_stream_controller_clear_algorithms(controller);
  2205. // 2. Perform ! ReadableStreamClose(controller.[[stream]]).
  2206. readable_stream_close(*controller.stream());
  2207. }
  2208. // 3. Otherwise,
  2209. else {
  2210. // 1. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
  2211. readable_byte_stream_controller_call_pull_if_needed(controller);
  2212. }
  2213. }
  2214. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-invalidate-byob-request
  2215. void readable_byte_stream_controller_invalidate_byob_request(ReadableByteStreamController& controller)
  2216. {
  2217. // 1. If controller.[[byobRequest]] is null, return.
  2218. if (!controller.byob_request())
  2219. return;
  2220. // 2. Set controller.[[byobRequest]].[[controller]] to undefined.
  2221. controller.byob_request()->set_controller({});
  2222. // 3. Set controller.[[byobRequest]].[[view]] to null.
  2223. controller.byob_request()->set_view({});
  2224. // 4. Set controller.[[byobRequest]] to null.
  2225. controller.set_byob_request({});
  2226. }
  2227. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-error
  2228. bool readable_byte_stream_controller_should_call_pull(ReadableByteStreamController const& controller)
  2229. {
  2230. // 1. Let stream be controller.[[stream]].
  2231. auto stream = controller.stream();
  2232. // 2. If stream.[[state]] is not "readable", return false.
  2233. if (stream->state() != ReadableStream::State::Readable)
  2234. return false;
  2235. // 3. If controller.[[closeRequested]] is true, return false.
  2236. if (controller.close_requested())
  2237. return false;
  2238. // 4. If controller.[[started]] is false, return false.
  2239. if (!controller.started())
  2240. return false;
  2241. // 5. If ! ReadableStreamHasDefaultReader(stream) is true and ! ReadableStreamGetNumReadRequests(stream) > 0, return true.
  2242. if (readable_stream_has_default_reader(*stream) && readable_stream_get_num_read_requests(*stream) > 0)
  2243. return true;
  2244. // 6. If ! ReadableStreamHasBYOBReader(stream) is true and ! ReadableStreamGetNumReadIntoRequests(stream) > 0, return true.
  2245. if (readable_stream_has_byob_reader(*stream) && readable_stream_get_num_read_into_requests(*stream) > 0)
  2246. return true;
  2247. // 7. Let desiredSize be ! ReadableByteStreamControllerGetDesiredSize(controller).
  2248. auto desired_size = readable_byte_stream_controller_get_desired_size(controller);
  2249. // 8. Assert: desiredSize is not null.
  2250. VERIFY(desired_size.has_value());
  2251. // 9. If desiredSize > 0, return true.
  2252. if (*desired_size > 0.0)
  2253. return true;
  2254. // 10. Return false.
  2255. return false;
  2256. }
  2257. // NON-STANDARD: Can be used instead of CreateReadableStream in cases where we need to set up a newly allocated
  2258. // ReadableStream before initialization of said ReadableStream, i.e. ReadableStream is captured by lambdas in an uninitialized state.
  2259. // Spec steps are taken from: https://streams.spec.whatwg.org/#create-readable-stream
  2260. 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)
  2261. {
  2262. // 1. If highWaterMark was not passed, set it to 1.
  2263. if (!high_water_mark.has_value())
  2264. high_water_mark = 1.0;
  2265. // 2. If sizeAlgorithm was not passed, set it to an algorithm that returns 1.
  2266. if (!size_algorithm)
  2267. size_algorithm = JS::create_heap_function(realm.heap(), [](JS::Value) { return JS::normal_completion(JS::Value(1)); });
  2268. // 3. Assert: ! IsNonNegativeNumber(highWaterMark) is true.
  2269. VERIFY(is_non_negative_number(JS::Value { *high_water_mark }));
  2270. // 4. Let stream be a new ReadableStream.
  2271. // NOTE: The ReadableStream is allocated outside the scope of this method.
  2272. // 5. Perform ! InitializeReadableStream(stream).
  2273. initialize_readable_stream(stream);
  2274. // 6. Let controller be a new ReadableStreamDefaultController.
  2275. auto controller = realm.heap().allocate<ReadableStreamDefaultController>(realm, realm);
  2276. // 7. Perform ? SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm).
  2277. TRY(set_up_readable_stream_default_controller(stream, *controller, start_algorithm, pull_algorithm, cancel_algorithm, *high_water_mark, *size_algorithm));
  2278. return {};
  2279. }
  2280. // https://streams.spec.whatwg.org/#create-readable-stream
  2281. 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)
  2282. {
  2283. // 1. If highWaterMark was not passed, set it to 1.
  2284. if (!high_water_mark.has_value())
  2285. high_water_mark = 1.0;
  2286. // 2. If sizeAlgorithm was not passed, set it to an algorithm that returns 1.
  2287. if (!size_algorithm)
  2288. size_algorithm = JS::create_heap_function(realm.heap(), [](JS::Value) { return JS::normal_completion(JS::Value(1)); });
  2289. // 3. Assert: ! IsNonNegativeNumber(highWaterMark) is true.
  2290. VERIFY(is_non_negative_number(JS::Value { *high_water_mark }));
  2291. // 4. Let stream be a new ReadableStream.
  2292. auto stream = realm.heap().allocate<ReadableStream>(realm, realm);
  2293. // 5. Perform ! InitializeReadableStream(stream).
  2294. initialize_readable_stream(*stream);
  2295. // 6. Let controller be a new ReadableStreamDefaultController.
  2296. auto controller = realm.heap().allocate<ReadableStreamDefaultController>(realm, realm);
  2297. // 7. Perform ? SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm).
  2298. TRY(set_up_readable_stream_default_controller(*stream, *controller, start_algorithm, pull_algorithm, cancel_algorithm, *high_water_mark, *size_algorithm));
  2299. // 8. Return stream.
  2300. return stream;
  2301. }
  2302. // https://streams.spec.whatwg.org/#abstract-opdef-createreadablebytestream
  2303. 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)
  2304. {
  2305. // 1. Let stream be a new ReadableStream.
  2306. auto stream = realm.heap().allocate<ReadableStream>(realm, realm);
  2307. // 2. Perform ! InitializeReadableStream(stream).
  2308. initialize_readable_stream(*stream);
  2309. // 3. Let controller be a new ReadableByteStreamController.
  2310. auto controller = realm.heap().allocate<ReadableByteStreamController>(realm, realm);
  2311. // 4. Perform ? SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined).
  2312. TRY(set_up_readable_byte_stream_controller(stream, controller, start_algorithm, pull_algorithm, cancel_algorithm, 0, JS::js_undefined()));
  2313. // 5. Return stream.
  2314. return stream;
  2315. }
  2316. // https://streams.spec.whatwg.org/#create-writable-stream
  2317. 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)
  2318. {
  2319. // 1. Assert: ! IsNonNegativeNumber(highWaterMark) is true.
  2320. VERIFY(is_non_negative_number(JS::Value { high_water_mark }));
  2321. // 2. Let stream be a new WritableStream.
  2322. auto stream = realm.heap().allocate<WritableStream>(realm, realm);
  2323. // 3. Perform ! InitializeWritableStream(stream).
  2324. initialize_writable_stream(*stream);
  2325. // 4. Let controller be a new WritableStreamDefaultController.
  2326. auto controller = realm.heap().allocate<WritableStreamDefaultController>(realm, realm);
  2327. // 5. Perform ? SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm).
  2328. 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)));
  2329. // 6. Return stream.
  2330. return stream;
  2331. }
  2332. // https://streams.spec.whatwg.org/#initialize-readable-stream
  2333. void initialize_readable_stream(ReadableStream& stream)
  2334. {
  2335. // 1. Set stream.[[state]] to "readable".
  2336. stream.set_state(ReadableStream::State::Readable);
  2337. // 2. Set stream.[[reader]] and stream.[[storedError]] to undefined.
  2338. stream.set_reader({});
  2339. stream.set_stored_error({});
  2340. // 3. Set stream.[[disturbed]] to false.
  2341. stream.set_disturbed(false);
  2342. }
  2343. // https://streams.spec.whatwg.org/#initialize-writable-stream
  2344. void initialize_writable_stream(WritableStream& stream)
  2345. {
  2346. // 1. Set stream.[[state]] to "writable".
  2347. stream.set_state(WritableStream::State::Writable);
  2348. // 2. Set stream.[[storedError]], stream.[[writer]], stream.[[controller]], stream.[[inFlightWriteRequest]],
  2349. // stream.[[closeRequest]], stream.[[inFlightCloseRequest]], and stream.[[pendingAbortRequest]] to undefined.
  2350. stream.set_stored_error(JS::js_undefined());
  2351. stream.set_writer({});
  2352. stream.set_controller({});
  2353. stream.set_in_flight_write_request({});
  2354. stream.set_close_request({});
  2355. stream.set_in_flight_close_request({});
  2356. stream.set_pending_abort_request({});
  2357. // 3. Set stream.[[writeRequests]] to a new empty list.
  2358. stream.write_requests().clear();
  2359. // 4. Set stream.[[backpressure]] to false.
  2360. stream.set_backpressure(false);
  2361. }
  2362. // https://streams.spec.whatwg.org/#acquire-writable-stream-default-writer
  2363. WebIDL::ExceptionOr<JS::NonnullGCPtr<WritableStreamDefaultWriter>> acquire_writable_stream_default_writer(WritableStream& stream)
  2364. {
  2365. auto& realm = stream.realm();
  2366. // 1. Let writer be a new WritableStreamDefaultWriter.
  2367. auto writer = stream.heap().allocate<WritableStreamDefaultWriter>(realm, realm);
  2368. // 2. Perform ? SetUpWritableStreamDefaultWriter(writer, stream).
  2369. TRY(set_up_writable_stream_default_writer(*writer, stream));
  2370. // 3. Return writer.
  2371. return writer;
  2372. }
  2373. // https://streams.spec.whatwg.org/#is-writable-stream-locked
  2374. bool is_writable_stream_locked(WritableStream const& stream)
  2375. {
  2376. // 1. If stream.[[writer]] is undefined, return false.
  2377. if (!stream.writer())
  2378. return false;
  2379. // 2. Return true.
  2380. return true;
  2381. }
  2382. // https://streams.spec.whatwg.org/#set-up-writable-stream-default-writer
  2383. WebIDL::ExceptionOr<void> set_up_writable_stream_default_writer(WritableStreamDefaultWriter& writer, WritableStream& stream)
  2384. {
  2385. auto& realm = writer.realm();
  2386. // 1. If ! IsWritableStreamLocked(stream) is true, throw a TypeError exception.
  2387. if (is_writable_stream_locked(stream))
  2388. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Stream is locked"sv };
  2389. // 2. Set writer.[[stream]] to stream.
  2390. writer.set_stream(stream);
  2391. // 3. Set stream.[[writer]] to writer.
  2392. stream.set_writer(writer);
  2393. // 4. Let state be stream.[[state]].
  2394. auto state = stream.state();
  2395. // 5. If state is "writable",
  2396. if (state == WritableStream::State::Writable) {
  2397. // 1. If ! WritableStreamCloseQueuedOrInFlight(stream) is false and stream.[[backpressure]] is true, set writer.[[readyPromise]] to a new promise.
  2398. if (!writable_stream_close_queued_or_in_flight(stream) && stream.backpressure()) {
  2399. writer.set_ready_promise(WebIDL::create_promise(realm));
  2400. }
  2401. // 2. Otherwise, set writer.[[readyPromise]] to a promise resolved with undefined.
  2402. else {
  2403. writer.set_ready_promise(WebIDL::create_resolved_promise(realm, JS::js_undefined()));
  2404. }
  2405. // 3. Set writer.[[closedPromise]] to a new promise.
  2406. writer.set_closed_promise(WebIDL::create_promise(realm));
  2407. }
  2408. // 6. Otherwise, if state is "erroring",
  2409. else if (state == WritableStream::State::Erroring) {
  2410. // 1. Set writer.[[readyPromise]] to a promise rejected with stream.[[storedError]].
  2411. writer.set_ready_promise(WebIDL::create_rejected_promise(realm, stream.stored_error()));
  2412. // 2. Set writer.[[readyPromise]].[[PromiseIsHandled]] to true.
  2413. WebIDL::mark_promise_as_handled(*writer.ready_promise());
  2414. // 3. Set writer.[[closedPromise]] to a new promise.
  2415. writer.set_closed_promise(WebIDL::create_promise(realm));
  2416. }
  2417. // 7. Otherwise, if state is "closed",
  2418. else if (state == WritableStream::State::Closed) {
  2419. // 1. Set writer.[[readyPromise]] to a promise resolved with undefined.
  2420. writer.set_ready_promise(WebIDL::create_resolved_promise(realm, JS::js_undefined()));
  2421. // 2. Set writer.[[closedPromise]] to a promise resolved with undefined.
  2422. writer.set_closed_promise(WebIDL::create_resolved_promise(realm, JS::js_undefined()));
  2423. }
  2424. // 8. Otherwise,
  2425. else {
  2426. // 1. Assert: state is "errored".
  2427. VERIFY(state == WritableStream::State::Errored);
  2428. // 2. Let storedError be stream.[[storedError]].
  2429. auto stored_error = stream.stored_error();
  2430. // 3. Set writer.[[readyPromise]] to a promise rejected with storedError.
  2431. writer.set_ready_promise(WebIDL::create_rejected_promise(realm, stored_error));
  2432. // 4. Set writer.[[readyPromise]].[[PromiseIsHandled]] to true.
  2433. WebIDL::mark_promise_as_handled(*writer.ready_promise());
  2434. // 5. Set writer.[[closedPromise]] to a promise rejected with storedError.
  2435. writer.set_closed_promise(WebIDL::create_rejected_promise(realm, stored_error));
  2436. // 6. Set writer.[[closedPromise]].[[PromiseIsHandled]] to true.
  2437. WebIDL::mark_promise_as_handled(*writer.closed_promise());
  2438. }
  2439. return {};
  2440. }
  2441. // https://streams.spec.whatwg.org/#set-up-readable-byte-stream-controller
  2442. 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)
  2443. {
  2444. auto& realm = stream.realm();
  2445. // 1. Assert: stream.[[controller]] is undefined.
  2446. VERIFY(!stream.controller().has_value());
  2447. // 2. If autoAllocateChunkSize is not undefined,
  2448. if (!auto_allocate_chunk_size.is_undefined()) {
  2449. // 1. Assert: ! IsInteger(autoAllocateChunkSize) is true.
  2450. VERIFY(auto_allocate_chunk_size.is_integral_number());
  2451. // 2. Assert: autoAllocateChunkSize is positive.
  2452. VERIFY(auto_allocate_chunk_size.as_double() > 0);
  2453. }
  2454. // 3. Set controller.[[stream]] to stream.
  2455. controller.set_stream(stream);
  2456. // 4. Set controller.[[pullAgain]] and controller.[[pulling]] to false.
  2457. controller.set_pull_again(false);
  2458. controller.set_pulling(false);
  2459. // 5. Set controller.[[byobRequest]] to null.
  2460. controller.set_byob_request({});
  2461. // 6. Perform ! ResetQueue(controller).
  2462. reset_queue(controller);
  2463. // 7. Set controller.[[closeRequested]] and controller.[[started]] to false.
  2464. controller.set_close_requested(false);
  2465. controller.set_started(false);
  2466. // 8. Set controller.[[strategyHWM]] to highWaterMark.
  2467. controller.set_strategy_hwm(high_water_mark);
  2468. // 9. Set controller.[[pullAlgorithm]] to pullAlgorithm.
  2469. controller.set_pull_algorithm(pull_algorithm);
  2470. // 10. Set controller.[[cancelAlgorithm]] to cancelAlgorithm.
  2471. controller.set_cancel_algorithm(cancel_algorithm);
  2472. // 11. Set controller.[[autoAllocateChunkSize]] to autoAllocateChunkSize.
  2473. if (auto_allocate_chunk_size.is_integral_number())
  2474. controller.set_auto_allocate_chunk_size(auto_allocate_chunk_size.as_double());
  2475. // 12. Set controller.[[pendingPullIntos]] to a new empty list.
  2476. controller.pending_pull_intos().clear();
  2477. // 13. Set stream.[[controller]] to controller.
  2478. stream.set_controller(ReadableStreamController { controller });
  2479. // 14. Let startResult be the result of performing startAlgorithm.
  2480. auto start_result = TRY(start_algorithm->function()());
  2481. // 15. Let startPromise be a promise resolved with startResult.
  2482. auto start_promise = WebIDL::create_resolved_promise(realm, start_result);
  2483. // 16. Upon fulfillment of startPromise,
  2484. WebIDL::upon_fulfillment(start_promise, JS::create_heap_function(controller.heap(), [&controller](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {
  2485. // 1. Set controller.[[started]] to true.
  2486. controller.set_started(true);
  2487. // 2. Assert: controller.[[pulling]] is false.
  2488. VERIFY(!controller.pulling());
  2489. // 3. Assert: controller.[[pullAgain]] is false.
  2490. VERIFY(!controller.pull_again());
  2491. // 4. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
  2492. readable_byte_stream_controller_call_pull_if_needed(controller);
  2493. return JS::js_undefined();
  2494. }));
  2495. // 17. Upon rejection of startPromise with reason r,
  2496. WebIDL::upon_rejection(start_promise, JS::create_heap_function(controller.heap(), [&controller](JS::Value r) -> WebIDL::ExceptionOr<JS::Value> {
  2497. // 1. Perform ! ReadableByteStreamControllerError(controller, r).
  2498. readable_byte_stream_controller_error(controller, r);
  2499. return JS::js_undefined();
  2500. }));
  2501. return {};
  2502. }
  2503. // https://streams.spec.whatwg.org/#readablestream-enqueue
  2504. WebIDL::ExceptionOr<void> readable_stream_enqueue(ReadableStreamController& controller, JS::Value chunk)
  2505. {
  2506. // 1. If stream.[[controller]] implements ReadableStreamDefaultController,
  2507. if (controller.has<JS::NonnullGCPtr<ReadableStreamDefaultController>>()) {
  2508. // 1. Perform ! ReadableStreamDefaultControllerEnqueue(stream.[[controller]], chunk).
  2509. return readable_stream_default_controller_enqueue(controller.get<JS::NonnullGCPtr<ReadableStreamDefaultController>>(), chunk);
  2510. }
  2511. // 2. Otherwise,
  2512. else {
  2513. // 1. Assert: stream.[[controller]] implements ReadableByteStreamController.
  2514. VERIFY(controller.has<JS::NonnullGCPtr<ReadableByteStreamController>>());
  2515. auto readable_byte_controller = controller.get<JS::NonnullGCPtr<ReadableByteStreamController>>();
  2516. // FIXME: 2. Assert: chunk is an ArrayBufferView.
  2517. // 3. Let byobView be the current BYOB request view for stream.
  2518. // FIXME: This is not what the spec means by 'current BYOB request view'
  2519. auto byob_view = readable_byte_controller->raw_byob_request();
  2520. // 4. If byobView is non-null, and chunk.[[ViewedArrayBuffer]] is byobView.[[ViewedArrayBuffer]], then:
  2521. if (byob_view) {
  2522. // FIXME: 1. Assert: chunk.[[ByteOffset]] is byobView.[[ByteOffset]].
  2523. // FIXME: 2. Assert: chunk.[[ByteLength]] ≤ byobView.[[ByteLength]].
  2524. // FIXME: 3. Perform ? ReadableByteStreamControllerRespond(stream.[[controller]], chunk.[[ByteLength]]).
  2525. TODO();
  2526. }
  2527. // 5. Otherwise, perform ? ReadableByteStreamControllerEnqueue(stream.[[controller]], chunk).
  2528. return readable_byte_stream_controller_enqueue(readable_byte_controller, chunk);
  2529. }
  2530. }
  2531. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-enqueue
  2532. WebIDL::ExceptionOr<void> readable_byte_stream_controller_enqueue(ReadableByteStreamController& controller, JS::Value chunk)
  2533. {
  2534. auto& vm = controller.vm();
  2535. auto& realm = controller.realm();
  2536. // 1. Let stream be controller.[[stream]].
  2537. auto stream = controller.stream();
  2538. // 2. If controller.[[closeRequested]] is true or stream.[[state]] is not "readable", return.
  2539. if (controller.close_requested() || stream->state() != ReadableStream ::State::Readable)
  2540. return {};
  2541. // 3. Let buffer be chunk.[[ViewedArrayBuffer]].
  2542. auto* typed_array = TRY(JS::typed_array_from(vm, chunk));
  2543. auto* buffer = typed_array->viewed_array_buffer();
  2544. // 4. Let byteOffset be chunk.[[ByteOffset]].
  2545. auto byte_offset = typed_array->byte_offset();
  2546. // 6. If ! IsDetachedBuffer(buffer) is true, throw a TypeError exception.
  2547. // FIXME: The streams spec has not been updated for resizable ArrayBuffer objects. We must perform step 6 before
  2548. // invoking TypedArrayByteLength in step 5. We also must check if the array is out-of-bounds, rather than
  2549. // just detached.
  2550. auto typed_array_record = JS::make_typed_array_with_buffer_witness_record(*typed_array, JS::ArrayBuffer::Order::SeqCst);
  2551. if (JS::is_typed_array_out_of_bounds(typed_array_record))
  2552. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BufferOutOfBounds, "TypedArray"sv);
  2553. // 5. Let byteLength be chunk.[[ByteLength]].
  2554. auto byte_length = JS::typed_array_byte_length(typed_array_record);
  2555. // 7. Let transferredBuffer be ? TransferArrayBuffer(buffer).
  2556. auto transferred_buffer = TRY(transfer_array_buffer(realm, *buffer));
  2557. // 8. If controller.[[pendingPullIntos]] is not empty,
  2558. if (!controller.pending_pull_intos().is_empty()) {
  2559. // 1. Let firstPendingPullInto be controller.[[pendingPullIntos]][0].
  2560. auto& first_pending_pull_into = controller.pending_pull_intos().first();
  2561. // 2. If ! IsDetachedBuffer(firstPendingPullInto’s buffer) is true, throw a TypeError exception.
  2562. if (first_pending_pull_into.buffer->is_detached()) {
  2563. auto error = JS::TypeError::create(realm, "Buffer is detached"sv);
  2564. return JS::throw_completion(error);
  2565. }
  2566. // 3. Perform ! ReadableByteStreamControllerInvalidateBYOBRequest(controller).
  2567. readable_byte_stream_controller_invalidate_byob_request(controller);
  2568. // 4. Set firstPendingPullInto’s buffer to ! TransferArrayBuffer(firstPendingPullInto’s buffer).
  2569. first_pending_pull_into.buffer = MUST(transfer_array_buffer(realm, first_pending_pull_into.buffer));
  2570. // 5. If firstPendingPullInto’s reader type is "none", perform ? ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto).
  2571. if (first_pending_pull_into.reader_type == ReaderType::None)
  2572. TRY(readable_byte_stream_controller_enqueue_detached_pull_into_queue(controller, first_pending_pull_into));
  2573. }
  2574. // 9. If ! ReadableStreamHasDefaultReader(stream) is true,
  2575. if (readable_stream_has_default_reader(*stream)) {
  2576. // 1. Perform ! ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller).
  2577. readable_byte_stream_controller_process_read_requests_using_queue(controller);
  2578. // 2. If ! ReadableStreamGetNumReadRequests(stream) is 0,
  2579. if (readable_stream_get_num_read_requests(*stream) == 0) {
  2580. // 1. Assert: controller.[[pendingPullIntos]] is empty.
  2581. VERIFY(controller.pending_pull_intos().is_empty());
  2582. // 2. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength).
  2583. readable_byte_stream_controller_enqueue_chunk_to_queue(controller, transferred_buffer, byte_offset, byte_length);
  2584. }
  2585. // 3. Otherwise.
  2586. else {
  2587. // 1. Assert: controller.[[queue]] is empty.
  2588. VERIFY(controller.queue().is_empty());
  2589. // 2. If controller.[[pendingPullIntos]] is not empty,
  2590. if (!controller.pending_pull_intos().is_empty()) {
  2591. // 1. Assert: controller.[[pendingPullIntos]][0]'s reader type is "default".
  2592. VERIFY(controller.pending_pull_intos().first().reader_type == ReaderType::Default);
  2593. // 2. Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).
  2594. readable_byte_stream_controller_shift_pending_pull_into(controller);
  2595. }
  2596. // 3. Let transferredView be ! Construct(%Uint8Array%, « transferredBuffer, byteOffset, byteLength »).
  2597. auto transferred_view = MUST(JS::construct(vm, *realm.intrinsics().uint8_array_constructor(), transferred_buffer, JS::Value(byte_offset), JS::Value(byte_length)));
  2598. // 4. Perform ! ReadableStreamFulfillReadRequest(stream, transferredView, false).
  2599. readable_stream_fulfill_read_request(*stream, transferred_view, false);
  2600. }
  2601. }
  2602. // 10. Otherwise, if ! ReadableStreamHasBYOBReader(stream) is true,
  2603. else if (readable_stream_has_byob_reader(*stream)) {
  2604. // 1. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength).
  2605. readable_byte_stream_controller_enqueue_chunk_to_queue(controller, transferred_buffer, byte_offset, byte_length);
  2606. // 2. Perform ! ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller).
  2607. readable_byte_stream_controller_process_pull_into_descriptors_using_queue(controller);
  2608. }
  2609. // 11. Otherwise,
  2610. else {
  2611. // 1. Assert: ! IsReadableStreamLocked(stream) is false.
  2612. VERIFY(!is_readable_stream_locked(*stream));
  2613. // 2. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength).
  2614. readable_byte_stream_controller_enqueue_chunk_to_queue(controller, transferred_buffer, byte_offset, byte_length);
  2615. }
  2616. // 12. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
  2617. readable_byte_stream_controller_call_pull_if_needed(controller);
  2618. return {};
  2619. }
  2620. // https://streams.spec.whatwg.org/#readablestream-pull-from-bytes
  2621. WebIDL::ExceptionOr<void> readable_stream_pull_from_bytes(ReadableStream& stream, ByteBuffer bytes)
  2622. {
  2623. // 1. Assert: stream.[[controller]] implements ReadableByteStreamController.
  2624. auto controller = stream.controller()->get<JS::NonnullGCPtr<ReadableByteStreamController>>();
  2625. // 2. Let available be bytes’s length.
  2626. auto available = bytes.size();
  2627. // 3. Let desiredSize be available.
  2628. auto desired_size = available;
  2629. // FIXME: 4. If stream’s current BYOB request view is non-null, then set desiredSize to stream’s current BYOB request
  2630. // view's byte length.
  2631. // 5. Let pullSize be the smaller value of available and desiredSize.
  2632. auto pull_size = min(available, desired_size);
  2633. // 6. Let pulled be the first pullSize bytes of bytes.
  2634. auto pulled = pull_size == available ? move(bytes) : MUST(bytes.slice(0, pull_size));
  2635. // 7. Remove the first pullSize bytes from bytes.
  2636. if (pull_size != available)
  2637. bytes = MUST(bytes.slice(pull_size, available - pull_size));
  2638. // FIXME: 8. If stream’s current BYOB request view is non-null, then:
  2639. // 1. Write pulled into stream’s current BYOB request view.
  2640. // 2. Perform ? ReadableByteStreamControllerRespond(stream.[[controller]], pullSize).
  2641. // 9. Otherwise,
  2642. {
  2643. auto& realm = HTML::relevant_realm(stream);
  2644. // 1. Set view to the result of creating a Uint8Array from pulled in stream’s relevant Realm.
  2645. auto array_buffer = JS::ArrayBuffer::create(realm, move(pulled));
  2646. auto view = JS::Uint8Array::create(realm, array_buffer->byte_length(), *array_buffer);
  2647. // 2. Perform ? ReadableByteStreamControllerEnqueue(stream.[[controller]], view).
  2648. TRY(readable_byte_stream_controller_enqueue(controller, view));
  2649. }
  2650. return {};
  2651. }
  2652. // https://streams.spec.whatwg.org/#transfer-array-buffer
  2653. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::ArrayBuffer>> transfer_array_buffer(JS::Realm& realm, JS::ArrayBuffer& buffer)
  2654. {
  2655. auto& vm = realm.vm();
  2656. // 1. Assert: ! IsDetachedBuffer(O) is false.
  2657. VERIFY(!buffer.is_detached());
  2658. // 2. Let arrayBufferData be O.[[ArrayBufferData]].
  2659. // 3. Let arrayBufferByteLength be O.[[ArrayBufferByteLength]].
  2660. auto array_buffer = buffer.buffer();
  2661. // 4. Perform ? DetachArrayBuffer(O).
  2662. TRY(JS::detach_array_buffer(vm, buffer));
  2663. // 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.
  2664. return JS::ArrayBuffer::create(realm, move(array_buffer));
  2665. }
  2666. // https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerenqueuedetachedpullintotoqueue
  2667. WebIDL::ExceptionOr<void> readable_byte_stream_controller_enqueue_detached_pull_into_queue(ReadableByteStreamController& controller, PullIntoDescriptor& pull_into_descriptor)
  2668. {
  2669. // 1. Assert: pullIntoDescriptor’s reader type is "none".
  2670. VERIFY(pull_into_descriptor.reader_type == ReaderType::None);
  2671. // 2. If pullIntoDescriptor’s bytes filled > 0, perform ? ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor’s buffer, pullIntoDescriptor’s byte offset, pullIntoDescriptor’s bytes filled).
  2672. if (pull_into_descriptor.bytes_filled > 0)
  2673. 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));
  2674. // 3. Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).
  2675. readable_byte_stream_controller_shift_pending_pull_into(controller);
  2676. return {};
  2677. }
  2678. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-commit-pull-into-descriptor
  2679. void readable_byte_stream_controller_commit_pull_into_descriptor(ReadableStream& stream, PullIntoDescriptor const& pull_into_descriptor)
  2680. {
  2681. // 1. Assert: stream.[[state]] is not "errored".
  2682. VERIFY(!stream.is_errored());
  2683. // 2. Assert: pullIntoDescriptor.reader type is not "none".
  2684. VERIFY(pull_into_descriptor.reader_type != ReaderType::None);
  2685. // 3. Let done be false.
  2686. bool done = false;
  2687. // 4. If stream.[[state]] is "closed",
  2688. if (stream.is_closed()) {
  2689. // 1. Assert: pullIntoDescriptor’s bytes filled is 0.
  2690. VERIFY(pull_into_descriptor.bytes_filled == 0);
  2691. // 2. Set done to true.
  2692. done = true;
  2693. }
  2694. // 5. Let filledView be ! ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor).
  2695. auto filled_view = readable_byte_stream_controller_convert_pull_into_descriptor(stream.realm(), pull_into_descriptor);
  2696. // 6. If pullIntoDescriptor’s reader type is "default",
  2697. if (pull_into_descriptor.reader_type == ReaderType::Default) {
  2698. // 1. Perform ! ReadableStreamFulfillReadRequest(stream, filledView, done).
  2699. readable_stream_fulfill_read_request(stream, filled_view, done);
  2700. }
  2701. // 7. Otherwise,
  2702. else {
  2703. // 1. Assert: pullIntoDescriptor’s reader type is "byob".
  2704. VERIFY(pull_into_descriptor.reader_type == ReaderType::Byob);
  2705. // 2. Perform ! ReadableStreamFulfillReadIntoRequest(stream, filledView, done).
  2706. readable_stream_fulfill_read_into_request(stream, filled_view, done);
  2707. }
  2708. }
  2709. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-process-pull-into-descriptors-using-queue
  2710. void readable_byte_stream_controller_process_pull_into_descriptors_using_queue(ReadableByteStreamController& controller)
  2711. {
  2712. // 1. Assert: controller.[[closeRequested]] is false.
  2713. VERIFY(!controller.close_requested());
  2714. // 2. While controller.[[pendingPullIntos]] is not empty,
  2715. while (!controller.pending_pull_intos().is_empty()) {
  2716. // 1. If controller.[[queueTotalSize]] is 0, return.
  2717. if (controller.queue_total_size() == 0)
  2718. return;
  2719. // 2. Let pullIntoDescriptor be controller.[[pendingPullIntos]][0].
  2720. auto& pull_into_descriptor = controller.pending_pull_intos().first();
  2721. // 3. If ! ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) is true,
  2722. if (readable_byte_stream_controller_fill_pull_into_descriptor_from_queue(controller, pull_into_descriptor)) {
  2723. // NOTE: We store the returned pull into descriptor here as the 'shift pending pull into' will remove
  2724. // the first entry into the list which we have a reference to above.
  2725. // 1. Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).
  2726. auto descriptor = readable_byte_stream_controller_shift_pending_pull_into(controller);
  2727. // 2. Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(controller.[[stream]], pullIntoDescriptor).
  2728. readable_byte_stream_controller_commit_pull_into_descriptor(*controller.stream(), descriptor);
  2729. }
  2730. }
  2731. }
  2732. // https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerprocessreadrequestsusingqueue
  2733. void readable_byte_stream_controller_process_read_requests_using_queue(ReadableByteStreamController& controller)
  2734. {
  2735. // 1. Let reader be controller.[[stream]].[[reader]].
  2736. auto reader = controller.stream()->reader();
  2737. // 2. Assert: reader implements ReadableStreamDefaultReader.
  2738. VERIFY(reader->has<JS::NonnullGCPtr<ReadableStreamDefaultReader>>());
  2739. // 3. While reader.[[readRequests]] is not empty,
  2740. auto readable_stream_default_reader = reader->get<JS::NonnullGCPtr<ReadableStreamDefaultReader>>();
  2741. while (!readable_stream_default_reader->read_requests().is_empty()) {
  2742. // 1. If controller.[[queueTotalSize]] is 0, return.
  2743. if (controller.queue_total_size() == 0.0)
  2744. return;
  2745. // 2. Let readRequest be reader.[[readRequests]][0].
  2746. // 3. Remove readRequest from reader.[[readRequests]].
  2747. auto read_request = readable_stream_default_reader->read_requests().take_first();
  2748. // 4. Perform ! ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest).
  2749. readable_byte_stream_controller_fill_read_request_from_queue(controller, read_request);
  2750. }
  2751. }
  2752. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-enqueue-chunk-to-queue
  2753. void readable_byte_stream_controller_enqueue_chunk_to_queue(ReadableByteStreamController& controller, JS::NonnullGCPtr<JS::ArrayBuffer> buffer, u32 byte_offset, u32 byte_length)
  2754. {
  2755. // 1. Append a new readable byte stream queue entry with buffer buffer, byte offset byteOffset, and byte length byteLength to controller.[[queue]].
  2756. controller.queue().append(ReadableByteStreamQueueEntry {
  2757. .buffer = buffer,
  2758. .byte_offset = byte_offset,
  2759. .byte_length = byte_length,
  2760. });
  2761. // 2. Set controller.[[queueTotalSize]] to controller.[[queueTotalSize]] + byteLength.
  2762. controller.set_queue_total_size(controller.queue_total_size() + byte_length);
  2763. }
  2764. // https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerenqueueclonedchunktoqueue
  2765. WebIDL::ExceptionOr<void> readable_byte_stream_controller_enqueue_cloned_chunk_to_queue(ReadableByteStreamController& controller, JS::ArrayBuffer& buffer, u64 byte_offset, u64 byte_length)
  2766. {
  2767. auto& vm = controller.vm();
  2768. // 1. Let cloneResult be CloneArrayBuffer(buffer, byteOffset, byteLength, %ArrayBuffer%).
  2769. auto clone_result = JS::clone_array_buffer(vm, buffer, byte_offset, byte_length);
  2770. // 2. If cloneResult is an abrupt completion,
  2771. if (clone_result.is_throw_completion()) {
  2772. auto throw_completion = Bindings::throw_dom_exception_if_needed(vm, [&] { return clone_result; }).throw_completion();
  2773. // 1. Perform ! ReadableByteStreamControllerError(controller, cloneResult.[[Value]]).
  2774. readable_byte_stream_controller_error(controller, throw_completion.value().value());
  2775. // 2. Return cloneResult.
  2776. // Note: We need to return the throw_completion object here, as enqueue needs to throw the same object that the controller is errored with
  2777. return throw_completion;
  2778. }
  2779. // 3. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, cloneResult.[[Value]], 0, byteLength).
  2780. readable_byte_stream_controller_enqueue_chunk_to_queue(controller, *clone_result.release_value(), 0, byte_length);
  2781. return {};
  2782. }
  2783. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-shift-pending-pull-into
  2784. PullIntoDescriptor readable_byte_stream_controller_shift_pending_pull_into(ReadableByteStreamController& controller)
  2785. {
  2786. // 1. Assert: controller.[[byobRequest]] is null.
  2787. VERIFY(!controller.raw_byob_request());
  2788. // 2. Let descriptor be controller.[[pendingPullIntos]][0].
  2789. // 3. Remove descriptor from controller.[[pendingPullIntos]].
  2790. auto descriptor = controller.pending_pull_intos().take_first();
  2791. // 4. Return descriptor.
  2792. return descriptor;
  2793. }
  2794. // https://streams.spec.whatwg.org/#readablestream-set-up-with-byte-reading-support
  2795. 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)
  2796. {
  2797. auto& realm = stream.realm();
  2798. // 1. Let startAlgorithm be an algorithm that returns undefined.
  2799. auto start_algorithm = JS::create_heap_function(realm.heap(), []() -> WebIDL::ExceptionOr<JS::Value> { return JS::js_undefined(); });
  2800. // 2. Let pullAlgorithmWrapper be an algorithm that runs these steps:
  2801. auto pull_algorithm_wrapper = JS::create_heap_function(realm.heap(), [&realm, pull_algorithm]() {
  2802. // 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.
  2803. JS::GCPtr<JS::PromiseCapability> result = nullptr;
  2804. if (pull_algorithm)
  2805. result = pull_algorithm->function()();
  2806. // 2. If result is a Promise, then return result.
  2807. if (result != nullptr)
  2808. return JS::NonnullGCPtr(*result);
  2809. // 3. Return a promise resolved with undefined.
  2810. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2811. });
  2812. // 3. Let cancelAlgorithmWrapper be an algorithm that runs these steps:
  2813. auto cancel_algorithm_wrapper = JS::create_heap_function(realm.heap(), [&realm, cancel_algorithm](JS::Value c) {
  2814. // 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.
  2815. JS::GCPtr<JS::PromiseCapability> result = nullptr;
  2816. if (cancel_algorithm)
  2817. result = cancel_algorithm->function()(c);
  2818. // 2. If result is a Promise, then return result.
  2819. if (result != nullptr)
  2820. return JS::NonnullGCPtr(*result);
  2821. // 3. Return a promise resolved with undefined.
  2822. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2823. });
  2824. // 4. Perform ! InitializeReadableStream(stream).
  2825. // 5. Let controller be a new ReadableByteStreamController.
  2826. auto controller = stream.heap().allocate<ReadableByteStreamController>(realm, realm);
  2827. // 6. Perform ! SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithmWrapper, cancelAlgorithmWrapper, highWaterMark, undefined).
  2828. MUST(set_up_readable_byte_stream_controller(stream, controller, start_algorithm, pull_algorithm_wrapper, cancel_algorithm_wrapper, high_water_mark, JS::js_undefined()));
  2829. }
  2830. // https://streams.spec.whatwg.org/#writable-stream-abort
  2831. JS::NonnullGCPtr<WebIDL::Promise> writable_stream_abort(WritableStream& stream, JS::Value reason)
  2832. {
  2833. auto& realm = stream.realm();
  2834. // 1. If stream.[[state]] is "closed" or "errored", return a promise resolved with undefined.
  2835. auto state = stream.state();
  2836. if (state == WritableStream::State::Closed || state == WritableStream::State::Errored)
  2837. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2838. // 2. Signal abort on stream.[[controller]].[[signal]] with reason.
  2839. stream.controller()->signal()->signal_abort(reason);
  2840. // 3. Let state be stream.[[state]].
  2841. state = stream.state();
  2842. // 4. If state is "closed" or "errored", return a promise resolved with undefined.
  2843. if (state == WritableStream::State::Closed || state == WritableStream::State::Errored)
  2844. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2845. // 5. If stream.[[pendingAbortRequest]] is not undefined, return stream.[[pendingAbortRequest]]'s promise.
  2846. if (stream.pending_abort_request().has_value())
  2847. return stream.pending_abort_request()->promise;
  2848. // 6. Assert: state is "writable" or "erroring".
  2849. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  2850. // 7. Let wasAlreadyErroring be false.
  2851. auto was_already_erroring = false;
  2852. // 8. If state is "erroring",
  2853. if (state == WritableStream::State::Erroring) {
  2854. // 1. Set wasAlreadyErroring to true.
  2855. was_already_erroring = true;
  2856. // 2. Set reason to undefined.
  2857. reason = JS::js_undefined();
  2858. }
  2859. // 9. Let promise be a new promise.
  2860. auto promise = WebIDL::create_promise(realm);
  2861. // 10. Set stream.[[pendingAbortRequest]] to a new pending abort request whose promise is promise, reason is reason, and was already erroring is wasAlreadyErroring.
  2862. stream.set_pending_abort_request(PendingAbortRequest { promise, reason, was_already_erroring });
  2863. // 11. If wasAlreadyErroring is false, perform ! WritableStreamStartErroring(stream, reason).
  2864. if (!was_already_erroring)
  2865. writable_stream_start_erroring(stream, reason);
  2866. // 12. Return promise.
  2867. return promise;
  2868. }
  2869. // https://streams.spec.whatwg.org/#writable-stream-close
  2870. JS::NonnullGCPtr<WebIDL::Promise> writable_stream_close(WritableStream& stream)
  2871. {
  2872. auto& realm = stream.realm();
  2873. // 1. Let state be stream.[[state]].
  2874. auto state = stream.state();
  2875. // 2. If state is "closed" or "errored", return a promise rejected with a TypeError exception.
  2876. if (state == WritableStream::State::Closed || state == WritableStream::State::Errored) {
  2877. auto message = state == WritableStream::State::Closed ? "Cannot close a closed stream"sv : "Cannot close an errored stream"sv;
  2878. auto exception = JS::TypeError::create(realm, message);
  2879. return WebIDL::create_rejected_promise(realm, exception);
  2880. }
  2881. // 3. Assert: state is "writable" or "erroring".
  2882. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  2883. // 4. Assert: ! WritableStreamCloseQueuedOrInFlight(stream) is false.
  2884. VERIFY(!writable_stream_close_queued_or_in_flight(stream));
  2885. // 5. Let promise be a new promise.
  2886. auto promise = WebIDL::create_promise(realm);
  2887. // 6. Set stream.[[closeRequest]] to promise.
  2888. stream.set_close_request(promise);
  2889. // 7. Let writer be stream.[[writer]].
  2890. auto writer = stream.writer();
  2891. // 8. If writer is not undefined, and stream.[[backpressure]] is true, and state is "writable", resolve writer.[[readyPromise]] with undefined.
  2892. if (writer && stream.backpressure() && state == WritableStream::State::Writable)
  2893. WebIDL::resolve_promise(realm, *writer->ready_promise(), JS::js_undefined());
  2894. // 9. Perform ! WritableStreamDefaultControllerClose(stream.[[controller]]).
  2895. writable_stream_default_controller_close(*stream.controller());
  2896. // 10. Return promise.
  2897. return promise;
  2898. }
  2899. // https://streams.spec.whatwg.org/#writable-stream-add-write-request
  2900. JS::NonnullGCPtr<WebIDL::Promise> writable_stream_add_write_request(WritableStream& stream)
  2901. {
  2902. auto& realm = stream.realm();
  2903. // 1. Assert: ! IsWritableStreamLocked(stream) is true.
  2904. VERIFY(is_writable_stream_locked(stream));
  2905. // 2. Assert: stream.[[state]] is "writable".
  2906. VERIFY(stream.state() == WritableStream::State::Writable);
  2907. // 3. Let promise be a new promise.
  2908. auto promise = WebIDL::create_promise(realm);
  2909. // 4. Append promise to stream.[[writeRequests]].
  2910. stream.write_requests().append(promise);
  2911. // 5. Return promise.
  2912. return promise;
  2913. }
  2914. // https://streams.spec.whatwg.org/#writable-stream-close-queued-or-in-flight
  2915. bool writable_stream_close_queued_or_in_flight(WritableStream const& stream)
  2916. {
  2917. // 1. If stream.[[closeRequest]] is undefined and stream.[[inFlightCloseRequest]] is undefined, return false.
  2918. if (!stream.close_request() && !stream.in_flight_close_request())
  2919. return false;
  2920. // 2. Return true.
  2921. return true;
  2922. }
  2923. // https://streams.spec.whatwg.org/#writable-stream-deal-with-rejection
  2924. void writable_stream_deal_with_rejection(WritableStream& stream, JS::Value error)
  2925. {
  2926. // 1. Let state be stream.[[state]].
  2927. auto state = stream.state();
  2928. // 2. If state is "writable",
  2929. if (state == WritableStream::State::Writable) {
  2930. // 1. Perform ! WritableStreamStartErroring(stream, error).
  2931. writable_stream_start_erroring(stream, error);
  2932. // 2. Return.
  2933. return;
  2934. }
  2935. // 3. Assert: state is "erroring".
  2936. VERIFY(state == WritableStream::State::Erroring);
  2937. // 4. Perform ! WritableStreamFinishErroring(stream).
  2938. writable_stream_finish_erroring(stream);
  2939. }
  2940. // https://streams.spec.whatwg.org/#writable-stream-finish-erroring
  2941. void writable_stream_finish_erroring(WritableStream& stream)
  2942. {
  2943. auto& realm = stream.realm();
  2944. // 1. Assert: stream.[[state]] is "erroring".
  2945. VERIFY(stream.state() == WritableStream::State::Erroring);
  2946. // 2. Assert: ! WritableStreamHasOperationMarkedInFlight(stream) is false.
  2947. VERIFY(!writable_stream_has_operation_marked_in_flight(stream));
  2948. // 3. Set stream.[[state]] to "errored".
  2949. stream.set_state(WritableStream::State::Errored);
  2950. // 4. Perform ! stream.[[controller]].[[ErrorSteps]]().
  2951. stream.controller()->error_steps();
  2952. // 5. Let storedError be stream.[[storedError]].
  2953. auto stored_error = stream.stored_error();
  2954. // 6. For each writeRequest of stream.[[writeRequests]]:
  2955. for (auto& write_request : stream.write_requests()) {
  2956. // 1. Reject writeRequest with storedError.
  2957. WebIDL::reject_promise(realm, *write_request, stored_error);
  2958. }
  2959. // 7. Set stream.[[writeRequests]] to an empty list.
  2960. stream.write_requests().clear();
  2961. // 8. If stream.[[pendingAbortRequest]] is undefined,
  2962. if (!stream.pending_abort_request().has_value()) {
  2963. // 1. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).
  2964. writable_stream_reject_close_and_closed_promise_if_needed(stream);
  2965. // 2. Return.
  2966. return;
  2967. }
  2968. // 9. Let abortRequest be stream.[[pendingAbortRequest]].
  2969. // 10. Set stream.[[pendingAbortRequest]] to undefined.
  2970. auto abort_request = stream.pending_abort_request().release_value();
  2971. // 11. If abortRequest’s was already erroring is true,
  2972. if (abort_request.was_already_erroring) {
  2973. // 1. Reject abortRequest’s promise with storedError.
  2974. WebIDL::reject_promise(realm, abort_request.promise, stored_error);
  2975. // 2. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).
  2976. writable_stream_reject_close_and_closed_promise_if_needed(stream);
  2977. // 3. Return.
  2978. return;
  2979. }
  2980. // 12. Let promise be ! stream.[[controller]].[[AbortSteps]](abortRequest’s reason).
  2981. auto promise = stream.controller()->abort_steps(abort_request.reason);
  2982. // 13. Upon fulfillment of promise,
  2983. WebIDL::upon_fulfillment(*promise, JS::create_heap_function(realm.heap(), [&realm, &stream, abort_promise = abort_request.promise](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {
  2984. // 1. Resolve abortRequest’s promise with undefined.
  2985. WebIDL::resolve_promise(realm, abort_promise, JS::js_undefined());
  2986. // 2. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).
  2987. writable_stream_reject_close_and_closed_promise_if_needed(stream);
  2988. return JS::js_undefined();
  2989. }));
  2990. // 14. Upon rejection of promise with reason reason,
  2991. WebIDL::upon_rejection(*promise, JS::create_heap_function(realm.heap(), [&realm, &stream, abort_promise = abort_request.promise](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {
  2992. // 1. Reject abortRequest’s promise with reason.
  2993. WebIDL::reject_promise(realm, abort_promise, reason);
  2994. // 2. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).
  2995. writable_stream_reject_close_and_closed_promise_if_needed(stream);
  2996. return JS::js_undefined();
  2997. }));
  2998. }
  2999. // https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-close
  3000. void writable_stream_finish_in_flight_close(WritableStream& stream)
  3001. {
  3002. auto& realm = stream.realm();
  3003. // 1. Assert: stream.[[inFlightCloseRequest]] is not undefined.
  3004. VERIFY(stream.in_flight_close_request());
  3005. // 2. Resolve stream.[[inFlightCloseRequest]] with undefined.
  3006. WebIDL::resolve_promise(realm, *stream.in_flight_close_request(), JS::js_undefined());
  3007. // 3. Set stream.[[inFlightCloseRequest]] to undefined.
  3008. stream.set_in_flight_close_request({});
  3009. // 4. Let state be stream.[[state]].
  3010. auto state = stream.state();
  3011. // 5. Assert: stream.[[state]] is "writable" or "erroring".
  3012. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  3013. // 6. If state is "erroring",
  3014. if (state == WritableStream::State::Erroring) {
  3015. // 1. Set stream.[[storedError]] to undefined.
  3016. stream.set_stored_error(JS::js_undefined());
  3017. // 2. If stream.[[pendingAbortRequest]] is not undefined,
  3018. if (stream.pending_abort_request().has_value()) {
  3019. // 1. Resolve stream.[[pendingAbortRequest]]'s promise with undefined.
  3020. // 2. Set stream.[[pendingAbortRequest]] to undefined.
  3021. WebIDL::resolve_promise(realm, stream.pending_abort_request().release_value().promise, JS::js_undefined());
  3022. }
  3023. }
  3024. // 7. Set stream.[[state]] to "closed".
  3025. stream.set_state(WritableStream::State::Closed);
  3026. // 8. Let writer be stream.[[writer]].
  3027. auto writer = stream.writer();
  3028. // 9. If writer is not undefined, resolve writer.[[closedPromise]] with undefined.
  3029. if (writer)
  3030. WebIDL::resolve_promise(realm, *writer->closed_promise(), JS::js_undefined());
  3031. // 10. Assert: stream.[[pendingAbortRequest]] is undefined.
  3032. VERIFY(!stream.pending_abort_request().has_value());
  3033. // 11. Assert: stream.[[storedError]] is undefined.
  3034. VERIFY(stream.stored_error().is_undefined());
  3035. }
  3036. // https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-close-with-error
  3037. void writable_stream_finish_in_flight_close_with_error(WritableStream& stream, JS::Value error)
  3038. {
  3039. auto& realm = stream.realm();
  3040. // 1. Assert: stream.[[inFlightCloseRequest]] is not undefined.
  3041. VERIFY(stream.in_flight_close_request());
  3042. // 2. Reject stream.[[inFlightCloseRequest]] with error.
  3043. WebIDL::reject_promise(realm, *stream.in_flight_close_request(), error);
  3044. // 3. Set stream.[[inFlightCloseRequest]] to undefined.
  3045. stream.set_in_flight_close_request({});
  3046. // 4. Assert: stream.[[state]] is "writable" or "erroring".
  3047. auto state = stream.state();
  3048. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  3049. // 5. If stream.[[pendingAbortRequest]] is not undefined,
  3050. if (stream.pending_abort_request().has_value()) {
  3051. // 1. Reject stream.[[pendingAbortRequest]]'s promise with error.
  3052. // 2. Set stream.[[pendingAbortRequest]] to undefined.
  3053. WebIDL::reject_promise(realm, stream.pending_abort_request().release_value().promise, error);
  3054. }
  3055. // 6. Perform ! WritableStreamDealWithRejection(stream, error).
  3056. writable_stream_deal_with_rejection(stream, error);
  3057. }
  3058. // https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-write
  3059. void writable_stream_finish_in_flight_write(WritableStream& stream)
  3060. {
  3061. auto& realm = stream.realm();
  3062. // 1. Assert: stream.[[inFlightWriteRequest]] is not undefined.
  3063. VERIFY(stream.in_flight_write_request());
  3064. // 2. Resolve stream.[[inFlightWriteRequest]] with undefined.
  3065. WebIDL::resolve_promise(realm, *stream.in_flight_write_request(), JS::js_undefined());
  3066. // 3. Set stream.[[inFlightWriteRequest]] to undefined.
  3067. stream.set_in_flight_write_request({});
  3068. }
  3069. // https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-write-with-error
  3070. void writable_stream_finish_in_flight_write_with_error(WritableStream& stream, JS::Value error)
  3071. {
  3072. auto& realm = stream.realm();
  3073. // 1. Assert: stream.[[inFlightWriteRequest]] is not undefined.
  3074. VERIFY(stream.in_flight_write_request());
  3075. // 2. Reject stream.[[inFlightWriteRequest]] with error.
  3076. WebIDL::reject_promise(realm, *stream.in_flight_write_request(), error);
  3077. // 3. Set stream.[[inFlightWriteRequest]] to undefined.
  3078. stream.set_in_flight_write_request({});
  3079. // 4. Assert: stream.[[state]] is "writable" or "erroring".
  3080. auto state = stream.state();
  3081. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  3082. // 5. Perform ! WritableStreamDealWithRejection(stream, error).
  3083. writable_stream_deal_with_rejection(stream, error);
  3084. }
  3085. // https://streams.spec.whatwg.org/#writable-stream-has-operation-marked-in-flight
  3086. bool writable_stream_has_operation_marked_in_flight(WritableStream const& stream)
  3087. {
  3088. // 1. If stream.[[inFlightWriteRequest]] is undefined and stream.[[inFlightCloseRequest]] is undefined, return false.
  3089. if (!stream.in_flight_write_request() && !stream.in_flight_close_request())
  3090. return false;
  3091. // 2. Return true.
  3092. return true;
  3093. }
  3094. // https://streams.spec.whatwg.org/#writable-stream-mark-close-request-in-flight
  3095. void writable_stream_mark_close_request_in_flight(WritableStream& stream)
  3096. {
  3097. // 1. Assert: stream.[[inFlightCloseRequest]] is undefined.
  3098. VERIFY(!stream.in_flight_close_request());
  3099. // 2. Assert: stream.[[closeRequest]] is not undefined.
  3100. VERIFY(stream.close_request());
  3101. // 3. Set stream.[[inFlightCloseRequest]] to stream.[[closeRequest]].
  3102. stream.set_in_flight_close_request(stream.close_request());
  3103. // 4. Set stream.[[closeRequest]] to undefined.
  3104. stream.set_close_request({});
  3105. }
  3106. // https://streams.spec.whatwg.org/#writable-stream-mark-first-write-request-in-flight
  3107. void writable_stream_mark_first_write_request_in_flight(WritableStream& stream)
  3108. {
  3109. // 1. Assert: stream.[[inFlightWriteRequest]] is undefined.
  3110. VERIFY(!stream.in_flight_write_request());
  3111. // 2. Assert: stream.[[writeRequests]] is not empty.
  3112. VERIFY(!stream.write_requests().is_empty());
  3113. // 3. Let writeRequest be stream.[[writeRequests]][0].
  3114. // 4. Remove writeRequest from stream.[[writeRequests]].
  3115. auto write_request = stream.write_requests().take_first();
  3116. // 5. Set stream.[[inFlightWriteRequest]] to writeRequest.
  3117. stream.set_in_flight_write_request(write_request);
  3118. }
  3119. // https://streams.spec.whatwg.org/#writable-stream-reject-close-and-closed-promise-if-needed
  3120. void writable_stream_reject_close_and_closed_promise_if_needed(WritableStream& stream)
  3121. {
  3122. auto& realm = stream.realm();
  3123. // 1. Assert: stream.[[state]] is "errored".
  3124. VERIFY(stream.state() == WritableStream::State::Errored);
  3125. // 2. If stream.[[closeRequest]] is not undefined,
  3126. if (stream.close_request()) {
  3127. // 1. Assert: stream.[[inFlightCloseRequest]] is undefined.
  3128. VERIFY(!stream.in_flight_close_request());
  3129. // 2. Reject stream.[[closeRequest]] with stream.[[storedError]].
  3130. WebIDL::reject_promise(realm, *stream.close_request(), stream.stored_error());
  3131. // 3. Set stream.[[closeRequest]] to undefined.
  3132. stream.set_close_request({});
  3133. }
  3134. // 3. Let writer be stream.[[writer]].
  3135. auto writer = stream.writer();
  3136. // 4. If writer is not undefined,
  3137. if (writer) {
  3138. // 1. Reject writer.[[closedPromise]] with stream.[[storedError]].
  3139. WebIDL::reject_promise(realm, *writer->closed_promise(), stream.stored_error());
  3140. // 2. Set writer.[[closedPromise]].[[PromiseIsHandled]] to true.
  3141. WebIDL::mark_promise_as_handled(*writer->closed_promise());
  3142. }
  3143. }
  3144. // https://streams.spec.whatwg.org/#writable-stream-start-erroring
  3145. void writable_stream_start_erroring(WritableStream& stream, JS::Value reason)
  3146. {
  3147. // 1. Assert: stream.[[storedError]] is undefined.
  3148. VERIFY(stream.stored_error().is_undefined());
  3149. // 2. Assert: stream.[[state]] is "writable".
  3150. VERIFY(stream.state() == WritableStream::State::Writable);
  3151. // 3. Let controller be stream.[[controller]].
  3152. auto controller = stream.controller();
  3153. // 4. Assert: controller is not undefined.
  3154. VERIFY(controller);
  3155. // 5. Set stream.[[state]] to "erroring".
  3156. stream.set_state(WritableStream::State::Erroring);
  3157. // 6. Set stream.[[storedError]] to reason.
  3158. stream.set_stored_error(reason);
  3159. // 7. Let writer be stream.[[writer]].
  3160. auto writer = stream.writer();
  3161. // 8. If writer is not undefined, perform ! WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason).
  3162. if (writer)
  3163. writable_stream_default_writer_ensure_ready_promise_rejected(*writer, reason);
  3164. // 9. If ! WritableStreamHasOperationMarkedInFlight(stream) is false and controller.[[started]] is true, perform ! WritableStreamFinishErroring(stream).
  3165. if (!writable_stream_has_operation_marked_in_flight(stream) && controller->started())
  3166. writable_stream_finish_erroring(stream);
  3167. }
  3168. // https://streams.spec.whatwg.org/#writable-stream-update-backpressure
  3169. void writable_stream_update_backpressure(WritableStream& stream, bool backpressure)
  3170. {
  3171. auto& realm = stream.realm();
  3172. // 1. Assert: stream.[[state]] is "writable".
  3173. VERIFY(stream.state() == WritableStream::State::Writable);
  3174. // 2. Assert: ! WritableStreamCloseQueuedOrInFlight(stream) is false.
  3175. VERIFY(!writable_stream_close_queued_or_in_flight(stream));
  3176. // 3. Let writer be stream.[[writer]].
  3177. auto writer = stream.writer();
  3178. // 4. If writer is not undefined and backpressure is not stream.[[backpressure]],
  3179. if (writer && backpressure != stream.backpressure()) {
  3180. // 1. If backpressure is true, set writer.[[readyPromise]] to a new promise.
  3181. if (backpressure) {
  3182. writer->set_ready_promise(WebIDL::create_promise(realm));
  3183. }
  3184. // 2. Otherwise,
  3185. else {
  3186. // 1. Assert: backpressure is false.
  3187. // 2. Resolve writer.[[readyPromise]] with undefined.
  3188. WebIDL::resolve_promise(realm, *writer->ready_promise(), JS::js_undefined());
  3189. }
  3190. }
  3191. // 5. Set stream.[[backpressure]] to backpressure.
  3192. stream.set_backpressure(backpressure);
  3193. }
  3194. // https://streams.spec.whatwg.org/#writable-stream-default-writer-abort
  3195. JS::NonnullGCPtr<WebIDL::Promise> writable_stream_default_writer_abort(WritableStreamDefaultWriter& writer, JS::Value reason)
  3196. {
  3197. // 1. Let stream be writer.[[stream]].
  3198. auto stream = writer.stream();
  3199. // 2. Assert: stream is not undefined.
  3200. VERIFY(stream);
  3201. // 3. Return ! WritableStreamAbort(stream, reason).
  3202. return writable_stream_abort(*stream, reason);
  3203. }
  3204. // https://streams.spec.whatwg.org/#writable-stream-default-writer-close
  3205. JS::NonnullGCPtr<WebIDL::Promise> writable_stream_default_writer_close(WritableStreamDefaultWriter& writer)
  3206. {
  3207. // 1. Let stream be writer.[[stream]].
  3208. auto stream = writer.stream();
  3209. // 2. Assert: stream is not undefined.
  3210. VERIFY(stream);
  3211. // 3. Return ! WritableStreamClose(stream).
  3212. return writable_stream_close(*stream);
  3213. }
  3214. // https://streams.spec.whatwg.org/#writable-stream-default-writer-ensure-closed-promise-rejected
  3215. void writable_stream_default_writer_ensure_closed_promise_rejected(WritableStreamDefaultWriter& writer, JS::Value error)
  3216. {
  3217. auto& realm = writer.realm();
  3218. // 1. If writer.[[closedPromise]].[[PromiseState]] is "pending", reject writer.[[closedPromise]] with error.
  3219. auto& closed_promise = verify_cast<JS::Promise>(*writer.closed_promise()->promise());
  3220. if (closed_promise.state() == JS::Promise::State::Pending) {
  3221. WebIDL::reject_promise(realm, *writer.closed_promise(), error);
  3222. }
  3223. // 2. Otherwise, set writer.[[closedPromise]] to a promise rejected with error.
  3224. else {
  3225. writer.set_closed_promise(WebIDL::create_rejected_promise(realm, error));
  3226. }
  3227. // 3. Set writer.[[closedPromise]].[[PromiseIsHandled]] to true.
  3228. WebIDL::mark_promise_as_handled(*writer.closed_promise());
  3229. }
  3230. // https://streams.spec.whatwg.org/#writable-stream-default-writer-ensure-ready-promise-rejected
  3231. void writable_stream_default_writer_ensure_ready_promise_rejected(WritableStreamDefaultWriter& writer, JS::Value error)
  3232. {
  3233. auto& realm = writer.realm();
  3234. // 1. If writer.[[readyPromise]].[[PromiseState]] is "pending", reject writer.[[readyPromise]] with error.
  3235. auto& ready_promise = verify_cast<JS::Promise>(*writer.ready_promise()->promise());
  3236. if (ready_promise.state() == JS::Promise::State::Pending) {
  3237. WebIDL::reject_promise(realm, *writer.ready_promise(), error);
  3238. }
  3239. // 2. Otherwise, set writer.[[readyPromise]] to a promise rejected with error.
  3240. else {
  3241. writer.set_ready_promise(WebIDL::create_rejected_promise(realm, error));
  3242. }
  3243. // 3. Set writer.[[readyPromise]].[[PromiseIsHandled]] to true.
  3244. WebIDL::mark_promise_as_handled(*writer.ready_promise());
  3245. }
  3246. // https://streams.spec.whatwg.org/#writable-stream-default-writer-get-desired-size
  3247. Optional<double> writable_stream_default_writer_get_desired_size(WritableStreamDefaultWriter const& writer)
  3248. {
  3249. // 1. Let stream be writer.[[stream]].
  3250. auto stream = writer.stream();
  3251. // 2. Let state be stream.[[state]].
  3252. auto state = stream->state();
  3253. // 3. If state is "errored" or "erroring", return null.
  3254. if (state == WritableStream::State::Errored || state == WritableStream::State::Erroring)
  3255. return {};
  3256. // 4. If state is "closed", return 0.
  3257. if (state == WritableStream::State::Closed)
  3258. return 0.0;
  3259. // 5. Return ! WritableStreamDefaultControllerGetDesiredSize(stream.[[controller]]).
  3260. return writable_stream_default_controller_get_desired_size(*stream->controller());
  3261. }
  3262. // https://streams.spec.whatwg.org/#writable-stream-default-writer-release
  3263. void writable_stream_default_writer_release(WritableStreamDefaultWriter& writer)
  3264. {
  3265. auto& realm = writer.realm();
  3266. // 1. Let stream be writer.[[stream]].
  3267. auto stream = writer.stream();
  3268. // 2. Assert: stream is not undefined.
  3269. VERIFY(stream);
  3270. // 3. Assert: stream.[[writer]] is writer.
  3271. VERIFY(stream->writer().ptr() == &writer);
  3272. // 4. Let releasedError be a new TypeError.
  3273. auto released_error = JS::TypeError::create(realm, "Writer's stream lock has been released"sv);
  3274. // 5. Perform ! WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError).
  3275. writable_stream_default_writer_ensure_ready_promise_rejected(writer, released_error);
  3276. // 6. Perform ! WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError).
  3277. writable_stream_default_writer_ensure_closed_promise_rejected(writer, released_error);
  3278. // 7. Set stream.[[writer]] to undefined.
  3279. stream->set_writer({});
  3280. // 8. Set writer.[[stream]] to undefined.
  3281. writer.set_stream({});
  3282. }
  3283. // https://streams.spec.whatwg.org/#writable-stream-default-writer-write
  3284. JS::NonnullGCPtr<WebIDL::Promise> writable_stream_default_writer_write(WritableStreamDefaultWriter& writer, JS::Value chunk)
  3285. {
  3286. auto& realm = writer.realm();
  3287. // 1. Let stream be writer.[[stream]].
  3288. auto stream = writer.stream();
  3289. // 2. Assert: stream is not undefined.
  3290. VERIFY(stream);
  3291. // 3. Let controller be stream.[[controller]].
  3292. auto controller = stream->controller();
  3293. // 4. Let chunkSize be ! WritableStreamDefaultControllerGetChunkSize(controller, chunk).
  3294. auto chunk_size = writable_stream_default_controller_get_chunk_size(*controller, chunk);
  3295. // 5. If stream is not equal to writer.[[stream]], return a promise rejected with a TypeError exception.
  3296. if (stream.ptr() != writer.stream().ptr()) {
  3297. auto exception = JS::TypeError::create(realm, "Writer's locked stream changed during write"sv);
  3298. return WebIDL::create_rejected_promise(realm, exception);
  3299. }
  3300. // 6. Let state be stream.[[state]].
  3301. auto state = stream->state();
  3302. // 7. If state is "errored", return a promise rejected with stream.[[storedError]].
  3303. if (state == WritableStream::State::Errored)
  3304. return WebIDL::create_rejected_promise(realm, stream->stored_error());
  3305. // 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.
  3306. if (writable_stream_close_queued_or_in_flight(*stream) || state == WritableStream::State::Closed) {
  3307. auto exception = JS::TypeError::create(realm, "Cannot write to a writer whose stream is closing or already closed"sv);
  3308. return WebIDL::create_rejected_promise(realm, exception);
  3309. }
  3310. // 9. If state is "erroring", return a promise rejected with stream.[[storedError]].
  3311. if (state == WritableStream::State::Erroring)
  3312. return WebIDL::create_rejected_promise(realm, stream->stored_error());
  3313. // 10. Assert: state is "writable".
  3314. VERIFY(state == WritableStream::State::Writable);
  3315. // 11. Let promise be ! WritableStreamAddWriteRequest(stream).
  3316. auto promise = writable_stream_add_write_request(*stream);
  3317. // 12. Perform ! WritableStreamDefaultControllerWrite(controller, chunk, chunkSize).
  3318. writable_stream_default_controller_write(*controller, chunk, chunk_size);
  3319. // 13. Return promise.
  3320. return promise;
  3321. }
  3322. // https://streams.spec.whatwg.org/#set-up-writable-stream-default-controller
  3323. 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)
  3324. {
  3325. auto& realm = stream.realm();
  3326. // 1. Assert: stream implements WritableStream.
  3327. // 2. Assert: stream.[[controller]] is undefined.
  3328. VERIFY(!stream.controller());
  3329. // 3. Set controller.[[stream]] to stream.
  3330. controller.set_stream(stream);
  3331. // 4. Set stream.[[controller]] to controller.
  3332. stream.set_controller(controller);
  3333. // 5. Perform ! ResetQueue(controller).
  3334. reset_queue(controller);
  3335. // 6. Set controller.[[signal]] to a new AbortSignal.
  3336. controller.set_signal(realm.heap().allocate<DOM::AbortSignal>(realm, realm));
  3337. // 7. Set controller.[[started]] to false.
  3338. controller.set_started(false);
  3339. // 8. Set controller.[[strategySizeAlgorithm]] to sizeAlgorithm.
  3340. controller.set_strategy_size_algorithm(size_algorithm);
  3341. // 9. Set controller.[[strategyHWM]] to highWaterMark.
  3342. controller.set_strategy_hwm(high_water_mark);
  3343. // 10. Set controller.[[writeAlgorithm]] to writeAlgorithm.
  3344. controller.set_write_algorithm(write_algorithm);
  3345. // 11. Set controller.[[closeAlgorithm]] to closeAlgorithm.
  3346. controller.set_close_algorithm(close_algorithm);
  3347. // 12. Set controller.[[abortAlgorithm]] to abortAlgorithm.
  3348. controller.set_abort_algorithm(abort_algorithm);
  3349. // 13. Let backpressure be ! WritableStreamDefaultControllerGetBackpressure(controller).
  3350. auto backpressure = writable_stream_default_controller_get_backpressure(controller);
  3351. // 14. Perform ! WritableStreamUpdateBackpressure(stream, backpressure).
  3352. writable_stream_update_backpressure(stream, backpressure);
  3353. // 15. Let startResult be the result of performing startAlgorithm. (This may throw an exception.)
  3354. auto start_result = TRY(start_algorithm->function()());
  3355. // 16. Let startPromise be a promise resolved with startResult.
  3356. auto start_promise = WebIDL::create_resolved_promise(realm, start_result);
  3357. // 17. Upon fulfillment of startPromise,
  3358. WebIDL::upon_fulfillment(*start_promise, JS::create_heap_function(realm.heap(), [&controller, &stream](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {
  3359. // 1. Assert: stream.[[state]] is "writable" or "erroring".
  3360. auto state = stream.state();
  3361. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  3362. // 2. Set controller.[[started]] to true.
  3363. controller.set_started(true);
  3364. // 3. Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).
  3365. writable_stream_default_controller_advance_queue_if_needed(controller);
  3366. return JS::js_undefined();
  3367. }));
  3368. // 18. Upon rejection of startPromise with reason r,
  3369. WebIDL::upon_rejection(*start_promise, JS::create_heap_function(realm.heap(), [&stream, &controller](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {
  3370. // 1. Assert: stream.[[state]] is "writable" or "erroring".
  3371. auto state = stream.state();
  3372. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  3373. // 2. Set controller.[[started]] to true.
  3374. controller.set_started(true);
  3375. // 3. Perform ! WritableStreamDealWithRejection(stream, r).
  3376. writable_stream_deal_with_rejection(stream, reason);
  3377. return JS::js_undefined();
  3378. }));
  3379. return {};
  3380. }
  3381. // https://streams.spec.whatwg.org/#set-up-writable-stream-default-controller-from-underlying-sink
  3382. 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)
  3383. {
  3384. auto& realm = stream.realm();
  3385. // 1. Let controller be a new WritableStreamDefaultController.
  3386. auto controller = realm.heap().allocate<WritableStreamDefaultController>(realm, realm);
  3387. // 2. Let startAlgorithm be an algorithm that returns undefined.
  3388. auto start_algorithm = JS::create_heap_function(realm.heap(), []() -> WebIDL::ExceptionOr<JS::Value> { return JS::js_undefined(); });
  3389. // 3. Let writeAlgorithm be an algorithm that returns a promise resolved with undefined.
  3390. auto write_algorithm = JS::create_heap_function(realm.heap(), [&realm](JS::Value) {
  3391. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  3392. });
  3393. // 4. Let closeAlgorithm be an algorithm that returns a promise resolved with undefined.
  3394. auto close_algorithm = JS::create_heap_function(realm.heap(), [&realm]() {
  3395. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  3396. });
  3397. // 5. Let abortAlgorithm be an algorithm that returns a promise resolved with undefined.
  3398. auto abort_algorithm = JS::create_heap_function(realm.heap(), [&realm](JS::Value) {
  3399. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  3400. });
  3401. // 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.
  3402. if (underlying_sink.start) {
  3403. start_algorithm = JS::create_heap_function(realm.heap(), [controller, underlying_sink_value, callback = underlying_sink.start]() -> WebIDL::ExceptionOr<JS::Value> {
  3404. // Note: callback does not return a promise, so invoke_callback may return an abrupt completion
  3405. return TRY(WebIDL::invoke_callback(*callback, underlying_sink_value, controller)).release_value();
  3406. });
  3407. }
  3408. // 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.
  3409. if (underlying_sink.write) {
  3410. write_algorithm = JS::create_heap_function(realm.heap(), [&realm, controller, underlying_sink_value, callback = underlying_sink.write](JS::Value chunk) {
  3411. // Note: callback returns a promise, so invoke_callback will never return an abrupt completion
  3412. auto result = MUST(WebIDL::invoke_callback(*callback, underlying_sink_value, chunk, controller)).release_value();
  3413. return WebIDL::create_resolved_promise(realm, result);
  3414. });
  3415. }
  3416. // 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.
  3417. if (underlying_sink.close) {
  3418. close_algorithm = JS::create_heap_function(realm.heap(), [&realm, underlying_sink_value, callback = underlying_sink.close]() {
  3419. // Note: callback returns a promise, so invoke_callback will never return an abrupt completion
  3420. auto result = MUST(WebIDL::invoke_callback(*callback, underlying_sink_value)).release_value();
  3421. return WebIDL::create_resolved_promise(realm, result);
  3422. });
  3423. }
  3424. // 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.
  3425. if (underlying_sink.abort) {
  3426. abort_algorithm = JS::create_heap_function(realm.heap(), [&realm, underlying_sink_value, callback = underlying_sink.abort](JS::Value reason) {
  3427. // Note: callback returns a promise, so invoke_callback will never return an abrupt completion
  3428. auto result = MUST(WebIDL::invoke_callback(*callback, underlying_sink_value, reason)).release_value();
  3429. return WebIDL::create_resolved_promise(realm, result);
  3430. });
  3431. }
  3432. // 10. Perform ? SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm).
  3433. TRY(set_up_writable_stream_default_controller(stream, controller, start_algorithm, write_algorithm, close_algorithm, abort_algorithm, high_water_mark, size_algorithm));
  3434. return {};
  3435. }
  3436. // https://streams.spec.whatwg.org/#writable-stream-default-controller-advance-queue-if-needed
  3437. void writable_stream_default_controller_advance_queue_if_needed(WritableStreamDefaultController& controller)
  3438. {
  3439. // 1. Let stream be controller.[[stream]].
  3440. auto stream = controller.stream();
  3441. // 2. If controller.[[started]] is false, return.
  3442. if (!controller.started())
  3443. return;
  3444. // 3. If stream.[[inFlightWriteRequest]] is not undefined, return.
  3445. if (stream->in_flight_write_request())
  3446. return;
  3447. // 4. Let state be stream.[[state]].
  3448. auto state = stream->state();
  3449. // 5. Assert: state is not "closed" or "errored".
  3450. VERIFY(state != WritableStream::State::Closed && state != WritableStream::State::Errored);
  3451. // 6. If state is "erroring",
  3452. if (state == WritableStream::State::Erroring) {
  3453. // 1. Perform ! WritableStreamFinishErroring(stream).
  3454. writable_stream_finish_erroring(*stream);
  3455. // 2. Return.
  3456. return;
  3457. }
  3458. // 7. If controller.[[queue]] is empty, return.
  3459. if (controller.queue().is_empty())
  3460. return;
  3461. // 8. Let value be ! PeekQueueValue(controller).
  3462. auto value = peek_queue_value(controller);
  3463. // 9. If value is the close sentinel, perform ! WritableStreamDefaultControllerProcessClose(controller).
  3464. if (is_close_sentinel(value)) {
  3465. writable_stream_default_controller_process_close(controller);
  3466. }
  3467. // 10. Otherwise, perform ! WritableStreamDefaultControllerProcessWrite(controller, value).
  3468. else {
  3469. writable_stream_default_controller_process_write(controller, value);
  3470. }
  3471. }
  3472. // https://streams.spec.whatwg.org/#writable-stream-default-controller-clear-algorithms
  3473. void writable_stream_default_controller_clear_algorithms(WritableStreamDefaultController& controller)
  3474. {
  3475. // 1. Set controller.[[writeAlgorithm]] to undefined.
  3476. controller.set_write_algorithm({});
  3477. // 2. Set controller.[[closeAlgorithm]] to undefined.
  3478. controller.set_close_algorithm({});
  3479. // 3. Set controller.[[abortAlgorithm]] to undefined.
  3480. controller.set_abort_algorithm({});
  3481. // 4. Set controller.[[strategySizeAlgorithm]] to undefined.
  3482. controller.set_strategy_size_algorithm({});
  3483. }
  3484. // https://streams.spec.whatwg.org/#writable-stream-default-controller-close
  3485. void writable_stream_default_controller_close(WritableStreamDefaultController& controller)
  3486. {
  3487. // 1. Perform ! EnqueueValueWithSize(controller, close sentinel, 0).
  3488. MUST(enqueue_value_with_size(controller, create_close_sentinel(), JS::Value(0.0)));
  3489. // 2. Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).
  3490. writable_stream_default_controller_advance_queue_if_needed(controller);
  3491. }
  3492. // https://streams.spec.whatwg.org/#writable-stream-default-controller-error
  3493. void writable_stream_default_controller_error(WritableStreamDefaultController& controller, JS::Value error)
  3494. {
  3495. // 1. Let stream be controller.[[stream]].
  3496. auto stream = controller.stream();
  3497. // 2. Assert: stream.[[state]] is "writable".
  3498. VERIFY(stream->state() == WritableStream::State::Writable);
  3499. // 3. Perform ! WritableStreamDefaultControllerClearAlgorithms(controller).
  3500. writable_stream_default_controller_clear_algorithms(controller);
  3501. // 4. Perform ! WritableStreamStartErroring(stream, error).
  3502. writable_stream_start_erroring(stream, error);
  3503. }
  3504. // https://streams.spec.whatwg.org/#writable-stream-default-controller-error-if-needed
  3505. void writable_stream_default_controller_error_if_needed(WritableStreamDefaultController& controller, JS::Value error)
  3506. {
  3507. // 1. If controller.[[stream]].[[state]] is "writable", perform ! WritableStreamDefaultControllerError(controller, error).
  3508. if (controller.stream()->state() == WritableStream::State::Writable)
  3509. writable_stream_default_controller_error(controller, error);
  3510. }
  3511. // https://streams.spec.whatwg.org/#writable-stream-default-controller-get-backpressure
  3512. bool writable_stream_default_controller_get_backpressure(WritableStreamDefaultController const& controller)
  3513. {
  3514. // 1. Let desiredSize be ! WritableStreamDefaultControllerGetDesiredSize(controller).
  3515. auto desired_size = writable_stream_default_controller_get_desired_size(controller);
  3516. // 2. Return true if desiredSize ≤ 0, or false otherwise.
  3517. return desired_size <= 0.0;
  3518. }
  3519. // https://streams.spec.whatwg.org/#writable-stream-default-controller-get-chunk-size
  3520. JS::Value writable_stream_default_controller_get_chunk_size(WritableStreamDefaultController& controller, JS::Value chunk)
  3521. {
  3522. // 1. Let returnValue be the result of performing controller.[[strategySizeAlgorithm]], passing in chunk, and interpreting the result as a completion record.
  3523. auto return_value = controller.strategy_size_algorithm()->function()(chunk);
  3524. // 2. If returnValue is an abrupt completion,
  3525. if (return_value.is_abrupt()) {
  3526. // 1. Perform ! WritableStreamDefaultControllerErrorIfNeeded(controller, returnValue.[[Value]]).
  3527. writable_stream_default_controller_error_if_needed(controller, *return_value.release_value());
  3528. // 2. Return 1.
  3529. return JS::Value { 1.0 };
  3530. }
  3531. // 3. Return returnValue.[[Value]].
  3532. return *return_value.release_value();
  3533. }
  3534. // https://streams.spec.whatwg.org/#writable-stream-default-controller-get-desired-size
  3535. double writable_stream_default_controller_get_desired_size(WritableStreamDefaultController const& controller)
  3536. {
  3537. // 1. Return controller.[[strategyHWM]] − controller.[[queueTotalSize]].
  3538. return controller.strategy_hwm() - controller.queue_total_size();
  3539. }
  3540. // https://streams.spec.whatwg.org/#writable-stream-default-controller-process-close
  3541. void writable_stream_default_controller_process_close(WritableStreamDefaultController& controller)
  3542. {
  3543. // 1. Let stream be controller.[[stream]].
  3544. auto stream = controller.stream();
  3545. // 2. Perform ! WritableStreamMarkCloseRequestInFlight(stream).
  3546. writable_stream_mark_close_request_in_flight(*stream);
  3547. // 3. Perform ! DequeueValue(controller).
  3548. dequeue_value(controller);
  3549. // 4. Assert: controller.[[queue]] is empty.
  3550. VERIFY(controller.queue().is_empty());
  3551. // 5. Let sinkClosePromise be the result of performing controller.[[closeAlgorithm]].
  3552. auto sink_close_promise = controller.close_algorithm()->function()();
  3553. // 6. Perform ! WritableStreamDefaultControllerClearAlgorithms(controller).
  3554. writable_stream_default_controller_clear_algorithms(controller);
  3555. // 7. Upon fulfillment of sinkClosePromise,
  3556. WebIDL::upon_fulfillment(*sink_close_promise, JS::create_heap_function(controller.heap(), [stream](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {
  3557. // 1. Perform ! WritableStreamFinishInFlightClose(stream).
  3558. writable_stream_finish_in_flight_close(*stream);
  3559. return JS::js_undefined();
  3560. }));
  3561. // 8. Upon rejection of sinkClosePromise with reason reason,
  3562. WebIDL::upon_rejection(*sink_close_promise, JS::create_heap_function(controller.heap(), [stream = stream](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {
  3563. // 1. Perform ! WritableStreamFinishInFlightCloseWithError(stream, reason).
  3564. writable_stream_finish_in_flight_close_with_error(*stream, reason);
  3565. return JS::js_undefined();
  3566. }));
  3567. }
  3568. // https://streams.spec.whatwg.org/#writable-stream-default-controller-process-write
  3569. void writable_stream_default_controller_process_write(WritableStreamDefaultController& controller, JS::Value chunk)
  3570. {
  3571. // 1. Let stream be controller.[[stream]].
  3572. auto stream = controller.stream();
  3573. // 2. Perform ! WritableStreamMarkFirstWriteRequestInFlight(stream).
  3574. writable_stream_mark_first_write_request_in_flight(*stream);
  3575. // 3. Let sinkWritePromise be the result of performing controller.[[writeAlgorithm]], passing in chunk.
  3576. auto sink_write_promise = controller.write_algorithm()->function()(chunk);
  3577. // 4. Upon fulfillment of sinkWritePromise,
  3578. WebIDL::upon_fulfillment(*sink_write_promise, JS::create_heap_function(controller.heap(), [&controller, stream](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {
  3579. // 1. Perform ! WritableStreamFinishInFlightWrite(stream).
  3580. writable_stream_finish_in_flight_write(*stream);
  3581. // 2. Let state be stream.[[state]].
  3582. auto state = stream->state();
  3583. // 3. Assert: state is "writable" or "erroring".
  3584. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  3585. // 4. Perform ! DequeueValue(controller).
  3586. dequeue_value(controller);
  3587. // 5. If ! WritableStreamCloseQueuedOrInFlight(stream) is false and state is "writable",
  3588. if (!writable_stream_close_queued_or_in_flight(*stream) && state == WritableStream::State::Writable) {
  3589. // 1. Let backpressure be ! WritableStreamDefaultControllerGetBackpressure(controller).
  3590. auto backpressure = writable_stream_default_controller_get_backpressure(controller);
  3591. // 2. Perform ! WritableStreamUpdateBackpressure(stream, backpressure).
  3592. writable_stream_update_backpressure(*stream, backpressure);
  3593. }
  3594. // 6 .Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).
  3595. writable_stream_default_controller_advance_queue_if_needed(controller);
  3596. return JS::js_undefined();
  3597. }));
  3598. // 5. Upon rejection of sinkWritePromise with reason,
  3599. WebIDL::upon_rejection(*sink_write_promise, JS::create_heap_function(controller.heap(), [&controller, stream](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {
  3600. // 1. If stream.[[state]] is "writable", perform ! WritableStreamDefaultControllerClearAlgorithms(controller).
  3601. if (stream->state() == WritableStream::State::Writable)
  3602. writable_stream_default_controller_clear_algorithms(controller);
  3603. // 2. Perform ! WritableStreamFinishInFlightWriteWithError(stream, reason).
  3604. writable_stream_finish_in_flight_write_with_error(*stream, reason);
  3605. return JS::js_undefined();
  3606. }));
  3607. }
  3608. // https://streams.spec.whatwg.org/#writable-stream-default-controller-write
  3609. void writable_stream_default_controller_write(WritableStreamDefaultController& controller, JS::Value chunk, JS::Value chunk_size)
  3610. {
  3611. auto& vm = controller.vm();
  3612. // 1. Let enqueueResult be EnqueueValueWithSize(controller, chunk, chunkSize).
  3613. auto enqueue_result = enqueue_value_with_size(controller, chunk, chunk_size);
  3614. // 2. If enqueueResult is an abrupt completion,
  3615. if (enqueue_result.is_exception()) {
  3616. auto throw_completion = Bindings::throw_dom_exception_if_needed(vm, [&] { return enqueue_result; }).throw_completion();
  3617. // 1. Perform ! WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueResult.[[Value]]).
  3618. writable_stream_default_controller_error_if_needed(controller, *throw_completion.release_value());
  3619. // 2. Return.
  3620. return;
  3621. }
  3622. // 3. Let stream be controller.[[stream]].
  3623. auto stream = controller.stream();
  3624. // 4. If ! WritableStreamCloseQueuedOrInFlight(stream) is false and stream.[[state]] is "writable",
  3625. if (!writable_stream_close_queued_or_in_flight(*stream) && stream->state() == WritableStream::State::Writable) {
  3626. // 1. Let backpressure be ! WritableStreamDefaultControllerGetBackpressure(controller).
  3627. auto backpressure = writable_stream_default_controller_get_backpressure(controller);
  3628. // 2. Perform ! WritableStreamUpdateBackpressure(stream, backpressure).
  3629. writable_stream_update_backpressure(*stream, backpressure);
  3630. }
  3631. // 5. Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).
  3632. writable_stream_default_controller_advance_queue_if_needed(controller);
  3633. }
  3634. // https://streams.spec.whatwg.org/#initialize-transform-stream
  3635. 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)
  3636. {
  3637. auto& realm = stream.realm();
  3638. // 1. Let startAlgorithm be an algorithm that returns startPromise.
  3639. auto writable_start_algorithm = JS::create_heap_function(realm.heap(), [start_promise]() -> WebIDL::ExceptionOr<JS::Value> {
  3640. return start_promise->promise();
  3641. });
  3642. auto readable_start_algorithm = JS::create_heap_function(realm.heap(), [start_promise]() -> WebIDL::ExceptionOr<JS::Value> {
  3643. return start_promise->promise();
  3644. });
  3645. // 2. Let writeAlgorithm be the following steps, taking a chunk argument:
  3646. auto write_algorithm = JS::create_heap_function(realm.heap(), [&stream](JS::Value chunk) {
  3647. // 1. Return ! TransformStreamDefaultSinkWriteAlgorithm(stream, chunk).
  3648. return transform_stream_default_sink_write_algorithm(stream, chunk);
  3649. });
  3650. // 3. Let abortAlgorithm be the following steps, taking a reason argument:
  3651. auto abort_algorithm = JS::create_heap_function(realm.heap(), [&stream](JS::Value reason) {
  3652. // 1. Return ! TransformStreamDefaultSinkAbortAlgorithm(stream, reason).
  3653. return transform_stream_default_sink_abort_algorithm(stream, reason);
  3654. });
  3655. // 4. Let closeAlgorithm be the following steps:
  3656. auto close_algorithm = JS::create_heap_function(realm.heap(), [&stream]() {
  3657. // 1. Return ! TransformStreamDefaultSinkCloseAlgorithm(stream).
  3658. return transform_stream_default_sink_close_algorithm(stream);
  3659. });
  3660. // 5. Set stream.[[writable]] to ! CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm).
  3661. stream.set_writable(MUST(create_writable_stream(realm, writable_start_algorithm, write_algorithm, close_algorithm, abort_algorithm, writable_high_water_mark, writable_size_algorithm)));
  3662. // 6. Let pullAlgorithm be the following steps:
  3663. auto pull_algorithm = JS::create_heap_function(realm.heap(), [&stream]() {
  3664. // 1. Return ! TransformStreamDefaultSourcePullAlgorithm(stream).
  3665. return transform_stream_default_source_pull_algorithm(stream);
  3666. });
  3667. // 7. Let cancelAlgorithm be the following steps, taking a reason argument:
  3668. auto cancel_algorithm = JS::create_heap_function(realm.heap(), [&stream](JS::Value reason) {
  3669. // 1. Return ! TransformStreamDefaultSourceCancelAlgorithm(stream, reason).
  3670. return transform_stream_default_source_cancel_algorithm(stream, reason);
  3671. });
  3672. // 8. Set stream.[[readable]] to ! CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm).
  3673. stream.set_readable(MUST(create_readable_stream(realm, readable_start_algorithm, pull_algorithm, cancel_algorithm, readable_high_water_mark, readable_size_algorithm)));
  3674. // 9. Set stream.[[backpressure]] and stream.[[backpressureChangePromise]] to undefined.
  3675. stream.set_backpressure({});
  3676. stream.set_backpressure_change_promise({});
  3677. // 10. Perform ! TransformStreamSetBackpressure(stream, true).
  3678. transform_stream_set_backpressure(stream, true);
  3679. // 11. Set stream.[[controller]] to undefined.
  3680. stream.set_controller({});
  3681. }
  3682. // https://streams.spec.whatwg.org/#set-up-transform-stream-default-controller
  3683. 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)
  3684. {
  3685. // 1. Assert: stream implements TransformStream.
  3686. // 2. Assert: stream.[[controller]] is undefined.
  3687. VERIFY(!stream.controller());
  3688. // 3. Set controller.[[stream]] to stream.
  3689. controller.set_stream(stream);
  3690. // 4. Set stream.[[controller]] to controller.
  3691. stream.set_controller(controller);
  3692. // 5. Set controller.[[transformAlgorithm]] to transformAlgorithm.
  3693. controller.set_transform_algorithm(transform_algorithm);
  3694. // 6. Set controller.[[flushAlgorithm]] to flushAlgorithm.
  3695. controller.set_flush_algorithm(flush_algorithm);
  3696. // 7. Set controller.[[cancelAlgorithm]] to cancelAlgorithm.
  3697. controller.set_cancel_algorithm(cancel_algorithm);
  3698. }
  3699. // https://streams.spec.whatwg.org/#set-up-transform-stream-default-controller-from-transformer
  3700. void set_up_transform_stream_default_controller_from_transformer(TransformStream& stream, JS::Value transformer, Transformer& transformer_dict)
  3701. {
  3702. auto& realm = stream.realm();
  3703. auto& vm = realm.vm();
  3704. // 1. Let controller be a new TransformStreamDefaultController.
  3705. auto controller = realm.heap().allocate<TransformStreamDefaultController>(realm, realm);
  3706. // 2. Let transformAlgorithm be the following steps, taking a chunk argument:
  3707. auto transform_algorithm = JS::create_heap_function(realm.heap(), [controller, &realm, &vm](JS::Value chunk) {
  3708. // 1. Let result be TransformStreamDefaultControllerEnqueue(controller, chunk).
  3709. auto result = transform_stream_default_controller_enqueue(*controller, chunk);
  3710. // 2. If result is an abrupt completion, return a promise rejected with result.[[Value]].
  3711. if (result.is_error()) {
  3712. auto throw_completion = Bindings::dom_exception_to_throw_completion(vm, result.exception());
  3713. return WebIDL::create_rejected_promise(realm, *throw_completion.release_value());
  3714. }
  3715. // 3. Otherwise, return a promise resolved with undefined.
  3716. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  3717. });
  3718. // 3. Let flushAlgorithm be an algorithm which returns a promise resolved with undefined.
  3719. auto flush_algorithm = JS::create_heap_function(realm.heap(), [&realm]() {
  3720. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  3721. });
  3722. // 4. Let cancelAlgorithm be an algorithm which returns a promise resolved with undefined.
  3723. auto cancel_algorithm = JS::create_heap_function(realm.heap(), [&realm](JS::Value) {
  3724. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  3725. });
  3726. // 5. If transformerDict["transform"] exists, set transformAlgorithm to an algorithm which takes an argument chunk
  3727. // and returns the result of invoking transformerDict["transform"] with argument list « chunk, controller » and
  3728. // callback this value transformer.
  3729. if (transformer_dict.transform) {
  3730. transform_algorithm = JS::create_heap_function(realm.heap(), [controller, &realm, transformer, callback = transformer_dict.transform](JS::Value chunk) {
  3731. // Note: callback returns a promise, so invoke_callback will never return an abrupt completion
  3732. auto result = MUST(WebIDL::invoke_callback(*callback, transformer, chunk, controller)).release_value();
  3733. return WebIDL::create_resolved_promise(realm, result);
  3734. });
  3735. }
  3736. // 6. If transformerDict["flush"] exists, set flushAlgorithm to an algorithm which returns the result of invoking
  3737. // transformerDict["flush"] with argument list « controller » and callback this value transformer.
  3738. if (transformer_dict.flush) {
  3739. flush_algorithm = JS::create_heap_function(realm.heap(), [&realm, transformer, callback = transformer_dict.flush, controller]() {
  3740. // Note: callback returns a promise, so invoke_callback will never return an abrupt completion
  3741. auto result = MUST(WebIDL::invoke_callback(*callback, transformer, controller)).release_value();
  3742. return WebIDL::create_resolved_promise(realm, result);
  3743. });
  3744. }
  3745. // 7. If transformerDict["cancel"] exists, set cancelAlgorithm to an algorithm which takes an argument reason and returns
  3746. // the result of invoking transformerDict["cancel"] with argument list « reason » and callback this value transformer.
  3747. if (transformer_dict.cancel) {
  3748. cancel_algorithm = JS::create_heap_function(realm.heap(), [&realm, transformer, callback = transformer_dict.cancel](JS::Value reason) {
  3749. // Note: callback returns a promise, so invoke_callback will never return an abrupt completion
  3750. auto result = MUST(WebIDL::invoke_callback(*callback, transformer, reason)).release_value();
  3751. return WebIDL::create_resolved_promise(realm, result);
  3752. });
  3753. }
  3754. // 8. Perform ! SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm).
  3755. set_up_transform_stream_default_controller(stream, *controller, transform_algorithm, flush_algorithm, cancel_algorithm);
  3756. }
  3757. // https://streams.spec.whatwg.org/#transform-stream-default-controller-clear-algorithms
  3758. void transform_stream_default_controller_clear_algorithms(TransformStreamDefaultController& controller)
  3759. {
  3760. // NOTE: This is observable using weak references. See tc39/proposal-weakrefs#31 for more detail.
  3761. // 1. Set controller.[[transformAlgorithm]] to undefined.
  3762. controller.set_transform_algorithm({});
  3763. // 2. Set controller.[[flushAlgorithm]] to undefined.
  3764. controller.set_flush_algorithm({});
  3765. // 3. Set controller.[[cancelAlgorithm]] to undefined.
  3766. controller.set_cancel_algorithm({});
  3767. }
  3768. // https://streams.spec.whatwg.org/#transform-stream-default-controller-enqueue
  3769. WebIDL::ExceptionOr<void> transform_stream_default_controller_enqueue(TransformStreamDefaultController& controller, JS::Value chunk)
  3770. {
  3771. auto& vm = controller.vm();
  3772. // 1. Let stream be controller.[[stream]].
  3773. auto stream = controller.stream();
  3774. // 2. Let readableController be stream.[[readable]].[[controller]].
  3775. VERIFY(stream->readable()->controller().has_value() && stream->readable()->controller()->has<JS::NonnullGCPtr<ReadableStreamDefaultController>>());
  3776. auto& readable_controller = stream->readable()->controller()->get<JS::NonnullGCPtr<ReadableStreamDefaultController>>();
  3777. // 3. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController) is false, throw a TypeError exception.
  3778. if (!readable_stream_default_controller_can_close_or_enqueue(readable_controller))
  3779. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "ReadableController is either closed or not readable."sv };
  3780. // 4. Let enqueueResult be ReadableStreamDefaultControllerEnqueue(readableController, chunk).
  3781. auto enqueue_result = readable_stream_default_controller_enqueue(readable_controller, chunk);
  3782. // 5. If enqueueResult is an abrupt completion,
  3783. if (enqueue_result.is_error()) {
  3784. auto throw_completion = Bindings::dom_exception_to_throw_completion(vm, enqueue_result.exception());
  3785. // 1. Perform ! TransformStreamErrorWritableAndUnblockWrite(stream, enqueueResult.[[Value]]).
  3786. transform_stream_error_writable_and_unblock_write(*stream, throw_completion.value().value());
  3787. // 2. Throw stream.[[readable]].[[storedError]].
  3788. return JS::throw_completion(stream->readable()->stored_error());
  3789. }
  3790. // 6. Let backpressure be ! ReadableStreamDefaultControllerHasBackpressure(readableController).
  3791. auto backpressure = readable_stream_default_controller_has_backpressure(readable_controller);
  3792. // 7. If backpressure is not stream.[[backpressure]],
  3793. if (backpressure != stream->backpressure()) {
  3794. // 1. Assert: backpressure is true.
  3795. VERIFY(backpressure);
  3796. // 2. Perform ! TransformStreamSetBackpressure(stream, true).
  3797. transform_stream_set_backpressure(*stream, true);
  3798. }
  3799. return {};
  3800. }
  3801. // https://streams.spec.whatwg.org/#transform-stream-default-controller-error
  3802. void transform_stream_default_controller_error(TransformStreamDefaultController& controller, JS::Value error)
  3803. {
  3804. // 1. Perform ! TransformStreamError(controller.[[stream]], e).
  3805. transform_stream_error(*controller.stream(), error);
  3806. }
  3807. // https://streams.spec.whatwg.org/#transform-stream-default-controller-terminate
  3808. void transform_stream_default_controller_terminate(TransformStreamDefaultController& controller)
  3809. {
  3810. auto& realm = controller.realm();
  3811. // 1. Let stream be controller.[[stream]].
  3812. auto stream = controller.stream();
  3813. // 2. Let readableController be stream.[[readable]].[[controller]].
  3814. VERIFY(stream->readable()->controller().has_value() && stream->readable()->controller()->has<JS::NonnullGCPtr<ReadableStreamDefaultController>>());
  3815. auto readable_controller = stream->readable()->controller()->get<JS::NonnullGCPtr<ReadableStreamDefaultController>>();
  3816. // 3. Perform ! ReadableStreamDefaultControllerClose(readableController).
  3817. readable_stream_default_controller_close(readable_controller);
  3818. // 4. Let error be a TypeError exception indicating that the stream has been terminated.
  3819. auto error = JS::TypeError::create(realm, "Stream has been terminated."sv);
  3820. // 5. Perform ! TransformStreamErrorWritableAndUnblockWrite(stream, error).
  3821. transform_stream_error_writable_and_unblock_write(*stream, error);
  3822. }
  3823. // https://streams.spec.whatwg.org/#transform-stream-default-controller-perform-transform
  3824. JS::NonnullGCPtr<WebIDL::Promise> transform_stream_default_controller_perform_transform(TransformStreamDefaultController& controller, JS::Value chunk)
  3825. {
  3826. auto& realm = controller.realm();
  3827. // 1. Let transformPromise be the result of performing controller.[[transformAlgorithm]], passing chunk.
  3828. auto transform_promise = controller.transform_algorithm()->function()(chunk);
  3829. // 2. Return the result of reacting to transformPromise with the following rejection steps given the argument r:
  3830. auto react_result = WebIDL::react_to_promise(*transform_promise,
  3831. {},
  3832. JS::create_heap_function(realm.heap(), [&controller](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {
  3833. // 1. Perform ! TransformStreamError(controller.[[stream]], r).
  3834. transform_stream_error(*controller.stream(), reason);
  3835. // 2. Throw r.
  3836. return JS::throw_completion(reason);
  3837. }));
  3838. return WebIDL::create_resolved_promise(realm, react_result);
  3839. }
  3840. // https://streams.spec.whatwg.org/#transform-stream-default-sink-abort-algorithm
  3841. JS::NonnullGCPtr<WebIDL::Promise> transform_stream_default_sink_abort_algorithm(TransformStream& stream, JS::Value reason)
  3842. {
  3843. auto& realm = stream.realm();
  3844. // 1. Let controller be stream.[[controller]].
  3845. auto controller = stream.controller();
  3846. VERIFY(controller);
  3847. // 2. If controller.[[finishPromise]] is not undefined, return controller.[[finishPromise]].
  3848. if (controller->finish_promise())
  3849. return JS::NonnullGCPtr { *controller->finish_promise() };
  3850. // 3. Let readable be stream.[[readable]].
  3851. auto readable = stream.readable();
  3852. // 4. Let controller.[[finishPromise]] be a new promise.
  3853. controller->set_finish_promise(WebIDL::create_promise(realm));
  3854. // 5. Let cancelPromise be the result of performing controller.[[cancelAlgorithm]], passing reason.
  3855. auto cancel_promise = controller->cancel_algorithm()->function()(reason);
  3856. // 6. Perform ! TransformStreamDefaultControllerClearAlgorithms(controller).
  3857. transform_stream_default_controller_clear_algorithms(*controller);
  3858. // 7. React to cancelPromise:
  3859. WebIDL::react_to_promise(
  3860. *cancel_promise,
  3861. // 1. If cancelPromise was fulfilled, then:
  3862. JS::create_heap_function(realm.heap(), [&realm, readable, controller](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {
  3863. // 1. If readable.[[state]] is "errored", reject controller.[[finishPromise]] with readable.[[storedError]].
  3864. if (readable->state() == ReadableStream::State::Errored) {
  3865. WebIDL::reject_promise(realm, *controller->finish_promise(), readable->stored_error());
  3866. }
  3867. // 2. Otherwise:
  3868. else {
  3869. VERIFY(readable->controller().has_value() && readable->controller()->has<JS::NonnullGCPtr<ReadableStreamDefaultController>>());
  3870. // 1. Perform ! ReadableStreamDefaultControllerError(readable.[[controller]], reason).
  3871. readable_stream_default_controller_error(readable->controller()->get<JS::NonnullGCPtr<ReadableStreamDefaultController>>(), reason);
  3872. // 2. Resolve controller.[[finishPromise]] with undefined.
  3873. WebIDL::resolve_promise(realm, *controller->finish_promise(), JS::js_undefined());
  3874. }
  3875. return JS::js_undefined();
  3876. }),
  3877. // 2. If cancelPromise was rejected with reason r, then:
  3878. JS::create_heap_function(realm.heap(), [&realm, readable, controller](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {
  3879. VERIFY(readable->controller().has_value() && readable->controller()->has<JS::NonnullGCPtr<ReadableStreamDefaultController>>());
  3880. // 1. Perform ! ReadableStreamDefaultControllerError(readable.[[controller]], r).
  3881. readable_stream_default_controller_error(readable->controller()->get<JS::NonnullGCPtr<ReadableStreamDefaultController>>(), reason);
  3882. // 2. Reject controller.[[finishPromise]] with r.
  3883. WebIDL::reject_promise(realm, *controller->finish_promise(), reason);
  3884. return JS::js_undefined();
  3885. }));
  3886. // 8. Return controller.[[finishPromise]].
  3887. return JS::NonnullGCPtr { *controller->finish_promise() };
  3888. }
  3889. // https://streams.spec.whatwg.org/#transform-stream-default-sink-close-algorithm
  3890. JS::NonnullGCPtr<WebIDL::Promise> transform_stream_default_sink_close_algorithm(TransformStream& stream)
  3891. {
  3892. auto& realm = stream.realm();
  3893. // 1. Let readable be stream.[[readable]].
  3894. auto readable = stream.readable();
  3895. // 2. Let controller be stream.[[controller]].
  3896. auto controller = stream.controller();
  3897. // 3. Let flushPromise be the result of performing controller.[[flushAlgorithm]].
  3898. auto flush_promise = controller->flush_algorithm()->function()();
  3899. // 4. Perform ! TransformStreamDefaultControllerClearAlgorithms(controller).
  3900. transform_stream_default_controller_clear_algorithms(*controller);
  3901. // 5. Return the result of reacting to flushPromise:
  3902. auto react_result = WebIDL::react_to_promise(
  3903. *flush_promise,
  3904. // 1. If flushPromise was fulfilled, then:
  3905. JS::create_heap_function(realm.heap(), [readable](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {
  3906. // 1. If readable.[[state]] is "errored", throw readable.[[storedError]].
  3907. if (readable->state() == ReadableStream::State::Errored)
  3908. return JS::throw_completion(readable->stored_error());
  3909. VERIFY(readable->controller().has_value() && readable->controller()->has<JS::NonnullGCPtr<ReadableStreamDefaultController>>());
  3910. // 2. Perform ! ReadableStreamDefaultControllerClose(readable.[[controller]]).
  3911. readable_stream_default_controller_close(readable->controller().value().get<JS::NonnullGCPtr<ReadableStreamDefaultController>>());
  3912. return JS::js_undefined();
  3913. }),
  3914. // 2. If flushPromise was rejected with reason r, then:
  3915. JS::create_heap_function(realm.heap(), [&stream, readable](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {
  3916. // 1. Perform ! TransformStreamError(stream, r).
  3917. transform_stream_error(stream, reason);
  3918. // 2. Throw readable.[[storedError]].
  3919. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, readable->stored_error().as_string().utf8_string() };
  3920. }));
  3921. return WebIDL::create_resolved_promise(realm, react_result);
  3922. }
  3923. // https://streams.spec.whatwg.org/#transform-stream-default-sink-write-algorithm
  3924. JS::NonnullGCPtr<WebIDL::Promise> transform_stream_default_sink_write_algorithm(TransformStream& stream, JS::Value chunk)
  3925. {
  3926. auto& realm = stream.realm();
  3927. // 1. Assert: stream.[[writable]].[[state]] is "writable".
  3928. VERIFY(stream.writable()->state() == WritableStream::State::Writable);
  3929. // 2. Let controller be stream.[[controller]].
  3930. auto controller = stream.controller();
  3931. // 3. If stream.[[backpressure]] is true,
  3932. if (stream.backpressure().has_value() && *stream.backpressure()) {
  3933. // 1. Let backpressureChangePromise be stream.[[backpressureChangePromise]].
  3934. auto backpressure_change_promise = stream.backpressure_change_promise();
  3935. // 2. Assert: backpressureChangePromise is not undefined.
  3936. VERIFY(backpressure_change_promise);
  3937. // 3. Return the result of reacting to backpressureChangePromise with the following fulfillment steps:
  3938. auto react_result = WebIDL::react_to_promise(*backpressure_change_promise,
  3939. JS::create_heap_function(realm.heap(), [&stream, controller, chunk](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {
  3940. // 1. Let writable be stream.[[writable]].
  3941. auto writable = stream.writable();
  3942. // 2. Let state be writable.[[state]].
  3943. auto state = writable->state();
  3944. // 3. If state is "erroring", throw writable.[[storedError]].
  3945. if (state == WritableStream::State::Erroring)
  3946. return JS::throw_completion(writable->stored_error());
  3947. // 4. Assert: state is "writable".
  3948. VERIFY(state == WritableStream::State::Writable);
  3949. // 5. Return ! TransformStreamDefaultControllerPerformTransform(controller, chunk).
  3950. return transform_stream_default_controller_perform_transform(*controller, chunk)->promise();
  3951. }),
  3952. {});
  3953. return WebIDL::create_resolved_promise(realm, react_result);
  3954. }
  3955. // 4. Return ! TransformStreamDefaultControllerPerformTransform(controller, chunk).
  3956. return transform_stream_default_controller_perform_transform(*controller, chunk);
  3957. }
  3958. JS::NonnullGCPtr<WebIDL::Promise> transform_stream_default_source_pull_algorithm(TransformStream& stream)
  3959. {
  3960. // 1. Assert: stream.[[backpressure]] is true.
  3961. VERIFY(stream.backpressure().has_value() && *stream.backpressure());
  3962. // 2. Assert: stream.[[backpressureChangePromise]] is not undefined.
  3963. VERIFY(stream.backpressure_change_promise());
  3964. // 3. Perform ! TransformStreamSetBackpressure(stream, false).
  3965. transform_stream_set_backpressure(stream, false);
  3966. // 4. Return stream.[[backpressureChangePromise]].
  3967. return JS::NonnullGCPtr { *stream.backpressure_change_promise() };
  3968. }
  3969. // https://streams.spec.whatwg.org/#transform-stream-default-source-cancel
  3970. JS::NonnullGCPtr<WebIDL::Promise> transform_stream_default_source_cancel_algorithm(TransformStream& stream, JS::Value reason)
  3971. {
  3972. auto& realm = stream.realm();
  3973. // 1. Let controller be stream.[[controller]].
  3974. auto controller = stream.controller();
  3975. // 2. If controller.[[finishPromise]] is not undefined, return controller.[[finishPromise]].
  3976. if (controller->finish_promise())
  3977. return JS::NonnullGCPtr { *controller->finish_promise() };
  3978. // 3. Let writable be stream.[[writable]].
  3979. auto writable = stream.writable();
  3980. // 4. Let controller.[[finishPromise]] be a new promise.
  3981. controller->set_finish_promise(WebIDL::create_promise(realm));
  3982. // 5. Let cancelPromise be the result of performing controller.[[cancelAlgorithm]], passing reason.
  3983. auto cancel_promise = controller->cancel_algorithm()->function()(reason);
  3984. // 6. Perform ! TransformStreamDefaultControllerClearAlgorithms(controller).
  3985. transform_stream_default_controller_clear_algorithms(*controller);
  3986. // 7. React to cancelPromise:
  3987. WebIDL::react_to_promise(
  3988. *cancel_promise,
  3989. // 1. If cancelPromise was fulfilled, then:
  3990. JS::create_heap_function(realm.heap(), [&realm, writable, controller, &stream](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {
  3991. // 1. If writable.[[state]] is "errored", reject controller.[[finishPromise]] with writable.[[storedError]].
  3992. if (writable->state() == WritableStream::State::Errored) {
  3993. WebIDL::reject_promise(realm, *controller->finish_promise(), writable->stored_error());
  3994. }
  3995. // 2. Otherwise:
  3996. else {
  3997. // 1. Perform ! WritableStreamDefaultControllerErrorIfNeeded(writable.[[controller]], reason).
  3998. writable_stream_default_controller_error_if_needed(*writable->controller(), reason);
  3999. // 2. Perform ! TransformStreamUnblockWrite(stream).
  4000. transform_stream_unblock_write(stream);
  4001. // 3. Resolve controller.[[finishPromise]] with undefined.
  4002. WebIDL::resolve_promise(realm, *controller->finish_promise(), JS::js_undefined());
  4003. }
  4004. return JS::js_undefined();
  4005. }),
  4006. // 2. If cancelPromise was rejected with reason r, then:
  4007. JS::create_heap_function(realm.heap(), [&realm, writable, &stream, controller](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {
  4008. // 1. Perform ! WritableStreamDefaultControllerErrorIfNeeded(writable.[[controller]], r).
  4009. writable_stream_default_controller_error_if_needed(*writable->controller(), reason);
  4010. // 2. Perform ! TransformStreamUnblockWrite(stream).
  4011. transform_stream_unblock_write(stream);
  4012. // 3. Reject controller.[[finishPromise]] with r.
  4013. WebIDL::reject_promise(realm, *controller->finish_promise(), reason);
  4014. return JS::js_undefined();
  4015. }));
  4016. // 8. Return controller.[[finishPromise]].
  4017. return JS::NonnullGCPtr { *controller->finish_promise() };
  4018. }
  4019. // https://streams.spec.whatwg.org/#transform-stream-error
  4020. void transform_stream_error(TransformStream& stream, JS::Value error)
  4021. {
  4022. VERIFY(stream.readable()->controller().has_value() && stream.readable()->controller()->has<JS::NonnullGCPtr<ReadableStreamDefaultController>>());
  4023. auto readable_controller = stream.readable()->controller()->get<JS::NonnullGCPtr<ReadableStreamDefaultController>>();
  4024. // 1. Perform ! ReadableStreamDefaultControllerError(stream.[[readable]].[[controller]], e).
  4025. readable_stream_default_controller_error(*readable_controller, error);
  4026. // 2. Perform ! TransformStreamErrorWritableAndUnblockWrite(stream, e).
  4027. transform_stream_error_writable_and_unblock_write(stream, error);
  4028. }
  4029. // https://streams.spec.whatwg.org/#transform-stream-error-writable-and-unblock-write
  4030. void transform_stream_error_writable_and_unblock_write(TransformStream& stream, JS::Value error)
  4031. {
  4032. // 1. Perform ! TransformStreamDefaultControllerClearAlgorithms(stream.[[controller]]).
  4033. transform_stream_default_controller_clear_algorithms(*stream.controller());
  4034. // 2. Perform ! WritableStreamDefaultControllerErrorIfNeeded(stream.[[writable]].[[controller]], e).
  4035. writable_stream_default_controller_error_if_needed(*stream.writable()->controller(), error);
  4036. // 3. If stream.[[backpressure]] is true, perform ! TransformStreamSetBackpressure(stream, false).
  4037. if (stream.backpressure().has_value() && *stream.backpressure())
  4038. transform_stream_set_backpressure(stream, false);
  4039. }
  4040. // https://streams.spec.whatwg.org/#transform-stream-set-backpressure
  4041. void transform_stream_set_backpressure(TransformStream& stream, bool backpressure)
  4042. {
  4043. auto& realm = stream.realm();
  4044. // 1. Assert: stream.[[backpressure]] is not backpressure.
  4045. VERIFY(stream.backpressure() != backpressure);
  4046. // 2. If stream.[[backpressureChangePromise]] is not undefined, resolve stream.[[backpressureChangePromise]] with undefined.
  4047. if (stream.backpressure_change_promise())
  4048. WebIDL::resolve_promise(realm, *stream.backpressure_change_promise(), JS::js_undefined());
  4049. // 3. Set stream.[[backpressureChangePromise]] to a new promise.
  4050. stream.set_backpressure_change_promise(WebIDL::create_promise(realm));
  4051. // 4. Set stream.[[backpressure]] to backpressure.
  4052. stream.set_backpressure(backpressure);
  4053. }
  4054. // https://streams.spec.whatwg.org/#transformstream-set-up
  4055. void transform_stream_set_up(TransformStream& stream, JS::NonnullGCPtr<TransformAlgorithm> transform_algorithm, JS::GCPtr<FlushAlgorithm> flush_algorithm, JS::GCPtr<CancelAlgorithm> cancel_algorithm)
  4056. {
  4057. auto& realm = stream.realm();
  4058. // 1. Let writableHighWaterMark be 1.
  4059. auto writable_high_water_mark = 1.0;
  4060. // 2. Let writableSizeAlgorithm be an algorithm that returns 1.
  4061. auto writable_size_algorithm = JS::create_heap_function(realm.heap(), [](JS::Value) {
  4062. return JS::normal_completion(JS::Value { 1 });
  4063. });
  4064. // 3. Let readableHighWaterMark be 0.
  4065. auto readable_high_water_mark = 0.0;
  4066. // 4. Let readableSizeAlgorithm be an algorithm that returns 1.
  4067. auto readable_size_algorithm = JS::create_heap_function(realm.heap(), [](JS::Value) {
  4068. return JS::normal_completion(JS::Value { 1 });
  4069. });
  4070. // 5. Let transformAlgorithmWrapper be an algorithm that runs these steps given a value chunk:
  4071. auto transform_algorithm_wrapper = JS::create_heap_function(realm.heap(), [&realm, transform_algorithm](JS::Value chunk) -> JS::NonnullGCPtr<WebIDL::Promise> {
  4072. // 1. Let result be the result of running transformAlgorithm given chunk. If this throws an exception e, return a promise rejected with e.
  4073. JS::GCPtr<JS::PromiseCapability> result = nullptr;
  4074. result = transform_algorithm->function()(chunk);
  4075. // 2. If result is a Promise, then return result.
  4076. if (result)
  4077. return JS::NonnullGCPtr { *result };
  4078. // 3. Return a promise resolved with undefined.
  4079. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  4080. });
  4081. // 6. Let flushAlgorithmWrapper be an algorithm that runs these steps:
  4082. auto flush_algorithm_wrapper = JS::create_heap_function(realm.heap(), [&realm, flush_algorithm]() -> JS::NonnullGCPtr<WebIDL::Promise> {
  4083. // 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.
  4084. JS::GCPtr<JS::PromiseCapability> result = nullptr;
  4085. if (flush_algorithm)
  4086. result = flush_algorithm->function()();
  4087. // 2. If result is a Promise, then return result.
  4088. if (result)
  4089. return JS::NonnullGCPtr { *result };
  4090. // 3. Return a promise resolved with undefined.
  4091. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  4092. });
  4093. // 7. Let cancelAlgorithmWrapper be an algorithm that runs these steps given a value reason:
  4094. auto cancel_algorithm_wrapper = JS::create_heap_function(realm.heap(), [&realm, cancel_algorithm](JS::Value reason) -> JS::NonnullGCPtr<WebIDL::Promise> {
  4095. // 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.
  4096. JS::GCPtr<JS::PromiseCapability> result = nullptr;
  4097. if (cancel_algorithm)
  4098. result = cancel_algorithm->function()(reason);
  4099. // 2. If result is a Promise, then return result.
  4100. if (result)
  4101. return JS::NonnullGCPtr { *result };
  4102. // 3. Return a promise resolved with undefined.
  4103. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  4104. });
  4105. // 8. Let startPromise be a promise resolved with undefined.
  4106. auto start_promise = WebIDL::create_resolved_promise(realm, JS::js_undefined());
  4107. // 9. Perform ! InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm).
  4108. initialize_transform_stream(stream, start_promise, writable_high_water_mark, writable_size_algorithm, readable_high_water_mark, readable_size_algorithm);
  4109. // 10. Let controller be a new TransformStreamDefaultController.
  4110. auto controller = realm.heap().allocate<TransformStreamDefaultController>(realm, realm);
  4111. // 11. Perform ! SetUpTransformStreamDefaultController(stream, controller, transformAlgorithmWrapper, flushAlgorithmWrapper, cancelAlgorithmWrapper).
  4112. set_up_transform_stream_default_controller(stream, controller, transform_algorithm_wrapper, flush_algorithm_wrapper, cancel_algorithm_wrapper);
  4113. }
  4114. // https://streams.spec.whatwg.org/#transform-stream-unblock-write
  4115. void transform_stream_unblock_write(TransformStream& stream)
  4116. {
  4117. // 1. If stream.[[backpressure]] is true, perform ! TransformStreamSetBackpressure(stream, false).
  4118. if (stream.backpressure().has_value() && stream.backpressure().value())
  4119. transform_stream_set_backpressure(stream, false);
  4120. }
  4121. // https://streams.spec.whatwg.org/#is-non-negative-number
  4122. bool is_non_negative_number(JS::Value value)
  4123. {
  4124. // 1. If Type(v) is not Number, return false.
  4125. if (!value.is_number())
  4126. return false;
  4127. // 2. If v is NaN, return false.
  4128. if (value.is_nan())
  4129. return false;
  4130. // 3. If v < 0, return false.
  4131. if (value.as_double() < 0.0)
  4132. return false;
  4133. // 4. Return true.
  4134. return true;
  4135. }
  4136. // https://streams.spec.whatwg.org/#can-transfer-array-buffer
  4137. bool can_transfer_array_buffer(JS::ArrayBuffer const& array_buffer)
  4138. {
  4139. // 1. Assert: Type(O) is Object.
  4140. // 2. Assert: O has an [[ArrayBufferData]] internal slot.
  4141. // 3. If ! IsDetachedBuffer(O) is true, return false.
  4142. if (array_buffer.is_detached())
  4143. return false;
  4144. // 4. If SameValue(O.[[ArrayBufferDetachKey]], undefined) is false, return false.
  4145. if (!JS::same_value(array_buffer.detach_key(), JS::js_undefined()))
  4146. return false;
  4147. // 5. Return true.
  4148. return true;
  4149. }
  4150. // https://streams.spec.whatwg.org/#abstract-opdef-cloneasuint8array
  4151. WebIDL::ExceptionOr<JS::Value> clone_as_uint8_array(JS::Realm& realm, WebIDL::ArrayBufferView& view)
  4152. {
  4153. auto& vm = realm.vm();
  4154. // 1. Assert: Type(O) is Object.
  4155. // 2. Assert: O has an [[ViewedArrayBuffer]] internal slot.
  4156. // 3. Assert: ! IsDetachedBuffer(O.[[ViewedArrayBuffer]]) is false.
  4157. VERIFY(!view.viewed_array_buffer()->is_detached());
  4158. // 4. Let buffer be ? CloneArrayBuffer(O.[[ViewedArrayBuffer]], O.[[ByteOffset]], O.[[ByteLength]], %ArrayBuffer%).
  4159. auto* buffer = TRY(JS::clone_array_buffer(vm, *view.viewed_array_buffer(), view.byte_offset(), view.byte_length()));
  4160. // 5. Let array be ! Construct(%Uint8Array%, « buffer »).
  4161. auto array = MUST(JS::construct(vm, *realm.intrinsics().uint8_array_constructor(), buffer));
  4162. // 5. Return array.
  4163. return array;
  4164. }
  4165. // https://streams.spec.whatwg.org/#abstract-opdef-structuredclone
  4166. WebIDL::ExceptionOr<JS::Value> structured_clone(JS::Realm& realm, JS::Value value)
  4167. {
  4168. auto& vm = realm.vm();
  4169. // 1. Let serialized be ? StructuredSerialize(v).
  4170. auto serialized = TRY(HTML::structured_serialize(vm, value));
  4171. // 2. Return ? StructuredDeserialize(serialized, the current Realm).
  4172. return TRY(HTML::structured_deserialize(vm, serialized, realm, {}));
  4173. }
  4174. // https://streams.spec.whatwg.org/#close-sentinel
  4175. // Non-standard function that implements the "close sentinel" value.
  4176. JS::Value create_close_sentinel()
  4177. {
  4178. // 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.
  4179. // 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.
  4180. return {};
  4181. }
  4182. // https://streams.spec.whatwg.org/#close-sentinel
  4183. // Non-standard function that implements the "If value is a close sentinel" check.
  4184. bool is_close_sentinel(JS::Value value)
  4185. {
  4186. return value.is_empty();
  4187. }
  4188. // Non-standard function to aid in converting a user-provided function into a WebIDL::Callback. This is essentially
  4189. // what the Bindings generator would do at compile time, but at runtime instead.
  4190. 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)
  4191. {
  4192. auto property = TRY(value.get(vm, property_key));
  4193. if (property.is_undefined())
  4194. return JS::Handle<WebIDL::CallbackType> {};
  4195. if (!property.is_function())
  4196. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAFunction, property.to_string_without_side_effects());
  4197. return vm.heap().allocate_without_realm<WebIDL::CallbackType>(property.as_object(), HTML::incumbent_settings_object(), operation_returns_promise);
  4198. }
  4199. // https://streams.spec.whatwg.org/#set-up-readable-byte-stream-controller-from-underlying-source
  4200. 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)
  4201. {
  4202. auto& realm = stream.realm();
  4203. // 1. Let controller be a new ReadableByteStreamController.
  4204. auto controller = stream.heap().allocate<ReadableByteStreamController>(realm, realm);
  4205. // 2. Let startAlgorithm be an algorithm that returns undefined.
  4206. auto start_algorithm = JS::create_heap_function(realm.heap(), []() -> WebIDL::ExceptionOr<JS::Value> { return JS::js_undefined(); });
  4207. // 3. Let pullAlgorithm be an algorithm that returns a promise resolved with undefined.
  4208. auto pull_algorithm = JS::create_heap_function(realm.heap(), [&realm]() {
  4209. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  4210. });
  4211. // 4. Let cancelAlgorithm be an algorithm that returns a promise resolved with undefined.
  4212. auto cancel_algorithm = JS::create_heap_function(realm.heap(), [&realm](JS::Value) {
  4213. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  4214. });
  4215. // 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.
  4216. if (underlying_source_dict.start) {
  4217. start_algorithm = JS::create_heap_function(realm.heap(), [controller, underlying_source, callback = underlying_source_dict.start]() -> WebIDL::ExceptionOr<JS::Value> {
  4218. // Note: callback does not return a promise, so invoke_callback may return an abrupt completion
  4219. return TRY(WebIDL::invoke_callback(*callback, underlying_source, controller)).release_value();
  4220. });
  4221. }
  4222. // 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.
  4223. if (underlying_source_dict.pull) {
  4224. pull_algorithm = JS::create_heap_function(realm.heap(), [&realm, controller, underlying_source, callback = underlying_source_dict.pull]() {
  4225. // Note: callback returns a promise, so invoke_callback will never return an abrupt completion
  4226. auto result = MUST(WebIDL::invoke_callback(*callback, underlying_source, controller)).release_value();
  4227. return WebIDL::create_resolved_promise(realm, result);
  4228. });
  4229. }
  4230. // 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.
  4231. if (underlying_source_dict.cancel) {
  4232. cancel_algorithm = JS::create_heap_function(realm.heap(), [&realm, underlying_source, callback = underlying_source_dict.cancel](JS::Value reason) {
  4233. // Note: callback returns a promise, so invoke_callback will never return an abrupt completion
  4234. auto result = MUST(WebIDL::invoke_callback(*callback, underlying_source, reason)).release_value();
  4235. return WebIDL::create_resolved_promise(realm, result);
  4236. });
  4237. }
  4238. // 8. Let autoAllocateChunkSize be underlyingSourceDict["autoAllocateChunkSize"], if it exists, or undefined otherwise.
  4239. auto auto_allocate_chunk_size = underlying_source_dict.auto_allocate_chunk_size.has_value()
  4240. ? JS::Value(underlying_source_dict.auto_allocate_chunk_size.value())
  4241. : JS::js_undefined();
  4242. // 9. If autoAllocateChunkSize is 0, then throw a TypeError exception.
  4243. if (auto_allocate_chunk_size.is_integral_number() && auto_allocate_chunk_size.as_double() == 0)
  4244. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot use an auto allocate chunk size of 0"sv };
  4245. // 10. Perform ? SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize).
  4246. return set_up_readable_byte_stream_controller(stream, controller, start_algorithm, pull_algorithm, cancel_algorithm, high_water_mark, auto_allocate_chunk_size);
  4247. }
  4248. }