AbstractOperations.cpp 243 KB

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