index.cjs 237 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843
  1. "use strict";
  2. var __create = Object.create;
  3. var __defProp = Object.defineProperty;
  4. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  5. var __getOwnPropNames = Object.getOwnPropertyNames;
  6. var __getProtoOf = Object.getPrototypeOf;
  7. var __hasOwnProp = Object.prototype.hasOwnProperty;
  8. var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  9. var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
  10. var __glob = (map) => (path) => {
  11. var fn = map[path];
  12. if (fn) return fn();
  13. throw new Error("Module not found in bundle: " + path);
  14. };
  15. var __esm = (fn, res) => function __init() {
  16. return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
  17. };
  18. var __export = (target, all) => {
  19. for (var name in all)
  20. __defProp(target, name, { get: all[name], enumerable: true });
  21. };
  22. var __copyProps = (to, from, except, desc) => {
  23. if (from && typeof from === "object" || typeof from === "function") {
  24. for (let key of __getOwnPropNames(from))
  25. if (!__hasOwnProp.call(to, key) && key !== except)
  26. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  27. }
  28. return to;
  29. };
  30. var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  31. // If the importer is in node compatibility mode or this is not an ESM
  32. // file that has been converted to a CommonJS file using a Babel-
  33. // compatible transform (i.e. "__esModule" has not been set), then set
  34. // "default" to the CommonJS "module.exports" for node compatibility.
  35. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  36. mod
  37. ));
  38. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  39. var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  40. // node_modules/@e22m4u/js-format/src/utils/is-class.js
  41. function isClass(value) {
  42. if (!value) return false;
  43. return typeof value === "function" && /^class\s/.test(Function.prototype.toString.call(value));
  44. }
  45. var init_is_class = __esm({
  46. "node_modules/@e22m4u/js-format/src/utils/is-class.js"() {
  47. __name(isClass, "isClass");
  48. }
  49. });
  50. // node_modules/@e22m4u/js-format/src/utils/index.js
  51. var init_utils = __esm({
  52. "node_modules/@e22m4u/js-format/src/utils/index.js"() {
  53. init_is_class();
  54. }
  55. });
  56. // node_modules/@e22m4u/js-format/src/value-to-string.js
  57. function valueToString(input) {
  58. if (input == null) return String(input);
  59. if (typeof input === "string") return `"${input}"`;
  60. if (typeof input === "number" || typeof input === "boolean")
  61. return String(input);
  62. if (isClass(input)) return input.name ? input.name : "Class";
  63. if (input.constructor && input.constructor.name)
  64. return BASE_CTOR_NAMES.includes(input.constructor.name) ? input.constructor.name : `${input.constructor.name} (instance)`;
  65. if (typeof input === "object" && input.constructor == null) return "Object";
  66. return String(input);
  67. }
  68. var BASE_CTOR_NAMES;
  69. var init_value_to_string = __esm({
  70. "node_modules/@e22m4u/js-format/src/value-to-string.js"() {
  71. init_utils();
  72. BASE_CTOR_NAMES = [
  73. "String",
  74. "Number",
  75. "Boolean",
  76. "Object",
  77. "Array",
  78. "Function",
  79. "Symbol",
  80. "Map",
  81. "Set",
  82. "Date"
  83. ];
  84. __name(valueToString, "valueToString");
  85. }
  86. });
  87. // node_modules/@e22m4u/js-format/src/array-to-list.js
  88. function arrayToList(input) {
  89. if (Array.isArray(input) && input.length)
  90. return input.map(valueToString).join(SEPARATOR);
  91. return valueToString(input);
  92. }
  93. var SEPARATOR;
  94. var init_array_to_list = __esm({
  95. "node_modules/@e22m4u/js-format/src/array-to-list.js"() {
  96. init_value_to_string();
  97. SEPARATOR = ", ";
  98. __name(arrayToList, "arrayToList");
  99. }
  100. });
  101. // node_modules/@e22m4u/js-format/src/format.js
  102. function format(pattern) {
  103. if (pattern instanceof Date) {
  104. pattern = pattern.toISOString();
  105. } else if (typeof pattern !== "string") {
  106. pattern = String(pattern);
  107. }
  108. const re = /(%?)(%([sdjvl]))/g;
  109. const args = Array.prototype.slice.call(arguments, 1);
  110. if (args.length) {
  111. pattern = pattern.replace(re, function(match, escaped, ptn, flag) {
  112. let arg = args.shift();
  113. switch (flag) {
  114. case "s":
  115. arg = String(arg);
  116. break;
  117. case "d":
  118. arg = Number(arg);
  119. break;
  120. case "j":
  121. arg = JSON.stringify(arg);
  122. break;
  123. case "v":
  124. arg = valueToString(arg);
  125. break;
  126. case "l":
  127. arg = arrayToList(arg);
  128. break;
  129. }
  130. if (!escaped) return arg;
  131. args.unshift(arg);
  132. return match;
  133. });
  134. }
  135. if (args.length) pattern += " " + args.join(" ");
  136. pattern = pattern.replace(/%{2}/g, "%");
  137. return "" + pattern;
  138. }
  139. var init_format = __esm({
  140. "node_modules/@e22m4u/js-format/src/format.js"() {
  141. init_array_to_list();
  142. init_value_to_string();
  143. __name(format, "format");
  144. }
  145. });
  146. // node_modules/@e22m4u/js-format/src/errorf.js
  147. var _Errorf, Errorf;
  148. var init_errorf = __esm({
  149. "node_modules/@e22m4u/js-format/src/errorf.js"() {
  150. init_format();
  151. _Errorf = class _Errorf extends Error {
  152. /**
  153. * Constructor.
  154. *
  155. * @param {string|undefined} pattern
  156. * @param {any} args
  157. */
  158. constructor(pattern = void 0, ...args) {
  159. const message = pattern != null ? format(pattern, ...args) : void 0;
  160. super(message);
  161. }
  162. };
  163. __name(_Errorf, "Errorf");
  164. Errorf = _Errorf;
  165. }
  166. });
  167. // node_modules/@e22m4u/js-format/src/index.js
  168. var init_src = __esm({
  169. "node_modules/@e22m4u/js-format/src/index.js"() {
  170. init_format();
  171. init_errorf();
  172. }
  173. });
  174. // node_modules/@e22m4u/js-service/src/errors/invalid-argument-error.js
  175. var _InvalidArgumentError, InvalidArgumentError;
  176. var init_invalid_argument_error = __esm({
  177. "node_modules/@e22m4u/js-service/src/errors/invalid-argument-error.js"() {
  178. init_src();
  179. _InvalidArgumentError = class _InvalidArgumentError extends Errorf {
  180. };
  181. __name(_InvalidArgumentError, "InvalidArgumentError");
  182. InvalidArgumentError = _InvalidArgumentError;
  183. }
  184. });
  185. // node_modules/@e22m4u/js-service/src/errors/index.js
  186. var init_errors = __esm({
  187. "node_modules/@e22m4u/js-service/src/errors/index.js"() {
  188. init_invalid_argument_error();
  189. }
  190. });
  191. // node_modules/@e22m4u/js-service/src/service-container.js
  192. var _ServiceContainer, ServiceContainer;
  193. var init_service_container = __esm({
  194. "node_modules/@e22m4u/js-service/src/service-container.js"() {
  195. init_service();
  196. init_errors();
  197. _ServiceContainer = class _ServiceContainer {
  198. /**
  199. * Services map.
  200. *
  201. * @type {Map<any, any>}
  202. * @private
  203. */
  204. _services = /* @__PURE__ */ new Map();
  205. /**
  206. * Parent container.
  207. *
  208. * @type {ServiceContainer}
  209. * @private
  210. */
  211. _parent;
  212. /**
  213. * Constructor.
  214. *
  215. * @param {ServiceContainer|undefined} parent
  216. */
  217. constructor(parent = void 0) {
  218. if (parent != null) {
  219. if (!(parent instanceof _ServiceContainer))
  220. throw new InvalidArgumentError(
  221. 'The provided parameter "parent" of ServicesContainer.constructor must be an instance ServiceContainer, but %v given.',
  222. parent
  223. );
  224. this._parent = parent;
  225. }
  226. }
  227. /**
  228. * Получить существующий или новый экземпляр.
  229. *
  230. * @param {*} ctor
  231. * @param {*} args
  232. * @return {*}
  233. */
  234. get(ctor, ...args) {
  235. if (!ctor || typeof ctor !== "function")
  236. throw new InvalidArgumentError(
  237. "The first argument of ServicesContainer.get must be a class constructor, but %v given.",
  238. ctor
  239. );
  240. if (!this._services.has(ctor) && this._parent && this._parent.has(ctor)) {
  241. return this._parent.get(ctor);
  242. }
  243. let service = this._services.get(ctor);
  244. if (!service || args.length) {
  245. service = "prototype" in ctor && ctor.prototype instanceof Service ? new ctor(this, ...args) : new ctor(...args);
  246. this._services.set(ctor, service);
  247. } else if (typeof service === "function") {
  248. service = service();
  249. this._services.set(ctor, service);
  250. }
  251. return service;
  252. }
  253. /**
  254. * Проверка существования конструктора в контейнере.
  255. *
  256. * @param {*} ctor
  257. * @return {boolean}
  258. */
  259. has(ctor) {
  260. if (this._services.has(ctor)) return true;
  261. if (this._parent) return this._parent.has(ctor);
  262. return false;
  263. }
  264. /**
  265. * Добавить конструктор в контейнер.
  266. *
  267. * @param {*} ctor
  268. * @param {*} args
  269. * @return {this}
  270. */
  271. add(ctor, ...args) {
  272. if (!ctor || typeof ctor !== "function")
  273. throw new InvalidArgumentError(
  274. "The first argument of ServicesContainer.add must be a class constructor, but %v given.",
  275. ctor
  276. );
  277. const factory = /* @__PURE__ */ __name(() => ctor.prototype instanceof Service ? new ctor(this, ...args) : new ctor(...args), "factory");
  278. this._services.set(ctor, factory);
  279. return this;
  280. }
  281. /**
  282. * Добавить конструктор и создать экземпляр.
  283. *
  284. * @param {*} ctor
  285. * @param {*} args
  286. * @return {this}
  287. */
  288. use(ctor, ...args) {
  289. if (!ctor || typeof ctor !== "function")
  290. throw new InvalidArgumentError(
  291. "The first argument of ServicesContainer.use must be a class constructor, but %v given.",
  292. ctor
  293. );
  294. const service = ctor.prototype instanceof Service ? new ctor(this, ...args) : new ctor(...args);
  295. this._services.set(ctor, service);
  296. return this;
  297. }
  298. /**
  299. * Добавить конструктор и связанный экземпляр.
  300. *
  301. * @param {*} ctor
  302. * @param {*} service
  303. * @return {this}
  304. */
  305. set(ctor, service) {
  306. if (!ctor || typeof ctor !== "function")
  307. throw new InvalidArgumentError(
  308. "The first argument of ServicesContainer.set must be a class constructor, but %v given.",
  309. ctor
  310. );
  311. if (!service || typeof service !== "object" || Array.isArray(service))
  312. throw new InvalidArgumentError(
  313. "The second argument of ServicesContainer.set must be an Object, but %v given.",
  314. service
  315. );
  316. this._services.set(ctor, service);
  317. return this;
  318. }
  319. };
  320. __name(_ServiceContainer, "ServiceContainer");
  321. ServiceContainer = _ServiceContainer;
  322. }
  323. });
  324. // node_modules/@e22m4u/js-service/src/service.js
  325. var _Service, Service;
  326. var init_service = __esm({
  327. "node_modules/@e22m4u/js-service/src/service.js"() {
  328. init_service_container();
  329. _Service = class _Service {
  330. /**
  331. * Container.
  332. *
  333. * @type {ServiceContainer}
  334. */
  335. container;
  336. /**
  337. * Constructor.
  338. *
  339. * @param {ServiceContainer|undefined} container
  340. */
  341. constructor(container = void 0) {
  342. this.container = container instanceof ServiceContainer ? container : new ServiceContainer();
  343. }
  344. /**
  345. * Получить существующий или новый экземпляр.
  346. *
  347. * @param {*} ctor
  348. * @param {*} args
  349. * @return {*}
  350. */
  351. getService(ctor, ...args) {
  352. return this.container.get(ctor, ...args);
  353. }
  354. /**
  355. * Проверка существования конструктора в контейнере.
  356. *
  357. * @param {*} ctor
  358. * @return {boolean}
  359. */
  360. hasService(ctor) {
  361. return this.container.has(ctor);
  362. }
  363. /**
  364. * Добавить конструктор в контейнер.
  365. *
  366. * @param {*} ctor
  367. * @param {*} args
  368. * @return {this}
  369. */
  370. addService(ctor, ...args) {
  371. this.container.add(ctor, ...args);
  372. return this;
  373. }
  374. /**
  375. * Добавить конструктор и создать экземпляр.
  376. *
  377. * @param {*} ctor
  378. * @param {*} args
  379. * @return {this}
  380. */
  381. useService(ctor, ...args) {
  382. this.container.use(ctor, ...args);
  383. return this;
  384. }
  385. /**
  386. * Добавить конструктор и связанный экземпляр.
  387. *
  388. * @param {*} ctor
  389. * @param {*} service
  390. * @return {this}
  391. */
  392. setService(ctor, service) {
  393. this.container.set(ctor, service);
  394. return this;
  395. }
  396. };
  397. __name(_Service, "Service");
  398. Service = _Service;
  399. }
  400. });
  401. // node_modules/@e22m4u/js-service/src/index.js
  402. var init_src2 = __esm({
  403. "node_modules/@e22m4u/js-service/src/index.js"() {
  404. init_service();
  405. init_service_container();
  406. }
  407. });
  408. // src/errors/not-implemented-error.js
  409. var _NotImplementedError, NotImplementedError;
  410. var init_not_implemented_error = __esm({
  411. "src/errors/not-implemented-error.js"() {
  412. "use strict";
  413. init_src();
  414. _NotImplementedError = class _NotImplementedError extends Errorf {
  415. };
  416. __name(_NotImplementedError, "NotImplementedError");
  417. NotImplementedError = _NotImplementedError;
  418. }
  419. });
  420. // src/errors/invalid-argument-error.js
  421. var _InvalidArgumentError2, InvalidArgumentError2;
  422. var init_invalid_argument_error2 = __esm({
  423. "src/errors/invalid-argument-error.js"() {
  424. "use strict";
  425. init_src();
  426. _InvalidArgumentError2 = class _InvalidArgumentError2 extends Errorf {
  427. };
  428. __name(_InvalidArgumentError2, "InvalidArgumentError");
  429. InvalidArgumentError2 = _InvalidArgumentError2;
  430. }
  431. });
  432. // src/errors/invalid-operator-value-error.js
  433. var _InvalidOperatorValueError, InvalidOperatorValueError;
  434. var init_invalid_operator_value_error = __esm({
  435. "src/errors/invalid-operator-value-error.js"() {
  436. "use strict";
  437. init_src();
  438. _InvalidOperatorValueError = class _InvalidOperatorValueError extends Error {
  439. /**
  440. * Constructor.
  441. *
  442. * @param {string} operator
  443. * @param {string} expected
  444. * @param {*} value
  445. */
  446. constructor(operator, expected, value) {
  447. super(
  448. format(
  449. "Condition of {%s: ...} should have %s, but %v given.",
  450. operator,
  451. expected,
  452. value
  453. )
  454. );
  455. }
  456. };
  457. __name(_InvalidOperatorValueError, "InvalidOperatorValueError");
  458. InvalidOperatorValueError = _InvalidOperatorValueError;
  459. }
  460. });
  461. // src/errors/index.js
  462. var init_errors2 = __esm({
  463. "src/errors/index.js"() {
  464. "use strict";
  465. init_not_implemented_error();
  466. init_invalid_argument_error2();
  467. init_invalid_operator_value_error();
  468. }
  469. });
  470. // src/filter/slice-clause-tool.js
  471. var _SliceClauseTool, SliceClauseTool;
  472. var init_slice_clause_tool = __esm({
  473. "src/filter/slice-clause-tool.js"() {
  474. "use strict";
  475. init_src2();
  476. init_errors2();
  477. _SliceClauseTool = class _SliceClauseTool extends Service {
  478. /**
  479. * Slice.
  480. *
  481. * @param {object[]} entities
  482. * @param {number|undefined} skip
  483. * @param {number|undefined} limit
  484. * @returns {object[]}
  485. */
  486. slice(entities, skip = void 0, limit = void 0) {
  487. if (!Array.isArray(entities))
  488. throw new InvalidArgumentError2(
  489. "The first argument of SliceClauseTool.slice should be an Array, but %v given.",
  490. entities
  491. );
  492. if (skip != null && typeof skip !== "number")
  493. throw new InvalidArgumentError2(
  494. 'The provided option "skip" should be a Number, but %v given.',
  495. skip
  496. );
  497. if (limit != null && typeof limit !== "number")
  498. throw new InvalidArgumentError2(
  499. 'The provided option "limit" should be a Number, but %v given.',
  500. limit
  501. );
  502. skip = skip || 0;
  503. limit = limit || entities.length;
  504. return entities.slice(skip, skip + limit);
  505. }
  506. /**
  507. * Validate skip clause.
  508. *
  509. * @param {number|undefined} skip
  510. */
  511. static validateSkipClause(skip) {
  512. if (skip == null) return;
  513. if (typeof skip !== "number")
  514. throw new InvalidArgumentError2(
  515. 'The provided option "skip" should be a Number, but %v given.',
  516. skip
  517. );
  518. }
  519. /**
  520. * Validate limit clause.
  521. *
  522. * @param {number|undefined} limit
  523. */
  524. static validateLimitClause(limit) {
  525. if (limit == null) return;
  526. if (typeof limit !== "number")
  527. throw new InvalidArgumentError2(
  528. 'The provided option "limit" should be a Number, but %v given.',
  529. limit
  530. );
  531. }
  532. };
  533. __name(_SliceClauseTool, "SliceClauseTool");
  534. SliceClauseTool = _SliceClauseTool;
  535. }
  536. });
  537. // src/utils/is-ctor.js
  538. function isCtor(value) {
  539. if (!value) return false;
  540. return typeof value === "function" && "prototype" in value;
  541. }
  542. var init_is_ctor = __esm({
  543. "src/utils/is-ctor.js"() {
  544. "use strict";
  545. __name(isCtor, "isCtor");
  546. }
  547. });
  548. // src/utils/is-promise.js
  549. function isPromise(value) {
  550. if (!value) return false;
  551. if (typeof value !== "object") return false;
  552. return typeof value.then === "function";
  553. }
  554. var init_is_promise = __esm({
  555. "src/utils/is-promise.js"() {
  556. "use strict";
  557. __name(isPromise, "isPromise");
  558. }
  559. });
  560. // src/utils/capitalize.js
  561. function capitalize(string) {
  562. if (!string || typeof string !== "string") return string;
  563. return string.charAt(0).toUpperCase() + string.slice(1);
  564. }
  565. var init_capitalize = __esm({
  566. "src/utils/capitalize.js"() {
  567. "use strict";
  568. __name(capitalize, "capitalize");
  569. }
  570. });
  571. // src/utils/clone-deep.js
  572. function cloneDeep(value) {
  573. if (!value) return value;
  574. const types = [Number, String, Boolean];
  575. let result;
  576. types.forEach((type) => {
  577. if (value instanceof type) result = type(value);
  578. });
  579. if (result === void 0) {
  580. if (Array.isArray(value)) {
  581. result = [];
  582. value.forEach((child, index) => {
  583. result[index] = cloneDeep(child);
  584. });
  585. } else if (typeof value === "object") {
  586. if ("nodeType" in value && value.nodeType && "cloneNode" in value && typeof value.cloneNode === "function") {
  587. result = value.cloneNode(true);
  588. } else if (!("prototype" in value) || !value.prototype) {
  589. if (value instanceof Date) {
  590. result = new Date(value);
  591. } else if (value.constructor && value.constructor.name === "Object") {
  592. result = {};
  593. for (const key in value) {
  594. result[key] = cloneDeep(value[key]);
  595. }
  596. } else {
  597. result = value;
  598. }
  599. } else {
  600. result = value;
  601. }
  602. } else {
  603. result = value;
  604. }
  605. }
  606. return result;
  607. }
  608. var init_clone_deep = __esm({
  609. "src/utils/clone-deep.js"() {
  610. "use strict";
  611. __name(cloneDeep, "cloneDeep");
  612. }
  613. });
  614. // src/utils/singularize.js
  615. function singularize(noun) {
  616. if (!noun || typeof noun !== "string") return noun;
  617. const endings = {
  618. ves: "fe",
  619. ies: "y",
  620. i: "us",
  621. zes: "ze",
  622. ses: "s",
  623. es: "e",
  624. s: ""
  625. };
  626. return noun.replace(
  627. new RegExp(`(${Object.keys(endings).join("|")})$`),
  628. (r) => endings[r]
  629. );
  630. }
  631. var init_singularize = __esm({
  632. "src/utils/singularize.js"() {
  633. "use strict";
  634. __name(singularize, "singularize");
  635. }
  636. });
  637. // src/utils/is-deep-equal.js
  638. function isDeepEqual(firstValue, secondValue) {
  639. const cached = /* @__PURE__ */ new WeakMap();
  640. const compare = /* @__PURE__ */ __name((a, b) => {
  641. if (a === null || b === null) return a === b;
  642. if (typeof a !== "object" || typeof b !== "object") return a === b;
  643. const dataTypeA = Array.isArray(a) ? "array" : "object";
  644. const dataTypeB = Array.isArray(b) ? "array" : "object";
  645. if (dataTypeA !== dataTypeB) return false;
  646. const keysA = Object.keys(a);
  647. const keysB = Object.keys(b);
  648. if (keysA.length !== keysB.length) return false;
  649. const symbolsA = Object.getOwnPropertySymbols(a);
  650. const symbolsB = Object.getOwnPropertySymbols(b);
  651. if (symbolsA.length !== symbolsB.length) return false;
  652. let setForA = cached.get(a);
  653. if (setForA == null) {
  654. setForA = /* @__PURE__ */ new Set();
  655. cached.set(a, setForA);
  656. } else if (setForA.has(b)) {
  657. return true;
  658. }
  659. setForA.add(b);
  660. let setForB = cached.get(b);
  661. if (setForB == null) {
  662. setForB = /* @__PURE__ */ new Set();
  663. cached.set(b, setForB);
  664. } else if (setForB.has(a)) {
  665. return true;
  666. }
  667. setForB.add(a);
  668. const propertyNamesA = [...keysA, ...symbolsA];
  669. for (const propertyNameA of propertyNamesA) {
  670. if (!Object.prototype.hasOwnProperty.call(b, propertyNameA)) return false;
  671. const propertyValueA = a[propertyNameA];
  672. const propertyValueB = b[propertyNameA];
  673. if (!compare(propertyValueA, propertyValueB)) return false;
  674. }
  675. return true;
  676. }, "compare");
  677. return compare(firstValue, secondValue);
  678. }
  679. var init_is_deep_equal = __esm({
  680. "src/utils/is-deep-equal.js"() {
  681. "use strict";
  682. __name(isDeepEqual, "isDeepEqual");
  683. }
  684. });
  685. // src/utils/get-ctor-name.js
  686. function getCtorName(value) {
  687. if (value === null) return "Null";
  688. if (value === void 0) return "Undefined";
  689. return value.constructor && value.constructor.name || void 0;
  690. }
  691. var init_get_ctor_name = __esm({
  692. "src/utils/get-ctor-name.js"() {
  693. "use strict";
  694. __name(getCtorName, "getCtorName");
  695. }
  696. });
  697. // src/utils/is-pure-object.js
  698. function isPureObject(value) {
  699. return Boolean(
  700. typeof value === "object" && value && !Array.isArray(value) && (!value.constructor || value.constructor && value.constructor.name === "Object")
  701. );
  702. }
  703. var init_is_pure_object = __esm({
  704. "src/utils/is-pure-object.js"() {
  705. "use strict";
  706. __name(isPureObject, "isPureObject");
  707. }
  708. });
  709. // src/utils/string-to-regexp.js
  710. function stringToRegexp(pattern, flags = void 0) {
  711. if (pattern instanceof RegExp) {
  712. return new RegExp(pattern, flags);
  713. }
  714. let regex = "";
  715. for (let i = 0, n = pattern.length; i < n; i++) {
  716. const char = pattern.charAt(i);
  717. if (char === "%") {
  718. regex += ".*";
  719. } else {
  720. regex += char;
  721. }
  722. }
  723. return new RegExp(regex, flags);
  724. }
  725. var init_string_to_regexp = __esm({
  726. "src/utils/string-to-regexp.js"() {
  727. "use strict";
  728. __name(stringToRegexp, "stringToRegexp");
  729. }
  730. });
  731. // src/utils/get-value-by-path.js
  732. function getValueByPath(obj, path, orElse = void 0) {
  733. if (!obj || typeof obj !== "object") return orElse;
  734. if (!path || typeof path !== "string") return orElse;
  735. const keys = path.split(".");
  736. let value = obj;
  737. for (const key of keys) {
  738. if (typeof value === "object" && value !== null && key in value) {
  739. value = value[key];
  740. } else {
  741. value = orElse;
  742. break;
  743. }
  744. }
  745. return value;
  746. }
  747. var init_get_value_by_path = __esm({
  748. "src/utils/get-value-by-path.js"() {
  749. "use strict";
  750. __name(getValueByPath, "getValueByPath");
  751. }
  752. });
  753. // src/utils/transform-promise.js
  754. function transformPromise(valueOrPromise, transformer) {
  755. return isPromise(valueOrPromise) ? valueOrPromise.then(transformer) : transformer(valueOrPromise);
  756. }
  757. var init_transform_promise = __esm({
  758. "src/utils/transform-promise.js"() {
  759. "use strict";
  760. init_is_promise();
  761. __name(transformPromise, "transformPromise");
  762. }
  763. });
  764. // src/utils/select-object-keys.js
  765. function selectObjectKeys(obj, keys) {
  766. if (!obj || typeof obj !== "object" || Array.isArray(obj))
  767. throw new InvalidArgumentError2(
  768. "The first argument of selectObjectKeys should be an Object, but %v given.",
  769. obj
  770. );
  771. if (!Array.isArray(keys))
  772. throw new InvalidArgumentError2(
  773. "The second argument of selectObjectKeys should be an Array of String, but %v given.",
  774. keys
  775. );
  776. keys.forEach((key) => {
  777. if (typeof key !== "string")
  778. throw new InvalidArgumentError2(
  779. "The second argument of selectObjectKeys should be an Array of String, but %v given.",
  780. key
  781. );
  782. });
  783. const result = {};
  784. const allKeys = Object.keys(obj);
  785. allKeys.forEach((key) => {
  786. if (keys.includes(key)) result[key] = obj[key];
  787. });
  788. return result;
  789. }
  790. var init_select_object_keys = __esm({
  791. "src/utils/select-object-keys.js"() {
  792. "use strict";
  793. init_errors2();
  794. __name(selectObjectKeys, "selectObjectKeys");
  795. }
  796. });
  797. // src/utils/exclude-object-keys.js
  798. function excludeObjectKeys(obj, keys) {
  799. if (typeof obj !== "object" || !obj || Array.isArray(obj))
  800. throw new InvalidArgumentError2(
  801. "Cannot exclude keys from a non-Object value, %v given.",
  802. obj
  803. );
  804. const result = { ...obj };
  805. keys = Array.isArray(keys) ? keys : [keys];
  806. keys.forEach((key) => delete result[key]);
  807. return result;
  808. }
  809. var init_exclude_object_keys = __esm({
  810. "src/utils/exclude-object-keys.js"() {
  811. "use strict";
  812. init_errors2();
  813. __name(excludeObjectKeys, "excludeObjectKeys");
  814. }
  815. });
  816. // src/utils/get-decorator-target-type.js
  817. function getDecoratorTargetType(target, propertyKey, descriptorOrIndex) {
  818. const isCtor2 = typeof target === "function";
  819. const isParameter = typeof descriptorOrIndex === "number";
  820. const isProperty = propertyKey != null && descriptorOrIndex == null;
  821. const isMethod = propertyKey != null && descriptorOrIndex != null;
  822. const D = DecoratorTargetType;
  823. if (isCtor2) {
  824. if (isParameter)
  825. return propertyKey ? D.STATIC_METHOD_PARAMETER : D.CONSTRUCTOR_PARAMETER;
  826. if (isProperty) return D.STATIC_PROPERTY;
  827. if (isMethod) return D.STATIC_METHOD;
  828. return D.CONSTRUCTOR;
  829. } else {
  830. if (isParameter) return D.INSTANCE_METHOD_PARAMETER;
  831. if (isProperty) return D.INSTANCE_PROPERTY;
  832. if (isMethod) return D.INSTANCE_METHOD;
  833. return D.INSTANCE;
  834. }
  835. }
  836. var DecoratorTargetType;
  837. var init_get_decorator_target_type = __esm({
  838. "src/utils/get-decorator-target-type.js"() {
  839. "use strict";
  840. DecoratorTargetType = {
  841. CONSTRUCTOR: "constructor",
  842. INSTANCE: "instance",
  843. STATIC_METHOD: "staticMethod",
  844. INSTANCE_METHOD: "instanceMethod",
  845. STATIC_PROPERTY: "staticProperty",
  846. INSTANCE_PROPERTY: "instanceProperty",
  847. CONSTRUCTOR_PARAMETER: "constructorParameter",
  848. STATIC_METHOD_PARAMETER: "staticMethodParameter",
  849. INSTANCE_METHOD_PARAMETER: "instanceMethodParameter"
  850. };
  851. __name(getDecoratorTargetType, "getDecoratorTargetType");
  852. }
  853. });
  854. // src/utils/index.js
  855. var init_utils2 = __esm({
  856. "src/utils/index.js"() {
  857. "use strict";
  858. init_is_ctor();
  859. init_is_promise();
  860. init_capitalize();
  861. init_clone_deep();
  862. init_singularize();
  863. init_is_deep_equal();
  864. init_get_ctor_name();
  865. init_is_pure_object();
  866. init_string_to_regexp();
  867. init_get_value_by_path();
  868. init_transform_promise();
  869. init_select_object_keys();
  870. init_exclude_object_keys();
  871. init_get_decorator_target_type();
  872. }
  873. });
  874. // src/filter/order-clause-tool.js
  875. function compareFn(a, b) {
  876. let undefinedA, undefinedB;
  877. for (let i = 0, l = this.length; i < l; i++) {
  878. const aVal = getValueByPath(a, this[i].key);
  879. const bVal = getValueByPath(b, this[i].key);
  880. undefinedB = bVal === void 0 && aVal !== void 0;
  881. undefinedA = aVal === void 0 && bVal !== void 0;
  882. if (undefinedB || aVal > bVal) {
  883. return this[i].reverse;
  884. } else if (undefinedA || aVal < bVal) {
  885. return -1 * this[i].reverse;
  886. }
  887. }
  888. return 0;
  889. }
  890. var _OrderClauseTool, OrderClauseTool;
  891. var init_order_clause_tool = __esm({
  892. "src/filter/order-clause-tool.js"() {
  893. "use strict";
  894. init_src2();
  895. init_utils2();
  896. init_errors2();
  897. _OrderClauseTool = class _OrderClauseTool extends Service {
  898. /**
  899. * Sort.
  900. *
  901. * @param {object[]} entities
  902. * @param {string|string[]|undefined} clause
  903. */
  904. sort(entities, clause) {
  905. if (clause == null) return;
  906. if (Array.isArray(clause) === false) clause = [clause];
  907. if (!clause.length) return;
  908. const mapping = [];
  909. clause.forEach((key, index) => {
  910. if (!key || typeof key !== "string")
  911. throw new InvalidArgumentError2(
  912. 'The provided option "order" should be a non-empty String or an Array of non-empty String, but %v given.',
  913. key
  914. );
  915. let reverse = 1;
  916. const matches = key.match(/\s+(A|DE)SC$/i);
  917. if (matches) {
  918. key = key.replace(/\s+(A|DE)SC/i, "");
  919. if (matches[1].toLowerCase() === "de") reverse = -1;
  920. }
  921. mapping[index] = { key, reverse };
  922. });
  923. entities.sort(compareFn.bind(mapping));
  924. }
  925. /**
  926. * Validate order clause.
  927. *
  928. * @param {string|string[]|undefined} clause
  929. */
  930. static validateOrderClause(clause) {
  931. if (clause == null) return;
  932. if (Array.isArray(clause) === false) clause = [clause];
  933. if (!clause.length) return;
  934. clause.forEach((field) => {
  935. if (!field || typeof field !== "string")
  936. throw new InvalidArgumentError2(
  937. 'The provided option "order" should be a non-empty String or an Array of non-empty String, but %v given.',
  938. field
  939. );
  940. });
  941. }
  942. /**
  943. * Normalize order clause.
  944. *
  945. * @param {string|string[]|undefined} clause
  946. * @returns {string[]|undefined}
  947. */
  948. static normalizeOrderClause(clause) {
  949. if (clause == null) return;
  950. if (Array.isArray(clause) === false) clause = [clause];
  951. if (!clause.length) return;
  952. clause.forEach((field) => {
  953. if (!field || typeof field !== "string")
  954. throw new InvalidArgumentError2(
  955. 'The provided option "order" should be a non-empty String or an Array of non-empty String, but %v given.',
  956. field
  957. );
  958. });
  959. return clause;
  960. }
  961. };
  962. __name(_OrderClauseTool, "OrderClauseTool");
  963. OrderClauseTool = _OrderClauseTool;
  964. __name(compareFn, "compareFn");
  965. }
  966. });
  967. // src/filter/operator-clause-tool.js
  968. var _OperatorClauseTool, OperatorClauseTool;
  969. var init_operator_clause_tool = __esm({
  970. "src/filter/operator-clause-tool.js"() {
  971. "use strict";
  972. init_src2();
  973. init_utils2();
  974. init_errors2();
  975. init_errors2();
  976. _OperatorClauseTool = class _OperatorClauseTool extends Service {
  977. /**
  978. * Compare.
  979. *
  980. * @param {*} val1 The 1st value
  981. * @param {*} val2 The 2nd value
  982. * @returns {number} 0: =, positive: >, negative <
  983. */
  984. compare(val1, val2) {
  985. if (val1 == null || val2 == null) {
  986. return val1 == val2 ? 0 : NaN;
  987. }
  988. if (typeof val1 === "number") {
  989. if (typeof val2 === "number" || typeof val2 === "string" || typeof val2 === "boolean") {
  990. if (val1 === val2) return 0;
  991. return val1 - Number(val2);
  992. }
  993. return NaN;
  994. }
  995. if (typeof val1 === "string") {
  996. const isDigits = /^\d+$/.test(val1);
  997. if (isDigits) return this.compare(Number(val1), val2);
  998. try {
  999. if (val1 > val2) return 1;
  1000. if (val1 < val2) return -1;
  1001. if (val1 == val2) return 0;
  1002. } catch (e) {
  1003. }
  1004. return NaN;
  1005. }
  1006. if (typeof val1 === "boolean") {
  1007. return Number(val1) - Number(val2);
  1008. }
  1009. return val1 === val2 ? 0 : NaN;
  1010. }
  1011. /**
  1012. * Test all operators.
  1013. *
  1014. * @param {object} clause
  1015. * @param {*} value
  1016. * @returns {boolean|undefined}
  1017. */
  1018. testAll(clause, value) {
  1019. if (!clause || typeof clause !== "object" || Array.isArray(clause))
  1020. throw new InvalidArgumentError2(
  1021. "The first argument of OperatorUtils.testAll should be an Object, but %v given.",
  1022. clause
  1023. );
  1024. const eqNeqTest = this.testEqNeq(clause, value);
  1025. if (eqNeqTest !== void 0) return eqNeqTest;
  1026. const gtLtTest = this.testGtLt(clause, value);
  1027. if (gtLtTest !== void 0) return gtLtTest;
  1028. const incTest = this.testInq(clause, value);
  1029. if (incTest !== void 0) return incTest;
  1030. const ninTest = this.testNin(clause, value);
  1031. if (ninTest !== void 0) return ninTest;
  1032. const betweenTest = this.testBetween(clause, value);
  1033. if (betweenTest !== void 0) return betweenTest;
  1034. const existsTest = this.testExists(clause, value);
  1035. if (existsTest !== void 0) return existsTest;
  1036. const likeTest = this.testLike(clause, value);
  1037. if (likeTest !== void 0) return likeTest;
  1038. const nlikeTest = this.testNlike(clause, value);
  1039. if (nlikeTest !== void 0) return nlikeTest;
  1040. const ilikeTest = this.testIlike(clause, value);
  1041. if (ilikeTest !== void 0) return ilikeTest;
  1042. const nilikeTest = this.testNilike(clause, value);
  1043. if (nilikeTest !== void 0) return nilikeTest;
  1044. const regExpTest = this.testRegexp(clause, value);
  1045. if (regExpTest !== void 0) return regExpTest;
  1046. }
  1047. /**
  1048. * Test eq/neq operator.
  1049. *
  1050. * @example
  1051. * ```ts
  1052. * {
  1053. * eq: 'foo',
  1054. * }
  1055. * ```
  1056. *
  1057. * @example
  1058. * ```ts
  1059. * {
  1060. * neq: 'foo',
  1061. * }
  1062. * ```
  1063. *
  1064. * @param {object} clause
  1065. * @param {*} value
  1066. * @returns {boolean|undefined}
  1067. */
  1068. testEqNeq(clause, value) {
  1069. if (!clause || typeof clause !== "object")
  1070. throw new InvalidArgumentError2(
  1071. "The first argument of OperatorUtils.testEqNeq should be an Object, but %v given.",
  1072. clause
  1073. );
  1074. if ("eq" in clause) return this.compare(clause.eq, value) === 0;
  1075. if ("neq" in clause) return this.compare(clause.neq, value) !== 0;
  1076. }
  1077. /**
  1078. * Test lt/gt/lte/gte operator.
  1079. *
  1080. * @example
  1081. * ```ts
  1082. * {
  1083. * lt: 10,
  1084. * }
  1085. * ```
  1086. *
  1087. * @example
  1088. * ```ts
  1089. * {
  1090. * lte: 10,
  1091. * }
  1092. * ```
  1093. *
  1094. * @example
  1095. * ```ts
  1096. * {
  1097. * gt: 10,
  1098. * }
  1099. * ```
  1100. *
  1101. * @example
  1102. * ```ts
  1103. * {
  1104. * gte: 10,
  1105. * }
  1106. * ```
  1107. *
  1108. * @param {object} clause
  1109. * @param {*} value
  1110. * @returns {boolean|undefined}
  1111. */
  1112. testGtLt(clause, value) {
  1113. if (!clause || typeof clause !== "object")
  1114. throw new InvalidArgumentError2(
  1115. "The first argument of OperatorUtils.testGtLt should be an Object, but %v given.",
  1116. clause
  1117. );
  1118. if ("gt" in clause) return this.compare(value, clause.gt) > 0;
  1119. if ("gte" in clause) return this.compare(value, clause.gte) >= 0;
  1120. if ("lt" in clause) return this.compare(value, clause.lt) < 0;
  1121. if ("lte" in clause) return this.compare(value, clause.lte) <= 0;
  1122. }
  1123. /**
  1124. * Test inc operator.
  1125. *
  1126. * @example
  1127. * ```ts
  1128. * {
  1129. * inc: ['foo', 'bar'],
  1130. * }
  1131. * ```
  1132. *
  1133. * @param {object} clause
  1134. * @param {*} value
  1135. * @returns {boolean|undefined}
  1136. */
  1137. testInq(clause, value) {
  1138. if (!clause || typeof clause !== "object")
  1139. throw new InvalidArgumentError2(
  1140. "The first argument of OperatorUtils.testInq should be an Object, but %v given.",
  1141. clause
  1142. );
  1143. if ("inq" in clause && clause.inq !== void 0) {
  1144. if (!clause.inq || !Array.isArray(clause.inq)) {
  1145. throw new InvalidOperatorValueError(
  1146. "inq",
  1147. "an Array of possible values",
  1148. clause.inq
  1149. );
  1150. }
  1151. for (let i = 0; i < clause.inq.length; i++) {
  1152. if (clause.inq[i] == value) return true;
  1153. }
  1154. return false;
  1155. }
  1156. }
  1157. /**
  1158. * Test nin operator.
  1159. *
  1160. * @example
  1161. * ```ts
  1162. * {
  1163. * nin: ['foo', 'bar'],
  1164. * }
  1165. * ```
  1166. *
  1167. * @param {object} clause
  1168. * @param {*} value
  1169. * @returns {boolean|undefined}
  1170. */
  1171. testNin(clause, value) {
  1172. if (!clause || typeof clause !== "object")
  1173. throw new InvalidArgumentError2(
  1174. "The first argument of OperatorUtils.testNin should be an Object, but %v given.",
  1175. clause
  1176. );
  1177. if ("nin" in clause && clause.nin !== void 0) {
  1178. if (!clause.nin || !Array.isArray(clause.nin)) {
  1179. throw new InvalidOperatorValueError(
  1180. "nin",
  1181. "an Array of possible values",
  1182. clause.nin
  1183. );
  1184. }
  1185. for (let i = 0; i < clause.nin.length; i++) {
  1186. if (clause.nin[i] == value) return false;
  1187. }
  1188. return true;
  1189. }
  1190. }
  1191. /**
  1192. * Test between operator.
  1193. *
  1194. * @example
  1195. * ```ts
  1196. * {
  1197. * between: [10, 20],
  1198. * }
  1199. * ```
  1200. *
  1201. * @param {object} clause
  1202. * @param {*} value
  1203. * @returns {boolean|undefined}
  1204. */
  1205. testBetween(clause, value) {
  1206. if (!clause || typeof clause !== "object")
  1207. throw new InvalidArgumentError2(
  1208. "The first argument of OperatorUtils.testBetween should be an Object, but %v given.",
  1209. clause
  1210. );
  1211. if ("between" in clause && clause.between !== void 0) {
  1212. if (!Array.isArray(clause.between) || clause.between.length !== 2) {
  1213. throw new InvalidOperatorValueError(
  1214. "between",
  1215. "an Array of 2 elements",
  1216. clause.between
  1217. );
  1218. }
  1219. return this.testGtLt({ gte: clause.between[0] }, value) && this.testGtLt({ lte: clause.between[1] }, value);
  1220. }
  1221. }
  1222. /**
  1223. * Test exists operator.
  1224. *
  1225. * @example
  1226. * ```ts
  1227. * {
  1228. * exists: true,
  1229. * }
  1230. * ```
  1231. *
  1232. * @param {object} clause
  1233. * @param {*} value
  1234. * @returns {boolean|undefined}
  1235. */
  1236. testExists(clause, value) {
  1237. if (!clause || typeof clause !== "object")
  1238. throw new InvalidArgumentError2(
  1239. "The first argument of OperatorUtils.testExists should be an Object, but %v given.",
  1240. clause
  1241. );
  1242. if ("exists" in clause && clause.exists !== void 0) {
  1243. if (typeof clause.exists !== "boolean") {
  1244. throw new InvalidOperatorValueError(
  1245. "exists",
  1246. "a Boolean",
  1247. clause.exists
  1248. );
  1249. }
  1250. return clause.exists ? value !== void 0 : value === void 0;
  1251. }
  1252. }
  1253. /**
  1254. * Test like operator.
  1255. *
  1256. * @example
  1257. * ```ts
  1258. * {
  1259. * like: 'foo',
  1260. * }
  1261. * ```
  1262. *
  1263. * @param {object} clause
  1264. * @param {*} value
  1265. * @returns {boolean|undefined}
  1266. */
  1267. testLike(clause, value) {
  1268. if (!clause || typeof clause !== "object")
  1269. throw new InvalidArgumentError2(
  1270. "The first argument of OperatorUtils.testLike should be an Object, but %v given.",
  1271. clause
  1272. );
  1273. if ("like" in clause && clause.like !== void 0) {
  1274. if (typeof clause.like !== "string" && !(clause.like instanceof RegExp))
  1275. throw new InvalidOperatorValueError("like", "a String", clause.like);
  1276. return stringToRegexp(clause.like).test(value);
  1277. }
  1278. }
  1279. /**
  1280. * Test nlike operator.
  1281. *
  1282. * @example
  1283. * ```ts
  1284. * {
  1285. * nlike: 'foo',
  1286. * }
  1287. * ```
  1288. *
  1289. * @param {object} clause
  1290. * @param {*} value
  1291. * @returns {boolean|undefined}
  1292. */
  1293. testNlike(clause, value) {
  1294. if (!clause || typeof clause !== "object")
  1295. throw new InvalidArgumentError2(
  1296. "The first argument of OperatorUtils.testNlike should be an Object, but %v given.",
  1297. clause
  1298. );
  1299. if ("nlike" in clause && clause.nlike !== void 0) {
  1300. if (typeof clause.nlike !== "string" && !(clause.nlike instanceof RegExp)) {
  1301. throw new InvalidOperatorValueError("nlike", "a String", clause.nlike);
  1302. }
  1303. return !stringToRegexp(clause.nlike).test(value);
  1304. }
  1305. }
  1306. /**
  1307. * Test ilike operator.
  1308. *
  1309. * @example
  1310. * ```ts
  1311. * {
  1312. * ilike: 'foo',
  1313. * }
  1314. * ```
  1315. *
  1316. * @param {object} clause
  1317. * @param {*} value
  1318. * @returns {boolean|undefined}
  1319. */
  1320. testIlike(clause, value) {
  1321. if (!clause || typeof clause !== "object")
  1322. throw new InvalidArgumentError2(
  1323. "The first argument of OperatorUtils.testIlike should be an Object, but %v given.",
  1324. clause
  1325. );
  1326. if ("ilike" in clause && clause.ilike !== void 0) {
  1327. if (typeof clause.ilike !== "string" && !(clause.ilike instanceof RegExp)) {
  1328. throw new InvalidOperatorValueError("ilike", "a String", clause.ilike);
  1329. }
  1330. return stringToRegexp(clause.ilike, "i").test(value);
  1331. }
  1332. }
  1333. /**
  1334. * Test nilike operator.
  1335. *
  1336. * @example
  1337. * ```ts
  1338. * {
  1339. * nilike: 'foo',
  1340. * }
  1341. * ```
  1342. *
  1343. * @param {object} clause
  1344. * @param {*} value
  1345. * @returns {boolean|undefined}
  1346. */
  1347. testNilike(clause, value) {
  1348. if (!clause || typeof clause !== "object")
  1349. throw new InvalidArgumentError2(
  1350. "The first argument of OperatorUtils.testNilike should be an Object, but %v given.",
  1351. clause
  1352. );
  1353. if ("nilike" in clause && clause.nilike !== void 0) {
  1354. if (typeof clause.nilike !== "string" && !(clause.nilike instanceof RegExp)) {
  1355. throw new InvalidOperatorValueError(
  1356. "nilike",
  1357. "a String",
  1358. clause.nilike
  1359. );
  1360. }
  1361. return !stringToRegexp(clause.nilike, "i").test(value);
  1362. }
  1363. }
  1364. /**
  1365. * Test regexp.
  1366. *
  1367. * @example
  1368. * ```ts
  1369. * {
  1370. * regexp: 'foo.*',
  1371. * }
  1372. * ```
  1373. *
  1374. * @example
  1375. * ```ts
  1376. * {
  1377. * regexp: 'foo.*',
  1378. * flags: 'i',
  1379. * }
  1380. * ```
  1381. *
  1382. * @param {object} clause
  1383. * @param {*} value
  1384. * @returns {boolean|undefined}
  1385. */
  1386. testRegexp(clause, value) {
  1387. if (!clause || typeof clause !== "object")
  1388. throw new InvalidArgumentError2(
  1389. "The first argument of OperatorUtils.testRegexp should be an Object, but %v given.",
  1390. clause
  1391. );
  1392. if ("regexp" in clause && clause.regexp !== void 0) {
  1393. if (typeof clause.regexp !== "string" && !(clause.regexp instanceof RegExp)) {
  1394. throw new InvalidOperatorValueError(
  1395. "regexp",
  1396. "a String",
  1397. clause.regexp
  1398. );
  1399. }
  1400. const flags = clause.flags || void 0;
  1401. if (flags && typeof flags !== "string")
  1402. throw new InvalidArgumentError2(
  1403. "RegExp flags should be a String, but %v given.",
  1404. clause.flags
  1405. );
  1406. if (!value || typeof value !== "string") return false;
  1407. const regExp = stringToRegexp(clause.regexp, flags);
  1408. return !!value.match(regExp);
  1409. }
  1410. }
  1411. };
  1412. __name(_OperatorClauseTool, "OperatorClauseTool");
  1413. OperatorClauseTool = _OperatorClauseTool;
  1414. }
  1415. });
  1416. // src/filter/where-clause-tool.js
  1417. var _WhereClauseTool, WhereClauseTool;
  1418. var init_where_clause_tool = __esm({
  1419. "src/filter/where-clause-tool.js"() {
  1420. "use strict";
  1421. init_src2();
  1422. init_utils2();
  1423. init_errors2();
  1424. init_operator_clause_tool();
  1425. _WhereClauseTool = class _WhereClauseTool extends Service {
  1426. /**
  1427. * Filter by where clause.
  1428. *
  1429. * @example
  1430. * ```
  1431. * const entities = [
  1432. * {foo: 1, bar: 'a'},
  1433. * {foo: 2, bar: 'b'},
  1434. * {foo: 3, bar: 'b'},
  1435. * {foo: 4, bar: 'b'},
  1436. * ];
  1437. *
  1438. * const result = filterByWhereClause(entities, {
  1439. * foo: {gt: 2},
  1440. * bar: 'b',
  1441. * });
  1442. *
  1443. * console.log(result);
  1444. * // [
  1445. * // {foo: 3, bar: 'b'},
  1446. * // {foo: 4, bar: 'b'},
  1447. * // ];
  1448. *
  1449. * ```
  1450. *
  1451. * @param {object[]} entities
  1452. * @param {WhereClause|undefined} where
  1453. * @returns {object[]}
  1454. */
  1455. filter(entities, where = void 0) {
  1456. if (!Array.isArray(entities))
  1457. throw new InvalidArgumentError2(
  1458. "The first argument of WhereClauseTool.filter should be an Array of Object, but %v given.",
  1459. entities
  1460. );
  1461. if (where == null) return entities;
  1462. return entities.filter(this._createFilter(where));
  1463. }
  1464. /**
  1465. * Create where filter.
  1466. *
  1467. * @param {WhereClause} whereClause
  1468. * @returns {Function}
  1469. */
  1470. _createFilter(whereClause) {
  1471. if (typeof whereClause !== "object" || Array.isArray(whereClause))
  1472. throw new InvalidArgumentError2(
  1473. 'The provided option "where" should be an Object, but %v given.',
  1474. whereClause
  1475. );
  1476. const keys = Object.keys(whereClause);
  1477. return (data) => {
  1478. if (typeof data !== "object")
  1479. throw new InvalidArgumentError2(
  1480. "The first argument of WhereClauseTool.filter should be an Array of Object, but %v given.",
  1481. data
  1482. );
  1483. return keys.every((key) => {
  1484. if (key === "and" && key in whereClause) {
  1485. const andClause = whereClause[key];
  1486. if (Array.isArray(andClause))
  1487. return andClause.every((clause) => this._createFilter(clause)(data));
  1488. } else if (key === "or" && key in whereClause) {
  1489. const orClause = whereClause[key];
  1490. if (Array.isArray(orClause))
  1491. return orClause.some((clause) => this._createFilter(clause)(data));
  1492. }
  1493. const value = getValueByPath(data, key);
  1494. const matcher = whereClause[key];
  1495. if (Array.isArray(value)) {
  1496. if (typeof matcher === "object" && matcher !== null && "neq" in matcher && matcher.neq !== void 0) {
  1497. if (value.length === 0) return true;
  1498. return value.every((el, index) => {
  1499. const where = {};
  1500. where[index] = matcher;
  1501. return this._createFilter(where)({ ...value });
  1502. });
  1503. }
  1504. return value.some((el, index) => {
  1505. const where = {};
  1506. where[index] = matcher;
  1507. return this._createFilter(where)({ ...value });
  1508. });
  1509. }
  1510. if (this._test(matcher, value)) return true;
  1511. });
  1512. };
  1513. }
  1514. /**
  1515. * Value testing.
  1516. *
  1517. * @param {*} example
  1518. * @param {*} value
  1519. * @returns {boolean}
  1520. */
  1521. _test(example, value) {
  1522. if (example === null) {
  1523. return value === null;
  1524. }
  1525. if (example === void 0) {
  1526. return value === void 0;
  1527. }
  1528. if (example instanceof RegExp) {
  1529. if (typeof value === "string") return !!value.match(example);
  1530. return false;
  1531. }
  1532. if (typeof example === "object") {
  1533. const operatorsTest = this.getService(OperatorClauseTool).testAll(
  1534. example,
  1535. value
  1536. );
  1537. if (operatorsTest !== void 0) return operatorsTest;
  1538. }
  1539. return example == value;
  1540. }
  1541. /**
  1542. * Validate where clause.
  1543. *
  1544. * @param {WhereClause|undefined} clause
  1545. */
  1546. static validateWhereClause(clause) {
  1547. if (clause == null || typeof clause === "function") return;
  1548. if (typeof clause !== "object" || Array.isArray(clause))
  1549. throw new InvalidArgumentError2(
  1550. 'The provided option "where" should be an Object, but %v given.',
  1551. clause
  1552. );
  1553. }
  1554. };
  1555. __name(_WhereClauseTool, "WhereClauseTool");
  1556. WhereClauseTool = _WhereClauseTool;
  1557. }
  1558. });
  1559. // src/definition/model/relations/relation-type.js
  1560. var RelationType;
  1561. var init_relation_type = __esm({
  1562. "src/definition/model/relations/relation-type.js"() {
  1563. "use strict";
  1564. RelationType = {
  1565. BELONGS_TO: "belongsTo",
  1566. HAS_ONE: "hasOne",
  1567. HAS_MANY: "hasMany",
  1568. REFERENCES_MANY: "referencesMany"
  1569. };
  1570. }
  1571. });
  1572. // src/definition/model/relations/relation-definition.js
  1573. var init_relation_definition = __esm({
  1574. "src/definition/model/relations/relation-definition.js"() {
  1575. "use strict";
  1576. }
  1577. });
  1578. // src/definition/model/relations/relations-definition-validator.js
  1579. var _RelationsDefinitionValidator, RelationsDefinitionValidator;
  1580. var init_relations_definition_validator = __esm({
  1581. "src/definition/model/relations/relations-definition-validator.js"() {
  1582. "use strict";
  1583. init_src2();
  1584. init_relation_type();
  1585. init_relation_type();
  1586. init_errors2();
  1587. _RelationsDefinitionValidator = class _RelationsDefinitionValidator extends Service {
  1588. /**
  1589. * Validate.
  1590. *
  1591. * @param {string} modelName
  1592. * @param {object} relDefs
  1593. */
  1594. validate(modelName, relDefs) {
  1595. if (!modelName || typeof modelName !== "string")
  1596. throw new InvalidArgumentError2(
  1597. "The first argument of RelationsDefinitionValidator.validate should be a non-empty String, but %v given.",
  1598. modelName
  1599. );
  1600. if (!relDefs || typeof relDefs !== "object" || Array.isArray(relDefs))
  1601. throw new InvalidArgumentError2(
  1602. 'The provided option "relations" of the model %v should be an Object, but %v given.',
  1603. modelName,
  1604. relDefs
  1605. );
  1606. const relNames = Object.keys(relDefs);
  1607. relNames.forEach((relName) => {
  1608. const relDef = relDefs[relName];
  1609. this._validateRelation(modelName, relName, relDef);
  1610. });
  1611. }
  1612. /**
  1613. * Validate relation.
  1614. *
  1615. * @param {string} modelName
  1616. * @param {string} relName
  1617. * @param {object} relDef
  1618. */
  1619. _validateRelation(modelName, relName, relDef) {
  1620. if (!modelName || typeof modelName !== "string")
  1621. throw new InvalidArgumentError2(
  1622. "The first argument of RelationsDefinitionValidator._validateRelation should be a non-empty String, but %v given.",
  1623. modelName
  1624. );
  1625. if (!relName || typeof relName !== "string")
  1626. throw new InvalidArgumentError2(
  1627. "The relation name of the model %v should be a non-empty String, but %v given.",
  1628. modelName,
  1629. relName
  1630. );
  1631. if (!relDef || typeof relDef !== "object" || Array.isArray(relDef))
  1632. throw new InvalidArgumentError2(
  1633. "The relation %v of the model %v should be an Object, but %v given.",
  1634. relName,
  1635. modelName,
  1636. relDef
  1637. );
  1638. if (!relDef.type || !Object.values(RelationType).includes(relDef.type))
  1639. throw new InvalidArgumentError2(
  1640. 'The relation %v of the model %v requires the option "type" to have one of relation types: %l, but %v given.',
  1641. relName,
  1642. modelName,
  1643. Object.values(RelationType),
  1644. relDef.type
  1645. );
  1646. this._validateBelongsTo(modelName, relName, relDef);
  1647. this._validateHasOne(modelName, relName, relDef);
  1648. this._validateHasMany(modelName, relName, relDef);
  1649. this._validateReferencesMany(modelName, relName, relDef);
  1650. }
  1651. /**
  1652. * Validate "belongsTo".
  1653. *
  1654. * @example The regular "belongsTo" relation.
  1655. * ```
  1656. * {
  1657. * type: RelationType.BELONGS_TO,
  1658. * model: 'model',
  1659. * foreignKey: 'modelId', // optional
  1660. * }
  1661. * ```
  1662. *
  1663. * @example The polymorphic "belongsTo" relation.
  1664. * ```
  1665. * {
  1666. * type: RelationType.BELONGS_TO,
  1667. * polymorphic: true,
  1668. * foreignKey: 'referenceId', // optional
  1669. * discriminator: 'referenceType', // optional
  1670. * }
  1671. * ```
  1672. *
  1673. * @param {string} modelName
  1674. * @param {string} relName
  1675. * @param {object} relDef
  1676. * @private
  1677. */
  1678. _validateBelongsTo(modelName, relName, relDef) {
  1679. if (relDef.type !== RelationType.BELONGS_TO) return;
  1680. if (relDef.polymorphic) {
  1681. if (typeof relDef.polymorphic !== "boolean")
  1682. throw new InvalidArgumentError2(
  1683. 'The relation %v of the model %v has the type "belongsTo", so it expects the option "polymorphic" to be a Boolean, but %v given.',
  1684. relName,
  1685. modelName,
  1686. relDef.polymorphic
  1687. );
  1688. if (relDef.foreignKey && typeof relDef.foreignKey !== "string")
  1689. throw new InvalidArgumentError2(
  1690. 'The relation %v of the model %v is a polymorphic "belongsTo" relation, so it expects the provided option "foreignKey" to be a String, but %v given.',
  1691. relName,
  1692. modelName,
  1693. relDef.foreignKey
  1694. );
  1695. if (relDef.discriminator && typeof relDef.discriminator !== "string")
  1696. throw new InvalidArgumentError2(
  1697. 'The relation %v of the model %v is a polymorphic "belongsTo" relation, so it expects the provided option "discriminator" to be a String, but %v given.',
  1698. relName,
  1699. modelName,
  1700. relDef.discriminator
  1701. );
  1702. } else {
  1703. if (!relDef.model || typeof relDef.model !== "string")
  1704. throw new InvalidArgumentError2(
  1705. 'The relation %v of the model %v has the type "belongsTo", so it requires the option "model" to be a non-empty String, but %v given.',
  1706. relName,
  1707. modelName,
  1708. relDef.model
  1709. );
  1710. if (relDef.foreignKey && typeof relDef.foreignKey !== "string")
  1711. throw new InvalidArgumentError2(
  1712. 'The relation %v of the model %v has the type "belongsTo", so it expects the provided option "foreignKey" to be a String, but %v given.',
  1713. relName,
  1714. modelName,
  1715. relDef.foreignKey
  1716. );
  1717. if (relDef.discriminator)
  1718. throw new InvalidArgumentError2(
  1719. 'The relation %v of the model %v is a non-polymorphic "belongsTo" relation, so it should not have the option "discriminator" to be provided.',
  1720. relName,
  1721. modelName
  1722. );
  1723. }
  1724. }
  1725. /**
  1726. * Validate "hasOne".
  1727. *
  1728. * @example The regular "hasOne" relation.
  1729. * ```
  1730. * {
  1731. * type: RelationType.HAS_ONE,
  1732. * model: 'model',
  1733. * foreignKey: 'modelId',
  1734. * }
  1735. * ```
  1736. *
  1737. * @example The polymorphic "hasOne" relation with a target relation name.
  1738. * ```
  1739. * {
  1740. * type: RelationType.HAS_ONE,
  1741. * model: 'model',
  1742. * polymorphic: 'reference',
  1743. * }
  1744. * ```
  1745. *
  1746. * @example The polymorphic "hasOne" relation with target relation keys.
  1747. * ```
  1748. * {
  1749. * type: RelationType.HAS_ONE,
  1750. * model: 'model',
  1751. * polymorphic: true,
  1752. * foreignKey: 'referenceId',
  1753. * discriminator: 'referenceType',
  1754. * }
  1755. * ```
  1756. *
  1757. * @param {string} modelName
  1758. * @param {string} relName
  1759. * @param {object} relDef
  1760. * @private
  1761. */
  1762. _validateHasOne(modelName, relName, relDef) {
  1763. if (relDef.type !== RelationType.HAS_ONE) return;
  1764. if (!relDef.model || typeof relDef.model !== "string")
  1765. throw new InvalidArgumentError2(
  1766. 'The relation %v of the model %v has the type "hasOne", so it requires the option "model" to be a non-empty String, but %v given.',
  1767. relName,
  1768. modelName,
  1769. relDef.model
  1770. );
  1771. if (relDef.polymorphic) {
  1772. if (typeof relDef.polymorphic === "string") {
  1773. if (relDef.foreignKey)
  1774. throw new InvalidArgumentError2(
  1775. 'The relation %v of the model %v has the option "polymorphic" with a String value, so it should not have the option "foreignKey" to be provided.',
  1776. relName,
  1777. modelName
  1778. );
  1779. if (relDef.discriminator)
  1780. throw new InvalidArgumentError2(
  1781. 'The relation %v of the model %v has the option "polymorphic" with a String value, so it should not have the option "discriminator" to be provided.',
  1782. relName,
  1783. modelName
  1784. );
  1785. } else if (typeof relDef.polymorphic === "boolean") {
  1786. if (!relDef.foreignKey || typeof relDef.foreignKey !== "string")
  1787. throw new InvalidArgumentError2(
  1788. 'The relation %v of the model %v has the option "polymorphic" with "true" value, so it requires the option "foreignKey" to be a non-empty String, but %v given.',
  1789. relName,
  1790. modelName,
  1791. relDef.foreignKey
  1792. );
  1793. if (!relDef.discriminator || typeof relDef.discriminator !== "string")
  1794. throw new InvalidArgumentError2(
  1795. 'The relation %v of the model %v has the option "polymorphic" with "true" value, so it requires the option "discriminator" to be a non-empty String, but %v given.',
  1796. relName,
  1797. modelName,
  1798. relDef.discriminator
  1799. );
  1800. } else {
  1801. throw new InvalidArgumentError2(
  1802. 'The relation %v of the model %v has the type "hasOne", so it expects the provided option "polymorphic" to be a String or a Boolean, but %v given.',
  1803. relName,
  1804. modelName,
  1805. relDef.polymorphic
  1806. );
  1807. }
  1808. } else {
  1809. if (!relDef.foreignKey || typeof relDef.foreignKey !== "string")
  1810. throw new InvalidArgumentError2(
  1811. 'The relation %v of the model %v has the type "hasOne", so it requires the option "foreignKey" to be a non-empty String, but %v given.',
  1812. relName,
  1813. modelName,
  1814. relDef.foreignKey
  1815. );
  1816. if (relDef.discriminator)
  1817. throw new InvalidArgumentError2(
  1818. 'The relation %v of the model %v is a non-polymorphic "hasOne" relation, so it should not have the option "discriminator" to be provided.',
  1819. relName,
  1820. modelName
  1821. );
  1822. }
  1823. }
  1824. /**
  1825. * Validate "hasMany".
  1826. *
  1827. * @example The regular "hasMany" relation.
  1828. * ```
  1829. * {
  1830. * type: RelationType.HAS_MANY,
  1831. * model: 'model',
  1832. * foreignKey: 'modelId',
  1833. * }
  1834. * ```
  1835. *
  1836. * @example The polymorphic "hasMany" relation with a target relation name.
  1837. * ```
  1838. * {
  1839. * type: RelationType.HAS_MANY,
  1840. * model: 'model',
  1841. * polymorphic: 'reference',
  1842. * }
  1843. * ```
  1844. *
  1845. * @example The polymorphic "hasMany" relation with target relation keys.
  1846. * ```
  1847. * {
  1848. * type: RelationType.HAS_MANY,
  1849. * model: 'model',
  1850. * polymorphic: true,
  1851. * foreignKey: 'referenceId',
  1852. * discriminator: 'referenceType',
  1853. * }
  1854. * ```
  1855. *
  1856. * @param {string} modelName
  1857. * @param {string} relName
  1858. * @param {object} relDef
  1859. * @private
  1860. */
  1861. _validateHasMany(modelName, relName, relDef) {
  1862. if (relDef.type !== RelationType.HAS_MANY) return;
  1863. if (!relDef.model || typeof relDef.model !== "string")
  1864. throw new InvalidArgumentError2(
  1865. 'The relation %v of the model %v has the type "hasMany", so it requires the option "model" to be a non-empty String, but %v given.',
  1866. relName,
  1867. modelName,
  1868. relDef.model
  1869. );
  1870. if (relDef.polymorphic) {
  1871. if (typeof relDef.polymorphic === "string") {
  1872. if (relDef.foreignKey)
  1873. throw new InvalidArgumentError2(
  1874. 'The relation %v of the model %v has the option "polymorphic" with a String value, so it should not have the option "foreignKey" to be provided.',
  1875. relName,
  1876. modelName
  1877. );
  1878. if (relDef.discriminator)
  1879. throw new InvalidArgumentError2(
  1880. 'The relation %v of the model %v has the option "polymorphic" with a String value, so it should not have the option "discriminator" to be provided.',
  1881. relName,
  1882. modelName
  1883. );
  1884. } else if (typeof relDef.polymorphic === "boolean") {
  1885. if (!relDef.foreignKey || typeof relDef.foreignKey !== "string")
  1886. throw new InvalidArgumentError2(
  1887. 'The relation %v of the model %v has the option "polymorphic" with "true" value, so it requires the option "foreignKey" to be a non-empty String, but %v given.',
  1888. relName,
  1889. modelName,
  1890. relDef.foreignKey
  1891. );
  1892. if (!relDef.discriminator || typeof relDef.discriminator !== "string")
  1893. throw new InvalidArgumentError2(
  1894. 'The relation %v of the model %v has the option "polymorphic" with "true" value, so it requires the option "discriminator" to be a non-empty String, but %v given.',
  1895. relName,
  1896. modelName,
  1897. relDef.discriminator
  1898. );
  1899. } else {
  1900. throw new InvalidArgumentError2(
  1901. 'The relation %v of the model %v has the type "hasMany", so it expects the provided option "polymorphic" to be a String or a Boolean, but %v given.',
  1902. relName,
  1903. modelName,
  1904. relDef.polymorphic
  1905. );
  1906. }
  1907. } else {
  1908. if (!relDef.foreignKey || typeof relDef.foreignKey !== "string")
  1909. throw new InvalidArgumentError2(
  1910. 'The relation %v of the model %v has the type "hasMany", so it requires the option "foreignKey" to be a non-empty String, but %v given.',
  1911. relName,
  1912. modelName,
  1913. relDef.foreignKey
  1914. );
  1915. if (relDef.discriminator)
  1916. throw new InvalidArgumentError2(
  1917. 'The relation %v of the model %v is a non-polymorphic "hasMany" relation, so it should not have the option "discriminator" to be provided.',
  1918. relName,
  1919. modelName
  1920. );
  1921. }
  1922. }
  1923. /**
  1924. * Validate "referencesMany".
  1925. *
  1926. * @example
  1927. * ```
  1928. * {
  1929. * type: RelationType.REFERENCES_MANY,
  1930. * model: 'model',
  1931. * foreignKey: 'modelIds', // optional
  1932. * }
  1933. * ```
  1934. *
  1935. * @param {string} modelName
  1936. * @param {string} relName
  1937. * @param {object} relDef
  1938. * @private
  1939. */
  1940. _validateReferencesMany(modelName, relName, relDef) {
  1941. if (relDef.type !== RelationType.REFERENCES_MANY) return;
  1942. if (!relDef.model || typeof relDef.model !== "string")
  1943. throw new InvalidArgumentError2(
  1944. 'The relation %v of the model %v has the type "referencesMany", so it requires the option "model" to be a non-empty String, but %v given.',
  1945. relName,
  1946. modelName,
  1947. relDef.model
  1948. );
  1949. if (relDef.foreignKey && typeof relDef.foreignKey !== "string")
  1950. throw new InvalidArgumentError2(
  1951. 'The relation %v of the model %v has the type "referencesMany", so it expects the provided option "foreignKey" to be a String, but %v given.',
  1952. relName,
  1953. modelName,
  1954. relDef.foreignKey
  1955. );
  1956. if (relDef.discriminator)
  1957. throw new InvalidArgumentError2(
  1958. 'The relation %v of the model %v has the type "referencesMany", so it should not have the option "discriminator" to be provided.',
  1959. relName,
  1960. modelName
  1961. );
  1962. }
  1963. };
  1964. __name(_RelationsDefinitionValidator, "RelationsDefinitionValidator");
  1965. RelationsDefinitionValidator = _RelationsDefinitionValidator;
  1966. }
  1967. });
  1968. // src/definition/model/relations/index.js
  1969. var init_relations = __esm({
  1970. "src/definition/model/relations/index.js"() {
  1971. "use strict";
  1972. init_relation_type();
  1973. init_relation_definition();
  1974. init_relations_definition_validator();
  1975. }
  1976. });
  1977. // src/definition/model/properties/data-type.js
  1978. var DataType;
  1979. var init_data_type = __esm({
  1980. "src/definition/model/properties/data-type.js"() {
  1981. "use strict";
  1982. DataType = {
  1983. ANY: "any",
  1984. STRING: "string",
  1985. NUMBER: "number",
  1986. BOOLEAN: "boolean",
  1987. ARRAY: "array",
  1988. OBJECT: "object"
  1989. };
  1990. }
  1991. });
  1992. // src/definition/model/properties/property-definition.js
  1993. var init_property_definition = __esm({
  1994. "src/definition/model/properties/property-definition.js"() {
  1995. "use strict";
  1996. }
  1997. });
  1998. // src/definition/model/properties/property-uniqueness.js
  1999. var PropertyUniqueness;
  2000. var init_property_uniqueness = __esm({
  2001. "src/definition/model/properties/property-uniqueness.js"() {
  2002. "use strict";
  2003. PropertyUniqueness = {
  2004. STRICT: "strict",
  2005. SPARSE: "sparse",
  2006. NON_UNIQUE: "nonUnique"
  2007. };
  2008. }
  2009. });
  2010. // src/definition/model/properties/empty-values-definer.js
  2011. var _EmptyValuesDefiner, EmptyValuesDefiner;
  2012. var init_empty_values_definer = __esm({
  2013. "src/definition/model/properties/empty-values-definer.js"() {
  2014. "use strict";
  2015. init_data_type();
  2016. init_src2();
  2017. init_utils2();
  2018. init_errors2();
  2019. _EmptyValuesDefiner = class _EmptyValuesDefiner extends Service {
  2020. /**
  2021. * Empty values map.
  2022. *
  2023. * @type {Map<string, *[]>}
  2024. */
  2025. _emptyValuesMap = /* @__PURE__ */ new Map([
  2026. [DataType.ANY, [void 0, null]],
  2027. [DataType.STRING, [void 0, null, ""]],
  2028. [DataType.NUMBER, [void 0, null, 0]],
  2029. [DataType.BOOLEAN, [void 0, null]],
  2030. [DataType.ARRAY, [void 0, null, []]],
  2031. [DataType.OBJECT, [void 0, null, {}]]
  2032. ]);
  2033. /**
  2034. * Set empty values of data type.
  2035. *
  2036. * @param {string} dataType
  2037. * @param {*[]} emptyValues
  2038. * @returns {EmptyValuesDefiner}
  2039. */
  2040. setEmptyValuesOf(dataType, emptyValues) {
  2041. if (!Object.values(DataType).includes(dataType))
  2042. throw new InvalidArgumentError2(
  2043. 'The argument "dataType" of the EmptyValuesDefiner.setEmptyValuesOf must be one of data types: %l, but %v given.',
  2044. Object.values(DataType),
  2045. dataType
  2046. );
  2047. if (!Array.isArray(emptyValues))
  2048. throw new InvalidArgumentError2(
  2049. 'The argument "emptyValues" of the EmptyValuesDefiner.setEmptyValuesOf must be an Array, but %v given.',
  2050. emptyValues
  2051. );
  2052. this._emptyValuesMap.set(dataType, emptyValues);
  2053. return this;
  2054. }
  2055. /**
  2056. * Is empty.
  2057. *
  2058. * @param {string} dataType
  2059. * @param {*} value
  2060. * @returns {boolean}
  2061. */
  2062. isEmpty(dataType, value) {
  2063. if (!Object.values(DataType).includes(dataType))
  2064. throw new InvalidArgumentError2(
  2065. 'The argument "dataType" of the EmptyValuesDefiner.isEmpty must be one of data types: %l, but %v given.',
  2066. Object.values(DataType),
  2067. dataType
  2068. );
  2069. return this._emptyValuesMap.get(dataType).some((v) => isDeepEqual(v, value));
  2070. }
  2071. };
  2072. __name(_EmptyValuesDefiner, "EmptyValuesDefiner");
  2073. EmptyValuesDefiner = _EmptyValuesDefiner;
  2074. }
  2075. });
  2076. // src/definition/model/properties/property-validator/property-validator.js
  2077. var init_property_validator = __esm({
  2078. "src/definition/model/properties/property-validator/property-validator.js"() {
  2079. "use strict";
  2080. }
  2081. });
  2082. // src/definition/model/properties/property-validator/builtin/regexp-validator.js
  2083. function regexpValidator(value, options, context) {
  2084. if (value == null || options === false) return true;
  2085. if (typeof options !== "string" && !(options instanceof RegExp))
  2086. throw new InvalidArgumentError2(
  2087. 'The validator %v requires the "options" argument as a String or RegExp, but %v given.',
  2088. context.validatorName,
  2089. options
  2090. );
  2091. if (typeof value === "string") {
  2092. const regexp = stringToRegexp(options);
  2093. return regexp.test(value);
  2094. }
  2095. throw new InvalidArgumentError2(
  2096. "The property validator %v requires a String value, but %v given.",
  2097. context.validatorName,
  2098. value
  2099. );
  2100. }
  2101. var init_regexp_validator = __esm({
  2102. "src/definition/model/properties/property-validator/builtin/regexp-validator.js"() {
  2103. "use strict";
  2104. init_utils2();
  2105. init_errors2();
  2106. __name(regexpValidator, "regexpValidator");
  2107. }
  2108. });
  2109. // src/definition/model/properties/property-validator/builtin/max-length-validator.js
  2110. function maxLengthValidator(value, options, context) {
  2111. if (value == null || options === false) return true;
  2112. if (typeof options !== "number")
  2113. throw new InvalidArgumentError2(
  2114. 'The validator %v requires the "options" argument as a Number, but %v given.',
  2115. context.validatorName,
  2116. options
  2117. );
  2118. if (typeof value === "string" || Array.isArray(value))
  2119. return value.length <= options;
  2120. throw new InvalidArgumentError2(
  2121. "The property validator %v requires a String or an Array value, but %v given.",
  2122. context.validatorName,
  2123. value
  2124. );
  2125. }
  2126. var init_max_length_validator = __esm({
  2127. "src/definition/model/properties/property-validator/builtin/max-length-validator.js"() {
  2128. "use strict";
  2129. init_errors2();
  2130. __name(maxLengthValidator, "maxLengthValidator");
  2131. }
  2132. });
  2133. // src/definition/model/properties/property-validator/builtin/min-length-validator.js
  2134. function minLengthValidator(value, options, context) {
  2135. if (value == null || options === false) return true;
  2136. if (typeof options !== "number")
  2137. throw new InvalidArgumentError2(
  2138. 'The validator %v requires the "options" argument as a Number, but %v given.',
  2139. context.validatorName,
  2140. options
  2141. );
  2142. if (typeof value === "string" || Array.isArray(value))
  2143. return value.length >= options;
  2144. throw new InvalidArgumentError2(
  2145. "The property validator %v requires a String or an Array value, but %v given.",
  2146. context.validatorName,
  2147. value
  2148. );
  2149. }
  2150. var init_min_length_validator = __esm({
  2151. "src/definition/model/properties/property-validator/builtin/min-length-validator.js"() {
  2152. "use strict";
  2153. init_errors2();
  2154. __name(minLengthValidator, "minLengthValidator");
  2155. }
  2156. });
  2157. // src/definition/model/properties/property-validator/builtin/index.js
  2158. var init_builtin = __esm({
  2159. "src/definition/model/properties/property-validator/builtin/index.js"() {
  2160. "use strict";
  2161. init_regexp_validator();
  2162. init_max_length_validator();
  2163. init_min_length_validator();
  2164. }
  2165. });
  2166. // src/definition/model/properties/property-validator/property-validator-registry.js
  2167. var _PropertyValidatorRegistry, PropertyValidatorRegistry;
  2168. var init_property_validator_registry = __esm({
  2169. "src/definition/model/properties/property-validator/property-validator-registry.js"() {
  2170. "use strict";
  2171. init_src2();
  2172. init_builtin();
  2173. init_builtin();
  2174. init_builtin();
  2175. init_errors2();
  2176. _PropertyValidatorRegistry = class _PropertyValidatorRegistry extends Service {
  2177. /**
  2178. * Validators.
  2179. *
  2180. * @type {object}
  2181. */
  2182. _validators = {
  2183. maxLength: maxLengthValidator,
  2184. minLength: minLengthValidator,
  2185. regexp: regexpValidator
  2186. };
  2187. /**
  2188. * Add validator.
  2189. *
  2190. * @param {string} name
  2191. * @param {Function} validator
  2192. * @returns {PropertyValidatorRegistry}
  2193. */
  2194. addValidator(name, validator) {
  2195. if (!name || typeof name !== "string")
  2196. throw new InvalidArgumentError2(
  2197. "A name of the property validator must be a non-empty String, but %v given.",
  2198. name
  2199. );
  2200. if (name in this._validators)
  2201. throw new InvalidArgumentError2(
  2202. "The property validator %v is already defined.",
  2203. name
  2204. );
  2205. if (typeof validator !== "function")
  2206. throw new InvalidArgumentError2(
  2207. "The property validator %v must be a Function, but %v given.",
  2208. name,
  2209. validator
  2210. );
  2211. this._validators[name] = validator;
  2212. return this;
  2213. }
  2214. /**
  2215. * Has validator.
  2216. *
  2217. * @param {string} name
  2218. * @returns {boolean}
  2219. */
  2220. hasValidator(name) {
  2221. return Boolean(this._validators[name]);
  2222. }
  2223. /**
  2224. * Get validator.
  2225. *
  2226. * @param {string} name
  2227. * @returns {Function}
  2228. */
  2229. getValidator(name) {
  2230. const validator = this._validators[name];
  2231. if (!validator)
  2232. throw new InvalidArgumentError2(
  2233. "The property validator %v is not defined.",
  2234. name
  2235. );
  2236. return validator;
  2237. }
  2238. };
  2239. __name(_PropertyValidatorRegistry, "PropertyValidatorRegistry");
  2240. PropertyValidatorRegistry = _PropertyValidatorRegistry;
  2241. }
  2242. });
  2243. // src/definition/model/properties/property-validator/index.js
  2244. var init_property_validator2 = __esm({
  2245. "src/definition/model/properties/property-validator/index.js"() {
  2246. "use strict";
  2247. init_property_validator();
  2248. init_property_validator_registry();
  2249. }
  2250. });
  2251. // src/definition/model/properties/property-transformer/property-transformer.js
  2252. var init_property_transformer = __esm({
  2253. "src/definition/model/properties/property-transformer/property-transformer.js"() {
  2254. "use strict";
  2255. }
  2256. });
  2257. // src/definition/model/properties/property-transformer/builtin/trim-transformer.js
  2258. function trimTransformer(value, options, context) {
  2259. if (value == null) return value;
  2260. if (typeof value === "string") return value.trim();
  2261. throw new InvalidArgumentError2(
  2262. "The property transformer %v requires a String value, but %v given.",
  2263. context.transformerName,
  2264. value
  2265. );
  2266. }
  2267. var init_trim_transformer = __esm({
  2268. "src/definition/model/properties/property-transformer/builtin/trim-transformer.js"() {
  2269. "use strict";
  2270. init_errors2();
  2271. __name(trimTransformer, "trimTransformer");
  2272. }
  2273. });
  2274. // src/definition/model/properties/property-transformer/builtin/to-lower-case-transformer.js
  2275. function toLowerCaseTransformer(value, options, context) {
  2276. if (value == null) return value;
  2277. if (typeof value === "string") return value.toLowerCase();
  2278. throw new InvalidArgumentError2(
  2279. "The property transformer %v requires a String value, but %v given.",
  2280. context.transformerName,
  2281. value
  2282. );
  2283. }
  2284. var init_to_lower_case_transformer = __esm({
  2285. "src/definition/model/properties/property-transformer/builtin/to-lower-case-transformer.js"() {
  2286. "use strict";
  2287. init_errors2();
  2288. __name(toLowerCaseTransformer, "toLowerCaseTransformer");
  2289. }
  2290. });
  2291. // src/definition/model/properties/property-transformer/builtin/to-upper-case-transformer.js
  2292. function toUpperCaseTransformer(value, options, context) {
  2293. if (value == null) return value;
  2294. if (typeof value === "string") return value.toUpperCase();
  2295. throw new InvalidArgumentError2(
  2296. "The property transformer %v requires a String value, but %v given.",
  2297. context.transformerName,
  2298. value
  2299. );
  2300. }
  2301. var init_to_upper_case_transformer = __esm({
  2302. "src/definition/model/properties/property-transformer/builtin/to-upper-case-transformer.js"() {
  2303. "use strict";
  2304. init_errors2();
  2305. __name(toUpperCaseTransformer, "toUpperCaseTransformer");
  2306. }
  2307. });
  2308. // src/definition/model/properties/property-transformer/builtin/to-title-case-transformer.js
  2309. function toTitleCaseTransformer(value, options, context) {
  2310. if (value == null) return value;
  2311. if (typeof value === "string")
  2312. return value.replace(new RegExp("\\p{L}\\S*", "gu"), (text) => {
  2313. return text.charAt(0).toUpperCase() + text.substring(1).toLowerCase();
  2314. });
  2315. throw new InvalidArgumentError2(
  2316. "The property transformer %v requires a String value, but %v given.",
  2317. context.transformerName,
  2318. value
  2319. );
  2320. }
  2321. var init_to_title_case_transformer = __esm({
  2322. "src/definition/model/properties/property-transformer/builtin/to-title-case-transformer.js"() {
  2323. "use strict";
  2324. init_errors2();
  2325. __name(toTitleCaseTransformer, "toTitleCaseTransformer");
  2326. }
  2327. });
  2328. // src/definition/model/properties/property-transformer/builtin/index.js
  2329. var init_builtin2 = __esm({
  2330. "src/definition/model/properties/property-transformer/builtin/index.js"() {
  2331. "use strict";
  2332. init_trim_transformer();
  2333. init_to_lower_case_transformer();
  2334. init_to_upper_case_transformer();
  2335. init_to_title_case_transformer();
  2336. }
  2337. });
  2338. // src/definition/model/properties/property-transformer/property-transformer-registry.js
  2339. var _PropertyTransformerRegistry, PropertyTransformerRegistry;
  2340. var init_property_transformer_registry = __esm({
  2341. "src/definition/model/properties/property-transformer/property-transformer-registry.js"() {
  2342. "use strict";
  2343. init_src2();
  2344. init_builtin2();
  2345. init_builtin2();
  2346. init_builtin2();
  2347. init_builtin2();
  2348. init_errors2();
  2349. _PropertyTransformerRegistry = class _PropertyTransformerRegistry extends Service {
  2350. /**
  2351. * Transformers.
  2352. *
  2353. * @type {object}
  2354. */
  2355. _transformers = {
  2356. trim: trimTransformer,
  2357. toUpperCase: toUpperCaseTransformer,
  2358. toLowerCase: toLowerCaseTransformer,
  2359. toTitleCase: toTitleCaseTransformer
  2360. };
  2361. /**
  2362. * Add transformer.
  2363. *
  2364. * @param {string} name
  2365. * @param {Function} transformer
  2366. * @returns {PropertyTransformerRegistry}
  2367. */
  2368. addTransformer(name, transformer) {
  2369. if (!name || typeof name !== "string")
  2370. throw new InvalidArgumentError2(
  2371. "A name of the property transformer must be a non-empty String, but %v given.",
  2372. name
  2373. );
  2374. if (name in this._transformers)
  2375. throw new InvalidArgumentError2(
  2376. "The property transformer %v is already defined.",
  2377. name
  2378. );
  2379. if (typeof transformer !== "function")
  2380. throw new InvalidArgumentError2(
  2381. "The property transformer %v must be a Function, but %v given.",
  2382. name,
  2383. transformer
  2384. );
  2385. this._transformers[name] = transformer;
  2386. return this;
  2387. }
  2388. /**
  2389. * Has transformer.
  2390. *
  2391. * @param {string} name
  2392. * @returns {boolean}
  2393. */
  2394. hasTransformer(name) {
  2395. return Boolean(this._transformers[name]);
  2396. }
  2397. /**
  2398. * Get transformer.
  2399. *
  2400. * @param {string} name
  2401. * @returns {Function}
  2402. */
  2403. getTransformer(name) {
  2404. const transformer = this._transformers[name];
  2405. if (!transformer)
  2406. throw new InvalidArgumentError2(
  2407. "The property transformer %v is not defined.",
  2408. name
  2409. );
  2410. return transformer;
  2411. }
  2412. };
  2413. __name(_PropertyTransformerRegistry, "PropertyTransformerRegistry");
  2414. PropertyTransformerRegistry = _PropertyTransformerRegistry;
  2415. }
  2416. });
  2417. // src/definition/model/properties/property-transformer/index.js
  2418. var init_property_transformer2 = __esm({
  2419. "src/definition/model/properties/property-transformer/index.js"() {
  2420. "use strict";
  2421. init_property_transformer();
  2422. init_property_transformer_registry();
  2423. }
  2424. });
  2425. // src/definition/definition-registry.js
  2426. var _DefinitionRegistry, DefinitionRegistry;
  2427. var init_definition_registry = __esm({
  2428. "src/definition/definition-registry.js"() {
  2429. "use strict";
  2430. init_src2();
  2431. init_errors2();
  2432. init_model();
  2433. init_definition();
  2434. _DefinitionRegistry = class _DefinitionRegistry extends Service {
  2435. /**
  2436. * Datasources.
  2437. *
  2438. * @type {object}
  2439. */
  2440. _datasources = {};
  2441. /**
  2442. * Models.
  2443. *
  2444. * @type {object}
  2445. */
  2446. _models = {};
  2447. /**
  2448. * Add datasource.
  2449. *
  2450. * @param {object} datasourceDef
  2451. */
  2452. addDatasource(datasourceDef) {
  2453. this.getService(DatasourceDefinitionValidator).validate(datasourceDef);
  2454. const name = datasourceDef.name;
  2455. if (name in this._datasources)
  2456. throw new InvalidArgumentError2(
  2457. "The datasource %v is already defined.",
  2458. name
  2459. );
  2460. this._datasources[name] = datasourceDef;
  2461. }
  2462. /**
  2463. * Has datasource.
  2464. *
  2465. * @param {string} name
  2466. * @returns {boolean}
  2467. */
  2468. hasDatasource(name) {
  2469. return Boolean(this._datasources[name]);
  2470. }
  2471. /**
  2472. * Get datasource.
  2473. *
  2474. * @param {string} name
  2475. * @returns {object}
  2476. */
  2477. getDatasource(name) {
  2478. const datasourceDef = this._datasources[name];
  2479. if (!datasourceDef)
  2480. throw new InvalidArgumentError2("The datasource %v is not defined.", name);
  2481. return datasourceDef;
  2482. }
  2483. /**
  2484. * Add model.
  2485. *
  2486. * @param {object} modelDef
  2487. */
  2488. addModel(modelDef) {
  2489. this.getService(ModelDefinitionValidator).validate(modelDef);
  2490. const name = modelDef.name;
  2491. if (name in this._models)
  2492. throw new InvalidArgumentError2("The model %v is already defined.", name);
  2493. this._models[name] = modelDef;
  2494. }
  2495. /**
  2496. * Has model.
  2497. *
  2498. * @param {string} name
  2499. * @returns {boolean}
  2500. */
  2501. hasModel(name) {
  2502. return Boolean(this._models[name]);
  2503. }
  2504. /**
  2505. * Get model.
  2506. *
  2507. * @param {string} name
  2508. * @returns {object}
  2509. */
  2510. getModel(name) {
  2511. const modelDef = this._models[name];
  2512. if (!modelDef)
  2513. throw new InvalidArgumentError2("The model %v is not defined.", name);
  2514. return modelDef;
  2515. }
  2516. };
  2517. __name(_DefinitionRegistry, "DefinitionRegistry");
  2518. DefinitionRegistry = _DefinitionRegistry;
  2519. }
  2520. });
  2521. // src/definition/model/model-definition-utils.js
  2522. var DEFAULT_PRIMARY_KEY_PROPERTY_NAME, _ModelDefinitionUtils, ModelDefinitionUtils;
  2523. var init_model_definition_utils = __esm({
  2524. "src/definition/model/model-definition-utils.js"() {
  2525. "use strict";
  2526. init_src2();
  2527. init_properties();
  2528. init_utils2();
  2529. init_utils2();
  2530. init_properties();
  2531. init_errors2();
  2532. init_definition_registry();
  2533. DEFAULT_PRIMARY_KEY_PROPERTY_NAME = "id";
  2534. _ModelDefinitionUtils = class _ModelDefinitionUtils extends Service {
  2535. /**
  2536. * Get primary key as property name.
  2537. *
  2538. * @param {string} modelName
  2539. * @returns {string}
  2540. */
  2541. getPrimaryKeyAsPropertyName(modelName) {
  2542. const propDefs = this.getPropertiesDefinitionInBaseModelHierarchy(modelName);
  2543. const propNames = Object.keys(propDefs).filter((propName) => {
  2544. const propDef = propDefs[propName];
  2545. return propDef && typeof propDef === "object" && propDef.primaryKey;
  2546. });
  2547. if (propNames.length < 1) {
  2548. const isDefaultPrimaryKeyAlreadyInUse = Object.keys(propDefs).includes(
  2549. DEFAULT_PRIMARY_KEY_PROPERTY_NAME
  2550. );
  2551. if (isDefaultPrimaryKeyAlreadyInUse)
  2552. throw new InvalidArgumentError2(
  2553. 'The property name %v of the model %v is defined as a regular property. In this case, a primary key should be defined explicitly. Do use the option "primaryKey" to specify the primary key.',
  2554. DEFAULT_PRIMARY_KEY_PROPERTY_NAME,
  2555. modelName
  2556. );
  2557. return DEFAULT_PRIMARY_KEY_PROPERTY_NAME;
  2558. }
  2559. return propNames[0];
  2560. }
  2561. /**
  2562. * Get primary key as column name.
  2563. *
  2564. * @param {string} modelName
  2565. * @returns {string}
  2566. */
  2567. getPrimaryKeyAsColumnName(modelName) {
  2568. const pkPropName = this.getPrimaryKeyAsPropertyName(modelName);
  2569. let pkColName;
  2570. try {
  2571. pkColName = this.getColumnNameByPropertyName(modelName, pkPropName);
  2572. } catch (error) {
  2573. if (!(error instanceof InvalidArgumentError2)) throw error;
  2574. }
  2575. if (pkColName === void 0) return pkPropName;
  2576. return pkColName;
  2577. }
  2578. /**
  2579. * Get table name by model name.
  2580. *
  2581. * @param {string} modelName
  2582. * @returns {string}
  2583. */
  2584. getTableNameByModelName(modelName) {
  2585. var _a;
  2586. const modelDef = this.getService(DefinitionRegistry).getModel(modelName);
  2587. return (_a = modelDef.tableName) != null ? _a : modelName;
  2588. }
  2589. /**
  2590. * Get column name by property name.
  2591. *
  2592. * @param {string} modelName
  2593. * @param {string} propertyName
  2594. * @returns {string}
  2595. */
  2596. getColumnNameByPropertyName(modelName, propertyName) {
  2597. var _a;
  2598. const propDefs = this.getPropertiesDefinitionInBaseModelHierarchy(modelName);
  2599. const propDef = propDefs[propertyName];
  2600. if (!propDef)
  2601. throw new InvalidArgumentError2(
  2602. "The model %v does not have the property %v.",
  2603. modelName,
  2604. propertyName
  2605. );
  2606. if (propDef && typeof propDef === "object")
  2607. return (_a = propDef.columnName) != null ? _a : propertyName;
  2608. return propertyName;
  2609. }
  2610. /**
  2611. * Get default property value.
  2612. *
  2613. * @param {string} modelName
  2614. * @param {string} propertyName
  2615. * @returns {*}
  2616. */
  2617. getDefaultPropertyValue(modelName, propertyName) {
  2618. const propDefs = this.getPropertiesDefinitionInBaseModelHierarchy(modelName);
  2619. const propDef = propDefs[propertyName];
  2620. if (!propDef)
  2621. throw new InvalidArgumentError2(
  2622. "The model %v does not have the property %v.",
  2623. modelName,
  2624. propertyName
  2625. );
  2626. if (propDef && typeof propDef === "object")
  2627. return propDef.default instanceof Function ? propDef.default() : propDef.default;
  2628. }
  2629. /**
  2630. * Set default values for empty properties.
  2631. *
  2632. * @param {string} modelName
  2633. * @param {object} modelData
  2634. * @param {boolean|undefined} onlyProvidedProperties
  2635. * @returns {object}
  2636. */
  2637. setDefaultValuesToEmptyProperties(modelName, modelData, onlyProvidedProperties = false) {
  2638. const propDefs = this.getPropertiesDefinitionInBaseModelHierarchy(modelName);
  2639. const propNames = onlyProvidedProperties ? Object.keys(modelData) : Object.keys(propDefs);
  2640. const extendedData = cloneDeep(modelData);
  2641. const emptyValueDefiner = this.getService(EmptyValuesDefiner);
  2642. propNames.forEach((propName) => {
  2643. const propDef = propDefs[propName];
  2644. const propValue = extendedData[propName];
  2645. const propType = propDef != null ? this.getDataTypeFromPropertyDefinition(propDef) : DataType.ANY;
  2646. const isEmpty = emptyValueDefiner.isEmpty(propType, propValue);
  2647. if (!isEmpty) return;
  2648. if (propDef && typeof propDef === "object" && propDef.default !== void 0) {
  2649. extendedData[propName] = this.getDefaultPropertyValue(
  2650. modelName,
  2651. propName
  2652. );
  2653. }
  2654. });
  2655. return extendedData;
  2656. }
  2657. /**
  2658. * Convert property names to column names.
  2659. *
  2660. * @param {string} modelName
  2661. * @param {object} modelData
  2662. * @returns {object}
  2663. */
  2664. convertPropertyNamesToColumnNames(modelName, modelData) {
  2665. const propDefs = this.getPropertiesDefinitionInBaseModelHierarchy(modelName);
  2666. const propNames = Object.keys(propDefs);
  2667. const convertedData = cloneDeep(modelData);
  2668. propNames.forEach((propName) => {
  2669. if (!(propName in convertedData)) return;
  2670. const colName = this.getColumnNameByPropertyName(modelName, propName);
  2671. if (propName === colName) return;
  2672. const propValue = convertedData[propName];
  2673. delete convertedData[propName];
  2674. convertedData[colName] = propValue;
  2675. });
  2676. return convertedData;
  2677. }
  2678. /**
  2679. * Convert column names to property names.
  2680. *
  2681. * @param {string} modelName
  2682. * @param {object} tableData
  2683. * @returns {object}
  2684. */
  2685. convertColumnNamesToPropertyNames(modelName, tableData) {
  2686. const propDefs = this.getPropertiesDefinitionInBaseModelHierarchy(modelName);
  2687. const propNames = Object.keys(propDefs);
  2688. const convertedData = cloneDeep(tableData);
  2689. propNames.forEach((propName) => {
  2690. const colName = this.getColumnNameByPropertyName(modelName, propName);
  2691. if (!(colName in convertedData) || colName === propName) return;
  2692. const colValue = convertedData[colName];
  2693. delete convertedData[colName];
  2694. convertedData[propName] = colValue;
  2695. });
  2696. return convertedData;
  2697. }
  2698. /**
  2699. * Get data type by property name.
  2700. *
  2701. * @param {string} modelName
  2702. * @param {string} propertyName
  2703. * @returns {string}
  2704. */
  2705. getDataTypeByPropertyName(modelName, propertyName) {
  2706. const propDefs = this.getPropertiesDefinitionInBaseModelHierarchy(modelName);
  2707. const propDef = propDefs[propertyName];
  2708. if (!propDef) {
  2709. const pkPropName = this.getPrimaryKeyAsPropertyName(modelName);
  2710. if (pkPropName === propertyName) return DataType.ANY;
  2711. throw new InvalidArgumentError2(
  2712. "The model %v does not have the property %v.",
  2713. modelName,
  2714. propertyName
  2715. );
  2716. }
  2717. if (typeof propDef === "string") return propDef;
  2718. return propDef.type;
  2719. }
  2720. /**
  2721. * Get data type from property definition.
  2722. *
  2723. * @param {object} propDef
  2724. * @returns {string}
  2725. */
  2726. getDataTypeFromPropertyDefinition(propDef) {
  2727. if ((!propDef || typeof propDef !== "object") && !Object.values(DataType).includes(propDef)) {
  2728. throw new InvalidArgumentError2(
  2729. 'The argument "propDef" of the ModelDefinitionUtils.getDataTypeFromPropertyDefinition should be an Object or the DataType enum, but %v given.',
  2730. propDef
  2731. );
  2732. }
  2733. if (typeof propDef === "string") return propDef;
  2734. const dataType = propDef.type;
  2735. if (!Object.values(DataType).includes(dataType))
  2736. throw new InvalidArgumentError2(
  2737. 'The given Object to the ModelDefinitionUtils.getDataTypeFromPropertyDefinition should have the "type" property with one of values: %l, but %v given.',
  2738. Object.values(DataType),
  2739. propDef.type
  2740. );
  2741. return dataType;
  2742. }
  2743. /**
  2744. * Get own properties definition of primary keys.
  2745. *
  2746. * @param {string} modelName
  2747. * @returns {object}
  2748. */
  2749. getOwnPropertiesDefinitionOfPrimaryKeys(modelName) {
  2750. var _a;
  2751. const modelDef = this.getService(DefinitionRegistry).getModel(modelName);
  2752. const propDefs = (_a = modelDef.properties) != null ? _a : {};
  2753. const pkPropNames = Object.keys(propDefs).filter((propName) => {
  2754. const propDef = propDefs[propName];
  2755. return typeof propDef === "object" && propDef.primaryKey;
  2756. });
  2757. return pkPropNames.reduce((a, k) => ({ ...a, [k]: propDefs[k] }), {});
  2758. }
  2759. /**
  2760. * Get own properties definition without primary keys.
  2761. *
  2762. * @param {string} modelName
  2763. * @returns {object}
  2764. */
  2765. getOwnPropertiesDefinitionWithoutPrimaryKeys(modelName) {
  2766. var _a;
  2767. const modelDef = this.getService(DefinitionRegistry).getModel(modelName);
  2768. const propDefs = (_a = modelDef.properties) != null ? _a : {};
  2769. return Object.keys(propDefs).reduce((result, propName) => {
  2770. const propDef = propDefs[propName];
  2771. if (typeof propDef === "object" && propDef.primaryKey) return result;
  2772. return { ...result, [propName]: propDef };
  2773. }, {});
  2774. }
  2775. /**
  2776. * Get properties definition in base model hierarchy.
  2777. *
  2778. * @param {string} modelName
  2779. * @returns {object}
  2780. */
  2781. getPropertiesDefinitionInBaseModelHierarchy(modelName) {
  2782. let result = {};
  2783. let pkPropDefs = {};
  2784. const recursion = /* @__PURE__ */ __name((currModelName, prevModelName = void 0) => {
  2785. if (currModelName === prevModelName)
  2786. throw new InvalidArgumentError2(
  2787. "The model %v has a circular inheritance.",
  2788. currModelName
  2789. );
  2790. if (Object.keys(pkPropDefs).length === 0) {
  2791. pkPropDefs = this.getOwnPropertiesDefinitionOfPrimaryKeys(currModelName);
  2792. result = { ...result, ...pkPropDefs };
  2793. }
  2794. const regularPropDefs = this.getOwnPropertiesDefinitionWithoutPrimaryKeys(currModelName);
  2795. result = { ...regularPropDefs, ...result };
  2796. const modelDef = this.getService(DefinitionRegistry).getModel(currModelName);
  2797. if (modelDef.base) recursion(modelDef.base, currModelName);
  2798. }, "recursion");
  2799. recursion(modelName);
  2800. return result;
  2801. }
  2802. /**
  2803. * Get own relations definition.
  2804. *
  2805. * @param {string} modelName
  2806. * @returns {object}
  2807. */
  2808. getOwnRelationsDefinition(modelName) {
  2809. var _a;
  2810. const modelDef = this.getService(DefinitionRegistry).getModel(modelName);
  2811. return (_a = modelDef.relations) != null ? _a : {};
  2812. }
  2813. /**
  2814. * Get relations definition in base model hierarchy.
  2815. *
  2816. * @param {string} modelName
  2817. * @returns {object}
  2818. */
  2819. getRelationsDefinitionInBaseModelHierarchy(modelName) {
  2820. let result = {};
  2821. const recursion = /* @__PURE__ */ __name((currModelName, prevModelName = void 0) => {
  2822. var _a;
  2823. if (currModelName === prevModelName)
  2824. throw new InvalidArgumentError2(
  2825. "The model %v has a circular inheritance.",
  2826. currModelName
  2827. );
  2828. const modelDef = this.getService(DefinitionRegistry).getModel(currModelName);
  2829. const ownRelDefs = (_a = modelDef.relations) != null ? _a : {};
  2830. result = { ...ownRelDefs, ...result };
  2831. if (modelDef.base) recursion(modelDef.base, currModelName);
  2832. }, "recursion");
  2833. recursion(modelName);
  2834. return result;
  2835. }
  2836. /**
  2837. * Get relation definition by name.
  2838. *
  2839. * @param {string} modelName
  2840. * @param {string} relationName
  2841. * @returns {object}
  2842. */
  2843. getRelationDefinitionByName(modelName, relationName) {
  2844. const relDefs = this.getRelationsDefinitionInBaseModelHierarchy(modelName);
  2845. const relNames = Object.keys(relDefs);
  2846. let foundDef;
  2847. for (const relName of relNames) {
  2848. if (relName === relationName) {
  2849. foundDef = relDefs[relName];
  2850. break;
  2851. }
  2852. }
  2853. if (!foundDef)
  2854. throw new InvalidArgumentError2(
  2855. "The model %v does not have relation name %v.",
  2856. modelName,
  2857. relationName
  2858. );
  2859. return foundDef;
  2860. }
  2861. /**
  2862. * Exclude object keys by relation names.
  2863. *
  2864. * @param {string} modelName
  2865. * @param {object} modelData
  2866. * @returns {object}
  2867. */
  2868. excludeObjectKeysByRelationNames(modelName, modelData) {
  2869. if (!modelData || typeof modelData !== "object" || Array.isArray(modelData))
  2870. throw new InvalidArgumentError2(
  2871. "The second argument of ModelDefinitionUtils.excludeObjectKeysByRelationNames should be an Object, but %v given.",
  2872. modelData
  2873. );
  2874. const relDefs = this.getRelationsDefinitionInBaseModelHierarchy(modelName);
  2875. const relNames = Object.keys(relDefs);
  2876. return excludeObjectKeys(modelData, relNames);
  2877. }
  2878. };
  2879. __name(_ModelDefinitionUtils, "ModelDefinitionUtils");
  2880. ModelDefinitionUtils = _ModelDefinitionUtils;
  2881. }
  2882. });
  2883. // src/definition/model/properties/property-uniqueness-validator.js
  2884. var _PropertyUniquenessValidator, PropertyUniquenessValidator;
  2885. var init_property_uniqueness_validator = __esm({
  2886. "src/definition/model/properties/property-uniqueness-validator.js"() {
  2887. "use strict";
  2888. init_data_type();
  2889. init_src2();
  2890. init_utils2();
  2891. init_property_uniqueness();
  2892. init_empty_values_definer();
  2893. init_errors2();
  2894. init_model_definition_utils();
  2895. _PropertyUniquenessValidator = class _PropertyUniquenessValidator extends Service {
  2896. /**
  2897. * Validate.
  2898. *
  2899. * @param {Function} countMethod
  2900. * @param {string} methodName
  2901. * @param {string} modelName
  2902. * @param {object} modelData
  2903. * @param {*} modelId
  2904. * @returns {Promise<undefined>}
  2905. */
  2906. async validate(countMethod, methodName, modelName, modelData, modelId = void 0) {
  2907. if (typeof countMethod !== "function")
  2908. throw new InvalidArgumentError2(
  2909. 'The parameter "countMethod" of the PropertyUniquenessValidator must be a Function, but %v given.',
  2910. countMethod
  2911. );
  2912. if (!methodName || typeof methodName !== "string")
  2913. throw new InvalidArgumentError2(
  2914. 'The parameter "methodName" of the PropertyUniquenessValidator must be a non-empty String, but %v given.',
  2915. methodName
  2916. );
  2917. if (!modelName || typeof modelName !== "string")
  2918. throw new InvalidArgumentError2(
  2919. 'The parameter "modelName" of the PropertyUniquenessValidator must be a non-empty String, but %v given.',
  2920. modelName
  2921. );
  2922. if (!isPureObject(modelData))
  2923. throw new InvalidArgumentError2(
  2924. "The data of the model %v should be an Object, but %v given.",
  2925. modelName,
  2926. modelData
  2927. );
  2928. const propDefs = this.getService(
  2929. ModelDefinitionUtils
  2930. ).getPropertiesDefinitionInBaseModelHierarchy(modelName);
  2931. const isPartial = methodName === "patch" || methodName === "patchById";
  2932. const propNames = Object.keys(isPartial ? modelData : propDefs);
  2933. const idProp = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  2934. modelName
  2935. );
  2936. const createError = /* @__PURE__ */ __name((propName, propValue) => new InvalidArgumentError2(
  2937. "An existing document of the model %v already has the property %v with the value %v and should be unique.",
  2938. modelName,
  2939. propName,
  2940. propValue
  2941. ), "createError");
  2942. let willBeReplaced = void 0;
  2943. const emptyValuesDefiner = this.getService(EmptyValuesDefiner);
  2944. for (const propName of propNames) {
  2945. const propDef = propDefs[propName];
  2946. if (!propDef || typeof propDef === "string" || !propDef.unique || propDef.unique === PropertyUniqueness.NON_UNIQUE) {
  2947. continue;
  2948. }
  2949. const propValue = modelData[propName];
  2950. if (propDef.unique === PropertyUniqueness.SPARSE) {
  2951. const propType = propDef.type || DataType.ANY;
  2952. const isEmpty = emptyValuesDefiner.isEmpty(propType, propValue);
  2953. if (isEmpty) continue;
  2954. }
  2955. if (methodName === "create") {
  2956. const count = await countMethod({ [propName]: propValue });
  2957. if (count > 0) throw createError(propName, propValue);
  2958. } else if (methodName === "replaceById") {
  2959. const count = await countMethod({
  2960. [idProp]: { neq: modelId },
  2961. [propName]: propValue
  2962. });
  2963. if (count > 0) throw createError(propName, propValue);
  2964. } else if (methodName === "replaceOrCreate") {
  2965. const idFromData = modelData[idProp];
  2966. if (willBeReplaced == null && idFromData != null) {
  2967. const count = await countMethod({ [idProp]: idFromData });
  2968. willBeReplaced = count > 0;
  2969. }
  2970. if (willBeReplaced) {
  2971. const count = await countMethod({
  2972. [idProp]: { neq: idFromData },
  2973. [propName]: propValue
  2974. });
  2975. if (count > 0) throw createError(propName, propValue);
  2976. } else {
  2977. const count = await countMethod({ [propName]: propValue });
  2978. if (count > 0) throw createError(propName, propValue);
  2979. }
  2980. } else if (methodName === "patch") {
  2981. const count = await countMethod({ [propName]: propValue });
  2982. if (count > 0) throw createError(propName, propValue);
  2983. } else if (methodName === "patchById") {
  2984. const count = await countMethod({
  2985. [idProp]: { neq: modelId },
  2986. [propName]: propValue
  2987. });
  2988. if (count > 0) throw createError(propName, propValue);
  2989. } else {
  2990. throw new InvalidArgumentError2(
  2991. "The PropertyUniquenessValidator does not support the adapter method %v.",
  2992. methodName
  2993. );
  2994. }
  2995. }
  2996. }
  2997. };
  2998. __name(_PropertyUniquenessValidator, "PropertyUniquenessValidator");
  2999. PropertyUniquenessValidator = _PropertyUniquenessValidator;
  3000. }
  3001. });
  3002. // src/definition/model/properties/primary-keys-definition-validator.js
  3003. var _PrimaryKeysDefinitionValidator, PrimaryKeysDefinitionValidator;
  3004. var init_primary_keys_definition_validator = __esm({
  3005. "src/definition/model/properties/primary-keys-definition-validator.js"() {
  3006. "use strict";
  3007. init_src2();
  3008. init_errors2();
  3009. init_model_definition_utils();
  3010. _PrimaryKeysDefinitionValidator = class _PrimaryKeysDefinitionValidator extends Service {
  3011. /**
  3012. * Validate.
  3013. *
  3014. * @param {string} modelName
  3015. * @param {object} propDefs
  3016. */
  3017. validate(modelName, propDefs) {
  3018. const propNames = Object.keys(propDefs).filter((propName) => {
  3019. const propDef = propDefs[propName];
  3020. return propDef && typeof propDef === "object" && propDef.primaryKey;
  3021. });
  3022. if (propNames.length < 1) {
  3023. const isDefaultPrimaryKeyAlreadyInUse = Object.keys(propDefs).includes(DEFAULT_PRIMARY_KEY_PROPERTY_NAME);
  3024. if (isDefaultPrimaryKeyAlreadyInUse)
  3025. throw new InvalidArgumentError2(
  3026. 'The property name %v of the model %v is defined as a regular property. In this case, a primary key should be defined explicitly. Do use the option "primaryKey" to specify the primary key.',
  3027. DEFAULT_PRIMARY_KEY_PROPERTY_NAME,
  3028. modelName
  3029. );
  3030. return;
  3031. }
  3032. if (propNames.length > 1)
  3033. throw new InvalidArgumentError2(
  3034. "The model definition %v should not have multiple primary keys, but %v keys given.",
  3035. modelName,
  3036. propNames.length
  3037. );
  3038. const pkPropName = propNames[0];
  3039. const pkPropDef = propDefs[pkPropName];
  3040. if (pkPropDef && typeof pkPropDef === "object" && pkPropDef.default !== void 0) {
  3041. throw new InvalidArgumentError2(
  3042. "Do not specify a default value for the primary key %v of the model %v.",
  3043. pkPropName,
  3044. modelName
  3045. );
  3046. }
  3047. }
  3048. };
  3049. __name(_PrimaryKeysDefinitionValidator, "PrimaryKeysDefinitionValidator");
  3050. PrimaryKeysDefinitionValidator = _PrimaryKeysDefinitionValidator;
  3051. }
  3052. });
  3053. // src/definition/model/properties/properties-definition-validator.js
  3054. var _PropertiesDefinitionValidator, PropertiesDefinitionValidator;
  3055. var init_properties_definition_validator = __esm({
  3056. "src/definition/model/properties/properties-definition-validator.js"() {
  3057. "use strict";
  3058. init_src2();
  3059. init_data_type();
  3060. init_utils2();
  3061. init_property_uniqueness();
  3062. init_errors2();
  3063. init_property_validator2();
  3064. init_property_transformer2();
  3065. init_primary_keys_definition_validator();
  3066. _PropertiesDefinitionValidator = class _PropertiesDefinitionValidator extends Service {
  3067. /**
  3068. * Validate.
  3069. *
  3070. * @param {string} modelName
  3071. * @param {object} propDefs
  3072. */
  3073. validate(modelName, propDefs) {
  3074. if (!modelName || typeof modelName !== "string")
  3075. throw new InvalidArgumentError2(
  3076. "The first argument of PropertiesDefinitionValidator.validate should be a non-empty String, but %v given.",
  3077. modelName
  3078. );
  3079. if (!propDefs || typeof propDefs !== "object" || Array.isArray(propDefs)) {
  3080. throw new InvalidArgumentError2(
  3081. 'The provided option "properties" of the model %v should be an Object, but %v given.',
  3082. modelName,
  3083. propDefs
  3084. );
  3085. }
  3086. const propNames = Object.keys(propDefs);
  3087. propNames.forEach((propName) => {
  3088. const propDef = propDefs[propName];
  3089. this._validateProperty(modelName, propName, propDef);
  3090. });
  3091. this.getService(PrimaryKeysDefinitionValidator).validate(
  3092. modelName,
  3093. propDefs
  3094. );
  3095. }
  3096. /**
  3097. * Validate property.
  3098. *
  3099. * @param {string} modelName
  3100. * @param {string} propName
  3101. * @param {object} propDef
  3102. */
  3103. _validateProperty(modelName, propName, propDef) {
  3104. if (!modelName || typeof modelName !== "string")
  3105. throw new InvalidArgumentError2(
  3106. "The first argument of PropertiesDefinitionValidator._validateProperty should be a non-empty String, but %v given.",
  3107. modelName
  3108. );
  3109. if (!propName || typeof propName !== "string")
  3110. throw new InvalidArgumentError2(
  3111. "The property name of the model %v should be a non-empty String, but %v given.",
  3112. modelName,
  3113. propName
  3114. );
  3115. if (!propDef)
  3116. throw new InvalidArgumentError2(
  3117. "The property %v of the model %v should have a property definition, but %v given.",
  3118. propName,
  3119. modelName,
  3120. propDef
  3121. );
  3122. if (typeof propDef === "string") {
  3123. if (!Object.values(DataType).includes(propDef))
  3124. throw new InvalidArgumentError2(
  3125. "In case of a short property definition, the property %v of the model %v should have one of data types: %l, but %v given.",
  3126. propName,
  3127. modelName,
  3128. Object.values(DataType),
  3129. propDef
  3130. );
  3131. return;
  3132. }
  3133. if (!propDef || typeof propDef !== "object" || Array.isArray(propDef)) {
  3134. throw new InvalidArgumentError2(
  3135. "In case of a full property definition, the property %v of the model %v should be an Object, but %v given.",
  3136. propName,
  3137. modelName,
  3138. propDef
  3139. );
  3140. }
  3141. if (!propDef.type || !Object.values(DataType).includes(propDef.type))
  3142. throw new InvalidArgumentError2(
  3143. 'The property %v of the model %v requires the option "type" to have one of data types: %l, but %v given.',
  3144. propName,
  3145. modelName,
  3146. Object.values(DataType),
  3147. propDef.type
  3148. );
  3149. if (propDef.itemType && !Object.values(DataType).includes(propDef.itemType)) {
  3150. throw new InvalidArgumentError2(
  3151. 'The provided option "itemType" of the property %v in the model %v should have one of data types: %l, but %v given.',
  3152. propName,
  3153. modelName,
  3154. Object.values(DataType),
  3155. propDef.itemType
  3156. );
  3157. }
  3158. if (propDef.model && typeof propDef.model !== "string")
  3159. throw new InvalidArgumentError2(
  3160. 'The provided option "model" of the property %v in the model %v should be a String, but %v given.',
  3161. propName,
  3162. modelName,
  3163. propDef.model
  3164. );
  3165. if (propDef.primaryKey && typeof propDef.primaryKey !== "boolean")
  3166. throw new InvalidArgumentError2(
  3167. 'The provided option "primaryKey" of the property %v in the model %v should be a Boolean, but %v given.',
  3168. propName,
  3169. modelName,
  3170. propDef.primaryKey
  3171. );
  3172. if (propDef.columnName && typeof propDef.columnName !== "string")
  3173. throw new InvalidArgumentError2(
  3174. 'The provided option "columnName" of the property %v in the model %v should be a String, but %v given.',
  3175. propName,
  3176. modelName,
  3177. propDef.columnName
  3178. );
  3179. if (propDef.columnType && typeof propDef.columnType !== "string")
  3180. throw new InvalidArgumentError2(
  3181. 'The provided option "columnType" of the property %v in the model %v should be a String, but %v given.',
  3182. propName,
  3183. modelName,
  3184. propDef.columnType
  3185. );
  3186. if (propDef.required && typeof propDef.required !== "boolean")
  3187. throw new InvalidArgumentError2(
  3188. 'The provided option "required" of the property %v in the model %v should be a Boolean, but %v given.',
  3189. propName,
  3190. modelName,
  3191. propDef.required
  3192. );
  3193. if (propDef.required && propDef.default !== void 0)
  3194. throw new InvalidArgumentError2(
  3195. 'The property %v of the model %v is a required property, so it should not have the option "default" to be provided.',
  3196. propName,
  3197. modelName
  3198. );
  3199. if (propDef.primaryKey && propDef.required)
  3200. throw new InvalidArgumentError2(
  3201. 'The property %v of the model %v is a primary key, so it should not have the option "required" to be provided.',
  3202. propName,
  3203. modelName
  3204. );
  3205. if (propDef.primaryKey && propDef.default !== void 0)
  3206. throw new InvalidArgumentError2(
  3207. 'The property %v of the model %v is a primary key, so it should not have the option "default" to be provided.',
  3208. propName,
  3209. modelName
  3210. );
  3211. if (propDef.itemType && propDef.type !== DataType.ARRAY)
  3212. throw new InvalidArgumentError2(
  3213. 'The property %v of the model %v has the non-array type, so it should not have the option "itemType" to be provided.',
  3214. propName,
  3215. modelName,
  3216. propDef.type
  3217. );
  3218. if (propDef.model && propDef.type !== DataType.OBJECT && propDef.itemType !== DataType.OBJECT) {
  3219. if (propDef.type !== DataType.ARRAY) {
  3220. throw new InvalidArgumentError2(
  3221. 'The option "model" is not supported for %s property type, so the property %v of the model %v should not have the option "model" to be provided.',
  3222. capitalize(propDef.type),
  3223. propName,
  3224. modelName
  3225. );
  3226. } else {
  3227. throw new InvalidArgumentError2(
  3228. 'The option "model" is not supported for Array property type of %s, so the property %v of the model %v should not have the option "model" to be provided.',
  3229. capitalize(propDef.itemType),
  3230. propName,
  3231. modelName
  3232. );
  3233. }
  3234. }
  3235. if (propDef.validate != null) {
  3236. const propertyValidatorRegistry = this.getService(
  3237. PropertyValidatorRegistry
  3238. );
  3239. if (propDef.validate && typeof propDef.validate === "string") {
  3240. if (!propertyValidatorRegistry.hasValidator(propDef.validate))
  3241. throw new InvalidArgumentError2(
  3242. "The property validator %v is not found.",
  3243. propDef.validate
  3244. );
  3245. } else if (Array.isArray(propDef.validate)) {
  3246. for (const validatorName of propDef.validate) {
  3247. if (typeof validatorName !== "string")
  3248. throw new InvalidArgumentError2(
  3249. 'The provided option "validate" of the property %v in the model %v has an Array value that should have a non-empty String, but %v given.',
  3250. propName,
  3251. modelName,
  3252. validatorName
  3253. );
  3254. if (!propertyValidatorRegistry.hasValidator(validatorName))
  3255. throw new InvalidArgumentError2(
  3256. "The property validator %v is not found.",
  3257. validatorName
  3258. );
  3259. }
  3260. } else if (typeof propDef.validate === "object") {
  3261. for (const validatorName in propDef.validate) {
  3262. if (!propertyValidatorRegistry.hasValidator(validatorName))
  3263. throw new InvalidArgumentError2(
  3264. "The property validator %v is not found.",
  3265. validatorName
  3266. );
  3267. }
  3268. } else {
  3269. throw new InvalidArgumentError2(
  3270. 'The provided option "validate" of the property %v in the model %v should be a non-empty String, an Array of String or an Object, but %v given.',
  3271. propName,
  3272. modelName,
  3273. propDef.validate
  3274. );
  3275. }
  3276. }
  3277. if (propDef.transform != null) {
  3278. const propertyTransformerRegistry = this.getService(
  3279. PropertyTransformerRegistry
  3280. );
  3281. if (propDef.transform && typeof propDef.transform === "string") {
  3282. if (!propertyTransformerRegistry.hasTransformer(propDef.transform))
  3283. throw new InvalidArgumentError2(
  3284. "The property transformer %v is not found.",
  3285. propDef.transform
  3286. );
  3287. } else if (Array.isArray(propDef.transform)) {
  3288. for (const transformerName of propDef.transform) {
  3289. if (typeof transformerName !== "string")
  3290. throw new InvalidArgumentError2(
  3291. 'The provided option "transform" of the property %v in the model %v has an Array value that should have a non-empty String, but %v given.',
  3292. propName,
  3293. modelName,
  3294. transformerName
  3295. );
  3296. if (!propertyTransformerRegistry.hasTransformer(transformerName))
  3297. throw new InvalidArgumentError2(
  3298. "The property transformer %v is not found.",
  3299. transformerName
  3300. );
  3301. }
  3302. } else if (typeof propDef.transform === "object") {
  3303. for (const transformerName in propDef.transform) {
  3304. if (!propertyTransformerRegistry.hasTransformer(transformerName))
  3305. throw new InvalidArgumentError2(
  3306. "The property transformer %v is not found.",
  3307. transformerName
  3308. );
  3309. }
  3310. } else {
  3311. throw new InvalidArgumentError2(
  3312. 'The provided option "transform" of the property %v in the model %v should be a non-empty String, an Array of String or an Object, but %v given.',
  3313. propName,
  3314. modelName,
  3315. propDef.transform
  3316. );
  3317. }
  3318. }
  3319. if (propDef.unique) {
  3320. if (typeof propDef.unique !== "boolean" && !Object.values(PropertyUniqueness).includes(propDef.unique)) {
  3321. throw new InvalidArgumentError2(
  3322. 'The provided option "unique" of the property %v in the model %v should be a Boolean or one of values: %l, but %v given.',
  3323. propName,
  3324. modelName,
  3325. Object.values(PropertyUniqueness),
  3326. propDef.unique
  3327. );
  3328. }
  3329. }
  3330. if (propDef.unique && propDef.primaryKey)
  3331. throw new InvalidArgumentError2(
  3332. 'The property %v of the model %v is a primary key, so it should not have the option "unique" to be provided.',
  3333. propName,
  3334. modelName
  3335. );
  3336. }
  3337. };
  3338. __name(_PropertiesDefinitionValidator, "PropertiesDefinitionValidator");
  3339. PropertiesDefinitionValidator = _PropertiesDefinitionValidator;
  3340. }
  3341. });
  3342. // src/definition/model/properties/index.js
  3343. var init_properties = __esm({
  3344. "src/definition/model/properties/index.js"() {
  3345. "use strict";
  3346. init_data_type();
  3347. init_property_definition();
  3348. init_property_uniqueness();
  3349. init_empty_values_definer();
  3350. init_property_validator2();
  3351. init_property_transformer2();
  3352. init_property_uniqueness_validator();
  3353. init_properties_definition_validator();
  3354. init_primary_keys_definition_validator();
  3355. }
  3356. });
  3357. // src/definition/model/model-definition.js
  3358. var init_model_definition = __esm({
  3359. "src/definition/model/model-definition.js"() {
  3360. "use strict";
  3361. }
  3362. });
  3363. // src/definition/model/model-data-validator.js
  3364. var _ModelDataValidator, ModelDataValidator;
  3365. var init_model_data_validator = __esm({
  3366. "src/definition/model/model-data-validator.js"() {
  3367. "use strict";
  3368. init_src2();
  3369. init_properties();
  3370. init_utils2();
  3371. init_utils2();
  3372. init_properties();
  3373. init_errors2();
  3374. init_properties();
  3375. init_model_definition_utils();
  3376. _ModelDataValidator = class _ModelDataValidator extends Service {
  3377. /**
  3378. * Validate.
  3379. *
  3380. * @param {string} modelName
  3381. * @param {object} modelData
  3382. * @param {boolean} isPartial
  3383. * @returns {undefined}
  3384. */
  3385. validate(modelName, modelData, isPartial = false) {
  3386. if (!isPureObject(modelData))
  3387. throw new InvalidArgumentError2(
  3388. "The data of the model %v should be an Object, but %v given.",
  3389. modelName,
  3390. modelData
  3391. );
  3392. const propDefs = this.getService(
  3393. ModelDefinitionUtils
  3394. ).getPropertiesDefinitionInBaseModelHierarchy(modelName);
  3395. const propNames = Object.keys(isPartial ? modelData : propDefs);
  3396. propNames.forEach((propName) => {
  3397. const propDef = propDefs[propName];
  3398. if (!propDef) return;
  3399. this._validatePropertyValue(
  3400. modelName,
  3401. propName,
  3402. propDef,
  3403. modelData[propName]
  3404. );
  3405. });
  3406. }
  3407. /**
  3408. * Validate property value.
  3409. *
  3410. * @param {string} modelName
  3411. * @param {string} propName
  3412. * @param {string|object} propDef
  3413. * @param {*} propValue
  3414. * @returns {undefined}
  3415. */
  3416. _validatePropertyValue(modelName, propName, propDef, propValue) {
  3417. const propType = this.getService(ModelDefinitionUtils).getDataTypeFromPropertyDefinition(
  3418. propDef
  3419. );
  3420. const isEmpty = this.getService(EmptyValuesDefiner).isEmpty(
  3421. propType,
  3422. propValue
  3423. );
  3424. if (isEmpty) {
  3425. const isRequired = typeof propDef === "string" ? false : Boolean(propDef.required);
  3426. if (!isRequired) return;
  3427. throw new InvalidArgumentError2(
  3428. "The property %v of the model %v is required, but %v given.",
  3429. propName,
  3430. modelName,
  3431. propValue
  3432. );
  3433. }
  3434. this._validateValueByPropertyValidators(
  3435. modelName,
  3436. propName,
  3437. propDef,
  3438. propValue
  3439. );
  3440. this._validateValueByPropertyType(modelName, propName, propDef, propValue);
  3441. }
  3442. /**
  3443. * Validate value by property type.
  3444. *
  3445. * @param {string} modelName
  3446. * @param {string} propName
  3447. * @param {string|object} propDef
  3448. * @param {*} propValue
  3449. * @param {boolean} isArrayValue
  3450. * @returns {undefined}
  3451. */
  3452. _validateValueByPropertyType(modelName, propName, propDef, propValue, isArrayValue = false) {
  3453. var _a;
  3454. let expectingType;
  3455. if (isArrayValue) {
  3456. if (typeof propDef === "object") {
  3457. expectingType = (_a = propDef.itemType) != null ? _a : DataType.ANY;
  3458. } else {
  3459. expectingType = DataType.ANY;
  3460. }
  3461. } else {
  3462. expectingType = typeof propDef !== "string" ? propDef.type : propDef;
  3463. }
  3464. const createError = /* @__PURE__ */ __name((expected) => {
  3465. const pattern = isArrayValue ? "The array property %v of the model %v must have %s element, but %s given." : "The property %v of the model %v must have %s, but %s given.";
  3466. const ctorName = getCtorName(propValue);
  3467. const givenStr = ctorName != null ? ctorName : typeof propValue;
  3468. return new InvalidArgumentError2(
  3469. pattern,
  3470. propName,
  3471. modelName,
  3472. expected,
  3473. givenStr
  3474. );
  3475. }, "createError");
  3476. switch (expectingType) {
  3477. // STRING
  3478. case DataType.STRING:
  3479. if (typeof propValue !== "string") throw createError("a String");
  3480. break;
  3481. // NUMBER
  3482. case DataType.NUMBER:
  3483. if (typeof propValue !== "number") throw createError("a Number");
  3484. break;
  3485. // BOOLEAN
  3486. case DataType.BOOLEAN:
  3487. if (typeof propValue !== "boolean") throw createError("a Boolean");
  3488. break;
  3489. // ARRAY
  3490. case DataType.ARRAY:
  3491. if (!Array.isArray(propValue)) throw createError("an Array");
  3492. propValue.forEach(
  3493. (value) => this._validateValueByPropertyType(
  3494. modelName,
  3495. propName,
  3496. propDef,
  3497. value,
  3498. true
  3499. )
  3500. );
  3501. break;
  3502. // OBJECT
  3503. case DataType.OBJECT:
  3504. if (!isPureObject(propValue)) throw createError("an Object");
  3505. if (typeof propDef === "object" && propDef.model)
  3506. this.validate(propDef.model, propValue);
  3507. break;
  3508. }
  3509. }
  3510. /**
  3511. * Validate value by property validators.
  3512. *
  3513. * @param {string} modelName
  3514. * @param {string} propName
  3515. * @param {string|object} propDef
  3516. * @param {*} propValue
  3517. * @returns {undefined}
  3518. */
  3519. _validateValueByPropertyValidators(modelName, propName, propDef, propValue) {
  3520. if (typeof propDef === "string" || propDef.validate == null) return;
  3521. const validateDef = propDef.validate;
  3522. const validatorRegistry = this.getService(PropertyValidatorRegistry);
  3523. const createError = /* @__PURE__ */ __name((validatorName) => new InvalidArgumentError2(
  3524. "The property %v of the model %v has an invalid value %v that caught by the validator %v.",
  3525. propName,
  3526. modelName,
  3527. propValue,
  3528. validatorName
  3529. ), "createError");
  3530. const validateBy = /* @__PURE__ */ __name((validatorName, validatorOptions = void 0) => {
  3531. const validator = validatorRegistry.getValidator(validatorName);
  3532. const context = { validatorName, modelName, propName };
  3533. const valid = validator(propValue, validatorOptions, context);
  3534. if (valid instanceof Promise) {
  3535. throw new InvalidArgumentError2(
  3536. "Asynchronous property validators are not supported, but the property validator %v returns a Promise.",
  3537. validatorName
  3538. );
  3539. } else if (valid !== true) {
  3540. throw createError(validatorName);
  3541. }
  3542. }, "validateBy");
  3543. if (validateDef && typeof validateDef === "string") {
  3544. validateBy(validateDef);
  3545. } else if (Array.isArray(validateDef)) {
  3546. validateDef.forEach((validatorName) => validateBy(validatorName));
  3547. } else if (validateDef !== null && typeof validateDef === "object") {
  3548. Object.keys(validateDef).forEach((validatorName) => {
  3549. if (Object.prototype.hasOwnProperty.call(validateDef, validatorName)) {
  3550. const validatorOptions = validateDef[validatorName];
  3551. validateBy(validatorName, validatorOptions);
  3552. }
  3553. });
  3554. } else {
  3555. throw new InvalidArgumentError2(
  3556. 'The provided option "validate" of the property %v in the model %v should be a non-empty String, an Array of String or an Object, but %v given.',
  3557. propName,
  3558. modelName,
  3559. validateDef
  3560. );
  3561. }
  3562. }
  3563. };
  3564. __name(_ModelDataValidator, "ModelDataValidator");
  3565. ModelDataValidator = _ModelDataValidator;
  3566. }
  3567. });
  3568. // src/definition/model/model-data-sanitizer.js
  3569. var _ModelDataSanitizer, ModelDataSanitizer;
  3570. var init_model_data_sanitizer = __esm({
  3571. "src/definition/model/model-data-sanitizer.js"() {
  3572. "use strict";
  3573. init_src2();
  3574. init_errors2();
  3575. init_model_definition_utils();
  3576. _ModelDataSanitizer = class _ModelDataSanitizer extends Service {
  3577. /**
  3578. * Validate.
  3579. *
  3580. * @param {string} modelName
  3581. * @param {object} modelData
  3582. * @returns {object}
  3583. */
  3584. sanitize(modelName, modelData) {
  3585. if (!modelName || typeof modelName !== "string")
  3586. throw new InvalidArgumentError2(
  3587. "The first argument of ModelDataSanitizer.sanitize should be a string, but %v given.",
  3588. modelName
  3589. );
  3590. if (!modelData || typeof modelData !== "object")
  3591. throw new InvalidArgumentError2(
  3592. "The second argument of ModelDataSanitizer.sanitize should be an Object, but %v given.",
  3593. modelData
  3594. );
  3595. return this.getService(
  3596. ModelDefinitionUtils
  3597. ).excludeObjectKeysByRelationNames(modelName, modelData);
  3598. }
  3599. };
  3600. __name(_ModelDataSanitizer, "ModelDataSanitizer");
  3601. ModelDataSanitizer = _ModelDataSanitizer;
  3602. }
  3603. });
  3604. // src/definition/model/model-data-transformer.js
  3605. var _ModelDataTransformer, ModelDataTransformer;
  3606. var init_model_data_transformer = __esm({
  3607. "src/definition/model/model-data-transformer.js"() {
  3608. "use strict";
  3609. init_src2();
  3610. init_utils2();
  3611. init_utils2();
  3612. init_utils2();
  3613. init_properties();
  3614. init_errors2();
  3615. init_model_definition_utils();
  3616. init_properties();
  3617. _ModelDataTransformer = class _ModelDataTransformer extends Service {
  3618. /**
  3619. * Transform.
  3620. *
  3621. * @param {string} modelName
  3622. * @param {object} modelData
  3623. * @param {boolean} isPartial
  3624. * @returns {object|Promise<object>}
  3625. */
  3626. transform(modelName, modelData, isPartial = false) {
  3627. if (!isPureObject(modelData))
  3628. throw new InvalidArgumentError2(
  3629. "The data of the model %v should be an Object, but %v given.",
  3630. modelName,
  3631. modelData
  3632. );
  3633. const emptyValuesDefiner = this.getService(EmptyValuesDefiner);
  3634. const modelDefinitionUtils = this.getService(ModelDefinitionUtils);
  3635. const propDefs = modelDefinitionUtils.getPropertiesDefinitionInBaseModelHierarchy(
  3636. modelName
  3637. );
  3638. const propNames = Object.keys(isPartial ? modelData : propDefs);
  3639. const transformedData = cloneDeep(modelData);
  3640. return propNames.reduce((transformedDataOrPromise, propName) => {
  3641. const propDef = propDefs[propName];
  3642. if (!propDef) return transformedDataOrPromise;
  3643. const propType = modelDefinitionUtils.getDataTypeFromPropertyDefinition(propDef);
  3644. const propValue = modelData[propName];
  3645. const isEmpty = emptyValuesDefiner.isEmpty(propType, propValue);
  3646. if (isEmpty) return transformedDataOrPromise;
  3647. const newPropValueOrPromise = this._transformPropertyValue(
  3648. modelName,
  3649. propName,
  3650. propDef,
  3651. propValue
  3652. );
  3653. return transformPromise(newPropValueOrPromise, (newPropValue) => {
  3654. return transformPromise(transformedDataOrPromise, (resolvedData) => {
  3655. if (newPropValue !== propValue) resolvedData[propName] = newPropValue;
  3656. return resolvedData;
  3657. });
  3658. });
  3659. }, transformedData);
  3660. }
  3661. /**
  3662. * Transform property value.
  3663. *
  3664. * @param {string} modelName
  3665. * @param {string} propName
  3666. * @param {string|object} propDef
  3667. * @param {*} propValue
  3668. * @returns {*}
  3669. */
  3670. _transformPropertyValue(modelName, propName, propDef, propValue) {
  3671. if (typeof propDef === "string" || propDef.transform == null)
  3672. return propValue;
  3673. const transformDef = propDef.transform;
  3674. const transformerRegistry = this.getService(PropertyTransformerRegistry);
  3675. const transformFn = /* @__PURE__ */ __name((value, transformerName, transformerOptions = void 0) => {
  3676. const transformer = transformerRegistry.getTransformer(transformerName);
  3677. const context = { transformerName, modelName, propName };
  3678. return transformer(value, transformerOptions, context);
  3679. }, "transformFn");
  3680. if (transformDef && typeof transformDef === "string") {
  3681. return transformFn(propValue, transformDef);
  3682. } else if (Array.isArray(transformDef)) {
  3683. return transformDef.reduce((valueOrPromise, transformerName) => {
  3684. return transformPromise(valueOrPromise, (value) => {
  3685. return transformFn(value, transformerName);
  3686. });
  3687. }, propValue);
  3688. } else if (transformDef !== null && typeof transformDef === "object") {
  3689. return Object.keys(transformDef).reduce(
  3690. (valueOrPromise, transformerName) => {
  3691. const transformerOptions = transformDef[transformerName];
  3692. return transformPromise(valueOrPromise, (value) => {
  3693. return transformFn(value, transformerName, transformerOptions);
  3694. });
  3695. },
  3696. propValue
  3697. );
  3698. } else {
  3699. throw new InvalidArgumentError2(
  3700. 'The provided option "transform" of the property %v in the model %v should be a non-empty String, an Array of String or an Object, but %v given.',
  3701. propName,
  3702. modelName,
  3703. transformDef
  3704. );
  3705. }
  3706. }
  3707. };
  3708. __name(_ModelDataTransformer, "ModelDataTransformer");
  3709. ModelDataTransformer = _ModelDataTransformer;
  3710. }
  3711. });
  3712. // src/definition/model/model-definition-validator.js
  3713. var _ModelDefinitionValidator, ModelDefinitionValidator;
  3714. var init_model_definition_validator = __esm({
  3715. "src/definition/model/model-definition-validator.js"() {
  3716. "use strict";
  3717. init_src2();
  3718. init_errors2();
  3719. init_relations();
  3720. init_properties();
  3721. _ModelDefinitionValidator = class _ModelDefinitionValidator extends Service {
  3722. /**
  3723. * Validate.
  3724. *
  3725. * @param {object} modelDef
  3726. */
  3727. validate(modelDef) {
  3728. if (!modelDef || typeof modelDef !== "object" || Array.isArray(modelDef))
  3729. throw new InvalidArgumentError2(
  3730. "The model definition should be an Object, but %v given.",
  3731. modelDef
  3732. );
  3733. if (!modelDef.name || typeof modelDef.name !== "string")
  3734. throw new InvalidArgumentError2(
  3735. 'The model definition requires the option "name" as a non-empty String, but %v given.',
  3736. modelDef.name
  3737. );
  3738. if (modelDef.datasource && typeof modelDef.datasource !== "string")
  3739. throw new InvalidArgumentError2(
  3740. 'The provided option "datasource" of the model %v should be a String, but %v given.',
  3741. modelDef.name,
  3742. modelDef.datasource
  3743. );
  3744. if (modelDef.base && typeof modelDef.base !== "string")
  3745. throw new InvalidArgumentError2(
  3746. 'The provided option "base" of the model %v should be a String, but %v given.',
  3747. modelDef.name,
  3748. modelDef.base
  3749. );
  3750. if (modelDef.tableName && typeof modelDef.tableName !== "string")
  3751. throw new InvalidArgumentError2(
  3752. 'The provided option "tableName" of the model %v should be a String, but %v given.',
  3753. modelDef.name,
  3754. modelDef.tableName
  3755. );
  3756. if (modelDef.properties) {
  3757. if (typeof modelDef.properties !== "object" || Array.isArray(modelDef.properties)) {
  3758. throw new InvalidArgumentError2(
  3759. 'The provided option "properties" of the model %v should be an Object, but %v given.',
  3760. modelDef.name,
  3761. modelDef.properties
  3762. );
  3763. }
  3764. this.getService(PropertiesDefinitionValidator).validate(
  3765. modelDef.name,
  3766. modelDef.properties
  3767. );
  3768. }
  3769. if (modelDef.relations) {
  3770. if (typeof modelDef.relations !== "object" || Array.isArray(modelDef.relations)) {
  3771. throw new InvalidArgumentError2(
  3772. 'The provided option "relations" of the model %v should be an Object, but %v given.',
  3773. modelDef.name,
  3774. modelDef.relations
  3775. );
  3776. }
  3777. this.getService(RelationsDefinitionValidator).validate(
  3778. modelDef.name,
  3779. modelDef.relations
  3780. );
  3781. }
  3782. }
  3783. };
  3784. __name(_ModelDefinitionValidator, "ModelDefinitionValidator");
  3785. ModelDefinitionValidator = _ModelDefinitionValidator;
  3786. }
  3787. });
  3788. // src/definition/model/index.js
  3789. var init_model = __esm({
  3790. "src/definition/model/index.js"() {
  3791. "use strict";
  3792. init_relations();
  3793. init_properties();
  3794. init_model_definition();
  3795. init_model_data_validator();
  3796. init_model_data_sanitizer();
  3797. init_model_data_transformer();
  3798. init_model_definition_utils();
  3799. init_model_definition_validator();
  3800. }
  3801. });
  3802. // src/definition/datasource/datasource-definition-validator.js
  3803. var _DatasourceDefinitionValidator, DatasourceDefinitionValidator;
  3804. var init_datasource_definition_validator = __esm({
  3805. "src/definition/datasource/datasource-definition-validator.js"() {
  3806. "use strict";
  3807. init_src2();
  3808. init_errors2();
  3809. _DatasourceDefinitionValidator = class _DatasourceDefinitionValidator extends Service {
  3810. /**
  3811. * Validate.
  3812. *
  3813. * @param {object} datasourceDef
  3814. */
  3815. validate(datasourceDef) {
  3816. if (!datasourceDef || typeof datasourceDef !== "object")
  3817. throw new InvalidArgumentError2(
  3818. "The datasource definition should be an Object, but %v given.",
  3819. datasourceDef
  3820. );
  3821. if (!datasourceDef.name || typeof datasourceDef.name !== "string")
  3822. throw new InvalidArgumentError2(
  3823. 'The datasource definition requires the option "name" as a non-empty String, but %v given.',
  3824. datasourceDef.name
  3825. );
  3826. if (!datasourceDef.adapter || typeof datasourceDef.adapter !== "string")
  3827. throw new InvalidArgumentError2(
  3828. 'The datasource %v requires the option "adapter" as a non-empty String, but %v given.',
  3829. datasourceDef.name,
  3830. datasourceDef.adapter
  3831. );
  3832. }
  3833. };
  3834. __name(_DatasourceDefinitionValidator, "DatasourceDefinitionValidator");
  3835. DatasourceDefinitionValidator = _DatasourceDefinitionValidator;
  3836. }
  3837. });
  3838. // src/definition/datasource/index.js
  3839. var init_datasource = __esm({
  3840. "src/definition/datasource/index.js"() {
  3841. "use strict";
  3842. init_datasource_definition_validator();
  3843. }
  3844. });
  3845. // src/definition/index.js
  3846. var init_definition = __esm({
  3847. "src/definition/index.js"() {
  3848. "use strict";
  3849. init_model();
  3850. init_datasource();
  3851. init_definition_registry();
  3852. }
  3853. });
  3854. // src/filter/fields-clause-tool.js
  3855. var _FieldsClauseTool, FieldsClauseTool;
  3856. var init_fields_clause_tool = __esm({
  3857. "src/filter/fields-clause-tool.js"() {
  3858. "use strict";
  3859. init_src2();
  3860. init_utils2();
  3861. init_errors2();
  3862. init_definition();
  3863. _FieldsClauseTool = class _FieldsClauseTool extends Service {
  3864. /**
  3865. * Filter.
  3866. *
  3867. * @param {object|object[]} input
  3868. * @param {string} modelName
  3869. * @param {string|string[]|undefined} clause
  3870. * @returns {object|object[]}
  3871. */
  3872. filter(input, modelName, clause) {
  3873. const isArray = Array.isArray(input);
  3874. let entities = isArray ? input : [input];
  3875. entities.forEach((entity) => {
  3876. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  3877. throw new InvalidArgumentError2(
  3878. "The first argument of FieldsClauseTool.filter should be an Object or an Array of Object, but %v given.",
  3879. entity
  3880. );
  3881. });
  3882. if (!modelName || typeof modelName !== "string")
  3883. throw new InvalidArgumentError2(
  3884. "The second argument of FieldsClauseTool.filter should be a non-empty String, but %v given.",
  3885. modelName
  3886. );
  3887. if (clause == null) return input;
  3888. const fields = Array.isArray(clause) ? clause.slice() : [clause];
  3889. if (!fields.length) return input;
  3890. fields.forEach((field) => {
  3891. if (!field || typeof field !== "string")
  3892. throw new InvalidArgumentError2(
  3893. 'The provided option "fields" should be a non-empty String or an Array of non-empty String, but %v given.',
  3894. field
  3895. );
  3896. });
  3897. const pkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  3898. modelName
  3899. );
  3900. if (fields.indexOf(pkPropName) === -1) fields.push(pkPropName);
  3901. entities = entities.map((entity) => selectObjectKeys(entity, fields));
  3902. return isArray ? entities : entities[0];
  3903. }
  3904. /**
  3905. * Validate fields clause.
  3906. *
  3907. * @param {string|string[]|undefined} clause
  3908. */
  3909. static validateFieldsClause(clause) {
  3910. if (clause == null) return;
  3911. const fields = Array.isArray(clause) ? clause : [clause];
  3912. if (!fields.length) return;
  3913. fields.forEach((field) => {
  3914. if (!field || typeof field !== "string")
  3915. throw new InvalidArgumentError2(
  3916. 'The provided option "fields" should be a non-empty String or an Array of non-empty String, but %v given.',
  3917. field
  3918. );
  3919. });
  3920. }
  3921. /**
  3922. * Normalize fields clause.
  3923. *
  3924. * @param {string|string[]|undefined} clause
  3925. * @returns {string[]|undefined}
  3926. */
  3927. static normalizeFieldsClause(clause) {
  3928. if (clause == null) return;
  3929. const fields = Array.isArray(clause) ? clause : [clause];
  3930. if (!fields.length) return;
  3931. fields.forEach((field) => {
  3932. if (!field || typeof field !== "string")
  3933. throw new InvalidArgumentError2(
  3934. 'The provided option "fields" should be a non-empty String or an Array of non-empty String, but %v given.',
  3935. field
  3936. );
  3937. });
  3938. return fields;
  3939. }
  3940. };
  3941. __name(_FieldsClauseTool, "FieldsClauseTool");
  3942. FieldsClauseTool = _FieldsClauseTool;
  3943. }
  3944. });
  3945. // src/relations/has-one-resolver.js
  3946. var _HasOneResolver, HasOneResolver;
  3947. var init_has_one_resolver = __esm({
  3948. "src/relations/has-one-resolver.js"() {
  3949. "use strict";
  3950. init_src2();
  3951. init_utils2();
  3952. init_definition();
  3953. init_errors2();
  3954. init_repository2();
  3955. init_definition();
  3956. _HasOneResolver = class _HasOneResolver extends Service {
  3957. /**
  3958. * Include to.
  3959. *
  3960. * @param {object[]} entities
  3961. * @param {string} sourceName
  3962. * @param {string} targetName
  3963. * @param {string} relationName
  3964. * @param {string} foreignKey
  3965. * @param {object|undefined} scope
  3966. * @returns {Promise<void>}
  3967. */
  3968. async includeTo(entities, sourceName, targetName, relationName, foreignKey, scope = void 0) {
  3969. if (!entities || !Array.isArray(entities))
  3970. throw new InvalidArgumentError2(
  3971. 'The parameter "entities" of HasOneResolver.includeTo requires an Array of Object, but %v given.',
  3972. entities
  3973. );
  3974. if (!sourceName || typeof sourceName !== "string")
  3975. throw new InvalidArgumentError2(
  3976. 'The parameter "sourceName" of HasOneResolver.includeTo requires a non-empty String, but %v given.',
  3977. sourceName
  3978. );
  3979. if (!targetName || typeof targetName !== "string")
  3980. throw new InvalidArgumentError2(
  3981. 'The parameter "targetName" of HasOneResolver.includeTo requires a non-empty String, but %v given.',
  3982. targetName
  3983. );
  3984. if (!relationName || typeof relationName !== "string")
  3985. throw new InvalidArgumentError2(
  3986. 'The parameter "relationName" of HasOneResolver.includeTo requires a non-empty String, but %v given.',
  3987. relationName
  3988. );
  3989. if (!foreignKey || typeof foreignKey !== "string")
  3990. throw new InvalidArgumentError2(
  3991. 'The parameter "foreignKey" of HasOneResolver.includeTo requires a non-empty String, but %v given.',
  3992. foreignKey
  3993. );
  3994. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  3995. throw new InvalidArgumentError2(
  3996. 'The provided parameter "scope" of HasOneResolver.includeTo should be an Object, but %v given.',
  3997. scope
  3998. );
  3999. const sourcePkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  4000. sourceName
  4001. );
  4002. const sourceIds = [];
  4003. entities.forEach((entity) => {
  4004. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  4005. throw new InvalidArgumentError2(
  4006. 'The parameter "entities" of HasOneResolver.includeTo requires an Array of Object, but %v given.',
  4007. entity
  4008. );
  4009. const sourceId = entity[sourcePkPropName];
  4010. if (sourceIds.includes(sourceId)) return;
  4011. sourceIds.push(sourceId);
  4012. });
  4013. const promises = [];
  4014. const targetRepository = this.getService(RepositoryRegistry).getRepository(targetName);
  4015. scope = scope ? cloneDeep(scope) : {};
  4016. const targetBySourceId = /* @__PURE__ */ new Map();
  4017. sourceIds.forEach((sourceId) => {
  4018. const filter = cloneDeep(scope);
  4019. filter.where = {
  4020. and: [{ [foreignKey]: sourceId }, ...scope.where ? [scope.where] : []]
  4021. };
  4022. filter.limit = 1;
  4023. promises.push(
  4024. targetRepository.find(filter).then((result) => {
  4025. if (result.length) targetBySourceId.set(sourceId, result[0]);
  4026. })
  4027. );
  4028. });
  4029. await Promise.all(promises);
  4030. Array.from(targetBySourceId.keys()).forEach((sourceId) => {
  4031. const sources = entities.filter((v) => v[sourcePkPropName] === sourceId);
  4032. sources.forEach((v) => v[relationName] = targetBySourceId.get(sourceId));
  4033. });
  4034. }
  4035. /**
  4036. * Include polymorphic to.
  4037. *
  4038. * @param {object[]} entities
  4039. * @param {string} sourceName
  4040. * @param {string} targetName
  4041. * @param {string} relationName
  4042. * @param {string} foreignKey
  4043. * @param {string} discriminator
  4044. * @param {object|undefined} scope
  4045. * @returns {Promise<void>}
  4046. */
  4047. async includePolymorphicTo(entities, sourceName, targetName, relationName, foreignKey, discriminator, scope = void 0) {
  4048. if (!entities || !Array.isArray(entities))
  4049. throw new InvalidArgumentError2(
  4050. 'The parameter "entities" of HasOneResolver.includePolymorphicTo requires an Array of Object, but %v given.',
  4051. entities
  4052. );
  4053. if (!sourceName || typeof sourceName !== "string")
  4054. throw new InvalidArgumentError2(
  4055. 'The parameter "sourceName" of HasOneResolver.includePolymorphicTo requires a non-empty String, but %v given.',
  4056. sourceName
  4057. );
  4058. if (!targetName || typeof targetName !== "string")
  4059. throw new InvalidArgumentError2(
  4060. 'The parameter "targetName" of HasOneResolver.includePolymorphicTo requires a non-empty String, but %v given.',
  4061. targetName
  4062. );
  4063. if (!relationName || typeof relationName !== "string")
  4064. throw new InvalidArgumentError2(
  4065. 'The parameter "relationName" of HasOneResolver.includePolymorphicTo requires a non-empty String, but %v given.',
  4066. relationName
  4067. );
  4068. if (!foreignKey || typeof foreignKey !== "string")
  4069. throw new InvalidArgumentError2(
  4070. 'The parameter "foreignKey" of HasOneResolver.includePolymorphicTo requires a non-empty String, but %v given.',
  4071. foreignKey
  4072. );
  4073. if (!discriminator || typeof discriminator !== "string")
  4074. throw new InvalidArgumentError2(
  4075. 'The parameter "discriminator" of HasOneResolver.includePolymorphicTo requires a non-empty String, but %v given.',
  4076. discriminator
  4077. );
  4078. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  4079. throw new InvalidArgumentError2(
  4080. 'The provided parameter "scope" of HasOneResolver.includePolymorphicTo should be an Object, but %v given.',
  4081. scope
  4082. );
  4083. const sourcePkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  4084. sourceName
  4085. );
  4086. const sourceIds = [];
  4087. entities.forEach((entity) => {
  4088. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  4089. throw new InvalidArgumentError2(
  4090. 'The parameter "entities" of HasOneResolver.includePolymorphicTo requires an Array of Object, but %v given.',
  4091. entity
  4092. );
  4093. const sourceId = entity[sourcePkPropName];
  4094. if (sourceIds.includes(sourceId)) return;
  4095. sourceIds.push(sourceId);
  4096. });
  4097. const promises = [];
  4098. const targetRepository = this.getService(RepositoryRegistry).getRepository(targetName);
  4099. scope = scope ? cloneDeep(scope) : {};
  4100. const targetBySourceId = /* @__PURE__ */ new Map();
  4101. sourceIds.forEach((sourceId) => {
  4102. const filter = cloneDeep(scope);
  4103. filter.where = {
  4104. and: [
  4105. { [foreignKey]: sourceId, [discriminator]: sourceName },
  4106. ...scope.where ? [scope.where] : []
  4107. ]
  4108. };
  4109. filter.limit = 1;
  4110. promises.push(
  4111. targetRepository.find(filter).then((result) => {
  4112. if (result.length) targetBySourceId.set(sourceId, result[0]);
  4113. })
  4114. );
  4115. });
  4116. await Promise.all(promises);
  4117. Array.from(targetBySourceId.keys()).forEach((sourceId) => {
  4118. const sources = entities.filter((v) => v[sourcePkPropName] === sourceId);
  4119. sources.forEach((v) => v[relationName] = targetBySourceId.get(sourceId));
  4120. });
  4121. }
  4122. /**
  4123. * Include polymorphic by relation name.
  4124. *
  4125. * @param {object[]} entities
  4126. * @param {string} sourceName
  4127. * @param {string} targetName
  4128. * @param {string} relationName
  4129. * @param {string} targetRelationName
  4130. * @param {object|undefined} scope
  4131. * @returns {Promise<void>}
  4132. */
  4133. async includePolymorphicByRelationName(entities, sourceName, targetName, relationName, targetRelationName, scope = void 0) {
  4134. if (!entities || !Array.isArray(entities))
  4135. throw new InvalidArgumentError2(
  4136. 'The parameter "entities" of HasOneResolver.includePolymorphicByRelationName requires an Array of Object, but %v given.',
  4137. entities
  4138. );
  4139. if (!sourceName || typeof sourceName !== "string")
  4140. throw new InvalidArgumentError2(
  4141. 'The parameter "sourceName" of HasOneResolver.includePolymorphicByRelationName requires a non-empty String, but %v given.',
  4142. sourceName
  4143. );
  4144. if (!targetName || typeof targetName !== "string")
  4145. throw new InvalidArgumentError2(
  4146. 'The parameter "targetName" of HasOneResolver.includePolymorphicByRelationName requires a non-empty String, but %v given.',
  4147. targetName
  4148. );
  4149. if (!relationName || typeof relationName !== "string")
  4150. throw new InvalidArgumentError2(
  4151. 'The parameter "relationName" of HasOneResolver.includePolymorphicByRelationName requires a non-empty String, but %v given.',
  4152. relationName
  4153. );
  4154. if (!targetRelationName || typeof targetRelationName !== "string")
  4155. throw new InvalidArgumentError2(
  4156. 'The parameter "targetRelationName" of HasOneResolver.includePolymorphicByRelationName requires a non-empty String, but %v given.',
  4157. targetRelationName
  4158. );
  4159. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  4160. throw new InvalidArgumentError2(
  4161. 'The provided parameter "scope" of HasOneResolver.includePolymorphicByRelationName should be an Object, but %v given.',
  4162. scope
  4163. );
  4164. const targetRelationDef = this.getService(
  4165. ModelDefinitionUtils
  4166. ).getRelationDefinitionByName(targetName, targetRelationName);
  4167. if (targetRelationDef.type !== RelationType.BELONGS_TO)
  4168. throw new InvalidArgumentError2(
  4169. 'The relation %v of the model %v is a polymorphic "hasOne" relation, so it requires the target relation %v to be a polymorphic "belongsTo", but %v type given.',
  4170. relationName,
  4171. sourceName,
  4172. targetRelationName,
  4173. targetRelationDef.type
  4174. );
  4175. if (!targetRelationDef.polymorphic)
  4176. throw new InvalidArgumentError2(
  4177. 'The relation %v of the model %v is a polymorphic "hasOne" relation, so it requires the target relation %v to be a polymorphic too.',
  4178. relationName,
  4179. sourceName,
  4180. targetRelationName
  4181. );
  4182. const foreignKey = targetRelationDef.foreignKey || `${targetRelationName}Id`;
  4183. const discriminator = targetRelationDef.discriminator || `${targetRelationName}Type`;
  4184. return this.includePolymorphicTo(
  4185. entities,
  4186. sourceName,
  4187. targetName,
  4188. relationName,
  4189. foreignKey,
  4190. discriminator,
  4191. scope
  4192. );
  4193. }
  4194. };
  4195. __name(_HasOneResolver, "HasOneResolver");
  4196. HasOneResolver = _HasOneResolver;
  4197. }
  4198. });
  4199. // src/relations/has-many-resolver.js
  4200. var _HasManyResolver, HasManyResolver;
  4201. var init_has_many_resolver = __esm({
  4202. "src/relations/has-many-resolver.js"() {
  4203. "use strict";
  4204. init_src2();
  4205. init_utils2();
  4206. init_definition();
  4207. init_errors2();
  4208. init_repository2();
  4209. init_definition();
  4210. _HasManyResolver = class _HasManyResolver extends Service {
  4211. /**
  4212. * Include to.
  4213. *
  4214. * @param {object[]} entities
  4215. * @param {string} sourceName
  4216. * @param {string} targetName
  4217. * @param {string} relationName
  4218. * @param {string} foreignKey
  4219. * @param {object|undefined} scope
  4220. * @returns {Promise<void>}
  4221. */
  4222. async includeTo(entities, sourceName, targetName, relationName, foreignKey, scope = void 0) {
  4223. if (!entities || !Array.isArray(entities))
  4224. throw new InvalidArgumentError2(
  4225. 'The parameter "entities" of HasManyResolver.includeTo requires an Array of Object, but %v given.',
  4226. entities
  4227. );
  4228. if (!sourceName || typeof sourceName !== "string")
  4229. throw new InvalidArgumentError2(
  4230. 'The parameter "sourceName" of HasManyResolver.includeTo requires a non-empty String, but %v given.',
  4231. sourceName
  4232. );
  4233. if (!targetName || typeof targetName !== "string")
  4234. throw new InvalidArgumentError2(
  4235. 'The parameter "targetName" of HasManyResolver.includeTo requires a non-empty String, but %v given.',
  4236. targetName
  4237. );
  4238. if (!relationName || typeof relationName !== "string")
  4239. throw new InvalidArgumentError2(
  4240. 'The parameter "relationName" of HasManyResolver.includeTo requires a non-empty String, but %v given.',
  4241. relationName
  4242. );
  4243. if (!foreignKey || typeof foreignKey !== "string")
  4244. throw new InvalidArgumentError2(
  4245. 'The parameter "foreignKey" of HasManyResolver.includeTo requires a non-empty String, but %v given.',
  4246. foreignKey
  4247. );
  4248. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  4249. throw new InvalidArgumentError2(
  4250. 'The provided parameter "scope" of HasManyResolver.includeTo should be an Object, but %v given.',
  4251. scope
  4252. );
  4253. const sourcePkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  4254. sourceName
  4255. );
  4256. const sourceIds = [];
  4257. entities.forEach((entity) => {
  4258. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  4259. throw new InvalidArgumentError2(
  4260. 'The parameter "entities" of HasManyResolver.includeTo requires an Array of Object, but %v given.',
  4261. entity
  4262. );
  4263. const sourceId = entity[sourcePkPropName];
  4264. if (sourceIds.includes(sourceId)) return;
  4265. sourceIds.push(sourceId);
  4266. });
  4267. const promises = [];
  4268. const targetRepository = this.getService(RepositoryRegistry).getRepository(targetName);
  4269. scope = scope ? cloneDeep(scope) : {};
  4270. const targetsBySourceId = /* @__PURE__ */ new Map();
  4271. sourceIds.forEach((sourceId) => {
  4272. const filter = cloneDeep(scope);
  4273. filter.where = {
  4274. and: [{ [foreignKey]: sourceId }, ...scope.where ? [scope.where] : []]
  4275. };
  4276. promises.push(
  4277. targetRepository.find(filter).then((result) => {
  4278. var _a;
  4279. if (result.length) {
  4280. let targets = (_a = targetsBySourceId.get(sourceId)) != null ? _a : [];
  4281. targets = [...targets, ...result];
  4282. targetsBySourceId.set(sourceId, targets);
  4283. }
  4284. })
  4285. );
  4286. });
  4287. await Promise.all(promises);
  4288. entities.forEach((entity) => {
  4289. var _a;
  4290. const sourceId = entity[sourcePkPropName];
  4291. entity[relationName] = (_a = targetsBySourceId.get(sourceId)) != null ? _a : [];
  4292. });
  4293. }
  4294. /**
  4295. * Include polymorphic to.
  4296. *
  4297. * @param {object[]} entities
  4298. * @param {string} sourceName
  4299. * @param {string} targetName
  4300. * @param {string} relationName
  4301. * @param {string} foreignKey
  4302. * @param {string} discriminator
  4303. * @param {object|undefined} scope
  4304. * @returns {Promise<void>}
  4305. */
  4306. async includePolymorphicTo(entities, sourceName, targetName, relationName, foreignKey, discriminator, scope = void 0) {
  4307. if (!entities || !Array.isArray(entities))
  4308. throw new InvalidArgumentError2(
  4309. 'The parameter "entities" of HasManyResolver.includePolymorphicTo requires an Array of Object, but %v given.',
  4310. entities
  4311. );
  4312. if (!sourceName || typeof sourceName !== "string")
  4313. throw new InvalidArgumentError2(
  4314. 'The parameter "sourceName" of HasManyResolver.includePolymorphicTo requires a non-empty String, but %v given.',
  4315. sourceName
  4316. );
  4317. if (!targetName || typeof targetName !== "string")
  4318. throw new InvalidArgumentError2(
  4319. 'The parameter "targetName" of HasManyResolver.includePolymorphicTo requires a non-empty String, but %v given.',
  4320. targetName
  4321. );
  4322. if (!relationName || typeof relationName !== "string")
  4323. throw new InvalidArgumentError2(
  4324. 'The parameter "relationName" of HasManyResolver.includePolymorphicTo requires a non-empty String, but %v given.',
  4325. relationName
  4326. );
  4327. if (!foreignKey || typeof foreignKey !== "string")
  4328. throw new InvalidArgumentError2(
  4329. 'The parameter "foreignKey" of HasManyResolver.includePolymorphicTo requires a non-empty String, but %v given.',
  4330. foreignKey
  4331. );
  4332. if (!discriminator || typeof discriminator !== "string")
  4333. throw new InvalidArgumentError2(
  4334. 'The parameter "discriminator" of HasManyResolver.includePolymorphicTo requires a non-empty String, but %v given.',
  4335. discriminator
  4336. );
  4337. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  4338. throw new InvalidArgumentError2(
  4339. 'The provided parameter "scope" of HasManyResolver.includePolymorphicTo should be an Object, but %v given.',
  4340. scope
  4341. );
  4342. const sourcePkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  4343. sourceName
  4344. );
  4345. const sourceIds = [];
  4346. entities.forEach((entity) => {
  4347. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  4348. throw new InvalidArgumentError2(
  4349. 'The parameter "entities" of HasManyResolver.includePolymorphicTo requires an Array of Object, but %v given.',
  4350. entity
  4351. );
  4352. const sourceId = entity[sourcePkPropName];
  4353. if (sourceIds.includes(sourceId)) return;
  4354. sourceIds.push(sourceId);
  4355. });
  4356. const promises = [];
  4357. const targetRepository = this.getService(RepositoryRegistry).getRepository(targetName);
  4358. scope = scope ? cloneDeep(scope) : {};
  4359. const targetsBySourceId = /* @__PURE__ */ new Map();
  4360. sourceIds.forEach((sourceId) => {
  4361. const filter = cloneDeep(scope);
  4362. filter.where = {
  4363. and: [
  4364. { [foreignKey]: sourceId, [discriminator]: sourceName },
  4365. ...scope.where ? [scope.where] : []
  4366. ]
  4367. };
  4368. promises.push(
  4369. targetRepository.find(filter).then((result) => {
  4370. var _a;
  4371. if (result.length) {
  4372. let targets = (_a = targetsBySourceId.get(sourceId)) != null ? _a : [];
  4373. targets = [...targets, ...result];
  4374. targetsBySourceId.set(sourceId, targets);
  4375. }
  4376. })
  4377. );
  4378. });
  4379. await Promise.all(promises);
  4380. entities.forEach((entity) => {
  4381. var _a;
  4382. const sourceId = entity[sourcePkPropName];
  4383. entity[relationName] = (_a = targetsBySourceId.get(sourceId)) != null ? _a : [];
  4384. });
  4385. }
  4386. /**
  4387. * Include polymorphic by relation name.
  4388. *
  4389. * @param {object[]} entities
  4390. * @param {string} sourceName
  4391. * @param {string} targetName
  4392. * @param {string} relationName
  4393. * @param {string} targetRelationName
  4394. * @param {object|undefined} scope
  4395. * @returns {Promise<void>}
  4396. */
  4397. async includePolymorphicByRelationName(entities, sourceName, targetName, relationName, targetRelationName, scope = void 0) {
  4398. if (!entities || !Array.isArray(entities))
  4399. throw new InvalidArgumentError2(
  4400. 'The parameter "entities" of HasManyResolver.includePolymorphicByRelationName requires an Array of Object, but %v given.',
  4401. entities
  4402. );
  4403. if (!sourceName || typeof sourceName !== "string")
  4404. throw new InvalidArgumentError2(
  4405. 'The parameter "sourceName" of HasManyResolver.includePolymorphicByRelationName requires a non-empty String, but %v given.',
  4406. sourceName
  4407. );
  4408. if (!targetName || typeof targetName !== "string")
  4409. throw new InvalidArgumentError2(
  4410. 'The parameter "targetName" of HasManyResolver.includePolymorphicByRelationName requires a non-empty String, but %v given.',
  4411. targetName
  4412. );
  4413. if (!relationName || typeof relationName !== "string")
  4414. throw new InvalidArgumentError2(
  4415. 'The parameter "relationName" of HasManyResolver.includePolymorphicByRelationName requires a non-empty String, but %v given.',
  4416. relationName
  4417. );
  4418. if (!targetRelationName || typeof targetRelationName !== "string")
  4419. throw new InvalidArgumentError2(
  4420. 'The parameter "targetRelationName" of HasManyResolver.includePolymorphicByRelationName requires a non-empty String, but %v given.',
  4421. targetRelationName
  4422. );
  4423. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  4424. throw new InvalidArgumentError2(
  4425. 'The provided parameter "scope" of HasManyResolver.includePolymorphicByRelationName should be an Object, but %v given.',
  4426. scope
  4427. );
  4428. const targetRelationDef = this.getService(
  4429. ModelDefinitionUtils
  4430. ).getRelationDefinitionByName(targetName, targetRelationName);
  4431. if (targetRelationDef.type !== RelationType.BELONGS_TO)
  4432. throw new InvalidArgumentError2(
  4433. 'The relation %v of the model %v is a polymorphic "hasMany" relation, so it requires the target relation %v to be a polymorphic "belongsTo", but %v type given.',
  4434. relationName,
  4435. sourceName,
  4436. targetRelationName,
  4437. targetRelationDef.type
  4438. );
  4439. if (!targetRelationDef.polymorphic)
  4440. throw new InvalidArgumentError2(
  4441. 'The relation %v of the model %v is a polymorphic "hasMany" relation, so it requires the target relation %v to be a polymorphic too.',
  4442. relationName,
  4443. sourceName,
  4444. targetRelationName
  4445. );
  4446. const foreignKey = targetRelationDef.foreignKey || `${targetRelationName}Id`;
  4447. const discriminator = targetRelationDef.discriminator || `${targetRelationName}Type`;
  4448. return this.includePolymorphicTo(
  4449. entities,
  4450. sourceName,
  4451. targetName,
  4452. relationName,
  4453. foreignKey,
  4454. discriminator,
  4455. scope
  4456. );
  4457. }
  4458. };
  4459. __name(_HasManyResolver, "HasManyResolver");
  4460. HasManyResolver = _HasManyResolver;
  4461. }
  4462. });
  4463. // src/relations/belongs-to-resolver.js
  4464. var _BelongsToResolver, BelongsToResolver;
  4465. var init_belongs_to_resolver = __esm({
  4466. "src/relations/belongs-to-resolver.js"() {
  4467. "use strict";
  4468. init_src2();
  4469. init_utils2();
  4470. init_utils2();
  4471. init_errors2();
  4472. init_repository2();
  4473. init_definition();
  4474. _BelongsToResolver = class _BelongsToResolver extends Service {
  4475. /**
  4476. * Include to.
  4477. *
  4478. * @param {object[]} entities
  4479. * @param {string} sourceName
  4480. * @param {string} targetName
  4481. * @param {string} relationName
  4482. * @param {string|undefined} foreignKey
  4483. * @param {object|undefined} scope
  4484. * @returns {Promise<void>}
  4485. */
  4486. async includeTo(entities, sourceName, targetName, relationName, foreignKey = void 0, scope = void 0) {
  4487. if (!entities || !Array.isArray(entities))
  4488. throw new InvalidArgumentError2(
  4489. 'The parameter "entities" of BelongsToResolver.includeTo requires an Array of Object, but %v given.',
  4490. entities
  4491. );
  4492. if (!sourceName || typeof sourceName !== "string")
  4493. throw new InvalidArgumentError2(
  4494. 'The parameter "sourceName" of BelongsToResolver.includeTo requires a non-empty String, but %v given.',
  4495. sourceName
  4496. );
  4497. if (!targetName || typeof targetName !== "string")
  4498. throw new InvalidArgumentError2(
  4499. 'The parameter "targetName" of BelongsToResolver.includeTo requires a non-empty String, but %v given.',
  4500. targetName
  4501. );
  4502. if (!relationName || typeof relationName !== "string")
  4503. throw new InvalidArgumentError2(
  4504. 'The parameter "relationName" of BelongsToResolver.includeTo requires a non-empty String, but %v given.',
  4505. relationName
  4506. );
  4507. if (foreignKey && typeof foreignKey !== "string")
  4508. throw new InvalidArgumentError2(
  4509. 'The provided parameter "foreignKey" of BelongsToResolver.includeTo should be a String, but %v given.',
  4510. foreignKey
  4511. );
  4512. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  4513. throw new InvalidArgumentError2(
  4514. 'The provided parameter "scope" of BelongsToResolver.includeTo should be an Object, but %v given.',
  4515. scope
  4516. );
  4517. if (foreignKey == null) foreignKey = `${relationName}Id`;
  4518. const targetIds = entities.reduce((acc, entity) => {
  4519. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  4520. throw new InvalidArgumentError2(
  4521. 'The parameter "entities" of BelongsToResolver.includeTo requires an Array of Object, but %v given.',
  4522. entity
  4523. );
  4524. const targetId = entity[foreignKey];
  4525. return targetId != null ? [...acc, targetId] : acc;
  4526. }, []);
  4527. const targetRepository = this.getService(RepositoryRegistry).getRepository(targetName);
  4528. const targetPkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  4529. targetName
  4530. );
  4531. scope = scope ? cloneDeep(scope) : {};
  4532. const filter = cloneDeep(scope);
  4533. filter.where = {
  4534. and: [
  4535. { [targetPkPropName]: { inq: targetIds } },
  4536. ...scope.where ? [scope.where] : []
  4537. ]
  4538. };
  4539. const targets = await targetRepository.find(filter);
  4540. entities.forEach((entity) => {
  4541. const target = targets.find(
  4542. (e) => e[targetPkPropName] === entity[foreignKey]
  4543. );
  4544. if (target) entity[relationName] = target;
  4545. });
  4546. }
  4547. /**
  4548. * Include polymorphic to.
  4549. *
  4550. * @param {object[]} entities
  4551. * @param {string} sourceName
  4552. * @param {string} relationName
  4553. * @param {string|undefined} foreignKey
  4554. * @param {string|undefined} discriminator
  4555. * @param {object|undefined} scope
  4556. * @returns {Promise<void>}
  4557. */
  4558. async includePolymorphicTo(entities, sourceName, relationName, foreignKey = void 0, discriminator = void 0, scope = void 0) {
  4559. if (!entities || !Array.isArray(entities))
  4560. throw new InvalidArgumentError2(
  4561. 'The parameter "entities" of BelongsToResolver.includePolymorphicTo requires an Array of Object, but %v given.',
  4562. entities
  4563. );
  4564. if (!sourceName || typeof sourceName !== "string")
  4565. throw new InvalidArgumentError2(
  4566. 'The parameter "sourceName" of BelongsToResolver.includePolymorphicTo requires a non-empty String, but %v given.',
  4567. sourceName
  4568. );
  4569. if (!relationName || typeof relationName !== "string")
  4570. throw new InvalidArgumentError2(
  4571. 'The parameter "relationName" of BelongsToResolver.includePolymorphicTo requires a non-empty String, but %v given.',
  4572. relationName
  4573. );
  4574. if (foreignKey && typeof foreignKey !== "string")
  4575. throw new InvalidArgumentError2(
  4576. 'The provided parameter "foreignKey" of BelongsToResolver.includePolymorphicTo should be a String, but %v given.',
  4577. foreignKey
  4578. );
  4579. if (discriminator && typeof discriminator !== "string")
  4580. throw new InvalidArgumentError2(
  4581. 'The provided parameter "discriminator" of BelongsToResolver.includePolymorphicTo should be a String, but %v given.',
  4582. discriminator
  4583. );
  4584. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  4585. throw new InvalidArgumentError2(
  4586. 'The provided parameter "scope" of BelongsToResolver.includePolymorphicTo should be an Object, but %v given.',
  4587. scope
  4588. );
  4589. if (foreignKey == null) {
  4590. const singularRelationName = singularize(relationName);
  4591. foreignKey = `${singularRelationName}Id`;
  4592. }
  4593. if (discriminator == null) {
  4594. const singularRelationName = singularize(relationName);
  4595. discriminator = `${singularRelationName}Type`;
  4596. }
  4597. const targetIdsByTargetName = {};
  4598. entities.forEach((entity) => {
  4599. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  4600. throw new InvalidArgumentError2(
  4601. 'The parameter "entities" of BelongsToResolver.includePolymorphicTo requires an Array of Object, but %v given.',
  4602. entity
  4603. );
  4604. const targetId = entity[foreignKey];
  4605. const targetName = entity[discriminator];
  4606. if (targetId == null || targetName == null) return;
  4607. if (targetIdsByTargetName[targetName] == null)
  4608. targetIdsByTargetName[targetName] = [];
  4609. if (!targetIdsByTargetName[targetName].includes(targetId))
  4610. targetIdsByTargetName[targetName].push(targetId);
  4611. });
  4612. const promises = [];
  4613. const targetNames = Object.keys(targetIdsByTargetName);
  4614. scope = scope ? cloneDeep(scope) : {};
  4615. const targetEntitiesByTargetNames = {};
  4616. targetNames.forEach((targetName) => {
  4617. let targetRepository;
  4618. try {
  4619. targetRepository = this.getService(RepositoryRegistry).getRepository(targetName);
  4620. } catch (error) {
  4621. if (error instanceof InvalidArgumentError2) {
  4622. if (error.message === `The model "${targetName}" is not defined.` || error.message === `The model "${targetName}" does not have a specified datasource.`) {
  4623. return;
  4624. }
  4625. } else {
  4626. throw error;
  4627. }
  4628. }
  4629. const targetPkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  4630. targetName
  4631. );
  4632. const targetFilter = cloneDeep(scope);
  4633. const targetIds = targetIdsByTargetName[targetName];
  4634. targetFilter.where = {
  4635. and: [
  4636. { [targetPkPropName]: { inq: targetIds } },
  4637. ...scope.where ? [scope.where] : []
  4638. ]
  4639. };
  4640. const promise = targetRepository.find(targetFilter).then((result) => {
  4641. var _a;
  4642. targetEntitiesByTargetNames[targetName] = [
  4643. ...(_a = targetEntitiesByTargetNames[targetName]) != null ? _a : [],
  4644. ...result
  4645. ];
  4646. });
  4647. promises.push(promise);
  4648. });
  4649. await Promise.all(promises);
  4650. entities.forEach((entity) => {
  4651. var _a;
  4652. const targetId = entity[foreignKey];
  4653. const targetName = entity[discriminator];
  4654. if (targetId == null || targetName == null || targetEntitiesByTargetNames[targetName] == null) {
  4655. return;
  4656. }
  4657. const targetEntities = (_a = targetEntitiesByTargetNames[targetName]) != null ? _a : [];
  4658. const targetPkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  4659. targetName
  4660. );
  4661. const target = targetEntities.find((e) => e[targetPkPropName] === targetId);
  4662. if (target) entity[relationName] = target;
  4663. });
  4664. }
  4665. };
  4666. __name(_BelongsToResolver, "BelongsToResolver");
  4667. BelongsToResolver = _BelongsToResolver;
  4668. }
  4669. });
  4670. // src/relations/references-many-resolver.js
  4671. var _ReferencesManyResolver, ReferencesManyResolver;
  4672. var init_references_many_resolver = __esm({
  4673. "src/relations/references-many-resolver.js"() {
  4674. "use strict";
  4675. init_src2();
  4676. init_utils2();
  4677. init_utils2();
  4678. init_errors2();
  4679. init_repository2();
  4680. init_definition();
  4681. _ReferencesManyResolver = class _ReferencesManyResolver extends Service {
  4682. /**
  4683. * Include to.
  4684. *
  4685. * @param {object[]} entities
  4686. * @param {string} sourceName
  4687. * @param {string} targetName
  4688. * @param {string} relationName
  4689. * @param {string|undefined} foreignKey
  4690. * @param {object|undefined} scope
  4691. * @returns {Promise<void>}
  4692. */
  4693. async includeTo(entities, sourceName, targetName, relationName, foreignKey = void 0, scope = void 0) {
  4694. if (!entities || !Array.isArray(entities))
  4695. throw new InvalidArgumentError2(
  4696. 'The parameter "entities" of ReferencesManyResolver.includeTo requires an Array of Object, but %v given.',
  4697. entities
  4698. );
  4699. if (!sourceName || typeof sourceName !== "string")
  4700. throw new InvalidArgumentError2(
  4701. 'The parameter "sourceName" of ReferencesManyResolver.includeTo requires a non-empty String, but %v given.',
  4702. sourceName
  4703. );
  4704. if (!targetName || typeof targetName !== "string")
  4705. throw new InvalidArgumentError2(
  4706. 'The parameter "targetName" of ReferencesManyResolver.includeTo requires a non-empty String, but %v given.',
  4707. targetName
  4708. );
  4709. if (!relationName || typeof relationName !== "string")
  4710. throw new InvalidArgumentError2(
  4711. 'The parameter "relationName" of ReferencesManyResolver.includeTo requires a non-empty String, but %v given.',
  4712. relationName
  4713. );
  4714. if (foreignKey && typeof foreignKey !== "string")
  4715. throw new InvalidArgumentError2(
  4716. 'The provided parameter "foreignKey" of ReferencesManyResolver.includeTo should be a String, but %v given.',
  4717. foreignKey
  4718. );
  4719. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  4720. throw new InvalidArgumentError2(
  4721. 'The provided parameter "scope" of ReferencesManyResolver.includeTo should be an Object, but %v given.',
  4722. scope
  4723. );
  4724. if (foreignKey == null) {
  4725. const singularRelationName = singularize(relationName);
  4726. foreignKey = `${singularRelationName}Ids`;
  4727. }
  4728. const targetIds = entities.reduce((acc, entity) => {
  4729. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  4730. throw new InvalidArgumentError2(
  4731. 'The parameter "entities" of ReferencesManyResolver.includeTo requires an Array of Object, but %v given.',
  4732. entity
  4733. );
  4734. const ids = entity[foreignKey];
  4735. if (Array.isArray(ids))
  4736. ids.forEach((id) => {
  4737. if (id == null || acc.includes(id)) return;
  4738. acc.push(id);
  4739. });
  4740. return acc;
  4741. }, []);
  4742. const targetRepository = this.getService(RepositoryRegistry).getRepository(targetName);
  4743. const targetPkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  4744. targetName
  4745. );
  4746. scope = scope ? cloneDeep(scope) : {};
  4747. const filter = cloneDeep(scope);
  4748. filter.where = {
  4749. and: [
  4750. { [targetPkPropName]: { inq: targetIds } },
  4751. ...scope.where ? [scope.where] : []
  4752. ]
  4753. };
  4754. const targets = await targetRepository.find(filter);
  4755. entities.forEach((entity) => {
  4756. const ids = entity[foreignKey];
  4757. entity[relationName] = [];
  4758. if (Array.isArray(ids))
  4759. targets.forEach((target) => {
  4760. const targetId = target[targetPkPropName];
  4761. if (ids.includes(targetId)) entity[relationName].push(target);
  4762. });
  4763. });
  4764. }
  4765. };
  4766. __name(_ReferencesManyResolver, "ReferencesManyResolver");
  4767. ReferencesManyResolver = _ReferencesManyResolver;
  4768. }
  4769. });
  4770. // src/relations/index.js
  4771. var init_relations2 = __esm({
  4772. "src/relations/index.js"() {
  4773. "use strict";
  4774. init_has_one_resolver();
  4775. init_has_many_resolver();
  4776. init_belongs_to_resolver();
  4777. init_references_many_resolver();
  4778. }
  4779. });
  4780. // src/filter/include-clause-tool.js
  4781. var _IncludeClauseTool, IncludeClauseTool;
  4782. var init_include_clause_tool = __esm({
  4783. "src/filter/include-clause-tool.js"() {
  4784. "use strict";
  4785. init_src2();
  4786. init_definition();
  4787. init_relations2();
  4788. init_relations2();
  4789. init_where_clause_tool();
  4790. init_order_clause_tool();
  4791. init_slice_clause_tool();
  4792. init_errors2();
  4793. init_relations2();
  4794. init_fields_clause_tool();
  4795. init_definition();
  4796. init_relations2();
  4797. _IncludeClauseTool = class _IncludeClauseTool extends Service {
  4798. /**
  4799. * Include to.
  4800. *
  4801. * @param {object[]} entities
  4802. * @param {string} modelName
  4803. * @param {IncludeClause|undefined} clause
  4804. * @returns {Promise<void>}
  4805. */
  4806. async includeTo(entities, modelName, clause) {
  4807. clause = _IncludeClauseTool.normalizeIncludeClause(clause);
  4808. const promises = [];
  4809. clause.forEach((inclusion) => {
  4810. const relDef = this.getService(
  4811. ModelDefinitionUtils
  4812. ).getRelationDefinitionByName(modelName, inclusion.relation);
  4813. switch (relDef.type) {
  4814. // BELONGS_TO
  4815. case RelationType.BELONGS_TO:
  4816. if (relDef.polymorphic) {
  4817. promises.push(
  4818. this.getService(BelongsToResolver).includePolymorphicTo(
  4819. entities,
  4820. modelName,
  4821. inclusion.relation,
  4822. relDef.foreignKey,
  4823. relDef.discriminator,
  4824. inclusion.scope
  4825. )
  4826. );
  4827. } else {
  4828. promises.push(
  4829. this.getService(BelongsToResolver).includeTo(
  4830. entities,
  4831. modelName,
  4832. relDef.model,
  4833. inclusion.relation,
  4834. relDef.foreignKey,
  4835. inclusion.scope
  4836. )
  4837. );
  4838. }
  4839. break;
  4840. // HAS_ONE
  4841. case RelationType.HAS_ONE:
  4842. if (relDef.polymorphic && typeof relDef.polymorphic === "string") {
  4843. promises.push(
  4844. this.getService(HasOneResolver).includePolymorphicByRelationName(
  4845. entities,
  4846. modelName,
  4847. relDef.model,
  4848. inclusion.relation,
  4849. relDef.polymorphic,
  4850. inclusion.scope
  4851. )
  4852. );
  4853. } else if (relDef.polymorphic) {
  4854. promises.push(
  4855. this.getService(HasOneResolver).includePolymorphicTo(
  4856. entities,
  4857. modelName,
  4858. relDef.model,
  4859. inclusion.relation,
  4860. relDef.foreignKey,
  4861. relDef.discriminator,
  4862. inclusion.scope
  4863. )
  4864. );
  4865. } else {
  4866. promises.push(
  4867. this.getService(HasOneResolver).includeTo(
  4868. entities,
  4869. modelName,
  4870. relDef.model,
  4871. inclusion.relation,
  4872. relDef.foreignKey,
  4873. inclusion.scope
  4874. )
  4875. );
  4876. }
  4877. break;
  4878. // HAS_MANY
  4879. case RelationType.HAS_MANY:
  4880. if (relDef.polymorphic && typeof relDef.polymorphic === "string") {
  4881. promises.push(
  4882. this.getService(HasManyResolver).includePolymorphicByRelationName(
  4883. entities,
  4884. modelName,
  4885. relDef.model,
  4886. inclusion.relation,
  4887. relDef.polymorphic,
  4888. inclusion.scope
  4889. )
  4890. );
  4891. } else if (relDef.polymorphic) {
  4892. promises.push(
  4893. this.getService(HasManyResolver).includePolymorphicTo(
  4894. entities,
  4895. modelName,
  4896. relDef.model,
  4897. inclusion.relation,
  4898. relDef.foreignKey,
  4899. relDef.discriminator,
  4900. inclusion.scope
  4901. )
  4902. );
  4903. } else {
  4904. promises.push(
  4905. this.getService(HasManyResolver).includeTo(
  4906. entities,
  4907. modelName,
  4908. relDef.model,
  4909. inclusion.relation,
  4910. relDef.foreignKey,
  4911. inclusion.scope
  4912. )
  4913. );
  4914. }
  4915. break;
  4916. case RelationType.REFERENCES_MANY:
  4917. promises.push(
  4918. this.getService(ReferencesManyResolver).includeTo(
  4919. entities,
  4920. modelName,
  4921. relDef.model,
  4922. inclusion.relation,
  4923. relDef.foreignKey,
  4924. inclusion.scope
  4925. )
  4926. );
  4927. break;
  4928. default:
  4929. throw new InvalidArgumentError2(
  4930. "The relation type %v does not have an inclusion resolver.",
  4931. relDef.type
  4932. );
  4933. }
  4934. });
  4935. await Promise.all(promises);
  4936. }
  4937. /**
  4938. * Validate include clause.
  4939. *
  4940. * @param {IncludeClause|undefined} clause
  4941. */
  4942. static validateIncludeClause(clause) {
  4943. if (clause == null) {
  4944. } else if (clause && typeof clause === "string") {
  4945. } else if (Array.isArray(clause)) {
  4946. const relNames = [];
  4947. clause.flat(Infinity).forEach((el) => {
  4948. this.validateIncludeClause(el);
  4949. if (typeof el === "string") {
  4950. relNames.push(el);
  4951. } else if (typeof el === "object") {
  4952. Object.keys(el).forEach((key) => {
  4953. if (Object.prototype.hasOwnProperty.call(el, key))
  4954. relNames.push(key);
  4955. });
  4956. }
  4957. });
  4958. const duplicateNames = relNames.filter(
  4959. (name, i) => relNames.indexOf(name) !== i
  4960. );
  4961. if (duplicateNames.length)
  4962. throw new InvalidArgumentError2(
  4963. 'The provided option "include" has duplicates of %v.',
  4964. duplicateNames[0]
  4965. );
  4966. } else if (typeof clause === "object") {
  4967. if ("relation" in clause) {
  4968. if (!clause.relation || typeof clause.relation !== "string")
  4969. throw new InvalidArgumentError2(
  4970. 'The provided option "relation" should be a non-empty String, but %v given.',
  4971. clause.relation
  4972. );
  4973. if ("scope" in clause && clause) this.validateScopeClause(clause.scope);
  4974. } else {
  4975. Object.keys(clause).forEach((key) => {
  4976. if (!Object.prototype.hasOwnProperty.call(clause, key)) return;
  4977. this.validateIncludeClause(key);
  4978. this.validateIncludeClause(clause[key]);
  4979. });
  4980. }
  4981. } else {
  4982. throw new InvalidArgumentError2(
  4983. 'The provided option "include" should have a non-empty String, an Object or an Array, but %v given.',
  4984. clause
  4985. );
  4986. }
  4987. }
  4988. /**
  4989. * Validate scope clause.
  4990. *
  4991. * @param {object|undefined} clause
  4992. */
  4993. static validateScopeClause(clause) {
  4994. if (clause == null) return;
  4995. if (typeof clause !== "object" || Array.isArray(clause))
  4996. throw new InvalidArgumentError2(
  4997. 'The provided option "scope" should be an Object, but %v given.',
  4998. clause
  4999. );
  5000. if (clause.where != null) {
  5001. WhereClauseTool.validateWhereClause(clause.where);
  5002. }
  5003. if (clause.order != null) {
  5004. OrderClauseTool.validateOrderClause(clause.order);
  5005. }
  5006. if (clause.skip != null) {
  5007. SliceClauseTool.validateSkipClause(clause.skip);
  5008. }
  5009. if (clause.limit != null) {
  5010. SliceClauseTool.validateLimitClause(clause.limit);
  5011. }
  5012. if (clause.fields != null) {
  5013. FieldsClauseTool.validateFieldsClause(clause.fields);
  5014. }
  5015. if (clause.include != null) {
  5016. _IncludeClauseTool.validateIncludeClause(clause.include);
  5017. }
  5018. }
  5019. /**
  5020. * Normalize include clause.
  5021. *
  5022. * @param {IncludeClause|undefined} clause
  5023. * @returns {object[]}
  5024. */
  5025. static normalizeIncludeClause(clause) {
  5026. let result = [];
  5027. if (clause == null) {
  5028. return result;
  5029. } else if (clause && typeof clause === "string") {
  5030. result.push({ relation: clause });
  5031. } else if (Array.isArray(clause)) {
  5032. clause.flat(Infinity).forEach((el) => {
  5033. el = this.normalizeIncludeClause(el);
  5034. result = [...result, ...el];
  5035. });
  5036. const relNames = result.map((v) => v.relation);
  5037. const duplicateNames = relNames.filter(
  5038. (name, i) => relNames.indexOf(name) !== i
  5039. );
  5040. if (duplicateNames.length)
  5041. throw new InvalidArgumentError2(
  5042. 'The provided option "include" has duplicates of %v.',
  5043. duplicateNames[0]
  5044. );
  5045. } else if (typeof clause === "object") {
  5046. if ("relation" in clause) {
  5047. if (!clause.relation || typeof clause.relation !== "string")
  5048. throw new InvalidArgumentError2(
  5049. 'The provided option "relation" should be a non-empty String, but %v given.',
  5050. clause.relation
  5051. );
  5052. const normalized = { relation: clause.relation };
  5053. const scope = this.normalizeScopeClause(clause.scope);
  5054. if (scope) normalized.scope = scope;
  5055. result.push(normalized);
  5056. } else {
  5057. Object.keys(clause).forEach((key) => {
  5058. if (!Object.prototype.hasOwnProperty.call(clause, key)) return;
  5059. this.validateIncludeClause(key);
  5060. const normalized = { relation: key };
  5061. const include = this.normalizeIncludeClause(clause[key]);
  5062. if (include.length) normalized.scope = { include };
  5063. result.push(normalized);
  5064. });
  5065. }
  5066. } else {
  5067. throw new InvalidArgumentError2(
  5068. 'The provided option "include" should have a non-empty String, an Object or an Array, but %v given.',
  5069. clause
  5070. );
  5071. }
  5072. return result;
  5073. }
  5074. /**
  5075. * Normalize scope clause.
  5076. *
  5077. * @param {object|undefined} clause
  5078. * @returns {object|undefined}
  5079. */
  5080. static normalizeScopeClause(clause) {
  5081. if (clause == null) return;
  5082. if (typeof clause !== "object" || Array.isArray(clause))
  5083. throw new InvalidArgumentError2(
  5084. 'The provided option "scope" should be an Object, but %v given.',
  5085. clause
  5086. );
  5087. const result = {};
  5088. if (clause.where != null) {
  5089. WhereClauseTool.validateWhereClause(clause.where);
  5090. result.where = clause.where;
  5091. }
  5092. if (clause.order != null) {
  5093. OrderClauseTool.validateOrderClause(clause.order);
  5094. result.order = clause.order;
  5095. }
  5096. if (clause.skip != null) {
  5097. SliceClauseTool.validateSkipClause(clause.skip);
  5098. result.skip = clause.skip;
  5099. }
  5100. if (clause.limit != null) {
  5101. SliceClauseTool.validateLimitClause(clause.limit);
  5102. result.limit = clause.limit;
  5103. }
  5104. if (clause.fields != null) {
  5105. FieldsClauseTool.validateFieldsClause(clause.fields);
  5106. result.fields = clause.fields;
  5107. }
  5108. if (clause.include != null) {
  5109. result.include = this.normalizeIncludeClause(clause.include);
  5110. }
  5111. if (Object.keys(result).length) return result;
  5112. return void 0;
  5113. }
  5114. };
  5115. __name(_IncludeClauseTool, "IncludeClauseTool");
  5116. IncludeClauseTool = _IncludeClauseTool;
  5117. }
  5118. });
  5119. // src/filter/index.js
  5120. var init_filter = __esm({
  5121. "src/filter/index.js"() {
  5122. "use strict";
  5123. init_slice_clause_tool();
  5124. init_order_clause_tool();
  5125. init_where_clause_tool();
  5126. init_fields_clause_tool();
  5127. init_include_clause_tool();
  5128. init_operator_clause_tool();
  5129. }
  5130. });
  5131. // src/adapter/decorator/inclusion-decorator.js
  5132. var _InclusionDecorator, InclusionDecorator;
  5133. var init_inclusion_decorator = __esm({
  5134. "src/adapter/decorator/inclusion-decorator.js"() {
  5135. "use strict";
  5136. init_adapter();
  5137. init_src2();
  5138. init_filter();
  5139. init_errors2();
  5140. _InclusionDecorator = class _InclusionDecorator extends Service {
  5141. /**
  5142. * Decorate.
  5143. *
  5144. * @param {Adapter} adapter
  5145. */
  5146. decorate(adapter) {
  5147. if (!adapter || !(adapter instanceof Adapter))
  5148. throw new InvalidArgumentError2(
  5149. "The first argument of InclusionDecorator.decorate should be an Adapter instance, but %v given.",
  5150. adapter
  5151. );
  5152. const tool = adapter.getService(IncludeClauseTool);
  5153. const includeTo = /* @__PURE__ */ __name((...args) => tool.includeTo(...args), "includeTo");
  5154. const create = adapter.create;
  5155. adapter.create = async function(modelName, modelData, filter) {
  5156. const retvalData = await create.call(this, modelName, modelData, filter);
  5157. if (filter && typeof filter === "object" && filter.include)
  5158. await includeTo([retvalData], modelName, filter.include);
  5159. return retvalData;
  5160. };
  5161. const replaceById = adapter.replaceById;
  5162. adapter.replaceById = async function(modelName, id, modelData, filter) {
  5163. const retvalData = await replaceById.call(
  5164. this,
  5165. modelName,
  5166. id,
  5167. modelData,
  5168. filter
  5169. );
  5170. if (filter && typeof filter === "object" && filter.include)
  5171. await includeTo([retvalData], modelName, filter.include);
  5172. return retvalData;
  5173. };
  5174. const replaceOrCreate = adapter.replaceOrCreate;
  5175. adapter.replaceOrCreate = async function(modelName, modelData, filter) {
  5176. const retvalData = await replaceOrCreate.call(
  5177. this,
  5178. modelName,
  5179. modelData,
  5180. filter
  5181. );
  5182. if (filter && typeof filter === "object" && filter.include)
  5183. await includeTo([retvalData], modelName, filter.include);
  5184. return retvalData;
  5185. };
  5186. const patchById = adapter.patchById;
  5187. adapter.patchById = async function(modelName, id, modelData, filter) {
  5188. const retvalData = await patchById.call(
  5189. this,
  5190. modelName,
  5191. id,
  5192. modelData,
  5193. filter
  5194. );
  5195. if (filter && typeof filter === "object" && filter.include)
  5196. await includeTo([retvalData], modelName, filter.include);
  5197. return retvalData;
  5198. };
  5199. const find = adapter.find;
  5200. adapter.find = async function(modelName, filter) {
  5201. const modelItems = await find.call(this, modelName, filter);
  5202. if (filter && typeof filter === "object" && filter.include)
  5203. await includeTo(modelItems, modelName, filter.include);
  5204. return modelItems;
  5205. };
  5206. const findById = adapter.findById;
  5207. adapter.findById = async function(modelName, id, filter) {
  5208. const retvalData = await findById.call(this, modelName, id, filter);
  5209. if (filter && typeof filter === "object" && filter.include)
  5210. await includeTo([retvalData], modelName, filter.include);
  5211. return retvalData;
  5212. };
  5213. }
  5214. };
  5215. __name(_InclusionDecorator, "InclusionDecorator");
  5216. InclusionDecorator = _InclusionDecorator;
  5217. }
  5218. });
  5219. // src/adapter/decorator/default-values-decorator.js
  5220. var _DefaultValuesDecorator, DefaultValuesDecorator;
  5221. var init_default_values_decorator = __esm({
  5222. "src/adapter/decorator/default-values-decorator.js"() {
  5223. "use strict";
  5224. init_adapter();
  5225. init_src2();
  5226. init_errors2();
  5227. init_definition();
  5228. _DefaultValuesDecorator = class _DefaultValuesDecorator extends Service {
  5229. /**
  5230. * Decorate.
  5231. *
  5232. * @param {Adapter} adapter
  5233. */
  5234. decorate(adapter) {
  5235. if (!adapter || !(adapter instanceof Adapter))
  5236. throw new InvalidArgumentError2(
  5237. "The first argument of DefaultValuesDecorator.decorate should be an Adapter instance, but %v given.",
  5238. adapter
  5239. );
  5240. const utils = adapter.getService(ModelDefinitionUtils);
  5241. const setDefaults = /* @__PURE__ */ __name((...args) => utils.setDefaultValuesToEmptyProperties(...args), "setDefaults");
  5242. const create = adapter.create;
  5243. adapter.create = function(modelName, modelData, filter) {
  5244. modelData = setDefaults(modelName, modelData);
  5245. return create.call(this, modelName, modelData, filter);
  5246. };
  5247. const replaceById = adapter.replaceById;
  5248. adapter.replaceById = function(modelName, id, modelData, filter) {
  5249. modelData = setDefaults(modelName, modelData);
  5250. return replaceById.call(this, modelName, id, modelData, filter);
  5251. };
  5252. const replaceOrCreate = adapter.replaceOrCreate;
  5253. adapter.replaceOrCreate = function(modelName, modelData, filter) {
  5254. modelData = setDefaults(modelName, modelData);
  5255. return replaceOrCreate.call(this, modelName, modelData, filter);
  5256. };
  5257. const patch = adapter.patch;
  5258. adapter.patch = function(modelName, modelData, where) {
  5259. modelData = setDefaults(modelName, modelData, true);
  5260. return patch.call(this, modelName, modelData, where);
  5261. };
  5262. const patchById = adapter.patchById;
  5263. adapter.patchById = function(modelName, id, modelData, filter) {
  5264. modelData = setDefaults(modelName, modelData, true);
  5265. return patchById.call(this, modelName, id, modelData, filter);
  5266. };
  5267. const find = adapter.find;
  5268. adapter.find = async function(modelName, filter) {
  5269. const modelItems = await find.call(this, modelName, filter);
  5270. return modelItems.map((modelItem) => setDefaults(modelName, modelItem));
  5271. };
  5272. const findById = adapter.findById;
  5273. adapter.findById = async function(modelName, id, filter) {
  5274. const retvalData = await findById.call(this, modelName, id, filter);
  5275. return setDefaults(modelName, retvalData);
  5276. };
  5277. }
  5278. };
  5279. __name(_DefaultValuesDecorator, "DefaultValuesDecorator");
  5280. DefaultValuesDecorator = _DefaultValuesDecorator;
  5281. }
  5282. });
  5283. // src/adapter/decorator/data-sanitizing-decorator.js
  5284. var _DataSanitizingDecorator, DataSanitizingDecorator;
  5285. var init_data_sanitizing_decorator = __esm({
  5286. "src/adapter/decorator/data-sanitizing-decorator.js"() {
  5287. "use strict";
  5288. init_adapter();
  5289. init_src2();
  5290. init_errors2();
  5291. init_definition();
  5292. _DataSanitizingDecorator = class _DataSanitizingDecorator extends Service {
  5293. /**
  5294. * Decorate.
  5295. *
  5296. * @param {Adapter} adapter
  5297. */
  5298. decorate(adapter) {
  5299. if (!adapter || !(adapter instanceof Adapter))
  5300. throw new InvalidArgumentError2(
  5301. "The first argument of DataSanitizingDecorator.decorate should be an Adapter instance, but %v given.",
  5302. adapter
  5303. );
  5304. const sanitizer = adapter.getService(ModelDataSanitizer);
  5305. const sanitize = /* @__PURE__ */ __name((...args) => sanitizer.sanitize(...args), "sanitize");
  5306. const create = adapter.create;
  5307. adapter.create = async function(modelName, modelData, filter) {
  5308. modelData = sanitize(modelName, modelData);
  5309. return create.call(this, modelName, modelData, filter);
  5310. };
  5311. const replaceById = adapter.replaceById;
  5312. adapter.replaceById = async function(modelName, id, modelData, filter) {
  5313. modelData = sanitize(modelName, modelData);
  5314. return replaceById.call(this, modelName, id, modelData, filter);
  5315. };
  5316. const replaceOrCreate = adapter.replaceOrCreate;
  5317. adapter.replaceOrCreate = async function(modelName, modelData, filter) {
  5318. modelData = sanitize(modelName, modelData);
  5319. return replaceOrCreate.call(this, modelName, modelData, filter);
  5320. };
  5321. const patch = adapter.patch;
  5322. adapter.patch = async function(modelName, modelData, where) {
  5323. modelData = sanitize(modelName, modelData);
  5324. return patch.call(this, modelName, modelData, where);
  5325. };
  5326. const patchById = adapter.patchById;
  5327. adapter.patchById = async function(modelName, id, modelData, filter) {
  5328. modelData = sanitize(modelName, modelData);
  5329. return patchById.call(this, modelName, id, modelData, filter);
  5330. };
  5331. }
  5332. };
  5333. __name(_DataSanitizingDecorator, "DataSanitizingDecorator");
  5334. DataSanitizingDecorator = _DataSanitizingDecorator;
  5335. }
  5336. });
  5337. // src/adapter/decorator/data-validation-decorator.js
  5338. var _DataValidationDecorator, DataValidationDecorator;
  5339. var init_data_validation_decorator = __esm({
  5340. "src/adapter/decorator/data-validation-decorator.js"() {
  5341. "use strict";
  5342. init_adapter();
  5343. init_src2();
  5344. init_errors2();
  5345. init_definition();
  5346. _DataValidationDecorator = class _DataValidationDecorator extends Service {
  5347. /**
  5348. * Decorate.
  5349. *
  5350. * @param {Adapter} adapter
  5351. */
  5352. decorate(adapter) {
  5353. if (!adapter || !(adapter instanceof Adapter))
  5354. throw new InvalidArgumentError2(
  5355. "The first argument of DataValidationDecorator.decorate should be an Adapter instance, but %v given.",
  5356. adapter
  5357. );
  5358. const validator = this.getService(ModelDataValidator);
  5359. const create = adapter.create;
  5360. adapter.create = function(modelName, modelData, filter) {
  5361. validator.validate(modelName, modelData);
  5362. return create.call(this, modelName, modelData, filter);
  5363. };
  5364. const replaceById = adapter.replaceById;
  5365. adapter.replaceById = function(modelName, id, modelData, filter) {
  5366. validator.validate(modelName, modelData);
  5367. return replaceById.call(this, modelName, id, modelData, filter);
  5368. };
  5369. const replaceOrCreate = adapter.replaceOrCreate;
  5370. adapter.replaceOrCreate = function(modelName, modelData, filter) {
  5371. validator.validate(modelName, modelData);
  5372. return replaceOrCreate.call(this, modelName, modelData, filter);
  5373. };
  5374. const patch = adapter.patch;
  5375. adapter.patch = function(modelName, modelData, where) {
  5376. validator.validate(modelName, modelData, true);
  5377. return patch.call(this, modelName, modelData, where);
  5378. };
  5379. const patchById = adapter.patchById;
  5380. adapter.patchById = function(modelName, id, modelData, filter) {
  5381. validator.validate(modelName, modelData, true);
  5382. return patchById.call(this, modelName, id, modelData, filter);
  5383. };
  5384. }
  5385. };
  5386. __name(_DataValidationDecorator, "DataValidationDecorator");
  5387. DataValidationDecorator = _DataValidationDecorator;
  5388. }
  5389. });
  5390. // src/adapter/decorator/fields-filtering-decorator.js
  5391. var _FieldsFilteringDecorator, FieldsFilteringDecorator;
  5392. var init_fields_filtering_decorator = __esm({
  5393. "src/adapter/decorator/fields-filtering-decorator.js"() {
  5394. "use strict";
  5395. init_adapter();
  5396. init_src2();
  5397. init_filter();
  5398. init_errors2();
  5399. _FieldsFilteringDecorator = class _FieldsFilteringDecorator extends Service {
  5400. /**
  5401. * Decorate.
  5402. *
  5403. * @param {Adapter} adapter
  5404. */
  5405. decorate(adapter) {
  5406. if (!adapter || !(adapter instanceof Adapter))
  5407. throw new InvalidArgumentError2(
  5408. "The first argument of FieldsFilteringDecorator.decorate should be an Adapter instance, but %v given.",
  5409. adapter
  5410. );
  5411. const tool = adapter.getService(FieldsClauseTool);
  5412. const selectFields = /* @__PURE__ */ __name((...args) => tool.filter(...args), "selectFields");
  5413. const create = adapter.create;
  5414. adapter.create = async function(modelName, modelData, filter) {
  5415. let result = await create.call(this, modelName, modelData, filter);
  5416. if (filter && typeof filter === "object" && filter.fields)
  5417. result = selectFields(result, modelName, filter.fields);
  5418. return result;
  5419. };
  5420. const replaceById = adapter.replaceById;
  5421. adapter.replaceById = async function(modelName, id, modelData, filter) {
  5422. let result = await replaceById.call(
  5423. this,
  5424. modelName,
  5425. id,
  5426. modelData,
  5427. filter
  5428. );
  5429. if (filter && typeof filter === "object" && filter.fields)
  5430. result = selectFields(result, modelName, filter.fields);
  5431. return result;
  5432. };
  5433. const replaceOrCreate = adapter.replaceOrCreate;
  5434. adapter.replaceOrCreate = async function(modelName, modelData, filter) {
  5435. let result = await replaceOrCreate.call(
  5436. this,
  5437. modelName,
  5438. modelData,
  5439. filter
  5440. );
  5441. if (filter && typeof filter === "object" && filter.fields)
  5442. result = selectFields(result, modelName, filter.fields);
  5443. return result;
  5444. };
  5445. const patchById = adapter.patchById;
  5446. adapter.patchById = async function(modelName, id, modelData, filter) {
  5447. let result = await patchById.call(this, modelName, id, modelData, filter);
  5448. if (filter && typeof filter === "object" && filter.fields)
  5449. result = selectFields(result, modelName, filter.fields);
  5450. return result;
  5451. };
  5452. const find = adapter.find;
  5453. adapter.find = async function(modelName, filter) {
  5454. let result = await find.call(this, modelName, filter);
  5455. if (filter && typeof filter === "object" && filter.fields)
  5456. result = selectFields(result, modelName, filter.fields);
  5457. return result;
  5458. };
  5459. const findById = adapter.findById;
  5460. adapter.findById = async function(modelName, id, filter) {
  5461. let result = await findById.call(this, modelName, id, filter);
  5462. if (filter && typeof filter === "object" && filter.fields)
  5463. result = selectFields(result, modelName, filter.fields);
  5464. return result;
  5465. };
  5466. }
  5467. };
  5468. __name(_FieldsFilteringDecorator, "FieldsFilteringDecorator");
  5469. FieldsFilteringDecorator = _FieldsFilteringDecorator;
  5470. }
  5471. });
  5472. // src/adapter/decorator/data-transformation-decorator.js
  5473. var _DataTransformationDecorator, DataTransformationDecorator;
  5474. var init_data_transformation_decorator = __esm({
  5475. "src/adapter/decorator/data-transformation-decorator.js"() {
  5476. "use strict";
  5477. init_adapter();
  5478. init_src2();
  5479. init_errors2();
  5480. init_definition();
  5481. _DataTransformationDecorator = class _DataTransformationDecorator extends Service {
  5482. /**
  5483. * Decorate.
  5484. *
  5485. * @param {Adapter} adapter
  5486. */
  5487. decorate(adapter) {
  5488. if (!adapter || !(adapter instanceof Adapter))
  5489. throw new InvalidArgumentError2(
  5490. "The first argument of DataTransformerDecorator.decorate should be an Adapter instance, but %v given.",
  5491. adapter
  5492. );
  5493. const transformer = this.getService(ModelDataTransformer);
  5494. const create = adapter.create;
  5495. adapter.create = async function(modelName, modelData, filter) {
  5496. modelData = await transformer.transform(modelName, modelData);
  5497. return create.call(this, modelName, modelData, filter);
  5498. };
  5499. const replaceById = adapter.replaceById;
  5500. adapter.replaceById = async function(modelName, id, modelData, filter) {
  5501. modelData = await transformer.transform(modelName, modelData);
  5502. return replaceById.call(this, modelName, id, modelData, filter);
  5503. };
  5504. const replaceOrCreate = adapter.replaceOrCreate;
  5505. adapter.replaceOrCreate = async function(modelName, modelData, filter) {
  5506. modelData = await transformer.transform(modelName, modelData);
  5507. return replaceOrCreate.call(this, modelName, modelData, filter);
  5508. };
  5509. const patch = adapter.patch;
  5510. adapter.patch = async function(modelName, modelData, where) {
  5511. modelData = await transformer.transform(modelName, modelData, true);
  5512. return patch.call(this, modelName, modelData, where);
  5513. };
  5514. const patchById = adapter.patchById;
  5515. adapter.patchById = async function(modelName, id, modelData, filter) {
  5516. modelData = await transformer.transform(modelName, modelData, true);
  5517. return patchById.call(this, modelName, id, modelData, filter);
  5518. };
  5519. }
  5520. };
  5521. __name(_DataTransformationDecorator, "DataTransformationDecorator");
  5522. DataTransformationDecorator = _DataTransformationDecorator;
  5523. }
  5524. });
  5525. // src/adapter/decorator/property-uniqueness-decorator.js
  5526. var _PropertyUniquenessDecorator, PropertyUniquenessDecorator;
  5527. var init_property_uniqueness_decorator = __esm({
  5528. "src/adapter/decorator/property-uniqueness-decorator.js"() {
  5529. "use strict";
  5530. init_adapter();
  5531. init_src2();
  5532. init_errors2();
  5533. init_definition();
  5534. _PropertyUniquenessDecorator = class _PropertyUniquenessDecorator extends Service {
  5535. /**
  5536. * Decorate.
  5537. *
  5538. * @param {Adapter} adapter
  5539. */
  5540. decorate(adapter) {
  5541. if (!adapter || !(adapter instanceof Adapter))
  5542. throw new InvalidArgumentError2(
  5543. "The first argument of PropertyUniquenessDecorator.decorate should be an Adapter instance, but %v given.",
  5544. adapter
  5545. );
  5546. const validator = this.getService(PropertyUniquenessValidator);
  5547. const create = adapter.create;
  5548. adapter.create = async function(modelName, modelData, filter) {
  5549. const countMethod = adapter.count.bind(adapter, modelName);
  5550. await validator.validate(countMethod, "create", modelName, modelData);
  5551. return create.call(this, modelName, modelData, filter);
  5552. };
  5553. const replaceById = adapter.replaceById;
  5554. adapter.replaceById = async function(modelName, id, modelData, filter) {
  5555. const countMethod = adapter.count.bind(adapter, modelName);
  5556. await validator.validate(
  5557. countMethod,
  5558. "replaceById",
  5559. modelName,
  5560. modelData,
  5561. id
  5562. );
  5563. return replaceById.call(this, modelName, id, modelData, filter);
  5564. };
  5565. const replaceOrCreate = adapter.replaceOrCreate;
  5566. adapter.replaceOrCreate = async function(modelName, modelData, filter) {
  5567. const countMethod = adapter.count.bind(adapter, modelName);
  5568. await validator.validate(
  5569. countMethod,
  5570. "replaceOrCreate",
  5571. modelName,
  5572. modelData
  5573. );
  5574. return replaceOrCreate.call(this, modelName, modelData, filter);
  5575. };
  5576. const patch = adapter.patch;
  5577. adapter.patch = async function(modelName, modelData, where) {
  5578. const countMethod = adapter.count.bind(adapter, modelName);
  5579. await validator.validate(countMethod, "patch", modelName, modelData);
  5580. return patch.call(this, modelName, modelData, where);
  5581. };
  5582. const patchById = adapter.patchById;
  5583. adapter.patchById = async function(modelName, id, modelData, filter) {
  5584. const countMethod = adapter.count.bind(adapter, modelName);
  5585. await validator.validate(
  5586. countMethod,
  5587. "patchById",
  5588. modelName,
  5589. modelData,
  5590. id
  5591. );
  5592. return patchById.call(this, modelName, id, modelData, filter);
  5593. };
  5594. }
  5595. };
  5596. __name(_PropertyUniquenessDecorator, "PropertyUniquenessDecorator");
  5597. PropertyUniquenessDecorator = _PropertyUniquenessDecorator;
  5598. }
  5599. });
  5600. // src/adapter/decorator/index.js
  5601. var init_decorator = __esm({
  5602. "src/adapter/decorator/index.js"() {
  5603. "use strict";
  5604. init_inclusion_decorator();
  5605. init_default_values_decorator();
  5606. init_data_sanitizing_decorator();
  5607. init_data_validation_decorator();
  5608. init_fields_filtering_decorator();
  5609. init_data_transformation_decorator();
  5610. init_property_uniqueness_decorator();
  5611. }
  5612. });
  5613. // src/adapter/adapter.js
  5614. var _Adapter, Adapter;
  5615. var init_adapter = __esm({
  5616. "src/adapter/adapter.js"() {
  5617. "use strict";
  5618. init_src2();
  5619. init_errors2();
  5620. init_decorator();
  5621. init_decorator();
  5622. init_decorator();
  5623. init_decorator();
  5624. init_decorator();
  5625. init_decorator();
  5626. init_decorator();
  5627. _Adapter = class _Adapter extends Service {
  5628. /**
  5629. * Settings.
  5630. *
  5631. * @type {object|undefined}
  5632. */
  5633. _settings;
  5634. /**
  5635. * Settings.
  5636. *
  5637. * @returns {object|undefined}
  5638. */
  5639. get settings() {
  5640. return this._settings;
  5641. }
  5642. /**
  5643. * Constructor.
  5644. *
  5645. * @param {object|undefined} container
  5646. * @param {object|undefined} settings
  5647. */
  5648. constructor(container = void 0, settings = void 0) {
  5649. super(container);
  5650. this._settings = settings;
  5651. if (this.constructor !== _Adapter) {
  5652. this.getService(DataSanitizingDecorator).decorate(this);
  5653. this.getService(DefaultValuesDecorator).decorate(this);
  5654. this.getService(DataTransformationDecorator).decorate(this);
  5655. this.getService(DataValidationDecorator).decorate(this);
  5656. this.getService(PropertyUniquenessDecorator).decorate(this);
  5657. this.getService(FieldsFilteringDecorator).decorate(this);
  5658. this.getService(InclusionDecorator).decorate(this);
  5659. }
  5660. }
  5661. /**
  5662. * Create.
  5663. *
  5664. * @param {string} modelName
  5665. * @param {object} modelData
  5666. * @param {object|undefined} filter
  5667. * @returns {Promise<object>}
  5668. */
  5669. create(modelName, modelData, filter = void 0) {
  5670. throw new NotImplementedError(
  5671. "%s.create is not implemented.",
  5672. this.constructor.name
  5673. );
  5674. }
  5675. /**
  5676. * Replace by id.
  5677. *
  5678. * @param {string} modelName
  5679. * @param {number|string} id
  5680. * @param {object} modelData
  5681. * @param {object|undefined} filter
  5682. * @returns {Promise<object>}
  5683. */
  5684. replaceById(modelName, id, modelData, filter = void 0) {
  5685. throw new NotImplementedError(
  5686. "%s.replaceById is not implemented.",
  5687. this.constructor.name
  5688. );
  5689. }
  5690. /**
  5691. * Replace or create.
  5692. *
  5693. * @param {string} modelName
  5694. * @param {object} modelData
  5695. * @param {object|undefined} filter
  5696. * @returns {Promise<object>}
  5697. */
  5698. replaceOrCreate(modelName, modelData, filter = void 0) {
  5699. throw new NotImplementedError(
  5700. "%s.replaceOrCreate is not implemented.",
  5701. this.constructor.name
  5702. );
  5703. }
  5704. /**
  5705. * Patch.
  5706. *
  5707. * @param {string} modelName
  5708. * @param {object} modelData
  5709. * @param {object|undefined} where
  5710. * @returns {Promise<number>}
  5711. */
  5712. patch(modelName, modelData, where = void 0) {
  5713. throw new NotImplementedError(
  5714. "%s.patch is not implemented.",
  5715. this.constructor.name
  5716. );
  5717. }
  5718. /**
  5719. * Patch by id.
  5720. *
  5721. * @param {string} modelName
  5722. * @param {number|string} id
  5723. * @param {object} modelData
  5724. * @param {object|undefined} filter
  5725. * @returns {Promise<object>}
  5726. */
  5727. patchById(modelName, id, modelData, filter = void 0) {
  5728. throw new NotImplementedError(
  5729. "%s.patchById is not implemented.",
  5730. this.constructor.name
  5731. );
  5732. }
  5733. /**
  5734. * Find.
  5735. *
  5736. * @param {string} modelName
  5737. * @param {object|undefined} filter
  5738. * @returns {Promise<object[]>}
  5739. */
  5740. find(modelName, filter = void 0) {
  5741. throw new NotImplementedError(
  5742. "%s.find is not implemented.",
  5743. this.constructor.name
  5744. );
  5745. }
  5746. /**
  5747. * Find by id.
  5748. *
  5749. * @param {string} modelName
  5750. * @param {number|string} id
  5751. * @param {object|undefined} filter
  5752. * @returns {Promise<object>}
  5753. */
  5754. findById(modelName, id, filter = void 0) {
  5755. throw new NotImplementedError(
  5756. "%s.findById is not implemented.",
  5757. this.constructor.name
  5758. );
  5759. }
  5760. /**
  5761. * Delete.
  5762. *
  5763. * @param {string} modelName
  5764. * @param {object|undefined} where
  5765. * @returns {Promise<number>}
  5766. */
  5767. delete(modelName, where = void 0) {
  5768. throw new NotImplementedError(
  5769. "%s.delete is not implemented.",
  5770. this.constructor.name
  5771. );
  5772. }
  5773. /**
  5774. * Delete by id.
  5775. *
  5776. * @param {string} modelName
  5777. * @param {number|string} id
  5778. * @returns {Promise<boolean>}
  5779. */
  5780. deleteById(modelName, id) {
  5781. throw new NotImplementedError(
  5782. "%s.deleteById is not implemented.",
  5783. this.constructor.name
  5784. );
  5785. }
  5786. /**
  5787. * Exists.
  5788. *
  5789. * @param {string} modelName
  5790. * @param {number|string} id
  5791. * @returns {Promise<boolean>}
  5792. */
  5793. exists(modelName, id) {
  5794. throw new NotImplementedError(
  5795. "%s.exists is not implemented.",
  5796. this.constructor.name
  5797. );
  5798. }
  5799. /**
  5800. * Count.
  5801. *
  5802. * @param {string} modelName
  5803. * @param {object|undefined} where
  5804. * @returns {Promise<number>}
  5805. */
  5806. count(modelName, where = void 0) {
  5807. throw new NotImplementedError(
  5808. "%s.count is not implemented.",
  5809. this.constructor.name
  5810. );
  5811. }
  5812. };
  5813. __name(_Adapter, "Adapter");
  5814. /**
  5815. * Kind.
  5816. *
  5817. * @type {string}
  5818. */
  5819. __publicField(_Adapter, "kind", "Adapter");
  5820. Adapter = _Adapter;
  5821. }
  5822. });
  5823. // src/adapter/builtin/memory-adapter.js
  5824. var memory_adapter_exports = {};
  5825. __export(memory_adapter_exports, {
  5826. MemoryAdapter: () => MemoryAdapter
  5827. });
  5828. var _MemoryAdapter, MemoryAdapter;
  5829. var init_memory_adapter = __esm({
  5830. "src/adapter/builtin/memory-adapter.js"() {
  5831. "use strict";
  5832. init_adapter();
  5833. init_utils2();
  5834. init_utils2();
  5835. init_definition();
  5836. init_filter();
  5837. init_filter();
  5838. init_filter();
  5839. init_errors2();
  5840. init_definition();
  5841. _MemoryAdapter = class _MemoryAdapter extends Adapter {
  5842. /**
  5843. * Tables.
  5844. *
  5845. * @type {Map<string, Map<number, Record<string, any>>>}
  5846. */
  5847. _tables = /* @__PURE__ */ new Map();
  5848. /**
  5849. * Last ids.
  5850. *
  5851. * @type {Map<string, number>}
  5852. */
  5853. _lastIds = /* @__PURE__ */ new Map();
  5854. /**
  5855. * Get table or create.
  5856. *
  5857. * @param {string} modelName
  5858. * @returns {Map<number, object>}
  5859. */
  5860. _getTableOrCreate(modelName) {
  5861. const tableName = this.getService(ModelDefinitionUtils).getTableNameByModelName(modelName);
  5862. let table = this._tables.get(tableName);
  5863. if (table) return table;
  5864. table = /* @__PURE__ */ new Map();
  5865. this._tables.set(tableName, table);
  5866. return table;
  5867. }
  5868. /**
  5869. * Gen next id value.
  5870. *
  5871. * @param {string} modelName
  5872. * @param {string} propName
  5873. * @returns {number}
  5874. */
  5875. _genNextIdValue(modelName, propName) {
  5876. var _a;
  5877. const propType = this.getService(
  5878. ModelDefinitionUtils
  5879. ).getDataTypeByPropertyName(modelName, propName);
  5880. if (propType !== DataType.ANY && propType !== DataType.NUMBER)
  5881. throw new InvalidArgumentError2(
  5882. "The memory adapter able to generate only Number identifiers, but the primary key %v of the model %v is defined as %s. Do provide your own value for the %v property, or change the type in the primary key definition to a Number that will be generated automatically.",
  5883. propName,
  5884. modelName,
  5885. capitalize(propType),
  5886. propName
  5887. );
  5888. const tableName = this.getService(ModelDefinitionUtils).getTableNameByModelName(modelName);
  5889. const lastId = (_a = this._lastIds.get(tableName)) != null ? _a : 0;
  5890. const nextId = lastId + 1;
  5891. this._lastIds.set(tableName, nextId);
  5892. const table = this._getTableOrCreate(modelName);
  5893. const existedIds = Array.from(table.keys());
  5894. if (existedIds.includes(nextId))
  5895. return this._genNextIdValue(modelName, propName);
  5896. return nextId;
  5897. }
  5898. /**
  5899. * Create
  5900. *
  5901. * @param {string} modelName
  5902. * @param {object} modelData
  5903. * @param {object|undefined} filter
  5904. * @returns {Promise<object>}
  5905. */
  5906. // eslint-disable-next-line no-unused-vars
  5907. async create(modelName, modelData, filter = void 0) {
  5908. const pkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  5909. modelName
  5910. );
  5911. let idValue = modelData[pkPropName];
  5912. if (idValue == null || idValue === "" || idValue === 0) {
  5913. idValue = this._genNextIdValue(modelName, pkPropName);
  5914. }
  5915. const table = this._getTableOrCreate(modelName);
  5916. if (table.has(idValue))
  5917. throw new InvalidArgumentError2(
  5918. "The value %v of the primary key %v already exists in the model %v.",
  5919. idValue,
  5920. pkPropName,
  5921. modelName
  5922. );
  5923. modelData = cloneDeep(modelData);
  5924. modelData[pkPropName] = idValue;
  5925. const tableData = this.getService(
  5926. ModelDefinitionUtils
  5927. ).convertPropertyNamesToColumnNames(modelName, modelData);
  5928. table.set(idValue, tableData);
  5929. return this.getService(
  5930. ModelDefinitionUtils
  5931. ).convertColumnNamesToPropertyNames(modelName, tableData);
  5932. }
  5933. /**
  5934. * Replace by id.
  5935. *
  5936. * @param {string} modelName
  5937. * @param {string|number} id
  5938. * @param {object} modelData
  5939. * @param {object|undefined} filter
  5940. * @returns {Promise<object>}
  5941. */
  5942. // eslint-disable-next-line no-unused-vars
  5943. async replaceById(modelName, id, modelData, filter = void 0) {
  5944. const table = this._getTableOrCreate(modelName);
  5945. const isExists = table.has(id);
  5946. const pkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  5947. modelName
  5948. );
  5949. if (!isExists)
  5950. throw new InvalidArgumentError2(
  5951. "The value %v of the primary key %v does not exist in the model %v.",
  5952. id,
  5953. pkPropName,
  5954. modelName
  5955. );
  5956. modelData = cloneDeep(modelData);
  5957. modelData[pkPropName] = id;
  5958. const tableData = this.getService(
  5959. ModelDefinitionUtils
  5960. ).convertPropertyNamesToColumnNames(modelName, modelData);
  5961. table.set(id, tableData);
  5962. return this.getService(
  5963. ModelDefinitionUtils
  5964. ).convertColumnNamesToPropertyNames(modelName, tableData);
  5965. }
  5966. /**
  5967. * Replace or create.
  5968. *
  5969. * @param {string} modelName
  5970. * @param {object} modelData
  5971. * @param {object|undefined} filter
  5972. * @returns {Promise<object>}
  5973. */
  5974. // eslint-disable-next-line no-unused-vars
  5975. async replaceOrCreate(modelName, modelData, filter = void 0) {
  5976. const pkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  5977. modelName
  5978. );
  5979. let idValue = modelData[pkPropName];
  5980. if (idValue == null || idValue === "" || idValue === 0) {
  5981. idValue = this._genNextIdValue(modelName, pkPropName);
  5982. }
  5983. const table = this._getTableOrCreate(modelName);
  5984. modelData = cloneDeep(modelData);
  5985. modelData[pkPropName] = idValue;
  5986. const tableData = this.getService(
  5987. ModelDefinitionUtils
  5988. ).convertPropertyNamesToColumnNames(modelName, modelData);
  5989. table.set(idValue, tableData);
  5990. return this.getService(
  5991. ModelDefinitionUtils
  5992. ).convertColumnNamesToPropertyNames(modelName, tableData);
  5993. }
  5994. /**
  5995. * Patch.
  5996. *
  5997. * @param {string} modelName
  5998. * @param {object} modelData
  5999. * @param {object|undefined} where
  6000. * @returns {Promise<number>}
  6001. */
  6002. async patch(modelName, modelData, where = void 0) {
  6003. const table = this._getTableOrCreate(modelName);
  6004. const tableItems = Array.from(table.values());
  6005. if (!tableItems.length) return 0;
  6006. let modelItems = tableItems.map(
  6007. (tableItem) => this.getService(ModelDefinitionUtils).convertColumnNamesToPropertyNames(
  6008. modelName,
  6009. tableItem
  6010. )
  6011. );
  6012. if (where && typeof where === "object")
  6013. modelItems = this.getService(WhereClauseTool).filter(modelItems, where);
  6014. const size = modelItems.length;
  6015. const pkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  6016. modelName
  6017. );
  6018. modelData = cloneDeep(modelData);
  6019. delete modelData[pkPropName];
  6020. modelItems.forEach((existingModelData) => {
  6021. const mergedModelData = Object.assign({}, existingModelData, modelData);
  6022. const mergedTableData = this.getService(
  6023. ModelDefinitionUtils
  6024. ).convertPropertyNamesToColumnNames(modelName, mergedModelData);
  6025. const idValue = existingModelData[pkPropName];
  6026. table.set(idValue, mergedTableData);
  6027. });
  6028. return size;
  6029. }
  6030. /**
  6031. * Patch by id.
  6032. *
  6033. * @param {string} modelName
  6034. * @param {string|number} id
  6035. * @param {object} modelData
  6036. * @param {object|undefined} filter
  6037. * @returns {Promise<object>}
  6038. */
  6039. // eslint-disable-next-line no-unused-vars
  6040. async patchById(modelName, id, modelData, filter = void 0) {
  6041. const table = this._getTableOrCreate(modelName);
  6042. const existingTableData = table.get(id);
  6043. const pkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  6044. modelName
  6045. );
  6046. if (existingTableData == null)
  6047. throw new InvalidArgumentError2(
  6048. "The value %v of the primary key %v does not exist in the model %v.",
  6049. id,
  6050. pkPropName,
  6051. modelName
  6052. );
  6053. modelData = cloneDeep(modelData);
  6054. delete modelData[pkPropName];
  6055. const existingModelData = this.getService(
  6056. ModelDefinitionUtils
  6057. ).convertColumnNamesToPropertyNames(modelName, existingTableData);
  6058. const mergedModelData = Object.assign({}, existingModelData, modelData);
  6059. const mergedTableData = this.getService(
  6060. ModelDefinitionUtils
  6061. ).convertPropertyNamesToColumnNames(modelName, mergedModelData);
  6062. table.set(id, mergedTableData);
  6063. return this.getService(
  6064. ModelDefinitionUtils
  6065. ).convertColumnNamesToPropertyNames(modelName, mergedTableData);
  6066. }
  6067. /**
  6068. * Find.
  6069. *
  6070. * @param {string} modelName
  6071. * @param {object|undefined} filter
  6072. * @returns {Promise<object[]>}
  6073. */
  6074. async find(modelName, filter = void 0) {
  6075. const table = this._getTableOrCreate(modelName);
  6076. const tableItems = Array.from(table.values());
  6077. let modelItems = tableItems.map(
  6078. (tableItem) => this.getService(ModelDefinitionUtils).convertColumnNamesToPropertyNames(
  6079. modelName,
  6080. tableItem
  6081. )
  6082. );
  6083. if (filter && typeof filter === "object") {
  6084. if (filter.where)
  6085. modelItems = this.getService(WhereClauseTool).filter(
  6086. modelItems,
  6087. filter.where
  6088. );
  6089. if (filter.skip || filter.limit)
  6090. modelItems = this.getService(SliceClauseTool).slice(
  6091. modelItems,
  6092. filter.skip,
  6093. filter.limit
  6094. );
  6095. if (filter.order)
  6096. this.getService(OrderClauseTool).sort(modelItems, filter.order);
  6097. }
  6098. return modelItems;
  6099. }
  6100. /**
  6101. * Find by id.
  6102. *
  6103. * @param {string} modelName
  6104. * @param {string|number} id
  6105. * @param {object|undefined} filter
  6106. * @returns {Promise<object>}
  6107. */
  6108. // eslint-disable-next-line no-unused-vars
  6109. async findById(modelName, id, filter = void 0) {
  6110. const table = this._getTableOrCreate(modelName);
  6111. const tableData = table.get(id);
  6112. const pkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  6113. modelName
  6114. );
  6115. if (!tableData)
  6116. throw new InvalidArgumentError2(
  6117. "The value %v of the primary key %v does not exist in the model %v.",
  6118. id,
  6119. pkPropName,
  6120. modelName
  6121. );
  6122. return this.getService(
  6123. ModelDefinitionUtils
  6124. ).convertColumnNamesToPropertyNames(modelName, tableData);
  6125. }
  6126. /**
  6127. * Delete.
  6128. *
  6129. * @param {string} modelName
  6130. * @param {object|undefined} where
  6131. * @returns {Promise<number>}
  6132. */
  6133. async delete(modelName, where = void 0) {
  6134. const table = this._getTableOrCreate(modelName);
  6135. const tableItems = Array.from(table.values());
  6136. if (!tableItems.length) return 0;
  6137. let modelItems = tableItems.map(
  6138. (tableItem) => this.getService(ModelDefinitionUtils).convertColumnNamesToPropertyNames(
  6139. modelName,
  6140. tableItem
  6141. )
  6142. );
  6143. if (where && typeof where === "object")
  6144. modelItems = this.getService(WhereClauseTool).filter(modelItems, where);
  6145. const size = modelItems.length;
  6146. const idPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  6147. modelName
  6148. );
  6149. modelItems.forEach((modelData) => {
  6150. const idValue = modelData[idPropName];
  6151. table.delete(idValue);
  6152. });
  6153. return size;
  6154. }
  6155. /**
  6156. * Delete by id.
  6157. *
  6158. * @param {string} modelName
  6159. * @param {string|number} id
  6160. * @returns {Promise<boolean>}
  6161. */
  6162. async deleteById(modelName, id) {
  6163. const table = this._getTableOrCreate(modelName);
  6164. const isExists = table.has(id);
  6165. table.delete(id);
  6166. return isExists;
  6167. }
  6168. /**
  6169. * Exists.
  6170. *
  6171. * @param {string} modelName
  6172. * @param {string|number} id
  6173. * @returns {Promise<boolean>}
  6174. */
  6175. async exists(modelName, id) {
  6176. const table = this._getTableOrCreate(modelName);
  6177. return table.has(id);
  6178. }
  6179. /**
  6180. * Count.
  6181. *
  6182. * @param {string} modelName
  6183. * @param {object|undefined} where
  6184. * @returns {Promise<number>}
  6185. */
  6186. async count(modelName, where = void 0) {
  6187. const table = this._getTableOrCreate(modelName);
  6188. const tableItems = Array.from(table.values());
  6189. let modelItems = tableItems.map(
  6190. (tableItem) => this.getService(ModelDefinitionUtils).convertColumnNamesToPropertyNames(
  6191. modelName,
  6192. tableItem
  6193. )
  6194. );
  6195. if (where && typeof where === "object")
  6196. modelItems = this.getService(WhereClauseTool).filter(modelItems, where);
  6197. return modelItems.length;
  6198. }
  6199. };
  6200. __name(_MemoryAdapter, "MemoryAdapter");
  6201. MemoryAdapter = _MemoryAdapter;
  6202. }
  6203. });
  6204. // import("./builtin/**/*-adapter.js") in src/adapter/adapter-loader.js
  6205. var globImport_builtin_adapter_js;
  6206. var init_ = __esm({
  6207. 'import("./builtin/**/*-adapter.js") in src/adapter/adapter-loader.js'() {
  6208. globImport_builtin_adapter_js = __glob({
  6209. "./builtin/memory-adapter.js": () => Promise.resolve().then(() => (init_memory_adapter(), memory_adapter_exports))
  6210. });
  6211. }
  6212. });
  6213. // src/adapter/adapter-loader.js
  6214. function findAdapterCtorInModule(module2) {
  6215. let adapterCtor;
  6216. if (!module2 || typeof module2 !== "object" || Array.isArray(module2)) return;
  6217. for (const ctor of Object.values(module2)) {
  6218. console.log(ctor);
  6219. if (typeof ctor === "function" && ctor.kind === Adapter.name) {
  6220. adapterCtor = ctor;
  6221. break;
  6222. }
  6223. }
  6224. return adapterCtor;
  6225. }
  6226. var _AdapterLoader, AdapterLoader;
  6227. var init_adapter_loader = __esm({
  6228. "src/adapter/adapter-loader.js"() {
  6229. "use strict";
  6230. init_adapter();
  6231. init_src2();
  6232. init_errors2();
  6233. init_();
  6234. _AdapterLoader = class _AdapterLoader extends Service {
  6235. /**
  6236. * Load by name.
  6237. *
  6238. * @param {string} adapterName
  6239. * @param {object|undefined} settings
  6240. * @returns {Promise<Adapter>}
  6241. */
  6242. async loadByName(adapterName, settings = void 0) {
  6243. if (!adapterName || typeof adapterName !== "string")
  6244. throw new InvalidArgumentError2(
  6245. "The adapter name should be a non-empty String, but %v given.",
  6246. adapterName
  6247. );
  6248. let adapterCtor;
  6249. try {
  6250. const module2 = await globImport_builtin_adapter_js(`./builtin/${adapterName}-adapter.js`);
  6251. adapterCtor = findAdapterCtorInModule(module2);
  6252. } catch (e) {
  6253. }
  6254. if (!adapterCtor)
  6255. try {
  6256. const module2 = await Promise.resolve().then(() => __toESM(require(`@e22m4u/js-repository-${adapterName}-adapter`)));
  6257. adapterCtor = findAdapterCtorInModule(module2);
  6258. } catch (e) {
  6259. }
  6260. if (!adapterCtor)
  6261. throw new InvalidArgumentError2(
  6262. "The adapter %v is not found.",
  6263. adapterName
  6264. );
  6265. return new adapterCtor(this.container, settings);
  6266. }
  6267. };
  6268. __name(_AdapterLoader, "AdapterLoader");
  6269. AdapterLoader = _AdapterLoader;
  6270. __name(findAdapterCtorInModule, "findAdapterCtorInModule");
  6271. }
  6272. });
  6273. // src/adapter/adapter-registry.js
  6274. var _AdapterRegistry, AdapterRegistry;
  6275. var init_adapter_registry = __esm({
  6276. "src/adapter/adapter-registry.js"() {
  6277. "use strict";
  6278. init_adapter();
  6279. init_src2();
  6280. init_adapter_loader();
  6281. init_definition();
  6282. _AdapterRegistry = class _AdapterRegistry extends Service {
  6283. /**
  6284. * Adapters.
  6285. *
  6286. * @type {object}
  6287. */
  6288. _adapters = {};
  6289. /**
  6290. * Get adapter.
  6291. *
  6292. * @param {string} datasourceName
  6293. * @returns {Promise<Adapter>}
  6294. */
  6295. async getAdapter(datasourceName) {
  6296. let adapter = this._adapters[datasourceName];
  6297. if (adapter) return adapter;
  6298. const datasource = this.getService(DefinitionRegistry).getDatasource(datasourceName);
  6299. const adapterName = datasource.adapter;
  6300. adapter = await this.getService(AdapterLoader).loadByName(
  6301. adapterName,
  6302. datasource
  6303. );
  6304. this._adapters[datasourceName] = adapter;
  6305. return adapter;
  6306. }
  6307. };
  6308. __name(_AdapterRegistry, "AdapterRegistry");
  6309. AdapterRegistry = _AdapterRegistry;
  6310. }
  6311. });
  6312. // src/adapter/index.js
  6313. var init_adapter2 = __esm({
  6314. "src/adapter/index.js"() {
  6315. "use strict";
  6316. init_adapter();
  6317. init_adapter_loader();
  6318. init_adapter_registry();
  6319. }
  6320. });
  6321. // src/repository/repository.js
  6322. var _Repository, Repository;
  6323. var init_repository = __esm({
  6324. "src/repository/repository.js"() {
  6325. "use strict";
  6326. init_src2();
  6327. init_adapter2();
  6328. init_adapter2();
  6329. init_errors2();
  6330. init_definition();
  6331. _Repository = class _Repository extends Service {
  6332. /**
  6333. * Model name.
  6334. *
  6335. * @type {string}
  6336. */
  6337. _modelName;
  6338. /**
  6339. * Model name.
  6340. *
  6341. * @returns {string}
  6342. */
  6343. get modelName() {
  6344. return this._modelName;
  6345. }
  6346. /**
  6347. * Datasource name.
  6348. *
  6349. * @type {string}
  6350. */
  6351. _datasourceName;
  6352. /**
  6353. * Datasource name.
  6354. *
  6355. * @returns {string}
  6356. */
  6357. get datasourceName() {
  6358. return this._datasourceName;
  6359. }
  6360. /**
  6361. * Constructor.
  6362. *
  6363. * @typedef {import('@e22m4u/js-service').ServiceContainer} ServiceContainer
  6364. * @param {ServiceContainer} container
  6365. * @param {string} modelName
  6366. */
  6367. constructor(container, modelName) {
  6368. super(container);
  6369. this._modelName = modelName;
  6370. const modelDef = this.getService(DefinitionRegistry).getModel(modelName);
  6371. const datasourceName = modelDef.datasource;
  6372. if (!datasourceName)
  6373. throw new InvalidArgumentError2(
  6374. "The model %v does not have a specified datasource.",
  6375. modelName
  6376. );
  6377. this._datasourceName = datasourceName;
  6378. }
  6379. /**
  6380. * Get adapter.
  6381. *
  6382. * @returns {Adapter}
  6383. */
  6384. async getAdapter() {
  6385. return this.getService(AdapterRegistry).getAdapter(this.datasourceName);
  6386. }
  6387. /**
  6388. * Create.
  6389. *
  6390. * @param {object} data
  6391. * @param {object|undefined} filter
  6392. * @returns {Promise<object>}
  6393. */
  6394. async create(data, filter = void 0) {
  6395. const adapter = await this.getAdapter();
  6396. return adapter.create(this.modelName, data, filter);
  6397. }
  6398. /**
  6399. * Replace by id.
  6400. *
  6401. * @param {number|string} id
  6402. * @param {object} data
  6403. * @param {object|undefined} filter
  6404. * @returns {Promise<object>}
  6405. */
  6406. async replaceById(id, data, filter = void 0) {
  6407. const adapter = await this.getAdapter();
  6408. return adapter.replaceById(this.modelName, id, data, filter);
  6409. }
  6410. /**
  6411. * Replace or create.
  6412. *
  6413. * @param {object} data
  6414. * @param {object|undefined} filter
  6415. * @returns {Promise<object>}
  6416. */
  6417. async replaceOrCreate(data, filter = void 0) {
  6418. const adapter = await this.getAdapter();
  6419. return adapter.replaceOrCreate(this.modelName, data, filter);
  6420. }
  6421. /**
  6422. * Patch.
  6423. *
  6424. * @param {object} data
  6425. * @param {object|undefined} where
  6426. * @returns {Promise<number>}
  6427. */
  6428. async patch(data, where = void 0) {
  6429. const adapter = await this.getAdapter();
  6430. return adapter.patch(this.modelName, data, where);
  6431. }
  6432. /**
  6433. * Patch by id.
  6434. *
  6435. * @param {number|string} id
  6436. * @param {object} data
  6437. * @param {object|undefined} filter
  6438. * @returns {Promise<object>}
  6439. */
  6440. async patchById(id, data, filter = void 0) {
  6441. const adapter = await this.getAdapter();
  6442. return adapter.patchById(this.modelName, id, data, filter);
  6443. }
  6444. /**
  6445. * Find.
  6446. *
  6447. * @param {object|undefined} filter
  6448. * @returns {Promise<object[]>}
  6449. */
  6450. async find(filter = void 0) {
  6451. const adapter = await this.getAdapter();
  6452. return adapter.find(this.modelName, filter);
  6453. }
  6454. /**
  6455. * Find one.
  6456. *
  6457. * @param {object|undefined} filter
  6458. * @returns {Promise<object|undefined>}
  6459. */
  6460. async findOne(filter = void 0) {
  6461. const adapter = await this.getAdapter();
  6462. filter = filter != null ? filter : {};
  6463. filter.limit = 1;
  6464. const result = await adapter.find(this.modelName, filter);
  6465. return result.length ? result[0] : void 0;
  6466. }
  6467. /**
  6468. * Find by id.
  6469. *
  6470. * @param {number|string} id
  6471. * @param {object|undefined} filter
  6472. * @returns {Promise<object>}
  6473. */
  6474. async findById(id, filter = void 0) {
  6475. const adapter = await this.getAdapter();
  6476. return adapter.findById(this.modelName, id, filter);
  6477. }
  6478. /**
  6479. * Delete.
  6480. *
  6481. * @param {object|undefined} where
  6482. * @returns {Promise<number>}
  6483. */
  6484. async delete(where = void 0) {
  6485. const adapter = await this.getAdapter();
  6486. return adapter.delete(this.modelName, where);
  6487. }
  6488. /**
  6489. * Delete by id.
  6490. *
  6491. * @param {number|string} id
  6492. * @returns {Promise<boolean>}
  6493. */
  6494. async deleteById(id) {
  6495. const adapter = await this.getAdapter();
  6496. return adapter.deleteById(this.modelName, id);
  6497. }
  6498. /**
  6499. * Exists.
  6500. *
  6501. * @param {number|string} id
  6502. * @returns {Promise<boolean>}
  6503. */
  6504. async exists(id) {
  6505. const adapter = await this.getAdapter();
  6506. return adapter.exists(this.modelName, id);
  6507. }
  6508. /**
  6509. * Count.
  6510. *
  6511. * @param {object|undefined} where
  6512. * @returns {Promise<number>}
  6513. */
  6514. async count(where = void 0) {
  6515. const adapter = await this.getAdapter();
  6516. return adapter.count(this.modelName, where);
  6517. }
  6518. };
  6519. __name(_Repository, "Repository");
  6520. Repository = _Repository;
  6521. }
  6522. });
  6523. // src/repository/repository-registry.js
  6524. var _RepositoryRegistry, RepositoryRegistry;
  6525. var init_repository_registry = __esm({
  6526. "src/repository/repository-registry.js"() {
  6527. "use strict";
  6528. init_src2();
  6529. init_repository();
  6530. init_errors2();
  6531. _RepositoryRegistry = class _RepositoryRegistry extends Service {
  6532. /**
  6533. * Repositories.
  6534. *
  6535. * @type {object}
  6536. */
  6537. _repositories = {};
  6538. /**
  6539. * Repository ctor.
  6540. *
  6541. * @type {typeof Repository}
  6542. * @private
  6543. */
  6544. _repositoryCtor = Repository;
  6545. /**
  6546. * Set repository ctor.
  6547. *
  6548. * @param {typeof Repository} ctor
  6549. */
  6550. setRepositoryCtor(ctor) {
  6551. if (!ctor || typeof ctor !== "function" || !(ctor.prototype instanceof Repository)) {
  6552. throw new InvalidArgumentError2(
  6553. "The first argument of RepositoryRegistry.setRepositoryCtor must inherit from Repository class, but %v given.",
  6554. ctor
  6555. );
  6556. }
  6557. this._repositoryCtor = ctor;
  6558. }
  6559. /**
  6560. * Get repository.
  6561. *
  6562. * @param {string} modelName
  6563. * @returns {Repository}
  6564. */
  6565. getRepository(modelName) {
  6566. let repository = this._repositories[modelName];
  6567. if (repository) return repository;
  6568. repository = new this._repositoryCtor(this.container, modelName);
  6569. this._repositories[modelName] = repository;
  6570. return repository;
  6571. }
  6572. };
  6573. __name(_RepositoryRegistry, "RepositoryRegistry");
  6574. RepositoryRegistry = _RepositoryRegistry;
  6575. }
  6576. });
  6577. // src/repository/index.js
  6578. var init_repository2 = __esm({
  6579. "src/repository/index.js"() {
  6580. "use strict";
  6581. init_repository();
  6582. init_repository_registry();
  6583. }
  6584. });
  6585. // src/index.js
  6586. var src_exports = {};
  6587. __export(src_exports, {
  6588. Adapter: () => Adapter,
  6589. AdapterLoader: () => AdapterLoader,
  6590. AdapterRegistry: () => AdapterRegistry,
  6591. BelongsToResolver: () => BelongsToResolver,
  6592. DEFAULT_PRIMARY_KEY_PROPERTY_NAME: () => DEFAULT_PRIMARY_KEY_PROPERTY_NAME,
  6593. DataType: () => DataType,
  6594. DatasourceDefinitionValidator: () => DatasourceDefinitionValidator,
  6595. DecoratorTargetType: () => DecoratorTargetType,
  6596. DefinitionRegistry: () => DefinitionRegistry,
  6597. EmptyValuesDefiner: () => EmptyValuesDefiner,
  6598. FieldsClauseTool: () => FieldsClauseTool,
  6599. HasManyResolver: () => HasManyResolver,
  6600. HasOneResolver: () => HasOneResolver,
  6601. IncludeClauseTool: () => IncludeClauseTool,
  6602. InvalidArgumentError: () => InvalidArgumentError2,
  6603. InvalidOperatorValueError: () => InvalidOperatorValueError,
  6604. ModelDataSanitizer: () => ModelDataSanitizer,
  6605. ModelDataTransformer: () => ModelDataTransformer,
  6606. ModelDataValidator: () => ModelDataValidator,
  6607. ModelDefinitionUtils: () => ModelDefinitionUtils,
  6608. ModelDefinitionValidator: () => ModelDefinitionValidator,
  6609. NotImplementedError: () => NotImplementedError,
  6610. OperatorClauseTool: () => OperatorClauseTool,
  6611. OrderClauseTool: () => OrderClauseTool,
  6612. PrimaryKeysDefinitionValidator: () => PrimaryKeysDefinitionValidator,
  6613. PropertiesDefinitionValidator: () => PropertiesDefinitionValidator,
  6614. PropertyTransformerRegistry: () => PropertyTransformerRegistry,
  6615. PropertyUniqueness: () => PropertyUniqueness,
  6616. PropertyUniquenessValidator: () => PropertyUniquenessValidator,
  6617. PropertyValidatorRegistry: () => PropertyValidatorRegistry,
  6618. ReferencesManyResolver: () => ReferencesManyResolver,
  6619. RelationType: () => RelationType,
  6620. RelationsDefinitionValidator: () => RelationsDefinitionValidator,
  6621. Repository: () => Repository,
  6622. RepositoryRegistry: () => RepositoryRegistry,
  6623. Schema: () => Schema,
  6624. SliceClauseTool: () => SliceClauseTool,
  6625. WhereClauseTool: () => WhereClauseTool,
  6626. capitalize: () => capitalize,
  6627. cloneDeep: () => cloneDeep,
  6628. excludeObjectKeys: () => excludeObjectKeys,
  6629. getCtorName: () => getCtorName,
  6630. getDecoratorTargetType: () => getDecoratorTargetType,
  6631. getValueByPath: () => getValueByPath,
  6632. isCtor: () => isCtor,
  6633. isDeepEqual: () => isDeepEqual,
  6634. isPromise: () => isPromise,
  6635. isPureObject: () => isPureObject,
  6636. selectObjectKeys: () => selectObjectKeys,
  6637. singularize: () => singularize,
  6638. stringToRegexp: () => stringToRegexp,
  6639. transformPromise: () => transformPromise
  6640. });
  6641. module.exports = __toCommonJS(src_exports);
  6642. // src/schema.js
  6643. init_src2();
  6644. init_repository2();
  6645. init_definition();
  6646. init_repository2();
  6647. var _Schema = class _Schema extends Service {
  6648. /**
  6649. * Define datasource.
  6650. *
  6651. * @param {object} datasourceDef
  6652. * @returns {this}
  6653. */
  6654. defineDatasource(datasourceDef) {
  6655. this.getService(DefinitionRegistry).addDatasource(datasourceDef);
  6656. return this;
  6657. }
  6658. /**
  6659. * Define model.
  6660. *
  6661. * @param {object} modelDef
  6662. * @returns {this}
  6663. */
  6664. defineModel(modelDef) {
  6665. this.getService(DefinitionRegistry).addModel(modelDef);
  6666. return this;
  6667. }
  6668. /**
  6669. * Get repository.
  6670. *
  6671. * @param {string} modelName
  6672. * @returns {Repository}
  6673. */
  6674. getRepository(modelName) {
  6675. return this.getService(RepositoryRegistry).getRepository(modelName);
  6676. }
  6677. };
  6678. __name(_Schema, "Schema");
  6679. var Schema = _Schema;
  6680. // src/index.js
  6681. init_utils2();
  6682. init_errors2();
  6683. init_filter();
  6684. init_adapter2();
  6685. init_relations2();
  6686. init_definition();
  6687. init_repository2();
  6688. // Annotate the CommonJS export names for ESM import in node:
  6689. 0 && (module.exports = {
  6690. Adapter,
  6691. AdapterLoader,
  6692. AdapterRegistry,
  6693. BelongsToResolver,
  6694. DEFAULT_PRIMARY_KEY_PROPERTY_NAME,
  6695. DataType,
  6696. DatasourceDefinitionValidator,
  6697. DecoratorTargetType,
  6698. DefinitionRegistry,
  6699. EmptyValuesDefiner,
  6700. FieldsClauseTool,
  6701. HasManyResolver,
  6702. HasOneResolver,
  6703. IncludeClauseTool,
  6704. InvalidArgumentError,
  6705. InvalidOperatorValueError,
  6706. ModelDataSanitizer,
  6707. ModelDataTransformer,
  6708. ModelDataValidator,
  6709. ModelDefinitionUtils,
  6710. ModelDefinitionValidator,
  6711. NotImplementedError,
  6712. OperatorClauseTool,
  6713. OrderClauseTool,
  6714. PrimaryKeysDefinitionValidator,
  6715. PropertiesDefinitionValidator,
  6716. PropertyTransformerRegistry,
  6717. PropertyUniqueness,
  6718. PropertyUniquenessValidator,
  6719. PropertyValidatorRegistry,
  6720. ReferencesManyResolver,
  6721. RelationType,
  6722. RelationsDefinitionValidator,
  6723. Repository,
  6724. RepositoryRegistry,
  6725. Schema,
  6726. SliceClauseTool,
  6727. WhereClauseTool,
  6728. capitalize,
  6729. cloneDeep,
  6730. excludeObjectKeys,
  6731. getCtorName,
  6732. getDecoratorTargetType,
  6733. getValueByPath,
  6734. isCtor,
  6735. isDeepEqual,
  6736. isPromise,
  6737. isPureObject,
  6738. selectObjectKeys,
  6739. singularize,
  6740. stringToRegexp,
  6741. transformPromise
  6742. });