@venizia/ignis-kernel 0.4.8-8 → 0.4.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/dist/esm/base/applications/artifact-index.d.ts +3 -3
  2. package/dist/esm/base/applications/artifact-index.js.map +1 -1
  3. package/dist/esm/base/applications/body-limit.js +1 -1
  4. package/dist/esm/base/applications/body-limit.js.map +1 -1
  5. package/dist/esm/base/applications/common/types/application.d.ts +2 -2
  6. package/dist/esm/base/applications/common/types/application.js.map +1 -1
  7. package/dist/esm/base/applications/common/types/middlewares.d.ts +2 -2
  8. package/dist/esm/base/applications/common/types/middlewares.js.map +1 -1
  9. package/dist/esm/base/applications/rest.js +6 -1
  10. package/dist/esm/base/applications/rest.js.map +1 -1
  11. package/dist/esm/base/auth/authenticate/common/types/jwt.d.ts +1 -1
  12. package/dist/esm/base/auth/authenticate/common/types/jwt.js.map +1 -1
  13. package/dist/esm/base/auth/authenticate/common/types/strategy.d.ts +2 -3
  14. package/dist/esm/base/auth/authenticate/common/types/strategy.js.map +1 -1
  15. package/dist/esm/base/auth/authenticate/strategies/strategy-registry.d.ts +1 -1
  16. package/dist/esm/base/auth/authenticate/strategies/strategy-registry.js +1 -1
  17. package/dist/esm/base/auth/authenticate/strategies/strategy-registry.js.map +1 -1
  18. package/dist/esm/base/auth/authorize/providers/request-domain.js +2 -1
  19. package/dist/esm/base/auth/authorize/providers/request-domain.js.map +1 -1
  20. package/dist/esm/base/controllers/common/types/route.d.ts +13 -4
  21. package/dist/esm/base/controllers/common/types/route.js.map +1 -1
  22. package/dist/esm/base/controllers/factory/controller.d.ts +3 -4
  23. package/dist/esm/base/controllers/factory/controller.js +0 -1
  24. package/dist/esm/base/controllers/factory/controller.js.map +1 -1
  25. package/dist/esm/base/controllers/factory/crud/abstract.d.ts +3 -4
  26. package/dist/esm/base/controllers/factory/crud/abstract.js.map +1 -1
  27. package/dist/esm/base/controllers/factory/definition.d.ts +21 -1
  28. package/dist/esm/base/controllers/factory/definition.js +45 -31
  29. package/dist/esm/base/controllers/factory/definition.js.map +1 -1
  30. package/dist/esm/base/controllers/factory/index.d.ts +1 -0
  31. package/dist/esm/base/controllers/factory/index.js +1 -0
  32. package/dist/esm/base/controllers/factory/index.js.map +1 -1
  33. package/dist/esm/base/controllers/factory/injection.d.ts +38 -0
  34. package/dist/esm/base/controllers/factory/injection.js +54 -0
  35. package/dist/esm/base/controllers/factory/injection.js.map +1 -0
  36. package/dist/esm/base/controllers/rest/abstract.js +1 -1
  37. package/dist/esm/base/controllers/rest/abstract.js.map +1 -1
  38. package/dist/esm/base/controllers/rest/base.d.ts +3 -3
  39. package/dist/esm/base/controllers/rest/base.js.map +1 -1
  40. package/dist/esm/base/datasources/abstract.d.ts +4 -92
  41. package/dist/esm/base/datasources/abstract.js +3 -217
  42. package/dist/esm/base/datasources/abstract.js.map +1 -1
  43. package/dist/esm/base/datasources/common/types.d.ts +2 -2
  44. package/dist/esm/base/datasources/common/types.js.map +1 -1
  45. package/dist/esm/base/datasources/index.d.ts +1 -0
  46. package/dist/esm/base/datasources/index.js +1 -0
  47. package/dist/esm/base/datasources/index.js.map +1 -1
  48. package/dist/esm/base/datasources/root.d.ts +107 -0
  49. package/dist/esm/base/datasources/root.js +237 -0
  50. package/dist/esm/base/datasources/root.js.map +1 -0
  51. package/dist/esm/base/events/event-bus.js.map +1 -1
  52. package/dist/esm/base/metadata/index.d.ts +1 -1
  53. package/dist/esm/base/metadata/index.js +1 -1
  54. package/dist/esm/base/metadata/injectors.d.ts +1 -1
  55. package/dist/esm/base/metadata/persistents/datasource.d.ts +21 -0
  56. package/dist/esm/base/metadata/persistents/datasource.js +46 -0
  57. package/dist/esm/base/metadata/persistents/datasource.js.map +1 -0
  58. package/dist/esm/base/metadata/persistents/index.d.ts +5 -0
  59. package/dist/esm/base/metadata/persistents/index.js +5 -0
  60. package/dist/esm/base/metadata/persistents/index.js.map +1 -0
  61. package/dist/esm/base/metadata/persistents/model.d.ts +18 -0
  62. package/dist/esm/base/metadata/persistents/model.js +64 -0
  63. package/dist/esm/base/metadata/persistents/model.js.map +1 -0
  64. package/dist/esm/base/metadata/persistents/repository/index.d.ts +19 -0
  65. package/dist/esm/base/metadata/persistents/repository/index.js +32 -0
  66. package/dist/esm/base/metadata/persistents/repository/index.js.map +1 -0
  67. package/dist/esm/base/metadata/persistents/repository/injection.d.ts +15 -0
  68. package/dist/esm/base/metadata/persistents/repository/injection.js +64 -0
  69. package/dist/esm/base/metadata/persistents/repository/injection.js.map +1 -0
  70. package/dist/esm/base/metadata/persistents/repository/resolve.d.ts +15 -0
  71. package/dist/esm/base/metadata/persistents/repository/resolve.js +76 -0
  72. package/dist/esm/base/metadata/persistents/repository/resolve.js.map +1 -0
  73. package/dist/esm/base/metadata/persistents/repository/validate.d.ts +15 -0
  74. package/dist/esm/base/metadata/persistents/repository/validate.js +50 -0
  75. package/dist/esm/base/metadata/persistents/repository/validate.js.map +1 -0
  76. package/dist/esm/base/models/common/utilities.d.ts +1 -1
  77. package/dist/esm/base/repositories/common/response-reader.d.ts +30 -0
  78. package/dist/esm/base/repositories/common/response-reader.js +53 -0
  79. package/dist/esm/base/repositories/common/response-reader.js.map +1 -1
  80. package/dist/esm/base/repositories/common/types/contracts.d.ts +2 -2
  81. package/dist/esm/base/repositories/common/types/contracts.js.map +1 -1
  82. package/dist/esm/base/repositories/common/types/options.d.ts +2 -2
  83. package/dist/esm/base/repositories/common/types/options.js.map +1 -1
  84. package/dist/esm/base/repositories/common/types/query.d.ts +6 -15
  85. package/dist/esm/base/repositories/common/types/query.js.map +1 -1
  86. package/dist/esm/base/repositories/core/abstract.d.ts +6 -6
  87. package/dist/esm/base/repositories/core/abstract.js.map +1 -1
  88. package/dist/esm/base/repositories/query-schemas/index.js +7 -0
  89. package/dist/esm/base/repositories/query-schemas/index.js.map +1 -1
  90. package/dist/esm/helpers/inversion/common/types/model.d.ts +1 -1
  91. package/dist/esm/helpers/inversion/common/types/model.js.map +1 -1
  92. package/dist/esm/helpers/inversion/mixins/artifact.mixin.d.ts +4 -3
  93. package/dist/esm/helpers/inversion/mixins/artifact.mixin.js +1 -0
  94. package/dist/esm/helpers/inversion/mixins/artifact.mixin.js.map +1 -1
  95. package/dist/esm/helpers/inversion/mixins/controllers/controller.d.ts +4 -3
  96. package/dist/esm/helpers/inversion/mixins/controllers/controller.js +1 -0
  97. package/dist/esm/helpers/inversion/mixins/controllers/controller.js.map +1 -1
  98. package/dist/esm/helpers/inversion/mixins/controllers/grpc.d.ts +4 -3
  99. package/dist/esm/helpers/inversion/mixins/controllers/grpc.js +1 -0
  100. package/dist/esm/helpers/inversion/mixins/controllers/grpc.js.map +1 -1
  101. package/dist/esm/helpers/inversion/mixins/controllers/rest.d.ts +4 -3
  102. package/dist/esm/helpers/inversion/mixins/controllers/rest.js +1 -0
  103. package/dist/esm/helpers/inversion/mixins/controllers/rest.js.map +1 -1
  104. package/dist/esm/helpers/inversion/mixins/datasource.mixin.d.ts +4 -3
  105. package/dist/esm/helpers/inversion/mixins/datasource.mixin.js +1 -0
  106. package/dist/esm/helpers/inversion/mixins/datasource.mixin.js.map +1 -1
  107. package/dist/esm/helpers/inversion/mixins/model.mixin.d.ts +4 -3
  108. package/dist/esm/helpers/inversion/mixins/model.mixin.js +1 -0
  109. package/dist/esm/helpers/inversion/mixins/model.mixin.js.map +1 -1
  110. package/dist/esm/helpers/inversion/mixins/repository.mixin.d.ts +9 -8
  111. package/dist/esm/helpers/inversion/mixins/repository.mixin.js +6 -6
  112. package/dist/esm/helpers/inversion/mixins/repository.mixin.js.map +1 -1
  113. package/dist/esm/helpers/inversion/registry.d.ts +26 -26
  114. package/dist/esm/helpers/inversion/registry.js.map +1 -1
  115. package/dist/esm/helpers/singleton-realm.js +5 -4
  116. package/dist/esm/helpers/singleton-realm.js.map +1 -1
  117. package/dist/esm/metadata.d.ts +1 -1
  118. package/dist/esm/metadata.js +1 -1
  119. package/dist/esm/repository.d.ts +1 -0
  120. package/dist/esm/repository.js +1 -0
  121. package/dist/esm/repository.js.map +1 -1
  122. package/dist/esm/utilities/index.d.ts +1 -0
  123. package/dist/esm/utilities/index.js +1 -0
  124. package/dist/esm/utilities/index.js.map +1 -1
  125. package/dist/esm/utilities/toggle.utility.d.ts +22 -0
  126. package/dist/esm/utilities/toggle.utility.js +16 -0
  127. package/dist/esm/utilities/toggle.utility.js.map +1 -0
  128. package/package.json +5 -5
  129. package/dist/esm/base/metadata/persistents.d.ts +0 -54
  130. package/dist/esm/base/metadata/persistents.js +0 -302
  131. package/dist/esm/base/metadata/persistents.js.map +0 -1
