@duraxis/orm 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/CHANGELOG.md CHANGED
@@ -1,5 +1,31 @@
1
1
  # @duraxis/orm changelog
2
2
 
3
+ ## 0.5.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 6377fde: Add framework-independent configuration and owned database/ORM factories, bounded decorated-entity discovery, and shared NestJS/CLI schema resolution. Initialize projects with one source-root configuration and direct AST-guided AppModule integration. Support static inspection/mutation, centralized named connections, registry-free generators and source/compiled deployments without runtime CLI dependencies. Use shared typed configuration across runtime and CLI, standard Nest feature modules, and authenticated encrypted cursors. Document storage, migration, discovery and lifecycle contracts.
8
+
9
+ ### Patch Changes
10
+
11
+ - Updated dependencies [6377fde]
12
+ - @duraxis/core@0.5.0
13
+
14
+ ## 0.4.0
15
+
16
+ ### Minor Changes
17
+
18
+ - a4bed1c: Harden bounded production pilots with hierarchical resource admission, query and transaction deadlines, tracked pending I/O, bounded materialization, weighted caches, incremental listings and journal replay, and verified single-owner garbage collection.
19
+
20
+ Breaking pre-1.0 changes: Core requires bounded-read adapter capabilities; resource limits now reject oversized work; destructive S3 GC fails closed; encrypted expiring v3 cursors replace signed database cursors. Restart pagination and provision stable encryption keys. Tenant context checks strengthen application isolation but do not authorize raw storage access.
21
+
22
+ Add conservative commit reconciliation and bounded atomic idempotency receipts without callback retries. Preserve manifest CAS, physical persistence formats and migration checksum identities. See docs/PRODUCTION-HARDENING.md for defaults, deployment constraints, receipt retention and remaining index/FK accounting limitations.
23
+
24
+ ### Patch Changes
25
+
26
+ - Updated dependencies [a4bed1c]
27
+ - @duraxis/core@0.4.0
28
+
3
29
  ## 0.3.0
4
30
 
5
31
  ### Minor Changes
package/README.md CHANGED
@@ -70,3 +70,13 @@ on registered entity/junction collections. Unrelated collections remain allowed.
70
70
  Existing `create` and `validate` modes preserve their behavior and declaration
71
71
  order. Production can run `duraxis migrate:up` before ORM initialization with
72
72
  schema validation; startup does not automatically execute migrations.
