@tstdl/base 0.92.123 → 0.92.125

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 (221) hide show
  1. package/ai/ai-file.service.js +23 -18
  2. package/ai/ai.service.d.ts +4 -12
  3. package/ai/ai.service.js +79 -147
  4. package/ai/functions.d.ts +1 -1
  5. package/ai/types.d.ts +3 -1
  6. package/api/server/gateway.js +6 -6
  7. package/authentication/authentication.api.js +24 -24
  8. package/authentication/server/authentication.service.js +20 -20
  9. package/browser/page-controller.js +1 -1
  10. package/context/context.js +5 -5
  11. package/document-management/api/document-management.api.d.ts +60 -215
  12. package/document-management/api/document-management.api.js +32 -68
  13. package/document-management/models/document-assignment-scope.model.d.ts +11 -0
  14. package/document-management/models/{document-request-assignment-task-collection.model.js → document-assignment-scope.model.js} +14 -10
  15. package/document-management/models/document-assignment-task.model.d.ts +13 -0
  16. package/document-management/models/document-assignment-task.model.js +38 -0
  17. package/document-management/models/document-category.model.d.ts +2 -0
  18. package/document-management/models/document-category.model.js +7 -1
  19. package/document-management/models/{document-collection-document.model.d.ts → document-collection-assignment.model.d.ts} +1 -1
  20. package/document-management/models/{document-collection-document.model.js → document-collection-assignment.model.js} +7 -7
  21. package/document-management/models/document-collection.model.d.ts +2 -0
  22. package/document-management/models/document-collection.model.js +10 -0
  23. package/document-management/models/document-property-value.model.d.ts +3 -11
  24. package/document-management/models/document-property-value.model.js +15 -46
  25. package/document-management/models/document-property.model.d.ts +2 -1
  26. package/document-management/models/document-property.model.js +2 -2
  27. package/document-management/models/document-request-submission.model.d.ts +7 -0
  28. package/document-management/models/document-request-submission.model.js +34 -0
  29. package/document-management/models/document-request-template.d.ts +2 -4
  30. package/document-management/models/document-request-template.js +3 -8
  31. package/document-management/models/document-request.model.d.ts +14 -6
  32. package/document-management/models/document-request.model.js +22 -12
  33. package/document-management/models/document-type-validation.model.d.ts +6 -0
  34. package/document-management/models/document-type-validation.model.js +34 -0
  35. package/document-management/models/document-type.model.d.ts +0 -1
  36. package/document-management/models/document-type.model.js +0 -5
  37. package/document-management/models/document-validation-definition.model.d.ts +10 -0
  38. package/document-management/models/document-validation-definition.model.js +39 -0
  39. package/document-management/models/document-validation-execution-related-document.model.d.ts +7 -0
  40. package/document-management/models/document-validation-execution-related-document.model.js +34 -0
  41. package/document-management/models/document-validation-execution.model.d.ts +26 -0
  42. package/document-management/models/document-validation-execution.model.js +72 -0
  43. package/document-management/models/document-workflow.model.d.ts +35 -0
  44. package/document-management/models/document-workflow.model.js +70 -0
  45. package/document-management/models/document.model.d.ts +12 -1
  46. package/document-management/models/document.model.js +21 -5
  47. package/document-management/models/index.d.ts +10 -5
  48. package/document-management/models/index.js +10 -5
  49. package/document-management/models/service-models/categories-and-types.view-model.d.ts +3 -3
  50. package/document-management/models/service-models/categories-and-types.view-model.js +2 -21
  51. package/document-management/models/service-models/document-folders.view-model.d.ts +7 -14
  52. package/document-management/models/service-models/document-folders.view-model.js +20 -44
  53. package/document-management/models/service-models/document-management.view-model.d.ts +41 -0
  54. package/document-management/models/service-models/{document.view-model.js → document-management.view-model.js} +43 -26
  55. package/document-management/models/service-models/document.service-model.d.ts +51 -81
  56. package/document-management/models/service-models/document.service-model.js +30 -28
  57. package/document-management/models/service-models/enriched/enriched-document-assignment.view.d.ts +11 -0
  58. package/document-management/models/service-models/enriched/enriched-document-assignment.view.js +12 -0
  59. package/document-management/models/service-models/enriched/enriched-document-category.view.d.ts +13 -0
  60. package/document-management/models/service-models/enriched/enriched-document-category.view.js +47 -0
  61. package/document-management/models/service-models/enriched/enriched-document-collection.view.d.ts +22 -0
  62. package/document-management/models/service-models/enriched/enriched-document-collection.view.js +89 -0
  63. package/document-management/models/service-models/enriched/enriched-document-file.view.d.ts +12 -0
  64. package/document-management/models/service-models/enriched/enriched-document-file.view.js +16 -0
  65. package/document-management/models/service-models/enriched/enriched-document-management-data.view.d.ts +41 -0
  66. package/document-management/models/service-models/enriched/enriched-document-management-data.view.js +130 -0
  67. package/document-management/models/service-models/enriched/enriched-document-request.view.d.ts +17 -0
  68. package/document-management/models/service-models/enriched/enriched-document-request.view.js +52 -0
  69. package/document-management/models/service-models/enriched/enriched-document-type.view.d.ts +9 -0
  70. package/document-management/models/service-models/enriched/enriched-document-type.view.js +10 -0
  71. package/document-management/models/service-models/enriched/enriched-document.view.d.ts +28 -0
  72. package/document-management/models/service-models/enriched/enriched-document.view.js +77 -0
  73. package/document-management/models/service-models/enriched/enriched.d.ts +18 -0
  74. package/document-management/models/service-models/enriched/enriched.js +39 -0
  75. package/document-management/models/service-models/enriched/index.d.ts +9 -0
  76. package/document-management/models/service-models/enriched/index.js +9 -0
  77. package/document-management/models/service-models/index.d.ts +2 -2
  78. package/document-management/models/service-models/index.js +2 -2
  79. package/document-management/models/service-models/normalized-requests-template-data.model.d.ts +12 -10
  80. package/document-management/models/service-models/normalized-requests-template-data.model.js +5 -4
  81. package/document-management/models/service-models/stats.view-model.d.ts +7 -5
  82. package/document-management/models/service-models/stats.view-model.js +19 -9
  83. package/document-management/server/module.d.ts +2 -2
  84. package/document-management/server/module.js +3 -7
  85. package/document-management/server/schemas.d.ts +18 -23
  86. package/document-management/server/schemas.js +18 -23
  87. package/document-management/server/services/document-category-type.service.d.ts +25 -0
  88. package/document-management/server/services/document-category-type.service.js +66 -0
  89. package/document-management/server/services/document-collection.service.d.ts +13 -0
  90. package/document-management/server/services/document-collection.service.js +41 -0
  91. package/document-management/server/services/document-file.service.d.ts +17 -0
  92. package/document-management/server/services/document-file.service.js +204 -0
  93. package/document-management/server/services/document-management-ai.service.d.ts +22 -0
  94. package/document-management/server/services/document-management-ai.service.js +340 -0
  95. package/document-management/server/services/document-management-ancillary.service.d.ts +127 -3
  96. package/document-management/server/services/document-management-ancillary.service.js +24 -0
  97. package/document-management/server/services/document-management.service.d.ts +10 -122
  98. package/document-management/server/services/document-management.service.js +106 -888
  99. package/document-management/server/services/document-property.service.d.ts +84 -0
  100. package/document-management/server/services/document-property.service.js +87 -0
  101. package/document-management/server/services/document-request.service.d.ts +30 -0
  102. package/document-management/server/services/document-request.service.js +138 -0
  103. package/document-management/server/services/document-validation.service.d.ts +20 -0
  104. package/document-management/server/services/document-validation.service.js +145 -0
  105. package/document-management/server/services/document-workflow.service.d.ts +20 -0
  106. package/document-management/server/services/document-workflow.service.js +132 -0
  107. package/document-management/server/services/document.service.d.ts +16 -0
  108. package/document-management/server/services/document.service.js +81 -0
  109. package/document-management/server/services/index.d.ts +9 -0
  110. package/document-management/server/services/index.js +9 -0
  111. package/document-management/server/validators/ai-validation-executor.d.ts +19 -0
  112. package/document-management/server/validators/ai-validation-executor.js +51 -0
  113. package/document-management/server/validators/index.d.ts +2 -0
  114. package/document-management/server/validators/index.js +2 -0
  115. package/document-management/server/validators/single-document-validation-executor.d.ts +16 -0
  116. package/document-management/server/validators/single-document-validation-executor.js +20 -0
  117. package/document-management/server/validators/validator.d.ts +21 -0
  118. package/document-management/server/validators/validator.js +2 -0
  119. package/eslint.config.js +31 -17
  120. package/examples/document-management/main.d.ts +18 -3
  121. package/examples/document-management/main.js +28 -12
  122. package/file/mime-type.js +2 -9
  123. package/formats.d.ts +5 -2
  124. package/formats.js +32 -23
  125. package/http/client/http-client.js +1 -1
  126. package/injector/injector.js +2 -2
  127. package/object-storage/s3/s3.object-storage.js +1 -1
  128. package/orm/data-types/bytea.d.ts +8 -0
  129. package/orm/data-types/bytea.js +8 -0
  130. package/orm/data-types/index.d.ts +4 -0
  131. package/orm/data-types/index.js +4 -0
  132. package/orm/data-types/numeric-date.d.ts +9 -0
  133. package/orm/data-types/numeric-date.js +9 -0
  134. package/orm/data-types/timestamp.d.ts +9 -0
  135. package/orm/data-types/timestamp.js +9 -0
  136. package/orm/decorators.d.ts +139 -5
  137. package/orm/decorators.js +50 -0
  138. package/orm/entity.d.ts +19 -0
  139. package/orm/entity.js +19 -0
  140. package/orm/index.d.ts +5 -0
  141. package/orm/index.js +5 -0
  142. package/orm/query.d.ts +51 -0
  143. package/orm/query.js +6 -0
  144. package/orm/repository.types.d.ts +54 -2
  145. package/orm/server/database-schema.d.ts +34 -0
  146. package/orm/server/database-schema.js +29 -0
  147. package/orm/server/database.d.ts +19 -1
  148. package/orm/server/database.js +17 -3
  149. package/orm/server/drizzle/schema-converter.d.ts +2 -1
  150. package/orm/server/drizzle/schema-converter.js +12 -1
  151. package/orm/server/encryption.d.ts +16 -0
  152. package/orm/server/encryption.js +29 -4
  153. package/orm/server/index.d.ts +7 -0
  154. package/orm/server/index.js +7 -0
  155. package/orm/server/module.d.ts +20 -0
  156. package/orm/server/module.js +9 -0
  157. package/orm/server/query-converter.d.ts +17 -0
  158. package/orm/server/query-converter.js +66 -11
  159. package/orm/server/repository.d.ts +324 -18
  160. package/orm/server/repository.js +344 -73
  161. package/orm/server/transaction.d.ts +5 -5
  162. package/orm/server/transaction.js +5 -5
  163. package/orm/server/transactional.d.ts +75 -0
  164. package/orm/server/transactional.js +134 -0
  165. package/orm/server/types.d.ts +1 -0
  166. package/orm/sqls.d.ts +55 -0
  167. package/orm/sqls.js +60 -0
  168. package/orm/types.d.ts +67 -4
  169. package/orm/utils.d.ts +19 -3
  170. package/orm/utils.js +12 -0
  171. package/package.json +32 -31
  172. package/password/password-check-result.model.d.ts +9 -7
  173. package/password/password-check-result.model.js +8 -8
  174. package/password/password-check.js +5 -7
  175. package/password/password-check.localization.js +12 -12
  176. package/pdf/pdf.service.js +1 -1
  177. package/pdf/utils.d.ts +9 -0
  178. package/pdf/utils.js +19 -2
  179. package/process/spawn.d.ts +11 -4
  180. package/process/spawn.js +42 -5
  181. package/queue/postgres/queue.js +5 -5
  182. package/queue/queue.d.ts +6 -4
  183. package/queue/queue.js +6 -6
  184. package/schema/schemas/one-or-many.d.ts +2 -1
  185. package/schema/schemas/one-or-many.js +1 -1
  186. package/search-index/elastic/model/index-mapping.d.ts +1 -1
  187. package/search-index/elastic/model/index-mapping.js +0 -1
  188. package/search-index/elastic/search-index.d.ts +1 -2
  189. package/search-index/elastic/search-index.js +3 -3
  190. package/types.d.ts +1 -0
  191. package/utils/async-hook/async-hook.d.ts +9 -0
  192. package/utils/async-hook/async-hook.js +21 -0
  193. package/utils/async-hook/index.d.ts +1 -0
  194. package/utils/async-hook/index.js +1 -0
  195. package/utils/compression.js +1 -1
  196. package/utils/function/class.d.ts +6 -0
  197. package/utils/function/class.js +9 -0
  198. package/utils/function/index.d.ts +1 -0
  199. package/utils/function/index.js +1 -0
  200. package/utils/function/memoize.d.ts +18 -0
  201. package/utils/function/memoize.js +41 -2
  202. package/utils/jwt.d.ts +1 -1
  203. package/utils/jwt.js +5 -5
  204. package/utils/object/forward-ref.d.ts +3 -2
  205. package/utils/object/forward-ref.js +12 -12
  206. package/utils/object/lazy-property.js +2 -2
  207. package/utils/proxy.js +1 -1
  208. package/utils/stream/{readable-stream-from-promise.d.ts → from-promise.d.ts} +1 -0
  209. package/utils/stream/from-promise.js +27 -0
  210. package/utils/stream/index.d.ts +1 -1
  211. package/utils/stream/index.js +1 -1
  212. package/utils/stream/stream-reader.js +71 -31
  213. package/document-management/models/document-request-assignment-task-collection.model.d.ts +0 -7
  214. package/document-management/models/document-request-assignment-task.model.d.ts +0 -14
  215. package/document-management/models/document-request-assignment-task.model.js +0 -77
  216. package/document-management/models/document-request-file.model.d.ts +0 -16
  217. package/document-management/models/document-request-file.model.js +0 -86
  218. package/document-management/models/service-models/document.view-model.d.ts +0 -41
  219. package/document-management/models/service-models/normalized-document-collection-view.model.d.ts +0 -73
  220. package/document-management/models/service-models/normalized-document-collection-view.model.js +0 -110
  221. package/utils/stream/readable-stream-from-promise.js +0 -8
