@theokit/orm 0.1.0 → 0.2.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,28 +1,60 @@
1
1
  # Changelog
2
2
 
3
- ## [0.1.0] - 2026-06-22
3
+ All notable changes to `@theokit/orm` are documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [0.2.0] - 2026-08-21
4
11
 
5
12
  ### Added
6
13
 
7
- - **M7-7 — `createRepository(db, table)` non-DI factory.** Plain CRUD needs no `@theokit/di`, decorators, or `reflect-metadata` (only `@Transactional` requires a bound DataSource). Works with any drizzle `db`, including better-sqlite3 (awaitable builders). First stable release (drops the `-next` prerelease tag).
14
+ - Every published export now carries documentation an editor can show. Measured on the emitted
15
+ declarations: the package went from 3/20 to 20/20, and `@theokit/orm/schema-export` — the
16
+ polyglot surface a Python or Go consumer reaches first — from 0/4 to 4/4. The four error
17
+ classes now say which fault each one reports, so a `catch` can be written against the right
18
+ one rather than against `OrmError`. (#24)
8
19
 
9
- ## [0.1.0-next.1] - 2026-06-01
20
+ - npm provenance is enabled again. It was switched off because npm refuses attestation for packages built from a private source repository; this one is public now, so published tarballs carry a sigstore attestation linking them to the commit and workflow that produced them.
21
+ - `bindDataSourceToInstance` and `TransactionalOptions` are exported from the package entry point. `bindDataSourceToInstance` is what the `@Transactional` error message tells you to call, and it was not reachable from the published package, so following that instruction did not compile (#4).
22
+
23
+ ### Changed
24
+
25
+ - The peer range on `@theokit/di` accepts `^0.2.0` alongside `^0.1.0`. `@theokit/di` ships
26
+ breaking disposal fixes as `0.2.0`, outside the old range. `OrmModule.forRoot` registers its
27
+ DataSource with `useValue`, which is the provider kind whose disposal changed — but the
28
+ DataSource is a plain object with no `dispose`, no `Symbol.asyncDispose` and no
29
+ `@PreDestroy`, so the container never tore it down and the new ownership rule changes
30
+ nothing here. (#20)
31
+ - `exportSchema` marks a column `required` only when it is `NOT NULL` **and** has no default —
32
+ which is what it always did, but nothing proved it. Every fixture paired `notNull` with no
33
+ default, or a default with a nullable column, so dropping half the rule left the suite green.
34
+ A `notNull().defaultNow()` column now covers the case, verified by mutation. (#24)
35
+ - `repository`, `homepage` and `bugs` now point at `usetheokit/theokit-di`. They pointed at `usetheo/theokit-sdk`, so every "Repository" and "Report issues" link on npm led to a project that does not host this package.
36
+ - `@Transactional` no longer claims the container binds its DataSource automatically. Nothing ever did. The error message now names `bindDataSourceToInstance`, the one call that fixes it, and the docs show the container recipe: inject `ORM_DATA_SOURCE_TOKEN` and bind in a `@PostConstruct` hook (#4).
37
+ - **Breaking:** `@Transactional({ isolationLevel })` was accepted and silently ignored — the options parameter was never read. The level is now passed to the driver, and rejected with an `OrmConfigurationError` on `sqlite`, which has no per-transaction isolation level to set. Code that passed a level on sqlite and appeared to work was never getting one; it now fails instead of pretending (#4).
38
+
39
+
40
+ ## [0.1.0] - 2026-06-22
10
41
 
11
42
  ### Added
12
43
 
13
- - Python SQLAlchemy polyglot smoke test (T6.2) — exported JSON Schema 7 loads into SQLAlchemy `MetaData` + `create_all` succeeds against in-memory SQLite. Proves ADR D11 polyglot story works end-to-end across language boundaries. The smoke test gracefully skips when Python 3.10+ or `sqlalchemy` is unavailable.
14
- - `tests/integration/scripts/load_schema.py` — reference Python harness for consumers that want to load orm-emitted schemas into their own SQLAlchemy models.
44
+ - **`createRepository(db, table)` non-DI factory.** Plain CRUD needs no `@theokit/di`, decorators, or `reflect-metadata` (only `@Transactional` requires a bound DataSource). Works with any drizzle `db`, including better-sqlite3 (awaitable builders). First stable release (drops the `-next` prerelease tag).
15
45
 
16
- ## [Unreleased]
46
+ ## [0.1.0-next.1] - 2026-06-01
17
47
 
18
48
  ### Added
19
49
 
50
+ - Python SQLAlchemy polyglot smoke test — exported JSON Schema 7 loads into SQLAlchemy `MetaData` + `create_all` succeeds against in-memory SQLite. Proves the polyglot story works end-to-end across language boundaries. The smoke test gracefully skips when Python 3.10+ or `sqlalchemy` is unavailable.
51
+ - `tests/integration/scripts/load_schema.py` — reference Python harness for consumers that want to load orm-emitted schemas into their own SQLAlchemy models.
20
52
  - Package scaffold for `@theokit/orm`: tsup build, vitest setup, tsconfig with `experimentalDecorators` + `emitDecoratorMetadata`.
21
- - `Repository<T>` class with 6 minimum methods (`findById`, `findMany`, `insert`, `update`, `delete`, `query`) over `drizzle-orm`. EC-1 absorbed: throws `OrmConfigurationError` at construction when entity has no primary key. EC-2 absorbed: `findById`/`update`/`delete` validate `id` is non-null, non-empty, string-or-number to prevent data-loss from `DELETE WHERE id IS NULL`.
53
+ - `Repository<T>` class with 6 minimum methods (`findById`, `findMany`, `insert`, `update`, `delete`, `query`) over `drizzle-orm`. Throws `OrmConfigurationError` at construction when the entity has no primary key, and `findById`/`update`/`delete` validate `id` is non-null, non-empty, string-or-number to prevent data-loss from `DELETE WHERE id IS NULL`.
22
54
  - `getRepositoryToken(entity, dataSourceName?)` token generator. Mirrors NestJS TypeORM convention (`REPO:${entityName}` / `REPO:${dataSourceName}:${entityName}`).
23
55
  - `@InjectRepository(entity, dataSourceName?)` parameter decorator wrapping `@Inject` from `@theokit/di`.
24
- - `OrmModule.forRoot(opts)` / `OrmModule.forFeature(entities, dataSourceName?)` provider builders. EC-5 absorbed: `forFeature` throws `OrmConfigurationError` with actionable message if `forRoot` was not called for the dataSource first.
56
+ - `OrmModule.forRoot(opts)` / `OrmModule.forFeature(entities, dataSourceName?)` provider builders. `forFeature` throws `OrmConfigurationError` with actionable message if `forRoot` was not called for the dataSource first.
25
57
  - `withAgentContext({ agentId, runId, conversationId }, fn)` AsyncLocalStorage helper. Repository `insert`/`update` auto-fill matching columns when context is present and column exists on the table.
26
- - `@Transactional()` method decorator wraps `db.transaction(...)` with rollback-on-throw. Tx propagated via `withTxContext` AsyncLocalStorage so injected Repositories transparently use the tx scope. EC-9 absorbed: throws `OrmConfigurationError` with actionable message when the host class is not DI-managed (no DataSource bound).
27
- - `exportSchemas(schema)` / `exportSchema(table)` (from `@theokit/orm/schema-export`): emit JSON Schema 7 from Drizzle tables. 12 column types mapped (text, varchar, integer, bigint, real, numeric, boolean, json, uuid, blob, timestamp, enum). EC-11 absorbed: unknown column types throw `OrmSchemaExportError` with actionable message — no silent fallback.
58
+ - `@Transactional()` method decorator wraps `db.transaction(...)` with rollback-on-throw. Tx propagated via `withTxContext` AsyncLocalStorage so injected Repositories transparently use the tx scope. Throws `OrmConfigurationError` with actionable message when the host class is not DI-managed (no DataSource bound).
59
+ - `exportSchemas(schema)` / `exportSchema(table)` (from `@theokit/orm/schema-export`): emit JSON Schema 7 from Drizzle tables. 12 column types mapped (text, varchar, integer, bigint, real, numeric, boolean, json, uuid, blob, timestamp, enum). Unknown column types throw `OrmSchemaExportError` with actionable message — no silent fallback.
28
60
  - `OrmError`, `OrmConfigurationError`, `OrmValidationError`, `OrmSchemaExportError` typed error hierarchy.
package/LICENSE CHANGED
@@ -137,8 +137,8 @@
137
137
 
138
138
  6. Trademarks. This License does not grant permission to use the trade
139
139
  names, trademarks, service marks, or product names of the Licensor,
140
- except as required for describing the origin of the Work and
141
- reproducing the content of the NOTICE file.
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
142
 
143
143
  7. Disclaimer of Warranty. Unless required by applicable law or
144
144
  agreed to in writing, Licensor provides the Work (and each
package/dist/index.cjs CHANGED
@@ -314,34 +314,52 @@ var OrmModule = {
314
314
 
315
315
  // src/transactional.ts
316
316
  var DATA_SOURCE_KEY = /* @__PURE__ */ Symbol.for("Theo:orm:dataSource");
317
+ function bindDataSourceToInstance(instance, ds) {
318
+ instance[DATA_SOURCE_KEY] = ds;
319
+ }
320
+ __name(bindDataSourceToInstance, "bindDataSourceToInstance");
317
321
  function readDataSourceFromInstance(instance) {
318
322
  const v = instance[DATA_SOURCE_KEY];
319
323
  return v ?? void 0;
320
324
  }
321
325
  __name(readDataSourceFromInstance, "readDataSourceFromInstance");
322
- function Transactional(_opts = {}) {
326
+ var DIALECTS_WITH_ISOLATION_LEVEL = /* @__PURE__ */ new Set([
327
+ "pg",
328
+ "mysql"
329
+ ]);
330
+ function Transactional(opts = {}) {
323
331
  return /* @__PURE__ */ __name(function transactionalDecorator(_target, propertyKey, descriptor) {
324
332
  const original = descriptor.value;
325
333
  if (typeof original !== "function") {
326
334
  throw new OrmConfigurationError(`@Transactional on ${String(propertyKey)}: target is not a method.`);
327
335
  }
328
336
  descriptor.value = /* @__PURE__ */ __name(async function transactionalWrapper(...args) {
329
- const ds = readDataSourceFromInstance(this);
330
- if (!ds) {
331
- throw new OrmConfigurationError(`@Transactional ${String(propertyKey)}: no DataSource bound to instance. The class must be DI-managed via Container.resolve OR bindDataSourceToInstance(instance, ds) must be called before invoking the method.`);
332
- }
333
- const db = ds.db;
334
- if (typeof db.transaction !== "function") {
335
- throw new OrmConfigurationError(`@Transactional ${String(propertyKey)}: DataSource.db does not expose .transaction(). Ensure you passed a Drizzle db instance.`);
336
- }
337
- return db.transaction(async (tx) => {
338
- return withTxContext(tx, () => original.apply(this, args));
337
+ const transaction = resolveTransactionFn(this, propertyKey, opts);
338
+ const run = /* @__PURE__ */ __name((tx) => withTxContext(tx, () => original.apply(this, args)), "run");
339
+ return opts.isolationLevel === void 0 ? transaction(run) : transaction(run, {
340
+ isolationLevel: opts.isolationLevel
339
341
  });
340
342
  }, "transactionalWrapper");
341
343
  return descriptor;
342
344
  }, "transactionalDecorator");
343
345
  }
344
346
  __name(Transactional, "Transactional");
347
+ function resolveTransactionFn(instance, propertyKey, opts) {
348
+ const where = `@Transactional ${String(propertyKey)}`;
349
+ const ds = readDataSourceFromInstance(instance);
350
+ if (!ds) {
351
+ throw new OrmConfigurationError(`${where}: no DataSource bound to instance. Call bindDataSourceToInstance(this, dataSource) before invoking the method \u2014 from a @PostConstruct hook when the class is container-managed, or directly after construction when it is not.`);
352
+ }
353
+ if (opts.isolationLevel !== void 0 && !DIALECTS_WITH_ISOLATION_LEVEL.has(ds.dialect)) {
354
+ throw new OrmConfigurationError(`${where}: isolationLevel "${opts.isolationLevel}" is not supported on ${ds.dialect}. Remove the option, or use a dialect that has isolation levels (pg, mysql).`);
355
+ }
356
+ const db = ds.db;
357
+ if (typeof db.transaction !== "function") {
358
+ throw new OrmConfigurationError(`${where}: DataSource.db does not expose .transaction(). Ensure you passed a Drizzle db instance.`);
359
+ }
360
+ return db.transaction.bind(db);
361
+ }
362
+ __name(resolveTransactionFn, "resolveTransactionFn");
345
363
 
346
364
  exports.InjectRepository = InjectRepository;
347
365
  exports.ORM_DATA_SOURCE_TOKEN = ORM_DATA_SOURCE_TOKEN;
@@ -352,6 +370,7 @@ exports.OrmSchemaExportError = OrmSchemaExportError;
352
370
  exports.OrmValidationError = OrmValidationError;
353
371
  exports.Repository = Repository;
354
372
  exports.Transactional = Transactional;
373
+ exports.bindDataSourceToInstance = bindDataSourceToInstance;
355
374
  exports.createRepository = createRepository;
356
375
  exports.getAgentContext = getAgentContext;
357
376
  exports.getRepositoryToken = getRepositoryToken;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/als-context.ts","../src/errors.ts","../src/tokens.ts","../src/inject-repository.ts","../src/internal/data-source.ts","../src/internal/agent-column-filler.ts","../src/internal/tx-context.ts","../src/repository.ts","../src/types.ts","../src/module.ts","../src/transactional.ts"],"names":["als","AsyncLocalStorage","withAgentContext","ctx","fn","Promise","resolve","run","getAgentContext","getStore","OrmError","Error","name","OrmConfigurationError","OrmValidationError","OrmSchemaExportError","DEFAULT_DS","DRIZZLE_NAME_SYMBOL","Symbol","for","resolveEntityName","entity","undefined","ent","symbolName","length","inner","_","getRepositoryToken","dataSourceName","entityName","InjectRepository","Inject","createDataSource","opts","dialect","schema","db","TRACKED_COLS","warnedTables","WeakSet","getTableColumnNames","table","Object","keys","getTableColumns","fillAgentColumns","row","columns","hasAnyTrackedCol","some","c","includes","process","env","NODE_ENV","has","add","console","warn","filled","col","txAls","withTxContext","tx","getTxContext","resolveTableName","sym","detectPrimaryKey","tableName","colName","entries","meta","primary","isPrimaryKey","primaryKey","column","id","assertValidId","method","Repository","pkColumn","pkName","defaultDb","pk","findById","rows","select","from","where","eq","limit","findMany","q","insert","values","op","returning","update","patch","set","delete","query","_primaryKeyName","createRepository","ORM_DATA_SOURCE_TOKEN","registeredDataSources","Set","dataSourceTokenFor","entityArrayOrThrow","entities","Array","isArray","OrmModule","forRoot","dataSource","token","provide","useValue","forFeature","ents","dsToken","map","inject","useFactory","ds","_resetForTesting","clear","DATA_SOURCE_KEY","readDataSourceFromInstance","instance","v","Transactional","_opts","transactionalDecorator","_target","propertyKey","descriptor","original","value","String","transactionalWrapper","args","transaction","apply"],"mappings":";;;;;;;;AAGA,IAAMA,GAAAA,GAAM,IAAIC,6BAAAA,EAAAA;AAET,SAASC,gBAAAA,CAAoBC,KAAmBC,EAAAA,EAAwB;AAC7E,EAAA,OAAOC,QAAQC,OAAAA,CAAQN,GAAAA,CAAIO,GAAAA,CAAIJ,GAAAA,EAAKC,EAAAA,CAAAA,CAAAA;AACtC;AAFgBF,MAAAA,CAAAA,gBAAAA,EAAAA,kBAAAA,CAAAA;AAIT,SAASM,eAAAA,GAAAA;AACd,EAAA,OAAOR,IAAIS,QAAAA,EAAQ;AACrB;AAFgBD,MAAAA,CAAAA,eAAAA,EAAAA,iBAAAA,CAAAA;;;ACTT,IAAME,QAAAA,GAAN,cAAuBC,KAAAA,CAAAA;EAA9B;;;EACoBC,IAAAA,GAAe,UAAA;AACnC;AAEO,IAAMC,qBAAAA,GAAN,cAAoCH,QAAAA,CAAAA;EAJ3C;;;EAKoBE,IAAAA,GAAO,uBAAA;AAC3B;AAEO,IAAME,kBAAAA,GAAN,cAAiCJ,QAAAA,CAAAA;EARxC;;;EASoBE,IAAAA,GAAO,oBAAA;AAC3B;AAEO,IAAMG,oBAAAA,GAAN,cAAmCL,QAAAA,CAAAA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age } from \"node:async_hooks\";\nimport type { AgentContext } from \"./types.js\";\n\nconst als = new AsyncLocalStorage<AgentContext>();\n\nexport function withAgentContext<R>(ctx: AgentContext, fn: () => R | Promise<R>): Promise<R> {\n return Promise.resolve(als.run(ctx, fn));\n}\n\nexport function getAgentContext(): AgentContext | undefined {\n return als.getStore();\n}\n","export class OrmError extends Error {\n override readonly name: string = \"OrmError\";\n}\n\nexport class OrmConfigurationError extends OrmError {\n override readonly name = \"OrmConfigurationError\";\n}\n\nexport class OrmValidationError extends OrmError {\n override readonly name = \"OrmValidationError\";\n}\n\nexport class OrmSchemaExportError extends OrmError {\n override readonly name = \"OrmSchemaExportError\";\n}\n","import { OrmConfigurationError } from \"./errors.js\";\n\nconst DEFAULT_DS = \"default\";\n\nconst DRIZZLE_NAME_SYMBOL = Symbol.for(\"drizzle:Name\");\n\nfunction resolveEntityName(entity: unknown): string {\n if (entity === null || entity === undefined) {\n throw new OrmConfigurationError(\n \"[orm] getRepositoryToken: entity is null/undefined. Pass a Drizzle table object.\",\n );\n }\n const ent = entity as Record<string | symbol, unknown>;\n const symbolName = ent[DRIZZLE_NAME_SYMBOL];\n if (typeof symbolName === \"string\" && symbolName.length > 0) return symbolName;\n const inner = ent._ as { name?: unknown } | undefined;\n if (inner && typeof inner.name === \"string\" && inner.name.length > 0) {\n return inner.name;\n }\n throw new OrmConfigurationError(\n \"[orm] getRepositoryToken: cannot resolve entity name. Pass a Drizzle table (must have either Symbol.for('drizzle:Name') or _.name).\",\n );\n}\n\nexport function getRepositoryToken(entity: unknown, dataSourceName: string = DEFAULT_DS): string {\n const entityName = resolveEntityName(entity);\n return dataSourceName === DEFAULT_DS\n ? `REPO:${entityName}`\n : `REPO:${dataSourceName}:${entityName}`;\n}\n","import { Inject } from \"@theokit/di\";\nimport { getRepositoryToken } from \"./tokens.js\";\n\nexport function InjectRepository(entity: unknown, dataSourceName?: string): ParameterDecorator {\n return Inject(getRepositoryToken(entity, dataSourceName));\n}\n","import type { AnyTable, DataSource, OrmRootOptions } from \"../types.js\";\n\nexport function createDataSource<TSchema extends Record<string, AnyTable>>(\n opts: OrmRootOptions<TSchema>,\n): DataSource<TSchema> {\n const name = opts.dataSourceName ?? \"default\";\n return {\n name,\n dialect: opts.dialect,\n schema: opts.schema,\n db: opts.db,\n };\n}\n","import { getTableColumns } from \"drizzle-orm\";\nimport { getAgentContext } from \"../als-context.js\";\n\nconst TRACKED_COLS = [\"agentId\", \"runId\", \"conversationId\"] as const;\n\nconst warnedTables = new WeakSet<object>();\n\nfunction getTableColumnNames(table: unknown): string[] {\n if (table === null || typeof table !== \"object\") return [];\n try {\n return Object.keys(getTableColumns(table as Parameters<typeof getTableColumns>[0]));\n } catch {\n return [];\n }\n}\n\nexport function fillAgentColumns<T extends Record<string, unknown>>(table: unknown, row: T): T {\n const columns = getTableColumnNames(table);\n const hasAnyTrackedCol = TRACKED_COLS.some((c) => columns.includes(c));\n if (!hasAnyTrackedCol) return row;\n\n const ctx = getAgentContext();\n if (!ctx) {\n if (\n process.env.NODE_ENV !== \"production\" &&\n typeof table === \"object\" &&\n table !== null &&\n !warnedTables.has(table)\n ) {\n warnedTables.add(table);\n console.warn(\n `[@theokit/orm] Table has agentId/runId/conversationId column(s) but no AgentContext set. Wrap calls with withAgentContext({...}, () => ...) to auto-fill.`,\n );\n }\n return row;\n }\n\n const filled: Record<string, unknown> = { ...row };\n for (const col of TRACKED_COLS) {\n if (columns.includes(col) && filled[col] === undefined && ctx[col] !== undefined) {\n filled[col] = ctx[col];\n }\n }\n return filled as T;\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\n\nconst txAls = new AsyncLocalStorage<unknown>();\n\nexport function withTxContext<R>(tx: unknown, fn: () => R | Promise<R>): Promise<R> {\n return Promise.resolve(txAls.run(tx, fn));\n}\n\nexport function getTxContext(): unknown | undefined {\n return txAls.getStore();\n}\n","import type { Column, InferInsertModel, InferSelectModel, SQL, Table } from \"drizzle-orm\";\nimport { eq, getTableColumns } from \"drizzle-orm\";\nimport { OrmConfigurationError, OrmValidationError } from \"./errors.js\";\nimport { fillAgentColumns } from \"./internal/agent-column-filler.js\";\nimport { getTxContext } from \"./internal/tx-context.js\";\n\ninterface DrizzleColumnMeta {\n primary?: boolean;\n isPrimaryKey?: boolean;\n primaryKey?: boolean;\n name?: string;\n}\n\nfunction resolveTableName(table: unknown): string {\n if (table === null || typeof table !== \"object\") return \"<unknown>\";\n const sym = (table as Record<symbol, unknown>)[Symbol.for(\"drizzle:Name\")];\n if (typeof sym === \"string\") return sym;\n const inner = (table as { _?: { name?: string } })._;\n return inner?.name ?? \"<unknown>\";\n}\n\nfunction detectPrimaryKey(table: Table): { name: string; column: Column } {\n const columns = getTableColumns(table) as Record<string, Column>;\n const tableName = resolveTableName(table);\n for (const [colName, col] of Object.entries(columns)) {\n const meta = col as unknown as DrizzleColumnMeta;\n if (meta.primary === true || meta.isPrimaryKey === true || meta.primaryKey === true) {\n return { name: colName, column: col };\n }\n }\n if (\"id\" in columns) {\n return { name: \"id\", column: columns.id as Column };\n }\n throw new OrmConfigurationError(\n `Entity \"${tableName}\" has no primary key. v0.1 requires a single-column PK named \"id\" or marked .primaryKey(). Use repo.query() for composite/custom keys.`,\n );\n}\n\nfunction assertValidId(method: string, id: unknown): asserts id is string | number {\n if (id === undefined || id === null) {\n throw new OrmValidationError(\n `Repository.${method}: id is required and non-null (received ${id === null ? \"null\" : \"undefined\"}).`,\n );\n }\n if (typeof id === \"string\" && id.length === 0) {\n throw new OrmValidationError(\n `Repository.${method}: id is required and non-empty (received empty string).`,\n );\n }\n if (typeof id !== \"string\" && typeof id !== \"number\") {\n throw new OrmValidationError(\n `Repository.${method}: id must be string or number (received ${typeof id}).`,\n );\n }\n}\n\ninterface DialectAwareDb {\n insert: (table: unknown) => {\n values: (v: unknown) => {\n returning?: () => Promise<unknown[]>;\n run?: () => unknown;\n get?: () => unknown;\n };\n };\n update: (table: unknown) => {\n set: (v: unknown) => {\n where: (w: unknown) => {\n returning?: () => Promise<unknown[]>;\n run?: () => unknown;\n };\n };\n };\n delete: (table: unknown) => {\n where: (w: unknown) => Promise<unknown> | { run?: () => unknown };\n };\n select: () => { from: (table: unknown) => unknown };\n}\n\nexport class Repository<T extends Table> {\n private readonly pkColumn: Column;\n private readonly pkName: string;\n private readonly tableName: string;\n\n constructor(\n private readonly defaultDb: unknown,\n private readonly table: T,\n ) {\n const pk = detectPrimaryKey(table);\n this.pkColumn = pk.column;\n this.pkName = pk.name;\n this.tableName = resolveTableName(table);\n }\n\n private get db(): DialectAwareDb {\n const tx = getTxContext();\n return (tx ?? this.defaultDb) as DialectAwareDb;\n }\n\n async findById(id: string | number): Promise<InferSelectModel<T> | null> {\n assertValidId(\"findById\", id);\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle generic chain — fluent query builder types are too complex to narrow at call site without importing internal Drizzle types\n const rows = (await (this.db.select().from(this.table) as any)\n .where(eq(this.pkColumn, id))\n .limit(1)) as unknown[];\n return (rows[0] as InferSelectModel<T>) ?? null;\n }\n\n async findMany(where?: SQL): Promise<InferSelectModel<T>[]> {\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle generic chain — fluent query builder types are too complex to narrow at call site without importing internal Drizzle types\n const q = this.db.select().from(this.table) as any;\n const rows = (where ? await q.where(where) : await q) as unknown[];\n return rows as InferSelectModel<T>[];\n }\n\n async insert(values: InferInsertModel<T>): Promise<InferSelectModel<T>> {\n const filled = fillAgentColumns(this.table, values as Record<string, unknown>);\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle generic chain — fluent query builder types are too complex to narrow at call site without importing internal Drizzle types\n const op = this.db.insert(this.table).values(filled) as any;\n if (typeof op.returning === \"function\") {\n const rows = (await op.returning()) as unknown[];\n const row = rows[0];\n if (row === undefined) {\n throw new OrmValidationError(\n `Repository.insert on \"${this.tableName}\" returned zero rows. Driver may not support .returning() (MySQL?). Use repo.query() with manual fetch for that dialect.`,\n );\n }\n return row as InferSelectModel<T>;\n }\n throw new OrmConfigurationError(\n `Repository.insert on \"${this.tableName}\": driver does not expose .returning(). v0.1 supports SQLite/Postgres. For MySQL, use repo.query() and manually fetch the inserted row.`,\n );\n }\n\n async update(\n id: string | number,\n patch: Partial<InferInsertModel<T>>,\n ): Promise<InferSelectModel<T>> {\n assertValidId(\"update\", id);\n const filled = fillAgentColumns(this.table, patch as Record<string, unknown>);\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle generic chain — fluent query builder types are too complex to narrow at call site without importing internal Drizzle types\n const op = this.db.update(this.table).set(filled).where(eq(this.pkColumn, id)) as any;\n if (typeof op.returning === \"function\") {\n const rows = (await op.returning()) as unknown[];\n const row = rows[0];\n if (row === undefined) {\n throw new OrmValidationError(\n `Repository.update on \"${this.tableName}\" id=\"${id}\": no row matched.`,\n );\n }\n return row as InferSelectModel<T>;\n }\n throw new OrmConfigurationError(\n `Repository.update on \"${this.tableName}\": driver does not expose .returning(). v0.1 supports SQLite/Postgres. For MySQL, use repo.query() and manually fetch.`,\n );\n }\n\n async delete(id: string | number): Promise<void> {\n assertValidId(\"delete\", id);\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle generic chain — fluent query builder types are too complex to narrow at call site without importing internal Drizzle types\n await (this.db.delete(this.table) as any).where(eq(this.pkColumn, id));\n }\n\n query() {\n return this.db.select().from(this.table);\n }\n\n /** @internal exposed for tests */\n get _primaryKeyName(): string {\n return this.pkName;\n }\n}\n\n/**\n * M7-7 — non-DI factory for {@link Repository}. The `Repository` constructor is\n * already DI-free (`new Repository(db, table)`); this factory makes the non-DI\n * path explicit and discoverable, so consumers do NOT need `@theokit/di`,\n * decorators, or `reflect-metadata` for plain CRUD — only `@Transactional`\n * requires a bound DataSource. Works with any drizzle `db` (incl. better-sqlite3,\n * whose query builders are awaitable).\n *\n * @public\n */\nexport function createRepository<T extends Table>(db: unknown, table: T): Repository<T> {\n return new Repository(db, table);\n}\n","import type { Table } from \"drizzle-orm\";\n\nexport type AnyTable = Table;\n\nexport type Dialect = \"sqlite\" | \"pg\" | \"mysql\";\n\nexport interface OrmRootOptions<\n TSchema extends Record<string, AnyTable> = Record<string, AnyTable>,\n> {\n schema: TSchema;\n dialect: Dialect;\n db: unknown;\n dataSourceName?: string;\n}\n\nexport interface DataSource<TSchema extends Record<string, AnyTable> = Record<string, AnyTable>> {\n readonly name: string;\n readonly dialect: Dialect;\n readonly schema: TSchema;\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle db handle has driver-specific shape (BetterSQLite3Database vs PgDatabase vs MySqlDatabase); narrow types come at use-site via Repository<T> generic\n readonly db: any;\n}\n\nexport const ORM_DATA_SOURCE_TOKEN = \"ORM_DATA_SOURCE\";\n\nexport interface AgentContext {\n agentId?: string;\n runId?: string;\n conversationId?: string;\n}\n","import type { Provider } from \"@theokit/di\";\nimport { OrmConfigurationError } from \"./errors.js\";\nimport { createDataSource } from \"./internal/data-source.js\";\nimport { Repository } from \"./repository.js\";\nimport { getRepositoryToken } from \"./tokens.js\";\nimport {\n type AnyTable,\n type DataSource,\n ORM_DATA_SOURCE_TOKEN,\n type OrmRootOptions,\n} from \"./types.js\";\n\nconst registeredDataSources = new Set<string>();\n\nfunction dataSourceTokenFor(name: string): string {\n return name === \"default\" ? ORM_DATA_SOURCE_TOKEN : `${ORM_DATA_SOURCE_TOKEN}:${name}`;\n}\n\nfunction entityArrayOrThrow(entities: unknown): readonly unknown[] {\n if (!Array.isArray(entities)) {\n throw new OrmConfigurationError(\n `OrmModule.forFeature: entities must be an array of Drizzle tables. Got ${typeof entities}`,\n );\n }\n if (entities.length === 0) {\n throw new OrmConfigurationError(\n \"OrmModule.forFeature: entities array is empty. Provide at least one Drizzle table.\",\n );\n }\n return entities;\n}\n\nexport const OrmModule = {\n forRoot<TSchema extends Record<string, AnyTable>>(opts: OrmRootOptions<TSchema>): Provider[] {\n if (opts === null || typeof opts !== \"object\") {\n throw new OrmConfigurationError(\n \"OrmModule.forRoot: options is required. Pass { schema, dialect, db }.\",\n );\n }\n if (opts.db === undefined || opts.db === null) {\n throw new OrmConfigurationError(\n \"OrmModule.forRoot: opts.db is required. Pass the Drizzle db instance (e.g. drizzle(client, { schema })).\",\n );\n }\n if (![\"sqlite\", \"pg\", \"mysql\"].includes(opts.dialect)) {\n throw new OrmConfigurationError(\n `OrmModule.forRoot: opts.dialect must be one of \"sqlite\" | \"pg\" | \"mysql\". Got \"${opts.dialect}\".`,\n );\n }\n const name = opts.dataSourceName ?? \"default\";\n const dataSource = createDataSource(opts);\n const token = dataSourceTokenFor(name);\n\n registeredDataSources.add(name);\n\n return [\n {\n provide: token,\n useValue: dataSource,\n },\n ];\n },\n\n forFeature(entities: readonly unknown[], dataSourceName: string = \"default\"): Provider[] {\n const ents = entityArrayOrThrow(entities);\n\n if (!registeredDataSources.has(dataSourceName)) {\n throw new OrmConfigurationError(\n `OrmModule.forFeature called${\n dataSourceName === \"default\" ? \"\" : ` for dataSource=\"${dataSourceName}\"`\n } before OrmModule.forRoot. Call OrmModule.forRoot(opts) first in your Container providers array.`,\n );\n }\n\n const dsToken = dataSourceTokenFor(dataSourceName);\n\n return ents.map((entity) => ({\n provide: getRepositoryToken(entity, dataSourceName),\n inject: [dsToken],\n useFactory: (ds: DataSource) => new Repository(ds.db, entity as AnyTable),\n }));\n },\n\n /** @internal — testing escape hatch to reset module-level state */\n _resetForTesting(): void {\n registeredDataSources.clear();\n },\n};\n","import { OrmConfigurationError } from \"./errors.js\";\nimport { withTxContext } from \"./internal/tx-context.js\";\nimport type { DataSource } from \"./types.js\";\n\nconst DATA_SOURCE_KEY = Symbol.for(\"Theo:orm:dataSource\");\n\n/**\n * Internal: any class containing @Transactional methods must have its\n * DataSource injected via this protocol so the decorator can find it.\n * The OrmModule arranges this automatically when classes are DI-managed.\n *\n * Direct (non-DI) instantiation requires manually calling\n * `bindDataSourceToInstance(instance, ds)` before invoking the method.\n */\nexport function bindDataSourceToInstance(instance: object, ds: DataSource): void {\n (instance as Record<symbol, unknown>)[DATA_SOURCE_KEY] = ds;\n}\n\nfunction readDataSourceFromInstance(instance: object): DataSource | undefined {\n const v = (instance as Record<symbol, unknown>)[DATA_SOURCE_KEY];\n return (v as DataSource | undefined) ?? undefined;\n}\n\ninterface TransactionalOptions {\n isolationLevel?: \"read uncommitted\" | \"read committed\" | \"repeatable read\" | \"serializable\";\n}\n\nexport function Transactional(_opts: TransactionalOptions = {}): MethodDecorator {\n return function transactionalDecorator(\n _target: object,\n propertyKey: string | symbol,\n descriptor: PropertyDescriptor,\n ): PropertyDescriptor {\n const original = descriptor.value;\n if (typeof original !== \"function\") {\n throw new OrmConfigurationError(\n `@Transactional on ${String(propertyKey)}: target is not a method.`,\n );\n }\n\n descriptor.value = async function transactionalWrapper(\n this: object,\n ...args: unknown[]\n ): Promise<unknown> {\n const ds = readDataSourceFromInstance(this);\n if (!ds) {\n throw new OrmConfigurationError(\n `@Transactional ${String(propertyKey)}: no DataSource bound to instance. The class must be DI-managed via Container.resolve OR bindDataSourceToInstance(instance, ds) must be called before invoking the method.`,\n );\n }\n\n const db = ds.db as {\n transaction?: (cb: (tx: unknown) => Promise<unknown>) => Promise<unknown>;\n };\n if (typeof db.transaction !== \"function\") {\n throw new OrmConfigurationError(\n `@Transactional ${String(propertyKey)}: DataSource.db does not expose .transaction(). Ensure you passed a Drizzle db instance.`,\n );\n }\n\n return db.transaction(async (tx: unknown) => {\n return withTxContext(tx, () => original.apply(this, args));\n });\n };\n\n return descriptor;\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/als-context.ts","../src/errors.ts","../src/tokens.ts","../src/inject-repository.ts","../src/internal/data-source.ts","../src/internal/agent-column-filler.ts","../src/internal/tx-context.ts","../src/repository.ts","../src/types.ts","../src/module.ts","../src/transactional.ts"],"names":["als","AsyncLocalStorage","withAgentContext","ctx","fn","Promise","resolve","run","getAgentContext","getStore","OrmError","Error","name","OrmConfigurationError","OrmValidationError","OrmSchemaExportError","DEFAULT_DS","DRIZZLE_NAME_SYMBOL","Symbol","for","resolveEntityName","entity","undefined","ent","symbolName","length","inner","_","getRepositoryToken","dataSourceName","entityName","InjectRepository","Inject","createDataSource","opts","dialect","schema","db","TRACKED_COLS","warnedTables","WeakSet","getTableColumnNames","table","Object","keys","getTableColumns","fillAgentColumns","row","columns","hasAnyTrackedCol","some","c","includes","process","env","NODE_ENV","has","add","console","warn","filled","col","txAls","withTxContext","tx","getTxContext","resolveTableName","sym","detectPrimaryKey","tableName","colName","entries","meta","primary","isPrimaryKey","primaryKey","column","id","assertValidId","method","Repository","pkColumn","pkName","defaultDb","pk","findById","rows","select","from","where","eq","limit","findMany","q","insert","values","op","returning","update","patch","set","delete","query","_primaryKeyName","createRepository","ORM_DATA_SOURCE_TOKEN","registeredDataSources","Set","dataSourceTokenFor","entityArrayOrThrow","entities","Array","isArray","OrmModule","forRoot","dataSource","token","provide","useValue","forFeature","ents","dsToken","map","inject","useFactory","ds","_resetForTesting","clear","DATA_SOURCE_KEY","bindDataSourceToInstance","instance","readDataSourceFromInstance","v","DIALECTS_WITH_ISOLATION_LEVEL","Transactional","transactionalDecorator","_target","propertyKey","descriptor","original","value","String","transactionalWrapper","args","transaction","resolveTransactionFn","apply","isolationLevel","bind"],"mappings":";;;;;;;;AAGA,IAAMA,GAAAA,GAAM,IAAIC,6BAAAA,EAAAA;AAcT,SAASC,gBAAAA,CAAoBC,KAAmBC,EAAAA,EAAwB;AAC7E,EAAA,OAAOC,QAAQC,OAAAA,CAAQN,GAAAA,CAAIO,GAAAA,CAAIJ,GAAAA,EAAKC,EAAAA,CAAAA,CAAAA;AACtC;AAFgBF,MAAAA,CAAAA,gBAAAA,EAAAA,kBAAAA,CAAAA;AAUT,SAASM,eAAAA,GAAAA;AACd,EAAA,OAAOR,IAAIS,QAAAA,EAAQ;AACrB;AAFgBD,MAAAA,CAAAA,eAAAA,EAAAA,iBAAAA,CAAAA;;;ACpBT,IAAME,QAAAA,GAAN,cAAuBC,KAAAA,CAAAA;EAP9B;;;EAQoBC,IAAAA,GAAe,UAAA;AACnC;AAUO,IAAMC,qBAAAA,GAAN,cAA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4G,MAAAA,CAAAA,oBAAAA,EAAAA,sBAAAA,CAAAA","file":"index.cjs","sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { AgentContext } from \"./types.js\";\n\nconst als = new AsyncLocalStorage<AgentContext>();\n\n/**\n * Run `fn` with an agent context attached, so repositories can stamp agent-aware columns without\n * the caller threading the ids through every function in between.\n *\n * The context follows the async chain rather than the call stack, so it survives every `await`\n * inside `fn`. It does NOT survive an escape from that chain: a bare `setTimeout` or `setImmediate`\n * inside `fn` starts a new chain and sees no context. Wrap the whole unit of work, not a fragment\n * of it.\n *\n * @returns whatever `fn` returns, always as a Promise, so a synchronous and an asynchronous `fn`\n * are called the same way.\n */\nexport function withAgentContext<R>(ctx: AgentContext, fn: () => R | Promise<R>): Promise<R> {\n return Promise.resolve(als.run(ctx, fn));\n}\n\n/**\n * The agent context of the current async chain, or `undefined` outside {@link withAgentContext}.\n *\n * `undefined` is a normal answer, not an error: a repository writing agent-aware columns leaves\n * them unset rather than refusing the write, because plain application code has no agent to name.\n */\nexport function getAgentContext(): AgentContext | undefined {\n return als.getStore();\n}\n","/**\n * Base class for every error this package raises.\n *\n * Catch this to handle anything from `@theokit/orm` without naming each subclass, and catch a\n * subclass when the response differs: a configuration fault needs a deploy, a validation fault\n * needs a different call.\n */\nexport class OrmError extends Error {\n override readonly name: string = \"OrmError\";\n}\n\n/**\n * The wiring is wrong, and no input will make the call succeed.\n *\n * Raised when an entity has no primary key, when `forFeature` runs before `forRoot` for its data\n * source, when `@Transactional` finds no DataSource bound to the instance, or when the handle\n * passed as `db` does not expose `transaction()`. Every case is a mistake in setup rather than in\n * the data, so it fails at the earliest point that can see it rather than at the first query.\n */\nexport class OrmConfigurationError extends OrmError {\n override readonly name = \"OrmConfigurationError\";\n}\n\n/**\n * A caller-supplied value was rejected at the boundary.\n *\n * The id guards are the reason this exists: `findById`, `update` and `delete` refuse a null, empty\n * or non-scalar id rather than passing it to Drizzle, because a `DELETE` whose `WHERE` matched\n * nothing usable is indistinguishable from one that matched everything until the rows are gone.\n */\nexport class OrmValidationError extends OrmError {\n override readonly name = \"OrmValidationError\";\n}\n\n/**\n * A table could not be expressed as JSON Schema.\n *\n * Raised by {@link exportSchema} for a column whose type has no mapping. It fails rather than\n * skipping the column: a consumer generating a model in another language would get one missing a\n * field and find out at the first insert.\n */\nexport class OrmSchemaExportError extends OrmError {\n override readonly name = \"OrmSchemaExportError\";\n}\n","import { OrmConfigurationError } from \"./errors.js\";\n\nconst DEFAULT_DS = \"default\";\n\nconst DRIZZLE_NAME_SYMBOL = Symbol.for(\"drizzle:Name\");\n\nfunction resolveEntityName(entity: unknown): string {\n if (entity === null || entity === undefined) {\n throw new OrmConfigurationError(\n \"[orm] getRepositoryToken: entity is null/undefined. Pass a Drizzle table object.\",\n );\n }\n const ent = entity as Record<string | symbol, unknown>;\n const symbolName = ent[DRIZZLE_NAME_SYMBOL];\n if (typeof symbolName === \"string\" && symbolName.length > 0) return symbolName;\n const inner = ent._ as { name?: unknown } | undefined;\n if (inner && typeof inner.name === \"string\" && inner.name.length > 0) {\n return inner.name;\n }\n throw new OrmConfigurationError(\n \"[orm] getRepositoryToken: cannot resolve entity name. Pass a Drizzle table (must have either Symbol.for('drizzle:Name') or _.name).\",\n );\n}\n\n/**\n * The container token under which one table's {@link Repository} is registered.\n *\n * `REPO:<table>` for the default data source and `REPO:<source>:<table>` for a named one, mirroring\n * the NestJS TypeORM convention. The name comes from the table as the DATABASE knows it, not from\n * the key it has in your schema object — the two differ whenever a table is declared as\n * `users: sqliteTable(\"app_users\", ...)`.\n *\n * @throws {OrmConfigurationError} when `entity` is null, undefined, or carries no resolvable\n * Drizzle name. Deriving a token from an unnameable entity would register the repository under a\n * token nothing could ask for.\n */\nexport function getRepositoryToken(entity: unknown, dataSourceName: string = DEFAULT_DS): string {\n const entityName = resolveEntityName(entity);\n return dataSourceName === DEFAULT_DS\n ? `REPO:${entityName}`\n : `REPO:${dataSourceName}:${entityName}`;\n}\n","import { Inject } from \"@theokit/di\";\nimport { getRepositoryToken } from \"./tokens.js\";\n\n/**\n * Inject the {@link Repository} for one table.\n *\n * Shorthand for `@Inject(getRepositoryToken(entity, dataSourceName))` — the repository must have\n * been registered by {@link OrmModule.forFeature} for the same data source, or resolution fails\n * with `TokenNotFoundError` naming the token.\n *\n * @param entity a Drizzle table object\n * @param dataSourceName the data source this table belongs to; omit for the default one\n * @throws {OrmConfigurationError} at decoration time when `entity` is not a Drizzle table — the\n * token is derived from the table's name, so an unnameable entity cannot produce one.\n */\nexport function InjectRepository(entity: unknown, dataSourceName?: string): ParameterDecorator {\n return Inject(getRepositoryToken(entity, dataSourceName));\n}\n","import type { AnyTable, DataSource, OrmRootOptions } from \"../types.js\";\n\nexport function createDataSource<TSchema extends Record<string, AnyTable>>(\n opts: OrmRootOptions<TSchema>,\n): DataSource<TSchema> {\n const name = opts.dataSourceName ?? \"default\";\n return {\n name,\n dialect: opts.dialect,\n schema: opts.schema,\n db: opts.db,\n };\n}\n","import { getTableColumns } from \"drizzle-orm\";\nimport { getAgentContext } from \"../als-context.js\";\n\nconst TRACKED_COLS = [\"agentId\", \"runId\", \"conversationId\"] as const;\n\nconst warnedTables = new WeakSet<object>();\n\nfunction getTableColumnNames(table: unknown): string[] {\n if (table === null || typeof table !== \"object\") return [];\n try {\n return Object.keys(getTableColumns(table as Parameters<typeof getTableColumns>[0]));\n } catch {\n return [];\n }\n}\n\nexport function fillAgentColumns<T extends Record<string, unknown>>(table: unknown, row: T): T {\n const columns = getTableColumnNames(table);\n const hasAnyTrackedCol = TRACKED_COLS.some((c) => columns.includes(c));\n if (!hasAnyTrackedCol) return row;\n\n const ctx = getAgentContext();\n if (!ctx) {\n if (\n process.env.NODE_ENV !== \"production\" &&\n typeof table === \"object\" &&\n table !== null &&\n !warnedTables.has(table)\n ) {\n warnedTables.add(table);\n console.warn(\n `[@theokit/orm] Table has agentId/runId/conversationId column(s) but no AgentContext set. Wrap calls with withAgentContext({...}, () => ...) to auto-fill.`,\n );\n }\n return row;\n }\n\n const filled: Record<string, unknown> = { ...row };\n for (const col of TRACKED_COLS) {\n if (columns.includes(col) && filled[col] === undefined && ctx[col] !== undefined) {\n filled[col] = ctx[col];\n }\n }\n return filled as T;\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\n\nconst txAls = new AsyncLocalStorage<unknown>();\n\nexport function withTxContext<R>(tx: unknown, fn: () => R | Promise<R>): Promise<R> {\n return Promise.resolve(txAls.run(tx, fn));\n}\n\nexport function getTxContext(): unknown | undefined {\n return txAls.getStore();\n}\n","import type { Column, InferInsertModel, InferSelectModel, SQL, Table } from \"drizzle-orm\";\nimport { eq, getTableColumns } from \"drizzle-orm\";\nimport { OrmConfigurationError, OrmValidationError } from \"./errors.js\";\nimport { fillAgentColumns } from \"./internal/agent-column-filler.js\";\nimport { getTxContext } from \"./internal/tx-context.js\";\n\ninterface DrizzleColumnMeta {\n primary?: boolean;\n isPrimaryKey?: boolean;\n primaryKey?: boolean;\n name?: string;\n}\n\nfunction resolveTableName(table: unknown): string {\n if (table === null || typeof table !== \"object\") return \"<unknown>\";\n const sym = (table as Record<symbol, unknown>)[Symbol.for(\"drizzle:Name\")];\n if (typeof sym === \"string\") return sym;\n const inner = (table as { _?: { name?: string } })._;\n return inner?.name ?? \"<unknown>\";\n}\n\nfunction detectPrimaryKey(table: Table): { name: string; column: Column } {\n const columns = getTableColumns(table) as Record<string, Column>;\n const tableName = resolveTableName(table);\n for (const [colName, col] of Object.entries(columns)) {\n const meta = col as unknown as DrizzleColumnMeta;\n if (meta.primary === true || meta.isPrimaryKey === true || meta.primaryKey === true) {\n return { name: colName, column: col };\n }\n }\n if (\"id\" in columns) {\n return { name: \"id\", column: columns.id as Column };\n }\n throw new OrmConfigurationError(\n `Entity \"${tableName}\" has no primary key. v0.1 requires a single-column PK named \"id\" or marked .primaryKey(). Use repo.query() for composite/custom keys.`,\n );\n}\n\nfunction assertValidId(method: string, id: unknown): asserts id is string | number {\n if (id === undefined || id === null) {\n throw new OrmValidationError(\n `Repository.${method}: id is required and non-null (received ${id === null ? \"null\" : \"undefined\"}).`,\n );\n }\n if (typeof id === \"string\" && id.length === 0) {\n throw new OrmValidationError(\n `Repository.${method}: id is required and non-empty (received empty string).`,\n );\n }\n if (typeof id !== \"string\" && typeof id !== \"number\") {\n throw new OrmValidationError(\n `Repository.${method}: id must be string or number (received ${typeof id}).`,\n );\n }\n}\n\ninterface DialectAwareDb {\n insert: (table: unknown) => {\n values: (v: unknown) => {\n returning?: () => Promise<unknown[]>;\n run?: () => unknown;\n get?: () => unknown;\n };\n };\n update: (table: unknown) => {\n set: (v: unknown) => {\n where: (w: unknown) => {\n returning?: () => Promise<unknown[]>;\n run?: () => unknown;\n };\n };\n };\n delete: (table: unknown) => {\n where: (w: unknown) => Promise<unknown> | { run?: () => unknown };\n };\n select: () => { from: (table: unknown) => unknown };\n}\n\n/**\n * CRUD over one Drizzle table, with the six methods most application code needs.\n *\n * Resolve one per table with {@link InjectRepository}, or build one directly with\n * {@link createRepository} when you want no container at all. Anything the six methods do not cover\n * is what `query()` is for: it hands back the Drizzle builder, so an arbitrary query stays possible\n * without this class growing a second query language.\n *\n * Two guards are deliberate. The constructor refuses a table with no primary key, because every\n * other method addresses rows by it. And `findById`, `update` and `delete` refuse an id that is\n * null, empty or not a string or number — a `DELETE` whose `WHERE` never matched anything usable\n * looks exactly like one that matched every row, and only afterwards.\n *\n * When an agent context is active (see {@link withAgentContext}) and the table declares the\n * matching columns, `insert` and `update` fill them in.\n */\nexport class Repository<T extends Table> {\n private readonly pkColumn: Column;\n private readonly pkName: string;\n private readonly tableName: string;\n\n constructor(\n private readonly defaultDb: unknown,\n private readonly table: T,\n ) {\n const pk = detectPrimaryKey(table);\n this.pkColumn = pk.column;\n this.pkName = pk.name;\n this.tableName = resolveTableName(table);\n }\n\n private get db(): DialectAwareDb {\n const tx = getTxContext();\n return (tx ?? this.defaultDb) as DialectAwareDb;\n }\n\n async findById(id: string | number): Promise<InferSelectModel<T> | null> {\n assertValidId(\"findById\", id);\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle generic chain — fluent query builder types are too complex to narrow at call site without importing internal Drizzle types\n const rows = (await (this.db.select().from(this.table) as any)\n .where(eq(this.pkColumn, id))\n .limit(1)) as unknown[];\n return (rows[0] as InferSelectModel<T>) ?? null;\n }\n\n async findMany(where?: SQL): Promise<InferSelectModel<T>[]> {\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle generic chain — fluent query builder types are too complex to narrow at call site without importing internal Drizzle types\n const q = this.db.select().from(this.table) as any;\n const rows = (where ? await q.where(where) : await q) as unknown[];\n return rows as InferSelectModel<T>[];\n }\n\n async insert(values: InferInsertModel<T>): Promise<InferSelectModel<T>> {\n const filled = fillAgentColumns(this.table, values as Record<string, unknown>);\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle generic chain — fluent query builder types are too complex to narrow at call site without importing internal Drizzle types\n const op = this.db.insert(this.table).values(filled) as any;\n if (typeof op.returning === \"function\") {\n const rows = (await op.returning()) as unknown[];\n const row = rows[0];\n if (row === undefined) {\n throw new OrmValidationError(\n `Repository.insert on \"${this.tableName}\" returned zero rows. Driver may not support .returning() (MySQL?). Use repo.query() with manual fetch for that dialect.`,\n );\n }\n return row as InferSelectModel<T>;\n }\n throw new OrmConfigurationError(\n `Repository.insert on \"${this.tableName}\": driver does not expose .returning(). v0.1 supports SQLite/Postgres. For MySQL, use repo.query() and manually fetch the inserted row.`,\n );\n }\n\n async update(\n id: string | number,\n patch: Partial<InferInsertModel<T>>,\n ): Promise<InferSelectModel<T>> {\n assertValidId(\"update\", id);\n const filled = fillAgentColumns(this.table, patch as Record<string, unknown>);\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle generic chain — fluent query builder types are too complex to narrow at call site without importing internal Drizzle types\n const op = this.db.update(this.table).set(filled).where(eq(this.pkColumn, id)) as any;\n if (typeof op.returning === \"function\") {\n const rows = (await op.returning()) as unknown[];\n const row = rows[0];\n if (row === undefined) {\n throw new OrmValidationError(\n `Repository.update on \"${this.tableName}\" id=\"${id}\": no row matched.`,\n );\n }\n return row as InferSelectModel<T>;\n }\n throw new OrmConfigurationError(\n `Repository.update on \"${this.tableName}\": driver does not expose .returning(). v0.1 supports SQLite/Postgres. For MySQL, use repo.query() and manually fetch.`,\n );\n }\n\n async delete(id: string | number): Promise<void> {\n assertValidId(\"delete\", id);\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle generic chain — fluent query builder types are too complex to narrow at call site without importing internal Drizzle types\n await (this.db.delete(this.table) as any).where(eq(this.pkColumn, id));\n }\n\n query() {\n return this.db.select().from(this.table);\n }\n\n /** @internal exposed for tests */\n get _primaryKeyName(): string {\n return this.pkName;\n }\n}\n\n/**\n * Non-DI factory for {@link Repository}. The `Repository` constructor is\n * already DI-free (`new Repository(db, table)`); this factory makes the non-DI\n * path explicit and discoverable, so consumers do NOT need `@theokit/di`,\n * decorators, or `reflect-metadata` for plain CRUD — only `@Transactional`\n * requires a bound DataSource. Works with any drizzle `db` (incl. better-sqlite3,\n * whose query builders are awaitable).\n *\n * @public\n */\nexport function createRepository<T extends Table>(db: unknown, table: T): Repository<T> {\n return new Repository(db, table);\n}\n","import type { Table } from \"drizzle-orm\";\n\n/** Any Drizzle table. The alias exists so this package's signatures name the domain concept\n * rather than repeating a dependency's type everywhere a table is accepted. */\nexport type AnyTable = Table;\n\n/**\n * The SQL dialect a data source speaks.\n *\n * It is carried rather than inferred because behaviour genuinely differs by dialect: `@Transactional`\n * refuses an `isolationLevel` on `sqlite`, which has transaction *behaviours* and no isolation level\n * to set, and accepting one there would drop it silently.\n */\nexport type Dialect = \"sqlite\" | \"pg\" | \"mysql\";\n\n/**\n * What {@link OrmModule.forRoot} needs to build a data source.\n *\n * `db` is the Drizzle handle you already built — this package never opens a connection of its own,\n * so pooling, credentials and migrations stay where you configured them. `dataSourceName` names\n * this source when an application has more than one; omit it and it is `\"default\"`.\n */\nexport interface OrmRootOptions<\n TSchema extends Record<string, AnyTable> = Record<string, AnyTable>,\n> {\n schema: TSchema;\n dialect: Dialect;\n db: unknown;\n dataSourceName?: string;\n}\n\n/**\n * A configured database handle plus the schema and dialect it belongs to.\n *\n * Resolve it from the container with {@link ORM_DATA_SOURCE_TOKEN} when you need the raw Drizzle\n * handle — running a query no repository covers, or binding it for `@Transactional`.\n */\nexport interface DataSource<TSchema extends Record<string, AnyTable> = Record<string, AnyTable>> {\n readonly name: string;\n readonly dialect: Dialect;\n readonly schema: TSchema;\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle db handle has driver-specific shape (BetterSQLite3Database vs PgDatabase vs MySqlDatabase); narrow types come at use-site via Repository<T> generic\n readonly db: any;\n}\n\n/**\n * Container token for the default {@link DataSource}.\n *\n * Inject it with `@Inject(ORM_DATA_SOURCE_TOKEN)`. A named data source is registered under its own\n * token, so this one resolves the source registered without a `dataSourceName`.\n */\nexport const ORM_DATA_SOURCE_TOKEN = \"ORM_DATA_SOURCE\";\n\n/**\n * Who is acting, for the duration of one async chain.\n *\n * Repositories copy these into agent-aware columns on insert and update when the table declares\n * them, so a row records which agent and which run produced it without the call sites passing ids\n * down. Established with {@link withAgentContext}; every field is optional because a partial\n * context is more useful than none.\n */\nexport interface AgentContext {\n agentId?: string;\n runId?: string;\n conversationId?: string;\n}\n","import type { Provider } from \"@theokit/di\";\nimport { OrmConfigurationError } from \"./errors.js\";\nimport { createDataSource } from \"./internal/data-source.js\";\nimport { Repository } from \"./repository.js\";\nimport { getRepositoryToken } from \"./tokens.js\";\nimport {\n type AnyTable,\n type DataSource,\n ORM_DATA_SOURCE_TOKEN,\n type OrmRootOptions,\n} from \"./types.js\";\n\nconst registeredDataSources = new Set<string>();\n\nfunction dataSourceTokenFor(name: string): string {\n return name === \"default\" ? ORM_DATA_SOURCE_TOKEN : `${ORM_DATA_SOURCE_TOKEN}:${name}`;\n}\n\nfunction entityArrayOrThrow(entities: unknown): readonly unknown[] {\n if (!Array.isArray(entities)) {\n throw new OrmConfigurationError(\n `OrmModule.forFeature: entities must be an array of Drizzle tables. Got ${typeof entities}`,\n );\n }\n if (entities.length === 0) {\n throw new OrmConfigurationError(\n \"OrmModule.forFeature: entities array is empty. Provide at least one Drizzle table.\",\n );\n }\n return entities;\n}\n\n/**\n * Provider builders that put a data source and its repositories into a container.\n *\n * Two calls, in this order: `forRoot` once per database, `forFeature` once per group of tables. The\n * split is what lets a feature module declare the tables it needs without repeating the connection\n * settings, and `forFeature` refuses outright when `forRoot` has not run for its data source —\n * otherwise the failure would surface as a missing token at the first query, far from its cause.\n */\nexport const OrmModule = {\n forRoot<TSchema extends Record<string, AnyTable>>(opts: OrmRootOptions<TSchema>): Provider[] {\n if (opts === null || typeof opts !== \"object\") {\n throw new OrmConfigurationError(\n \"OrmModule.forRoot: options is required. Pass { schema, dialect, db }.\",\n );\n }\n if (opts.db === undefined || opts.db === null) {\n throw new OrmConfigurationError(\n \"OrmModule.forRoot: opts.db is required. Pass the Drizzle db instance (e.g. drizzle(client, { schema })).\",\n );\n }\n if (![\"sqlite\", \"pg\", \"mysql\"].includes(opts.dialect)) {\n throw new OrmConfigurationError(\n `OrmModule.forRoot: opts.dialect must be one of \"sqlite\" | \"pg\" | \"mysql\". Got \"${opts.dialect}\".`,\n );\n }\n const name = opts.dataSourceName ?? \"default\";\n const dataSource = createDataSource(opts);\n const token = dataSourceTokenFor(name);\n\n registeredDataSources.add(name);\n\n return [\n {\n provide: token,\n useValue: dataSource,\n },\n ];\n },\n\n forFeature(entities: readonly unknown[], dataSourceName: string = \"default\"): Provider[] {\n const ents = entityArrayOrThrow(entities);\n\n if (!registeredDataSources.has(dataSourceName)) {\n throw new OrmConfigurationError(\n `OrmModule.forFeature called${\n dataSourceName === \"default\" ? \"\" : ` for dataSource=\"${dataSourceName}\"`\n } before OrmModule.forRoot. Call OrmModule.forRoot(opts) first in your Container providers array.`,\n );\n }\n\n const dsToken = dataSourceTokenFor(dataSourceName);\n\n return ents.map((entity) => ({\n provide: getRepositoryToken(entity, dataSourceName),\n inject: [dsToken],\n useFactory: (ds: DataSource) => new Repository(ds.db, entity as AnyTable),\n }));\n },\n\n /** @internal — testing escape hatch to reset module-level state */\n _resetForTesting(): void {\n registeredDataSources.clear();\n },\n};\n","import { OrmConfigurationError } from \"./errors.js\";\nimport { withTxContext } from \"./internal/tx-context.js\";\nimport type { DataSource } from \"./types.js\";\n\nconst DATA_SOURCE_KEY = Symbol.for(\"Theo:orm:dataSource\");\n\n/**\n * Attach a {@link DataSource} to an instance so its `@Transactional` methods can find one.\n *\n * `@Transactional` is a method decorator: it runs at class-definition time and has no\n * container to ask, so the DataSource has to be put on the instance before the method is\n * called. Nothing does that for you — not `OrmModule`, not the container.\n *\n * With the container, inject the DataSource and bind it in a `@PostConstruct` hook, which\n * runs after construction with every dependency already in place:\n *\n * @example\n * ```ts\n * @Injectable()\n * class TransferService {\n * constructor(@Inject(ORM_DATA_SOURCE_TOKEN) private readonly ds: DataSource) {}\n *\n * @PostConstruct\n * bindTransactions() {\n * bindDataSourceToInstance(this, this.ds);\n * }\n *\n * @Transactional()\n * async transfer() { ... }\n * }\n * ```\n *\n * Without the container, call it directly on the instance before invoking the method.\n */\nexport function bindDataSourceToInstance(instance: object, ds: DataSource): void {\n (instance as Record<symbol, unknown>)[DATA_SOURCE_KEY] = ds;\n}\n\nfunction readDataSourceFromInstance(instance: object): DataSource | undefined {\n const v = (instance as Record<symbol, unknown>)[DATA_SOURCE_KEY];\n return (v as DataSource | undefined) ?? undefined;\n}\n\n/** Options for {@link Transactional}. */\nexport interface TransactionalOptions {\n /**\n * Isolation level for the transaction, passed straight to the driver.\n *\n * Rejected on `sqlite`, which has no per-transaction isolation level to set — see\n * the note in {@link Transactional}.\n */\n isolationLevel?: \"read uncommitted\" | \"read committed\" | \"repeatable read\" | \"serializable\";\n}\n\n/**\n * Dialects that accept an isolation level on `db.transaction(cb, config)`.\n *\n * SQLite is deliberately absent. Its transactions take a `behavior` (deferred, immediate,\n * exclusive), not an isolation level, so a level passed there would be dropped on the\n * floor — and a silently ignored isolation level is the kind of thing that looks fine in\n * review and corrupts data under load.\n */\nconst DIALECTS_WITH_ISOLATION_LEVEL: ReadonlySet<DataSource[\"dialect\"]> = new Set([\"pg\", \"mysql\"]);\n\n/**\n * `@Transactional(options?)` — run a method inside a database transaction.\n *\n * The wrapped method executes within `db.transaction(...)`, and the transaction handle is\n * published on the async context so `getTxContext()` inside the call returns it. The\n * method's resolved value is returned; anything it throws rolls the transaction back.\n *\n * The instance must carry a DataSource before the method runs — see\n * {@link bindDataSourceToInstance}, which is the only thing that puts one there.\n */\nexport function Transactional(opts: TransactionalOptions = {}): MethodDecorator {\n return function transactionalDecorator(\n _target: object,\n propertyKey: string | symbol,\n descriptor: PropertyDescriptor,\n ): PropertyDescriptor {\n const original = descriptor.value;\n if (typeof original !== \"function\") {\n throw new OrmConfigurationError(\n `@Transactional on ${String(propertyKey)}: target is not a method.`,\n );\n }\n\n descriptor.value = async function transactionalWrapper(\n this: object,\n ...args: unknown[]\n ): Promise<unknown> {\n const transaction = resolveTransactionFn(this, propertyKey, opts);\n\n const run = (tx: unknown): Promise<unknown> =>\n withTxContext(tx, () => original.apply(this, args));\n\n // Only pass a config when one was asked for: drivers differ on what an empty\n // config object means, and the no-options case must stay byte-identical to before.\n return opts.isolationLevel === undefined\n ? transaction(run)\n : transaction(run, { isolationLevel: opts.isolationLevel });\n };\n\n return descriptor;\n };\n}\n\ntype TransactionFn = (cb: (tx: unknown) => Promise<unknown>, config?: unknown) => Promise<unknown>;\n\n/**\n * Everything that has to be true before a transaction can start, checked in one place so\n * the wrapper above stays readable: an instance carries a DataSource, the dialect can\n * honour the requested isolation level, and the driver exposes `transaction()`.\n */\nfunction resolveTransactionFn(\n instance: object,\n propertyKey: string | symbol,\n opts: TransactionalOptions,\n): TransactionFn {\n const where = `@Transactional ${String(propertyKey)}`;\n\n const ds = readDataSourceFromInstance(instance);\n if (!ds) {\n throw new OrmConfigurationError(\n `${where}: no DataSource bound to instance. ` +\n `Call bindDataSourceToInstance(this, dataSource) before invoking the method — ` +\n `from a @PostConstruct hook when the class is container-managed, or directly ` +\n `after construction when it is not.`,\n );\n }\n\n if (opts.isolationLevel !== undefined && !DIALECTS_WITH_ISOLATION_LEVEL.has(ds.dialect)) {\n throw new OrmConfigurationError(\n `${where}: isolationLevel \"${opts.isolationLevel}\" is not supported on ${ds.dialect}. ` +\n `Remove the option, or use a dialect that has isolation levels (pg, mysql).`,\n );\n }\n\n const db = ds.db as { transaction?: TransactionFn };\n if (typeof db.transaction !== \"function\") {\n throw new OrmConfigurationError(\n `${where}: DataSource.db does not expose .transaction(). ` +\n `Ensure you passed a Drizzle db instance.`,\n );\n }\n\n return db.transaction.bind(db);\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -1,45 +1,148 @@
1
1
  import { Table, InferSelectModel, SQL, InferInsertModel } from 'drizzle-orm';
2
2
  import { Provider } from '@theokit/di';
3
3
 
4
+ /** Any Drizzle table. The alias exists so this package's signatures name the domain concept
5
+ * rather than repeating a dependency's type everywhere a table is accepted. */
4
6
  type AnyTable = Table;
7
+ /**
8
+ * The SQL dialect a data source speaks.
9
+ *
10
+ * It is carried rather than inferred because behaviour genuinely differs by dialect: `@Transactional`
11
+ * refuses an `isolationLevel` on `sqlite`, which has transaction *behaviours* and no isolation level
12
+ * to set, and accepting one there would drop it silently.
13
+ */
5
14
  type Dialect = "sqlite" | "pg" | "mysql";
15
+ /**
16
+ * What {@link OrmModule.forRoot} needs to build a data source.
17
+ *
18
+ * `db` is the Drizzle handle you already built — this package never opens a connection of its own,
19
+ * so pooling, credentials and migrations stay where you configured them. `dataSourceName` names
20
+ * this source when an application has more than one; omit it and it is `"default"`.
21
+ */
6
22
  interface OrmRootOptions<TSchema extends Record<string, AnyTable> = Record<string, AnyTable>> {
7
23
  schema: TSchema;
8
24
  dialect: Dialect;
9
25
  db: unknown;
10
26
  dataSourceName?: string;
11
27
  }
28
+ /**
29
+ * A configured database handle plus the schema and dialect it belongs to.
30
+ *
31
+ * Resolve it from the container with {@link ORM_DATA_SOURCE_TOKEN} when you need the raw Drizzle
32
+ * handle — running a query no repository covers, or binding it for `@Transactional`.
33
+ */
12
34
  interface DataSource<TSchema extends Record<string, AnyTable> = Record<string, AnyTable>> {
13
35
  readonly name: string;
14
36
  readonly dialect: Dialect;
15
37
  readonly schema: TSchema;
16
38
  readonly db: any;
17
39
  }
40
+ /**
41
+ * Container token for the default {@link DataSource}.
42
+ *
43
+ * Inject it with `@Inject(ORM_DATA_SOURCE_TOKEN)`. A named data source is registered under its own
44
+ * token, so this one resolves the source registered without a `dataSourceName`.
45
+ */
18
46
  declare const ORM_DATA_SOURCE_TOKEN = "ORM_DATA_SOURCE";
47
+ /**
48
+ * Who is acting, for the duration of one async chain.
49
+ *
50
+ * Repositories copy these into agent-aware columns on insert and update when the table declares
51
+ * them, so a row records which agent and which run produced it without the call sites passing ids
52
+ * down. Established with {@link withAgentContext}; every field is optional because a partial
53
+ * context is more useful than none.
54
+ */
19
55
  interface AgentContext {
20
56
  agentId?: string;
21
57
  runId?: string;
22
58
  conversationId?: string;
23
59
  }
24
60
 
61
+ /**
62
+ * Run `fn` with an agent context attached, so repositories can stamp agent-aware columns without
63
+ * the caller threading the ids through every function in between.
64
+ *
65
+ * The context follows the async chain rather than the call stack, so it survives every `await`
66
+ * inside `fn`. It does NOT survive an escape from that chain: a bare `setTimeout` or `setImmediate`
67
+ * inside `fn` starts a new chain and sees no context. Wrap the whole unit of work, not a fragment
68
+ * of it.
69
+ *
70
+ * @returns whatever `fn` returns, always as a Promise, so a synchronous and an asynchronous `fn`
71
+ * are called the same way.
72
+ */
25
73
  declare function withAgentContext<R>(ctx: AgentContext, fn: () => R | Promise<R>): Promise<R>;
74
+ /**
75
+ * The agent context of the current async chain, or `undefined` outside {@link withAgentContext}.
76
+ *
77
+ * `undefined` is a normal answer, not an error: a repository writing agent-aware columns leaves
78
+ * them unset rather than refusing the write, because plain application code has no agent to name.
79
+ */
26
80
  declare function getAgentContext(): AgentContext | undefined;
27
81
 
82
+ /**
83
+ * Base class for every error this package raises.
84
+ *
85
+ * Catch this to handle anything from `@theokit/orm` without naming each subclass, and catch a
86
+ * subclass when the response differs: a configuration fault needs a deploy, a validation fault
87
+ * needs a different call.
88
+ */
28
89
  declare class OrmError extends Error {
29
90
  readonly name: string;
30
91
  }
92
+ /**
93
+ * The wiring is wrong, and no input will make the call succeed.
94
+ *
95
+ * Raised when an entity has no primary key, when `forFeature` runs before `forRoot` for its data
96
+ * source, when `@Transactional` finds no DataSource bound to the instance, or when the handle
97
+ * passed as `db` does not expose `transaction()`. Every case is a mistake in setup rather than in
98
+ * the data, so it fails at the earliest point that can see it rather than at the first query.
99
+ */
31
100
  declare class OrmConfigurationError extends OrmError {
32
101
  readonly name = "OrmConfigurationError";
33
102
  }
103
+ /**
104
+ * A caller-supplied value was rejected at the boundary.
105
+ *
106
+ * The id guards are the reason this exists: `findById`, `update` and `delete` refuse a null, empty
107
+ * or non-scalar id rather than passing it to Drizzle, because a `DELETE` whose `WHERE` matched
108
+ * nothing usable is indistinguishable from one that matched everything until the rows are gone.
109
+ */
34
110
  declare class OrmValidationError extends OrmError {
35
111
  readonly name = "OrmValidationError";
36
112
  }
113
+ /**
114
+ * A table could not be expressed as JSON Schema.
115
+ *
116
+ * Raised by {@link exportSchema} for a column whose type has no mapping. It fails rather than
117
+ * skipping the column: a consumer generating a model in another language would get one missing a
118
+ * field and find out at the first insert.
119
+ */
37
120
  declare class OrmSchemaExportError extends OrmError {
38
121
  readonly name = "OrmSchemaExportError";
39
122
  }
40
123
 
124
+ /**
125
+ * Inject the {@link Repository} for one table.
126
+ *
127
+ * Shorthand for `@Inject(getRepositoryToken(entity, dataSourceName))` — the repository must have
128
+ * been registered by {@link OrmModule.forFeature} for the same data source, or resolution fails
129
+ * with `TokenNotFoundError` naming the token.
130
+ *
131
+ * @param entity a Drizzle table object
132
+ * @param dataSourceName the data source this table belongs to; omit for the default one
133
+ * @throws {OrmConfigurationError} at decoration time when `entity` is not a Drizzle table — the
134
+ * token is derived from the table's name, so an unnameable entity cannot produce one.
135
+ */
41
136
  declare function InjectRepository(entity: unknown, dataSourceName?: string): ParameterDecorator;
42
137
 
138
+ /**
139
+ * Provider builders that put a data source and its repositories into a container.
140
+ *
141
+ * Two calls, in this order: `forRoot` once per database, `forFeature` once per group of tables. The
142
+ * split is what lets a feature module declare the tables it needs without repeating the connection
143
+ * settings, and `forFeature` refuses outright when `forRoot` has not run for its data source —
144
+ * otherwise the failure would surface as a missing token at the first query, far from its cause.
145
+ */
43
146
  declare const OrmModule: {
44
147
  forRoot<TSchema extends Record<string, AnyTable>>(opts: OrmRootOptions<TSchema>): Provider[];
45
148
  forFeature(entities: readonly unknown[], dataSourceName?: string): Provider[];
@@ -47,6 +150,22 @@ declare const OrmModule: {
47
150
  _resetForTesting(): void;
48
151
  };
49
152
 
153
+ /**
154
+ * CRUD over one Drizzle table, with the six methods most application code needs.
155
+ *
156
+ * Resolve one per table with {@link InjectRepository}, or build one directly with
157
+ * {@link createRepository} when you want no container at all. Anything the six methods do not cover
158
+ * is what `query()` is for: it hands back the Drizzle builder, so an arbitrary query stays possible
159
+ * without this class growing a second query language.
160
+ *
161
+ * Two guards are deliberate. The constructor refuses a table with no primary key, because every
162
+ * other method addresses rows by it. And `findById`, `update` and `delete` refuse an id that is
163
+ * null, empty or not a string or number — a `DELETE` whose `WHERE` never matched anything usable
164
+ * looks exactly like one that matched every row, and only afterwards.
165
+ *
166
+ * When an agent context is active (see {@link withAgentContext}) and the table declares the
167
+ * matching columns, `insert` and `update` fill them in.
168
+ */
50
169
  declare class Repository<T extends Table> {
51
170
  private readonly defaultDb;
52
171
  private readonly table;
@@ -63,7 +182,7 @@ declare class Repository<T extends Table> {
63
182
  query(): unknown;
64
183
  }
65
184
  /**
66
- * M7-7 — non-DI factory for {@link Repository}. The `Repository` constructor is
185
+ * Non-DI factory for {@link Repository}. The `Repository` constructor is
67
186
  * already DI-free (`new Repository(db, table)`); this factory makes the non-DI
68
187
  * path explicit and discoverable, so consumers do NOT need `@theokit/di`,
69
188
  * decorators, or `reflect-metadata` for plain CRUD — only `@Transactional`
@@ -74,11 +193,69 @@ declare class Repository<T extends Table> {
74
193
  */
75
194
  declare function createRepository<T extends Table>(db: unknown, table: T): Repository<T>;
76
195
 
196
+ /**
197
+ * The container token under which one table's {@link Repository} is registered.
198
+ *
199
+ * `REPO:<table>` for the default data source and `REPO:<source>:<table>` for a named one, mirroring
200
+ * the NestJS TypeORM convention. The name comes from the table as the DATABASE knows it, not from
201
+ * the key it has in your schema object — the two differ whenever a table is declared as
202
+ * `users: sqliteTable("app_users", ...)`.
203
+ *
204
+ * @throws {OrmConfigurationError} when `entity` is null, undefined, or carries no resolvable
205
+ * Drizzle name. Deriving a token from an unnameable entity would register the repository under a
206
+ * token nothing could ask for.
207
+ */
77
208
  declare function getRepositoryToken(entity: unknown, dataSourceName?: string): string;
78
209
 
210
+ /**
211
+ * Attach a {@link DataSource} to an instance so its `@Transactional` methods can find one.
212
+ *
213
+ * `@Transactional` is a method decorator: it runs at class-definition time and has no
214
+ * container to ask, so the DataSource has to be put on the instance before the method is
215
+ * called. Nothing does that for you — not `OrmModule`, not the container.
216
+ *
217
+ * With the container, inject the DataSource and bind it in a `@PostConstruct` hook, which
218
+ * runs after construction with every dependency already in place:
219
+ *
220
+ * @example
221
+ * ```ts
222
+ * @Injectable()
223
+ * class TransferService {
224
+ * constructor(@Inject(ORM_DATA_SOURCE_TOKEN) private readonly ds: DataSource) {}
225
+ *
226
+ * @PostConstruct
227
+ * bindTransactions() {
228
+ * bindDataSourceToInstance(this, this.ds);
229
+ * }
230
+ *
231
+ * @Transactional()
232
+ * async transfer() { ... }
233
+ * }
234
+ * ```
235
+ *
236
+ * Without the container, call it directly on the instance before invoking the method.
237
+ */
238
+ declare function bindDataSourceToInstance(instance: object, ds: DataSource): void;
239
+ /** Options for {@link Transactional}. */
79
240
  interface TransactionalOptions {
241
+ /**
242
+ * Isolation level for the transaction, passed straight to the driver.
243
+ *
244
+ * Rejected on `sqlite`, which has no per-transaction isolation level to set — see
245
+ * the note in {@link Transactional}.
246
+ */
80
247
  isolationLevel?: "read uncommitted" | "read committed" | "repeatable read" | "serializable";
81
248
  }
82
- declare function Transactional(_opts?: TransactionalOptions): MethodDecorator;
249
+ /**
250
+ * `@Transactional(options?)` — run a method inside a database transaction.
251
+ *
252
+ * The wrapped method executes within `db.transaction(...)`, and the transaction handle is
253
+ * published on the async context so `getTxContext()` inside the call returns it. The
254
+ * method's resolved value is returned; anything it throws rolls the transaction back.
255
+ *
256
+ * The instance must carry a DataSource before the method runs — see
257
+ * {@link bindDataSourceToInstance}, which is the only thing that puts one there.
258
+ */
259
+ declare function Transactional(opts?: TransactionalOptions): MethodDecorator;
83
260
 
84
- export { type AgentContext, type AnyTable, type DataSource, type Dialect, InjectRepository, ORM_DATA_SOURCE_TOKEN, OrmConfigurationError, OrmError, OrmModule, type OrmRootOptions, OrmSchemaExportError, OrmValidationError, Repository, Transactional, createRepository, getAgentContext, getRepositoryToken, withAgentContext };
261
+ export { type AgentContext, type AnyTable, type DataSource, type Dialect, InjectRepository, ORM_DATA_SOURCE_TOKEN, OrmConfigurationError, OrmError, OrmModule, type OrmRootOptions, OrmSchemaExportError, OrmValidationError, Repository, Transactional, type TransactionalOptions, bindDataSourceToInstance, createRepository, getAgentContext, getRepositoryToken, withAgentContext };