73
+
74
+ ## Production resource and lifecycle limits
75
+
76
+ See the [production hardening guide](../../docs/PRODUCTION-HARDENING.md) for bounded defaults, cancellation, verified maintenance, tenant trust boundaries, encrypted cursors, upgrade instructions and remaining pilot limitations. Core rejects storage adapters without bounded-read capability; destructive shared-storage garbage collection is unsupported.
77
+
78
+ ## CLI project setup
79
+
80
+ Run `npx --package @duraxis/cli@latest duraxis init` to generate one source-root configuration. NestJS AppModule integration is automatic; standalone applications call the public runtime factories. See the [shared configuration API and examples](../../docs/CLI-SETUP.md) and [setup guide](../../docs/CLI-SETUP.md).
81
+
82
+ `createORM(config, connectionName?)` resolves/validates entities before acquiring storage and releases owned resources after initialization failure or `orm.close()`. `discoverEntities` and `isDuraxisEntity` expose conventional file discovery and decorator checks. Explicit `entities` arrays/factories override discovery. Empty/missing/failed discovery is an error by default; named connections require isolated directories/lists. See the shared guide for filesystem boundaries, compiled deployments and Nest feature consistency.
@@ -0,0 +1,3 @@
1
+ import { type DuraxisConfiguration } from "@duraxis/core";
2
+ import { DuraxisORM } from "./duraxis-orm.js";
3
+ export declare function createORM(config: DuraxisConfiguration, name?: string): Promise<DuraxisORM>;
@@ -10,6 +10,7 @@ export declare class DuraxisORM {
10
10
  initialize(): Promise<void>;
11
11
  getRepository<TEntity extends object>(entity: EntityClass<TEntity>): Repository<TEntity>;
12
12
  transaction<TResult>(callback: (manager: TransactionContext) => Promise<TResult> | TResult): Promise<TResult>;
13
+ resolveCommitOutcome(transactionId: string): Promise<"COMMITTED" | "NOT_COMMITTED" | "UNKNOWN">;
13
14
  close(): Promise<void>;
14
15
  get metadata(): MetadataRegistry;
15
16
  private assertReady;
@@ -0,0 +1,4 @@
1
+ import { type DuraxisConnectionOptions } from "@duraxis/core";
2
+ import type { EntityClass } from "./metadata/entity-metadata.js";
3
+ export declare function isDuraxisEntity(value: unknown): value is EntityClass;
4
+ export declare function discoverEntities(config: DuraxisConnectionOptions, importer?: (url: URL) => Promise<unknown>): Promise<readonly EntityClass[]>;
package/dist/index.cjs CHANGED
@@ -1,6 +1,9 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  let _duraxis_core = require("@duraxis/core");
3
3
  let node_crypto = require("node:crypto");
4
+ let node_fs_promises = require("node:fs/promises");
5
+ let node_path = require("node:path");
6
+ let node_url = require("node:url");
4
7
  // src/metadata/decorator-metadata.ts
5
8
  var drafts = /* @__PURE__ */ new WeakMap();
6
9
  function ownDraft(entity) {
@@ -761,17 +764,25 @@ var MAX_RELATED_ENTITIES = 1e5;
761
764
  var RelationLoader = class {
762
765
  metadata;
763
766
  runtime;
764
- #loaded = 0;
765
767
  constructor(metadata, runtime) {
766
768
  this.metadata = metadata;
767
769
  this.runtime = runtime;
768
770
  }
769
771
  async load(entities, requested, signal) {
770
772
  if (!requested || entities.length == 0) return entities;
771
- await this.loadLevel(this.metadata, entities, requested, signal, 0, /* @__PURE__ */ new Set());
772
- return entities;
773
+ const state = {
774
+ loaded: 0,
775
+ budget: this.runtime.database.createMaterializationBudget()
776
+ };
777
+ try {
778
+ for (const entity of entities) state.budget.add(entity);
779
+ await this.loadLevel(this.metadata, entities, requested, signal, 0, /* @__PURE__ */ new Set(), state);
780
+ return entities;
781
+ } finally {
782
+ state.budget.close();
783
+ }
773
784
  }
774
- async loadLevel(metadata, entities, requested, signal, depth, path) {
785
+ async loadLevel(metadata, entities, requested, signal, depth, path, state) {
775
786
  if (depth >= MAX_DEPTH) throw new Error(`Relation depth exceeds ${MAX_DEPTH}`);
776
787
  for (const [property, nested] of Object.entries(requested)) {
777
788
  if (!nested) continue;
@@ -781,11 +792,12 @@ var RelationLoader = class {
781
792
  const edge = `${metadata.collection}.${property}`;
782
793
  if (path.has(edge)) continue;
783
794
  const related = await this.loadRelation(metadata, entities, relation, signal);
784
- this.#loaded += related.length;
785
- if (this.#loaded > MAX_RELATED_ENTITIES) throw new Error("Related entity expansion limit exceeded");
795
+ state.loaded += related.length;
796
+ for (const entity of related) state.budget.add(entity);
797
+ if (state.loaded > MAX_RELATED_ENTITIES) throw new Error("Related entity expansion limit exceeded");
786
798
  if (nested !== true && related.length) {
787
799
  const target = this.runtime.registry.get(relation.target);
788
- await this.loadLevel(target, related, nested, signal, depth + 1, /* @__PURE__ */ new Set([...path, edge]));
800
+ await this.loadLevel(target, related, nested, signal, depth + 1, /* @__PURE__ */ new Set([...path, edge]), state);
789
801
  }
790
802
  }
791
803
  }
@@ -851,22 +863,30 @@ var RelationLoader = class {
851
863
  async queryBatches(collection, field, values, signal) {
852
864
  const all = [...values];
853
865
  const rows = [];
854
- for (let offset = 0; offset < all.length; offset += BATCH_SIZE) {
855
- signal?.throwIfAborted();
856
- const batch = all.slice(offset, offset + BATCH_SIZE);
857
- if (!batch.length) continue;
858
- const query = {
859
- collection,
860
- where: {
861
- type: "in",
862
- field,
863
- values: batch
866
+ const memory = this.runtime.database.createMaterializationBudget();
867
+ try {
868
+ for (let offset = 0; offset < all.length; offset += BATCH_SIZE) {
869
+ signal?.throwIfAborted();
870
+ const batch = all.slice(offset, offset + BATCH_SIZE);
871
+ if (!batch.length) continue;
872
+ const query = {
873
+ collection,
874
+ where: {
875
+ type: "in",
876
+ field,
877
+ values: batch
878
+ }
879
+ };
880
+ const source = this.runtime.transaction ? this.runtime.transaction.query(query, { signal }) : this.runtime.database.query(query, { signal });
881
+ for await (const row of source) {
882
+ memory.add(row);
883
+ rows.push(row);
864
884
  }
865
- };
866
- const source = this.runtime.transaction ? this.runtime.transaction.query(query, { signal }) : this.runtime.database.query(query, { signal });
867
- for await (const row of source) rows.push(row);
885
+ }
886
+ return rows;
887
+ } finally {
888
+ memory.close();
868
889
  }
869
- return rows;
870
890
  }
871
891
  values(entities, property) {
872
892
  const result = /* @__PURE__ */ new Set();
@@ -1100,7 +1120,15 @@ var Repository = class {
1100
1120
  async queryRows(query, signal) {
1101
1121
  this.runtime.assertUsable();
1102
1122
  const rows = [];
1103
- for await (const row of this.sourceQuery(query, signal)) rows.push(row);
1123
+ const memory = this.runtime.database.createMaterializationBudget();
1124
+ try {
1125
+ for await (const row of this.sourceQuery(query, signal)) {
1126
+ memory.add(row);
1127
+ rows.push(row);
1128
+ }
1129
+ } finally {
1130
+ memory.close();
1131
+ }
1104
1132
  return rows;
1105
1133
  }
1106
1134
  queryPage(query, signal) {
@@ -1297,10 +1325,16 @@ var OrmTransactionManager = class {
1297
1325
  registry;
1298
1326
  #repositories = /* @__PURE__ */ new Map();
1299
1327
  #active = true;
1328
+ #abort = () => this.close();
1329
+ get signal() {
1330
+ return this.transaction.signal;
1331
+ }
1300
1332
  constructor(database, transaction, registry) {
1301
1333
  this.database = database;
1302
1334
  this.transaction = transaction;
1303
1335
  this.registry = registry;
1336
+ this.transaction.signal.addEventListener("abort", this.#abort, { once: true });
1337
+ if (this.transaction.signal.aborted) this.close();
1304
1338
  }
1305
1339
  getRepository(entity) {
1306
1340
  this.assertActive();
@@ -1317,10 +1351,11 @@ var OrmTransactionManager = class {
1317
1351
  }
1318
1352
  close() {
1319
1353
  this.#active = false;
1354
+ this.transaction.signal.removeEventListener("abort", this.#abort);
1320
1355
  this.#repositories.clear();
1321
1356
  }
1322
1357
  assertActive() {
1323
- if (!this.#active) throw new TransactionManagerClosedError();
1358
+ if (!this.#active || this.transaction.state != "ACTIVE") throw new TransactionManagerClosedError();
1324
1359
  }
1325
1360
  };
1326
1361
  // src/database/duraxis-orm.ts
@@ -1330,6 +1365,8 @@ var DuraxisORM = class {
1330
1365
  #repositories = /* @__PURE__ */ new Map();
1331
1366
  #lifecycle = "new";
1332
1367
  #initialization;
1368
+ #closing;
1369
+ #resourcesClosed = false;
1333
1370
  constructor(options) {
1334
1371
  this.options = options;
1335
1372
  this.#registry = new MetadataRegistry(options.entities).finalize();
@@ -1380,13 +1417,23 @@ var DuraxisORM = class {
1380
1417
  throw cause;
1381
1418
  }
1382
1419
  }
1383
- async close() {
1384
- if (this.#lifecycle == "closed") return;
1385
- const initialization = this.#initialization;
1386
- if (initialization) await initialization.catch(() => void 0);
1420
+ resolveCommitOutcome(transactionId) {
1421
+ return this.options.database.resolveCommitOutcome(transactionId);
1422
+ }
1423
+ close() {
1424
+ if (this.#resourcesClosed) return Promise.resolve();
1425
+ if (this.#closing) return this.#closing;
1387
1426
  this.#lifecycle = "closed";
1388
1427
  this.#repositories.clear();
1389
- if (this.options.closeDatabase || this.options.closeStorage) await this.options.database.close({ closeStorage: this.options.closeStorage ?? false });
1428
+ this.#closing = (async () => {
1429
+ if (this.#initialization) await this.#initialization.catch(() => void 0);
1430
+ if (this.options.closeDatabase || this.options.closeStorage) await this.options.database.close({ closeStorage: this.options.closeStorage ?? false });
1431
+ this.#resourcesClosed = true;
1432
+ })();
1433
+ this.#closing.catch(() => {
1434
+ this.#closing = void 0;
1435
+ });
1436
+ return this.#closing;
1390
1437
  }
1391
1438
  get metadata() {
1392
1439
  return this.#registry;
@@ -1396,6 +1443,120 @@ var DuraxisORM = class {
1396
1443
  if (this.#lifecycle != "initialized") throw new OrmNotInitializedError();
1397
1444
  }
1398
1445
  };
1446
+ // src/discovery.ts
1447
+ function isDuraxisEntity(value) {
1448
+ return typeof value === "function" && (ownDraft(value)?.entityApplications ?? 0) > 0;
1449
+ }
1450
+ var excluded = /* @__PURE__ */ new Set([
1451
+ "node_modules",
1452
+ ".git",
1453
+ "test",
1454
+ "tests",
1455
+ "__test__",
1456
+ "__tests__",
1457
+ "fixtures",
1458
+ "__fixtures__",
1459
+ "migrations",
1460
+ "snapshots",
1461
+ "dist",
1462
+ "build",
1463
+ "coverage"
1464
+ ]);
1465
+ var entityFile = /\.entity\.(?:[cm]?[jt]s)$/;
1466
+ async function noSymlinks(path) {
1467
+ let cursor = (0, node_path.resolve)(path);
1468
+ while (true) {
1469
+ if ((await (0, node_fs_promises.lstat)(cursor)).isSymbolicLink()) throw new Error(`Entity discovery does not follow symlinks: ${cursor}`);
1470
+ if ((0, node_path.dirname)(cursor) === cursor) return;
1471
+ cursor = (0, node_path.dirname)(cursor);
1472
+ }
1473
+ }
1474
+ async function discoverEntities(config, importer = (url) => import(url.href)) {
1475
+ const options = (0, _duraxis_core.normalizeDuraxisConnection)(config);
1476
+ if (options.entities !== void 0) {
1477
+ const entities = typeof options.entities === "function" ? await options.entities() : options.entities;
1478
+ if (!Array.isArray(entities) || entities.some((entity) => !isDuraxisEntity(entity))) throw new Error("Explicit entities must be Duraxis-decorated classes");
1479
+ const unique = [...new Set(entities)];
1480
+ new MetadataRegistry(unique).finalize();
1481
+ return unique;
1482
+ }
1483
+ if (!options.autoLoadEntities) return [];
1484
+ const discovery = typeof options.autoLoadEntities === "object" ? options.autoLoadEntities : {};
1485
+ if (options.name && options.name !== "default" && !discovery.directories?.length) throw new Error(`Named connection ${options.name} requires explicit entity directories or entities to prevent cross-connection discovery`);
1486
+ const files = /* @__PURE__ */ new Set();
1487
+ let inspected = 0;
1488
+ const boundary = await (0, node_fs_promises.realpath)(options.context.root);
1489
+ for (const directory of discovery.directories ?? ["."]) {
1490
+ const path = (0, node_path.resolve)(options.context.directory, directory);
1491
+ const within = (0, node_path.relative)(options.context.root, path);
1492
+ if (within === ".." || within.startsWith(`..${node_path.sep}`) || (0, node_path.resolve)(path) === (0, node_path.resolve)(node_path.sep)) throw new Error("Entity directory escapes project boundary");
1493
+ await noSymlinks(path);
1494
+ const root = await (0, node_fs_promises.realpath)(path);
1495
+ const actual = (0, node_path.relative)(boundary, root);
1496
+ if (actual === ".." || actual.startsWith(`..${node_path.sep}`)) throw new Error("Entity directory escapes project boundary");
1497
+ const walk = async (current, depth) => {
1498
+ if ((await (0, node_fs_promises.lstat)(current)).isSymbolicLink() || await (0, node_fs_promises.realpath)(current) !== current) throw new Error("Entity discovery directory changed or became a symlink");
1499
+ if (depth > 64) throw new Error("Entity discovery depth limit exceeded");
1500
+ for (const entry of (await (0, node_fs_promises.readdir)(current, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name, "en"))) {
1501
+ if (++inspected > 1e4) throw new Error("Entity discovery file limit exceeded");
1502
+ if (entry.isSymbolicLink()) continue;
1503
+ const child = (0, node_path.resolve)(current, entry.name);
1504
+ if (entry.isDirectory() && !excluded.has(entry.name) && !entry.name.startsWith(".")) await walk(child, depth + 1);
1505
+ if (entry.isFile() && entityFile.test(entry.name) && !/\.(?:test|spec|d)\./.test(entry.name)) files.add(child);
1506
+ }
1507
+ };
1508
+ await walk(root, 0);
1509
+ }
1510
+ const entities = /* @__PURE__ */ new Set();
1511
+ const identities = /* @__PURE__ */ new Set();
1512
+ for (const file of [...files].sort()) {
1513
+ const identity = file.replace(/\.[cm]?[jt]s$/, "");
1514
+ if (identities.has(identity)) throw new Error(`Duplicate source/compiled entity representation: ${identity}`);
1515
+ identities.add(identity);
1516
+ await noSymlinks(file);
1517
+ if (await (0, node_fs_promises.realpath)(file) !== file) throw new Error("Entity file changed or became a symlink");
1518
+ let module;
1519
+ try {
1520
+ module = await importer((0, node_url.pathToFileURL)(file));
1521
+ } catch (cause) {
1522
+ throw new Error(`Cannot load entity file ${file}`, { cause });
1523
+ }
1524
+ if (module && typeof module === "object") {
1525
+ for (const value of Object.values(module)) if (isDuraxisEntity(value)) entities.add(value);
1526
+ else if (value && typeof value === "object") {
1527
+ for (const item of Object.values(value)) if (isDuraxisEntity(item)) entities.add(item);
1528
+ }
1529
+ }
1530
+ }
1531
+ if (!entities.size && !discovery.allowEmpty) throw new Error("No Duraxis entities discovered. Check directories and decorators; use allowEmpty:true only for an intentionally empty schema");
1532
+ const result = [...entities];
1533
+ new MetadataRegistry(result).finalize();
1534
+ return result;
1535
+ }
1536
+ // src/database/create-orm.ts
1537
+ async function createORM(config, name) {
1538
+ const options = (0, _duraxis_core.normalizeDuraxisConnection)((0, _duraxis_core.selectDuraxisConnection)(config, name));
1539
+ const entities = await discoverEntities(options);
1540
+ const database = await (0, _duraxis_core.createDatabase)(options);
1541
+ try {
1542
+ const orm = new DuraxisORM({
1543
+ database,
1544
+ entities,
1545
+ schema: options.schema,
1546
+ closeDatabase: true,
1547
+ closeStorage: options.closeStorage ?? typeof options.driver === "function"
1548
+ });
1549
+ await orm.initialize();
1550
+ return orm;
1551
+ } catch (cause) {
1552
+ try {
1553
+ await database.close();
1554
+ } catch (cleanup) {
1555
+ throw new AggregateError([cause, cleanup], "ORM initialization and cleanup failed");
1556
+ }
1557
+ throw cause;
1558
+ }
1559
+ }
1399
1560
  exports.Column = Column;
1400
1561
  Object.defineProperty(exports, "CommitOutcomeUnknownError", {
1401
1562
  enumerable: true,
@@ -1442,6 +1603,9 @@ Object.defineProperty(exports, "TransactionConflictError", {
1442
1603
  exports.TransactionManagerClosedError = TransactionManagerClosedError;
1443
1604
  exports.UniqueIndexViolationOrmError = UniqueIndexViolationOrmError;
1444
1605
  exports.ValueTransformer = ValueTransformer;
1606
+ exports.createORM = createORM;
1607
+ exports.discoverEntities = discoverEntities;
1445
1608
  exports.exportSchema = exportSchema;
1609
+ exports.isDuraxisEntity = isDuraxisEntity;
1446
1610
 
1447
1611
  //# sourceMappingURL=index.cjs.map