@duraxis/nestjs 0.3.0 → 0.5.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.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- import { Global, Inject, Injectable, Module, Scope } from "@nestjs/common";
1
+ import { Global, Inject, Injectable, Module } from "@nestjs/common";
2
2
  import { DiscoveryModule, DiscoveryService } from "@nestjs/core";
3
- import { DuraxisDatabase } from "@duraxis/core";
4
- import { DuraxisORM, QueryBuilder } from "@duraxis/orm";
3
+ import { DuraxisORM, QueryBuilder, discoverEntities } from "@duraxis/orm";
4
+ import { DuraxisDatabase, isDuraxisConfiguration, normalizeDuraxisConnection, selectDuraxisConnection } from "@duraxis/core";
5
5
  import { AsyncLocalStorage } from "node:async_hooks";
6
6
  // src/duraxis.tokens.ts
7
7
  var DEFAULT_DURAXIS_CONNECTION = "default";
@@ -461,6 +461,7 @@ var TransactionManager = class {
461
461
  #ormFacade;
462
462
  #accepting = true;
463
463
  #activePhysicalTransactions = 0;
464
+ #shutdown;
464
465
  #shutdownWaiters = /* @__PURE__ */ new Set();
465
466
  constructor(connectionName, connection, orm, contexts) {
466
467
  this.connectionName = connectionName;
@@ -547,10 +548,27 @@ var TransactionManager = class {
547
548
  rejectMixedTransaction() {
548
549
  throw new UnsupportedMixedTransactionError();
549
550
  }
550
- async shutdown() {
551
+ shutdown(timeoutMs = 3e4) {
551
552
  this.#accepting = false;
552
- if (this.#activePhysicalTransactions == 0) return;
553
- await new Promise((resolve) => this.#shutdownWaiters.add(resolve));
553
+ if (this.#activePhysicalTransactions == 0) return Promise.resolve();
554
+ if (this.#shutdown) return this.#shutdown;
555
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1) return Promise.reject(/* @__PURE__ */ new RangeError("Invalid transaction-manager shutdown deadline"));
556
+ this.#shutdown = new Promise((resolve, reject) => {
557
+ const complete = () => {
558
+ clearTimeout(timer);
559
+ this.#shutdownWaiters.delete(complete);
560
+ resolve();
561
+ };
562
+ const timer = setTimeout(() => {
563
+ this.#shutdownWaiters.delete(complete);
564
+ reject(/* @__PURE__ */ new Error("Transaction-manager shutdown deadline exceeded; active operations remain"));
565
+ }, timeoutMs);
566
+ this.#shutdownWaiters.add(complete);
567
+ });
568
+ this.#shutdown.catch(() => {
569
+ this.#shutdown = void 0;
570
+ });
571
+ return this.#shutdown;
554
572
  }
555
573
  async start(options, methodName, invocation) {
556
574
  if (!this.#accepting) throw new TransactionManagerShuttingDownError();
@@ -563,6 +581,11 @@ var TransactionManager = class {
563
581
  active: true,
564
582
  rollbackOnly: false
565
583
  };
584
+ const abort = () => {
585
+ physical.active = false;
586
+ physical.pending.clear();
587
+ };
588
+ manager.signal?.addEventListener("abort", abort, { once: true });
566
589
  const context = {
567
590
  physical,
568
591
  readOnly: options.readOnly ?? false,
@@ -590,6 +613,7 @@ var TransactionManager = class {
590
613
  });
591
614
  } finally {
592
615
  physical.active = false;
616
+ manager.signal?.removeEventListener("abort", abort);
593
617
  }
594
618
  });
595
619
  if (outcome.type == "committed-error") throw outcome.error;
@@ -635,72 +659,25 @@ var TransactionManager = class {
635
659
  if (options.connectionName != null) normalizeDuraxisConnectionName(options.connectionName);
636
660
  }
637
661
  };
638
- // src/transactions/transactional.metadata.ts
639
- var TRANSACTIONAL_METADATA = Symbol.for("@duraxis/nestjs/transactional");
640
- function transactionalOptions(instance, method) {
641
- const classOptions = Reflect.getMetadata(TRANSACTIONAL_METADATA, instance.constructor);
642
- const methodOptions = Reflect.getMetadata(TRANSACTIONAL_METADATA, method);
643
- return !classOptions && !methodOptions ? void 0 : {
644
- ...classOptions,
645
- ...methodOptions
646
- };
647
- }
648
- // src/transactions/transactional.instrumentation.ts
649
- var MANAGERS = Symbol("Duraxis transaction managers");
650
- var bindings = /* @__PURE__ */ new WeakMap();
651
- var defaultConnections = /* @__PURE__ */ new WeakMap();
652
- var injectablePrototypes = /* @__PURE__ */ new WeakSet();
653
- var wrappers = /* @__PURE__ */ new WeakSet();
654
- var LIFECYCLE_METHODS = /* @__PURE__ */ new Set([
655
- "onModuleInit",
656
- "onApplicationBootstrap",
657
- "onModuleDestroy",
658
- "beforeApplicationShutdown",
659
- "onApplicationShutdown"
660
- ]);
661
- function injectTransactionManagers(prototype) {
662
- if (injectablePrototypes.has(prototype)) return;
663
- injectablePrototypes.add(prototype);
664
- Object.defineProperty(prototype, MANAGERS, { set(managers) {
665
- bindings.set(this, managers);
666
- instrumentTransactionalMethods(this);
667
- } });
668
- Inject(TransactionManagerRegistry)(prototype, MANAGERS);
669
- }
670
- function setTransactionalDefaultConnection(instance, name) {
671
- defaultConnections.set(instance, name);
672
- }
673
- function wrapTransactionalMethod(method, property) {
674
- if (wrappers.has(method)) return method;
675
- const wrapped = function(...arguments_) {
676
- const methodName = `${this.constructor.name}.${String(property)}`;
677
- const managers = bindings.get(this);
678
- if (!managers) throw new TransactionalProviderNotReadyError(methodName);
679
- const options = transactionalOptions(this, wrapped) ?? {};
680
- const name = normalizeDuraxisConnectionName(options.connectionName ?? defaultConnections.get(this));
681
- return managers.get(name).execute(options, methodName, () => Reflect.apply(method, this, arguments_));
662
+ // src/duraxis.module.ts
663
+ var _DuraxisModule;
664
+ function isSharedConfiguration(options) {
665
+ return isDuraxisConfiguration(options) || "location" in options || "baseDirectory" in options || "migrations" in options || typeof options.autoLoadEntities === "object" || typeof options.entities === "function" || typeof options.driver === "function" && options.driver.length > 0;
666
+ }
667
+ async function sharedConnectionOptions(config, discovery, name) {
668
+ const normalized = normalizeDuraxisConnection(config);
669
+ const entities = await discoverEntities(config);
670
+ const features = discoverFeatureEntities(discovery, name);
671
+ if (config.autoLoadEntities && features.length && (features.length !== entities.length || features.some((entity) => !entities.includes(entity)))) throw new Error(`Duraxis entity discovery differs from forFeature registrations for connection ${name}. Align feature registrations and configured directories.`);
672
+ const driver = config.driver;
673
+ return {
674
+ driver: typeof driver === "function" ? () => driver(normalized.context) : driver,
675
+ database: normalized.database,
676
+ schema: normalized.schema,
677
+ entities,
678
+ closeStorage: config.closeStorage ?? typeof driver === "function"
682
679
  };
683
- for (const key of Reflect.getOwnMetadataKeys(method)) Reflect.defineMetadata(key, Reflect.getOwnMetadata(key, method), wrapped);
684
- wrappers.add(wrapped);
685
- return wrapped;
686
- }
687
- function instrumentTransactionalMethods(target) {
688
- const visited = /* @__PURE__ */ new Set();
689
- for (let prototype = target; prototype && prototype != Object.prototype; prototype = Object.getPrototypeOf(prototype)) for (const property of Reflect.ownKeys(prototype)) {
690
- if (visited.has(property)) continue;
691
- visited.add(property);
692
- if (property == "constructor" || LIFECYCLE_METHODS.has(property)) continue;
693
- const descriptor = Object.getOwnPropertyDescriptor(prototype, property);
694
- const method = descriptor?.value;
695
- if (typeof method != "function" || !transactionalOptions(target, method)) continue;
696
- if (wrappers.has(method)) continue;
697
- Object.defineProperty(target, property, {
698
- ...descriptor,
699
- value: wrapTransactionalMethod(method, property)
700
- });
701
- }
702
680
  }
703
- // src/duraxis.module.ts
704
681
  function rootProviders(name, optionsProvider) {
705
682
  const connectionToken = getDuraxisConnectionToken(name);
706
683
  const ormToken = getDuraxisOrmToken(name);
@@ -770,25 +747,10 @@ function rootModule(name, providers, imports = []) {
770
747
  ]
771
748
  };
772
749
  }
773
- function featureModule(entities, services, connectionName) {
750
+ function featureModule(entities, connectionName) {
774
751
  const name = normalizeDuraxisConnectionName(connectionName);
775
752
  const uniqueEntities = [...new Set(entities)];
776
- const uniqueServices = [...new Set(services)];
777
753
  const repositoryProviders = uniqueEntities.map((entity) => repositoryProvider(entity, name));
778
- const serviceProviders = uniqueServices.flatMap((service) => {
779
- return [{
780
- provide: service,
781
- useClass: service,
782
- scope: Scope.DEFAULT
783
- }, {
784
- provide: Symbol(`${service.name} default transaction connection`),
785
- inject: [service],
786
- useFactory: (instance) => {
787
- setTransactionalDefaultConnection(instance, name);
788
- return name;
789
- }
790
- }];
791
- });
792
754
  let DuraxisFeatureEntitiesMarker = class DuraxisFeatureEntitiesMarker {};
793
755
  DuraxisFeatureEntitiesMarker = __decorate([DuraxisFeatureEntities({
794
756
  connectionName: name,
@@ -796,12 +758,8 @@ function featureModule(entities, services, connectionName) {
796
758
  })], DuraxisFeatureEntitiesMarker);
797
759
  return {
798
760
  module: DuraxisModule,
799
- providers: [
800
- DuraxisFeatureEntitiesMarker,
801
- ...repositoryProviders,
802
- ...serviceProviders
803
- ],
804
- exports: [...repositoryProviders.map((provider) => provider.provide), ...uniqueServices]
761
+ providers: [DuraxisFeatureEntitiesMarker, ...repositoryProviders],
762
+ exports: [...repositoryProviders.map((provider) => provider.provide)]
805
763
  };
806
764
  }
807
765
  function repositoryProvider(entity, connectionName) {
@@ -811,16 +769,41 @@ function repositoryProvider(entity, connectionName) {
811
769
  useFactory: (orm) => orm.getRepository(entity)
812
770
  };
813
771
  }
814
- var DuraxisModule = class DuraxisModule {
772
+ var DuraxisModule = _DuraxisModule = class DuraxisModule {
815
773
  static forRoot(options) {
816
- const name = normalizeDuraxisConnectionName(options.name);
774
+ if ("connections" in options) {
775
+ selectDuraxisConnection(options);
776
+ return {
777
+ module: _DuraxisModule,
778
+ imports: Object.keys(options.connections).sort().map((name) => {
779
+ const selected = selectDuraxisConnection(options, name);
780
+ return _DuraxisModule.forRoot({
781
+ ...selected,
782
+ baseDirectory: selected.baseDirectory ?? normalizeDuraxisConnection(selected).context.root
783
+ });
784
+ }),
785
+ exports: [_DuraxisModule]
786
+ };
787
+ }
788
+ if (isSharedConfiguration(options)) {
789
+ const config = options;
790
+ normalizeDuraxisConnection(config);
791
+ const name = normalizeDuraxisConnectionName(config.name);
792
+ return rootModule(name, rootProviders(name, {
793
+ provide: getDuraxisOptionsToken(name),
794
+ inject: [DiscoveryService],
795
+ useFactory: (discovery) => sharedConnectionOptions(config, discovery, name)
796
+ }));
797
+ }
798
+ const rootOptions = options;
799
+ const name = normalizeDuraxisConnectionName(rootOptions.name);
817
800
  const connectionOptions = {
818
- driver: options.driver,
819
- ...options.entities == null ? {} : { entities: options.entities },
820
- ...options.autoLoadEntities == null ? {} : { autoLoadEntities: options.autoLoadEntities },
821
- ...options.database == null ? {} : { database: options.database },
822
- ...options.schema == null ? {} : { schema: options.schema },
823
- ...options.closeStorage == null ? {} : { closeStorage: options.closeStorage }
801
+ driver: rootOptions.driver,
802
+ ...rootOptions.entities == null ? {} : { entities: rootOptions.entities },
803
+ ...rootOptions.autoLoadEntities == null ? {} : { autoLoadEntities: rootOptions.autoLoadEntities },
804
+ ...rootOptions.database == null ? {} : { database: rootOptions.database },
805
+ ...rootOptions.schema == null ? {} : { schema: rootOptions.schema },
806
+ ...rootOptions.closeStorage == null ? {} : { closeStorage: rootOptions.closeStorage }
824
807
  };
825
808
  return rootModule(name, rootProviders(name, {
826
809
  provide: getDuraxisOptionsToken(name),
@@ -831,23 +814,26 @@ var DuraxisModule = class DuraxisModule {
831
814
  const name = normalizeDuraxisConnectionName(options.name);
832
815
  return rootModule(name, rootProviders(name, {
833
816
  provide: getDuraxisOptionsToken(name),
834
- inject: options.inject == null ? [] : [...options.inject],
835
- useFactory: options.useFactory
817
+ inject: [DiscoveryService, ...options.inject ?? []],
818
+ useFactory: async (discovery, ...args) => {
819
+ const config = await options.useFactory(...args);
820
+ if (isSharedConfiguration(config)) {
821
+ const shared = config;
822
+ if (shared.name && shared.name !== name) throw new Error("Async configuration connection name must match forRootAsync name");
823
+ return sharedConnectionOptions({
824
+ ...shared,
825
+ name
826
+ }, discovery, name);
827
+ }
828
+ return config;
829
+ }
836
830
  }), options.imports);
837
831
  }
838
832
  static forFeature(entities, connectionName) {
839
- return featureModule(entities, [], connectionName);
840
- }
841
- /** @deprecated Use forFeature(entities, connectionName) and regular module providers. */
842
- static forTransactionalFeature(entities, providers, connectionName) {
843
- return featureModule(entities, providers, connectionName);
844
- }
845
- /** @deprecated Declare services in the consuming module's providers array. */
846
- static forTransactionalProviders(providers, connectionName) {
847
- return featureModule([], providers, connectionName);
833
+ return featureModule(entities, connectionName);
848
834
  }
849
835
  };
850
- DuraxisModule = __decorate([Module({})], DuraxisModule);
836
+ DuraxisModule = _DuraxisModule = __decorate([Module({})], DuraxisModule);
851
837
  // src/duraxis.decorators.ts
852
838
  function InjectDuraxisRepository(entity, connectionName) {
853
839
  return Inject(getDuraxisRepositoryToken(entity, connectionName));
@@ -861,6 +847,67 @@ function InjectDuraxisDatabase(connectionName) {
861
847
  function InjectDuraxisTransactionManager(connectionName) {
862
848
  return Inject(getDuraxisTransactionManagerToken(connectionName));
863
849
  }
850
+ // src/transactions/transactional.metadata.ts
851
+ var TRANSACTIONAL_METADATA = Symbol.for("@duraxis/nestjs/transactional");
852
+ function transactionalOptions(instance, method) {
853
+ const classOptions = Reflect.getMetadata(TRANSACTIONAL_METADATA, instance.constructor);
854
+ const methodOptions = Reflect.getMetadata(TRANSACTIONAL_METADATA, method);
855
+ return !classOptions && !methodOptions ? void 0 : {
856
+ ...classOptions,
857
+ ...methodOptions
858
+ };
859
+ }
860
+ // src/transactions/transactional.instrumentation.ts
861
+ var MANAGERS = Symbol("Duraxis transaction managers");
862
+ var bindings = /* @__PURE__ */ new WeakMap();
863
+ var injectablePrototypes = /* @__PURE__ */ new WeakSet();
864
+ var wrappers = /* @__PURE__ */ new WeakSet();
865
+ var LIFECYCLE_METHODS = /* @__PURE__ */ new Set([
866
+ "onModuleInit",
867
+ "onApplicationBootstrap",
868
+ "onModuleDestroy",
869
+ "beforeApplicationShutdown",
870
+ "onApplicationShutdown"
871
+ ]);
872
+ function injectTransactionManagers(prototype) {
873
+ if (injectablePrototypes.has(prototype)) return;
874
+ injectablePrototypes.add(prototype);
875
+ Object.defineProperty(prototype, MANAGERS, { set(managers) {
876
+ bindings.set(this, managers);
877
+ instrumentTransactionalMethods(this);
878
+ } });
879
+ Inject(TransactionManagerRegistry)(prototype, MANAGERS);
880
+ }
881
+ function wrapTransactionalMethod(method, property) {
882
+ if (wrappers.has(method)) return method;
883
+ const wrapped = function(...arguments_) {
884
+ const methodName = `${this.constructor.name}.${String(property)}`;
885
+ const managers = bindings.get(this);
886
+ if (!managers) throw new TransactionalProviderNotReadyError(methodName);
887
+ const options = transactionalOptions(this, wrapped) ?? {};
888
+ const name = normalizeDuraxisConnectionName(options.connectionName);
889
+ return managers.get(name).execute(options, methodName, () => Reflect.apply(method, this, arguments_));
890
+ };
891
+ for (const key of Reflect.getOwnMetadataKeys(method)) Reflect.defineMetadata(key, Reflect.getOwnMetadata(key, method), wrapped);
892
+ wrappers.add(wrapped);
893
+ return wrapped;
894
+ }
895
+ function instrumentTransactionalMethods(target) {
896
+ const visited = /* @__PURE__ */ new Set();
897
+ for (let prototype = target; prototype && prototype != Object.prototype; prototype = Object.getPrototypeOf(prototype)) for (const property of Reflect.ownKeys(prototype)) {
898
+ if (visited.has(property)) continue;
899
+ visited.add(property);
900
+ if (property == "constructor" || LIFECYCLE_METHODS.has(property)) continue;
901
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, property);
902
+ const method = descriptor?.value;
903
+ if (typeof method != "function" || !transactionalOptions(target, method)) continue;
904
+ if (wrappers.has(method)) continue;
905
+ Object.defineProperty(target, property, {
906
+ ...descriptor,
907
+ value: wrapTransactionalMethod(method, property)
908
+ });
909
+ }
910
+ }
864
911
  // src/transactions/transactional.decorator.ts
865
912
  function Transactional(options = {}) {
866
913
  return (target, _propertyKey, descriptor) => {