@@ -1,7 +1,8 @@
1
+ import type { PgTransaction as DrizzlePgTransaction, PgQueryResultHKT, PgTransactionConfig } from 'drizzle-orm/pg-core';
1
2
  import { DeferredPromise } from '../../promise/deferred-promise.js';
2
- import type { PgTransaction as DrizzlePgTransaction, PgTransactionConfig } from 'drizzle-orm/pg-core';
3
+ import type { Record } from '../../types.js';
3
4
  import type { Database } from './database.js';
4
- type PgTransaction = DrizzlePgTransaction<any, any, any>;
5
+ export type PgTransaction = DrizzlePgTransaction<PgQueryResultHKT, Record, Record>;
5
6
  export type TransactionConfig = PgTransactionConfig;
6
7
  export declare abstract class Transaction {
7
8
  #private;
@@ -18,12 +19,11 @@ export declare abstract class Transaction {
18
19
  protected abstract _rollback(): void;
19
20
  }
20
21
  export declare class DrizzleTransaction extends Transaction {
21
- readonly transaction: PgTransaction;
22
+ readonly pgTransaction: PgTransaction;
22
23
  readonly deferPromise: DeferredPromise<void>;
23
24
  readonly pgTransactionPromise: Promise<void>;
24
- constructor(transaction: PgTransaction, pgTransactionPromise: Promise<void>);
25
+ constructor(pgTransaction: PgTransaction, pgTransactionPromise: Promise<void>);
25
26
  static create(session: Database | PgTransaction, config?: TransactionConfig): Promise<DrizzleTransaction>;
26
27
  protected _commit(): Promise<void>;
27
28
  protected _rollback(): void;
28
29
  }
29
- export {};
@@ -1,5 +1,5 @@
1
- import { DeferredPromise } from '../../promise/deferred-promise.js';
2
1
  import { Subject } from 'rxjs';
2
+ import { DeferredPromise } from '../../promise/deferred-promise.js';
3
3
  export class Transaction {
4
4
  #afterCommitSubject = new Subject();
5
5
  #useCounter = 0;
@@ -36,12 +36,12 @@ export class Transaction {
36
36
  }
37
37
  }
38
38
  export class DrizzleTransaction extends Transaction {
39
- transaction;
39
+ pgTransaction;
40
40
  deferPromise = new DeferredPromise();
41
41
  pgTransactionPromise;
42
- constructor(transaction, pgTransactionPromise) {
42
+ constructor(pgTransaction, pgTransactionPromise) {
43
43
  super();
44
- this.transaction = transaction;
44
+ this.pgTransaction = pgTransaction;
45
45
  this.pgTransactionPromise = pgTransactionPromise;
46
46
  }
47
47
  static async create(session, config) {
@@ -64,7 +64,7 @@ export class DrizzleTransaction extends Transaction {
64
64
  }
65
65
  _rollback() {
66
66
  try {
67
- this.transaction.rollback();
67
+ this.pgTransaction.rollback();
68
68
  }
69
69
  catch (error) {
70
70
  this.deferPromise.reject(error);
@@ -0,0 +1,75 @@
1
+ import { Database } from './database.js';
2
+ import { type PgTransaction, type Transaction, type TransactionConfig } from './transaction.js';
3
+ export type TransactionInitOptions = TransactionConfig & {
4
+ /**
5
+ * Indicates that an existing transaction should be used if available instead of creating a new one.
6
+ * @default true
7
+ */
8
+ useExisting?: boolean;
9
+ };
10
+ export type TransactionHandler<R> = (transaction: Transaction) => Promise<R>;
11
+ type TransactionalContext<ContextData = unknown> = {
12
+ session: Database | PgTransaction;
13
+ cache: WeakMap<Database | PgTransaction, any>;
14
+ data: ContextData;
15
+ };
16
+ declare const getCurrentTransactionalContext: {
17
+ (required: true, debugFn: import("../../types.js").Function): TransactionalContext<unknown>;
18
+ (required?: false, debugFn?: import("../../types.js").Function): TransactionalContext<unknown> | null;
19
+ (required: boolean, debugFn: import("../../types.js").Function): TransactionalContext<unknown> | null;
20
+ }, runInTransactionalContext: <ReturnT>(context: TransactionalContext<unknown>, fn: () => ReturnT) => ReturnT, isInTransactionalContext: () => boolean;
21
+ export { getCurrentTransactionalContext, isInTransactionalContext, runInTransactionalContext };
22
+ export declare abstract class Transactional<ContextData = unknown> {
23
+ #private;
24
+ readonly session: PgTransaction | Database;
25
+ readonly isInTransaction: boolean;
26
+ constructor();
27
+ /**
28
+ * Starts a new database transaction.
29
+ * @param config Optional transaction configuration.
30
+ * @returns A promise that resolves to the new Transaction instance.
31
+ */
32
+ startTransaction(config?: TransactionInitOptions): Promise<Transaction>;
33
+ /**
34
+ * Returns a new instance of the repository bound to the provided session.
35
+ * Useful for performing multiple operations within a single database session.
36
+ * @param session The session to bind to.
37
+ * @returns A new repository instance bound to the session.
38
+ */
39
+ withSession(session: Database | PgTransaction): this;
40
+ /**
41
+ * Returns a new instance of the repository bound to the provided transaction, if a transaction is provided.
42
+ * Otherwise, returns the current instance.
43
+ * @param transaction The transaction to bind to (optional).
44
+ * @returns A repository instance bound to the transaction or the current instance.
45
+ */
46
+ withOptionalTransaction(transaction: Transaction | undefined): this;
47
+ /**
48
+ * Returns a new instance of the repository bound to the provided transaction.
49
+ * Useful for performing multiple operations within a single database transaction.
50
+ * @param transaction The transaction to bind to.
51
+ * @returns A new repository instance bound to the transaction.
52
+ */
53
+ withTransaction(transaction: Transaction): this;
54
+ /**
55
+ * Executes a handler function within the provided transaction. If no transaction is provided,
56
+ * it starts a new transaction, executes the handler, and commits or rolls back based on the outcome.
57
+ * @template R The return type of the handler.
58
+ * @param existingTransaction The transaction to use (optional). Creates a new one otherwise.
59
+ * @param handler The function to execute within the transaction.
60
+ * @returns A promise that resolves to the result of the handler function.
61
+ */
62
+ useTransaction<R>(existingTransaction: Transaction | undefined, handler: TransactionHandler<R>): Promise<R>;
63
+ /**
64
+ * Starts a new transaction, executes the provided handler function within it,
65
+ * and automatically commits the transaction if the handler succeeds or rolls it back if it throws an error.
66
+ * @template R The return type of the handler.
67
+ * @param handler The function to execute within the transaction.
68
+ * @param config Optional transaction configuration.
69
+ * @returns A promise that resolves to the result of the handler function.
70
+ */
71
+ transaction<R>(handler: TransactionHandler<R>, config?: TransactionInitOptions): Promise<R>;
72
+ protected getTransactionalContextData(): ContextData;
73
+ }
74
+ export declare function tryGetTransactionalContextData<T>(_instance?: Transactional<T>): T | undefined;
75
+ export declare function getTransactionalContextData<T>(_instance?: Transactional<T>): T;
@@ -0,0 +1,134 @@
1
+ import { PgTransaction as DrizzlePgTransaction } from 'drizzle-orm/pg-core';
2
+ import { createContextProvider } from '../../context/context.js';
3
+ import { Injector } from '../../injector/index.js';
4
+ import { inject, runInInjectionContext } from '../../injector/inject.js';
5
+ import { isDefined, isUndefined } from '../../utils/type-guards.js';
6
+ import { Database } from './database.js';
7
+ import { DrizzleTransaction } from './transaction.js';
8
+ const transactionCache = new WeakMap();
9
+ const { getCurrentTransactionalContext, runInTransactionalContext, isInTransactionalContext } = createContextProvider('Transactional');
10
+ export { getCurrentTransactionalContext, isInTransactionalContext, runInTransactionalContext };
11
+ function transactionalContextDataGuardFunction() {
12
+ throw new Error('function getTransactionalContextData must be implemented to use transactional context data.');
13
+ }
14
+ const transactionalContextDataGuard = new Proxy({}, {
15
+ apply: transactionalContextDataGuardFunction,
16
+ construct: transactionalContextDataGuardFunction,
17
+ defineProperty: transactionalContextDataGuardFunction,
18
+ deleteProperty: transactionalContextDataGuardFunction,
19
+ get: transactionalContextDataGuardFunction,
20
+ getOwnPropertyDescriptor: transactionalContextDataGuardFunction,
21
+ getPrototypeOf: transactionalContextDataGuardFunction,
22
+ has: transactionalContextDataGuardFunction,
23
+ isExtensible: transactionalContextDataGuardFunction,
24
+ ownKeys: transactionalContextDataGuardFunction,
25
+ preventExtensions: transactionalContextDataGuardFunction,
26
+ set: transactionalContextDataGuardFunction,
27
+ setPrototypeOf: transactionalContextDataGuardFunction,
28
+ });
29
+ export class Transactional {
30
+ #injector = inject(Injector);
31
+ #classConstructor;
32
+ #instanceCache = getCurrentTransactionalContext()?.cache ?? new WeakMap();
33
+ #context = getCurrentTransactionalContext() ?? {};
34
+ session = this.#context.session ?? inject(Database);
35
+ isInTransaction = this.session instanceof DrizzlePgTransaction;
36
+ constructor() {
37
+ this.#classConstructor = new.target;
38
+ }
39
+ /**
40
+ * Starts a new database transaction.
41
+ * @param config Optional transaction configuration.
42
+ * @returns A promise that resolves to the new Transaction instance.
43
+ */
44
+ async startTransaction(config) {
45
+ if ((config?.useExisting != false) && this.isInTransaction) {
46
+ const existing = transactionCache.get(this.session);
47
+ if (isDefined(existing)) {
48
+ return existing;
49
+ }
50
+ }
51
+ const transaction = await DrizzleTransaction.create(this.session, config);
52
+ transactionCache.set(transaction.pgTransaction, transaction);
53
+ return transaction;
54
+ }
55
+ /**
56
+ * Returns a new instance of the repository bound to the provided session.
57
+ * Useful for performing multiple operations within a single database session.
58
+ * @param session The session to bind to.
59
+ * @returns A new repository instance bound to the session.
60
+ */
61
+ withSession(session) {
62
+ if (this.#instanceCache.has(session)) {
63
+ return this.#instanceCache.get(session);
64
+ }
65
+ if (session == this.session) {
66
+ this.#instanceCache.set(session, this);
67
+ return this;
68
+ }
69
+ const context = {
70
+ session: session,
71
+ cache: this.#instanceCache,
72
+ data: this.getTransactionalContextData(),
73
+ };
74
+ const repositoryWithSession = runInInjectionContext(this.#injector, () => runInTransactionalContext(context, () => new this.#classConstructor()));
75
+ this.#instanceCache.set(session, repositoryWithSession);
76
+ return repositoryWithSession;
77
+ }
78
+ /**
79
+ * Returns a new instance of the repository bound to the provided transaction, if a transaction is provided.
80
+ * Otherwise, returns the current instance.
81
+ * @param transaction The transaction to bind to (optional).
82
+ * @returns A repository instance bound to the transaction or the current instance.
83
+ */
84
+ withOptionalTransaction(transaction) {
85
+ if (isUndefined(transaction)) {
86
+ return this;
87
+ }
88
+ return this.withTransaction(transaction);
89
+ }
90
+ /**
91
+ * Returns a new instance of the repository bound to the provided transaction.
92
+ * Useful for performing multiple operations within a single database transaction.
93
+ * @param transaction The transaction to bind to.
94
+ * @returns A new repository instance bound to the transaction.
95
+ */
96
+ withTransaction(transaction) {
97
+ return this.withSession(transaction.pgTransaction);
98
+ }
99
+ /**
100
+ * Executes a handler function within the provided transaction. If no transaction is provided,
101
+ * it starts a new transaction, executes the handler, and commits or rolls back based on the outcome.
102
+ * @template R The return type of the handler.
103
+ * @param existingTransaction The transaction to use (optional). Creates a new one otherwise.
104
+ * @param handler The function to execute within the transaction.
105
+ * @returns A promise that resolves to the result of the handler function.
106
+ */
107
+ async useTransaction(existingTransaction, handler) {
108
+ if (isUndefined(existingTransaction)) {
109
+ return this.transaction(handler);
110
+ }
111
+ return existingTransaction.use(async () => handler(existingTransaction));
112
+ }
113
+ /**
114
+ * Starts a new transaction, executes the provided handler function within it,
115
+ * and automatically commits the transaction if the handler succeeds or rolls it back if it throws an error.
116
+ * @template R The return type of the handler.
117
+ * @param handler The function to execute within the transaction.
118
+ * @param config Optional transaction configuration.
119
+ * @returns A promise that resolves to the result of the handler function.
120
+ */
121
+ async transaction(handler, config) {
122
+ const transaction = await this.startTransaction(config);
123
+ return transaction.use(async () => handler(transaction));
124
+ }
125
+ getTransactionalContextData() {
126
+ return transactionalContextDataGuard; // eslint-disable-line @typescript-eslint/no-unsafe-return
127
+ }
128
+ }
129
+ export function tryGetTransactionalContextData(_instance) {
130
+ return getCurrentTransactionalContext()?.data;
131
+ }
132
+ export function getTransactionalContextData(_instance) {
133
+ return getCurrentTransactionalContext(true, getTransactionalContextData).data;
134
+ }
@@ -20,6 +20,7 @@ export type ColumnDefinition = {
20
20
  toDatabase: (value: unknown, context: TransformContext) => any;
21
21
  fromDatabase: (value: unknown, context: TransformContext) => any;
22
22
  };
23
+ export type ColumnDefinitionsMap = Map<string, ColumnDefinition>;
23
24
  export type TransformContext = {
24
25
  encryptionKey?: CryptoKey;
25
26
  };
package/orm/sqls.d.ts CHANGED
@@ -1,16 +1,71 @@
1
+ /**
2
+ * @module
3
+ * Provides utility SQL functions and constants for use with Drizzle ORM,
4
+ * simplifying common SQL operations like generating UUIDs, working with intervals,
5
+ * and aggregating data.
6
+ */
1
7
  import { type Column, type SQL } from 'drizzle-orm';
2
8
  import type { GetSelectTableSelection, SelectResultField, TableLike } from 'drizzle-orm/query-builders/select.types';
3
9
  import type { Uuid } from './types.js';
10
+ /** Drizzle SQL helper for getting the current transaction's timestamp. Returns a Date object. */
4
11
  export declare const TRANSACTION_TIMESTAMP: SQL<Date>;
12
+ /** Drizzle SQL helper for generating a random UUID (v4). Returns a Uuid string. */
5
13
  export declare const RANDOM_UUID: SQL<Uuid>;
14
+ /** Represents valid units for PostgreSQL interval values. */
6
15
  export type IntervalUnit = 'millennium' | 'millenniums' | 'millennia' | 'century' | 'centuries' | 'decade' | 'decades' | 'year' | 'years' | 'day' | 'days' | 'hour' | 'hours' | 'minute' | 'minutes' | 'second' | 'seconds' | 'millisecond' | 'milliseconds' | 'microsecond' | 'microseconds';
16
+ /**
17
+ * Creates a Drizzle SQL interval expression.
18
+ * @param value - The numeric value of the interval.
19
+ * @param unit - The unit of the interval (e.g., 'day', 'hour').
20
+ * @returns A Drizzle SQL object representing the interval.
21
+ */
7
22
  export declare function interval(value: number, unit: IntervalUnit): SQL;
23
+ /**
24
+ * Creates a Drizzle SQL `array_agg` aggregate function call.
25
+ * Aggregates values from a column into a PostgreSQL array.
26
+ * @template T - The Drizzle column type.
27
+ * @param column - The column to aggregate.
28
+ * @returns A Drizzle SQL object representing the aggregated array.
29
+ */
8
30
  export declare function arrayAgg<T extends Column>(column: T): SQL<SelectResultField<T>[]>;
31
+ /**
32
+ * Creates a Drizzle SQL `json_agg` aggregate function call.
33
+ * Aggregates rows or column values into a JSON array.
34
+ * @template T - The Drizzle table or column type.
35
+ * @param tableOrColumn - The table or column to aggregate into JSON.
36
+ * @returns A Drizzle SQL object representing the JSON aggregated array.
37
+ */
9
38
  export declare function jsonAgg<T extends TableLike>(tableOrColumn: T): SQL<SelectResultField<GetSelectTableSelection<T>>[]>;
10
39
  export declare namespace jsonAgg {
11
40
  var withNull: <T extends TableLike>(tableOrColumn: T) => SQL<(SelectResultField<GetSelectTableSelection<T>> | null)[]>;
12
41
  }
42
+ /**
43
+ * Creates a Drizzle SQL `coalesce` function call.
44
+ * Returns the first non-null value from the provided list of columns or SQL expressions.
45
+ * @template T - An array type of Drizzle Columns or SQL expressions.
46
+ * @param columns - The columns or SQL expressions to check.
47
+ * @returns A Drizzle SQL object representing the coalesced value.
48
+ */
13
49
  export declare function coalesce<T extends (Column | SQL)[]>(...columns: T): SQL<SelectResultField<T>[number]>;
50
+ /**
51
+ * Creates a Drizzle SQL `to_jsonb` function call.
52
+ * Converts the input column or SQL expression to a JSONB value.
53
+ * @template T - The Drizzle column or SQL expression type.
54
+ * @param column - The column or SQL expression to convert.
55
+ * @returns A Drizzle SQL object representing the value as JSONB.
56
+ */
14
57
  export declare function toJsonb<T extends (Column | SQL)>(column: T): SQL<SelectResultField<T>>;
58
+ /**
59
+ * Creates a Drizzle SQL `num_nulls` function call.
60
+ * Counts the number of null arguments.
61
+ * @param columns - The columns to check for nulls.
62
+ * @returns A Drizzle SQL object representing the count of nulls.
63
+ */
15
64
  export declare function numNulls(...columns: Column[]): SQL<number>;
65
+ /**
66
+ * Creates a Drizzle SQL `num_nonnulls` function call.
67
+ * Counts the number of non-null arguments.
68
+ * @param columns - The columns to check for non-nulls.
69
+ * @returns A Drizzle SQL object representing the count of non-nulls.
70
+ */
16
71
  export declare function numNonNulls(...columns: Column[]): SQL<number>;
package/orm/sqls.js CHANGED
@@ -1,25 +1,85 @@
1
+ /**
2
+ * @module
3
+ * Provides utility SQL functions and constants for use with Drizzle ORM,
4
+ * simplifying common SQL operations like generating UUIDs, working with intervals,
5
+ * and aggregating data.
6
+ */
1
7
  import { sql } from 'drizzle-orm';
8
+ /** Drizzle SQL helper for getting the current transaction's timestamp. Returns a Date object. */
2
9
  export const TRANSACTION_TIMESTAMP = sql `transaction_timestamp()`;
10
+ /** Drizzle SQL helper for generating a random UUID (v4). Returns a Uuid string. */
3
11
  export const RANDOM_UUID = sql `gen_random_uuid()`;
12
+ /**
13
+ * Creates a Drizzle SQL interval expression.
14
+ * @param value - The numeric value of the interval.
15
+ * @param unit - The unit of the interval (e.g., 'day', 'hour').
16
+ * @returns A Drizzle SQL object representing the interval.
17
+ */
4
18
  export function interval(value, unit) {
5
19
  return sql `(${value} ||' ${sql.raw(unit)}')::interval`;
6
20
  }
21
+ /**
22
+ * Creates a Drizzle SQL `array_agg` aggregate function call.
23
+ * Aggregates values from a column into a PostgreSQL array.
24
+ * @template T - The Drizzle column type.
25
+ * @param column - The column to aggregate.
26
+ * @returns A Drizzle SQL object representing the aggregated array.
27
+ */
7
28
  export function arrayAgg(column) {
8
29
  return sql `array_agg(${column})`;
9
30
  }
31
+ /**
32
+ * Creates a Drizzle SQL `json_agg` aggregate function call.
33
+ * Aggregates rows or column values into a JSON array.
34
+ * @template T - The Drizzle table or column type.
35
+ * @param tableOrColumn - The table or column to aggregate into JSON.
36
+ * @returns A Drizzle SQL object representing the JSON aggregated array.
37
+ */
10
38
  export function jsonAgg(tableOrColumn) {
11
39
  return sql `json_agg(${tableOrColumn})`;
12
40
  }
41
+ /**
42
+ * Variant of `jsonAgg` that includes null values in the resulting JSON array.
43
+ * @template T - The Drizzle table or column type.
44
+ * @param tableOrColumn - The table or column to aggregate into JSON.
45
+ * @returns A Drizzle SQL object representing the JSON aggregated array, potentially containing nulls.
46
+ */
13
47
  jsonAgg.withNull = jsonAgg;
48
+ /**
49
+ * Creates a Drizzle SQL `coalesce` function call.
50
+ * Returns the first non-null value from the provided list of columns or SQL expressions.
51
+ * @template T - An array type of Drizzle Columns or SQL expressions.
52
+ * @param columns - The columns or SQL expressions to check.
53
+ * @returns A Drizzle SQL object representing the coalesced value.
54
+ */
14
55
  export function coalesce(...columns) {
15
56
  return sql `coalesce(${sql.join(columns, sql.raw(', '))})`;
16
57
  }
58
+ /**
59
+ * Creates a Drizzle SQL `to_jsonb` function call.
60
+ * Converts the input column or SQL expression to a JSONB value.
61
+ * @template T - The Drizzle column or SQL expression type.
62
+ * @param column - The column or SQL expression to convert.
63
+ * @returns A Drizzle SQL object representing the value as JSONB.
64
+ */
17
65
  export function toJsonb(column) {
18
66
  return sql `to_jsonb(${column})`;
19
67
  }
68
+ /**
69
+ * Creates a Drizzle SQL `num_nulls` function call.
70
+ * Counts the number of null arguments.
71
+ * @param columns - The columns to check for nulls.
72
+ * @returns A Drizzle SQL object representing the count of nulls.
73
+ */
20
74
  export function numNulls(...columns) {
21
75
  return sql `num_nulls(${sql.join(columns, sql.raw(', '))})`;
22
76
  }
77
+ /**
78
+ * Creates a Drizzle SQL `num_nonnulls` function call.
79
+ * Counts the number of non-null arguments.
80
+ * @param columns - The columns to check for non-nulls.
81
+ * @returns A Drizzle SQL object representing the count of non-nulls.
82
+ */
23
83
  export function numNonNulls(...columns) {
24
84
  return sql `num_nonnulls(${sql.join(columns, sql.raw(', '))})`;
25
85
  }
package/orm/types.d.ts CHANGED
@@ -1,3 +1,9 @@
1
+ /**
2
+ * @module
3
+ * Defines core ORM types, including tagged types for representing database column types
4
+ * (like Uuid, Timestamp, Json, etc.) and helper types for working with Drizzle ORM features
5
+ * like primary keys and default values. It also re-exports common decorators and schemas.
6
+ */
1
7
  import type { $Type, HasDefault as DrizzleHasDefault, IsPrimaryKey as DrizzleIsPrimaryKey } from 'drizzle-orm';
2
8
  import type { boolean, doublePrecision, integer, jsonb, PgColumnBuilder, PgColumnBuilderBase, PgEnumColumnBuilderInitial, text, uuid } from 'drizzle-orm/pg-core';
3
9
  import { Array, Integer } from '../schema/index.js';
@@ -6,25 +12,82 @@ import type { GetTagMetadata, HasTag, Tagged, UnwrapTagged } from '../types/inde
6
12
  import type { bytea, numericDate, timestamp } from './data-types/index.js';
7
13
  import { Check, Column, Embedded, Encrypted, Index, PrimaryKey, References, Table, Unique } from './decorators.js';
8
14
  import { Json, NumericDate, Timestamp, Uuid } from './schemas/index.js';
15
+ /** Tag identifier for column type information. */
9
16
  export type ColumnTypeTag = 'column';
17
+ /** Tag identifier for embedded type configuration. */
10
18
  export type EmbeddedConfigTag = 'embedded';
19
+ /**
20
+ * Helper type to tag a column type as being a primary key.
21
+ * It wraps the original type `T` and associates Drizzle's `IsPrimaryKey` marker
22
+ * with the underlying Drizzle column builder type stored in the tag metadata.
23
+ * @template T - The original column type (e.g., Uuid, Integer).
24
+ */
11
25
  export type IsPrimaryKey<T> = T extends Tagged<unknown, ColumnTypeTag, PgColumnBuilderBase> ? Tagged<UnwrapTagged<T>, ColumnTypeTag, DrizzleIsPrimaryKey<GetTagMetadata<T, ColumnTypeTag>>> : Tagged<T, ColumnTypeTag, DrizzleIsPrimaryKey<ColumnBuilder<T>>>;
26
+ /**
27
+ * Helper type to tag a column type as having a default value.
28
+ * It wraps the original type `T` and associates Drizzle's `HasDefault` marker
29
+ * with the underlying Drizzle column builder type stored in the tag metadata.
30
+ * @template T - The original column type (e.g., Uuid, Timestamp).
31
+ */
12
32
  export type HasDefault<T> = T extends Tagged<unknown, ColumnTypeTag, PgColumnBuilderBase> ? Tagged<UnwrapTagged<T>, ColumnTypeTag, DrizzleHasDefault<GetTagMetadata<T, ColumnTypeTag>>> : Tagged<T, ColumnTypeTag, DrizzleHasDefault<ColumnBuilder<T>>>;
13
- type EnumColumn<T extends EnumerationObject, ColumnName extends string = ''> = PgEnumColumnBuilderInitial<ColumnName, UnionToTuple<`${EnumerationValue<T>}`> extends [string, ...string[]] ? UnionToTuple<`${EnumerationValue<T>}`> : ['NO_VALUES_PROVIDED']>;
14
- export type ColumnBuilder<T, ColumnName extends string = never> = HasTag<T> extends true ? T extends Tagged<T, ColumnTypeTag, any> ? GetTagMetadata<T, ColumnTypeTag> : never : T extends string ? string extends ColumnName ? ReturnType<typeof text<ColumnName, string, [string, ...string[]]>> : ReturnType<typeof text<string, [string, ...string[]]>> : T extends number ? string extends ColumnName ? ReturnType<typeof doublePrecision<ColumnName>> : ReturnType<typeof doublePrecision> : T extends boolean ? string extends ColumnName ? ReturnType<typeof boolean<ColumnName>> : ReturnType<typeof boolean> : T extends Uint8Array ? string extends ColumnName ? ReturnType<typeof bytea<ColumnName>> : ReturnType<typeof bytea> : T extends EnumerationObject ? string extends ColumnName ? EnumColumn<T, ColumnName> : EnumColumn<T> : T extends (infer U)[] ? string extends ColumnName ? ReturnType<ColumnBuilder<U, ColumnName>['array']> : ReturnType<ColumnBuilder<U>['array']> : never;
33
+ type EnumColumn<T extends string | number, ColumnName extends string = ''> = PgEnumColumnBuilderInitial<ColumnName, UnionToTuple<`${T}`> extends [string, ...string[]] ? UnionToTuple<`${T}`> : ['NO_VALUES_PROVIDED']>;
34
+ type TextTuple<T extends string> = UnionToTuple<`${T}`> extends [string, ...string[]] ? UnionToTuple<`${T}`> : [string];
35
+ type HandledColumnName<T extends string = never> = [T] extends [never] ? '' : T;
36
+ /**
37
+ * Utility type to infer the Drizzle column builder type based on a TypeScript type `T`.
38
+ * Handles primitive types (string, number, boolean), arrays, enums, Uint8Array,
39
+ * and existing tagged column types.
40
+ * @template T - The TypeScript type to map to a column builder.
41
+ * @template ColumnName - Optional column name for context.
42
+ */
43
+ export type ColumnBuilder<T, ColumnName extends string = never> = HasTag<T> extends true ? T extends Tagged<unknown, ColumnTypeTag, any> ? GetTagMetadata<T, ColumnTypeTag> : never : T extends string ? ReturnType<typeof text<HandledColumnName<ColumnName>, string, TextTuple<T>>> : T extends number ? ReturnType<typeof doublePrecision<HandledColumnName<ColumnName>>> : T extends boolean ? ReturnType<typeof boolean<HandledColumnName<ColumnName>>> : T extends Uint8Array ? ReturnType<typeof bytea<HandledColumnName<ColumnName>>> : T extends EnumerationObject ? EnumColumn<EnumerationValue<T>, HandledColumnName<ColumnName>> : T extends (infer U)[] ? ReturnType<ColumnBuilder<U, HandledColumnName<ColumnName>>['array']> : never;
44
+ /**
45
+ * Tagged type representing an embedded class configuration.
46
+ * Stores the embedded type `T` and an optional column name prefix `P`.
47
+ * @template T - The constructor of the class being embedded.
48
+ * @template P - An optional prefix for the column names generated from the embedded class properties.
49
+ */
15
50
  export type Embedded<T = AbstractConstructor, P extends string = ''> = Tagged<T, EmbeddedConfigTag, {
16
51
  prefix: P;
17
52
  }>;
53
+ /**
54
+ * Tagged type representing a PostgreSQL array column.
55
+ * Wraps an existing tagged column type `T` and derives the Drizzle array column builder.
56
+ * @template T - The tagged type of the array elements.
57
+ */
18
58
  export type Array<T extends Tagged<ObjectLiteral, ColumnTypeTag, PgColumnBuilder<any>>> = Tagged<UnwrapTagged<T>[], ColumnTypeTag, ReturnType<GetTagMetadata<T, ColumnTypeTag>['array']>>;
59
+ /**
60
+ * Tagged type representing a JSONB column.
61
+ * Stores the TypeScript type `T` that the JSONB data represents.
62
+ * @template T - The TypeScript type of the data stored in the JSONB column.
63
+ */
19
64
  export type Json<T> = Tagged<T, ColumnTypeTag, $Type<ReturnType<typeof jsonb>, T>>;
20
- export type Enum<T extends EnumerationObject> = Tagged<EnumerationValue<T>, ColumnTypeTag, EnumColumn<T>>;
21
- export type Text = Tagged<string, ColumnTypeTag, ReturnType<typeof text<string, [string, ...string[]]>>>;
65
+ /**
66
+ * Tagged type representing a PostgreSQL enum column.
67
+ * Derives the enum values and the Drizzle enum column builder from the provided enum object `T`.
68
+ * @template T - The enumeration object type.
69
+ */
70
+ export type Enum<T extends string | number> = Tagged<T, ColumnTypeTag, EnumColumn<T>>;
71
+ /** Tagged type representing a `text` column. */
72
+ export type Text<T extends string = string> = Tagged<string, ColumnTypeTag, ReturnType<typeof text<string, TextTuple<T>>>>;
73
+ /** Tagged type representing a `uuid` column. Stores the UUID as a string. */
22
74
  export type Uuid = Tagged<string, ColumnTypeTag, ReturnType<typeof uuid>>;
75
+ /** Tagged type representing an `integer` column. */
23
76
  export type Integer = Tagged<number, ColumnTypeTag, ReturnType<typeof integer>>;
77
+ /** Tagged type representing a `double precision` column. */
24
78
  export type DoublePrecision = Tagged<number, ColumnTypeTag, ReturnType<typeof doublePrecision>>;
79
+ /** Tagged type representing a `boolean` column. */
25
80
  export type Boolean = Tagged<number, ColumnTypeTag, ReturnType<typeof boolean>>;
81
+ /** Tagged type representing a custom `numericDate` column (stores date as number YYYYMMDD). */
26
82
  export type NumericDate = Tagged<number, ColumnTypeTag, ReturnType<typeof numericDate>>;
83
+ /** Tagged type representing a `timestamp` column (stores timestamp as number - milliseconds since epoch). */
27
84
  export type Timestamp = Tagged<number, ColumnTypeTag, ReturnType<typeof timestamp>>;
85
+ /** Tagged type representing a `bytea` (byte array) column. */
28
86
  export type Bytea = Tagged<Uint8Array, ColumnTypeTag, ReturnType<typeof bytea>>;
87
+ /**
88
+ * Tagged type representing an encrypted column.
89
+ * Stores the original TypeScript type `T`, but the underlying database type is `bytea`.
90
+ * @template T - The original (unencrypted) type of the data.
91
+ */
29
92
  export type Encrypted<T> = Tagged<T, ColumnTypeTag, ReturnType<typeof bytea>>;
30
93
  export { Array, Check, Column, Embedded, Encrypted, Index, Integer, Json, NumericDate, PrimaryKey, References, Table, Timestamp, Unique, Uuid };
package/orm/utils.d.ts CHANGED
@@ -1,3 +1,19 @@
1
- import type { Entity } from './entity.js';
2
- export declare function getEntityMap<T extends Entity>(entities: T[]): Map<string, T>;
3
- export declare function getEntityIds<T extends Entity>(entities: T[]): string[];
1
+ /**
2
+ * @module
3
+ * Provides utility functions for working with ORM entities.
4
+ */
5
+ import type { Entity, EntityWithoutMetadata } from './entity.js';
6
+ /**
7
+ * Converts an array of entities into a Map keyed by entity ID.
8
+ * @template T - The entity type, must extend `Entity` (i.e., have an `id` property).
9
+ * @param entities - An array of entities.
10
+ * @returns A Map where keys are entity IDs and values are the corresponding entities.
11
+ */
12
+ export declare function getEntityMap<T extends Entity | EntityWithoutMetadata>(entities: T[]): Map<string, T>;
13
+ /**
14
+ * Extracts the IDs from an array of entities.
15
+ * @template T - The entity type, must extend `Entity` (i.e., have an `id` property).
16
+ * @param entities - An array of entities.
17
+ * @returns An array containing the IDs of the entities.
18
+ */
19
+ export declare function getEntityIds(entities: (Entity | EntityWithoutMetadata)[]): string[];
package/orm/utils.js CHANGED
@@ -1,6 +1,18 @@
1
+ /**
2
+ * Converts an array of entities into a Map keyed by entity ID.
3
+ * @template T - The entity type, must extend `Entity` (i.e., have an `id` property).
4
+ * @param entities - An array of entities.
5
+ * @returns A Map where keys are entity IDs and values are the corresponding entities.
6
+ */
1
7
  export function getEntityMap(entities) {
2
8
  return new Map(entities.map((entity) => [entity.id, entity]));
3
9
  }
10
+ /**
11
+ * Extracts the IDs from an array of entities.
12
+ * @template T - The entity type, must extend `Entity` (i.e., have an `id` property).
13
+ * @param entities - An array of entities.
14
+ * @returns An array containing the IDs of the entities.
15
+ */
4
16
  export function getEntityIds(entities) {
5
17
  return entities.map((entity) => entity.id);
6
18
  }