index.cjs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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. DebuggableService: () => DebuggableService,
  25. SERVICE_CLASS_NAME: () => SERVICE_CLASS_NAME,
  26. SERVICE_CONTAINER_CLASS_NAME: () => SERVICE_CONTAINER_CLASS_NAME,
  27. Service: () => Service,
  28. ServiceContainer: () => ServiceContainer,
  29. isServiceContainer: () => isServiceContainer
  30. });
  31. module.exports = __toCommonJS(index_exports);
  32. // src/errors/invalid-argument-error.js
  33. var import_js_format = require("@e22m4u/js-format");
  34. var _InvalidArgumentError = class _InvalidArgumentError extends import_js_format.Errorf {
  35. };
  36. __name(_InvalidArgumentError, "InvalidArgumentError");
  37. var InvalidArgumentError = _InvalidArgumentError;
  38. // src/service-container.js
  39. var SERVICE_CONTAINER_CLASS_NAME = "ServiceContainer";
  40. var _ServiceContainer = class _ServiceContainer {
  41. /**
  42. * Services map.
  43. *
  44. * @type {Map<*, *>}
  45. */
  46. _services = /* @__PURE__ */ new Map();
  47. /**
  48. * Parent container.
  49. *
  50. * @type {ServiceContainer}
  51. */
  52. _parent;
  53. /**
  54. * Constructor.
  55. *
  56. * @param {ServiceContainer|undefined} parent
  57. */
  58. constructor(parent = void 0) {
  59. if (parent != null) {
  60. if (!(parent instanceof _ServiceContainer))
  61. throw new InvalidArgumentError(
  62. 'The provided parameter "parent" of ServicesContainer.constructor must be an instance ServiceContainer, but %v given.',
  63. parent
  64. );
  65. this._parent = parent;
  66. }
  67. }
  68. /**
  69. * Получить родительский сервис-контейнер или выбросить ошибку.
  70. *
  71. * @returns {ServiceContainer}
  72. */
  73. getParent() {
  74. if (!this._parent)
  75. throw new InvalidArgumentError("The service container has no parent.");
  76. return this._parent;
  77. }
  78. /**
  79. * Проверить наличие родительского сервис-контейнера.
  80. *
  81. * @returns {boolean}
  82. */
  83. hasParent() {
  84. return Boolean(this._parent);
  85. }
  86. /**
  87. * Получить существующий или новый экземпляр.
  88. *
  89. * @param {*} ctor
  90. * @param {*} args
  91. * @returns {*}
  92. */
  93. get(ctor, ...args) {
  94. if (!ctor || typeof ctor !== "function")
  95. throw new InvalidArgumentError(
  96. "The first argument of ServicesContainer.get must be a class constructor, but %v given.",
  97. ctor
  98. );
  99. const isCtorRegistered = this._services.has(ctor);
  100. let service = this._services.get(ctor);
  101. let inheritedCtor = void 0;
  102. if (!service) {
  103. const ctors = Array.from(this._services.keys());
  104. inheritedCtor = ctors.find((v) => v.prototype instanceof ctor);
  105. if (inheritedCtor) service = this._services.get(inheritedCtor);
  106. }
  107. if (!service && !isCtorRegistered && !inheritedCtor && this._parent && this._parent.has(ctor)) {
  108. return this._parent.get(ctor, ...args);
  109. }
  110. if (!isCtorRegistered && inheritedCtor) {
  111. ctor = inheritedCtor;
  112. }
  113. if (!service || args.length) {
  114. service = Array.isArray(ctor.kinds) && ctor.kinds.includes(SERVICE_CLASS_NAME) ? new ctor(this, ...args) : new ctor(...args);
  115. this._services.set(ctor, service);
  116. } else if (typeof service === "function") {
  117. service = service();
  118. this._services.set(ctor, service);
  119. }
  120. return service;
  121. }
  122. /**
  123. * Получить существующий или новый экземпляр,
  124. * только если конструктор зарегистрирован.
  125. *
  126. * @param {*} ctor
  127. * @param {*} args
  128. * @returns {*}
  129. */
  130. getRegistered(ctor, ...args) {
  131. if (!this.has(ctor))
  132. throw new InvalidArgumentError(
  133. "The constructor %v is not registered.",
  134. ctor
  135. );
  136. return this.get(ctor, ...args);
  137. }
  138. /**
  139. * Проверить существование конструктора в контейнере.
  140. *
  141. * @param {*} ctor
  142. * @returns {boolean}
  143. */
  144. has(ctor) {
  145. if (this._services.has(ctor)) return true;
  146. const ctors = Array.from(this._services.keys());
  147. const inheritedCtor = ctors.find((v) => v.prototype instanceof ctor);
  148. if (inheritedCtor) return true;
  149. if (this._parent) return this._parent.has(ctor);
  150. return false;
  151. }
  152. /**
  153. * Добавить конструктор в контейнер.
  154. *
  155. * @param {*} ctor
  156. * @param {*} args
  157. * @returns {this}
  158. */
  159. add(ctor, ...args) {
  160. if (!ctor || typeof ctor !== "function")
  161. throw new InvalidArgumentError(
  162. "The first argument of ServicesContainer.add must be a class constructor, but %v given.",
  163. ctor
  164. );
  165. const factory = /* @__PURE__ */ __name(() => Array.isArray(ctor.kinds) && ctor.kinds.includes(SERVICE_CLASS_NAME) ? new ctor(this, ...args) : new ctor(...args), "factory");
  166. this._services.set(ctor, factory);
  167. return this;
  168. }
  169. /**
  170. * Добавить конструктор и создать экземпляр.
  171. *
  172. * @param {*} ctor
  173. * @param {*} args
  174. * @returns {this}
  175. */
  176. use(ctor, ...args) {
  177. if (!ctor || typeof ctor !== "function")
  178. throw new InvalidArgumentError(
  179. "The first argument of ServicesContainer.use must be a class constructor, but %v given.",
  180. ctor
  181. );
  182. const service = Array.isArray(ctor.kinds) && ctor.kinds.includes(SERVICE_CLASS_NAME) ? new ctor(this, ...args) : new ctor(...args);
  183. this._services.set(ctor, service);
  184. return this;
  185. }
  186. /**
  187. * Добавить конструктор и связанный экземпляр.
  188. *
  189. * @param {*} ctor
  190. * @param {*} service
  191. * @returns {this}
  192. */
  193. set(ctor, service) {
  194. if (!ctor || typeof ctor !== "function")
  195. throw new InvalidArgumentError(
  196. "The first argument of ServicesContainer.set must be a class constructor, but %v given.",
  197. ctor
  198. );
  199. if (!service || typeof service !== "object" || Array.isArray(service))
  200. throw new InvalidArgumentError(
  201. "The second argument of ServicesContainer.set must be an Object, but %v given.",
  202. service
  203. );
  204. this._services.set(ctor, service);
  205. return this;
  206. }
  207. /**
  208. * Найти сервис удовлетворяющий условию.
  209. *
  210. * @param {Function} predicate
  211. * @param {boolean} noParent
  212. * @returns {*}
  213. */
  214. find(predicate, noParent = false) {
  215. if (typeof predicate !== "function") {
  216. throw new InvalidArgumentError(
  217. "The first argument of ServiceContainer.find must be a function, but %v given.",
  218. predicate
  219. );
  220. }
  221. const isRecursive = !noParent;
  222. let currentContainer = this;
  223. do {
  224. for (const ctor of currentContainer._services.keys()) {
  225. if (predicate(ctor, currentContainer) === true) {
  226. return this.get(ctor);
  227. }
  228. }
  229. if (isRecursive && currentContainer.hasParent()) {
  230. currentContainer = currentContainer.getParent();
  231. } else {
  232. currentContainer = null;
  233. }
  234. } while (currentContainer);
  235. return void 0;
  236. }
  237. };
  238. __name(_ServiceContainer, "ServiceContainer");
  239. /**
  240. * Kinds.
  241. *
  242. * @type {string[]}
  243. */
  244. __publicField(_ServiceContainer, "kinds", [SERVICE_CONTAINER_CLASS_NAME]);
  245. var ServiceContainer = _ServiceContainer;
  246. // src/utils/is-service-container.js
  247. function isServiceContainer(container) {
  248. return Boolean(
  249. container && typeof container === "object" && typeof container.constructor === "function" && Array.isArray(container.constructor.kinds) && container.constructor.kinds.includes(SERVICE_CONTAINER_CLASS_NAME)
  250. );
  251. }
  252. __name(isServiceContainer, "isServiceContainer");
  253. // src/service.js
  254. var SERVICE_CLASS_NAME = "Service";
  255. var _Service = class _Service {
  256. /**
  257. * Container.
  258. *
  259. * @type {ServiceContainer}
  260. */
  261. container;
  262. /**
  263. * Constructor.
  264. *
  265. * @param {ServiceContainer|undefined} container
  266. */
  267. constructor(container = void 0) {
  268. this.container = isServiceContainer(container) ? container : new ServiceContainer();
  269. }
  270. /**
  271. * Получить существующий или новый экземпляр.
  272. *
  273. * @param {*} ctor
  274. * @param {*} args
  275. * @returns {*}
  276. */
  277. getService(ctor, ...args) {
  278. return this.container.get(ctor, ...args);
  279. }
  280. /**
  281. * Получить существующий или новый экземпляр,
  282. * только если конструктор зарегистрирован.
  283. *
  284. * @param {*} ctor
  285. * @param {*} args
  286. * @returns {*}
  287. */
  288. getRegisteredService(ctor, ...args) {
  289. return this.container.getRegistered(ctor, ...args);
  290. }
  291. /**
  292. * Проверка существования конструктора в контейнере.
  293. *
  294. * @param {*} ctor
  295. * @returns {boolean}
  296. */
  297. hasService(ctor) {
  298. return this.container.has(ctor);
  299. }
  300. /**
  301. * Добавить конструктор в контейнер.
  302. *
  303. * @param {*} ctor
  304. * @param {*} args
  305. * @returns {this}
  306. */
  307. addService(ctor, ...args) {
  308. this.container.add(ctor, ...args);
  309. return this;
  310. }
  311. /**
  312. * Добавить конструктор и создать экземпляр.
  313. *
  314. * @param {*} ctor
  315. * @param {*} args
  316. * @returns {this}
  317. */
  318. useService(ctor, ...args) {
  319. this.container.use(ctor, ...args);
  320. return this;
  321. }
  322. /**
  323. * Добавить конструктор и связанный экземпляр.
  324. *
  325. * @param {*} ctor
  326. * @param {*} service
  327. * @returns {this}
  328. */
  329. setService(ctor, service) {
  330. this.container.set(ctor, service);
  331. return this;
  332. }
  333. /**
  334. * Найти сервис удовлетворяющий условию.
  335. *
  336. * @param {Function} predicate
  337. * @param {boolean} noParent
  338. * @returns {*}
  339. */
  340. findService(predicate, noParent = false) {
  341. return this.container.find(predicate, noParent);
  342. }
  343. };
  344. __name(_Service, "Service");
  345. /**
  346. * Kinds.
  347. *
  348. * @type {string[]}
  349. */
  350. __publicField(_Service, "kinds", [SERVICE_CLASS_NAME]);
  351. var Service = _Service;
  352. // src/debuggable-service.js
  353. var import_js_debug = require("@e22m4u/js-debug");
  354. var _DebuggableService = class _DebuggableService extends import_js_debug.Debuggable {
  355. /**
  356. * Service.
  357. *
  358. * @type {Service}
  359. */
  360. _service;
  361. /**
  362. * Container.
  363. *
  364. * @type {ServiceContainer}
  365. */
  366. get container() {
  367. return this._service.container;
  368. }
  369. /**
  370. * Получить существующий или новый экземпляр.
  371. *
  372. * @type {Service['getService']}
  373. */
  374. get getService() {
  375. return this._service.getService;
  376. }
  377. /**
  378. * Получить существующий или новый экземпляр,
  379. * только если конструктор зарегистрирован.
  380. *
  381. * @type {Service['getRegisteredService']}
  382. */
  383. get getRegisteredService() {
  384. return this._service.getRegisteredService;
  385. }
  386. /**
  387. * Проверка существования конструктора в контейнере.
  388. *
  389. * @type {Service['hasService']}
  390. */
  391. get hasService() {
  392. return this._service.hasService;
  393. }
  394. /**
  395. * Добавить конструктор в контейнер.
  396. *
  397. * @type {Service['addService']}
  398. */
  399. get addService() {
  400. return this._service.addService;
  401. }
  402. /**
  403. * Добавить конструктор и создать экземпляр.
  404. *
  405. * @type {Service['useService']}
  406. */
  407. get useService() {
  408. return this._service.useService;
  409. }
  410. /**
  411. * Добавить конструктор и связанный экземпляр.
  412. *
  413. * @type {Service['setService']}
  414. */
  415. get setService() {
  416. return this._service.setService;
  417. }
  418. /**
  419. * Найти сервис удовлетворяющий условию.
  420. *
  421. * @type {Service['findService']}
  422. */
  423. get findService() {
  424. return this._service.findService;
  425. }
  426. /**
  427. * Constructor.
  428. *
  429. * @param {ServiceContainer|undefined} container
  430. * @param {import('@e22m4u/js-debug').DebuggableOptions|undefined} options
  431. */
  432. constructor(container = void 0, options = void 0) {
  433. super(options);
  434. this._service = new Service(container);
  435. }
  436. };
  437. __name(_DebuggableService, "DebuggableService");
  438. /**
  439. * Kinds.
  440. *
  441. * @type {string[]}
  442. */
  443. __publicField(_DebuggableService, "kinds", Service.kinds);
  444. var DebuggableService = _DebuggableService;
  445. // Annotate the CommonJS export names for ESM import in node:
  446. 0 && (module.exports = {
  447. DebuggableService,
  448. SERVICE_CLASS_NAME,
  449. SERVICE_CONTAINER_CLASS_NAME,
  450. Service,
  451. ServiceContainer,
  452. isServiceContainer
  453. });