@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 +26 -0
- package/README.md +10 -0
- package/dist/database/create-orm.d.ts +3 -0
- package/dist/database/duraxis-orm.d.ts +1 -0
- package/dist/discovery.d.ts +4 -0
- package/dist/index.cjs +192 -28
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +191 -30
- package/dist/index.js.map +1 -1
- package/dist/relations/relation-loader.d.ts +0 -1
- package/dist/transactions/orm-transaction.d.ts +1 -0
- package/dist/transactions/transaction-context.d.ts +1 -0
- package/package.json +5 -5
package/dist/index.d.ts
CHANGED
|
@@ -26,3 +26,5 @@ export type { Where, WhereOperator, WhereValue, QueryComparisonOperator, QueryCo
|
|
|
26
26
|
export * from "./errors/index.js";
|
|
27
27
|
export { TransactionConflictError, CommitOutcomeUnknownError } from "@duraxis/core";
|
|
28
28
|
export { exportSchema } from "./schema/schema-exporter.js";
|
|
29
|
+
export { discoverEntities, isDuraxisEntity } from "./discovery.js";
|
|
30
|
+
export { createORM } from "./database/create-orm.js";
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
|
-
import { CommitOutcomeUnknownError, CommitOutcomeUnknownError as CommitOutcomeUnknownError$1, TransactionConflictError, TransactionConflictError as TransactionConflictError$1, UniqueIndexViolationError, normalizeCollection } from "@duraxis/core";
|
|
1
|
+
import { CommitOutcomeUnknownError, CommitOutcomeUnknownError as CommitOutcomeUnknownError$1, TransactionConflictError, TransactionConflictError as TransactionConflictError$1, UniqueIndexViolationError, createDatabase, normalizeCollection, normalizeDuraxisConnection, selectDuraxisConnection } from "@duraxis/core";
|
|
2
2
|
import { createHash } from "node:crypto";
|
|
3
|
+
import { lstat, readdir, realpath } from "node:fs/promises";
|
|
4
|
+
import { dirname, relative, resolve, sep } from "node:path";
|
|
5
|
+
import { pathToFileURL } from "node:url";
|
|
3
6
|
// src/metadata/decorator-metadata.ts
|
|
4
7
|
var drafts = /* @__PURE__ */ new WeakMap();
|
|
5
8
|
function ownDraft(entity) {
|
|
@@ -760,17 +763,25 @@ var MAX_RELATED_ENTITIES = 1e5;
|
|
|
760
763
|
var RelationLoader = class {
|
|
761
764
|
metadata;
|
|
762
765
|
runtime;
|
|
763
|
-
#loaded = 0;
|
|
764
766
|
constructor(metadata, runtime) {
|
|
765
767
|
this.metadata = metadata;
|
|
766
768
|
this.runtime = runtime;
|
|
767
769
|
}
|
|
768
770
|
async load(entities, requested, signal) {
|
|
769
771
|
if (!requested || entities.length == 0) return entities;
|
|
770
|
-
|
|
771
|
-
|
|
772
|
+
const state = {
|
|
773
|
+
loaded: 0,
|
|
774
|
+
budget: this.runtime.database.createMaterializationBudget()
|
|
775
|
+
};
|
|
776
|
+
try {
|
|
777
|
+
for (const entity of entities) state.budget.add(entity);
|
|
778
|
+
await this.loadLevel(this.metadata, entities, requested, signal, 0, /* @__PURE__ */ new Set(), state);
|
|
779
|
+
return entities;
|
|
780
|
+
} finally {
|
|
781
|
+
state.budget.close();
|
|
782
|
+
}
|
|
772
783
|
}
|
|
773
|
-
async loadLevel(metadata, entities, requested, signal, depth, path) {
|
|
784
|
+
async loadLevel(metadata, entities, requested, signal, depth, path, state) {
|
|
774
785
|
if (depth >= MAX_DEPTH) throw new Error(`Relation depth exceeds ${MAX_DEPTH}`);
|
|
775
786
|
for (const [property, nested] of Object.entries(requested)) {
|
|
776
787
|
if (!nested) continue;
|
|
@@ -780,11 +791,12 @@ var RelationLoader = class {
|
|
|
780
791
|
const edge = `${metadata.collection}.${property}`;
|
|
781
792
|
if (path.has(edge)) continue;
|
|
782
793
|
const related = await this.loadRelation(metadata, entities, relation, signal);
|
|
783
|
-
|
|
784
|
-
|
|
794
|
+
state.loaded += related.length;
|
|
795
|
+
for (const entity of related) state.budget.add(entity);
|
|
796
|
+
if (state.loaded > MAX_RELATED_ENTITIES) throw new Error("Related entity expansion limit exceeded");
|
|
785
797
|
if (nested !== true && related.length) {
|
|
786
798
|
const target = this.runtime.registry.get(relation.target);
|
|
787
|
-
await this.loadLevel(target, related, nested, signal, depth + 1, /* @__PURE__ */ new Set([...path, edge]));
|
|
799
|
+
await this.loadLevel(target, related, nested, signal, depth + 1, /* @__PURE__ */ new Set([...path, edge]), state);
|
|
788
800
|
}
|
|
789
801
|
}
|
|
790
802
|
}
|
|
@@ -850,22 +862,30 @@ var RelationLoader = class {
|
|
|
850
862
|
async queryBatches(collection, field, values, signal) {
|
|
851
863
|
const all = [...values];
|
|
852
864
|
const rows = [];
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
865
|
+
const memory = this.runtime.database.createMaterializationBudget();
|
|
866
|
+
try {
|
|
867
|
+
for (let offset = 0; offset < all.length; offset += BATCH_SIZE) {
|
|
868
|
+
signal?.throwIfAborted();
|
|
869
|
+
const batch = all.slice(offset, offset + BATCH_SIZE);
|
|
870
|
+
if (!batch.length) continue;
|
|
871
|
+
const query = {
|
|
872
|
+
collection,
|
|
873
|
+
where: {
|
|
874
|
+
type: "in",
|
|
875
|
+
field,
|
|
876
|
+
values: batch
|
|
877
|
+
}
|
|
878
|
+
};
|
|
879
|
+
const source = this.runtime.transaction ? this.runtime.transaction.query(query, { signal }) : this.runtime.database.query(query, { signal });
|
|
880
|
+
for await (const row of source) {
|
|
881
|
+
memory.add(row);
|
|
882
|
+
rows.push(row);
|
|
863
883
|
}
|
|
864
|
-
}
|
|
865
|
-
|
|
866
|
-
|
|
884
|
+
}
|
|
885
|
+
return rows;
|
|
886
|
+
} finally {
|
|
887
|
+
memory.close();
|
|
867
888
|
}
|
|
868
|
-
return rows;
|
|
869
889
|
}
|
|
870
890
|
values(entities, property) {
|
|
871
891
|
const result = /* @__PURE__ */ new Set();
|
|
@@ -1099,7 +1119,15 @@ var Repository = class {
|
|
|
1099
1119
|
async queryRows(query, signal) {
|
|
1100
1120
|
this.runtime.assertUsable();
|
|
1101
1121
|
const rows = [];
|
|
1102
|
-
|
|
1122
|
+
const memory = this.runtime.database.createMaterializationBudget();
|
|
1123
|
+
try {
|
|
1124
|
+
for await (const row of this.sourceQuery(query, signal)) {
|
|
1125
|
+
memory.add(row);
|
|
1126
|
+
rows.push(row);
|
|
1127
|
+
}
|
|
1128
|
+
} finally {
|
|
1129
|
+
memory.close();
|
|
1130
|
+
}
|
|
1103
1131
|
return rows;
|
|
1104
1132
|
}
|
|
1105
1133
|
queryPage(query, signal) {
|
|
@@ -1296,10 +1324,16 @@ var OrmTransactionManager = class {
|
|
|
1296
1324
|
registry;
|
|
1297
1325
|
#repositories = /* @__PURE__ */ new Map();
|
|
1298
1326
|
#active = true;
|
|
1327
|
+
#abort = () => this.close();
|
|
1328
|
+
get signal() {
|
|
1329
|
+
return this.transaction.signal;
|
|
1330
|
+
}
|
|
1299
1331
|
constructor(database, transaction, registry) {
|
|
1300
1332
|
this.database = database;
|
|
1301
1333
|
this.transaction = transaction;
|
|
1302
1334
|
this.registry = registry;
|
|
1335
|
+
this.transaction.signal.addEventListener("abort", this.#abort, { once: true });
|
|
1336
|
+
if (this.transaction.signal.aborted) this.close();
|
|
1303
1337
|
}
|
|
1304
1338
|
getRepository(entity) {
|
|
1305
1339
|
this.assertActive();
|
|
@@ -1316,10 +1350,11 @@ var OrmTransactionManager = class {
|
|
|
1316
1350
|
}
|
|
1317
1351
|
close() {
|
|
1318
1352
|
this.#active = false;
|
|
1353
|
+
this.transaction.signal.removeEventListener("abort", this.#abort);
|
|
1319
1354
|
this.#repositories.clear();
|
|
1320
1355
|
}
|
|
1321
1356
|
assertActive() {
|
|
1322
|
-
if (!this.#active) throw new TransactionManagerClosedError();
|
|
1357
|
+
if (!this.#active || this.transaction.state != "ACTIVE") throw new TransactionManagerClosedError();
|
|
1323
1358
|
}
|
|
1324
1359
|
};
|
|
1325
1360
|
// src/database/duraxis-orm.ts
|
|
@@ -1329,6 +1364,8 @@ var DuraxisORM = class {
|
|
|
1329
1364
|
#repositories = /* @__PURE__ */ new Map();
|
|
1330
1365
|
#lifecycle = "new";
|
|
1331
1366
|
#initialization;
|
|
1367
|
+
#closing;
|
|
1368
|
+
#resourcesClosed = false;
|
|
1332
1369
|
constructor(options) {
|
|
1333
1370
|
this.options = options;
|
|
1334
1371
|
this.#registry = new MetadataRegistry(options.entities).finalize();
|
|
@@ -1379,13 +1416,23 @@ var DuraxisORM = class {
|
|
|
1379
1416
|
throw cause;
|
|
1380
1417
|
}
|
|
1381
1418
|
}
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1419
|
+
resolveCommitOutcome(transactionId) {
|
|
1420
|
+
return this.options.database.resolveCommitOutcome(transactionId);
|
|
1421
|
+
}
|
|
1422
|
+
close() {
|
|
1423
|
+
if (this.#resourcesClosed) return Promise.resolve();
|
|
1424
|
+
if (this.#closing) return this.#closing;
|
|
1386
1425
|
this.#lifecycle = "closed";
|
|
1387
1426
|
this.#repositories.clear();
|
|
1388
|
-
|
|
1427
|
+
this.#closing = (async () => {
|
|
1428
|
+
if (this.#initialization) await this.#initialization.catch(() => void 0);
|
|
1429
|
+
if (this.options.closeDatabase || this.options.closeStorage) await this.options.database.close({ closeStorage: this.options.closeStorage ?? false });
|
|
1430
|
+
this.#resourcesClosed = true;
|
|
1431
|
+
})();
|
|
1432
|
+
this.#closing.catch(() => {
|
|
1433
|
+
this.#closing = void 0;
|
|
1434
|
+
});
|
|
1435
|
+
return this.#closing;
|
|
1389
1436
|
}
|
|
1390
1437
|
get metadata() {
|
|
1391
1438
|
return this.#registry;
|
|
@@ -1395,6 +1442,120 @@ var DuraxisORM = class {
|
|
|
1395
1442
|
if (this.#lifecycle != "initialized") throw new OrmNotInitializedError();
|
|
1396
1443
|
}
|
|
1397
1444
|
};
|
|
1398
|
-
|
|
1445
|
+
// src/discovery.ts
|
|
1446
|
+
function isDuraxisEntity(value) {
|
|
1447
|
+
return typeof value === "function" && (ownDraft(value)?.entityApplications ?? 0) > 0;
|
|
1448
|
+
}
|
|
1449
|
+
var excluded = /* @__PURE__ */ new Set([
|
|
1450
|
+
"node_modules",
|
|
1451
|
+
".git",
|
|
1452
|
+
"test",
|
|
1453
|
+
"tests",
|
|
1454
|
+
"__test__",
|
|
1455
|
+
"__tests__",
|
|
1456
|
+
"fixtures",
|
|
1457
|
+
"__fixtures__",
|
|
1458
|
+
"migrations",
|
|
1459
|
+
"snapshots",
|
|
1460
|
+
"dist",
|
|
1461
|
+
"build",
|
|
1462
|
+
"coverage"
|
|
1463
|
+
]);
|
|
1464
|
+
var entityFile = /\.entity\.(?:[cm]?[jt]s)$/;
|
|
1465
|
+
async function noSymlinks(path) {
|
|
1466
|
+
let cursor = resolve(path);
|
|
1467
|
+
while (true) {
|
|
1468
|
+
if ((await lstat(cursor)).isSymbolicLink()) throw new Error(`Entity discovery does not follow symlinks: ${cursor}`);
|
|
1469
|
+
if (dirname(cursor) === cursor) return;
|
|
1470
|
+
cursor = dirname(cursor);
|
|
1471
|
+
}
|
|
1472
|
+
}
|
|
1473
|
+
async function discoverEntities(config, importer = (url) => import(url.href)) {
|
|
1474
|
+
const options = normalizeDuraxisConnection(config);
|
|
1475
|
+
if (options.entities !== void 0) {
|
|
1476
|
+
const entities = typeof options.entities === "function" ? await options.entities() : options.entities;
|
|
1477
|
+
if (!Array.isArray(entities) || entities.some((entity) => !isDuraxisEntity(entity))) throw new Error("Explicit entities must be Duraxis-decorated classes");
|
|
1478
|
+
const unique = [...new Set(entities)];
|
|
1479
|
+
new MetadataRegistry(unique).finalize();
|
|
1480
|
+
return unique;
|
|
1481
|
+
}
|
|
1482
|
+
if (!options.autoLoadEntities) return [];
|
|
1483
|
+
const discovery = typeof options.autoLoadEntities === "object" ? options.autoLoadEntities : {};
|
|
1484
|
+
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`);
|
|
1485
|
+
const files = /* @__PURE__ */ new Set();
|
|
1486
|
+
let inspected = 0;
|
|
1487
|
+
const boundary = await realpath(options.context.root);
|
|
1488
|
+
for (const directory of discovery.directories ?? ["."]) {
|
|
1489
|
+
const path = resolve(options.context.directory, directory);
|
|
1490
|
+
const within = relative(options.context.root, path);
|
|
1491
|
+
if (within === ".." || within.startsWith(`..${sep}`) || resolve(path) === resolve(sep)) throw new Error("Entity directory escapes project boundary");
|
|
1492
|
+
await noSymlinks(path);
|
|
1493
|
+
const root = await realpath(path);
|
|
1494
|
+
const actual = relative(boundary, root);
|
|
1495
|
+
if (actual === ".." || actual.startsWith(`..${sep}`)) throw new Error("Entity directory escapes project boundary");
|
|
1496
|
+
const walk = async (current, depth) => {
|
|
1497
|
+
if ((await lstat(current)).isSymbolicLink() || await realpath(current) !== current) throw new Error("Entity discovery directory changed or became a symlink");
|
|
1498
|
+
if (depth > 64) throw new Error("Entity discovery depth limit exceeded");
|
|
1499
|
+
for (const entry of (await readdir(current, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name, "en"))) {
|
|
1500
|
+
if (++inspected > 1e4) throw new Error("Entity discovery file limit exceeded");
|
|
1501
|
+
if (entry.isSymbolicLink()) continue;
|
|
1502
|
+
const child = resolve(current, entry.name);
|
|
1503
|
+
if (entry.isDirectory() && !excluded.has(entry.name) && !entry.name.startsWith(".")) await walk(child, depth + 1);
|
|
1504
|
+
if (entry.isFile() && entityFile.test(entry.name) && !/\.(?:test|spec|d)\./.test(entry.name)) files.add(child);
|
|
1505
|
+
}
|
|
1506
|
+
};
|
|
1507
|
+
await walk(root, 0);
|
|
1508
|
+
}
|
|
1509
|
+
const entities = /* @__PURE__ */ new Set();
|
|
1510
|
+
const identities = /* @__PURE__ */ new Set();
|
|
1511
|
+
for (const file of [...files].sort()) {
|
|
1512
|
+
const identity = file.replace(/\.[cm]?[jt]s$/, "");
|
|
1513
|
+
if (identities.has(identity)) throw new Error(`Duplicate source/compiled entity representation: ${identity}`);
|
|
1514
|
+
identities.add(identity);
|
|
1515
|
+
await noSymlinks(file);
|
|
1516
|
+
if (await realpath(file) !== file) throw new Error("Entity file changed or became a symlink");
|
|
1517
|
+
let module;
|
|
1518
|
+
try {
|
|
1519
|
+
module = await importer(pathToFileURL(file));
|
|
1520
|
+
} catch (cause) {
|
|
1521
|
+
throw new Error(`Cannot load entity file ${file}`, { cause });
|
|
1522
|
+
}
|
|
1523
|
+
if (module && typeof module === "object") {
|
|
1524
|
+
for (const value of Object.values(module)) if (isDuraxisEntity(value)) entities.add(value);
|
|
1525
|
+
else if (value && typeof value === "object") {
|
|
1526
|
+
for (const item of Object.values(value)) if (isDuraxisEntity(item)) entities.add(item);
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
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");
|
|
1531
|
+
const result = [...entities];
|
|
1532
|
+
new MetadataRegistry(result).finalize();
|
|
1533
|
+
return result;
|
|
1534
|
+
}
|
|
1535
|
+
// src/database/create-orm.ts
|
|
1536
|
+
async function createORM(config, name) {
|
|
1537
|
+
const options = normalizeDuraxisConnection(selectDuraxisConnection(config, name));
|
|
1538
|
+
const entities = await discoverEntities(options);
|
|
1539
|
+
const database = await createDatabase(options);
|
|
1540
|
+
try {
|
|
1541
|
+
const orm = new DuraxisORM({
|
|
1542
|
+
database,
|
|
1543
|
+
entities,
|
|
1544
|
+
schema: options.schema,
|
|
1545
|
+
closeDatabase: true,
|
|
1546
|
+
closeStorage: options.closeStorage ?? typeof options.driver === "function"
|
|
1547
|
+
});
|
|
1548
|
+
await orm.initialize();
|
|
1549
|
+
return orm;
|
|
1550
|
+
} catch (cause) {
|
|
1551
|
+
try {
|
|
1552
|
+
await database.close();
|
|
1553
|
+
} catch (cleanup) {
|
|
1554
|
+
throw new AggregateError([cause, cleanup], "ORM initialization and cleanup failed");
|
|
1555
|
+
}
|
|
1556
|
+
throw cause;
|
|
1557
|
+
}
|
|
1558
|
+
}
|
|
1559
|
+
export { Column, CommitOutcomeUnknownError, DuplicateRecordError, DuraxisORM, DuraxisOrmError, Entity, EntityHydrator, EntityMapper, EntityMetadata, EntityNotRegisteredError, Index, InvalidColumnError, InvalidMetadataError, InvalidQueryError, JoinTable, ManyToMany, ManyToOne, MetadataRegistry, MissingPrimaryKeyError, OneToMany, OneToOne, OrmClosedError, OrmNotInitializedError, OrmTransactionManager, PrimaryKey, QueryBuilder, RecordNotFoundError, RelationLoader, RelationOperations, Repository, SchemaManager, SchemaViolationError, TransactionConflictError, TransactionManagerClosedError, UniqueIndexViolationOrmError, ValueTransformer, createORM, discoverEntities, exportSchema, isDuraxisEntity };
|
|
1399
1560
|
|
|
1400
1561
|
//# sourceMappingURL=index.js.map
|