f_00000e 315 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205
  1. import {
  2. __commonJS,
  3. __publicField,
  4. __require
  5. } from "/node_modules/.vite/deps/chunk-WQG2LZMB.js?v=9548b9c3";
  6. // browser-external:crypto
  7. var require_crypto = __commonJS({
  8. "browser-external:crypto"(exports, module2) {
  9. module2.exports = Object.create(new Proxy({}, {
  10. get(_, key) {
  11. if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") {
  12. console.warn(`Module "crypto" has been externalized for browser compatibility. Cannot access "crypto.${key}" in client code. See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
  13. }
  14. }
  15. }));
  16. }
  17. });
  18. // node_modules/nats.ws/esm/nats.js
  19. var Empty = new Uint8Array(0);
  20. var TE = new TextEncoder();
  21. var TD = new TextDecoder();
  22. function concat(...bufs) {
  23. let max = 0;
  24. for (let i = 0; i < bufs.length; i++) {
  25. max += bufs[i].length;
  26. }
  27. const out = new Uint8Array(max);
  28. let index = 0;
  29. for (let i = 0; i < bufs.length; i++) {
  30. out.set(bufs[i], index);
  31. index += bufs[i].length;
  32. }
  33. return out;
  34. }
  35. function encode(...a) {
  36. const bufs = [];
  37. for (let i = 0; i < a.length; i++) {
  38. bufs.push(TE.encode(a[i]));
  39. }
  40. if (bufs.length === 0) {
  41. return Empty;
  42. }
  43. if (bufs.length === 1) {
  44. return bufs[0];
  45. }
  46. return concat(...bufs);
  47. }
  48. function decode(a) {
  49. if (!a || a.length === 0) {
  50. return "";
  51. }
  52. return TD.decode(a);
  53. }
  54. var digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  55. var base = 36;
  56. var maxSeq = 3656158440062976;
  57. var minInc = 33;
  58. var maxInc = 333;
  59. var totalLen = 12 + 10;
  60. function _getRandomValues(a) {
  61. for (let i = 0; i < a.length; i++) {
  62. a[i] = Math.floor(Math.random() * 255);
  63. }
  64. }
  65. function fillRandom(a) {
  66. var _a;
  67. if ((_a = globalThis == null ? void 0 : globalThis.crypto) == null ? void 0 : _a.getRandomValues) {
  68. globalThis.crypto.getRandomValues(a);
  69. } else {
  70. _getRandomValues(a);
  71. }
  72. }
  73. var Nuid = class {
  74. constructor() {
  75. __publicField(this, "buf");
  76. __publicField(this, "seq");
  77. __publicField(this, "inc");
  78. this.buf = new Uint8Array(totalLen);
  79. this.init();
  80. }
  81. init() {
  82. this.setPre();
  83. this.initSeqAndInc();
  84. this.fillSeq();
  85. }
  86. initSeqAndInc() {
  87. this.seq = Math.floor(Math.random() * maxSeq);
  88. this.inc = Math.floor(Math.random() * (maxInc - minInc) + minInc);
  89. }
  90. setPre() {
  91. const cbuf = new Uint8Array(12);
  92. fillRandom(cbuf);
  93. for (let i = 0; i < 12; i++) {
  94. const di = cbuf[i] % 36;
  95. this.buf[i] = digits.charCodeAt(di);
  96. }
  97. }
  98. fillSeq() {
  99. let n = this.seq;
  100. for (let i = totalLen - 1; i >= 12; i--) {
  101. this.buf[i] = digits.charCodeAt(n % base);
  102. n = Math.floor(n / base);
  103. }
  104. }
  105. next() {
  106. this.seq += this.inc;
  107. if (this.seq > 3656158440062976) {
  108. this.setPre();
  109. this.initSeqAndInc();
  110. }
  111. this.fillSeq();
  112. return String.fromCharCode.apply(String, this.buf);
  113. }
  114. reset() {
  115. this.init();
  116. }
  117. };
  118. var nuid = new Nuid();
  119. var Events;
  120. (function(Events2) {
  121. Events2["Disconnect"] = "disconnect";
  122. Events2["Reconnect"] = "reconnect";
  123. Events2["Update"] = "update";
  124. Events2["LDM"] = "ldm";
  125. Events2["Error"] = "error";
  126. })(Events || (Events = {}));
  127. var DebugEvents;
  128. (function(DebugEvents2) {
  129. DebugEvents2["Reconnecting"] = "reconnecting";
  130. DebugEvents2["PingTimer"] = "pingTimer";
  131. DebugEvents2["StaleConnection"] = "staleConnection";
  132. DebugEvents2["ClientInitiatedReconnect"] = "client initiated reconnect";
  133. })(DebugEvents || (DebugEvents = {}));
  134. var ErrorCode;
  135. (function(ErrorCode2) {
  136. ErrorCode2["ApiError"] = "BAD API";
  137. ErrorCode2["BadAuthentication"] = "BAD_AUTHENTICATION";
  138. ErrorCode2["BadCreds"] = "BAD_CREDS";
  139. ErrorCode2["BadHeader"] = "BAD_HEADER";
  140. ErrorCode2["BadJson"] = "BAD_JSON";
  141. ErrorCode2["BadPayload"] = "BAD_PAYLOAD";
  142. ErrorCode2["BadSubject"] = "BAD_SUBJECT";
  143. ErrorCode2["Cancelled"] = "CANCELLED";
  144. ErrorCode2["ConnectionClosed"] = "CONNECTION_CLOSED";
  145. ErrorCode2["ConnectionDraining"] = "CONNECTION_DRAINING";
  146. ErrorCode2["ConnectionRefused"] = "CONNECTION_REFUSED";
  147. ErrorCode2["ConnectionTimeout"] = "CONNECTION_TIMEOUT";
  148. ErrorCode2["Disconnect"] = "DISCONNECT";
  149. ErrorCode2["InvalidOption"] = "INVALID_OPTION";
  150. ErrorCode2["InvalidPayload"] = "INVALID_PAYLOAD";
  151. ErrorCode2["MaxPayloadExceeded"] = "MAX_PAYLOAD_EXCEEDED";
  152. ErrorCode2["NoResponders"] = "503";
  153. ErrorCode2["NotFunction"] = "NOT_FUNC";
  154. ErrorCode2["RequestError"] = "REQUEST_ERROR";
  155. ErrorCode2["ServerOptionNotAvailable"] = "SERVER_OPT_NA";
  156. ErrorCode2["SubClosed"] = "SUB_CLOSED";
  157. ErrorCode2["SubDraining"] = "SUB_DRAINING";
  158. ErrorCode2["Timeout"] = "TIMEOUT";
  159. ErrorCode2["Tls"] = "TLS";
  160. ErrorCode2["Unknown"] = "UNKNOWN_ERROR";
  161. ErrorCode2["WssRequired"] = "WSS_REQUIRED";
  162. ErrorCode2["JetStreamInvalidAck"] = "JESTREAM_INVALID_ACK";
  163. ErrorCode2["JetStream404NoMessages"] = "404";
  164. ErrorCode2["JetStream408RequestTimeout"] = "408";
  165. ErrorCode2["JetStream409MaxAckPendingExceeded"] = "409";
  166. ErrorCode2["JetStream409"] = "409";
  167. ErrorCode2["JetStreamNotEnabled"] = "503";
  168. ErrorCode2["JetStreamIdleHeartBeat"] = "IDLE_HEARTBEAT";
  169. ErrorCode2["AuthorizationViolation"] = "AUTHORIZATION_VIOLATION";
  170. ErrorCode2["AuthenticationExpired"] = "AUTHENTICATION_EXPIRED";
  171. ErrorCode2["ProtocolError"] = "NATS_PROTOCOL_ERR";
  172. ErrorCode2["PermissionsViolation"] = "PERMISSIONS_VIOLATION";
  173. ErrorCode2["AuthenticationTimeout"] = "AUTHENTICATION_TIMEOUT";
  174. })(ErrorCode || (ErrorCode = {}));
  175. function isNatsError(err) {
  176. return typeof err.code === "string";
  177. }
  178. var Messages = class {
  179. constructor() {
  180. __publicField(this, "messages");
  181. this.messages = /* @__PURE__ */ new Map();
  182. this.messages.set(ErrorCode.InvalidPayload, "Invalid payload type - payloads can be 'binary', 'string', or 'json'");
  183. this.messages.set(ErrorCode.BadJson, "Bad JSON");
  184. this.messages.set(ErrorCode.WssRequired, "TLS is required, therefore a secure websocket connection is also required");
  185. }
  186. static getMessage(s) {
  187. return messages.getMessage(s);
  188. }
  189. getMessage(s) {
  190. return this.messages.get(s) || s;
  191. }
  192. };
  193. var messages = new Messages();
  194. var NatsError = class extends Error {
  195. constructor(message, code2, chainedError) {
  196. super(message);
  197. __publicField(this, "name");
  198. __publicField(this, "message");
  199. __publicField(this, "code");
  200. __publicField(this, "permissionContext");
  201. __publicField(this, "chainedError");
  202. __publicField(this, "api_error");
  203. this.name = "NatsError";
  204. this.message = message;
  205. this.code = code2;
  206. this.chainedError = chainedError;
  207. }
  208. static errorForCode(code2, chainedError) {
  209. const m = Messages.getMessage(code2);
  210. return new NatsError(m, code2, chainedError);
  211. }
  212. isAuthError() {
  213. return this.code === ErrorCode.AuthenticationExpired || this.code === ErrorCode.AuthorizationViolation;
  214. }
  215. isAuthTimeout() {
  216. return this.code === ErrorCode.AuthenticationTimeout;
  217. }
  218. isPermissionError() {
  219. return this.code === ErrorCode.PermissionsViolation;
  220. }
  221. isProtocolError() {
  222. return this.code === ErrorCode.ProtocolError;
  223. }
  224. isJetStreamError() {
  225. return this.api_error !== void 0;
  226. }
  227. jsError() {
  228. return this.api_error ? this.api_error : null;
  229. }
  230. };
  231. var Match;
  232. (function(Match2) {
  233. Match2[Match2["Exact"] = 0] = "Exact";
  234. Match2[Match2["CanonicalMIME"] = 1] = "CanonicalMIME";
  235. Match2[Match2["IgnoreCase"] = 2] = "IgnoreCase";
  236. })(Match || (Match = {}));
  237. var RequestStrategy;
  238. (function(RequestStrategy2) {
  239. RequestStrategy2["Timer"] = "timer";
  240. RequestStrategy2["Count"] = "count";
  241. RequestStrategy2["JitterTimer"] = "jitterTimer";
  242. RequestStrategy2["SentinelMsg"] = "sentinelMsg";
  243. })(RequestStrategy || (RequestStrategy = {}));
  244. function syncIterator(src) {
  245. const iter = src[Symbol.asyncIterator]();
  246. return {
  247. async next() {
  248. const m = await iter.next();
  249. if (m.done) {
  250. return Promise.resolve(null);
  251. }
  252. return Promise.resolve(m.value);
  253. }
  254. };
  255. }
  256. var ServiceResponseType;
  257. (function(ServiceResponseType2) {
  258. ServiceResponseType2["STATS"] = "io.nats.micro.v1.stats_response";
  259. ServiceResponseType2["INFO"] = "io.nats.micro.v1.info_response";
  260. ServiceResponseType2["PING"] = "io.nats.micro.v1.ping_response";
  261. })(ServiceResponseType || (ServiceResponseType = {}));
  262. var ServiceErrorHeader = "Nats-Service-Error";
  263. var ServiceErrorCodeHeader = "Nats-Service-Error-Code";
  264. var ServiceError = class extends Error {
  265. constructor(code2, message) {
  266. super(message);
  267. __publicField(this, "code");
  268. this.code = code2;
  269. }
  270. static isServiceError(msg) {
  271. return ServiceError.toServiceError(msg) !== null;
  272. }
  273. static toServiceError(msg) {
  274. var _a, _b;
  275. const scode = ((_a = msg == null ? void 0 : msg.headers) == null ? void 0 : _a.get(ServiceErrorCodeHeader)) || "";
  276. if (scode !== "") {
  277. const code2 = parseInt(scode) || 400;
  278. const description = ((_b = msg == null ? void 0 : msg.headers) == null ? void 0 : _b.get(ServiceErrorHeader)) || "";
  279. return new ServiceError(code2, description.length ? description : scode);
  280. }
  281. return null;
  282. }
  283. };
  284. function createInbox(prefix = "") {
  285. prefix = prefix || "_INBOX";
  286. if (typeof prefix !== "string") {
  287. throw new Error("prefix must be a string");
  288. }
  289. prefix.split(".").forEach((v) => {
  290. if (v === "*" || v === ">") {
  291. throw new Error(`inbox prefixes cannot have wildcards '${prefix}'`);
  292. }
  293. });
  294. return `${prefix}.${nuid.next()}`;
  295. }
  296. var DEFAULT_HOST = "127.0.0.1";
  297. var ServiceVerb;
  298. (function(ServiceVerb2) {
  299. ServiceVerb2["PING"] = "PING";
  300. ServiceVerb2["STATS"] = "STATS";
  301. ServiceVerb2["INFO"] = "INFO";
  302. })(ServiceVerb || (ServiceVerb = {}));
  303. function extend(a, ...b) {
  304. for (let i = 0; i < b.length; i++) {
  305. const o = b[i];
  306. Object.keys(o).forEach(function(k) {
  307. a[k] = o[k];
  308. });
  309. }
  310. return a;
  311. }
  312. function render(frame) {
  313. const cr = "␍";
  314. const lf = "␊";
  315. return TD.decode(frame).replace(/\n/g, lf).replace(/\r/g, cr);
  316. }
  317. function timeout(ms, asyncTraces = true) {
  318. const err = asyncTraces ? NatsError.errorForCode(ErrorCode.Timeout) : null;
  319. let methods;
  320. let timer;
  321. const p = new Promise((_resolve, reject) => {
  322. const cancel = () => {
  323. if (timer) {
  324. clearTimeout(timer);
  325. }
  326. };
  327. methods = {
  328. cancel
  329. };
  330. timer = setTimeout(() => {
  331. if (err === null) {
  332. reject(NatsError.errorForCode(ErrorCode.Timeout));
  333. } else {
  334. reject(err);
  335. }
  336. }, ms);
  337. });
  338. return Object.assign(p, methods);
  339. }
  340. function delay(ms = 0) {
  341. return new Promise((resolve) => {
  342. setTimeout(() => {
  343. resolve();
  344. }, ms);
  345. });
  346. }
  347. function deadline(p, millis2 = 1e3) {
  348. const err = new Error(`deadline exceeded`);
  349. const d = deferred();
  350. const timer = setTimeout(() => d.reject(err), millis2);
  351. return Promise.race([
  352. p,
  353. d
  354. ]).finally(() => clearTimeout(timer));
  355. }
  356. function deferred() {
  357. let methods = {};
  358. const p = new Promise((resolve, reject) => {
  359. methods = {
  360. resolve,
  361. reject
  362. };
  363. });
  364. return Object.assign(p, methods);
  365. }
  366. function shuffle(a) {
  367. for (let i = a.length - 1; i > 0; i--) {
  368. const j = Math.floor(Math.random() * (i + 1));
  369. [a[i], a[j]] = [
  370. a[j],
  371. a[i]
  372. ];
  373. }
  374. return a;
  375. }
  376. var Perf = class {
  377. constructor() {
  378. __publicField(this, "timers");
  379. __publicField(this, "measures");
  380. this.timers = /* @__PURE__ */ new Map();
  381. this.measures = /* @__PURE__ */ new Map();
  382. }
  383. mark(key) {
  384. this.timers.set(key, performance.now());
  385. }
  386. measure(key, startKey, endKey) {
  387. const s = this.timers.get(startKey);
  388. if (s === void 0) {
  389. throw new Error(`${startKey} is not defined`);
  390. }
  391. const e = this.timers.get(endKey);
  392. if (e === void 0) {
  393. throw new Error(`${endKey} is not defined`);
  394. }
  395. this.measures.set(key, e - s);
  396. }
  397. getEntries() {
  398. const values = [];
  399. this.measures.forEach((v, k) => {
  400. values.push({
  401. name: k,
  402. duration: v
  403. });
  404. });
  405. return values;
  406. }
  407. };
  408. function jitter(n) {
  409. if (n === 0) {
  410. return 0;
  411. }
  412. return Math.floor(n / 2 + Math.random() * n);
  413. }
  414. function backoff(policy = [
  415. 0,
  416. 250,
  417. 250,
  418. 500,
  419. 500,
  420. 3e3,
  421. 5e3
  422. ]) {
  423. if (!Array.isArray(policy)) {
  424. policy = [
  425. 0,
  426. 250,
  427. 250,
  428. 500,
  429. 500,
  430. 3e3,
  431. 5e3
  432. ];
  433. }
  434. const max = policy.length - 1;
  435. return {
  436. backoff(attempt) {
  437. return jitter(attempt > max ? policy[max] : policy[attempt]);
  438. }
  439. };
  440. }
  441. var DataBuffer = class {
  442. constructor() {
  443. __publicField(this, "buffers");
  444. __publicField(this, "byteLength");
  445. this.buffers = [];
  446. this.byteLength = 0;
  447. }
  448. static concat(...bufs) {
  449. let max = 0;
  450. for (let i = 0; i < bufs.length; i++) {
  451. max += bufs[i].length;
  452. }
  453. const out = new Uint8Array(max);
  454. let index = 0;
  455. for (let i = 0; i < bufs.length; i++) {
  456. out.set(bufs[i], index);
  457. index += bufs[i].length;
  458. }
  459. return out;
  460. }
  461. static fromAscii(m) {
  462. if (!m) {
  463. m = "";
  464. }
  465. return TE.encode(m);
  466. }
  467. static toAscii(a) {
  468. return TD.decode(a);
  469. }
  470. reset() {
  471. this.buffers.length = 0;
  472. this.byteLength = 0;
  473. }
  474. pack() {
  475. if (this.buffers.length > 1) {
  476. const v = new Uint8Array(this.byteLength);
  477. let index = 0;
  478. for (let i = 0; i < this.buffers.length; i++) {
  479. v.set(this.buffers[i], index);
  480. index += this.buffers[i].length;
  481. }
  482. this.buffers.length = 0;
  483. this.buffers.push(v);
  484. }
  485. }
  486. shift() {
  487. if (this.buffers.length) {
  488. const a = this.buffers.shift();
  489. if (a) {
  490. this.byteLength -= a.length;
  491. return a;
  492. }
  493. }
  494. return new Uint8Array(0);
  495. }
  496. drain(n) {
  497. if (this.buffers.length) {
  498. this.pack();
  499. const v = this.buffers.pop();
  500. if (v) {
  501. const max = this.byteLength;
  502. if (n === void 0 || n > max) {
  503. n = max;
  504. }
  505. const d = v.subarray(0, n);
  506. if (max > n) {
  507. this.buffers.push(v.subarray(n));
  508. }
  509. this.byteLength = max - n;
  510. return d;
  511. }
  512. }
  513. return new Uint8Array(0);
  514. }
  515. fill(a, ...bufs) {
  516. if (a) {
  517. this.buffers.push(a);
  518. this.byteLength += a.length;
  519. }
  520. for (let i = 0; i < bufs.length; i++) {
  521. if (bufs[i] && bufs[i].length) {
  522. this.buffers.push(bufs[i]);
  523. this.byteLength += bufs[i].length;
  524. }
  525. }
  526. }
  527. peek() {
  528. if (this.buffers.length) {
  529. this.pack();
  530. return this.buffers[0];
  531. }
  532. return new Uint8Array(0);
  533. }
  534. size() {
  535. return this.byteLength;
  536. }
  537. length() {
  538. return this.buffers.length;
  539. }
  540. };
  541. var transportConfig;
  542. function setTransportFactory(config) {
  543. transportConfig = config;
  544. }
  545. function defaultPort() {
  546. return transportConfig !== void 0 && transportConfig.defaultPort !== void 0 ? transportConfig.defaultPort : 4222;
  547. }
  548. function getUrlParseFn() {
  549. return transportConfig !== void 0 && transportConfig.urlParseFn ? transportConfig.urlParseFn : void 0;
  550. }
  551. function newTransport() {
  552. if (!transportConfig || typeof transportConfig.factory !== "function") {
  553. throw new Error("transport fn is not set");
  554. }
  555. return transportConfig.factory();
  556. }
  557. function getResolveFn() {
  558. return transportConfig !== void 0 && transportConfig.dnsResolveFn ? transportConfig.dnsResolveFn : void 0;
  559. }
  560. var CR_LF = "\r\n";
  561. CR_LF.length;
  562. var CRLF = DataBuffer.fromAscii(CR_LF);
  563. var CR = new Uint8Array(CRLF)[0];
  564. var LF = new Uint8Array(CRLF)[1];
  565. function protoLen(ba) {
  566. for (let i = 0; i < ba.length; i++) {
  567. const n = i + 1;
  568. if (ba.byteLength > n && ba[i] === CR && ba[n] === LF) {
  569. return n + 1;
  570. }
  571. }
  572. return 0;
  573. }
  574. function extractProtocolMessage(a) {
  575. const len = protoLen(a);
  576. if (len > 0) {
  577. const ba = new Uint8Array(a);
  578. const out = ba.slice(0, len);
  579. return TD.decode(out);
  580. }
  581. return "";
  582. }
  583. var IPv4LEN = 4;
  584. var ASCII0 = 48;
  585. var ASCIIA = 65;
  586. var ASCIIa = 97;
  587. function ipV4(a, b, c, d) {
  588. const ip = new Uint8Array(16);
  589. const prefix = [
  590. 0,
  591. 0,
  592. 0,
  593. 0,
  594. 0,
  595. 0,
  596. 0,
  597. 0,
  598. 0,
  599. 0,
  600. 255,
  601. 255
  602. ];
  603. prefix.forEach((v, idx) => {
  604. ip[idx] = v;
  605. });
  606. ip[12] = a;
  607. ip[13] = b;
  608. ip[14] = c;
  609. ip[15] = d;
  610. return ip;
  611. }
  612. function isIP(h) {
  613. return parseIP(h) !== void 0;
  614. }
  615. function parseIP(h) {
  616. for (let i = 0; i < h.length; i++) {
  617. switch (h[i]) {
  618. case ".":
  619. return parseIPv4(h);
  620. case ":":
  621. return parseIPv6(h);
  622. }
  623. }
  624. return;
  625. }
  626. function parseIPv4(s) {
  627. const ip = new Uint8Array(4);
  628. for (let i = 0; i < 4; i++) {
  629. if (s.length === 0) {
  630. return void 0;
  631. }
  632. if (i > 0) {
  633. if (s[0] !== ".") {
  634. return void 0;
  635. }
  636. s = s.substring(1);
  637. }
  638. const { n, c, ok } = dtoi(s);
  639. if (!ok || n > 255) {
  640. return void 0;
  641. }
  642. s = s.substring(c);
  643. ip[i] = n;
  644. }
  645. return ipV4(ip[0], ip[1], ip[2], ip[3]);
  646. }
  647. function parseIPv6(s) {
  648. const ip = new Uint8Array(16);
  649. let ellipsis = -1;
  650. if (s.length >= 2 && s[0] === ":" && s[1] === ":") {
  651. ellipsis = 0;
  652. s = s.substring(2);
  653. if (s.length === 0) {
  654. return ip;
  655. }
  656. }
  657. let i = 0;
  658. while (i < 16) {
  659. const { n, c, ok } = xtoi(s);
  660. if (!ok || n > 65535) {
  661. return void 0;
  662. }
  663. if (c < s.length && s[c] === ".") {
  664. if (ellipsis < 0 && i != 16 - 4) {
  665. return void 0;
  666. }
  667. if (i + 4 > 16) {
  668. return void 0;
  669. }
  670. const ip4 = parseIPv4(s);
  671. if (ip4 === void 0) {
  672. return void 0;
  673. }
  674. ip[i] = ip4[12];
  675. ip[i + 1] = ip4[13];
  676. ip[i + 2] = ip4[14];
  677. ip[i + 3] = ip4[15];
  678. s = "";
  679. i += IPv4LEN;
  680. break;
  681. }
  682. ip[i] = n >> 8;
  683. ip[i + 1] = n;
  684. i += 2;
  685. s = s.substring(c);
  686. if (s.length === 0) {
  687. break;
  688. }
  689. if (s[0] !== ":" || s.length == 1) {
  690. return void 0;
  691. }
  692. s = s.substring(1);
  693. if (s[0] === ":") {
  694. if (ellipsis >= 0) {
  695. return void 0;
  696. }
  697. ellipsis = i;
  698. s = s.substring(1);
  699. if (s.length === 0) {
  700. break;
  701. }
  702. }
  703. }
  704. if (s.length !== 0) {
  705. return void 0;
  706. }
  707. if (i < 16) {
  708. if (ellipsis < 0) {
  709. return void 0;
  710. }
  711. const n = 16 - i;
  712. for (let j = i - 1; j >= ellipsis; j--) {
  713. ip[j + n] = ip[j];
  714. }
  715. for (let j = ellipsis + n - 1; j >= ellipsis; j--) {
  716. ip[j] = 0;
  717. }
  718. } else if (ellipsis >= 0) {
  719. return void 0;
  720. }
  721. return ip;
  722. }
  723. function dtoi(s) {
  724. let i = 0;
  725. let n = 0;
  726. for (i = 0; i < s.length && 48 <= s.charCodeAt(i) && s.charCodeAt(i) <= 57; i++) {
  727. n = n * 10 + (s.charCodeAt(i) - ASCII0);
  728. if (n >= 16777215) {
  729. return {
  730. n: 16777215,
  731. c: i,
  732. ok: false
  733. };
  734. }
  735. }
  736. if (i === 0) {
  737. return {
  738. n: 0,
  739. c: 0,
  740. ok: false
  741. };
  742. }
  743. return {
  744. n,
  745. c: i,
  746. ok: true
  747. };
  748. }
  749. function xtoi(s) {
  750. let n = 0;
  751. let i = 0;
  752. for (i = 0; i < s.length; i++) {
  753. if (48 <= s.charCodeAt(i) && s.charCodeAt(i) <= 57) {
  754. n *= 16;
  755. n += s.charCodeAt(i) - ASCII0;
  756. } else if (97 <= s.charCodeAt(i) && s.charCodeAt(i) <= 102) {
  757. n *= 16;
  758. n += s.charCodeAt(i) - ASCIIa + 10;
  759. } else if (65 <= s.charCodeAt(i) && s.charCodeAt(i) <= 70) {
  760. n *= 16;
  761. n += s.charCodeAt(i) - ASCIIA + 10;
  762. } else {
  763. break;
  764. }
  765. if (n >= 16777215) {
  766. return {
  767. n: 0,
  768. c: i,
  769. ok: false
  770. };
  771. }
  772. }
  773. if (i === 0) {
  774. return {
  775. n: 0,
  776. c: i,
  777. ok: false
  778. };
  779. }
  780. return {
  781. n,
  782. c: i,
  783. ok: true
  784. };
  785. }
  786. function isIPV4OrHostname(hp) {
  787. if (hp.indexOf(".") !== -1) {
  788. return true;
  789. }
  790. if (hp.indexOf("[") !== -1 || hp.indexOf("::") !== -1) {
  791. return false;
  792. }
  793. if (hp.split(":").length <= 2) {
  794. return true;
  795. }
  796. return false;
  797. }
  798. function isIPV6(hp) {
  799. return !isIPV4OrHostname(hp);
  800. }
  801. function filterIpv6MappedToIpv4(hp) {
  802. const prefix = "::FFFF:";
  803. const idx = hp.toUpperCase().indexOf(prefix);
  804. if (idx !== -1 && hp.indexOf(".") !== -1) {
  805. let ip = hp.substring(idx + prefix.length);
  806. ip = ip.replace("[", "");
  807. return ip.replace("]", "");
  808. }
  809. return hp;
  810. }
  811. function hostPort(u) {
  812. u = u.trim();
  813. if (u.match(/^(.*:\/\/)(.*)/m)) {
  814. u = u.replace(/^(.*:\/\/)(.*)/gm, "$2");
  815. }
  816. u = filterIpv6MappedToIpv4(u);
  817. if (isIPV6(u) && u.indexOf("[") === -1) {
  818. u = `[${u}]`;
  819. }
  820. const op = isIPV6(u) ? u.match(/(]:)(\d+)/) : u.match(/(:)(\d+)/);
  821. const port = op && op.length === 3 && op[1] && op[2] ? parseInt(op[2]) : 4222;
  822. const protocol = port === 80 ? "https" : "http";
  823. const url = new URL(`${protocol}://${u}`);
  824. url.port = `${port}`;
  825. let hostname = url.hostname;
  826. if (hostname.charAt(0) === "[") {
  827. hostname = hostname.substring(1, hostname.length - 1);
  828. }
  829. const listen = url.host;
  830. return {
  831. listen,
  832. hostname,
  833. port
  834. };
  835. }
  836. var ServerImpl = class {
  837. constructor(u, gossiped = false) {
  838. __publicField(this, "src");
  839. __publicField(this, "listen");
  840. __publicField(this, "hostname");
  841. __publicField(this, "port");
  842. __publicField(this, "didConnect");
  843. __publicField(this, "reconnects");
  844. __publicField(this, "lastConnect");
  845. __publicField(this, "gossiped");
  846. __publicField(this, "tlsName");
  847. __publicField(this, "resolves");
  848. this.src = u;
  849. this.tlsName = "";
  850. const v = hostPort(u);
  851. this.listen = v.listen;
  852. this.hostname = v.hostname;
  853. this.port = v.port;
  854. this.didConnect = false;
  855. this.reconnects = 0;
  856. this.lastConnect = 0;
  857. this.gossiped = gossiped;
  858. }
  859. toString() {
  860. return this.listen;
  861. }
  862. async resolve(opts) {
  863. if (!opts.fn) {
  864. return [
  865. this
  866. ];
  867. }
  868. const buf = [];
  869. if (isIP(this.hostname)) {
  870. return [
  871. this
  872. ];
  873. } else {
  874. const ips = await opts.fn(this.hostname);
  875. if (opts.debug) {
  876. console.log(`resolve ${this.hostname} = ${ips.join(",")}`);
  877. }
  878. for (const ip of ips) {
  879. const proto = this.port === 80 ? "https" : "http";
  880. const url = new URL(`${proto}://${isIPV6(ip) ? "[" + ip + "]" : ip}`);
  881. url.port = `${this.port}`;
  882. const ss = new ServerImpl(url.host, false);
  883. ss.tlsName = this.hostname;
  884. buf.push(ss);
  885. }
  886. }
  887. if (opts.randomize) {
  888. shuffle(buf);
  889. }
  890. this.resolves = buf;
  891. return buf;
  892. }
  893. };
  894. var Servers = class {
  895. constructor(listens = [], opts = {}) {
  896. __publicField(this, "firstSelect");
  897. __publicField(this, "servers");
  898. __publicField(this, "currentServer");
  899. __publicField(this, "tlsName");
  900. __publicField(this, "randomize");
  901. this.firstSelect = true;
  902. this.servers = [];
  903. this.tlsName = "";
  904. this.randomize = opts.randomize || false;
  905. const urlParseFn = getUrlParseFn();
  906. if (listens) {
  907. listens.forEach((hp) => {
  908. hp = urlParseFn ? urlParseFn(hp) : hp;
  909. this.servers.push(new ServerImpl(hp));
  910. });
  911. if (this.randomize) {
  912. this.servers = shuffle(this.servers);
  913. }
  914. }
  915. if (this.servers.length === 0) {
  916. this.addServer(`${DEFAULT_HOST}:${defaultPort()}`, false);
  917. }
  918. this.currentServer = this.servers[0];
  919. }
  920. clear() {
  921. this.servers.length = 0;
  922. }
  923. updateTLSName() {
  924. const cs = this.getCurrentServer();
  925. if (!isIP(cs.hostname)) {
  926. this.tlsName = cs.hostname;
  927. this.servers.forEach((s) => {
  928. if (s.gossiped) {
  929. s.tlsName = this.tlsName;
  930. }
  931. });
  932. }
  933. }
  934. getCurrentServer() {
  935. return this.currentServer;
  936. }
  937. addServer(u, implicit = false) {
  938. const urlParseFn = getUrlParseFn();
  939. u = urlParseFn ? urlParseFn(u) : u;
  940. const s = new ServerImpl(u, implicit);
  941. if (isIP(s.hostname)) {
  942. s.tlsName = this.tlsName;
  943. }
  944. this.servers.push(s);
  945. }
  946. selectServer() {
  947. if (this.firstSelect) {
  948. this.firstSelect = false;
  949. return this.currentServer;
  950. }
  951. const t = this.servers.shift();
  952. if (t) {
  953. this.servers.push(t);
  954. this.currentServer = t;
  955. }
  956. return t;
  957. }
  958. removeCurrentServer() {
  959. this.removeServer(this.currentServer);
  960. }
  961. removeServer(server) {
  962. if (server) {
  963. const index = this.servers.indexOf(server);
  964. this.servers.splice(index, 1);
  965. }
  966. }
  967. length() {
  968. return this.servers.length;
  969. }
  970. next() {
  971. return this.servers.length ? this.servers[0] : void 0;
  972. }
  973. getServers() {
  974. return this.servers;
  975. }
  976. update(info) {
  977. const added = [];
  978. let deleted = [];
  979. const urlParseFn = getUrlParseFn();
  980. const discovered = /* @__PURE__ */ new Map();
  981. if (info.connect_urls && info.connect_urls.length > 0) {
  982. info.connect_urls.forEach((hp) => {
  983. hp = urlParseFn ? urlParseFn(hp) : hp;
  984. const s = new ServerImpl(hp, true);
  985. discovered.set(hp, s);
  986. });
  987. }
  988. const toDelete = [];
  989. this.servers.forEach((s, index) => {
  990. const u = s.listen;
  991. if (s.gossiped && this.currentServer.listen !== u && discovered.get(u) === void 0) {
  992. toDelete.push(index);
  993. }
  994. discovered.delete(u);
  995. });
  996. toDelete.reverse();
  997. toDelete.forEach((index) => {
  998. const removed = this.servers.splice(index, 1);
  999. deleted = deleted.concat(removed[0].listen);
  1000. });
  1001. discovered.forEach((v, k) => {
  1002. this.servers.push(v);
  1003. added.push(k);
  1004. });
  1005. return {
  1006. added,
  1007. deleted
  1008. };
  1009. }
  1010. };
  1011. var QueuedIteratorImpl = class {
  1012. constructor() {
  1013. __publicField(this, "inflight");
  1014. __publicField(this, "processed");
  1015. __publicField(this, "received");
  1016. __publicField(this, "noIterator");
  1017. __publicField(this, "iterClosed");
  1018. __publicField(this, "done");
  1019. __publicField(this, "signal");
  1020. __publicField(this, "yields");
  1021. __publicField(this, "filtered");
  1022. __publicField(this, "pendingFiltered");
  1023. __publicField(this, "ingestionFilterFn");
  1024. __publicField(this, "protocolFilterFn");
  1025. __publicField(this, "dispatchedFn");
  1026. __publicField(this, "ctx");
  1027. __publicField(this, "_data");
  1028. __publicField(this, "err");
  1029. __publicField(this, "time");
  1030. __publicField(this, "yielding");
  1031. this.inflight = 0;
  1032. this.filtered = 0;
  1033. this.pendingFiltered = 0;
  1034. this.processed = 0;
  1035. this.received = 0;
  1036. this.noIterator = false;
  1037. this.done = false;
  1038. this.signal = deferred();
  1039. this.yields = [];
  1040. this.iterClosed = deferred();
  1041. this.time = 0;
  1042. this.yielding = false;
  1043. }
  1044. [Symbol.asyncIterator]() {
  1045. return this.iterate();
  1046. }
  1047. push(v) {
  1048. if (this.done) {
  1049. return;
  1050. }
  1051. if (typeof v === "function") {
  1052. this.yields.push(v);
  1053. this.signal.resolve();
  1054. return;
  1055. }
  1056. const { ingest, protocol } = this.ingestionFilterFn ? this.ingestionFilterFn(v, this.ctx || this) : {
  1057. ingest: true,
  1058. protocol: false
  1059. };
  1060. if (ingest) {
  1061. if (protocol) {
  1062. this.filtered++;
  1063. this.pendingFiltered++;
  1064. }
  1065. this.yields.push(v);
  1066. this.signal.resolve();
  1067. }
  1068. }
  1069. async *iterate() {
  1070. if (this.noIterator) {
  1071. throw new NatsError("unsupported iterator", ErrorCode.ApiError);
  1072. }
  1073. if (this.yielding) {
  1074. throw new NatsError("already yielding", ErrorCode.ApiError);
  1075. }
  1076. this.yielding = true;
  1077. try {
  1078. while (true) {
  1079. if (this.yields.length === 0) {
  1080. await this.signal;
  1081. }
  1082. if (this.err) {
  1083. throw this.err;
  1084. }
  1085. const yields = this.yields;
  1086. this.inflight = yields.length;
  1087. this.yields = [];
  1088. for (let i = 0; i < yields.length; i++) {
  1089. if (typeof yields[i] === "function") {
  1090. const fn = yields[i];
  1091. try {
  1092. fn();
  1093. } catch (err) {
  1094. throw err;
  1095. }
  1096. if (this.err) {
  1097. throw this.err;
  1098. }
  1099. continue;
  1100. }
  1101. const ok = this.protocolFilterFn ? this.protocolFilterFn(yields[i]) : true;
  1102. if (ok) {
  1103. this.processed++;
  1104. const start = Date.now();
  1105. yield yields[i];
  1106. this.time = Date.now() - start;
  1107. if (this.dispatchedFn && yields[i]) {
  1108. this.dispatchedFn(yields[i]);
  1109. }
  1110. } else {
  1111. this.pendingFiltered--;
  1112. }
  1113. this.inflight--;
  1114. }
  1115. if (this.done) {
  1116. break;
  1117. } else if (this.yields.length === 0) {
  1118. yields.length = 0;
  1119. this.yields = yields;
  1120. this.signal = deferred();
  1121. }
  1122. }
  1123. } finally {
  1124. this.stop();
  1125. }
  1126. }
  1127. stop(err) {
  1128. if (this.done) {
  1129. return;
  1130. }
  1131. this.err = err;
  1132. this.done = true;
  1133. this.signal.resolve();
  1134. this.iterClosed.resolve();
  1135. }
  1136. getProcessed() {
  1137. return this.noIterator ? this.received : this.processed;
  1138. }
  1139. getPending() {
  1140. return this.yields.length + this.inflight - this.pendingFiltered;
  1141. }
  1142. getReceived() {
  1143. return this.received - this.filtered;
  1144. }
  1145. };
  1146. function canonicalMIMEHeaderKey(k) {
  1147. const dash = 45;
  1148. const toLower = 97 - 65;
  1149. let upper = true;
  1150. const buf = new Array(k.length);
  1151. for (let i = 0; i < k.length; i++) {
  1152. let c = k.charCodeAt(i);
  1153. if (c === 58 || c < 33 || c > 126) {
  1154. throw new NatsError(`'${k[i]}' is not a valid character for a header key`, ErrorCode.BadHeader);
  1155. }
  1156. if (upper && 97 <= c && c <= 122) {
  1157. c -= toLower;
  1158. } else if (!upper && 65 <= c && c <= 90) {
  1159. c += toLower;
  1160. }
  1161. buf[i] = c;
  1162. upper = c == dash;
  1163. }
  1164. return String.fromCharCode(...buf);
  1165. }
  1166. function headers(code2 = 0, description = "") {
  1167. if (code2 === 0 && description !== "" || code2 > 0 && description === "") {
  1168. throw new Error("setting status requires both code and description");
  1169. }
  1170. return new MsgHdrsImpl(code2, description);
  1171. }
  1172. var HEADER = "NATS/1.0";
  1173. var MsgHdrsImpl = class {
  1174. constructor(code2 = 0, description = "") {
  1175. __publicField(this, "_code");
  1176. __publicField(this, "headers");
  1177. __publicField(this, "_description");
  1178. this._code = code2;
  1179. this._description = description;
  1180. this.headers = /* @__PURE__ */ new Map();
  1181. }
  1182. [Symbol.iterator]() {
  1183. return this.headers.entries();
  1184. }
  1185. size() {
  1186. return this.headers.size;
  1187. }
  1188. equals(mh) {
  1189. if (mh && this.headers.size === mh.headers.size && this._code === mh._code) {
  1190. for (const [k, v] of this.headers) {
  1191. const a = mh.values(k);
  1192. if (v.length !== a.length) {
  1193. return false;
  1194. }
  1195. const vv = [
  1196. ...v
  1197. ].sort();
  1198. const aa = [
  1199. ...a
  1200. ].sort();
  1201. for (let i = 0; i < vv.length; i++) {
  1202. if (vv[i] !== aa[i]) {
  1203. return false;
  1204. }
  1205. }
  1206. }
  1207. return true;
  1208. }
  1209. return false;
  1210. }
  1211. static decode(a) {
  1212. const mh = new MsgHdrsImpl();
  1213. const s = TD.decode(a);
  1214. const lines = s.split("\r\n");
  1215. const h = lines[0];
  1216. if (h !== HEADER) {
  1217. let str = h.replace(HEADER, "").trim();
  1218. if (str.length > 0) {
  1219. mh._code = parseInt(str, 10);
  1220. if (isNaN(mh._code)) {
  1221. mh._code = 0;
  1222. }
  1223. const scode = mh._code.toString();
  1224. str = str.replace(scode, "");
  1225. mh._description = str.trim();
  1226. }
  1227. }
  1228. if (lines.length >= 1) {
  1229. lines.slice(1).map((s2) => {
  1230. if (s2) {
  1231. const idx = s2.indexOf(":");
  1232. if (idx > -1) {
  1233. const k = s2.slice(0, idx);
  1234. const v = s2.slice(idx + 1).trim();
  1235. mh.append(k, v);
  1236. }
  1237. }
  1238. });
  1239. }
  1240. return mh;
  1241. }
  1242. toString() {
  1243. if (this.headers.size === 0 && this._code === 0) {
  1244. return "";
  1245. }
  1246. let s = HEADER;
  1247. if (this._code > 0 && this._description !== "") {
  1248. s += ` ${this._code} ${this._description}`;
  1249. }
  1250. for (const [k, v] of this.headers) {
  1251. for (let i = 0; i < v.length; i++) {
  1252. s = `${s}\r
  1253. ${k}: ${v[i]}`;
  1254. }
  1255. }
  1256. return `${s}\r
  1257. \r
  1258. `;
  1259. }
  1260. encode() {
  1261. return TE.encode(this.toString());
  1262. }
  1263. static validHeaderValue(k) {
  1264. const inv = /[\r\n]/;
  1265. if (inv.test(k)) {
  1266. throw new NatsError("invalid header value - \\r and \\n are not allowed.", ErrorCode.BadHeader);
  1267. }
  1268. return k.trim();
  1269. }
  1270. keys() {
  1271. const keys = [];
  1272. for (const sk of this.headers.keys()) {
  1273. keys.push(sk);
  1274. }
  1275. return keys;
  1276. }
  1277. findKeys(k, match = Match.Exact) {
  1278. const keys = this.keys();
  1279. switch (match) {
  1280. case Match.Exact:
  1281. return keys.filter((v) => {
  1282. return v === k;
  1283. });
  1284. case Match.CanonicalMIME:
  1285. k = canonicalMIMEHeaderKey(k);
  1286. return keys.filter((v) => {
  1287. return v === k;
  1288. });
  1289. default: {
  1290. const lci = k.toLowerCase();
  1291. return keys.filter((v) => {
  1292. return lci === v.toLowerCase();
  1293. });
  1294. }
  1295. }
  1296. }
  1297. get(k, match = Match.Exact) {
  1298. const keys = this.findKeys(k, match);
  1299. if (keys.length) {
  1300. const v = this.headers.get(keys[0]);
  1301. if (v) {
  1302. return Array.isArray(v) ? v[0] : v;
  1303. }
  1304. }
  1305. return "";
  1306. }
  1307. last(k, match = Match.Exact) {
  1308. const keys = this.findKeys(k, match);
  1309. if (keys.length) {
  1310. const v = this.headers.get(keys[0]);
  1311. if (v) {
  1312. return Array.isArray(v) ? v[v.length - 1] : v;
  1313. }
  1314. }
  1315. return "";
  1316. }
  1317. has(k, match = Match.Exact) {
  1318. return this.findKeys(k, match).length > 0;
  1319. }
  1320. set(k, v, match = Match.Exact) {
  1321. this.delete(k, match);
  1322. this.append(k, v, match);
  1323. }
  1324. append(k, v, match = Match.Exact) {
  1325. const ck = canonicalMIMEHeaderKey(k);
  1326. if (match === Match.CanonicalMIME) {
  1327. k = ck;
  1328. }
  1329. const keys = this.findKeys(k, match);
  1330. k = keys.length > 0 ? keys[0] : k;
  1331. const value = MsgHdrsImpl.validHeaderValue(v);
  1332. let a = this.headers.get(k);
  1333. if (!a) {
  1334. a = [];
  1335. this.headers.set(k, a);
  1336. }
  1337. a.push(value);
  1338. }
  1339. values(k, match = Match.Exact) {
  1340. const buf = [];
  1341. const keys = this.findKeys(k, match);
  1342. keys.forEach((v) => {
  1343. const values = this.headers.get(v);
  1344. if (values) {
  1345. buf.push(...values);
  1346. }
  1347. });
  1348. return buf;
  1349. }
  1350. delete(k, match = Match.Exact) {
  1351. const keys = this.findKeys(k, match);
  1352. keys.forEach((v) => {
  1353. this.headers.delete(v);
  1354. });
  1355. }
  1356. get hasError() {
  1357. return this._code >= 300;
  1358. }
  1359. get status() {
  1360. return `${this._code} ${this._description}`.trim();
  1361. }
  1362. toRecord() {
  1363. const data = {};
  1364. this.keys().forEach((v) => {
  1365. data[v] = this.values(v);
  1366. });
  1367. return data;
  1368. }
  1369. get code() {
  1370. return this._code;
  1371. }
  1372. get description() {
  1373. return this._description;
  1374. }
  1375. static fromRecord(r) {
  1376. const h = new MsgHdrsImpl();
  1377. for (const k in r) {
  1378. h.headers.set(k, r[k]);
  1379. }
  1380. return h;
  1381. }
  1382. };
  1383. function StringCodec() {
  1384. return {
  1385. encode(d) {
  1386. return TE.encode(d);
  1387. },
  1388. decode(a) {
  1389. return TD.decode(a);
  1390. }
  1391. };
  1392. }
  1393. function JSONCodec(reviver) {
  1394. return {
  1395. encode(d) {
  1396. try {
  1397. if (d === void 0) {
  1398. d = null;
  1399. }
  1400. return TE.encode(JSON.stringify(d));
  1401. } catch (err) {
  1402. throw NatsError.errorForCode(ErrorCode.BadJson, err);
  1403. }
  1404. },
  1405. decode(a) {
  1406. try {
  1407. return JSON.parse(TD.decode(a), reviver);
  1408. } catch (err) {
  1409. throw NatsError.errorForCode(ErrorCode.BadJson, err);
  1410. }
  1411. }
  1412. };
  1413. }
  1414. function isRequestError(msg) {
  1415. var _a;
  1416. if (msg && msg.data.length === 0 && ((_a = msg.headers) == null ? void 0 : _a.code) === 503) {
  1417. return NatsError.errorForCode(ErrorCode.NoResponders);
  1418. }
  1419. return null;
  1420. }
  1421. var MsgImpl = class {
  1422. constructor(msg, data, publisher) {
  1423. __publicField(this, "_headers");
  1424. __publicField(this, "_msg");
  1425. __publicField(this, "_rdata");
  1426. __publicField(this, "_reply");
  1427. __publicField(this, "_subject");
  1428. __publicField(this, "publisher");
  1429. this._msg = msg;
  1430. this._rdata = data;
  1431. this.publisher = publisher;
  1432. }
  1433. get subject() {
  1434. if (this._subject) {
  1435. return this._subject;
  1436. }
  1437. this._subject = TD.decode(this._msg.subject);
  1438. return this._subject;
  1439. }
  1440. get reply() {
  1441. if (this._reply) {
  1442. return this._reply;
  1443. }
  1444. this._reply = TD.decode(this._msg.reply);
  1445. return this._reply;
  1446. }
  1447. get sid() {
  1448. return this._msg.sid;
  1449. }
  1450. get headers() {
  1451. if (this._msg.hdr > -1 && !this._headers) {
  1452. const buf = this._rdata.subarray(0, this._msg.hdr);
  1453. this._headers = MsgHdrsImpl.decode(buf);
  1454. }
  1455. return this._headers;
  1456. }
  1457. get data() {
  1458. if (!this._rdata) {
  1459. return new Uint8Array(0);
  1460. }
  1461. return this._msg.hdr > -1 ? this._rdata.subarray(this._msg.hdr) : this._rdata;
  1462. }
  1463. respond(data = Empty, opts) {
  1464. if (this.reply) {
  1465. this.publisher.publish(this.reply, data, opts);
  1466. return true;
  1467. }
  1468. return false;
  1469. }
  1470. size() {
  1471. var _a;
  1472. const subj = this._msg.subject.length;
  1473. const reply = ((_a = this._msg.reply) == null ? void 0 : _a.length) || 0;
  1474. const payloadAndHeaders = this._msg.size === -1 ? 0 : this._msg.size;
  1475. return subj + reply + payloadAndHeaders;
  1476. }
  1477. json(reviver) {
  1478. return JSONCodec(reviver).decode(this.data);
  1479. }
  1480. string() {
  1481. return TD.decode(this.data);
  1482. }
  1483. };
  1484. __publicField(MsgImpl, "jc");
  1485. var MuxSubscription = class {
  1486. constructor() {
  1487. __publicField(this, "baseInbox");
  1488. __publicField(this, "reqs");
  1489. this.reqs = /* @__PURE__ */ new Map();
  1490. }
  1491. size() {
  1492. return this.reqs.size;
  1493. }
  1494. init(prefix) {
  1495. this.baseInbox = `${createInbox(prefix)}.`;
  1496. return this.baseInbox;
  1497. }
  1498. add(r) {
  1499. if (!isNaN(r.received)) {
  1500. r.received = 0;
  1501. }
  1502. this.reqs.set(r.token, r);
  1503. }
  1504. get(token) {
  1505. return this.reqs.get(token);
  1506. }
  1507. cancel(r) {
  1508. this.reqs.delete(r.token);
  1509. }
  1510. getToken(m) {
  1511. const s = m.subject || "";
  1512. if (s.indexOf(this.baseInbox) === 0) {
  1513. return s.substring(this.baseInbox.length);
  1514. }
  1515. return null;
  1516. }
  1517. all() {
  1518. return Array.from(this.reqs.values());
  1519. }
  1520. handleError(isMuxPermissionError, err) {
  1521. if (err && err.permissionContext) {
  1522. if (isMuxPermissionError) {
  1523. this.all().forEach((r) => {
  1524. r.resolver(err, {});
  1525. });
  1526. return true;
  1527. }
  1528. const ctx = err.permissionContext;
  1529. if (ctx.operation === "publish") {
  1530. const req = this.all().find((s) => {
  1531. return s.requestSubject === ctx.subject;
  1532. });
  1533. if (req) {
  1534. req.resolver(err, {});
  1535. return true;
  1536. }
  1537. }
  1538. }
  1539. return false;
  1540. }
  1541. dispatcher() {
  1542. return (err, m) => {
  1543. const token = this.getToken(m);
  1544. if (token) {
  1545. const r = this.get(token);
  1546. if (r) {
  1547. if (err === null && m.headers) {
  1548. err = isRequestError(m);
  1549. }
  1550. r.resolver(err, m);
  1551. }
  1552. }
  1553. };
  1554. }
  1555. close() {
  1556. const err = NatsError.errorForCode(ErrorCode.Timeout);
  1557. this.reqs.forEach((req) => {
  1558. req.resolver(err, {});
  1559. });
  1560. }
  1561. };
  1562. var Heartbeat = class {
  1563. constructor(ph, interval, maxOut) {
  1564. __publicField(this, "ph");
  1565. __publicField(this, "interval");
  1566. __publicField(this, "maxOut");
  1567. __publicField(this, "timer");
  1568. __publicField(this, "pendings");
  1569. this.ph = ph;
  1570. this.interval = interval;
  1571. this.maxOut = maxOut;
  1572. this.pendings = [];
  1573. }
  1574. start() {
  1575. this.cancel();
  1576. this._schedule();
  1577. }
  1578. cancel(stale) {
  1579. if (this.timer) {
  1580. clearTimeout(this.timer);
  1581. this.timer = void 0;
  1582. }
  1583. this._reset();
  1584. if (stale) {
  1585. this.ph.disconnect();
  1586. }
  1587. }
  1588. _schedule() {
  1589. this.timer = setTimeout(() => {
  1590. this.ph.dispatchStatus({
  1591. type: DebugEvents.PingTimer,
  1592. data: `${this.pendings.length + 1}`
  1593. });
  1594. if (this.pendings.length === this.maxOut) {
  1595. this.cancel(true);
  1596. return;
  1597. }
  1598. const ping = deferred();
  1599. this.ph.flush(ping).then(() => {
  1600. this._reset();
  1601. }).catch(() => {
  1602. this.cancel();
  1603. });
  1604. this.pendings.push(ping);
  1605. this._schedule();
  1606. }, this.interval);
  1607. }
  1608. _reset() {
  1609. this.pendings = this.pendings.filter((p) => {
  1610. const d = p;
  1611. d.resolve();
  1612. return false;
  1613. });
  1614. }
  1615. };
  1616. var AssertionError = class extends Error {
  1617. constructor(msg) {
  1618. super(msg);
  1619. this.name = "AssertionError";
  1620. }
  1621. };
  1622. function assert(cond, msg = "Assertion failed.") {
  1623. if (!cond) {
  1624. throw new AssertionError(msg);
  1625. }
  1626. }
  1627. var MIN_READ = 32 * 1024;
  1628. var MAX_SIZE = 2 ** 32 - 2;
  1629. function copy(src, dst, off = 0) {
  1630. const r = dst.byteLength - off;
  1631. if (src.byteLength > r) {
  1632. src = src.subarray(0, r);
  1633. }
  1634. dst.set(src, off);
  1635. return src.byteLength;
  1636. }
  1637. var DenoBuffer = class {
  1638. constructor(ab) {
  1639. __publicField(this, "_buf");
  1640. __publicField(this, "_off");
  1641. this._off = 0;
  1642. if (ab == null) {
  1643. this._buf = new Uint8Array(0);
  1644. return;
  1645. }
  1646. this._buf = new Uint8Array(ab);
  1647. }
  1648. bytes(options = {
  1649. copy: true
  1650. }) {
  1651. if (options.copy === false)
  1652. return this._buf.subarray(this._off);
  1653. return this._buf.slice(this._off);
  1654. }
  1655. empty() {
  1656. return this._buf.byteLength <= this._off;
  1657. }
  1658. get length() {
  1659. return this._buf.byteLength - this._off;
  1660. }
  1661. get capacity() {
  1662. return this._buf.buffer.byteLength;
  1663. }
  1664. truncate(n) {
  1665. if (n === 0) {
  1666. this.reset();
  1667. return;
  1668. }
  1669. if (n < 0 || n > this.length) {
  1670. throw Error("bytes.Buffer: truncation out of range");
  1671. }
  1672. this._reslice(this._off + n);
  1673. }
  1674. reset() {
  1675. this._reslice(0);
  1676. this._off = 0;
  1677. }
  1678. _tryGrowByReslice(n) {
  1679. const l = this._buf.byteLength;
  1680. if (n <= this.capacity - l) {
  1681. this._reslice(l + n);
  1682. return l;
  1683. }
  1684. return -1;
  1685. }
  1686. _reslice(len) {
  1687. assert(len <= this._buf.buffer.byteLength);
  1688. this._buf = new Uint8Array(this._buf.buffer, 0, len);
  1689. }
  1690. readByte() {
  1691. const a = new Uint8Array(1);
  1692. if (this.read(a)) {
  1693. return a[0];
  1694. }
  1695. return null;
  1696. }
  1697. read(p) {
  1698. if (this.empty()) {
  1699. this.reset();
  1700. if (p.byteLength === 0) {
  1701. return 0;
  1702. }
  1703. return null;
  1704. }
  1705. const nread = copy(this._buf.subarray(this._off), p);
  1706. this._off += nread;
  1707. return nread;
  1708. }
  1709. writeByte(n) {
  1710. return this.write(Uint8Array.of(n));
  1711. }
  1712. writeString(s) {
  1713. return this.write(TE.encode(s));
  1714. }
  1715. write(p) {
  1716. const m = this._grow(p.byteLength);
  1717. return copy(p, this._buf, m);
  1718. }
  1719. _grow(n) {
  1720. const m = this.length;
  1721. if (m === 0 && this._off !== 0) {
  1722. this.reset();
  1723. }
  1724. const i = this._tryGrowByReslice(n);
  1725. if (i >= 0) {
  1726. return i;
  1727. }
  1728. const c = this.capacity;
  1729. if (n <= Math.floor(c / 2) - m) {
  1730. copy(this._buf.subarray(this._off), this._buf);
  1731. } else if (c + n > MAX_SIZE) {
  1732. throw new Error("The buffer cannot be grown beyond the maximum size.");
  1733. } else {
  1734. const buf = new Uint8Array(Math.min(2 * c + n, MAX_SIZE));
  1735. copy(this._buf.subarray(this._off), buf);
  1736. this._buf = buf;
  1737. }
  1738. this._off = 0;
  1739. this._reslice(Math.min(m + n, MAX_SIZE));
  1740. return m;
  1741. }
  1742. grow(n) {
  1743. if (n < 0) {
  1744. throw Error("Buffer._grow: negative count");
  1745. }
  1746. const m = this._grow(n);
  1747. this._reslice(m);
  1748. }
  1749. readFrom(r) {
  1750. let n = 0;
  1751. const tmp = new Uint8Array(MIN_READ);
  1752. while (true) {
  1753. const shouldGrow = this.capacity - this.length < MIN_READ;
  1754. const buf = shouldGrow ? tmp : new Uint8Array(this._buf.buffer, this.length);
  1755. const nread = r.read(buf);
  1756. if (nread === null) {
  1757. return n;
  1758. }
  1759. if (shouldGrow)
  1760. this.write(buf.subarray(0, nread));
  1761. else
  1762. this._reslice(this.length + nread);
  1763. n += nread;
  1764. }
  1765. }
  1766. };
  1767. var Kind;
  1768. (function(Kind2) {
  1769. Kind2[Kind2["OK"] = 0] = "OK";
  1770. Kind2[Kind2["ERR"] = 1] = "ERR";
  1771. Kind2[Kind2["MSG"] = 2] = "MSG";
  1772. Kind2[Kind2["INFO"] = 3] = "INFO";
  1773. Kind2[Kind2["PING"] = 4] = "PING";
  1774. Kind2[Kind2["PONG"] = 5] = "PONG";
  1775. })(Kind || (Kind = {}));
  1776. function newMsgArg() {
  1777. const ma = {};
  1778. ma.sid = -1;
  1779. ma.hdr = -1;
  1780. ma.size = -1;
  1781. return ma;
  1782. }
  1783. var ASCII_0 = 48;
  1784. var Parser = class {
  1785. constructor(dispatcher) {
  1786. __publicField(this, "dispatcher");
  1787. __publicField(this, "state");
  1788. __publicField(this, "as");
  1789. __publicField(this, "drop");
  1790. __publicField(this, "hdr");
  1791. __publicField(this, "ma");
  1792. __publicField(this, "argBuf");
  1793. __publicField(this, "msgBuf");
  1794. this.dispatcher = dispatcher;
  1795. this.state = State.OP_START;
  1796. this.as = 0;
  1797. this.drop = 0;
  1798. this.hdr = 0;
  1799. }
  1800. parse(buf) {
  1801. let i;
  1802. for (i = 0; i < buf.length; i++) {
  1803. const b = buf[i];
  1804. switch (this.state) {
  1805. case State.OP_START:
  1806. switch (b) {
  1807. case cc.M:
  1808. case cc.m:
  1809. this.state = State.OP_M;
  1810. this.hdr = -1;
  1811. this.ma = newMsgArg();
  1812. break;
  1813. case cc.H:
  1814. case cc.h:
  1815. this.state = State.OP_H;
  1816. this.hdr = 0;
  1817. this.ma = newMsgArg();
  1818. break;
  1819. case cc.P:
  1820. case cc.p:
  1821. this.state = State.OP_P;
  1822. break;
  1823. case cc.PLUS:
  1824. this.state = State.OP_PLUS;
  1825. break;
  1826. case cc.MINUS:
  1827. this.state = State.OP_MINUS;
  1828. break;
  1829. case cc.I:
  1830. case cc.i:
  1831. this.state = State.OP_I;
  1832. break;
  1833. default:
  1834. throw this.fail(buf.subarray(i));
  1835. }
  1836. break;
  1837. case State.OP_H:
  1838. switch (b) {
  1839. case cc.M:
  1840. case cc.m:
  1841. this.state = State.OP_M;
  1842. break;
  1843. default:
  1844. throw this.fail(buf.subarray(i));
  1845. }
  1846. break;
  1847. case State.OP_M:
  1848. switch (b) {
  1849. case cc.S:
  1850. case cc.s:
  1851. this.state = State.OP_MS;
  1852. break;
  1853. default:
  1854. throw this.fail(buf.subarray(i));
  1855. }
  1856. break;
  1857. case State.OP_MS:
  1858. switch (b) {
  1859. case cc.G:
  1860. case cc.g:
  1861. this.state = State.OP_MSG;
  1862. break;
  1863. default:
  1864. throw this.fail(buf.subarray(i));
  1865. }
  1866. break;
  1867. case State.OP_MSG:
  1868. switch (b) {
  1869. case cc.SPACE:
  1870. case cc.TAB:
  1871. this.state = State.OP_MSG_SPC;
  1872. break;
  1873. default:
  1874. throw this.fail(buf.subarray(i));
  1875. }
  1876. break;
  1877. case State.OP_MSG_SPC:
  1878. switch (b) {
  1879. case cc.SPACE:
  1880. case cc.TAB:
  1881. continue;
  1882. default:
  1883. this.state = State.MSG_ARG;
  1884. this.as = i;
  1885. }
  1886. break;
  1887. case State.MSG_ARG:
  1888. switch (b) {
  1889. case cc.CR:
  1890. this.drop = 1;
  1891. break;
  1892. case cc.NL: {
  1893. const arg = this.argBuf ? this.argBuf.bytes() : buf.subarray(this.as, i - this.drop);
  1894. this.processMsgArgs(arg);
  1895. this.drop = 0;
  1896. this.as = i + 1;
  1897. this.state = State.MSG_PAYLOAD;
  1898. i = this.as + this.ma.size - 1;
  1899. break;
  1900. }
  1901. default:
  1902. if (this.argBuf) {
  1903. this.argBuf.writeByte(b);
  1904. }
  1905. }
  1906. break;
  1907. case State.MSG_PAYLOAD:
  1908. if (this.msgBuf) {
  1909. if (this.msgBuf.length >= this.ma.size) {
  1910. const data = this.msgBuf.bytes({
  1911. copy: false
  1912. });
  1913. this.dispatcher.push({
  1914. kind: Kind.MSG,
  1915. msg: this.ma,
  1916. data
  1917. });
  1918. this.argBuf = void 0;
  1919. this.msgBuf = void 0;
  1920. this.state = State.MSG_END;
  1921. } else {
  1922. let toCopy = this.ma.size - this.msgBuf.length;
  1923. const avail = buf.length - i;
  1924. if (avail < toCopy) {
  1925. toCopy = avail;
  1926. }
  1927. if (toCopy > 0) {
  1928. this.msgBuf.write(buf.subarray(i, i + toCopy));
  1929. i = i + toCopy - 1;
  1930. } else {
  1931. this.msgBuf.writeByte(b);
  1932. }
  1933. }
  1934. } else if (i - this.as >= this.ma.size) {
  1935. this.dispatcher.push({
  1936. kind: Kind.MSG,
  1937. msg: this.ma,
  1938. data: buf.subarray(this.as, i)
  1939. });
  1940. this.argBuf = void 0;
  1941. this.msgBuf = void 0;
  1942. this.state = State.MSG_END;
  1943. }
  1944. break;
  1945. case State.MSG_END:
  1946. switch (b) {
  1947. case cc.NL:
  1948. this.drop = 0;
  1949. this.as = i + 1;
  1950. this.state = State.OP_START;
  1951. break;
  1952. default:
  1953. continue;
  1954. }
  1955. break;
  1956. case State.OP_PLUS:
  1957. switch (b) {
  1958. case cc.O:
  1959. case cc.o:
  1960. this.state = State.OP_PLUS_O;
  1961. break;
  1962. default:
  1963. throw this.fail(buf.subarray(i));
  1964. }
  1965. break;
  1966. case State.OP_PLUS_O:
  1967. switch (b) {
  1968. case cc.K:
  1969. case cc.k:
  1970. this.state = State.OP_PLUS_OK;
  1971. break;
  1972. default:
  1973. throw this.fail(buf.subarray(i));
  1974. }
  1975. break;
  1976. case State.OP_PLUS_OK:
  1977. switch (b) {
  1978. case cc.NL:
  1979. this.dispatcher.push({
  1980. kind: Kind.OK
  1981. });
  1982. this.drop = 0;
  1983. this.state = State.OP_START;
  1984. break;
  1985. }
  1986. break;
  1987. case State.OP_MINUS:
  1988. switch (b) {
  1989. case cc.E:
  1990. case cc.e:
  1991. this.state = State.OP_MINUS_E;
  1992. break;
  1993. default:
  1994. throw this.fail(buf.subarray(i));
  1995. }
  1996. break;
  1997. case State.OP_MINUS_E:
  1998. switch (b) {
  1999. case cc.R:
  2000. case cc.r:
  2001. this.state = State.OP_MINUS_ER;
  2002. break;
  2003. default:
  2004. throw this.fail(buf.subarray(i));
  2005. }
  2006. break;
  2007. case State.OP_MINUS_ER:
  2008. switch (b) {
  2009. case cc.R:
  2010. case cc.r:
  2011. this.state = State.OP_MINUS_ERR;
  2012. break;
  2013. default:
  2014. throw this.fail(buf.subarray(i));
  2015. }
  2016. break;
  2017. case State.OP_MINUS_ERR:
  2018. switch (b) {
  2019. case cc.SPACE:
  2020. case cc.TAB:
  2021. this.state = State.OP_MINUS_ERR_SPC;
  2022. break;
  2023. default:
  2024. throw this.fail(buf.subarray(i));
  2025. }
  2026. break;
  2027. case State.OP_MINUS_ERR_SPC:
  2028. switch (b) {
  2029. case cc.SPACE:
  2030. case cc.TAB:
  2031. continue;
  2032. default:
  2033. this.state = State.MINUS_ERR_ARG;
  2034. this.as = i;
  2035. }
  2036. break;
  2037. case State.MINUS_ERR_ARG:
  2038. switch (b) {
  2039. case cc.CR:
  2040. this.drop = 1;
  2041. break;
  2042. case cc.NL: {
  2043. let arg;
  2044. if (this.argBuf) {
  2045. arg = this.argBuf.bytes();
  2046. this.argBuf = void 0;
  2047. } else {
  2048. arg = buf.subarray(this.as, i - this.drop);
  2049. }
  2050. this.dispatcher.push({
  2051. kind: Kind.ERR,
  2052. data: arg
  2053. });
  2054. this.drop = 0;
  2055. this.as = i + 1;
  2056. this.state = State.OP_START;
  2057. break;
  2058. }
  2059. default:
  2060. if (this.argBuf) {
  2061. this.argBuf.write(Uint8Array.of(b));
  2062. }
  2063. }
  2064. break;
  2065. case State.OP_P:
  2066. switch (b) {
  2067. case cc.I:
  2068. case cc.i:
  2069. this.state = State.OP_PI;
  2070. break;
  2071. case cc.O:
  2072. case cc.o:
  2073. this.state = State.OP_PO;
  2074. break;
  2075. default:
  2076. throw this.fail(buf.subarray(i));
  2077. }
  2078. break;
  2079. case State.OP_PO:
  2080. switch (b) {
  2081. case cc.N:
  2082. case cc.n:
  2083. this.state = State.OP_PON;
  2084. break;
  2085. default:
  2086. throw this.fail(buf.subarray(i));
  2087. }
  2088. break;
  2089. case State.OP_PON:
  2090. switch (b) {
  2091. case cc.G:
  2092. case cc.g:
  2093. this.state = State.OP_PONG;
  2094. break;
  2095. default:
  2096. throw this.fail(buf.subarray(i));
  2097. }
  2098. break;
  2099. case State.OP_PONG:
  2100. switch (b) {
  2101. case cc.NL:
  2102. this.dispatcher.push({
  2103. kind: Kind.PONG
  2104. });
  2105. this.drop = 0;
  2106. this.state = State.OP_START;
  2107. break;
  2108. }
  2109. break;
  2110. case State.OP_PI:
  2111. switch (b) {
  2112. case cc.N:
  2113. case cc.n:
  2114. this.state = State.OP_PIN;
  2115. break;
  2116. default:
  2117. throw this.fail(buf.subarray(i));
  2118. }
  2119. break;
  2120. case State.OP_PIN:
  2121. switch (b) {
  2122. case cc.G:
  2123. case cc.g:
  2124. this.state = State.OP_PING;
  2125. break;
  2126. default:
  2127. throw this.fail(buf.subarray(i));
  2128. }
  2129. break;
  2130. case State.OP_PING:
  2131. switch (b) {
  2132. case cc.NL:
  2133. this.dispatcher.push({
  2134. kind: Kind.PING
  2135. });
  2136. this.drop = 0;
  2137. this.state = State.OP_START;
  2138. break;
  2139. }
  2140. break;
  2141. case State.OP_I:
  2142. switch (b) {
  2143. case cc.N:
  2144. case cc.n:
  2145. this.state = State.OP_IN;
  2146. break;
  2147. default:
  2148. throw this.fail(buf.subarray(i));
  2149. }
  2150. break;
  2151. case State.OP_IN:
  2152. switch (b) {
  2153. case cc.F:
  2154. case cc.f:
  2155. this.state = State.OP_INF;
  2156. break;
  2157. default:
  2158. throw this.fail(buf.subarray(i));
  2159. }
  2160. break;
  2161. case State.OP_INF:
  2162. switch (b) {
  2163. case cc.O:
  2164. case cc.o:
  2165. this.state = State.OP_INFO;
  2166. break;
  2167. default:
  2168. throw this.fail(buf.subarray(i));
  2169. }
  2170. break;
  2171. case State.OP_INFO:
  2172. switch (b) {
  2173. case cc.SPACE:
  2174. case cc.TAB:
  2175. this.state = State.OP_INFO_SPC;
  2176. break;
  2177. default:
  2178. throw this.fail(buf.subarray(i));
  2179. }
  2180. break;
  2181. case State.OP_INFO_SPC:
  2182. switch (b) {
  2183. case cc.SPACE:
  2184. case cc.TAB:
  2185. continue;
  2186. default:
  2187. this.state = State.INFO_ARG;
  2188. this.as = i;
  2189. }
  2190. break;
  2191. case State.INFO_ARG:
  2192. switch (b) {
  2193. case cc.CR:
  2194. this.drop = 1;
  2195. break;
  2196. case cc.NL: {
  2197. let arg;
  2198. if (this.argBuf) {
  2199. arg = this.argBuf.bytes();
  2200. this.argBuf = void 0;
  2201. } else {
  2202. arg = buf.subarray(this.as, i - this.drop);
  2203. }
  2204. this.dispatcher.push({
  2205. kind: Kind.INFO,
  2206. data: arg
  2207. });
  2208. this.drop = 0;
  2209. this.as = i + 1;
  2210. this.state = State.OP_START;
  2211. break;
  2212. }
  2213. default:
  2214. if (this.argBuf) {
  2215. this.argBuf.writeByte(b);
  2216. }
  2217. }
  2218. break;
  2219. default:
  2220. throw this.fail(buf.subarray(i));
  2221. }
  2222. }
  2223. if ((this.state === State.MSG_ARG || this.state === State.MINUS_ERR_ARG || this.state === State.INFO_ARG) && !this.argBuf) {
  2224. this.argBuf = new DenoBuffer(buf.subarray(this.as, i - this.drop));
  2225. }
  2226. if (this.state === State.MSG_PAYLOAD && !this.msgBuf) {
  2227. if (!this.argBuf) {
  2228. this.cloneMsgArg();
  2229. }
  2230. this.msgBuf = new DenoBuffer(buf.subarray(this.as));
  2231. }
  2232. }
  2233. cloneMsgArg() {
  2234. const s = this.ma.subject.length;
  2235. const r = this.ma.reply ? this.ma.reply.length : 0;
  2236. const buf = new Uint8Array(s + r);
  2237. buf.set(this.ma.subject);
  2238. if (this.ma.reply) {
  2239. buf.set(this.ma.reply, s);
  2240. }
  2241. this.argBuf = new DenoBuffer(buf);
  2242. this.ma.subject = buf.subarray(0, s);
  2243. if (this.ma.reply) {
  2244. this.ma.reply = buf.subarray(s);
  2245. }
  2246. }
  2247. processMsgArgs(arg) {
  2248. if (this.hdr >= 0) {
  2249. return this.processHeaderMsgArgs(arg);
  2250. }
  2251. const args = [];
  2252. let start = -1;
  2253. for (let i = 0; i < arg.length; i++) {
  2254. const b = arg[i];
  2255. switch (b) {
  2256. case cc.SPACE:
  2257. case cc.TAB:
  2258. case cc.CR:
  2259. case cc.NL:
  2260. if (start >= 0) {
  2261. args.push(arg.subarray(start, i));
  2262. start = -1;
  2263. }
  2264. break;
  2265. default:
  2266. if (start < 0) {
  2267. start = i;
  2268. }
  2269. }
  2270. }
  2271. if (start >= 0) {
  2272. args.push(arg.subarray(start));
  2273. }
  2274. switch (args.length) {
  2275. case 3:
  2276. this.ma.subject = args[0];
  2277. this.ma.sid = this.protoParseInt(args[1]);
  2278. this.ma.reply = void 0;
  2279. this.ma.size = this.protoParseInt(args[2]);
  2280. break;
  2281. case 4:
  2282. this.ma.subject = args[0];
  2283. this.ma.sid = this.protoParseInt(args[1]);
  2284. this.ma.reply = args[2];
  2285. this.ma.size = this.protoParseInt(args[3]);
  2286. break;
  2287. default:
  2288. throw this.fail(arg, "processMsgArgs Parse Error");
  2289. }
  2290. if (this.ma.sid < 0) {
  2291. throw this.fail(arg, "processMsgArgs Bad or Missing Sid Error");
  2292. }
  2293. if (this.ma.size < 0) {
  2294. throw this.fail(arg, "processMsgArgs Bad or Missing Size Error");
  2295. }
  2296. }
  2297. fail(data, label = "") {
  2298. if (!label) {
  2299. label = `parse error [${this.state}]`;
  2300. } else {
  2301. label = `${label} [${this.state}]`;
  2302. }
  2303. return new Error(`${label}: ${TD.decode(data)}`);
  2304. }
  2305. processHeaderMsgArgs(arg) {
  2306. const args = [];
  2307. let start = -1;
  2308. for (let i = 0; i < arg.length; i++) {
  2309. const b = arg[i];
  2310. switch (b) {
  2311. case cc.SPACE:
  2312. case cc.TAB:
  2313. case cc.CR:
  2314. case cc.NL:
  2315. if (start >= 0) {
  2316. args.push(arg.subarray(start, i));
  2317. start = -1;
  2318. }
  2319. break;
  2320. default:
  2321. if (start < 0) {
  2322. start = i;
  2323. }
  2324. }
  2325. }
  2326. if (start >= 0) {
  2327. args.push(arg.subarray(start));
  2328. }
  2329. switch (args.length) {
  2330. case 4:
  2331. this.ma.subject = args[0];
  2332. this.ma.sid = this.protoParseInt(args[1]);
  2333. this.ma.reply = void 0;
  2334. this.ma.hdr = this.protoParseInt(args[2]);
  2335. this.ma.size = this.protoParseInt(args[3]);
  2336. break;
  2337. case 5:
  2338. this.ma.subject = args[0];
  2339. this.ma.sid = this.protoParseInt(args[1]);
  2340. this.ma.reply = args[2];
  2341. this.ma.hdr = this.protoParseInt(args[3]);
  2342. this.ma.size = this.protoParseInt(args[4]);
  2343. break;
  2344. default:
  2345. throw this.fail(arg, "processHeaderMsgArgs Parse Error");
  2346. }
  2347. if (this.ma.sid < 0) {
  2348. throw this.fail(arg, "processHeaderMsgArgs Bad or Missing Sid Error");
  2349. }
  2350. if (this.ma.hdr < 0 || this.ma.hdr > this.ma.size) {
  2351. throw this.fail(arg, "processHeaderMsgArgs Bad or Missing Header Size Error");
  2352. }
  2353. if (this.ma.size < 0) {
  2354. throw this.fail(arg, "processHeaderMsgArgs Bad or Missing Size Error");
  2355. }
  2356. }
  2357. protoParseInt(a) {
  2358. if (a.length === 0) {
  2359. return -1;
  2360. }
  2361. let n = 0;
  2362. for (let i = 0; i < a.length; i++) {
  2363. if (a[i] < 48 || a[i] > 57) {
  2364. return -1;
  2365. }
  2366. n = n * 10 + (a[i] - ASCII_0);
  2367. }
  2368. return n;
  2369. }
  2370. };
  2371. var State;
  2372. (function(State2) {
  2373. State2[State2["OP_START"] = 0] = "OP_START";
  2374. State2[State2["OP_PLUS"] = 1] = "OP_PLUS";
  2375. State2[State2["OP_PLUS_O"] = 2] = "OP_PLUS_O";
  2376. State2[State2["OP_PLUS_OK"] = 3] = "OP_PLUS_OK";
  2377. State2[State2["OP_MINUS"] = 4] = "OP_MINUS";
  2378. State2[State2["OP_MINUS_E"] = 5] = "OP_MINUS_E";
  2379. State2[State2["OP_MINUS_ER"] = 6] = "OP_MINUS_ER";
  2380. State2[State2["OP_MINUS_ERR"] = 7] = "OP_MINUS_ERR";
  2381. State2[State2["OP_MINUS_ERR_SPC"] = 8] = "OP_MINUS_ERR_SPC";
  2382. State2[State2["MINUS_ERR_ARG"] = 9] = "MINUS_ERR_ARG";
  2383. State2[State2["OP_M"] = 10] = "OP_M";
  2384. State2[State2["OP_MS"] = 11] = "OP_MS";
  2385. State2[State2["OP_MSG"] = 12] = "OP_MSG";
  2386. State2[State2["OP_MSG_SPC"] = 13] = "OP_MSG_SPC";
  2387. State2[State2["MSG_ARG"] = 14] = "MSG_ARG";
  2388. State2[State2["MSG_PAYLOAD"] = 15] = "MSG_PAYLOAD";
  2389. State2[State2["MSG_END"] = 16] = "MSG_END";
  2390. State2[State2["OP_H"] = 17] = "OP_H";
  2391. State2[State2["OP_P"] = 18] = "OP_P";
  2392. State2[State2["OP_PI"] = 19] = "OP_PI";
  2393. State2[State2["OP_PIN"] = 20] = "OP_PIN";
  2394. State2[State2["OP_PING"] = 21] = "OP_PING";
  2395. State2[State2["OP_PO"] = 22] = "OP_PO";
  2396. State2[State2["OP_PON"] = 23] = "OP_PON";
  2397. State2[State2["OP_PONG"] = 24] = "OP_PONG";
  2398. State2[State2["OP_I"] = 25] = "OP_I";
  2399. State2[State2["OP_IN"] = 26] = "OP_IN";
  2400. State2[State2["OP_INF"] = 27] = "OP_INF";
  2401. State2[State2["OP_INFO"] = 28] = "OP_INFO";
  2402. State2[State2["OP_INFO_SPC"] = 29] = "OP_INFO_SPC";
  2403. State2[State2["INFO_ARG"] = 30] = "INFO_ARG";
  2404. })(State || (State = {}));
  2405. var cc;
  2406. (function(cc2) {
  2407. cc2[cc2["CR"] = "\r".charCodeAt(0)] = "CR";
  2408. cc2[cc2["E"] = "E".charCodeAt(0)] = "E";
  2409. cc2[cc2["e"] = "e".charCodeAt(0)] = "e";
  2410. cc2[cc2["F"] = "F".charCodeAt(0)] = "F";
  2411. cc2[cc2["f"] = "f".charCodeAt(0)] = "f";
  2412. cc2[cc2["G"] = "G".charCodeAt(0)] = "G";
  2413. cc2[cc2["g"] = "g".charCodeAt(0)] = "g";
  2414. cc2[cc2["H"] = "H".charCodeAt(0)] = "H";
  2415. cc2[cc2["h"] = "h".charCodeAt(0)] = "h";
  2416. cc2[cc2["I"] = "I".charCodeAt(0)] = "I";
  2417. cc2[cc2["i"] = "i".charCodeAt(0)] = "i";
  2418. cc2[cc2["K"] = "K".charCodeAt(0)] = "K";
  2419. cc2[cc2["k"] = "k".charCodeAt(0)] = "k";
  2420. cc2[cc2["M"] = "M".charCodeAt(0)] = "M";
  2421. cc2[cc2["m"] = "m".charCodeAt(0)] = "m";
  2422. cc2[cc2["MINUS"] = "-".charCodeAt(0)] = "MINUS";
  2423. cc2[cc2["N"] = "N".charCodeAt(0)] = "N";
  2424. cc2[cc2["n"] = "n".charCodeAt(0)] = "n";
  2425. cc2[cc2["NL"] = "\n".charCodeAt(0)] = "NL";
  2426. cc2[cc2["O"] = "O".charCodeAt(0)] = "O";
  2427. cc2[cc2["o"] = "o".charCodeAt(0)] = "o";
  2428. cc2[cc2["P"] = "P".charCodeAt(0)] = "P";
  2429. cc2[cc2["p"] = "p".charCodeAt(0)] = "p";
  2430. cc2[cc2["PLUS"] = "+".charCodeAt(0)] = "PLUS";
  2431. cc2[cc2["R"] = "R".charCodeAt(0)] = "R";
  2432. cc2[cc2["r"] = "r".charCodeAt(0)] = "r";
  2433. cc2[cc2["S"] = "S".charCodeAt(0)] = "S";
  2434. cc2[cc2["s"] = "s".charCodeAt(0)] = "s";
  2435. cc2[cc2["SPACE"] = " ".charCodeAt(0)] = "SPACE";
  2436. cc2[cc2["TAB"] = " ".charCodeAt(0)] = "TAB";
  2437. })(cc || (cc = {}));
  2438. function parseSemVer(s = "") {
  2439. const m = s.match(/(\d+).(\d+).(\d+)/);
  2440. if (m) {
  2441. return {
  2442. major: parseInt(m[1]),
  2443. minor: parseInt(m[2]),
  2444. micro: parseInt(m[3])
  2445. };
  2446. }
  2447. throw new Error(`'${s}' is not a semver value`);
  2448. }
  2449. function compare(a, b) {
  2450. if (a.major < b.major)
  2451. return -1;
  2452. if (a.major > b.major)
  2453. return 1;
  2454. if (a.minor < b.minor)
  2455. return -1;
  2456. if (a.minor > b.minor)
  2457. return 1;
  2458. if (a.micro < b.micro)
  2459. return -1;
  2460. if (a.micro > b.micro)
  2461. return 1;
  2462. return 0;
  2463. }
  2464. var Feature;
  2465. (function(Feature2) {
  2466. Feature2["JS_KV"] = "js_kv";
  2467. Feature2["JS_OBJECTSTORE"] = "js_objectstore";
  2468. Feature2["JS_PULL_MAX_BYTES"] = "js_pull_max_bytes";
  2469. Feature2["JS_NEW_CONSUMER_CREATE_API"] = "js_new_consumer_create";
  2470. Feature2["JS_ALLOW_DIRECT"] = "js_allow_direct";
  2471. Feature2["JS_MULTIPLE_CONSUMER_FILTER"] = "js_multiple_consumer_filter";
  2472. Feature2["JS_SIMPLIFICATION"] = "js_simplification";
  2473. Feature2["JS_STREAM_CONSUMER_METADATA"] = "js_stream_consumer_metadata";
  2474. Feature2["JS_CONSUMER_FILTER_SUBJECTS"] = "js_consumer_filter_subjects";
  2475. Feature2["JS_STREAM_FIRST_SEQ"] = "js_stream_first_seq";
  2476. Feature2["JS_STREAM_SUBJECT_TRANSFORM"] = "js_stream_subject_transform";
  2477. Feature2["JS_STREAM_SOURCE_SUBJECT_TRANSFORM"] = "js_stream_source_subject_transform";
  2478. Feature2["JS_STREAM_COMPRESSION"] = "js_stream_compression";
  2479. Feature2["JS_DEFAULT_CONSUMER_LIMITS"] = "js_default_consumer_limits";
  2480. })(Feature || (Feature = {}));
  2481. var Features = class {
  2482. constructor(v) {
  2483. __publicField(this, "server");
  2484. __publicField(this, "features");
  2485. __publicField(this, "disabled");
  2486. this.features = /* @__PURE__ */ new Map();
  2487. this.disabled = [];
  2488. this.update(v);
  2489. }
  2490. resetDisabled() {
  2491. this.disabled.length = 0;
  2492. this.update(this.server);
  2493. }
  2494. disable(f) {
  2495. this.disabled.push(f);
  2496. this.update(this.server);
  2497. }
  2498. isDisabled(f) {
  2499. return this.disabled.indexOf(f) !== -1;
  2500. }
  2501. update(v) {
  2502. if (typeof v === "string") {
  2503. v = parseSemVer(v);
  2504. }
  2505. this.server = v;
  2506. this.set(Feature.JS_KV, "2.6.2");
  2507. this.set(Feature.JS_OBJECTSTORE, "2.6.3");
  2508. this.set(Feature.JS_PULL_MAX_BYTES, "2.8.3");
  2509. this.set(Feature.JS_NEW_CONSUMER_CREATE_API, "2.9.0");
  2510. this.set(Feature.JS_ALLOW_DIRECT, "2.9.0");
  2511. this.set(Feature.JS_MULTIPLE_CONSUMER_FILTER, "2.10.0");
  2512. this.set(Feature.JS_SIMPLIFICATION, "2.9.4");
  2513. this.set(Feature.JS_STREAM_CONSUMER_METADATA, "2.10.0");
  2514. this.set(Feature.JS_CONSUMER_FILTER_SUBJECTS, "2.10.0");
  2515. this.set(Feature.JS_STREAM_FIRST_SEQ, "2.10.0");
  2516. this.set(Feature.JS_STREAM_SUBJECT_TRANSFORM, "2.10.0");
  2517. this.set(Feature.JS_STREAM_SOURCE_SUBJECT_TRANSFORM, "2.10.0");
  2518. this.set(Feature.JS_STREAM_COMPRESSION, "2.10.0");
  2519. this.set(Feature.JS_DEFAULT_CONSUMER_LIMITS, "2.10.0");
  2520. this.disabled.forEach((f) => {
  2521. this.features.delete(f);
  2522. });
  2523. }
  2524. set(f, requires) {
  2525. this.features.set(f, {
  2526. min: requires,
  2527. ok: compare(this.server, parseSemVer(requires)) >= 0
  2528. });
  2529. }
  2530. get(f) {
  2531. return this.features.get(f) || {
  2532. min: "unknown",
  2533. ok: false
  2534. };
  2535. }
  2536. supports(f) {
  2537. var _a;
  2538. return ((_a = this.get(f)) == null ? void 0 : _a.ok) || false;
  2539. }
  2540. require(v) {
  2541. if (typeof v === "string") {
  2542. v = parseSemVer(v);
  2543. }
  2544. return compare(this.server, v) >= 0;
  2545. }
  2546. };
  2547. (function(nacl2) {
  2548. "use strict";
  2549. var u64 = function(h, l) {
  2550. this.hi = h | 0 >>> 0;
  2551. this.lo = l | 0 >>> 0;
  2552. };
  2553. var gf = function(init2) {
  2554. var i, r = new Float64Array(16);
  2555. if (init2)
  2556. for (i = 0; i < init2.length; i++)
  2557. r[i] = init2[i];
  2558. return r;
  2559. };
  2560. var randombytes = function() {
  2561. throw new Error("no PRNG");
  2562. };
  2563. var _0 = new Uint8Array(16);
  2564. var _9 = new Uint8Array(32);
  2565. _9[0] = 9;
  2566. var gf0 = gf(), gf1 = gf([
  2567. 1
  2568. ]), _121665 = gf([
  2569. 56129,
  2570. 1
  2571. ]), D = gf([
  2572. 30883,
  2573. 4953,
  2574. 19914,
  2575. 30187,
  2576. 55467,
  2577. 16705,
  2578. 2637,
  2579. 112,
  2580. 59544,
  2581. 30585,
  2582. 16505,
  2583. 36039,
  2584. 65139,
  2585. 11119,
  2586. 27886,
  2587. 20995
  2588. ]), D2 = gf([
  2589. 61785,
  2590. 9906,
  2591. 39828,
  2592. 60374,
  2593. 45398,
  2594. 33411,
  2595. 5274,
  2596. 224,
  2597. 53552,
  2598. 61171,
  2599. 33010,
  2600. 6542,
  2601. 64743,
  2602. 22239,
  2603. 55772,
  2604. 9222
  2605. ]), X = gf([
  2606. 54554,
  2607. 36645,
  2608. 11616,
  2609. 51542,
  2610. 42930,
  2611. 38181,
  2612. 51040,
  2613. 26924,
  2614. 56412,
  2615. 64982,
  2616. 57905,
  2617. 49316,
  2618. 21502,
  2619. 52590,
  2620. 14035,
  2621. 8553
  2622. ]), Y = gf([
  2623. 26200,
  2624. 26214,
  2625. 26214,
  2626. 26214,
  2627. 26214,
  2628. 26214,
  2629. 26214,
  2630. 26214,
  2631. 26214,
  2632. 26214,
  2633. 26214,
  2634. 26214,
  2635. 26214,
  2636. 26214,
  2637. 26214,
  2638. 26214
  2639. ]), I = gf([
  2640. 41136,
  2641. 18958,
  2642. 6951,
  2643. 50414,
  2644. 58488,
  2645. 44335,
  2646. 6150,
  2647. 12099,
  2648. 55207,
  2649. 15867,
  2650. 153,
  2651. 11085,
  2652. 57099,
  2653. 20417,
  2654. 9344,
  2655. 11139
  2656. ]);
  2657. function L32(x, c) {
  2658. return x << c | x >>> 32 - c;
  2659. }
  2660. function ld32(x, i) {
  2661. var u = x[i + 3] & 255;
  2662. u = u << 8 | x[i + 2] & 255;
  2663. u = u << 8 | x[i + 1] & 255;
  2664. return u << 8 | x[i + 0] & 255;
  2665. }
  2666. function dl64(x, i) {
  2667. var h = x[i] << 24 | x[i + 1] << 16 | x[i + 2] << 8 | x[i + 3];
  2668. var l = x[i + 4] << 24 | x[i + 5] << 16 | x[i + 6] << 8 | x[i + 7];
  2669. return new u64(h, l);
  2670. }
  2671. function st32(x, j, u) {
  2672. var i;
  2673. for (i = 0; i < 4; i++) {
  2674. x[j + i] = u & 255;
  2675. u >>>= 8;
  2676. }
  2677. }
  2678. function ts64(x, i, u) {
  2679. x[i] = u.hi >> 24 & 255;
  2680. x[i + 1] = u.hi >> 16 & 255;
  2681. x[i + 2] = u.hi >> 8 & 255;
  2682. x[i + 3] = u.hi & 255;
  2683. x[i + 4] = u.lo >> 24 & 255;
  2684. x[i + 5] = u.lo >> 16 & 255;
  2685. x[i + 6] = u.lo >> 8 & 255;
  2686. x[i + 7] = u.lo & 255;
  2687. }
  2688. function vn(x, xi, y, yi, n) {
  2689. var i, d = 0;
  2690. for (i = 0; i < n; i++)
  2691. d |= x[xi + i] ^ y[yi + i];
  2692. return (1 & d - 1 >>> 8) - 1;
  2693. }
  2694. function crypto_verify_16(x, xi, y, yi) {
  2695. return vn(x, xi, y, yi, 16);
  2696. }
  2697. function crypto_verify_32(x, xi, y, yi) {
  2698. return vn(x, xi, y, yi, 32);
  2699. }
  2700. function core(out, inp, k, c, h) {
  2701. var w = new Uint32Array(16), x = new Uint32Array(16), y = new Uint32Array(16), t = new Uint32Array(4);
  2702. var i, j, m;
  2703. for (i = 0; i < 4; i++) {
  2704. x[5 * i] = ld32(c, 4 * i);
  2705. x[1 + i] = ld32(k, 4 * i);
  2706. x[6 + i] = ld32(inp, 4 * i);
  2707. x[11 + i] = ld32(k, 16 + 4 * i);
  2708. }
  2709. for (i = 0; i < 16; i++)
  2710. y[i] = x[i];
  2711. for (i = 0; i < 20; i++) {
  2712. for (j = 0; j < 4; j++) {
  2713. for (m = 0; m < 4; m++)
  2714. t[m] = x[(5 * j + 4 * m) % 16];
  2715. t[1] ^= L32(t[0] + t[3] | 0, 7);
  2716. t[2] ^= L32(t[1] + t[0] | 0, 9);
  2717. t[3] ^= L32(t[2] + t[1] | 0, 13);
  2718. t[0] ^= L32(t[3] + t[2] | 0, 18);
  2719. for (m = 0; m < 4; m++)
  2720. w[4 * j + (j + m) % 4] = t[m];
  2721. }
  2722. for (m = 0; m < 16; m++)
  2723. x[m] = w[m];
  2724. }
  2725. if (h) {
  2726. for (i = 0; i < 16; i++)
  2727. x[i] = x[i] + y[i] | 0;
  2728. for (i = 0; i < 4; i++) {
  2729. x[5 * i] = x[5 * i] - ld32(c, 4 * i) | 0;
  2730. x[6 + i] = x[6 + i] - ld32(inp, 4 * i) | 0;
  2731. }
  2732. for (i = 0; i < 4; i++) {
  2733. st32(out, 4 * i, x[5 * i]);
  2734. st32(out, 16 + 4 * i, x[6 + i]);
  2735. }
  2736. } else {
  2737. for (i = 0; i < 16; i++)
  2738. st32(out, 4 * i, x[i] + y[i] | 0);
  2739. }
  2740. }
  2741. function crypto_core_salsa20(out, inp, k, c) {
  2742. core(out, inp, k, c, false);
  2743. return 0;
  2744. }
  2745. function crypto_core_hsalsa20(out, inp, k, c) {
  2746. core(out, inp, k, c, true);
  2747. return 0;
  2748. }
  2749. var sigma = new Uint8Array([
  2750. 101,
  2751. 120,
  2752. 112,
  2753. 97,
  2754. 110,
  2755. 100,
  2756. 32,
  2757. 51,
  2758. 50,
  2759. 45,
  2760. 98,
  2761. 121,
  2762. 116,
  2763. 101,
  2764. 32,
  2765. 107
  2766. ]);
  2767. function crypto_stream_salsa20_xor(c, cpos, m, mpos, b, n, k) {
  2768. var z = new Uint8Array(16), x = new Uint8Array(64);
  2769. var u, i;
  2770. if (!b)
  2771. return 0;
  2772. for (i = 0; i < 16; i++)
  2773. z[i] = 0;
  2774. for (i = 0; i < 8; i++)
  2775. z[i] = n[i];
  2776. while (b >= 64) {
  2777. crypto_core_salsa20(x, z, k, sigma);
  2778. for (i = 0; i < 64; i++)
  2779. c[cpos + i] = (m ? m[mpos + i] : 0) ^ x[i];
  2780. u = 1;
  2781. for (i = 8; i < 16; i++) {
  2782. u = u + (z[i] & 255) | 0;
  2783. z[i] = u & 255;
  2784. u >>>= 8;
  2785. }
  2786. b -= 64;
  2787. cpos += 64;
  2788. if (m)
  2789. mpos += 64;
  2790. }
  2791. if (b > 0) {
  2792. crypto_core_salsa20(x, z, k, sigma);
  2793. for (i = 0; i < b; i++)
  2794. c[cpos + i] = (m ? m[mpos + i] : 0) ^ x[i];
  2795. }
  2796. return 0;
  2797. }
  2798. function crypto_stream_salsa20(c, cpos, d, n, k) {
  2799. return crypto_stream_salsa20_xor(c, cpos, null, 0, d, n, k);
  2800. }
  2801. function crypto_stream(c, cpos, d, n, k) {
  2802. var s = new Uint8Array(32);
  2803. crypto_core_hsalsa20(s, n, k, sigma);
  2804. return crypto_stream_salsa20(c, cpos, d, n.subarray(16), s);
  2805. }
  2806. function crypto_stream_xor(c, cpos, m, mpos, d, n, k) {
  2807. var s = new Uint8Array(32);
  2808. crypto_core_hsalsa20(s, n, k, sigma);
  2809. return crypto_stream_salsa20_xor(c, cpos, m, mpos, d, n.subarray(16), s);
  2810. }
  2811. function add1305(h, c) {
  2812. var j, u = 0;
  2813. for (j = 0; j < 17; j++) {
  2814. u = u + (h[j] + c[j] | 0) | 0;
  2815. h[j] = u & 255;
  2816. u >>>= 8;
  2817. }
  2818. }
  2819. var minusp = new Uint32Array([
  2820. 5,
  2821. 0,
  2822. 0,
  2823. 0,
  2824. 0,
  2825. 0,
  2826. 0,
  2827. 0,
  2828. 0,
  2829. 0,
  2830. 0,
  2831. 0,
  2832. 0,
  2833. 0,
  2834. 0,
  2835. 0,
  2836. 252
  2837. ]);
  2838. function crypto_onetimeauth(out, outpos, m, mpos, n, k) {
  2839. var s, i, j, u;
  2840. var x = new Uint32Array(17), r = new Uint32Array(17), h = new Uint32Array(17), c = new Uint32Array(17), g = new Uint32Array(17);
  2841. for (j = 0; j < 17; j++)
  2842. r[j] = h[j] = 0;
  2843. for (j = 0; j < 16; j++)
  2844. r[j] = k[j];
  2845. r[3] &= 15;
  2846. r[4] &= 252;
  2847. r[7] &= 15;
  2848. r[8] &= 252;
  2849. r[11] &= 15;
  2850. r[12] &= 252;
  2851. r[15] &= 15;
  2852. while (n > 0) {
  2853. for (j = 0; j < 17; j++)
  2854. c[j] = 0;
  2855. for (j = 0; j < 16 && j < n; ++j)
  2856. c[j] = m[mpos + j];
  2857. c[j] = 1;
  2858. mpos += j;
  2859. n -= j;
  2860. add1305(h, c);
  2861. for (i = 0; i < 17; i++) {
  2862. x[i] = 0;
  2863. for (j = 0; j < 17; j++)
  2864. x[i] = x[i] + h[j] * (j <= i ? r[i - j] : 320 * r[i + 17 - j] | 0) | 0 | 0;
  2865. }
  2866. for (i = 0; i < 17; i++)
  2867. h[i] = x[i];
  2868. u = 0;
  2869. for (j = 0; j < 16; j++) {
  2870. u = u + h[j] | 0;
  2871. h[j] = u & 255;
  2872. u >>>= 8;
  2873. }
  2874. u = u + h[16] | 0;
  2875. h[16] = u & 3;
  2876. u = 5 * (u >>> 2) | 0;
  2877. for (j = 0; j < 16; j++) {
  2878. u = u + h[j] | 0;
  2879. h[j] = u & 255;
  2880. u >>>= 8;
  2881. }
  2882. u = u + h[16] | 0;
  2883. h[16] = u;
  2884. }
  2885. for (j = 0; j < 17; j++)
  2886. g[j] = h[j];
  2887. add1305(h, minusp);
  2888. s = -(h[16] >>> 7) | 0;
  2889. for (j = 0; j < 17; j++)
  2890. h[j] ^= s & (g[j] ^ h[j]);
  2891. for (j = 0; j < 16; j++)
  2892. c[j] = k[j + 16];
  2893. c[16] = 0;
  2894. add1305(h, c);
  2895. for (j = 0; j < 16; j++)
  2896. out[outpos + j] = h[j];
  2897. return 0;
  2898. }
  2899. function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) {
  2900. var x = new Uint8Array(16);
  2901. crypto_onetimeauth(x, 0, m, mpos, n, k);
  2902. return crypto_verify_16(h, hpos, x, 0);
  2903. }
  2904. function crypto_secretbox(c, m, d, n, k) {
  2905. var i;
  2906. if (d < 32)
  2907. return -1;
  2908. crypto_stream_xor(c, 0, m, 0, d, n, k);
  2909. crypto_onetimeauth(c, 16, c, 32, d - 32, c);
  2910. for (i = 0; i < 16; i++)
  2911. c[i] = 0;
  2912. return 0;
  2913. }
  2914. function crypto_secretbox_open(m, c, d, n, k) {
  2915. var i;
  2916. var x = new Uint8Array(32);
  2917. if (d < 32)
  2918. return -1;
  2919. crypto_stream(x, 0, 32, n, k);
  2920. if (crypto_onetimeauth_verify(c, 16, c, 32, d - 32, x) !== 0)
  2921. return -1;
  2922. crypto_stream_xor(m, 0, c, 0, d, n, k);
  2923. for (i = 0; i < 32; i++)
  2924. m[i] = 0;
  2925. return 0;
  2926. }
  2927. function set25519(r, a) {
  2928. var i;
  2929. for (i = 0; i < 16; i++)
  2930. r[i] = a[i] | 0;
  2931. }
  2932. function car25519(o) {
  2933. var c;
  2934. var i;
  2935. for (i = 0; i < 16; i++) {
  2936. o[i] += 65536;
  2937. c = Math.floor(o[i] / 65536);
  2938. o[(i + 1) * (i < 15 ? 1 : 0)] += c - 1 + 37 * (c - 1) * (i === 15 ? 1 : 0);
  2939. o[i] -= c * 65536;
  2940. }
  2941. }
  2942. function sel25519(p, q, b) {
  2943. var t, c = ~(b - 1);
  2944. for (var i = 0; i < 16; i++) {
  2945. t = c & (p[i] ^ q[i]);
  2946. p[i] ^= t;
  2947. q[i] ^= t;
  2948. }
  2949. }
  2950. function pack25519(o, n) {
  2951. var i, j, b;
  2952. var m = gf(), t = gf();
  2953. for (i = 0; i < 16; i++)
  2954. t[i] = n[i];
  2955. car25519(t);
  2956. car25519(t);
  2957. car25519(t);
  2958. for (j = 0; j < 2; j++) {
  2959. m[0] = t[0] - 65517;
  2960. for (i = 1; i < 15; i++) {
  2961. m[i] = t[i] - 65535 - (m[i - 1] >> 16 & 1);
  2962. m[i - 1] &= 65535;
  2963. }
  2964. m[15] = t[15] - 32767 - (m[14] >> 16 & 1);
  2965. b = m[15] >> 16 & 1;
  2966. m[14] &= 65535;
  2967. sel25519(t, m, 1 - b);
  2968. }
  2969. for (i = 0; i < 16; i++) {
  2970. o[2 * i] = t[i] & 255;
  2971. o[2 * i + 1] = t[i] >> 8;
  2972. }
  2973. }
  2974. function neq25519(a, b) {
  2975. var c = new Uint8Array(32), d = new Uint8Array(32);
  2976. pack25519(c, a);
  2977. pack25519(d, b);
  2978. return crypto_verify_32(c, 0, d, 0);
  2979. }
  2980. function par25519(a) {
  2981. var d = new Uint8Array(32);
  2982. pack25519(d, a);
  2983. return d[0] & 1;
  2984. }
  2985. function unpack25519(o, n) {
  2986. var i;
  2987. for (i = 0; i < 16; i++)
  2988. o[i] = n[2 * i] + (n[2 * i + 1] << 8);
  2989. o[15] &= 32767;
  2990. }
  2991. function A(o, a, b) {
  2992. var i;
  2993. for (i = 0; i < 16; i++)
  2994. o[i] = a[i] + b[i] | 0;
  2995. }
  2996. function Z(o, a, b) {
  2997. var i;
  2998. for (i = 0; i < 16; i++)
  2999. o[i] = a[i] - b[i] | 0;
  3000. }
  3001. function M(o, a, b) {
  3002. var i, j, t = new Float64Array(31);
  3003. for (i = 0; i < 31; i++)
  3004. t[i] = 0;
  3005. for (i = 0; i < 16; i++) {
  3006. for (j = 0; j < 16; j++) {
  3007. t[i + j] += a[i] * b[j];
  3008. }
  3009. }
  3010. for (i = 0; i < 15; i++) {
  3011. t[i] += 38 * t[i + 16];
  3012. }
  3013. for (i = 0; i < 16; i++)
  3014. o[i] = t[i];
  3015. car25519(o);
  3016. car25519(o);
  3017. }
  3018. function S(o, a) {
  3019. M(o, a, a);
  3020. }
  3021. function inv25519(o, i) {
  3022. var c = gf();
  3023. var a;
  3024. for (a = 0; a < 16; a++)
  3025. c[a] = i[a];
  3026. for (a = 253; a >= 0; a--) {
  3027. S(c, c);
  3028. if (a !== 2 && a !== 4)
  3029. M(c, c, i);
  3030. }
  3031. for (a = 0; a < 16; a++)
  3032. o[a] = c[a];
  3033. }
  3034. function pow2523(o, i) {
  3035. var c = gf();
  3036. var a;
  3037. for (a = 0; a < 16; a++)
  3038. c[a] = i[a];
  3039. for (a = 250; a >= 0; a--) {
  3040. S(c, c);
  3041. if (a !== 1)
  3042. M(c, c, i);
  3043. }
  3044. for (a = 0; a < 16; a++)
  3045. o[a] = c[a];
  3046. }
  3047. function crypto_scalarmult(q, n, p) {
  3048. var z = new Uint8Array(32);
  3049. var x = new Float64Array(80), r, i;
  3050. var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf();
  3051. for (i = 0; i < 31; i++)
  3052. z[i] = n[i];
  3053. z[31] = n[31] & 127 | 64;
  3054. z[0] &= 248;
  3055. unpack25519(x, p);
  3056. for (i = 0; i < 16; i++) {
  3057. b[i] = x[i];
  3058. d[i] = a[i] = c[i] = 0;
  3059. }
  3060. a[0] = d[0] = 1;
  3061. for (i = 254; i >= 0; --i) {
  3062. r = z[i >>> 3] >>> (i & 7) & 1;
  3063. sel25519(a, b, r);
  3064. sel25519(c, d, r);
  3065. A(e, a, c);
  3066. Z(a, a, c);
  3067. A(c, b, d);
  3068. Z(b, b, d);
  3069. S(d, e);
  3070. S(f, a);
  3071. M(a, c, a);
  3072. M(c, b, e);
  3073. A(e, a, c);
  3074. Z(a, a, c);
  3075. S(b, a);
  3076. Z(c, d, f);
  3077. M(a, c, _121665);
  3078. A(a, a, d);
  3079. M(c, c, a);
  3080. M(a, d, f);
  3081. M(d, b, x);
  3082. S(b, e);
  3083. sel25519(a, b, r);
  3084. sel25519(c, d, r);
  3085. }
  3086. for (i = 0; i < 16; i++) {
  3087. x[i + 16] = a[i];
  3088. x[i + 32] = c[i];
  3089. x[i + 48] = b[i];
  3090. x[i + 64] = d[i];
  3091. }
  3092. var x32 = x.subarray(32);
  3093. var x16 = x.subarray(16);
  3094. inv25519(x32, x32);
  3095. M(x16, x16, x32);
  3096. pack25519(q, x16);
  3097. return 0;
  3098. }
  3099. function crypto_scalarmult_base(q, n) {
  3100. return crypto_scalarmult(q, n, _9);
  3101. }
  3102. function crypto_box_keypair(y, x) {
  3103. randombytes(x, 32);
  3104. return crypto_scalarmult_base(y, x);
  3105. }
  3106. function crypto_box_beforenm(k, y, x) {
  3107. var s = new Uint8Array(32);
  3108. crypto_scalarmult(s, x, y);
  3109. return crypto_core_hsalsa20(k, _0, s, sigma);
  3110. }
  3111. var crypto_box_afternm = crypto_secretbox;
  3112. var crypto_box_open_afternm = crypto_secretbox_open;
  3113. function crypto_box(c, m, d, n, y, x) {
  3114. var k = new Uint8Array(32);
  3115. crypto_box_beforenm(k, y, x);
  3116. return crypto_box_afternm(c, m, d, n, k);
  3117. }
  3118. function crypto_box_open(m, c, d, n, y, x) {
  3119. var k = new Uint8Array(32);
  3120. crypto_box_beforenm(k, y, x);
  3121. return crypto_box_open_afternm(m, c, d, n, k);
  3122. }
  3123. function add64() {
  3124. var a = 0, b = 0, c = 0, d = 0, m16 = 65535, l, h, i;
  3125. for (i = 0; i < arguments.length; i++) {
  3126. l = arguments[i].lo;
  3127. h = arguments[i].hi;
  3128. a += l & m16;
  3129. b += l >>> 16;
  3130. c += h & m16;
  3131. d += h >>> 16;
  3132. }
  3133. b += a >>> 16;
  3134. c += b >>> 16;
  3135. d += c >>> 16;
  3136. return new u64(c & m16 | d << 16, a & m16 | b << 16);
  3137. }
  3138. function shr64(x, c) {
  3139. return new u64(x.hi >>> c, x.lo >>> c | x.hi << 32 - c);
  3140. }
  3141. function xor64() {
  3142. var l = 0, h = 0, i;
  3143. for (i = 0; i < arguments.length; i++) {
  3144. l ^= arguments[i].lo;
  3145. h ^= arguments[i].hi;
  3146. }
  3147. return new u64(h, l);
  3148. }
  3149. function R(x, c) {
  3150. var h, l, c1 = 32 - c;
  3151. if (c < 32) {
  3152. h = x.hi >>> c | x.lo << c1;
  3153. l = x.lo >>> c | x.hi << c1;
  3154. } else if (c < 64) {
  3155. h = x.lo >>> c | x.hi << c1;
  3156. l = x.hi >>> c | x.lo << c1;
  3157. }
  3158. return new u64(h, l);
  3159. }
  3160. function Ch(x, y, z) {
  3161. var h = x.hi & y.hi ^ ~x.hi & z.hi, l = x.lo & y.lo ^ ~x.lo & z.lo;
  3162. return new u64(h, l);
  3163. }
  3164. function Maj(x, y, z) {
  3165. var h = x.hi & y.hi ^ x.hi & z.hi ^ y.hi & z.hi, l = x.lo & y.lo ^ x.lo & z.lo ^ y.lo & z.lo;
  3166. return new u64(h, l);
  3167. }
  3168. function Sigma0(x) {
  3169. return xor64(R(x, 28), R(x, 34), R(x, 39));
  3170. }
  3171. function Sigma1(x) {
  3172. return xor64(R(x, 14), R(x, 18), R(x, 41));
  3173. }
  3174. function sigma0(x) {
  3175. return xor64(R(x, 1), R(x, 8), shr64(x, 7));
  3176. }
  3177. function sigma1(x) {
  3178. return xor64(R(x, 19), R(x, 61), shr64(x, 6));
  3179. }
  3180. var K = [
  3181. new u64(1116352408, 3609767458),
  3182. new u64(1899447441, 602891725),
  3183. new u64(3049323471, 3964484399),
  3184. new u64(3921009573, 2173295548),
  3185. new u64(961987163, 4081628472),
  3186. new u64(1508970993, 3053834265),
  3187. new u64(2453635748, 2937671579),
  3188. new u64(2870763221, 3664609560),
  3189. new u64(3624381080, 2734883394),
  3190. new u64(310598401, 1164996542),
  3191. new u64(607225278, 1323610764),
  3192. new u64(1426881987, 3590304994),
  3193. new u64(1925078388, 4068182383),
  3194. new u64(2162078206, 991336113),
  3195. new u64(2614888103, 633803317),
  3196. new u64(3248222580, 3479774868),
  3197. new u64(3835390401, 2666613458),
  3198. new u64(4022224774, 944711139),
  3199. new u64(264347078, 2341262773),
  3200. new u64(604807628, 2007800933),
  3201. new u64(770255983, 1495990901),
  3202. new u64(1249150122, 1856431235),
  3203. new u64(1555081692, 3175218132),
  3204. new u64(1996064986, 2198950837),
  3205. new u64(2554220882, 3999719339),
  3206. new u64(2821834349, 766784016),
  3207. new u64(2952996808, 2566594879),
  3208. new u64(3210313671, 3203337956),
  3209. new u64(3336571891, 1034457026),
  3210. new u64(3584528711, 2466948901),
  3211. new u64(113926993, 3758326383),
  3212. new u64(338241895, 168717936),
  3213. new u64(666307205, 1188179964),
  3214. new u64(773529912, 1546045734),
  3215. new u64(1294757372, 1522805485),
  3216. new u64(1396182291, 2643833823),
  3217. new u64(1695183700, 2343527390),
  3218. new u64(1986661051, 1014477480),
  3219. new u64(2177026350, 1206759142),
  3220. new u64(2456956037, 344077627),
  3221. new u64(2730485921, 1290863460),
  3222. new u64(2820302411, 3158454273),
  3223. new u64(3259730800, 3505952657),
  3224. new u64(3345764771, 106217008),
  3225. new u64(3516065817, 3606008344),
  3226. new u64(3600352804, 1432725776),
  3227. new u64(4094571909, 1467031594),
  3228. new u64(275423344, 851169720),
  3229. new u64(430227734, 3100823752),
  3230. new u64(506948616, 1363258195),
  3231. new u64(659060556, 3750685593),
  3232. new u64(883997877, 3785050280),
  3233. new u64(958139571, 3318307427),
  3234. new u64(1322822218, 3812723403),
  3235. new u64(1537002063, 2003034995),
  3236. new u64(1747873779, 3602036899),
  3237. new u64(1955562222, 1575990012),
  3238. new u64(2024104815, 1125592928),
  3239. new u64(2227730452, 2716904306),
  3240. new u64(2361852424, 442776044),
  3241. new u64(2428436474, 593698344),
  3242. new u64(2756734187, 3733110249),
  3243. new u64(3204031479, 2999351573),
  3244. new u64(3329325298, 3815920427),
  3245. new u64(3391569614, 3928383900),
  3246. new u64(3515267271, 566280711),
  3247. new u64(3940187606, 3454069534),
  3248. new u64(4118630271, 4000239992),
  3249. new u64(116418474, 1914138554),
  3250. new u64(174292421, 2731055270),
  3251. new u64(289380356, 3203993006),
  3252. new u64(460393269, 320620315),
  3253. new u64(685471733, 587496836),
  3254. new u64(852142971, 1086792851),
  3255. new u64(1017036298, 365543100),
  3256. new u64(1126000580, 2618297676),
  3257. new u64(1288033470, 3409855158),
  3258. new u64(1501505948, 4234509866),
  3259. new u64(1607167915, 987167468),
  3260. new u64(1816402316, 1246189591)
  3261. ];
  3262. function crypto_hashblocks(x, m, n) {
  3263. var z = [], b = [], a = [], w = [], t, i, j;
  3264. for (i = 0; i < 8; i++)
  3265. z[i] = a[i] = dl64(x, 8 * i);
  3266. var pos = 0;
  3267. while (n >= 128) {
  3268. for (i = 0; i < 16; i++)
  3269. w[i] = dl64(m, 8 * i + pos);
  3270. for (i = 0; i < 80; i++) {
  3271. for (j = 0; j < 8; j++)
  3272. b[j] = a[j];
  3273. t = add64(a[7], Sigma1(a[4]), Ch(a[4], a[5], a[6]), K[i], w[i % 16]);
  3274. b[7] = add64(t, Sigma0(a[0]), Maj(a[0], a[1], a[2]));
  3275. b[3] = add64(b[3], t);
  3276. for (j = 0; j < 8; j++)
  3277. a[(j + 1) % 8] = b[j];
  3278. if (i % 16 === 15) {
  3279. for (j = 0; j < 16; j++) {
  3280. w[j] = add64(w[j], w[(j + 9) % 16], sigma0(w[(j + 1) % 16]), sigma1(w[(j + 14) % 16]));
  3281. }
  3282. }
  3283. }
  3284. for (i = 0; i < 8; i++) {
  3285. a[i] = add64(a[i], z[i]);
  3286. z[i] = a[i];
  3287. }
  3288. pos += 128;
  3289. n -= 128;
  3290. }
  3291. for (i = 0; i < 8; i++)
  3292. ts64(x, 8 * i, z[i]);
  3293. return n;
  3294. }
  3295. var iv = new Uint8Array([
  3296. 106,
  3297. 9,
  3298. 230,
  3299. 103,
  3300. 243,
  3301. 188,
  3302. 201,
  3303. 8,
  3304. 187,
  3305. 103,
  3306. 174,
  3307. 133,
  3308. 132,
  3309. 202,
  3310. 167,
  3311. 59,
  3312. 60,
  3313. 110,
  3314. 243,
  3315. 114,
  3316. 254,
  3317. 148,
  3318. 248,
  3319. 43,
  3320. 165,
  3321. 79,
  3322. 245,
  3323. 58,
  3324. 95,
  3325. 29,
  3326. 54,
  3327. 241,
  3328. 81,
  3329. 14,
  3330. 82,
  3331. 127,
  3332. 173,
  3333. 230,
  3334. 130,
  3335. 209,
  3336. 155,
  3337. 5,
  3338. 104,
  3339. 140,
  3340. 43,
  3341. 62,
  3342. 108,
  3343. 31,
  3344. 31,
  3345. 131,
  3346. 217,
  3347. 171,
  3348. 251,
  3349. 65,
  3350. 189,
  3351. 107,
  3352. 91,
  3353. 224,
  3354. 205,
  3355. 25,
  3356. 19,
  3357. 126,
  3358. 33,
  3359. 121
  3360. ]);
  3361. function crypto_hash(out, m, n) {
  3362. var h = new Uint8Array(64), x = new Uint8Array(256);
  3363. var i, b = n;
  3364. for (i = 0; i < 64; i++)
  3365. h[i] = iv[i];
  3366. crypto_hashblocks(h, m, n);
  3367. n %= 128;
  3368. for (i = 0; i < 256; i++)
  3369. x[i] = 0;
  3370. for (i = 0; i < n; i++)
  3371. x[i] = m[b - n + i];
  3372. x[n] = 128;
  3373. n = 256 - 128 * (n < 112 ? 1 : 0);
  3374. x[n - 9] = 0;
  3375. ts64(x, n - 8, new u64(b / 536870912 | 0, b << 3));
  3376. crypto_hashblocks(h, x, n);
  3377. for (i = 0; i < 64; i++)
  3378. out[i] = h[i];
  3379. return 0;
  3380. }
  3381. function add(p, q) {
  3382. var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(), g = gf(), h = gf(), t = gf();
  3383. Z(a, p[1], p[0]);
  3384. Z(t, q[1], q[0]);
  3385. M(a, a, t);
  3386. A(b, p[0], p[1]);
  3387. A(t, q[0], q[1]);
  3388. M(b, b, t);
  3389. M(c, p[3], q[3]);
  3390. M(c, c, D2);
  3391. M(d, p[2], q[2]);
  3392. A(d, d, d);
  3393. Z(e, b, a);
  3394. Z(f, d, c);
  3395. A(g, d, c);
  3396. A(h, b, a);
  3397. M(p[0], e, f);
  3398. M(p[1], h, g);
  3399. M(p[2], g, f);
  3400. M(p[3], e, h);
  3401. }
  3402. function cswap(p, q, b) {
  3403. var i;
  3404. for (i = 0; i < 4; i++) {
  3405. sel25519(p[i], q[i], b);
  3406. }
  3407. }
  3408. function pack(r, p) {
  3409. var tx = gf(), ty = gf(), zi = gf();
  3410. inv25519(zi, p[2]);
  3411. M(tx, p[0], zi);
  3412. M(ty, p[1], zi);
  3413. pack25519(r, ty);
  3414. r[31] ^= par25519(tx) << 7;
  3415. }
  3416. function scalarmult(p, q, s) {
  3417. var b, i;
  3418. set25519(p[0], gf0);
  3419. set25519(p[1], gf1);
  3420. set25519(p[2], gf1);
  3421. set25519(p[3], gf0);
  3422. for (i = 255; i >= 0; --i) {
  3423. b = s[i / 8 | 0] >> (i & 7) & 1;
  3424. cswap(p, q, b);
  3425. add(q, p);
  3426. add(p, p);
  3427. cswap(p, q, b);
  3428. }
  3429. }
  3430. function scalarbase(p, s) {
  3431. var q = [
  3432. gf(),
  3433. gf(),
  3434. gf(),
  3435. gf()
  3436. ];
  3437. set25519(q[0], X);
  3438. set25519(q[1], Y);
  3439. set25519(q[2], gf1);
  3440. M(q[3], X, Y);
  3441. scalarmult(p, q, s);
  3442. }
  3443. function crypto_sign_keypair(pk, sk, seeded) {
  3444. var d = new Uint8Array(64);
  3445. var p = [
  3446. gf(),
  3447. gf(),
  3448. gf(),
  3449. gf()
  3450. ];
  3451. var i;
  3452. if (!seeded)
  3453. randombytes(sk, 32);
  3454. crypto_hash(d, sk, 32);
  3455. d[0] &= 248;
  3456. d[31] &= 127;
  3457. d[31] |= 64;
  3458. scalarbase(p, d);
  3459. pack(pk, p);
  3460. for (i = 0; i < 32; i++)
  3461. sk[i + 32] = pk[i];
  3462. return 0;
  3463. }
  3464. var L = new Float64Array([
  3465. 237,
  3466. 211,
  3467. 245,
  3468. 92,
  3469. 26,
  3470. 99,
  3471. 18,
  3472. 88,
  3473. 214,
  3474. 156,
  3475. 247,
  3476. 162,
  3477. 222,
  3478. 249,
  3479. 222,
  3480. 20,
  3481. 0,
  3482. 0,
  3483. 0,
  3484. 0,
  3485. 0,
  3486. 0,
  3487. 0,
  3488. 0,
  3489. 0,
  3490. 0,
  3491. 0,
  3492. 0,
  3493. 0,
  3494. 0,
  3495. 0,
  3496. 16
  3497. ]);
  3498. function modL(r, x) {
  3499. var carry, i, j, k;
  3500. for (i = 63; i >= 32; --i) {
  3501. carry = 0;
  3502. for (j = i - 32, k = i - 12; j < k; ++j) {
  3503. x[j] += carry - 16 * x[i] * L[j - (i - 32)];
  3504. carry = Math.floor((x[j] + 128) / 256);
  3505. x[j] -= carry * 256;
  3506. }
  3507. x[j] += carry;
  3508. x[i] = 0;
  3509. }
  3510. carry = 0;
  3511. for (j = 0; j < 32; j++) {
  3512. x[j] += carry - (x[31] >> 4) * L[j];
  3513. carry = x[j] >> 8;
  3514. x[j] &= 255;
  3515. }
  3516. for (j = 0; j < 32; j++)
  3517. x[j] -= carry * L[j];
  3518. for (i = 0; i < 32; i++) {
  3519. x[i + 1] += x[i] >> 8;
  3520. r[i] = x[i] & 255;
  3521. }
  3522. }
  3523. function reduce(r) {
  3524. var x = new Float64Array(64), i;
  3525. for (i = 0; i < 64; i++)
  3526. x[i] = r[i];
  3527. for (i = 0; i < 64; i++)
  3528. r[i] = 0;
  3529. modL(r, x);
  3530. }
  3531. function crypto_sign(sm, m, n, sk) {
  3532. var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64);
  3533. var i, j, x = new Float64Array(64);
  3534. var p = [
  3535. gf(),
  3536. gf(),
  3537. gf(),
  3538. gf()
  3539. ];
  3540. crypto_hash(d, sk, 32);
  3541. d[0] &= 248;
  3542. d[31] &= 127;
  3543. d[31] |= 64;
  3544. var smlen = n + 64;
  3545. for (i = 0; i < n; i++)
  3546. sm[64 + i] = m[i];
  3547. for (i = 0; i < 32; i++)
  3548. sm[32 + i] = d[32 + i];
  3549. crypto_hash(r, sm.subarray(32), n + 32);
  3550. reduce(r);
  3551. scalarbase(p, r);
  3552. pack(sm, p);
  3553. for (i = 32; i < 64; i++)
  3554. sm[i] = sk[i];
  3555. crypto_hash(h, sm, n + 64);
  3556. reduce(h);
  3557. for (i = 0; i < 64; i++)
  3558. x[i] = 0;
  3559. for (i = 0; i < 32; i++)
  3560. x[i] = r[i];
  3561. for (i = 0; i < 32; i++) {
  3562. for (j = 0; j < 32; j++) {
  3563. x[i + j] += h[i] * d[j];
  3564. }
  3565. }
  3566. modL(sm.subarray(32), x);
  3567. return smlen;
  3568. }
  3569. function unpackneg(r, p) {
  3570. var t = gf(), chk = gf(), num = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf();
  3571. set25519(r[2], gf1);
  3572. unpack25519(r[1], p);
  3573. S(num, r[1]);
  3574. M(den, num, D);
  3575. Z(num, num, r[2]);
  3576. A(den, r[2], den);
  3577. S(den2, den);
  3578. S(den4, den2);
  3579. M(den6, den4, den2);
  3580. M(t, den6, num);
  3581. M(t, t, den);
  3582. pow2523(t, t);
  3583. M(t, t, num);
  3584. M(t, t, den);
  3585. M(t, t, den);
  3586. M(r[0], t, den);
  3587. S(chk, r[0]);
  3588. M(chk, chk, den);
  3589. if (neq25519(chk, num))
  3590. M(r[0], r[0], I);
  3591. S(chk, r[0]);
  3592. M(chk, chk, den);
  3593. if (neq25519(chk, num))
  3594. return -1;
  3595. if (par25519(r[0]) === p[31] >> 7)
  3596. Z(r[0], gf0, r[0]);
  3597. M(r[3], r[0], r[1]);
  3598. return 0;
  3599. }
  3600. function crypto_sign_open(m, sm, n, pk) {
  3601. var i;
  3602. var t = new Uint8Array(32), h = new Uint8Array(64);
  3603. var p = [
  3604. gf(),
  3605. gf(),
  3606. gf(),
  3607. gf()
  3608. ], q = [
  3609. gf(),
  3610. gf(),
  3611. gf(),
  3612. gf()
  3613. ];
  3614. if (n < 64)
  3615. return -1;
  3616. if (unpackneg(q, pk))
  3617. return -1;
  3618. for (i = 0; i < n; i++)
  3619. m[i] = sm[i];
  3620. for (i = 0; i < 32; i++)
  3621. m[i + 32] = pk[i];
  3622. crypto_hash(h, m, n);
  3623. reduce(h);
  3624. scalarmult(p, q, h);
  3625. scalarbase(q, sm.subarray(32));
  3626. add(p, q);
  3627. pack(t, p);
  3628. n -= 64;
  3629. if (crypto_verify_32(sm, 0, t, 0)) {
  3630. for (i = 0; i < n; i++)
  3631. m[i] = 0;
  3632. return -1;
  3633. }
  3634. for (i = 0; i < n; i++)
  3635. m[i] = sm[i + 64];
  3636. return n;
  3637. }
  3638. var crypto_secretbox_KEYBYTES = 32, crypto_secretbox_NONCEBYTES = 24, crypto_secretbox_ZEROBYTES = 32, crypto_secretbox_BOXZEROBYTES = 16, crypto_scalarmult_BYTES = 32, crypto_scalarmult_SCALARBYTES = 32, crypto_box_PUBLICKEYBYTES = 32, crypto_box_SECRETKEYBYTES = 32, crypto_box_BEFORENMBYTES = 32, crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, crypto_sign_BYTES = 64, crypto_sign_PUBLICKEYBYTES = 32, crypto_sign_SECRETKEYBYTES = 64, crypto_sign_SEEDBYTES = 32, crypto_hash_BYTES = 64;
  3639. nacl2.lowlevel = {
  3640. crypto_core_hsalsa20,
  3641. crypto_stream_xor,
  3642. crypto_stream,
  3643. crypto_stream_salsa20_xor,
  3644. crypto_stream_salsa20,
  3645. crypto_onetimeauth,
  3646. crypto_onetimeauth_verify,
  3647. crypto_verify_16,
  3648. crypto_verify_32,
  3649. crypto_secretbox,
  3650. crypto_secretbox_open,
  3651. crypto_scalarmult,
  3652. crypto_scalarmult_base,
  3653. crypto_box_beforenm,
  3654. crypto_box_afternm,
  3655. crypto_box,
  3656. crypto_box_open,
  3657. crypto_box_keypair,
  3658. crypto_hash,
  3659. crypto_sign,
  3660. crypto_sign_keypair,
  3661. crypto_sign_open,
  3662. crypto_secretbox_KEYBYTES,
  3663. crypto_secretbox_NONCEBYTES,
  3664. crypto_secretbox_ZEROBYTES,
  3665. crypto_secretbox_BOXZEROBYTES,
  3666. crypto_scalarmult_BYTES,
  3667. crypto_scalarmult_SCALARBYTES,
  3668. crypto_box_PUBLICKEYBYTES,
  3669. crypto_box_SECRETKEYBYTES,
  3670. crypto_box_BEFORENMBYTES,
  3671. crypto_box_NONCEBYTES,
  3672. crypto_box_ZEROBYTES,
  3673. crypto_box_BOXZEROBYTES,
  3674. crypto_sign_BYTES,
  3675. crypto_sign_PUBLICKEYBYTES,
  3676. crypto_sign_SECRETKEYBYTES,
  3677. crypto_sign_SEEDBYTES,
  3678. crypto_hash_BYTES,
  3679. gf,
  3680. D,
  3681. L,
  3682. pack25519,
  3683. unpack25519,
  3684. M,
  3685. A,
  3686. S,
  3687. Z,
  3688. pow2523,
  3689. add,
  3690. set25519,
  3691. modL,
  3692. scalarmult,
  3693. scalarbase
  3694. };
  3695. function checkLengths(k, n) {
  3696. if (k.length !== crypto_secretbox_KEYBYTES)
  3697. throw new Error("bad key size");
  3698. if (n.length !== crypto_secretbox_NONCEBYTES)
  3699. throw new Error("bad nonce size");
  3700. }
  3701. function checkBoxLengths(pk, sk) {
  3702. if (pk.length !== crypto_box_PUBLICKEYBYTES)
  3703. throw new Error("bad public key size");
  3704. if (sk.length !== crypto_box_SECRETKEYBYTES)
  3705. throw new Error("bad secret key size");
  3706. }
  3707. function checkArrayTypes() {
  3708. for (var i = 0; i < arguments.length; i++) {
  3709. if (!(arguments[i] instanceof Uint8Array))
  3710. throw new TypeError("unexpected type, use Uint8Array");
  3711. }
  3712. }
  3713. function cleanup(arr) {
  3714. for (var i = 0; i < arr.length; i++)
  3715. arr[i] = 0;
  3716. }
  3717. nacl2.randomBytes = function(n) {
  3718. var b = new Uint8Array(n);
  3719. randombytes(b, n);
  3720. return b;
  3721. };
  3722. nacl2.secretbox = function(msg, nonce, key) {
  3723. checkArrayTypes(msg, nonce, key);
  3724. checkLengths(key, nonce);
  3725. var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length);
  3726. var c = new Uint8Array(m.length);
  3727. for (var i = 0; i < msg.length; i++)
  3728. m[i + crypto_secretbox_ZEROBYTES] = msg[i];
  3729. crypto_secretbox(c, m, m.length, nonce, key);
  3730. return c.subarray(crypto_secretbox_BOXZEROBYTES);
  3731. };
  3732. nacl2.secretbox.open = function(box, nonce, key) {
  3733. checkArrayTypes(box, nonce, key);
  3734. checkLengths(key, nonce);
  3735. var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length);
  3736. var m = new Uint8Array(c.length);
  3737. for (var i = 0; i < box.length; i++)
  3738. c[i + crypto_secretbox_BOXZEROBYTES] = box[i];
  3739. if (c.length < 32)
  3740. return null;
  3741. if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0)
  3742. return null;
  3743. return m.subarray(crypto_secretbox_ZEROBYTES);
  3744. };
  3745. nacl2.secretbox.keyLength = crypto_secretbox_KEYBYTES;
  3746. nacl2.secretbox.nonceLength = crypto_secretbox_NONCEBYTES;
  3747. nacl2.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES;
  3748. nacl2.scalarMult = function(n, p) {
  3749. checkArrayTypes(n, p);
  3750. if (n.length !== crypto_scalarmult_SCALARBYTES)
  3751. throw new Error("bad n size");
  3752. if (p.length !== crypto_scalarmult_BYTES)
  3753. throw new Error("bad p size");
  3754. var q = new Uint8Array(crypto_scalarmult_BYTES);
  3755. crypto_scalarmult(q, n, p);
  3756. return q;
  3757. };
  3758. nacl2.scalarMult.base = function(n) {
  3759. checkArrayTypes(n);
  3760. if (n.length !== crypto_scalarmult_SCALARBYTES)
  3761. throw new Error("bad n size");
  3762. var q = new Uint8Array(crypto_scalarmult_BYTES);
  3763. crypto_scalarmult_base(q, n);
  3764. return q;
  3765. };
  3766. nacl2.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES;
  3767. nacl2.scalarMult.groupElementLength = crypto_scalarmult_BYTES;
  3768. nacl2.box = function(msg, nonce, publicKey, secretKey) {
  3769. var k = nacl2.box.before(publicKey, secretKey);
  3770. return nacl2.secretbox(msg, nonce, k);
  3771. };
  3772. nacl2.box.before = function(publicKey, secretKey) {
  3773. checkArrayTypes(publicKey, secretKey);
  3774. checkBoxLengths(publicKey, secretKey);
  3775. var k = new Uint8Array(crypto_box_BEFORENMBYTES);
  3776. crypto_box_beforenm(k, publicKey, secretKey);
  3777. return k;
  3778. };
  3779. nacl2.box.after = nacl2.secretbox;
  3780. nacl2.box.open = function(msg, nonce, publicKey, secretKey) {
  3781. var k = nacl2.box.before(publicKey, secretKey);
  3782. return nacl2.secretbox.open(msg, nonce, k);
  3783. };
  3784. nacl2.box.open.after = nacl2.secretbox.open;
  3785. nacl2.box.keyPair = function() {
  3786. var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
  3787. var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);
  3788. crypto_box_keypair(pk, sk);
  3789. return {
  3790. publicKey: pk,
  3791. secretKey: sk
  3792. };
  3793. };
  3794. nacl2.box.keyPair.fromSecretKey = function(secretKey) {
  3795. checkArrayTypes(secretKey);
  3796. if (secretKey.length !== crypto_box_SECRETKEYBYTES)
  3797. throw new Error("bad secret key size");
  3798. var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
  3799. crypto_scalarmult_base(pk, secretKey);
  3800. return {
  3801. publicKey: pk,
  3802. secretKey: new Uint8Array(secretKey)
  3803. };
  3804. };
  3805. nacl2.box.publicKeyLength = crypto_box_PUBLICKEYBYTES;
  3806. nacl2.box.secretKeyLength = crypto_box_SECRETKEYBYTES;
  3807. nacl2.box.sharedKeyLength = crypto_box_BEFORENMBYTES;
  3808. nacl2.box.nonceLength = crypto_box_NONCEBYTES;
  3809. nacl2.box.overheadLength = nacl2.secretbox.overheadLength;
  3810. nacl2.sign = function(msg, secretKey) {
  3811. checkArrayTypes(msg, secretKey);
  3812. if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
  3813. throw new Error("bad secret key size");
  3814. var signedMsg = new Uint8Array(crypto_sign_BYTES + msg.length);
  3815. crypto_sign(signedMsg, msg, msg.length, secretKey);
  3816. return signedMsg;
  3817. };
  3818. nacl2.sign.open = function(signedMsg, publicKey) {
  3819. checkArrayTypes(signedMsg, publicKey);
  3820. if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
  3821. throw new Error("bad public key size");
  3822. var tmp = new Uint8Array(signedMsg.length);
  3823. var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey);
  3824. if (mlen < 0)
  3825. return null;
  3826. var m = new Uint8Array(mlen);
  3827. for (var i = 0; i < m.length; i++)
  3828. m[i] = tmp[i];
  3829. return m;
  3830. };
  3831. nacl2.sign.detached = function(msg, secretKey) {
  3832. var signedMsg = nacl2.sign(msg, secretKey);
  3833. var sig = new Uint8Array(crypto_sign_BYTES);
  3834. for (var i = 0; i < sig.length; i++)
  3835. sig[i] = signedMsg[i];
  3836. return sig;
  3837. };
  3838. nacl2.sign.detached.verify = function(msg, sig, publicKey) {
  3839. checkArrayTypes(msg, sig, publicKey);
  3840. if (sig.length !== crypto_sign_BYTES)
  3841. throw new Error("bad signature size");
  3842. if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
  3843. throw new Error("bad public key size");
  3844. var sm = new Uint8Array(crypto_sign_BYTES + msg.length);
  3845. var m = new Uint8Array(crypto_sign_BYTES + msg.length);
  3846. var i;
  3847. for (i = 0; i < crypto_sign_BYTES; i++)
  3848. sm[i] = sig[i];
  3849. for (i = 0; i < msg.length; i++)
  3850. sm[i + crypto_sign_BYTES] = msg[i];
  3851. return crypto_sign_open(m, sm, sm.length, publicKey) >= 0;
  3852. };
  3853. nacl2.sign.keyPair = function() {
  3854. var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
  3855. var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
  3856. crypto_sign_keypair(pk, sk);
  3857. return {
  3858. publicKey: pk,
  3859. secretKey: sk
  3860. };
  3861. };
  3862. nacl2.sign.keyPair.fromSecretKey = function(secretKey) {
  3863. checkArrayTypes(secretKey);
  3864. if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
  3865. throw new Error("bad secret key size");
  3866. var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
  3867. for (var i = 0; i < pk.length; i++)
  3868. pk[i] = secretKey[32 + i];
  3869. return {
  3870. publicKey: pk,
  3871. secretKey: new Uint8Array(secretKey)
  3872. };
  3873. };
  3874. nacl2.sign.keyPair.fromSeed = function(seed) {
  3875. checkArrayTypes(seed);
  3876. if (seed.length !== crypto_sign_SEEDBYTES)
  3877. throw new Error("bad seed size");
  3878. var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
  3879. var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
  3880. for (var i = 0; i < 32; i++)
  3881. sk[i] = seed[i];
  3882. crypto_sign_keypair(pk, sk, true);
  3883. return {
  3884. publicKey: pk,
  3885. secretKey: sk
  3886. };
  3887. };
  3888. nacl2.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES;
  3889. nacl2.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES;
  3890. nacl2.sign.seedLength = crypto_sign_SEEDBYTES;
  3891. nacl2.sign.signatureLength = crypto_sign_BYTES;
  3892. nacl2.hash = function(msg) {
  3893. checkArrayTypes(msg);
  3894. var h = new Uint8Array(crypto_hash_BYTES);
  3895. crypto_hash(h, msg, msg.length);
  3896. return h;
  3897. };
  3898. nacl2.hash.hashLength = crypto_hash_BYTES;
  3899. nacl2.verify = function(x, y) {
  3900. checkArrayTypes(x, y);
  3901. if (x.length === 0 || y.length === 0)
  3902. return false;
  3903. if (x.length !== y.length)
  3904. return false;
  3905. return vn(x, 0, y, 0, x.length) === 0 ? true : false;
  3906. };
  3907. nacl2.setPRNG = function(fn) {
  3908. randombytes = fn;
  3909. };
  3910. (function() {
  3911. var crypto1 = typeof globalThis !== "undefined" ? globalThis.crypto || globalThis.msCrypto : null;
  3912. if (crypto1 && crypto1.getRandomValues) {
  3913. var QUOTA = 65536;
  3914. nacl2.setPRNG(function(x, n) {
  3915. var i, v = new Uint8Array(n);
  3916. for (i = 0; i < n; i += QUOTA) {
  3917. crypto1.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));
  3918. }
  3919. for (i = 0; i < n; i++)
  3920. x[i] = v[i];
  3921. cleanup(v);
  3922. });
  3923. } else if (typeof __require !== "undefined") {
  3924. crypto1 = require_crypto();
  3925. if (crypto1 && crypto1.randomBytes) {
  3926. nacl2.setPRNG(function(x, n) {
  3927. var i, v = crypto1.randomBytes(n);
  3928. for (i = 0; i < n; i++)
  3929. x[i] = v[i];
  3930. cleanup(v);
  3931. });
  3932. }
  3933. }
  3934. })();
  3935. })(typeof module !== "undefined" && module.exports ? module.exports : globalThis.nacl = globalThis.nacl || {});
  3936. var nacl = typeof module !== "undefined" && module.exports ? module.exports : globalThis.nacl;
  3937. var denoHelper = {
  3938. fromSeed: nacl.sign.keyPair.fromSeed,
  3939. sign: nacl.sign.detached,
  3940. verify: nacl.sign.detached.verify,
  3941. randomBytes: nacl.randomBytes
  3942. };
  3943. var helper;
  3944. function setEd25519Helper(lib) {
  3945. helper = lib;
  3946. }
  3947. function getEd25519Helper() {
  3948. return helper;
  3949. }
  3950. var crc16tab = new Uint16Array([
  3951. 0,
  3952. 4129,
  3953. 8258,
  3954. 12387,
  3955. 16516,
  3956. 20645,
  3957. 24774,
  3958. 28903,
  3959. 33032,
  3960. 37161,
  3961. 41290,
  3962. 45419,
  3963. 49548,
  3964. 53677,
  3965. 57806,
  3966. 61935,
  3967. 4657,
  3968. 528,
  3969. 12915,
  3970. 8786,
  3971. 21173,
  3972. 17044,
  3973. 29431,
  3974. 25302,
  3975. 37689,
  3976. 33560,
  3977. 45947,
  3978. 41818,
  3979. 54205,
  3980. 50076,
  3981. 62463,
  3982. 58334,
  3983. 9314,
  3984. 13379,
  3985. 1056,
  3986. 5121,
  3987. 25830,
  3988. 29895,
  3989. 17572,
  3990. 21637,
  3991. 42346,
  3992. 46411,
  3993. 34088,
  3994. 38153,
  3995. 58862,
  3996. 62927,
  3997. 50604,
  3998. 54669,
  3999. 13907,
  4000. 9842,
  4001. 5649,
  4002. 1584,
  4003. 30423,
  4004. 26358,
  4005. 22165,
  4006. 18100,
  4007. 46939,
  4008. 42874,
  4009. 38681,
  4010. 34616,
  4011. 63455,
  4012. 59390,
  4013. 55197,
  4014. 51132,
  4015. 18628,
  4016. 22757,
  4017. 26758,
  4018. 30887,
  4019. 2112,
  4020. 6241,
  4021. 10242,
  4022. 14371,
  4023. 51660,
  4024. 55789,
  4025. 59790,
  4026. 63919,
  4027. 35144,
  4028. 39273,
  4029. 43274,
  4030. 47403,
  4031. 23285,
  4032. 19156,
  4033. 31415,
  4034. 27286,
  4035. 6769,
  4036. 2640,
  4037. 14899,
  4038. 10770,
  4039. 56317,
  4040. 52188,
  4041. 64447,
  4042. 60318,
  4043. 39801,
  4044. 35672,
  4045. 47931,
  4046. 43802,
  4047. 27814,
  4048. 31879,
  4049. 19684,
  4050. 23749,
  4051. 11298,
  4052. 15363,
  4053. 3168,
  4054. 7233,
  4055. 60846,
  4056. 64911,
  4057. 52716,
  4058. 56781,
  4059. 44330,
  4060. 48395,
  4061. 36200,
  4062. 40265,
  4063. 32407,
  4064. 28342,
  4065. 24277,
  4066. 20212,
  4067. 15891,
  4068. 11826,
  4069. 7761,
  4070. 3696,
  4071. 65439,
  4072. 61374,
  4073. 57309,
  4074. 53244,
  4075. 48923,
  4076. 44858,
  4077. 40793,
  4078. 36728,
  4079. 37256,
  4080. 33193,
  4081. 45514,
  4082. 41451,
  4083. 53516,
  4084. 49453,
  4085. 61774,
  4086. 57711,
  4087. 4224,
  4088. 161,
  4089. 12482,
  4090. 8419,
  4091. 20484,
  4092. 16421,
  4093. 28742,
  4094. 24679,
  4095. 33721,
  4096. 37784,
  4097. 41979,
  4098. 46042,
  4099. 49981,
  4100. 54044,
  4101. 58239,
  4102. 62302,
  4103. 689,
  4104. 4752,
  4105. 8947,
  4106. 13010,
  4107. 16949,
  4108. 21012,
  4109. 25207,
  4110. 29270,
  4111. 46570,
  4112. 42443,
  4113. 38312,
  4114. 34185,
  4115. 62830,
  4116. 58703,
  4117. 54572,
  4118. 50445,
  4119. 13538,
  4120. 9411,
  4121. 5280,
  4122. 1153,
  4123. 29798,
  4124. 25671,
  4125. 21540,
  4126. 17413,
  4127. 42971,
  4128. 47098,
  4129. 34713,
  4130. 38840,
  4131. 59231,
  4132. 63358,
  4133. 50973,
  4134. 55100,
  4135. 9939,
  4136. 14066,
  4137. 1681,
  4138. 5808,
  4139. 26199,
  4140. 30326,
  4141. 17941,
  4142. 22068,
  4143. 55628,
  4144. 51565,
  4145. 63758,
  4146. 59695,
  4147. 39368,
  4148. 35305,
  4149. 47498,
  4150. 43435,
  4151. 22596,
  4152. 18533,
  4153. 30726,
  4154. 26663,
  4155. 6336,
  4156. 2273,
  4157. 14466,
  4158. 10403,
  4159. 52093,
  4160. 56156,
  4161. 60223,
  4162. 64286,
  4163. 35833,
  4164. 39896,
  4165. 43963,
  4166. 48026,
  4167. 19061,
  4168. 23124,
  4169. 27191,
  4170. 31254,
  4171. 2801,
  4172. 6864,
  4173. 10931,
  4174. 14994,
  4175. 64814,
  4176. 60687,
  4177. 56684,
  4178. 52557,
  4179. 48554,
  4180. 44427,
  4181. 40424,
  4182. 36297,
  4183. 31782,
  4184. 27655,
  4185. 23652,
  4186. 19525,
  4187. 15522,
  4188. 11395,
  4189. 7392,
  4190. 3265,
  4191. 61215,
  4192. 65342,
  4193. 53085,
  4194. 57212,
  4195. 44955,
  4196. 49082,
  4197. 36825,
  4198. 40952,
  4199. 28183,
  4200. 32310,
  4201. 20053,
  4202. 24180,
  4203. 11923,
  4204. 16050,
  4205. 3793,
  4206. 7920
  4207. ]);
  4208. var crc16 = class {
  4209. static checksum(data) {
  4210. let crc = 0;
  4211. for (let i = 0; i < data.byteLength; i++) {
  4212. let b = data[i];
  4213. crc = crc << 8 & 65535 ^ crc16tab[(crc >> 8 ^ b) & 255];
  4214. }
  4215. return crc;
  4216. }
  4217. static validate(data, expected) {
  4218. let ba = crc16.checksum(data);
  4219. return ba == expected;
  4220. }
  4221. };
  4222. var b32Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
  4223. var base32 = class {
  4224. static encode(src) {
  4225. let bits = 0;
  4226. let value = 0;
  4227. let a = new Uint8Array(src);
  4228. let buf = new Uint8Array(src.byteLength * 2);
  4229. let j = 0;
  4230. for (let i = 0; i < a.byteLength; i++) {
  4231. value = value << 8 | a[i];
  4232. bits += 8;
  4233. while (bits >= 5) {
  4234. let index = value >>> bits - 5 & 31;
  4235. buf[j++] = b32Alphabet.charAt(index).charCodeAt(0);
  4236. bits -= 5;
  4237. }
  4238. }
  4239. if (bits > 0) {
  4240. let index = value << 5 - bits & 31;
  4241. buf[j++] = b32Alphabet.charAt(index).charCodeAt(0);
  4242. }
  4243. return buf.slice(0, j);
  4244. }
  4245. static decode(src) {
  4246. let bits = 0;
  4247. let __byte = 0;
  4248. let j = 0;
  4249. let a = new Uint8Array(src);
  4250. let out = new Uint8Array(a.byteLength * 5 / 8 | 0);
  4251. for (let i = 0; i < a.byteLength; i++) {
  4252. let v = String.fromCharCode(a[i]);
  4253. let vv = b32Alphabet.indexOf(v);
  4254. if (vv === -1) {
  4255. throw new Error("Illegal Base32 character: " + a[i]);
  4256. }
  4257. __byte = __byte << 5 | vv;
  4258. bits += 5;
  4259. if (bits >= 8) {
  4260. out[j++] = __byte >>> bits - 8 & 255;
  4261. bits -= 8;
  4262. }
  4263. }
  4264. return out.slice(0, j);
  4265. }
  4266. };
  4267. var NKeysError = class extends Error {
  4268. constructor(code2, chainedError) {
  4269. super(code2);
  4270. __publicField(this, "name");
  4271. __publicField(this, "code");
  4272. __publicField(this, "chainedError");
  4273. this.name = "NKeysError";
  4274. this.code = code2;
  4275. this.chainedError = chainedError;
  4276. }
  4277. };
  4278. function createOperator() {
  4279. return createPair(Prefix.Operator);
  4280. }
  4281. function createAccount() {
  4282. return createPair(Prefix.Account);
  4283. }
  4284. function createUser() {
  4285. return createPair(Prefix.User);
  4286. }
  4287. var NKeysErrorCode;
  4288. (function(NKeysErrorCode2) {
  4289. NKeysErrorCode2["InvalidPrefixByte"] = "nkeys: invalid prefix byte";
  4290. NKeysErrorCode2["InvalidKey"] = "nkeys: invalid key";
  4291. NKeysErrorCode2["InvalidPublicKey"] = "nkeys: invalid public key";
  4292. NKeysErrorCode2["InvalidSeedLen"] = "nkeys: invalid seed length";
  4293. NKeysErrorCode2["InvalidSeed"] = "nkeys: invalid seed";
  4294. NKeysErrorCode2["InvalidEncoding"] = "nkeys: invalid encoded key";
  4295. NKeysErrorCode2["InvalidSignature"] = "nkeys: signature verification failed";
  4296. NKeysErrorCode2["CannotSign"] = "nkeys: cannot sign, no private key available";
  4297. NKeysErrorCode2["PublicKeyOnly"] = "nkeys: no seed or private key available";
  4298. NKeysErrorCode2["InvalidChecksum"] = "nkeys: invalid checksum";
  4299. NKeysErrorCode2["SerializationError"] = "nkeys: serialization error";
  4300. NKeysErrorCode2["ApiError"] = "nkeys: api error";
  4301. NKeysErrorCode2["ClearedPair"] = "nkeys: pair is cleared";
  4302. })(NKeysErrorCode || (NKeysErrorCode = {}));
  4303. var Prefix;
  4304. (function(Prefix2) {
  4305. Prefix2[Prefix2["Seed"] = 144] = "Seed";
  4306. Prefix2[Prefix2["Private"] = 120] = "Private";
  4307. Prefix2[Prefix2["Operator"] = 112] = "Operator";
  4308. Prefix2[Prefix2["Server"] = 104] = "Server";
  4309. Prefix2[Prefix2["Cluster"] = 16] = "Cluster";
  4310. Prefix2[Prefix2["Account"] = 0] = "Account";
  4311. Prefix2[Prefix2["User"] = 160] = "User";
  4312. })(Prefix || (Prefix = {}));
  4313. var Prefixes = class {
  4314. static isValidPublicPrefix(prefix) {
  4315. return prefix == Prefix.Server || prefix == Prefix.Operator || prefix == Prefix.Cluster || prefix == Prefix.Account || prefix == Prefix.User;
  4316. }
  4317. static startsWithValidPrefix(s) {
  4318. let c = s[0];
  4319. return c == "S" || c == "P" || c == "O" || c == "N" || c == "C" || c == "A" || c == "U";
  4320. }
  4321. static isValidPrefix(prefix) {
  4322. let v = this.parsePrefix(prefix);
  4323. return v != -1;
  4324. }
  4325. static parsePrefix(v) {
  4326. switch (v) {
  4327. case Prefix.Seed:
  4328. return Prefix.Seed;
  4329. case Prefix.Private:
  4330. return Prefix.Private;
  4331. case Prefix.Operator:
  4332. return Prefix.Operator;
  4333. case Prefix.Server:
  4334. return Prefix.Server;
  4335. case Prefix.Cluster:
  4336. return Prefix.Cluster;
  4337. case Prefix.Account:
  4338. return Prefix.Account;
  4339. case Prefix.User:
  4340. return Prefix.User;
  4341. default:
  4342. return -1;
  4343. }
  4344. }
  4345. };
  4346. var Codec = class {
  4347. static encode(prefix, src) {
  4348. if (!src || !(src instanceof Uint8Array)) {
  4349. throw new NKeysError(NKeysErrorCode.SerializationError);
  4350. }
  4351. if (!Prefixes.isValidPrefix(prefix)) {
  4352. throw new NKeysError(NKeysErrorCode.InvalidPrefixByte);
  4353. }
  4354. return Codec._encode(false, prefix, src);
  4355. }
  4356. static encodeSeed(role, src) {
  4357. if (!src) {
  4358. throw new NKeysError(NKeysErrorCode.ApiError);
  4359. }
  4360. if (!Prefixes.isValidPublicPrefix(role)) {
  4361. throw new NKeysError(NKeysErrorCode.InvalidPrefixByte);
  4362. }
  4363. if (src.byteLength !== 32) {
  4364. throw new NKeysError(NKeysErrorCode.InvalidSeedLen);
  4365. }
  4366. return Codec._encode(true, role, src);
  4367. }
  4368. static decode(expected, src) {
  4369. if (!Prefixes.isValidPrefix(expected)) {
  4370. throw new NKeysError(NKeysErrorCode.InvalidPrefixByte);
  4371. }
  4372. const raw = Codec._decode(src);
  4373. if (raw[0] !== expected) {
  4374. throw new NKeysError(NKeysErrorCode.InvalidPrefixByte);
  4375. }
  4376. return raw.slice(1);
  4377. }
  4378. static decodeSeed(src) {
  4379. const raw = Codec._decode(src);
  4380. const prefix = Codec._decodePrefix(raw);
  4381. if (prefix[0] != Prefix.Seed) {
  4382. throw new NKeysError(NKeysErrorCode.InvalidSeed);
  4383. }
  4384. if (!Prefixes.isValidPublicPrefix(prefix[1])) {
  4385. throw new NKeysError(NKeysErrorCode.InvalidPrefixByte);
  4386. }
  4387. return {
  4388. buf: raw.slice(2),
  4389. prefix: prefix[1]
  4390. };
  4391. }
  4392. static _encode(seed, role, payload) {
  4393. const payloadOffset = seed ? 2 : 1;
  4394. const payloadLen = payload.byteLength;
  4395. const cap = payloadOffset + payloadLen + 2;
  4396. const checkOffset = payloadOffset + payloadLen;
  4397. const raw = new Uint8Array(cap);
  4398. if (seed) {
  4399. const encodedPrefix = Codec._encodePrefix(Prefix.Seed, role);
  4400. raw.set(encodedPrefix);
  4401. } else {
  4402. raw[0] = role;
  4403. }
  4404. raw.set(payload, payloadOffset);
  4405. const checksum = crc16.checksum(raw.slice(0, checkOffset));
  4406. const dv = new DataView(raw.buffer);
  4407. dv.setUint16(checkOffset, checksum, true);
  4408. return base32.encode(raw);
  4409. }
  4410. static _decode(src) {
  4411. if (src.byteLength < 4) {
  4412. throw new NKeysError(NKeysErrorCode.InvalidEncoding);
  4413. }
  4414. let raw;
  4415. try {
  4416. raw = base32.decode(src);
  4417. } catch (ex) {
  4418. throw new NKeysError(NKeysErrorCode.InvalidEncoding, ex);
  4419. }
  4420. const checkOffset = raw.byteLength - 2;
  4421. const dv = new DataView(raw.buffer);
  4422. const checksum = dv.getUint16(checkOffset, true);
  4423. const payload = raw.slice(0, checkOffset);
  4424. if (!crc16.validate(payload, checksum)) {
  4425. throw new NKeysError(NKeysErrorCode.InvalidChecksum);
  4426. }
  4427. return payload;
  4428. }
  4429. static _encodePrefix(kind, role) {
  4430. const b1 = kind | role >> 5;
  4431. const b2 = (role & 31) << 3;
  4432. return new Uint8Array([
  4433. b1,
  4434. b2
  4435. ]);
  4436. }
  4437. static _decodePrefix(raw) {
  4438. const b1 = raw[0] & 248;
  4439. const b2 = (raw[0] & 7) << 5 | (raw[1] & 248) >> 3;
  4440. return new Uint8Array([
  4441. b1,
  4442. b2
  4443. ]);
  4444. }
  4445. };
  4446. var KP = class {
  4447. constructor(seed) {
  4448. __publicField(this, "seed");
  4449. this.seed = seed;
  4450. }
  4451. getRawSeed() {
  4452. if (!this.seed) {
  4453. throw new NKeysError(NKeysErrorCode.ClearedPair);
  4454. }
  4455. let sd = Codec.decodeSeed(this.seed);
  4456. return sd.buf;
  4457. }
  4458. getSeed() {
  4459. if (!this.seed) {
  4460. throw new NKeysError(NKeysErrorCode.ClearedPair);
  4461. }
  4462. return this.seed;
  4463. }
  4464. getPublicKey() {
  4465. if (!this.seed) {
  4466. throw new NKeysError(NKeysErrorCode.ClearedPair);
  4467. }
  4468. const sd = Codec.decodeSeed(this.seed);
  4469. const kp = getEd25519Helper().fromSeed(this.getRawSeed());
  4470. const buf = Codec.encode(sd.prefix, kp.publicKey);
  4471. return new TextDecoder().decode(buf);
  4472. }
  4473. getPrivateKey() {
  4474. if (!this.seed) {
  4475. throw new NKeysError(NKeysErrorCode.ClearedPair);
  4476. }
  4477. const kp = getEd25519Helper().fromSeed(this.getRawSeed());
  4478. return Codec.encode(Prefix.Private, kp.secretKey);
  4479. }
  4480. sign(input) {
  4481. if (!this.seed) {
  4482. throw new NKeysError(NKeysErrorCode.ClearedPair);
  4483. }
  4484. const kp = getEd25519Helper().fromSeed(this.getRawSeed());
  4485. return getEd25519Helper().sign(input, kp.secretKey);
  4486. }
  4487. verify(input, sig) {
  4488. if (!this.seed) {
  4489. throw new NKeysError(NKeysErrorCode.ClearedPair);
  4490. }
  4491. const kp = getEd25519Helper().fromSeed(this.getRawSeed());
  4492. return getEd25519Helper().verify(input, sig, kp.publicKey);
  4493. }
  4494. clear() {
  4495. if (!this.seed) {
  4496. return;
  4497. }
  4498. this.seed.fill(0);
  4499. this.seed = void 0;
  4500. }
  4501. };
  4502. function createPair(prefix) {
  4503. const rawSeed = getEd25519Helper().randomBytes(32);
  4504. let str = Codec.encodeSeed(prefix, new Uint8Array(rawSeed));
  4505. return new KP(str);
  4506. }
  4507. var PublicKey = class {
  4508. constructor(publicKey) {
  4509. __publicField(this, "publicKey");
  4510. this.publicKey = publicKey;
  4511. }
  4512. getPublicKey() {
  4513. if (!this.publicKey) {
  4514. throw new NKeysError(NKeysErrorCode.ClearedPair);
  4515. }
  4516. return new TextDecoder().decode(this.publicKey);
  4517. }
  4518. getPrivateKey() {
  4519. if (!this.publicKey) {
  4520. throw new NKeysError(NKeysErrorCode.ClearedPair);
  4521. }
  4522. throw new NKeysError(NKeysErrorCode.PublicKeyOnly);
  4523. }
  4524. getSeed() {
  4525. if (!this.publicKey) {
  4526. throw new NKeysError(NKeysErrorCode.ClearedPair);
  4527. }
  4528. throw new NKeysError(NKeysErrorCode.PublicKeyOnly);
  4529. }
  4530. sign(_) {
  4531. if (!this.publicKey) {
  4532. throw new NKeysError(NKeysErrorCode.ClearedPair);
  4533. }
  4534. throw new NKeysError(NKeysErrorCode.CannotSign);
  4535. }
  4536. verify(input, sig) {
  4537. if (!this.publicKey) {
  4538. throw new NKeysError(NKeysErrorCode.ClearedPair);
  4539. }
  4540. let buf = Codec._decode(this.publicKey);
  4541. return getEd25519Helper().verify(input, sig, buf.slice(1));
  4542. }
  4543. clear() {
  4544. if (!this.publicKey) {
  4545. return;
  4546. }
  4547. this.publicKey.fill(0);
  4548. this.publicKey = void 0;
  4549. }
  4550. };
  4551. function fromPublic(src) {
  4552. const ba = new TextEncoder().encode(src);
  4553. const raw = Codec._decode(ba);
  4554. const prefix = Prefixes.parsePrefix(raw[0]);
  4555. if (Prefixes.isValidPublicPrefix(prefix)) {
  4556. return new PublicKey(ba);
  4557. }
  4558. throw new NKeysError(NKeysErrorCode.InvalidPublicKey);
  4559. }
  4560. function fromSeed(src) {
  4561. Codec.decodeSeed(src);
  4562. return new KP(src);
  4563. }
  4564. function encode1(bytes) {
  4565. return btoa(String.fromCharCode(...bytes));
  4566. }
  4567. function decode1(b64str) {
  4568. const bin = atob(b64str);
  4569. const bytes = new Uint8Array(bin.length);
  4570. for (let i = 0; i < bin.length; i++) {
  4571. bytes[i] = bin.charCodeAt(i);
  4572. }
  4573. return bytes;
  4574. }
  4575. setEd25519Helper(denoHelper);
  4576. var mod = {
  4577. createAccount,
  4578. createOperator,
  4579. createPair,
  4580. createUser,
  4581. fromPublic,
  4582. fromSeed,
  4583. NKeysError,
  4584. NKeysErrorCode,
  4585. Prefix,
  4586. decode: decode1,
  4587. encode: encode1
  4588. };
  4589. function multiAuthenticator(authenticators) {
  4590. return (nonce) => {
  4591. let auth = {};
  4592. authenticators.forEach((a) => {
  4593. const args = a(nonce) || {};
  4594. auth = Object.assign(auth, args);
  4595. });
  4596. return auth;
  4597. };
  4598. }
  4599. function noAuthFn() {
  4600. return () => {
  4601. return;
  4602. };
  4603. }
  4604. function usernamePasswordAuthenticator(user, pass) {
  4605. return () => {
  4606. const u = typeof user === "function" ? user() : user;
  4607. const p = typeof pass === "function" ? pass() : pass;
  4608. return {
  4609. user: u,
  4610. pass: p
  4611. };
  4612. };
  4613. }
  4614. function tokenAuthenticator(token) {
  4615. return () => {
  4616. const auth_token = typeof token === "function" ? token() : token;
  4617. return {
  4618. auth_token
  4619. };
  4620. };
  4621. }
  4622. function nkeyAuthenticator(seed) {
  4623. return (nonce) => {
  4624. const s = typeof seed === "function" ? seed() : seed;
  4625. const kp = s ? mod.fromSeed(s) : void 0;
  4626. const nkey = kp ? kp.getPublicKey() : "";
  4627. const challenge = TE.encode(nonce || "");
  4628. const sigBytes = kp !== void 0 && nonce ? kp.sign(challenge) : void 0;
  4629. const sig = sigBytes ? mod.encode(sigBytes) : "";
  4630. return {
  4631. nkey,
  4632. sig
  4633. };
  4634. };
  4635. }
  4636. function jwtAuthenticator(ajwt, seed) {
  4637. return (nonce) => {
  4638. const jwt = typeof ajwt === "function" ? ajwt() : ajwt;
  4639. const fn = nkeyAuthenticator(seed);
  4640. const { nkey, sig } = fn(nonce);
  4641. return {
  4642. jwt,
  4643. nkey,
  4644. sig
  4645. };
  4646. };
  4647. }
  4648. function credsAuthenticator(creds) {
  4649. const fn = typeof creds !== "function" ? () => creds : creds;
  4650. const parse = () => {
  4651. const CREDS = /\s*(?:(?:[-]{3,}[^\n]*[-]{3,}\n)(.+)(?:\n\s*[-]{3,}[^\n]*[-]{3,}\n))/ig;
  4652. const s = TD.decode(fn());
  4653. let m = CREDS.exec(s);
  4654. if (!m) {
  4655. throw NatsError.errorForCode(ErrorCode.BadCreds);
  4656. }
  4657. const jwt = m[1].trim();
  4658. m = CREDS.exec(s);
  4659. if (!m) {
  4660. throw NatsError.errorForCode(ErrorCode.BadCreds);
  4661. }
  4662. if (!m) {
  4663. throw NatsError.errorForCode(ErrorCode.BadCreds);
  4664. }
  4665. const seed = TE.encode(m[1].trim());
  4666. return {
  4667. jwt,
  4668. seed
  4669. };
  4670. };
  4671. const jwtFn = () => {
  4672. const { jwt } = parse();
  4673. return jwt;
  4674. };
  4675. const nkeyFn = () => {
  4676. const { seed } = parse();
  4677. return seed;
  4678. };
  4679. return jwtAuthenticator(jwtFn, nkeyFn);
  4680. }
  4681. var DEFAULT_PING_INTERVAL = 2 * 60 * 1e3;
  4682. var DEFAULT_MAX_PING_OUT = 2;
  4683. var DEFAULT_RECONNECT_TIME_WAIT = 2 * 1e3;
  4684. function defaultOptions() {
  4685. return {
  4686. maxPingOut: 2,
  4687. maxReconnectAttempts: 10,
  4688. noRandomize: false,
  4689. pedantic: false,
  4690. pingInterval: DEFAULT_PING_INTERVAL,
  4691. reconnect: true,
  4692. reconnectJitter: 100,
  4693. reconnectJitterTLS: 1e3,
  4694. reconnectTimeWait: DEFAULT_RECONNECT_TIME_WAIT,
  4695. tls: void 0,
  4696. verbose: false,
  4697. waitOnFirstConnect: false,
  4698. ignoreAuthErrorAbort: false
  4699. };
  4700. }
  4701. function buildAuthenticator(opts) {
  4702. const buf = [];
  4703. if (typeof opts.authenticator === "function") {
  4704. buf.push(opts.authenticator);
  4705. }
  4706. if (Array.isArray(opts.authenticator)) {
  4707. buf.push(...opts.authenticator);
  4708. }
  4709. if (opts.token) {
  4710. buf.push(tokenAuthenticator(opts.token));
  4711. }
  4712. if (opts.user) {
  4713. buf.push(usernamePasswordAuthenticator(opts.user, opts.pass));
  4714. }
  4715. return buf.length === 0 ? noAuthFn() : multiAuthenticator(buf);
  4716. }
  4717. function parseOptions(opts) {
  4718. const dhp = `${DEFAULT_HOST}:${defaultPort()}`;
  4719. opts = opts || {
  4720. servers: [
  4721. dhp
  4722. ]
  4723. };
  4724. opts.servers = opts.servers || [];
  4725. if (typeof opts.servers === "string") {
  4726. opts.servers = [
  4727. opts.servers
  4728. ];
  4729. }
  4730. if (opts.servers.length > 0 && opts.port) {
  4731. throw new NatsError("port and servers options are mutually exclusive", ErrorCode.InvalidOption);
  4732. }
  4733. if (opts.servers.length === 0 && opts.port) {
  4734. opts.servers = [
  4735. `${DEFAULT_HOST}:${opts.port}`
  4736. ];
  4737. }
  4738. if (opts.servers && opts.servers.length === 0) {
  4739. opts.servers = [
  4740. dhp
  4741. ];
  4742. }
  4743. const options = extend(defaultOptions(), opts);
  4744. options.authenticator = buildAuthenticator(options);
  4745. [
  4746. "reconnectDelayHandler",
  4747. "authenticator"
  4748. ].forEach((n) => {
  4749. if (options[n] && typeof options[n] !== "function") {
  4750. throw new NatsError(`${n} option should be a function`, ErrorCode.NotFunction);
  4751. }
  4752. });
  4753. if (!options.reconnectDelayHandler) {
  4754. options.reconnectDelayHandler = () => {
  4755. let extra = options.tls ? options.reconnectJitterTLS : options.reconnectJitter;
  4756. if (extra) {
  4757. extra++;
  4758. extra = Math.floor(Math.random() * extra);
  4759. }
  4760. return options.reconnectTimeWait + extra;
  4761. };
  4762. }
  4763. if (options.inboxPrefix) {
  4764. try {
  4765. createInbox(options.inboxPrefix);
  4766. } catch (err) {
  4767. throw new NatsError(err.message, ErrorCode.ApiError);
  4768. }
  4769. }
  4770. if (options.resolve) {
  4771. if (typeof getResolveFn() !== "function") {
  4772. throw new NatsError(`'resolve' is not supported on this client`, ErrorCode.InvalidOption);
  4773. }
  4774. }
  4775. return options;
  4776. }
  4777. function checkOptions(info, options) {
  4778. const { proto, tls_required: tlsRequired, tls_available: tlsAvailable } = info;
  4779. if ((proto === void 0 || proto < 1) && options.noEcho) {
  4780. throw new NatsError("noEcho", ErrorCode.ServerOptionNotAvailable);
  4781. }
  4782. const tls = tlsRequired || tlsAvailable || false;
  4783. if (options.tls && !tls) {
  4784. throw new NatsError("tls", ErrorCode.ServerOptionNotAvailable);
  4785. }
  4786. }
  4787. var FLUSH_THRESHOLD = 1024 * 32;
  4788. var INFO = /^INFO\s+([^\r\n]+)\r\n/i;
  4789. var PONG_CMD = encode("PONG\r\n");
  4790. var PING_CMD = encode("PING\r\n");
  4791. var Connect = class {
  4792. constructor(transport, opts, nonce) {
  4793. __publicField(this, "echo");
  4794. __publicField(this, "no_responders");
  4795. __publicField(this, "protocol");
  4796. __publicField(this, "verbose");
  4797. __publicField(this, "pedantic");
  4798. __publicField(this, "jwt");
  4799. __publicField(this, "nkey");
  4800. __publicField(this, "sig");
  4801. __publicField(this, "user");
  4802. __publicField(this, "pass");
  4803. __publicField(this, "auth_token");
  4804. __publicField(this, "tls_required");
  4805. __publicField(this, "name");
  4806. __publicField(this, "lang");
  4807. __publicField(this, "version");
  4808. __publicField(this, "headers");
  4809. this.protocol = 1;
  4810. this.version = transport.version;
  4811. this.lang = transport.lang;
  4812. this.echo = opts.noEcho ? false : void 0;
  4813. this.verbose = opts.verbose;
  4814. this.pedantic = opts.pedantic;
  4815. this.tls_required = opts.tls ? true : void 0;
  4816. this.name = opts.name;
  4817. const creds = (opts && typeof opts.authenticator === "function" ? opts.authenticator(nonce) : {}) || {};
  4818. extend(this, creds);
  4819. }
  4820. };
  4821. var SubscriptionImpl = class extends QueuedIteratorImpl {
  4822. constructor(protocol, subject, opts = {}) {
  4823. var _a;
  4824. super();
  4825. __publicField(this, "sid");
  4826. __publicField(this, "queue");
  4827. __publicField(this, "draining");
  4828. __publicField(this, "max");
  4829. __publicField(this, "subject");
  4830. __publicField(this, "drained");
  4831. __publicField(this, "protocol");
  4832. __publicField(this, "timer");
  4833. __publicField(this, "info");
  4834. __publicField(this, "cleanupFn");
  4835. __publicField(this, "closed");
  4836. __publicField(this, "requestSubject");
  4837. extend(this, opts);
  4838. this.protocol = protocol;
  4839. this.subject = subject;
  4840. this.draining = false;
  4841. this.noIterator = typeof opts.callback === "function";
  4842. this.closed = deferred();
  4843. const asyncTraces = !(((_a = protocol.options) == null ? void 0 : _a.noAsyncTraces) || false);
  4844. if (opts.timeout) {
  4845. this.timer = timeout(opts.timeout, asyncTraces);
  4846. this.timer.then(() => {
  4847. this.timer = void 0;
  4848. }).catch((err) => {
  4849. this.stop(err);
  4850. if (this.noIterator) {
  4851. this.callback(err, {});
  4852. }
  4853. });
  4854. }
  4855. if (!this.noIterator) {
  4856. this.iterClosed.then(() => {
  4857. this.closed.resolve();
  4858. this.unsubscribe();
  4859. });
  4860. }
  4861. }
  4862. setPrePostHandlers(opts) {
  4863. if (this.noIterator) {
  4864. const uc = this.callback;
  4865. const ingestion = opts.ingestionFilterFn ? opts.ingestionFilterFn : () => {
  4866. return {
  4867. ingest: true,
  4868. protocol: false
  4869. };
  4870. };
  4871. const filter = opts.protocolFilterFn ? opts.protocolFilterFn : () => {
  4872. return true;
  4873. };
  4874. const dispatched = opts.dispatchedFn ? opts.dispatchedFn : () => {
  4875. };
  4876. this.callback = (err, msg) => {
  4877. const { ingest } = ingestion(msg);
  4878. if (!ingest) {
  4879. return;
  4880. }
  4881. if (filter(msg)) {
  4882. uc(err, msg);
  4883. dispatched(msg);
  4884. }
  4885. };
  4886. } else {
  4887. this.protocolFilterFn = opts.protocolFilterFn;
  4888. this.dispatchedFn = opts.dispatchedFn;
  4889. }
  4890. }
  4891. callback(err, msg) {
  4892. this.cancelTimeout();
  4893. err ? this.stop(err) : this.push(msg);
  4894. }
  4895. close() {
  4896. if (!this.isClosed()) {
  4897. this.cancelTimeout();
  4898. const fn = () => {
  4899. this.stop();
  4900. if (this.cleanupFn) {
  4901. try {
  4902. this.cleanupFn(this, this.info);
  4903. } catch (_err) {
  4904. }
  4905. }
  4906. this.closed.resolve();
  4907. };
  4908. if (this.noIterator) {
  4909. fn();
  4910. } else {
  4911. this.push(fn);
  4912. }
  4913. }
  4914. }
  4915. unsubscribe(max) {
  4916. this.protocol.unsubscribe(this, max);
  4917. }
  4918. cancelTimeout() {
  4919. if (this.timer) {
  4920. this.timer.cancel();
  4921. this.timer = void 0;
  4922. }
  4923. }
  4924. drain() {
  4925. if (this.protocol.isClosed()) {
  4926. return Promise.reject(NatsError.errorForCode(ErrorCode.ConnectionClosed));
  4927. }
  4928. if (this.isClosed()) {
  4929. return Promise.reject(NatsError.errorForCode(ErrorCode.SubClosed));
  4930. }
  4931. if (!this.drained) {
  4932. this.draining = true;
  4933. this.protocol.unsub(this);
  4934. this.drained = this.protocol.flush(deferred()).then(() => {
  4935. this.protocol.subscriptions.cancel(this);
  4936. }).catch(() => {
  4937. this.protocol.subscriptions.cancel(this);
  4938. });
  4939. }
  4940. return this.drained;
  4941. }
  4942. isDraining() {
  4943. return this.draining;
  4944. }
  4945. isClosed() {
  4946. return this.done;
  4947. }
  4948. getSubject() {
  4949. return this.subject;
  4950. }
  4951. getMax() {
  4952. return this.max;
  4953. }
  4954. getID() {
  4955. return this.sid;
  4956. }
  4957. };
  4958. var Subscriptions = class {
  4959. constructor() {
  4960. __publicField(this, "mux");
  4961. __publicField(this, "subs");
  4962. __publicField(this, "sidCounter");
  4963. this.sidCounter = 0;
  4964. this.mux = null;
  4965. this.subs = /* @__PURE__ */ new Map();
  4966. }
  4967. size() {
  4968. return this.subs.size;
  4969. }
  4970. add(s) {
  4971. this.sidCounter++;
  4972. s.sid = this.sidCounter;
  4973. this.subs.set(s.sid, s);
  4974. return s;
  4975. }
  4976. setMux(s) {
  4977. this.mux = s;
  4978. return s;
  4979. }
  4980. getMux() {
  4981. return this.mux;
  4982. }
  4983. get(sid) {
  4984. return this.subs.get(sid);
  4985. }
  4986. resub(s) {
  4987. this.sidCounter++;
  4988. this.subs.delete(s.sid);
  4989. s.sid = this.sidCounter;
  4990. this.subs.set(s.sid, s);
  4991. return s;
  4992. }
  4993. all() {
  4994. return Array.from(this.subs.values());
  4995. }
  4996. cancel(s) {
  4997. if (s) {
  4998. s.close();
  4999. this.subs.delete(s.sid);
  5000. }
  5001. }
  5002. handleError(err) {
  5003. if (err && err.permissionContext) {
  5004. const ctx = err.permissionContext;
  5005. const subs = this.all();
  5006. let sub;
  5007. if (ctx.operation === "subscription") {
  5008. sub = subs.find((s) => {
  5009. return s.subject === ctx.subject;
  5010. });
  5011. }
  5012. if (ctx.operation === "publish") {
  5013. sub = subs.find((s) => {
  5014. return s.requestSubject === ctx.subject;
  5015. });
  5016. }
  5017. if (sub) {
  5018. sub.callback(err, {});
  5019. sub.close();
  5020. this.subs.delete(sub.sid);
  5021. return sub !== this.mux;
  5022. }
  5023. }
  5024. return false;
  5025. }
  5026. close() {
  5027. this.subs.forEach((sub) => {
  5028. sub.close();
  5029. });
  5030. }
  5031. };
  5032. var ProtocolHandler = class {
  5033. constructor(options, publisher) {
  5034. __publicField(this, "connected");
  5035. __publicField(this, "connectedOnce");
  5036. __publicField(this, "infoReceived");
  5037. __publicField(this, "info");
  5038. __publicField(this, "muxSubscriptions");
  5039. __publicField(this, "options");
  5040. __publicField(this, "outbound");
  5041. __publicField(this, "pongs");
  5042. __publicField(this, "subscriptions");
  5043. __publicField(this, "transport");
  5044. __publicField(this, "noMorePublishing");
  5045. __publicField(this, "connectError");
  5046. __publicField(this, "publisher");
  5047. __publicField(this, "_closed");
  5048. __publicField(this, "closed");
  5049. __publicField(this, "listeners");
  5050. __publicField(this, "heartbeats");
  5051. __publicField(this, "parser");
  5052. __publicField(this, "outMsgs");
  5053. __publicField(this, "inMsgs");
  5054. __publicField(this, "outBytes");
  5055. __publicField(this, "inBytes");
  5056. __publicField(this, "pendingLimit");
  5057. __publicField(this, "lastError");
  5058. __publicField(this, "abortReconnect");
  5059. __publicField(this, "servers");
  5060. __publicField(this, "server");
  5061. __publicField(this, "features");
  5062. __publicField(this, "connectPromise");
  5063. this._closed = false;
  5064. this.connected = false;
  5065. this.connectedOnce = false;
  5066. this.infoReceived = false;
  5067. this.noMorePublishing = false;
  5068. this.abortReconnect = false;
  5069. this.listeners = [];
  5070. this.pendingLimit = FLUSH_THRESHOLD;
  5071. this.outMsgs = 0;
  5072. this.inMsgs = 0;
  5073. this.outBytes = 0;
  5074. this.inBytes = 0;
  5075. this.options = options;
  5076. this.publisher = publisher;
  5077. this.subscriptions = new Subscriptions();
  5078. this.muxSubscriptions = new MuxSubscription();
  5079. this.outbound = new DataBuffer();
  5080. this.pongs = [];
  5081. this.pendingLimit = options.pendingLimit || this.pendingLimit;
  5082. this.features = new Features({
  5083. major: 0,
  5084. minor: 0,
  5085. micro: 0
  5086. });
  5087. this.connectPromise = null;
  5088. const servers = typeof options.servers === "string" ? [
  5089. options.servers
  5090. ] : options.servers;
  5091. this.servers = new Servers(servers, {
  5092. randomize: !options.noRandomize
  5093. });
  5094. this.closed = deferred();
  5095. this.parser = new Parser(this);
  5096. this.heartbeats = new Heartbeat(this, this.options.pingInterval || DEFAULT_PING_INTERVAL, this.options.maxPingOut || DEFAULT_MAX_PING_OUT);
  5097. }
  5098. resetOutbound() {
  5099. this.outbound.reset();
  5100. const pongs = this.pongs;
  5101. this.pongs = [];
  5102. const err = NatsError.errorForCode(ErrorCode.Disconnect);
  5103. err.stack = "";
  5104. pongs.forEach((p) => {
  5105. p.reject(err);
  5106. });
  5107. this.parser = new Parser(this);
  5108. this.infoReceived = false;
  5109. }
  5110. dispatchStatus(status) {
  5111. this.listeners.forEach((q) => {
  5112. q.push(status);
  5113. });
  5114. }
  5115. status() {
  5116. const iter = new QueuedIteratorImpl();
  5117. this.listeners.push(iter);
  5118. return iter;
  5119. }
  5120. prepare() {
  5121. if (this.transport) {
  5122. this.transport.discard();
  5123. }
  5124. this.info = void 0;
  5125. this.resetOutbound();
  5126. const pong = deferred();
  5127. pong.catch(() => {
  5128. });
  5129. this.pongs.unshift(pong);
  5130. this.connectError = (err) => {
  5131. pong.reject(err);
  5132. };
  5133. this.transport = newTransport();
  5134. this.transport.closed().then(async (_err) => {
  5135. this.connected = false;
  5136. if (!this.isClosed()) {
  5137. await this.disconnected(this.transport.closeError || this.lastError);
  5138. return;
  5139. }
  5140. });
  5141. return pong;
  5142. }
  5143. disconnect() {
  5144. this.dispatchStatus({
  5145. type: DebugEvents.StaleConnection,
  5146. data: ""
  5147. });
  5148. this.transport.disconnect();
  5149. }
  5150. reconnect() {
  5151. if (this.connected) {
  5152. this.dispatchStatus({
  5153. type: DebugEvents.ClientInitiatedReconnect,
  5154. data: ""
  5155. });
  5156. this.transport.disconnect();
  5157. }
  5158. return Promise.resolve();
  5159. }
  5160. async disconnected(err) {
  5161. this.dispatchStatus({
  5162. type: Events.Disconnect,
  5163. data: this.servers.getCurrentServer().toString()
  5164. });
  5165. if (this.options.reconnect) {
  5166. await this.dialLoop().then(() => {
  5167. var _a;
  5168. this.dispatchStatus({
  5169. type: Events.Reconnect,
  5170. data: this.servers.getCurrentServer().toString()
  5171. });
  5172. if (((_a = this.lastError) == null ? void 0 : _a.code) === ErrorCode.AuthenticationExpired) {
  5173. this.lastError = void 0;
  5174. }
  5175. }).catch((err2) => {
  5176. this._close(err2);
  5177. });
  5178. } else {
  5179. await this._close(err);
  5180. }
  5181. }
  5182. async dial(srv) {
  5183. const pong = this.prepare();
  5184. let timer;
  5185. try {
  5186. timer = timeout(this.options.timeout || 2e4);
  5187. const cp = this.transport.connect(srv, this.options);
  5188. await Promise.race([
  5189. cp,
  5190. timer
  5191. ]);
  5192. (async () => {
  5193. try {
  5194. for await (const b of this.transport) {
  5195. this.parser.parse(b);
  5196. }
  5197. } catch (err) {
  5198. console.log("reader closed", err);
  5199. }
  5200. })().then();
  5201. } catch (err) {
  5202. pong.reject(err);
  5203. }
  5204. try {
  5205. await Promise.race([
  5206. timer,
  5207. pong
  5208. ]);
  5209. if (timer) {
  5210. timer.cancel();
  5211. }
  5212. this.connected = true;
  5213. this.connectError = void 0;
  5214. this.sendSubscriptions();
  5215. this.connectedOnce = true;
  5216. this.server.didConnect = true;
  5217. this.server.reconnects = 0;
  5218. this.flushPending();
  5219. this.heartbeats.start();
  5220. } catch (err) {
  5221. if (timer) {
  5222. timer.cancel();
  5223. }
  5224. await this.transport.close(err);
  5225. throw err;
  5226. }
  5227. }
  5228. async _doDial(srv) {
  5229. const alts = await srv.resolve({
  5230. fn: getResolveFn(),
  5231. debug: this.options.debug,
  5232. randomize: !this.options.noRandomize
  5233. });
  5234. let lastErr = null;
  5235. for (const a of alts) {
  5236. try {
  5237. lastErr = null;
  5238. this.dispatchStatus({
  5239. type: DebugEvents.Reconnecting,
  5240. data: a.toString()
  5241. });
  5242. await this.dial(a);
  5243. return;
  5244. } catch (err) {
  5245. lastErr = err;
  5246. }
  5247. }
  5248. throw lastErr;
  5249. }
  5250. dialLoop() {
  5251. if (this.connectPromise === null) {
  5252. this.connectPromise = this.dodialLoop();
  5253. this.connectPromise.then(() => {
  5254. }).catch(() => {
  5255. }).finally(() => {
  5256. this.connectPromise = null;
  5257. });
  5258. }
  5259. return this.connectPromise;
  5260. }
  5261. async dodialLoop() {
  5262. let lastError;
  5263. while (true) {
  5264. if (this._closed) {
  5265. this.servers.clear();
  5266. }
  5267. const wait = this.options.reconnectDelayHandler ? this.options.reconnectDelayHandler() : DEFAULT_RECONNECT_TIME_WAIT;
  5268. let maxWait = wait;
  5269. const srv = this.selectServer();
  5270. if (!srv || this.abortReconnect) {
  5271. if (lastError) {
  5272. throw lastError;
  5273. } else if (this.lastError) {
  5274. throw this.lastError;
  5275. } else {
  5276. throw NatsError.errorForCode(ErrorCode.ConnectionRefused);
  5277. }
  5278. }
  5279. const now = Date.now();
  5280. if (srv.lastConnect === 0 || srv.lastConnect + wait <= now) {
  5281. srv.lastConnect = Date.now();
  5282. try {
  5283. await this._doDial(srv);
  5284. break;
  5285. } catch (err) {
  5286. lastError = err;
  5287. if (!this.connectedOnce) {
  5288. if (this.options.waitOnFirstConnect) {
  5289. continue;
  5290. }
  5291. this.servers.removeCurrentServer();
  5292. }
  5293. srv.reconnects++;
  5294. const mra = this.options.maxReconnectAttempts || 0;
  5295. if (mra !== -1 && srv.reconnects >= mra) {
  5296. this.servers.removeCurrentServer();
  5297. }
  5298. }
  5299. } else {
  5300. maxWait = Math.min(maxWait, srv.lastConnect + wait - now);
  5301. await delay(maxWait);
  5302. }
  5303. }
  5304. }
  5305. static async connect(options, publisher) {
  5306. const h = new ProtocolHandler(options, publisher);
  5307. await h.dialLoop();
  5308. return h;
  5309. }
  5310. static toError(s) {
  5311. const t = s ? s.toLowerCase() : "";
  5312. if (t.indexOf("permissions violation") !== -1) {
  5313. const err = new NatsError(s, ErrorCode.PermissionsViolation);
  5314. const m = s.match(/(Publish|Subscription) to "(\S+)"/);
  5315. if (m) {
  5316. err.permissionContext = {
  5317. operation: m[1].toLowerCase(),
  5318. subject: m[2]
  5319. };
  5320. }
  5321. return err;
  5322. } else if (t.indexOf("authorization violation") !== -1) {
  5323. return new NatsError(s, ErrorCode.AuthorizationViolation);
  5324. } else if (t.indexOf("user authentication expired") !== -1) {
  5325. return new NatsError(s, ErrorCode.AuthenticationExpired);
  5326. } else if (t.indexOf("authentication timeout") !== -1) {
  5327. return new NatsError(s, ErrorCode.AuthenticationTimeout);
  5328. } else {
  5329. return new NatsError(s, ErrorCode.ProtocolError);
  5330. }
  5331. }
  5332. processMsg(msg, data) {
  5333. this.inMsgs++;
  5334. this.inBytes += data.length;
  5335. if (!this.subscriptions.sidCounter) {
  5336. return;
  5337. }
  5338. const sub = this.subscriptions.get(msg.sid);
  5339. if (!sub) {
  5340. return;
  5341. }
  5342. sub.received += 1;
  5343. if (sub.callback) {
  5344. sub.callback(null, new MsgImpl(msg, data, this));
  5345. }
  5346. if (sub.max !== void 0 && sub.received >= sub.max) {
  5347. sub.unsubscribe();
  5348. }
  5349. }
  5350. processError(m) {
  5351. const s = decode(m);
  5352. const err = ProtocolHandler.toError(s);
  5353. const status = {
  5354. type: Events.Error,
  5355. data: err.code
  5356. };
  5357. if (err.isPermissionError()) {
  5358. let isMuxPermissionError = false;
  5359. if (err.permissionContext) {
  5360. status.permissionContext = err.permissionContext;
  5361. const mux = this.subscriptions.getMux();
  5362. isMuxPermissionError = (mux == null ? void 0 : mux.subject) === err.permissionContext.subject;
  5363. }
  5364. this.subscriptions.handleError(err);
  5365. this.muxSubscriptions.handleError(isMuxPermissionError, err);
  5366. if (isMuxPermissionError) {
  5367. this.subscriptions.setMux(null);
  5368. }
  5369. }
  5370. this.dispatchStatus(status);
  5371. this.handleError(err);
  5372. }
  5373. handleError(err) {
  5374. if (err.isAuthError()) {
  5375. this.handleAuthError(err);
  5376. } else if (err.isProtocolError()) {
  5377. this.lastError = err;
  5378. } else if (err.isAuthTimeout()) {
  5379. this.lastError = err;
  5380. }
  5381. if (!err.isPermissionError()) {
  5382. this.lastError = err;
  5383. }
  5384. }
  5385. handleAuthError(err) {
  5386. if (this.lastError && err.code === this.lastError.code && this.options.ignoreAuthErrorAbort === false) {
  5387. this.abortReconnect = true;
  5388. }
  5389. if (this.connectError) {
  5390. this.connectError(err);
  5391. } else {
  5392. this.disconnect();
  5393. }
  5394. }
  5395. processPing() {
  5396. this.transport.send(PONG_CMD);
  5397. }
  5398. processPong() {
  5399. const cb = this.pongs.shift();
  5400. if (cb) {
  5401. cb.resolve();
  5402. }
  5403. }
  5404. processInfo(m) {
  5405. const info = JSON.parse(decode(m));
  5406. this.info = info;
  5407. const updates = this.options && this.options.ignoreClusterUpdates ? void 0 : this.servers.update(info);
  5408. if (!this.infoReceived) {
  5409. this.features.update(parseSemVer(info.version));
  5410. this.infoReceived = true;
  5411. if (this.transport.isEncrypted()) {
  5412. this.servers.updateTLSName();
  5413. }
  5414. const { version, lang } = this.transport;
  5415. try {
  5416. const c = new Connect({
  5417. version,
  5418. lang
  5419. }, this.options, info.nonce);
  5420. if (info.headers) {
  5421. c.headers = true;
  5422. c.no_responders = true;
  5423. }
  5424. const cs = JSON.stringify(c);
  5425. this.transport.send(encode(`CONNECT ${cs}${CR_LF}`));
  5426. this.transport.send(PING_CMD);
  5427. } catch (err) {
  5428. this._close(err);
  5429. }
  5430. }
  5431. if (updates) {
  5432. this.dispatchStatus({
  5433. type: Events.Update,
  5434. data: updates
  5435. });
  5436. }
  5437. const ldm = info.ldm !== void 0 ? info.ldm : false;
  5438. if (ldm) {
  5439. this.dispatchStatus({
  5440. type: Events.LDM,
  5441. data: this.servers.getCurrentServer().toString()
  5442. });
  5443. }
  5444. }
  5445. push(e) {
  5446. switch (e.kind) {
  5447. case Kind.MSG: {
  5448. const { msg, data } = e;
  5449. this.processMsg(msg, data);
  5450. break;
  5451. }
  5452. case Kind.OK:
  5453. break;
  5454. case Kind.ERR:
  5455. this.processError(e.data);
  5456. break;
  5457. case Kind.PING:
  5458. this.processPing();
  5459. break;
  5460. case Kind.PONG:
  5461. this.processPong();
  5462. break;
  5463. case Kind.INFO:
  5464. this.processInfo(e.data);
  5465. break;
  5466. }
  5467. }
  5468. sendCommand(cmd, ...payloads) {
  5469. const len = this.outbound.length();
  5470. let buf;
  5471. if (typeof cmd === "string") {
  5472. buf = encode(cmd);
  5473. } else {
  5474. buf = cmd;
  5475. }
  5476. this.outbound.fill(buf, ...payloads);
  5477. if (len === 0) {
  5478. queueMicrotask(() => {
  5479. this.flushPending();
  5480. });
  5481. } else if (this.outbound.size() >= this.pendingLimit) {
  5482. this.flushPending();
  5483. }
  5484. }
  5485. publish(subject, payload = Empty, options) {
  5486. let data;
  5487. if (payload instanceof Uint8Array) {
  5488. data = payload;
  5489. } else if (typeof payload === "string") {
  5490. data = TE.encode(payload);
  5491. } else {
  5492. throw NatsError.errorForCode(ErrorCode.BadPayload);
  5493. }
  5494. let len = data.length;
  5495. options = options || {};
  5496. options.reply = options.reply || "";
  5497. let headers2 = Empty;
  5498. let hlen = 0;
  5499. if (options.headers) {
  5500. if (this.info && !this.info.headers) {
  5501. throw new NatsError("headers", ErrorCode.ServerOptionNotAvailable);
  5502. }
  5503. const hdrs = options.headers;
  5504. headers2 = hdrs.encode();
  5505. hlen = headers2.length;
  5506. len = data.length + hlen;
  5507. }
  5508. if (this.info && len > this.info.max_payload) {
  5509. throw NatsError.errorForCode(ErrorCode.MaxPayloadExceeded);
  5510. }
  5511. this.outBytes += len;
  5512. this.outMsgs++;
  5513. let proto;
  5514. if (options.headers) {
  5515. if (options.reply) {
  5516. proto = `HPUB ${subject} ${options.reply} ${hlen} ${len}\r
  5517. `;
  5518. } else {
  5519. proto = `HPUB ${subject} ${hlen} ${len}\r
  5520. `;
  5521. }
  5522. this.sendCommand(proto, headers2, data, CRLF);
  5523. } else {
  5524. if (options.reply) {
  5525. proto = `PUB ${subject} ${options.reply} ${len}\r
  5526. `;
  5527. } else {
  5528. proto = `PUB ${subject} ${len}\r
  5529. `;
  5530. }
  5531. this.sendCommand(proto, data, CRLF);
  5532. }
  5533. }
  5534. request(r) {
  5535. this.initMux();
  5536. this.muxSubscriptions.add(r);
  5537. return r;
  5538. }
  5539. subscribe(s) {
  5540. this.subscriptions.add(s);
  5541. this._subunsub(s);
  5542. return s;
  5543. }
  5544. _sub(s) {
  5545. if (s.queue) {
  5546. this.sendCommand(`SUB ${s.subject} ${s.queue} ${s.sid}\r
  5547. `);
  5548. } else {
  5549. this.sendCommand(`SUB ${s.subject} ${s.sid}\r
  5550. `);
  5551. }
  5552. }
  5553. _subunsub(s) {
  5554. this._sub(s);
  5555. if (s.max) {
  5556. this.unsubscribe(s, s.max);
  5557. }
  5558. return s;
  5559. }
  5560. unsubscribe(s, max) {
  5561. this.unsub(s, max);
  5562. if (s.max === void 0 || s.received >= s.max) {
  5563. this.subscriptions.cancel(s);
  5564. }
  5565. }
  5566. unsub(s, max) {
  5567. if (!s || this.isClosed()) {
  5568. return;
  5569. }
  5570. if (max) {
  5571. this.sendCommand(`UNSUB ${s.sid} ${max}\r
  5572. `);
  5573. } else {
  5574. this.sendCommand(`UNSUB ${s.sid}\r
  5575. `);
  5576. }
  5577. s.max = max;
  5578. }
  5579. resub(s, subject) {
  5580. if (!s || this.isClosed()) {
  5581. return;
  5582. }
  5583. s.subject = subject;
  5584. this.subscriptions.resub(s);
  5585. this._sub(s);
  5586. }
  5587. flush(p) {
  5588. if (!p) {
  5589. p = deferred();
  5590. }
  5591. this.pongs.push(p);
  5592. this.outbound.fill(PING_CMD);
  5593. this.flushPending();
  5594. return p;
  5595. }
  5596. sendSubscriptions() {
  5597. const cmds = [];
  5598. this.subscriptions.all().forEach((s) => {
  5599. const sub = s;
  5600. if (sub.queue) {
  5601. cmds.push(`SUB ${sub.subject} ${sub.queue} ${sub.sid}${CR_LF}`);
  5602. } else {
  5603. cmds.push(`SUB ${sub.subject} ${sub.sid}${CR_LF}`);
  5604. }
  5605. });
  5606. if (cmds.length) {
  5607. this.transport.send(encode(cmds.join("")));
  5608. }
  5609. }
  5610. async _close(err) {
  5611. if (this._closed) {
  5612. return;
  5613. }
  5614. this.heartbeats.cancel();
  5615. if (this.connectError) {
  5616. this.connectError(err);
  5617. this.connectError = void 0;
  5618. }
  5619. this.muxSubscriptions.close();
  5620. this.subscriptions.close();
  5621. this.listeners.forEach((l) => {
  5622. l.stop();
  5623. });
  5624. this._closed = true;
  5625. await this.transport.close(err);
  5626. await this.closed.resolve(err);
  5627. }
  5628. close() {
  5629. return this._close();
  5630. }
  5631. isClosed() {
  5632. return this._closed;
  5633. }
  5634. drain() {
  5635. const subs = this.subscriptions.all();
  5636. const promises = [];
  5637. subs.forEach((sub) => {
  5638. promises.push(sub.drain());
  5639. });
  5640. return Promise.all(promises).then(async () => {
  5641. this.noMorePublishing = true;
  5642. await this.flush();
  5643. return this.close();
  5644. }).catch(() => {
  5645. });
  5646. }
  5647. flushPending() {
  5648. if (!this.infoReceived || !this.connected) {
  5649. return;
  5650. }
  5651. if (this.outbound.size()) {
  5652. const d = this.outbound.drain();
  5653. this.transport.send(d);
  5654. }
  5655. }
  5656. initMux() {
  5657. const mux = this.subscriptions.getMux();
  5658. if (!mux) {
  5659. const inbox = this.muxSubscriptions.init(this.options.inboxPrefix);
  5660. const sub = new SubscriptionImpl(this, `${inbox}*`);
  5661. sub.callback = this.muxSubscriptions.dispatcher();
  5662. this.subscriptions.setMux(sub);
  5663. this.subscribe(sub);
  5664. }
  5665. }
  5666. selectServer() {
  5667. const server = this.servers.selectServer();
  5668. if (server === void 0) {
  5669. return void 0;
  5670. }
  5671. this.server = server;
  5672. return this.server;
  5673. }
  5674. getServer() {
  5675. return this.server;
  5676. }
  5677. };
  5678. var BaseRequest = class {
  5679. constructor(mux, requestSubject, asyncTraces = true) {
  5680. __publicField(this, "token");
  5681. __publicField(this, "received");
  5682. __publicField(this, "ctx");
  5683. __publicField(this, "requestSubject");
  5684. __publicField(this, "mux");
  5685. this.mux = mux;
  5686. this.requestSubject = requestSubject;
  5687. this.received = 0;
  5688. this.token = nuid.next();
  5689. if (asyncTraces) {
  5690. this.ctx = new Error();
  5691. }
  5692. }
  5693. };
  5694. var RequestMany = class extends BaseRequest {
  5695. constructor(mux, requestSubject, opts = {
  5696. maxWait: 1e3
  5697. }) {
  5698. super(mux, requestSubject);
  5699. __publicField(this, "callback");
  5700. __publicField(this, "done");
  5701. __publicField(this, "timer");
  5702. __publicField(this, "max");
  5703. __publicField(this, "opts");
  5704. this.opts = opts;
  5705. if (typeof this.opts.callback !== "function") {
  5706. throw new Error("callback is required");
  5707. }
  5708. this.callback = this.opts.callback;
  5709. this.max = typeof opts.maxMessages === "number" && opts.maxMessages > 0 ? opts.maxMessages : -1;
  5710. this.done = deferred();
  5711. this.done.then(() => {
  5712. this.callback(null, null);
  5713. });
  5714. this.timer = setTimeout(() => {
  5715. this.cancel();
  5716. }, opts.maxWait);
  5717. }
  5718. cancel(err) {
  5719. if (err) {
  5720. this.callback(err, null);
  5721. }
  5722. clearTimeout(this.timer);
  5723. this.mux.cancel(this);
  5724. this.done.resolve();
  5725. }
  5726. resolver(err, msg) {
  5727. if (err) {
  5728. if (this.ctx) {
  5729. err.stack += `
  5730. ${this.ctx.stack}`;
  5731. }
  5732. this.cancel(err);
  5733. } else {
  5734. this.callback(null, msg);
  5735. if (this.opts.strategy === RequestStrategy.Count) {
  5736. this.max--;
  5737. if (this.max === 0) {
  5738. this.cancel();
  5739. }
  5740. }
  5741. if (this.opts.strategy === RequestStrategy.JitterTimer) {
  5742. clearTimeout(this.timer);
  5743. this.timer = setTimeout(() => {
  5744. this.cancel();
  5745. }, this.opts.jitter || 300);
  5746. }
  5747. if (this.opts.strategy === RequestStrategy.SentinelMsg) {
  5748. if (msg && msg.data.length === 0) {
  5749. this.cancel();
  5750. }
  5751. }
  5752. }
  5753. }
  5754. };
  5755. var RequestOne = class extends BaseRequest {
  5756. constructor(mux, requestSubject, opts = {
  5757. timeout: 1e3
  5758. }, asyncTraces = true) {
  5759. super(mux, requestSubject, asyncTraces);
  5760. __publicField(this, "deferred");
  5761. __publicField(this, "timer");
  5762. this.deferred = deferred();
  5763. this.timer = timeout(opts.timeout, asyncTraces);
  5764. }
  5765. resolver(err, msg) {
  5766. if (this.timer) {
  5767. this.timer.cancel();
  5768. }
  5769. if (err) {
  5770. if (this.ctx) {
  5771. err.stack += `
  5772. ${this.ctx.stack}`;
  5773. }
  5774. this.deferred.reject(err);
  5775. } else {
  5776. this.deferred.resolve(msg);
  5777. }
  5778. this.cancel();
  5779. }
  5780. cancel(err) {
  5781. if (this.timer) {
  5782. this.timer.cancel();
  5783. }
  5784. this.mux.cancel(this);
  5785. this.deferred.reject(err ? err : NatsError.errorForCode(ErrorCode.Cancelled));
  5786. }
  5787. };
  5788. function validateDurableName(name) {
  5789. return minValidation("durable", name);
  5790. }
  5791. function validateStreamName(name) {
  5792. return minValidation("stream", name);
  5793. }
  5794. function minValidation(context, name = "") {
  5795. if (name === "") {
  5796. throw Error(`${context} name required`);
  5797. }
  5798. const bad = [
  5799. ".",
  5800. "*",
  5801. ">",
  5802. "/",
  5803. "\\",
  5804. " ",
  5805. " ",
  5806. "\n",
  5807. "\r"
  5808. ];
  5809. bad.forEach((v) => {
  5810. if (name.indexOf(v) !== -1) {
  5811. switch (v) {
  5812. case "\n":
  5813. v = "\\n";
  5814. break;
  5815. case "\r":
  5816. v = "\\r";
  5817. break;
  5818. case " ":
  5819. v = "\\t";
  5820. break;
  5821. default:
  5822. }
  5823. throw Error(`invalid ${context} name - ${context} name cannot contain '${v}'`);
  5824. }
  5825. });
  5826. return "";
  5827. }
  5828. function validateName(context, name = "") {
  5829. if (name === "") {
  5830. throw Error(`${context} name required`);
  5831. }
  5832. const m = validName(name);
  5833. if (m.length) {
  5834. throw new Error(`invalid ${context} name - ${context} name ${m}`);
  5835. }
  5836. }
  5837. function validName(name = "") {
  5838. if (name === "") {
  5839. throw Error(`name required`);
  5840. }
  5841. const RE = /^[-\w]+$/g;
  5842. const m = name.match(RE);
  5843. if (m === null) {
  5844. for (const c of name.split("")) {
  5845. const mm = c.match(RE);
  5846. if (mm === null) {
  5847. return `cannot contain '${c}'`;
  5848. }
  5849. }
  5850. }
  5851. return "";
  5852. }
  5853. function nanos(millis2) {
  5854. return millis2 * 1e6;
  5855. }
  5856. function millis(ns) {
  5857. return Math.floor(ns / 1e6);
  5858. }
  5859. function isFlowControlMsg(msg) {
  5860. if (msg.data.length > 0) {
  5861. return false;
  5862. }
  5863. const h = msg.headers;
  5864. if (!h) {
  5865. return false;
  5866. }
  5867. return h.code >= 100 && h.code < 200;
  5868. }
  5869. function isHeartbeatMsg(msg) {
  5870. var _a;
  5871. return isFlowControlMsg(msg) && ((_a = msg.headers) == null ? void 0 : _a.description) === "Idle Heartbeat";
  5872. }
  5873. function newJsErrorMsg(code2, description, subject) {
  5874. const h = headers(code2, description);
  5875. const arg = {
  5876. hdr: 1,
  5877. sid: 0,
  5878. size: 0
  5879. };
  5880. const msg = new MsgImpl(arg, Empty, {});
  5881. msg._headers = h;
  5882. msg._subject = subject;
  5883. return msg;
  5884. }
  5885. function checkJsError(msg) {
  5886. if (msg.data.length !== 0) {
  5887. return null;
  5888. }
  5889. const h = msg.headers;
  5890. if (!h) {
  5891. return null;
  5892. }
  5893. return checkJsErrorCode(h.code, h.description);
  5894. }
  5895. var Js409Errors;
  5896. (function(Js409Errors2) {
  5897. Js409Errors2["MaxBatchExceeded"] = "exceeded maxrequestbatch of";
  5898. Js409Errors2["MaxExpiresExceeded"] = "exceeded maxrequestexpires of";
  5899. Js409Errors2["MaxBytesExceeded"] = "exceeded maxrequestmaxbytes of";
  5900. Js409Errors2["MaxMessageSizeExceeded"] = "message size exceeds maxbytes";
  5901. Js409Errors2["PushConsumer"] = "consumer is push based";
  5902. Js409Errors2["MaxWaitingExceeded"] = "exceeded maxwaiting";
  5903. Js409Errors2["IdleHeartbeatMissed"] = "idle heartbeats missed";
  5904. Js409Errors2["ConsumerDeleted"] = "consumer deleted";
  5905. })(Js409Errors || (Js409Errors = {}));
  5906. var MAX_WAITING_FAIL = false;
  5907. function isTerminal409(err) {
  5908. if (err.code !== ErrorCode.JetStream409) {
  5909. return false;
  5910. }
  5911. const fatal = [
  5912. Js409Errors.MaxBatchExceeded,
  5913. Js409Errors.MaxExpiresExceeded,
  5914. Js409Errors.MaxBytesExceeded,
  5915. Js409Errors.MaxMessageSizeExceeded,
  5916. Js409Errors.PushConsumer,
  5917. Js409Errors.IdleHeartbeatMissed,
  5918. Js409Errors.ConsumerDeleted
  5919. ];
  5920. if (MAX_WAITING_FAIL) {
  5921. fatal.push(Js409Errors.MaxWaitingExceeded);
  5922. }
  5923. return fatal.find((s) => {
  5924. return err.message.indexOf(s) !== -1;
  5925. }) !== void 0;
  5926. }
  5927. function checkJsErrorCode(code2, description = "") {
  5928. if (code2 < 300) {
  5929. return null;
  5930. }
  5931. description = description.toLowerCase();
  5932. switch (code2) {
  5933. case 404:
  5934. return new NatsError(description, ErrorCode.JetStream404NoMessages);
  5935. case 408:
  5936. return new NatsError(description, ErrorCode.JetStream408RequestTimeout);
  5937. case 409: {
  5938. const ec = description.startsWith(Js409Errors.IdleHeartbeatMissed) ? ErrorCode.JetStreamIdleHeartBeat : ErrorCode.JetStream409;
  5939. return new NatsError(description, ec);
  5940. }
  5941. case 503:
  5942. return NatsError.errorForCode(ErrorCode.JetStreamNotEnabled, new Error(description));
  5943. default:
  5944. if (description === "") {
  5945. description = ErrorCode.Unknown;
  5946. }
  5947. return new NatsError(description, `${code2}`);
  5948. }
  5949. }
  5950. var defaultPrefix = "$JS.API";
  5951. function defaultJsOptions(opts) {
  5952. opts = opts || {};
  5953. if (opts.domain) {
  5954. opts.apiPrefix = `$JS.${opts.domain}.API`;
  5955. delete opts.domain;
  5956. }
  5957. return extend({
  5958. apiPrefix: defaultPrefix,
  5959. timeout: 5e3
  5960. }, opts);
  5961. }
  5962. var BaseApiClient = class {
  5963. constructor(nc, opts) {
  5964. __publicField(this, "nc");
  5965. __publicField(this, "opts");
  5966. __publicField(this, "prefix");
  5967. __publicField(this, "timeout");
  5968. __publicField(this, "jc");
  5969. this.nc = nc;
  5970. this.opts = defaultJsOptions(opts);
  5971. this._parseOpts();
  5972. this.prefix = this.opts.apiPrefix;
  5973. this.timeout = this.opts.timeout;
  5974. this.jc = JSONCodec();
  5975. }
  5976. getOptions() {
  5977. return Object.assign({}, this.opts);
  5978. }
  5979. _parseOpts() {
  5980. let prefix = this.opts.apiPrefix;
  5981. if (!prefix || prefix.length === 0) {
  5982. throw new Error("invalid empty prefix");
  5983. }
  5984. const c = prefix[prefix.length - 1];
  5985. if (c === ".") {
  5986. prefix = prefix.substr(0, prefix.length - 1);
  5987. }
  5988. this.opts.apiPrefix = prefix;
  5989. }
  5990. async _request(subj, data = null, opts) {
  5991. opts = opts || {};
  5992. opts.timeout = this.timeout;
  5993. let a = Empty;
  5994. if (data) {
  5995. a = this.jc.encode(data);
  5996. }
  5997. const m = await this.nc.request(subj, a, opts);
  5998. return this.parseJsResponse(m);
  5999. }
  6000. async findStream(subject) {
  6001. const q = {
  6002. subject
  6003. };
  6004. const r = await this._request(`${this.prefix}.STREAM.NAMES`, q);
  6005. const names = r;
  6006. if (!names.streams || names.streams.length !== 1) {
  6007. throw new Error("no stream matches subject");
  6008. }
  6009. return names.streams[0];
  6010. }
  6011. getConnection() {
  6012. return this.nc;
  6013. }
  6014. parseJsResponse(m) {
  6015. const v = this.jc.decode(m.data);
  6016. const r = v;
  6017. if (r.error) {
  6018. const err = checkJsErrorCode(r.error.code, r.error.description);
  6019. if (err !== null) {
  6020. err.api_error = r.error;
  6021. throw err;
  6022. }
  6023. }
  6024. return v;
  6025. }
  6026. };
  6027. var Base64Codec = class {
  6028. static encode(bytes) {
  6029. if (typeof bytes === "string") {
  6030. return btoa(bytes);
  6031. }
  6032. const a = Array.from(bytes);
  6033. return btoa(String.fromCharCode(...a));
  6034. }
  6035. static decode(s, binary = false) {
  6036. const bin = atob(s);
  6037. if (!binary) {
  6038. return bin;
  6039. }
  6040. return Uint8Array.from(bin, (c) => c.charCodeAt(0));
  6041. }
  6042. };
  6043. var Base64UrlPaddedCodec = class {
  6044. static encode(bytes) {
  6045. return Base64UrlPaddedCodec.toB64URLEncoding(Base64Codec.encode(bytes));
  6046. }
  6047. static decode(s, binary = false) {
  6048. return Base64UrlPaddedCodec.decode(Base64UrlPaddedCodec.fromB64URLEncoding(s), binary);
  6049. }
  6050. static toB64URLEncoding(b64str) {
  6051. return b64str.replace(/\+/g, "-").replace(/\//g, "_");
  6052. }
  6053. static fromB64URLEncoding(b64str) {
  6054. return b64str.replace(/_/g, "/").replace(/-/g, "+");
  6055. }
  6056. };
  6057. var RetentionPolicy;
  6058. (function(RetentionPolicy2) {
  6059. RetentionPolicy2["Limits"] = "limits";
  6060. RetentionPolicy2["Interest"] = "interest";
  6061. RetentionPolicy2["Workqueue"] = "workqueue";
  6062. })(RetentionPolicy || (RetentionPolicy = {}));
  6063. var DiscardPolicy;
  6064. (function(DiscardPolicy2) {
  6065. DiscardPolicy2["Old"] = "old";
  6066. DiscardPolicy2["New"] = "new";
  6067. })(DiscardPolicy || (DiscardPolicy = {}));
  6068. var StorageType;
  6069. (function(StorageType2) {
  6070. StorageType2["File"] = "file";
  6071. StorageType2["Memory"] = "memory";
  6072. })(StorageType || (StorageType = {}));
  6073. var DeliverPolicy;
  6074. (function(DeliverPolicy2) {
  6075. DeliverPolicy2["All"] = "all";
  6076. DeliverPolicy2["Last"] = "last";
  6077. DeliverPolicy2["New"] = "new";
  6078. DeliverPolicy2["StartSequence"] = "by_start_sequence";
  6079. DeliverPolicy2["StartTime"] = "by_start_time";
  6080. DeliverPolicy2["LastPerSubject"] = "last_per_subject";
  6081. })(DeliverPolicy || (DeliverPolicy = {}));
  6082. var AckPolicy;
  6083. (function(AckPolicy2) {
  6084. AckPolicy2["None"] = "none";
  6085. AckPolicy2["All"] = "all";
  6086. AckPolicy2["Explicit"] = "explicit";
  6087. AckPolicy2["NotSet"] = "";
  6088. })(AckPolicy || (AckPolicy = {}));
  6089. var ReplayPolicy;
  6090. (function(ReplayPolicy2) {
  6091. ReplayPolicy2["Instant"] = "instant";
  6092. ReplayPolicy2["Original"] = "original";
  6093. })(ReplayPolicy || (ReplayPolicy = {}));
  6094. var StoreCompression;
  6095. (function(StoreCompression2) {
  6096. StoreCompression2["None"] = "none";
  6097. StoreCompression2["S2"] = "s2";
  6098. })(StoreCompression || (StoreCompression = {}));
  6099. var ConsumerApiAction;
  6100. (function(ConsumerApiAction2) {
  6101. ConsumerApiAction2["CreateOrUpdate"] = "";
  6102. ConsumerApiAction2["Update"] = "update";
  6103. ConsumerApiAction2["Create"] = "create";
  6104. })(ConsumerApiAction || (ConsumerApiAction = {}));
  6105. function defaultConsumer(name, opts = {}) {
  6106. return Object.assign({
  6107. name,
  6108. deliver_policy: DeliverPolicy.All,
  6109. ack_policy: AckPolicy.Explicit,
  6110. ack_wait: nanos(30 * 1e3),
  6111. replay_policy: ReplayPolicy.Instant
  6112. }, opts);
  6113. }
  6114. var AdvisoryKind;
  6115. (function(AdvisoryKind2) {
  6116. AdvisoryKind2["API"] = "api_audit";
  6117. AdvisoryKind2["StreamAction"] = "stream_action";
  6118. AdvisoryKind2["ConsumerAction"] = "consumer_action";
  6119. AdvisoryKind2["SnapshotCreate"] = "snapshot_create";
  6120. AdvisoryKind2["SnapshotComplete"] = "snapshot_complete";
  6121. AdvisoryKind2["RestoreCreate"] = "restore_create";
  6122. AdvisoryKind2["RestoreComplete"] = "restore_complete";
  6123. AdvisoryKind2["MaxDeliver"] = "max_deliver";
  6124. AdvisoryKind2["Terminated"] = "terminated";
  6125. AdvisoryKind2["Ack"] = "consumer_ack";
  6126. AdvisoryKind2["StreamLeaderElected"] = "stream_leader_elected";
  6127. AdvisoryKind2["StreamQuorumLost"] = "stream_quorum_lost";
  6128. AdvisoryKind2["ConsumerLeaderElected"] = "consumer_leader_elected";
  6129. AdvisoryKind2["ConsumerQuorumLost"] = "consumer_quorum_lost";
  6130. })(AdvisoryKind || (AdvisoryKind = {}));
  6131. var JsHeaders;
  6132. (function(JsHeaders2) {
  6133. JsHeaders2["StreamSourceHdr"] = "Nats-Stream-Source";
  6134. JsHeaders2["LastConsumerSeqHdr"] = "Nats-Last-Consumer";
  6135. JsHeaders2["LastStreamSeqHdr"] = "Nats-Last-Stream";
  6136. JsHeaders2["ConsumerStalledHdr"] = "Nats-Consumer-Stalled";
  6137. JsHeaders2["MessageSizeHdr"] = "Nats-Msg-Size";
  6138. JsHeaders2["RollupHdr"] = "Nats-Rollup";
  6139. JsHeaders2["RollupValueSubject"] = "sub";
  6140. JsHeaders2["RollupValueAll"] = "all";
  6141. JsHeaders2["PendingMessagesHdr"] = "Nats-Pending-Messages";
  6142. JsHeaders2["PendingBytesHdr"] = "Nats-Pending-Bytes";
  6143. })(JsHeaders || (JsHeaders = {}));
  6144. var KvWatchInclude;
  6145. (function(KvWatchInclude2) {
  6146. KvWatchInclude2["LastValue"] = "";
  6147. KvWatchInclude2["AllHistory"] = "history";
  6148. KvWatchInclude2["UpdatesOnly"] = "updates";
  6149. })(KvWatchInclude || (KvWatchInclude = {}));
  6150. var DirectMsgHeaders;
  6151. (function(DirectMsgHeaders2) {
  6152. DirectMsgHeaders2["Stream"] = "Nats-Stream";
  6153. DirectMsgHeaders2["Sequence"] = "Nats-Sequence";
  6154. DirectMsgHeaders2["TimeStamp"] = "Nats-Time-Stamp";
  6155. DirectMsgHeaders2["Subject"] = "Nats-Subject";
  6156. })(DirectMsgHeaders || (DirectMsgHeaders = {}));
  6157. var RepublishHeaders;
  6158. (function(RepublishHeaders2) {
  6159. RepublishHeaders2["Stream"] = "Nats-Stream";
  6160. RepublishHeaders2["Subject"] = "Nats-Subject";
  6161. RepublishHeaders2["Sequence"] = "Nats-Sequence";
  6162. RepublishHeaders2["LastSequence"] = "Nats-Last-Sequence";
  6163. RepublishHeaders2["Size"] = "Nats-Msg-Size";
  6164. })(RepublishHeaders || (RepublishHeaders = {}));
  6165. var kvPrefix = "KV_";
  6166. var ConsumerOptsBuilderImpl = class {
  6167. constructor(opts) {
  6168. __publicField(this, "config");
  6169. __publicField(this, "ordered");
  6170. __publicField(this, "mack");
  6171. __publicField(this, "stream");
  6172. __publicField(this, "callbackFn");
  6173. __publicField(this, "max");
  6174. __publicField(this, "qname");
  6175. __publicField(this, "isBind");
  6176. __publicField(this, "filters");
  6177. this.stream = "";
  6178. this.mack = false;
  6179. this.ordered = false;
  6180. this.config = defaultConsumer("", opts || {});
  6181. }
  6182. getOpts() {
  6183. var _a;
  6184. const o = {};
  6185. o.config = Object.assign({}, this.config);
  6186. if (o.config.filter_subject) {
  6187. this.filterSubject(o.config.filter_subject);
  6188. o.config.filter_subject = void 0;
  6189. }
  6190. if (o.config.filter_subjects) {
  6191. (_a = o.config.filter_subjects) == null ? void 0 : _a.forEach((v) => {
  6192. this.filterSubject(v);
  6193. });
  6194. o.config.filter_subjects = void 0;
  6195. }
  6196. o.mack = this.mack;
  6197. o.stream = this.stream;
  6198. o.callbackFn = this.callbackFn;
  6199. o.max = this.max;
  6200. o.queue = this.qname;
  6201. o.ordered = this.ordered;
  6202. o.config.ack_policy = o.ordered ? AckPolicy.None : o.config.ack_policy;
  6203. o.isBind = o.isBind || false;
  6204. if (this.filters) {
  6205. switch (this.filters.length) {
  6206. case 0:
  6207. break;
  6208. case 1:
  6209. o.config.filter_subject = this.filters[0];
  6210. break;
  6211. default:
  6212. o.config.filter_subjects = this.filters;
  6213. }
  6214. }
  6215. return o;
  6216. }
  6217. description(description) {
  6218. this.config.description = description;
  6219. return this;
  6220. }
  6221. deliverTo(subject) {
  6222. this.config.deliver_subject = subject;
  6223. return this;
  6224. }
  6225. durable(name) {
  6226. validateDurableName(name);
  6227. this.config.durable_name = name;
  6228. return this;
  6229. }
  6230. startSequence(seq) {
  6231. if (seq <= 0) {
  6232. throw new Error("sequence must be greater than 0");
  6233. }
  6234. this.config.deliver_policy = DeliverPolicy.StartSequence;
  6235. this.config.opt_start_seq = seq;
  6236. return this;
  6237. }
  6238. startTime(time) {
  6239. this.config.deliver_policy = DeliverPolicy.StartTime;
  6240. this.config.opt_start_time = time.toISOString();
  6241. return this;
  6242. }
  6243. deliverAll() {
  6244. this.config.deliver_policy = DeliverPolicy.All;
  6245. return this;
  6246. }
  6247. deliverLastPerSubject() {
  6248. this.config.deliver_policy = DeliverPolicy.LastPerSubject;
  6249. return this;
  6250. }
  6251. deliverLast() {
  6252. this.config.deliver_policy = DeliverPolicy.Last;
  6253. return this;
  6254. }
  6255. deliverNew() {
  6256. this.config.deliver_policy = DeliverPolicy.New;
  6257. return this;
  6258. }
  6259. startAtTimeDelta(millis2) {
  6260. this.startTime(new Date(Date.now() - millis2));
  6261. return this;
  6262. }
  6263. headersOnly() {
  6264. this.config.headers_only = true;
  6265. return this;
  6266. }
  6267. ackNone() {
  6268. this.config.ack_policy = AckPolicy.None;
  6269. return this;
  6270. }
  6271. ackAll() {
  6272. this.config.ack_policy = AckPolicy.All;
  6273. return this;
  6274. }
  6275. ackExplicit() {
  6276. this.config.ack_policy = AckPolicy.Explicit;
  6277. return this;
  6278. }
  6279. ackWait(millis2) {
  6280. this.config.ack_wait = nanos(millis2);
  6281. return this;
  6282. }
  6283. maxDeliver(max) {
  6284. this.config.max_deliver = max;
  6285. return this;
  6286. }
  6287. filterSubject(s) {
  6288. this.filters = this.filters || [];
  6289. this.filters.push(s);
  6290. return this;
  6291. }
  6292. replayInstantly() {
  6293. this.config.replay_policy = ReplayPolicy.Instant;
  6294. return this;
  6295. }
  6296. replayOriginal() {
  6297. this.config.replay_policy = ReplayPolicy.Original;
  6298. return this;
  6299. }
  6300. sample(n) {
  6301. n = Math.trunc(n);
  6302. if (n < 0 || n > 100) {
  6303. throw new Error(`value must be between 0-100`);
  6304. }
  6305. this.config.sample_freq = `${n}%`;
  6306. return this;
  6307. }
  6308. limit(n) {
  6309. this.config.rate_limit_bps = n;
  6310. return this;
  6311. }
  6312. maxWaiting(max) {
  6313. this.config.max_waiting = max;
  6314. return this;
  6315. }
  6316. maxAckPending(max) {
  6317. this.config.max_ack_pending = max;
  6318. return this;
  6319. }
  6320. idleHeartbeat(millis2) {
  6321. this.config.idle_heartbeat = nanos(millis2);
  6322. return this;
  6323. }
  6324. flowControl() {
  6325. this.config.flow_control = true;
  6326. return this;
  6327. }
  6328. deliverGroup(name) {
  6329. this.queue(name);
  6330. return this;
  6331. }
  6332. manualAck() {
  6333. this.mack = true;
  6334. return this;
  6335. }
  6336. maxMessages(max) {
  6337. this.max = max;
  6338. return this;
  6339. }
  6340. callback(fn) {
  6341. this.callbackFn = fn;
  6342. return this;
  6343. }
  6344. queue(n) {
  6345. this.qname = n;
  6346. this.config.deliver_group = n;
  6347. return this;
  6348. }
  6349. orderedConsumer() {
  6350. this.ordered = true;
  6351. return this;
  6352. }
  6353. bind(stream, durable) {
  6354. this.stream = stream;
  6355. this.config.durable_name = durable;
  6356. this.isBind = true;
  6357. return this;
  6358. }
  6359. bindStream(stream) {
  6360. this.stream = stream;
  6361. return this;
  6362. }
  6363. inactiveEphemeralThreshold(millis2) {
  6364. this.config.inactive_threshold = nanos(millis2);
  6365. return this;
  6366. }
  6367. maxPullBatch(n) {
  6368. this.config.max_batch = n;
  6369. return this;
  6370. }
  6371. maxPullRequestExpires(millis2) {
  6372. this.config.max_expires = nanos(millis2);
  6373. return this;
  6374. }
  6375. memory() {
  6376. this.config.mem_storage = true;
  6377. return this;
  6378. }
  6379. numReplicas(n) {
  6380. this.config.num_replicas = n;
  6381. return this;
  6382. }
  6383. };
  6384. function consumerOpts(opts) {
  6385. return new ConsumerOptsBuilderImpl(opts);
  6386. }
  6387. function isConsumerOptsBuilder(o) {
  6388. return typeof o.getOpts === "function";
  6389. }
  6390. function getLengths(b64) {
  6391. const len = b64.length;
  6392. let validLen = b64.indexOf("=");
  6393. if (validLen === -1) {
  6394. validLen = len;
  6395. }
  6396. const placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4;
  6397. return [
  6398. validLen,
  6399. placeHoldersLen
  6400. ];
  6401. }
  6402. function init(lookup2, revLookup2, urlsafe = false) {
  6403. function _byteLength(validLen, placeHoldersLen) {
  6404. return Math.floor((validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen);
  6405. }
  6406. function tripletToBase64(num) {
  6407. return lookup2[num >> 18 & 63] + lookup2[num >> 12 & 63] + lookup2[num >> 6 & 63] + lookup2[num & 63];
  6408. }
  6409. function encodeChunk(buf, start, end) {
  6410. const out = new Array((end - start) / 3);
  6411. for (let i = start, curTriplet = 0; i < end; i += 3) {
  6412. out[curTriplet++] = tripletToBase64((buf[i] << 16) + (buf[i + 1] << 8) + buf[i + 2]);
  6413. }
  6414. return out.join("");
  6415. }
  6416. return {
  6417. byteLength(b64) {
  6418. return _byteLength.apply(null, getLengths(b64));
  6419. },
  6420. toUint8Array(b64) {
  6421. const [validLen, placeHoldersLen] = getLengths(b64);
  6422. const buf = new Uint8Array(_byteLength(validLen, placeHoldersLen));
  6423. const len = placeHoldersLen ? validLen - 4 : validLen;
  6424. let tmp;
  6425. let curByte = 0;
  6426. let i;
  6427. for (i = 0; i < len; i += 4) {
  6428. tmp = revLookup2[b64.charCodeAt(i)] << 18 | revLookup2[b64.charCodeAt(i + 1)] << 12 | revLookup2[b64.charCodeAt(i + 2)] << 6 | revLookup2[b64.charCodeAt(i + 3)];
  6429. buf[curByte++] = tmp >> 16 & 255;
  6430. buf[curByte++] = tmp >> 8 & 255;
  6431. buf[curByte++] = tmp & 255;
  6432. }
  6433. if (placeHoldersLen === 2) {
  6434. tmp = revLookup2[b64.charCodeAt(i)] << 2 | revLookup2[b64.charCodeAt(i + 1)] >> 4;
  6435. buf[curByte++] = tmp & 255;
  6436. } else if (placeHoldersLen === 1) {
  6437. tmp = revLookup2[b64.charCodeAt(i)] << 10 | revLookup2[b64.charCodeAt(i + 1)] << 4 | revLookup2[b64.charCodeAt(i + 2)] >> 2;
  6438. buf[curByte++] = tmp >> 8 & 255;
  6439. buf[curByte++] = tmp & 255;
  6440. }
  6441. return buf;
  6442. },
  6443. fromUint8Array(buf) {
  6444. const maxChunkLength = 16383;
  6445. const len = buf.length;
  6446. const extraBytes = len % 3;
  6447. const len2 = len - extraBytes;
  6448. const parts = new Array(Math.ceil(len2 / 16383) + (extraBytes ? 1 : 0));
  6449. let curChunk = 0;
  6450. let chunkEnd;
  6451. for (let i = 0; i < len2; i += maxChunkLength) {
  6452. chunkEnd = i + maxChunkLength;
  6453. parts[curChunk++] = encodeChunk(buf, i, chunkEnd > len2 ? len2 : chunkEnd);
  6454. }
  6455. let tmp;
  6456. if (extraBytes === 1) {
  6457. tmp = buf[len2];
  6458. parts[curChunk] = lookup2[tmp >> 2] + lookup2[tmp << 4 & 63];
  6459. if (!urlsafe)
  6460. parts[curChunk] += "==";
  6461. } else if (extraBytes === 2) {
  6462. tmp = buf[len2] << 8 | buf[len2 + 1] & 255;
  6463. parts[curChunk] = lookup2[tmp >> 10] + lookup2[tmp >> 4 & 63] + lookup2[tmp << 2 & 63];
  6464. if (!urlsafe)
  6465. parts[curChunk] += "=";
  6466. }
  6467. return parts.join("");
  6468. }
  6469. };
  6470. }
  6471. var lookup = [];
  6472. var revLookup = [];
  6473. var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
  6474. for (let i = 0, l = code.length; i < l; ++i) {
  6475. lookup[i] = code[i];
  6476. revLookup[code.charCodeAt(i)] = i;
  6477. }
  6478. var { byteLength, toUint8Array, fromUint8Array } = init(lookup, revLookup, true);
  6479. var decoder = new TextDecoder();
  6480. var encoder = new TextEncoder();
  6481. function toHexString(buf) {
  6482. return buf.reduce((hex, __byte) => `${hex}${__byte < 16 ? "0" : ""}${__byte.toString(16)}`, "");
  6483. }
  6484. function fromHexString(hex) {
  6485. const len = hex.length;
  6486. if (len % 2 || !/^[0-9a-fA-F]+$/.test(hex)) {
  6487. throw new TypeError("Invalid hex string.");
  6488. }
  6489. hex = hex.toLowerCase();
  6490. const buf = new Uint8Array(Math.floor(len / 2));
  6491. const end = len / 2;
  6492. for (let i = 0; i < end; ++i) {
  6493. buf[i] = parseInt(hex.substr(i * 2, 2), 16);
  6494. }
  6495. return buf;
  6496. }
  6497. function decode2(buf, encoding = "utf8") {
  6498. if (/^utf-?8$/i.test(encoding)) {
  6499. return decoder.decode(buf);
  6500. } else if (/^base64$/i.test(encoding)) {
  6501. return fromUint8Array(buf);
  6502. } else if (/^hex(?:adecimal)?$/i.test(encoding)) {
  6503. return toHexString(buf);
  6504. } else {
  6505. throw new TypeError("Unsupported string encoding.");
  6506. }
  6507. }
  6508. function encode2(str, encoding = "utf8") {
  6509. if (/^utf-?8$/i.test(encoding)) {
  6510. return encoder.encode(str);
  6511. } else if (/^base64$/i.test(encoding)) {
  6512. return toUint8Array(str);
  6513. } else if (/^hex(?:adecimal)?$/i.test(encoding)) {
  6514. return fromHexString(str);
  6515. } else {
  6516. throw new TypeError("Unsupported string encoding.");
  6517. }
  6518. }
  6519. var SHA256 = class {
  6520. constructor() {
  6521. __publicField(this, "hashSize", 32);
  6522. __publicField(this, "_buf");
  6523. __publicField(this, "_bufIdx");
  6524. __publicField(this, "_count");
  6525. __publicField(this, "_K");
  6526. __publicField(this, "_H");
  6527. __publicField(this, "_finalized");
  6528. this._buf = new Uint8Array(64);
  6529. this._K = new Uint32Array([
  6530. 1116352408,
  6531. 1899447441,
  6532. 3049323471,
  6533. 3921009573,
  6534. 961987163,
  6535. 1508970993,
  6536. 2453635748,
  6537. 2870763221,
  6538. 3624381080,
  6539. 310598401,
  6540. 607225278,
  6541. 1426881987,
  6542. 1925078388,
  6543. 2162078206,
  6544. 2614888103,
  6545. 3248222580,
  6546. 3835390401,
  6547. 4022224774,
  6548. 264347078,
  6549. 604807628,
  6550. 770255983,
  6551. 1249150122,
  6552. 1555081692,
  6553. 1996064986,
  6554. 2554220882,
  6555. 2821834349,
  6556. 2952996808,
  6557. 3210313671,
  6558. 3336571891,
  6559. 3584528711,
  6560. 113926993,
  6561. 338241895,
  6562. 666307205,
  6563. 773529912,
  6564. 1294757372,
  6565. 1396182291,
  6566. 1695183700,
  6567. 1986661051,
  6568. 2177026350,
  6569. 2456956037,
  6570. 2730485921,
  6571. 2820302411,
  6572. 3259730800,
  6573. 3345764771,
  6574. 3516065817,
  6575. 3600352804,
  6576. 4094571909,
  6577. 275423344,
  6578. 430227734,
  6579. 506948616,
  6580. 659060556,
  6581. 883997877,
  6582. 958139571,
  6583. 1322822218,
  6584. 1537002063,
  6585. 1747873779,
  6586. 1955562222,
  6587. 2024104815,
  6588. 2227730452,
  6589. 2361852424,
  6590. 2428436474,
  6591. 2756734187,
  6592. 3204031479,
  6593. 3329325298
  6594. ]);
  6595. this.init();
  6596. }
  6597. init() {
  6598. this._H = new Uint32Array([
  6599. 1779033703,
  6600. 3144134277,
  6601. 1013904242,
  6602. 2773480762,
  6603. 1359893119,
  6604. 2600822924,
  6605. 528734635,
  6606. 1541459225
  6607. ]);
  6608. this._bufIdx = 0;
  6609. this._count = new Uint32Array(2);
  6610. this._buf.fill(0);
  6611. this._finalized = false;
  6612. return this;
  6613. }
  6614. update(msg, inputEncoding) {
  6615. if (msg === null) {
  6616. throw new TypeError("msg must be a string or Uint8Array.");
  6617. } else if (typeof msg === "string") {
  6618. msg = encode2(msg, inputEncoding);
  6619. }
  6620. for (let i = 0, len = msg.length; i < len; i++) {
  6621. this._buf[this._bufIdx++] = msg[i];
  6622. if (this._bufIdx === 64) {
  6623. this._transform();
  6624. this._bufIdx = 0;
  6625. }
  6626. }
  6627. const c = this._count;
  6628. if ((c[0] += msg.length << 3) < msg.length << 3) {
  6629. c[1]++;
  6630. }
  6631. c[1] += msg.length >>> 29;
  6632. return this;
  6633. }
  6634. digest(outputEncoding) {
  6635. if (this._finalized) {
  6636. throw new Error("digest has already been called.");
  6637. }
  6638. this._finalized = true;
  6639. const b = this._buf;
  6640. let idx = this._bufIdx;
  6641. b[idx++] = 128;
  6642. while (idx !== 56) {
  6643. if (idx === 64) {
  6644. this._transform();
  6645. idx = 0;
  6646. }
  6647. b[idx++] = 0;
  6648. }
  6649. const c = this._count;
  6650. b[56] = c[1] >>> 24 & 255;
  6651. b[57] = c[1] >>> 16 & 255;
  6652. b[58] = c[1] >>> 8 & 255;
  6653. b[59] = c[1] >>> 0 & 255;
  6654. b[60] = c[0] >>> 24 & 255;
  6655. b[61] = c[0] >>> 16 & 255;
  6656. b[62] = c[0] >>> 8 & 255;
  6657. b[63] = c[0] >>> 0 & 255;
  6658. this._transform();
  6659. const hash = new Uint8Array(32);
  6660. for (let i = 0; i < 8; i++) {
  6661. hash[(i << 2) + 0] = this._H[i] >>> 24 & 255;
  6662. hash[(i << 2) + 1] = this._H[i] >>> 16 & 255;
  6663. hash[(i << 2) + 2] = this._H[i] >>> 8 & 255;
  6664. hash[(i << 2) + 3] = this._H[i] >>> 0 & 255;
  6665. }
  6666. this.init();
  6667. return outputEncoding ? decode2(hash, outputEncoding) : hash;
  6668. }
  6669. _transform() {
  6670. const h = this._H;
  6671. let h0 = h[0];
  6672. let h1 = h[1];
  6673. let h2 = h[2];
  6674. let h3 = h[3];
  6675. let h4 = h[4];
  6676. let h5 = h[5];
  6677. let h6 = h[6];
  6678. let h7 = h[7];
  6679. const w = new Uint32Array(16);
  6680. let i;
  6681. for (i = 0; i < 16; i++) {
  6682. w[i] = this._buf[(i << 2) + 3] | this._buf[(i << 2) + 2] << 8 | this._buf[(i << 2) + 1] << 16 | this._buf[i << 2] << 24;
  6683. }
  6684. for (i = 0; i < 64; i++) {
  6685. let tmp;
  6686. if (i < 16) {
  6687. tmp = w[i];
  6688. } else {
  6689. let a = w[i + 1 & 15];
  6690. let b = w[i + 14 & 15];
  6691. tmp = w[i & 15] = (a >>> 7 ^ a >>> 18 ^ a >>> 3 ^ a << 25 ^ a << 14) + (b >>> 17 ^ b >>> 19 ^ b >>> 10 ^ b << 15 ^ b << 13) + w[i & 15] + w[i + 9 & 15] | 0;
  6692. }
  6693. tmp = tmp + h7 + (h4 >>> 6 ^ h4 >>> 11 ^ h4 >>> 25 ^ h4 << 26 ^ h4 << 21 ^ h4 << 7) + (h6 ^ h4 & (h5 ^ h6)) + this._K[i] | 0;
  6694. h7 = h6;
  6695. h6 = h5;
  6696. h5 = h4;
  6697. h4 = h3 + tmp;
  6698. h3 = h2;
  6699. h2 = h1;
  6700. h1 = h0;
  6701. h0 = tmp + (h1 & h2 ^ h3 & (h1 ^ h2)) + (h1 >>> 2 ^ h1 >>> 13 ^ h1 >>> 22 ^ h1 << 30 ^ h1 << 19 ^ h1 << 10) | 0;
  6702. }
  6703. h[0] = h[0] + h0 | 0;
  6704. h[1] = h[1] + h1 | 0;
  6705. h[2] = h[2] + h2 | 0;
  6706. h[3] = h[3] + h3 | 0;
  6707. h[4] = h[4] + h4 | 0;
  6708. h[5] = h[5] + h5 | 0;
  6709. h[6] = h[6] + h6 | 0;
  6710. h[7] = h[7] + h7 | 0;
  6711. }
  6712. };
  6713. var ListerImpl = class {
  6714. constructor(subject, filter, jsm, payload) {
  6715. __publicField(this, "err");
  6716. __publicField(this, "offset");
  6717. __publicField(this, "pageInfo");
  6718. __publicField(this, "subject");
  6719. __publicField(this, "jsm");
  6720. __publicField(this, "filter");
  6721. __publicField(this, "payload");
  6722. if (!subject) {
  6723. throw new Error("subject is required");
  6724. }
  6725. this.subject = subject;
  6726. this.jsm = jsm;
  6727. this.offset = 0;
  6728. this.pageInfo = {};
  6729. this.filter = filter;
  6730. this.payload = payload || {};
  6731. }
  6732. async next() {
  6733. if (this.err) {
  6734. return [];
  6735. }
  6736. if (this.pageInfo && this.offset >= this.pageInfo.total) {
  6737. return [];
  6738. }
  6739. const offset = {
  6740. offset: this.offset
  6741. };
  6742. if (this.payload) {
  6743. Object.assign(offset, this.payload);
  6744. }
  6745. try {
  6746. const r = await this.jsm._request(this.subject, offset, {
  6747. timeout: this.jsm.timeout
  6748. });
  6749. this.pageInfo = r;
  6750. this.offset += this.countResponse(r);
  6751. const a = this.filter(r);
  6752. return a;
  6753. } catch (err) {
  6754. this.err = err;
  6755. throw err;
  6756. }
  6757. }
  6758. countResponse(r) {
  6759. var _a;
  6760. switch (r == null ? void 0 : r.type) {
  6761. case "io.nats.jetstream.api.v1.stream_names_response":
  6762. case "io.nats.jetstream.api.v1.stream_list_response":
  6763. return r.streams.length;
  6764. case "io.nats.jetstream.api.v1.consumer_list_response":
  6765. return r.consumers.length;
  6766. default:
  6767. console.error(`jslister.ts: unknown API response for paged output: ${r == null ? void 0 : r.type}`);
  6768. return ((_a = r.streams) == null ? void 0 : _a.length) || 0;
  6769. }
  6770. return 0;
  6771. }
  6772. async *[Symbol.asyncIterator]() {
  6773. let page = await this.next();
  6774. while (page.length > 0) {
  6775. for (const item of page) {
  6776. yield item;
  6777. }
  6778. page = await this.next();
  6779. }
  6780. }
  6781. };
  6782. var ConsumerAPIImpl = class extends BaseApiClient {
  6783. constructor(nc, opts) {
  6784. super(nc, opts);
  6785. }
  6786. async add(stream, cfg, action = ConsumerApiAction.Create) {
  6787. validateStreamName(stream);
  6788. if (cfg.deliver_group && cfg.flow_control) {
  6789. throw new Error("jetstream flow control is not supported with queue groups");
  6790. }
  6791. if (cfg.deliver_group && cfg.idle_heartbeat) {
  6792. throw new Error("jetstream idle heartbeat is not supported with queue groups");
  6793. }
  6794. const cr = {};
  6795. cr.config = cfg;
  6796. cr.stream_name = stream;
  6797. cr.action = action;
  6798. if (cr.config.durable_name) {
  6799. validateDurableName(cr.config.durable_name);
  6800. }
  6801. const nci = this.nc;
  6802. let { min, ok: newAPI } = nci.features.get(Feature.JS_NEW_CONSUMER_CREATE_API);
  6803. const name = cfg.name === "" ? void 0 : cfg.name;
  6804. if (name && !newAPI) {
  6805. throw new Error(`consumer 'name' requires server ${min}`);
  6806. }
  6807. if (name) {
  6808. try {
  6809. minValidation("name", name);
  6810. } catch (err) {
  6811. const m = err.message;
  6812. const idx = m.indexOf("cannot contain");
  6813. if (idx !== -1) {
  6814. throw new Error(`consumer 'name' ${m.substring(idx)}`);
  6815. }
  6816. throw err;
  6817. }
  6818. }
  6819. let subj;
  6820. let consumerName = "";
  6821. if (Array.isArray(cfg.filter_subjects)) {
  6822. const { min: min2, ok } = nci.features.get(Feature.JS_MULTIPLE_CONSUMER_FILTER);
  6823. if (!ok) {
  6824. throw new Error(`consumer 'filter_subjects' requires server ${min2}`);
  6825. }
  6826. newAPI = false;
  6827. }
  6828. if (cfg.metadata) {
  6829. const { min: min2, ok } = nci.features.get(Feature.JS_STREAM_CONSUMER_METADATA);
  6830. if (!ok) {
  6831. throw new Error(`consumer 'metadata' requires server ${min2}`);
  6832. }
  6833. }
  6834. if (newAPI) {
  6835. consumerName = cfg.name ?? cfg.durable_name ?? "";
  6836. }
  6837. if (consumerName !== "") {
  6838. let fs = cfg.filter_subject ?? void 0;
  6839. if (fs === ">") {
  6840. fs = void 0;
  6841. }
  6842. subj = fs !== void 0 ? `${this.prefix}.CONSUMER.CREATE.${stream}.${consumerName}.${fs}` : `${this.prefix}.CONSUMER.CREATE.${stream}.${consumerName}`;
  6843. } else {
  6844. subj = cfg.durable_name ? `${this.prefix}.CONSUMER.DURABLE.CREATE.${stream}.${cfg.durable_name}` : `${this.prefix}.CONSUMER.CREATE.${stream}`;
  6845. }
  6846. const r = await this._request(subj, cr);
  6847. return r;
  6848. }
  6849. async update(stream, durable, cfg) {
  6850. const ci = await this.info(stream, durable);
  6851. const changable = cfg;
  6852. return this.add(stream, Object.assign(ci.config, changable), ConsumerApiAction.Update);
  6853. }
  6854. async info(stream, name) {
  6855. validateStreamName(stream);
  6856. validateDurableName(name);
  6857. const r = await this._request(`${this.prefix}.CONSUMER.INFO.${stream}.${name}`);
  6858. return r;
  6859. }
  6860. async delete(stream, name) {
  6861. validateStreamName(stream);
  6862. validateDurableName(name);
  6863. const r = await this._request(`${this.prefix}.CONSUMER.DELETE.${stream}.${name}`);
  6864. const cr = r;
  6865. return cr.success;
  6866. }
  6867. list(stream) {
  6868. validateStreamName(stream);
  6869. const filter = (v) => {
  6870. const clr = v;
  6871. return clr.consumers;
  6872. };
  6873. const subj = `${this.prefix}.CONSUMER.LIST.${stream}`;
  6874. return new ListerImpl(subj, filter, this);
  6875. }
  6876. };
  6877. var ACK = Uint8Array.of(43, 65, 67, 75);
  6878. var NAK = Uint8Array.of(45, 78, 65, 75);
  6879. var WPI = Uint8Array.of(43, 87, 80, 73);
  6880. var NXT = Uint8Array.of(43, 78, 88, 84);
  6881. var TERM = Uint8Array.of(43, 84, 69, 82, 77);
  6882. var SPACE = Uint8Array.of(32);
  6883. function toJsMsg(m) {
  6884. return new JsMsgImpl(m);
  6885. }
  6886. function parseInfo(s) {
  6887. const tokens = s.split(".");
  6888. if (tokens.length === 9) {
  6889. tokens.splice(2, 0, "_", "");
  6890. }
  6891. if (tokens.length < 11 || tokens[0] !== "$JS" || tokens[1] !== "ACK") {
  6892. throw new Error(`not js message`);
  6893. }
  6894. const di = {};
  6895. di.domain = tokens[2] === "_" ? "" : tokens[2];
  6896. di.account_hash = tokens[3];
  6897. di.stream = tokens[4];
  6898. di.consumer = tokens[5];
  6899. di.redeliveryCount = parseInt(tokens[6], 10);
  6900. di.redelivered = di.redeliveryCount > 1;
  6901. di.streamSequence = parseInt(tokens[7], 10);
  6902. di.deliverySequence = parseInt(tokens[8], 10);
  6903. di.timestampNanos = parseInt(tokens[9], 10);
  6904. di.pending = parseInt(tokens[10], 10);
  6905. return di;
  6906. }
  6907. var JsMsgImpl = class {
  6908. constructor(msg) {
  6909. __publicField(this, "msg");
  6910. __publicField(this, "di");
  6911. __publicField(this, "didAck");
  6912. this.msg = msg;
  6913. this.didAck = false;
  6914. }
  6915. get subject() {
  6916. return this.msg.subject;
  6917. }
  6918. get sid() {
  6919. return this.msg.sid;
  6920. }
  6921. get data() {
  6922. return this.msg.data;
  6923. }
  6924. get headers() {
  6925. return this.msg.headers;
  6926. }
  6927. get info() {
  6928. if (!this.di) {
  6929. this.di = parseInfo(this.reply);
  6930. }
  6931. return this.di;
  6932. }
  6933. get redelivered() {
  6934. return this.info.redeliveryCount > 1;
  6935. }
  6936. get reply() {
  6937. return this.msg.reply || "";
  6938. }
  6939. get seq() {
  6940. return this.info.streamSequence;
  6941. }
  6942. doAck(payload) {
  6943. if (!this.didAck) {
  6944. this.didAck = !this.isWIP(payload);
  6945. this.msg.respond(payload);
  6946. }
  6947. }
  6948. isWIP(p) {
  6949. return p.length === 4 && p[0] === WPI[0] && p[1] === WPI[1] && p[2] === WPI[2] && p[3] === WPI[3];
  6950. }
  6951. async ackAck() {
  6952. var _a;
  6953. if (!this.didAck) {
  6954. this.didAck = true;
  6955. if (this.msg.reply) {
  6956. const mi = this.msg;
  6957. const proto = mi.publisher;
  6958. const trace = !(((_a = proto.options) == null ? void 0 : _a.noAsyncTraces) || false);
  6959. const r = new RequestOne(proto.muxSubscriptions, this.msg.reply, {
  6960. timeout: 1e3
  6961. }, trace);
  6962. proto.request(r);
  6963. try {
  6964. proto.publish(this.msg.reply, ACK, {
  6965. reply: `${proto.muxSubscriptions.baseInbox}${r.token}`
  6966. });
  6967. } catch (err) {
  6968. r.cancel(err);
  6969. }
  6970. try {
  6971. await Promise.race([
  6972. r.timer,
  6973. r.deferred
  6974. ]);
  6975. return true;
  6976. } catch (err) {
  6977. r.cancel(err);
  6978. }
  6979. }
  6980. }
  6981. return false;
  6982. }
  6983. ack() {
  6984. this.doAck(ACK);
  6985. }
  6986. nak(millis2) {
  6987. let payload = NAK;
  6988. if (millis2) {
  6989. payload = StringCodec().encode(`-NAK ${JSON.stringify({
  6990. delay: nanos(millis2)
  6991. })}`);
  6992. }
  6993. this.doAck(payload);
  6994. }
  6995. working() {
  6996. this.doAck(WPI);
  6997. }
  6998. next(subj, opts = {
  6999. batch: 1
  7000. }) {
  7001. const args = {};
  7002. args.batch = opts.batch || 1;
  7003. args.no_wait = opts.no_wait || false;
  7004. if (opts.expires && opts.expires > 0) {
  7005. args.expires = nanos(opts.expires);
  7006. }
  7007. const data = JSONCodec().encode(args);
  7008. const payload = DataBuffer.concat(NXT, SPACE, data);
  7009. const reqOpts = subj ? {
  7010. reply: subj
  7011. } : void 0;
  7012. this.msg.respond(payload, reqOpts);
  7013. }
  7014. term(reason = "") {
  7015. let term = TERM;
  7016. if ((reason == null ? void 0 : reason.length) > 0) {
  7017. term = StringCodec().encode(`+TERM ${reason}`);
  7018. }
  7019. this.doAck(term);
  7020. }
  7021. json() {
  7022. return this.msg.json();
  7023. }
  7024. string() {
  7025. return this.msg.string();
  7026. }
  7027. };
  7028. function checkFn(fn, name, required = false) {
  7029. if (required === true && !fn) {
  7030. throw NatsError.errorForCode(ErrorCode.ApiError, new Error(`${name} is not a function`));
  7031. }
  7032. if (fn && typeof fn !== "function") {
  7033. throw NatsError.errorForCode(ErrorCode.ApiError, new Error(`${name} is not a function`));
  7034. }
  7035. }
  7036. var TypedSubscription = class extends QueuedIteratorImpl {
  7037. constructor(nc, subject, opts) {
  7038. super();
  7039. __publicField(this, "sub");
  7040. __publicField(this, "adapter");
  7041. __publicField(this, "subIterDone");
  7042. checkFn(opts.adapter, "adapter", true);
  7043. this.adapter = opts.adapter;
  7044. if (opts.callback) {
  7045. checkFn(opts.callback, "callback");
  7046. }
  7047. this.noIterator = typeof opts.callback === "function";
  7048. if (opts.ingestionFilterFn) {
  7049. checkFn(opts.ingestionFilterFn, "ingestionFilterFn");
  7050. this.ingestionFilterFn = opts.ingestionFilterFn;
  7051. }
  7052. if (opts.protocolFilterFn) {
  7053. checkFn(opts.protocolFilterFn, "protocolFilterFn");
  7054. this.protocolFilterFn = opts.protocolFilterFn;
  7055. }
  7056. if (opts.dispatchedFn) {
  7057. checkFn(opts.dispatchedFn, "dispatchedFn");
  7058. this.dispatchedFn = opts.dispatchedFn;
  7059. }
  7060. if (opts.cleanupFn) {
  7061. checkFn(opts.cleanupFn, "cleanupFn");
  7062. }
  7063. let callback = (err, msg) => {
  7064. this.callback(err, msg);
  7065. };
  7066. if (opts.callback) {
  7067. const uh = opts.callback;
  7068. callback = (err, msg) => {
  7069. const [jer, tm] = this.adapter(err, msg);
  7070. if (jer) {
  7071. uh(jer, null);
  7072. return;
  7073. }
  7074. const { ingest } = this.ingestionFilterFn ? this.ingestionFilterFn(tm, this) : {
  7075. ingest: true
  7076. };
  7077. if (ingest) {
  7078. const ok = this.protocolFilterFn ? this.protocolFilterFn(tm) : true;
  7079. if (ok) {
  7080. uh(jer, tm);
  7081. if (this.dispatchedFn && tm) {
  7082. this.dispatchedFn(tm);
  7083. }
  7084. }
  7085. }
  7086. };
  7087. }
  7088. const { max, queue, timeout: timeout2 } = opts;
  7089. const sopts = {
  7090. queue,
  7091. timeout: timeout2,
  7092. callback
  7093. };
  7094. if (max && max > 0) {
  7095. sopts.max = max;
  7096. }
  7097. this.sub = nc.subscribe(subject, sopts);
  7098. if (opts.cleanupFn) {
  7099. this.sub.cleanupFn = opts.cleanupFn;
  7100. }
  7101. if (!this.noIterator) {
  7102. this.iterClosed.then(() => {
  7103. this.unsubscribe();
  7104. });
  7105. }
  7106. this.subIterDone = deferred();
  7107. Promise.all([
  7108. this.sub.closed,
  7109. this.iterClosed
  7110. ]).then(() => {
  7111. this.subIterDone.resolve();
  7112. }).catch(() => {
  7113. this.subIterDone.resolve();
  7114. });
  7115. (async (s) => {
  7116. await s.closed;
  7117. this.stop();
  7118. })(this.sub).then().catch();
  7119. }
  7120. unsubscribe(max) {
  7121. this.sub.unsubscribe(max);
  7122. }
  7123. drain() {
  7124. return this.sub.drain();
  7125. }
  7126. isDraining() {
  7127. return this.sub.isDraining();
  7128. }
  7129. isClosed() {
  7130. return this.sub.isClosed();
  7131. }
  7132. callback(e, msg) {
  7133. this.sub.cancelTimeout();
  7134. const [err, tm] = this.adapter(e, msg);
  7135. if (err) {
  7136. this.stop(err);
  7137. }
  7138. if (tm) {
  7139. this.push(tm);
  7140. }
  7141. }
  7142. getSubject() {
  7143. return this.sub.getSubject();
  7144. }
  7145. getReceived() {
  7146. return this.sub.getReceived();
  7147. }
  7148. getProcessed() {
  7149. return this.sub.getProcessed();
  7150. }
  7151. getPending() {
  7152. return this.sub.getPending();
  7153. }
  7154. getID() {
  7155. return this.sub.getID();
  7156. }
  7157. getMax() {
  7158. return this.sub.getMax();
  7159. }
  7160. get closed() {
  7161. return this.sub.closed;
  7162. }
  7163. };
  7164. var IdleHeartbeatMonitor = class {
  7165. constructor(interval, cb, opts = {
  7166. maxOut: 2
  7167. }) {
  7168. __publicField(this, "interval");
  7169. __publicField(this, "maxOut");
  7170. __publicField(this, "cancelAfter");
  7171. __publicField(this, "timer");
  7172. __publicField(this, "autoCancelTimer");
  7173. __publicField(this, "last");
  7174. __publicField(this, "missed");
  7175. __publicField(this, "count");
  7176. __publicField(this, "callback");
  7177. this.interval = interval;
  7178. this.maxOut = (opts == null ? void 0 : opts.maxOut) || 2;
  7179. this.cancelAfter = (opts == null ? void 0 : opts.cancelAfter) || 0;
  7180. this.last = Date.now();
  7181. this.missed = 0;
  7182. this.count = 0;
  7183. this.callback = cb;
  7184. this._schedule();
  7185. }
  7186. cancel() {
  7187. if (this.autoCancelTimer) {
  7188. clearTimeout(this.autoCancelTimer);
  7189. }
  7190. if (this.timer) {
  7191. clearInterval(this.timer);
  7192. }
  7193. this.timer = 0;
  7194. this.autoCancelTimer = 0;
  7195. }
  7196. work() {
  7197. this.last = Date.now();
  7198. this.missed = 0;
  7199. }
  7200. _change(interval, cancelAfter = 0, maxOut = 2) {
  7201. this.interval = interval;
  7202. this.maxOut = maxOut;
  7203. this.cancelAfter = cancelAfter;
  7204. this.restart();
  7205. }
  7206. restart() {
  7207. this.cancel();
  7208. this._schedule();
  7209. }
  7210. _schedule() {
  7211. if (this.cancelAfter > 0) {
  7212. this.autoCancelTimer = setTimeout(() => {
  7213. this.cancel();
  7214. }, this.cancelAfter);
  7215. }
  7216. this.timer = setInterval(() => {
  7217. this.count++;
  7218. if (Date.now() - this.last > this.interval) {
  7219. this.missed++;
  7220. }
  7221. if (this.missed >= this.maxOut) {
  7222. try {
  7223. if (this.callback(this.missed) === true) {
  7224. this.cancel();
  7225. }
  7226. } catch (err) {
  7227. console.log(err);
  7228. }
  7229. }
  7230. }, this.interval);
  7231. }
  7232. };
  7233. var PullConsumerType;
  7234. (function(PullConsumerType2) {
  7235. PullConsumerType2[PullConsumerType2["Unset"] = -1] = "Unset";
  7236. PullConsumerType2[PullConsumerType2["Consume"] = 0] = "Consume";
  7237. PullConsumerType2[PullConsumerType2["Fetch"] = 1] = "Fetch";
  7238. })(PullConsumerType || (PullConsumerType = {}));
  7239. var ConsumerEvents;
  7240. (function(ConsumerEvents2) {
  7241. ConsumerEvents2["HeartbeatsMissed"] = "heartbeats_missed";
  7242. ConsumerEvents2["ConsumerNotFound"] = "consumer_not_found";
  7243. ConsumerEvents2["OrderedConsumerRecreated"] = "ordered_consumer_recreated";
  7244. })(ConsumerEvents || (ConsumerEvents = {}));
  7245. var ConsumerDebugEvents;
  7246. (function(ConsumerDebugEvents2) {
  7247. ConsumerDebugEvents2["DebugEvent"] = "debug";
  7248. ConsumerDebugEvents2["Discard"] = "discard";
  7249. ConsumerDebugEvents2["Next"] = "next";
  7250. })(ConsumerDebugEvents || (ConsumerDebugEvents = {}));
  7251. var PullConsumerMessagesImpl = class extends QueuedIteratorImpl {
  7252. constructor(c, opts, refilling = false) {
  7253. super();
  7254. __publicField(this, "consumer");
  7255. __publicField(this, "opts");
  7256. __publicField(this, "sub");
  7257. __publicField(this, "monitor");
  7258. __publicField(this, "pending");
  7259. __publicField(this, "inbox");
  7260. __publicField(this, "refilling");
  7261. __publicField(this, "stack");
  7262. __publicField(this, "pong");
  7263. __publicField(this, "callback");
  7264. __publicField(this, "timeout");
  7265. __publicField(this, "cleanupHandler");
  7266. __publicField(this, "listeners");
  7267. __publicField(this, "statusIterator");
  7268. __publicField(this, "forOrderedConsumer");
  7269. __publicField(this, "resetHandler");
  7270. this.consumer = c;
  7271. this.opts = this.parseOptions(opts, refilling);
  7272. this.callback = opts.callback || null;
  7273. this.noIterator = typeof this.callback === "function";
  7274. this.monitor = null;
  7275. this.pong = null;
  7276. this.pending = {
  7277. msgs: 0,
  7278. bytes: 0,
  7279. requests: 0
  7280. };
  7281. this.refilling = refilling;
  7282. this.stack = new Error().stack.split("\n").slice(1).join("\n");
  7283. this.timeout = null;
  7284. this.inbox = createInbox(c.api.nc.options.inboxPrefix);
  7285. this.listeners = [];
  7286. this.forOrderedConsumer = false;
  7287. this.start();
  7288. }
  7289. start() {
  7290. const { max_messages, max_bytes, idle_heartbeat, threshold_bytes, threshold_messages } = this.opts;
  7291. this.closed().then(() => {
  7292. if (this.cleanupHandler) {
  7293. try {
  7294. this.cleanupHandler();
  7295. } catch (_err) {
  7296. }
  7297. }
  7298. });
  7299. const { sub } = this;
  7300. if (sub) {
  7301. sub.unsubscribe();
  7302. }
  7303. this.sub = this.consumer.api.nc.subscribe(this.inbox, {
  7304. callback: (err, msg) => {
  7305. var _a, _b, _c, _d;
  7306. if (err) {
  7307. this.stop();
  7308. return;
  7309. }
  7310. (_a = this.monitor) == null ? void 0 : _a.work();
  7311. const isProtocol = msg.subject === this.inbox;
  7312. if (isProtocol) {
  7313. if (isHeartbeatMsg(msg)) {
  7314. return;
  7315. }
  7316. const code2 = (_b = msg.headers) == null ? void 0 : _b.code;
  7317. const description = ((_d = (_c = msg.headers) == null ? void 0 : _c.description) == null ? void 0 : _d.toLowerCase()) || "unknown";
  7318. const { msgsLeft, bytesLeft } = this.parseDiscard(msg.headers);
  7319. if (msgsLeft > 0 || bytesLeft > 0) {
  7320. this.pending.msgs -= msgsLeft;
  7321. this.pending.bytes -= bytesLeft;
  7322. this.pending.requests--;
  7323. this.notify(ConsumerDebugEvents.Discard, {
  7324. msgsLeft,
  7325. bytesLeft
  7326. });
  7327. } else {
  7328. const toErr = () => {
  7329. const err2 = new NatsError(description, `${code2}`);
  7330. err2.stack += `
  7331. ${this.stack}`;
  7332. return err2;
  7333. };
  7334. if (code2 === 400) {
  7335. const error = toErr();
  7336. this._push(() => {
  7337. this.stop(error);
  7338. });
  7339. } else if (code2 === 409 && description === "consumer deleted") {
  7340. const error = toErr();
  7341. this.stop(error);
  7342. } else {
  7343. this.notify(ConsumerDebugEvents.DebugEvent, `${code2} ${description}`);
  7344. }
  7345. }
  7346. } else {
  7347. this._push(toJsMsg(msg));
  7348. this.received++;
  7349. if (this.pending.msgs) {
  7350. this.pending.msgs--;
  7351. }
  7352. if (this.pending.bytes) {
  7353. this.pending.bytes -= msg.size();
  7354. }
  7355. }
  7356. if (this.pending.msgs === 0 && this.pending.bytes === 0) {
  7357. this.pending.requests = 0;
  7358. }
  7359. if (this.refilling) {
  7360. if (max_messages && this.pending.msgs <= threshold_messages || max_bytes && this.pending.bytes <= threshold_bytes) {
  7361. const batch = this.pullOptions();
  7362. this.pull(batch);
  7363. }
  7364. } else if (this.pending.requests === 0) {
  7365. this._push(() => {
  7366. this.stop();
  7367. });
  7368. }
  7369. }
  7370. });
  7371. this.sub.closed.then(() => {
  7372. if (this.sub.draining) {
  7373. this._push(() => {
  7374. this.stop();
  7375. });
  7376. }
  7377. });
  7378. if (idle_heartbeat) {
  7379. this.monitor = new IdleHeartbeatMonitor(idle_heartbeat, (data) => {
  7380. this.notify(ConsumerEvents.HeartbeatsMissed, data);
  7381. this.resetPending().then(() => {
  7382. }).catch(() => {
  7383. });
  7384. return false;
  7385. }, {
  7386. maxOut: 2
  7387. });
  7388. }
  7389. (async () => {
  7390. var _a;
  7391. const status = this.consumer.api.nc.status();
  7392. this.statusIterator = status;
  7393. for await (const s of status) {
  7394. switch (s.type) {
  7395. case Events.Disconnect:
  7396. (_a = this.monitor) == null ? void 0 : _a.cancel();
  7397. break;
  7398. case Events.Reconnect:
  7399. this.resetPending().then((ok) => {
  7400. var _a2;
  7401. if (ok) {
  7402. (_a2 = this.monitor) == null ? void 0 : _a2.restart();
  7403. }
  7404. }).catch(() => {
  7405. });
  7406. break;
  7407. default:
  7408. }
  7409. }
  7410. })();
  7411. this.pull(this.pullOptions());
  7412. }
  7413. _push(r) {
  7414. if (!this.callback) {
  7415. super.push(r);
  7416. } else {
  7417. const fn = typeof r === "function" ? r : null;
  7418. try {
  7419. if (!fn) {
  7420. this.callback(r);
  7421. } else {
  7422. fn();
  7423. }
  7424. } catch (err) {
  7425. this.stop(err);
  7426. }
  7427. }
  7428. }
  7429. notify(type, data) {
  7430. if (this.listeners.length > 0) {
  7431. (() => {
  7432. this.listeners.forEach((l) => {
  7433. if (!l.done) {
  7434. l.push({
  7435. type,
  7436. data
  7437. });
  7438. }
  7439. });
  7440. })();
  7441. }
  7442. }
  7443. async resetPending() {
  7444. let notFound = 0;
  7445. const bo = backoff();
  7446. let attempt = 0;
  7447. while (true) {
  7448. if (this.consumer.api.nc.isClosed()) {
  7449. console.error("aborting resetPending - connection is closed");
  7450. return false;
  7451. }
  7452. try {
  7453. await this.consumer.info();
  7454. notFound = 0;
  7455. this.pending.msgs = 0;
  7456. this.pending.bytes = 0;
  7457. this.pending.requests = 0;
  7458. this.pull(this.pullOptions());
  7459. return true;
  7460. } catch (err) {
  7461. if (err.message === "consumer not found") {
  7462. notFound++;
  7463. this.notify(ConsumerEvents.ConsumerNotFound, notFound);
  7464. if (this.resetHandler) {
  7465. try {
  7466. this.resetHandler();
  7467. } catch (_) {
  7468. }
  7469. }
  7470. if (this.forOrderedConsumer) {
  7471. return false;
  7472. }
  7473. } else {
  7474. notFound = 0;
  7475. }
  7476. const to = bo.backoff(attempt);
  7477. await Promise.race([
  7478. delay(to),
  7479. this.consumer.api.nc.closed()
  7480. ]);
  7481. attempt++;
  7482. }
  7483. }
  7484. }
  7485. pull(opts) {
  7486. this.pending.bytes += opts.max_bytes ?? 0;
  7487. this.pending.msgs += opts.batch ?? 0;
  7488. this.pending.requests++;
  7489. const nc = this.consumer.api.nc;
  7490. this._push(() => {
  7491. nc.publish(`${this.consumer.api.prefix}.CONSUMER.MSG.NEXT.${this.consumer.stream}.${this.consumer.name}`, this.consumer.api.jc.encode(opts), {
  7492. reply: this.inbox
  7493. });
  7494. this.notify(ConsumerDebugEvents.Next, opts);
  7495. });
  7496. }
  7497. pullOptions() {
  7498. const batch = this.opts.max_messages - this.pending.msgs;
  7499. const max_bytes = this.opts.max_bytes - this.pending.bytes;
  7500. const idle_heartbeat = nanos(this.opts.idle_heartbeat);
  7501. const expires = nanos(this.opts.expires);
  7502. return {
  7503. batch,
  7504. max_bytes,
  7505. idle_heartbeat,
  7506. expires
  7507. };
  7508. }
  7509. parseDiscard(headers2) {
  7510. const discard = {
  7511. msgsLeft: 0,
  7512. bytesLeft: 0
  7513. };
  7514. const msgsLeft = headers2 == null ? void 0 : headers2.get(JsHeaders.PendingMessagesHdr);
  7515. if (msgsLeft) {
  7516. discard.msgsLeft = parseInt(msgsLeft);
  7517. }
  7518. const bytesLeft = headers2 == null ? void 0 : headers2.get(JsHeaders.PendingBytesHdr);
  7519. if (bytesLeft) {
  7520. discard.bytesLeft = parseInt(bytesLeft);
  7521. }
  7522. return discard;
  7523. }
  7524. trackTimeout(t) {
  7525. this.timeout = t;
  7526. }
  7527. close() {
  7528. this.stop();
  7529. return this.iterClosed;
  7530. }
  7531. closed() {
  7532. return this.iterClosed;
  7533. }
  7534. clearTimers() {
  7535. var _a, _b;
  7536. (_a = this.monitor) == null ? void 0 : _a.cancel();
  7537. this.monitor = null;
  7538. (_b = this.timeout) == null ? void 0 : _b.cancel();
  7539. this.timeout = null;
  7540. }
  7541. setCleanupHandler(fn) {
  7542. this.cleanupHandler = fn;
  7543. }
  7544. stop(err) {
  7545. var _a, _b;
  7546. (_a = this.sub) == null ? void 0 : _a.unsubscribe();
  7547. this.clearTimers();
  7548. (_b = this.statusIterator) == null ? void 0 : _b.stop();
  7549. this._push(() => {
  7550. super.stop(err);
  7551. this.listeners.forEach((n) => {
  7552. n.stop();
  7553. });
  7554. });
  7555. }
  7556. parseOptions(opts, refilling = false) {
  7557. const args = opts || {};
  7558. args.max_messages = args.max_messages || 0;
  7559. args.max_bytes = args.max_bytes || 0;
  7560. if (args.max_messages !== 0 && args.max_bytes !== 0) {
  7561. throw new Error(`only specify one of max_messages or max_bytes`);
  7562. }
  7563. if (args.max_messages === 0) {
  7564. args.max_messages = 100;
  7565. }
  7566. args.expires = args.expires || 3e4;
  7567. if (args.expires < 1e3) {
  7568. throw new Error("expires should be at least 1000ms");
  7569. }
  7570. args.idle_heartbeat = args.idle_heartbeat || args.expires / 2;
  7571. args.idle_heartbeat = args.idle_heartbeat > 3e4 ? 3e4 : args.idle_heartbeat;
  7572. if (refilling) {
  7573. const minMsgs = Math.round(args.max_messages * 0.75) || 1;
  7574. args.threshold_messages = args.threshold_messages || minMsgs;
  7575. const minBytes = Math.round(args.max_bytes * 0.75) || 1;
  7576. args.threshold_bytes = args.threshold_bytes || minBytes;
  7577. }
  7578. return args;
  7579. }
  7580. status() {
  7581. const iter = new QueuedIteratorImpl();
  7582. this.listeners.push(iter);
  7583. return Promise.resolve(iter);
  7584. }
  7585. };
  7586. var OrderedConsumerMessages = class extends QueuedIteratorImpl {
  7587. constructor() {
  7588. super();
  7589. __publicField(this, "src");
  7590. __publicField(this, "listeners");
  7591. this.listeners = [];
  7592. }
  7593. setSource(src) {
  7594. if (this.src) {
  7595. this.src.resetHandler = void 0;
  7596. this.src.setCleanupHandler();
  7597. this.src.stop();
  7598. }
  7599. this.src = src;
  7600. this.src.setCleanupHandler(() => {
  7601. this.close().catch();
  7602. });
  7603. (async () => {
  7604. const status = await this.src.status();
  7605. for await (const s of status) {
  7606. this.notify(s.type, s.data);
  7607. }
  7608. })().catch(() => {
  7609. });
  7610. }
  7611. notify(type, data) {
  7612. if (this.listeners.length > 0) {
  7613. (() => {
  7614. this.listeners.forEach((l) => {
  7615. if (!l.done) {
  7616. l.push({
  7617. type,
  7618. data
  7619. });
  7620. }
  7621. });
  7622. })();
  7623. }
  7624. }
  7625. stop(err) {
  7626. var _a;
  7627. (_a = this.src) == null ? void 0 : _a.stop(err);
  7628. super.stop(err);
  7629. this.listeners.forEach((n) => {
  7630. n.stop();
  7631. });
  7632. }
  7633. close() {
  7634. this.stop();
  7635. return this.iterClosed;
  7636. }
  7637. status() {
  7638. const iter = new QueuedIteratorImpl();
  7639. this.listeners.push(iter);
  7640. return Promise.resolve(iter);
  7641. }
  7642. };
  7643. var PullConsumerImpl = class {
  7644. constructor(api, info) {
  7645. __publicField(this, "api");
  7646. __publicField(this, "_info");
  7647. __publicField(this, "stream");
  7648. __publicField(this, "name");
  7649. this.api = api;
  7650. this._info = info;
  7651. this.stream = info.stream_name;
  7652. this.name = info.name;
  7653. }
  7654. consume(opts = {
  7655. max_messages: 100,
  7656. expires: 3e4
  7657. }) {
  7658. return Promise.resolve(new PullConsumerMessagesImpl(this, opts, true));
  7659. }
  7660. fetch(opts = {
  7661. max_messages: 100,
  7662. expires: 3e4
  7663. }) {
  7664. const m = new PullConsumerMessagesImpl(this, opts, false);
  7665. const to = Math.round(m.opts.expires * 1.05);
  7666. const timer = timeout(to);
  7667. m.closed().then(() => {
  7668. timer.cancel();
  7669. });
  7670. timer.catch(() => {
  7671. m.close().catch();
  7672. });
  7673. m.trackTimeout(timer);
  7674. return Promise.resolve(m);
  7675. }
  7676. next(opts = {
  7677. expires: 3e4
  7678. }) {
  7679. const d = deferred();
  7680. const fopts = opts;
  7681. fopts.max_messages = 1;
  7682. const iter = new PullConsumerMessagesImpl(this, fopts, false);
  7683. const to = Math.round(iter.opts.expires * 1.05);
  7684. if (to >= 6e4) {
  7685. (async () => {
  7686. for await (const s of await iter.status()) {
  7687. if (s.type === ConsumerEvents.HeartbeatsMissed && s.data >= 2) {
  7688. d.reject(new Error("consumer missed heartbeats"));
  7689. break;
  7690. }
  7691. }
  7692. })().catch();
  7693. }
  7694. (async () => {
  7695. for await (const m of iter) {
  7696. d.resolve(m);
  7697. break;
  7698. }
  7699. })().catch();
  7700. const timer = timeout(to);
  7701. iter.closed().then(() => {
  7702. d.resolve(null);
  7703. timer.cancel();
  7704. }).catch((err) => {
  7705. d.reject(err);
  7706. });
  7707. timer.catch((_err) => {
  7708. d.resolve(null);
  7709. iter.close().catch();
  7710. });
  7711. iter.trackTimeout(timer);
  7712. return d;
  7713. }
  7714. delete() {
  7715. const { stream_name, name } = this._info;
  7716. return this.api.delete(stream_name, name);
  7717. }
  7718. info(cached = false) {
  7719. if (cached) {
  7720. return Promise.resolve(this._info);
  7721. }
  7722. const { stream_name, name } = this._info;
  7723. return this.api.info(stream_name, name).then((ci) => {
  7724. this._info = ci;
  7725. return this._info;
  7726. });
  7727. }
  7728. };
  7729. var OrderedPullConsumerImpl = class {
  7730. constructor(api, stream, opts = {}) {
  7731. __publicField(this, "api");
  7732. __publicField(this, "consumerOpts");
  7733. __publicField(this, "consumer");
  7734. __publicField(this, "opts");
  7735. __publicField(this, "cursor");
  7736. __publicField(this, "stream");
  7737. __publicField(this, "namePrefix");
  7738. __publicField(this, "serial");
  7739. __publicField(this, "currentConsumer");
  7740. __publicField(this, "userCallback");
  7741. __publicField(this, "iter");
  7742. __publicField(this, "type");
  7743. __publicField(this, "startSeq");
  7744. this.api = api;
  7745. this.stream = stream;
  7746. this.cursor = {
  7747. stream_seq: 1,
  7748. deliver_seq: 0
  7749. };
  7750. this.namePrefix = nuid.next();
  7751. this.serial = 0;
  7752. this.currentConsumer = null;
  7753. this.userCallback = null;
  7754. this.iter = null;
  7755. this.type = PullConsumerType.Unset;
  7756. this.consumerOpts = opts;
  7757. this.startSeq = this.consumerOpts.opt_start_seq || 0;
  7758. this.cursor.stream_seq = this.startSeq > 0 ? this.startSeq - 1 : 0;
  7759. }
  7760. getConsumerOpts(seq) {
  7761. this.serial++;
  7762. const name = `${this.namePrefix}_${this.serial}`;
  7763. seq = seq === 0 ? 1 : seq;
  7764. const config = {
  7765. name,
  7766. deliver_policy: DeliverPolicy.StartSequence,
  7767. opt_start_seq: seq,
  7768. ack_policy: AckPolicy.None,
  7769. inactive_threshold: nanos(5 * 60 * 1e3),
  7770. num_replicas: 1
  7771. };
  7772. if (this.consumerOpts.headers_only === true) {
  7773. config.headers_only = true;
  7774. }
  7775. if (Array.isArray(this.consumerOpts.filterSubjects)) {
  7776. config.filter_subjects = this.consumerOpts.filterSubjects;
  7777. }
  7778. if (typeof this.consumerOpts.filterSubjects === "string") {
  7779. config.filter_subject = this.consumerOpts.filterSubjects;
  7780. }
  7781. if (seq === this.startSeq + 1) {
  7782. config.deliver_policy = this.consumerOpts.deliver_policy || DeliverPolicy.StartSequence;
  7783. if (this.consumerOpts.deliver_policy === DeliverPolicy.LastPerSubject || this.consumerOpts.deliver_policy === DeliverPolicy.New || this.consumerOpts.deliver_policy === DeliverPolicy.Last) {
  7784. delete config.opt_start_seq;
  7785. config.deliver_policy = this.consumerOpts.deliver_policy;
  7786. }
  7787. if (config.deliver_policy === DeliverPolicy.LastPerSubject) {
  7788. if (typeof config.filter_subjects === "undefined" && typeof config.filter_subject === "undefined") {
  7789. config.filter_subject = ">";
  7790. }
  7791. }
  7792. if (this.consumerOpts.opt_start_time) {
  7793. delete config.opt_start_seq;
  7794. config.deliver_policy = DeliverPolicy.StartTime;
  7795. config.opt_start_time = this.consumerOpts.opt_start_time;
  7796. }
  7797. if (this.consumerOpts.inactive_threshold) {
  7798. config.inactive_threshold = nanos(this.consumerOpts.inactive_threshold);
  7799. }
  7800. }
  7801. return config;
  7802. }
  7803. async resetConsumer(seq = 0) {
  7804. var _a, _b;
  7805. (_a = this.consumer) == null ? void 0 : _a.delete().catch(() => {
  7806. });
  7807. seq = seq === 0 ? 1 : seq;
  7808. this.cursor.deliver_seq = 0;
  7809. const config = this.getConsumerOpts(seq);
  7810. config.max_deliver = 1;
  7811. config.mem_storage = true;
  7812. const bo = backoff();
  7813. let ci;
  7814. for (let i = 0; ; i++) {
  7815. try {
  7816. ci = await this.api.add(this.stream, config);
  7817. (_b = this.iter) == null ? void 0 : _b.notify(ConsumerEvents.OrderedConsumerRecreated, ci.name);
  7818. break;
  7819. } catch (err) {
  7820. if (seq === 0 && i >= 30) {
  7821. throw err;
  7822. } else {
  7823. await delay(bo.backoff(i + 1));
  7824. }
  7825. }
  7826. }
  7827. return ci;
  7828. }
  7829. internalHandler(serial) {
  7830. return (m) => {
  7831. var _a;
  7832. if (this.serial !== serial) {
  7833. return;
  7834. }
  7835. const dseq = m.info.deliverySequence;
  7836. if (dseq !== this.cursor.deliver_seq + 1) {
  7837. this.reset(this.opts);
  7838. return;
  7839. }
  7840. this.cursor.deliver_seq = dseq;
  7841. this.cursor.stream_seq = m.info.streamSequence;
  7842. if (this.userCallback) {
  7843. this.userCallback(m);
  7844. } else {
  7845. (_a = this.iter) == null ? void 0 : _a.push(m);
  7846. }
  7847. };
  7848. }
  7849. async reset(opts = {
  7850. max_messages: 100,
  7851. expires: 3e4
  7852. }, fromFetch = false) {
  7853. this.currentConsumer = await this.resetConsumer(this.cursor.stream_seq + 1);
  7854. if (this.iter === null) {
  7855. this.iter = new OrderedConsumerMessages();
  7856. }
  7857. this.consumer = new PullConsumerImpl(this.api, this.currentConsumer);
  7858. const copts = opts;
  7859. copts.callback = this.internalHandler(this.serial);
  7860. let msgs = null;
  7861. if (this.type === PullConsumerType.Fetch && fromFetch) {
  7862. msgs = await this.consumer.fetch(opts);
  7863. } else if (this.type === PullConsumerType.Consume) {
  7864. msgs = await this.consumer.consume(opts);
  7865. } else {
  7866. return Promise.reject("reset called with unset consumer type");
  7867. }
  7868. const msgsImpl = msgs;
  7869. msgsImpl.forOrderedConsumer = true;
  7870. msgsImpl.resetHandler = () => {
  7871. this.reset(this.opts);
  7872. };
  7873. this.iter.setSource(msgsImpl);
  7874. return this.iter;
  7875. }
  7876. consume(opts = {
  7877. max_messages: 100,
  7878. expires: 3e4
  7879. }) {
  7880. if (this.type === PullConsumerType.Fetch) {
  7881. return Promise.reject(new Error("ordered consumer initialized as fetch"));
  7882. }
  7883. if (this.type === PullConsumerType.Consume) {
  7884. return Promise.reject(new Error("ordered consumer doesn't support concurrent consume"));
  7885. }
  7886. const { callback } = opts;
  7887. if (callback) {
  7888. this.userCallback = callback;
  7889. }
  7890. this.type = PullConsumerType.Consume;
  7891. this.opts = opts;
  7892. return this.reset(opts);
  7893. }
  7894. fetch(opts = {
  7895. max_messages: 100,
  7896. expires: 3e4
  7897. }) {
  7898. var _a;
  7899. if (this.type === PullConsumerType.Consume) {
  7900. return Promise.reject(new Error("ordered consumer already initialized as consume"));
  7901. }
  7902. if (((_a = this.iter) == null ? void 0 : _a.done) === false) {
  7903. return Promise.reject(new Error("ordered consumer doesn't support concurrent fetch"));
  7904. }
  7905. const { callback } = opts;
  7906. if (callback) {
  7907. this.userCallback = callback;
  7908. }
  7909. this.type = PullConsumerType.Fetch;
  7910. this.opts = opts;
  7911. this.iter = new OrderedConsumerMessages();
  7912. return this.reset(opts, true);
  7913. }
  7914. async next(opts = {
  7915. expires: 3e4
  7916. }) {
  7917. const d = deferred();
  7918. const copts = opts;
  7919. copts.max_messages = 1;
  7920. copts.callback = (m) => {
  7921. this.userCallback = null;
  7922. d.resolve(m);
  7923. };
  7924. const iter = await this.fetch(copts);
  7925. iter.iterClosed.then(() => {
  7926. d.resolve(null);
  7927. }).catch((err) => {
  7928. d.reject(err);
  7929. });
  7930. return d;
  7931. }
  7932. delete() {
  7933. if (!this.currentConsumer) {
  7934. return Promise.resolve(false);
  7935. }
  7936. return this.api.delete(this.stream, this.currentConsumer.name).then((tf) => {
  7937. return Promise.resolve(tf);
  7938. }).catch((err) => {
  7939. return Promise.reject(err);
  7940. }).finally(() => {
  7941. this.currentConsumer = null;
  7942. });
  7943. }
  7944. async info(cached) {
  7945. if (this.currentConsumer == null) {
  7946. this.currentConsumer = await this.resetConsumer(this.serial);
  7947. return Promise.resolve(this.currentConsumer);
  7948. }
  7949. if (cached && this.currentConsumer) {
  7950. return Promise.resolve(this.currentConsumer);
  7951. }
  7952. return this.api.info(this.stream, this.currentConsumer.name);
  7953. }
  7954. };
  7955. function convertStreamSourceDomain(s) {
  7956. if (s === void 0) {
  7957. return void 0;
  7958. }
  7959. const { domain } = s;
  7960. if (domain === void 0) {
  7961. return s;
  7962. }
  7963. const copy2 = Object.assign({}, s);
  7964. delete copy2.domain;
  7965. if (domain === "") {
  7966. return copy2;
  7967. }
  7968. if (copy2.external) {
  7969. throw new Error("domain and external are both set");
  7970. }
  7971. copy2.external = {
  7972. api: `$JS.${domain}.API`
  7973. };
  7974. return copy2;
  7975. }
  7976. var PubHeaders;
  7977. var osPrefix = "OBJ_";
  7978. var ConsumersImpl = class {
  7979. constructor(api) {
  7980. __publicField(this, "api");
  7981. __publicField(this, "notified");
  7982. this.api = api;
  7983. this.notified = false;
  7984. }
  7985. checkVersion() {
  7986. const fv = this.api.nc.features.get(Feature.JS_SIMPLIFICATION);
  7987. if (!fv.ok) {
  7988. return Promise.reject(new Error(`consumers framework is only supported on servers ${fv.min} or better`));
  7989. }
  7990. return Promise.resolve();
  7991. }
  7992. async get(stream, name = {}) {
  7993. if (typeof name === "object") {
  7994. return this.ordered(stream, name);
  7995. }
  7996. await this.checkVersion();
  7997. return this.api.info(stream, name).then((ci) => {
  7998. if (ci.config.deliver_subject !== void 0) {
  7999. return Promise.reject(new Error("push consumer not supported"));
  8000. }
  8001. return new PullConsumerImpl(this.api, ci);
  8002. }).catch((err) => {
  8003. return Promise.reject(err);
  8004. });
  8005. }
  8006. async ordered(stream, opts) {
  8007. await this.checkVersion();
  8008. const impl = this.api;
  8009. const sapi = new StreamAPIImpl(impl.nc, impl.opts);
  8010. return sapi.info(stream).then((_si) => {
  8011. return Promise.resolve(new OrderedPullConsumerImpl(this.api, stream, opts));
  8012. }).catch((err) => {
  8013. return Promise.reject(err);
  8014. });
  8015. }
  8016. };
  8017. var StreamImpl = class {
  8018. constructor(api, info) {
  8019. __publicField(this, "api");
  8020. __publicField(this, "_info");
  8021. this.api = api;
  8022. this._info = info;
  8023. }
  8024. get name() {
  8025. return this._info.config.name;
  8026. }
  8027. alternates() {
  8028. return this.info().then((si) => {
  8029. return si.alternates ? si.alternates : [];
  8030. });
  8031. }
  8032. async best() {
  8033. await this.info();
  8034. if (this._info.alternates) {
  8035. const asi = await this.api.info(this._info.alternates[0].name);
  8036. return new StreamImpl(this.api, asi);
  8037. } else {
  8038. return this;
  8039. }
  8040. }
  8041. info(cached = false, opts) {
  8042. if (cached) {
  8043. return Promise.resolve(this._info);
  8044. }
  8045. return this.api.info(this.name, opts).then((si) => {
  8046. this._info = si;
  8047. return this._info;
  8048. });
  8049. }
  8050. getConsumer(name) {
  8051. return new ConsumersImpl(new ConsumerAPIImpl(this.api.nc, this.api.opts)).get(this.name, name);
  8052. }
  8053. getMessage(query) {
  8054. return this.api.getMessage(this.name, query);
  8055. }
  8056. deleteMessage(seq, erase) {
  8057. return this.api.deleteMessage(this.name, seq, erase);
  8058. }
  8059. };
  8060. function NoopKvCodecs() {
  8061. return {
  8062. key: {
  8063. encode(k) {
  8064. return k;
  8065. },
  8066. decode(k) {
  8067. return k;
  8068. }
  8069. },
  8070. value: {
  8071. encode(v) {
  8072. return v;
  8073. },
  8074. decode(v) {
  8075. return v;
  8076. }
  8077. }
  8078. };
  8079. }
  8080. function defaultBucketOpts() {
  8081. return {
  8082. replicas: 1,
  8083. history: 1,
  8084. timeout: 2e3,
  8085. maxBucketSize: -1,
  8086. maxValueSize: -1,
  8087. codec: NoopKvCodecs(),
  8088. storage: StorageType.File
  8089. };
  8090. }
  8091. var kvOperationHdr = "KV-Operation";
  8092. var kvSubjectPrefix = "$KV";
  8093. var validKeyRe = /^[-/=.\w]+$/;
  8094. var validSearchKey = /^[-/=.>*\w]+$/;
  8095. var validBucketRe = /^[-\w]+$/;
  8096. function validateKey(k) {
  8097. if (k.startsWith(".") || k.endsWith(".") || !validKeyRe.test(k)) {
  8098. throw new Error(`invalid key: ${k}`);
  8099. }
  8100. }
  8101. function validateSearchKey(k) {
  8102. if (k.startsWith(".") || k.endsWith(".") || !validSearchKey.test(k)) {
  8103. throw new Error(`invalid key: ${k}`);
  8104. }
  8105. }
  8106. function hasWildcards(k) {
  8107. if (k.startsWith(".") || k.endsWith(".")) {
  8108. throw new Error(`invalid key: ${k}`);
  8109. }
  8110. const chunks = k.split(".");
  8111. let hasWildcards2 = false;
  8112. for (let i = 0; i < chunks.length; i++) {
  8113. switch (chunks[i]) {
  8114. case "*":
  8115. hasWildcards2 = true;
  8116. break;
  8117. case ">":
  8118. if (i !== chunks.length - 1) {
  8119. throw new Error(`invalid key: ${k}`);
  8120. }
  8121. hasWildcards2 = true;
  8122. break;
  8123. default:
  8124. }
  8125. }
  8126. return hasWildcards2;
  8127. }
  8128. function validateBucket(name) {
  8129. if (!validBucketRe.test(name)) {
  8130. throw new Error(`invalid bucket name: ${name}`);
  8131. }
  8132. }
  8133. (function(PubHeaders2) {
  8134. PubHeaders2["MsgIdHdr"] = "Nats-Msg-Id";
  8135. PubHeaders2["ExpectedStreamHdr"] = "Nats-Expected-Stream";
  8136. PubHeaders2["ExpectedLastSeqHdr"] = "Nats-Expected-Last-Sequence";
  8137. PubHeaders2["ExpectedLastMsgIdHdr"] = "Nats-Expected-Last-Msg-Id";
  8138. PubHeaders2["ExpectedLastSubjectSequenceHdr"] = "Nats-Expected-Last-Subject-Sequence";
  8139. })(PubHeaders || (PubHeaders = {}));
  8140. var Bucket = class {
  8141. constructor(bucket, js, jsm) {
  8142. __publicField(this, "js");
  8143. __publicField(this, "jsm");
  8144. __publicField(this, "stream");
  8145. __publicField(this, "bucket");
  8146. __publicField(this, "direct");
  8147. __publicField(this, "codec");
  8148. __publicField(this, "prefix");
  8149. __publicField(this, "editPrefix");
  8150. __publicField(this, "useJsPrefix");
  8151. __publicField(this, "_prefixLen");
  8152. __publicField(this, "validateKey", validateKey);
  8153. __publicField(this, "validateSearchKey", validateSearchKey);
  8154. __publicField(this, "hasWildcards", hasWildcards);
  8155. validateBucket(bucket);
  8156. this.js = js;
  8157. this.jsm = jsm;
  8158. this.bucket = bucket;
  8159. this.prefix = kvSubjectPrefix;
  8160. this.editPrefix = "";
  8161. this.useJsPrefix = false;
  8162. this._prefixLen = 0;
  8163. }
  8164. static async create(js, name, opts = {}) {
  8165. validateBucket(name);
  8166. const jsm = await js.jetstreamManager();
  8167. const bucket = new Bucket(name, js, jsm);
  8168. await bucket.init(opts);
  8169. return bucket;
  8170. }
  8171. static async bind(js, name, opts = {}) {
  8172. const jsm = await js.jetstreamManager();
  8173. const info = await jsm.streams.info(`${kvPrefix}${name}`);
  8174. validateBucket(info.config.name);
  8175. const bucket = new Bucket(name, js, jsm);
  8176. Object.assign(bucket, info);
  8177. bucket.codec = opts.codec || NoopKvCodecs();
  8178. bucket.direct = info.config.allow_direct ?? false;
  8179. bucket.initializePrefixes(info);
  8180. return bucket;
  8181. }
  8182. async init(opts = {}) {
  8183. const bo = Object.assign(defaultBucketOpts(), opts);
  8184. this.codec = bo.codec;
  8185. const sc = {};
  8186. this.stream = sc.name = opts.streamName ?? this.bucketName();
  8187. sc.retention = RetentionPolicy.Limits;
  8188. sc.max_msgs_per_subject = bo.history;
  8189. if (bo.maxBucketSize) {
  8190. bo.max_bytes = bo.maxBucketSize;
  8191. }
  8192. if (bo.max_bytes) {
  8193. sc.max_bytes = bo.max_bytes;
  8194. }
  8195. sc.max_msg_size = bo.maxValueSize;
  8196. sc.storage = bo.storage;
  8197. const location = opts.placementCluster ?? "";
  8198. if (location) {
  8199. opts.placement = {};
  8200. opts.placement.cluster = location;
  8201. opts.placement.tags = [];
  8202. }
  8203. if (opts.placement) {
  8204. sc.placement = opts.placement;
  8205. }
  8206. if (opts.republish) {
  8207. sc.republish = opts.republish;
  8208. }
  8209. if (opts.description) {
  8210. sc.description = opts.description;
  8211. }
  8212. if (opts.mirror) {
  8213. const mirror = Object.assign({}, opts.mirror);
  8214. if (!mirror.name.startsWith(kvPrefix)) {
  8215. mirror.name = `${kvPrefix}${mirror.name}`;
  8216. }
  8217. sc.mirror = mirror;
  8218. sc.mirror_direct = true;
  8219. } else if (opts.sources) {
  8220. const sources = opts.sources.map((s) => {
  8221. const c = Object.assign({}, s);
  8222. if (!c.name.startsWith(kvPrefix)) {
  8223. c.name = `${kvPrefix}${c.name}`;
  8224. }
  8225. });
  8226. sc.sources = sources;
  8227. } else {
  8228. sc.subjects = [
  8229. this.subjectForBucket()
  8230. ];
  8231. }
  8232. if (opts.metadata) {
  8233. sc.metadata = opts.metadata;
  8234. }
  8235. if (typeof opts.compression === "boolean") {
  8236. sc.compression = opts.compression ? StoreCompression.S2 : StoreCompression.None;
  8237. }
  8238. const nci = this.js.nc;
  8239. const have = nci.getServerVersion();
  8240. const discardNew = have ? compare(have, parseSemVer("2.7.2")) >= 0 : false;
  8241. sc.discard = discardNew ? DiscardPolicy.New : DiscardPolicy.Old;
  8242. const { ok: direct, min } = nci.features.get(Feature.JS_ALLOW_DIRECT);
  8243. if (!direct && opts.allow_direct === true) {
  8244. const v = have ? `${have.major}.${have.minor}.${have.micro}` : "unknown";
  8245. return Promise.reject(new Error(`allow_direct is not available on server version ${v} - requires ${min}`));
  8246. }
  8247. opts.allow_direct = typeof opts.allow_direct === "boolean" ? opts.allow_direct : direct;
  8248. sc.allow_direct = opts.allow_direct;
  8249. this.direct = sc.allow_direct;
  8250. sc.num_replicas = bo.replicas;
  8251. if (bo.ttl) {
  8252. sc.max_age = nanos(bo.ttl);
  8253. }
  8254. sc.allow_rollup_hdrs = true;
  8255. let info;
  8256. try {
  8257. info = await this.jsm.streams.info(sc.name);
  8258. if (!info.config.allow_direct && this.direct === true) {
  8259. this.direct = false;
  8260. }
  8261. } catch (err) {
  8262. if (err.message === "stream not found") {
  8263. info = await this.jsm.streams.add(sc);
  8264. } else {
  8265. throw err;
  8266. }
  8267. }
  8268. this.initializePrefixes(info);
  8269. }
  8270. initializePrefixes(info) {
  8271. this._prefixLen = 0;
  8272. this.prefix = `$KV.${this.bucket}`;
  8273. this.useJsPrefix = this.js.apiPrefix !== "$JS.API";
  8274. const { mirror } = info.config;
  8275. if (mirror) {
  8276. let n = mirror.name;
  8277. if (n.startsWith(kvPrefix)) {
  8278. n = n.substring(kvPrefix.length);
  8279. }
  8280. if (mirror.external && mirror.external.api !== "") {
  8281. const mb = mirror.name.substring(kvPrefix.length);
  8282. this.useJsPrefix = false;
  8283. this.prefix = `$KV.${mb}`;
  8284. this.editPrefix = `${mirror.external.api}.$KV.${n}`;
  8285. } else {
  8286. this.editPrefix = this.prefix;
  8287. }
  8288. }
  8289. }
  8290. bucketName() {
  8291. return this.stream ?? `${kvPrefix}${this.bucket}`;
  8292. }
  8293. subjectForBucket() {
  8294. return `${this.prefix}.${this.bucket}.>`;
  8295. }
  8296. subjectForKey(k, edit = false) {
  8297. const builder = [];
  8298. if (edit) {
  8299. if (this.useJsPrefix) {
  8300. builder.push(this.js.apiPrefix);
  8301. }
  8302. if (this.editPrefix !== "") {
  8303. builder.push(this.editPrefix);
  8304. } else {
  8305. builder.push(this.prefix);
  8306. }
  8307. } else {
  8308. if (this.prefix) {
  8309. builder.push(this.prefix);
  8310. }
  8311. }
  8312. builder.push(k);
  8313. return builder.join(".");
  8314. }
  8315. fullKeyName(k) {
  8316. if (this.prefix !== "") {
  8317. return `${this.prefix}.${k}`;
  8318. }
  8319. return `${kvSubjectPrefix}.${this.bucket}.${k}`;
  8320. }
  8321. get prefixLen() {
  8322. if (this._prefixLen === 0) {
  8323. this._prefixLen = this.prefix.length + 1;
  8324. }
  8325. return this._prefixLen;
  8326. }
  8327. encodeKey(key) {
  8328. const chunks = [];
  8329. for (const t of key.split(".")) {
  8330. switch (t) {
  8331. case ">":
  8332. case "*":
  8333. chunks.push(t);
  8334. break;
  8335. default:
  8336. chunks.push(this.codec.key.encode(t));
  8337. break;
  8338. }
  8339. }
  8340. return chunks.join(".");
  8341. }
  8342. decodeKey(ekey) {
  8343. const chunks = [];
  8344. for (const t of ekey.split(".")) {
  8345. switch (t) {
  8346. case ">":
  8347. case "*":
  8348. chunks.push(t);
  8349. break;
  8350. default:
  8351. chunks.push(this.codec.key.decode(t));
  8352. break;
  8353. }
  8354. }
  8355. return chunks.join(".");
  8356. }
  8357. close() {
  8358. return Promise.resolve();
  8359. }
  8360. dataLen(data, h) {
  8361. const slen = h ? h.get(JsHeaders.MessageSizeHdr) || "" : "";
  8362. if (slen !== "") {
  8363. return parseInt(slen, 10);
  8364. }
  8365. return data.length;
  8366. }
  8367. smToEntry(sm) {
  8368. return new KvStoredEntryImpl(this.bucket, this.prefixLen, sm);
  8369. }
  8370. jmToEntry(jm) {
  8371. const key = this.decodeKey(jm.subject.substring(this.prefixLen));
  8372. return new KvJsMsgEntryImpl(this.bucket, key, jm);
  8373. }
  8374. async create(k, data) {
  8375. var _a;
  8376. let firstErr;
  8377. try {
  8378. const n = await this.put(k, data, {
  8379. previousSeq: 0
  8380. });
  8381. return Promise.resolve(n);
  8382. } catch (err) {
  8383. firstErr = err;
  8384. if (((_a = err == null ? void 0 : err.api_error) == null ? void 0 : _a.err_code) !== 10071) {
  8385. return Promise.reject(err);
  8386. }
  8387. }
  8388. let rev = 0;
  8389. try {
  8390. const e = await this.get(k);
  8391. if ((e == null ? void 0 : e.operation) === "DEL" || (e == null ? void 0 : e.operation) === "PURGE") {
  8392. rev = e !== null ? e.revision : 0;
  8393. return this.update(k, data, rev);
  8394. } else {
  8395. return Promise.reject(firstErr);
  8396. }
  8397. } catch (err) {
  8398. return Promise.reject(err);
  8399. }
  8400. }
  8401. update(k, data, version) {
  8402. if (version <= 0) {
  8403. throw new Error("version must be greater than 0");
  8404. }
  8405. return this.put(k, data, {
  8406. previousSeq: version
  8407. });
  8408. }
  8409. async put(k, data, opts = {}) {
  8410. var _a, _b;
  8411. const ek = this.encodeKey(k);
  8412. this.validateKey(ek);
  8413. const o = {};
  8414. if (opts.previousSeq !== void 0) {
  8415. const h = headers();
  8416. o.headers = h;
  8417. h.set(PubHeaders.ExpectedLastSubjectSequenceHdr, `${opts.previousSeq}`);
  8418. }
  8419. try {
  8420. const pa = await this.js.publish(this.subjectForKey(ek, true), data, o);
  8421. return pa.seq;
  8422. } catch (err) {
  8423. const ne = err;
  8424. if (ne.isJetStreamError()) {
  8425. ne.message = (_a = ne.api_error) == null ? void 0 : _a.description;
  8426. ne.code = `${(_b = ne.api_error) == null ? void 0 : _b.code}`;
  8427. return Promise.reject(ne);
  8428. }
  8429. return Promise.reject(err);
  8430. }
  8431. }
  8432. async get(k, opts) {
  8433. const ek = this.encodeKey(k);
  8434. this.validateKey(ek);
  8435. let arg = {
  8436. last_by_subj: this.subjectForKey(ek)
  8437. };
  8438. if (opts && opts.revision > 0) {
  8439. arg = {
  8440. seq: opts.revision
  8441. };
  8442. }
  8443. let sm;
  8444. try {
  8445. if (this.direct) {
  8446. const direct = this.jsm.direct;
  8447. sm = await direct.getMessage(this.bucketName(), arg);
  8448. } else {
  8449. sm = await this.jsm.streams.getMessage(this.bucketName(), arg);
  8450. }
  8451. const ke = this.smToEntry(sm);
  8452. if (ke.key !== ek) {
  8453. return null;
  8454. }
  8455. return ke;
  8456. } catch (err) {
  8457. if (err.code === ErrorCode.JetStream404NoMessages) {
  8458. return null;
  8459. }
  8460. throw err;
  8461. }
  8462. }
  8463. purge(k) {
  8464. return this._deleteOrPurge(k, "PURGE");
  8465. }
  8466. delete(k) {
  8467. return this._deleteOrPurge(k, "DEL");
  8468. }
  8469. async purgeDeletes(olderMillis = 30 * 60 * 1e3) {
  8470. const done = deferred();
  8471. const buf = [];
  8472. const i = await this.watch({
  8473. key: ">",
  8474. initializedFn: () => {
  8475. done.resolve();
  8476. }
  8477. });
  8478. (async () => {
  8479. for await (const e of i) {
  8480. if (e.operation === "DEL" || e.operation === "PURGE") {
  8481. buf.push(e);
  8482. }
  8483. }
  8484. })().then();
  8485. await done;
  8486. i.stop();
  8487. const min = Date.now() - olderMillis;
  8488. const proms = buf.map((e) => {
  8489. const subj = this.subjectForKey(e.key);
  8490. if (e.created.getTime() >= min) {
  8491. return this.jsm.streams.purge(this.stream, {
  8492. filter: subj,
  8493. keep: 1
  8494. });
  8495. } else {
  8496. return this.jsm.streams.purge(this.stream, {
  8497. filter: subj,
  8498. keep: 0
  8499. });
  8500. }
  8501. });
  8502. const purged = await Promise.all(proms);
  8503. purged.unshift({
  8504. success: true,
  8505. purged: 0
  8506. });
  8507. return purged.reduce((pv, cv) => {
  8508. pv.purged += cv.purged;
  8509. return pv;
  8510. });
  8511. }
  8512. async _deleteOrPurge(k, op) {
  8513. if (!this.hasWildcards(k)) {
  8514. return this._doDeleteOrPurge(k, op);
  8515. }
  8516. const iter = await this.keys(k);
  8517. const buf = [];
  8518. for await (const k2 of iter) {
  8519. buf.push(this._doDeleteOrPurge(k2, op));
  8520. if (buf.length === 100) {
  8521. await Promise.all(buf);
  8522. buf.length = 0;
  8523. }
  8524. }
  8525. if (buf.length > 0) {
  8526. await Promise.all(buf);
  8527. }
  8528. }
  8529. async _doDeleteOrPurge(k, op) {
  8530. const ek = this.encodeKey(k);
  8531. this.validateKey(ek);
  8532. const h = headers();
  8533. h.set(kvOperationHdr, op);
  8534. if (op === "PURGE") {
  8535. h.set(JsHeaders.RollupHdr, JsHeaders.RollupValueSubject);
  8536. }
  8537. await this.js.publish(this.subjectForKey(ek, true), Empty, {
  8538. headers: h
  8539. });
  8540. }
  8541. _buildCC(k, content, opts = {}) {
  8542. const ek = this.encodeKey(k);
  8543. this.validateSearchKey(k);
  8544. let deliver_policy = DeliverPolicy.LastPerSubject;
  8545. if (content === KvWatchInclude.AllHistory) {
  8546. deliver_policy = DeliverPolicy.All;
  8547. }
  8548. if (content === KvWatchInclude.UpdatesOnly) {
  8549. deliver_policy = DeliverPolicy.New;
  8550. }
  8551. return Object.assign({
  8552. deliver_policy,
  8553. "ack_policy": AckPolicy.None,
  8554. "filter_subject": this.fullKeyName(ek),
  8555. "flow_control": true,
  8556. "idle_heartbeat": nanos(5 * 1e3)
  8557. }, opts);
  8558. }
  8559. remove(k) {
  8560. return this.purge(k);
  8561. }
  8562. async history(opts = {}) {
  8563. const k = opts.key ?? ">";
  8564. const qi = new QueuedIteratorImpl();
  8565. const co = {};
  8566. co.headers_only = opts.headers_only || false;
  8567. let fn;
  8568. fn = () => {
  8569. qi.stop();
  8570. };
  8571. let count = 0;
  8572. const cc2 = this._buildCC(k, KvWatchInclude.AllHistory, co);
  8573. const subj = cc2.filter_subject;
  8574. const copts = consumerOpts(cc2);
  8575. copts.bindStream(this.stream);
  8576. copts.orderedConsumer();
  8577. copts.callback((err, jm) => {
  8578. if (err) {
  8579. qi.stop(err);
  8580. return;
  8581. }
  8582. if (jm) {
  8583. const e = this.jmToEntry(jm);
  8584. qi.push(e);
  8585. qi.received++;
  8586. if (fn && count > 0 && qi.received >= count || jm.info.pending === 0) {
  8587. qi.push(fn);
  8588. fn = void 0;
  8589. }
  8590. }
  8591. });
  8592. const sub = await this.js.subscribe(subj, copts);
  8593. if (fn) {
  8594. const { info: { last } } = sub;
  8595. const expect = last.num_pending + last.delivered.consumer_seq;
  8596. if (expect === 0 || qi.received >= expect) {
  8597. try {
  8598. fn();
  8599. } catch (err) {
  8600. qi.stop(err);
  8601. } finally {
  8602. fn = void 0;
  8603. }
  8604. } else {
  8605. count = expect;
  8606. }
  8607. }
  8608. qi._data = sub;
  8609. qi.iterClosed.then(() => {
  8610. sub.unsubscribe();
  8611. });
  8612. sub.closed.then(() => {
  8613. qi.stop();
  8614. }).catch((err) => {
  8615. qi.stop(err);
  8616. });
  8617. return qi;
  8618. }
  8619. async watch(opts = {}) {
  8620. const k = opts.key ?? ">";
  8621. const qi = new QueuedIteratorImpl();
  8622. const co = {};
  8623. co.headers_only = opts.headers_only || false;
  8624. let content = KvWatchInclude.LastValue;
  8625. if (opts.include === KvWatchInclude.AllHistory) {
  8626. content = KvWatchInclude.AllHistory;
  8627. } else if (opts.include === KvWatchInclude.UpdatesOnly) {
  8628. content = KvWatchInclude.UpdatesOnly;
  8629. }
  8630. const ignoreDeletes = opts.ignoreDeletes === true;
  8631. let fn = opts.initializedFn;
  8632. let count = 0;
  8633. const cc2 = this._buildCC(k, content, co);
  8634. const subj = cc2.filter_subject;
  8635. const copts = consumerOpts(cc2);
  8636. copts.bindStream(this.stream);
  8637. copts.orderedConsumer();
  8638. copts.callback((err, jm) => {
  8639. if (err) {
  8640. qi.stop(err);
  8641. return;
  8642. }
  8643. if (jm) {
  8644. const e = this.jmToEntry(jm);
  8645. if (ignoreDeletes && e.operation === "DEL") {
  8646. return;
  8647. }
  8648. qi.push(e);
  8649. qi.received++;
  8650. if (fn && (count > 0 && qi.received >= count || jm.info.pending === 0)) {
  8651. qi.push(fn);
  8652. fn = void 0;
  8653. }
  8654. }
  8655. });
  8656. const sub = await this.js.subscribe(subj, copts);
  8657. if (fn) {
  8658. const { info: { last } } = sub;
  8659. const expect = last.num_pending + last.delivered.consumer_seq;
  8660. if (expect === 0 || qi.received >= expect) {
  8661. try {
  8662. fn();
  8663. } catch (err) {
  8664. qi.stop(err);
  8665. } finally {
  8666. fn = void 0;
  8667. }
  8668. } else {
  8669. count = expect;
  8670. }
  8671. }
  8672. qi._data = sub;
  8673. qi.iterClosed.then(() => {
  8674. sub.unsubscribe();
  8675. });
  8676. sub.closed.then(() => {
  8677. qi.stop();
  8678. }).catch((err) => {
  8679. qi.stop(err);
  8680. });
  8681. return qi;
  8682. }
  8683. async keys(k = ">") {
  8684. const keys = new QueuedIteratorImpl();
  8685. const cc2 = this._buildCC(k, KvWatchInclude.LastValue, {
  8686. headers_only: true
  8687. });
  8688. const subj = cc2.filter_subject;
  8689. const copts = consumerOpts(cc2);
  8690. copts.bindStream(this.stream);
  8691. copts.orderedConsumer();
  8692. const sub = await this.js.subscribe(subj, copts);
  8693. (async () => {
  8694. var _a;
  8695. for await (const jm of sub) {
  8696. const op = (_a = jm.headers) == null ? void 0 : _a.get(kvOperationHdr);
  8697. if (op !== "DEL" && op !== "PURGE") {
  8698. const key = this.decodeKey(jm.subject.substring(this.prefixLen));
  8699. keys.push(key);
  8700. }
  8701. if (jm.info.pending === 0) {
  8702. sub.unsubscribe();
  8703. }
  8704. }
  8705. })().then(() => {
  8706. keys.stop();
  8707. }).catch((err) => {
  8708. keys.stop(err);
  8709. });
  8710. const si = sub;
  8711. if (si.info.last.num_pending === 0) {
  8712. sub.unsubscribe();
  8713. }
  8714. return keys;
  8715. }
  8716. purgeBucket(opts) {
  8717. return this.jsm.streams.purge(this.bucketName(), opts);
  8718. }
  8719. destroy() {
  8720. return this.jsm.streams.delete(this.bucketName());
  8721. }
  8722. async status() {
  8723. var _a;
  8724. const nc = this.js.nc;
  8725. const cluster = ((_a = nc.info) == null ? void 0 : _a.cluster) ?? "";
  8726. const bn = this.bucketName();
  8727. const si = await this.jsm.streams.info(bn);
  8728. return new KvStatusImpl(si, cluster);
  8729. }
  8730. };
  8731. var KvStatusImpl = class {
  8732. constructor(si, cluster = "") {
  8733. __publicField(this, "si");
  8734. __publicField(this, "cluster");
  8735. this.si = si;
  8736. this.cluster = cluster;
  8737. }
  8738. get bucket() {
  8739. return this.si.config.name.startsWith(kvPrefix) ? this.si.config.name.substring(kvPrefix.length) : this.si.config.name;
  8740. }
  8741. get values() {
  8742. return this.si.state.messages;
  8743. }
  8744. get history() {
  8745. return this.si.config.max_msgs_per_subject;
  8746. }
  8747. get ttl() {
  8748. return millis(this.si.config.max_age);
  8749. }
  8750. get bucket_location() {
  8751. return this.cluster;
  8752. }
  8753. get backingStore() {
  8754. return this.si.config.storage;
  8755. }
  8756. get storage() {
  8757. return this.si.config.storage;
  8758. }
  8759. get replicas() {
  8760. return this.si.config.num_replicas;
  8761. }
  8762. get description() {
  8763. return this.si.config.description ?? "";
  8764. }
  8765. get maxBucketSize() {
  8766. return this.si.config.max_bytes;
  8767. }
  8768. get maxValueSize() {
  8769. return this.si.config.max_msg_size;
  8770. }
  8771. get max_bytes() {
  8772. return this.si.config.max_bytes;
  8773. }
  8774. get placement() {
  8775. return this.si.config.placement || {
  8776. cluster: "",
  8777. tags: []
  8778. };
  8779. }
  8780. get placementCluster() {
  8781. var _a;
  8782. return ((_a = this.si.config.placement) == null ? void 0 : _a.cluster) ?? "";
  8783. }
  8784. get republish() {
  8785. return this.si.config.republish ?? {
  8786. src: "",
  8787. dest: ""
  8788. };
  8789. }
  8790. get streamInfo() {
  8791. return this.si;
  8792. }
  8793. get size() {
  8794. return this.si.state.bytes;
  8795. }
  8796. get metadata() {
  8797. return this.si.config.metadata ?? {};
  8798. }
  8799. get compression() {
  8800. if (this.si.config.compression) {
  8801. return this.si.config.compression !== StoreCompression.None;
  8802. }
  8803. return false;
  8804. }
  8805. };
  8806. var digestType = "SHA-256=";
  8807. function objectStoreStreamName(bucket) {
  8808. validateBucket(bucket);
  8809. return `${osPrefix}${bucket}`;
  8810. }
  8811. function objectStoreBucketName(stream) {
  8812. if (stream.startsWith(osPrefix)) {
  8813. return stream.substring(4);
  8814. }
  8815. return stream;
  8816. }
  8817. var ObjectStoreStatusImpl = class {
  8818. constructor(si) {
  8819. __publicField(this, "si");
  8820. __publicField(this, "backingStore");
  8821. this.si = si;
  8822. this.backingStore = "JetStream";
  8823. }
  8824. get bucket() {
  8825. return objectStoreBucketName(this.si.config.name);
  8826. }
  8827. get description() {
  8828. return this.si.config.description ?? "";
  8829. }
  8830. get ttl() {
  8831. return this.si.config.max_age;
  8832. }
  8833. get storage() {
  8834. return this.si.config.storage;
  8835. }
  8836. get replicas() {
  8837. return this.si.config.num_replicas;
  8838. }
  8839. get sealed() {
  8840. return this.si.config.sealed;
  8841. }
  8842. get size() {
  8843. return this.si.state.bytes;
  8844. }
  8845. get streamInfo() {
  8846. return this.si;
  8847. }
  8848. get metadata() {
  8849. return this.si.config.metadata;
  8850. }
  8851. get compression() {
  8852. if (this.si.config.compression) {
  8853. return this.si.config.compression !== StoreCompression.None;
  8854. }
  8855. return false;
  8856. }
  8857. };
  8858. var StreamAPIImpl = class extends BaseApiClient {
  8859. constructor(nc, opts) {
  8860. super(nc, opts);
  8861. }
  8862. checkStreamConfigVersions(cfg) {
  8863. const nci = this.nc;
  8864. if (cfg.metadata) {
  8865. const { min, ok } = nci.features.get(Feature.JS_STREAM_CONSUMER_METADATA);
  8866. if (!ok) {
  8867. throw new Error(`stream 'metadata' requires server ${min}`);
  8868. }
  8869. }
  8870. if (cfg.first_seq) {
  8871. const { min, ok } = nci.features.get(Feature.JS_STREAM_FIRST_SEQ);
  8872. if (!ok) {
  8873. throw new Error(`stream 'first_seq' requires server ${min}`);
  8874. }
  8875. }
  8876. if (cfg.subject_transform) {
  8877. const { min, ok } = nci.features.get(Feature.JS_STREAM_SUBJECT_TRANSFORM);
  8878. if (!ok) {
  8879. throw new Error(`stream 'subject_transform' requires server ${min}`);
  8880. }
  8881. }
  8882. if (cfg.compression) {
  8883. const { min, ok } = nci.features.get(Feature.JS_STREAM_COMPRESSION);
  8884. if (!ok) {
  8885. throw new Error(`stream 'compression' requires server ${min}`);
  8886. }
  8887. }
  8888. if (cfg.consumer_limits) {
  8889. const { min, ok } = nci.features.get(Feature.JS_DEFAULT_CONSUMER_LIMITS);
  8890. if (!ok) {
  8891. throw new Error(`stream 'consumer_limits' requires server ${min}`);
  8892. }
  8893. }
  8894. function validateStreamSource(context, src) {
  8895. var _a;
  8896. const count = ((_a = src.subject_transforms) == null ? void 0 : _a.length) || 0;
  8897. if (count > 0) {
  8898. const { min, ok } = nci.features.get(Feature.JS_STREAM_SOURCE_SUBJECT_TRANSFORM);
  8899. if (!ok) {
  8900. throw new Error(`${context} 'subject_transforms' requires server ${min}`);
  8901. }
  8902. }
  8903. }
  8904. if (cfg.sources) {
  8905. cfg.sources.forEach((src) => {
  8906. validateStreamSource("stream sources", src);
  8907. });
  8908. }
  8909. if (cfg.mirror) {
  8910. validateStreamSource("stream mirror", cfg.mirror);
  8911. }
  8912. }
  8913. async add(cfg = {}) {
  8914. var _a;
  8915. this.checkStreamConfigVersions(cfg);
  8916. validateStreamName(cfg.name);
  8917. cfg.mirror = convertStreamSourceDomain(cfg.mirror);
  8918. cfg.sources = (_a = cfg.sources) == null ? void 0 : _a.map(convertStreamSourceDomain);
  8919. const r = await this._request(`${this.prefix}.STREAM.CREATE.${cfg.name}`, cfg);
  8920. const si = r;
  8921. this._fixInfo(si);
  8922. return si;
  8923. }
  8924. async delete(stream) {
  8925. validateStreamName(stream);
  8926. const r = await this._request(`${this.prefix}.STREAM.DELETE.${stream}`);
  8927. const cr = r;
  8928. return cr.success;
  8929. }
  8930. async update(name, cfg = {}) {
  8931. var _a;
  8932. if (typeof name === "object") {
  8933. const sc = name;
  8934. name = sc.name;
  8935. cfg = sc;
  8936. console.trace(`\x1B[33m >> streams.update(config: StreamConfig) api changed to streams.update(name: string, config: StreamUpdateConfig) - this shim will be removed - update your code. \x1B[0m`);
  8937. }
  8938. this.checkStreamConfigVersions(cfg);
  8939. validateStreamName(name);
  8940. const old = await this.info(name);
  8941. const update = Object.assign(old.config, cfg);
  8942. update.mirror = convertStreamSourceDomain(update.mirror);
  8943. update.sources = (_a = update.sources) == null ? void 0 : _a.map(convertStreamSourceDomain);
  8944. const r = await this._request(`${this.prefix}.STREAM.UPDATE.${name}`, update);
  8945. const si = r;
  8946. this._fixInfo(si);
  8947. return si;
  8948. }
  8949. async info(name, data) {
  8950. validateStreamName(name);
  8951. const subj = `${this.prefix}.STREAM.INFO.${name}`;
  8952. const r = await this._request(subj, data);
  8953. let si = r;
  8954. let { total, limit } = si;
  8955. let have = si.state.subjects ? Object.getOwnPropertyNames(si.state.subjects).length : 1;
  8956. if (total && total > have) {
  8957. const infos = [
  8958. si
  8959. ];
  8960. const paged = data || {};
  8961. let i = 0;
  8962. while (total > have) {
  8963. i++;
  8964. paged.offset = limit * i;
  8965. const r2 = await this._request(subj, paged);
  8966. total = r2.total;
  8967. infos.push(r2);
  8968. const count = Object.getOwnPropertyNames(r2.state.subjects).length;
  8969. have += count;
  8970. if (count < limit) {
  8971. break;
  8972. }
  8973. }
  8974. let subjects = {};
  8975. for (let i2 = 0; i2 < infos.length; i2++) {
  8976. si = infos[i2];
  8977. if (si.state.subjects) {
  8978. subjects = Object.assign(subjects, si.state.subjects);
  8979. }
  8980. }
  8981. si.offset = 0;
  8982. si.total = 0;
  8983. si.limit = 0;
  8984. si.state.subjects = subjects;
  8985. }
  8986. this._fixInfo(si);
  8987. return si;
  8988. }
  8989. list(subject = "") {
  8990. const payload = (subject == null ? void 0 : subject.length) ? {
  8991. subject
  8992. } : {};
  8993. const listerFilter = (v) => {
  8994. const slr = v;
  8995. slr.streams.forEach((si) => {
  8996. this._fixInfo(si);
  8997. });
  8998. return slr.streams;
  8999. };
  9000. const subj = `${this.prefix}.STREAM.LIST`;
  9001. return new ListerImpl(subj, listerFilter, this, payload);
  9002. }
  9003. _fixInfo(si) {
  9004. si.config.sealed = si.config.sealed || false;
  9005. si.config.deny_delete = si.config.deny_delete || false;
  9006. si.config.deny_purge = si.config.deny_purge || false;
  9007. si.config.allow_rollup_hdrs = si.config.allow_rollup_hdrs || false;
  9008. }
  9009. async purge(name, opts) {
  9010. if (opts) {
  9011. const { keep, seq } = opts;
  9012. if (typeof keep === "number" && typeof seq === "number") {
  9013. throw new Error("can specify one of keep or seq");
  9014. }
  9015. }
  9016. validateStreamName(name);
  9017. const v = await this._request(`${this.prefix}.STREAM.PURGE.${name}`, opts);
  9018. return v;
  9019. }
  9020. async deleteMessage(stream, seq, erase = true) {
  9021. validateStreamName(stream);
  9022. const dr = {
  9023. seq
  9024. };
  9025. if (!erase) {
  9026. dr.no_erase = true;
  9027. }
  9028. const r = await this._request(`${this.prefix}.STREAM.MSG.DELETE.${stream}`, dr);
  9029. const cr = r;
  9030. return cr.success;
  9031. }
  9032. async getMessage(stream, query) {
  9033. validateStreamName(stream);
  9034. const r = await this._request(`${this.prefix}.STREAM.MSG.GET.${stream}`, query);
  9035. const sm = r;
  9036. return new StoredMsgImpl(sm);
  9037. }
  9038. find(subject) {
  9039. return this.findStream(subject);
  9040. }
  9041. listKvs() {
  9042. const filter = (v) => {
  9043. var _a;
  9044. const slr = v;
  9045. const kvStreams = slr.streams.filter((v2) => {
  9046. return v2.config.name.startsWith(kvPrefix);
  9047. });
  9048. kvStreams.forEach((si) => {
  9049. this._fixInfo(si);
  9050. });
  9051. let cluster = "";
  9052. if (kvStreams.length) {
  9053. cluster = ((_a = this.nc.info) == null ? void 0 : _a.cluster) ?? "";
  9054. }
  9055. const status = kvStreams.map((si) => {
  9056. return new KvStatusImpl(si, cluster);
  9057. });
  9058. return status;
  9059. };
  9060. const subj = `${this.prefix}.STREAM.LIST`;
  9061. return new ListerImpl(subj, filter, this);
  9062. }
  9063. listObjectStores() {
  9064. const filter = (v) => {
  9065. const slr = v;
  9066. const objStreams = slr.streams.filter((v2) => {
  9067. return v2.config.name.startsWith(osPrefix);
  9068. });
  9069. objStreams.forEach((si) => {
  9070. this._fixInfo(si);
  9071. });
  9072. const status = objStreams.map((si) => {
  9073. return new ObjectStoreStatusImpl(si);
  9074. });
  9075. return status;
  9076. };
  9077. const subj = `${this.prefix}.STREAM.LIST`;
  9078. return new ListerImpl(subj, filter, this);
  9079. }
  9080. names(subject = "") {
  9081. const payload = (subject == null ? void 0 : subject.length) ? {
  9082. subject
  9083. } : {};
  9084. const listerFilter = (v) => {
  9085. const sr = v;
  9086. return sr.streams;
  9087. };
  9088. const subj = `${this.prefix}.STREAM.NAMES`;
  9089. return new ListerImpl(subj, listerFilter, this, payload);
  9090. }
  9091. async get(name) {
  9092. const si = await this.info(name);
  9093. return Promise.resolve(new StreamImpl(this, si));
  9094. }
  9095. };
  9096. var StoredMsgImpl = class {
  9097. constructor(smr) {
  9098. __publicField(this, "_header");
  9099. __publicField(this, "smr");
  9100. this.smr = smr;
  9101. }
  9102. get subject() {
  9103. return this.smr.message.subject;
  9104. }
  9105. get seq() {
  9106. return this.smr.message.seq;
  9107. }
  9108. get timestamp() {
  9109. return this.smr.message.time;
  9110. }
  9111. get time() {
  9112. return new Date(Date.parse(this.timestamp));
  9113. }
  9114. get data() {
  9115. return this.smr.message.data ? this._parse(this.smr.message.data) : Empty;
  9116. }
  9117. get header() {
  9118. if (!this._header) {
  9119. if (this.smr.message.hdrs) {
  9120. const hd = this._parse(this.smr.message.hdrs);
  9121. this._header = MsgHdrsImpl.decode(hd);
  9122. } else {
  9123. this._header = headers();
  9124. }
  9125. }
  9126. return this._header;
  9127. }
  9128. _parse(s) {
  9129. const bs = atob(s);
  9130. const len = bs.length;
  9131. const bytes = new Uint8Array(len);
  9132. for (let i = 0; i < len; i++) {
  9133. bytes[i] = bs.charCodeAt(i);
  9134. }
  9135. return bytes;
  9136. }
  9137. json(reviver) {
  9138. return JSONCodec(reviver).decode(this.data);
  9139. }
  9140. string() {
  9141. return TD.decode(this.data);
  9142. }
  9143. };
  9144. __publicField(StoredMsgImpl, "jc");
  9145. var StreamsImpl = class {
  9146. constructor(api) {
  9147. __publicField(this, "api");
  9148. this.api = api;
  9149. }
  9150. get(stream) {
  9151. return this.api.info(stream).then((si) => {
  9152. return new StreamImpl(this.api, si);
  9153. });
  9154. }
  9155. };
  9156. var KvStoredEntryImpl = class {
  9157. constructor(bucket, prefixLen, sm) {
  9158. __publicField(this, "bucket");
  9159. __publicField(this, "sm");
  9160. __publicField(this, "prefixLen");
  9161. this.bucket = bucket;
  9162. this.prefixLen = prefixLen;
  9163. this.sm = sm;
  9164. }
  9165. get key() {
  9166. return this.sm.subject.substring(this.prefixLen);
  9167. }
  9168. get value() {
  9169. return this.sm.data;
  9170. }
  9171. get delta() {
  9172. return 0;
  9173. }
  9174. get created() {
  9175. return this.sm.time;
  9176. }
  9177. get revision() {
  9178. return this.sm.seq;
  9179. }
  9180. get operation() {
  9181. return this.sm.header.get(kvOperationHdr) || "PUT";
  9182. }
  9183. get length() {
  9184. const slen = this.sm.header.get(JsHeaders.MessageSizeHdr) || "";
  9185. if (slen !== "") {
  9186. return parseInt(slen, 10);
  9187. }
  9188. return this.sm.data.length;
  9189. }
  9190. json() {
  9191. return this.sm.json();
  9192. }
  9193. string() {
  9194. return this.sm.string();
  9195. }
  9196. };
  9197. var KvJsMsgEntryImpl = class {
  9198. constructor(bucket, key, sm) {
  9199. __publicField(this, "bucket");
  9200. __publicField(this, "key");
  9201. __publicField(this, "sm");
  9202. this.bucket = bucket;
  9203. this.key = key;
  9204. this.sm = sm;
  9205. }
  9206. get value() {
  9207. return this.sm.data;
  9208. }
  9209. get created() {
  9210. return new Date(millis(this.sm.info.timestampNanos));
  9211. }
  9212. get revision() {
  9213. return this.sm.seq;
  9214. }
  9215. get operation() {
  9216. var _a;
  9217. return ((_a = this.sm.headers) == null ? void 0 : _a.get(kvOperationHdr)) || "PUT";
  9218. }
  9219. get delta() {
  9220. return this.sm.info.pending;
  9221. }
  9222. get length() {
  9223. var _a;
  9224. const slen = ((_a = this.sm.headers) == null ? void 0 : _a.get(JsHeaders.MessageSizeHdr)) || "";
  9225. if (slen !== "") {
  9226. return parseInt(slen, 10);
  9227. }
  9228. return this.sm.data.length;
  9229. }
  9230. json() {
  9231. return this.sm.json();
  9232. }
  9233. string() {
  9234. return this.sm.string();
  9235. }
  9236. };
  9237. var ObjectInfoImpl = class {
  9238. constructor(oi) {
  9239. __publicField(this, "info");
  9240. __publicField(this, "hdrs");
  9241. this.info = oi;
  9242. }
  9243. get name() {
  9244. return this.info.name;
  9245. }
  9246. get description() {
  9247. return this.info.description ?? "";
  9248. }
  9249. get headers() {
  9250. if (!this.hdrs) {
  9251. this.hdrs = MsgHdrsImpl.fromRecord(this.info.headers || {});
  9252. }
  9253. return this.hdrs;
  9254. }
  9255. get options() {
  9256. return this.info.options;
  9257. }
  9258. get bucket() {
  9259. return this.info.bucket;
  9260. }
  9261. get chunks() {
  9262. return this.info.chunks;
  9263. }
  9264. get deleted() {
  9265. return this.info.deleted ?? false;
  9266. }
  9267. get digest() {
  9268. return this.info.digest;
  9269. }
  9270. get mtime() {
  9271. return this.info.mtime;
  9272. }
  9273. get nuid() {
  9274. return this.info.nuid;
  9275. }
  9276. get size() {
  9277. return this.info.size;
  9278. }
  9279. get revision() {
  9280. return this.info.revision;
  9281. }
  9282. get metadata() {
  9283. return this.info.metadata || {};
  9284. }
  9285. isLink() {
  9286. var _a, _b;
  9287. return ((_a = this.info.options) == null ? void 0 : _a.link) !== void 0 && ((_b = this.info.options) == null ? void 0 : _b.link) !== null;
  9288. }
  9289. };
  9290. function toServerObjectStoreMeta(meta) {
  9291. const v = {
  9292. name: meta.name,
  9293. description: meta.description ?? "",
  9294. options: meta.options,
  9295. metadata: meta.metadata
  9296. };
  9297. if (meta.headers) {
  9298. const mhi = meta.headers;
  9299. v.headers = mhi.toRecord();
  9300. }
  9301. return v;
  9302. }
  9303. function emptyReadableStream() {
  9304. return new ReadableStream({
  9305. pull(c) {
  9306. c.enqueue(new Uint8Array(0));
  9307. c.close();
  9308. }
  9309. });
  9310. }
  9311. var ObjectStoreImpl = class {
  9312. constructor(name, jsm, js) {
  9313. __publicField(this, "jsm");
  9314. __publicField(this, "js");
  9315. __publicField(this, "stream");
  9316. __publicField(this, "name");
  9317. this.name = name;
  9318. this.jsm = jsm;
  9319. this.js = js;
  9320. }
  9321. _checkNotEmpty(name) {
  9322. if (!name || name.length === 0) {
  9323. return {
  9324. name,
  9325. error: new Error("name cannot be empty")
  9326. };
  9327. }
  9328. return {
  9329. name
  9330. };
  9331. }
  9332. async info(name) {
  9333. const info = await this.rawInfo(name);
  9334. return info ? new ObjectInfoImpl(info) : null;
  9335. }
  9336. async list() {
  9337. const buf = [];
  9338. const iter = await this.watch({
  9339. ignoreDeletes: true,
  9340. includeHistory: true
  9341. });
  9342. for await (const info of iter) {
  9343. if (info === null) {
  9344. break;
  9345. }
  9346. buf.push(info);
  9347. }
  9348. return Promise.resolve(buf);
  9349. }
  9350. async rawInfo(name) {
  9351. const { name: obj, error } = this._checkNotEmpty(name);
  9352. if (error) {
  9353. return Promise.reject(error);
  9354. }
  9355. const meta = this._metaSubject(obj);
  9356. try {
  9357. const m = await this.jsm.streams.getMessage(this.stream, {
  9358. last_by_subj: meta
  9359. });
  9360. const jc = JSONCodec();
  9361. const soi = jc.decode(m.data);
  9362. soi.revision = m.seq;
  9363. return soi;
  9364. } catch (err) {
  9365. if (err.code === "404") {
  9366. return null;
  9367. }
  9368. return Promise.reject(err);
  9369. }
  9370. }
  9371. async _si(opts) {
  9372. try {
  9373. return await this.jsm.streams.info(this.stream, opts);
  9374. } catch (err) {
  9375. const nerr = err;
  9376. if (nerr.code === "404") {
  9377. return null;
  9378. }
  9379. return Promise.reject(err);
  9380. }
  9381. }
  9382. async seal() {
  9383. let info = await this._si();
  9384. if (info === null) {
  9385. return Promise.reject(new Error("object store not found"));
  9386. }
  9387. info.config.sealed = true;
  9388. info = await this.jsm.streams.update(this.stream, info.config);
  9389. return Promise.resolve(new ObjectStoreStatusImpl(info));
  9390. }
  9391. async status(opts) {
  9392. const info = await this._si(opts);
  9393. if (info === null) {
  9394. return Promise.reject(new Error("object store not found"));
  9395. }
  9396. return Promise.resolve(new ObjectStoreStatusImpl(info));
  9397. }
  9398. destroy() {
  9399. return this.jsm.streams.delete(this.stream);
  9400. }
  9401. async _put(meta, rs, opts) {
  9402. var _a;
  9403. const jsopts = this.js.getOptions();
  9404. opts = opts || {
  9405. timeout: jsopts.timeout
  9406. };
  9407. opts.timeout = opts.timeout || jsopts.timeout;
  9408. opts.previousRevision = opts.previousRevision ?? void 0;
  9409. const { timeout: timeout2, previousRevision } = opts;
  9410. const si = this.js.nc.info;
  9411. const maxPayload = (si == null ? void 0 : si.max_payload) || 1024;
  9412. meta = meta || {};
  9413. meta.options = meta.options || {};
  9414. let maxChunk = ((_a = meta.options) == null ? void 0 : _a.max_chunk_size) || 128 * 1024;
  9415. maxChunk = maxChunk > maxPayload ? maxPayload : maxChunk;
  9416. meta.options.max_chunk_size = maxChunk;
  9417. const old = await this.info(meta.name);
  9418. const { name: n, error } = this._checkNotEmpty(meta.name);
  9419. if (error) {
  9420. return Promise.reject(error);
  9421. }
  9422. const id = nuid.next();
  9423. const chunkSubj = this._chunkSubject(id);
  9424. const metaSubj = this._metaSubject(n);
  9425. const info = Object.assign({
  9426. bucket: this.name,
  9427. nuid: id,
  9428. size: 0,
  9429. chunks: 0
  9430. }, toServerObjectStoreMeta(meta));
  9431. const d = deferred();
  9432. const proms = [];
  9433. const db = new DataBuffer();
  9434. try {
  9435. const reader = rs ? rs.getReader() : null;
  9436. const sha = new SHA256();
  9437. while (true) {
  9438. const { done, value } = reader ? await reader.read() : {
  9439. done: true,
  9440. value: void 0
  9441. };
  9442. if (done) {
  9443. if (db.size() > 0) {
  9444. const payload = db.drain();
  9445. sha.update(payload);
  9446. info.chunks++;
  9447. info.size += payload.length;
  9448. proms.push(this.js.publish(chunkSubj, payload, {
  9449. timeout: timeout2
  9450. }));
  9451. }
  9452. await Promise.all(proms);
  9453. proms.length = 0;
  9454. info.mtime = (/* @__PURE__ */ new Date()).toISOString();
  9455. const digest = sha.digest("base64");
  9456. const pad = digest.length % 3;
  9457. const padding = pad > 0 ? "=".repeat(pad) : "";
  9458. info.digest = `${digestType}${digest}${padding}`;
  9459. info.deleted = false;
  9460. const h = headers();
  9461. if (typeof previousRevision === "number") {
  9462. h.set(PubHeaders.ExpectedLastSubjectSequenceHdr, `${previousRevision}`);
  9463. }
  9464. h.set(JsHeaders.RollupHdr, JsHeaders.RollupValueSubject);
  9465. const pa = await this.js.publish(metaSubj, JSONCodec().encode(info), {
  9466. headers: h,
  9467. timeout: timeout2
  9468. });
  9469. info.revision = pa.seq;
  9470. if (old) {
  9471. try {
  9472. await this.jsm.streams.purge(this.stream, {
  9473. filter: `$O.${this.name}.C.${old.nuid}`
  9474. });
  9475. } catch (_err) {
  9476. }
  9477. }
  9478. d.resolve(new ObjectInfoImpl(info));
  9479. break;
  9480. }
  9481. if (value) {
  9482. db.fill(value);
  9483. while (db.size() > maxChunk) {
  9484. info.chunks++;
  9485. info.size += maxChunk;
  9486. const payload = db.drain(meta.options.max_chunk_size);
  9487. sha.update(payload);
  9488. proms.push(this.js.publish(chunkSubj, payload, {
  9489. timeout: timeout2
  9490. }));
  9491. }
  9492. }
  9493. }
  9494. } catch (err) {
  9495. await this.jsm.streams.purge(this.stream, {
  9496. filter: chunkSubj
  9497. });
  9498. d.reject(err);
  9499. }
  9500. return d;
  9501. }
  9502. putBlob(meta, data, opts) {
  9503. function readableStreamFrom(data2) {
  9504. return new ReadableStream({
  9505. pull(controller) {
  9506. controller.enqueue(data2);
  9507. controller.close();
  9508. }
  9509. });
  9510. }
  9511. if (data === null) {
  9512. data = new Uint8Array(0);
  9513. }
  9514. return this.put(meta, readableStreamFrom(data), opts);
  9515. }
  9516. put(meta, rs, opts) {
  9517. var _a;
  9518. if ((_a = meta == null ? void 0 : meta.options) == null ? void 0 : _a.link) {
  9519. return Promise.reject(new Error("link cannot be set when putting the object in bucket"));
  9520. }
  9521. return this._put(meta, rs, opts);
  9522. }
  9523. async getBlob(name) {
  9524. async function fromReadableStream(rs) {
  9525. const buf = new DataBuffer();
  9526. const reader = rs.getReader();
  9527. while (true) {
  9528. const { done, value } = await reader.read();
  9529. if (done) {
  9530. return buf.drain();
  9531. }
  9532. if (value && value.length) {
  9533. buf.fill(value);
  9534. }
  9535. }
  9536. }
  9537. const r = await this.get(name);
  9538. if (r === null) {
  9539. return Promise.resolve(null);
  9540. }
  9541. const vs = await Promise.all([
  9542. r.error,
  9543. fromReadableStream(r.data)
  9544. ]);
  9545. if (vs[0]) {
  9546. return Promise.reject(vs[0]);
  9547. } else {
  9548. return Promise.resolve(vs[1]);
  9549. }
  9550. }
  9551. async get(name) {
  9552. const info = await this.rawInfo(name);
  9553. if (info === null) {
  9554. return Promise.resolve(null);
  9555. }
  9556. if (info.deleted) {
  9557. return Promise.resolve(null);
  9558. }
  9559. if (info.options && info.options.link) {
  9560. const ln = info.options.link.name || "";
  9561. if (ln === "") {
  9562. throw new Error("link is a bucket");
  9563. }
  9564. const os = info.options.link.bucket !== this.name ? await ObjectStoreImpl.create(this.js, info.options.link.bucket) : this;
  9565. return os.get(ln);
  9566. }
  9567. const d = deferred();
  9568. const r = {
  9569. info: new ObjectInfoImpl(info),
  9570. error: d
  9571. };
  9572. if (info.size === 0) {
  9573. r.data = emptyReadableStream();
  9574. d.resolve(null);
  9575. return Promise.resolve(r);
  9576. }
  9577. let controller;
  9578. const oc = consumerOpts();
  9579. oc.orderedConsumer();
  9580. const sha = new SHA256();
  9581. const subj = `$O.${this.name}.C.${info.nuid}`;
  9582. const sub = await this.js.subscribe(subj, oc);
  9583. (async () => {
  9584. for await (const jm of sub) {
  9585. if (jm.data.length > 0) {
  9586. sha.update(jm.data);
  9587. controller.enqueue(jm.data);
  9588. }
  9589. if (jm.info.pending === 0) {
  9590. const hash = sha.digest("base64");
  9591. const pad = hash.length % 3;
  9592. const padding = pad > 0 ? "=".repeat(pad) : "";
  9593. const digest = `${digestType}${hash}${padding}`;
  9594. if (digest !== info.digest) {
  9595. controller.error(new Error(`received a corrupt object, digests do not match received: ${info.digest} calculated ${digest}`));
  9596. } else {
  9597. controller.close();
  9598. }
  9599. sub.unsubscribe();
  9600. }
  9601. }
  9602. })().then(() => {
  9603. d.resolve();
  9604. }).catch((err) => {
  9605. controller.error(err);
  9606. d.reject(err);
  9607. });
  9608. r.data = new ReadableStream({
  9609. start(c) {
  9610. controller = c;
  9611. },
  9612. cancel() {
  9613. sub.unsubscribe();
  9614. }
  9615. });
  9616. return r;
  9617. }
  9618. linkStore(name, bucket) {
  9619. if (!(bucket instanceof ObjectStoreImpl)) {
  9620. return Promise.reject("bucket required");
  9621. }
  9622. const osi = bucket;
  9623. const { name: n, error } = this._checkNotEmpty(name);
  9624. if (error) {
  9625. return Promise.reject(error);
  9626. }
  9627. const meta = {
  9628. name: n,
  9629. options: {
  9630. link: {
  9631. bucket: osi.name
  9632. }
  9633. }
  9634. };
  9635. return this._put(meta, null);
  9636. }
  9637. async link(name, info) {
  9638. const { name: n, error } = this._checkNotEmpty(name);
  9639. if (error) {
  9640. return Promise.reject(error);
  9641. }
  9642. if (info.deleted) {
  9643. return Promise.reject(new Error("src object is deleted"));
  9644. }
  9645. if (info.isLink()) {
  9646. return Promise.reject(new Error("src object is a link"));
  9647. }
  9648. const dest = await this.rawInfo(name);
  9649. if (dest !== null && !dest.deleted) {
  9650. return Promise.reject(new Error("an object already exists with that name"));
  9651. }
  9652. const link = {
  9653. bucket: info.bucket,
  9654. name: info.name
  9655. };
  9656. const mm = {
  9657. name: n,
  9658. bucket: info.bucket,
  9659. options: {
  9660. link
  9661. }
  9662. };
  9663. await this.js.publish(this._metaSubject(name), JSON.stringify(mm));
  9664. const i = await this.info(name);
  9665. return Promise.resolve(i);
  9666. }
  9667. async delete(name) {
  9668. const info = await this.rawInfo(name);
  9669. if (info === null) {
  9670. return Promise.resolve({
  9671. purged: 0,
  9672. success: false
  9673. });
  9674. }
  9675. info.deleted = true;
  9676. info.size = 0;
  9677. info.chunks = 0;
  9678. info.digest = "";
  9679. const jc = JSONCodec();
  9680. const h = headers();
  9681. h.set(JsHeaders.RollupHdr, JsHeaders.RollupValueSubject);
  9682. await this.js.publish(this._metaSubject(info.name), jc.encode(info), {
  9683. headers: h
  9684. });
  9685. return this.jsm.streams.purge(this.stream, {
  9686. filter: this._chunkSubject(info.nuid)
  9687. });
  9688. }
  9689. async update(name, meta = {}) {
  9690. const info = await this.rawInfo(name);
  9691. if (info === null) {
  9692. return Promise.reject(new Error("object not found"));
  9693. }
  9694. if (info.deleted) {
  9695. return Promise.reject(new Error("cannot update meta for a deleted object"));
  9696. }
  9697. meta.name = meta.name ?? info.name;
  9698. const { name: n, error } = this._checkNotEmpty(meta.name);
  9699. if (error) {
  9700. return Promise.reject(error);
  9701. }
  9702. if (name !== meta.name) {
  9703. const i = await this.info(meta.name);
  9704. if (i && !i.deleted) {
  9705. return Promise.reject(new Error("an object already exists with that name"));
  9706. }
  9707. }
  9708. meta.name = n;
  9709. const ii = Object.assign({}, info, toServerObjectStoreMeta(meta));
  9710. const ack = await this.js.publish(this._metaSubject(ii.name), JSON.stringify(ii));
  9711. if (name !== meta.name) {
  9712. await this.jsm.streams.purge(this.stream, {
  9713. filter: this._metaSubject(name)
  9714. });
  9715. }
  9716. return Promise.resolve(ack);
  9717. }
  9718. async watch(opts = {}) {
  9719. opts.includeHistory = opts.includeHistory ?? false;
  9720. opts.ignoreDeletes = opts.ignoreDeletes ?? false;
  9721. let initialized = false;
  9722. const qi = new QueuedIteratorImpl();
  9723. const subj = this._metaSubjectAll();
  9724. try {
  9725. await this.jsm.streams.getMessage(this.stream, {
  9726. last_by_subj: subj
  9727. });
  9728. } catch (err) {
  9729. if (err.code === "404") {
  9730. qi.push(null);
  9731. initialized = true;
  9732. } else {
  9733. qi.stop(err);
  9734. }
  9735. }
  9736. const jc = JSONCodec();
  9737. const copts = consumerOpts();
  9738. copts.orderedConsumer();
  9739. if (opts.includeHistory) {
  9740. copts.deliverLastPerSubject();
  9741. } else {
  9742. initialized = true;
  9743. copts.deliverNew();
  9744. }
  9745. copts.callback((err, jm) => {
  9746. var _a;
  9747. if (err) {
  9748. qi.stop(err);
  9749. return;
  9750. }
  9751. if (jm !== null) {
  9752. const oi = jc.decode(jm.data);
  9753. if (oi.deleted && opts.ignoreDeletes === true) {
  9754. } else {
  9755. qi.push(oi);
  9756. }
  9757. if (((_a = jm.info) == null ? void 0 : _a.pending) === 0 && !initialized) {
  9758. initialized = true;
  9759. qi.push(null);
  9760. }
  9761. }
  9762. });
  9763. const sub = await this.js.subscribe(subj, copts);
  9764. qi._data = sub;
  9765. qi.iterClosed.then(() => {
  9766. sub.unsubscribe();
  9767. });
  9768. sub.closed.then(() => {
  9769. qi.stop();
  9770. }).catch((err) => {
  9771. qi.stop(err);
  9772. });
  9773. return qi;
  9774. }
  9775. _chunkSubject(id) {
  9776. return `$O.${this.name}.C.${id}`;
  9777. }
  9778. _metaSubject(n) {
  9779. return `$O.${this.name}.M.${Base64UrlPaddedCodec.encode(n)}`;
  9780. }
  9781. _metaSubjectAll() {
  9782. return `$O.${this.name}.M.>`;
  9783. }
  9784. async init(opts = {}) {
  9785. try {
  9786. this.stream = objectStoreStreamName(this.name);
  9787. } catch (err) {
  9788. return Promise.reject(err);
  9789. }
  9790. const max_age = (opts == null ? void 0 : opts.ttl) || 0;
  9791. delete opts.ttl;
  9792. const sc = Object.assign({
  9793. max_age
  9794. }, opts);
  9795. sc.name = this.stream;
  9796. sc.allow_direct = true;
  9797. sc.allow_rollup_hdrs = true;
  9798. sc.discard = DiscardPolicy.New;
  9799. sc.subjects = [
  9800. `$O.${this.name}.C.>`,
  9801. `$O.${this.name}.M.>`
  9802. ];
  9803. if (opts.placement) {
  9804. sc.placement = opts.placement;
  9805. }
  9806. if (opts.metadata) {
  9807. sc.metadata = opts.metadata;
  9808. }
  9809. if (typeof opts.compression === "boolean") {
  9810. sc.compression = opts.compression ? StoreCompression.S2 : StoreCompression.None;
  9811. }
  9812. try {
  9813. await this.jsm.streams.info(sc.name);
  9814. } catch (err) {
  9815. if (err.message === "stream not found") {
  9816. await this.jsm.streams.add(sc);
  9817. }
  9818. }
  9819. }
  9820. static async create(js, name, opts = {}) {
  9821. const jsm = await js.jetstreamManager();
  9822. const os = new ObjectStoreImpl(name, jsm, js);
  9823. await os.init(opts);
  9824. return Promise.resolve(os);
  9825. }
  9826. };
  9827. var ViewsImpl = class {
  9828. constructor(js) {
  9829. __publicField(this, "js");
  9830. __publicField(this, "jsm");
  9831. this.js = js;
  9832. }
  9833. kv(name, opts = {}) {
  9834. const jsi = this.js;
  9835. const { ok, min } = jsi.nc.features.get(Feature.JS_KV);
  9836. if (!ok) {
  9837. return Promise.reject(new Error(`kv is only supported on servers ${min} or better`));
  9838. }
  9839. if (opts.bindOnly) {
  9840. return Bucket.bind(this.js, name);
  9841. }
  9842. return Bucket.create(this.js, name, opts);
  9843. }
  9844. os(name, opts = {}) {
  9845. var _a;
  9846. if (typeof ((_a = crypto == null ? void 0 : crypto.subtle) == null ? void 0 : _a.digest) !== "function") {
  9847. return Promise.reject(new Error("objectstore: unable to calculate hashes - crypto.subtle.digest with sha256 support is required"));
  9848. }
  9849. const jsi = this.js;
  9850. const { ok, min } = jsi.nc.features.get(Feature.JS_OBJECTSTORE);
  9851. if (!ok) {
  9852. return Promise.reject(new Error(`objectstore is only supported on servers ${min} or better`));
  9853. }
  9854. return ObjectStoreImpl.create(this.js, name, opts);
  9855. }
  9856. };
  9857. var JetStreamClientImpl = class extends BaseApiClient {
  9858. constructor(nc, opts) {
  9859. super(nc, opts);
  9860. __publicField(this, "consumers");
  9861. __publicField(this, "streams");
  9862. __publicField(this, "consumerAPI");
  9863. __publicField(this, "streamAPI");
  9864. this.consumerAPI = new ConsumerAPIImpl(nc, opts);
  9865. this.streamAPI = new StreamAPIImpl(nc, opts);
  9866. this.consumers = new ConsumersImpl(this.consumerAPI);
  9867. this.streams = new StreamsImpl(this.streamAPI);
  9868. }
  9869. jetstreamManager(checkAPI) {
  9870. const opts = Object.assign({
  9871. checkAPI
  9872. }, this.opts);
  9873. return this.nc.jetstreamManager(opts);
  9874. }
  9875. get apiPrefix() {
  9876. return this.prefix;
  9877. }
  9878. get views() {
  9879. return new ViewsImpl(this);
  9880. }
  9881. async publish(subj, data = Empty, opts) {
  9882. opts = opts || {};
  9883. opts.expect = opts.expect || {};
  9884. const mh = (opts == null ? void 0 : opts.headers) || headers();
  9885. if (opts) {
  9886. if (opts.msgID) {
  9887. mh.set(PubHeaders.MsgIdHdr, opts.msgID);
  9888. }
  9889. if (opts.expect.lastMsgID) {
  9890. mh.set(PubHeaders.ExpectedLastMsgIdHdr, opts.expect.lastMsgID);
  9891. }
  9892. if (opts.expect.streamName) {
  9893. mh.set(PubHeaders.ExpectedStreamHdr, opts.expect.streamName);
  9894. }
  9895. if (typeof opts.expect.lastSequence === "number") {
  9896. mh.set(PubHeaders.ExpectedLastSeqHdr, `${opts.expect.lastSequence}`);
  9897. }
  9898. if (typeof opts.expect.lastSubjectSequence === "number") {
  9899. mh.set(PubHeaders.ExpectedLastSubjectSequenceHdr, `${opts.expect.lastSubjectSequence}`);
  9900. }
  9901. }
  9902. const to = opts.timeout || this.timeout;
  9903. const ro = {};
  9904. if (to) {
  9905. ro.timeout = to;
  9906. }
  9907. if (opts) {
  9908. ro.headers = mh;
  9909. }
  9910. let { retries, retry_delay } = opts;
  9911. retries = retries || 1;
  9912. retry_delay = retry_delay || 250;
  9913. let r;
  9914. for (let i = 0; i < retries; i++) {
  9915. try {
  9916. r = await this.nc.request(subj, data, ro);
  9917. break;
  9918. } catch (err) {
  9919. const ne = err;
  9920. if (ne.code === "503" && i + 1 < retries) {
  9921. await delay(retry_delay);
  9922. } else {
  9923. throw err;
  9924. }
  9925. }
  9926. }
  9927. const pa = this.parseJsResponse(r);
  9928. if (pa.stream === "") {
  9929. throw NatsError.errorForCode(ErrorCode.JetStreamInvalidAck);
  9930. }
  9931. pa.duplicate = pa.duplicate ? pa.duplicate : false;
  9932. return pa;
  9933. }
  9934. async pull(stream, durable, expires = 0) {
  9935. validateStreamName(stream);
  9936. validateDurableName(durable);
  9937. let timeout2 = this.timeout;
  9938. if (expires > timeout2) {
  9939. timeout2 = expires;
  9940. }
  9941. expires = expires < 0 ? 0 : nanos(expires);
  9942. const pullOpts = {
  9943. batch: 1,
  9944. no_wait: expires === 0,
  9945. expires
  9946. };
  9947. const msg = await this.nc.request(`${this.prefix}.CONSUMER.MSG.NEXT.${stream}.${durable}`, this.jc.encode(pullOpts), {
  9948. noMux: true,
  9949. timeout: timeout2
  9950. });
  9951. const err = checkJsError(msg);
  9952. if (err) {
  9953. throw err;
  9954. }
  9955. return toJsMsg(msg);
  9956. }
  9957. fetch(stream, durable, opts = {}) {
  9958. validateStreamName(stream);
  9959. validateDurableName(durable);
  9960. let timer = null;
  9961. const trackBytes = (opts.max_bytes ?? 0) > 0;
  9962. let receivedBytes = 0;
  9963. const max_bytes = trackBytes ? opts.max_bytes : 0;
  9964. let monitor = null;
  9965. const args = {};
  9966. args.batch = opts.batch || 1;
  9967. if (max_bytes) {
  9968. const fv = this.nc.features.get(Feature.JS_PULL_MAX_BYTES);
  9969. if (!fv.ok) {
  9970. throw new Error(`max_bytes is only supported on servers ${fv.min} or better`);
  9971. }
  9972. args.max_bytes = max_bytes;
  9973. }
  9974. args.no_wait = opts.no_wait || false;
  9975. if (args.no_wait && args.expires) {
  9976. args.expires = 0;
  9977. }
  9978. const expires = opts.expires || 0;
  9979. if (expires) {
  9980. args.expires = nanos(expires);
  9981. }
  9982. if (expires === 0 && args.no_wait === false) {
  9983. throw new Error("expires or no_wait is required");
  9984. }
  9985. const hb = opts.idle_heartbeat || 0;
  9986. if (hb) {
  9987. args.idle_heartbeat = nanos(hb);
  9988. if (opts.delay_heartbeat === true) {
  9989. args.idle_heartbeat = nanos(hb * 4);
  9990. }
  9991. }
  9992. const qi = new QueuedIteratorImpl();
  9993. const wants = args.batch;
  9994. let received = 0;
  9995. qi.protocolFilterFn = (jm, _ingest = false) => {
  9996. const jsmi = jm;
  9997. if (isHeartbeatMsg(jsmi.msg)) {
  9998. monitor == null ? void 0 : monitor.work();
  9999. return false;
  10000. }
  10001. return true;
  10002. };
  10003. qi.dispatchedFn = (m) => {
  10004. if (m) {
  10005. if (trackBytes) {
  10006. receivedBytes += m.data.length;
  10007. }
  10008. received++;
  10009. if (timer && m.info.pending === 0) {
  10010. return;
  10011. }
  10012. if (qi.getPending() === 1 && m.info.pending === 0 || wants === received || max_bytes > 0 && receivedBytes >= max_bytes) {
  10013. qi.stop();
  10014. }
  10015. }
  10016. };
  10017. const inbox = createInbox(this.nc.options.inboxPrefix);
  10018. const sub = this.nc.subscribe(inbox, {
  10019. max: opts.batch,
  10020. callback: (err, msg) => {
  10021. if (err === null) {
  10022. err = checkJsError(msg);
  10023. }
  10024. if (err !== null) {
  10025. if (timer) {
  10026. timer.cancel();
  10027. timer = null;
  10028. }
  10029. if (isNatsError(err)) {
  10030. qi.stop(hideNonTerminalJsErrors(err) === null ? void 0 : err);
  10031. } else {
  10032. qi.stop(err);
  10033. }
  10034. } else {
  10035. monitor == null ? void 0 : monitor.work();
  10036. qi.received++;
  10037. qi.push(toJsMsg(msg));
  10038. }
  10039. }
  10040. });
  10041. if (expires) {
  10042. timer = timeout(expires);
  10043. timer.catch(() => {
  10044. if (!sub.isClosed()) {
  10045. sub.drain().catch(() => {
  10046. });
  10047. timer = null;
  10048. }
  10049. if (monitor) {
  10050. monitor.cancel();
  10051. }
  10052. });
  10053. }
  10054. (async () => {
  10055. try {
  10056. if (hb) {
  10057. monitor = new IdleHeartbeatMonitor(hb, (v) => {
  10058. qi.push(() => {
  10059. qi.err = new NatsError(`${Js409Errors.IdleHeartbeatMissed}: ${v}`, ErrorCode.JetStreamIdleHeartBeat);
  10060. });
  10061. return true;
  10062. });
  10063. }
  10064. } catch (_err) {
  10065. }
  10066. await sub.closed;
  10067. if (timer !== null) {
  10068. timer.cancel();
  10069. timer = null;
  10070. }
  10071. if (monitor) {
  10072. monitor.cancel();
  10073. }
  10074. qi.stop();
  10075. })().catch();
  10076. this.nc.publish(`${this.prefix}.CONSUMER.MSG.NEXT.${stream}.${durable}`, this.jc.encode(args), {
  10077. reply: inbox
  10078. });
  10079. return qi;
  10080. }
  10081. async pullSubscribe(subject, opts = consumerOpts()) {
  10082. const cso = await this._processOptions(subject, opts);
  10083. if (cso.ordered) {
  10084. throw new Error("pull subscribers cannot be be ordered");
  10085. }
  10086. if (cso.config.deliver_subject) {
  10087. throw new Error("consumer info specifies deliver_subject - pull consumers cannot have deliver_subject set");
  10088. }
  10089. const ackPolicy = cso.config.ack_policy;
  10090. if (ackPolicy === AckPolicy.None || ackPolicy === AckPolicy.All) {
  10091. throw new Error("ack policy for pull consumers must be explicit");
  10092. }
  10093. const so = this._buildTypedSubscriptionOpts(cso);
  10094. const sub = new JetStreamPullSubscriptionImpl(this, cso.deliver, so);
  10095. sub.info = cso;
  10096. try {
  10097. await this._maybeCreateConsumer(cso);
  10098. } catch (err) {
  10099. sub.unsubscribe();
  10100. throw err;
  10101. }
  10102. return sub;
  10103. }
  10104. async subscribe(subject, opts = consumerOpts()) {
  10105. const cso = await this._processOptions(subject, opts);
  10106. if (!cso.isBind && !cso.config.deliver_subject) {
  10107. throw new Error("push consumer requires deliver_subject");
  10108. }
  10109. const so = this._buildTypedSubscriptionOpts(cso);
  10110. const sub = new JetStreamSubscriptionImpl(this, cso.deliver, so);
  10111. sub.info = cso;
  10112. try {
  10113. await this._maybeCreateConsumer(cso);
  10114. } catch (err) {
  10115. sub.unsubscribe();
  10116. throw err;
  10117. }
  10118. sub._maybeSetupHbMonitoring();
  10119. return sub;
  10120. }
  10121. async _processOptions(subject, opts = consumerOpts()) {
  10122. const jsi = isConsumerOptsBuilder(opts) ? opts.getOpts() : opts;
  10123. jsi.isBind = isConsumerOptsBuilder(opts) ? opts.isBind : false;
  10124. jsi.flow_control = {
  10125. heartbeat_count: 0,
  10126. fc_count: 0,
  10127. consumer_restarts: 0
  10128. };
  10129. if (jsi.ordered) {
  10130. jsi.ordered_consumer_sequence = {
  10131. stream_seq: 0,
  10132. delivery_seq: 0
  10133. };
  10134. if (jsi.config.ack_policy !== AckPolicy.NotSet && jsi.config.ack_policy !== AckPolicy.None) {
  10135. throw new NatsError("ordered consumer: ack_policy can only be set to 'none'", ErrorCode.ApiError);
  10136. }
  10137. if (jsi.config.durable_name && jsi.config.durable_name.length > 0) {
  10138. throw new NatsError("ordered consumer: durable_name cannot be set", ErrorCode.ApiError);
  10139. }
  10140. if (jsi.config.deliver_subject && jsi.config.deliver_subject.length > 0) {
  10141. throw new NatsError("ordered consumer: deliver_subject cannot be set", ErrorCode.ApiError);
  10142. }
  10143. if (jsi.config.max_deliver !== void 0 && jsi.config.max_deliver > 1) {
  10144. throw new NatsError("ordered consumer: max_deliver cannot be set", ErrorCode.ApiError);
  10145. }
  10146. if (jsi.config.deliver_group && jsi.config.deliver_group.length > 0) {
  10147. throw new NatsError("ordered consumer: deliver_group cannot be set", ErrorCode.ApiError);
  10148. }
  10149. jsi.config.deliver_subject = createInbox(this.nc.options.inboxPrefix);
  10150. jsi.config.ack_policy = AckPolicy.None;
  10151. jsi.config.max_deliver = 1;
  10152. jsi.config.flow_control = true;
  10153. jsi.config.idle_heartbeat = jsi.config.idle_heartbeat || nanos(5e3);
  10154. jsi.config.ack_wait = nanos(22 * 60 * 60 * 1e3);
  10155. jsi.config.mem_storage = true;
  10156. jsi.config.num_replicas = 1;
  10157. }
  10158. if (jsi.config.ack_policy === AckPolicy.NotSet) {
  10159. jsi.config.ack_policy = AckPolicy.All;
  10160. }
  10161. jsi.api = this;
  10162. jsi.config = jsi.config || {};
  10163. jsi.stream = jsi.stream ? jsi.stream : await this.findStream(subject);
  10164. jsi.attached = false;
  10165. if (jsi.config.durable_name) {
  10166. try {
  10167. const info = await this.consumerAPI.info(jsi.stream, jsi.config.durable_name);
  10168. if (info) {
  10169. if (info.config.filter_subject && info.config.filter_subject !== subject) {
  10170. throw new Error("subject does not match consumer");
  10171. }
  10172. const qn = jsi.config.deliver_group ?? "";
  10173. if (qn === "" && info.push_bound === true) {
  10174. throw new Error(`duplicate subscription`);
  10175. }
  10176. const rqn = info.config.deliver_group ?? "";
  10177. if (qn !== rqn) {
  10178. if (rqn === "") {
  10179. throw new Error(`durable requires no queue group`);
  10180. } else {
  10181. throw new Error(`durable requires queue group '${rqn}'`);
  10182. }
  10183. }
  10184. jsi.last = info;
  10185. jsi.config = info.config;
  10186. jsi.attached = true;
  10187. if (!jsi.config.durable_name) {
  10188. jsi.name = info.name;
  10189. }
  10190. }
  10191. } catch (err) {
  10192. if (err.code !== "404") {
  10193. throw err;
  10194. }
  10195. }
  10196. }
  10197. if (!jsi.attached && jsi.config.filter_subject === void 0 && jsi.config.filter_subjects === void 0) {
  10198. jsi.config.filter_subject = subject;
  10199. }
  10200. jsi.deliver = jsi.config.deliver_subject || createInbox(this.nc.options.inboxPrefix);
  10201. return jsi;
  10202. }
  10203. _buildTypedSubscriptionOpts(jsi) {
  10204. const so = {};
  10205. so.adapter = msgAdapter(jsi.callbackFn === void 0);
  10206. so.ingestionFilterFn = JetStreamClientImpl.ingestionFn(jsi.ordered);
  10207. so.protocolFilterFn = (jm, ingest = false) => {
  10208. const jsmi = jm;
  10209. if (isFlowControlMsg(jsmi.msg)) {
  10210. if (!ingest) {
  10211. jsmi.msg.respond();
  10212. }
  10213. return false;
  10214. }
  10215. return true;
  10216. };
  10217. if (!jsi.mack && jsi.config.ack_policy !== AckPolicy.None) {
  10218. so.dispatchedFn = autoAckJsMsg;
  10219. }
  10220. if (jsi.callbackFn) {
  10221. so.callback = jsi.callbackFn;
  10222. }
  10223. so.max = jsi.max || 0;
  10224. so.queue = jsi.queue;
  10225. return so;
  10226. }
  10227. async _maybeCreateConsumer(jsi) {
  10228. if (jsi.attached) {
  10229. return;
  10230. }
  10231. if (jsi.isBind) {
  10232. throw new Error(`unable to bind - durable consumer ${jsi.config.durable_name} doesn't exist in ${jsi.stream}`);
  10233. }
  10234. jsi.config = Object.assign({
  10235. deliver_policy: DeliverPolicy.All,
  10236. ack_policy: AckPolicy.Explicit,
  10237. ack_wait: nanos(30 * 1e3),
  10238. replay_policy: ReplayPolicy.Instant
  10239. }, jsi.config);
  10240. const ci = await this.consumerAPI.add(jsi.stream, jsi.config);
  10241. if (Array.isArray(jsi.config.filter_subjects && !Array.isArray(ci.config.filter_subjects))) {
  10242. throw new Error(`jetstream server doesn't support consumers with multiple filter subjects`);
  10243. }
  10244. jsi.name = ci.name;
  10245. jsi.config = ci.config;
  10246. jsi.last = ci;
  10247. }
  10248. static ingestionFn(ordered) {
  10249. return (jm, ctx) => {
  10250. var _a;
  10251. const jsub = ctx;
  10252. if (!jm)
  10253. return {
  10254. ingest: false,
  10255. protocol: false
  10256. };
  10257. const jmi = jm;
  10258. if (!checkJsError(jmi.msg)) {
  10259. (_a = jsub.monitor) == null ? void 0 : _a.work();
  10260. }
  10261. if (isHeartbeatMsg(jmi.msg)) {
  10262. const ingest2 = ordered ? jsub._checkHbOrderConsumer(jmi.msg) : true;
  10263. if (!ordered) {
  10264. jsub.info.flow_control.heartbeat_count++;
  10265. }
  10266. return {
  10267. ingest: ingest2,
  10268. protocol: true
  10269. };
  10270. } else if (isFlowControlMsg(jmi.msg)) {
  10271. jsub.info.flow_control.fc_count++;
  10272. return {
  10273. ingest: true,
  10274. protocol: true
  10275. };
  10276. }
  10277. const ingest = ordered ? jsub._checkOrderedConsumer(jm) : true;
  10278. return {
  10279. ingest,
  10280. protocol: false
  10281. };
  10282. };
  10283. }
  10284. };
  10285. var JetStreamSubscriptionImpl = class extends TypedSubscription {
  10286. constructor(js, subject, opts) {
  10287. super(js.nc, subject, opts);
  10288. __publicField(this, "js");
  10289. __publicField(this, "monitor");
  10290. this.js = js;
  10291. this.monitor = null;
  10292. this.sub.closed.then(() => {
  10293. if (this.monitor) {
  10294. this.monitor.cancel();
  10295. }
  10296. });
  10297. }
  10298. set info(info) {
  10299. this.sub.info = info;
  10300. }
  10301. get info() {
  10302. return this.sub.info;
  10303. }
  10304. _resetOrderedConsumer(sseq) {
  10305. if (this.info === null || this.sub.isClosed()) {
  10306. return;
  10307. }
  10308. const newDeliver = createInbox(this.js.nc.options.inboxPrefix);
  10309. const nci = this.js.nc;
  10310. nci._resub(this.sub, newDeliver);
  10311. const info = this.info;
  10312. info.ordered_consumer_sequence.delivery_seq = 0;
  10313. info.flow_control.heartbeat_count = 0;
  10314. info.flow_control.fc_count = 0;
  10315. info.flow_control.consumer_restarts++;
  10316. info.deliver = newDeliver;
  10317. info.config.deliver_subject = newDeliver;
  10318. info.config.deliver_policy = DeliverPolicy.StartSequence;
  10319. info.config.opt_start_seq = sseq;
  10320. const req = {};
  10321. req.stream_name = this.info.stream;
  10322. req.config = info.config;
  10323. const subj = `${info.api.prefix}.CONSUMER.CREATE.${info.stream}`;
  10324. this.js._request(subj, req).then((v) => {
  10325. const ci = v;
  10326. this.info.config = ci.config;
  10327. this.info.name = ci.name;
  10328. }).catch((err) => {
  10329. const nerr = new NatsError(`unable to recreate ordered consumer ${info.stream} at seq ${sseq}`, ErrorCode.RequestError, err);
  10330. this.sub.callback(nerr, {});
  10331. });
  10332. }
  10333. _maybeSetupHbMonitoring() {
  10334. var _a, _b;
  10335. const ns = ((_b = (_a = this.info) == null ? void 0 : _a.config) == null ? void 0 : _b.idle_heartbeat) || 0;
  10336. if (ns) {
  10337. this._setupHbMonitoring(millis(ns));
  10338. }
  10339. }
  10340. _setupHbMonitoring(millis2, cancelAfter = 0) {
  10341. const opts = {
  10342. cancelAfter: 0,
  10343. maxOut: 2
  10344. };
  10345. if (cancelAfter) {
  10346. opts.cancelAfter = cancelAfter;
  10347. }
  10348. const sub = this.sub;
  10349. const handler = (v) => {
  10350. var _a, _b, _c;
  10351. const msg = newJsErrorMsg(409, `${Js409Errors.IdleHeartbeatMissed}: ${v}`, this.sub.subject);
  10352. const ordered = (_a = this.info) == null ? void 0 : _a.ordered;
  10353. if (!ordered) {
  10354. this.sub.callback(null, msg);
  10355. } else {
  10356. if (!this.js.nc.protocol.connected) {
  10357. return false;
  10358. }
  10359. const seq = ((_c = (_b = this.info) == null ? void 0 : _b.ordered_consumer_sequence) == null ? void 0 : _c.stream_seq) || 0;
  10360. this._resetOrderedConsumer(seq + 1);
  10361. return false;
  10362. }
  10363. return !sub.noIterator;
  10364. };
  10365. this.monitor = new IdleHeartbeatMonitor(millis2, handler, opts);
  10366. }
  10367. _checkHbOrderConsumer(msg) {
  10368. const rm = msg.headers.get(JsHeaders.ConsumerStalledHdr);
  10369. if (rm !== "") {
  10370. const nci = this.js.nc;
  10371. nci.publish(rm);
  10372. }
  10373. const lastDelivered = parseInt(msg.headers.get(JsHeaders.LastConsumerSeqHdr), 10);
  10374. const ordered = this.info.ordered_consumer_sequence;
  10375. this.info.flow_control.heartbeat_count++;
  10376. if (lastDelivered !== ordered.delivery_seq) {
  10377. this._resetOrderedConsumer(ordered.stream_seq + 1);
  10378. }
  10379. return false;
  10380. }
  10381. _checkOrderedConsumer(jm) {
  10382. const ordered = this.info.ordered_consumer_sequence;
  10383. const sseq = jm.info.streamSequence;
  10384. const dseq = jm.info.deliverySequence;
  10385. if (dseq != ordered.delivery_seq + 1) {
  10386. this._resetOrderedConsumer(ordered.stream_seq + 1);
  10387. return false;
  10388. }
  10389. ordered.delivery_seq = dseq;
  10390. ordered.stream_seq = sseq;
  10391. return true;
  10392. }
  10393. async destroy() {
  10394. if (!this.isClosed()) {
  10395. await this.drain();
  10396. }
  10397. const jinfo = this.sub.info;
  10398. const name = jinfo.config.durable_name || jinfo.name;
  10399. const subj = `${jinfo.api.prefix}.CONSUMER.DELETE.${jinfo.stream}.${name}`;
  10400. await jinfo.api._request(subj);
  10401. }
  10402. async consumerInfo() {
  10403. const jinfo = this.sub.info;
  10404. const name = jinfo.config.durable_name || jinfo.name;
  10405. const subj = `${jinfo.api.prefix}.CONSUMER.INFO.${jinfo.stream}.${name}`;
  10406. const ci = await jinfo.api._request(subj);
  10407. jinfo.last = ci;
  10408. return ci;
  10409. }
  10410. };
  10411. var JetStreamPullSubscriptionImpl = class extends JetStreamSubscriptionImpl {
  10412. constructor(js, subject, opts) {
  10413. super(js, subject, opts);
  10414. }
  10415. pull(opts = {
  10416. batch: 1
  10417. }) {
  10418. const { stream, config, name } = this.sub.info;
  10419. const consumer = config.durable_name ?? name;
  10420. const args = {};
  10421. args.batch = opts.batch || 1;
  10422. args.no_wait = opts.no_wait || false;
  10423. if ((opts.max_bytes ?? 0) > 0) {
  10424. const fv = this.js.nc.features.get(Feature.JS_PULL_MAX_BYTES);
  10425. if (!fv.ok) {
  10426. throw new Error(`max_bytes is only supported on servers ${fv.min} or better`);
  10427. }
  10428. args.max_bytes = opts.max_bytes;
  10429. }
  10430. let expires = 0;
  10431. if (opts.expires && opts.expires > 0) {
  10432. expires = opts.expires;
  10433. args.expires = nanos(expires);
  10434. }
  10435. let hb = 0;
  10436. if (opts.idle_heartbeat && opts.idle_heartbeat > 0) {
  10437. hb = opts.idle_heartbeat;
  10438. args.idle_heartbeat = nanos(hb);
  10439. }
  10440. if (hb && expires === 0) {
  10441. throw new Error("idle_heartbeat requires expires");
  10442. }
  10443. if (hb > expires) {
  10444. throw new Error("expires must be greater than idle_heartbeat");
  10445. }
  10446. if (this.info) {
  10447. if (this.monitor) {
  10448. this.monitor.cancel();
  10449. }
  10450. if (expires && hb) {
  10451. if (!this.monitor) {
  10452. this._setupHbMonitoring(hb, expires);
  10453. } else {
  10454. this.monitor._change(hb, expires);
  10455. }
  10456. }
  10457. const api = this.info.api;
  10458. const subj = `${api.prefix}.CONSUMER.MSG.NEXT.${stream}.${consumer}`;
  10459. const reply = this.sub.subject;
  10460. api.nc.publish(subj, api.jc.encode(args), {
  10461. reply
  10462. });
  10463. }
  10464. }
  10465. };
  10466. function msgAdapter(iterator) {
  10467. if (iterator) {
  10468. return iterMsgAdapter;
  10469. } else {
  10470. return cbMsgAdapter;
  10471. }
  10472. }
  10473. function cbMsgAdapter(err, msg) {
  10474. if (err) {
  10475. return [
  10476. err,
  10477. null
  10478. ];
  10479. }
  10480. err = checkJsError(msg);
  10481. if (err) {
  10482. return [
  10483. err,
  10484. null
  10485. ];
  10486. }
  10487. return [
  10488. null,
  10489. toJsMsg(msg)
  10490. ];
  10491. }
  10492. function iterMsgAdapter(err, msg) {
  10493. if (err) {
  10494. return [
  10495. err,
  10496. null
  10497. ];
  10498. }
  10499. const ne = checkJsError(msg);
  10500. if (ne !== null) {
  10501. return [
  10502. hideNonTerminalJsErrors(ne),
  10503. null
  10504. ];
  10505. }
  10506. return [
  10507. null,
  10508. toJsMsg(msg)
  10509. ];
  10510. }
  10511. function hideNonTerminalJsErrors(ne) {
  10512. if (ne !== null) {
  10513. switch (ne.code) {
  10514. case ErrorCode.JetStream404NoMessages:
  10515. case ErrorCode.JetStream408RequestTimeout:
  10516. return null;
  10517. case ErrorCode.JetStream409:
  10518. if (isTerminal409(ne)) {
  10519. return ne;
  10520. }
  10521. return null;
  10522. default:
  10523. return ne;
  10524. }
  10525. }
  10526. return null;
  10527. }
  10528. function autoAckJsMsg(data) {
  10529. if (data) {
  10530. data.ack();
  10531. }
  10532. }
  10533. var DirectStreamAPIImpl = class extends BaseApiClient {
  10534. constructor(nc, opts) {
  10535. super(nc, opts);
  10536. }
  10537. async getMessage(stream, query) {
  10538. validateStreamName(stream);
  10539. let qq = query;
  10540. const { last_by_subj } = qq;
  10541. if (last_by_subj) {
  10542. qq = null;
  10543. }
  10544. const payload = qq ? this.jc.encode(qq) : Empty;
  10545. const pre = this.opts.apiPrefix || "$JS.API";
  10546. const subj = last_by_subj ? `${pre}.DIRECT.GET.${stream}.${last_by_subj}` : `${pre}.DIRECT.GET.${stream}`;
  10547. const r = await this.nc.request(subj, payload);
  10548. const err = checkJsError(r);
  10549. if (err) {
  10550. return Promise.reject(err);
  10551. }
  10552. const dm = new DirectMsgImpl(r);
  10553. return Promise.resolve(dm);
  10554. }
  10555. };
  10556. var DirectMsgImpl = class {
  10557. constructor(m) {
  10558. __publicField(this, "data");
  10559. __publicField(this, "header");
  10560. if (!m.headers) {
  10561. throw new Error("headers expected");
  10562. }
  10563. this.data = m.data;
  10564. this.header = m.headers;
  10565. }
  10566. get subject() {
  10567. return this.header.last(DirectMsgHeaders.Subject);
  10568. }
  10569. get seq() {
  10570. const v = this.header.last(DirectMsgHeaders.Sequence);
  10571. return typeof v === "string" ? parseInt(v) : 0;
  10572. }
  10573. get time() {
  10574. return new Date(Date.parse(this.timestamp));
  10575. }
  10576. get timestamp() {
  10577. return this.header.last(DirectMsgHeaders.TimeStamp);
  10578. }
  10579. get stream() {
  10580. return this.header.last(DirectMsgHeaders.Stream);
  10581. }
  10582. json(reviver) {
  10583. return JSONCodec(reviver).decode(this.data);
  10584. }
  10585. string() {
  10586. return TD.decode(this.data);
  10587. }
  10588. };
  10589. __publicField(DirectMsgImpl, "jc");
  10590. var JetStreamManagerImpl = class extends BaseApiClient {
  10591. constructor(nc, opts) {
  10592. super(nc, opts);
  10593. __publicField(this, "streams");
  10594. __publicField(this, "consumers");
  10595. __publicField(this, "direct");
  10596. this.streams = new StreamAPIImpl(nc, opts);
  10597. this.consumers = new ConsumerAPIImpl(nc, opts);
  10598. this.direct = new DirectStreamAPIImpl(nc, opts);
  10599. }
  10600. async getAccountInfo() {
  10601. const r = await this._request(`${this.prefix}.INFO`);
  10602. return r;
  10603. }
  10604. jetstream() {
  10605. return this.nc.jetstream(this.getOptions());
  10606. }
  10607. advisories() {
  10608. const iter = new QueuedIteratorImpl();
  10609. this.nc.subscribe(`$JS.EVENT.ADVISORY.>`, {
  10610. callback: (err, msg) => {
  10611. if (err) {
  10612. throw err;
  10613. }
  10614. try {
  10615. const d = this.parseJsResponse(msg);
  10616. const chunks = d.type.split(".");
  10617. const kind = chunks[chunks.length - 1];
  10618. iter.push({
  10619. kind,
  10620. data: d
  10621. });
  10622. } catch (err2) {
  10623. iter.stop(err2);
  10624. }
  10625. }
  10626. });
  10627. return iter;
  10628. }
  10629. };
  10630. var ServiceApiPrefix = "$SRV";
  10631. var ServiceMsgImpl = class {
  10632. constructor(msg) {
  10633. __publicField(this, "msg");
  10634. this.msg = msg;
  10635. }
  10636. get data() {
  10637. return this.msg.data;
  10638. }
  10639. get sid() {
  10640. return this.msg.sid;
  10641. }
  10642. get subject() {
  10643. return this.msg.subject;
  10644. }
  10645. get reply() {
  10646. return this.msg.reply || "";
  10647. }
  10648. get headers() {
  10649. return this.msg.headers;
  10650. }
  10651. respond(data, opts) {
  10652. return this.msg.respond(data, opts);
  10653. }
  10654. respondError(code2, description, data, opts) {
  10655. var _a, _b;
  10656. opts = opts || {};
  10657. opts.headers = opts.headers || headers();
  10658. (_a = opts.headers) == null ? void 0 : _a.set(ServiceErrorCodeHeader, `${code2}`);
  10659. (_b = opts.headers) == null ? void 0 : _b.set(ServiceErrorHeader, description);
  10660. return this.msg.respond(data, opts);
  10661. }
  10662. json(reviver) {
  10663. return this.msg.json(reviver);
  10664. }
  10665. string() {
  10666. return this.msg.string();
  10667. }
  10668. };
  10669. var ServiceGroupImpl = class {
  10670. constructor(parent, name = "", queue = "") {
  10671. __publicField(this, "subject");
  10672. __publicField(this, "queue");
  10673. __publicField(this, "srv");
  10674. if (name !== "") {
  10675. validInternalToken("service group", name);
  10676. }
  10677. let root = "";
  10678. if (parent instanceof ServiceImpl) {
  10679. this.srv = parent;
  10680. root = "";
  10681. } else if (parent instanceof ServiceGroupImpl) {
  10682. const sg = parent;
  10683. this.srv = sg.srv;
  10684. if (queue === "" && sg.queue !== "") {
  10685. queue = sg.queue;
  10686. }
  10687. root = sg.subject;
  10688. } else {
  10689. throw new Error("unknown ServiceGroup type");
  10690. }
  10691. this.subject = this.calcSubject(root, name);
  10692. this.queue = queue;
  10693. }
  10694. calcSubject(root, name = "") {
  10695. if (name === "") {
  10696. return root;
  10697. }
  10698. return root !== "" ? `${root}.${name}` : name;
  10699. }
  10700. addEndpoint(name = "", opts) {
  10701. opts = opts || {
  10702. subject: name
  10703. };
  10704. const args = typeof opts === "function" ? {
  10705. handler: opts,
  10706. subject: name
  10707. } : opts;
  10708. validateName("endpoint", name);
  10709. let { subject, handler, metadata, queue } = args;
  10710. subject = subject || name;
  10711. queue = queue || this.queue;
  10712. validSubjectName("endpoint subject", subject);
  10713. subject = this.calcSubject(this.subject, subject);
  10714. const ne = {
  10715. name,
  10716. subject,
  10717. queue,
  10718. handler,
  10719. metadata
  10720. };
  10721. return this.srv._addEndpoint(ne);
  10722. }
  10723. addGroup(name = "", queue = "") {
  10724. return new ServiceGroupImpl(this, name, queue);
  10725. }
  10726. };
  10727. function validSubjectName(context, subj) {
  10728. if (subj === "") {
  10729. throw new Error(`${context} cannot be empty`);
  10730. }
  10731. if (subj.indexOf(" ") !== -1) {
  10732. throw new Error(`${context} cannot contain spaces: '${subj}'`);
  10733. }
  10734. const tokens = subj.split(".");
  10735. tokens.forEach((v, idx) => {
  10736. if (v === ">" && idx !== tokens.length - 1) {
  10737. throw new Error(`${context} cannot have internal '>': '${subj}'`);
  10738. }
  10739. });
  10740. }
  10741. function validInternalToken(context, subj) {
  10742. if (subj.indexOf(" ") !== -1) {
  10743. throw new Error(`${context} cannot contain spaces: '${subj}'`);
  10744. }
  10745. const tokens = subj.split(".");
  10746. tokens.forEach((v) => {
  10747. if (v === ">") {
  10748. throw new Error(`${context} name cannot contain internal '>': '${subj}'`);
  10749. }
  10750. });
  10751. }
  10752. var ServiceImpl = class {
  10753. constructor(nc, config = {
  10754. name: "",
  10755. version: ""
  10756. }) {
  10757. __publicField(this, "nc");
  10758. __publicField(this, "_id");
  10759. __publicField(this, "config");
  10760. __publicField(this, "handlers");
  10761. __publicField(this, "internal");
  10762. __publicField(this, "_stopped");
  10763. __publicField(this, "_done");
  10764. __publicField(this, "started");
  10765. this.nc = nc;
  10766. this.config = Object.assign({}, config);
  10767. if (!this.config.queue) {
  10768. this.config.queue = "q";
  10769. }
  10770. validateName("name", this.config.name);
  10771. validateName("queue", this.config.queue);
  10772. parseSemVer(this.config.version);
  10773. this._id = nuid.next();
  10774. this.internal = [];
  10775. this._done = deferred();
  10776. this._stopped = false;
  10777. this.handlers = [];
  10778. this.started = (/* @__PURE__ */ new Date()).toISOString();
  10779. this.reset();
  10780. this.nc.closed().then(() => {
  10781. this.close().catch();
  10782. }).catch((err) => {
  10783. this.close(err).catch();
  10784. });
  10785. }
  10786. static controlSubject(verb, name = "", id = "", prefix) {
  10787. const pre = prefix ?? ServiceApiPrefix;
  10788. if (name === "" && id === "") {
  10789. return `${pre}.${verb}`;
  10790. }
  10791. validateName("control subject name", name);
  10792. if (id !== "") {
  10793. validateName("control subject id", id);
  10794. return `${pre}.${verb}.${name}.${id}`;
  10795. }
  10796. return `${pre}.${verb}.${name}`;
  10797. }
  10798. get subjects() {
  10799. return this.handlers.filter((s) => {
  10800. return s.internal === false;
  10801. }).map((s) => {
  10802. return s.subject;
  10803. });
  10804. }
  10805. get id() {
  10806. return this._id;
  10807. }
  10808. get name() {
  10809. return this.config.name;
  10810. }
  10811. get description() {
  10812. return this.config.description ?? "";
  10813. }
  10814. get version() {
  10815. return this.config.version;
  10816. }
  10817. get metadata() {
  10818. return this.config.metadata;
  10819. }
  10820. errorToHeader(err) {
  10821. const h = headers();
  10822. if (err instanceof ServiceError) {
  10823. const se = err;
  10824. h.set(ServiceErrorHeader, se.message);
  10825. h.set(ServiceErrorCodeHeader, `${se.code}`);
  10826. } else {
  10827. h.set(ServiceErrorHeader, err.message);
  10828. h.set(ServiceErrorCodeHeader, "500");
  10829. }
  10830. return h;
  10831. }
  10832. setupHandler(h, internal = false) {
  10833. const queue = internal ? "" : h.queue ? h.queue : this.config.queue;
  10834. const { name, subject, handler } = h;
  10835. const sv = h;
  10836. sv.internal = internal;
  10837. if (internal) {
  10838. this.internal.push(sv);
  10839. }
  10840. sv.stats = new NamedEndpointStatsImpl(name, subject, queue);
  10841. sv.queue = queue;
  10842. const callback = handler ? (err, msg) => {
  10843. if (err) {
  10844. this.close(err);
  10845. return;
  10846. }
  10847. const start = Date.now();
  10848. try {
  10849. handler(err, new ServiceMsgImpl(msg));
  10850. } catch (err2) {
  10851. sv.stats.countError(err2);
  10852. msg == null ? void 0 : msg.respond(Empty, {
  10853. headers: this.errorToHeader(err2)
  10854. });
  10855. } finally {
  10856. sv.stats.countLatency(start);
  10857. }
  10858. } : void 0;
  10859. sv.sub = this.nc.subscribe(subject, {
  10860. callback,
  10861. queue
  10862. });
  10863. sv.sub.closed.then(() => {
  10864. if (!this._stopped) {
  10865. this.close(new Error(`required subscription ${h.subject} stopped`)).catch();
  10866. }
  10867. }).catch((err) => {
  10868. if (!this._stopped) {
  10869. const ne = new Error(`required subscription ${h.subject} errored: ${err.message}`);
  10870. ne.stack = err.stack;
  10871. this.close(ne).catch();
  10872. }
  10873. });
  10874. return sv;
  10875. }
  10876. info() {
  10877. return {
  10878. type: ServiceResponseType.INFO,
  10879. name: this.name,
  10880. id: this.id,
  10881. version: this.version,
  10882. description: this.description,
  10883. metadata: this.metadata,
  10884. endpoints: this.endpoints()
  10885. };
  10886. }
  10887. endpoints() {
  10888. return this.handlers.map((v) => {
  10889. const { subject, metadata, name, queue } = v;
  10890. return {
  10891. subject,
  10892. metadata,
  10893. name,
  10894. queue_group: queue
  10895. };
  10896. });
  10897. }
  10898. async stats() {
  10899. const endpoints = [];
  10900. for (const h of this.handlers) {
  10901. if (typeof this.config.statsHandler === "function") {
  10902. try {
  10903. h.stats.data = await this.config.statsHandler(h);
  10904. } catch (err) {
  10905. h.stats.countError(err);
  10906. }
  10907. }
  10908. endpoints.push(h.stats.stats(h.qi));
  10909. }
  10910. return {
  10911. type: ServiceResponseType.STATS,
  10912. name: this.name,
  10913. id: this.id,
  10914. version: this.version,
  10915. started: this.started,
  10916. metadata: this.metadata,
  10917. endpoints
  10918. };
  10919. }
  10920. addInternalHandler(verb, handler) {
  10921. const v = `${verb}`.toUpperCase();
  10922. this._doAddInternalHandler(`${v}-all`, verb, handler);
  10923. this._doAddInternalHandler(`${v}-kind`, verb, handler, this.name);
  10924. this._doAddInternalHandler(`${v}`, verb, handler, this.name, this.id);
  10925. }
  10926. _doAddInternalHandler(name, verb, handler, kind = "", id = "") {
  10927. const endpoint = {};
  10928. endpoint.name = name;
  10929. endpoint.subject = ServiceImpl.controlSubject(verb, kind, id);
  10930. endpoint.handler = handler;
  10931. this.setupHandler(endpoint, true);
  10932. }
  10933. start() {
  10934. const jc = JSONCodec();
  10935. const statsHandler = (err, msg) => {
  10936. if (err) {
  10937. this.close(err);
  10938. return Promise.reject(err);
  10939. }
  10940. return this.stats().then((s) => {
  10941. msg == null ? void 0 : msg.respond(jc.encode(s));
  10942. return Promise.resolve();
  10943. });
  10944. };
  10945. const infoHandler = (err, msg) => {
  10946. if (err) {
  10947. this.close(err);
  10948. return Promise.reject(err);
  10949. }
  10950. msg == null ? void 0 : msg.respond(jc.encode(this.info()));
  10951. return Promise.resolve();
  10952. };
  10953. const ping = jc.encode(this.ping());
  10954. const pingHandler = (err, msg) => {
  10955. if (err) {
  10956. this.close(err).then().catch();
  10957. return Promise.reject(err);
  10958. }
  10959. msg.respond(ping);
  10960. return Promise.resolve();
  10961. };
  10962. this.addInternalHandler(ServiceVerb.PING, pingHandler);
  10963. this.addInternalHandler(ServiceVerb.STATS, statsHandler);
  10964. this.addInternalHandler(ServiceVerb.INFO, infoHandler);
  10965. this.handlers.forEach((h) => {
  10966. const { subject } = h;
  10967. if (typeof subject !== "string") {
  10968. return;
  10969. }
  10970. if (h.handler === null) {
  10971. return;
  10972. }
  10973. this.setupHandler(h);
  10974. });
  10975. return Promise.resolve(this);
  10976. }
  10977. close(err) {
  10978. if (this._stopped) {
  10979. return this._done;
  10980. }
  10981. this._stopped = true;
  10982. let buf = [];
  10983. if (!this.nc.isClosed()) {
  10984. buf = this.handlers.concat(this.internal).map((h) => {
  10985. return h.sub.drain();
  10986. });
  10987. }
  10988. Promise.allSettled(buf).then(() => {
  10989. this._done.resolve(err ? err : null);
  10990. });
  10991. return this._done;
  10992. }
  10993. get stopped() {
  10994. return this._done;
  10995. }
  10996. get isStopped() {
  10997. return this._stopped;
  10998. }
  10999. stop(err) {
  11000. return this.close(err);
  11001. }
  11002. ping() {
  11003. return {
  11004. type: ServiceResponseType.PING,
  11005. name: this.name,
  11006. id: this.id,
  11007. version: this.version,
  11008. metadata: this.metadata
  11009. };
  11010. }
  11011. reset() {
  11012. this.started = (/* @__PURE__ */ new Date()).toISOString();
  11013. if (this.handlers) {
  11014. for (const h of this.handlers) {
  11015. h.stats.reset(h.qi);
  11016. }
  11017. }
  11018. }
  11019. addGroup(name, queue) {
  11020. return new ServiceGroupImpl(this, name, queue);
  11021. }
  11022. addEndpoint(name, handler) {
  11023. const sg = new ServiceGroupImpl(this);
  11024. return sg.addEndpoint(name, handler);
  11025. }
  11026. _addEndpoint(e) {
  11027. const qi = new QueuedIteratorImpl();
  11028. qi.noIterator = typeof e.handler === "function";
  11029. if (!qi.noIterator) {
  11030. e.handler = (err, msg) => {
  11031. err ? this.stop(err).catch() : qi.push(new ServiceMsgImpl(msg));
  11032. };
  11033. qi.iterClosed.then(() => {
  11034. this.close().catch();
  11035. });
  11036. }
  11037. const ss = this.setupHandler(e, false);
  11038. ss.qi = qi;
  11039. this.handlers.push(ss);
  11040. return qi;
  11041. }
  11042. };
  11043. var NamedEndpointStatsImpl = class {
  11044. constructor(name, subject, queue = "") {
  11045. __publicField(this, "name");
  11046. __publicField(this, "subject");
  11047. __publicField(this, "average_processing_time");
  11048. __publicField(this, "num_requests");
  11049. __publicField(this, "processing_time");
  11050. __publicField(this, "num_errors");
  11051. __publicField(this, "last_error");
  11052. __publicField(this, "data");
  11053. __publicField(this, "metadata");
  11054. __publicField(this, "queue");
  11055. this.name = name;
  11056. this.subject = subject;
  11057. this.average_processing_time = 0;
  11058. this.num_errors = 0;
  11059. this.num_requests = 0;
  11060. this.processing_time = 0;
  11061. this.queue = queue;
  11062. }
  11063. reset(qi) {
  11064. this.num_requests = 0;
  11065. this.processing_time = 0;
  11066. this.average_processing_time = 0;
  11067. this.num_errors = 0;
  11068. this.last_error = void 0;
  11069. this.data = void 0;
  11070. const qii = qi;
  11071. if (qii) {
  11072. qii.time = 0;
  11073. qii.processed = 0;
  11074. }
  11075. }
  11076. countLatency(start) {
  11077. this.num_requests++;
  11078. this.processing_time += nanos(Date.now() - start);
  11079. this.average_processing_time = Math.round(this.processing_time / this.num_requests);
  11080. }
  11081. countError(err) {
  11082. this.num_errors++;
  11083. this.last_error = err.message;
  11084. }
  11085. _stats() {
  11086. const { name, subject, average_processing_time, num_errors, num_requests, processing_time, last_error, data, queue } = this;
  11087. return {
  11088. name,
  11089. subject,
  11090. average_processing_time,
  11091. num_errors,
  11092. num_requests,
  11093. processing_time,
  11094. last_error,
  11095. data,
  11096. queue_group: queue
  11097. };
  11098. }
  11099. stats(qi) {
  11100. const qii = qi;
  11101. if ((qii == null ? void 0 : qii.noIterator) === false) {
  11102. this.processing_time = qii.time;
  11103. this.num_requests = qii.processed;
  11104. this.average_processing_time = this.processing_time > 0 && this.num_requests > 0 ? this.processing_time / this.num_requests : 0;
  11105. }
  11106. return this._stats();
  11107. }
  11108. };
  11109. var ServiceClientImpl = class {
  11110. constructor(nc, opts = {
  11111. strategy: RequestStrategy.JitterTimer,
  11112. maxWait: 2e3
  11113. }, prefix) {
  11114. __publicField(this, "nc");
  11115. __publicField(this, "prefix");
  11116. __publicField(this, "opts");
  11117. this.nc = nc;
  11118. this.prefix = prefix;
  11119. this.opts = opts;
  11120. }
  11121. ping(name = "", id = "") {
  11122. return this.q(ServiceVerb.PING, name, id);
  11123. }
  11124. stats(name = "", id = "") {
  11125. return this.q(ServiceVerb.STATS, name, id);
  11126. }
  11127. info(name = "", id = "") {
  11128. return this.q(ServiceVerb.INFO, name, id);
  11129. }
  11130. async q(v, name = "", id = "") {
  11131. const iter = new QueuedIteratorImpl();
  11132. const jc = JSONCodec();
  11133. const subj = ServiceImpl.controlSubject(v, name, id, this.prefix);
  11134. const responses = await this.nc.requestMany(subj, Empty, this.opts);
  11135. (async () => {
  11136. for await (const m of responses) {
  11137. try {
  11138. const s = jc.decode(m.data);
  11139. iter.push(s);
  11140. } catch (err) {
  11141. iter.push(() => {
  11142. iter.stop(err);
  11143. });
  11144. }
  11145. }
  11146. iter.push(() => {
  11147. iter.stop();
  11148. });
  11149. })().catch((err) => {
  11150. iter.stop(err);
  11151. });
  11152. return iter;
  11153. }
  11154. };
  11155. var NatsConnectionImpl = class {
  11156. constructor(opts) {
  11157. __publicField(this, "options");
  11158. __publicField(this, "protocol");
  11159. __publicField(this, "draining");
  11160. __publicField(this, "listeners");
  11161. __publicField(this, "_services");
  11162. this.draining = false;
  11163. this.options = parseOptions(opts);
  11164. this.listeners = [];
  11165. }
  11166. static connect(opts = {}) {
  11167. return new Promise((resolve, reject) => {
  11168. const nc = new NatsConnectionImpl(opts);
  11169. ProtocolHandler.connect(nc.options, nc).then((ph) => {
  11170. nc.protocol = ph;
  11171. (async function() {
  11172. for await (const s of ph.status()) {
  11173. nc.listeners.forEach((l) => {
  11174. l.push(s);
  11175. });
  11176. }
  11177. })();
  11178. resolve(nc);
  11179. }).catch((err) => {
  11180. reject(err);
  11181. });
  11182. });
  11183. }
  11184. closed() {
  11185. return this.protocol.closed;
  11186. }
  11187. async close() {
  11188. await this.protocol.close();
  11189. }
  11190. _check(subject, sub, pub) {
  11191. if (this.isClosed()) {
  11192. throw NatsError.errorForCode(ErrorCode.ConnectionClosed);
  11193. }
  11194. if (sub && this.isDraining()) {
  11195. throw NatsError.errorForCode(ErrorCode.ConnectionDraining);
  11196. }
  11197. if (pub && this.protocol.noMorePublishing) {
  11198. throw NatsError.errorForCode(ErrorCode.ConnectionDraining);
  11199. }
  11200. subject = subject || "";
  11201. if (subject.length === 0) {
  11202. throw NatsError.errorForCode(ErrorCode.BadSubject);
  11203. }
  11204. }
  11205. publish(subject, data, options) {
  11206. this._check(subject, false, true);
  11207. this.protocol.publish(subject, data, options);
  11208. }
  11209. subscribe(subject, opts = {}) {
  11210. this._check(subject, true, false);
  11211. const sub = new SubscriptionImpl(this.protocol, subject, opts);
  11212. this.protocol.subscribe(sub);
  11213. return sub;
  11214. }
  11215. _resub(s, subject, max) {
  11216. this._check(subject, true, false);
  11217. const si = s;
  11218. si.max = max;
  11219. if (max) {
  11220. si.max = max + si.received;
  11221. }
  11222. this.protocol.resub(si, subject);
  11223. }
  11224. requestMany(subject, data = Empty, opts = {
  11225. maxWait: 1e3,
  11226. maxMessages: -1
  11227. }) {
  11228. const asyncTraces = !(this.protocol.options.noAsyncTraces || false);
  11229. try {
  11230. this._check(subject, true, true);
  11231. } catch (err) {
  11232. return Promise.reject(err);
  11233. }
  11234. opts.strategy = opts.strategy || RequestStrategy.Timer;
  11235. opts.maxWait = opts.maxWait || 1e3;
  11236. if (opts.maxWait < 1) {
  11237. return Promise.reject(new NatsError("timeout", ErrorCode.InvalidOption));
  11238. }
  11239. const qi = new QueuedIteratorImpl();
  11240. function stop(err) {
  11241. qi.push(() => {
  11242. qi.stop(err);
  11243. });
  11244. }
  11245. function callback(err, msg) {
  11246. if (err || msg === null) {
  11247. stop(err === null ? void 0 : err);
  11248. } else {
  11249. qi.push(msg);
  11250. }
  11251. }
  11252. if (opts.noMux) {
  11253. const stack = asyncTraces ? new Error().stack : null;
  11254. let max = typeof opts.maxMessages === "number" && opts.maxMessages > 0 ? opts.maxMessages : -1;
  11255. const sub = this.subscribe(createInbox(this.options.inboxPrefix), {
  11256. callback: (err, msg) => {
  11257. var _a, _b;
  11258. if (((_a = msg == null ? void 0 : msg.data) == null ? void 0 : _a.length) === 0 && ((_b = msg == null ? void 0 : msg.headers) == null ? void 0 : _b.status) === ErrorCode.NoResponders) {
  11259. err = NatsError.errorForCode(ErrorCode.NoResponders);
  11260. }
  11261. if (err) {
  11262. if (stack) {
  11263. err.stack += `
  11264. ${stack}`;
  11265. }
  11266. cancel(err);
  11267. return;
  11268. }
  11269. callback(null, msg);
  11270. if (opts.strategy === RequestStrategy.Count) {
  11271. max--;
  11272. if (max === 0) {
  11273. cancel();
  11274. }
  11275. }
  11276. if (opts.strategy === RequestStrategy.JitterTimer) {
  11277. clearTimers();
  11278. timer = setTimeout(() => {
  11279. cancel();
  11280. }, 300);
  11281. }
  11282. if (opts.strategy === RequestStrategy.SentinelMsg) {
  11283. if (msg && msg.data.length === 0) {
  11284. cancel();
  11285. }
  11286. }
  11287. }
  11288. });
  11289. sub.closed.then(() => {
  11290. stop();
  11291. }).catch((err) => {
  11292. qi.stop(err);
  11293. });
  11294. const cancel = (err) => {
  11295. if (err) {
  11296. qi.push(() => {
  11297. throw err;
  11298. });
  11299. }
  11300. clearTimers();
  11301. sub.drain().then(() => {
  11302. stop();
  11303. }).catch((_err) => {
  11304. stop();
  11305. });
  11306. };
  11307. qi.iterClosed.then(() => {
  11308. clearTimers();
  11309. sub == null ? void 0 : sub.unsubscribe();
  11310. }).catch((_err) => {
  11311. clearTimers();
  11312. sub == null ? void 0 : sub.unsubscribe();
  11313. });
  11314. try {
  11315. this.publish(subject, data, {
  11316. reply: sub.getSubject()
  11317. });
  11318. } catch (err) {
  11319. cancel(err);
  11320. }
  11321. let timer = setTimeout(() => {
  11322. cancel();
  11323. }, opts.maxWait);
  11324. const clearTimers = () => {
  11325. if (timer) {
  11326. clearTimeout(timer);
  11327. }
  11328. };
  11329. } else {
  11330. const rmo = opts;
  11331. rmo.callback = callback;
  11332. qi.iterClosed.then(() => {
  11333. r.cancel();
  11334. }).catch((err) => {
  11335. r.cancel(err);
  11336. });
  11337. const r = new RequestMany(this.protocol.muxSubscriptions, subject, rmo);
  11338. this.protocol.request(r);
  11339. try {
  11340. this.publish(subject, data, {
  11341. reply: `${this.protocol.muxSubscriptions.baseInbox}${r.token}`,
  11342. headers: opts.headers
  11343. });
  11344. } catch (err) {
  11345. r.cancel(err);
  11346. }
  11347. }
  11348. return Promise.resolve(qi);
  11349. }
  11350. request(subject, data, opts = {
  11351. timeout: 1e3,
  11352. noMux: false
  11353. }) {
  11354. try {
  11355. this._check(subject, true, true);
  11356. } catch (err) {
  11357. return Promise.reject(err);
  11358. }
  11359. const asyncTraces = !(this.protocol.options.noAsyncTraces || false);
  11360. opts.timeout = opts.timeout || 1e3;
  11361. if (opts.timeout < 1) {
  11362. return Promise.reject(new NatsError("timeout", ErrorCode.InvalidOption));
  11363. }
  11364. if (!opts.noMux && opts.reply) {
  11365. return Promise.reject(new NatsError("reply can only be used with noMux", ErrorCode.InvalidOption));
  11366. }
  11367. if (opts.noMux) {
  11368. const inbox = opts.reply ? opts.reply : createInbox(this.options.inboxPrefix);
  11369. const d = deferred();
  11370. const errCtx = asyncTraces ? new Error() : null;
  11371. const sub = this.subscribe(inbox, {
  11372. max: 1,
  11373. timeout: opts.timeout,
  11374. callback: (err, msg) => {
  11375. if (err) {
  11376. if (errCtx && err.code !== ErrorCode.Timeout) {
  11377. err.stack += `
  11378. ${errCtx.stack}`;
  11379. }
  11380. d.reject(err);
  11381. } else {
  11382. err = isRequestError(msg);
  11383. if (err) {
  11384. if (errCtx) {
  11385. err.stack += `
  11386. ${errCtx.stack}`;
  11387. }
  11388. d.reject(err);
  11389. } else {
  11390. d.resolve(msg);
  11391. }
  11392. }
  11393. }
  11394. });
  11395. sub.requestSubject = subject;
  11396. this.protocol.publish(subject, data, {
  11397. reply: inbox,
  11398. headers: opts.headers
  11399. });
  11400. return d;
  11401. } else {
  11402. const r = new RequestOne(this.protocol.muxSubscriptions, subject, opts, asyncTraces);
  11403. this.protocol.request(r);
  11404. try {
  11405. this.publish(subject, data, {
  11406. reply: `${this.protocol.muxSubscriptions.baseInbox}${r.token}`,
  11407. headers: opts.headers
  11408. });
  11409. } catch (err) {
  11410. r.cancel(err);
  11411. }
  11412. const p = Promise.race([
  11413. r.timer,
  11414. r.deferred
  11415. ]);
  11416. p.catch(() => {
  11417. r.cancel();
  11418. });
  11419. return p;
  11420. }
  11421. }
  11422. flush() {
  11423. if (this.isClosed()) {
  11424. return Promise.reject(NatsError.errorForCode(ErrorCode.ConnectionClosed));
  11425. }
  11426. return this.protocol.flush();
  11427. }
  11428. drain() {
  11429. if (this.isClosed()) {
  11430. return Promise.reject(NatsError.errorForCode(ErrorCode.ConnectionClosed));
  11431. }
  11432. if (this.isDraining()) {
  11433. return Promise.reject(NatsError.errorForCode(ErrorCode.ConnectionDraining));
  11434. }
  11435. this.draining = true;
  11436. return this.protocol.drain();
  11437. }
  11438. isClosed() {
  11439. return this.protocol.isClosed();
  11440. }
  11441. isDraining() {
  11442. return this.draining;
  11443. }
  11444. getServer() {
  11445. const srv = this.protocol.getServer();
  11446. return srv ? srv.listen : "";
  11447. }
  11448. status() {
  11449. const iter = new QueuedIteratorImpl();
  11450. iter.iterClosed.then(() => {
  11451. const idx = this.listeners.indexOf(iter);
  11452. this.listeners.splice(idx, 1);
  11453. });
  11454. this.listeners.push(iter);
  11455. return iter;
  11456. }
  11457. get info() {
  11458. return this.protocol.isClosed() ? void 0 : this.protocol.info;
  11459. }
  11460. stats() {
  11461. return {
  11462. inBytes: this.protocol.inBytes,
  11463. outBytes: this.protocol.outBytes,
  11464. inMsgs: this.protocol.inMsgs,
  11465. outMsgs: this.protocol.outMsgs
  11466. };
  11467. }
  11468. async jetstreamManager(opts = {}) {
  11469. const adm = new JetStreamManagerImpl(this, opts);
  11470. if (opts.checkAPI !== false) {
  11471. try {
  11472. await adm.getAccountInfo();
  11473. } catch (err) {
  11474. const ne = err;
  11475. if (ne.code === ErrorCode.NoResponders) {
  11476. ne.code = ErrorCode.JetStreamNotEnabled;
  11477. }
  11478. throw ne;
  11479. }
  11480. }
  11481. return adm;
  11482. }
  11483. jetstream(opts = {}) {
  11484. return new JetStreamClientImpl(this, opts);
  11485. }
  11486. getServerVersion() {
  11487. const info = this.info;
  11488. return info ? parseSemVer(info.version) : void 0;
  11489. }
  11490. async rtt() {
  11491. if (!this.protocol._closed && !this.protocol.connected) {
  11492. throw NatsError.errorForCode(ErrorCode.Disconnect);
  11493. }
  11494. const start = Date.now();
  11495. await this.flush();
  11496. return Date.now() - start;
  11497. }
  11498. get features() {
  11499. return this.protocol.features;
  11500. }
  11501. get services() {
  11502. if (!this._services) {
  11503. this._services = new ServicesFactory(this);
  11504. }
  11505. return this._services;
  11506. }
  11507. reconnect() {
  11508. if (this.isClosed()) {
  11509. return Promise.reject(NatsError.errorForCode(ErrorCode.ConnectionClosed));
  11510. }
  11511. if (this.isDraining()) {
  11512. return Promise.reject(NatsError.errorForCode(ErrorCode.ConnectionDraining));
  11513. }
  11514. return this.protocol.reconnect();
  11515. }
  11516. };
  11517. var ServicesFactory = class {
  11518. constructor(nc) {
  11519. __publicField(this, "nc");
  11520. this.nc = nc;
  11521. }
  11522. add(config) {
  11523. try {
  11524. const s = new ServiceImpl(this.nc, config);
  11525. return s.start();
  11526. } catch (err) {
  11527. return Promise.reject(err);
  11528. }
  11529. }
  11530. client(opts, prefix) {
  11531. return new ServiceClientImpl(this.nc, opts, prefix);
  11532. }
  11533. };
  11534. var Metric = class {
  11535. constructor(name, duration) {
  11536. __publicField(this, "name");
  11537. __publicField(this, "duration");
  11538. __publicField(this, "date");
  11539. __publicField(this, "payload");
  11540. __publicField(this, "msgs");
  11541. __publicField(this, "lang");
  11542. __publicField(this, "version");
  11543. __publicField(this, "bytes");
  11544. __publicField(this, "asyncRequests");
  11545. __publicField(this, "min");
  11546. __publicField(this, "max");
  11547. this.name = name;
  11548. this.duration = duration;
  11549. this.date = Date.now();
  11550. this.payload = 0;
  11551. this.msgs = 0;
  11552. this.bytes = 0;
  11553. }
  11554. toString() {
  11555. const sec = this.duration / 1e3;
  11556. const mps = Math.round(this.msgs / sec);
  11557. const label = this.asyncRequests ? "asyncRequests" : "";
  11558. let minmax = "";
  11559. if (this.max) {
  11560. minmax = `${this.min}/${this.max}`;
  11561. }
  11562. return `${this.name}${label ? " [asyncRequests]" : ""} ${humanizeNumber(mps)} msgs/sec - [${sec.toFixed(2)} secs] ~ ${throughput(this.bytes, sec)} ${minmax}`;
  11563. }
  11564. toCsv() {
  11565. return `"${this.name}",${new Date(this.date).toISOString()},${this.lang},${this.version},${this.msgs},${this.payload},${this.bytes},${this.duration},${this.asyncRequests ? this.asyncRequests : false}
  11566. `;
  11567. }
  11568. static header() {
  11569. return `Test,Date,Lang,Version,Count,MsgPayload,Bytes,Millis,Async
  11570. `;
  11571. }
  11572. };
  11573. var Bench = class {
  11574. constructor(nc, opts = {
  11575. msgs: 1e5,
  11576. size: 128,
  11577. subject: "",
  11578. asyncRequests: false,
  11579. pub: false,
  11580. sub: false,
  11581. req: false,
  11582. rep: false
  11583. }) {
  11584. __publicField(this, "nc");
  11585. __publicField(this, "callbacks");
  11586. __publicField(this, "msgs");
  11587. __publicField(this, "size");
  11588. __publicField(this, "subject");
  11589. __publicField(this, "asyncRequests");
  11590. __publicField(this, "pub");
  11591. __publicField(this, "sub");
  11592. __publicField(this, "req");
  11593. __publicField(this, "rep");
  11594. __publicField(this, "perf");
  11595. __publicField(this, "payload");
  11596. this.nc = nc;
  11597. this.callbacks = opts.callbacks || false;
  11598. this.msgs = opts.msgs || 0;
  11599. this.size = opts.size || 0;
  11600. this.subject = opts.subject || nuid.next();
  11601. this.asyncRequests = opts.asyncRequests || false;
  11602. this.pub = opts.pub || false;
  11603. this.sub = opts.sub || false;
  11604. this.req = opts.req || false;
  11605. this.rep = opts.rep || false;
  11606. this.perf = new Perf();
  11607. this.payload = this.size ? new Uint8Array(this.size) : Empty;
  11608. if (!this.pub && !this.sub && !this.req && !this.rep) {
  11609. throw new Error("no bench option selected");
  11610. }
  11611. }
  11612. async run() {
  11613. this.nc.closed().then((err) => {
  11614. if (err) {
  11615. throw new NatsError(`bench closed with an error: ${err.message}`, ErrorCode.Unknown, err);
  11616. }
  11617. });
  11618. if (this.callbacks) {
  11619. await this.runCallbacks();
  11620. } else {
  11621. await this.runAsync();
  11622. }
  11623. return this.processMetrics();
  11624. }
  11625. processMetrics() {
  11626. const nc = this.nc;
  11627. const { lang, version } = nc.protocol.transport;
  11628. if (this.pub && this.sub) {
  11629. this.perf.measure("pubsub", "pubStart", "subStop");
  11630. }
  11631. if (this.req && this.rep) {
  11632. this.perf.measure("reqrep", "reqStart", "reqStop");
  11633. }
  11634. const measures = this.perf.getEntries();
  11635. const pubsub = measures.find((m) => m.name === "pubsub");
  11636. const reqrep = measures.find((m) => m.name === "reqrep");
  11637. const req = measures.find((m) => m.name === "req");
  11638. const rep = measures.find((m) => m.name === "rep");
  11639. const pub = measures.find((m) => m.name === "pub");
  11640. const sub = measures.find((m) => m.name === "sub");
  11641. const stats = this.nc.stats();
  11642. const metrics = [];
  11643. if (pubsub) {
  11644. const { name, duration } = pubsub;
  11645. const m = new Metric(name, duration);
  11646. m.msgs = this.msgs * 2;
  11647. m.bytes = stats.inBytes + stats.outBytes;
  11648. m.lang = lang;
  11649. m.version = version;
  11650. m.payload = this.payload.length;
  11651. metrics.push(m);
  11652. }
  11653. if (reqrep) {
  11654. const { name, duration } = reqrep;
  11655. const m = new Metric(name, duration);
  11656. m.msgs = this.msgs * 2;
  11657. m.bytes = stats.inBytes + stats.outBytes;
  11658. m.lang = lang;
  11659. m.version = version;
  11660. m.payload = this.payload.length;
  11661. metrics.push(m);
  11662. }
  11663. if (pub) {
  11664. const { name, duration } = pub;
  11665. const m = new Metric(name, duration);
  11666. m.msgs = this.msgs;
  11667. m.bytes = stats.outBytes;
  11668. m.lang = lang;
  11669. m.version = version;
  11670. m.payload = this.payload.length;
  11671. metrics.push(m);
  11672. }
  11673. if (sub) {
  11674. const { name, duration } = sub;
  11675. const m = new Metric(name, duration);
  11676. m.msgs = this.msgs;
  11677. m.bytes = stats.inBytes;
  11678. m.lang = lang;
  11679. m.version = version;
  11680. m.payload = this.payload.length;
  11681. metrics.push(m);
  11682. }
  11683. if (rep) {
  11684. const { name, duration } = rep;
  11685. const m = new Metric(name, duration);
  11686. m.msgs = this.msgs;
  11687. m.bytes = stats.inBytes + stats.outBytes;
  11688. m.lang = lang;
  11689. m.version = version;
  11690. m.payload = this.payload.length;
  11691. metrics.push(m);
  11692. }
  11693. if (req) {
  11694. const { name, duration } = req;
  11695. const m = new Metric(name, duration);
  11696. m.msgs = this.msgs;
  11697. m.bytes = stats.inBytes + stats.outBytes;
  11698. m.lang = lang;
  11699. m.version = version;
  11700. m.payload = this.payload.length;
  11701. metrics.push(m);
  11702. }
  11703. return metrics;
  11704. }
  11705. async runCallbacks() {
  11706. const jobs = [];
  11707. if (this.sub) {
  11708. const d = deferred();
  11709. jobs.push(d);
  11710. let i = 0;
  11711. this.nc.subscribe(this.subject, {
  11712. max: this.msgs,
  11713. callback: () => {
  11714. i++;
  11715. if (i === 1) {
  11716. this.perf.mark("subStart");
  11717. }
  11718. if (i === this.msgs) {
  11719. this.perf.mark("subStop");
  11720. this.perf.measure("sub", "subStart", "subStop");
  11721. d.resolve();
  11722. }
  11723. }
  11724. });
  11725. }
  11726. if (this.rep) {
  11727. const d = deferred();
  11728. jobs.push(d);
  11729. let i = 0;
  11730. this.nc.subscribe(this.subject, {
  11731. max: this.msgs,
  11732. callback: (_, m) => {
  11733. m.respond(this.payload);
  11734. i++;
  11735. if (i === 1) {
  11736. this.perf.mark("repStart");
  11737. }
  11738. if (i === this.msgs) {
  11739. this.perf.mark("repStop");
  11740. this.perf.measure("rep", "repStart", "repStop");
  11741. d.resolve();
  11742. }
  11743. }
  11744. });
  11745. }
  11746. if (this.pub) {
  11747. const job = (async () => {
  11748. this.perf.mark("pubStart");
  11749. for (let i = 0; i < this.msgs; i++) {
  11750. this.nc.publish(this.subject, this.payload);
  11751. }
  11752. await this.nc.flush();
  11753. this.perf.mark("pubStop");
  11754. this.perf.measure("pub", "pubStart", "pubStop");
  11755. })();
  11756. jobs.push(job);
  11757. }
  11758. if (this.req) {
  11759. const job = (async () => {
  11760. if (this.asyncRequests) {
  11761. this.perf.mark("reqStart");
  11762. const a = [];
  11763. for (let i = 0; i < this.msgs; i++) {
  11764. a.push(this.nc.request(this.subject, this.payload, {
  11765. timeout: 2e4
  11766. }));
  11767. }
  11768. await Promise.all(a);
  11769. this.perf.mark("reqStop");
  11770. this.perf.measure("req", "reqStart", "reqStop");
  11771. } else {
  11772. this.perf.mark("reqStart");
  11773. for (let i = 0; i < this.msgs; i++) {
  11774. await this.nc.request(this.subject);
  11775. }
  11776. this.perf.mark("reqStop");
  11777. this.perf.measure("req", "reqStart", "reqStop");
  11778. }
  11779. })();
  11780. jobs.push(job);
  11781. }
  11782. await Promise.all(jobs);
  11783. }
  11784. async runAsync() {
  11785. const jobs = [];
  11786. if (this.rep) {
  11787. let first = false;
  11788. const sub = this.nc.subscribe(this.subject, {
  11789. max: this.msgs
  11790. });
  11791. const job = (async () => {
  11792. for await (const m of sub) {
  11793. if (!first) {
  11794. this.perf.mark("repStart");
  11795. first = true;
  11796. }
  11797. m.respond(this.payload);
  11798. }
  11799. await this.nc.flush();
  11800. this.perf.mark("repStop");
  11801. this.perf.measure("rep", "repStart", "repStop");
  11802. })();
  11803. jobs.push(job);
  11804. }
  11805. if (this.sub) {
  11806. let first = false;
  11807. const sub = this.nc.subscribe(this.subject, {
  11808. max: this.msgs
  11809. });
  11810. const job = (async () => {
  11811. for await (const _m of sub) {
  11812. if (!first) {
  11813. this.perf.mark("subStart");
  11814. first = true;
  11815. }
  11816. }
  11817. this.perf.mark("subStop");
  11818. this.perf.measure("sub", "subStart", "subStop");
  11819. })();
  11820. jobs.push(job);
  11821. }
  11822. if (this.pub) {
  11823. const job = (async () => {
  11824. this.perf.mark("pubStart");
  11825. for (let i = 0; i < this.msgs; i++) {
  11826. this.nc.publish(this.subject, this.payload);
  11827. }
  11828. await this.nc.flush();
  11829. this.perf.mark("pubStop");
  11830. this.perf.measure("pub", "pubStart", "pubStop");
  11831. })();
  11832. jobs.push(job);
  11833. }
  11834. if (this.req) {
  11835. const job = (async () => {
  11836. if (this.asyncRequests) {
  11837. this.perf.mark("reqStart");
  11838. const a = [];
  11839. for (let i = 0; i < this.msgs; i++) {
  11840. a.push(this.nc.request(this.subject, this.payload, {
  11841. timeout: 2e4
  11842. }));
  11843. }
  11844. await Promise.all(a);
  11845. this.perf.mark("reqStop");
  11846. this.perf.measure("req", "reqStart", "reqStop");
  11847. } else {
  11848. this.perf.mark("reqStart");
  11849. for (let i = 0; i < this.msgs; i++) {
  11850. await this.nc.request(this.subject);
  11851. }
  11852. this.perf.mark("reqStop");
  11853. this.perf.measure("req", "reqStart", "reqStop");
  11854. }
  11855. })();
  11856. jobs.push(job);
  11857. }
  11858. await Promise.all(jobs);
  11859. }
  11860. };
  11861. function throughput(bytes, seconds) {
  11862. return `${humanizeBytes(bytes / seconds)}/sec`;
  11863. }
  11864. function humanizeBytes(bytes, si = false) {
  11865. const base2 = si ? 1e3 : 1024;
  11866. const pre = si ? [
  11867. "k",
  11868. "M",
  11869. "G",
  11870. "T",
  11871. "P",
  11872. "E"
  11873. ] : [
  11874. "K",
  11875. "M",
  11876. "G",
  11877. "T",
  11878. "P",
  11879. "E"
  11880. ];
  11881. const post = si ? "iB" : "B";
  11882. if (bytes < base2) {
  11883. return `${bytes.toFixed(2)} ${post}`;
  11884. }
  11885. const exp = parseInt(Math.log(bytes) / Math.log(base2) + "");
  11886. const index = parseInt(exp - 1 + "");
  11887. return `${(bytes / Math.pow(base2, exp)).toFixed(2)} ${pre[index]}${post}`;
  11888. }
  11889. function humanizeNumber(n) {
  11890. return n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  11891. }
  11892. var VERSION = "1.19.1";
  11893. var LANG = "nats.ws";
  11894. var WsTransport = class {
  11895. constructor() {
  11896. __publicField(this, "version");
  11897. __publicField(this, "lang");
  11898. __publicField(this, "closeError");
  11899. __publicField(this, "connected");
  11900. __publicField(this, "done");
  11901. __publicField(this, "socket");
  11902. __publicField(this, "options");
  11903. __publicField(this, "socketClosed");
  11904. __publicField(this, "encrypted");
  11905. __publicField(this, "peeked");
  11906. __publicField(this, "yields");
  11907. __publicField(this, "signal");
  11908. __publicField(this, "closedNotification");
  11909. this.version = VERSION;
  11910. this.lang = LANG;
  11911. this.connected = false;
  11912. this.done = false;
  11913. this.socketClosed = false;
  11914. this.encrypted = false;
  11915. this.peeked = false;
  11916. this.yields = [];
  11917. this.signal = deferred();
  11918. this.closedNotification = deferred();
  11919. }
  11920. async connect(server, options) {
  11921. const connected = false;
  11922. const connLock = deferred();
  11923. if (options.tls) {
  11924. connLock.reject(new NatsError("tls", ErrorCode.InvalidOption));
  11925. return connLock;
  11926. }
  11927. this.options = options;
  11928. const u = server.src;
  11929. if (options.wsFactory) {
  11930. const { socket, encrypted } = await options.wsFactory(server.src, options);
  11931. this.socket = socket;
  11932. this.encrypted = encrypted;
  11933. } else {
  11934. this.encrypted = u.indexOf("wss://") === 0;
  11935. this.socket = new WebSocket(u);
  11936. }
  11937. this.socket.binaryType = "arraybuffer";
  11938. this.socket.onopen = () => {
  11939. if (this.isDiscarded()) {
  11940. return;
  11941. }
  11942. };
  11943. this.socket.onmessage = (me) => {
  11944. if (this.isDiscarded()) {
  11945. return;
  11946. }
  11947. this.yields.push(new Uint8Array(me.data));
  11948. if (this.peeked) {
  11949. this.signal.resolve();
  11950. return;
  11951. }
  11952. const t = DataBuffer.concat(...this.yields);
  11953. const pm = extractProtocolMessage(t);
  11954. if (pm !== "") {
  11955. const m = INFO.exec(pm);
  11956. if (!m) {
  11957. if (options.debug) {
  11958. console.error("!!!", render(t));
  11959. }
  11960. connLock.reject(new Error("unexpected response from server"));
  11961. return;
  11962. }
  11963. try {
  11964. const info = JSON.parse(m[1]);
  11965. checkOptions(info, this.options);
  11966. this.peeked = true;
  11967. this.connected = true;
  11968. this.signal.resolve();
  11969. connLock.resolve();
  11970. } catch (err) {
  11971. connLock.reject(err);
  11972. return;
  11973. }
  11974. }
  11975. };
  11976. this.socket.onclose = (evt) => {
  11977. if (this.isDiscarded()) {
  11978. return;
  11979. }
  11980. this.socketClosed = true;
  11981. let reason;
  11982. if (this.done)
  11983. return;
  11984. if (!evt.wasClean) {
  11985. reason = new Error(evt.reason);
  11986. }
  11987. this._closed(reason);
  11988. };
  11989. this.socket.onerror = (e) => {
  11990. if (this.isDiscarded()) {
  11991. return;
  11992. }
  11993. const evt = e;
  11994. const err = new NatsError(evt.message, ErrorCode.Unknown, new Error(evt.error));
  11995. if (!connected) {
  11996. connLock.reject(err);
  11997. } else {
  11998. this._closed(err);
  11999. }
  12000. };
  12001. return connLock;
  12002. }
  12003. disconnect() {
  12004. this._closed(void 0, true);
  12005. }
  12006. async _closed(err, internal = true) {
  12007. if (this.isDiscarded()) {
  12008. return;
  12009. }
  12010. if (!this.connected)
  12011. return;
  12012. if (this.done)
  12013. return;
  12014. this.closeError = err;
  12015. if (!err) {
  12016. while (!this.socketClosed && this.socket.bufferedAmount > 0) {
  12017. await delay(100);
  12018. }
  12019. }
  12020. this.done = true;
  12021. try {
  12022. this.socket.close(err ? 1002 : 1e3, err ? err.message : void 0);
  12023. } catch (err2) {
  12024. }
  12025. if (internal) {
  12026. this.closedNotification.resolve(err);
  12027. }
  12028. }
  12029. get isClosed() {
  12030. return this.done;
  12031. }
  12032. [Symbol.asyncIterator]() {
  12033. return this.iterate();
  12034. }
  12035. async *iterate() {
  12036. while (true) {
  12037. if (this.isDiscarded()) {
  12038. return;
  12039. }
  12040. if (this.yields.length === 0) {
  12041. await this.signal;
  12042. }
  12043. const yields = this.yields;
  12044. this.yields = [];
  12045. for (let i = 0; i < yields.length; i++) {
  12046. if (this.options.debug) {
  12047. console.info(`> ${render(yields[i])}`);
  12048. }
  12049. yield yields[i];
  12050. }
  12051. if (this.done) {
  12052. break;
  12053. } else if (this.yields.length === 0) {
  12054. yields.length = 0;
  12055. this.yields = yields;
  12056. this.signal = deferred();
  12057. }
  12058. }
  12059. }
  12060. isEncrypted() {
  12061. return this.connected && this.encrypted;
  12062. }
  12063. send(frame) {
  12064. if (this.isDiscarded()) {
  12065. return;
  12066. }
  12067. try {
  12068. this.socket.send(frame.buffer);
  12069. if (this.options.debug) {
  12070. console.info(`< ${render(frame)}`);
  12071. }
  12072. return;
  12073. } catch (err) {
  12074. if (this.options.debug) {
  12075. console.error(`!!! ${render(frame)}: ${err}`);
  12076. }
  12077. }
  12078. }
  12079. close(err) {
  12080. return this._closed(err, false);
  12081. }
  12082. closed() {
  12083. return this.closedNotification;
  12084. }
  12085. isDiscarded() {
  12086. if (this.done) {
  12087. this.discard();
  12088. return true;
  12089. }
  12090. return false;
  12091. }
  12092. discard() {
  12093. var _a;
  12094. this.done = true;
  12095. try {
  12096. (_a = this.socket) == null ? void 0 : _a.close();
  12097. } catch (_err) {
  12098. }
  12099. }
  12100. };
  12101. function wsUrlParseFn(u) {
  12102. const ut = /^(.*:\/\/)(.*)/;
  12103. if (!ut.test(u)) {
  12104. u = `https://${u}`;
  12105. }
  12106. let url = new URL(u);
  12107. const srcProto = url.protocol.toLowerCase();
  12108. if (srcProto !== "https:" && srcProto !== "http") {
  12109. u = u.replace(/^(.*:\/\/)(.*)/gm, "$2");
  12110. url = new URL(`http://${u}`);
  12111. }
  12112. let protocol;
  12113. let port;
  12114. const host = url.hostname;
  12115. const path = url.pathname;
  12116. const search = url.search || "";
  12117. switch (srcProto) {
  12118. case "http:":
  12119. case "ws:":
  12120. case "nats:":
  12121. port = url.port || "80";
  12122. protocol = "ws:";
  12123. break;
  12124. default:
  12125. port = url.port || "443";
  12126. protocol = "wss:";
  12127. break;
  12128. }
  12129. return `${protocol}//${host}:${port}${path}${search}`;
  12130. }
  12131. function connect(opts = {}) {
  12132. setTransportFactory({
  12133. defaultPort: 443,
  12134. urlParseFn: wsUrlParseFn,
  12135. factory: () => {
  12136. return new WsTransport();
  12137. }
  12138. });
  12139. return NatsConnectionImpl.connect(opts);
  12140. }
  12141. export {
  12142. AckPolicy,
  12143. AdvisoryKind,
  12144. Bench,
  12145. ConsumerDebugEvents,
  12146. ConsumerEvents,
  12147. DebugEvents,
  12148. DeliverPolicy,
  12149. DirectMsgHeaders,
  12150. DiscardPolicy,
  12151. Empty,
  12152. ErrorCode,
  12153. Events,
  12154. JSONCodec,
  12155. JsHeaders,
  12156. Match,
  12157. Metric,
  12158. MsgHdrsImpl,
  12159. NatsError,
  12160. Nuid,
  12161. ReplayPolicy,
  12162. RepublishHeaders,
  12163. RequestStrategy,
  12164. RetentionPolicy,
  12165. ServiceError,
  12166. ServiceErrorCodeHeader,
  12167. ServiceErrorHeader,
  12168. ServiceResponseType,
  12169. ServiceVerb,
  12170. StorageType,
  12171. StoreCompression,
  12172. StringCodec,
  12173. backoff,
  12174. buildAuthenticator,
  12175. canonicalMIMEHeaderKey,
  12176. checkJsError,
  12177. connect,
  12178. consumerOpts,
  12179. createInbox,
  12180. credsAuthenticator,
  12181. deadline,
  12182. deferred,
  12183. delay,
  12184. headers,
  12185. isFlowControlMsg,
  12186. isHeartbeatMsg,
  12187. jwtAuthenticator,
  12188. millis,
  12189. nanos,
  12190. nkeyAuthenticator,
  12191. mod as nkeys,
  12192. nuid,
  12193. syncIterator,
  12194. tokenAuthenticator,
  12195. usernamePasswordAuthenticator
  12196. };
  12197. //# sourceMappingURL=nats__ws.js.map