@@ -0,0 +1,237 @@
1
+ var _a;
2
+ import { NotSupportedUtility } from '../../utilities/not-supported.utility.js';
3
+ import { BaseHelper, getError } from '@venizia/ignis-helpers/core';
4
+ import { DataSourceOpenDefaults, DataSourceOpenModes } from './common/index.js';
5
+ import { OPENING_HANDLES } from './opening-handles.js';
6
+ /**
7
+ * Brands the datasource root so `@repository` can recognise a subclass WITHOUT `instanceof`.
8
+ *
9
+ * Two copies of this package give two `DataSourceRoot` classes, and `instanceof` across them is
10
+ * false - the same trap `isApplicationError` exists to avoid for `ApplicationError`. `Symbol.for` is
11
+ * realm-keyed, so both copies produce this exact symbol, and a static is inherited by every
12
+ * subclass however deep.
13
+ */
14
+ /**
15
+ * The key keeps its old name, `abstract-data-source`, so a copy of the package from before `DataSourceRoot` still recognises the
16
+ * classes of a newer one, and the other way round.
17
+ */
18
+ export const DATA_SOURCE_BRAND = Symbol.for('@venizia/ignis-kernel:abstract-data-source');
19
+ /** True for `DataSourceRoot` itself and for any class extending it (`AbstractDataSource` among them), across package copies. */
20
+ export const isDataSourceClass = (value) => {
21
+ return typeof value === 'function' && DATA_SOURCE_BRAND in value;
22
+ };
23
+ /** The two ways a race between the open and its timeout can end. */
24
+ const OPEN_DONE = 'done';
25
+ const OPEN_TIMED_OUT = 'timed-out';
26
+ /**
27
+ * The datasource root with no dependency-injection import: the brand, the settings, the open-on-first-use state machine
28
+ * and the no-op defaults. A client that only talks HTTP extends this, so a browser bundle does not carry the metadata
29
+ * registry; {@link AbstractDataSource} adds what reads `@datasource` and `@repository` metadata.
30
+ */
31
+ export class DataSourceRoot extends BaseHelper {
32
+ constructor() {
33
+ super(...arguments);
34
+ this.isOpened = false;
35
+ this.isShutDown = false;
36
+ }
37
+ /** Read by {@link isDataSourceClass}. Static, so every subclass inherits it. */
38
+ static { this[_a] = true; }
39
+ /**
40
+ * Whether this family can open on first use: only a family whose every entry point first awaits {@link ensureOpen}
41
+ * says yes (the relational one does). A family that does not is refused at boot rather than left half-working.
42
+ */
43
+ supportsDeferredOpen() {
44
+ return false;
45
+ }
46
+ /** How the datasource opens: `start` here. {@link AbstractDataSource} reads the `open.on` of `@datasource`. */
47
+ getOpenMode() {
48
+ return DataSourceOpenModes.START;
49
+ }
50
+ isOpenDeferred() {
51
+ return this.getOpenMode() === DataSourceOpenModes.FIRST_USE;
52
+ }
53
+ /** How long an open may take (ms; `0` waits for ever): 60 s here. {@link AbstractDataSource} reads the `open.timeoutMs` of `@datasource`. */
54
+ getOpenTimeoutMs() {
55
+ return DataSourceOpenDefaults.TIMEOUT_MS;
56
+ }
57
+ /**
58
+ * Whether the datasource is open. One that opens on first use: after the first use has finished, until `close()`. One that
59
+ * opens at start: from the moment the application has started it, until `close()`.
60
+ */
61
+ isOpen() {
62
+ if (this.isShutDown) {
63
+ return false;
64
+ }
65
+ return this.isOpenDeferred() ? this.isOpened : true;
66
+ }
67
+ /** Whether the first use is opening the datasource right now. */
68
+ isOpening() {
69
+ return this.opening !== undefined;
70
+ }
71
+ /** Whether `close()` has begun. A datasource that opens on first use is not reopened after it. */
72
+ isClosed() {
73
+ return this.isShutDown;
74
+ }
75
+ /**
76
+ * What the application boot calls to get the handles it passes to `configure()` of a datasource that opens at start. Keyed by a
77
+ * symbol the package does not export, so nothing else can obtain the handles: see {@link OPENING_HANDLES}.
78
+ */
79
+ [(_a = DATA_SOURCE_BRAND, OPENING_HANDLES)]() {
80
+ return this.createOpening();
81
+ }
82
+ /**
83
+ * The handles `configure()` gets as its second argument, in both modes. The root has no connector, client or transaction to
84
+ * hand out; a family that has them overrides this. Protected: the only ways out are the argument of `configure()` and the
85
+ * boot's private key.
86
+ */
87
+ createOpening() {
88
+ const refuse = (member) => NotSupportedUtility.throwNotSupported({
89
+ scope: this.constructor.name,
90
+ feature: `opening.${member}`,
91
+ logger: this.logger,
92
+ });
93
+ return {
94
+ getConnector: () => refuse('getConnector'),
95
+ getClient: () => refuse('getClient'),
96
+ beginTransaction: () => Promise.resolve().then(() => refuse('beginTransaction')),
97
+ };
98
+ }
99
+ /**
100
+ * The boot's replacement for `configure()` on a datasource that opens on first use: records the options and opens nothing.
101
+ * Refused for a family that cannot honour it.
102
+ */
103
+ deferOpen(opts) {
104
+ if (!this.supportsDeferredOpen()) {
105
+ throw getError({
106
+ message: `[${this.constructor.name}][deferOpen] open: 'first-use' is not supported by this datasource family | Use open: { on: 'start' }, or remove the option`,
107
+ });
108
+ }
109
+ this.deferredOptions = opts.options;
110
+ }
111
+ /**
112
+ * Resolves once the datasource is open. At once for one that opens with the application. Otherwise the first caller
113
+ * starts `configure()` and the rest await the same promise, so it runs once; a failure rejects all of them, undoes what the
114
+ * failed `configure()` left ({@link discardPartialOpen}) and clears the slot, so the next call opens afresh. After
115
+ * `close()` it rejects: a stopped application does not reopen its datasources.
116
+ */
117
+ ensureOpen() {
118
+ if (!this.isOpenDeferred()) {
119
+ return Promise.resolve();
120
+ }
121
+ // Closed first: a call after `close()` is told so, whether or not the datasource had been opened.
122
+ if (this.isShutDown) {
123
+ return Promise.reject(getError({
124
+ message: `[${this.constructor.name}][ensureOpen] The datasource is closed | It opens on first use only before close()`,
125
+ }));
126
+ }
127
+ if (this.isOpened) {
128
+ return Promise.resolve();
129
+ }
130
+ if (this.abandoned) {
131
+ return Promise.reject(getError({
132
+ message: `[${this.constructor.name}][ensureOpen] The previous open is still running after its timeout | It is retried once it has settled`,
133
+ }));
134
+ }
135
+ this.opening ??= this.runOpen();
136
+ return this.opening;
137
+ }
138
+ async runOpen() {
139
+ const timeoutMs = this.getOpenTimeoutMs();
140
+ const work = Promise.resolve().then(() => this.configure(this.deferredOptions, this.createOpening()));
141
+ let timer;
142
+ const expired = new Promise((resolve) => {
143
+ if (timeoutMs > 0) {
144
+ timer = setTimeout(() => resolve(OPEN_TIMED_OUT), timeoutMs);
145
+ }
146
+ });
147
+ try {
148
+ const outcome = await Promise.race([work.then(() => OPEN_DONE), expired]);
149
+ if (outcome === OPEN_TIMED_OUT) {
150
+ this.abandoned = this.settleAbandoned({ work });
151
+ throw getError({
152
+ message: `[${this.constructor.name}][ensureOpen] The open did not finish within ${timeoutMs} ms | Does configure() await the datasource (a repository, ensureOpen)? Use the opening argument inside configure()`,
153
+ });
154
+ }
155
+ this.isOpened = true;
156
+ }
157
+ catch (error) {
158
+ await this.discardOpenAttempt();
159
+ throw error;
160
+ }
161
+ finally {
162
+ if (timer !== undefined) {
163
+ clearTimeout(timer);
164
+ }
165
+ this.opening = undefined;
166
+ }
167
+ }
168
+ /** When an abandoned open finally settles, whatever it built is closed (it was never published) and retries are allowed again. */
169
+ async settleAbandoned(opts) {
170
+ try {
171
+ await opts.work;
172
+ // eslint-disable-next-line venizia/no-silent-catch -- the abandoned attempt's own outcome was already reported by the timeout; only its clean-up matters now
173
+ }
174
+ catch {
175
+ // Falls through to the clean-up.
176
+ }
177
+ await this.discardOpenAttempt();
178
+ this.abandoned = undefined;
179
+ }
180
+ async discardOpenAttempt() {
181
+ try {
182
+ await this.discardPartialOpen();
183
+ // eslint-disable-next-line venizia/no-silent-catch -- the open's own error is what the caller must see: a failed clean-up is logged, never thrown over it
184
+ }
185
+ catch (cleanupError) {
186
+ this.logger
187
+ .for(this.ensureOpen.name)
188
+ .warn('Clean-up after a failed open also failed | error: %s', cleanupError);
189
+ }
190
+ }
191
+ /** Undoes what a `configure()` that threw left behind, so the next open starts clean. The root holds nothing; a family that keeps a client overrides it. */
192
+ discardPartialOpen() { }
193
+ /**
194
+ * Waits for an open in flight and refuses any later one. A family's `close()` calls it first, so a stop that arrives
195
+ * during the first use closes what that open built instead of racing it.
196
+ */
197
+ async settleOpening() {
198
+ this.isShutDown = true;
199
+ try {
200
+ await this.opening;
201
+ // eslint-disable-next-line venizia/no-silent-catch -- the failed open was reported to its own waiters; stopping goes on
202
+ }
203
+ catch (openError) {
204
+ this.logger
205
+ .for(this.close.name)
206
+ .debug('The open in flight failed while stopping | error: %s', openError);
207
+ }
208
+ }
209
+ getSettings() {
210
+ return this.settings;
211
+ }
212
+ getSchema() {
213
+ if (!this.schema) {
214
+ throw getError({
215
+ message: `[${this.constructor.name}] Schema not initialized. Override getSchema() or provide schema in constructor.`,
216
+ });
217
+ }
218
+ return this.schema;
219
+ }
220
+ /** Capability probe, overridden by connectors that support it (e.g. postgres reports `{ transactions: true }`). */
221
+ getCapabilities() {
222
+ return { transactions: false };
223
+ }
224
+ /** Nothing to release at this root; a family that holds a connection overrides it. */
225
+ close() {
226
+ return Promise.resolve();
227
+ }
228
+ /** Defaults to throwing NotSupported - only connectors with real transaction support override this; async so callers get a rejected promise, not a synchronous throw that skips try/catch. */
229
+ async beginTransaction(_opts) {
230
+ return NotSupportedUtility.throwNotSupported({
231
+ scope: this.constructor.name,
232
+ feature: 'Transactions',
233
+ logger: this.logger,
234
+ });
235
+ }
236
+ }
237
+ //# sourceMappingURL=root.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"root.js","sourceRoot":"","sources":["../../../../src/base/datasources/root.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AAExE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAUnE,OAAO,EAAE,sBAAsB,EAAE,mBAAmB,EAAE,MAAM,UAAU,CAAC;AACvE,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAEpD;;;;;;;GAOG;AACH;;;G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QAC1H,CAAC;QAAC,OAAO,SAAS,EAAE,CAAC;YACnB,IAAI,CAAC,MAAM;iBACR,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC;iBACpB,KAAK,CAAC,sDAAsD,EAAE,SAAS,CAAC,CAAC;QAC9E,CAAC;IACH,CAAC;IAED,WAAW;QACT,OAAO,IAAI,CAAC,QAAQ,CAAC;IACvB,CAAC;IAED,SAAS;QACP,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;YACjB,MAAM,QAAQ,CAAC;gBACb,OAAO,EAAE,IAAI,IAAI,CAAC,WAAW,CAAC,IAAI,kFAAkF;aACrH,CAAC,CAAC;QACL,CAAC;QAED,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;IAED,mHAAmH;IACnH,eAAe;QACb,OAAO,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC;IACjC,CAAC;IAED,sFAAsF;IACtF,KAAK;QACH,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IAED,8LAA8L;IAC9L,KAAK,CAAC,gBAAgB,CAAC,KAA2B;QAChD,OAAO,mBAAmB,CAAC,iBAAiB,CAAC;YAC3C,KAAK,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI;YAC5B,OAAO,EAAE,cAAc;YACvB,MAAM,EAAE,IAAI,CAAC,MAAM;SACpB,CAAC,CAAC;IACL,CAAC","sourcesContent":["import { NotSupportedUtility } from '@/utilities/not-supported.utility';\nimport type { TClass, ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport type {\n IDataSource,\n IDataSourceCapabilities,\n IDataSourceOpening,\n ITransaction,\n ITransactionOptions,\n TAnyDataSourceSchema,\n TDataSourceOpenMode,\n} from './common';\nimport { DataSourceOpenDefaults, DataSourceOpenModes } from './common';\nimport { OPENING_HANDLES } from './opening-handles';\n\n/**\n * Brands the datasource root so `@repository` can recognise a subclass WITHOUT `instanceof`.\n *\n * Two copies of this package give two `DataSourceRoot` classes, and `instanceof` across them is\n * false - the same trap `isApplicationError` exists to avoid for `ApplicationError`. `Symbol.for` is\n * realm-keyed, so both copies produce this exact symbol, and a static is inherited by every\n * subclass however deep.\n */\n/**\n * The key keeps its old name, `abstract-data-source`, so a copy of the package from before `DataSourceRoot` still recognises the\n * classes of a newer one, and the other way round.\n */\nexport const DATA_SOURCE_BRAND = Symbol.for('@venizia/ignis-kernel:abstract-data-source');\n\n/** True for `DataSourceRoot` itself and for any class extending it (`AbstractDataSource` among them), across package copies. */\nexport const isDataSourceClass = (value: unknown): value is TClass<unknown> => {\n return typeof value === 'function' && DATA_SOURCE_BRAND in value;\n};\n\n/** The two ways a race between the open and its timeout can end. */\nconst OPEN_DONE = 'done';\nconst OPEN_TIMED_OUT = 'timed-out';\n\n/**\n * The datasource root with no dependency-injection import: the brand, the settings, the open-on-first-use state machine\n * and the no-op defaults. A client that only talks HTTP extends this, so a browser bundle does not carry the metadata\n * registry; {@link AbstractDataSource} adds what reads `@datasource` and `@repository` metadata.\n */\nexport abstract class DataSourceRoot<\n Settings extends object = {},\n Schema extends TAnyDataSourceSchema = TAnyDataSourceSchema,\n ConfigurableOptions extends object = {},\n>\n extends BaseHelper\n implements IDataSource<Settings, Schema, ConfigurableOptions>\n{\n /** Read by {@link isDataSourceClass}. Static, so every subclass inherits it. */\n static readonly [DATA_SOURCE_BRAND] = true;\n\n name: string;\n settings: Settings;\n schema: Schema;\n\n abstract configure(\n opts?: ConfigurableOptions,\n opening?: IDataSourceOpening,\n ): ValueOrPromise<void>;\n\n /** The options the boot would have given `configure()`, kept for the open that the first use starts. */\n private deferredOptions?: ConfigurableOptions;\n\n /** The open in flight: every call that arrives meanwhile awaits this one promise. */\n private opening?: Promise<void>;\n\n /**\n * An open that outlived its timeout and has not settled. Nothing is retried until it has: two `configure()` must never\n * run at once, and when it does settle what it built is closed, never published.\n */\n private abandoned?: Promise<void>;\n\n private isOpened = false;\n private isShutDown = false;\n\n /**\n * Whether this family can open on first use: only a family whose every entry point first awaits {@link ensureOpen}\n * says yes (the relational one does). A family that does not is refused at boot rather than left half-working.\n */\n protected supportsDeferredOpen(): boolean {\n return false;\n }\n\n /** How the datasource opens: `start` here. {@link AbstractDataSource} reads the `open.on` of `@datasource`. */\n getOpenMode(): TDataSourceOpenMode {\n return DataSourceOpenModes.START;\n }\n\n isOpenDeferred(): boolean {\n return this.getOpenMode() === DataSourceOpenModes.FIRST_USE;\n }\n\n /** How long an open may take (ms; `0` waits for ever): 60 s here. {@link AbstractDataSource} reads the `open.timeoutMs` of `@datasource`. */\n getOpenTimeoutMs(): number {\n return DataSourceOpenDefaults.TIMEOUT_MS;\n }\n\n /**\n * Whether the datasource is open. One that opens on first use: after the first use has finished, until `close()`. One that\n * opens at start: from the moment the application has started it, until `close()`.\n */\n isOpen(): boolean {\n if (this.isShutDown) {\n return false;\n }\n\n return this.isOpenDeferred() ? this.isOpened : true;\n }\n\n /** Whether the first use is opening the datasource right now. */\n isOpening(): boolean {\n return this.opening !== undefined;\n }\n\n /** Whether `close()` has begun. A datasource that opens on first use is not reopened after it. */\n isClosed(): boolean {\n return this.isShutDown;\n }\n\n /**\n * What the application boot calls to get the handles it passes to `configure()` of a datasource that opens at start. Keyed by a\n * symbol the package does not export, so nothing else can obtain the handles: see {@link OPENING_HANDLES}.\n */\n [OPENING_HANDLES](): IDataSourceOpening {\n return this.createOpening();\n }\n\n /**\n * The handles `configure()` gets as its second argument, in both modes. The root has no connector, client or transaction to\n * hand out; a family that has them overrides this. Protected: the only ways out are the argument of `configure()` and the\n * boot's private key.\n */\n protected createOpening(): IDataSourceOpening {\n const refuse = (member: string): never =>\n NotSupportedUtility.throwNotSupported({\n scope: this.constructor.name,\n feature: `opening.${member}`,\n logger: this.logger,\n });\n\n return {\n getConnector: () => refuse('getConnector'),\n getClient: () => refuse('getClient'),\n beginTransaction: () => Promise.resolve().then(() => refuse('beginTransaction')),\n };\n }\n\n /**\n * The boot's replacement for `configure()` on a datasource that opens on first use: records the options and opens nothing.\n * Refused for a family that cannot honour it.\n */\n deferOpen(opts: { options?: ConfigurableOptions }): void {\n if (!this.supportsDeferredOpen()) {\n throw getError({\n message: `[${this.constructor.name}][deferOpen] open: 'first-use' is not supported by this datasource family | Use open: { on: 'start' }, or remove the option`,\n });\n }\n\n this.deferredOptions = opts.options;\n }\n\n /**\n * Resolves once the datasource is open. At once for one that opens with the application. Otherwise the first caller\n * starts `configure()` and the rest await the same promise, so it runs once; a failure rejects all of them, undoes what the\n * failed `configure()` left ({@link discardPartialOpen}) and clears the slot, so the next call opens afresh. After\n * `close()` it rejects: a stopped application does not reopen its datasources.\n */\n ensureOpen(): Promise<void> {\n if (!this.isOpenDeferred()) {\n return Promise.resolve();\n }\n\n // Closed first: a call after `close()` is told so, whether or not the datasource had been opened.\n if (this.isShutDown) {\n return Promise.reject(\n getError({\n message: `[${this.constructor.name}][ensureOpen] The datasource is closed | It opens on first use only before close()`,\n }),\n );\n }\n\n if (this.isOpened) {\n return Promise.resolve();\n }\n\n if (this.abandoned) {\n return Promise.reject(\n getError({\n message: `[${this.constructor.name}][ensureOpen] The previous open is still running after its timeout | It is retried once it has settled`,\n }),\n );\n }\n\n this.opening ??= this.runOpen();\n\n return this.opening;\n }\n\n private async runOpen(): Promise<void> {\n const timeoutMs = this.getOpenTimeoutMs();\n const work = Promise.resolve().then(() =>\n this.configure(this.deferredOptions, this.createOpening()),\n );\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expired = new Promise<typeof OPEN_TIMED_OUT>((resolve) => {\n if (timeoutMs > 0) {\n timer = setTimeout(() => resolve(OPEN_TIMED_OUT), timeoutMs);\n }\n });\n\n try {\n const outcome = await Promise.race([work.then(() => OPEN_DONE), expired]);\n\n if (outcome === OPEN_TIMED_OUT) {\n this.abandoned = this.settleAbandoned({ work });\n\n throw getError({\n message: `[${this.constructor.name}][ensureOpen] The open did not finish within ${timeoutMs} ms | Does configure() await the datasource (a repository, ensureOpen)? Use the opening argument inside configure()`,\n });\n }\n\n this.isOpened = true;\n } catch (error) {\n await this.discardOpenAttempt();\n\n throw error;\n } finally {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n\n this.opening = undefined;\n }\n }\n\n /** When an abandoned open finally settles, whatever it built is closed (it was never published) and retries are allowed again. */\n private async settleAbandoned(opts: { work: Promise<unknown> }): Promise<void> {\n try {\n await opts.work;\n // eslint-disable-next-line venizia/no-silent-catch -- the abandoned attempt's own outcome was already reported by the timeout; only its clean-up matters now\n } catch {\n // Falls through to the clean-up.\n }\n\n await this.discardOpenAttempt();\n this.abandoned = undefined;\n }\n\n private async discardOpenAttempt(): Promise<void> {\n try {\n await this.discardPartialOpen();\n // eslint-disable-next-line venizia/no-silent-catch -- the open's own error is what the caller must see: a failed clean-up is logged, never thrown over it\n } catch (cleanupError) {\n this.logger\n .for(this.ensureOpen.name)\n .warn('Clean-up after a failed open also failed | error: %s', cleanupError);\n }\n }\n\n /** Undoes what a `configure()` that threw left behind, so the next open starts clean. The root holds nothing; a family that keeps a client overrides it. */\n protected discardPartialOpen(): ValueOrPromise<void> {}\n\n /**\n * Waits for an open in flight and refuses any later one. A family's `close()` calls it first, so a stop that arrives\n * during the first use closes what that open built instead of racing it.\n */\n protected async settleOpening(): Promise<void> {\n this.isShutDown = true;\n\n try {\n await this.opening;\n // eslint-disable-next-line venizia/no-silent-catch -- the failed open was reported to its own waiters; stopping goes on\n } catch (openError) {\n this.logger\n .for(this.close.name)\n .debug('The open in flight failed while stopping | error: %s', openError);\n }\n }\n\n getSettings() {\n return this.settings;\n }\n\n getSchema(): Schema {\n if (!this.schema) {\n throw getError({\n message: `[${this.constructor.name}] Schema not initialized. Override getSchema() or provide schema in constructor.`,\n });\n }\n\n return this.schema;\n }\n\n /** Capability probe, overridden by connectors that support it (e.g. postgres reports `{ transactions: true }`). */\n getCapabilities(): IDataSourceCapabilities {\n return { transactions: false };\n }\n\n /** Nothing to release at this root; a family that holds a connection overrides it. */\n close(): Promise<void> {\n return Promise.resolve();\n }\n\n /** Defaults to throwing NotSupported - only connectors with real transaction support override this; async so callers get a rejected promise, not a synchronous throw that skips try/catch. */\n async beginTransaction(_opts?: ITransactionOptions): Promise<ITransaction> {\n return NotSupportedUtility.throwNotSupported({\n scope: this.constructor.name,\n feature: 'Transactions',\n logger: this.logger,\n });\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"event-bus.js","sourceRoot":"","sources":["../../../../src/base/events/event-bus.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAG9D,OAAO,EACL,UAAU,EACV,QAAQ,EACR,sBAAsB,EACtB,WAAW,EACX,gBAAgB,GACjB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAqB3E;;;;;;;+EAO+E;AAC/E,MAAM,OAAO,QAAqC,SAAQ,UAAU;IAOlE,YAAY,IAA8C;QACxD,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,IAAI,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC;QAC9C,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;QAChC,IAAI,CAAC,mBAAmB,GAAG,IAAI,GAAG,EAAE,CAAC;IACvC,CAAC;IAED;sGACkG;IAC1F,MAAM,CAAC,oBAAoB,CAAC,IAAkD;QACpF,MAAM,EAAE,WAAW,EAAE,WAAW,EAAE,GAAG,IAAI,CAAC;QAC1C,IAAI,aAAa,GAAG,CAAC,CAAC;QAEtB,KAAK,IAAI,OAAO,GAAG,CAAC,EAAE,OAAO,GAAG,WAAW,EAAE,OAAO,EAAE,EAAE,CAAC;YACvD,aAAa,IAAI,WAAW,CAAC,qBAAqB,CAAC;gBACjD,OAAO;gBACP,OAAO,EAAE;oBACP,QAAQ,EAAE,sBAAsB,CAAC,WAAW;oBAC5C,cAAc,EAAE,WAAW;oBAC3B,MA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AAI,CAAC;YACH,MAAM,WAAW,CAAC,gBAAgB,CAAC;gBACjC,SAAS,EAAE,qBAAqB,KAAK,CAAC,IAAI,EAAE;gBAC5C,WAAW;gBACX,OAAO,EAAE;oBACP,QAAQ,EAAE,sBAAsB,CAAC,WAAW;oBAC5C,cAAc,EAAE,WAAW;oBAC3B,MAAM,EAAE,gBAAgB,CAAC,IAAI;iBAC9B;gBACD,SAAS,EAAE,KAAK,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE;oBAC/B,WAAW,GAAG,OAAO,CAAC;oBACtB,MAAM,aAAa,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;gBACjC,CAAC;aACF,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,4FAA4F;YAC5F,6EAA6E;YAC7E,IAAI,CAAC,MAAM,CAAC,KAAK,CACf,wGAAwG,EACxG,KAAK,CAAC,IAAI,EACV,KAAK,CAAC,OAAO,EACb,WAAW,EACX,WAAW,EACX,KAAK,CACN,CAAC;QACJ,CAAC;IACH,CAAC;CACF","sourcesContent":["import { ObjectUtility } from '@venizia/ignis-helpers/common';\nimport type { Container } from '@/helpers/inversion/container';\nimport type { AnyType, ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport {\n BaseHelper,\n getError,\n RetryBackoffStrategies,\n RetryHelper,\n RetryJitterModes,\n} from '@venizia/ignis-helpers/core';\nimport { EventDispatchRetry, EventHandlerTypes } from './common/constants';\nimport type {\n IDomainEvent,\n IEventHandler,\n IEventHandlerRetryOptions,\n TEventHandlerReference,\n} from './common/types';\n\ntype TEventHandlerInvoker = (opts: { event: IDomainEvent<unknown> }) => ValueOrPromise<void>;\n\n/** One `register`ed handler, resolved to concrete retry numbers and a ready-to-call invoker -\n * `EventDispatchRetry`'s defaults already applied and `handler`'s shape already resolved, so\n * `dispatch` never has to branch on either. */\ninterface IResolvedEventRegistration {\n invokeHandler: TEventHandlerInvoker;\n /** For the exhaustion log line only - a binding key or `<function fn.name>`. */\n description: string;\n maxAttempts: number;\n baseDelayMs: number;\n}\n\n/** In-process, fire-and-forget domain event bus. `TPayloadMap` keys the event names, so a wrong name\n * or payload shape is a compile error. Delivery is always async. Retry timing is a property of the\n * handler's own failure mode, not of the event, so `register` may tune it per registration. But\n * nobody awaits a fire-and-forget dispatch, so an unbounded window would let one event hold a\n * handler - and whatever it holds open, e.g. a database connection - for an unbounded time with no\n * one to report it. What the bus guarantees instead: a bounded MAXIMUM time a single dispatch can\n * occupy, enforced as a hard ceiling at `register()` - see `EventDispatchRetry`. Retry makes\n * delivery at-least-once: handlers must be idempotent, see `IEventHandler`. */\nexport class EventBus<TPayloadMap extends object> extends BaseHelper {\n private readonly container: Container;\n\n /** `register` appends, never replaces - two handlers may share an event name, and replacing would\n * drop the first with no way for the caller to notice. */\n private readonly registrationsByName: Map<string, IResolvedEventRegistration[]>;\n\n constructor(opts: { scope?: string; container: Container }) {\n super({ scope: opts.scope ?? EventBus.name });\n this.container = opts.container;\n this.registrationsByName = new Map();\n }\n\n /** The pre-jitter total of every inter-attempt delay `maxAttempts`/`baseDelayMs` would produce -\n * jitter (always on, see `dispatch`) only ever shrinks a delay, so this is a true upper bound. */\n private static computeTotalWindowMs(opts: { maxAttempts: number; baseDelayMs: number }): number {\n const { maxAttempts, baseDelayMs } = opts;\n let totalWindowMs = 0;\n\n for (let attempt = 1; attempt < maxAttempts; attempt++) {\n totalWindowMs += RetryHelper.computeBackoffDelayMs({\n attempt,\n backoff: {\n strategy: RetryBackoffStrategies.EXPONENTIAL,\n initialDelayMs: baseDelayMs,\n jitter: RetryJitterModes.NONE,\n },\n });\n }\n\n return totalWindowMs;\n }\n\n /** Loud rejection, never a silent clamp: a caller who believes a number the bus does not honour is\n * worse off than one who sees the ceiling at boot. */\n private static assertValidRetry(opts: {\n name: string;\n maxAttempts: number;\n baseDelayMs: number;\n }): void {\n const { name, maxAttempts, baseDelayMs } = opts;\n\n if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {\n throw getError({\n message: `[EventBus][register] retry.maxAttempts must be a positive integer | name: ${name} | Got: ${maxAttempts}`,\n });\n }\n\n if (!Number.isInteger(baseDelayMs) || baseDelayMs < 1) {\n throw getError({\n message: `[EventBus][register] retry.baseDelayMs must be a positive integer | name: ${name} | Got: ${baseDelayMs}`,\n });\n }\n\n if (maxAttempts > EventDispatchRetry.MAX_ATTEMPTS_CEILING) {\n throw getError({\n message: `[EventBus][register] retry.maxAttempts exceeds the ceiling | name: ${name} | Got: ${maxAttempts} | Ceiling: ${EventDispatchRetry.MAX_ATTEMPTS_CEILING} | Lower retry.maxAttempts`,\n });\n }\n\n const totalWindowMs = EventBus.computeTotalWindowMs({ maxAttempts, baseDelayMs });\n\n if (totalWindowMs > EventDispatchRetry.MAX_TOTAL_WINDOW_MS) {\n throw getError({\n message: `[EventBus][register] retry window exceeds the ceiling | name: ${name} | Got: ${totalWindowMs}ms | Ceiling: ${EventDispatchRetry.MAX_TOTAL_WINDOW_MS}ms | Lower retry.maxAttempts or retry.baseDelayMs`,\n });\n }\n }\n\n /**\n * Turns `handler` into a uniform invoker plus a description for the exhaustion log line.\n * `BINDING_KEY` resolves through the container INSIDE the returned closure, so every call re-reads\n * the current binding; `FUNCTION` calls `fn` directly, so the closure IS the resolution - there is\n * nothing left to re-read on a later attempt. The tag (`handler.type`) is what this switches on,\n * not which field happens to be present - see `EventHandlerTypes`' doc.\n */\n private static buildHandlerInvoker(opts: {\n container: Container;\n handler: TEventHandlerReference<AnyType>;\n name: string;\n }): { invokeHandler: TEventHandlerInvoker; description: string } {\n const { container, handler, name } = opts;\n\n if (ObjectUtility.isEmpty({ value: handler })) {\n throw getError({\n message: `[EventBus][register] Invalid handler | name: ${name} | Got: ${handler}`,\n });\n }\n\n switch (handler.type) {\n case EventHandlerTypes.BINDING_KEY: {\n const { key } = handler;\n\n if (ObjectUtility.isEmpty({ value: key })) {\n throw getError({\n message: `[EventBus][register] Invalid handler.key | name: ${name} | Got: ${key}`,\n });\n }\n\n return {\n invokeHandler: ({ event }) => container.get<IEventHandler>({ key }).handle({ event }),\n description: `binding-key:${key}`,\n };\n }\n\n case EventHandlerTypes.FUNCTION: {\n const { fn } = handler;\n\n if (typeof fn !== 'function') {\n throw getError({\n message: `[EventBus][register] Invalid handler.fn | name: ${name} | Expected a function | Got: ${typeof fn}`,\n });\n }\n\n return {\n invokeHandler: ({ event }) => fn({ event }),\n description: `function:${fn.name || 'anonymous'}`,\n };\n }\n\n default: {\n throw getError({\n message: `[EventBus][register] Unknown handler.type | name: ${name} | Expected one of: ${[...EventHandlerTypes.SCHEME_SET].join(', ')} | Got: ${(handler as { type?: unknown }).type}`,\n });\n }\n }\n }\n\n /**\n * `retry` is optional and per REGISTRATION, not per publish: the right window belongs to the\n * handler's own failure mode, and two handlers on the same event name may each pick their own.\n * Omitting it reproduces today's `EventDispatchRetry` defaults exactly. Both `maxAttempts` and the\n * total backoff window it implies are bounded - see `EventDispatchRetry` - and exceeding either\n * throws here, at boot where a human sees it, rather than being silently clamped at dispatch time.\n */\n register<K extends keyof TPayloadMap & string>(opts: {\n name: K;\n /** A `BINDING_KEY` reference re-resolves through the container on every retry attempt, so a\n * rebind reaches a dispatch already in flight. A `FUNCTION` reference is captured as-is: a\n * rebind has nothing to reach, and every attempt in a long retry window calls the exact `fn`\n * registered here. */\n handler: TEventHandlerReference<TPayloadMap[K]>;\n retry?: IEventHandlerRetryOptions;\n }): void {\n const { name, handler, retry } = opts;\n\n if (ObjectUtility.isEmpty({ value: name })) {\n throw getError({\n message: `[EventBus][register] Invalid registration | name: ${String(name)}`,\n });\n }\n\n const maxAttempts = retry?.maxAttempts ?? EventDispatchRetry.MAX_ATTEMPTS;\n const baseDelayMs = retry?.baseDelayMs ?? EventDispatchRetry.BASE_DELAY_MS;\n EventBus.assertValidRetry({ name, maxAttempts, baseDelayMs });\n\n const { invokeHandler, description } = EventBus.buildHandlerInvoker({\n container: this.container,\n handler,\n name,\n });\n\n const registration: IResolvedEventRegistration = {\n invokeHandler,\n description,\n maxAttempts,\n baseDelayMs,\n };\n\n const existing = this.registrationsByName.get(name);\n\n if (existing) {\n existing.push(registration);\n\n return;\n }\n\n this.registrationsByName.set(name, [registration]);\n }\n\n /**\n * Never blocks and never throws back to the caller: dispatch runs outside this call's flow via\n * `queueMicrotask`, and a handler failure is caught and logged where it happens (`dispatch`),\n * never here.\n */\n publish<K extends keyof TPayloadMap & string>(opts: {\n name: K;\n payload: TPayloadMap[K];\n traceId?: string;\n }): void {\n const { name, payload, traceId } = opts;\n\n const event: IDomainEvent<TPayloadMap[K]> = {\n name,\n payload,\n occurredAt: new Date().toISOString(),\n traceId,\n };\n\n const registrations = this.registrationsByName.get(name);\n\n if (!registrations?.length) {\n // A typo is already a compile error, so at runtime this only means nobody is listening yet -\n // a legitimate state on a fire-and-forget bus, not an incident.\n this.logger.debug('[publish] No handler registered | name: %s | traceId: %s', name, traceId);\n\n return;\n }\n\n for (const registration of registrations) {\n queueMicrotask(() => {\n // `dispatch` catches every failure path itself and never rejects - this `.catch` is an\n // unreachable backstop, kept (and logged) rather than left floating, for the day it isn't.\n this.dispatch({ event, registration }).catch((error: unknown) => {\n this.logger.error(\n '[publish] Unexpected dispatch failure | name: %s | Error: %s',\n event.name,\n error,\n );\n });\n });\n }\n }\n\n /**\n * Attempts/backoff come from the registration (`EventDispatchRetry`'s defaults when omitted),\n * always with full jitter - `RetryJitterModes.FULL` decorrelates a shared-resource pile-up hardest,\n * so many handlers retrying the same lock do not collide on the same instant a second and third\n * time. `invokeHandler` already encodes whether that re-resolves (`BINDING_KEY`) or was captured\n * once (`FUNCTION`) - see `buildHandlerInvoker` - so this method calls it uniformly. A handler that\n * throws synchronously is caught exactly like one that returns a rejected promise: `execution`\n * here is itself `async`, and JS converts a synchronous throw inside an async function body into a\n * rejection of that function's own promise - `RetryHelper.executeWithRetry`'s attempt loop never\n * sees the difference.\n *\n * `RetryHelper.executeWithRetry` is used without its own `logger` - its internal per-attempt/exhaustion\n * logging knows nothing about the event name or `traceId`, so it cannot be the trace anyone\n * relies on. The one line below, logged only on final failure, is.\n */\n private async dispatch(opts: {\n event: IDomainEvent<unknown>;\n registration: IResolvedEventRegistration;\n }): Promise<void> {\n const { event, registration } = opts;\n const { invokeHandler, description, maxAttempts, baseDelayMs } = registration;\n let lastAttempt = 0;\n\n try {\n await RetryHelper.executeWithRetry({\n operation: `EventBus.dispatch:${event.name}`,\n maxAttempts,\n backoff: {\n strategy: RetryBackoffStrategies.EXPONENTIAL,\n initialDelayMs: baseDelayMs,\n jitter: RetryJitterModes.FULL,\n },\n execution: async ({ attempt }) => {\n lastAttempt = attempt;\n await invokeHandler({ event });\n },\n });\n } catch (error) {\n // The only trace this failure leaves: it is caught here and never reaches the publisher, so\n // the event name, traceId and attempt count all have to be on this one line.\n this.logger.error(\n '[dispatch] Handler exhausted retries | name: %s | traceId: %s | attempts: %d | handler: %s | Error: %s',\n event.name,\n event.traceId,\n lastAttempt,\n description,\n error,\n );\n }\n }\n}\n"]}
1
+ {"version":3,"file":"event-bus.js","sourceRoot":"","sources":["../../../../src/base/events/event-bus.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAG9D,OAAO,EACL,UAAU,EACV,QAAQ,EACR,sBAAsB,EACtB,WAAW,EACX,gBAAgB,GACjB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAoB3E;;;;;;;+EAO+E;AAC/E,MAAM,OAAO,QAAqC,SAAQ,UAAU;IAOlE,YAAY,IAA8C;QACxD,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,IAAI,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC;QAC9C,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;QAChC,IAAI,CAAC,mBAAmB,GAAG,IAAI,GAAG,EAAE,CAAC;IACvC,CAAC;IAED;sGACkG;IAC1F,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DAA8D,EAC9D,KAAK,CAAC,IAAI,EACV,KAAK,CACN,CAAC;gBACJ,CAAC,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED;;;;;;;;;;;;;;OAcG;IACK,KAAK,CAAC,QAAQ,CAAC,IAGtB;QACC,MAAM,EAAE,KAAK,EAAE,YAAY,EAAE,GAAG,IAAI,CAAC;QACrC,MAAM,EAAE,aAAa,EAAE,WAAW,EAAE,WAAW,EAAE,WAAW,EAAE,GAAG,YAAY,CAAC;QAC9E,IAAI,WAAW,GAAG,CAAC,CAAC;QAEpB,IAAI,CAAC;YACH,MAAM,WAAW,CAAC,gBAAgB,CAAC;gBACjC,SAAS,EAAE,qBAAqB,KAAK,CAAC,IAAI,EAAE;gBAC5C,WAAW;gBACX,OAAO,EAAE;oBACP,QAAQ,EAAE,sBAAsB,CAAC,WAAW;oBAC5C,cAAc,EAAE,WAAW;oBAC3B,MAAM,EAAE,gBAAgB,CAAC,IAAI;iBAC9B;gBACD,SAAS,EAAE,KAAK,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE;oBAC/B,WAAW,GAAG,OAAO,CAAC;oBACtB,MAAM,aAAa,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;gBACjC,CAAC;aACF,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,4FAA4F;YAC5F,6EAA6E;YAC7E,IAAI,CAAC,MAAM,CAAC,KAAK,CACf,wGAAwG,EACxG,KAAK,CAAC,IAAI,EACV,KAAK,CAAC,OAAO,EACb,WAAW,EACX,WAAW,EACX,KAAK,CACN,CAAC;QACJ,CAAC;IACH,CAAC;CACF","sourcesContent":["import { ObjectUtility } from '@venizia/ignis-helpers/common';\nimport type { Container } from '@/helpers/inversion/container';\nimport type { ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport {\n BaseHelper,\n getError,\n RetryBackoffStrategies,\n RetryHelper,\n RetryJitterModes,\n} from '@venizia/ignis-helpers/core';\nimport { EventDispatchRetry, EventHandlerTypes } from './common/constants';\nimport type {\n IDomainEvent,\n IEventHandler,\n IEventHandlerRetryOptions,\n TEventHandlerReference,\n} from './common/types';\n\n/** One `register`ed handler, resolved to concrete retry numbers and a ready-to-call invoker -\n * `EventDispatchRetry`'s defaults already applied and `handler`'s shape already resolved, so\n * `dispatch` never has to branch on either. */\ninterface IResolvedEventRegistration {\n // A method signature on purpose: its parameter is bivariant, so a registration holds the invoker of any payload type, which the registry cannot tell apart.\n invokeHandler(opts: { event: IDomainEvent<unknown> }): ValueOrPromise<void>;\n /** For the exhaustion log line only - a binding key or `<function fn.name>`. */\n description: string;\n maxAttempts: number;\n baseDelayMs: number;\n}\n\n/** In-process, fire-and-forget domain event bus. `TPayloadMap` keys the event names, so a wrong name\n * or payload shape is a compile error. Delivery is always async. Retry timing is a property of the\n * handler's own failure mode, not of the event, so `register` may tune it per registration. But\n * nobody awaits a fire-and-forget dispatch, so an unbounded window would let one event hold a\n * handler - and whatever it holds open, e.g. a database connection - for an unbounded time with no\n * one to report it. What the bus guarantees instead: a bounded MAXIMUM time a single dispatch can\n * occupy, enforced as a hard ceiling at `register()` - see `EventDispatchRetry`. Retry makes\n * delivery at-least-once: handlers must be idempotent, see `IEventHandler`. */\nexport class EventBus<TPayloadMap extends object> extends BaseHelper {\n private readonly container: Container;\n\n /** `register` appends, never replaces - two handlers may share an event name, and replacing would\n * drop the first with no way for the caller to notice. */\n private readonly registrationsByName: Map<string, IResolvedEventRegistration[]>;\n\n constructor(opts: { scope?: string; container: Container }) {\n super({ scope: opts.scope ?? EventBus.name });\n this.container = opts.container;\n this.registrationsByName = new Map();\n }\n\n /** The pre-jitter total of every inter-attempt delay `maxAttempts`/`baseDelayMs` would produce -\n * jitter (always on, see `dispatch`) only ever shrinks a delay, so this is a true upper bound. */\n private static computeTotalWindowMs(opts: { maxAttempts: number; baseDelayMs: number }): number {\n const { maxAttempts, baseDelayMs } = opts;\n let totalWindowMs = 0;\n\n for (let attempt = 1; attempt < maxAttempts; attempt++) {\n totalWindowMs += RetryHelper.computeBackoffDelayMs({\n attempt,\n backoff: {\n strategy: RetryBackoffStrategies.EXPONENTIAL,\n initialDelayMs: baseDelayMs,\n jitter: RetryJitterModes.NONE,\n },\n });\n }\n\n return totalWindowMs;\n }\n\n /** Loud rejection, never a silent clamp: a caller who believes a number the bus does not honour is\n * worse off than one who sees the ceiling at boot. */\n private static assertValidRetry(opts: {\n name: string;\n maxAttempts: number;\n baseDelayMs: number;\n }): void {\n const { name, maxAttempts, baseDelayMs } = opts;\n\n if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {\n throw getError({\n message: `[EventBus][register] retry.maxAttempts must be a positive integer | name: ${name} | Got: ${maxAttempts}`,\n });\n }\n\n if (!Number.isInteger(baseDelayMs) || baseDelayMs < 1) {\n throw getError({\n message: `[EventBus][register] retry.baseDelayMs must be a positive integer | name: ${name} | Got: ${baseDelayMs}`,\n });\n }\n\n if (maxAttempts > EventDispatchRetry.MAX_ATTEMPTS_CEILING) {\n throw getError({\n message: `[EventBus][register] retry.maxAttempts exceeds the ceiling | name: ${name} | Got: ${maxAttempts} | Ceiling: ${EventDispatchRetry.MAX_ATTEMPTS_CEILING} | Lower retry.maxAttempts`,\n });\n }\n\n const totalWindowMs = EventBus.computeTotalWindowMs({ maxAttempts, baseDelayMs });\n\n if (totalWindowMs > EventDispatchRetry.MAX_TOTAL_WINDOW_MS) {\n throw getError({\n message: `[EventBus][register] retry window exceeds the ceiling | name: ${name} | Got: ${totalWindowMs}ms | Ceiling: ${EventDispatchRetry.MAX_TOTAL_WINDOW_MS}ms | Lower retry.maxAttempts or retry.baseDelayMs`,\n });\n }\n }\n\n /**\n * Turns `handler` into a uniform invoker plus a description for the exhaustion log line.\n * `BINDING_KEY` resolves through the container INSIDE the returned closure, so every call re-reads\n * the current binding; `FUNCTION` calls `fn` directly, so the closure IS the resolution - there is\n * nothing left to re-read on a later attempt. The tag (`handler.type`) is what this switches on,\n * not which field happens to be present - see `EventHandlerTypes`' doc.\n */\n private static buildHandlerInvoker<TPayload>(opts: {\n container: Container;\n handler: TEventHandlerReference<TPayload>;\n name: string;\n }): {\n invokeHandler: (opts: { event: IDomainEvent<TPayload> }) => ValueOrPromise<void>;\n description: string;\n } {\n const { container, handler, name } = opts;\n\n if (ObjectUtility.isEmpty({ value: handler })) {\n throw getError({\n message: `[EventBus][register] Invalid handler | name: ${name} | Got: ${handler}`,\n });\n }\n\n switch (handler.type) {\n case EventHandlerTypes.BINDING_KEY: {\n const { key } = handler;\n\n if (ObjectUtility.isEmpty({ value: key })) {\n throw getError({\n message: `[EventBus][register] Invalid handler.key | name: ${name} | Got: ${key}`,\n });\n }\n\n return {\n invokeHandler: ({ event }) => container.get<IEventHandler>({ key }).handle({ event }),\n description: `binding-key:${key}`,\n };\n }\n\n case EventHandlerTypes.FUNCTION: {\n const { fn } = handler;\n\n if (typeof fn !== 'function') {\n throw getError({\n message: `[EventBus][register] Invalid handler.fn | name: ${name} | Expected a function | Got: ${typeof fn}`,\n });\n }\n\n return {\n invokeHandler: ({ event }) => fn({ event }),\n description: `function:${fn.name || 'anonymous'}`,\n };\n }\n\n default: {\n throw getError({\n message: `[EventBus][register] Unknown handler.type | name: ${name} | Expected one of: ${[...EventHandlerTypes.SCHEME_SET].join(', ')} | Got: ${(handler as { type?: unknown }).type}`,\n });\n }\n }\n }\n\n /**\n * `retry` is optional and per REGISTRATION, not per publish: the right window belongs to the\n * handler's own failure mode, and two handlers on the same event name may each pick their own.\n * Omitting it reproduces today's `EventDispatchRetry` defaults exactly. Both `maxAttempts` and the\n * total backoff window it implies are bounded - see `EventDispatchRetry` - and exceeding either\n * throws here, at boot where a human sees it, rather than being silently clamped at dispatch time.\n */\n register<K extends keyof TPayloadMap & string>(opts: {\n name: K;\n /** A `BINDING_KEY` reference re-resolves through the container on every retry attempt, so a\n * rebind reaches a dispatch already in flight. A `FUNCTION` reference is captured as-is: a\n * rebind has nothing to reach, and every attempt in a long retry window calls the exact `fn`\n * registered here. */\n handler: TEventHandlerReference<TPayloadMap[K]>;\n retry?: IEventHandlerRetryOptions;\n }): void {\n const { name, handler, retry } = opts;\n\n if (ObjectUtility.isEmpty({ value: name })) {\n throw getError({\n message: `[EventBus][register] Invalid registration | name: ${String(name)}`,\n });\n }\n\n const maxAttempts = retry?.maxAttempts ?? EventDispatchRetry.MAX_ATTEMPTS;\n const baseDelayMs = retry?.baseDelayMs ?? EventDispatchRetry.BASE_DELAY_MS;\n EventBus.assertValidRetry({ name, maxAttempts, baseDelayMs });\n\n const { invokeHandler, description } = EventBus.buildHandlerInvoker({\n container: this.container,\n handler,\n name,\n });\n\n const registration: IResolvedEventRegistration = {\n invokeHandler,\n description,\n maxAttempts,\n baseDelayMs,\n };\n\n const existing = this.registrationsByName.get(name);\n\n if (existing) {\n existing.push(registration);\n\n return;\n }\n\n this.registrationsByName.set(name, [registration]);\n }\n\n /**\n * Never blocks and never throws back to the caller: dispatch runs outside this call's flow via\n * `queueMicrotask`, and a handler failure is caught and logged where it happens (`dispatch`),\n * never here.\n */\n publish<K extends keyof TPayloadMap & string>(opts: {\n name: K;\n payload: TPayloadMap[K];\n traceId?: string;\n }): void {\n const { name, payload, traceId } = opts;\n\n const event: IDomainEvent<TPayloadMap[K]> = {\n name,\n payload,\n occurredAt: new Date().toISOString(),\n traceId,\n };\n\n const registrations = this.registrationsByName.get(name);\n\n if (!registrations?.length) {\n // A typo is already a compile error, so at runtime this only means nobody is listening yet -\n // a legitimate state on a fire-and-forget bus, not an incident.\n this.logger.debug('[publish] No handler registered | name: %s | traceId: %s', name, traceId);\n\n return;\n }\n\n for (const registration of registrations) {\n queueMicrotask(() => {\n // `dispatch` catches every failure path itself and never rejects - this `.catch` is an\n // unreachable backstop, kept (and logged) rather than left floating, for the day it isn't.\n this.dispatch({ event, registration }).catch((error: unknown) => {\n this.logger.error(\n '[publish] Unexpected dispatch failure | name: %s | Error: %s',\n event.name,\n error,\n );\n });\n });\n }\n }\n\n /**\n * Attempts/backoff come from the registration (`EventDispatchRetry`'s defaults when omitted),\n * always with full jitter - `RetryJitterModes.FULL` decorrelates a shared-resource pile-up hardest,\n * so many handlers retrying the same lock do not collide on the same instant a second and third\n * time. `invokeHandler` already encodes whether that re-resolves (`BINDING_KEY`) or was captured\n * once (`FUNCTION`) - see `buildHandlerInvoker` - so this method calls it uniformly. A handler that\n * throws synchronously is caught exactly like one that returns a rejected promise: `execution`\n * here is itself `async`, and JS converts a synchronous throw inside an async function body into a\n * rejection of that function's own promise - `RetryHelper.executeWithRetry`'s attempt loop never\n * sees the difference.\n *\n * `RetryHelper.executeWithRetry` is used without its own `logger` - its internal per-attempt/exhaustion\n * logging knows nothing about the event name or `traceId`, so it cannot be the trace anyone\n * relies on. The one line below, logged only on final failure, is.\n */\n private async dispatch(opts: {\n event: IDomainEvent<unknown>;\n registration: IResolvedEventRegistration;\n }): Promise<void> {\n const { event, registration } = opts;\n const { invokeHandler, description, maxAttempts, baseDelayMs } = registration;\n let lastAttempt = 0;\n\n try {\n await RetryHelper.executeWithRetry({\n operation: `EventBus.dispatch:${event.name}`,\n maxAttempts,\n backoff: {\n strategy: RetryBackoffStrategies.EXPONENTIAL,\n initialDelayMs: baseDelayMs,\n jitter: RetryJitterModes.FULL,\n },\n execution: async ({ attempt }) => {\n lastAttempt = attempt;\n await invokeHandler({ event });\n },\n });\n } catch (error) {\n // The only trace this failure leaves: it is caught here and never reaches the publisher, so\n // the event name, traceId and attempt count all have to be on this one line.\n this.logger.error(\n '[dispatch] Handler exhausted retries | name: %s | traceId: %s | attempts: %d | handler: %s | Error: %s',\n event.name,\n event.traceId,\n lastAttempt,\n description,\n error,\n );\n }\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  export * from './injectable.js';
2
2
  export * from './injectors.js';
3
- export * from './persistents.js';
3
+ export * from './persistents/index.js';
4
4
  export * from './routes/index.js';
5
5
  //# sourceMappingURL=index.d.ts.map
@@ -1,5 +1,5 @@
1
1
  export * from './injectable.js';
2
2
  export * from './injectors.js';
3
- export * from './persistents.js';
3
+ export * from './persistents/index.js';
4
4
  export * from './routes/index.js';
5
5
  //# sourceMappingURL=index.js.map
@@ -11,6 +11,6 @@ export type TInjectOptions = TWithoutRegistry<TCoreInjectOptions>;
11
11
  * `MetadataRegistry.getInstance()` (`helpers/inversion/container.ts`), while inversion's own
12
12
  * `inject` writes to its module-level registry - metadata written there is never read back.
13
13
  */
14
- export declare const inject: (opts: TInjectOptions) => (target: any, propertyName: string | symbol | undefined, parameterIndex?: number) => void;
14
+ export declare const inject: (opts: TInjectOptions) => (target: object, propertyName: string | symbol | undefined, parameterIndex?: number) => void;
15
15
  export {};
16
16
  //# sourceMappingURL=injectors.d.ts.map
@@ -0,0 +1,21 @@
1
+ import type { IDataSourceMetadata } from '../../../helpers/inversion/index.js';
2
+ /**
3
+ * Registers a datasource with driver and auto-discovery settings.
4
+ *
5
+ * @example
6
+ * ```typescript
7
+ * import { datasource } from '@venizia/ignis';
8
+ * import { BasePostgresDataSource } from '@venizia/ignis-connectors/postgres';
9
+ * import { NodePostgresDriver } from '@venizia/ignis-connectors/postgres/node-postgres';
10
+ * import { Pool } from 'pg';
11
+ *
12
+ * export @datasource({ driver: NodePostgresDriver })
13
+ * class AppDataSource extends BasePostgresDataSource<{ connectionString: string }> {
14
+ * constructor() { super({ name: AppDataSource.name, config: { connectionString: 'postgres://localhost/app' } }); }
15
+ * override configure(): void { this.client = new Pool(this.settings); }
16
+ * override getConnectionString(): string { return this.settings.connectionString; }
17
+ * }
18
+ * ```
19
+ */
20
+ export declare const datasource: (metadata?: IDataSourceMetadata) => ClassDecorator;
21
+ //# sourceMappingURL=datasource.d.ts.map
@@ -0,0 +1,46 @@
1
+ import { ArtifactTypes, MetadataRegistry } from '../../../helpers/inversion/index.js';
2
+ import { getError } from '@venizia/ignis-helpers/core';
3
+ import { DataSourceOpenModes } from '../../datasources/index.js';
4
+ import { injectable, InjectableUtility } from '../injectable.js';
5
+ /**
6
+ * Registers a datasource with driver and auto-discovery settings.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * import { datasource } from '@venizia/ignis';
11
+ * import { BasePostgresDataSource } from '@venizia/ignis-connectors/postgres';
12
+ * import { NodePostgresDriver } from '@venizia/ignis-connectors/postgres/node-postgres';
13
+ * import { Pool } from 'pg';
14
+ *
15
+ * export @datasource({ driver: NodePostgresDriver })
16
+ * class AppDataSource extends BasePostgresDataSource<{ connectionString: string }> {
17
+ * constructor() { super({ name: AppDataSource.name, config: { connectionString: 'postgres://localhost/app' } }); }
18
+ * override configure(): void { this.client = new Pool(this.settings); }
19
+ * override getConnectionString(): string { return this.settings.connectionString; }
20
+ * }
21
+ * ```
22
+ */
23
+ export const datasource = (metadata) => {
24
+ return (target) => {
25
+ const openTimeout = metadata?.open?.timeoutMs;
26
+ if (openTimeout !== undefined &&
27
+ (typeof openTimeout !== 'number' || !Number.isInteger(openTimeout) || openTimeout < 0)) {
28
+ throw getError({
29
+ message: `[datasource][@datasource][${target.name}] Invalid metadata | 'open.timeoutMs' must be a non-negative integer (ms; 0 waits for ever) | Got: ${String(openTimeout)}`,
30
+ });
31
+ }
32
+ const openMode = metadata?.open?.on;
33
+ // Untyped JS callers: a misspelt mode would silently mean "start", so it is refused where it is written.
34
+ if (openMode !== undefined && !DataSourceOpenModes.isValid(openMode)) {
35
+ throw getError({
36
+ message: `[datasource][@datasource][${target.name}] Invalid metadata | Unknown 'open.on': ${String(openMode)} | Expected one of: ${[...DataSourceOpenModes.SCHEME_SET].join(', ')}`,
37
+ });
38
+ }
39
+ injectable({
40
+ type: ArtifactTypes.DATASOURCE,
41
+ ...InjectableUtility.pickRegistrationOptions({ metadata: metadata ?? {} }),
42
+ })(target);
43
+ MetadataRegistry.getInstance().setDataSourceMetadata({ target, metadata });
44
+ };
45
+ };
46
+ //# sourceMappingURL=datasource.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"datasource.js","sourceRoot":"","sources":["../../../../../src/base/metadata/persistents/datasource.ts"],"names":[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AAQ,IAAI,EAAE,EAAE,CAAC;SAC3E,CAAC,CAAC,MAAM,CAAC,CAAC;QACX,gBAAgB,CAAC,WAAW,EAAE,CAAC,qBAAqB,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC;IAC7E,CAAC,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import { ArtifactTypes, MetadataRegistry } from '@/helpers/inversion';\nimport type { IDataSourceMetadata } from '@/helpers/inversion';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { DataSourceOpenModes } from '../../datasources';\nimport { injectable, InjectableUtility } from '../injectable';\n\n/**\n * Registers a datasource with driver and auto-discovery settings.\n *\n * @example\n * ```typescript\n * import { datasource } from '@venizia/ignis';\n * import { BasePostgresDataSource } from '@venizia/ignis-connectors/postgres';\n * import { NodePostgresDriver } from '@venizia/ignis-connectors/postgres/node-postgres';\n * import { Pool } from 'pg';\n *\n * export @datasource({ driver: NodePostgresDriver })\n * class AppDataSource extends BasePostgresDataSource<{ connectionString: string }> {\n * constructor() { super({ name: AppDataSource.name, config: { connectionString: 'postgres://localhost/app' } }); }\n * override configure(): void { this.client = new Pool(this.settings); }\n * override getConnectionString(): string { return this.settings.connectionString; }\n * }\n * ```\n */\nexport const datasource = (metadata?: IDataSourceMetadata): ClassDecorator => {\n return (target) => {\n const openTimeout = metadata?.open?.timeoutMs;\n\n if (\n openTimeout !== undefined &&\n (typeof openTimeout !== 'number' || !Number.isInteger(openTimeout) || openTimeout < 0)\n ) {\n throw getError({\n message: `[datasource][@datasource][${target.name}] Invalid metadata | 'open.timeoutMs' must be a non-negative integer (ms; 0 waits for ever) | Got: ${String(openTimeout)}`,\n });\n }\n\n const openMode = metadata?.open?.on;\n\n // Untyped JS callers: a misspelt mode would silently mean \"start\", so it is refused where it is written.\n if (openMode !== undefined && !DataSourceOpenModes.isValid(openMode)) {\n throw getError({\n message: `[datasource][@datasource][${target.name}] Invalid metadata | Unknown 'open.on': ${String(openMode)} | Expected one of: ${[...DataSourceOpenModes.SCHEME_SET].join(', ')}`,\n });\n }\n\n injectable({\n type: ArtifactTypes.DATASOURCE,\n ...InjectableUtility.pickRegistrationOptions({ metadata: metadata ?? {} }),\n })(target);\n MetadataRegistry.getInstance().setDataSourceMetadata({ target, metadata });\n };\n};\n"]}
@@ -0,0 +1,5 @@
1
+ import 'reflect-metadata';
2
+ export * from './datasource.js';
3
+ export * from './model.js';
4
+ export * from './repository/index.js';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,5 @@
1
+ import 'reflect-metadata';
2
+ export * from './datasource.js';
3
+ export * from './model.js';
4
+ export * from './repository/index.js';
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/base/metadata/persistents/index.ts"],"names":[],"mappings":"AAAA,OAAO,kBAAkB,CAAC;AAE1B,cAAc,cAAc,CAAC;AAC7B,cAAc,SAAS,CAAC;AACxB,cAAc,cAAc,CAAC","sourcesContent":["import 'reflect-metadata';\n\nexport * from './datasource';\nexport * from './model';\nexport * from './repository';\n"]}
@@ -0,0 +1,18 @@
1
+ import type { IModelMetadata } from '../../../helpers/inversion/index.js';
2
+ /**
3
+ * Registers a model class with its static schema and relations.
4
+ *
5
+ * @example
6
+ * ```typescript
7
+ * import { model } from '@venizia/ignis';
8
+ * import { ModelFactory } from '@venizia/ignis-connectors/postgres';
9
+ * import { pgTable, serial, text } from 'drizzle-orm/pg-core';
10
+ *
11
+ * const noteTable = pgTable('Note', { id: serial('id').primaryKey(), body: text('body') });
12
+ *
13
+ * export @model({ settings: { query: { limit: { default: 20 } } } })
14
+ * class Note extends ModelFactory.defineEntity({ table: noteTable }) {}
15
+ * ```
16
+ */
17
+ export declare const model: (input?: IModelMetadata) => ClassDecorator;
18
+ //# sourceMappingURL=model.d.ts.map
@@ -0,0 +1,64 @@
1
+ import { ArtifactTypes, MetadataRegistry } from '../../../helpers/inversion/index.js';
2
+ import { getError } from '@venizia/ignis-helpers/core';
3
+ import { injectable, InjectableUtility } from '../injectable.js';
4
+ import { ModelMetadataUtility } from '../model-metadata.js';
5
+ /**
6
+ * Registers a model class with its static schema and relations.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * import { model } from '@venizia/ignis';
11
+ * import { ModelFactory } from '@venizia/ignis-connectors/postgres';
12
+ * import { pgTable, serial, text } from 'drizzle-orm/pg-core';
13
+ *
14
+ * const noteTable = pgTable('Note', { id: serial('id').primaryKey(), body: text('body') });
15
+ *
16
+ * export @model({ settings: { query: { limit: { default: 20 } } } })
17
+ * class Note extends ModelFactory.defineEntity({ table: noteTable }) {}
18
+ * ```
19
+ */
20
+ export const model = (input = {}) => {
21
+ return (target) => {
22
+ injectable({
23
+ type: ArtifactTypes.MODEL,
24
+ ...InjectableUtility.pickRegistrationOptions({ metadata: input }),
25
+ })(target);
26
+ const metadata = ModelMetadataUtility.normalizeModelMetadata({
27
+ model: target.name,
28
+ metadata: input,
29
+ });
30
+ const { settings } = metadata;
31
+ if (settings && Reflect.has(settings, 'hiddenProperties')) {
32
+ throw getError({
33
+ message: `[model][${target.name}] hiddenProperties was replaced by properties.hidden`,
34
+ });
35
+ }
36
+ const defaultLimit = settings?.query?.limit?.default;
37
+ if (defaultLimit !== undefined && (!Number.isInteger(defaultLimit) || defaultLimit <= 0)) {
38
+ throw getError({
39
+ message: `[model][${target.name}] Invalid 'query.limit.default' | Expected a positive integer | Got: ${defaultLimit}`,
40
+ });
41
+ }
42
+ // Validated at DECORATION time, like the default limit: a bad ceiling is a wiring mistake, and
43
+ // catching it at boot beats catching it on the one request that happens to reach the limit.
44
+ const maxLimit = settings?.query?.limit?.max;
45
+ if (maxLimit !== undefined && (!Number.isInteger(maxLimit) || maxLimit <= 0)) {
46
+ throw getError({
47
+ message: `[model][${target.name}] Invalid 'query.limit.max' | Expected a positive integer | Got: ${maxLimit}`,
48
+ });
49
+ }
50
+ // Auto-populate AUTHORIZATION_SUBJECT from authorize.principal if not already set
51
+ const principal = settings?.authorize?.principal;
52
+ if (principal && !Object.hasOwn(target, 'AUTHORIZATION_SUBJECT')) {
53
+ // Assigning to a read-only or getter-only inherited property, or on a non-extensible class, threw;
54
+ // `Reflect.set` only answers false, so keep the throw.
55
+ if (!Reflect.set(target, 'AUTHORIZATION_SUBJECT', principal)) {
56
+ throw getError({
57
+ message: `[model][${target.name}] Cannot set 'AUTHORIZATION_SUBJECT' | The class has a read-only or getter-only 'AUTHORIZATION_SUBJECT', or is not extensible`,
58
+ });
59
+ }
60
+ }
61
+ MetadataRegistry.getInstance().registerModel({ target, metadata });
62
+ };
63
+ };
64
+ //# sourceMappingURL=model.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model.js","sourceRoot":"","sources":["../../../../../src/base/metadata/persistents/model.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEtE,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAC9D,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAEzD;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,MAAM,KAAK,GAAG,CAAC,QAAwB,EAAE,EAAkB,EAAE;IAClE,OAAO,CAAC,MAAM,EAAE,EAAE;QAChB,UAAU,CAAC;YACT,IAAI,EAAE,aAAa,CAAC,KAAK;YACzB,GAAG,iBAAiB,CAAC,uBAAuB,CAAC,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;SAClE,CAAC,CAAC,MAAM,CAAC,CAAC;QAEX,MAAM,QAAQ,GAAG,oBAAoB,CAAC,sBAAsB,CAAC;YAC3D,KAAK,EAAE,MAAM,CAAC,IAAI;YAClB,QAAQ,EAAE,KAAK;SAChB,CAAC,CAAC;QAEH,MAAM,EAAE,QAAQ,EAAE,GAAG,QAAQ,CAAC;QAE9B,IAAI,Q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AC,CAAC;YACL,CAAC;QACH,CAAC;QAED,gBAAgB,CAAC,WAAW,EAAE,CAAC,aAAa,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC;IACrE,CAAC,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import { ArtifactTypes, MetadataRegistry } from '@/helpers/inversion';\nimport type { IModelMetadata } from '@/helpers/inversion';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { injectable, InjectableUtility } from '../injectable';\nimport { ModelMetadataUtility } from '../model-metadata';\n\n/**\n * Registers a model class with its static schema and relations.\n *\n * @example\n * ```typescript\n * import { model } from '@venizia/ignis';\n * import { ModelFactory } from '@venizia/ignis-connectors/postgres';\n * import { pgTable, serial, text } from 'drizzle-orm/pg-core';\n *\n * const noteTable = pgTable('Note', { id: serial('id').primaryKey(), body: text('body') });\n *\n * export @model({ settings: { query: { limit: { default: 20 } } } })\n * class Note extends ModelFactory.defineEntity({ table: noteTable }) {}\n * ```\n */\nexport const model = (input: IModelMetadata = {}): ClassDecorator => {\n return (target) => {\n injectable({\n type: ArtifactTypes.MODEL,\n ...InjectableUtility.pickRegistrationOptions({ metadata: input }),\n })(target);\n\n const metadata = ModelMetadataUtility.normalizeModelMetadata({\n model: target.name,\n metadata: input,\n });\n\n const { settings } = metadata;\n\n if (settings && Reflect.has(settings, 'hiddenProperties')) {\n throw getError({\n message: `[model][${target.name}] hiddenProperties was replaced by properties.hidden`,\n });\n }\n\n const defaultLimit = settings?.query?.limit?.default;\n\n if (defaultLimit !== undefined && (!Number.isInteger(defaultLimit) || defaultLimit <= 0)) {\n throw getError({\n message: `[model][${target.name}] Invalid 'query.limit.default' | Expected a positive integer | Got: ${defaultLimit}`,\n });\n }\n\n // Validated at DECORATION time, like the default limit: a bad ceiling is a wiring mistake, and\n // catching it at boot beats catching it on the one request that happens to reach the limit.\n const maxLimit = settings?.query?.limit?.max;\n\n if (maxLimit !== undefined && (!Number.isInteger(maxLimit) || maxLimit <= 0)) {\n throw getError({\n message: `[model][${target.name}] Invalid 'query.limit.max' | Expected a positive integer | Got: ${maxLimit}`,\n });\n }\n\n // Auto-populate AUTHORIZATION_SUBJECT from authorize.principal if not already set\n const principal = settings?.authorize?.principal;\n\n if (principal && !Object.hasOwn(target, 'AUTHORIZATION_SUBJECT')) {\n // Assigning to a read-only or getter-only inherited property, or on a non-extensible class, threw;\n // `Reflect.set` only answers false, so keep the throw.\n if (!Reflect.set(target, 'AUTHORIZATION_SUBJECT', principal)) {\n throw getError({\n message: `[model][${target.name}] Cannot set 'AUTHORIZATION_SUBJECT' | The class has a read-only or getter-only 'AUTHORIZATION_SUBJECT', or is not extensible`,\n });\n }\n }\n\n MetadataRegistry.getInstance().registerModel({ target, metadata });\n };\n};\n"]}
@@ -0,0 +1,19 @@
1
+ import type { TRepositoryMetadata } from '../../../../helpers/inversion/index.js';
2
+ import type { IDataSource } from '../../../datasources/index.js';
3
+ import type { AbstractEntity } from '../../../models/index.js';
4
+ /**
5
+ * Class decorator that registers a repository and binds it to a model (or, for a remote repository, only a datasource). Called without arguments on a subclass it reuses the type, model and datasource of its nearest decorated parent; registration options are not inherited.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * import { repository } from '@venizia/ignis';
10
+ * import { DefaultCRUDRepository } from '@venizia/ignis-connectors/postgres';
11
+ * import { AppDataSource } from './app.datasource';
12
+ * import { Note, noteTable } from './note.model';
13
+ *
14
+ * export @repository({ model: Note, dataSource: AppDataSource })
15
+ * class NoteRepository extends DefaultCRUDRepository<typeof noteTable> {}
16
+ * ```
17
+ */
18
+ export declare const repository: <Model extends AbstractEntity = AbstractEntity, DataSource extends IDataSource = IDataSource>(metadata?: TRepositoryMetadata<Model, DataSource>) => ClassDecorator;
19
+ //# sourceMappingURL=index.d.ts.map