index.cjs 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795
  1. var __defProp = Object.defineProperty;
  2. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  3. var __getOwnPropNames = Object.getOwnPropertyNames;
  4. var __hasOwnProp = Object.prototype.hasOwnProperty;
  5. var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  6. var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
  7. var __export = (target, all) => {
  8. for (var name in all)
  9. __defProp(target, name, { get: all[name], enumerable: true });
  10. };
  11. var __copyProps = (to, from, except, desc) => {
  12. if (from && typeof from === "object" || typeof from === "function") {
  13. for (let key of __getOwnPropNames(from))
  14. if (!__hasOwnProp.call(to, key) && key !== except)
  15. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  16. }
  17. return to;
  18. };
  19. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  20. var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  21. // src/index.js
  22. var index_exports = {};
  23. __export(index_exports, {
  24. MongodbAdapter: () => MongodbAdapter
  25. });
  26. module.exports = __toCommonJS(index_exports);
  27. // src/mongodb-adapter.js
  28. var import_mongodb2 = require("mongodb");
  29. var import_mongodb3 = require("mongodb");
  30. // src/utils/pluralize.js
  31. var singularExceptions = [
  32. /access$/i,
  33. /address$/i,
  34. /alias$/i,
  35. /bonus$/i,
  36. /boss$/i,
  37. /bus$/i,
  38. /business$/i,
  39. /canvas$/i,
  40. /class$/i,
  41. /cross$/i,
  42. /dress$/i,
  43. /focus$/i,
  44. /gas$/i,
  45. /glass$/i,
  46. /kiss$/i,
  47. /lens$/i,
  48. /loss$/i,
  49. /pass$/i,
  50. /plus$/i,
  51. /process$/i,
  52. /status$/i,
  53. /success$/i,
  54. /virus$/i
  55. ];
  56. function pluralize(input) {
  57. if (!input || typeof input !== "string") {
  58. return input;
  59. }
  60. if (/s$/i.test(input) && !singularExceptions.some((re) => re.test(input))) {
  61. return input;
  62. }
  63. const lastChar = input.slice(-1);
  64. const isLastCharUpper = lastChar === lastChar.toUpperCase() && lastChar !== lastChar.toLowerCase();
  65. if (/(s|x|z|ch|sh)$/i.test(input)) {
  66. return input + (isLastCharUpper ? "ES" : "es");
  67. }
  68. if (/[^aeiou]y$/i.test(input)) {
  69. return input.slice(0, -1) + (isLastCharUpper ? "IES" : "ies");
  70. }
  71. return input + (isLastCharUpper ? "S" : "s");
  72. }
  73. __name(pluralize, "pluralize");
  74. // src/utils/is-iso-date.js
  75. function isIsoDate(value) {
  76. if (!value) return false;
  77. if (value instanceof Date) return true;
  78. if (!/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z/.test(value)) return false;
  79. const d = new Date(value);
  80. return d instanceof Date && !isNaN(d.getTime()) && d.toISOString() === value;
  81. }
  82. __name(isIsoDate, "isIsoDate");
  83. // src/utils/is-object-id.js
  84. var import_mongodb = require("mongodb");
  85. function isObjectId(value) {
  86. if (!value) return false;
  87. if (value instanceof import_mongodb.ObjectId) return true;
  88. if (typeof value !== "string") return false;
  89. return value.match(/^[a-fA-F0-9]{24}$/) != null;
  90. }
  91. __name(isObjectId, "isObjectId");
  92. // src/utils/to-camel-case.js
  93. function toCamelCase(input) {
  94. if (!input) return "";
  95. const spacedString = String(input).replace(/([-_])/g, " ").replace(/([a-z])([A-Z])/g, "$1 $2");
  96. const intermediateCased = spacedString.toLowerCase().replace(/\s(.)/g, ($1) => $1.toUpperCase()).replace(/\s/g, "");
  97. if (!intermediateCased) return "";
  98. return intermediateCased.charAt(0).toLowerCase() + intermediateCased.slice(1);
  99. }
  100. __name(toCamelCase, "toCamelCase");
  101. // src/utils/create-mongodb-url.js
  102. var import_js_repository = require("@e22m4u/js-repository");
  103. function createMongodbUrl(options = {}) {
  104. if (!options || typeof options !== "object" || Array.isArray(options))
  105. throw new import_js_repository.InvalidArgumentError(
  106. 'The first argument of "createMongodbUrl" must be an Object, but %v given.',
  107. options
  108. );
  109. if (options.protocol && typeof options.protocol !== "string")
  110. throw new import_js_repository.InvalidArgumentError(
  111. 'MongoDB option "protocol" must be a String, but %v given.',
  112. options.protocol
  113. );
  114. if (options.hostname && typeof options.hostname !== "string")
  115. throw new import_js_repository.InvalidArgumentError(
  116. 'MongoDB option "hostname" must be a String, but %v given.',
  117. options.hostname
  118. );
  119. if (options.host && typeof options.host !== "string")
  120. throw new import_js_repository.InvalidArgumentError(
  121. 'MongoDB option "host" must be a String, but %v given.',
  122. options.host
  123. );
  124. if (options.port && typeof options.port !== "number" && typeof options.port !== "string") {
  125. throw new import_js_repository.InvalidArgumentError(
  126. 'MongoDB option "port" must be a Number or a String, but %v given.',
  127. options.port
  128. );
  129. }
  130. if (options.database && typeof options.database !== "string")
  131. throw new import_js_repository.InvalidArgumentError(
  132. 'MongoDB option "database" must be a String, but %v given.',
  133. options.database
  134. );
  135. if (options.db && typeof options.db !== "string")
  136. throw new import_js_repository.InvalidArgumentError(
  137. 'MongoDB option "db" must be a String, but %v given.',
  138. options.db
  139. );
  140. if (options.username && typeof options.username !== "string")
  141. throw new import_js_repository.InvalidArgumentError(
  142. 'MongoDB option "username" must be a String, but %v given.',
  143. options.username
  144. );
  145. if (options.password && typeof options.password !== "string" && typeof options.password !== "number") {
  146. throw new import_js_repository.InvalidArgumentError(
  147. 'MongoDB option "password" must be a String or a Number, but %v given.',
  148. options.password
  149. );
  150. }
  151. if (options.pass && typeof options.pass !== "string" && typeof options.pass !== "number") {
  152. throw new import_js_repository.InvalidArgumentError(
  153. 'MongoDB option "pass" must be a String or a Number, but %v given.',
  154. options.pass
  155. );
  156. }
  157. const protocol = options.protocol || "mongodb";
  158. const hostname = options.hostname || options.host || "127.0.0.1";
  159. const port = options.port || 27017;
  160. const database = options.database || options.db || "database";
  161. const username = options.username || options.user;
  162. const password = options.password || options.pass || void 0;
  163. let portUrl = "";
  164. if (protocol !== "mongodb+srv") {
  165. portUrl = ":" + port;
  166. }
  167. if (username && password) {
  168. return `${protocol}://${username}:${password}@${hostname}${portUrl}/${database}`;
  169. } else {
  170. return `${protocol}://${hostname}${portUrl}/${database}`;
  171. }
  172. }
  173. __name(createMongodbUrl, "createMongodbUrl");
  174. // src/utils/transform-values-deep.js
  175. var import_js_repository2 = require("@e22m4u/js-repository");
  176. function transformValuesDeep(value, transformer) {
  177. if (!transformer || typeof transformer !== "function")
  178. throw new import_js_repository2.InvalidArgumentError(
  179. 'The second argument of "transformValuesDeep" must be a Function, but %v given.',
  180. transformer
  181. );
  182. if (Array.isArray(value)) {
  183. value.forEach((v, i) => value[i] = transformValuesDeep(v, transformer));
  184. return value;
  185. } else if (value && typeof value === "object") {
  186. if (!value.constructor || value.constructor && value.constructor.name === "Object") {
  187. Object.keys(value).forEach((key) => {
  188. if (Object.prototype.hasOwnProperty.call(value, key))
  189. value[key] = transformValuesDeep(value[key], transformer);
  190. });
  191. return value;
  192. } else {
  193. return transformer(value);
  194. }
  195. } else {
  196. return transformer(value);
  197. }
  198. }
  199. __name(transformValuesDeep, "transformValuesDeep");
  200. // src/utils/model-name-to-collection-name.js
  201. function modelNameToCollectionName(modelName) {
  202. const ccName = toCamelCase(modelName);
  203. const woModel = ccName.replace(/Model$/i, "");
  204. if (woModel.length <= 2) {
  205. return pluralize(ccName);
  206. }
  207. return pluralize(woModel);
  208. }
  209. __name(modelNameToCollectionName, "modelNameToCollectionName");
  210. // src/mongodb-adapter.js
  211. var import_js_repository3 = require("@e22m4u/js-repository");
  212. var import_js_repository4 = require("@e22m4u/js-repository");
  213. var import_js_repository5 = require("@e22m4u/js-repository");
  214. // node_modules/@e22m4u/js-service/src/errors/invalid-argument-error.js
  215. var import_js_format = require("@e22m4u/js-format");
  216. var _InvalidArgumentError = class _InvalidArgumentError extends import_js_format.Errorf {
  217. };
  218. __name(_InvalidArgumentError, "InvalidArgumentError");
  219. var InvalidArgumentError3 = _InvalidArgumentError;
  220. // node_modules/@e22m4u/js-service/src/service-container.js
  221. var SERVICE_CONTAINER_CLASS_NAME = "ServiceContainer";
  222. var _ServiceContainer = class _ServiceContainer {
  223. /**
  224. * Services map.
  225. *
  226. * @type {Map<any, any>}
  227. * @private
  228. */
  229. _services = /* @__PURE__ */ new Map();
  230. /**
  231. * Parent container.
  232. *
  233. * @type {ServiceContainer}
  234. * @private
  235. */
  236. _parent;
  237. /**
  238. * Constructor.
  239. *
  240. * @param {ServiceContainer|undefined} parent
  241. */
  242. constructor(parent = void 0) {
  243. if (parent != null) {
  244. if (!(parent instanceof _ServiceContainer))
  245. throw new InvalidArgumentError3(
  246. 'The provided parameter "parent" of ServicesContainer.constructor must be an instance ServiceContainer, but %v given.',
  247. parent
  248. );
  249. this._parent = parent;
  250. }
  251. }
  252. /**
  253. * Получить родительский сервис-контейнер или выбросить ошибку.
  254. *
  255. * @returns {ServiceContainer}
  256. */
  257. getParent() {
  258. if (!this._parent)
  259. throw new InvalidArgumentError3("The service container has no parent.");
  260. return this._parent;
  261. }
  262. /**
  263. * Проверить наличие родительского сервис-контейнера.
  264. *
  265. * @returns {boolean}
  266. */
  267. hasParent() {
  268. return Boolean(this._parent);
  269. }
  270. /**
  271. * Получить существующий или новый экземпляр.
  272. *
  273. * @param {*} ctor
  274. * @param {*} args
  275. * @returns {*}
  276. */
  277. get(ctor, ...args) {
  278. if (!ctor || typeof ctor !== "function")
  279. throw new InvalidArgumentError3(
  280. "The first argument of ServicesContainer.get must be a class constructor, but %v given.",
  281. ctor
  282. );
  283. if (!this._services.has(ctor) && this._parent && this._parent.has(ctor)) {
  284. return this._parent.get(ctor);
  285. }
  286. let service = this._services.get(ctor);
  287. if (!service) {
  288. const ctors = this._services.keys();
  289. const inheritedCtor = ctors.find((v) => v.prototype instanceof ctor);
  290. if (inheritedCtor) {
  291. service = this._services.get(inheritedCtor);
  292. ctor = inheritedCtor;
  293. }
  294. }
  295. if (!service || args.length) {
  296. service = Array.isArray(ctor.kinds) && ctor.kinds.includes(SERVICE_CLASS_NAME) ? new ctor(this, ...args) : new ctor(...args);
  297. this._services.set(ctor, service);
  298. } else if (typeof service === "function") {
  299. service = service();
  300. this._services.set(ctor, service);
  301. }
  302. return service;
  303. }
  304. /**
  305. * Получить существующий или новый экземпляр,
  306. * только если конструктор зарегистрирован.
  307. *
  308. * @param {*} ctor
  309. * @param {*} args
  310. * @returns {*}
  311. */
  312. getRegistered(ctor, ...args) {
  313. if (!this.has(ctor))
  314. throw new InvalidArgumentError3(
  315. "The constructor %v is not registered.",
  316. ctor
  317. );
  318. return this.get(ctor, ...args);
  319. }
  320. /**
  321. * Проверить существование конструктора в контейнере.
  322. *
  323. * @param {*} ctor
  324. * @returns {boolean}
  325. */
  326. has(ctor) {
  327. if (this._services.has(ctor)) return true;
  328. if (this._parent) return this._parent.has(ctor);
  329. const ctors = this._services.keys();
  330. const inheritedCtor = ctors.find((v) => v.prototype instanceof ctor);
  331. if (inheritedCtor) return true;
  332. return false;
  333. }
  334. /**
  335. * Добавить конструктор в контейнер.
  336. *
  337. * @param {*} ctor
  338. * @param {*} args
  339. * @returns {this}
  340. */
  341. add(ctor, ...args) {
  342. if (!ctor || typeof ctor !== "function")
  343. throw new InvalidArgumentError3(
  344. "The first argument of ServicesContainer.add must be a class constructor, but %v given.",
  345. ctor
  346. );
  347. const factory = /* @__PURE__ */ __name(() => Array.isArray(ctor.kinds) && ctor.kinds.includes(SERVICE_CLASS_NAME) ? new ctor(this, ...args) : new ctor(...args), "factory");
  348. this._services.set(ctor, factory);
  349. return this;
  350. }
  351. /**
  352. * Добавить конструктор и создать экземпляр.
  353. *
  354. * @param {*} ctor
  355. * @param {*} args
  356. * @returns {this}
  357. */
  358. use(ctor, ...args) {
  359. if (!ctor || typeof ctor !== "function")
  360. throw new InvalidArgumentError3(
  361. "The first argument of ServicesContainer.use must be a class constructor, but %v given.",
  362. ctor
  363. );
  364. const service = Array.isArray(ctor.kinds) && ctor.kinds.includes(SERVICE_CLASS_NAME) ? new ctor(this, ...args) : new ctor(...args);
  365. this._services.set(ctor, service);
  366. return this;
  367. }
  368. /**
  369. * Добавить конструктор и связанный экземпляр.
  370. *
  371. * @param {*} ctor
  372. * @param {*} service
  373. * @returns {this}
  374. */
  375. set(ctor, service) {
  376. if (!ctor || typeof ctor !== "function")
  377. throw new InvalidArgumentError3(
  378. "The first argument of ServicesContainer.set must be a class constructor, but %v given.",
  379. ctor
  380. );
  381. if (!service || typeof service !== "object" || Array.isArray(service))
  382. throw new InvalidArgumentError3(
  383. "The second argument of ServicesContainer.set must be an Object, but %v given.",
  384. service
  385. );
  386. this._services.set(ctor, service);
  387. return this;
  388. }
  389. };
  390. __name(_ServiceContainer, "ServiceContainer");
  391. /**
  392. * Kinds.
  393. *
  394. * @type {string[]}
  395. */
  396. __publicField(_ServiceContainer, "kinds", [SERVICE_CONTAINER_CLASS_NAME]);
  397. var ServiceContainer = _ServiceContainer;
  398. // node_modules/@e22m4u/js-service/src/utils/is-service-container.js
  399. function isServiceContainer(container) {
  400. return Boolean(
  401. container && typeof container === "object" && typeof container.constructor === "function" && Array.isArray(container.constructor.kinds) && container.constructor.kinds.includes(SERVICE_CONTAINER_CLASS_NAME)
  402. );
  403. }
  404. __name(isServiceContainer, "isServiceContainer");
  405. // node_modules/@e22m4u/js-service/src/service.js
  406. var SERVICE_CLASS_NAME = "Service";
  407. var _Service = class _Service {
  408. /**
  409. * Container.
  410. *
  411. * @type {ServiceContainer}
  412. */
  413. container;
  414. /**
  415. * Constructor.
  416. *
  417. * @param {ServiceContainer|undefined} container
  418. */
  419. constructor(container = void 0) {
  420. this.container = isServiceContainer(container) ? container : new ServiceContainer();
  421. }
  422. /**
  423. * Получить существующий или новый экземпляр.
  424. *
  425. * @param {*} ctor
  426. * @param {*} args
  427. * @returns {*}
  428. */
  429. getService(ctor, ...args) {
  430. return this.container.get(ctor, ...args);
  431. }
  432. /**
  433. * Получить существующий или новый экземпляр,
  434. * только если конструктор зарегистрирован.
  435. *
  436. * @param {*} ctor
  437. * @param {*} args
  438. * @returns {*}
  439. */
  440. getRegisteredService(ctor, ...args) {
  441. return this.container.getRegistered(ctor, ...args);
  442. }
  443. /**
  444. * Проверка существования конструктора в контейнере.
  445. *
  446. * @param {*} ctor
  447. * @returns {boolean}
  448. */
  449. hasService(ctor) {
  450. return this.container.has(ctor);
  451. }
  452. /**
  453. * Добавить конструктор в контейнер.
  454. *
  455. * @param {*} ctor
  456. * @param {*} args
  457. * @returns {this}
  458. */
  459. addService(ctor, ...args) {
  460. this.container.add(ctor, ...args);
  461. return this;
  462. }
  463. /**
  464. * Добавить конструктор и создать экземпляр.
  465. *
  466. * @param {*} ctor
  467. * @param {*} args
  468. * @returns {this}
  469. */
  470. useService(ctor, ...args) {
  471. this.container.use(ctor, ...args);
  472. return this;
  473. }
  474. /**
  475. * Добавить конструктор и связанный экземпляр.
  476. *
  477. * @param {*} ctor
  478. * @param {*} service
  479. * @returns {this}
  480. */
  481. setService(ctor, service) {
  482. this.container.set(ctor, service);
  483. return this;
  484. }
  485. };
  486. __name(_Service, "Service");
  487. /**
  488. * Kinds.
  489. *
  490. * @type {string[]}
  491. */
  492. __publicField(_Service, "kinds", [SERVICE_CLASS_NAME]);
  493. var Service = _Service;
  494. // node_modules/@e22m4u/js-debug/src/utils/to-camel-case.js
  495. function toCamelCase2(input) {
  496. return input.replace(/(^\w|[A-Z]|\b\w)/g, (c) => c.toUpperCase()).replace(/\W+/g, "").replace(/(^\w)/g, (c) => c.toLowerCase());
  497. }
  498. __name(toCamelCase2, "toCamelCase");
  499. // node_modules/@e22m4u/js-debug/src/utils/is-non-array-object.js
  500. function isNonArrayObject(input) {
  501. return Boolean(input && typeof input === "object" && !Array.isArray(input));
  502. }
  503. __name(isNonArrayObject, "isNonArrayObject");
  504. // node_modules/@e22m4u/js-debug/src/utils/generate-random-hex.js
  505. function generateRandomHex(length = 4) {
  506. if (length <= 0) {
  507. return "";
  508. }
  509. const firstCharCandidates = "abcdef";
  510. const restCharCandidates = "0123456789abcdef";
  511. let result = "";
  512. const firstCharIndex = Math.floor(Math.random() * firstCharCandidates.length);
  513. result += firstCharCandidates[firstCharIndex];
  514. for (let i = 1; i < length; i++) {
  515. const randomIndex = Math.floor(Math.random() * restCharCandidates.length);
  516. result += restCharCandidates[randomIndex];
  517. }
  518. return result;
  519. }
  520. __name(generateRandomHex, "generateRandomHex");
  521. // node_modules/@e22m4u/js-debug/src/debuggable.js
  522. var _Debuggable = class _Debuggable {
  523. /**
  524. * Debug.
  525. *
  526. * @type {Function}
  527. */
  528. debug;
  529. /**
  530. * Ctor Debug.
  531. *
  532. * @type {Function}
  533. */
  534. ctorDebug;
  535. /**
  536. * Возвращает функцию-отладчик с сегментом пространства имен
  537. * указанного в параметре метода.
  538. *
  539. * @param {Function} method
  540. * @returns {Function}
  541. */
  542. getDebuggerFor(method) {
  543. return this.debug.withHash().withNs(method.name);
  544. }
  545. /**
  546. * Constructor.
  547. *
  548. * @param {object|undefined} container
  549. * @param {DebuggableOptions|undefined} options
  550. */
  551. constructor(options = void 0) {
  552. const className = toCamelCase2(this.constructor.name);
  553. options = typeof options === "object" && options || {};
  554. const namespace = options.namespace && String(options.namespace) || void 0;
  555. if (namespace) {
  556. this.debug = createDebugger(namespace, className);
  557. } else {
  558. this.debug = createDebugger(className);
  559. }
  560. const noEnvNs = Boolean(options.noEnvNs);
  561. if (noEnvNs) this.debug = this.debug.withoutEnvNs();
  562. this.ctorDebug = this.debug.withNs("constructor").withHash();
  563. this.ctorDebug(_Debuggable.INSTANTIATION_MESSAGE);
  564. }
  565. };
  566. __name(_Debuggable, "Debuggable");
  567. /**
  568. * Instantiation message;
  569. *
  570. * @type {string}
  571. */
  572. __publicField(_Debuggable, "INSTANTIATION_MESSAGE", "Instantiated.");
  573. var Debuggable = _Debuggable;
  574. // node_modules/@e22m4u/js-debug/src/create-debugger.js
  575. var import_js_format2 = require("@e22m4u/js-format");
  576. var import_js_format3 = require("@e22m4u/js-format");
  577. // node_modules/@e22m4u/js-debug/src/create-colorized-dump.js
  578. var import_util = require("util");
  579. var INSPECT_OPTIONS = {
  580. showHidden: false,
  581. depth: null,
  582. colors: true,
  583. compact: false
  584. };
  585. function createColorizedDump(value) {
  586. return (0, import_util.inspect)(value, INSPECT_OPTIONS);
  587. }
  588. __name(createColorizedDump, "createColorizedDump");
  589. // node_modules/@e22m4u/js-debug/src/create-debugger.js
  590. var AVAILABLE_COLORS = [
  591. 20,
  592. 21,
  593. 26,
  594. 27,
  595. 32,
  596. 33,
  597. 38,
  598. 39,
  599. 40,
  600. 41,
  601. 42,
  602. 43,
  603. 44,
  604. 45,
  605. 56,
  606. 57,
  607. 62,
  608. 63,
  609. 68,
  610. 69,
  611. 74,
  612. 75,
  613. 76,
  614. 77,
  615. 78,
  616. 79,
  617. 80,
  618. 81,
  619. 92,
  620. 93,
  621. 98,
  622. 99,
  623. 112,
  624. 113,
  625. 128,
  626. 129,
  627. 134,
  628. 135,
  629. 148,
  630. 149,
  631. 160,
  632. 161,
  633. 162,
  634. 163,
  635. 164,
  636. 165,
  637. 166,
  638. 167,
  639. 168,
  640. 169,
  641. 170,
  642. 171,
  643. 172,
  644. 173,
  645. 178,
  646. 179,
  647. 184,
  648. 185,
  649. 196,
  650. 197,
  651. 198,
  652. 199,
  653. 200,
  654. 201,
  655. 202,
  656. 203,
  657. 204,
  658. 205,
  659. 206,
  660. 207,
  661. 208,
  662. 209,
  663. 214,
  664. 215,
  665. 220,
  666. 221
  667. ];
  668. var DEFAULT_OFFSET_STEP_SPACES = 2;
  669. function pickColorCode(input) {
  670. if (typeof input !== "string")
  671. throw new import_js_format2.Errorf(
  672. 'The parameter "input" of the function pickColorCode must be a String, but %v given.',
  673. input
  674. );
  675. let hash = 0;
  676. for (let i = 0; i < input.length; i++) {
  677. hash = (hash << 5) - hash + input.charCodeAt(i);
  678. hash |= 0;
  679. }
  680. return AVAILABLE_COLORS[Math.abs(hash) % AVAILABLE_COLORS.length];
  681. }
  682. __name(pickColorCode, "pickColorCode");
  683. function wrapStringByColorCode(input, color) {
  684. if (typeof input !== "string")
  685. throw new import_js_format2.Errorf(
  686. 'The parameter "input" of the function wrapStringByColorCode must be a String, but %v given.',
  687. input
  688. );
  689. if (typeof color !== "number")
  690. throw new import_js_format2.Errorf(
  691. 'The parameter "color" of the function wrapStringByColorCode must be a Number, but %v given.',
  692. color
  693. );
  694. const colorCode = "\x1B[3" + (Number(color) < 8 ? color : "8;5;" + color);
  695. return `${colorCode};1m${input}\x1B[0m`;
  696. }
  697. __name(wrapStringByColorCode, "wrapStringByColorCode");
  698. function matchPattern(pattern, input) {
  699. if (typeof pattern !== "string")
  700. throw new import_js_format2.Errorf(
  701. 'The parameter "pattern" of the function matchPattern must be a String, but %v given.',
  702. pattern
  703. );
  704. if (typeof input !== "string")
  705. throw new import_js_format2.Errorf(
  706. 'The parameter "input" of the function matchPattern must be a String, but %v given.',
  707. input
  708. );
  709. const regexpStr = pattern.replace(/\*/g, ".*?");
  710. const regexp = new RegExp("^" + regexpStr + "$");
  711. return regexp.test(input);
  712. }
  713. __name(matchPattern, "matchPattern");
  714. function createDebugger(namespaceOrOptions = void 0, ...namespaceSegments) {
  715. if (namespaceOrOptions && typeof namespaceOrOptions !== "string" && !isNonArrayObject(namespaceOrOptions)) {
  716. throw new import_js_format2.Errorf(
  717. 'The parameter "namespace" of the function createDebugger must be a String or an Object, but %v given.',
  718. namespaceOrOptions
  719. );
  720. }
  721. const withCustomState = isNonArrayObject(namespaceOrOptions);
  722. const state = withCustomState ? namespaceOrOptions : {};
  723. state.envNsSegments = Array.isArray(state.envNsSegments) ? state.envNsSegments : [];
  724. state.nsSegments = Array.isArray(state.nsSegments) ? state.nsSegments : [];
  725. state.pattern = typeof state.pattern === "string" ? state.pattern : "";
  726. state.hash = typeof state.hash === "string" ? state.hash : "";
  727. state.offsetSize = typeof state.offsetSize === "number" ? state.offsetSize : 0;
  728. state.offsetStep = typeof state.offsetStep !== "string" ? " ".repeat(DEFAULT_OFFSET_STEP_SPACES) : state.offsetStep;
  729. state.delimiter = state.delimiter && typeof state.delimiter === "string" ? state.delimiter : ":";
  730. if (!withCustomState) {
  731. if (typeof process !== "undefined" && process.env && process.env["DEBUGGER_NAMESPACE"]) {
  732. state.envNsSegments.push(process.env.DEBUGGER_NAMESPACE);
  733. }
  734. if (typeof namespaceOrOptions === "string")
  735. state.nsSegments.push(namespaceOrOptions);
  736. }
  737. namespaceSegments.forEach((segment) => {
  738. if (!segment || typeof segment !== "string")
  739. throw new import_js_format2.Errorf(
  740. "Namespace segment must be a non-empty String, but %v given.",
  741. segment
  742. );
  743. state.nsSegments.push(segment);
  744. });
  745. if (typeof process !== "undefined" && process.env && process.env["DEBUG"]) {
  746. state.pattern = process.env["DEBUG"];
  747. } else if (typeof localStorage !== "undefined" && typeof localStorage.getItem("debug") === "string") {
  748. state.pattern = localStorage.getItem("debug");
  749. }
  750. const isDebuggerEnabled = /* @__PURE__ */ __name(() => {
  751. const nsStr = [...state.envNsSegments, ...state.nsSegments].join(
  752. state.delimiter
  753. );
  754. const patterns = state.pattern.split(/[\s,]+/).filter((p) => p.length > 0);
  755. if (patterns.length === 0 && state.pattern !== "*") return false;
  756. for (const singlePattern of patterns) {
  757. if (matchPattern(singlePattern, nsStr)) return true;
  758. }
  759. return false;
  760. }, "isDebuggerEnabled");
  761. const getPrefix = /* @__PURE__ */ __name(() => {
  762. let tokens = [];
  763. [...state.envNsSegments, ...state.nsSegments, state.hash].filter(Boolean).forEach((token) => {
  764. const extractedTokens = token.split(state.delimiter).filter(Boolean);
  765. tokens = [...tokens, ...extractedTokens];
  766. });
  767. let res = tokens.reduce((acc, token, index) => {
  768. const isLast = tokens.length - 1 === index;
  769. const tokenColor = pickColorCode(token);
  770. acc += wrapStringByColorCode(token, tokenColor);
  771. if (!isLast) acc += state.delimiter;
  772. return acc;
  773. }, "");
  774. if (state.offsetSize > 0) res += state.offsetStep.repeat(state.offsetSize);
  775. return res;
  776. }, "getPrefix");
  777. function debugFn(messageOrData, ...args) {
  778. if (!isDebuggerEnabled()) return;
  779. const prefix = getPrefix();
  780. const multiString = (0, import_js_format3.format)(messageOrData, ...args);
  781. const rows = multiString.split("\n");
  782. rows.forEach((message) => {
  783. prefix ? console.log(`${prefix} ${message}`) : console.log(message);
  784. });
  785. }
  786. __name(debugFn, "debugFn");
  787. debugFn.withNs = function(namespace, ...args) {
  788. const stateCopy = JSON.parse(JSON.stringify(state));
  789. [namespace, ...args].forEach((ns) => {
  790. if (!ns || typeof ns !== "string")
  791. throw new import_js_format2.Errorf(
  792. "Debugger namespace must be a non-empty String, but %v given.",
  793. ns
  794. );
  795. stateCopy.nsSegments.push(ns);
  796. });
  797. return createDebugger(stateCopy);
  798. };
  799. debugFn.withHash = function(hashLength = 4) {
  800. const stateCopy = JSON.parse(JSON.stringify(state));
  801. if (!hashLength || typeof hashLength !== "number" || hashLength < 1) {
  802. throw new import_js_format2.Errorf(
  803. "Debugger hash must be a positive Number, but %v given.",
  804. hashLength
  805. );
  806. }
  807. stateCopy.hash = generateRandomHex(hashLength);
  808. return createDebugger(stateCopy);
  809. };
  810. debugFn.withOffset = function(offsetSize) {
  811. const stateCopy = JSON.parse(JSON.stringify(state));
  812. if (!offsetSize || typeof offsetSize !== "number" || offsetSize < 1) {
  813. throw new import_js_format2.Errorf(
  814. "Debugger offset must be a positive Number, but %v given.",
  815. offsetSize
  816. );
  817. }
  818. stateCopy.offsetSize = offsetSize;
  819. return createDebugger(stateCopy);
  820. };
  821. debugFn.withoutEnvNs = function() {
  822. const stateCopy = JSON.parse(JSON.stringify(state));
  823. stateCopy.envNsSegments = [];
  824. return createDebugger(stateCopy);
  825. };
  826. debugFn.inspect = function(valueOrDesc, ...args) {
  827. if (!isDebuggerEnabled()) return;
  828. const prefix = getPrefix();
  829. let multiString = "";
  830. if (typeof valueOrDesc === "string" && args.length) {
  831. multiString += `${valueOrDesc}
  832. `;
  833. const multilineDump = args.map((v) => createColorizedDump(v)).join("\n");
  834. const dumpRows = multilineDump.split("\n");
  835. multiString += dumpRows.map((v) => `${state.offsetStep}${v}`).join("\n");
  836. } else {
  837. multiString += [valueOrDesc, ...args].map((v) => createColorizedDump(v)).join("\n");
  838. }
  839. const rows = multiString.split("\n");
  840. rows.forEach((message) => {
  841. prefix ? console.log(`${prefix} ${message}`) : console.log(message);
  842. });
  843. };
  844. debugFn.state = state;
  845. return debugFn;
  846. }
  847. __name(createDebugger, "createDebugger");
  848. // node_modules/@e22m4u/js-service/src/debuggable-service.js
  849. var _DebuggableService = class _DebuggableService extends Debuggable {
  850. /**
  851. * Service.
  852. *
  853. * @type {Service}
  854. */
  855. _service;
  856. /**
  857. * Container.
  858. *
  859. * @type {ServiceContainer}
  860. */
  861. get container() {
  862. return this._service.container;
  863. }
  864. /**
  865. * Получить существующий или новый экземпляр.
  866. *
  867. * @type {Service['getService']}
  868. */
  869. get getService() {
  870. return this._service.getService;
  871. }
  872. /**
  873. * Получить существующий или новый экземпляр,
  874. * только если конструктор зарегистрирован.
  875. *
  876. * @type {Service['getRegisteredService']}
  877. */
  878. get getRegisteredService() {
  879. return this._service.getRegisteredService;
  880. }
  881. /**
  882. * Проверка существования конструктора в контейнере.
  883. *
  884. * @type {Service['hasService']}
  885. */
  886. get hasService() {
  887. return this._service.hasService;
  888. }
  889. /**
  890. * Добавить конструктор в контейнер.
  891. *
  892. * @type {Service['addService']}
  893. */
  894. get addService() {
  895. return this._service.addService;
  896. }
  897. /**
  898. * Добавить конструктор и создать экземпляр.
  899. *
  900. * @type {Service['useService']}
  901. */
  902. get useService() {
  903. return this._service.useService;
  904. }
  905. /**
  906. * Добавить конструктор и связанный экземпляр.
  907. *
  908. * @type {Service['setService']}
  909. */
  910. get setService() {
  911. return this._service.setService;
  912. }
  913. /**
  914. * Constructor.
  915. *
  916. * @param {ServiceContainer|undefined} container
  917. * @param {import('@e22m4u/js-debug').DebuggableOptions|undefined} options
  918. */
  919. constructor(container = void 0, options = void 0) {
  920. super(options);
  921. this._service = new Service(container);
  922. }
  923. };
  924. __name(_DebuggableService, "DebuggableService");
  925. /**
  926. * Kinds.
  927. *
  928. * @type {string[]}
  929. */
  930. __publicField(_DebuggableService, "kinds", Service.kinds);
  931. var DebuggableService = _DebuggableService;
  932. // src/mongodb-adapter.js
  933. var import_js_repository6 = require("@e22m4u/js-repository");
  934. var import_js_repository7 = require("@e22m4u/js-repository");
  935. var import_js_repository8 = require("@e22m4u/js-repository");
  936. var import_js_repository9 = require("@e22m4u/js-repository");
  937. var import_js_repository10 = require("@e22m4u/js-repository");
  938. var import_js_repository11 = require("@e22m4u/js-repository");
  939. var MONGODB_OPTION_NAMES = [
  940. "ALPNProtocols",
  941. "allowPartialTrustChain",
  942. "appName",
  943. "auth",
  944. "authMechanism",
  945. "authMechanismProperties",
  946. "authSource",
  947. "autoEncryption",
  948. "autoSelectFamily",
  949. "autoSelectFamilyAttemptTimeout",
  950. "bsonRegExp",
  951. "ca",
  952. "cert",
  953. "checkKeys",
  954. "checkServerIdentity",
  955. "ciphers",
  956. "compressors",
  957. "connectTimeoutMS",
  958. "crl",
  959. "directConnection",
  960. "driverInfo",
  961. "ecdhCurve",
  962. "enableUtf8Validation",
  963. "family",
  964. "fieldsAsRaw",
  965. "forceServerObjectId",
  966. "heartbeatFrequencyMS",
  967. "hints",
  968. "ignoreUndefined",
  969. "journal",
  970. "keepAliveInitialDelay",
  971. "key",
  972. "loadBalanced",
  973. "localAddress",
  974. "localPort",
  975. "localThresholdMS",
  976. "lookup",
  977. "maxConnecting",
  978. "maxIdleTimeMS",
  979. "maxPoolSize",
  980. "maxStalenessSeconds",
  981. "minDHSize",
  982. "minHeartbeatFrequencyMS",
  983. "minPoolSize",
  984. "mongodbLogComponentSeverities",
  985. "mongodbLogMaxDocumentLength",
  986. "mongodbLogPath",
  987. "monitorCommands",
  988. "noDelay",
  989. "passphrase",
  990. "pfx",
  991. "pkFactory",
  992. "promoteBuffers",
  993. "promoteLongs",
  994. "promoteValues",
  995. "proxyHost",
  996. "proxyPassword",
  997. "proxyPort",
  998. "proxyUsername",
  999. "raw",
  1000. "readConcern",
  1001. "readConcernLevel",
  1002. "readPreference",
  1003. "readPreferenceTags",
  1004. "rejectUnauthorized",
  1005. "replicaSet",
  1006. "retryReads",
  1007. "retryWrites",
  1008. "secureContext",
  1009. "secureProtocol",
  1010. "serializeFunctions",
  1011. "serverApi",
  1012. "serverMonitoringMode",
  1013. "serverSelectionTimeoutMS",
  1014. "servername",
  1015. "session",
  1016. "socketTimeoutMS",
  1017. "srvMaxHosts",
  1018. "srvServiceName",
  1019. "ssl",
  1020. "timeoutMS",
  1021. "tls",
  1022. "tlsAllowInvalidCertificates",
  1023. "tlsAllowInvalidHostnames",
  1024. "tlsCAFile",
  1025. "tlsCRLFile",
  1026. "tlsCertificateKeyFile",
  1027. "tlsCertificateKeyFilePassword",
  1028. "tlsInsecure",
  1029. "useBigInt64",
  1030. "w",
  1031. "waitQueueTimeoutMS",
  1032. "writeConcern",
  1033. "wtimeoutMS",
  1034. "zlibCompressionLevel"
  1035. ];
  1036. var DEFAULT_SETTINGS = {
  1037. // connectTimeoutMS: 2500,
  1038. // serverSelectionTimeoutMS: 2500,
  1039. };
  1040. var _MongodbAdapter = class _MongodbAdapter extends import_js_repository3.Adapter {
  1041. /**
  1042. * Mongodb instance.
  1043. *
  1044. * @type {MongoClient}
  1045. * @private
  1046. */
  1047. _client;
  1048. /**
  1049. * Client.
  1050. *
  1051. * @returns {MongoClient}
  1052. */
  1053. get client() {
  1054. return this._client;
  1055. }
  1056. /**
  1057. * Collections.
  1058. *
  1059. * @type {Map<any, any>}
  1060. * @private
  1061. */
  1062. _collections = /* @__PURE__ */ new Map();
  1063. /**
  1064. * Constructor.
  1065. *
  1066. * @param {ServiceContainer} container
  1067. * @param settings
  1068. */
  1069. constructor(container, settings) {
  1070. settings = Object.assign({}, DEFAULT_SETTINGS, settings || {});
  1071. settings.protocol = settings.protocol || "mongodb";
  1072. settings.hostname = settings.hostname || settings.host || "127.0.0.1";
  1073. settings.port = settings.port || 27017;
  1074. settings.database = settings.database || settings.db || "database";
  1075. super(container, settings);
  1076. const options = (0, import_js_repository7.selectObjectKeys)(this.settings, MONGODB_OPTION_NAMES);
  1077. const url = createMongodbUrl(this.settings);
  1078. this._client = new import_mongodb3.MongoClient(url, options);
  1079. }
  1080. /**
  1081. * Get id prop name.
  1082. *
  1083. * @param modelName
  1084. * @private
  1085. */
  1086. _getIdPropName(modelName) {
  1087. return this.getService(import_js_repository9.ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  1088. modelName
  1089. );
  1090. }
  1091. /**
  1092. * Get id col name.
  1093. *
  1094. * @param modelName
  1095. * @private
  1096. */
  1097. _getIdColName(modelName) {
  1098. return this.getService(import_js_repository9.ModelDefinitionUtils).getPrimaryKeyAsColumnName(
  1099. modelName
  1100. );
  1101. }
  1102. /**
  1103. * Coerce id.
  1104. *
  1105. * @param value
  1106. * @returns {ObjectId|*}
  1107. * @private
  1108. */
  1109. _coerceId(value) {
  1110. if (value == null) return value;
  1111. if (isObjectId(value)) return new import_mongodb2.ObjectId(value);
  1112. return value;
  1113. }
  1114. /**
  1115. * Coerce date.
  1116. *
  1117. * @param value
  1118. * @returns {Date|*}
  1119. * @private
  1120. */
  1121. _coerceDate(value) {
  1122. if (value == null) return value;
  1123. if (value instanceof Date) return value;
  1124. if (isIsoDate(value)) return new Date(value);
  1125. return value;
  1126. }
  1127. /**
  1128. * To database.
  1129. *
  1130. * @param {string} modelName
  1131. * @param {object} modelData
  1132. * @returns {object}
  1133. * @private
  1134. */
  1135. _toDatabase(modelName, modelData) {
  1136. const tableData = this.getService(
  1137. import_js_repository9.ModelDefinitionUtils
  1138. ).convertPropertyNamesToColumnNames(modelName, modelData);
  1139. const idColName = this._getIdColName(modelName);
  1140. if (idColName !== "id" && idColName !== "_id")
  1141. throw new import_js_repository10.InvalidArgumentError(
  1142. 'MongoDB is not supporting custom names of the primary key. Do use "id" as a primary key instead of %v.',
  1143. idColName
  1144. );
  1145. if (idColName in tableData && idColName !== "_id") {
  1146. tableData._id = tableData[idColName];
  1147. delete tableData[idColName];
  1148. }
  1149. return transformValuesDeep(tableData, (value) => {
  1150. if (value instanceof import_mongodb2.ObjectId) return value;
  1151. if (value instanceof Date) return value;
  1152. if (isObjectId(value)) return new import_mongodb2.ObjectId(value);
  1153. if (isIsoDate(value)) return new Date(value);
  1154. return value;
  1155. });
  1156. }
  1157. /**
  1158. * From database.
  1159. *
  1160. * @param {string} modelName
  1161. * @param {object} tableData
  1162. * @returns {object}
  1163. * @private
  1164. */
  1165. _fromDatabase(modelName, tableData) {
  1166. if ("_id" in tableData) {
  1167. const idColName = this._getIdColName(modelName);
  1168. if (idColName !== "id" && idColName !== "_id")
  1169. throw new import_js_repository10.InvalidArgumentError(
  1170. 'MongoDB is not supporting custom names of the primary key. Do use "id" as a primary key instead of %v.',
  1171. idColName
  1172. );
  1173. if (idColName !== "_id") {
  1174. tableData[idColName] = tableData._id;
  1175. delete tableData._id;
  1176. }
  1177. }
  1178. const modelData = this.getService(
  1179. import_js_repository9.ModelDefinitionUtils
  1180. ).convertColumnNamesToPropertyNames(modelName, tableData);
  1181. return transformValuesDeep(modelData, (value) => {
  1182. if (value instanceof import_mongodb2.ObjectId) return String(value);
  1183. if (value instanceof Date) return value.toISOString();
  1184. return value;
  1185. });
  1186. }
  1187. /**
  1188. * Get collection name by model name.
  1189. *
  1190. * @param {string} modelName
  1191. */
  1192. _getCollectionNameByModelName(modelName) {
  1193. const modelDef = this.getService(import_js_repository8.DefinitionRegistry).getModel(modelName);
  1194. if (modelDef.tableName != null) return modelDef.tableName;
  1195. return modelNameToCollectionName(modelDef.name);
  1196. }
  1197. /**
  1198. * Get collection.
  1199. *
  1200. * @param {string} modelName
  1201. * @returns {*}
  1202. * @private
  1203. */
  1204. _getCollection(modelName) {
  1205. let collection = this._collections.get(modelName);
  1206. if (collection) return collection;
  1207. const collectionName = this._getCollectionNameByModelName(modelName);
  1208. collection = this.client.db(this.settings.database).collection(collectionName);
  1209. this._collections.set(modelName, collection);
  1210. return collection;
  1211. }
  1212. /**
  1213. * Get id type.
  1214. *
  1215. * @param modelName
  1216. * @returns {string|*}
  1217. * @private
  1218. */
  1219. _getIdType(modelName) {
  1220. const utils = this.getService(import_js_repository9.ModelDefinitionUtils);
  1221. const pkPropName = utils.getPrimaryKeyAsPropertyName(modelName);
  1222. return utils.getDataTypeByPropertyName(modelName, pkPropName);
  1223. }
  1224. /**
  1225. * Get col name.
  1226. *
  1227. * @param {string} modelName
  1228. * @param {string} propName
  1229. * @returns {string}
  1230. * @private
  1231. */
  1232. _getColName(modelName, propName) {
  1233. if (!propName || typeof propName !== "string")
  1234. throw new import_js_repository10.InvalidArgumentError(
  1235. "Property name must be a non-empty String, but %v given.",
  1236. propName
  1237. );
  1238. const utils = this.getService(import_js_repository9.ModelDefinitionUtils);
  1239. let colName = propName;
  1240. try {
  1241. colName = utils.getColumnNameByPropertyName(modelName, propName);
  1242. } catch (error) {
  1243. if (!(error instanceof import_js_repository10.InvalidArgumentError) || error.message.indexOf("does not have the property") === -1) {
  1244. throw error;
  1245. }
  1246. }
  1247. return colName;
  1248. }
  1249. /**
  1250. * Convert prop names chain to col names chain.
  1251. *
  1252. * @param {string} modelName
  1253. * @param {string} propsChain
  1254. * @returns {string}
  1255. * @private
  1256. */
  1257. _convertPropNamesChainToColNamesChain(modelName, propsChain) {
  1258. if (!modelName || typeof modelName !== "string")
  1259. throw new import_js_repository10.InvalidArgumentError(
  1260. "Model name must be a non-empty String, but %v given.",
  1261. modelName
  1262. );
  1263. if (!propsChain || typeof propsChain !== "string")
  1264. throw new import_js_repository10.InvalidArgumentError(
  1265. "Properties chain must be a non-empty String, but %v given.",
  1266. propsChain
  1267. );
  1268. propsChain = propsChain.replace(/\.{2,}/g, ".");
  1269. const propNames = propsChain.split(".");
  1270. const utils = this.getService(import_js_repository9.ModelDefinitionUtils);
  1271. let currModelName = modelName;
  1272. return propNames.map((currPropName) => {
  1273. if (!currModelName) return currPropName;
  1274. const colName = this._getColName(currModelName, currPropName);
  1275. currModelName = utils.getModelNameOfPropertyValueIfDefined(
  1276. currModelName,
  1277. currPropName
  1278. );
  1279. return colName;
  1280. }).join(".");
  1281. }
  1282. /**
  1283. * Build projection.
  1284. *
  1285. * @param {string} modelName
  1286. * @param {string|string[]} fields
  1287. * @returns {Record<string, number>|undefined}
  1288. * @private
  1289. */
  1290. _buildProjection(modelName, fields) {
  1291. if (fields == null) return;
  1292. if (Array.isArray(fields) === false) fields = [fields];
  1293. if (!fields.length) return;
  1294. if (fields.indexOf("_id") === -1) fields.push("_id");
  1295. return fields.reduce((acc, field) => {
  1296. if (!field || typeof field !== "string")
  1297. throw new import_js_repository10.InvalidArgumentError(
  1298. 'The provided option "fields" should be a non-empty String or an Array of non-empty String, but %v given.',
  1299. field
  1300. );
  1301. let colName = this._convertPropNamesChainToColNamesChain(
  1302. modelName,
  1303. field
  1304. );
  1305. acc[colName] = 1;
  1306. return acc;
  1307. }, {});
  1308. }
  1309. /**
  1310. * Build sort.
  1311. *
  1312. * @param {string} modelName
  1313. * @param {string|string[]} clause
  1314. * @returns {object|undefined}
  1315. * @private
  1316. */
  1317. _buildSort(modelName, clause) {
  1318. if (clause == null) return;
  1319. if (Array.isArray(clause) === false) clause = [clause];
  1320. if (!clause.length) return;
  1321. const idPropName = this._getIdPropName(modelName);
  1322. return clause.reduce((acc, order) => {
  1323. if (!order || typeof order !== "string")
  1324. throw new import_js_repository10.InvalidArgumentError(
  1325. 'The provided option "order" should be a non-empty String or an Array of non-empty String, but %v given.',
  1326. order
  1327. );
  1328. const direction = order.match(/\s+(A|DE)SC$/);
  1329. let field = order.replace(/\s+(A|DE)SC$/, "").trim();
  1330. if (field === idPropName) {
  1331. field = "_id";
  1332. } else {
  1333. try {
  1334. field = this._convertPropNamesChainToColNamesChain(modelName, field);
  1335. } catch (error) {
  1336. if (!(error instanceof import_js_repository10.InvalidArgumentError) || error.message.indexOf("does not have the property") === -1) {
  1337. throw error;
  1338. }
  1339. }
  1340. }
  1341. acc[field] = direction && direction[1] === "DE" ? -1 : 1;
  1342. return acc;
  1343. }, {});
  1344. }
  1345. /**
  1346. * Build query.
  1347. *
  1348. * @param {string} modelName
  1349. * @param {object} clause
  1350. * @returns {object}
  1351. * @private
  1352. */
  1353. _buildQuery(modelName, clause) {
  1354. if (clause == null) return;
  1355. if (typeof clause !== "object" || Array.isArray(clause))
  1356. throw new import_js_repository10.InvalidArgumentError(
  1357. 'The provided option "where" should be an Object, but %v given.',
  1358. clause
  1359. );
  1360. const query = {};
  1361. const idPropName = this._getIdPropName(modelName);
  1362. Object.keys(clause).forEach((key) => {
  1363. var _a, _b;
  1364. if (String(key).indexOf("$") !== -1)
  1365. throw new import_js_repository10.InvalidArgumentError(
  1366. 'The symbol "$" is not supported, but %v given.',
  1367. key
  1368. );
  1369. let cond = clause[key];
  1370. if (key === "and" || key === "or" || key === "nor") {
  1371. if (cond == null) return;
  1372. if (!Array.isArray(cond))
  1373. throw new import_js_repository11.InvalidOperatorValueError(key, "an Array", cond);
  1374. if (cond.length === 0) return;
  1375. cond = cond.map((c) => this._buildQuery(modelName, c));
  1376. cond = cond.filter((c) => c != null);
  1377. const opKey = "$" + key;
  1378. query[opKey] = (_a = query[opKey]) != null ? _a : [];
  1379. query[opKey] = [...query[opKey], ...cond];
  1380. return;
  1381. }
  1382. if (key === idPropName) {
  1383. key = "_id";
  1384. } else {
  1385. key = this._convertPropNamesChainToColNamesChain(modelName, key);
  1386. }
  1387. if (typeof cond === "string") {
  1388. query[key] = this._coerceId(cond);
  1389. query[key] = this._coerceDate(query[key]);
  1390. return;
  1391. }
  1392. if (cond instanceof import_mongodb2.ObjectId) {
  1393. query[key] = cond;
  1394. return;
  1395. }
  1396. if (cond && cond.constructor && cond.constructor.name === "Object") {
  1397. const opConds = [];
  1398. if ("eq" in cond) {
  1399. let eq = this._coerceId(cond.eq);
  1400. eq = this._coerceDate(eq);
  1401. opConds.push({ $eq: eq });
  1402. }
  1403. if ("neq" in cond) {
  1404. let neq = this._coerceId(cond.neq);
  1405. neq = this._coerceDate(neq);
  1406. opConds.push({ $ne: neq });
  1407. }
  1408. if ("gt" in cond) {
  1409. const gt = this._coerceDate(cond.gt);
  1410. opConds.push({ $gt: gt });
  1411. }
  1412. if ("lt" in cond) {
  1413. const lt = this._coerceDate(cond.lt);
  1414. opConds.push({ $lt: lt });
  1415. }
  1416. if ("gte" in cond) {
  1417. const gte = this._coerceDate(cond.gte);
  1418. opConds.push({ $gte: gte });
  1419. }
  1420. if ("lte" in cond) {
  1421. const lte = this._coerceDate(cond.lte);
  1422. opConds.push({ $lte: lte });
  1423. }
  1424. if ("inq" in cond) {
  1425. if (!cond.inq || !Array.isArray(cond.inq))
  1426. throw new import_js_repository11.InvalidOperatorValueError(
  1427. "inq",
  1428. "an Array of possible values",
  1429. cond.inq
  1430. );
  1431. const inq = cond.inq.map((v) => {
  1432. v = this._coerceId(v);
  1433. v = this._coerceDate(v);
  1434. return v;
  1435. });
  1436. opConds.push({ $in: inq });
  1437. }
  1438. if ("nin" in cond) {
  1439. if (!cond.nin || !Array.isArray(cond.nin))
  1440. throw new import_js_repository11.InvalidOperatorValueError(
  1441. "nin",
  1442. "an Array of possible values",
  1443. cond
  1444. );
  1445. const nin = cond.nin.map((v) => {
  1446. v = this._coerceId(v);
  1447. v = this._coerceDate(v);
  1448. return v;
  1449. });
  1450. opConds.push({ $nin: nin });
  1451. }
  1452. if ("between" in cond) {
  1453. if (!Array.isArray(cond.between) || cond.between.length !== 2)
  1454. throw new import_js_repository11.InvalidOperatorValueError(
  1455. "between",
  1456. "an Array of 2 elements",
  1457. cond.between
  1458. );
  1459. const gte = this._coerceDate(cond.between[0]);
  1460. const lte = this._coerceDate(cond.between[1]);
  1461. opConds.push({ $gte: gte, $lte: lte });
  1462. }
  1463. if ("exists" in cond) {
  1464. if (typeof cond.exists !== "boolean")
  1465. throw new import_js_repository11.InvalidOperatorValueError(
  1466. "exists",
  1467. "a Boolean",
  1468. cond.exists
  1469. );
  1470. opConds.push({ $exists: cond.exists });
  1471. }
  1472. if ("like" in cond) {
  1473. if (typeof cond.like !== "string" && !(cond.like instanceof RegExp))
  1474. throw new import_js_repository11.InvalidOperatorValueError(
  1475. "like",
  1476. "a String or RegExp",
  1477. cond.like
  1478. );
  1479. opConds.push({ $regex: (0, import_js_repository6.stringToRegexp)(cond.like) });
  1480. }
  1481. if ("nlike" in cond) {
  1482. if (typeof cond.nlike !== "string" && !(cond.nlike instanceof RegExp))
  1483. throw new import_js_repository11.InvalidOperatorValueError(
  1484. "nlike",
  1485. "a String or RegExp",
  1486. cond.nlike
  1487. );
  1488. opConds.push({ $not: (0, import_js_repository6.stringToRegexp)(cond.nlike) });
  1489. }
  1490. if ("ilike" in cond) {
  1491. if (typeof cond.ilike !== "string" && !(cond.ilike instanceof RegExp))
  1492. throw new import_js_repository11.InvalidOperatorValueError(
  1493. "ilike",
  1494. "a String or RegExp",
  1495. cond.ilike
  1496. );
  1497. opConds.push({ $regex: (0, import_js_repository6.stringToRegexp)(cond.ilike, "i") });
  1498. }
  1499. if ("nilike" in cond) {
  1500. if (typeof cond.nilike !== "string" && !(cond.nilike instanceof RegExp)) {
  1501. throw new import_js_repository11.InvalidOperatorValueError(
  1502. "nilike",
  1503. "a String or RegExp",
  1504. cond.nilike
  1505. );
  1506. }
  1507. opConds.push({ $not: (0, import_js_repository6.stringToRegexp)(cond.nilike, "i") });
  1508. }
  1509. if ("regexp" in cond) {
  1510. if (typeof cond.regexp !== "string" && !(cond.regexp instanceof RegExp)) {
  1511. throw new import_js_repository11.InvalidOperatorValueError(
  1512. "regexp",
  1513. "a String or RegExp",
  1514. cond.regexp
  1515. );
  1516. }
  1517. const flags = cond.flags || void 0;
  1518. if (flags && typeof flags !== "string")
  1519. throw new import_js_repository10.InvalidArgumentError(
  1520. "RegExp flags must be a String, but %v given.",
  1521. cond.flags
  1522. );
  1523. opConds.push({ $regex: (0, import_js_repository6.stringToRegexp)(cond.regexp, flags) });
  1524. }
  1525. if (opConds.length === 1) {
  1526. query[key] = opConds[0];
  1527. } else if (opConds.length > 1) {
  1528. query["$and"] = (_b = query["$and"]) != null ? _b : [];
  1529. opConds.forEach((c) => query["$and"].push({ [key]: c }));
  1530. }
  1531. return;
  1532. }
  1533. query[key] = cond;
  1534. });
  1535. return Object.keys(query).length ? query : void 0;
  1536. }
  1537. /**
  1538. * Create.
  1539. *
  1540. * @param {string} modelName
  1541. * @param {object} modelData
  1542. * @param {object|undefined} filter
  1543. * @returns {Promise<object>}
  1544. */
  1545. async create(modelName, modelData, filter = void 0) {
  1546. const idPropName = this._getIdPropName(modelName);
  1547. const idValue = modelData[idPropName];
  1548. if (idValue == null || idValue === "" || idValue === 0) {
  1549. const pkType = this._getIdType(modelName);
  1550. if (pkType !== import_js_repository4.DataType.STRING && pkType !== import_js_repository4.DataType.ANY)
  1551. throw new import_js_repository10.InvalidArgumentError(
  1552. "MongoDB unable to generate primary keys of %s. Do provide your own value for the %v property or set property type to String.",
  1553. (0, import_js_repository5.capitalize)(pkType),
  1554. idPropName
  1555. );
  1556. delete modelData[idPropName];
  1557. }
  1558. const tableData = this._toDatabase(modelName, modelData);
  1559. const table = this._getCollection(modelName);
  1560. const { insertedId } = await table.insertOne(tableData);
  1561. const projection = this._buildProjection(
  1562. modelName,
  1563. filter && filter.fields
  1564. );
  1565. const insertedData = await table.findOne({ _id: insertedId }, { projection });
  1566. return this._fromDatabase(modelName, insertedData);
  1567. }
  1568. /**
  1569. * Replace by id.
  1570. *
  1571. * @param {string} modelName
  1572. * @param {string|number} id
  1573. * @param {object} modelData
  1574. * @param {object|undefined} filter
  1575. * @returns {Promise<object>}
  1576. */
  1577. async replaceById(modelName, id, modelData, filter = void 0) {
  1578. id = this._coerceId(id);
  1579. const idPropName = this._getIdPropName(modelName);
  1580. modelData[idPropName] = id;
  1581. const tableData = this._toDatabase(modelName, modelData);
  1582. const table = this._getCollection(modelName);
  1583. const { matchedCount } = await table.replaceOne({ _id: id }, tableData);
  1584. if (matchedCount < 1)
  1585. throw new import_js_repository10.InvalidArgumentError("Identifier %v is not found.", String(id));
  1586. const projection = this._buildProjection(
  1587. modelName,
  1588. filter && filter.fields
  1589. );
  1590. const replacedData = await table.findOne({ _id: id }, { projection });
  1591. return this._fromDatabase(modelName, replacedData);
  1592. }
  1593. /**
  1594. * Replace or create.
  1595. *
  1596. * @param {string} modelName
  1597. * @param {object} modelData
  1598. * @param {object|undefined} filter
  1599. * @returns {Promise<object>}
  1600. */
  1601. async replaceOrCreate(modelName, modelData, filter = void 0) {
  1602. const idPropName = this._getIdPropName(modelName);
  1603. let idValue = modelData[idPropName];
  1604. idValue = this._coerceId(idValue);
  1605. if (idValue == null || idValue === "" || idValue === 0) {
  1606. const pkType = this._getIdType(modelName);
  1607. if (pkType !== import_js_repository4.DataType.STRING && pkType !== import_js_repository4.DataType.ANY)
  1608. throw new import_js_repository10.InvalidArgumentError(
  1609. "MongoDB unable to generate primary keys of %s. Do provide your own value for the %v property or set property type to String.",
  1610. (0, import_js_repository5.capitalize)(pkType),
  1611. idPropName
  1612. );
  1613. delete modelData[idPropName];
  1614. idValue = void 0;
  1615. }
  1616. const tableData = this._toDatabase(modelName, modelData);
  1617. const table = this._getCollection(modelName);
  1618. if (idValue == null) {
  1619. const { insertedId } = await table.insertOne(tableData);
  1620. idValue = insertedId;
  1621. } else {
  1622. const { upsertedId } = await table.replaceOne({ _id: idValue }, tableData, {
  1623. upsert: true
  1624. });
  1625. if (upsertedId) idValue = upsertedId;
  1626. }
  1627. const projection = this._buildProjection(
  1628. modelName,
  1629. filter && filter.fields
  1630. );
  1631. const upsertedData = await table.findOne({ _id: idValue }, { projection });
  1632. return this._fromDatabase(modelName, upsertedData);
  1633. }
  1634. /**
  1635. * Patch.
  1636. *
  1637. * @param {string} modelName
  1638. * @param {object} modelData
  1639. * @param {object|undefined} where
  1640. * @returns {Promise<number>}
  1641. */
  1642. async patch(modelName, modelData, where = void 0) {
  1643. const idPropName = this._getIdPropName(modelName);
  1644. delete modelData[idPropName];
  1645. const query = this._buildQuery(modelName, where) || {};
  1646. const tableData = this._toDatabase(modelName, modelData);
  1647. const table = this._getCollection(modelName);
  1648. const { matchedCount } = await table.updateMany(query, { $set: tableData });
  1649. return matchedCount;
  1650. }
  1651. /**
  1652. * Patch by id.
  1653. *
  1654. * @param {string} modelName
  1655. * @param {string|number} id
  1656. * @param {object} modelData
  1657. * @param {object|undefined} filter
  1658. * @returns {Promise<object>}
  1659. */
  1660. async patchById(modelName, id, modelData, filter = void 0) {
  1661. id = this._coerceId(id);
  1662. const idPropName = this._getIdPropName(modelName);
  1663. delete modelData[idPropName];
  1664. const tableData = this._toDatabase(modelName, modelData);
  1665. const table = this._getCollection(modelName);
  1666. const { matchedCount } = await table.updateOne({ _id: id }, { $set: tableData });
  1667. if (matchedCount < 1)
  1668. throw new import_js_repository10.InvalidArgumentError("Identifier %v is not found.", String(id));
  1669. const projection = this._buildProjection(
  1670. modelName,
  1671. filter && filter.fields
  1672. );
  1673. const patchedData = await table.findOne({ _id: id }, { projection });
  1674. return this._fromDatabase(modelName, patchedData);
  1675. }
  1676. /**
  1677. * Find.
  1678. *
  1679. * @param {string} modelName
  1680. * @param {object|undefined} filter
  1681. * @returns {Promise<object[]>}
  1682. */
  1683. async find(modelName, filter = void 0) {
  1684. filter = filter || {};
  1685. const query = this._buildQuery(modelName, filter.where);
  1686. const sort = this._buildSort(modelName, filter.order);
  1687. const limit = filter.limit || void 0;
  1688. const skip = filter.skip || void 0;
  1689. const projection = this._buildProjection(modelName, filter.fields);
  1690. const collection = this._getCollection(modelName);
  1691. const options = { sort, limit, skip, projection };
  1692. const tableItems = await collection.find(query, options).toArray();
  1693. return tableItems.map((v) => this._fromDatabase(modelName, v));
  1694. }
  1695. /**
  1696. * Find by id.
  1697. *
  1698. * @param {string} modelName
  1699. * @param {string|number} id
  1700. * @param {object|undefined} filter
  1701. * @returns {Promise<object>}
  1702. */
  1703. async findById(modelName, id, filter = void 0) {
  1704. id = this._coerceId(id);
  1705. const table = this._getCollection(modelName);
  1706. const projection = this._buildProjection(
  1707. modelName,
  1708. filter && filter.fields
  1709. );
  1710. const patchedData = await table.findOne({ _id: id }, { projection });
  1711. if (!patchedData)
  1712. throw new import_js_repository10.InvalidArgumentError("Identifier %v is not found.", String(id));
  1713. return this._fromDatabase(modelName, patchedData);
  1714. }
  1715. /**
  1716. * Delete.
  1717. *
  1718. * @param {string} modelName
  1719. * @param {object|undefined} where
  1720. * @returns {Promise<number>}
  1721. */
  1722. async delete(modelName, where = void 0) {
  1723. const table = this._getCollection(modelName);
  1724. const query = this._buildQuery(modelName, where);
  1725. const { deletedCount } = await table.deleteMany(query);
  1726. return deletedCount;
  1727. }
  1728. /**
  1729. * Delete by id.
  1730. *
  1731. * @param {string} modelName
  1732. * @param {string|number} id
  1733. * @returns {Promise<boolean>}
  1734. */
  1735. async deleteById(modelName, id) {
  1736. id = this._coerceId(id);
  1737. const table = this._getCollection(modelName);
  1738. const { deletedCount } = await table.deleteOne({ _id: id });
  1739. return deletedCount > 0;
  1740. }
  1741. /**
  1742. * Exists.
  1743. *
  1744. * @param {string} modelName
  1745. * @param {string|number} id
  1746. * @returns {Promise<boolean>}
  1747. */
  1748. async exists(modelName, id) {
  1749. id = this._coerceId(id);
  1750. const table = this._getCollection(modelName);
  1751. const result = await table.findOne({ _id: id }, {});
  1752. return result != null;
  1753. }
  1754. /**
  1755. * Count.
  1756. *
  1757. * @param {string} modelName
  1758. * @param {object|undefined} where
  1759. * @returns {Promise<number>}
  1760. */
  1761. async count(modelName, where = void 0) {
  1762. const query = this._buildQuery(modelName, where);
  1763. const table = this._getCollection(modelName);
  1764. return await table.countDocuments(query);
  1765. }
  1766. };
  1767. __name(_MongodbAdapter, "MongodbAdapter");
  1768. var MongodbAdapter = _MongodbAdapter;
  1769. // Annotate the CommonJS export names for ESM import in node:
  1770. 0 && (module.exports = {
  1771. MongodbAdapter
  1772. });