index.cjs 198 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564
  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. // src/utils/is-promise.js
  41. function isPromise(value) {
  42. if (!value) return false;
  43. if (typeof value !== "object") return false;
  44. return typeof value.then === "function";
  45. }
  46. var init_is_promise = __esm({
  47. "src/utils/is-promise.js"() {
  48. "use strict";
  49. __name(isPromise, "isPromise");
  50. }
  51. });
  52. // src/utils/capitalize.js
  53. function capitalize(string) {
  54. if (!string || typeof string !== "string") return string;
  55. return string.charAt(0).toUpperCase() + string.slice(1);
  56. }
  57. var init_capitalize = __esm({
  58. "src/utils/capitalize.js"() {
  59. "use strict";
  60. __name(capitalize, "capitalize");
  61. }
  62. });
  63. // src/utils/clone-deep.js
  64. function cloneDeep(value) {
  65. if (!value) return value;
  66. const types = [Number, String, Boolean];
  67. let result;
  68. types.forEach((type) => {
  69. if (value instanceof type) result = type(value);
  70. });
  71. if (result === void 0) {
  72. if (Array.isArray(value)) {
  73. result = [];
  74. value.forEach((child, index) => {
  75. result[index] = cloneDeep(child);
  76. });
  77. } else if (typeof value === "object") {
  78. if ("nodeType" in value && value.nodeType && "cloneNode" in value && typeof value.cloneNode === "function") {
  79. result = value.cloneNode(true);
  80. } else if (!("prototype" in value) || !value.prototype) {
  81. if (value instanceof Date) {
  82. result = new Date(value);
  83. } else if (value.constructor && value.constructor.name === "Object") {
  84. result = {};
  85. for (const key in value) {
  86. result[key] = cloneDeep(value[key]);
  87. }
  88. } else {
  89. result = value;
  90. }
  91. } else {
  92. result = value;
  93. }
  94. } else {
  95. result = value;
  96. }
  97. }
  98. return result;
  99. }
  100. var init_clone_deep = __esm({
  101. "src/utils/clone-deep.js"() {
  102. "use strict";
  103. __name(cloneDeep, "cloneDeep");
  104. }
  105. });
  106. // src/utils/singularize.js
  107. function singularize(noun) {
  108. if (!noun || typeof noun !== "string") return noun;
  109. const endings = {
  110. ves: "fe",
  111. ies: "y",
  112. i: "us",
  113. zes: "ze",
  114. ses: "s",
  115. es: "e",
  116. s: ""
  117. };
  118. return noun.replace(
  119. new RegExp(`(${Object.keys(endings).join("|")})$`),
  120. (r) => endings[r]
  121. );
  122. }
  123. var init_singularize = __esm({
  124. "src/utils/singularize.js"() {
  125. "use strict";
  126. __name(singularize, "singularize");
  127. }
  128. });
  129. // src/utils/is-deep-equal.js
  130. function isDeepEqual(firstValue, secondValue) {
  131. const cached = /* @__PURE__ */ new WeakMap();
  132. const compare = /* @__PURE__ */ __name((a, b) => {
  133. if (a === null || b === null) return a === b;
  134. if (typeof a !== "object" || typeof b !== "object") return a === b;
  135. const dataTypeA = Array.isArray(a) ? "array" : "object";
  136. const dataTypeB = Array.isArray(b) ? "array" : "object";
  137. if (dataTypeA !== dataTypeB) return false;
  138. const keysA = Object.keys(a);
  139. const keysB = Object.keys(b);
  140. if (keysA.length !== keysB.length) return false;
  141. const symbolsA = Object.getOwnPropertySymbols(a);
  142. const symbolsB = Object.getOwnPropertySymbols(b);
  143. if (symbolsA.length !== symbolsB.length) return false;
  144. let setForA = cached.get(a);
  145. if (setForA == null) {
  146. setForA = /* @__PURE__ */ new Set();
  147. cached.set(a, setForA);
  148. } else if (setForA.has(b)) {
  149. return true;
  150. }
  151. setForA.add(b);
  152. let setForB = cached.get(b);
  153. if (setForB == null) {
  154. setForB = /* @__PURE__ */ new Set();
  155. cached.set(b, setForB);
  156. } else if (setForB.has(a)) {
  157. return true;
  158. }
  159. setForB.add(a);
  160. const propertyNamesA = [...keysA, ...symbolsA];
  161. for (const propertyNameA of propertyNamesA) {
  162. if (!Object.prototype.hasOwnProperty.call(b, propertyNameA)) return false;
  163. const propertyValueA = a[propertyNameA];
  164. const propertyValueB = b[propertyNameA];
  165. if (!compare(propertyValueA, propertyValueB)) return false;
  166. }
  167. return true;
  168. }, "compare");
  169. return compare(firstValue, secondValue);
  170. }
  171. var init_is_deep_equal = __esm({
  172. "src/utils/is-deep-equal.js"() {
  173. "use strict";
  174. __name(isDeepEqual, "isDeepEqual");
  175. }
  176. });
  177. // src/errors/not-implemented-error.js
  178. var import_js_format, _NotImplementedError, NotImplementedError;
  179. var init_not_implemented_error = __esm({
  180. "src/errors/not-implemented-error.js"() {
  181. "use strict";
  182. import_js_format = require("@e22m4u/js-format");
  183. _NotImplementedError = class _NotImplementedError extends import_js_format.Errorf {
  184. };
  185. __name(_NotImplementedError, "NotImplementedError");
  186. NotImplementedError = _NotImplementedError;
  187. }
  188. });
  189. // src/errors/invalid-argument-error.js
  190. var import_js_format2, _InvalidArgumentError, InvalidArgumentError;
  191. var init_invalid_argument_error = __esm({
  192. "src/errors/invalid-argument-error.js"() {
  193. "use strict";
  194. import_js_format2 = require("@e22m4u/js-format");
  195. _InvalidArgumentError = class _InvalidArgumentError extends import_js_format2.Errorf {
  196. };
  197. __name(_InvalidArgumentError, "InvalidArgumentError");
  198. InvalidArgumentError = _InvalidArgumentError;
  199. }
  200. });
  201. // src/errors/invalid-operator-value-error.js
  202. var import_js_format3, _InvalidOperatorValueError, InvalidOperatorValueError;
  203. var init_invalid_operator_value_error = __esm({
  204. "src/errors/invalid-operator-value-error.js"() {
  205. "use strict";
  206. import_js_format3 = require("@e22m4u/js-format");
  207. _InvalidOperatorValueError = class _InvalidOperatorValueError extends Error {
  208. /**
  209. * Constructor.
  210. *
  211. * @param {string} operator
  212. * @param {string} expected
  213. * @param {*} value
  214. */
  215. constructor(operator, expected, value) {
  216. super(
  217. (0, import_js_format3.format)(
  218. "Condition of {%s: ...} should have %s, but %v was given.",
  219. operator,
  220. expected,
  221. value
  222. )
  223. );
  224. }
  225. };
  226. __name(_InvalidOperatorValueError, "InvalidOperatorValueError");
  227. InvalidOperatorValueError = _InvalidOperatorValueError;
  228. }
  229. });
  230. // src/errors/index.js
  231. var init_errors = __esm({
  232. "src/errors/index.js"() {
  233. "use strict";
  234. init_not_implemented_error();
  235. init_invalid_argument_error();
  236. init_invalid_operator_value_error();
  237. }
  238. });
  239. // src/utils/like-to-regexp.js
  240. function likeToRegexp(pattern, isCaseInsensitive = false) {
  241. if (typeof pattern !== "string") {
  242. throw new InvalidArgumentError(
  243. "The first argument of `likeToRegexp` should be a String, but %v was given.",
  244. pattern
  245. );
  246. }
  247. const regexSpecials = "-[]{}()*+?.\\^$|";
  248. let regexString = "";
  249. let isEscaping = false;
  250. for (const char of pattern) {
  251. if (isEscaping) {
  252. regexString += regexSpecials.includes(char) ? `\\${char}` : char;
  253. isEscaping = false;
  254. } else if (char === "\\") {
  255. isEscaping = true;
  256. } else if (char === "%") {
  257. regexString += ".*";
  258. } else if (char === "_") {
  259. regexString += ".";
  260. } else if (regexSpecials.includes(char)) {
  261. regexString += `\\${char}`;
  262. } else {
  263. regexString += char;
  264. }
  265. }
  266. if (isEscaping) {
  267. regexString += "\\\\";
  268. }
  269. const flags = isCaseInsensitive ? "i" : "";
  270. return new RegExp(`^${regexString}$`, flags);
  271. }
  272. var init_like_to_regexp = __esm({
  273. "src/utils/like-to-regexp.js"() {
  274. "use strict";
  275. init_errors();
  276. __name(likeToRegexp, "likeToRegexp");
  277. }
  278. });
  279. // src/utils/is-plain-object.js
  280. function isPlainObject(value) {
  281. return Boolean(
  282. typeof value === "object" && value && !Array.isArray(value) && (!value.constructor || value.constructor && value.constructor.name === "Object")
  283. );
  284. }
  285. var init_is_plain_object = __esm({
  286. "src/utils/is-plain-object.js"() {
  287. "use strict";
  288. __name(isPlainObject, "isPlainObject");
  289. }
  290. });
  291. // src/utils/string-to-regexp.js
  292. function stringToRegexp(pattern, flags = void 0) {
  293. if (pattern instanceof RegExp) {
  294. return new RegExp(pattern, flags);
  295. }
  296. return new RegExp(pattern, flags);
  297. }
  298. var init_string_to_regexp = __esm({
  299. "src/utils/string-to-regexp.js"() {
  300. "use strict";
  301. __name(stringToRegexp, "stringToRegexp");
  302. }
  303. });
  304. // src/utils/get-value-by-path.js
  305. function getValueByPath(obj, path, orElse = void 0) {
  306. if (!obj || typeof obj !== "object") return orElse;
  307. if (!path || typeof path !== "string") return orElse;
  308. const keys = path.split(".");
  309. let value = obj;
  310. for (const key of keys) {
  311. if (typeof value === "object" && value !== null && key in value) {
  312. value = value[key];
  313. } else {
  314. value = orElse;
  315. break;
  316. }
  317. }
  318. return value;
  319. }
  320. var init_get_value_by_path = __esm({
  321. "src/utils/get-value-by-path.js"() {
  322. "use strict";
  323. __name(getValueByPath, "getValueByPath");
  324. }
  325. });
  326. // src/utils/select-object-keys.js
  327. function selectObjectKeys(obj, keys) {
  328. if (!obj || typeof obj !== "object" || Array.isArray(obj))
  329. throw new InvalidArgumentError(
  330. "The first argument of selectObjectKeys should be an Object, but %v was given.",
  331. obj
  332. );
  333. if (!Array.isArray(keys))
  334. throw new InvalidArgumentError(
  335. "The second argument of selectObjectKeys should be an Array of String, but %v was given.",
  336. keys
  337. );
  338. keys.forEach((key) => {
  339. if (typeof key !== "string")
  340. throw new InvalidArgumentError(
  341. "The second argument of selectObjectKeys should be an Array of String, but %v was given.",
  342. key
  343. );
  344. });
  345. const result = {};
  346. const allKeys = Object.keys(obj);
  347. allKeys.forEach((key) => {
  348. if (keys.includes(key)) result[key] = obj[key];
  349. });
  350. return result;
  351. }
  352. var init_select_object_keys = __esm({
  353. "src/utils/select-object-keys.js"() {
  354. "use strict";
  355. init_errors();
  356. __name(selectObjectKeys, "selectObjectKeys");
  357. }
  358. });
  359. // src/utils/exclude-object-keys.js
  360. function excludeObjectKeys(obj, keys) {
  361. if (typeof obj !== "object" || !obj || Array.isArray(obj))
  362. throw new InvalidArgumentError(
  363. "Cannot exclude keys from a non-Object value, %v was given.",
  364. obj
  365. );
  366. const result = { ...obj };
  367. keys = Array.isArray(keys) ? keys : [keys];
  368. keys.forEach((key) => delete result[key]);
  369. return result;
  370. }
  371. var init_exclude_object_keys = __esm({
  372. "src/utils/exclude-object-keys.js"() {
  373. "use strict";
  374. init_errors();
  375. __name(excludeObjectKeys, "excludeObjectKeys");
  376. }
  377. });
  378. // src/utils/model-name-to-model-key.js
  379. function modelNameToModelKey(modelName) {
  380. if (!modelName || typeof modelName !== "string" || /\s/.test(modelName))
  381. throw new InvalidArgumentError(
  382. "The model name should be a non-empty String without spaces, but %v was given.",
  383. modelName
  384. );
  385. return modelName.toLowerCase().replace(/[-_]/g, "");
  386. }
  387. var init_model_name_to_model_key = __esm({
  388. "src/utils/model-name-to-model-key.js"() {
  389. "use strict";
  390. init_errors();
  391. __name(modelNameToModelKey, "modelNameToModelKey");
  392. }
  393. });
  394. // src/utils/index.js
  395. var init_utils = __esm({
  396. "src/utils/index.js"() {
  397. "use strict";
  398. init_is_promise();
  399. init_capitalize();
  400. init_clone_deep();
  401. init_singularize();
  402. init_is_deep_equal();
  403. init_like_to_regexp();
  404. init_is_plain_object();
  405. init_string_to_regexp();
  406. init_get_value_by_path();
  407. init_select_object_keys();
  408. init_exclude_object_keys();
  409. init_model_name_to_model_key();
  410. }
  411. });
  412. // src/filter/slice-clause-tool.js
  413. var import_js_service, _SliceClauseTool, SliceClauseTool;
  414. var init_slice_clause_tool = __esm({
  415. "src/filter/slice-clause-tool.js"() {
  416. "use strict";
  417. import_js_service = require("@e22m4u/js-service");
  418. init_errors();
  419. _SliceClauseTool = class _SliceClauseTool extends import_js_service.Service {
  420. /**
  421. * Slice.
  422. *
  423. * @param {object[]} entities
  424. * @param {number|undefined} skip
  425. * @param {number|undefined} limit
  426. * @returns {object[]}
  427. */
  428. slice(entities, skip = void 0, limit = void 0) {
  429. if (!Array.isArray(entities))
  430. throw new InvalidArgumentError(
  431. "The first argument of SliceClauseTool.slice should be an Array, but %v was given.",
  432. entities
  433. );
  434. if (skip != null && typeof skip !== "number")
  435. throw new InvalidArgumentError(
  436. 'The provided option "skip" should be a Number, but %v was given.',
  437. skip
  438. );
  439. if (limit != null && typeof limit !== "number")
  440. throw new InvalidArgumentError(
  441. 'The provided option "limit" should be a Number, but %v was given.',
  442. limit
  443. );
  444. skip = skip || 0;
  445. limit = limit || entities.length;
  446. return entities.slice(skip, skip + limit);
  447. }
  448. /**
  449. * Validate skip clause.
  450. *
  451. * @param {number|undefined} skip
  452. */
  453. static validateSkipClause(skip) {
  454. if (skip == null) return;
  455. if (typeof skip !== "number")
  456. throw new InvalidArgumentError(
  457. 'The provided option "skip" should be a Number, but %v was given.',
  458. skip
  459. );
  460. }
  461. /**
  462. * Validate limit clause.
  463. *
  464. * @param {number|undefined} limit
  465. */
  466. static validateLimitClause(limit) {
  467. if (limit == null) return;
  468. if (typeof limit !== "number")
  469. throw new InvalidArgumentError(
  470. 'The provided option "limit" should be a Number, but %v was given.',
  471. limit
  472. );
  473. }
  474. };
  475. __name(_SliceClauseTool, "SliceClauseTool");
  476. SliceClauseTool = _SliceClauseTool;
  477. }
  478. });
  479. // src/filter/order-clause-tool.js
  480. function compareFn(a, b) {
  481. let undefinedA, undefinedB;
  482. for (let i = 0, l = this.length; i < l; i++) {
  483. const aVal = getValueByPath(a, this[i].key);
  484. const bVal = getValueByPath(b, this[i].key);
  485. undefinedB = bVal === void 0 && aVal !== void 0;
  486. undefinedA = aVal === void 0 && bVal !== void 0;
  487. if (undefinedB || aVal > bVal) {
  488. return this[i].reverse;
  489. } else if (undefinedA || aVal < bVal) {
  490. return -1 * this[i].reverse;
  491. }
  492. }
  493. return 0;
  494. }
  495. var import_js_service2, _OrderClauseTool, OrderClauseTool;
  496. var init_order_clause_tool = __esm({
  497. "src/filter/order-clause-tool.js"() {
  498. "use strict";
  499. import_js_service2 = require("@e22m4u/js-service");
  500. init_utils();
  501. init_errors();
  502. _OrderClauseTool = class _OrderClauseTool extends import_js_service2.Service {
  503. /**
  504. * Sort.
  505. *
  506. * @param {object[]} entities
  507. * @param {string|string[]|undefined} clause
  508. */
  509. sort(entities, clause) {
  510. if (clause == null) return;
  511. if (Array.isArray(clause) === false) clause = [clause];
  512. if (!clause.length) return;
  513. const mapping = [];
  514. clause.forEach((key, index) => {
  515. if (!key || typeof key !== "string")
  516. throw new InvalidArgumentError(
  517. 'The provided option "order" should be a non-empty String or an Array of non-empty String, but %v was given.',
  518. key
  519. );
  520. let reverse = 1;
  521. const matches = key.match(/\s+(A|DE)SC$/i);
  522. if (matches) {
  523. key = key.replace(/\s+(A|DE)SC/i, "");
  524. if (matches[1].toLowerCase() === "de") reverse = -1;
  525. }
  526. mapping[index] = { key, reverse };
  527. });
  528. entities.sort(compareFn.bind(mapping));
  529. }
  530. /**
  531. * Validate order clause.
  532. *
  533. * @param {string|string[]|undefined} clause
  534. */
  535. static validateOrderClause(clause) {
  536. if (clause == null) return;
  537. if (Array.isArray(clause) === false) clause = [clause];
  538. if (!clause.length) return;
  539. clause.forEach((field) => {
  540. if (!field || typeof field !== "string")
  541. throw new InvalidArgumentError(
  542. 'The provided option "order" should be a non-empty String or an Array of non-empty String, but %v was given.',
  543. field
  544. );
  545. });
  546. }
  547. /**
  548. * Normalize order clause.
  549. *
  550. * @param {string|string[]|undefined} clause
  551. * @returns {string[]|undefined}
  552. */
  553. static normalizeOrderClause(clause) {
  554. if (clause == null) return;
  555. if (Array.isArray(clause) === false) clause = [clause];
  556. if (!clause.length) return;
  557. clause.forEach((field) => {
  558. if (!field || typeof field !== "string")
  559. throw new InvalidArgumentError(
  560. 'The provided option "order" should be a non-empty String or an Array of non-empty String, but %v was given.',
  561. field
  562. );
  563. });
  564. return clause;
  565. }
  566. };
  567. __name(_OrderClauseTool, "OrderClauseTool");
  568. OrderClauseTool = _OrderClauseTool;
  569. __name(compareFn, "compareFn");
  570. }
  571. });
  572. // src/filter/operator-clause-tool.js
  573. var import_js_service3, _OperatorClauseTool, OperatorClauseTool;
  574. var init_operator_clause_tool = __esm({
  575. "src/filter/operator-clause-tool.js"() {
  576. "use strict";
  577. import_js_service3 = require("@e22m4u/js-service");
  578. init_utils();
  579. init_errors();
  580. _OperatorClauseTool = class _OperatorClauseTool extends import_js_service3.Service {
  581. /**
  582. * Compare.
  583. *
  584. * @param {*} val1 The 1st value
  585. * @param {*} val2 The 2nd value
  586. * @param {*} noTypeConversion
  587. * @returns {number} 0: =, positive: >, negative <
  588. */
  589. compare(val1, val2, noTypeConversion = false) {
  590. if (val1 === val2) {
  591. return 0;
  592. }
  593. if (val1 == null || val2 == null) {
  594. return val1 == val2 ? 0 : NaN;
  595. }
  596. const type1 = typeof val1;
  597. const type2 = typeof val2;
  598. if (type1 === "object" || type2 === "object") {
  599. return isDeepEqual(val1, val2) ? 0 : NaN;
  600. }
  601. if ((type1 === "number" || type1 === "string" || type1 === "boolean") && (type2 === "number" || type2 === "string" || type2 === "boolean")) {
  602. if (noTypeConversion && type1 !== type2) {
  603. return NaN;
  604. }
  605. const num1 = Number(val1);
  606. const num2 = Number(val2);
  607. if (!isNaN(num1) && !isNaN(num2)) {
  608. return num1 - num2;
  609. }
  610. }
  611. if (type1 === "string" && type2 === "string") {
  612. if (val1 > val2) return 1;
  613. if (val1 < val2) return -1;
  614. return 0;
  615. }
  616. return NaN;
  617. }
  618. /**
  619. * Test all operators.
  620. *
  621. * @param {object} clause
  622. * @param {*} value
  623. * @returns {boolean|undefined}
  624. */
  625. testAll(clause, value) {
  626. if (!clause || typeof clause !== "object" || Array.isArray(clause))
  627. throw new InvalidArgumentError(
  628. "The first argument of OperatorUtils.testAll should be an Object, but %v was given.",
  629. clause
  630. );
  631. const operatorMap = {
  632. eq: this.testEqNeq,
  633. neq: this.testEqNeq,
  634. gt: this.testGtLt,
  635. gte: this.testGtLt,
  636. lt: this.testGtLt,
  637. lte: this.testGtLt,
  638. inq: this.testInq,
  639. nin: this.testNin,
  640. between: this.testBetween,
  641. exists: this.testExists,
  642. like: this.testLike,
  643. nlike: this.testNlike,
  644. ilike: this.testIlike,
  645. nilike: this.testNilike,
  646. regexp: this.testRegexp
  647. };
  648. const clauseKeys = Object.keys(clause);
  649. const knownOperators = clauseKeys.filter((key) => operatorMap[key]);
  650. if (knownOperators.length === 0) {
  651. return void 0;
  652. }
  653. return knownOperators.every((op) => {
  654. const singleOpClause = { [op]: clause[op] };
  655. if (op === "regexp" && "flags" in clause) {
  656. singleOpClause.flags = clause.flags;
  657. }
  658. const testFn = operatorMap[op];
  659. const result = testFn.call(this, singleOpClause, value);
  660. return result;
  661. });
  662. }
  663. /**
  664. * Test eq/neq operator.
  665. *
  666. * @example
  667. * ```ts
  668. * {
  669. * eq: 'foo',
  670. * }
  671. * ```
  672. *
  673. * @example
  674. * ```ts
  675. * {
  676. * neq: 'foo',
  677. * }
  678. * ```
  679. *
  680. * @param {object} clause
  681. * @param {*} value
  682. * @returns {boolean|undefined}
  683. */
  684. testEqNeq(clause, value) {
  685. if (!clause || typeof clause !== "object")
  686. throw new InvalidArgumentError(
  687. "The first argument of OperatorUtils.testEqNeq should be an Object, but %v was given.",
  688. clause
  689. );
  690. if ("eq" in clause) return this.compare(clause.eq, value, true) === 0;
  691. if ("neq" in clause) return this.compare(clause.neq, value, true) !== 0;
  692. }
  693. /**
  694. * Test lt/gt/lte/gte operator.
  695. *
  696. * @example
  697. * ```ts
  698. * {
  699. * lt: 10,
  700. * }
  701. * ```
  702. *
  703. * @example
  704. * ```ts
  705. * {
  706. * lte: 10,
  707. * }
  708. * ```
  709. *
  710. * @example
  711. * ```ts
  712. * {
  713. * gt: 10,
  714. * }
  715. * ```
  716. *
  717. * @example
  718. * ```ts
  719. * {
  720. * gte: 10,
  721. * }
  722. * ```
  723. *
  724. * @param {object} clause
  725. * @param {*} value
  726. * @returns {boolean|undefined}
  727. */
  728. testGtLt(clause, value) {
  729. if (!clause || typeof clause !== "object")
  730. throw new InvalidArgumentError(
  731. "The first argument of OperatorUtils.testGtLt should be an Object, but %v was given.",
  732. clause
  733. );
  734. if ("gt" in clause) return this.compare(value, clause.gt) > 0;
  735. if ("gte" in clause) return this.compare(value, clause.gte) >= 0;
  736. if ("lt" in clause) return this.compare(value, clause.lt) < 0;
  737. if ("lte" in clause) return this.compare(value, clause.lte) <= 0;
  738. }
  739. /**
  740. * Test inc operator.
  741. *
  742. * @example
  743. * ```ts
  744. * {
  745. * inc: ['foo', 'bar'],
  746. * }
  747. * ```
  748. *
  749. * @param {object} clause
  750. * @param {*} value
  751. * @returns {boolean|undefined}
  752. */
  753. testInq(clause, value) {
  754. if (!clause || typeof clause !== "object")
  755. throw new InvalidArgumentError(
  756. "The first argument of OperatorUtils.testInq should be an Object, but %v was given.",
  757. clause
  758. );
  759. if ("inq" in clause && clause.inq !== void 0) {
  760. if (!clause.inq || !Array.isArray(clause.inq)) {
  761. throw new InvalidOperatorValueError(
  762. "inq",
  763. "an Array of possible values",
  764. clause.inq
  765. );
  766. }
  767. for (let i = 0; i < clause.inq.length; i++) {
  768. if (this.compare(clause.inq[i], value, true) === 0) {
  769. return true;
  770. }
  771. }
  772. return false;
  773. }
  774. }
  775. /**
  776. * Test nin operator.
  777. *
  778. * @example
  779. * ```ts
  780. * {
  781. * nin: ['foo', 'bar'],
  782. * }
  783. * ```
  784. *
  785. * @param {object} clause
  786. * @param {*} value
  787. * @returns {boolean|undefined}
  788. */
  789. testNin(clause, value) {
  790. if (!clause || typeof clause !== "object")
  791. throw new InvalidArgumentError(
  792. "The first argument of OperatorUtils.testNin should be an Object, but %v was given.",
  793. clause
  794. );
  795. if ("nin" in clause && clause.nin !== void 0) {
  796. if (!clause.nin || !Array.isArray(clause.nin)) {
  797. throw new InvalidOperatorValueError(
  798. "nin",
  799. "an Array of possible values",
  800. clause.nin
  801. );
  802. }
  803. return clause.nin.every((element) => {
  804. return this.compare(element, value, true) !== 0;
  805. });
  806. }
  807. }
  808. /**
  809. * Test between operator.
  810. *
  811. * @example
  812. * ```ts
  813. * {
  814. * between: [10, 20],
  815. * }
  816. * ```
  817. *
  818. * @param {object} clause
  819. * @param {*} value
  820. * @returns {boolean|undefined}
  821. */
  822. testBetween(clause, value) {
  823. if (!clause || typeof clause !== "object")
  824. throw new InvalidArgumentError(
  825. "The first argument of OperatorUtils.testBetween should be an Object, but %v was given.",
  826. clause
  827. );
  828. if ("between" in clause && clause.between !== void 0) {
  829. if (!Array.isArray(clause.between) || clause.between.length !== 2) {
  830. throw new InvalidOperatorValueError(
  831. "between",
  832. "an Array of 2 elements",
  833. clause.between
  834. );
  835. }
  836. return this.testGtLt({ gte: clause.between[0] }, value) && this.testGtLt({ lte: clause.between[1] }, value);
  837. }
  838. }
  839. /**
  840. * Test exists operator.
  841. *
  842. * @example
  843. * ```ts
  844. * {
  845. * exists: true,
  846. * }
  847. * ```
  848. *
  849. * @param {object} clause
  850. * @param {*} value
  851. * @returns {boolean|undefined}
  852. */
  853. testExists(clause, value) {
  854. if (!clause || typeof clause !== "object")
  855. throw new InvalidArgumentError(
  856. "The first argument of OperatorUtils.testExists should be an Object, but %v was given.",
  857. clause
  858. );
  859. if ("exists" in clause && clause.exists !== void 0) {
  860. if (typeof clause.exists !== "boolean") {
  861. throw new InvalidOperatorValueError(
  862. "exists",
  863. "a Boolean",
  864. clause.exists
  865. );
  866. }
  867. return clause.exists ? value !== void 0 : value === void 0;
  868. }
  869. }
  870. /**
  871. * Test like operator.
  872. *
  873. * @example
  874. * ```ts
  875. * {
  876. * like: 'foo',
  877. * }
  878. * ```
  879. *
  880. * @param {object} clause
  881. * @param {*} value
  882. * @returns {boolean|undefined}
  883. */
  884. testLike(clause, value) {
  885. if (!clause || typeof clause !== "object" || Array.isArray(clause))
  886. throw new InvalidArgumentError(
  887. "The first argument of OperatorUtils.testLike should be an Object, but %v was given.",
  888. clause
  889. );
  890. if ("like" in clause && clause.like !== void 0) {
  891. if (typeof clause.like !== "string")
  892. throw new InvalidOperatorValueError("like", "a String", clause.like);
  893. return likeToRegexp(clause.like).test(value);
  894. }
  895. }
  896. /**
  897. * Test nlike operator.
  898. *
  899. * @example
  900. * ```ts
  901. * {
  902. * nlike: 'foo',
  903. * }
  904. * ```
  905. *
  906. * @param {object} clause
  907. * @param {*} value
  908. * @returns {boolean|undefined}
  909. */
  910. testNlike(clause, value) {
  911. if (!clause || typeof clause !== "object" || Array.isArray(clause))
  912. throw new InvalidArgumentError(
  913. "The first argument of OperatorUtils.testNlike should be an Object, but %v was given.",
  914. clause
  915. );
  916. if ("nlike" in clause && clause.nlike !== void 0) {
  917. if (typeof clause.nlike !== "string") {
  918. throw new InvalidOperatorValueError("nlike", "a String", clause.nlike);
  919. }
  920. return !likeToRegexp(clause.nlike).test(value);
  921. }
  922. }
  923. /**
  924. * Test ilike operator.
  925. *
  926. * @example
  927. * ```ts
  928. * {
  929. * ilike: 'foo',
  930. * }
  931. * ```
  932. *
  933. * @param {object} clause
  934. * @param {*} value
  935. * @returns {boolean|undefined}
  936. */
  937. testIlike(clause, value) {
  938. if (!clause || typeof clause !== "object" || Array.isArray(clause))
  939. throw new InvalidArgumentError(
  940. "The first argument of OperatorUtils.testIlike should be an Object, but %v was given.",
  941. clause
  942. );
  943. if ("ilike" in clause && clause.ilike !== void 0) {
  944. if (typeof clause.ilike !== "string") {
  945. throw new InvalidOperatorValueError("ilike", "a String", clause.ilike);
  946. }
  947. return likeToRegexp(clause.ilike, true).test(value);
  948. }
  949. }
  950. /**
  951. * Test nilike operator.
  952. *
  953. * @example
  954. * ```ts
  955. * {
  956. * nilike: 'foo',
  957. * }
  958. * ```
  959. *
  960. * @param {object} clause
  961. * @param {*} value
  962. * @returns {boolean|undefined}
  963. */
  964. testNilike(clause, value) {
  965. if (!clause || typeof clause !== "object" || Array.isArray(clause))
  966. throw new InvalidArgumentError(
  967. "The first argument of OperatorUtils.testNilike should be an Object, but %v was given.",
  968. clause
  969. );
  970. if ("nilike" in clause && clause.nilike !== void 0) {
  971. if (typeof clause.nilike !== "string") {
  972. throw new InvalidOperatorValueError(
  973. "nilike",
  974. "a String",
  975. clause.nilike
  976. );
  977. }
  978. return !likeToRegexp(clause.nilike, true).test(value);
  979. }
  980. }
  981. /**
  982. * Test regexp.
  983. *
  984. * @example
  985. * ```ts
  986. * {
  987. * regexp: 'foo.*',
  988. * }
  989. * ```
  990. *
  991. * @example
  992. * ```ts
  993. * {
  994. * regexp: 'foo.*',
  995. * flags: 'i',
  996. * }
  997. * ```
  998. *
  999. * @param {object} clause
  1000. * @param {*} value
  1001. * @returns {boolean|undefined}
  1002. */
  1003. testRegexp(clause, value) {
  1004. if (!clause || typeof clause !== "object")
  1005. throw new InvalidArgumentError(
  1006. "The first argument of OperatorUtils.testRegexp should be an Object, but %v was given.",
  1007. clause
  1008. );
  1009. if ("regexp" in clause && clause.regexp !== void 0) {
  1010. if (typeof clause.regexp !== "string" && !(clause.regexp instanceof RegExp)) {
  1011. throw new InvalidOperatorValueError(
  1012. "regexp",
  1013. "a String",
  1014. clause.regexp
  1015. );
  1016. }
  1017. const flags = clause.flags || void 0;
  1018. if (flags && typeof flags !== "string")
  1019. throw new InvalidArgumentError(
  1020. "RegExp flags should be a String, but %v was given.",
  1021. clause.flags
  1022. );
  1023. if (!value || typeof value !== "string") return false;
  1024. const regExp = stringToRegexp(clause.regexp, flags);
  1025. return !!value.match(regExp);
  1026. }
  1027. }
  1028. };
  1029. __name(_OperatorClauseTool, "OperatorClauseTool");
  1030. OperatorClauseTool = _OperatorClauseTool;
  1031. }
  1032. });
  1033. // src/filter/where-clause-tool.js
  1034. var import_js_service4, _WhereClauseTool, WhereClauseTool;
  1035. var init_where_clause_tool = __esm({
  1036. "src/filter/where-clause-tool.js"() {
  1037. "use strict";
  1038. import_js_service4 = require("@e22m4u/js-service");
  1039. init_errors();
  1040. init_operator_clause_tool();
  1041. init_utils();
  1042. _WhereClauseTool = class _WhereClauseTool extends import_js_service4.Service {
  1043. /**
  1044. * Filter by where clause.
  1045. *
  1046. * @example
  1047. * ```
  1048. * const entities = [
  1049. * {foo: 1, bar: 'a'},
  1050. * {foo: 2, bar: 'b'},
  1051. * {foo: 3, bar: 'b'},
  1052. * {foo: 4, bar: 'b'},
  1053. * ];
  1054. *
  1055. * const result = filterByWhereClause(entities, {
  1056. * foo: {gt: 2},
  1057. * bar: 'b',
  1058. * });
  1059. *
  1060. * console.log(result);
  1061. * // [
  1062. * // {foo: 3, bar: 'b'},
  1063. * // {foo: 4, bar: 'b'},
  1064. * // ];
  1065. *
  1066. * ```
  1067. *
  1068. * @param {object[]} entities
  1069. * @param {WhereClause|undefined} where
  1070. * @returns {object[]}
  1071. */
  1072. filter(entities, where = void 0) {
  1073. if (!Array.isArray(entities))
  1074. throw new InvalidArgumentError(
  1075. "The first argument of WhereClauseTool.filter should be an Array of Object, but %v was given.",
  1076. entities
  1077. );
  1078. if (where == null) return entities;
  1079. return entities.filter(this._createFilter(where));
  1080. }
  1081. /**
  1082. * Create where filter.
  1083. *
  1084. * @param {WhereClause} whereClause
  1085. * @returns {Function}
  1086. */
  1087. _createFilter(whereClause) {
  1088. if (typeof whereClause !== "object" || Array.isArray(whereClause))
  1089. throw new InvalidArgumentError(
  1090. 'The provided option "where" should be an Object, but %v was given.',
  1091. whereClause
  1092. );
  1093. const keys = Object.keys(whereClause);
  1094. return (data) => {
  1095. if (typeof data !== "object")
  1096. throw new InvalidArgumentError(
  1097. "The first argument of WhereClauseTool.filter should be an Array of Object, but %v was given.",
  1098. data
  1099. );
  1100. return keys.every((key) => {
  1101. if (key === "and" && key in whereClause) {
  1102. const andClause = whereClause[key];
  1103. if (Array.isArray(andClause))
  1104. return andClause.every((clause) => this._createFilter(clause)(data));
  1105. } else if (key === "or" && key in whereClause) {
  1106. const orClause = whereClause[key];
  1107. if (Array.isArray(orClause))
  1108. return orClause.some((clause) => this._createFilter(clause)(data));
  1109. }
  1110. const value = getValueByPath(data, key);
  1111. const matcher = whereClause[key];
  1112. if (this._test(matcher, value)) return true;
  1113. });
  1114. };
  1115. }
  1116. /**
  1117. * Value testing.
  1118. *
  1119. * @param {*} example
  1120. * @param {*} value
  1121. * @returns {boolean}
  1122. */
  1123. _test(example, value) {
  1124. if (example === value) {
  1125. return true;
  1126. }
  1127. if (example === null) {
  1128. return value === null;
  1129. }
  1130. if (example === void 0) {
  1131. return value === void 0;
  1132. }
  1133. if (example instanceof RegExp) {
  1134. if (typeof value === "string") {
  1135. return example.test(value);
  1136. }
  1137. if (Array.isArray(value)) {
  1138. return value.some((el) => typeof el === "string" && example.test(el));
  1139. }
  1140. return false;
  1141. }
  1142. if (isPlainObject(example)) {
  1143. const operatorsTest = this.getService(OperatorClauseTool).testAll(
  1144. example,
  1145. value
  1146. );
  1147. if (operatorsTest !== void 0) {
  1148. if ("neq" in example && Array.isArray(value)) {
  1149. return !value.some((el) => isDeepEqual(el, example.neq));
  1150. }
  1151. return operatorsTest;
  1152. }
  1153. }
  1154. if (Array.isArray(value)) {
  1155. const isElementMatched = value.some((el) => isDeepEqual(el, example));
  1156. if (isElementMatched) return true;
  1157. }
  1158. return isDeepEqual(example, value);
  1159. }
  1160. /**
  1161. * Validate where clause.
  1162. *
  1163. * @param {WhereClause|undefined} clause
  1164. */
  1165. static validateWhereClause(clause) {
  1166. if (clause == null || typeof clause === "function") return;
  1167. if (typeof clause !== "object" || Array.isArray(clause))
  1168. throw new InvalidArgumentError(
  1169. 'The provided option "where" should be an Object, but %v was given.',
  1170. clause
  1171. );
  1172. }
  1173. };
  1174. __name(_WhereClauseTool, "WhereClauseTool");
  1175. WhereClauseTool = _WhereClauseTool;
  1176. }
  1177. });
  1178. // src/definition/model/relations/relation-type.js
  1179. var RelationType;
  1180. var init_relation_type = __esm({
  1181. "src/definition/model/relations/relation-type.js"() {
  1182. "use strict";
  1183. RelationType = {
  1184. BELONGS_TO: "belongsTo",
  1185. HAS_ONE: "hasOne",
  1186. HAS_MANY: "hasMany",
  1187. REFERENCES_MANY: "referencesMany"
  1188. };
  1189. }
  1190. });
  1191. // src/definition/model/relations/relation-definition.js
  1192. var init_relation_definition = __esm({
  1193. "src/definition/model/relations/relation-definition.js"() {
  1194. "use strict";
  1195. }
  1196. });
  1197. // src/definition/model/relations/relations-definition-validator.js
  1198. var import_js_service5, _RelationsDefinitionValidator, RelationsDefinitionValidator;
  1199. var init_relations_definition_validator = __esm({
  1200. "src/definition/model/relations/relations-definition-validator.js"() {
  1201. "use strict";
  1202. import_js_service5 = require("@e22m4u/js-service");
  1203. init_relation_type();
  1204. init_errors();
  1205. _RelationsDefinitionValidator = class _RelationsDefinitionValidator extends import_js_service5.Service {
  1206. /**
  1207. * Validate.
  1208. *
  1209. * @param {string} modelName
  1210. * @param {object} relDefs
  1211. */
  1212. validate(modelName, relDefs) {
  1213. if (!modelName || typeof modelName !== "string")
  1214. throw new InvalidArgumentError(
  1215. "The first argument of RelationsDefinitionValidator.validate should be a non-empty String, but %v was given.",
  1216. modelName
  1217. );
  1218. if (!relDefs || typeof relDefs !== "object" || Array.isArray(relDefs))
  1219. throw new InvalidArgumentError(
  1220. 'The provided option "relations" of the model %v should be an Object, but %v was given.',
  1221. modelName,
  1222. relDefs
  1223. );
  1224. const relNames = Object.keys(relDefs);
  1225. relNames.forEach((relName) => {
  1226. const relDef = relDefs[relName];
  1227. this._validateRelation(modelName, relName, relDef);
  1228. });
  1229. }
  1230. /**
  1231. * Validate relation.
  1232. *
  1233. * @param {string} modelName
  1234. * @param {string} relName
  1235. * @param {object} relDef
  1236. */
  1237. _validateRelation(modelName, relName, relDef) {
  1238. if (!modelName || typeof modelName !== "string")
  1239. throw new InvalidArgumentError(
  1240. "The first argument of RelationsDefinitionValidator._validateRelation should be a non-empty String, but %v was given.",
  1241. modelName
  1242. );
  1243. if (!relName || typeof relName !== "string")
  1244. throw new InvalidArgumentError(
  1245. "The relation name of the model %v should be a non-empty String, but %v was given.",
  1246. modelName,
  1247. relName
  1248. );
  1249. if (!relDef || typeof relDef !== "object" || Array.isArray(relDef))
  1250. throw new InvalidArgumentError(
  1251. "The relation %v of the model %v should be an Object, but %v was given.",
  1252. relName,
  1253. modelName,
  1254. relDef
  1255. );
  1256. if (!relDef.type || !Object.values(RelationType).includes(relDef.type))
  1257. throw new InvalidArgumentError(
  1258. 'The relation %v of the model %v requires the option "type" to have one of relation types: %l, but %v was given.',
  1259. relName,
  1260. modelName,
  1261. Object.values(RelationType),
  1262. relDef.type
  1263. );
  1264. this._validateBelongsTo(modelName, relName, relDef);
  1265. this._validateHasOne(modelName, relName, relDef);
  1266. this._validateHasMany(modelName, relName, relDef);
  1267. this._validateReferencesMany(modelName, relName, relDef);
  1268. }
  1269. /**
  1270. * Validate "belongsTo".
  1271. *
  1272. * @example The regular "belongsTo" relation.
  1273. * ```
  1274. * {
  1275. * type: RelationType.BELONGS_TO,
  1276. * model: 'model',
  1277. * foreignKey: 'modelId', // optional
  1278. * }
  1279. * ```
  1280. *
  1281. * @example The polymorphic "belongsTo" relation.
  1282. * ```
  1283. * {
  1284. * type: RelationType.BELONGS_TO,
  1285. * polymorphic: true,
  1286. * foreignKey: 'referenceId', // optional
  1287. * discriminator: 'referenceType', // optional
  1288. * }
  1289. * ```
  1290. *
  1291. * @param {string} modelName
  1292. * @param {string} relName
  1293. * @param {object} relDef
  1294. * @private
  1295. */
  1296. _validateBelongsTo(modelName, relName, relDef) {
  1297. if (relDef.type !== RelationType.BELONGS_TO) return;
  1298. if (relDef.polymorphic) {
  1299. if (typeof relDef.polymorphic !== "boolean")
  1300. throw new InvalidArgumentError(
  1301. 'The relation %v of the model %v has the type "belongsTo", so it expects the option "polymorphic" to be a Boolean, but %v was given.',
  1302. relName,
  1303. modelName,
  1304. relDef.polymorphic
  1305. );
  1306. if (relDef.foreignKey && typeof relDef.foreignKey !== "string")
  1307. throw new InvalidArgumentError(
  1308. '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 was given.',
  1309. relName,
  1310. modelName,
  1311. relDef.foreignKey
  1312. );
  1313. if (relDef.discriminator && typeof relDef.discriminator !== "string")
  1314. throw new InvalidArgumentError(
  1315. '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 was given.',
  1316. relName,
  1317. modelName,
  1318. relDef.discriminator
  1319. );
  1320. } else {
  1321. if (!relDef.model || typeof relDef.model !== "string")
  1322. throw new InvalidArgumentError(
  1323. '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 was given.',
  1324. relName,
  1325. modelName,
  1326. relDef.model
  1327. );
  1328. if (relDef.foreignKey && typeof relDef.foreignKey !== "string")
  1329. throw new InvalidArgumentError(
  1330. 'The relation %v of the model %v has the type "belongsTo", so it expects the provided option "foreignKey" to be a String, but %v was given.',
  1331. relName,
  1332. modelName,
  1333. relDef.foreignKey
  1334. );
  1335. if (relDef.discriminator)
  1336. throw new InvalidArgumentError(
  1337. 'The relation %v of the model %v is a non-polymorphic "belongsTo" relation, so it should not have the option "discriminator" to be provided.',
  1338. relName,
  1339. modelName
  1340. );
  1341. }
  1342. }
  1343. /**
  1344. * Validate "hasOne".
  1345. *
  1346. * @example The regular "hasOne" relation.
  1347. * ```
  1348. * {
  1349. * type: RelationType.HAS_ONE,
  1350. * model: 'model',
  1351. * foreignKey: 'modelId',
  1352. * }
  1353. * ```
  1354. *
  1355. * @example The polymorphic "hasOne" relation with a target relation name.
  1356. * ```
  1357. * {
  1358. * type: RelationType.HAS_ONE,
  1359. * model: 'model',
  1360. * polymorphic: 'reference',
  1361. * }
  1362. * ```
  1363. *
  1364. * @example The polymorphic "hasOne" relation with target relation keys.
  1365. * ```
  1366. * {
  1367. * type: RelationType.HAS_ONE,
  1368. * model: 'model',
  1369. * polymorphic: true,
  1370. * foreignKey: 'referenceId',
  1371. * discriminator: 'referenceType',
  1372. * }
  1373. * ```
  1374. *
  1375. * @param {string} modelName
  1376. * @param {string} relName
  1377. * @param {object} relDef
  1378. * @private
  1379. */
  1380. _validateHasOne(modelName, relName, relDef) {
  1381. if (relDef.type !== RelationType.HAS_ONE) return;
  1382. if (!relDef.model || typeof relDef.model !== "string")
  1383. throw new InvalidArgumentError(
  1384. '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 was given.',
  1385. relName,
  1386. modelName,
  1387. relDef.model
  1388. );
  1389. if (relDef.polymorphic) {
  1390. if (typeof relDef.polymorphic === "string") {
  1391. if (relDef.foreignKey)
  1392. throw new InvalidArgumentError(
  1393. '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.',
  1394. relName,
  1395. modelName
  1396. );
  1397. if (relDef.discriminator)
  1398. throw new InvalidArgumentError(
  1399. '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.',
  1400. relName,
  1401. modelName
  1402. );
  1403. } else if (typeof relDef.polymorphic === "boolean") {
  1404. if (!relDef.foreignKey || typeof relDef.foreignKey !== "string")
  1405. throw new InvalidArgumentError(
  1406. '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 was given.',
  1407. relName,
  1408. modelName,
  1409. relDef.foreignKey
  1410. );
  1411. if (!relDef.discriminator || typeof relDef.discriminator !== "string")
  1412. throw new InvalidArgumentError(
  1413. '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 was given.',
  1414. relName,
  1415. modelName,
  1416. relDef.discriminator
  1417. );
  1418. } else {
  1419. throw new InvalidArgumentError(
  1420. '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 was given.',
  1421. relName,
  1422. modelName,
  1423. relDef.polymorphic
  1424. );
  1425. }
  1426. } else {
  1427. if (!relDef.foreignKey || typeof relDef.foreignKey !== "string")
  1428. throw new InvalidArgumentError(
  1429. '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 was given.',
  1430. relName,
  1431. modelName,
  1432. relDef.foreignKey
  1433. );
  1434. if (relDef.discriminator)
  1435. throw new InvalidArgumentError(
  1436. 'The relation %v of the model %v is a non-polymorphic "hasOne" relation, so it should not have the option "discriminator" to be provided.',
  1437. relName,
  1438. modelName
  1439. );
  1440. }
  1441. }
  1442. /**
  1443. * Validate "hasMany".
  1444. *
  1445. * @example The regular "hasMany" relation.
  1446. * ```
  1447. * {
  1448. * type: RelationType.HAS_MANY,
  1449. * model: 'model',
  1450. * foreignKey: 'modelId',
  1451. * }
  1452. * ```
  1453. *
  1454. * @example The polymorphic "hasMany" relation with a target relation name.
  1455. * ```
  1456. * {
  1457. * type: RelationType.HAS_MANY,
  1458. * model: 'model',
  1459. * polymorphic: 'reference',
  1460. * }
  1461. * ```
  1462. *
  1463. * @example The polymorphic "hasMany" relation with target relation keys.
  1464. * ```
  1465. * {
  1466. * type: RelationType.HAS_MANY,
  1467. * model: 'model',
  1468. * polymorphic: true,
  1469. * foreignKey: 'referenceId',
  1470. * discriminator: 'referenceType',
  1471. * }
  1472. * ```
  1473. *
  1474. * @param {string} modelName
  1475. * @param {string} relName
  1476. * @param {object} relDef
  1477. * @private
  1478. */
  1479. _validateHasMany(modelName, relName, relDef) {
  1480. if (relDef.type !== RelationType.HAS_MANY) return;
  1481. if (!relDef.model || typeof relDef.model !== "string")
  1482. throw new InvalidArgumentError(
  1483. '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 was given.',
  1484. relName,
  1485. modelName,
  1486. relDef.model
  1487. );
  1488. if (relDef.polymorphic) {
  1489. if (typeof relDef.polymorphic === "string") {
  1490. if (relDef.foreignKey)
  1491. throw new InvalidArgumentError(
  1492. '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.',
  1493. relName,
  1494. modelName
  1495. );
  1496. if (relDef.discriminator)
  1497. throw new InvalidArgumentError(
  1498. '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.',
  1499. relName,
  1500. modelName
  1501. );
  1502. } else if (typeof relDef.polymorphic === "boolean") {
  1503. if (!relDef.foreignKey || typeof relDef.foreignKey !== "string")
  1504. throw new InvalidArgumentError(
  1505. '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 was given.',
  1506. relName,
  1507. modelName,
  1508. relDef.foreignKey
  1509. );
  1510. if (!relDef.discriminator || typeof relDef.discriminator !== "string")
  1511. throw new InvalidArgumentError(
  1512. '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 was given.',
  1513. relName,
  1514. modelName,
  1515. relDef.discriminator
  1516. );
  1517. } else {
  1518. throw new InvalidArgumentError(
  1519. '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 was given.',
  1520. relName,
  1521. modelName,
  1522. relDef.polymorphic
  1523. );
  1524. }
  1525. } else {
  1526. if (!relDef.foreignKey || typeof relDef.foreignKey !== "string")
  1527. throw new InvalidArgumentError(
  1528. '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 was given.',
  1529. relName,
  1530. modelName,
  1531. relDef.foreignKey
  1532. );
  1533. if (relDef.discriminator)
  1534. throw new InvalidArgumentError(
  1535. 'The relation %v of the model %v is a non-polymorphic "hasMany" relation, so it should not have the option "discriminator" to be provided.',
  1536. relName,
  1537. modelName
  1538. );
  1539. }
  1540. }
  1541. /**
  1542. * Validate "referencesMany".
  1543. *
  1544. * @example
  1545. * ```
  1546. * {
  1547. * type: RelationType.REFERENCES_MANY,
  1548. * model: 'model',
  1549. * foreignKey: 'modelIds', // optional
  1550. * }
  1551. * ```
  1552. *
  1553. * @param {string} modelName
  1554. * @param {string} relName
  1555. * @param {object} relDef
  1556. * @private
  1557. */
  1558. _validateReferencesMany(modelName, relName, relDef) {
  1559. if (relDef.type !== RelationType.REFERENCES_MANY) return;
  1560. if (!relDef.model || typeof relDef.model !== "string")
  1561. throw new InvalidArgumentError(
  1562. '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 was given.',
  1563. relName,
  1564. modelName,
  1565. relDef.model
  1566. );
  1567. if (relDef.foreignKey && typeof relDef.foreignKey !== "string")
  1568. throw new InvalidArgumentError(
  1569. 'The relation %v of the model %v has the type "referencesMany", so it expects the provided option "foreignKey" to be a String, but %v was given.',
  1570. relName,
  1571. modelName,
  1572. relDef.foreignKey
  1573. );
  1574. if (relDef.discriminator)
  1575. throw new InvalidArgumentError(
  1576. 'The relation %v of the model %v has the type "referencesMany", so it should not have the option "discriminator" to be provided.',
  1577. relName,
  1578. modelName
  1579. );
  1580. }
  1581. };
  1582. __name(_RelationsDefinitionValidator, "RelationsDefinitionValidator");
  1583. RelationsDefinitionValidator = _RelationsDefinitionValidator;
  1584. }
  1585. });
  1586. // src/definition/model/relations/index.js
  1587. var init_relations = __esm({
  1588. "src/definition/model/relations/index.js"() {
  1589. "use strict";
  1590. init_relation_type();
  1591. init_relation_definition();
  1592. init_relations_definition_validator();
  1593. }
  1594. });
  1595. // src/definition/model/properties/data-type.js
  1596. var DataType;
  1597. var init_data_type = __esm({
  1598. "src/definition/model/properties/data-type.js"() {
  1599. "use strict";
  1600. DataType = {
  1601. ANY: "any",
  1602. STRING: "string",
  1603. NUMBER: "number",
  1604. BOOLEAN: "boolean",
  1605. ARRAY: "array",
  1606. OBJECT: "object"
  1607. };
  1608. }
  1609. });
  1610. // src/definition/model/properties/property-definition.js
  1611. var init_property_definition = __esm({
  1612. "src/definition/model/properties/property-definition.js"() {
  1613. "use strict";
  1614. }
  1615. });
  1616. // src/definition/model/properties/property-uniqueness.js
  1617. var PropertyUniqueness;
  1618. var init_property_uniqueness = __esm({
  1619. "src/definition/model/properties/property-uniqueness.js"() {
  1620. "use strict";
  1621. PropertyUniqueness = {
  1622. STRICT: "strict",
  1623. SPARSE: "sparse",
  1624. NON_UNIQUE: "nonUnique"
  1625. };
  1626. }
  1627. });
  1628. // src/definition/definition-registry.js
  1629. var import_js_service6, _DefinitionRegistry, DefinitionRegistry;
  1630. var init_definition_registry = __esm({
  1631. "src/definition/definition-registry.js"() {
  1632. "use strict";
  1633. import_js_service6 = require("@e22m4u/js-service");
  1634. init_utils();
  1635. init_errors();
  1636. init_model();
  1637. init_definition();
  1638. _DefinitionRegistry = class _DefinitionRegistry extends import_js_service6.Service {
  1639. /**
  1640. * Datasources.
  1641. *
  1642. * @type {object}
  1643. */
  1644. _datasources = {};
  1645. /**
  1646. * Models.
  1647. *
  1648. * @type {object}
  1649. */
  1650. _models = {};
  1651. /**
  1652. * Add datasource.
  1653. *
  1654. * @param {object} datasourceDef
  1655. */
  1656. addDatasource(datasourceDef) {
  1657. this.getService(DatasourceDefinitionValidator).validate(datasourceDef);
  1658. const name = datasourceDef.name;
  1659. if (name in this._datasources)
  1660. throw new InvalidArgumentError(
  1661. "The datasource %v is already defined.",
  1662. name
  1663. );
  1664. this._datasources[name] = datasourceDef;
  1665. }
  1666. /**
  1667. * Has datasource.
  1668. *
  1669. * @param {string} name
  1670. * @returns {boolean}
  1671. */
  1672. hasDatasource(name) {
  1673. return Boolean(this._datasources[name]);
  1674. }
  1675. /**
  1676. * Get datasource.
  1677. *
  1678. * @param {string} name
  1679. * @returns {object}
  1680. */
  1681. getDatasource(name) {
  1682. const datasourceDef = this._datasources[name];
  1683. if (!datasourceDef)
  1684. throw new InvalidArgumentError("The datasource %v is not defined.", name);
  1685. return datasourceDef;
  1686. }
  1687. /**
  1688. * Add model.
  1689. *
  1690. * @param {object} modelDef
  1691. */
  1692. addModel(modelDef) {
  1693. this.getService(ModelDefinitionValidator).validate(modelDef);
  1694. const modelKey = modelNameToModelKey(modelDef.name);
  1695. if (modelKey in this._models)
  1696. throw new InvalidArgumentError(
  1697. "The model %v is already defined.",
  1698. modelDef.name
  1699. );
  1700. this._models[modelKey] = modelDef;
  1701. }
  1702. /**
  1703. * Has model.
  1704. *
  1705. * @param {string} name
  1706. * @returns {boolean}
  1707. */
  1708. hasModel(name) {
  1709. const modelKey = modelNameToModelKey(name);
  1710. return Boolean(this._models[modelKey]);
  1711. }
  1712. /**
  1713. * Get model.
  1714. *
  1715. * @param {string} name
  1716. * @returns {object}
  1717. */
  1718. getModel(name) {
  1719. const modelKey = modelNameToModelKey(name);
  1720. const modelDef = this._models[modelKey];
  1721. if (!modelDef)
  1722. throw new InvalidArgumentError("The model %v is not defined.", name);
  1723. return modelDef;
  1724. }
  1725. };
  1726. __name(_DefinitionRegistry, "DefinitionRegistry");
  1727. DefinitionRegistry = _DefinitionRegistry;
  1728. }
  1729. });
  1730. // src/definition/model/model-definition-utils.js
  1731. var import_js_service7, import_js_empty_values, DEFAULT_PRIMARY_KEY_PROPERTY_NAME, _ModelDefinitionUtils, ModelDefinitionUtils;
  1732. var init_model_definition_utils = __esm({
  1733. "src/definition/model/model-definition-utils.js"() {
  1734. "use strict";
  1735. import_js_service7 = require("@e22m4u/js-service");
  1736. init_properties();
  1737. import_js_empty_values = require("@e22m4u/js-empty-values");
  1738. init_errors();
  1739. init_definition_registry();
  1740. init_utils();
  1741. DEFAULT_PRIMARY_KEY_PROPERTY_NAME = "id";
  1742. _ModelDefinitionUtils = class _ModelDefinitionUtils extends import_js_service7.Service {
  1743. /**
  1744. * Get primary key as property name.
  1745. *
  1746. * @param {string} modelName
  1747. * @returns {string}
  1748. */
  1749. getPrimaryKeyAsPropertyName(modelName) {
  1750. const propDefs = this.getPropertiesDefinitionInBaseModelHierarchy(modelName);
  1751. const propNames = Object.keys(propDefs).filter((propName) => {
  1752. const propDef = propDefs[propName];
  1753. return propDef && typeof propDef === "object" && propDef.primaryKey;
  1754. });
  1755. if (propNames.length < 1) {
  1756. const isDefaultPrimaryKeyAlreadyInUse = Object.keys(propDefs).includes(
  1757. DEFAULT_PRIMARY_KEY_PROPERTY_NAME
  1758. );
  1759. if (isDefaultPrimaryKeyAlreadyInUse)
  1760. throw new InvalidArgumentError(
  1761. '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.',
  1762. DEFAULT_PRIMARY_KEY_PROPERTY_NAME,
  1763. modelName
  1764. );
  1765. return DEFAULT_PRIMARY_KEY_PROPERTY_NAME;
  1766. }
  1767. return propNames[0];
  1768. }
  1769. /**
  1770. * Get primary key as column name.
  1771. *
  1772. * @param {string} modelName
  1773. * @returns {string}
  1774. */
  1775. getPrimaryKeyAsColumnName(modelName) {
  1776. const pkPropName = this.getPrimaryKeyAsPropertyName(modelName);
  1777. let pkColName;
  1778. try {
  1779. pkColName = this.getColumnNameByPropertyName(modelName, pkPropName);
  1780. } catch (error) {
  1781. if (!(error instanceof InvalidArgumentError)) throw error;
  1782. }
  1783. if (pkColName === void 0) return pkPropName;
  1784. return pkColName;
  1785. }
  1786. /**
  1787. * Get table name by model name.
  1788. *
  1789. * @param {string} modelName
  1790. * @returns {string}
  1791. */
  1792. getTableNameByModelName(modelName) {
  1793. var _a;
  1794. const modelDef = this.getService(DefinitionRegistry).getModel(modelName);
  1795. return (_a = modelDef.tableName) != null ? _a : modelName;
  1796. }
  1797. /**
  1798. * Get column name by property name.
  1799. *
  1800. * @param {string} modelName
  1801. * @param {string} propertyName
  1802. * @returns {string}
  1803. */
  1804. getColumnNameByPropertyName(modelName, propertyName) {
  1805. var _a;
  1806. const propDefs = this.getPropertiesDefinitionInBaseModelHierarchy(modelName);
  1807. const propDef = propDefs[propertyName];
  1808. if (!propDef)
  1809. throw new InvalidArgumentError(
  1810. "The model %v does not have the property %v.",
  1811. modelName,
  1812. propertyName
  1813. );
  1814. if (propDef && typeof propDef === "object")
  1815. return (_a = propDef.columnName) != null ? _a : propertyName;
  1816. return propertyName;
  1817. }
  1818. /**
  1819. * Get default property value.
  1820. *
  1821. * @param {string} modelName
  1822. * @param {string} propertyName
  1823. * @returns {*}
  1824. */
  1825. getDefaultPropertyValue(modelName, propertyName) {
  1826. const propDefs = this.getPropertiesDefinitionInBaseModelHierarchy(modelName);
  1827. const propDef = propDefs[propertyName];
  1828. if (!propDef)
  1829. throw new InvalidArgumentError(
  1830. "The model %v does not have the property %v.",
  1831. modelName,
  1832. propertyName
  1833. );
  1834. if (propDef && typeof propDef === "object")
  1835. return propDef.default instanceof Function ? propDef.default() : propDef.default;
  1836. }
  1837. /**
  1838. * Set default values for empty properties.
  1839. *
  1840. * @param {string} modelName
  1841. * @param {object} modelData
  1842. * @param {boolean|undefined} onlyProvidedProperties
  1843. * @returns {object}
  1844. */
  1845. setDefaultValuesToEmptyProperties(modelName, modelData, onlyProvidedProperties = false) {
  1846. const propDefs = this.getPropertiesDefinitionInBaseModelHierarchy(modelName);
  1847. const propNames = onlyProvidedProperties ? Object.keys(modelData) : Object.keys(propDefs);
  1848. const extendedData = cloneDeep(modelData);
  1849. const emptyValuesService = this.getService(import_js_empty_values.EmptyValuesService);
  1850. propNames.forEach((propName) => {
  1851. const propDef = propDefs[propName];
  1852. const propValue = extendedData[propName];
  1853. const propType = propDef != null ? this.getDataTypeFromPropertyDefinition(propDef) : DataType.ANY;
  1854. const isEmpty = emptyValuesService.isEmptyByType(propType, propValue);
  1855. if (!isEmpty) return;
  1856. if (propDef && typeof propDef === "object" && propDef.default !== void 0) {
  1857. extendedData[propName] = this.getDefaultPropertyValue(
  1858. modelName,
  1859. propName
  1860. );
  1861. }
  1862. });
  1863. return extendedData;
  1864. }
  1865. /**
  1866. * Convert property names to column names.
  1867. *
  1868. * @param {string} modelName
  1869. * @param {object} modelData
  1870. * @returns {object}
  1871. */
  1872. convertPropertyNamesToColumnNames(modelName, modelData) {
  1873. const propDefs = this.getPropertiesDefinitionInBaseModelHierarchy(modelName);
  1874. const propNames = Object.keys(propDefs);
  1875. const convertedData = cloneDeep(modelData);
  1876. propNames.forEach((propName) => {
  1877. if (!(propName in convertedData)) return;
  1878. const colName = this.getColumnNameByPropertyName(modelName, propName);
  1879. let propValue = convertedData[propName];
  1880. const propDef = propDefs[propName];
  1881. if (propValue !== null && typeof propValue === "object" && !Array.isArray(propValue) && propDef !== null && typeof propDef === "object" && propDef.type === DataType.OBJECT && propDef.model) {
  1882. propValue = this.convertPropertyNamesToColumnNames(
  1883. propDef.model,
  1884. propValue
  1885. );
  1886. }
  1887. if (Array.isArray(propValue) && propDef !== null && typeof propDef === "object" && propDef.type === DataType.ARRAY && propDef.itemModel) {
  1888. propValue = propValue.map((el) => {
  1889. return el !== null && typeof el === "object" && !Array.isArray(el) ? this.convertPropertyNamesToColumnNames(propDef.itemModel, el) : el;
  1890. });
  1891. }
  1892. delete convertedData[propName];
  1893. convertedData[colName] = propValue;
  1894. });
  1895. return convertedData;
  1896. }
  1897. /**
  1898. * Convert column names to property names.
  1899. *
  1900. * @param {string} modelName
  1901. * @param {object} tableData
  1902. * @returns {object}
  1903. */
  1904. convertColumnNamesToPropertyNames(modelName, tableData) {
  1905. const propDefs = this.getPropertiesDefinitionInBaseModelHierarchy(modelName);
  1906. const propNames = Object.keys(propDefs);
  1907. const convertedData = cloneDeep(tableData);
  1908. propNames.forEach((propName) => {
  1909. const colName = this.getColumnNameByPropertyName(modelName, propName);
  1910. if (!(colName in convertedData)) return;
  1911. let colValue = convertedData[colName];
  1912. const propDef = propDefs[propName];
  1913. if (colValue !== null && typeof colValue === "object" && !Array.isArray(colValue) && propDef !== null && typeof propDef === "object" && propDef.type === DataType.OBJECT && propDef.model) {
  1914. colValue = this.convertColumnNamesToPropertyNames(
  1915. propDef.model,
  1916. colValue
  1917. );
  1918. }
  1919. if (Array.isArray(colValue) && propDef !== null && typeof propDef === "object" && propDef.type === DataType.ARRAY && propDef.itemModel) {
  1920. colValue = colValue.map((el) => {
  1921. return el !== null && typeof el === "object" && !Array.isArray(el) ? this.convertColumnNamesToPropertyNames(propDef.itemModel, el) : el;
  1922. });
  1923. }
  1924. delete convertedData[colName];
  1925. convertedData[propName] = colValue;
  1926. });
  1927. return convertedData;
  1928. }
  1929. /**
  1930. * Get data type by property name.
  1931. *
  1932. * @param {string} modelName
  1933. * @param {string} propertyName
  1934. * @returns {string}
  1935. */
  1936. getDataTypeByPropertyName(modelName, propertyName) {
  1937. const propDefs = this.getPropertiesDefinitionInBaseModelHierarchy(modelName);
  1938. const propDef = propDefs[propertyName];
  1939. if (!propDef) {
  1940. const pkPropName = this.getPrimaryKeyAsPropertyName(modelName);
  1941. if (pkPropName === propertyName) return DataType.ANY;
  1942. throw new InvalidArgumentError(
  1943. "The model %v does not have the property %v.",
  1944. modelName,
  1945. propertyName
  1946. );
  1947. }
  1948. if (typeof propDef === "string") return propDef;
  1949. return propDef.type;
  1950. }
  1951. /**
  1952. * Get data type from property definition.
  1953. *
  1954. * @param {object} propDef
  1955. * @returns {string}
  1956. */
  1957. getDataTypeFromPropertyDefinition(propDef) {
  1958. if ((!propDef || typeof propDef !== "object") && !Object.values(DataType).includes(propDef)) {
  1959. throw new InvalidArgumentError(
  1960. 'The argument "propDef" of the ModelDefinitionUtils.getDataTypeFromPropertyDefinition should be an Object or the DataType enum, but %v was given.',
  1961. propDef
  1962. );
  1963. }
  1964. if (typeof propDef === "string") return propDef;
  1965. const dataType = propDef.type;
  1966. if (!Object.values(DataType).includes(dataType))
  1967. throw new InvalidArgumentError(
  1968. 'The given Object to the ModelDefinitionUtils.getDataTypeFromPropertyDefinition should have the "type" property with one of values: %l, but %v was given.',
  1969. Object.values(DataType),
  1970. propDef.type
  1971. );
  1972. return dataType;
  1973. }
  1974. /**
  1975. * Get own properties definition of primary keys.
  1976. *
  1977. * @param {string} modelName
  1978. * @returns {object}
  1979. */
  1980. getOwnPropertiesDefinitionOfPrimaryKeys(modelName) {
  1981. var _a;
  1982. const modelDef = this.getService(DefinitionRegistry).getModel(modelName);
  1983. const propDefs = (_a = modelDef.properties) != null ? _a : {};
  1984. const pkPropNames = Object.keys(propDefs).filter((propName) => {
  1985. const propDef = propDefs[propName];
  1986. return typeof propDef === "object" && propDef.primaryKey;
  1987. });
  1988. return pkPropNames.reduce((a, k) => ({ ...a, [k]: propDefs[k] }), {});
  1989. }
  1990. /**
  1991. * Get own properties definition without primary keys.
  1992. *
  1993. * @param {string} modelName
  1994. * @returns {object}
  1995. */
  1996. getOwnPropertiesDefinitionWithoutPrimaryKeys(modelName) {
  1997. var _a;
  1998. const modelDef = this.getService(DefinitionRegistry).getModel(modelName);
  1999. const propDefs = (_a = modelDef.properties) != null ? _a : {};
  2000. return Object.keys(propDefs).reduce((result, propName) => {
  2001. const propDef = propDefs[propName];
  2002. if (typeof propDef === "object" && propDef.primaryKey) return result;
  2003. return { ...result, [propName]: propDef };
  2004. }, {});
  2005. }
  2006. /**
  2007. * Get properties definition in base model hierarchy.
  2008. *
  2009. * @param {string} modelName
  2010. * @returns {object}
  2011. */
  2012. getPropertiesDefinitionInBaseModelHierarchy(modelName) {
  2013. let pkPropDefs = {};
  2014. let regularPropDefs = {};
  2015. const recursion = /* @__PURE__ */ __name((currModelName, prevModelName = void 0) => {
  2016. if (currModelName === prevModelName)
  2017. throw new InvalidArgumentError(
  2018. "The model %v has a circular inheritance.",
  2019. currModelName
  2020. );
  2021. if (Object.keys(pkPropDefs).length === 0)
  2022. pkPropDefs = this.getOwnPropertiesDefinitionOfPrimaryKeys(currModelName);
  2023. regularPropDefs = {
  2024. ...this.getOwnPropertiesDefinitionWithoutPrimaryKeys(currModelName),
  2025. ...regularPropDefs
  2026. };
  2027. const modelDef = this.getService(DefinitionRegistry).getModel(currModelName);
  2028. if (modelDef.base) recursion(modelDef.base, currModelName);
  2029. }, "recursion");
  2030. recursion(modelName);
  2031. return { ...pkPropDefs, ...regularPropDefs };
  2032. }
  2033. /**
  2034. * Get own relations definition.
  2035. *
  2036. * @param {string} modelName
  2037. * @returns {object}
  2038. */
  2039. getOwnRelationsDefinition(modelName) {
  2040. var _a;
  2041. const modelDef = this.getService(DefinitionRegistry).getModel(modelName);
  2042. return (_a = modelDef.relations) != null ? _a : {};
  2043. }
  2044. /**
  2045. * Get relations definition in base model hierarchy.
  2046. *
  2047. * @param {string} modelName
  2048. * @returns {object}
  2049. */
  2050. getRelationsDefinitionInBaseModelHierarchy(modelName) {
  2051. let result = {};
  2052. const recursion = /* @__PURE__ */ __name((currModelName, prevModelName = void 0) => {
  2053. var _a;
  2054. if (currModelName === prevModelName)
  2055. throw new InvalidArgumentError(
  2056. "The model %v has a circular inheritance.",
  2057. currModelName
  2058. );
  2059. const modelDef = this.getService(DefinitionRegistry).getModel(currModelName);
  2060. const ownRelDefs = (_a = modelDef.relations) != null ? _a : {};
  2061. result = { ...ownRelDefs, ...result };
  2062. if (modelDef.base) recursion(modelDef.base, currModelName);
  2063. }, "recursion");
  2064. recursion(modelName);
  2065. return result;
  2066. }
  2067. /**
  2068. * Get relation definition by name.
  2069. *
  2070. * @param {string} modelName
  2071. * @param {string} relationName
  2072. * @returns {object}
  2073. */
  2074. getRelationDefinitionByName(modelName, relationName) {
  2075. const relDefs = this.getRelationsDefinitionInBaseModelHierarchy(modelName);
  2076. const relNames = Object.keys(relDefs);
  2077. let foundDef;
  2078. for (const relName of relNames) {
  2079. if (relName === relationName) {
  2080. foundDef = relDefs[relName];
  2081. break;
  2082. }
  2083. }
  2084. if (!foundDef)
  2085. throw new InvalidArgumentError(
  2086. "The model %v does not have relation name %v.",
  2087. modelName,
  2088. relationName
  2089. );
  2090. return foundDef;
  2091. }
  2092. /**
  2093. * Exclude object keys by relation names.
  2094. *
  2095. * @param {string} modelName
  2096. * @param {object} modelData
  2097. * @returns {object}
  2098. */
  2099. excludeObjectKeysByRelationNames(modelName, modelData) {
  2100. if (!modelData || typeof modelData !== "object" || Array.isArray(modelData))
  2101. throw new InvalidArgumentError(
  2102. "The second argument of ModelDefinitionUtils.excludeObjectKeysByRelationNames should be an Object, but %v was given.",
  2103. modelData
  2104. );
  2105. const relDefs = this.getRelationsDefinitionInBaseModelHierarchy(modelName);
  2106. const relNames = Object.keys(relDefs);
  2107. return excludeObjectKeys(modelData, relNames);
  2108. }
  2109. /**
  2110. * Get model name of property value if defined.
  2111. *
  2112. * @param {string} modelName
  2113. * @param {string} propertyName
  2114. * @returns {string|undefined}
  2115. */
  2116. getModelNameOfPropertyValueIfDefined(modelName, propertyName) {
  2117. if (!modelName || typeof modelName !== "string")
  2118. throw new InvalidArgumentError(
  2119. 'Parameter "modelName" of ModelDefinitionUtils.getModelNameOfPropertyValueIfDefined requires a non-empty String, but %v was given.',
  2120. modelName
  2121. );
  2122. if (!propertyName || typeof propertyName !== "string")
  2123. throw new InvalidArgumentError(
  2124. 'Parameter "propertyName" of ModelDefinitionUtils.getModelNameOfPropertyValueIfDefined requires a non-empty String, but %v was given.',
  2125. propertyName
  2126. );
  2127. const propDefs = this.getPropertiesDefinitionInBaseModelHierarchy(modelName);
  2128. const propDef = propDefs[propertyName];
  2129. if (!propDef) return void 0;
  2130. if (propDef && typeof propDef === "object") {
  2131. if (propDef.type === DataType.OBJECT) return propDef.model || void 0;
  2132. if (propDef.type === DataType.ARRAY)
  2133. return propDef.itemModel || void 0;
  2134. }
  2135. return void 0;
  2136. }
  2137. };
  2138. __name(_ModelDefinitionUtils, "ModelDefinitionUtils");
  2139. ModelDefinitionUtils = _ModelDefinitionUtils;
  2140. }
  2141. });
  2142. // src/definition/model/properties/property-uniqueness-validator.js
  2143. var import_js_service8, import_js_empty_values2, _PropertyUniquenessValidator, PropertyUniquenessValidator;
  2144. var init_property_uniqueness_validator = __esm({
  2145. "src/definition/model/properties/property-uniqueness-validator.js"() {
  2146. "use strict";
  2147. init_data_type();
  2148. import_js_service8 = require("@e22m4u/js-service");
  2149. init_utils();
  2150. import_js_empty_values2 = require("@e22m4u/js-empty-values");
  2151. init_property_uniqueness();
  2152. init_errors();
  2153. init_model_definition_utils();
  2154. _PropertyUniquenessValidator = class _PropertyUniquenessValidator extends import_js_service8.Service {
  2155. /**
  2156. * Validate.
  2157. *
  2158. * @param {Function} countMethod
  2159. * @param {string} methodName
  2160. * @param {string} modelName
  2161. * @param {object} modelData
  2162. * @param {*} modelId
  2163. * @returns {Promise<undefined>}
  2164. */
  2165. async validate(countMethod, methodName, modelName, modelData, modelId = void 0) {
  2166. if (typeof countMethod !== "function")
  2167. throw new InvalidArgumentError(
  2168. 'The parameter "countMethod" of the PropertyUniquenessValidator must be a Function, but %v was given.',
  2169. countMethod
  2170. );
  2171. if (!methodName || typeof methodName !== "string")
  2172. throw new InvalidArgumentError(
  2173. 'The parameter "methodName" of the PropertyUniquenessValidator must be a non-empty String, but %v was given.',
  2174. methodName
  2175. );
  2176. if (!modelName || typeof modelName !== "string")
  2177. throw new InvalidArgumentError(
  2178. 'The parameter "modelName" of the PropertyUniquenessValidator must be a non-empty String, but %v was given.',
  2179. modelName
  2180. );
  2181. if (!isPlainObject(modelData))
  2182. throw new InvalidArgumentError(
  2183. "The data of the model %v should be an Object, but %v was given.",
  2184. modelName,
  2185. modelData
  2186. );
  2187. const propDefs = this.getService(
  2188. ModelDefinitionUtils
  2189. ).getPropertiesDefinitionInBaseModelHierarchy(modelName);
  2190. const isPartial = methodName === "patch" || methodName === "patchById";
  2191. const propNames = Object.keys(isPartial ? modelData : propDefs);
  2192. const idProp = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  2193. modelName
  2194. );
  2195. const createError = /* @__PURE__ */ __name((propName, propValue) => new InvalidArgumentError(
  2196. "An existing document of the model %v already has the property %v with the value %v and should be unique.",
  2197. modelName,
  2198. propName,
  2199. propValue
  2200. ), "createError");
  2201. let willBeReplaced = void 0;
  2202. const emptyValuesService = this.getService(import_js_empty_values2.EmptyValuesService);
  2203. for (const propName of propNames) {
  2204. const propDef = propDefs[propName];
  2205. if (!propDef || typeof propDef === "string" || !propDef.unique || propDef.unique === PropertyUniqueness.NON_UNIQUE) {
  2206. continue;
  2207. }
  2208. const propValue = modelData[propName];
  2209. if (propDef.unique === PropertyUniqueness.SPARSE) {
  2210. const propType = propDef.type || DataType.ANY;
  2211. const isEmpty = emptyValuesService.isEmptyByType(propType, propValue);
  2212. if (isEmpty) continue;
  2213. }
  2214. if (methodName === "create") {
  2215. const count = await countMethod({ [propName]: propValue });
  2216. if (count > 0) throw createError(propName, propValue);
  2217. } else if (methodName === "replaceById") {
  2218. const count = await countMethod({
  2219. [idProp]: { neq: modelId },
  2220. [propName]: propValue
  2221. });
  2222. if (count > 0) throw createError(propName, propValue);
  2223. } else if (methodName === "replaceOrCreate") {
  2224. const idFromData = modelData[idProp];
  2225. if (willBeReplaced == null && idFromData != null) {
  2226. const count = await countMethod({ [idProp]: idFromData });
  2227. willBeReplaced = count > 0;
  2228. }
  2229. if (willBeReplaced) {
  2230. const count = await countMethod({
  2231. [idProp]: { neq: idFromData },
  2232. [propName]: propValue
  2233. });
  2234. if (count > 0) throw createError(propName, propValue);
  2235. } else {
  2236. const count = await countMethod({ [propName]: propValue });
  2237. if (count > 0) throw createError(propName, propValue);
  2238. }
  2239. } else if (methodName === "patch") {
  2240. const count = await countMethod({ [propName]: propValue });
  2241. if (count > 0) throw createError(propName, propValue);
  2242. } else if (methodName === "patchById") {
  2243. const count = await countMethod({
  2244. [idProp]: { neq: modelId },
  2245. [propName]: propValue
  2246. });
  2247. if (count > 0) throw createError(propName, propValue);
  2248. } else {
  2249. throw new InvalidArgumentError(
  2250. "The PropertyUniquenessValidator does not support the adapter method %v.",
  2251. methodName
  2252. );
  2253. }
  2254. }
  2255. }
  2256. };
  2257. __name(_PropertyUniquenessValidator, "PropertyUniquenessValidator");
  2258. PropertyUniquenessValidator = _PropertyUniquenessValidator;
  2259. }
  2260. });
  2261. // src/definition/model/properties/primary-keys-definition-validator.js
  2262. var import_js_service9, _PrimaryKeysDefinitionValidator, PrimaryKeysDefinitionValidator;
  2263. var init_primary_keys_definition_validator = __esm({
  2264. "src/definition/model/properties/primary-keys-definition-validator.js"() {
  2265. "use strict";
  2266. import_js_service9 = require("@e22m4u/js-service");
  2267. init_errors();
  2268. init_model_definition_utils();
  2269. _PrimaryKeysDefinitionValidator = class _PrimaryKeysDefinitionValidator extends import_js_service9.Service {
  2270. /**
  2271. * Validate.
  2272. *
  2273. * @param {string} modelName
  2274. * @param {object} propDefs
  2275. */
  2276. validate(modelName, propDefs) {
  2277. const propNames = Object.keys(propDefs).filter((propName) => {
  2278. const propDef = propDefs[propName];
  2279. return propDef && typeof propDef === "object" && propDef.primaryKey;
  2280. });
  2281. if (propNames.length < 1) {
  2282. const isDefaultPrimaryKeyAlreadyInUse = Object.keys(propDefs).includes(DEFAULT_PRIMARY_KEY_PROPERTY_NAME);
  2283. if (isDefaultPrimaryKeyAlreadyInUse)
  2284. throw new InvalidArgumentError(
  2285. '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.',
  2286. DEFAULT_PRIMARY_KEY_PROPERTY_NAME,
  2287. modelName
  2288. );
  2289. return;
  2290. }
  2291. if (propNames.length > 1)
  2292. throw new InvalidArgumentError(
  2293. "The model definition %v should not have multiple primary keys, but %v keys given.",
  2294. modelName,
  2295. propNames.length
  2296. );
  2297. const pkPropName = propNames[0];
  2298. const pkPropDef = propDefs[pkPropName];
  2299. if (pkPropDef && typeof pkPropDef === "object" && pkPropDef.default !== void 0) {
  2300. throw new InvalidArgumentError(
  2301. "Do not specify a default value for the primary key %v of the model %v.",
  2302. pkPropName,
  2303. modelName
  2304. );
  2305. }
  2306. }
  2307. };
  2308. __name(_PrimaryKeysDefinitionValidator, "PrimaryKeysDefinitionValidator");
  2309. PrimaryKeysDefinitionValidator = _PrimaryKeysDefinitionValidator;
  2310. }
  2311. });
  2312. // src/definition/model/properties/properties-definition-validator.js
  2313. var import_js_service10, _PropertiesDefinitionValidator, PropertiesDefinitionValidator;
  2314. var init_properties_definition_validator = __esm({
  2315. "src/definition/model/properties/properties-definition-validator.js"() {
  2316. "use strict";
  2317. import_js_service10 = require("@e22m4u/js-service");
  2318. init_data_type();
  2319. init_utils();
  2320. init_property_uniqueness();
  2321. init_errors();
  2322. init_primary_keys_definition_validator();
  2323. _PropertiesDefinitionValidator = class _PropertiesDefinitionValidator extends import_js_service10.Service {
  2324. /**
  2325. * Validate.
  2326. *
  2327. * @param {string} modelName
  2328. * @param {object} propDefs
  2329. */
  2330. validate(modelName, propDefs) {
  2331. if (!modelName || typeof modelName !== "string")
  2332. throw new InvalidArgumentError(
  2333. "The first argument of PropertiesDefinitionValidator.validate should be a non-empty String, but %v was given.",
  2334. modelName
  2335. );
  2336. if (!propDefs || typeof propDefs !== "object" || Array.isArray(propDefs)) {
  2337. throw new InvalidArgumentError(
  2338. 'The provided option "properties" of the model %v should be an Object, but %v was given.',
  2339. modelName,
  2340. propDefs
  2341. );
  2342. }
  2343. const propNames = Object.keys(propDefs);
  2344. propNames.forEach((propName) => {
  2345. const propDef = propDefs[propName];
  2346. this._validateProperty(modelName, propName, propDef);
  2347. });
  2348. this.getService(PrimaryKeysDefinitionValidator).validate(
  2349. modelName,
  2350. propDefs
  2351. );
  2352. }
  2353. /**
  2354. * Validate property.
  2355. *
  2356. * @param {string} modelName
  2357. * @param {string} propName
  2358. * @param {object} propDef
  2359. */
  2360. _validateProperty(modelName, propName, propDef) {
  2361. if (!modelName || typeof modelName !== "string")
  2362. throw new InvalidArgumentError(
  2363. "The first argument of PropertiesDefinitionValidator._validateProperty should be a non-empty String, but %v was given.",
  2364. modelName
  2365. );
  2366. if (!propName || typeof propName !== "string")
  2367. throw new InvalidArgumentError(
  2368. "The property name of the model %v should be a non-empty String, but %v was given.",
  2369. modelName,
  2370. propName
  2371. );
  2372. if (!propDef)
  2373. throw new InvalidArgumentError(
  2374. "The property %v of the model %v should have a property definition, but %v was given.",
  2375. propName,
  2376. modelName,
  2377. propDef
  2378. );
  2379. if (typeof propDef === "string") {
  2380. if (!Object.values(DataType).includes(propDef))
  2381. throw new InvalidArgumentError(
  2382. "In case of a short property definition, the property %v of the model %v should have one of data types: %l, but %v was given.",
  2383. propName,
  2384. modelName,
  2385. Object.values(DataType),
  2386. propDef
  2387. );
  2388. return;
  2389. }
  2390. if (!propDef || typeof propDef !== "object" || Array.isArray(propDef)) {
  2391. throw new InvalidArgumentError(
  2392. "In case of a full property definition, the property %v of the model %v should be an Object, but %v was given.",
  2393. propName,
  2394. modelName,
  2395. propDef
  2396. );
  2397. }
  2398. if (!propDef.type || !Object.values(DataType).includes(propDef.type))
  2399. throw new InvalidArgumentError(
  2400. 'The property %v of the model %v requires the option "type" to have one of data types: %l, but %v was given.',
  2401. propName,
  2402. modelName,
  2403. Object.values(DataType),
  2404. propDef.type
  2405. );
  2406. if (propDef.itemType && !Object.values(DataType).includes(propDef.itemType)) {
  2407. throw new InvalidArgumentError(
  2408. 'The provided option "itemType" of the property %v in the model %v should have one of data types: %l, but %v was given.',
  2409. propName,
  2410. modelName,
  2411. Object.values(DataType),
  2412. propDef.itemType
  2413. );
  2414. }
  2415. if (propDef.itemModel && typeof propDef.itemModel !== "string") {
  2416. throw new InvalidArgumentError(
  2417. 'The provided option "itemModel" of the property %v in the model %v should be a String, but %v was given.',
  2418. propName,
  2419. modelName,
  2420. propDef.itemModel
  2421. );
  2422. }
  2423. if (propDef.model && typeof propDef.model !== "string")
  2424. throw new InvalidArgumentError(
  2425. 'The provided option "model" of the property %v in the model %v should be a String, but %v was given.',
  2426. propName,
  2427. modelName,
  2428. propDef.model
  2429. );
  2430. if (propDef.primaryKey && typeof propDef.primaryKey !== "boolean")
  2431. throw new InvalidArgumentError(
  2432. 'The provided option "primaryKey" of the property %v in the model %v should be a Boolean, but %v was given.',
  2433. propName,
  2434. modelName,
  2435. propDef.primaryKey
  2436. );
  2437. if (propDef.columnName && typeof propDef.columnName !== "string")
  2438. throw new InvalidArgumentError(
  2439. 'The provided option "columnName" of the property %v in the model %v should be a String, but %v was given.',
  2440. propName,
  2441. modelName,
  2442. propDef.columnName
  2443. );
  2444. if (propDef.columnType && typeof propDef.columnType !== "string")
  2445. throw new InvalidArgumentError(
  2446. 'The provided option "columnType" of the property %v in the model %v should be a String, but %v was given.',
  2447. propName,
  2448. modelName,
  2449. propDef.columnType
  2450. );
  2451. if (propDef.required && typeof propDef.required !== "boolean")
  2452. throw new InvalidArgumentError(
  2453. 'The provided option "required" of the property %v in the model %v should be a Boolean, but %v was given.',
  2454. propName,
  2455. modelName,
  2456. propDef.required
  2457. );
  2458. if (propDef.required && propDef.default !== void 0)
  2459. throw new InvalidArgumentError(
  2460. 'The property %v of the model %v is a required property, so it should not have the option "default" to be provided.',
  2461. propName,
  2462. modelName
  2463. );
  2464. if (propDef.primaryKey && propDef.required)
  2465. throw new InvalidArgumentError(
  2466. 'The property %v of the model %v is a primary key, so it should not have the option "required" to be provided.',
  2467. propName,
  2468. modelName
  2469. );
  2470. if (propDef.primaryKey && propDef.default !== void 0)
  2471. throw new InvalidArgumentError(
  2472. 'The property %v of the model %v is a primary key, so it should not have the option "default" to be provided.',
  2473. propName,
  2474. modelName
  2475. );
  2476. if (propDef.itemType && propDef.type !== DataType.ARRAY)
  2477. throw new InvalidArgumentError(
  2478. 'The property %v of the model %v has a non-array type, so it should not have the option "itemType" to be provided.',
  2479. propName,
  2480. modelName,
  2481. propDef.type
  2482. );
  2483. if (propDef.itemModel && propDef.type !== DataType.ARRAY)
  2484. throw new InvalidArgumentError(
  2485. 'The option "itemModel" is not supported for %s property type, so the property %v of the model %v should not have the option "itemModel" to be provided.',
  2486. capitalize(propDef.type),
  2487. propName,
  2488. modelName
  2489. );
  2490. if (propDef.itemModel && propDef.itemType !== DataType.OBJECT) {
  2491. if (propDef.itemType) {
  2492. throw new InvalidArgumentError(
  2493. 'The provided option "itemModel" requires the option "itemType" to be explicitly set to Object, but the property %v of the model %v has specified item type as %s.',
  2494. propName,
  2495. modelName,
  2496. capitalize(propDef.itemType)
  2497. );
  2498. } else {
  2499. throw new InvalidArgumentError(
  2500. 'The provided option "itemModel" requires the option "itemType" to be explicitly set to Object, but the property %v of the model %v does not have specified item type.',
  2501. propName,
  2502. modelName
  2503. );
  2504. }
  2505. }
  2506. if (propDef.model && propDef.type !== DataType.OBJECT)
  2507. throw new InvalidArgumentError(
  2508. '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.',
  2509. capitalize(propDef.type),
  2510. propName,
  2511. modelName
  2512. );
  2513. if (propDef.unique) {
  2514. if (typeof propDef.unique !== "boolean" && !Object.values(PropertyUniqueness).includes(propDef.unique)) {
  2515. throw new InvalidArgumentError(
  2516. 'The provided option "unique" of the property %v in the model %v should be a Boolean or one of values: %l, but %v was given.',
  2517. propName,
  2518. modelName,
  2519. Object.values(PropertyUniqueness),
  2520. propDef.unique
  2521. );
  2522. }
  2523. }
  2524. if (propDef.unique && propDef.primaryKey)
  2525. throw new InvalidArgumentError(
  2526. 'The property %v of the model %v is a primary key, so it should not have the option "unique" to be provided.',
  2527. propName,
  2528. modelName
  2529. );
  2530. }
  2531. };
  2532. __name(_PropertiesDefinitionValidator, "PropertiesDefinitionValidator");
  2533. PropertiesDefinitionValidator = _PropertiesDefinitionValidator;
  2534. }
  2535. });
  2536. // src/definition/model/properties/index.js
  2537. var init_properties = __esm({
  2538. "src/definition/model/properties/index.js"() {
  2539. "use strict";
  2540. init_data_type();
  2541. init_property_definition();
  2542. init_property_uniqueness();
  2543. init_property_uniqueness_validator();
  2544. init_properties_definition_validator();
  2545. init_primary_keys_definition_validator();
  2546. }
  2547. });
  2548. // src/definition/model/model-definition.js
  2549. var init_model_definition = __esm({
  2550. "src/definition/model/model-definition.js"() {
  2551. "use strict";
  2552. }
  2553. });
  2554. // src/definition/model/model-data-sanitizer.js
  2555. var import_js_service11, _ModelDataSanitizer, ModelDataSanitizer;
  2556. var init_model_data_sanitizer = __esm({
  2557. "src/definition/model/model-data-sanitizer.js"() {
  2558. "use strict";
  2559. import_js_service11 = require("@e22m4u/js-service");
  2560. init_errors();
  2561. init_model_definition_utils();
  2562. _ModelDataSanitizer = class _ModelDataSanitizer extends import_js_service11.Service {
  2563. /**
  2564. * Validate.
  2565. *
  2566. * @param {string} modelName
  2567. * @param {object} modelData
  2568. * @returns {object}
  2569. */
  2570. sanitize(modelName, modelData) {
  2571. if (!modelName || typeof modelName !== "string")
  2572. throw new InvalidArgumentError(
  2573. "The first argument of ModelDataSanitizer.sanitize should be a string, but %v was given.",
  2574. modelName
  2575. );
  2576. if (!modelData || typeof modelData !== "object")
  2577. throw new InvalidArgumentError(
  2578. "The second argument of ModelDataSanitizer.sanitize should be an Object, but %v was given.",
  2579. modelData
  2580. );
  2581. return this.getService(
  2582. ModelDefinitionUtils
  2583. ).excludeObjectKeysByRelationNames(modelName, modelData);
  2584. }
  2585. };
  2586. __name(_ModelDataSanitizer, "ModelDataSanitizer");
  2587. ModelDataSanitizer = _ModelDataSanitizer;
  2588. }
  2589. });
  2590. // src/definition/model/model-definition-validator.js
  2591. var import_js_service12, _ModelDefinitionValidator, ModelDefinitionValidator;
  2592. var init_model_definition_validator = __esm({
  2593. "src/definition/model/model-definition-validator.js"() {
  2594. "use strict";
  2595. import_js_service12 = require("@e22m4u/js-service");
  2596. init_errors();
  2597. init_relations();
  2598. init_properties();
  2599. _ModelDefinitionValidator = class _ModelDefinitionValidator extends import_js_service12.Service {
  2600. /**
  2601. * Validate.
  2602. *
  2603. * @param {object} modelDef
  2604. */
  2605. validate(modelDef) {
  2606. if (!modelDef || typeof modelDef !== "object" || Array.isArray(modelDef))
  2607. throw new InvalidArgumentError(
  2608. "The model definition should be an Object, but %v was given.",
  2609. modelDef
  2610. );
  2611. if (!modelDef.name || typeof modelDef.name !== "string")
  2612. throw new InvalidArgumentError(
  2613. 'The model definition requires the option "name" as a non-empty String, but %v was given.',
  2614. modelDef.name
  2615. );
  2616. if (modelDef.datasource && typeof modelDef.datasource !== "string")
  2617. throw new InvalidArgumentError(
  2618. 'The provided option "datasource" of the model %v should be a String, but %v was given.',
  2619. modelDef.name,
  2620. modelDef.datasource
  2621. );
  2622. if (modelDef.base && typeof modelDef.base !== "string")
  2623. throw new InvalidArgumentError(
  2624. 'The provided option "base" of the model %v should be a String, but %v was given.',
  2625. modelDef.name,
  2626. modelDef.base
  2627. );
  2628. if (modelDef.tableName && typeof modelDef.tableName !== "string")
  2629. throw new InvalidArgumentError(
  2630. 'The provided option "tableName" of the model %v should be a String, but %v was given.',
  2631. modelDef.name,
  2632. modelDef.tableName
  2633. );
  2634. if (modelDef.properties) {
  2635. if (typeof modelDef.properties !== "object" || Array.isArray(modelDef.properties)) {
  2636. throw new InvalidArgumentError(
  2637. 'The provided option "properties" of the model %v should be an Object, but %v was given.',
  2638. modelDef.name,
  2639. modelDef.properties
  2640. );
  2641. }
  2642. this.getService(PropertiesDefinitionValidator).validate(
  2643. modelDef.name,
  2644. modelDef.properties
  2645. );
  2646. }
  2647. if (modelDef.relations) {
  2648. if (typeof modelDef.relations !== "object" || Array.isArray(modelDef.relations)) {
  2649. throw new InvalidArgumentError(
  2650. 'The provided option "relations" of the model %v should be an Object, but %v was given.',
  2651. modelDef.name,
  2652. modelDef.relations
  2653. );
  2654. }
  2655. this.getService(RelationsDefinitionValidator).validate(
  2656. modelDef.name,
  2657. modelDef.relations
  2658. );
  2659. }
  2660. }
  2661. };
  2662. __name(_ModelDefinitionValidator, "ModelDefinitionValidator");
  2663. ModelDefinitionValidator = _ModelDefinitionValidator;
  2664. }
  2665. });
  2666. // src/definition/model/index.js
  2667. var init_model = __esm({
  2668. "src/definition/model/index.js"() {
  2669. "use strict";
  2670. init_relations();
  2671. init_properties();
  2672. init_model_definition();
  2673. init_model_data_sanitizer();
  2674. init_model_definition_utils();
  2675. init_model_definition_validator();
  2676. }
  2677. });
  2678. // src/definition/datasource/datasource-definition-validator.js
  2679. var import_js_service13, _DatasourceDefinitionValidator, DatasourceDefinitionValidator;
  2680. var init_datasource_definition_validator = __esm({
  2681. "src/definition/datasource/datasource-definition-validator.js"() {
  2682. "use strict";
  2683. import_js_service13 = require("@e22m4u/js-service");
  2684. init_errors();
  2685. _DatasourceDefinitionValidator = class _DatasourceDefinitionValidator extends import_js_service13.Service {
  2686. /**
  2687. * Validate.
  2688. *
  2689. * @param {object} datasourceDef
  2690. */
  2691. validate(datasourceDef) {
  2692. if (!datasourceDef || typeof datasourceDef !== "object")
  2693. throw new InvalidArgumentError(
  2694. "The datasource definition should be an Object, but %v was given.",
  2695. datasourceDef
  2696. );
  2697. if (!datasourceDef.name || typeof datasourceDef.name !== "string")
  2698. throw new InvalidArgumentError(
  2699. 'The datasource definition requires the option "name" as a non-empty String, but %v was given.',
  2700. datasourceDef.name
  2701. );
  2702. if (!datasourceDef.adapter || typeof datasourceDef.adapter !== "string")
  2703. throw new InvalidArgumentError(
  2704. 'The datasource %v requires the option "adapter" as a non-empty String, but %v was given.',
  2705. datasourceDef.name,
  2706. datasourceDef.adapter
  2707. );
  2708. }
  2709. };
  2710. __name(_DatasourceDefinitionValidator, "DatasourceDefinitionValidator");
  2711. DatasourceDefinitionValidator = _DatasourceDefinitionValidator;
  2712. }
  2713. });
  2714. // src/definition/datasource/index.js
  2715. var init_datasource = __esm({
  2716. "src/definition/datasource/index.js"() {
  2717. "use strict";
  2718. init_datasource_definition_validator();
  2719. }
  2720. });
  2721. // src/definition/index.js
  2722. var init_definition = __esm({
  2723. "src/definition/index.js"() {
  2724. "use strict";
  2725. init_model();
  2726. init_datasource();
  2727. init_definition_registry();
  2728. }
  2729. });
  2730. // src/filter/fields-clause-tool.js
  2731. var import_js_service14, _FieldsClauseTool, FieldsClauseTool;
  2732. var init_fields_clause_tool = __esm({
  2733. "src/filter/fields-clause-tool.js"() {
  2734. "use strict";
  2735. import_js_service14 = require("@e22m4u/js-service");
  2736. init_utils();
  2737. init_errors();
  2738. init_definition();
  2739. _FieldsClauseTool = class _FieldsClauseTool extends import_js_service14.Service {
  2740. /**
  2741. * Filter.
  2742. *
  2743. * @param {object|object[]} input
  2744. * @param {string} modelName
  2745. * @param {string|string[]|undefined} clause
  2746. * @returns {object|object[]}
  2747. */
  2748. filter(input, modelName, clause) {
  2749. const isArray = Array.isArray(input);
  2750. let entities = isArray ? input : [input];
  2751. entities.forEach((entity) => {
  2752. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  2753. throw new InvalidArgumentError(
  2754. "The first argument of FieldsClauseTool.filter should be an Object or an Array of Object, but %v was given.",
  2755. entity
  2756. );
  2757. });
  2758. if (!modelName || typeof modelName !== "string")
  2759. throw new InvalidArgumentError(
  2760. "The second argument of FieldsClauseTool.filter should be a non-empty String, but %v was given.",
  2761. modelName
  2762. );
  2763. if (clause == null) return input;
  2764. const fields = Array.isArray(clause) ? clause.slice() : [clause];
  2765. if (!fields.length) return input;
  2766. fields.forEach((field) => {
  2767. if (!field || typeof field !== "string")
  2768. throw new InvalidArgumentError(
  2769. 'The provided option "fields" should be a non-empty String or an Array of non-empty String, but %v was given.',
  2770. field
  2771. );
  2772. });
  2773. const pkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  2774. modelName
  2775. );
  2776. if (fields.indexOf(pkPropName) === -1) fields.push(pkPropName);
  2777. entities = entities.map((entity) => selectObjectKeys(entity, fields));
  2778. return isArray ? entities : entities[0];
  2779. }
  2780. /**
  2781. * Validate fields clause.
  2782. *
  2783. * @param {string|string[]|undefined} clause
  2784. */
  2785. static validateFieldsClause(clause) {
  2786. if (clause == null) return;
  2787. const fields = Array.isArray(clause) ? clause : [clause];
  2788. if (!fields.length) return;
  2789. fields.forEach((field) => {
  2790. if (!field || typeof field !== "string")
  2791. throw new InvalidArgumentError(
  2792. 'The provided option "fields" should be a non-empty String or an Array of non-empty String, but %v was given.',
  2793. field
  2794. );
  2795. });
  2796. }
  2797. /**
  2798. * Normalize fields clause.
  2799. *
  2800. * @param {string|string[]|undefined} clause
  2801. * @returns {string[]|undefined}
  2802. */
  2803. static normalizeFieldsClause(clause) {
  2804. if (clause == null) return;
  2805. const fields = Array.isArray(clause) ? clause : [clause];
  2806. if (!fields.length) return;
  2807. fields.forEach((field) => {
  2808. if (!field || typeof field !== "string")
  2809. throw new InvalidArgumentError(
  2810. 'The provided option "fields" should be a non-empty String or an Array of non-empty String, but %v was given.',
  2811. field
  2812. );
  2813. });
  2814. return fields;
  2815. }
  2816. };
  2817. __name(_FieldsClauseTool, "FieldsClauseTool");
  2818. FieldsClauseTool = _FieldsClauseTool;
  2819. }
  2820. });
  2821. // src/adapter/decorator/inclusion-decorator.js
  2822. var import_js_service15, _InclusionDecorator, InclusionDecorator;
  2823. var init_inclusion_decorator = __esm({
  2824. "src/adapter/decorator/inclusion-decorator.js"() {
  2825. "use strict";
  2826. init_adapter();
  2827. import_js_service15 = require("@e22m4u/js-service");
  2828. init_filter();
  2829. init_errors();
  2830. _InclusionDecorator = class _InclusionDecorator extends import_js_service15.Service {
  2831. /**
  2832. * Decorate.
  2833. *
  2834. * @param {Adapter} adapter
  2835. */
  2836. decorate(adapter) {
  2837. if (!adapter || !(adapter instanceof Adapter))
  2838. throw new InvalidArgumentError(
  2839. "The first argument of InclusionDecorator.decorate should be an Adapter instance, but %v was given.",
  2840. adapter
  2841. );
  2842. const tool = adapter.getService(IncludeClauseTool);
  2843. const includeTo = /* @__PURE__ */ __name((...args) => tool.includeTo(...args), "includeTo");
  2844. const create = adapter.create;
  2845. adapter.create = async function(modelName, modelData, filter) {
  2846. const retvalData = await create.call(this, modelName, modelData, filter);
  2847. if (filter && typeof filter === "object" && filter.include)
  2848. await includeTo([retvalData], modelName, filter.include);
  2849. return retvalData;
  2850. };
  2851. const replaceById = adapter.replaceById;
  2852. adapter.replaceById = async function(modelName, id, modelData, filter) {
  2853. const retvalData = await replaceById.call(
  2854. this,
  2855. modelName,
  2856. id,
  2857. modelData,
  2858. filter
  2859. );
  2860. if (filter && typeof filter === "object" && filter.include)
  2861. await includeTo([retvalData], modelName, filter.include);
  2862. return retvalData;
  2863. };
  2864. const replaceOrCreate = adapter.replaceOrCreate;
  2865. adapter.replaceOrCreate = async function(modelName, modelData, filter) {
  2866. const retvalData = await replaceOrCreate.call(
  2867. this,
  2868. modelName,
  2869. modelData,
  2870. filter
  2871. );
  2872. if (filter && typeof filter === "object" && filter.include)
  2873. await includeTo([retvalData], modelName, filter.include);
  2874. return retvalData;
  2875. };
  2876. const patchById = adapter.patchById;
  2877. adapter.patchById = async function(modelName, id, modelData, filter) {
  2878. const retvalData = await patchById.call(
  2879. this,
  2880. modelName,
  2881. id,
  2882. modelData,
  2883. filter
  2884. );
  2885. if (filter && typeof filter === "object" && filter.include)
  2886. await includeTo([retvalData], modelName, filter.include);
  2887. return retvalData;
  2888. };
  2889. const find = adapter.find;
  2890. adapter.find = async function(modelName, filter) {
  2891. const modelItems = await find.call(this, modelName, filter);
  2892. if (filter && typeof filter === "object" && filter.include)
  2893. await includeTo(modelItems, modelName, filter.include);
  2894. return modelItems;
  2895. };
  2896. const findById = adapter.findById;
  2897. adapter.findById = async function(modelName, id, filter) {
  2898. const retvalData = await findById.call(this, modelName, id, filter);
  2899. if (filter && typeof filter === "object" && filter.include)
  2900. await includeTo([retvalData], modelName, filter.include);
  2901. return retvalData;
  2902. };
  2903. }
  2904. };
  2905. __name(_InclusionDecorator, "InclusionDecorator");
  2906. InclusionDecorator = _InclusionDecorator;
  2907. }
  2908. });
  2909. // src/adapter/decorator/default-values-decorator.js
  2910. var import_js_service16, _DefaultValuesDecorator, DefaultValuesDecorator;
  2911. var init_default_values_decorator = __esm({
  2912. "src/adapter/decorator/default-values-decorator.js"() {
  2913. "use strict";
  2914. init_adapter();
  2915. import_js_service16 = require("@e22m4u/js-service");
  2916. init_errors();
  2917. init_definition();
  2918. _DefaultValuesDecorator = class _DefaultValuesDecorator extends import_js_service16.Service {
  2919. /**
  2920. * Decorate.
  2921. *
  2922. * @param {Adapter} adapter
  2923. */
  2924. decorate(adapter) {
  2925. if (!adapter || !(adapter instanceof Adapter))
  2926. throw new InvalidArgumentError(
  2927. "The first argument of DefaultValuesDecorator.decorate should be an Adapter instance, but %v was given.",
  2928. adapter
  2929. );
  2930. const utils = adapter.getService(ModelDefinitionUtils);
  2931. const setDefaults = /* @__PURE__ */ __name((...args) => utils.setDefaultValuesToEmptyProperties(...args), "setDefaults");
  2932. const create = adapter.create;
  2933. adapter.create = function(modelName, modelData, filter) {
  2934. modelData = setDefaults(modelName, modelData);
  2935. return create.call(this, modelName, modelData, filter);
  2936. };
  2937. const replaceById = adapter.replaceById;
  2938. adapter.replaceById = function(modelName, id, modelData, filter) {
  2939. modelData = setDefaults(modelName, modelData);
  2940. return replaceById.call(this, modelName, id, modelData, filter);
  2941. };
  2942. const replaceOrCreate = adapter.replaceOrCreate;
  2943. adapter.replaceOrCreate = function(modelName, modelData, filter) {
  2944. modelData = setDefaults(modelName, modelData);
  2945. return replaceOrCreate.call(this, modelName, modelData, filter);
  2946. };
  2947. const patch = adapter.patch;
  2948. adapter.patch = function(modelName, modelData, where) {
  2949. modelData = setDefaults(modelName, modelData, true);
  2950. return patch.call(this, modelName, modelData, where);
  2951. };
  2952. const patchById = adapter.patchById;
  2953. adapter.patchById = function(modelName, id, modelData, filter) {
  2954. modelData = setDefaults(modelName, modelData, true);
  2955. return patchById.call(this, modelName, id, modelData, filter);
  2956. };
  2957. const find = adapter.find;
  2958. adapter.find = async function(modelName, filter) {
  2959. const modelItems = await find.call(this, modelName, filter);
  2960. return modelItems.map((modelItem) => setDefaults(modelName, modelItem));
  2961. };
  2962. const findById = adapter.findById;
  2963. adapter.findById = async function(modelName, id, filter) {
  2964. const retvalData = await findById.call(this, modelName, id, filter);
  2965. return setDefaults(modelName, retvalData);
  2966. };
  2967. }
  2968. };
  2969. __name(_DefaultValuesDecorator, "DefaultValuesDecorator");
  2970. DefaultValuesDecorator = _DefaultValuesDecorator;
  2971. }
  2972. });
  2973. // src/adapter/decorator/data-sanitizing-decorator.js
  2974. var import_js_service17, _DataSanitizingDecorator, DataSanitizingDecorator;
  2975. var init_data_sanitizing_decorator = __esm({
  2976. "src/adapter/decorator/data-sanitizing-decorator.js"() {
  2977. "use strict";
  2978. init_adapter();
  2979. import_js_service17 = require("@e22m4u/js-service");
  2980. init_errors();
  2981. init_definition();
  2982. _DataSanitizingDecorator = class _DataSanitizingDecorator extends import_js_service17.Service {
  2983. /**
  2984. * Decorate.
  2985. *
  2986. * @param {Adapter} adapter
  2987. */
  2988. decorate(adapter) {
  2989. if (!adapter || !(adapter instanceof Adapter))
  2990. throw new InvalidArgumentError(
  2991. "The first argument of DataSanitizingDecorator.decorate should be an Adapter instance, but %v was given.",
  2992. adapter
  2993. );
  2994. const sanitizer = adapter.getService(ModelDataSanitizer);
  2995. const sanitize = /* @__PURE__ */ __name((...args) => sanitizer.sanitize(...args), "sanitize");
  2996. const create = adapter.create;
  2997. adapter.create = async function(modelName, modelData, filter) {
  2998. modelData = sanitize(modelName, modelData);
  2999. return create.call(this, modelName, modelData, filter);
  3000. };
  3001. const replaceById = adapter.replaceById;
  3002. adapter.replaceById = async function(modelName, id, modelData, filter) {
  3003. modelData = sanitize(modelName, modelData);
  3004. return replaceById.call(this, modelName, id, modelData, filter);
  3005. };
  3006. const replaceOrCreate = adapter.replaceOrCreate;
  3007. adapter.replaceOrCreate = async function(modelName, modelData, filter) {
  3008. modelData = sanitize(modelName, modelData);
  3009. return replaceOrCreate.call(this, modelName, modelData, filter);
  3010. };
  3011. const patch = adapter.patch;
  3012. adapter.patch = async function(modelName, modelData, where) {
  3013. modelData = sanitize(modelName, modelData);
  3014. return patch.call(this, modelName, modelData, where);
  3015. };
  3016. const patchById = adapter.patchById;
  3017. adapter.patchById = async function(modelName, id, modelData, filter) {
  3018. modelData = sanitize(modelName, modelData);
  3019. return patchById.call(this, modelName, id, modelData, filter);
  3020. };
  3021. }
  3022. };
  3023. __name(_DataSanitizingDecorator, "DataSanitizingDecorator");
  3024. DataSanitizingDecorator = _DataSanitizingDecorator;
  3025. }
  3026. });
  3027. // src/adapter/decorator/fields-filtering-decorator.js
  3028. var import_js_service18, _FieldsFilteringDecorator, FieldsFilteringDecorator;
  3029. var init_fields_filtering_decorator = __esm({
  3030. "src/adapter/decorator/fields-filtering-decorator.js"() {
  3031. "use strict";
  3032. init_adapter();
  3033. import_js_service18 = require("@e22m4u/js-service");
  3034. init_filter();
  3035. init_errors();
  3036. _FieldsFilteringDecorator = class _FieldsFilteringDecorator extends import_js_service18.Service {
  3037. /**
  3038. * Decorate.
  3039. *
  3040. * @param {Adapter} adapter
  3041. */
  3042. decorate(adapter) {
  3043. if (!adapter || !(adapter instanceof Adapter))
  3044. throw new InvalidArgumentError(
  3045. "The first argument of FieldsFilteringDecorator.decorate should be an Adapter instance, but %v was given.",
  3046. adapter
  3047. );
  3048. const tool = adapter.getService(FieldsClauseTool);
  3049. const selectFields = /* @__PURE__ */ __name((...args) => tool.filter(...args), "selectFields");
  3050. const create = adapter.create;
  3051. adapter.create = async function(modelName, modelData, filter) {
  3052. let result = await create.call(this, modelName, modelData, filter);
  3053. if (filter && typeof filter === "object" && filter.fields)
  3054. result = selectFields(result, modelName, filter.fields);
  3055. return result;
  3056. };
  3057. const replaceById = adapter.replaceById;
  3058. adapter.replaceById = async function(modelName, id, modelData, filter) {
  3059. let result = await replaceById.call(
  3060. this,
  3061. modelName,
  3062. id,
  3063. modelData,
  3064. filter
  3065. );
  3066. if (filter && typeof filter === "object" && filter.fields)
  3067. result = selectFields(result, modelName, filter.fields);
  3068. return result;
  3069. };
  3070. const replaceOrCreate = adapter.replaceOrCreate;
  3071. adapter.replaceOrCreate = async function(modelName, modelData, filter) {
  3072. let result = await replaceOrCreate.call(
  3073. this,
  3074. modelName,
  3075. modelData,
  3076. filter
  3077. );
  3078. if (filter && typeof filter === "object" && filter.fields)
  3079. result = selectFields(result, modelName, filter.fields);
  3080. return result;
  3081. };
  3082. const patchById = adapter.patchById;
  3083. adapter.patchById = async function(modelName, id, modelData, filter) {
  3084. let result = await patchById.call(this, modelName, id, modelData, filter);
  3085. if (filter && typeof filter === "object" && filter.fields)
  3086. result = selectFields(result, modelName, filter.fields);
  3087. return result;
  3088. };
  3089. const find = adapter.find;
  3090. adapter.find = async function(modelName, filter) {
  3091. let result = await find.call(this, modelName, filter);
  3092. if (filter && typeof filter === "object" && filter.fields)
  3093. result = selectFields(result, modelName, filter.fields);
  3094. return result;
  3095. };
  3096. const findById = adapter.findById;
  3097. adapter.findById = async function(modelName, id, filter) {
  3098. let result = await findById.call(this, modelName, id, filter);
  3099. if (filter && typeof filter === "object" && filter.fields)
  3100. result = selectFields(result, modelName, filter.fields);
  3101. return result;
  3102. };
  3103. }
  3104. };
  3105. __name(_FieldsFilteringDecorator, "FieldsFilteringDecorator");
  3106. FieldsFilteringDecorator = _FieldsFilteringDecorator;
  3107. }
  3108. });
  3109. // src/adapter/decorator/property-uniqueness-decorator.js
  3110. var import_js_service19, _PropertyUniquenessDecorator, PropertyUniquenessDecorator;
  3111. var init_property_uniqueness_decorator = __esm({
  3112. "src/adapter/decorator/property-uniqueness-decorator.js"() {
  3113. "use strict";
  3114. init_adapter();
  3115. import_js_service19 = require("@e22m4u/js-service");
  3116. init_errors();
  3117. init_definition();
  3118. _PropertyUniquenessDecorator = class _PropertyUniquenessDecorator extends import_js_service19.Service {
  3119. /**
  3120. * Decorate.
  3121. *
  3122. * @param {Adapter} adapter
  3123. */
  3124. decorate(adapter) {
  3125. if (!adapter || !(adapter instanceof Adapter))
  3126. throw new InvalidArgumentError(
  3127. "The first argument of PropertyUniquenessDecorator.decorate should be an Adapter instance, but %v was given.",
  3128. adapter
  3129. );
  3130. const validator = this.getService(PropertyUniquenessValidator);
  3131. const create = adapter.create;
  3132. adapter.create = async function(modelName, modelData, filter) {
  3133. const countMethod = adapter.count.bind(adapter, modelName);
  3134. await validator.validate(countMethod, "create", modelName, modelData);
  3135. return create.call(this, modelName, modelData, filter);
  3136. };
  3137. const replaceById = adapter.replaceById;
  3138. adapter.replaceById = async function(modelName, id, modelData, filter) {
  3139. const countMethod = adapter.count.bind(adapter, modelName);
  3140. await validator.validate(
  3141. countMethod,
  3142. "replaceById",
  3143. modelName,
  3144. modelData,
  3145. id
  3146. );
  3147. return replaceById.call(this, modelName, id, modelData, filter);
  3148. };
  3149. const replaceOrCreate = adapter.replaceOrCreate;
  3150. adapter.replaceOrCreate = async function(modelName, modelData, filter) {
  3151. const countMethod = adapter.count.bind(adapter, modelName);
  3152. await validator.validate(
  3153. countMethod,
  3154. "replaceOrCreate",
  3155. modelName,
  3156. modelData
  3157. );
  3158. return replaceOrCreate.call(this, modelName, modelData, filter);
  3159. };
  3160. const patch = adapter.patch;
  3161. adapter.patch = async function(modelName, modelData, where) {
  3162. const countMethod = adapter.count.bind(adapter, modelName);
  3163. await validator.validate(countMethod, "patch", modelName, modelData);
  3164. return patch.call(this, modelName, modelData, where);
  3165. };
  3166. const patchById = adapter.patchById;
  3167. adapter.patchById = async function(modelName, id, modelData, filter) {
  3168. const countMethod = adapter.count.bind(adapter, modelName);
  3169. await validator.validate(
  3170. countMethod,
  3171. "patchById",
  3172. modelName,
  3173. modelData,
  3174. id
  3175. );
  3176. return patchById.call(this, modelName, id, modelData, filter);
  3177. };
  3178. }
  3179. };
  3180. __name(_PropertyUniquenessDecorator, "PropertyUniquenessDecorator");
  3181. PropertyUniquenessDecorator = _PropertyUniquenessDecorator;
  3182. }
  3183. });
  3184. // src/adapter/decorator/index.js
  3185. var init_decorator = __esm({
  3186. "src/adapter/decorator/index.js"() {
  3187. "use strict";
  3188. init_inclusion_decorator();
  3189. init_default_values_decorator();
  3190. init_data_sanitizing_decorator();
  3191. init_fields_filtering_decorator();
  3192. init_property_uniqueness_decorator();
  3193. }
  3194. });
  3195. // src/adapter/adapter.js
  3196. var import_js_service20, ADAPTER_CLASS_NAME, _Adapter, Adapter;
  3197. var init_adapter = __esm({
  3198. "src/adapter/adapter.js"() {
  3199. "use strict";
  3200. import_js_service20 = require("@e22m4u/js-service");
  3201. init_errors();
  3202. init_decorator();
  3203. ADAPTER_CLASS_NAME = "Adapter";
  3204. _Adapter = class _Adapter extends import_js_service20.Service {
  3205. /**
  3206. * Settings.
  3207. *
  3208. * @type {object|undefined}
  3209. */
  3210. _settings;
  3211. /**
  3212. * Settings.
  3213. *
  3214. * @returns {object|undefined}
  3215. */
  3216. get settings() {
  3217. return this._settings;
  3218. }
  3219. /**
  3220. * Constructor.
  3221. *
  3222. * @param {object|undefined} container
  3223. * @param {object|undefined} settings
  3224. */
  3225. constructor(container = void 0, settings = void 0) {
  3226. super(container);
  3227. this._settings = settings;
  3228. if (this.constructor !== _Adapter) {
  3229. this.getService(DataSanitizingDecorator).decorate(this);
  3230. this.getService(DefaultValuesDecorator).decorate(this);
  3231. this.getService(PropertyUniquenessDecorator).decorate(this);
  3232. this.getService(FieldsFilteringDecorator).decorate(this);
  3233. this.getService(InclusionDecorator).decorate(this);
  3234. }
  3235. }
  3236. /**
  3237. * Create.
  3238. *
  3239. * @param {string} modelName
  3240. * @param {object} modelData
  3241. * @param {object|undefined} filter
  3242. * @returns {Promise<object>}
  3243. */
  3244. create(modelName, modelData, filter = void 0) {
  3245. throw new NotImplementedError(
  3246. "%s.create is not implemented.",
  3247. this.constructor.name
  3248. );
  3249. }
  3250. /**
  3251. * Replace by id.
  3252. *
  3253. * @param {string} modelName
  3254. * @param {number|string} id
  3255. * @param {object} modelData
  3256. * @param {object|undefined} filter
  3257. * @returns {Promise<object>}
  3258. */
  3259. replaceById(modelName, id, modelData, filter = void 0) {
  3260. throw new NotImplementedError(
  3261. "%s.replaceById is not implemented.",
  3262. this.constructor.name
  3263. );
  3264. }
  3265. /**
  3266. * Replace or create.
  3267. *
  3268. * @param {string} modelName
  3269. * @param {object} modelData
  3270. * @param {object|undefined} filter
  3271. * @returns {Promise<object>}
  3272. */
  3273. replaceOrCreate(modelName, modelData, filter = void 0) {
  3274. throw new NotImplementedError(
  3275. "%s.replaceOrCreate is not implemented.",
  3276. this.constructor.name
  3277. );
  3278. }
  3279. /**
  3280. * Patch.
  3281. *
  3282. * @param {string} modelName
  3283. * @param {object} modelData
  3284. * @param {object|undefined} where
  3285. * @returns {Promise<number>}
  3286. */
  3287. patch(modelName, modelData, where = void 0) {
  3288. throw new NotImplementedError(
  3289. "%s.patch is not implemented.",
  3290. this.constructor.name
  3291. );
  3292. }
  3293. /**
  3294. * Patch by id.
  3295. *
  3296. * @param {string} modelName
  3297. * @param {number|string} id
  3298. * @param {object} modelData
  3299. * @param {object|undefined} filter
  3300. * @returns {Promise<object>}
  3301. */
  3302. patchById(modelName, id, modelData, filter = void 0) {
  3303. throw new NotImplementedError(
  3304. "%s.patchById is not implemented.",
  3305. this.constructor.name
  3306. );
  3307. }
  3308. /**
  3309. * Find.
  3310. *
  3311. * @param {string} modelName
  3312. * @param {object|undefined} filter
  3313. * @returns {Promise<object[]>}
  3314. */
  3315. find(modelName, filter = void 0) {
  3316. throw new NotImplementedError(
  3317. "%s.find is not implemented.",
  3318. this.constructor.name
  3319. );
  3320. }
  3321. /**
  3322. * Find by id.
  3323. *
  3324. * @param {string} modelName
  3325. * @param {number|string} id
  3326. * @param {object|undefined} filter
  3327. * @returns {Promise<object>}
  3328. */
  3329. findById(modelName, id, filter = void 0) {
  3330. throw new NotImplementedError(
  3331. "%s.findById is not implemented.",
  3332. this.constructor.name
  3333. );
  3334. }
  3335. /**
  3336. * Delete.
  3337. *
  3338. * @param {string} modelName
  3339. * @param {object|undefined} where
  3340. * @returns {Promise<number>}
  3341. */
  3342. delete(modelName, where = void 0) {
  3343. throw new NotImplementedError(
  3344. "%s.delete is not implemented.",
  3345. this.constructor.name
  3346. );
  3347. }
  3348. /**
  3349. * Delete by id.
  3350. *
  3351. * @param {string} modelName
  3352. * @param {number|string} id
  3353. * @returns {Promise<boolean>}
  3354. */
  3355. deleteById(modelName, id) {
  3356. throw new NotImplementedError(
  3357. "%s.deleteById is not implemented.",
  3358. this.constructor.name
  3359. );
  3360. }
  3361. /**
  3362. * Exists.
  3363. *
  3364. * @param {string} modelName
  3365. * @param {number|string} id
  3366. * @returns {Promise<boolean>}
  3367. */
  3368. exists(modelName, id) {
  3369. throw new NotImplementedError(
  3370. "%s.exists is not implemented.",
  3371. this.constructor.name
  3372. );
  3373. }
  3374. /**
  3375. * Count.
  3376. *
  3377. * @param {string} modelName
  3378. * @param {object|undefined} where
  3379. * @returns {Promise<number>}
  3380. */
  3381. count(modelName, where = void 0) {
  3382. throw new NotImplementedError(
  3383. "%s.count is not implemented.",
  3384. this.constructor.name
  3385. );
  3386. }
  3387. };
  3388. __name(_Adapter, "Adapter");
  3389. /**
  3390. * Kinds.
  3391. *
  3392. * @type {string[]}
  3393. */
  3394. __publicField(_Adapter, "kinds", [...import_js_service20.Service.kinds, ADAPTER_CLASS_NAME]);
  3395. Adapter = _Adapter;
  3396. }
  3397. });
  3398. // src/adapter/builtin/memory-adapter.js
  3399. var memory_adapter_exports = {};
  3400. __export(memory_adapter_exports, {
  3401. MemoryAdapter: () => MemoryAdapter
  3402. });
  3403. var _MemoryAdapter, MemoryAdapter;
  3404. var init_memory_adapter = __esm({
  3405. "src/adapter/builtin/memory-adapter.js"() {
  3406. "use strict";
  3407. init_adapter();
  3408. init_errors();
  3409. init_utils();
  3410. init_definition();
  3411. init_filter();
  3412. _MemoryAdapter = class _MemoryAdapter extends Adapter {
  3413. /**
  3414. * Tables.
  3415. *
  3416. * @type {Map<string, Map<number, Record<string, any>>>}
  3417. */
  3418. _tables = /* @__PURE__ */ new Map();
  3419. /**
  3420. * Last ids.
  3421. *
  3422. * @type {Map<string, number>}
  3423. */
  3424. _lastIds = /* @__PURE__ */ new Map();
  3425. /**
  3426. * Get table or create.
  3427. *
  3428. * @param {string} modelName
  3429. * @returns {Map<number, object>}
  3430. */
  3431. _getTableOrCreate(modelName) {
  3432. const tableName = this.getService(ModelDefinitionUtils).getTableNameByModelName(modelName);
  3433. let table = this._tables.get(tableName);
  3434. if (table) return table;
  3435. table = /* @__PURE__ */ new Map();
  3436. this._tables.set(tableName, table);
  3437. return table;
  3438. }
  3439. /**
  3440. * Gen next id value.
  3441. *
  3442. * @param {string} modelName
  3443. * @param {string} propName
  3444. * @returns {number}
  3445. */
  3446. _genNextIdValue(modelName, propName) {
  3447. var _a;
  3448. const modelUtils = this.getService(ModelDefinitionUtils);
  3449. const propType = modelUtils.getDataTypeByPropertyName(modelName, propName);
  3450. if (propType !== DataType.ANY && propType !== DataType.NUMBER) {
  3451. throw new InvalidArgumentError(
  3452. "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.",
  3453. propName,
  3454. modelName,
  3455. capitalize(propType),
  3456. propName
  3457. );
  3458. }
  3459. const tableName = modelUtils.getTableNameByModelName(modelName);
  3460. const table = this._getTableOrCreate(modelName);
  3461. let nextId = (_a = this._lastIds.get(tableName)) != null ? _a : 0;
  3462. do {
  3463. nextId++;
  3464. } while (table.has(nextId));
  3465. this._lastIds.set(tableName, nextId);
  3466. return nextId;
  3467. }
  3468. /**
  3469. * Update last id value if needed.
  3470. *
  3471. * Если переданное значение последнего использованного
  3472. * идентификатора больше текущего, то текущее значение
  3473. * перезаписывается полученным.
  3474. *
  3475. * @param {string} modelName
  3476. * @param {number} idValue
  3477. */
  3478. _updateLastIdValueIfNeeded(modelName, idValue) {
  3479. var _a;
  3480. const tableName = this.getService(ModelDefinitionUtils).getTableNameByModelName(modelName);
  3481. const currentLastId = (_a = this._lastIds.get(tableName)) != null ? _a : 0;
  3482. if (idValue > currentLastId) {
  3483. this._lastIds.set(tableName, idValue);
  3484. }
  3485. }
  3486. /**
  3487. * Create
  3488. *
  3489. * @param {string} modelName
  3490. * @param {object} modelData
  3491. * @param {object|undefined} filter
  3492. * @returns {Promise<object>}
  3493. */
  3494. // eslint-disable-next-line no-unused-vars
  3495. async create(modelName, modelData, filter = void 0) {
  3496. const pkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  3497. modelName
  3498. );
  3499. let idValue = modelData[pkPropName];
  3500. if (idValue == null || idValue === "" || idValue === 0) {
  3501. idValue = this._genNextIdValue(modelName, pkPropName);
  3502. } else if (typeof idValue === "number") {
  3503. this._updateLastIdValueIfNeeded(modelName, idValue);
  3504. }
  3505. const table = this._getTableOrCreate(modelName);
  3506. if (table.has(idValue))
  3507. throw new InvalidArgumentError(
  3508. "The value %v of the primary key %v already exists in the model %v.",
  3509. idValue,
  3510. pkPropName,
  3511. modelName
  3512. );
  3513. modelData = cloneDeep(modelData);
  3514. modelData[pkPropName] = idValue;
  3515. const tableData = this.getService(
  3516. ModelDefinitionUtils
  3517. ).convertPropertyNamesToColumnNames(modelName, modelData);
  3518. table.set(idValue, tableData);
  3519. return this.getService(
  3520. ModelDefinitionUtils
  3521. ).convertColumnNamesToPropertyNames(modelName, tableData);
  3522. }
  3523. /**
  3524. * Replace by id.
  3525. *
  3526. * @param {string} modelName
  3527. * @param {string|number} id
  3528. * @param {object} modelData
  3529. * @param {object|undefined} filter
  3530. * @returns {Promise<object>}
  3531. */
  3532. // eslint-disable-next-line no-unused-vars
  3533. async replaceById(modelName, id, modelData, filter = void 0) {
  3534. const table = this._getTableOrCreate(modelName);
  3535. const isExists = table.has(id);
  3536. const pkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  3537. modelName
  3538. );
  3539. if (!isExists)
  3540. throw new InvalidArgumentError(
  3541. "The value %v of the primary key %v does not exist in the model %v.",
  3542. id,
  3543. pkPropName,
  3544. modelName
  3545. );
  3546. modelData = cloneDeep(modelData);
  3547. modelData[pkPropName] = id;
  3548. const tableData = this.getService(
  3549. ModelDefinitionUtils
  3550. ).convertPropertyNamesToColumnNames(modelName, modelData);
  3551. table.set(id, tableData);
  3552. return this.getService(
  3553. ModelDefinitionUtils
  3554. ).convertColumnNamesToPropertyNames(modelName, tableData);
  3555. }
  3556. /**
  3557. * Replace or create.
  3558. *
  3559. * @param {string} modelName
  3560. * @param {object} modelData
  3561. * @param {object|undefined} filter
  3562. * @returns {Promise<object>}
  3563. */
  3564. // eslint-disable-next-line no-unused-vars
  3565. async replaceOrCreate(modelName, modelData, filter = void 0) {
  3566. const pkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  3567. modelName
  3568. );
  3569. let idValue = modelData[pkPropName];
  3570. if (idValue == null || idValue === "" || idValue === 0) {
  3571. idValue = this._genNextIdValue(modelName, pkPropName);
  3572. } else if (typeof idValue === "number") {
  3573. this._updateLastIdValueIfNeeded(modelName, idValue);
  3574. }
  3575. const table = this._getTableOrCreate(modelName);
  3576. modelData = cloneDeep(modelData);
  3577. modelData[pkPropName] = idValue;
  3578. const tableData = this.getService(
  3579. ModelDefinitionUtils
  3580. ).convertPropertyNamesToColumnNames(modelName, modelData);
  3581. table.set(idValue, tableData);
  3582. return this.getService(
  3583. ModelDefinitionUtils
  3584. ).convertColumnNamesToPropertyNames(modelName, tableData);
  3585. }
  3586. /**
  3587. * Patch.
  3588. *
  3589. * @param {string} modelName
  3590. * @param {object} modelData
  3591. * @param {object|undefined} where
  3592. * @returns {Promise<number>}
  3593. */
  3594. async patch(modelName, modelData, where = void 0) {
  3595. const table = this._getTableOrCreate(modelName);
  3596. const tableItems = Array.from(table.values());
  3597. if (!tableItems.length) return 0;
  3598. let modelItems = tableItems.map(
  3599. (tableItem) => this.getService(ModelDefinitionUtils).convertColumnNamesToPropertyNames(
  3600. modelName,
  3601. tableItem
  3602. )
  3603. );
  3604. if (where && typeof where === "object")
  3605. modelItems = this.getService(WhereClauseTool).filter(modelItems, where);
  3606. const size = modelItems.length;
  3607. const pkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  3608. modelName
  3609. );
  3610. modelData = cloneDeep(modelData);
  3611. delete modelData[pkPropName];
  3612. modelItems.forEach((existingModelData) => {
  3613. const mergedModelData = Object.assign({}, existingModelData, modelData);
  3614. const mergedTableData = this.getService(
  3615. ModelDefinitionUtils
  3616. ).convertPropertyNamesToColumnNames(modelName, mergedModelData);
  3617. const idValue = existingModelData[pkPropName];
  3618. table.set(idValue, mergedTableData);
  3619. });
  3620. return size;
  3621. }
  3622. /**
  3623. * Patch by id.
  3624. *
  3625. * @param {string} modelName
  3626. * @param {string|number} id
  3627. * @param {object} modelData
  3628. * @param {object|undefined} filter
  3629. * @returns {Promise<object>}
  3630. */
  3631. // eslint-disable-next-line no-unused-vars
  3632. async patchById(modelName, id, modelData, filter = void 0) {
  3633. const table = this._getTableOrCreate(modelName);
  3634. const existingTableData = table.get(id);
  3635. const pkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  3636. modelName
  3637. );
  3638. if (existingTableData == null)
  3639. throw new InvalidArgumentError(
  3640. "The value %v of the primary key %v does not exist in the model %v.",
  3641. id,
  3642. pkPropName,
  3643. modelName
  3644. );
  3645. modelData = cloneDeep(modelData);
  3646. delete modelData[pkPropName];
  3647. const existingModelData = this.getService(
  3648. ModelDefinitionUtils
  3649. ).convertColumnNamesToPropertyNames(modelName, existingTableData);
  3650. const mergedModelData = Object.assign({}, existingModelData, modelData);
  3651. const mergedTableData = this.getService(
  3652. ModelDefinitionUtils
  3653. ).convertPropertyNamesToColumnNames(modelName, mergedModelData);
  3654. table.set(id, mergedTableData);
  3655. return this.getService(
  3656. ModelDefinitionUtils
  3657. ).convertColumnNamesToPropertyNames(modelName, mergedTableData);
  3658. }
  3659. /**
  3660. * Find.
  3661. *
  3662. * @param {string} modelName
  3663. * @param {object|undefined} filter
  3664. * @returns {Promise<object[]>}
  3665. */
  3666. async find(modelName, filter = void 0) {
  3667. const table = this._getTableOrCreate(modelName);
  3668. const tableItems = Array.from(table.values());
  3669. let modelItems = tableItems.map(
  3670. (tableItem) => this.getService(ModelDefinitionUtils).convertColumnNamesToPropertyNames(
  3671. modelName,
  3672. tableItem
  3673. )
  3674. );
  3675. if (filter && typeof filter === "object") {
  3676. if (filter.where)
  3677. modelItems = this.getService(WhereClauseTool).filter(
  3678. modelItems,
  3679. filter.where
  3680. );
  3681. if (filter.skip || filter.limit)
  3682. modelItems = this.getService(SliceClauseTool).slice(
  3683. modelItems,
  3684. filter.skip,
  3685. filter.limit
  3686. );
  3687. if (filter.order)
  3688. this.getService(OrderClauseTool).sort(modelItems, filter.order);
  3689. }
  3690. return modelItems;
  3691. }
  3692. /**
  3693. * Find by id.
  3694. *
  3695. * @param {string} modelName
  3696. * @param {string|number} id
  3697. * @param {object|undefined} filter
  3698. * @returns {Promise<object>}
  3699. */
  3700. // eslint-disable-next-line no-unused-vars
  3701. async findById(modelName, id, filter = void 0) {
  3702. const table = this._getTableOrCreate(modelName);
  3703. const tableData = table.get(id);
  3704. const pkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  3705. modelName
  3706. );
  3707. if (!tableData)
  3708. throw new InvalidArgumentError(
  3709. "The value %v of the primary key %v does not exist in the model %v.",
  3710. id,
  3711. pkPropName,
  3712. modelName
  3713. );
  3714. return this.getService(
  3715. ModelDefinitionUtils
  3716. ).convertColumnNamesToPropertyNames(modelName, tableData);
  3717. }
  3718. /**
  3719. * Delete.
  3720. *
  3721. * @param {string} modelName
  3722. * @param {object|undefined} where
  3723. * @returns {Promise<number>}
  3724. */
  3725. async delete(modelName, where = void 0) {
  3726. const table = this._getTableOrCreate(modelName);
  3727. const tableItems = Array.from(table.values());
  3728. if (!tableItems.length) return 0;
  3729. let modelItems = tableItems.map(
  3730. (tableItem) => this.getService(ModelDefinitionUtils).convertColumnNamesToPropertyNames(
  3731. modelName,
  3732. tableItem
  3733. )
  3734. );
  3735. if (where && typeof where === "object")
  3736. modelItems = this.getService(WhereClauseTool).filter(modelItems, where);
  3737. const size = modelItems.length;
  3738. const idPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  3739. modelName
  3740. );
  3741. modelItems.forEach((modelData) => {
  3742. const idValue = modelData[idPropName];
  3743. table.delete(idValue);
  3744. });
  3745. return size;
  3746. }
  3747. /**
  3748. * Delete by id.
  3749. *
  3750. * @param {string} modelName
  3751. * @param {string|number} id
  3752. * @returns {Promise<boolean>}
  3753. */
  3754. async deleteById(modelName, id) {
  3755. const table = this._getTableOrCreate(modelName);
  3756. const isExists = table.has(id);
  3757. table.delete(id);
  3758. return isExists;
  3759. }
  3760. /**
  3761. * Exists.
  3762. *
  3763. * @param {string} modelName
  3764. * @param {string|number} id
  3765. * @returns {Promise<boolean>}
  3766. */
  3767. async exists(modelName, id) {
  3768. const table = this._getTableOrCreate(modelName);
  3769. return table.has(id);
  3770. }
  3771. /**
  3772. * Count.
  3773. *
  3774. * @param {string} modelName
  3775. * @param {object|undefined} where
  3776. * @returns {Promise<number>}
  3777. */
  3778. async count(modelName, where = void 0) {
  3779. const table = this._getTableOrCreate(modelName);
  3780. const tableItems = Array.from(table.values());
  3781. let modelItems = tableItems.map(
  3782. (tableItem) => this.getService(ModelDefinitionUtils).convertColumnNamesToPropertyNames(
  3783. modelName,
  3784. tableItem
  3785. )
  3786. );
  3787. if (where && typeof where === "object")
  3788. modelItems = this.getService(WhereClauseTool).filter(modelItems, where);
  3789. return modelItems.length;
  3790. }
  3791. };
  3792. __name(_MemoryAdapter, "MemoryAdapter");
  3793. MemoryAdapter = _MemoryAdapter;
  3794. }
  3795. });
  3796. // import("./builtin/**/*-adapter.js") in src/adapter/adapter-loader.js
  3797. var globImport_builtin_adapter_js;
  3798. var init_ = __esm({
  3799. 'import("./builtin/**/*-adapter.js") in src/adapter/adapter-loader.js'() {
  3800. globImport_builtin_adapter_js = __glob({
  3801. "./builtin/memory-adapter.js": () => Promise.resolve().then(() => (init_memory_adapter(), memory_adapter_exports))
  3802. });
  3803. }
  3804. });
  3805. // src/adapter/adapter-loader.js
  3806. function findAdapterCtorInModule(module2) {
  3807. let adapterCtor;
  3808. if (!module2 || typeof module2 !== "object" || Array.isArray(module2)) return;
  3809. for (const ctor of Object.values(module2)) {
  3810. if (typeof ctor === "function" && Array.isArray(ctor.kinds) && Adapter.kinds.includes(ADAPTER_CLASS_NAME)) {
  3811. adapterCtor = ctor;
  3812. break;
  3813. }
  3814. }
  3815. return adapterCtor;
  3816. }
  3817. var import_js_service21, _AdapterLoader, AdapterLoader;
  3818. var init_adapter_loader = __esm({
  3819. "src/adapter/adapter-loader.js"() {
  3820. "use strict";
  3821. import_js_service21 = require("@e22m4u/js-service");
  3822. init_errors();
  3823. init_adapter();
  3824. init_();
  3825. _AdapterLoader = class _AdapterLoader extends import_js_service21.Service {
  3826. /**
  3827. * Load by name.
  3828. *
  3829. * @param {string} adapterName
  3830. * @param {object|undefined} settings
  3831. * @returns {Promise<Adapter>}
  3832. */
  3833. async loadByName(adapterName, settings = void 0) {
  3834. if (!adapterName || typeof adapterName !== "string")
  3835. throw new InvalidArgumentError(
  3836. "The adapter name should be a non-empty String, but %v was given.",
  3837. adapterName
  3838. );
  3839. let adapterCtor;
  3840. try {
  3841. const module2 = await globImport_builtin_adapter_js(`./builtin/${adapterName}-adapter.js`);
  3842. adapterCtor = findAdapterCtorInModule(module2);
  3843. } catch {
  3844. }
  3845. if (!adapterCtor)
  3846. try {
  3847. const module2 = await Promise.resolve().then(() => __toESM(require(`@e22m4u/js-repository-${adapterName}-adapter`)));
  3848. adapterCtor = findAdapterCtorInModule(module2);
  3849. } catch {
  3850. }
  3851. if (!adapterCtor)
  3852. throw new InvalidArgumentError(
  3853. "The adapter %v is not found.",
  3854. adapterName
  3855. );
  3856. return new adapterCtor(this.container, settings);
  3857. }
  3858. };
  3859. __name(_AdapterLoader, "AdapterLoader");
  3860. AdapterLoader = _AdapterLoader;
  3861. __name(findAdapterCtorInModule, "findAdapterCtorInModule");
  3862. }
  3863. });
  3864. // src/adapter/adapter-registry.js
  3865. var import_js_service22, _AdapterRegistry, AdapterRegistry;
  3866. var init_adapter_registry = __esm({
  3867. "src/adapter/adapter-registry.js"() {
  3868. "use strict";
  3869. init_adapter();
  3870. import_js_service22 = require("@e22m4u/js-service");
  3871. init_adapter_loader();
  3872. init_definition();
  3873. _AdapterRegistry = class _AdapterRegistry extends import_js_service22.Service {
  3874. /**
  3875. * Adapters.
  3876. *
  3877. * @type {object}
  3878. */
  3879. _adapters = {};
  3880. /**
  3881. * Get adapter.
  3882. *
  3883. * @param {string} datasourceName
  3884. * @returns {Promise<Adapter>}
  3885. */
  3886. async getAdapter(datasourceName) {
  3887. let adapter = this._adapters[datasourceName];
  3888. if (adapter) return adapter;
  3889. const datasource = this.getService(DefinitionRegistry).getDatasource(datasourceName);
  3890. const adapterName = datasource.adapter;
  3891. adapter = await this.getService(AdapterLoader).loadByName(
  3892. adapterName,
  3893. datasource
  3894. );
  3895. this._adapters[datasourceName] = adapter;
  3896. return adapter;
  3897. }
  3898. };
  3899. __name(_AdapterRegistry, "AdapterRegistry");
  3900. AdapterRegistry = _AdapterRegistry;
  3901. }
  3902. });
  3903. // src/adapter/index.js
  3904. var init_adapter2 = __esm({
  3905. "src/adapter/index.js"() {
  3906. "use strict";
  3907. init_adapter();
  3908. init_adapter_loader();
  3909. init_adapter_registry();
  3910. }
  3911. });
  3912. // src/repository/repository.js
  3913. var import_js_service23, _Repository, Repository;
  3914. var init_repository = __esm({
  3915. "src/repository/repository.js"() {
  3916. "use strict";
  3917. import_js_service23 = require("@e22m4u/js-service");
  3918. init_errors();
  3919. init_definition();
  3920. init_adapter2();
  3921. _Repository = class _Repository extends import_js_service23.Service {
  3922. /**
  3923. * Model name.
  3924. *
  3925. * @type {string}
  3926. */
  3927. _modelName;
  3928. /**
  3929. * Model name.
  3930. *
  3931. * @returns {string}
  3932. */
  3933. get modelName() {
  3934. return this._modelName;
  3935. }
  3936. /**
  3937. * Datasource name.
  3938. *
  3939. * @type {string}
  3940. */
  3941. _datasourceName;
  3942. /**
  3943. * Datasource name.
  3944. *
  3945. * @returns {string}
  3946. */
  3947. get datasourceName() {
  3948. return this._datasourceName;
  3949. }
  3950. /**
  3951. * Constructor.
  3952. *
  3953. * @typedef {import('@e22m4u/js-service').ServiceContainer} ServiceContainer
  3954. * @param {ServiceContainer} container
  3955. * @param {string} modelName
  3956. */
  3957. constructor(container, modelName) {
  3958. super(container);
  3959. this._modelName = modelName;
  3960. const modelDef = this.getService(DefinitionRegistry).getModel(modelName);
  3961. const datasourceName = modelDef.datasource;
  3962. if (!datasourceName)
  3963. throw new InvalidArgumentError(
  3964. "The model %v does not have a specified datasource.",
  3965. modelName
  3966. );
  3967. this._datasourceName = datasourceName;
  3968. }
  3969. /**
  3970. * Get adapter.
  3971. *
  3972. * @returns {Adapter}
  3973. */
  3974. async getAdapter() {
  3975. return this.getService(AdapterRegistry).getAdapter(this.datasourceName);
  3976. }
  3977. /**
  3978. * Create.
  3979. *
  3980. * @param {object} data
  3981. * @param {object|undefined} filter
  3982. * @returns {Promise<object>}
  3983. */
  3984. async create(data, filter = void 0) {
  3985. const adapter = await this.getAdapter();
  3986. return adapter.create(this.modelName, data, filter);
  3987. }
  3988. /**
  3989. * Replace by id.
  3990. *
  3991. * @param {number|string} id
  3992. * @param {object} data
  3993. * @param {object|undefined} filter
  3994. * @returns {Promise<object>}
  3995. */
  3996. async replaceById(id, data, filter = void 0) {
  3997. const adapter = await this.getAdapter();
  3998. return adapter.replaceById(this.modelName, id, data, filter);
  3999. }
  4000. /**
  4001. * Replace or create.
  4002. *
  4003. * @param {object} data
  4004. * @param {object|undefined} filter
  4005. * @returns {Promise<object>}
  4006. */
  4007. async replaceOrCreate(data, filter = void 0) {
  4008. const adapter = await this.getAdapter();
  4009. return adapter.replaceOrCreate(this.modelName, data, filter);
  4010. }
  4011. /**
  4012. * Patch.
  4013. *
  4014. * @param {object} data
  4015. * @param {object|undefined} where
  4016. * @returns {Promise<number>}
  4017. */
  4018. async patch(data, where = void 0) {
  4019. const adapter = await this.getAdapter();
  4020. return adapter.patch(this.modelName, data, where);
  4021. }
  4022. /**
  4023. * Patch by id.
  4024. *
  4025. * @param {number|string} id
  4026. * @param {object} data
  4027. * @param {object|undefined} filter
  4028. * @returns {Promise<object>}
  4029. */
  4030. async patchById(id, data, filter = void 0) {
  4031. const adapter = await this.getAdapter();
  4032. return adapter.patchById(this.modelName, id, data, filter);
  4033. }
  4034. /**
  4035. * Find.
  4036. *
  4037. * @param {object|undefined} filter
  4038. * @returns {Promise<object[]>}
  4039. */
  4040. async find(filter = void 0) {
  4041. const adapter = await this.getAdapter();
  4042. return adapter.find(this.modelName, filter);
  4043. }
  4044. /**
  4045. * Find one.
  4046. *
  4047. * @param {object|undefined} filter
  4048. * @returns {Promise<object|undefined>}
  4049. */
  4050. async findOne(filter = void 0) {
  4051. const adapter = await this.getAdapter();
  4052. filter = filter != null ? filter : {};
  4053. filter.limit = 1;
  4054. const result = await adapter.find(this.modelName, filter);
  4055. return result.length ? result[0] : void 0;
  4056. }
  4057. /**
  4058. * Find by id.
  4059. *
  4060. * @param {number|string} id
  4061. * @param {object|undefined} filter
  4062. * @returns {Promise<object>}
  4063. */
  4064. async findById(id, filter = void 0) {
  4065. const adapter = await this.getAdapter();
  4066. return adapter.findById(this.modelName, id, filter);
  4067. }
  4068. /**
  4069. * Delete.
  4070. *
  4071. * @param {object|undefined} where
  4072. * @returns {Promise<number>}
  4073. */
  4074. async delete(where = void 0) {
  4075. const adapter = await this.getAdapter();
  4076. return adapter.delete(this.modelName, where);
  4077. }
  4078. /**
  4079. * Delete by id.
  4080. *
  4081. * @param {number|string} id
  4082. * @returns {Promise<boolean>}
  4083. */
  4084. async deleteById(id) {
  4085. const adapter = await this.getAdapter();
  4086. return adapter.deleteById(this.modelName, id);
  4087. }
  4088. /**
  4089. * Exists.
  4090. *
  4091. * @param {number|string} id
  4092. * @returns {Promise<boolean>}
  4093. */
  4094. async exists(id) {
  4095. const adapter = await this.getAdapter();
  4096. return adapter.exists(this.modelName, id);
  4097. }
  4098. /**
  4099. * Count.
  4100. *
  4101. * @param {object|undefined} where
  4102. * @returns {Promise<number>}
  4103. */
  4104. async count(where = void 0) {
  4105. const adapter = await this.getAdapter();
  4106. return adapter.count(this.modelName, where);
  4107. }
  4108. };
  4109. __name(_Repository, "Repository");
  4110. Repository = _Repository;
  4111. }
  4112. });
  4113. // src/repository/repository-registry.js
  4114. var import_js_service24, _RepositoryRegistry, RepositoryRegistry;
  4115. var init_repository_registry = __esm({
  4116. "src/repository/repository-registry.js"() {
  4117. "use strict";
  4118. import_js_service24 = require("@e22m4u/js-service");
  4119. init_repository();
  4120. init_utils();
  4121. init_errors();
  4122. _RepositoryRegistry = class _RepositoryRegistry extends import_js_service24.Service {
  4123. /**
  4124. * Repositories.
  4125. *
  4126. * @type {object}
  4127. */
  4128. _repositories = {};
  4129. /**
  4130. * Repository ctor.
  4131. *
  4132. * @type {typeof Repository}
  4133. * @private
  4134. */
  4135. _repositoryCtor = Repository;
  4136. /**
  4137. * Set repository ctor.
  4138. *
  4139. * @param {typeof Repository} ctor
  4140. */
  4141. setRepositoryCtor(ctor) {
  4142. if (!ctor || typeof ctor !== "function" || !(ctor.prototype instanceof Repository)) {
  4143. throw new InvalidArgumentError(
  4144. "The first argument of RepositoryRegistry.setRepositoryCtor must inherit from Repository class, but %v was given.",
  4145. ctor
  4146. );
  4147. }
  4148. this._repositoryCtor = ctor;
  4149. }
  4150. /**
  4151. * Get repository.
  4152. *
  4153. * @param {string} modelName
  4154. * @returns {Repository}
  4155. */
  4156. getRepository(modelName) {
  4157. const modelKey = modelNameToModelKey(modelName);
  4158. let repository = this._repositories[modelKey];
  4159. if (repository) return repository;
  4160. repository = new this._repositoryCtor(this.container, modelName);
  4161. this._repositories[modelKey] = repository;
  4162. return repository;
  4163. }
  4164. };
  4165. __name(_RepositoryRegistry, "RepositoryRegistry");
  4166. RepositoryRegistry = _RepositoryRegistry;
  4167. }
  4168. });
  4169. // src/repository/index.js
  4170. var init_repository2 = __esm({
  4171. "src/repository/index.js"() {
  4172. "use strict";
  4173. init_repository();
  4174. init_repository_registry();
  4175. }
  4176. });
  4177. // src/relations/has-one-resolver.js
  4178. var import_js_service25, _HasOneResolver, HasOneResolver;
  4179. var init_has_one_resolver = __esm({
  4180. "src/relations/has-one-resolver.js"() {
  4181. "use strict";
  4182. import_js_service25 = require("@e22m4u/js-service");
  4183. init_utils();
  4184. init_errors();
  4185. init_repository2();
  4186. init_definition();
  4187. _HasOneResolver = class _HasOneResolver extends import_js_service25.Service {
  4188. /**
  4189. * Include to.
  4190. *
  4191. * @param {object[]} entities
  4192. * @param {string} sourceName
  4193. * @param {string} targetName
  4194. * @param {string} relationName
  4195. * @param {string} foreignKey
  4196. * @param {object|undefined} scope
  4197. * @returns {Promise<void>}
  4198. */
  4199. async includeTo(entities, sourceName, targetName, relationName, foreignKey, scope = void 0) {
  4200. if (!entities || !Array.isArray(entities))
  4201. throw new InvalidArgumentError(
  4202. 'The parameter "entities" of HasOneResolver.includeTo requires an Array of Object, but %v was given.',
  4203. entities
  4204. );
  4205. if (!sourceName || typeof sourceName !== "string")
  4206. throw new InvalidArgumentError(
  4207. 'The parameter "sourceName" of HasOneResolver.includeTo requires a non-empty String, but %v was given.',
  4208. sourceName
  4209. );
  4210. if (!targetName || typeof targetName !== "string")
  4211. throw new InvalidArgumentError(
  4212. 'The parameter "targetName" of HasOneResolver.includeTo requires a non-empty String, but %v was given.',
  4213. targetName
  4214. );
  4215. if (!relationName || typeof relationName !== "string")
  4216. throw new InvalidArgumentError(
  4217. 'The parameter "relationName" of HasOneResolver.includeTo requires a non-empty String, but %v was given.',
  4218. relationName
  4219. );
  4220. if (!foreignKey || typeof foreignKey !== "string")
  4221. throw new InvalidArgumentError(
  4222. 'The parameter "foreignKey" of HasOneResolver.includeTo requires a non-empty String, but %v was given.',
  4223. foreignKey
  4224. );
  4225. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  4226. throw new InvalidArgumentError(
  4227. 'The provided parameter "scope" of HasOneResolver.includeTo should be an Object, but %v was given.',
  4228. scope
  4229. );
  4230. const sourcePkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  4231. sourceName
  4232. );
  4233. const sourceIds = [];
  4234. entities.forEach((entity) => {
  4235. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  4236. throw new InvalidArgumentError(
  4237. 'The parameter "entities" of HasOneResolver.includeTo requires an Array of Object, but %v was given.',
  4238. entity
  4239. );
  4240. const sourceId = entity[sourcePkPropName];
  4241. if (sourceIds.includes(sourceId)) return;
  4242. sourceIds.push(sourceId);
  4243. });
  4244. const promises = [];
  4245. const targetRepository = this.getService(RepositoryRegistry).getRepository(targetName);
  4246. scope = scope ? cloneDeep(scope) : {};
  4247. const targetBySourceId = /* @__PURE__ */ new Map();
  4248. sourceIds.forEach((sourceId) => {
  4249. const filter = cloneDeep(scope);
  4250. filter.where = {
  4251. and: [{ [foreignKey]: sourceId }, ...scope.where ? [scope.where] : []]
  4252. };
  4253. filter.limit = 1;
  4254. promises.push(
  4255. targetRepository.find(filter).then((result) => {
  4256. if (result.length) targetBySourceId.set(sourceId, result[0]);
  4257. })
  4258. );
  4259. });
  4260. await Promise.all(promises);
  4261. Array.from(targetBySourceId.keys()).forEach((sourceId) => {
  4262. const sources = entities.filter((v) => v[sourcePkPropName] === sourceId);
  4263. sources.forEach((v) => v[relationName] = targetBySourceId.get(sourceId));
  4264. });
  4265. }
  4266. /**
  4267. * Include polymorphic to.
  4268. *
  4269. * @param {object[]} entities
  4270. * @param {string} sourceName
  4271. * @param {string} targetName
  4272. * @param {string} relationName
  4273. * @param {string} foreignKey
  4274. * @param {string} discriminator
  4275. * @param {object|undefined} scope
  4276. * @returns {Promise<void>}
  4277. */
  4278. async includePolymorphicTo(entities, sourceName, targetName, relationName, foreignKey, discriminator, scope = void 0) {
  4279. if (!entities || !Array.isArray(entities))
  4280. throw new InvalidArgumentError(
  4281. 'The parameter "entities" of HasOneResolver.includePolymorphicTo requires an Array of Object, but %v was given.',
  4282. entities
  4283. );
  4284. if (!sourceName || typeof sourceName !== "string")
  4285. throw new InvalidArgumentError(
  4286. 'The parameter "sourceName" of HasOneResolver.includePolymorphicTo requires a non-empty String, but %v was given.',
  4287. sourceName
  4288. );
  4289. if (!targetName || typeof targetName !== "string")
  4290. throw new InvalidArgumentError(
  4291. 'The parameter "targetName" of HasOneResolver.includePolymorphicTo requires a non-empty String, but %v was given.',
  4292. targetName
  4293. );
  4294. if (!relationName || typeof relationName !== "string")
  4295. throw new InvalidArgumentError(
  4296. 'The parameter "relationName" of HasOneResolver.includePolymorphicTo requires a non-empty String, but %v was given.',
  4297. relationName
  4298. );
  4299. if (!foreignKey || typeof foreignKey !== "string")
  4300. throw new InvalidArgumentError(
  4301. 'The parameter "foreignKey" of HasOneResolver.includePolymorphicTo requires a non-empty String, but %v was given.',
  4302. foreignKey
  4303. );
  4304. if (!discriminator || typeof discriminator !== "string")
  4305. throw new InvalidArgumentError(
  4306. 'The parameter "discriminator" of HasOneResolver.includePolymorphicTo requires a non-empty String, but %v was given.',
  4307. discriminator
  4308. );
  4309. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  4310. throw new InvalidArgumentError(
  4311. 'The provided parameter "scope" of HasOneResolver.includePolymorphicTo should be an Object, but %v was given.',
  4312. scope
  4313. );
  4314. const sourcePkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  4315. sourceName
  4316. );
  4317. const sourceIds = [];
  4318. entities.forEach((entity) => {
  4319. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  4320. throw new InvalidArgumentError(
  4321. 'The parameter "entities" of HasOneResolver.includePolymorphicTo requires an Array of Object, but %v was given.',
  4322. entity
  4323. );
  4324. const sourceId = entity[sourcePkPropName];
  4325. if (sourceIds.includes(sourceId)) return;
  4326. sourceIds.push(sourceId);
  4327. });
  4328. const promises = [];
  4329. const targetRepository = this.getService(RepositoryRegistry).getRepository(targetName);
  4330. scope = scope ? cloneDeep(scope) : {};
  4331. const targetBySourceId = /* @__PURE__ */ new Map();
  4332. sourceIds.forEach((sourceId) => {
  4333. const filter = cloneDeep(scope);
  4334. filter.where = {
  4335. and: [
  4336. { [foreignKey]: sourceId, [discriminator]: sourceName },
  4337. ...scope.where ? [scope.where] : []
  4338. ]
  4339. };
  4340. filter.limit = 1;
  4341. promises.push(
  4342. targetRepository.find(filter).then((result) => {
  4343. if (result.length) targetBySourceId.set(sourceId, result[0]);
  4344. })
  4345. );
  4346. });
  4347. await Promise.all(promises);
  4348. Array.from(targetBySourceId.keys()).forEach((sourceId) => {
  4349. const sources = entities.filter((v) => v[sourcePkPropName] === sourceId);
  4350. sources.forEach((v) => v[relationName] = targetBySourceId.get(sourceId));
  4351. });
  4352. }
  4353. /**
  4354. * Include polymorphic by relation name.
  4355. *
  4356. * @param {object[]} entities
  4357. * @param {string} sourceName
  4358. * @param {string} targetName
  4359. * @param {string} relationName
  4360. * @param {string} targetRelationName
  4361. * @param {object|undefined} scope
  4362. * @returns {Promise<void>}
  4363. */
  4364. async includePolymorphicByRelationName(entities, sourceName, targetName, relationName, targetRelationName, scope = void 0) {
  4365. if (!entities || !Array.isArray(entities))
  4366. throw new InvalidArgumentError(
  4367. 'The parameter "entities" of HasOneResolver.includePolymorphicByRelationName requires an Array of Object, but %v was given.',
  4368. entities
  4369. );
  4370. if (!sourceName || typeof sourceName !== "string")
  4371. throw new InvalidArgumentError(
  4372. 'The parameter "sourceName" of HasOneResolver.includePolymorphicByRelationName requires a non-empty String, but %v was given.',
  4373. sourceName
  4374. );
  4375. if (!targetName || typeof targetName !== "string")
  4376. throw new InvalidArgumentError(
  4377. 'The parameter "targetName" of HasOneResolver.includePolymorphicByRelationName requires a non-empty String, but %v was given.',
  4378. targetName
  4379. );
  4380. if (!relationName || typeof relationName !== "string")
  4381. throw new InvalidArgumentError(
  4382. 'The parameter "relationName" of HasOneResolver.includePolymorphicByRelationName requires a non-empty String, but %v was given.',
  4383. relationName
  4384. );
  4385. if (!targetRelationName || typeof targetRelationName !== "string")
  4386. throw new InvalidArgumentError(
  4387. 'The parameter "targetRelationName" of HasOneResolver.includePolymorphicByRelationName requires a non-empty String, but %v was given.',
  4388. targetRelationName
  4389. );
  4390. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  4391. throw new InvalidArgumentError(
  4392. 'The provided parameter "scope" of HasOneResolver.includePolymorphicByRelationName should be an Object, but %v was given.',
  4393. scope
  4394. );
  4395. const targetRelationDef = this.getService(
  4396. ModelDefinitionUtils
  4397. ).getRelationDefinitionByName(targetName, targetRelationName);
  4398. if (targetRelationDef.type !== RelationType.BELONGS_TO)
  4399. throw new InvalidArgumentError(
  4400. '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 was given.',
  4401. relationName,
  4402. sourceName,
  4403. targetRelationName,
  4404. targetRelationDef.type
  4405. );
  4406. if (!targetRelationDef.polymorphic)
  4407. throw new InvalidArgumentError(
  4408. 'The relation %v of the model %v is a polymorphic "hasOne" relation, so it requires the target relation %v to be a polymorphic too.',
  4409. relationName,
  4410. sourceName,
  4411. targetRelationName
  4412. );
  4413. const foreignKey = targetRelationDef.foreignKey || `${targetRelationName}Id`;
  4414. const discriminator = targetRelationDef.discriminator || `${targetRelationName}Type`;
  4415. return this.includePolymorphicTo(
  4416. entities,
  4417. sourceName,
  4418. targetName,
  4419. relationName,
  4420. foreignKey,
  4421. discriminator,
  4422. scope
  4423. );
  4424. }
  4425. };
  4426. __name(_HasOneResolver, "HasOneResolver");
  4427. HasOneResolver = _HasOneResolver;
  4428. }
  4429. });
  4430. // src/relations/has-many-resolver.js
  4431. var import_js_service26, _HasManyResolver, HasManyResolver;
  4432. var init_has_many_resolver = __esm({
  4433. "src/relations/has-many-resolver.js"() {
  4434. "use strict";
  4435. import_js_service26 = require("@e22m4u/js-service");
  4436. init_utils();
  4437. init_errors();
  4438. init_repository2();
  4439. init_definition();
  4440. _HasManyResolver = class _HasManyResolver extends import_js_service26.Service {
  4441. /**
  4442. * Include to.
  4443. *
  4444. * @param {object[]} entities
  4445. * @param {string} sourceName
  4446. * @param {string} targetName
  4447. * @param {string} relationName
  4448. * @param {string} foreignKey
  4449. * @param {object|undefined} scope
  4450. * @returns {Promise<void>}
  4451. */
  4452. async includeTo(entities, sourceName, targetName, relationName, foreignKey, scope = void 0) {
  4453. if (!entities || !Array.isArray(entities))
  4454. throw new InvalidArgumentError(
  4455. 'The parameter "entities" of HasManyResolver.includeTo requires an Array of Object, but %v was given.',
  4456. entities
  4457. );
  4458. if (!sourceName || typeof sourceName !== "string")
  4459. throw new InvalidArgumentError(
  4460. 'The parameter "sourceName" of HasManyResolver.includeTo requires a non-empty String, but %v was given.',
  4461. sourceName
  4462. );
  4463. if (!targetName || typeof targetName !== "string")
  4464. throw new InvalidArgumentError(
  4465. 'The parameter "targetName" of HasManyResolver.includeTo requires a non-empty String, but %v was given.',
  4466. targetName
  4467. );
  4468. if (!relationName || typeof relationName !== "string")
  4469. throw new InvalidArgumentError(
  4470. 'The parameter "relationName" of HasManyResolver.includeTo requires a non-empty String, but %v was given.',
  4471. relationName
  4472. );
  4473. if (!foreignKey || typeof foreignKey !== "string")
  4474. throw new InvalidArgumentError(
  4475. 'The parameter "foreignKey" of HasManyResolver.includeTo requires a non-empty String, but %v was given.',
  4476. foreignKey
  4477. );
  4478. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  4479. throw new InvalidArgumentError(
  4480. 'The provided parameter "scope" of HasManyResolver.includeTo should be an Object, but %v was given.',
  4481. scope
  4482. );
  4483. const sourcePkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  4484. sourceName
  4485. );
  4486. const sourceIds = [];
  4487. entities.forEach((entity) => {
  4488. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  4489. throw new InvalidArgumentError(
  4490. 'The parameter "entities" of HasManyResolver.includeTo requires an Array of Object, but %v was given.',
  4491. entity
  4492. );
  4493. const sourceId = entity[sourcePkPropName];
  4494. if (sourceIds.includes(sourceId)) return;
  4495. sourceIds.push(sourceId);
  4496. });
  4497. const promises = [];
  4498. const targetRepository = this.getService(RepositoryRegistry).getRepository(targetName);
  4499. scope = scope ? cloneDeep(scope) : {};
  4500. const targetsBySourceId = /* @__PURE__ */ new Map();
  4501. sourceIds.forEach((sourceId) => {
  4502. const filter = cloneDeep(scope);
  4503. filter.where = {
  4504. and: [{ [foreignKey]: sourceId }, ...scope.where ? [scope.where] : []]
  4505. };
  4506. promises.push(
  4507. targetRepository.find(filter).then((result) => {
  4508. var _a;
  4509. if (result.length) {
  4510. let targets = (_a = targetsBySourceId.get(sourceId)) != null ? _a : [];
  4511. targets = [...targets, ...result];
  4512. targetsBySourceId.set(sourceId, targets);
  4513. }
  4514. })
  4515. );
  4516. });
  4517. await Promise.all(promises);
  4518. entities.forEach((entity) => {
  4519. var _a;
  4520. const sourceId = entity[sourcePkPropName];
  4521. entity[relationName] = (_a = targetsBySourceId.get(sourceId)) != null ? _a : [];
  4522. });
  4523. }
  4524. /**
  4525. * Include polymorphic to.
  4526. *
  4527. * @param {object[]} entities
  4528. * @param {string} sourceName
  4529. * @param {string} targetName
  4530. * @param {string} relationName
  4531. * @param {string} foreignKey
  4532. * @param {string} discriminator
  4533. * @param {object|undefined} scope
  4534. * @returns {Promise<void>}
  4535. */
  4536. async includePolymorphicTo(entities, sourceName, targetName, relationName, foreignKey, discriminator, scope = void 0) {
  4537. if (!entities || !Array.isArray(entities))
  4538. throw new InvalidArgumentError(
  4539. 'The parameter "entities" of HasManyResolver.includePolymorphicTo requires an Array of Object, but %v was given.',
  4540. entities
  4541. );
  4542. if (!sourceName || typeof sourceName !== "string")
  4543. throw new InvalidArgumentError(
  4544. 'The parameter "sourceName" of HasManyResolver.includePolymorphicTo requires a non-empty String, but %v was given.',
  4545. sourceName
  4546. );
  4547. if (!targetName || typeof targetName !== "string")
  4548. throw new InvalidArgumentError(
  4549. 'The parameter "targetName" of HasManyResolver.includePolymorphicTo requires a non-empty String, but %v was given.',
  4550. targetName
  4551. );
  4552. if (!relationName || typeof relationName !== "string")
  4553. throw new InvalidArgumentError(
  4554. 'The parameter "relationName" of HasManyResolver.includePolymorphicTo requires a non-empty String, but %v was given.',
  4555. relationName
  4556. );
  4557. if (!foreignKey || typeof foreignKey !== "string")
  4558. throw new InvalidArgumentError(
  4559. 'The parameter "foreignKey" of HasManyResolver.includePolymorphicTo requires a non-empty String, but %v was given.',
  4560. foreignKey
  4561. );
  4562. if (!discriminator || typeof discriminator !== "string")
  4563. throw new InvalidArgumentError(
  4564. 'The parameter "discriminator" of HasManyResolver.includePolymorphicTo requires a non-empty String, but %v was given.',
  4565. discriminator
  4566. );
  4567. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  4568. throw new InvalidArgumentError(
  4569. 'The provided parameter "scope" of HasManyResolver.includePolymorphicTo should be an Object, but %v was given.',
  4570. scope
  4571. );
  4572. const sourcePkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  4573. sourceName
  4574. );
  4575. const sourceIds = [];
  4576. entities.forEach((entity) => {
  4577. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  4578. throw new InvalidArgumentError(
  4579. 'The parameter "entities" of HasManyResolver.includePolymorphicTo requires an Array of Object, but %v was given.',
  4580. entity
  4581. );
  4582. const sourceId = entity[sourcePkPropName];
  4583. if (sourceIds.includes(sourceId)) return;
  4584. sourceIds.push(sourceId);
  4585. });
  4586. const promises = [];
  4587. const targetRepository = this.getService(RepositoryRegistry).getRepository(targetName);
  4588. scope = scope ? cloneDeep(scope) : {};
  4589. const targetsBySourceId = /* @__PURE__ */ new Map();
  4590. sourceIds.forEach((sourceId) => {
  4591. const filter = cloneDeep(scope);
  4592. filter.where = {
  4593. and: [
  4594. { [foreignKey]: sourceId, [discriminator]: sourceName },
  4595. ...scope.where ? [scope.where] : []
  4596. ]
  4597. };
  4598. promises.push(
  4599. targetRepository.find(filter).then((result) => {
  4600. var _a;
  4601. if (result.length) {
  4602. let targets = (_a = targetsBySourceId.get(sourceId)) != null ? _a : [];
  4603. targets = [...targets, ...result];
  4604. targetsBySourceId.set(sourceId, targets);
  4605. }
  4606. })
  4607. );
  4608. });
  4609. await Promise.all(promises);
  4610. entities.forEach((entity) => {
  4611. var _a;
  4612. const sourceId = entity[sourcePkPropName];
  4613. entity[relationName] = (_a = targetsBySourceId.get(sourceId)) != null ? _a : [];
  4614. });
  4615. }
  4616. /**
  4617. * Include polymorphic by relation name.
  4618. *
  4619. * @param {object[]} entities
  4620. * @param {string} sourceName
  4621. * @param {string} targetName
  4622. * @param {string} relationName
  4623. * @param {string} targetRelationName
  4624. * @param {object|undefined} scope
  4625. * @returns {Promise<void>}
  4626. */
  4627. async includePolymorphicByRelationName(entities, sourceName, targetName, relationName, targetRelationName, scope = void 0) {
  4628. if (!entities || !Array.isArray(entities))
  4629. throw new InvalidArgumentError(
  4630. 'The parameter "entities" of HasManyResolver.includePolymorphicByRelationName requires an Array of Object, but %v was given.',
  4631. entities
  4632. );
  4633. if (!sourceName || typeof sourceName !== "string")
  4634. throw new InvalidArgumentError(
  4635. 'The parameter "sourceName" of HasManyResolver.includePolymorphicByRelationName requires a non-empty String, but %v was given.',
  4636. sourceName
  4637. );
  4638. if (!targetName || typeof targetName !== "string")
  4639. throw new InvalidArgumentError(
  4640. 'The parameter "targetName" of HasManyResolver.includePolymorphicByRelationName requires a non-empty String, but %v was given.',
  4641. targetName
  4642. );
  4643. if (!relationName || typeof relationName !== "string")
  4644. throw new InvalidArgumentError(
  4645. 'The parameter "relationName" of HasManyResolver.includePolymorphicByRelationName requires a non-empty String, but %v was given.',
  4646. relationName
  4647. );
  4648. if (!targetRelationName || typeof targetRelationName !== "string")
  4649. throw new InvalidArgumentError(
  4650. 'The parameter "targetRelationName" of HasManyResolver.includePolymorphicByRelationName requires a non-empty String, but %v was given.',
  4651. targetRelationName
  4652. );
  4653. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  4654. throw new InvalidArgumentError(
  4655. 'The provided parameter "scope" of HasManyResolver.includePolymorphicByRelationName should be an Object, but %v was given.',
  4656. scope
  4657. );
  4658. const targetRelationDef = this.getService(
  4659. ModelDefinitionUtils
  4660. ).getRelationDefinitionByName(targetName, targetRelationName);
  4661. if (targetRelationDef.type !== RelationType.BELONGS_TO)
  4662. throw new InvalidArgumentError(
  4663. '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 was given.',
  4664. relationName,
  4665. sourceName,
  4666. targetRelationName,
  4667. targetRelationDef.type
  4668. );
  4669. if (!targetRelationDef.polymorphic)
  4670. throw new InvalidArgumentError(
  4671. 'The relation %v of the model %v is a polymorphic "hasMany" relation, so it requires the target relation %v to be a polymorphic too.',
  4672. relationName,
  4673. sourceName,
  4674. targetRelationName
  4675. );
  4676. const foreignKey = targetRelationDef.foreignKey || `${targetRelationName}Id`;
  4677. const discriminator = targetRelationDef.discriminator || `${targetRelationName}Type`;
  4678. return this.includePolymorphicTo(
  4679. entities,
  4680. sourceName,
  4681. targetName,
  4682. relationName,
  4683. foreignKey,
  4684. discriminator,
  4685. scope
  4686. );
  4687. }
  4688. };
  4689. __name(_HasManyResolver, "HasManyResolver");
  4690. HasManyResolver = _HasManyResolver;
  4691. }
  4692. });
  4693. // src/relations/belongs-to-resolver.js
  4694. var import_js_service27, _BelongsToResolver, BelongsToResolver;
  4695. var init_belongs_to_resolver = __esm({
  4696. "src/relations/belongs-to-resolver.js"() {
  4697. "use strict";
  4698. import_js_service27 = require("@e22m4u/js-service");
  4699. init_errors();
  4700. init_utils();
  4701. init_repository2();
  4702. init_definition();
  4703. _BelongsToResolver = class _BelongsToResolver extends import_js_service27.Service {
  4704. /**
  4705. * Include to.
  4706. *
  4707. * @param {object[]} entities
  4708. * @param {string} sourceName
  4709. * @param {string} targetName
  4710. * @param {string} relationName
  4711. * @param {string|undefined} foreignKey
  4712. * @param {object|undefined} scope
  4713. * @returns {Promise<void>}
  4714. */
  4715. async includeTo(entities, sourceName, targetName, relationName, foreignKey = void 0, scope = void 0) {
  4716. if (!entities || !Array.isArray(entities))
  4717. throw new InvalidArgumentError(
  4718. 'The parameter "entities" of BelongsToResolver.includeTo requires an Array of Object, but %v was given.',
  4719. entities
  4720. );
  4721. if (!sourceName || typeof sourceName !== "string")
  4722. throw new InvalidArgumentError(
  4723. 'The parameter "sourceName" of BelongsToResolver.includeTo requires a non-empty String, but %v was given.',
  4724. sourceName
  4725. );
  4726. if (!targetName || typeof targetName !== "string")
  4727. throw new InvalidArgumentError(
  4728. 'The parameter "targetName" of BelongsToResolver.includeTo requires a non-empty String, but %v was given.',
  4729. targetName
  4730. );
  4731. if (!relationName || typeof relationName !== "string")
  4732. throw new InvalidArgumentError(
  4733. 'The parameter "relationName" of BelongsToResolver.includeTo requires a non-empty String, but %v was given.',
  4734. relationName
  4735. );
  4736. if (foreignKey && typeof foreignKey !== "string")
  4737. throw new InvalidArgumentError(
  4738. 'The provided parameter "foreignKey" of BelongsToResolver.includeTo should be a String, but %v was given.',
  4739. foreignKey
  4740. );
  4741. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  4742. throw new InvalidArgumentError(
  4743. 'The provided parameter "scope" of BelongsToResolver.includeTo should be an Object, but %v was given.',
  4744. scope
  4745. );
  4746. if (foreignKey == null) foreignKey = `${relationName}Id`;
  4747. const targetIds = entities.reduce((acc, entity) => {
  4748. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  4749. throw new InvalidArgumentError(
  4750. 'The parameter "entities" of BelongsToResolver.includeTo requires an Array of Object, but %v was given.',
  4751. entity
  4752. );
  4753. const targetId = entity[foreignKey];
  4754. return targetId != null ? [...acc, targetId] : acc;
  4755. }, []);
  4756. const targetRepository = this.getService(RepositoryRegistry).getRepository(targetName);
  4757. const targetPkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  4758. targetName
  4759. );
  4760. scope = scope ? cloneDeep(scope) : {};
  4761. const filter = cloneDeep(scope);
  4762. filter.where = {
  4763. and: [
  4764. { [targetPkPropName]: { inq: targetIds } },
  4765. ...scope.where ? [scope.where] : []
  4766. ]
  4767. };
  4768. const targets = await targetRepository.find(filter);
  4769. entities.forEach((entity) => {
  4770. const target = targets.find(
  4771. (e) => e[targetPkPropName] === entity[foreignKey]
  4772. );
  4773. if (target) entity[relationName] = target;
  4774. });
  4775. }
  4776. /**
  4777. * Include polymorphic to.
  4778. *
  4779. * @param {object[]} entities
  4780. * @param {string} sourceName
  4781. * @param {string} relationName
  4782. * @param {string|undefined} foreignKey
  4783. * @param {string|undefined} discriminator
  4784. * @param {object|undefined} scope
  4785. * @returns {Promise<void>}
  4786. */
  4787. async includePolymorphicTo(entities, sourceName, relationName, foreignKey = void 0, discriminator = void 0, scope = void 0) {
  4788. if (!entities || !Array.isArray(entities))
  4789. throw new InvalidArgumentError(
  4790. 'The parameter "entities" of BelongsToResolver.includePolymorphicTo requires an Array of Object, but %v was given.',
  4791. entities
  4792. );
  4793. if (!sourceName || typeof sourceName !== "string")
  4794. throw new InvalidArgumentError(
  4795. 'The parameter "sourceName" of BelongsToResolver.includePolymorphicTo requires a non-empty String, but %v was given.',
  4796. sourceName
  4797. );
  4798. if (!relationName || typeof relationName !== "string")
  4799. throw new InvalidArgumentError(
  4800. 'The parameter "relationName" of BelongsToResolver.includePolymorphicTo requires a non-empty String, but %v was given.',
  4801. relationName
  4802. );
  4803. if (foreignKey && typeof foreignKey !== "string")
  4804. throw new InvalidArgumentError(
  4805. 'The provided parameter "foreignKey" of BelongsToResolver.includePolymorphicTo should be a String, but %v was given.',
  4806. foreignKey
  4807. );
  4808. if (discriminator && typeof discriminator !== "string")
  4809. throw new InvalidArgumentError(
  4810. 'The provided parameter "discriminator" of BelongsToResolver.includePolymorphicTo should be a String, but %v was given.',
  4811. discriminator
  4812. );
  4813. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  4814. throw new InvalidArgumentError(
  4815. 'The provided parameter "scope" of BelongsToResolver.includePolymorphicTo should be an Object, but %v was given.',
  4816. scope
  4817. );
  4818. if (foreignKey == null) {
  4819. const singularRelationName = singularize(relationName);
  4820. foreignKey = `${singularRelationName}Id`;
  4821. }
  4822. if (discriminator == null) {
  4823. const singularRelationName = singularize(relationName);
  4824. discriminator = `${singularRelationName}Type`;
  4825. }
  4826. const targetIdsByTargetName = {};
  4827. entities.forEach((entity) => {
  4828. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  4829. throw new InvalidArgumentError(
  4830. 'The parameter "entities" of BelongsToResolver.includePolymorphicTo requires an Array of Object, but %v was given.',
  4831. entity
  4832. );
  4833. const targetId = entity[foreignKey];
  4834. const targetName = entity[discriminator];
  4835. if (targetId == null || targetName == null) return;
  4836. if (targetIdsByTargetName[targetName] == null)
  4837. targetIdsByTargetName[targetName] = [];
  4838. if (!targetIdsByTargetName[targetName].includes(targetId))
  4839. targetIdsByTargetName[targetName].push(targetId);
  4840. });
  4841. const promises = [];
  4842. const targetNames = Object.keys(targetIdsByTargetName);
  4843. scope = scope ? cloneDeep(scope) : {};
  4844. const targetEntitiesByTargetNames = {};
  4845. targetNames.forEach((targetName) => {
  4846. let targetRepository;
  4847. try {
  4848. targetRepository = this.getService(RepositoryRegistry).getRepository(targetName);
  4849. } catch (error) {
  4850. if (error instanceof InvalidArgumentError) {
  4851. if (error.message === `The model "${targetName}" is not defined.` || error.message === `The model "${targetName}" does not have a specified datasource.`) {
  4852. return;
  4853. }
  4854. } else {
  4855. throw error;
  4856. }
  4857. }
  4858. const targetPkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  4859. targetName
  4860. );
  4861. const targetFilter = cloneDeep(scope);
  4862. const targetIds = targetIdsByTargetName[targetName];
  4863. targetFilter.where = {
  4864. and: [
  4865. { [targetPkPropName]: { inq: targetIds } },
  4866. ...scope.where ? [scope.where] : []
  4867. ]
  4868. };
  4869. const promise = targetRepository.find(targetFilter).then((result) => {
  4870. var _a;
  4871. targetEntitiesByTargetNames[targetName] = [
  4872. ...(_a = targetEntitiesByTargetNames[targetName]) != null ? _a : [],
  4873. ...result
  4874. ];
  4875. });
  4876. promises.push(promise);
  4877. });
  4878. await Promise.all(promises);
  4879. entities.forEach((entity) => {
  4880. var _a;
  4881. const targetId = entity[foreignKey];
  4882. const targetName = entity[discriminator];
  4883. if (targetId == null || targetName == null || targetEntitiesByTargetNames[targetName] == null) {
  4884. return;
  4885. }
  4886. const targetEntities = (_a = targetEntitiesByTargetNames[targetName]) != null ? _a : [];
  4887. const targetPkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  4888. targetName
  4889. );
  4890. const target = targetEntities.find((e) => e[targetPkPropName] === targetId);
  4891. if (target) entity[relationName] = target;
  4892. });
  4893. }
  4894. };
  4895. __name(_BelongsToResolver, "BelongsToResolver");
  4896. BelongsToResolver = _BelongsToResolver;
  4897. }
  4898. });
  4899. // src/relations/references-many-resolver.js
  4900. var import_js_service28, _ReferencesManyResolver, ReferencesManyResolver;
  4901. var init_references_many_resolver = __esm({
  4902. "src/relations/references-many-resolver.js"() {
  4903. "use strict";
  4904. import_js_service28 = require("@e22m4u/js-service");
  4905. init_errors();
  4906. init_utils();
  4907. init_repository2();
  4908. init_definition();
  4909. _ReferencesManyResolver = class _ReferencesManyResolver extends import_js_service28.Service {
  4910. /**
  4911. * Include to.
  4912. *
  4913. * @param {object[]} entities
  4914. * @param {string} sourceName
  4915. * @param {string} targetName
  4916. * @param {string} relationName
  4917. * @param {string|undefined} foreignKey
  4918. * @param {object|undefined} scope
  4919. * @returns {Promise<void>}
  4920. */
  4921. async includeTo(entities, sourceName, targetName, relationName, foreignKey = void 0, scope = void 0) {
  4922. if (!entities || !Array.isArray(entities))
  4923. throw new InvalidArgumentError(
  4924. 'The parameter "entities" of ReferencesManyResolver.includeTo requires an Array of Object, but %v was given.',
  4925. entities
  4926. );
  4927. if (!sourceName || typeof sourceName !== "string")
  4928. throw new InvalidArgumentError(
  4929. 'The parameter "sourceName" of ReferencesManyResolver.includeTo requires a non-empty String, but %v was given.',
  4930. sourceName
  4931. );
  4932. if (!targetName || typeof targetName !== "string")
  4933. throw new InvalidArgumentError(
  4934. 'The parameter "targetName" of ReferencesManyResolver.includeTo requires a non-empty String, but %v was given.',
  4935. targetName
  4936. );
  4937. if (!relationName || typeof relationName !== "string")
  4938. throw new InvalidArgumentError(
  4939. 'The parameter "relationName" of ReferencesManyResolver.includeTo requires a non-empty String, but %v was given.',
  4940. relationName
  4941. );
  4942. if (foreignKey && typeof foreignKey !== "string")
  4943. throw new InvalidArgumentError(
  4944. 'The provided parameter "foreignKey" of ReferencesManyResolver.includeTo should be a String, but %v was given.',
  4945. foreignKey
  4946. );
  4947. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  4948. throw new InvalidArgumentError(
  4949. 'The provided parameter "scope" of ReferencesManyResolver.includeTo should be an Object, but %v was given.',
  4950. scope
  4951. );
  4952. if (foreignKey == null) {
  4953. const singularRelationName = singularize(relationName);
  4954. foreignKey = `${singularRelationName}Ids`;
  4955. }
  4956. const targetIds = entities.reduce((acc, entity) => {
  4957. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  4958. throw new InvalidArgumentError(
  4959. 'The parameter "entities" of ReferencesManyResolver.includeTo requires an Array of Object, but %v was given.',
  4960. entity
  4961. );
  4962. const ids = entity[foreignKey];
  4963. if (Array.isArray(ids))
  4964. ids.forEach((id) => {
  4965. if (id == null || acc.includes(id)) return;
  4966. acc.push(id);
  4967. });
  4968. return acc;
  4969. }, []);
  4970. const targetRepository = this.getService(RepositoryRegistry).getRepository(targetName);
  4971. const targetPkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  4972. targetName
  4973. );
  4974. scope = scope ? cloneDeep(scope) : {};
  4975. const filter = cloneDeep(scope);
  4976. filter.where = {
  4977. and: [
  4978. { [targetPkPropName]: { inq: targetIds } },
  4979. ...scope.where ? [scope.where] : []
  4980. ]
  4981. };
  4982. const targets = await targetRepository.find(filter);
  4983. entities.forEach((entity) => {
  4984. const ids = entity[foreignKey];
  4985. entity[relationName] = [];
  4986. if (Array.isArray(ids))
  4987. targets.forEach((target) => {
  4988. const targetId = target[targetPkPropName];
  4989. if (ids.includes(targetId)) entity[relationName].push(target);
  4990. });
  4991. });
  4992. }
  4993. };
  4994. __name(_ReferencesManyResolver, "ReferencesManyResolver");
  4995. ReferencesManyResolver = _ReferencesManyResolver;
  4996. }
  4997. });
  4998. // src/relations/index.js
  4999. var init_relations2 = __esm({
  5000. "src/relations/index.js"() {
  5001. "use strict";
  5002. init_has_one_resolver();
  5003. init_has_many_resolver();
  5004. init_belongs_to_resolver();
  5005. init_references_many_resolver();
  5006. }
  5007. });
  5008. // src/filter/include-clause-tool.js
  5009. var import_js_service29, _IncludeClauseTool, IncludeClauseTool;
  5010. var init_include_clause_tool = __esm({
  5011. "src/filter/include-clause-tool.js"() {
  5012. "use strict";
  5013. import_js_service29 = require("@e22m4u/js-service");
  5014. init_where_clause_tool();
  5015. init_order_clause_tool();
  5016. init_slice_clause_tool();
  5017. init_errors();
  5018. init_fields_clause_tool();
  5019. init_definition();
  5020. init_relations2();
  5021. _IncludeClauseTool = class _IncludeClauseTool extends import_js_service29.Service {
  5022. /**
  5023. * Include to.
  5024. *
  5025. * @param {object[]} entities
  5026. * @param {string} modelName
  5027. * @param {IncludeClause|undefined} clause
  5028. * @returns {Promise<void>}
  5029. */
  5030. async includeTo(entities, modelName, clause) {
  5031. clause = _IncludeClauseTool.normalizeIncludeClause(clause);
  5032. const promises = [];
  5033. clause.forEach((inclusion) => {
  5034. const relDef = this.getService(
  5035. ModelDefinitionUtils
  5036. ).getRelationDefinitionByName(modelName, inclusion.relation);
  5037. switch (relDef.type) {
  5038. // BELONGS_TO
  5039. case RelationType.BELONGS_TO:
  5040. if (relDef.polymorphic) {
  5041. promises.push(
  5042. this.getService(BelongsToResolver).includePolymorphicTo(
  5043. entities,
  5044. modelName,
  5045. inclusion.relation,
  5046. relDef.foreignKey,
  5047. relDef.discriminator,
  5048. inclusion.scope
  5049. )
  5050. );
  5051. } else {
  5052. promises.push(
  5053. this.getService(BelongsToResolver).includeTo(
  5054. entities,
  5055. modelName,
  5056. relDef.model,
  5057. inclusion.relation,
  5058. relDef.foreignKey,
  5059. inclusion.scope
  5060. )
  5061. );
  5062. }
  5063. break;
  5064. // HAS_ONE
  5065. case RelationType.HAS_ONE:
  5066. if (relDef.polymorphic && typeof relDef.polymorphic === "string") {
  5067. promises.push(
  5068. this.getService(HasOneResolver).includePolymorphicByRelationName(
  5069. entities,
  5070. modelName,
  5071. relDef.model,
  5072. inclusion.relation,
  5073. relDef.polymorphic,
  5074. inclusion.scope
  5075. )
  5076. );
  5077. } else if (relDef.polymorphic) {
  5078. promises.push(
  5079. this.getService(HasOneResolver).includePolymorphicTo(
  5080. entities,
  5081. modelName,
  5082. relDef.model,
  5083. inclusion.relation,
  5084. relDef.foreignKey,
  5085. relDef.discriminator,
  5086. inclusion.scope
  5087. )
  5088. );
  5089. } else {
  5090. promises.push(
  5091. this.getService(HasOneResolver).includeTo(
  5092. entities,
  5093. modelName,
  5094. relDef.model,
  5095. inclusion.relation,
  5096. relDef.foreignKey,
  5097. inclusion.scope
  5098. )
  5099. );
  5100. }
  5101. break;
  5102. // HAS_MANY
  5103. case RelationType.HAS_MANY:
  5104. if (relDef.polymorphic && typeof relDef.polymorphic === "string") {
  5105. promises.push(
  5106. this.getService(HasManyResolver).includePolymorphicByRelationName(
  5107. entities,
  5108. modelName,
  5109. relDef.model,
  5110. inclusion.relation,
  5111. relDef.polymorphic,
  5112. inclusion.scope
  5113. )
  5114. );
  5115. } else if (relDef.polymorphic) {
  5116. promises.push(
  5117. this.getService(HasManyResolver).includePolymorphicTo(
  5118. entities,
  5119. modelName,
  5120. relDef.model,
  5121. inclusion.relation,
  5122. relDef.foreignKey,
  5123. relDef.discriminator,
  5124. inclusion.scope
  5125. )
  5126. );
  5127. } else {
  5128. promises.push(
  5129. this.getService(HasManyResolver).includeTo(
  5130. entities,
  5131. modelName,
  5132. relDef.model,
  5133. inclusion.relation,
  5134. relDef.foreignKey,
  5135. inclusion.scope
  5136. )
  5137. );
  5138. }
  5139. break;
  5140. case RelationType.REFERENCES_MANY:
  5141. promises.push(
  5142. this.getService(ReferencesManyResolver).includeTo(
  5143. entities,
  5144. modelName,
  5145. relDef.model,
  5146. inclusion.relation,
  5147. relDef.foreignKey,
  5148. inclusion.scope
  5149. )
  5150. );
  5151. break;
  5152. default:
  5153. throw new InvalidArgumentError(
  5154. "The relation type %v does not have an inclusion resolver.",
  5155. relDef.type
  5156. );
  5157. }
  5158. });
  5159. await Promise.all(promises);
  5160. }
  5161. /**
  5162. * Validate include clause.
  5163. *
  5164. * @param {IncludeClause|undefined} clause
  5165. */
  5166. static validateIncludeClause(clause) {
  5167. if (clause == null) {
  5168. } else if (clause && typeof clause === "string") {
  5169. } else if (Array.isArray(clause)) {
  5170. const relNames = [];
  5171. clause.flat(Infinity).forEach((el) => {
  5172. this.validateIncludeClause(el);
  5173. if (typeof el === "string") {
  5174. relNames.push(el);
  5175. } else if (typeof el === "object") {
  5176. Object.keys(el).forEach((key) => {
  5177. if (Object.prototype.hasOwnProperty.call(el, key))
  5178. relNames.push(key);
  5179. });
  5180. }
  5181. });
  5182. const duplicateNames = relNames.filter(
  5183. (name, i) => relNames.indexOf(name) !== i
  5184. );
  5185. if (duplicateNames.length)
  5186. throw new InvalidArgumentError(
  5187. 'The provided option "include" has duplicates of %v.',
  5188. duplicateNames[0]
  5189. );
  5190. } else if (typeof clause === "object") {
  5191. if ("relation" in clause) {
  5192. if (!clause.relation || typeof clause.relation !== "string")
  5193. throw new InvalidArgumentError(
  5194. 'The provided option "relation" should be a non-empty String, but %v was given.',
  5195. clause.relation
  5196. );
  5197. if ("scope" in clause && clause) this.validateScopeClause(clause.scope);
  5198. } else {
  5199. Object.keys(clause).forEach((key) => {
  5200. if (!Object.prototype.hasOwnProperty.call(clause, key)) return;
  5201. this.validateIncludeClause(key);
  5202. this.validateIncludeClause(clause[key]);
  5203. });
  5204. }
  5205. } else {
  5206. throw new InvalidArgumentError(
  5207. 'The provided option "include" should have a non-empty String, an Object or an Array, but %v was given.',
  5208. clause
  5209. );
  5210. }
  5211. }
  5212. /**
  5213. * Validate scope clause.
  5214. *
  5215. * @param {object|undefined} clause
  5216. */
  5217. static validateScopeClause(clause) {
  5218. if (clause == null) return;
  5219. if (typeof clause !== "object" || Array.isArray(clause))
  5220. throw new InvalidArgumentError(
  5221. 'The provided option "scope" should be an Object, but %v was given.',
  5222. clause
  5223. );
  5224. if (clause.where != null) {
  5225. WhereClauseTool.validateWhereClause(clause.where);
  5226. }
  5227. if (clause.order != null) {
  5228. OrderClauseTool.validateOrderClause(clause.order);
  5229. }
  5230. if (clause.skip != null) {
  5231. SliceClauseTool.validateSkipClause(clause.skip);
  5232. }
  5233. if (clause.limit != null) {
  5234. SliceClauseTool.validateLimitClause(clause.limit);
  5235. }
  5236. if (clause.fields != null) {
  5237. FieldsClauseTool.validateFieldsClause(clause.fields);
  5238. }
  5239. if (clause.include != null) {
  5240. _IncludeClauseTool.validateIncludeClause(clause.include);
  5241. }
  5242. }
  5243. /**
  5244. * Normalize include clause.
  5245. *
  5246. * @param {IncludeClause|undefined} clause
  5247. * @returns {object[]}
  5248. */
  5249. static normalizeIncludeClause(clause) {
  5250. let result = [];
  5251. if (clause == null) {
  5252. return result;
  5253. } else if (clause && typeof clause === "string") {
  5254. result.push({ relation: clause });
  5255. } else if (Array.isArray(clause)) {
  5256. clause.flat(Infinity).forEach((el) => {
  5257. el = this.normalizeIncludeClause(el);
  5258. result = [...result, ...el];
  5259. });
  5260. const relNames = result.map((v) => v.relation);
  5261. const duplicateNames = relNames.filter(
  5262. (name, i) => relNames.indexOf(name) !== i
  5263. );
  5264. if (duplicateNames.length)
  5265. throw new InvalidArgumentError(
  5266. 'The provided option "include" has duplicates of %v.',
  5267. duplicateNames[0]
  5268. );
  5269. } else if (typeof clause === "object") {
  5270. if ("relation" in clause) {
  5271. if (!clause.relation || typeof clause.relation !== "string")
  5272. throw new InvalidArgumentError(
  5273. 'The provided option "relation" should be a non-empty String, but %v was given.',
  5274. clause.relation
  5275. );
  5276. const normalized = { relation: clause.relation };
  5277. const scope = this.normalizeScopeClause(clause.scope);
  5278. if (scope) normalized.scope = scope;
  5279. result.push(normalized);
  5280. } else {
  5281. Object.keys(clause).forEach((key) => {
  5282. if (!Object.prototype.hasOwnProperty.call(clause, key)) return;
  5283. this.validateIncludeClause(key);
  5284. const normalized = { relation: key };
  5285. const include = this.normalizeIncludeClause(clause[key]);
  5286. if (include.length) normalized.scope = { include };
  5287. result.push(normalized);
  5288. });
  5289. }
  5290. } else {
  5291. throw new InvalidArgumentError(
  5292. 'The provided option "include" should have a non-empty String, an Object or an Array, but %v was given.',
  5293. clause
  5294. );
  5295. }
  5296. return result;
  5297. }
  5298. /**
  5299. * Normalize scope clause.
  5300. *
  5301. * @param {object|undefined} clause
  5302. * @returns {object|undefined}
  5303. */
  5304. static normalizeScopeClause(clause) {
  5305. if (clause == null) return;
  5306. if (typeof clause !== "object" || Array.isArray(clause))
  5307. throw new InvalidArgumentError(
  5308. 'The provided option "scope" should be an Object, but %v was given.',
  5309. clause
  5310. );
  5311. const result = {};
  5312. if (clause.where != null) {
  5313. WhereClauseTool.validateWhereClause(clause.where);
  5314. result.where = clause.where;
  5315. }
  5316. if (clause.order != null) {
  5317. OrderClauseTool.validateOrderClause(clause.order);
  5318. result.order = clause.order;
  5319. }
  5320. if (clause.skip != null) {
  5321. SliceClauseTool.validateSkipClause(clause.skip);
  5322. result.skip = clause.skip;
  5323. }
  5324. if (clause.limit != null) {
  5325. SliceClauseTool.validateLimitClause(clause.limit);
  5326. result.limit = clause.limit;
  5327. }
  5328. if (clause.fields != null) {
  5329. FieldsClauseTool.validateFieldsClause(clause.fields);
  5330. result.fields = clause.fields;
  5331. }
  5332. if (clause.include != null) {
  5333. result.include = this.normalizeIncludeClause(clause.include);
  5334. }
  5335. if (Object.keys(result).length) return result;
  5336. return void 0;
  5337. }
  5338. };
  5339. __name(_IncludeClauseTool, "IncludeClauseTool");
  5340. IncludeClauseTool = _IncludeClauseTool;
  5341. }
  5342. });
  5343. // src/filter/index.js
  5344. var init_filter = __esm({
  5345. "src/filter/index.js"() {
  5346. "use strict";
  5347. init_slice_clause_tool();
  5348. init_order_clause_tool();
  5349. init_where_clause_tool();
  5350. init_fields_clause_tool();
  5351. init_include_clause_tool();
  5352. init_operator_clause_tool();
  5353. }
  5354. });
  5355. // src/index.js
  5356. var index_exports = {};
  5357. __export(index_exports, {
  5358. ADAPTER_CLASS_NAME: () => ADAPTER_CLASS_NAME,
  5359. Adapter: () => Adapter,
  5360. AdapterLoader: () => AdapterLoader,
  5361. AdapterRegistry: () => AdapterRegistry,
  5362. BelongsToResolver: () => BelongsToResolver,
  5363. DEFAULT_PRIMARY_KEY_PROPERTY_NAME: () => DEFAULT_PRIMARY_KEY_PROPERTY_NAME,
  5364. DataType: () => DataType,
  5365. DatabaseSchema: () => DatabaseSchema,
  5366. DatasourceDefinitionValidator: () => DatasourceDefinitionValidator,
  5367. DefinitionRegistry: () => DefinitionRegistry,
  5368. FieldsClauseTool: () => FieldsClauseTool,
  5369. HasManyResolver: () => HasManyResolver,
  5370. HasOneResolver: () => HasOneResolver,
  5371. IncludeClauseTool: () => IncludeClauseTool,
  5372. InvalidArgumentError: () => InvalidArgumentError,
  5373. InvalidOperatorValueError: () => InvalidOperatorValueError,
  5374. ModelDataSanitizer: () => ModelDataSanitizer,
  5375. ModelDefinitionUtils: () => ModelDefinitionUtils,
  5376. ModelDefinitionValidator: () => ModelDefinitionValidator,
  5377. NotImplementedError: () => NotImplementedError,
  5378. OperatorClauseTool: () => OperatorClauseTool,
  5379. OrderClauseTool: () => OrderClauseTool,
  5380. PrimaryKeysDefinitionValidator: () => PrimaryKeysDefinitionValidator,
  5381. PropertiesDefinitionValidator: () => PropertiesDefinitionValidator,
  5382. PropertyUniqueness: () => PropertyUniqueness,
  5383. PropertyUniquenessValidator: () => PropertyUniquenessValidator,
  5384. ReferencesManyResolver: () => ReferencesManyResolver,
  5385. RelationType: () => RelationType,
  5386. RelationsDefinitionValidator: () => RelationsDefinitionValidator,
  5387. Repository: () => Repository,
  5388. RepositoryRegistry: () => RepositoryRegistry,
  5389. SliceClauseTool: () => SliceClauseTool,
  5390. WhereClauseTool: () => WhereClauseTool,
  5391. capitalize: () => capitalize,
  5392. cloneDeep: () => cloneDeep,
  5393. excludeObjectKeys: () => excludeObjectKeys,
  5394. getValueByPath: () => getValueByPath,
  5395. isDeepEqual: () => isDeepEqual,
  5396. isPlainObject: () => isPlainObject,
  5397. isPromise: () => isPromise,
  5398. likeToRegexp: () => likeToRegexp,
  5399. modelNameToModelKey: () => modelNameToModelKey,
  5400. selectObjectKeys: () => selectObjectKeys,
  5401. singularize: () => singularize,
  5402. stringToRegexp: () => stringToRegexp
  5403. });
  5404. module.exports = __toCommonJS(index_exports);
  5405. init_utils();
  5406. init_errors();
  5407. init_filter();
  5408. init_adapter2();
  5409. // src/database-schema.js
  5410. var import_js_service30 = require("@e22m4u/js-service");
  5411. init_definition();
  5412. init_repository2();
  5413. var _DatabaseSchema = class _DatabaseSchema extends import_js_service30.Service {
  5414. /**
  5415. * Define datasource.
  5416. *
  5417. * @param {object} datasourceDef
  5418. * @returns {this}
  5419. */
  5420. defineDatasource(datasourceDef) {
  5421. this.getService(DefinitionRegistry).addDatasource(datasourceDef);
  5422. return this;
  5423. }
  5424. /**
  5425. * Define model.
  5426. *
  5427. * @param {object} modelDef
  5428. * @returns {this}
  5429. */
  5430. defineModel(modelDef) {
  5431. this.getService(DefinitionRegistry).addModel(modelDef);
  5432. return this;
  5433. }
  5434. /**
  5435. * Get repository.
  5436. *
  5437. * @param {string} modelName
  5438. * @returns {Repository}
  5439. */
  5440. getRepository(modelName) {
  5441. return this.getService(RepositoryRegistry).getRepository(modelName);
  5442. }
  5443. };
  5444. __name(_DatabaseSchema, "DatabaseSchema");
  5445. var DatabaseSchema = _DatabaseSchema;
  5446. // src/index.js
  5447. init_relations2();
  5448. init_definition();
  5449. init_repository2();
  5450. // Annotate the CommonJS export names for ESM import in node:
  5451. 0 && (module.exports = {
  5452. ADAPTER_CLASS_NAME,
  5453. Adapter,
  5454. AdapterLoader,
  5455. AdapterRegistry,
  5456. BelongsToResolver,
  5457. DEFAULT_PRIMARY_KEY_PROPERTY_NAME,
  5458. DataType,
  5459. DatabaseSchema,
  5460. DatasourceDefinitionValidator,
  5461. DefinitionRegistry,
  5462. FieldsClauseTool,
  5463. HasManyResolver,
  5464. HasOneResolver,
  5465. IncludeClauseTool,
  5466. InvalidArgumentError,
  5467. InvalidOperatorValueError,
  5468. ModelDataSanitizer,
  5469. ModelDefinitionUtils,
  5470. ModelDefinitionValidator,
  5471. NotImplementedError,
  5472. OperatorClauseTool,
  5473. OrderClauseTool,
  5474. PrimaryKeysDefinitionValidator,
  5475. PropertiesDefinitionValidator,
  5476. PropertyUniqueness,
  5477. PropertyUniquenessValidator,
  5478. ReferencesManyResolver,
  5479. RelationType,
  5480. RelationsDefinitionValidator,
  5481. Repository,
  5482. RepositoryRegistry,
  5483. SliceClauseTool,
  5484. WhereClauseTool,
  5485. capitalize,
  5486. cloneDeep,
  5487. excludeObjectKeys,
  5488. getValueByPath,
  5489. isDeepEqual,
  5490. isPlainObject,
  5491. isPromise,
  5492. likeToRegexp,
  5493. modelNameToModelKey,
  5494. selectObjectKeys,
  5495. singularize,
  5496. stringToRegexp
  5497. });