@duraxis/nestjs 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["_decorate","isPromiseLike","_decorate"],"sources":["../src/duraxis.tokens.ts","../src/duraxis.connection.ts","../src/duraxis.errors.ts","../src/transactions/transaction-context.manager.ts","../src/transactions/transaction.errors.ts","../src/transactions/transaction-manager.registry.ts","../src/duraxis.registry.ts","../src/duraxis.feature-discovery.ts","../src/transactions/transaction.types.ts","../src/transactions/transaction-aware.repository.ts","../src/transactions/transaction.manager.ts","../src/transactions/transactional.decorator.ts","../src/transactions/transactional.proxy.ts","../src/duraxis.module.ts","../src/duraxis.decorators.ts"],"sourcesContent":["import type { EntityClass } from \"@duraxis/orm\";\n\nexport const DEFAULT_DURAXIS_CONNECTION = \"default\";\n\nconst repositoryTokens = new WeakMap<Function, Map<string, symbol>>();\n\nexport function normalizeDuraxisConnectionName(name?: string): string {\n const normalized = name ?? DEFAULT_DURAXIS_CONNECTION;\n if (\n typeof normalized != \"string\" ||\n normalized.trim() == \"\" ||\n normalized.length > 128 ||\n normalized.includes(\"\\0\")\n )\n throw new TypeError(\n \"Duraxis connection name must be a non-empty string of at most 128 characters\",\n );\n return normalized;\n}\n\nfunction connectionToken(kind: string, connectionName?: string): symbol {\n const name = normalizeDuraxisConnectionName(connectionName);\n return Symbol.for(`@duraxis/nestjs/${kind}/${encodeURIComponent(name)}`);\n}\n\nexport function getDuraxisOrmToken(connectionName?: string): symbol {\n return connectionToken(\"orm\", connectionName);\n}\n\nexport function getDuraxisDatabaseToken(connectionName?: string): symbol {\n return connectionToken(\"database\", connectionName);\n}\n\nexport function getDuraxisTransactionManagerToken(connectionName?: string): symbol {\n return connectionToken(\"transaction-manager\", connectionName);\n}\n\nexport function getDuraxisRepositoryToken<TEntity extends object>(\n entity: EntityClass<TEntity>,\n connectionName?: string,\n): symbol {\n const name = normalizeDuraxisConnectionName(connectionName);\n let byConnection = repositoryTokens.get(entity);\n if (!byConnection) {\n byConnection = new Map();\n repositoryTokens.set(entity, byConnection);\n }\n let token = byConnection.get(name);\n if (!token) {\n token = Symbol(`@duraxis/nestjs/repository/${name}/${entity.name}`);\n byConnection.set(name, token);\n }\n return token;\n}\n\nexport function getDuraxisOptionsToken(connectionName?: string): symbol {\n return connectionToken(\"options\", connectionName);\n}\n\nexport function getDuraxisConnectionToken(connectionName?: string): symbol {\n return connectionToken(\"connection\", connectionName);\n}\n","import type { OnApplicationShutdown, OnModuleDestroy } from \"@nestjs/common\";\nimport { DuraxisDatabase } from \"@duraxis/core\";\nimport { DuraxisORM } from \"@duraxis/orm\";\nimport type { StorageDriver } from \"@duraxis/storage\";\nimport type { DuraxisModuleOptions } from \"./duraxis.interfaces.js\";\n\nfunction isStorageDriver(value: unknown): value is StorageDriver {\n if (typeof value != \"object\" || value == null) return false;\n return [\"get\", \"put\", \"delete\", \"list\"].every(\n (method) => method in value && typeof Reflect.get(value, method) == \"function\",\n );\n}\n\nexport class DuraxisNestConnection implements OnModuleDestroy, OnApplicationShutdown {\n #closing?: Promise<void>;\n #beforeClose?: () => Promise<void>;\n\n private constructor(\n public readonly name: string,\n public readonly database: DuraxisDatabase,\n public readonly orm: DuraxisORM,\n private readonly onClosed: () => void,\n ) {}\n\n public static async create(\n name: string,\n options: DuraxisModuleOptions,\n onClosed: () => void = () => {},\n ): Promise<DuraxisNestConnection> {\n const driverIsFactory = typeof options.driver == \"function\";\n const closeStorage = options.closeStorage ?? driverIsFactory;\n let driver: StorageDriver | undefined;\n let database: DuraxisDatabase | undefined;\n let orm: DuraxisORM | undefined;\n\n try {\n driver = driverIsFactory ? await options.driver() : options.driver;\n if (!isStorageDriver(driver))\n throw new TypeError(\"Duraxis driver factory returned an invalid StorageDriver\");\n\n database = new DuraxisDatabase({\n ...options.database,\n storage: driver,\n });\n orm = new DuraxisORM({\n database,\n entities: options.entities ?? [],\n ...(options.schema == null ? {} : { schema: options.schema }),\n closeDatabase: true,\n closeStorage,\n });\n await orm.initialize();\n return new DuraxisNestConnection(name, database, orm, onClosed);\n } catch (cause) {\n try {\n if (orm) await orm.close();\n else if (database) await database.close({ closeStorage });\n else if (driver && closeStorage) await driver.close?.();\n } catch (cleanupCause) {\n throw new AggregateError(\n [cause, cleanupCause],\n `Duraxis connection ${name} initialization and cleanup both failed`,\n );\n }\n throw cause;\n }\n }\n\n public async close(): Promise<void> {\n if (!this.#closing) this.#closing = this.closeResources();\n await this.#closing;\n }\n\n public setBeforeClose(callback: () => Promise<void>): void {\n if (this.#beforeClose)\n throw new Error(`Duraxis connection ${this.name} already has a close coordinator`);\n this.#beforeClose = callback;\n }\n\n private async closeResources(): Promise<void> {\n const failures: unknown[] = [];\n try {\n await this.#beforeClose?.();\n } catch (error) {\n failures.push(error);\n }\n try {\n await this.orm.close();\n } catch (error) {\n failures.push(error);\n } finally {\n this.onClosed();\n }\n if (failures.length == 1) throw failures[0];\n if (failures.length > 1)\n throw new AggregateError(failures, `Duraxis connection ${this.name} shutdown failed`);\n }\n\n public async onModuleDestroy(): Promise<void> {\n await this.close();\n }\n\n public async onApplicationShutdown(): Promise<void> {\n await this.close();\n }\n}\n","export class DuraxisNestError extends Error {\n public constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = new.target.name;\n }\n}\n\nexport class DuplicateDuraxisConnectionError extends DuraxisNestError {\n public constructor(connectionName: string) {\n super(`Duraxis connection is configured more than once: ${connectionName}`);\n }\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { TransactionContext } from \"@duraxis/orm\";\n\nexport interface PhysicalTransactionState {\n readonly manager: TransactionContext;\n readonly pending: Set<Promise<unknown>>;\n active: boolean;\n rollbackOnly: boolean;\n}\n\nexport interface TransactionExecutionContext {\n readonly physical: PhysicalTransactionState;\n readonly readOnly: boolean;\n readonly newTransaction: boolean;\n}\n\nexport class TransactionContextManager {\n readonly #storage = new AsyncLocalStorage<ReadonlyMap<object, TransactionExecutionContext>>();\n\n public current(connectionIdentity: object): TransactionExecutionContext | undefined {\n return this.#storage.getStore()?.get(connectionIdentity);\n }\n\n public async run<TResult>(\n connectionIdentity: object,\n context: TransactionExecutionContext,\n callback: () => Promise<TResult>,\n ): Promise<TResult> {\n const contexts = new Map(this.#storage.getStore() ?? []);\n contexts.set(connectionIdentity, context);\n return await this.#storage.run(contexts, callback);\n }\n\n public async suspend<TResult>(\n connectionIdentity: object,\n callback: () => Promise<TResult>,\n ): Promise<TResult> {\n const contexts = new Map(this.#storage.getStore() ?? []);\n contexts.delete(connectionIdentity);\n return await this.#storage.run(contexts, callback);\n }\n}\n","import { DuraxisNestError } from \"../duraxis.errors.js\";\n\nexport class TransactionRequiredError extends DuraxisNestError {\n public constructor(connectionName: string) {\n super(`An active Duraxis transaction is required for connection ${connectionName}`);\n }\n}\n\nexport class ExistingTransactionError extends DuraxisNestError {\n public constructor(connectionName: string) {\n super(`An active Duraxis transaction is forbidden for connection ${connectionName}`);\n }\n}\n\nexport class NestedTransactionNotSupportedError extends DuraxisNestError {\n public constructor() {\n super(\"NESTED propagation is unavailable because Duraxis does not support savepoints\");\n }\n}\n\nexport class UnsupportedTransactionIsolationError extends DuraxisNestError {\n public constructor(isolation: string) {\n super(`Unsupported Duraxis transaction isolation: ${isolation}`);\n }\n}\n\nexport class UnsupportedTransactionTimeoutError extends DuraxisNestError {\n public constructor() {\n super(\"Transactional timeout is unavailable because Duraxis cannot safely cancel all writes\");\n }\n}\n\nexport class ReadOnlyTransactionError extends DuraxisNestError {\n public constructor(operation: string) {\n super(`Operation ${operation} is not allowed in a read-only Duraxis transaction`);\n }\n}\n\nexport class UnexpectedTransactionRollbackError extends DuraxisNestError {\n public constructor() {\n super(\"Duraxis transaction rolled back because a participating scope marked it rollback-only\");\n }\n}\n\nexport class TransactionContextClosedError extends DuraxisNestError {\n public constructor() {\n super(\"Duraxis transaction context is no longer active\");\n }\n}\n\nexport class TransactionalMethodReturnTypeError extends DuraxisNestError {\n public constructor(methodName: string) {\n super(`Transactional method ${methodName} must return a Promise`);\n }\n}\n\nexport class UnsupportedMixedTransactionError extends DuraxisNestError {\n public constructor() {\n super(\"Imperative orm.transaction() cannot be started inside a declarative transaction\");\n }\n}\n\nexport class UnawaitedTransactionOperationError extends DuraxisNestError {\n public constructor(options?: ErrorOptions) {\n super(\n \"A repository operation was still pending when the transactional method completed\",\n options,\n );\n }\n}\n\nexport class TransactionManagerShuttingDownError extends DuraxisNestError {\n public constructor() {\n super(\"Duraxis transaction manager is shutting down\");\n }\n}\n\nexport class TransactionManagerNotFoundError extends DuraxisNestError {\n public constructor(connectionName: string) {\n super(`No Duraxis transaction manager is registered for connection ${connectionName}`);\n }\n}\n","import { TransactionManagerNotFoundError } from \"./transaction.errors.js\";\nimport type { TransactionManager } from \"./transaction.manager.js\";\n\nexport class TransactionManagerRegistry {\n readonly #managers = new Map<string, TransactionManager>();\n\n public register(connectionName: string, manager: TransactionManager): void {\n this.#managers.set(connectionName, manager);\n }\n\n public unregister(connectionName: string, manager: TransactionManager): void {\n if (this.#managers.get(connectionName) == manager) this.#managers.delete(connectionName);\n }\n\n public get(connectionName: string): TransactionManager {\n const manager = this.#managers.get(connectionName);\n if (!manager) throw new TransactionManagerNotFoundError(connectionName);\n return manager;\n }\n}\n","import { Global, Injectable, Module } from \"@nestjs/common\";\nimport { DuraxisNestConnection } from \"./duraxis.connection.js\";\nimport { DuplicateDuraxisConnectionError } from \"./duraxis.errors.js\";\nimport type { DuraxisModuleOptions } from \"./duraxis.interfaces.js\";\nimport { TransactionContextManager } from \"./transactions/transaction-context.manager.js\";\nimport { TransactionManagerRegistry } from \"./transactions/transaction-manager.registry.js\";\n\n@Injectable()\nexport class DuraxisConnectionRegistry {\n readonly #active = new Map<string, Promise<DuraxisNestConnection>>();\n\n public async create(name: string, options: DuraxisModuleOptions): Promise<DuraxisNestConnection> {\n const existing = this.#active.get(name);\n if (existing) throw new DuplicateDuraxisConnectionError(name);\n\n let creation!: Promise<DuraxisNestConnection>;\n creation = DuraxisNestConnection.create(name, options, () => {\n if (this.#active.get(name) == creation) this.#active.delete(name);\n });\n this.#active.set(name, creation);\n try {\n return await creation;\n } catch (error) {\n if (this.#active.get(name) == creation) this.#active.delete(name);\n throw error;\n }\n }\n}\n\n@Global()\n@Module({\n providers: [DuraxisConnectionRegistry, TransactionContextManager, TransactionManagerRegistry],\n exports: [DuraxisConnectionRegistry, TransactionContextManager, TransactionManagerRegistry],\n})\nexport class DuraxisConnectionRegistryModule {}\n","import { DiscoveryService } from \"@nestjs/core\";\nimport type { EntityClass } from \"@duraxis/orm\";\n\nexport interface DuraxisFeatureEntitiesMetadata {\n readonly connectionName: string;\n readonly entities: readonly EntityClass[];\n}\n\nexport const DuraxisFeatureEntities =\n DiscoveryService.createDecorator<DuraxisFeatureEntitiesMetadata>();\n\nexport function discoverFeatureEntities(\n discovery: DiscoveryService,\n connectionName: string,\n): readonly EntityClass[] {\n const entities = new Set<EntityClass>();\n for (const provider of discovery.getProviders({ metadataKey: DuraxisFeatureEntities.KEY })) {\n const metadata = discovery.getMetadataByDecorator(DuraxisFeatureEntities, provider);\n if (metadata?.connectionName != connectionName) continue;\n for (const entity of metadata.entities) entities.add(entity);\n }\n return [...entities];\n}\n","export enum TransactionPropagation {\n REQUIRED = \"REQUIRED\",\n REQUIRES_NEW = \"REQUIRES_NEW\",\n SUPPORTS = \"SUPPORTS\",\n MANDATORY = \"MANDATORY\",\n NOT_SUPPORTED = \"NOT_SUPPORTED\",\n NEVER = \"NEVER\",\n NESTED = \"NESTED\",\n}\n\nexport enum TransactionIsolation {\n DEFAULT = \"DEFAULT\",\n SNAPSHOT = \"SNAPSHOT\",\n}\n\nexport type ErrorConstructor = new (...arguments_: never[]) => Error;\n\nexport interface TransactionalOptions {\n readonly propagation?: TransactionPropagation;\n readonly isolation?: TransactionIsolation;\n readonly readOnly?: boolean;\n readonly timeout?: number;\n readonly rollbackFor?: readonly ErrorConstructor[];\n readonly noRollbackFor?: readonly ErrorConstructor[];\n readonly connectionName?: string;\n}\n\nexport interface TransactionStatus {\n readonly connectionName: string;\n readonly active: boolean;\n readonly newTransaction: boolean;\n readonly readOnly: boolean;\n readonly rollbackOnly: boolean;\n}\n","import { QueryBuilder, type DuraxisORM, type EntityClass, type Repository } from \"@duraxis/orm\";\nimport type { TransactionExecutionContext } from \"./transaction-context.manager.js\";\nimport type { TransactionManager } from \"./transaction.manager.js\";\n\nconst WRITE_METHODS = new Set<PropertyKey>([\"insert\", \"save\", \"update\", \"upsert\", \"delete\"]);\nconst BUILDER_METHODS = new Set<PropertyKey>([\n \"where\",\n \"andWhere\",\n \"orWhere\",\n \"andWhereGroup\",\n \"orWhereGroup\",\n \"notWhere\",\n \"orderBy\",\n \"select\",\n \"limit\",\n \"cursor\",\n \"withSignal\",\n]);\nconst BUILDER_TERMINALS = new Set<PropertyKey>([\n \"getMany\",\n \"getOne\",\n \"getCount\",\n \"getPage\",\n \"explain\",\n \"toLogicalQuery\",\n]);\n\ninterface BuilderStep {\n readonly method: PropertyKey;\n readonly arguments: readonly unknown[];\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return (\n (typeof value == \"object\" || typeof value == \"function\") &&\n value != null &&\n typeof Reflect.get(value, \"then\") == \"function\"\n );\n}\n\nfunction transactionAwareBuilder<TEntity extends object>(\n entity: EntityClass<TEntity>,\n baseRepository: Repository<TEntity>,\n transactions: TransactionManager,\n captured: TransactionExecutionContext | undefined,\n steps: readonly BuilderStep[] = [],\n): QueryBuilder<TEntity> {\n const target = baseRepository.createQueryBuilder();\n return new Proxy(target, {\n get(_target, property) {\n if (BUILDER_METHODS.has(property))\n return (...arguments_: readonly unknown[]) =>\n transactionAwareBuilder(entity, baseRepository, transactions, captured, [\n ...steps,\n { method: property, arguments: arguments_ },\n ]);\n\n if (BUILDER_TERMINALS.has(property))\n return (...arguments_: readonly unknown[]) => {\n transactions.assertCapturedContext(captured);\n let builder = transactions.resolveRepository(entity, baseRepository).createQueryBuilder();\n for (const step of steps) {\n const method = Reflect.get(builder, step.method);\n if (typeof method != \"function\") throw new TypeError(\"Invalid QueryBuilder method\");\n const next = Reflect.apply(method, builder, step.arguments);\n if (!(next instanceof QueryBuilder))\n throw new TypeError(\"QueryBuilder chain returned an invalid value\");\n builder = next;\n }\n const terminal = Reflect.get(builder, property);\n if (typeof terminal != \"function\") throw new TypeError(\"Invalid QueryBuilder terminal\");\n const result: unknown = Reflect.apply(terminal, builder, arguments_);\n return isPromiseLike(result) ? transactions.track(result) : result;\n };\n\n const value: unknown = Reflect.get(target, property, target);\n return typeof value == \"function\" ? value.bind(target) : value;\n },\n });\n}\n\nexport function createTransactionAwareRepository<TEntity extends object>(\n entity: EntityClass<TEntity>,\n baseRepository: Repository<TEntity>,\n transactions: TransactionManager,\n): Repository<TEntity> {\n return new Proxy(baseRepository, {\n get(target, property) {\n if (property == \"createQueryBuilder\")\n return () =>\n transactionAwareBuilder(\n entity,\n baseRepository,\n transactions,\n transactions.currentContext(),\n );\n\n const effective = transactions.resolveRepository(entity, baseRepository);\n const value: unknown = Reflect.get(effective, property, effective);\n if (typeof value != \"function\") return value;\n\n return (...arguments_: readonly unknown[]) => {\n if (WRITE_METHODS.has(property)) transactions.assertWriteAllowed(String(property));\n const current = transactions.resolveRepository(entity, baseRepository);\n const method = Reflect.get(current, property, current);\n if (typeof method != \"function\") throw new TypeError(\"Invalid Repository method\");\n const result: unknown = Reflect.apply(method, current, arguments_);\n return isPromiseLike(result) ? transactions.track(result) : result;\n };\n },\n });\n}\n\nexport function createTransactionAwareOrm(\n orm: DuraxisORM,\n transactions: TransactionManager,\n): DuraxisORM {\n return new Proxy(orm, {\n get(target, property) {\n if (property == \"getRepository\")\n return <TEntity extends object>(entity: EntityClass<TEntity>): Repository<TEntity> =>\n transactions.getRepository(entity);\n if (property == \"transaction\")\n return (...arguments_: readonly unknown[]) => {\n if (transactions.currentContext()) transactions.rejectMixedTransaction();\n const method = Reflect.get(target, property, target);\n if (typeof method != \"function\") throw new TypeError(\"Invalid ORM transaction method\");\n return Reflect.apply(method, target, arguments_);\n };\n const value: unknown = Reflect.get(target, property, target);\n return typeof value == \"function\" ? value.bind(target) : value;\n },\n });\n}\n","import type { DuraxisORM, EntityClass, Repository, TransactionContext } from \"@duraxis/orm\";\nimport type { DuraxisNestConnection } from \"../duraxis.connection.js\";\nimport { normalizeDuraxisConnectionName } from \"../duraxis.tokens.js\";\nimport {\n ExistingTransactionError,\n NestedTransactionNotSupportedError,\n ReadOnlyTransactionError,\n TransactionContextClosedError,\n TransactionManagerShuttingDownError,\n TransactionRequiredError,\n TransactionalMethodReturnTypeError,\n UnawaitedTransactionOperationError,\n UnexpectedTransactionRollbackError,\n UnsupportedMixedTransactionError,\n UnsupportedTransactionIsolationError,\n UnsupportedTransactionTimeoutError,\n} from \"./transaction.errors.js\";\nimport {\n TransactionContextManager,\n type PhysicalTransactionState,\n type TransactionExecutionContext,\n} from \"./transaction-context.manager.js\";\nimport {\n TransactionIsolation,\n TransactionPropagation,\n type ErrorConstructor,\n type TransactionStatus,\n type TransactionalOptions,\n} from \"./transaction.types.js\";\nimport {\n createTransactionAwareOrm,\n createTransactionAwareRepository,\n} from \"./transaction-aware.repository.js\";\n\nclass RollbackOnlyAbort extends Error {}\n\ntype PhysicalOutcome<TResult> =\n | { readonly type: \"result\"; readonly value: TResult }\n | { readonly type: \"committed-error\"; readonly error: unknown };\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return (\n (typeof value == \"object\" || typeof value == \"function\") &&\n value != null &&\n typeof Reflect.get(value, \"then\") == \"function\"\n );\n}\n\nfunction inheritanceDistance(error: Error, constructor: ErrorConstructor): number {\n if (!(error instanceof constructor)) return Number.POSITIVE_INFINITY;\n let distance = 0;\n let prototype: object | null = Object.getPrototypeOf(error);\n while (prototype && prototype != constructor.prototype) {\n prototype = Object.getPrototypeOf(prototype);\n distance++;\n }\n return distance;\n}\n\nfunction shouldRollback(error: unknown, options: TransactionalOptions): boolean {\n if (!(error instanceof Error)) return true;\n let bestDistance = Number.POSITIVE_INFINITY;\n let rollback = true;\n for (const constructor of options.rollbackFor ?? []) {\n const distance = inheritanceDistance(error, constructor);\n if (distance < bestDistance) {\n bestDistance = distance;\n rollback = true;\n }\n }\n for (const constructor of options.noRollbackFor ?? []) {\n const distance = inheritanceDistance(error, constructor);\n if (distance <= bestDistance) {\n bestDistance = distance;\n rollback = false;\n }\n }\n return rollback;\n}\n\nexport class TransactionManager {\n readonly #repositories = new Map<Function, unknown>();\n readonly #ormFacade: DuraxisORM;\n #accepting = true;\n #activePhysicalTransactions = 0;\n readonly #shutdownWaiters = new Set<() => void>();\n\n public constructor(\n public readonly connectionName: string,\n private readonly connection: DuraxisNestConnection,\n private readonly orm: DuraxisORM,\n private readonly contexts: TransactionContextManager,\n ) {\n this.#ormFacade = createTransactionAwareOrm(orm, this);\n }\n\n public get ormProxy(): DuraxisORM {\n return this.#ormFacade;\n }\n\n public getRepository<TEntity extends object>(entity: EntityClass<TEntity>): Repository<TEntity> {\n const cached = this.#repositories.get(entity);\n if (cached) return cached as Repository<TEntity>;\n const repository = createTransactionAwareRepository(\n entity,\n this.orm.getRepository(entity),\n this,\n );\n this.#repositories.set(entity, repository);\n return repository;\n }\n\n public currentContext(): TransactionExecutionContext | undefined {\n const context = this.contexts.current(this.connection);\n if (context && !context.physical.active) throw new TransactionContextClosedError();\n return context;\n }\n\n public currentStatus(): TransactionStatus | null {\n const context = this.currentContext();\n return context\n ? {\n connectionName: this.connectionName,\n active: context.physical.active,\n newTransaction: context.newTransaction,\n readOnly: context.readOnly,\n rollbackOnly: context.physical.rollbackOnly,\n }\n : null;\n }\n\n public setRollbackOnly(): void {\n const context = this.currentContext();\n if (!context) throw new TransactionRequiredError(this.connectionName);\n context.physical.rollbackOnly = true;\n }\n\n public async execute<TResult>(\n options: TransactionalOptions,\n methodName: string,\n invocation: () => unknown,\n ): Promise<TResult> {\n this.validateOptions(options);\n const current = this.currentContext();\n if (!this.#accepting && !current) throw new TransactionManagerShuttingDownError();\n const propagation = options.propagation ?? TransactionPropagation.REQUIRED;\n switch (propagation) {\n case TransactionPropagation.REQUIRED:\n return current\n ? await this.join<TResult>(current, options, methodName, invocation)\n : await this.start<TResult>(options, methodName, invocation);\n case TransactionPropagation.REQUIRES_NEW:\n return await this.start<TResult>(options, methodName, invocation);\n case TransactionPropagation.SUPPORTS:\n return current\n ? await this.join<TResult>(current, options, methodName, invocation)\n : await this.invoke<TResult>(methodName, invocation);\n case TransactionPropagation.MANDATORY:\n if (!current) throw new TransactionRequiredError(this.connectionName);\n return await this.join<TResult>(current, options, methodName, invocation);\n case TransactionPropagation.NOT_SUPPORTED:\n return current\n ? await this.contexts.suspend(\n this.connection,\n async () => await this.invoke<TResult>(methodName, invocation),\n )\n : await this.invoke<TResult>(methodName, invocation);\n case TransactionPropagation.NEVER:\n if (current) throw new ExistingTransactionError(this.connectionName);\n return await this.invoke<TResult>(methodName, invocation);\n case TransactionPropagation.NESTED:\n throw new NestedTransactionNotSupportedError();\n }\n }\n\n public resolveRepository<TEntity extends object>(\n entity: EntityClass<TEntity>,\n baseRepository: Repository<TEntity>,\n ): Repository<TEntity> {\n const context = this.currentContext();\n return context ? context.physical.manager.getRepository(entity) : baseRepository;\n }\n\n public assertWriteAllowed(operation: string): void {\n if (this.currentContext()?.readOnly) throw new ReadOnlyTransactionError(operation);\n }\n\n public assertCapturedContext(captured: TransactionExecutionContext | undefined): void {\n if (!captured) return;\n const current = this.currentContext();\n if (!captured.physical.active || current?.physical != captured.physical)\n throw new TransactionContextClosedError();\n }\n\n public track(value: PromiseLike<unknown>): Promise<unknown> {\n const context = this.currentContext();\n const promise = Promise.resolve(value);\n if (!context) return promise;\n let tracked!: Promise<unknown>;\n tracked = (async () => {\n try {\n return await promise;\n } finally {\n context.physical.pending.delete(tracked);\n }\n })();\n context.physical.pending.add(tracked);\n return tracked;\n }\n\n public rejectMixedTransaction(): never {\n throw new UnsupportedMixedTransactionError();\n }\n\n public async shutdown(): Promise<void> {\n this.#accepting = false;\n if (this.#activePhysicalTransactions == 0) return;\n await new Promise<void>((resolve) => this.#shutdownWaiters.add(resolve));\n }\n\n private async start<TResult>(\n options: TransactionalOptions,\n methodName: string,\n invocation: () => unknown,\n ): Promise<TResult> {\n if (!this.#accepting) throw new TransactionManagerShuttingDownError();\n this.#activePhysicalTransactions++;\n try {\n const outcome = await this.orm.transaction(async (manager) => {\n const physical: PhysicalTransactionState = {\n manager,\n pending: new Set(),\n active: true,\n rollbackOnly: false,\n };\n const context: TransactionExecutionContext = {\n physical,\n readOnly: options.readOnly ?? false,\n newTransaction: true,\n };\n try {\n return await this.contexts.run(this.connection, context, async () => {\n try {\n const value = await this.invoke<TResult>(methodName, invocation);\n await this.rejectPendingOperations(physical);\n if (physical.rollbackOnly) throw new RollbackOnlyAbort();\n return { type: \"result\", value } satisfies PhysicalOutcome<TResult>;\n } catch (error) {\n await this.rejectPendingOperations(physical);\n if (error instanceof RollbackOnlyAbort || shouldRollback(error, options)) throw error;\n return { type: \"committed-error\", error } satisfies PhysicalOutcome<TResult>;\n }\n });\n } finally {\n physical.active = false;\n }\n });\n if (outcome.type == \"committed-error\") throw outcome.error;\n return outcome.value;\n } catch (error) {\n if (error instanceof RollbackOnlyAbort) throw new UnexpectedTransactionRollbackError();\n throw error;\n } finally {\n this.#activePhysicalTransactions--;\n if (this.#activePhysicalTransactions == 0)\n for (const resolve of this.#shutdownWaiters) resolve();\n if (this.#activePhysicalTransactions == 0) this.#shutdownWaiters.clear();\n }\n }\n\n private async join<TResult>(\n current: TransactionExecutionContext,\n options: TransactionalOptions,\n methodName: string,\n invocation: () => unknown,\n ): Promise<TResult> {\n const context: TransactionExecutionContext = {\n physical: current.physical,\n readOnly: current.readOnly || (options.readOnly ?? false),\n newTransaction: false,\n };\n return await this.contexts.run(this.connection, context, async () => {\n try {\n return await this.invoke<TResult>(methodName, invocation);\n } catch (error) {\n if (shouldRollback(error, options)) current.physical.rollbackOnly = true;\n throw error;\n }\n });\n }\n\n private async invoke<TResult>(methodName: string, invocation: () => unknown): Promise<TResult> {\n const result = invocation();\n if (!isPromiseLike(result)) throw new TransactionalMethodReturnTypeError(methodName);\n return (await result) as TResult;\n }\n\n private async rejectPendingOperations(physical: PhysicalTransactionState): Promise<void> {\n if (physical.pending.size == 0) return;\n const results = await Promise.allSettled([...physical.pending]);\n const rejected = results.find((result) => result.status == \"rejected\");\n throw new UnawaitedTransactionOperationError(\n rejected?.status == \"rejected\" ? { cause: rejected.reason } : undefined,\n );\n }\n\n private validateOptions(options: TransactionalOptions): void {\n if (options.timeout != null) throw new UnsupportedTransactionTimeoutError();\n const isolation = options.isolation ?? TransactionIsolation.DEFAULT;\n if (isolation != TransactionIsolation.DEFAULT && isolation != TransactionIsolation.SNAPSHOT)\n throw new UnsupportedTransactionIsolationError(String(isolation));\n if (options.connectionName != null) normalizeDuraxisConnectionName(options.connectionName);\n }\n}\n","import type { TransactionalOptions } from \"./transaction.types.js\";\n\nexport const TRANSACTIONAL_METADATA = Symbol.for(\"@duraxis/nestjs/transactional\");\n\nexport function Transactional(\n options: TransactionalOptions = {},\n): ClassDecorator & MethodDecorator {\n return (\n target: object | Function,\n _propertyKey?: string | symbol,\n descriptor?: PropertyDescriptor,\n ) => {\n const metadataTarget = descriptor?.value ?? target;\n Reflect.defineMetadata(TRANSACTIONAL_METADATA, Object.freeze({ ...options }), metadataTarget);\n };\n}\n\n/** Alias of `@Transactional()`. It is unrelated to `Transaction` from `@duraxis/core`. */\nexport const Transaction = Transactional;\n\nexport function transactionalOptions(\n instance: object,\n method: Function,\n): TransactionalOptions | undefined {\n const classOptions = Reflect.getMetadata(TRANSACTIONAL_METADATA, instance.constructor) as\n TransactionalOptions | undefined;\n const methodOptions = Reflect.getMetadata(TRANSACTIONAL_METADATA, method) as\n TransactionalOptions | undefined;\n if (!classOptions && !methodOptions) return undefined;\n return { ...classOptions, ...methodOptions };\n}\n","import type { FactoryProvider, Type } from \"@nestjs/common\";\nimport { ModuleRef } from \"@nestjs/core\";\nimport { normalizeDuraxisConnectionName } from \"../duraxis.tokens.js\";\nimport { TransactionManagerRegistry } from \"./transaction-manager.registry.js\";\nimport { transactionalOptions } from \"./transactional.decorator.js\";\n\nconst LIFECYCLE_METHODS = new Set<PropertyKey>([\n \"onModuleInit\",\n \"onApplicationBootstrap\",\n \"onModuleDestroy\",\n \"beforeApplicationShutdown\",\n \"onApplicationShutdown\",\n]);\n\nexport function createTransactionalServiceProxy<TService extends object>(\n instance: TService,\n managers: TransactionManagerRegistry,\n defaultConnectionName: string,\n): TService {\n const methods = new Map<PropertyKey, unknown>();\n return new Proxy(instance, {\n get(target, property) {\n const cached = methods.get(property);\n if (cached) return cached;\n const value: unknown = Reflect.get(target, property, target);\n if (typeof value != \"function\") return value;\n const options = LIFECYCLE_METHODS.has(property)\n ? undefined\n : transactionalOptions(target, value);\n const method = options\n ? (...arguments_: readonly unknown[]) => {\n const connectionName = normalizeDuraxisConnectionName(\n options.connectionName ?? defaultConnectionName,\n );\n return managers\n .get(connectionName)\n .execute(options, `${target.constructor.name}.${String(property)}`, () =>\n Reflect.apply(value, target, arguments_),\n );\n }\n : value.bind(target);\n methods.set(property, method);\n return method;\n },\n });\n}\n\nexport function transactionalServiceProvider<TService extends object>(\n service: Type<TService>,\n defaultConnectionName: string,\n): FactoryProvider<TService> {\n return {\n provide: service,\n inject: [ModuleRef, TransactionManagerRegistry],\n useFactory: async (\n moduleRef: ModuleRef,\n managers: TransactionManagerRegistry,\n ): Promise<TService> =>\n createTransactionalServiceProxy(\n await moduleRef.create(service),\n managers,\n defaultConnectionName,\n ),\n };\n}\n","import type { DynamicModule, FactoryProvider, Provider, Type, ValueProvider } from \"@nestjs/common\";\nimport { Module } from \"@nestjs/common\";\nimport { DiscoveryModule, DiscoveryService } from \"@nestjs/core\";\nimport type { DuraxisORM, EntityClass, Repository } from \"@duraxis/orm\";\nimport { DuraxisNestConnection } from \"./duraxis.connection.js\";\nimport type {\n DuraxisModuleAsyncOptions,\n DuraxisModuleOptions,\n DuraxisRootModuleOptions,\n} from \"./duraxis.interfaces.js\";\nimport {\n getDuraxisConnectionToken,\n getDuraxisDatabaseToken,\n getDuraxisOptionsToken,\n getDuraxisOrmToken,\n getDuraxisRepositoryToken,\n getDuraxisTransactionManagerToken,\n normalizeDuraxisConnectionName,\n} from \"./duraxis.tokens.js\";\nimport { DuraxisConnectionRegistry, DuraxisConnectionRegistryModule } from \"./duraxis.registry.js\";\nimport { discoverFeatureEntities, DuraxisFeatureEntities } from \"./duraxis.feature-discovery.js\";\nimport { TransactionContextManager } from \"./transactions/transaction-context.manager.js\";\nimport { TransactionManagerRegistry } from \"./transactions/transaction-manager.registry.js\";\nimport { TransactionManager } from \"./transactions/transaction.manager.js\";\nimport { transactionalServiceProvider } from \"./transactions/transactional.proxy.js\";\n\nfunction rootProviders(\n name: string,\n optionsProvider: Provider<DuraxisModuleOptions>,\n): readonly Provider[] {\n const connectionToken = getDuraxisConnectionToken(name);\n const ormToken = getDuraxisOrmToken(name);\n const databaseToken = getDuraxisDatabaseToken(name);\n const transactionManagerToken = getDuraxisTransactionManagerToken(name);\n return [\n optionsProvider,\n {\n provide: connectionToken,\n inject: [getDuraxisOptionsToken(name), DuraxisConnectionRegistry, DiscoveryService],\n useFactory: async (\n options: DuraxisModuleOptions,\n registry: DuraxisConnectionRegistry,\n discovery: DiscoveryService,\n ): Promise<DuraxisNestConnection> => {\n const entities = new Set(options.entities ?? []);\n if (options.autoLoadEntities)\n for (const entity of discoverFeatureEntities(discovery, name)) entities.add(entity);\n return await registry.create(name, { ...options, entities: [...entities] });\n },\n },\n {\n provide: transactionManagerToken,\n inject: [connectionToken, TransactionContextManager, TransactionManagerRegistry],\n useFactory: (\n connection: DuraxisNestConnection,\n contexts: TransactionContextManager,\n managers: TransactionManagerRegistry,\n ): TransactionManager => {\n const manager = new TransactionManager(name, connection, connection.orm, contexts);\n managers.register(name, manager);\n connection.setBeforeClose(async () => {\n await manager.shutdown();\n managers.unregister(name, manager);\n });\n return manager;\n },\n },\n {\n provide: ormToken,\n inject: [transactionManagerToken],\n useFactory: (transactions: TransactionManager) => transactions.ormProxy,\n },\n {\n provide: databaseToken,\n inject: [connectionToken],\n useFactory: (connection: DuraxisNestConnection) => connection.database,\n },\n ];\n}\n\nfunction rootModule(\n name: string,\n providers: readonly Provider[],\n imports: DynamicModule[\"imports\"] = [],\n): DynamicModule {\n return {\n module: DuraxisModule,\n global: true,\n imports: [DiscoveryModule, DuraxisConnectionRegistryModule, ...(imports ?? [])],\n providers: [...providers],\n exports: [\n getDuraxisOrmToken(name),\n getDuraxisDatabaseToken(name),\n getDuraxisTransactionManagerToken(name),\n ],\n };\n}\n\nfunction featureModule(\n entities: readonly EntityClass[],\n services: readonly Type<object>[],\n connectionName?: string,\n): DynamicModule {\n const name = normalizeDuraxisConnectionName(connectionName);\n const uniqueEntities = [...new Set(entities)];\n const uniqueServices = [...new Set(services)];\n const repositoryProviders = uniqueEntities.map((entity) => repositoryProvider(entity, name));\n const serviceProviders = uniqueServices.map((service) =>\n transactionalServiceProvider(service, name),\n );\n\n @DuraxisFeatureEntities({ connectionName: name, entities: uniqueEntities })\n class DuraxisFeatureEntitiesMarker {}\n\n return {\n module: DuraxisModule,\n providers: [DuraxisFeatureEntitiesMarker, ...repositoryProviders, ...serviceProviders],\n exports: [...repositoryProviders.map((provider) => provider.provide), ...uniqueServices],\n };\n}\n\nfunction repositoryProvider<TEntity extends object>(\n entity: EntityClass<TEntity>,\n connectionName: string,\n): FactoryProvider<Repository<TEntity>> {\n return {\n provide: getDuraxisRepositoryToken(entity, connectionName),\n inject: [getDuraxisOrmToken(connectionName)],\n useFactory: (orm: DuraxisORM): Repository<TEntity> => orm.getRepository(entity),\n };\n}\n\n@Module({})\nexport class DuraxisModule {\n public static forRoot(options: DuraxisRootModuleOptions): DynamicModule {\n const name = normalizeDuraxisConnectionName(options.name);\n const connectionOptions: DuraxisModuleOptions = {\n driver: options.driver,\n ...(options.entities == null ? {} : { entities: options.entities }),\n ...(options.autoLoadEntities == null ? {} : { autoLoadEntities: options.autoLoadEntities }),\n ...(options.database == null ? {} : { database: options.database }),\n ...(options.schema == null ? {} : { schema: options.schema }),\n ...(options.closeStorage == null ? {} : { closeStorage: options.closeStorage }),\n };\n const optionsProvider: ValueProvider<DuraxisModuleOptions> = {\n provide: getDuraxisOptionsToken(name),\n useValue: connectionOptions,\n };\n return rootModule(name, rootProviders(name, optionsProvider));\n }\n\n public static forRootAsync<TArguments extends readonly unknown[]>(\n options: DuraxisModuleAsyncOptions<TArguments>,\n ): DynamicModule {\n const name = normalizeDuraxisConnectionName(options.name);\n const optionsProvider: FactoryProvider<DuraxisModuleOptions> = {\n provide: getDuraxisOptionsToken(name),\n inject: options.inject == null ? [] : [...options.inject],\n useFactory: options.useFactory,\n };\n return rootModule(name, rootProviders(name, optionsProvider), options.imports);\n }\n\n public static forFeature(\n entities: readonly EntityClass[],\n connectionName?: string,\n ): DynamicModule {\n return featureModule(entities, [], connectionName);\n }\n\n public static forTransactionalFeature(\n entities: readonly EntityClass[],\n providers: readonly Type<object>[],\n connectionName?: string,\n ): DynamicModule {\n return featureModule(entities, providers, connectionName);\n }\n\n public static forTransactionalProviders(\n providers: readonly Type<object>[],\n connectionName?: string,\n ): DynamicModule {\n return featureModule([], providers, connectionName);\n }\n}\n","import { Inject } from \"@nestjs/common\";\nimport type { EntityClass } from \"@duraxis/orm\";\nimport {\n getDuraxisDatabaseToken,\n getDuraxisOrmToken,\n getDuraxisRepositoryToken,\n getDuraxisTransactionManagerToken,\n} from \"./duraxis.tokens.js\";\n\nexport function InjectDuraxisRepository<TEntity extends object>(\n entity: EntityClass<TEntity>,\n connectionName?: string,\n): ParameterDecorator & PropertyDecorator {\n return Inject(getDuraxisRepositoryToken(entity, connectionName));\n}\n\nexport function InjectDuraxisOrm(connectionName?: string): ParameterDecorator & PropertyDecorator {\n return Inject(getDuraxisOrmToken(connectionName));\n}\n\nexport function InjectDuraxisDatabase(\n connectionName?: string,\n): ParameterDecorator & PropertyDecorator {\n return Inject(getDuraxisDatabaseToken(connectionName));\n}\n\nexport function InjectDuraxisTransactionManager(\n connectionName?: string,\n): ParameterDecorator & PropertyDecorator {\n return Inject(getDuraxisTransactionManagerToken(connectionName));\n}\n"],"mappings":";;;;;;AAEA,IAAa,6BAA6B;AAE1C,IAAM,mCAAmB,IAAI,QAAuC;AAEpE,SAAgB,+BAA+B,MAAuB;CACpE,MAAM,aAAa,QAAA;CACnB,IACE,OAAO,cAAc,YACrB,WAAW,KAAK,KAAK,MACrB,WAAW,SAAS,OACpB,WAAW,SAAS,IAAI,GAExB,MAAM,IAAI,UACR,8EACF;CACF,OAAO;AACT;AAEA,SAAS,gBAAgB,MAAc,gBAAiC;CACtE,MAAM,OAAO,+BAA+B,cAAc;CAC1D,OAAO,OAAO,IAAI,mBAAmB,KAAK,GAAG,mBAAmB,IAAI,GAAG;AACzE;AAEA,SAAgB,mBAAmB,gBAAiC;CAClE,OAAO,gBAAgB,OAAO,cAAc;AAC9C;AAEA,SAAgB,wBAAwB,gBAAiC;CACvE,OAAO,gBAAgB,YAAY,cAAc;AACnD;AAEA,SAAgB,kCAAkC,gBAAiC;CACjF,OAAO,gBAAgB,uBAAuB,cAAc;AAC9D;AAEA,SAAgB,0BACd,QACA,gBACQ;CACR,MAAM,OAAO,+BAA+B,cAAc;CAC1D,IAAI,eAAe,iBAAiB,IAAI,MAAM;CAC9C,IAAI,CAAC,cAAc;EACjB,+BAAe,IAAI,IAAI;EACvB,iBAAiB,IAAI,QAAQ,YAAY;CAC3C;CACA,IAAI,QAAQ,aAAa,IAAI,IAAI;CACjC,IAAI,CAAC,OAAO;EACV,QAAQ,OAAO,8BAA8B,KAAK,GAAG,OAAO,MAAM;EAClE,aAAa,IAAI,MAAM,KAAK;CAC9B;CACA,OAAO;AACT;AAEA,SAAgB,uBAAuB,gBAAiC;CACtE,OAAO,gBAAgB,WAAW,cAAc;AAClD;AAEA,SAAgB,0BAA0B,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UAAU,WAAW,cAAc;CAC1D;CAEA,OAAc,0BACZ,WACA,gBACe;EACf,OAAO,cAAc,CAAC,GAAG,WAAW,cAAc;CACpD;AACF;AApDC,gBAAAA,WAAA,CAAA,OAAO,CAAC,CAAC,CAAA,GAAA,aAAA;;AC3HV,SAAgB,wBACd,QACA,gBACwC;CACxC,OAAO,OAAO,0BAA0B,QAAQ,cAAc,CAAC;AACjE;AAEA,SAAgB,iBAAiB,gBAAiE;CAChG,OAAO,OAAO,mBAAmB,cAAc,CAAC;AAClD;AAEA,SAAgB,sBACd,gBACwC;CACxC,OAAO,OAAO,wBAAwB,cAAc,CAAC;AACvD;AAEA,SAAgB,gCACd,gBACwC;CACxC,OAAO,OAAO,kCAAkC,cAAc,CAAC;AACjE"}
@@ -0,0 +1,4 @@
1
+ import { type DuraxisORM, type EntityClass, type Repository } from "@duraxis/orm";
2
+ import type { TransactionManager } from "./transaction.manager.js";
3
+ export declare function createTransactionAwareRepository<TEntity extends object>(entity: EntityClass<TEntity>, baseRepository: Repository<TEntity>, transactions: TransactionManager): Repository<TEntity>;
4
+ export declare function createTransactionAwareOrm(orm: DuraxisORM, transactions: TransactionManager): DuraxisORM;
@@ -0,0 +1,18 @@
1
+ import type { TransactionContext } from "@duraxis/orm";
2
+ export interface PhysicalTransactionState {
3
+ readonly manager: TransactionContext;
4
+ readonly pending: Set<Promise<unknown>>;
5
+ active: boolean;
6
+ rollbackOnly: boolean;
7
+ }
8
+ export interface TransactionExecutionContext {
9
+ readonly physical: PhysicalTransactionState;
10
+ readonly readOnly: boolean;
11
+ readonly newTransaction: boolean;
12
+ }
13
+ export declare class TransactionContextManager {
14
+ #private;
15
+ current(connectionIdentity: object): TransactionExecutionContext | undefined;
16
+ run<TResult>(connectionIdentity: object, context: TransactionExecutionContext, callback: () => Promise<TResult>): Promise<TResult>;
17
+ suspend<TResult>(connectionIdentity: object, callback: () => Promise<TResult>): Promise<TResult>;
18
+ }
@@ -0,0 +1,7 @@
1
+ import type { TransactionManager } from "./transaction.manager.js";
2
+ export declare class TransactionManagerRegistry {
3
+ #private;
4
+ register(connectionName: string, manager: TransactionManager): void;
5
+ unregister(connectionName: string, manager: TransactionManager): void;
6
+ get(connectionName: string): TransactionManager;
7
+ }
@@ -0,0 +1,40 @@
1
+ import { DuraxisNestError } from "../duraxis.errors.js";
2
+ export declare class TransactionRequiredError extends DuraxisNestError {
3
+ constructor(connectionName: string);
4
+ }
5
+ export declare class ExistingTransactionError extends DuraxisNestError {
6
+ constructor(connectionName: string);
7
+ }
8
+ export declare class NestedTransactionNotSupportedError extends DuraxisNestError {
9
+ constructor();
10
+ }
11
+ export declare class UnsupportedTransactionIsolationError extends DuraxisNestError {
12
+ constructor(isolation: string);
13
+ }
14
+ export declare class UnsupportedTransactionTimeoutError extends DuraxisNestError {
15
+ constructor();
16
+ }
17
+ export declare class ReadOnlyTransactionError extends DuraxisNestError {
18
+ constructor(operation: string);
19
+ }
20
+ export declare class UnexpectedTransactionRollbackError extends DuraxisNestError {
21
+ constructor();
22
+ }
23
+ export declare class TransactionContextClosedError extends DuraxisNestError {
24
+ constructor();
25
+ }
26
+ export declare class TransactionalMethodReturnTypeError extends DuraxisNestError {
27
+ constructor(methodName: string);
28
+ }
29
+ export declare class UnsupportedMixedTransactionError extends DuraxisNestError {
30
+ constructor();
31
+ }
32
+ export declare class UnawaitedTransactionOperationError extends DuraxisNestError {
33
+ constructor(options?: ErrorOptions);
34
+ }
35
+ export declare class TransactionManagerShuttingDownError extends DuraxisNestError {
36
+ constructor();
37
+ }
38
+ export declare class TransactionManagerNotFoundError extends DuraxisNestError {
39
+ constructor(connectionName: string);
40
+ }
@@ -0,0 +1,29 @@
1
+ import type { DuraxisORM, EntityClass, Repository } from "@duraxis/orm";
2
+ import type { DuraxisNestConnection } from "../duraxis.connection.js";
3
+ import { TransactionContextManager, type TransactionExecutionContext } from "./transaction-context.manager.js";
4
+ import { type TransactionStatus, type TransactionalOptions } from "./transaction.types.js";
5
+ export declare class TransactionManager {
6
+ #private;
7
+ readonly connectionName: string;
8
+ private readonly connection;
9
+ private readonly orm;
10
+ private readonly contexts;
11
+ constructor(connectionName: string, connection: DuraxisNestConnection, orm: DuraxisORM, contexts: TransactionContextManager);
12
+ get ormProxy(): DuraxisORM;
13
+ getRepository<TEntity extends object>(entity: EntityClass<TEntity>): Repository<TEntity>;
14
+ currentContext(): TransactionExecutionContext | undefined;
15
+ currentStatus(): TransactionStatus | null;
16
+ setRollbackOnly(): void;
17
+ execute<TResult>(options: TransactionalOptions, methodName: string, invocation: () => unknown): Promise<TResult>;
18
+ resolveRepository<TEntity extends object>(entity: EntityClass<TEntity>, baseRepository: Repository<TEntity>): Repository<TEntity>;
19
+ assertWriteAllowed(operation: string): void;
20
+ assertCapturedContext(captured: TransactionExecutionContext | undefined): void;
21
+ track(value: PromiseLike<unknown>): Promise<unknown>;
22
+ rejectMixedTransaction(): never;
23
+ shutdown(): Promise<void>;
24
+ private start;
25
+ private join;
26
+ private invoke;
27
+ private rejectPendingOperations;
28
+ private validateOptions;
29
+ }
@@ -0,0 +1,30 @@
1
+ export declare enum TransactionPropagation {
2
+ REQUIRED = "REQUIRED",
3
+ REQUIRES_NEW = "REQUIRES_NEW",
4
+ SUPPORTS = "SUPPORTS",
5
+ MANDATORY = "MANDATORY",
6
+ NOT_SUPPORTED = "NOT_SUPPORTED",
7
+ NEVER = "NEVER",
8
+ NESTED = "NESTED"
9
+ }
10
+ export declare enum TransactionIsolation {
11
+ DEFAULT = "DEFAULT",
12
+ SNAPSHOT = "SNAPSHOT"
13
+ }
14
+ export type ErrorConstructor = new (...arguments_: never[]) => Error;
15
+ export interface TransactionalOptions {
16
+ readonly propagation?: TransactionPropagation;
17
+ readonly isolation?: TransactionIsolation;
18
+ readonly readOnly?: boolean;
19
+ readonly timeout?: number;
20
+ readonly rollbackFor?: readonly ErrorConstructor[];
21
+ readonly noRollbackFor?: readonly ErrorConstructor[];
22
+ readonly connectionName?: string;
23
+ }
24
+ export interface TransactionStatus {
25
+ readonly connectionName: string;
26
+ readonly active: boolean;
27
+ readonly newTransaction: boolean;
28
+ readonly readOnly: boolean;
29
+ readonly rollbackOnly: boolean;
30
+ }
@@ -0,0 +1,6 @@
1
+ import type { TransactionalOptions } from "./transaction.types.js";
2
+ export declare const TRANSACTIONAL_METADATA: unique symbol;
3
+ export declare function Transactional(options?: TransactionalOptions): ClassDecorator & MethodDecorator;
4
+ /** Alias of `@Transactional()`. It is unrelated to `Transaction` from `@duraxis/core`. */
5
+ export declare const Transaction: typeof Transactional;
6
+ export declare function transactionalOptions(instance: object, method: Function): TransactionalOptions | undefined;
@@ -0,0 +1,4 @@
1
+ import type { FactoryProvider, Type } from "@nestjs/common";
2
+ import { TransactionManagerRegistry } from "./transaction-manager.registry.js";
3
+ export declare function createTransactionalServiceProxy<TService extends object>(instance: TService, managers: TransactionManagerRegistry, defaultConnectionName: string): TService;
4
+ export declare function transactionalServiceProvider<TService extends object>(service: Type<TService>, defaultConnectionName: string): FactoryProvider<TService>;
package/package.json CHANGED
@@ -1,6 +1,72 @@
1
1
  {
2
2
  "name": "@duraxis/nestjs",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "NestJS modules, injection tokens, repositories, and transactions for Duraxis.",
5
+ "license": "ISC",
6
+ "author": "João Paulo Dias <joaopdias.dev@gmail.com>",
7
+ "keywords": [
8
+ "duraxis",
9
+ "nestjs",
10
+ "database",
11
+ "orm",
12
+ "typescript"
13
+ ],
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "https://github.com/Joaopdiasventura/Duraxis.git",
17
+ "directory": "packages/nestjs"
18
+ },
19
+ "homepage": "https://github.com/Joaopdiasventura/Duraxis/tree/main/packages/nestjs#readme",
20
+ "bugs": {
21
+ "url": "https://github.com/Joaopdiasventura/Duraxis/issues"
22
+ },
23
+ "engines": {
24
+ "node": ">=22.12.0"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public",
28
+ "registry": "https://registry.npmjs.org/"
29
+ },
30
+ "type": "module",
31
+ "main": "./dist/index.cjs",
32
+ "module": "./dist/index.js",
33
+ "types": "./dist/index.d.ts",
34
+ "exports": {
35
+ ".": {
36
+ "types": "./dist/index.d.ts",
37
+ "import": "./dist/index.js",
38
+ "require": "./dist/index.cjs"
39
+ }
40
+ },
41
+ "files": [
42
+ "dist",
43
+ "README.md",
44
+ "LICENSE",
45
+ "CHANGELOG.md"
46
+ ],
47
+ "dependencies": {
48
+ "@duraxis/core": "0.1.0",
49
+ "@duraxis/orm": "0.1.0",
50
+ "@duraxis/storage": "0.1.0"
51
+ },
52
+ "peerDependencies": {
53
+ "@nestjs/common": "^10.0.0 || ^11.0.0",
54
+ "@nestjs/core": "^10.0.0 || ^11.0.0"
55
+ },
56
+ "devDependencies": {
57
+ "@duraxis/storage-disk": "0.1.0",
58
+ "@duraxis/storage-memory": "0.1.0",
59
+ "@nestjs/common": "^11.0.0",
60
+ "@nestjs/core": "^11.0.0",
61
+ "@nestjs/testing": "^11.0.0",
62
+ "reflect-metadata": "^0.2.2",
63
+ "rxjs": "^7.8.1"
64
+ },
65
+ "scripts": {
66
+ "build": "vite build && tsc -p tsconfig.build.json",
67
+ "dev": "vite build --watch",
68
+ "typecheck": "tsc --noEmit",
69
+ "test": "vitest run",
70
+ "test:watch": "vitest"
71
+ }
6
72
  }