@pattern-stack/codegen 0.7.8 → 0.8.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 +54 -0
- package/dist/runtime/base-classes/activity-entity-repository.js +98 -17
- package/dist/runtime/base-classes/activity-entity-repository.js.map +1 -1
- package/dist/runtime/base-classes/base-repository.d.ts +47 -3
- package/dist/runtime/base-classes/base-repository.js +98 -17
- package/dist/runtime/base-classes/base-repository.js.map +1 -1
- package/dist/runtime/base-classes/index.d.ts +1 -0
- package/dist/runtime/base-classes/index.js +137 -28
- package/dist/runtime/base-classes/index.js.map +1 -1
- package/dist/runtime/base-classes/junction-sync-repository.js +102 -21
- package/dist/runtime/base-classes/junction-sync-repository.js.map +1 -1
- package/dist/runtime/base-classes/knowledge-entity-repository.js +98 -17
- package/dist/runtime/base-classes/knowledge-entity-repository.js.map +1 -1
- package/dist/runtime/base-classes/metadata-entity-repository.js +101 -20
- package/dist/runtime/base-classes/metadata-entity-repository.js.map +1 -1
- package/dist/runtime/base-classes/synced-entity-repository.js +103 -22
- package/dist/runtime/base-classes/synced-entity-repository.js.map +1 -1
- package/dist/runtime/base-classes/tenant-context.d.ts +79 -0
- package/dist/runtime/base-classes/tenant-context.js +46 -0
- package/dist/runtime/base-classes/tenant-context.js.map +1 -0
- package/dist/src/cli/index.js +2 -0
- package/dist/src/cli/index.js.map +1 -1
- package/package.json +1 -1
- package/runtime/base-classes/base-repository.ts +96 -20
- package/runtime/base-classes/index.ts +13 -0
- package/runtime/base-classes/tenant-context.ts +175 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../runtime/base-classes/base-repository.ts","../../../runtime/base-classes/knowledge-entity-repository.ts"],"sourcesContent":["/**\n * BaseRepository<TEntity>\n *\n * Abstract base class providing standard CRUD operations via Drizzle ORM.\n * Every generated repository extends this class.\n *\n * Family-specific bases (CrmEntityRepository, etc.) extend this in v0.1\n * without any changes to BaseRepository.\n *\n * NOT @Injectable — concrete repositories are @Injectable and inject DRIZZLE.\n */\nimport { eq, inArray, isNull, sql } from 'drizzle-orm';\nimport type { PgTableWithColumns, PgColumn } from 'drizzle-orm/pg-core';\nimport type { SQL } from 'drizzle-orm';\nimport type { DrizzleClient, DrizzleTx } from '../types/drizzle';\n\n// ============================================================================\n// Interfaces\n// ============================================================================\n\n/**\n * Behavior flags for the repository. Controls automatic timestamp injection\n * and soft-delete filtering.\n */\nexport interface BehaviorConfig {\n timestamps: boolean;\n softDelete: boolean;\n userTracking: boolean;\n}\n\n/**\n * Options for the list() method.\n */\nexport interface ListOptions {\n where?: SQL;\n limit?: number;\n offset?: number;\n orderBy?: PgColumn | SQL;\n}\n\n// ============================================================================\n// BaseRepository\n// ============================================================================\n\nexport abstract class BaseRepository<TEntity> {\n /**\n * The Drizzle table schema for this entity.\n * Concrete repositories declare this as a class property.\n */\n protected abstract readonly table: PgTableWithColumns<any>; // eslint-disable-line @typescript-eslint/no-explicit-any\n\n /**\n * Behavior flags controlling automatic behavior injection.\n * Override in concrete repositories to enable behaviors.\n */\n protected readonly behaviors: BehaviorConfig = {\n timestamps: false,\n softDelete: false,\n userTracking: false,\n };\n\n protected readonly db: DrizzleClient;\n\n constructor(db: DrizzleClient) {\n this.db = db;\n }\n\n /**\n * Pick the runner for a write: the caller-supplied transaction handle\n * if present, otherwise the repository's own client. Keeps the `tx`\n * parameter purely additive — callers without a transaction call as\n * before. Used by the write methods below + consumer overrides (e.g.\n * the generated `upsertCurrentValues` on EAV value tables).\n */\n protected runner(tx?: DrizzleTx): DrizzleClient {\n return tx ?? this.db;\n }\n\n // ============================================================================\n // Read Operations\n // ============================================================================\n\n /**\n * Find a single entity by its primary key.\n * Returns null if not found (or soft-deleted when softDelete=true).\n */\n async findById(id: string): Promise<TEntity | null> {\n const rows = await this.baseQuery()\n .where(eq(this.table['id'], id))\n .limit(1);\n return (rows[0] as TEntity) ?? null;\n }\n\n /**\n * Find multiple entities by their primary keys.\n * Returns empty array immediately for empty input (avoids DB errors).\n */\n async findByIds(ids: string[]): Promise<TEntity[]> {\n if (ids.length === 0) return [];\n const rows = await this.baseQuery().where(inArray(this.table['id'], ids));\n return rows as TEntity[];\n }\n\n /**\n * List entities with optional filtering, pagination, and ordering.\n */\n async list(options?: ListOptions): Promise<TEntity[]> {\n let query = this.baseQuery();\n\n if (options?.where) {\n query = query.where(options.where) as typeof query;\n }\n if (options?.orderBy) {\n query = query.orderBy(options.orderBy as SQL) as typeof query;\n }\n if (options?.limit !== undefined) {\n query = query.limit(options.limit) as typeof query;\n }\n if (options?.offset !== undefined) {\n query = query.offset(options.offset) as typeof query;\n }\n\n const rows = await query;\n return rows as TEntity[];\n }\n\n /**\n * Count entities matching an optional WHERE clause.\n * Soft-deleted rows are always excluded when softDelete=true.\n */\n async count(where?: SQL): Promise<number> {\n let query = this.db\n .select({ count: sql<number>`cast(count(*) as integer)` })\n .from(this.table);\n\n const conditions: SQL[] = [];\n if (this.behaviors.softDelete) {\n conditions.push(isNull(this.table['deletedAt']));\n }\n if (where) {\n conditions.push(where);\n }\n\n if (conditions.length === 1) {\n query = query.where(conditions[0]) as typeof query;\n } else if (conditions.length > 1) {\n // Combine with AND by building the condition inline\n const { and } = await import('drizzle-orm');\n query = query.where(and(...conditions)) as typeof query;\n }\n\n const rows = await query;\n return rows[0]?.count ?? 0;\n }\n\n /**\n * Check whether an entity with the given id exists.\n */\n async exists(id: string): Promise<boolean> {\n const result = await this.findById(id);\n return result !== null;\n }\n\n // ============================================================================\n // Write Operations\n // ============================================================================\n\n /**\n * Insert a new entity. Timestamps are auto-injected when timestamps=true.\n */\n async create(input: Partial<TEntity>, tx?: DrizzleTx): Promise<TEntity> {\n const data = this.withTimestamps(input as Record<string, unknown>, 'create');\n const rows = await this.runner(tx)\n .insert(this.table)\n .values(data as any) // eslint-disable-line @typescript-eslint/no-explicit-any\n .returning();\n return rows[0] as TEntity;\n }\n\n /**\n * Update an existing entity by id. updatedAt is auto-injected when timestamps=true.\n * Returns the updated entity.\n */\n async update(id: string, input: Partial<TEntity>, tx?: DrizzleTx): Promise<TEntity> {\n const data = this.withTimestamps(input as Record<string, unknown>, 'update');\n const rows = await this.runner(tx)\n .update(this.table)\n .set(data as any) // eslint-disable-line @typescript-eslint/no-explicit-any\n .where(eq(this.table['id'], id))\n .returning();\n return rows[0] as TEntity;\n }\n\n /**\n * Delete an entity by id.\n * - softDelete=true: sets deletedAt to current timestamp\n * - softDelete=false: hard-deletes the row\n */\n async delete(id: string, tx?: DrizzleTx): Promise<void> {\n const runner = this.runner(tx);\n if (this.behaviors.softDelete) {\n await runner\n .update(this.table)\n .set({ deletedAt: new Date() } as any) // eslint-disable-line @typescript-eslint/no-explicit-any\n .where(eq(this.table['id'], id));\n } else {\n await runner\n .delete(this.table)\n .where(eq(this.table['id'], id));\n }\n }\n\n /**\n * Insert or update multiple entities.\n * Default naive implementation — family repositories override with\n * proper conflict-target upsert (e.g., CrmEntityRepository).\n */\n async upsertMany(inputs: Array<Partial<TEntity>>, tx?: DrizzleTx): Promise<TEntity[]> {\n return Promise.all(inputs.map((input) => this.create(input, tx)));\n }\n\n // ============================================================================\n // Protected Helpers\n // ============================================================================\n\n /**\n * Base SELECT query that automatically excludes soft-deleted rows\n * when softDelete behavior is enabled.\n */\n protected baseQuery() {\n const query = this.db.select().from(this.table).$dynamic();\n if (this.behaviors.softDelete) {\n return query.where(isNull(this.table['deletedAt']));\n }\n return query;\n }\n\n /**\n * Merge timestamp fields into an input object.\n * - mode='create': adds createdAt and updatedAt\n * - mode='update': adds updatedAt only\n *\n * No-op when timestamps behavior is disabled.\n */\n protected withTimestamps(\n input: Record<string, unknown>,\n mode: 'create' | 'update',\n ): Record<string, unknown> {\n if (!this.behaviors.timestamps) return input;\n const now = new Date();\n if (mode === 'create') {\n return { ...input, createdAt: now, updatedAt: now };\n }\n return { ...input, updatedAt: now };\n }\n\n /**\n * Build a WHERE clause fragment that restricts results to rows whose\n * parent (identified by a belongs_to FK) is not soft-deleted.\n *\n * Use this in custom repository methods when you need \"rows reachable\n * from an active parent\". The default findAll / findById behavior is\n * NOT changed by this helper — opt in explicitly where needed.\n *\n * ADR-021 — Soft-delete cascade: Option A (filter at query time).\n * `on_delete` FK rules do not fire for soft-deletes; use this helper\n * instead of expecting cascade semantics on the DB level.\n *\n * Example:\n * async listActiveMessages(): Promise<Message[]> {\n * return this.list({\n * where: this.activeParentFilter(conversations, this.table['conversationId']),\n * });\n * }\n *\n * @param parentTable The Drizzle table object for the parent entity.\n * @param parentFkColumn The FK column on this (child) table that references parent.id.\n */\n protected activeParentFilter(\n parentTable: PgTableWithColumns<any>, // eslint-disable-line @typescript-eslint/no-explicit-any\n parentFkColumn: PgColumn,\n ): SQL {\n return sql`EXISTS (\n SELECT 1 FROM ${parentTable} p\n WHERE p.id = ${parentFkColumn}\n AND p.deleted_at IS NULL\n )`;\n }\n}\n","/**\n * KnowledgeEntityRepository<TEntity>\n *\n * Stub for the knowledge family (requires pgvector — parked for now).\n * Concrete repos extend this when pgvector is available.\n */\nimport { BaseRepository } from './base-repository';\n\nexport abstract class KnowledgeEntityRepository<TEntity> extends BaseRepository<TEntity> {\n // pgvector-dependent methods will be added when the extension is available:\n // semanticSearch, findPendingByOpportunityId, updateStatus, updateStatusBatch\n}\n"],"mappings":";AAWA,SAAS,IAAI,SAAS,QAAQ,WAAW;AAiClC,IAAe,iBAAf,MAAuC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWzB,YAA4B;AAAA,IAC7C,YAAY;AAAA,IACZ,YAAY;AAAA,IACZ,cAAc;AAAA,EAChB;AAAA,EAEmB;AAAA,EAEnB,YAAY,IAAmB;AAC7B,SAAK,KAAK;AAAA,EACZ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASU,OAAO,IAA+B;AAC9C,WAAO,MAAM,KAAK;AAAA,EACpB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,MAAM,SAAS,IAA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,EAAE,CAAC;AAAA,IACnC;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,WAAW,QAAiC,IAAoC;AACpF,WAAO,QAAQ,IAAI,OAAO,IAAI,CAAC,UAAU,KAAK,OAAO,OAAO,EAAE,CAAC,CAAC;AAAA,EAClE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUU,YAAY;AACpB,UAAM,QAAQ,KAAK,GAAG,OAAO,EAAE,KAAK,KAAK,KAAK,EAAE,SAAS;AACzD,QAAI,KAAK,UAAU,YAAY;AAC7B,aAAO,MAAM,MAAM,OAAO,KAAK,MAAM,WAAW,CAAC,CAAC;AAAA,IACpD;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASU,eACR,OACA,MACyB;AACzB,QAAI,CAAC,KAAK,UAAU,WAAY,QAAO;AACvC,UAAM,MAAM,oBAAI,KAAK;AACrB,QAAI,SAAS,UAAU;AACrB,aAAO,EAAE,GAAG,OAAO,WAAW,KAAK,WAAW,IAAI;AAAA,IACpD;AACA,WAAO,EAAE,GAAG,OAAO,WAAW,IAAI;AAAA,EACpC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAwBU,mBACR,aACA,gBACK;AACL,WAAO;AAAA,sBACW,WAAW;AAAA,qBACZ,cAAc;AAAA;AAAA;AAAA,EAGjC;AACF;;;ACxRO,IAAe,4BAAf,cAA0D,eAAwB;AAAA;AAAA;AAGzF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../runtime/base-classes/base-repository.ts","../../../runtime/base-classes/tenant-context.ts","../../../runtime/base-classes/knowledge-entity-repository.ts"],"sourcesContent":["/**\n * BaseRepository<TEntity>\n *\n * Abstract base class providing standard CRUD operations via Drizzle ORM.\n * Every generated repository extends this class.\n *\n * Family-specific bases (CrmEntityRepository, etc.) extend this in v0.1\n * without any changes to BaseRepository.\n *\n * NOT @Injectable — concrete repositories are @Injectable and inject DRIZZLE.\n */\nimport { and, eq, inArray, isNull, sql } from 'drizzle-orm';\nimport type { PgTableWithColumns, PgColumn } from 'drizzle-orm/pg-core';\nimport type { SQL } from 'drizzle-orm';\nimport type { DrizzleClient, DrizzleTx } from '../types/drizzle';\nimport {\n requireRequester,\n tryGetRequester,\n type RequesterScope,\n} from './tenant-context';\n\n// ============================================================================\n// Interfaces\n// ============================================================================\n\n/**\n * Behavior flags for the repository. Controls automatic timestamp injection\n * and soft-delete filtering.\n */\nexport interface BehaviorConfig {\n timestamps: boolean;\n softDelete: boolean;\n userTracking: boolean;\n}\n\n/**\n * Options for the list() method.\n */\nexport interface ListOptions {\n where?: SQL;\n limit?: number;\n offset?: number;\n orderBy?: PgColumn | SQL;\n}\n\n// ============================================================================\n// BaseRepository\n// ============================================================================\n\nexport abstract class BaseRepository<TEntity> {\n /**\n * The Drizzle table schema for this entity.\n * Concrete repositories declare this as a class property.\n */\n protected abstract readonly table: PgTableWithColumns<any>; // eslint-disable-line @typescript-eslint/no-explicit-any\n\n /**\n * Behavior flags controlling automatic behavior injection.\n * Override in concrete repositories to enable behaviors.\n */\n protected readonly behaviors: BehaviorConfig = {\n timestamps: false,\n softDelete: false,\n userTracking: false,\n };\n\n /**\n * Ambient tenant-scope enforcement for `userTracking` repos (see\n * `scopePredicate`). Only has effect when `behaviors.userTracking === true`.\n *\n * - `'lenient'` (default): when no ambient requester context is active,\n * reads/writes are NOT scoped — preserves pre-scoping behavior, so adopting\n * ambient scoping is additive. Scoping kicks in automatically once a\n * boundary installs `withRequester(...)`.\n * - `'strict'`: a missing ambient context throws (`requireRequester`),\n * making a forgotten boundary fail loud instead of silently returning\n * cross-tenant rows. Recommended for new multi-tenant consumers — override\n * in a concrete repo or a family base class.\n */\n protected readonly scopeEnforcement: 'lenient' | 'strict' = 'lenient';\n\n protected readonly db: DrizzleClient;\n\n constructor(db: DrizzleClient) {\n this.db = db;\n }\n\n /**\n * Pick the runner for a write: the caller-supplied transaction handle\n * if present, otherwise the repository's own client. Keeps the `tx`\n * parameter purely additive — callers without a transaction call as\n * before. Used by the write methods below + consumer overrides (e.g.\n * the generated `upsertCurrentValues` on EAV value tables).\n */\n protected runner(tx?: DrizzleTx): DrizzleClient {\n return tx ?? this.db;\n }\n\n // ============================================================================\n // Read Operations\n // ============================================================================\n\n /**\n * Find a single entity by its primary key.\n * Returns null if not found (or soft-deleted when softDelete=true).\n */\n async findById(id: string): Promise<TEntity | null> {\n const rows = await this.baseQuery(eq(this.table['id'], id)).limit(1);\n return (rows[0] as TEntity) ?? null;\n }\n\n /**\n * Find multiple entities by their primary keys.\n * Returns empty array immediately for empty input (avoids DB errors).\n */\n async findByIds(ids: string[]): Promise<TEntity[]> {\n if (ids.length === 0) return [];\n const rows = await this.baseQuery(inArray(this.table['id'], ids));\n return rows as TEntity[];\n }\n\n /**\n * List entities with optional filtering, pagination, and ordering.\n */\n async list(options?: ListOptions): Promise<TEntity[]> {\n let query = this.baseQuery(options?.where);\n\n if (options?.orderBy) {\n query = query.orderBy(options.orderBy as SQL) as typeof query;\n }\n if (options?.limit !== undefined) {\n query = query.limit(options.limit) as typeof query;\n }\n if (options?.offset !== undefined) {\n query = query.offset(options.offset) as typeof query;\n }\n\n const rows = await query;\n return rows as TEntity[];\n }\n\n /**\n * Count entities matching an optional WHERE clause.\n * Soft-deleted rows are always excluded when softDelete=true.\n */\n async count(where?: SQL): Promise<number> {\n let query = this.db\n .select({ count: sql<number>`cast(count(*) as integer)` })\n .from(this.table);\n\n const conditions: SQL[] = [];\n if (this.behaviors.softDelete) {\n conditions.push(isNull(this.table['deletedAt']));\n }\n const scope = this.scopePredicate();\n if (scope) {\n conditions.push(scope);\n }\n if (where) {\n conditions.push(where);\n }\n\n if (conditions.length === 1) {\n query = query.where(conditions[0]) as typeof query;\n } else if (conditions.length > 1) {\n query = query.where(and(...conditions)) as typeof query;\n }\n\n const rows = await query;\n return rows[0]?.count ?? 0;\n }\n\n /**\n * Check whether an entity with the given id exists.\n */\n async exists(id: string): Promise<boolean> {\n const result = await this.findById(id);\n return result !== null;\n }\n\n // ============================================================================\n // Write Operations\n // ============================================================================\n\n /**\n * Insert a new entity. Timestamps are auto-injected when timestamps=true.\n */\n async create(input: Partial<TEntity>, tx?: DrizzleTx): Promise<TEntity> {\n const data = this.withTimestamps(input as Record<string, unknown>, 'create');\n const rows = await this.runner(tx)\n .insert(this.table)\n .values(data as any) // eslint-disable-line @typescript-eslint/no-explicit-any\n .returning();\n return rows[0] as TEntity;\n }\n\n /**\n * Update an existing entity by id. updatedAt is auto-injected when timestamps=true.\n * Returns the updated entity.\n */\n async update(id: string, input: Partial<TEntity>, tx?: DrizzleTx): Promise<TEntity> {\n const data = this.withTimestamps(input as Record<string, unknown>, 'update');\n const rows = await this.runner(tx)\n .update(this.table)\n .set(data as any) // eslint-disable-line @typescript-eslint/no-explicit-any\n .where(this.scopeAnd(eq(this.table['id'], id)))\n .returning();\n return rows[0] as TEntity;\n }\n\n /**\n * Delete an entity by id.\n * - softDelete=true: sets deletedAt to current timestamp\n * - softDelete=false: hard-deletes the row\n */\n async delete(id: string, tx?: DrizzleTx): Promise<void> {\n const runner = this.runner(tx);\n if (this.behaviors.softDelete) {\n await runner\n .update(this.table)\n .set({ deletedAt: new Date() } as any) // eslint-disable-line @typescript-eslint/no-explicit-any\n .where(this.scopeAnd(eq(this.table['id'], id)));\n } else {\n await runner\n .delete(this.table)\n .where(this.scopeAnd(eq(this.table['id'], id)));\n }\n }\n\n /**\n * Insert or update multiple entities.\n * Default naive implementation — family repositories override with\n * proper conflict-target upsert (e.g., CrmEntityRepository).\n */\n async upsertMany(inputs: Array<Partial<TEntity>>, tx?: DrizzleTx): Promise<TEntity[]> {\n return Promise.all(inputs.map((input) => this.create(input, tx)));\n }\n\n // ============================================================================\n // Protected Helpers\n // ============================================================================\n\n /**\n * Base SELECT query that automatically applies the ambient guards —\n * soft-delete exclusion (when `softDelete`) and tenant scope (when\n * `userTracking` + an active requester context) — combined with an optional\n * caller `extra` predicate into a SINGLE `WHERE`.\n *\n * Pass the leaf predicate as `extra` rather than chaining a second\n * `.where(...)`: Drizzle's `.where()` OVERRIDES (does not AND) a prior\n * `.where()` on a `$dynamic()` query, so a chained call would silently drop\n * the soft-delete and scope guards. `baseQuery(extra)` is the safe form.\n */\n protected baseQuery(extra?: SQL) {\n const query = this.db.select().from(this.table).$dynamic();\n const where = this.scopeAnd(extra, { softDelete: this.behaviors.softDelete });\n return where ? query.where(where) : query;\n }\n\n /**\n * Build the ambient tenant-scope predicate for this repo's table.\n *\n * Returns `undefined` (no scoping) when:\n * - `behaviors.userTracking` is false (repo is not user-owned), or\n * - no ambient requester context is active AND `scopeEnforcement` is\n * `'lenient'` (the default — preserves pre-scoping behavior).\n *\n * When a requester context is active, scopes by `user_id` per the ambient\n * scope: `'user'` → `user_id = ctx.userId`; `'org'` → `user_id IN\n * ctx.orgUserIds` (empty list matches nothing — fail-closed); `'superuser'`\n * → no filter. See `tenant-context.ts` for the boundary-install contract.\n */\n protected scopePredicate(): SQL | undefined {\n if (!this.behaviors.userTracking) return undefined;\n const ctx =\n this.scopeEnforcement === 'strict'\n ? requireRequester()\n : tryGetRequester();\n if (!ctx) return undefined;\n const scope: RequesterScope = ctx.scope ?? 'user';\n switch (scope) {\n case 'superuser':\n return undefined;\n case 'org':\n return ctx.orgUserIds && ctx.orgUserIds.length > 0\n ? inArray(this.table['userId'], ctx.orgUserIds as string[])\n : sql`false`;\n case 'user':\n default:\n return eq(this.table['userId'], ctx.userId);\n }\n }\n\n /**\n * Combine the ambient scope predicate (and, optionally, the soft-delete\n * guard) with a caller `extra` predicate into one `SQL`. Returns `undefined`\n * when nothing applies. Used by read + by-id write paths so a single\n * `.where(...)` carries every guard.\n */\n protected scopeAnd(\n extra?: SQL,\n opts?: { softDelete?: boolean },\n ): SQL | undefined {\n const conditions: SQL[] = [];\n if (opts?.softDelete) conditions.push(isNull(this.table['deletedAt']));\n const scope = this.scopePredicate();\n if (scope) conditions.push(scope);\n if (extra) conditions.push(extra);\n if (conditions.length === 0) return undefined;\n if (conditions.length === 1) return conditions[0];\n return and(...conditions);\n }\n\n /**\n * Merge timestamp fields into an input object.\n * - mode='create': adds createdAt and updatedAt\n * - mode='update': adds updatedAt only\n *\n * No-op when timestamps behavior is disabled.\n */\n protected withTimestamps(\n input: Record<string, unknown>,\n mode: 'create' | 'update',\n ): Record<string, unknown> {\n if (!this.behaviors.timestamps) return input;\n const now = new Date();\n if (mode === 'create') {\n return { ...input, createdAt: now, updatedAt: now };\n }\n return { ...input, updatedAt: now };\n }\n\n /**\n * Build a WHERE clause fragment that restricts results to rows whose\n * parent (identified by a belongs_to FK) is not soft-deleted.\n *\n * Use this in custom repository methods when you need \"rows reachable\n * from an active parent\". The default findAll / findById behavior is\n * NOT changed by this helper — opt in explicitly where needed.\n *\n * ADR-021 — Soft-delete cascade: Option A (filter at query time).\n * `on_delete` FK rules do not fire for soft-deletes; use this helper\n * instead of expecting cascade semantics on the DB level.\n *\n * Example:\n * async listActiveMessages(): Promise<Message[]> {\n * return this.list({\n * where: this.activeParentFilter(conversations, this.table['conversationId']),\n * });\n * }\n *\n * @param parentTable The Drizzle table object for the parent entity.\n * @param parentFkColumn The FK column on this (child) table that references parent.id.\n */\n protected activeParentFilter(\n parentTable: PgTableWithColumns<any>, // eslint-disable-line @typescript-eslint/no-explicit-any\n parentFkColumn: PgColumn,\n ): SQL {\n return sql`EXISTS (\n SELECT 1 FROM ${parentTable} p\n WHERE p.id = ${parentFkColumn}\n AND p.deleted_at IS NULL\n )`;\n }\n}\n","/**\n * Ambient requester context — AsyncLocalStorage-backed tenant scope.\n *\n * The alternative to threading `userId`/`organizationId` through every\n * repository/service signature. Set ONCE at each boundary the generated app\n * owns, read implicitly inside `BaseRepository` (see `scopePredicate`).\n *\n * ## Where to set it (boundaries)\n *\n * - HTTP / tRPC handlers — from the authenticated `ctx.user`\n * - OAuth callback controllers — from the authenticated session\n * - Queue/worker `process()` — from the job's owning user after the\n * job's record is loaded\n *\n * Each boundary wraps the rest of the request in `withRequester({ userId,\n * organizationId }, () => ...)`. The context propagates through every `await`\n * to all downstream repo/service calls without being passed explicitly.\n *\n * ## Where to read it\n *\n * - `BaseRepository.scopePredicate()` reads it (via `tryGetRequester` in\n * lenient mode, `requireRequester` in strict mode) and filters every read\n * by the ambient scope when the repo declares `userTracking: true`.\n *\n * ## Why AsyncLocalStorage over an explicit parameter\n *\n * Threading `userId` (and later `organizationId`) through dozens of method\n * signatures is pure parameter pollution. Ambient context also lets a repo\n * make the \"I forgot to scope\" mistake impossible at runtime: in strict mode\n * `requireRequester()` throws when no context is active, surfacing a missing\n * boundary call loudly rather than silently leaking cross-tenant data.\n *\n * ## Not-found semantics\n *\n * When a row exists but belongs to a different requester, scoped reads return\n * `null`/`[]` — identical to \"truly doesn't exist\". No existence oracle;\n * callers throw NotFound uniformly. Standard security practice.\n *\n * ## Testing\n *\n * Tests that exercise scoped repos must wrap the call in `withRequester(...)`.\n * In strict mode an unwrapped call hitting `requireRequester()` throws — by\n * design. In lenient mode (the default) an unwrapped call is simply unscoped.\n */\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\n/**\n * Data-visibility scope. The auth layer decides which scope a request is\n * allowed to claim; the repo trusts whatever the ambient context says.\n *\n * - `'user'`: filter every read by `user_id = ctx.userId`. Default.\n * - `'org'`: filter every read by membership in the requester's org, resolved\n * via `user_id IN (ctx.orgUserIds)` rather than via a per-entity\n * `organization_id` column. Works for every user-owned table and keeps repos\n * single-table — the org member list is pre-resolved at the boundary.\n * - `'superuser'`: no scope filter. Engineering / internal-tools only.\n *\n * AUTHORIZATION (who is allowed to claim each scope) lives in boundary\n * middleware, not in the repo. The repo trusts the ambient context — same\n * trust model as a threaded `userId`.\n */\nexport type RequesterScope = 'user' | 'org' | 'superuser';\n\nexport interface RequesterContext {\n /**\n * The user making the request. Always present — even in `'org'` and\n * `'superuser'` scopes it is the audit-trail \"who actually did this\".\n */\n readonly userId: string;\n /**\n * The organization the requester belongs to. Required when\n * `scope === 'org'`; may be null for `'user'` (users with no org) and for\n * `'superuser'` (cross-org reads).\n */\n readonly organizationId: string | null;\n /**\n * Data-visibility scope. Defaults to `'user'` when omitted.\n */\n readonly scope?: RequesterScope;\n /**\n * For `scope === 'org'`: the list of user IDs in the requester's org,\n * pre-resolved by the boundary middleware that established the `'org'`\n * scope (one `SELECT users.id WHERE organization_id = X` at the trust\n * boundary). Repos use this as a literal `IN (...)` filter — they never\n * JOIN to `users` themselves. Required when `scope === 'org'`.\n */\n readonly orgUserIds?: readonly string[];\n}\n\nconst als = new AsyncLocalStorage<RequesterContext>();\n\n/**\n * Set the ambient requester context for the duration of `fn`. The context\n * propagates through `await` boundaries to all downstream calls. Nesting is\n * fine — an inner `withRequester` overrides the outer for its callback.\n */\nexport function withRequester<T>(\n ctx: RequesterContext,\n fn: () => Promise<T>,\n): Promise<T> {\n return als.run(ctx, fn);\n}\n\n/**\n * Read the ambient requester context. Throws if no context is active — by\n * design. Used by repos in strict scope-enforcement mode; an unwrapped call\n * site is a missing boundary.\n */\nexport function requireRequester(): RequesterContext {\n const ctx = als.getStore();\n if (!ctx) {\n throw new Error(\n 'No requester context active. Wrap the entry point in ' +\n 'withRequester({ userId, organizationId }, fn). See tenant-context.ts.',\n );\n }\n return ctx;\n}\n\n/**\n * Read the ambient requester context without throwing. Returns `undefined`\n * when no context is active. Used by repos in lenient scope-enforcement mode\n * (the default) and by code paths that legitimately run outside a request.\n */\nexport function tryGetRequester(): RequesterContext | undefined {\n return als.getStore();\n}\n\n/**\n * Resolve the effective scope for the ambient context, defaulting to `'user'`.\n */\nexport function requireRequesterScope(): RequesterScope {\n return requireRequester().scope ?? 'user';\n}\n\n/**\n * Convenience helpers for setting scope explicitly. All three preserve\n * `userId` in the context (audit trail) regardless of scope.\n *\n * - `withUserScope`: regular end-user requests. Most call sites.\n * - `withOrgScope`: admin / org-shared resource access. The caller MUST verify\n * the requester's role permits `'org'` before calling — the helper does not\n * enforce authorization. `orgUserIds` is pre-resolved at the boundary.\n * - `withSuperuserScope`: engineering scripts / internal tools. `organizationId`\n * is null (cross-org is the point). Same authorization caveat applies.\n */\nexport function withUserScope<T>(\n userId: string,\n organizationId: string | null,\n fn: () => Promise<T>,\n): Promise<T> {\n return withRequester({ userId, organizationId, scope: 'user' }, fn);\n}\n\nexport function withOrgScope<T>(\n userId: string,\n organizationId: string,\n orgUserIds: readonly string[],\n fn: () => Promise<T>,\n): Promise<T> {\n return withRequester(\n { userId, organizationId, scope: 'org', orgUserIds },\n fn,\n );\n}\n\nexport function withSuperuserScope<T>(\n userId: string,\n fn: () => Promise<T>,\n): Promise<T> {\n return withRequester(\n { userId, organizationId: null, scope: 'superuser' },\n fn,\n );\n}\n","/**\n * KnowledgeEntityRepository<TEntity>\n *\n * Stub for the knowledge family (requires pgvector — parked for now).\n * Concrete repos extend this when pgvector is available.\n */\nimport { BaseRepository } from './base-repository';\n\nexport abstract class KnowledgeEntityRepository<TEntity> extends BaseRepository<TEntity> {\n // pgvector-dependent methods will be added when the extension is available:\n // semanticSearch, findPendingByOpportunityId, updateStatus, updateStatusBatch\n}\n"],"mappings":";AAWA,SAAS,KAAK,IAAI,SAAS,QAAQ,WAAW;;;ACiC9C,SAAS,yBAAyB;AA6ClC,IAAM,MAAM,IAAI,kBAAoC;AAmB7C,SAAS,mBAAqC;AACnD,QAAM,MAAM,IAAI,SAAS;AACzB,MAAI,CAAC,KAAK;AACR,UAAM,IAAI;AAAA,MACR;AAAA,IAEF;AAAA,EACF;AACA,SAAO;AACT;AAOO,SAAS,kBAAgD;AAC9D,SAAO,IAAI,SAAS;AACtB;;;AD7EO,IAAe,iBAAf,MAAuC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWzB,YAA4B;AAAA,IAC7C,YAAY;AAAA,IACZ,YAAY;AAAA,IACZ,cA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|
2
|
-
import { eq as eq2, and, desc } from "drizzle-orm";
|
|
2
|
+
import { eq as eq2, and as and2, desc } from "drizzle-orm";
|
|
3
|
+
|
|
4
|
+
// runtime/base-classes/base-repository.ts
|
|
5
|
+
import { and, eq, inArray, isNull, sql } from "drizzle-orm";
|
|
6
|
+
|
|
7
|
+
// runtime/base-classes/tenant-context.ts
|
|
8
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
9
|
+
var als = new AsyncLocalStorage();
|
|
10
|
+
function requireRequester() {
|
|
11
|
+
const ctx = als.getStore();
|
|
12
|
+
if (!ctx) {
|
|
13
|
+
throw new Error(
|
|
14
|
+
"No requester context active. Wrap the entry point in withRequester({ userId, organizationId }, fn). See tenant-context.ts."
|
|
15
|
+
);
|
|
16
|
+
}
|
|
17
|
+
return ctx;
|
|
18
|
+
}
|
|
19
|
+
function tryGetRequester() {
|
|
20
|
+
return als.getStore();
|
|
21
|
+
}
|
|
3
22
|
|
|
4
23
|
// runtime/base-classes/base-repository.ts
|
|
5
|
-
import { eq, inArray, isNull, sql } from "drizzle-orm";
|
|
6
24
|
var BaseRepository = class {
|
|
7
25
|
// eslint-disable-line @typescript-eslint/no-explicit-any
|
|
8
26
|
/**
|
|
@@ -14,6 +32,20 @@ var BaseRepository = class {
|
|
|
14
32
|
softDelete: false,
|
|
15
33
|
userTracking: false
|
|
16
34
|
};
|
|
35
|
+
/**
|
|
36
|
+
* Ambient tenant-scope enforcement for `userTracking` repos (see
|
|
37
|
+
* `scopePredicate`). Only has effect when `behaviors.userTracking === true`.
|
|
38
|
+
*
|
|
39
|
+
* - `'lenient'` (default): when no ambient requester context is active,
|
|
40
|
+
* reads/writes are NOT scoped — preserves pre-scoping behavior, so adopting
|
|
41
|
+
* ambient scoping is additive. Scoping kicks in automatically once a
|
|
42
|
+
* boundary installs `withRequester(...)`.
|
|
43
|
+
* - `'strict'`: a missing ambient context throws (`requireRequester`),
|
|
44
|
+
* making a forgotten boundary fail loud instead of silently returning
|
|
45
|
+
* cross-tenant rows. Recommended for new multi-tenant consumers — override
|
|
46
|
+
* in a concrete repo or a family base class.
|
|
47
|
+
*/
|
|
48
|
+
scopeEnforcement = "lenient";
|
|
17
49
|
db;
|
|
18
50
|
constructor(db) {
|
|
19
51
|
this.db = db;
|
|
@@ -36,7 +68,7 @@ var BaseRepository = class {
|
|
|
36
68
|
* Returns null if not found (or soft-deleted when softDelete=true).
|
|
37
69
|
*/
|
|
38
70
|
async findById(id) {
|
|
39
|
-
const rows = await this.baseQuery(
|
|
71
|
+
const rows = await this.baseQuery(eq(this.table["id"], id)).limit(1);
|
|
40
72
|
return rows[0] ?? null;
|
|
41
73
|
}
|
|
42
74
|
/**
|
|
@@ -45,17 +77,14 @@ var BaseRepository = class {
|
|
|
45
77
|
*/
|
|
46
78
|
async findByIds(ids) {
|
|
47
79
|
if (ids.length === 0) return [];
|
|
48
|
-
const rows = await this.baseQuery(
|
|
80
|
+
const rows = await this.baseQuery(inArray(this.table["id"], ids));
|
|
49
81
|
return rows;
|
|
50
82
|
}
|
|
51
83
|
/**
|
|
52
84
|
* List entities with optional filtering, pagination, and ordering.
|
|
53
85
|
*/
|
|
54
86
|
async list(options) {
|
|
55
|
-
let query = this.baseQuery();
|
|
56
|
-
if (options?.where) {
|
|
57
|
-
query = query.where(options.where);
|
|
58
|
-
}
|
|
87
|
+
let query = this.baseQuery(options?.where);
|
|
59
88
|
if (options?.orderBy) {
|
|
60
89
|
query = query.orderBy(options.orderBy);
|
|
61
90
|
}
|
|
@@ -78,14 +107,17 @@ var BaseRepository = class {
|
|
|
78
107
|
if (this.behaviors.softDelete) {
|
|
79
108
|
conditions.push(isNull(this.table["deletedAt"]));
|
|
80
109
|
}
|
|
110
|
+
const scope = this.scopePredicate();
|
|
111
|
+
if (scope) {
|
|
112
|
+
conditions.push(scope);
|
|
113
|
+
}
|
|
81
114
|
if (where) {
|
|
82
115
|
conditions.push(where);
|
|
83
116
|
}
|
|
84
117
|
if (conditions.length === 1) {
|
|
85
118
|
query = query.where(conditions[0]);
|
|
86
119
|
} else if (conditions.length > 1) {
|
|
87
|
-
|
|
88
|
-
query = query.where(and2(...conditions));
|
|
120
|
+
query = query.where(and(...conditions));
|
|
89
121
|
}
|
|
90
122
|
const rows = await query;
|
|
91
123
|
return rows[0]?.count ?? 0;
|
|
@@ -114,7 +146,7 @@ var BaseRepository = class {
|
|
|
114
146
|
*/
|
|
115
147
|
async update(id, input, tx) {
|
|
116
148
|
const data = this.withTimestamps(input, "update");
|
|
117
|
-
const rows = await this.runner(tx).update(this.table).set(data).where(eq(this.table["id"], id)).returning();
|
|
149
|
+
const rows = await this.runner(tx).update(this.table).set(data).where(this.scopeAnd(eq(this.table["id"], id))).returning();
|
|
118
150
|
return rows[0];
|
|
119
151
|
}
|
|
120
152
|
/**
|
|
@@ -125,9 +157,9 @@ var BaseRepository = class {
|
|
|
125
157
|
async delete(id, tx) {
|
|
126
158
|
const runner = this.runner(tx);
|
|
127
159
|
if (this.behaviors.softDelete) {
|
|
128
|
-
await runner.update(this.table).set({ deletedAt: /* @__PURE__ */ new Date() }).where(eq(this.table["id"], id));
|
|
160
|
+
await runner.update(this.table).set({ deletedAt: /* @__PURE__ */ new Date() }).where(this.scopeAnd(eq(this.table["id"], id)));
|
|
129
161
|
} else {
|
|
130
|
-
await runner.delete(this.table).where(eq(this.table["id"], id));
|
|
162
|
+
await runner.delete(this.table).where(this.scopeAnd(eq(this.table["id"], id)));
|
|
131
163
|
}
|
|
132
164
|
}
|
|
133
165
|
/**
|
|
@@ -142,15 +174,64 @@ var BaseRepository = class {
|
|
|
142
174
|
// Protected Helpers
|
|
143
175
|
// ============================================================================
|
|
144
176
|
/**
|
|
145
|
-
* Base SELECT query that automatically
|
|
146
|
-
* when softDelete
|
|
177
|
+
* Base SELECT query that automatically applies the ambient guards —
|
|
178
|
+
* soft-delete exclusion (when `softDelete`) and tenant scope (when
|
|
179
|
+
* `userTracking` + an active requester context) — combined with an optional
|
|
180
|
+
* caller `extra` predicate into a SINGLE `WHERE`.
|
|
181
|
+
*
|
|
182
|
+
* Pass the leaf predicate as `extra` rather than chaining a second
|
|
183
|
+
* `.where(...)`: Drizzle's `.where()` OVERRIDES (does not AND) a prior
|
|
184
|
+
* `.where()` on a `$dynamic()` query, so a chained call would silently drop
|
|
185
|
+
* the soft-delete and scope guards. `baseQuery(extra)` is the safe form.
|
|
147
186
|
*/
|
|
148
|
-
baseQuery() {
|
|
187
|
+
baseQuery(extra) {
|
|
149
188
|
const query = this.db.select().from(this.table).$dynamic();
|
|
150
|
-
|
|
151
|
-
|
|
189
|
+
const where = this.scopeAnd(extra, { softDelete: this.behaviors.softDelete });
|
|
190
|
+
return where ? query.where(where) : query;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Build the ambient tenant-scope predicate for this repo's table.
|
|
194
|
+
*
|
|
195
|
+
* Returns `undefined` (no scoping) when:
|
|
196
|
+
* - `behaviors.userTracking` is false (repo is not user-owned), or
|
|
197
|
+
* - no ambient requester context is active AND `scopeEnforcement` is
|
|
198
|
+
* `'lenient'` (the default — preserves pre-scoping behavior).
|
|
199
|
+
*
|
|
200
|
+
* When a requester context is active, scopes by `user_id` per the ambient
|
|
201
|
+
* scope: `'user'` → `user_id = ctx.userId`; `'org'` → `user_id IN
|
|
202
|
+
* ctx.orgUserIds` (empty list matches nothing — fail-closed); `'superuser'`
|
|
203
|
+
* → no filter. See `tenant-context.ts` for the boundary-install contract.
|
|
204
|
+
*/
|
|
205
|
+
scopePredicate() {
|
|
206
|
+
if (!this.behaviors.userTracking) return void 0;
|
|
207
|
+
const ctx = this.scopeEnforcement === "strict" ? requireRequester() : tryGetRequester();
|
|
208
|
+
if (!ctx) return void 0;
|
|
209
|
+
const scope = ctx.scope ?? "user";
|
|
210
|
+
switch (scope) {
|
|
211
|
+
case "superuser":
|
|
212
|
+
return void 0;
|
|
213
|
+
case "org":
|
|
214
|
+
return ctx.orgUserIds && ctx.orgUserIds.length > 0 ? inArray(this.table["userId"], ctx.orgUserIds) : sql`false`;
|
|
215
|
+
case "user":
|
|
216
|
+
default:
|
|
217
|
+
return eq(this.table["userId"], ctx.userId);
|
|
152
218
|
}
|
|
153
|
-
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* Combine the ambient scope predicate (and, optionally, the soft-delete
|
|
222
|
+
* guard) with a caller `extra` predicate into one `SQL`. Returns `undefined`
|
|
223
|
+
* when nothing applies. Used by read + by-id write paths so a single
|
|
224
|
+
* `.where(...)` carries every guard.
|
|
225
|
+
*/
|
|
226
|
+
scopeAnd(extra, opts) {
|
|
227
|
+
const conditions = [];
|
|
228
|
+
if (opts?.softDelete) conditions.push(isNull(this.table["deletedAt"]));
|
|
229
|
+
const scope = this.scopePredicate();
|
|
230
|
+
if (scope) conditions.push(scope);
|
|
231
|
+
if (extra) conditions.push(extra);
|
|
232
|
+
if (conditions.length === 0) return void 0;
|
|
233
|
+
if (conditions.length === 1) return conditions[0];
|
|
234
|
+
return and(...conditions);
|
|
154
235
|
}
|
|
155
236
|
/**
|
|
156
237
|
* Merge timestamp fields into an input object.
|
|
@@ -225,7 +306,7 @@ var MetadataEntityRepository = class extends BaseRepository {
|
|
|
225
306
|
*/
|
|
226
307
|
async findByEntityIdAndType(entityId, entityType) {
|
|
227
308
|
const rows = await this.baseQuery().where(
|
|
228
|
-
|
|
309
|
+
and2(
|
|
229
310
|
eq2(this.table["entityId"], entityId),
|
|
230
311
|
eq2(this.table["entityType"], entityType)
|
|
231
312
|
)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../runtime/base-classes/metadata-entity-repository.ts","../../../runtime/base-classes/base-repository.ts"],"sourcesContent":["/**\n * MetadataEntityRepository<TEntity>\n *\n * Family-specific base for metadata entities (field values, field history, tags).\n * Adds entity-scoped lookups, type filtering, history ordering, and bulk upsert.\n *\n * Concrete repos extend this and declare their table + behaviors.\n */\nimport { eq, and, desc } from 'drizzle-orm';\nimport type { PgTableWithColumns } from 'drizzle-orm/pg-core';\nimport { BaseRepository } from './base-repository';\nimport type { DrizzleTx } from '../types/drizzle';\n\nexport abstract class MetadataEntityRepository<TEntity> extends BaseRepository<TEntity> {\n /**\n * Bulk upsert with a caller-specified conflict target.\n * Uses Drizzle's onConflictDoUpdate to merge records.\n */\n override async upsertMany(\n inputs: Array<Partial<TEntity>>,\n tx?: DrizzleTx,\n options?: { conflictTarget?: keyof PgTableWithColumns<any>['_']['columns'] }, // eslint-disable-line @typescript-eslint/no-explicit-any\n ): Promise<TEntity[]> {\n if (inputs.length === 0) return [];\n const conflictTarget = options?.conflictTarget;\n\n // Fall back to base class naive upsert when no conflict target provided.\n if (!conflictTarget) {\n return super.upsertMany(inputs, tx);\n }\n\n const data = inputs.map((input) =>\n this.withTimestamps(input as Record<string, unknown>, 'create'),\n );\n\n const rows = await this.runner(tx)\n .insert(this.table)\n .values(data as any) // eslint-disable-line @typescript-eslint/no-explicit-any\n .onConflictDoUpdate({\n target: this.table[conflictTarget as string],\n set: data[0] as any, // eslint-disable-line @typescript-eslint/no-explicit-any\n })\n .returning();\n\n return rows as TEntity[];\n }\n\n /**\n * Find metadata by entity ID and entity type (compound lookup).\n */\n async findByEntityIdAndType(entityId: string, entityType: string): Promise<TEntity[]> {\n const rows = await this.baseQuery()\n .where(\n and(\n eq(this.table['entityId'], entityId),\n eq(this.table['entityType'], entityType),\n ),\n );\n return rows as TEntity[];\n }\n\n /**\n * List all metadata records for an entity.\n */\n async listByEntityId(entityId: string): Promise<TEntity[]> {\n const rows = await this.baseQuery()\n .where(eq(this.table['entityId'], entityId));\n return rows as TEntity[];\n }\n\n /**\n * List metadata history for an entity, ordered by validFrom descending.\n */\n async listHistoryByEntityId(entityId: string): Promise<TEntity[]> {\n const rows = await this.baseQuery()\n .where(eq(this.table['entityId'], entityId))\n .orderBy(desc(this.table['validFrom']));\n return rows as TEntity[];\n }\n}\n","/**\n * BaseRepository<TEntity>\n *\n * Abstract base class providing standard CRUD operations via Drizzle ORM.\n * Every generated repository extends this class.\n *\n * Family-specific bases (CrmEntityRepository, etc.) extend this in v0.1\n * without any changes to BaseRepository.\n *\n * NOT @Injectable — concrete repositories are @Injectable and inject DRIZZLE.\n */\nimport { eq, inArray, isNull, sql } from 'drizzle-orm';\nimport type { PgTableWithColumns, PgColumn } from 'drizzle-orm/pg-core';\nimport type { SQL } from 'drizzle-orm';\nimport type { DrizzleClient, DrizzleTx } from '../types/drizzle';\n\n// ============================================================================\n// Interfaces\n// ============================================================================\n\n/**\n * Behavior flags for the repository. Controls automatic timestamp injection\n * and soft-delete filtering.\n */\nexport interface BehaviorConfig {\n timestamps: boolean;\n softDelete: boolean;\n userTracking: boolean;\n}\n\n/**\n * Options for the list() method.\n */\nexport interface ListOptions {\n where?: SQL;\n limit?: number;\n offset?: number;\n orderBy?: PgColumn | SQL;\n}\n\n// ============================================================================\n// BaseRepository\n// ============================================================================\n\nexport abstract class BaseRepository<TEntity> {\n /**\n * The Drizzle table schema for this entity.\n * Concrete repositories declare this as a class property.\n */\n protected abstract readonly table: PgTableWithColumns<any>; // eslint-disable-line @typescript-eslint/no-explicit-any\n\n /**\n * Behavior flags controlling automatic behavior injection.\n * Override in concrete repositories to enable behaviors.\n */\n protected readonly behaviors: BehaviorConfig = {\n timestamps: false,\n softDelete: false,\n userTracking: false,\n };\n\n protected readonly db: DrizzleClient;\n\n constructor(db: DrizzleClient) {\n this.db = db;\n }\n\n /**\n * Pick the runner for a write: the caller-supplied transaction handle\n * if present, otherwise the repository's own client. Keeps the `tx`\n * parameter purely additive — callers without a transaction call as\n * before. Used by the write methods below + consumer overrides (e.g.\n * the generated `upsertCurrentValues` on EAV value tables).\n */\n protected runner(tx?: DrizzleTx): DrizzleClient {\n return tx ?? this.db;\n }\n\n // ============================================================================\n // Read Operations\n // ============================================================================\n\n /**\n * Find a single entity by its primary key.\n * Returns null if not found (or soft-deleted when softDelete=true).\n */\n async findById(id: string): Promise<TEntity | null> {\n const rows = await this.baseQuery()\n .where(eq(this.table['id'], id))\n .limit(1);\n return (rows[0] as TEntity) ?? null;\n }\n\n /**\n * Find multiple entities by their primary keys.\n * Returns empty array immediately for empty input (avoids DB errors).\n */\n async findByIds(ids: string[]): Promise<TEntity[]> {\n if (ids.length === 0) return [];\n const rows = await this.baseQuery().where(inArray(this.table['id'], ids));\n return rows as TEntity[];\n }\n\n /**\n * List entities with optional filtering, pagination, and ordering.\n */\n async list(options?: ListOptions): Promise<TEntity[]> {\n let query = this.baseQuery();\n\n if (options?.where) {\n query = query.where(options.where) as typeof query;\n }\n if (options?.orderBy) {\n query = query.orderBy(options.orderBy as SQL) as typeof query;\n }\n if (options?.limit !== undefined) {\n query = query.limit(options.limit) as typeof query;\n }\n if (options?.offset !== undefined) {\n query = query.offset(options.offset) as typeof query;\n }\n\n const rows = await query;\n return rows as TEntity[];\n }\n\n /**\n * Count entities matching an optional WHERE clause.\n * Soft-deleted rows are always excluded when softDelete=true.\n */\n async count(where?: SQL): Promise<number> {\n let query = this.db\n .select({ count: sql<number>`cast(count(*) as integer)` })\n .from(this.table);\n\n const conditions: SQL[] = [];\n if (this.behaviors.softDelete) {\n conditions.push(isNull(this.table['deletedAt']));\n }\n if (where) {\n conditions.push(where);\n }\n\n if (conditions.length === 1) {\n query = query.where(conditions[0]) as typeof query;\n } else if (conditions.length > 1) {\n // Combine with AND by building the condition inline\n const { and } = await import('drizzle-orm');\n query = query.where(and(...conditions)) as typeof query;\n }\n\n const rows = await query;\n return rows[0]?.count ?? 0;\n }\n\n /**\n * Check whether an entity with the given id exists.\n */\n async exists(id: string): Promise<boolean> {\n const result = await this.findById(id);\n return result !== null;\n }\n\n // ============================================================================\n // Write Operations\n // ============================================================================\n\n /**\n * Insert a new entity. Timestamps are auto-injected when timestamps=true.\n */\n async create(input: Partial<TEntity>, tx?: DrizzleTx): Promise<TEntity> {\n const data = this.withTimestamps(input as Record<string, unknown>, 'create');\n const rows = await this.runner(tx)\n .insert(this.table)\n .values(data as any) // eslint-disable-line @typescript-eslint/no-explicit-any\n .returning();\n return rows[0] as TEntity;\n }\n\n /**\n * Update an existing entity by id. updatedAt is auto-injected when timestamps=true.\n * Returns the updated entity.\n */\n async update(id: string, input: Partial<TEntity>, tx?: DrizzleTx): Promise<TEntity> {\n const data = this.withTimestamps(input as Record<string, unknown>, 'update');\n const rows = await this.runner(tx)\n .update(this.table)\n .set(data as any) // eslint-disable-line @typescript-eslint/no-explicit-any\n .where(eq(this.table['id'], id))\n .returning();\n return rows[0] as TEntity;\n }\n\n /**\n * Delete an entity by id.\n * - softDelete=true: sets deletedAt to current timestamp\n * - softDelete=false: hard-deletes the row\n */\n async delete(id: string, tx?: DrizzleTx): Promise<void> {\n const runner = this.runner(tx);\n if (this.behaviors.softDelete) {\n await runner\n .update(this.table)\n .set({ deletedAt: new Date() } as any) // eslint-disable-line @typescript-eslint/no-explicit-any\n .where(eq(this.table['id'], id));\n } else {\n await runner\n .delete(this.table)\n .where(eq(this.table['id'], id));\n }\n }\n\n /**\n * Insert or update multiple entities.\n * Default naive implementation — family repositories override with\n * proper conflict-target upsert (e.g., CrmEntityRepository).\n */\n async upsertMany(inputs: Array<Partial<TEntity>>, tx?: DrizzleTx): Promise<TEntity[]> {\n return Promise.all(inputs.map((input) => this.create(input, tx)));\n }\n\n // ============================================================================\n // Protected Helpers\n // ============================================================================\n\n /**\n * Base SELECT query that automatically excludes soft-deleted rows\n * when softDelete behavior is enabled.\n */\n protected baseQuery() {\n const query = this.db.select().from(this.table).$dynamic();\n if (this.behaviors.softDelete) {\n return query.where(isNull(this.table['deletedAt']));\n }\n return query;\n }\n\n /**\n * Merge timestamp fields into an input object.\n * - mode='create': adds createdAt and updatedAt\n * - mode='update': adds updatedAt only\n *\n * No-op when timestamps behavior is disabled.\n */\n protected withTimestamps(\n input: Record<string, unknown>,\n mode: 'create' | 'update',\n ): Record<string, unknown> {\n if (!this.behaviors.timestamps) return input;\n const now = new Date();\n if (mode === 'create') {\n return { ...input, createdAt: now, updatedAt: now };\n }\n return { ...input, updatedAt: now };\n }\n\n /**\n * Build a WHERE clause fragment that restricts results to rows whose\n * parent (identified by a belongs_to FK) is not soft-deleted.\n *\n * Use this in custom repository methods when you need \"rows reachable\n * from an active parent\". The default findAll / findById behavior is\n * NOT changed by this helper — opt in explicitly where needed.\n *\n * ADR-021 — Soft-delete cascade: Option A (filter at query time).\n * `on_delete` FK rules do not fire for soft-deletes; use this helper\n * instead of expecting cascade semantics on the DB level.\n *\n * Example:\n * async listActiveMessages(): Promise<Message[]> {\n * return this.list({\n * where: this.activeParentFilter(conversations, this.table['conversationId']),\n * });\n * }\n *\n * @param parentTable The Drizzle table object for the parent entity.\n * @param parentFkColumn The FK column on this (child) table that references parent.id.\n */\n protected activeParentFilter(\n parentTable: PgTableWithColumns<any>, // eslint-disable-line @typescript-eslint/no-explicit-any\n parentFkColumn: PgColumn,\n ): SQL {\n return sql`EXISTS (\n SELECT 1 FROM ${parentTable} p\n WHERE p.id = ${parentFkColumn}\n AND p.deleted_at IS NULL\n )`;\n }\n}\n"],"mappings":";AAQA,SAAS,MAAAA,KAAI,KAAK,YAAY;;;ACG9B,SAAS,IAAI,SAAS,QAAQ,WAAW;AAiClC,IAAe,iBAAf,MAAuC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWzB,YAA4B;AAAA,IAC7C,YAAY;AAAA,IACZ,YAAY;AAAA,IACZ,cAAc;AAAA,EAChB;AAAA,EAEmB;AAAA,EAEnB,YAAY,IAAmB;AAC7B,SAAK,KAAK;AAAA,EACZ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASU,OAAO,IAA+B;AAC9C,WAAO,MAAM,KAAK;AAAA,EACpB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,MAAM,SAAS,IAAqC;AAClD,UAAM,OAAO,MAAM,KAAK,UAAU,EAC/B,MAAM,GAAG,KAAK,MAAM,IAAI,GAAG,EAAE,CAAC,EAC9B,MAAM,CAAC;AACV,WAAQ,KAAK,CAAC,KA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C9B,OAAO,KAAK,KAAK,EACjB,OAAO,IAAW,EAClB,mBAAmB;AAAA,MAClB,QAAQ,KAAK,MAAM,cAAwB;AAAA,MAC3C,KAAK,KAAK,CAAC;AAAA;AAAA,IACb,CAAC,EACA,UAAU;AAEb,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,sBAAsB,UAAkB,YAAwC;AACpF,UAAM,OAAO,MAAM,KAAK,UAAU,EAC/B;AAAA,MACC;AAAA,QACEC,IAAG,KAAK,MAAM,UAAU,GAAG,QAAQ;AAAA,QACnCA,IAAG,KAAK,MAAM,YAAY,GAAG,UAAU;AAAA,MACzC;AAAA,IACF;AACF,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,eAAe,UAAsC;AACzD,UAAM,OAAO,MAAM,KAAK,UAAU,EAC/B,MAAMA,IAAG,KAAK,MAAM,UAAU,GAAG,QAAQ,CAAC;AAC7C,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,sBAAsB,UAAsC;AAChE,UAAM,OAAO,MAAM,KAAK,UAAU,EAC/B,MAAMA,IAAG,KAAK,MAAM,UAAU,GAAG,QAAQ,CAAC,EAC1C,QAAQ,KAAK,KAAK,MAAM,WAAW,CAAC,CAAC;AACxC,WAAO;AAAA,EACT;AACF;","names":["eq","and","eq"]}
|
|
1
|
+
{"version":3,"sources":["../../../runtime/base-classes/metadata-entity-repository.ts","../../../runtime/base-classes/base-repository.ts","../../../runtime/base-classes/tenant-context.ts"],"sourcesContent":["/**\n * MetadataEntityRepository<TEntity>\n *\n * Family-specific base for metadata entities (field values, field history, tags).\n * Adds entity-scoped lookups, type filtering, history ordering, and bulk upsert.\n *\n * Concrete repos extend this and declare their table + behaviors.\n */\nimport { eq, and, desc } from 'drizzle-orm';\nimport type { PgTableWithColumns } from 'drizzle-orm/pg-core';\nimport { BaseRepository } from './base-repository';\nimport type { DrizzleTx } from '../types/drizzle';\n\nexport abstract class MetadataEntityRepository<TEntity> extends BaseRepository<TEntity> {\n /**\n * Bulk upsert with a caller-specified conflict target.\n * Uses Drizzle's onConflictDoUpdate to merge records.\n */\n override async upsertMany(\n inputs: Array<Partial<TEntity>>,\n tx?: DrizzleTx,\n options?: { conflictTarget?: keyof PgTableWithColumns<any>['_']['columns'] }, // eslint-disable-line @typescript-eslint/no-explicit-any\n ): Promise<TEntity[]> {\n if (inputs.length === 0) return [];\n const conflictTarget = options?.conflictTarget;\n\n // Fall back to base class naive upsert when no conflict target provided.\n if (!conflictTarget) {\n return super.upsertMany(inputs, tx);\n }\n\n const data = inputs.map((input) =>\n this.withTimestamps(input as Record<string, unknown>, 'create'),\n );\n\n const rows = await this.runner(tx)\n .insert(this.table)\n .values(data as any) // eslint-disable-line @typescript-eslint/no-explicit-any\n .onConflictDoUpdate({\n target: this.table[conflictTarget as string],\n set: data[0] as any, // eslint-disable-line @typescript-eslint/no-explicit-any\n })\n .returning();\n\n return rows as TEntity[];\n }\n\n /**\n * Find metadata by entity ID and entity type (compound lookup).\n */\n async findByEntityIdAndType(entityId: string, entityType: string): Promise<TEntity[]> {\n const rows = await this.baseQuery()\n .where(\n and(\n eq(this.table['entityId'], entityId),\n eq(this.table['entityType'], entityType),\n ),\n );\n return rows as TEntity[];\n }\n\n /**\n * List all metadata records for an entity.\n */\n async listByEntityId(entityId: string): Promise<TEntity[]> {\n const rows = await this.baseQuery()\n .where(eq(this.table['entityId'], entityId));\n return rows as TEntity[];\n }\n\n /**\n * List metadata history for an entity, ordered by validFrom descending.\n */\n async listHistoryByEntityId(entityId: string): Promise<TEntity[]> {\n const rows = await this.baseQuery()\n .where(eq(this.table['entityId'], entityId))\n .orderBy(desc(this.table['validFrom']));\n return rows as TEntity[];\n }\n}\n","/**\n * BaseRepository<TEntity>\n *\n * Abstract base class providing standard CRUD operations via Drizzle ORM.\n * Every generated repository extends this class.\n *\n * Family-specific bases (CrmEntityRepository, etc.) extend this in v0.1\n * without any changes to BaseRepository.\n *\n * NOT @Injectable — concrete repositories are @Injectable and inject DRIZZLE.\n */\nimport { and, eq, inArray, isNull, sql } from 'drizzle-orm';\nimport type { PgTableWithColumns, PgColumn } from 'drizzle-orm/pg-core';\nimport type { SQL } from 'drizzle-orm';\nimport type { DrizzleClient, DrizzleTx } from '../types/drizzle';\nimport {\n requireRequester,\n tryGetRequester,\n type RequesterScope,\n} from './tenant-context';\n\n// ============================================================================\n// Interfaces\n// ============================================================================\n\n/**\n * Behavior flags for the repository. Controls automatic timestamp injection\n * and soft-delete filtering.\n */\nexport interface BehaviorConfig {\n timestamps: boolean;\n softDelete: boolean;\n userTracking: boolean;\n}\n\n/**\n * Options for the list() method.\n */\nexport interface ListOptions {\n where?: SQL;\n limit?: number;\n offset?: number;\n orderBy?: PgColumn | SQL;\n}\n\n// ============================================================================\n// BaseRepository\n// ============================================================================\n\nexport abstract class BaseRepository<TEntity> {\n /**\n * The Drizzle table schema for this entity.\n * Concrete repositories declare this as a class property.\n */\n protected abstract readonly table: PgTableWithColumns<any>; // eslint-disable-line @typescript-eslint/no-explicit-any\n\n /**\n * Behavior flags controlling automatic behavior injection.\n * Override in concrete repositories to enable behaviors.\n */\n protected readonly behaviors: BehaviorConfig = {\n timestamps: false,\n softDelete: false,\n userTracking: false,\n };\n\n /**\n * Ambient tenant-scope enforcement for `userTracking` repos (see\n * `scopePredicate`). Only has effect when `behaviors.userTracking === true`.\n *\n * - `'lenient'` (default): when no ambient requester context is active,\n * reads/writes are NOT scoped — preserves pre-scoping behavior, so adopting\n * ambient scoping is additive. Scoping kicks in automatically once a\n * boundary installs `withRequester(...)`.\n * - `'strict'`: a missing ambient context throws (`requireRequester`),\n * making a forgotten boundary fail loud instead of silently returning\n * cross-tenant rows. Recommended for new multi-tenant consumers — override\n * in a concrete repo or a family base class.\n */\n protected readonly scopeEnforcement: 'lenient' | 'strict' = 'lenient';\n\n protected readonly db: DrizzleClient;\n\n constructor(db: DrizzleClient) {\n this.db = db;\n }\n\n /**\n * Pick the runner for a write: the caller-supplied transaction handle\n * if present, otherwise the repository's own client. Keeps the `tx`\n * parameter purely additive — callers without a transaction call as\n * before. Used by the write methods below + consumer overrides (e.g.\n * the generated `upsertCurrentValues` on EAV value tables).\n */\n protected runner(tx?: DrizzleTx): DrizzleClient {\n return tx ?? this.db;\n }\n\n // ============================================================================\n // Read Operations\n // ============================================================================\n\n /**\n * Find a single entity by its primary key.\n * Returns null if not found (or soft-deleted when softDelete=true).\n */\n async findById(id: string): Promise<TEntity | null> {\n const rows = await this.baseQuery(eq(this.table['id'], id)).limit(1);\n return (rows[0] as TEntity) ?? null;\n }\n\n /**\n * Find multiple entities by their primary keys.\n * Returns empty array immediately for empty input (avoids DB errors).\n */\n async findByIds(ids: string[]): Promise<TEntity[]> {\n if (ids.length === 0) return [];\n const rows = await this.baseQuery(inArray(this.table['id'], ids));\n return rows as TEntity[];\n }\n\n /**\n * List entities with optional filtering, pagination, and ordering.\n */\n async list(options?: ListOptions): Promise<TEntity[]> {\n let query = this.baseQuery(options?.where);\n\n if (options?.orderBy) {\n query = query.orderBy(options.orderBy as SQL) as typeof query;\n }\n if (options?.limit !== undefined) {\n query = query.limit(options.limit) as typeof query;\n }\n if (options?.offset !== undefined) {\n query = query.offset(options.offset) as typeof query;\n }\n\n const rows = await query;\n return rows as TEntity[];\n }\n\n /**\n * Count entities matching an optional WHERE clause.\n * Soft-deleted rows are always excluded when softDelete=true.\n */\n async count(where?: SQL): Promise<number> {\n let query = this.db\n .select({ count: sql<number>`cast(count(*) as integer)` })\n .from(this.table);\n\n const conditions: SQL[] = [];\n if (this.behaviors.softDelete) {\n conditions.push(isNull(this.table['deletedAt']));\n }\n const scope = this.scopePredicate();\n if (scope) {\n conditions.push(scope);\n }\n if (where) {\n conditions.push(where);\n }\n\n if (conditions.length === 1) {\n query = query.where(conditions[0]) as typeof query;\n } else if (conditions.length > 1) {\n query = query.where(and(...conditions)) as typeof query;\n }\n\n const rows = await query;\n return rows[0]?.count ?? 0;\n }\n\n /**\n * Check whether an entity with the given id exists.\n */\n async exists(id: string): Promise<boolean> {\n const result = await this.findById(id);\n return result !== null;\n }\n\n // ============================================================================\n // Write Operations\n // ============================================================================\n\n /**\n * Insert a new entity. Timestamps are auto-injected when timestamps=true.\n */\n async create(input: Partial<TEntity>, tx?: DrizzleTx): Promise<TEntity> {\n const data = this.withTimestamps(input as Record<string, unknown>, 'create');\n const rows = await this.runner(tx)\n .insert(this.table)\n .values(data as any) // eslint-disable-line @typescript-eslint/no-explicit-any\n .returning();\n return rows[0] as TEntity;\n }\n\n /**\n * Update an existing entity by id. updatedAt is auto-injected when timestamps=true.\n * Returns the updated entity.\n */\n async update(id: string, input: Partial<TEntity>, tx?: DrizzleTx): Promise<TEntity> {\n const data = this.withTimestamps(input as Record<string, unknown>, 'update');\n const rows = await this.runner(tx)\n .update(this.table)\n .set(data as any) // eslint-disable-line @typescript-eslint/no-explicit-any\n .where(this.scopeAnd(eq(this.table['id'], id)))\n .returning();\n return rows[0] as TEntity;\n }\n\n /**\n * Delete an entity by id.\n * - softDelete=true: sets deletedAt to current timestamp\n * - softDelete=false: hard-deletes the row\n */\n async delete(id: string, tx?: DrizzleTx): Promise<void> {\n const runner = this.runner(tx);\n if (this.behaviors.softDelete) {\n await runner\n .update(this.table)\n .set({ deletedAt: new Date() } as any) // eslint-disable-line @typescript-eslint/no-explicit-any\n .where(this.scopeAnd(eq(this.table['id'], id)));\n } else {\n await runner\n .delete(this.table)\n .where(this.scopeAnd(eq(this.table['id'], id)));\n }\n }\n\n /**\n * Insert or update multiple entities.\n * Default naive implementation — family repositories override with\n * proper conflict-target upsert (e.g., CrmEntityRepository).\n */\n async upsertMany(inputs: Array<Partial<TEntity>>, tx?: DrizzleTx): Promise<TEntity[]> {\n return Promise.all(inputs.map((input) => this.create(input, tx)));\n }\n\n // ============================================================================\n // Protected Helpers\n // ============================================================================\n\n /**\n * Base SELECT query that automatically applies the ambient guards —\n * soft-delete exclusion (when `softDelete`) and tenant scope (when\n * `userTracking` + an active requester context) — combined with an optional\n * caller `extra` predicate into a SINGLE `WHERE`.\n *\n * Pass the leaf predicate as `extra` rather than chaining a second\n * `.where(...)`: Drizzle's `.where()` OVERRIDES (does not AND) a prior\n * `.where()` on a `$dynamic()` query, so a chained call would silently drop\n * the soft-delete and scope guards. `baseQuery(extra)` is the safe form.\n */\n protected baseQuery(extra?: SQL) {\n const query = this.db.select().from(this.table).$dynamic();\n const where = this.scopeAnd(extra, { softDelete: this.behaviors.softDelete });\n return where ? query.where(where) : query;\n }\n\n /**\n * Build the ambient tenant-scope predicate for this repo's table.\n *\n * Returns `undefined` (no scoping) when:\n * - `behaviors.userTracking` is false (repo is not user-owned), or\n * - no ambient requester context is active AND `scopeEnforcement` is\n * `'lenient'` (the default — preserves pre-scoping behavior).\n *\n * When a requester context is active, scopes by `user_id` per the ambient\n * scope: `'user'` → `user_id = ctx.userId`; `'org'` → `user_id IN\n * ctx.orgUserIds` (empty list matches nothing — fail-closed); `'superuser'`\n * → no filter. See `tenant-context.ts` for the boundary-install contract.\n */\n protected scopePredicate(): SQL | undefined {\n if (!this.behaviors.userTracking) return undefined;\n const ctx =\n this.scopeEnforcement === 'strict'\n ? requireRequester()\n : tryGetRequester();\n if (!ctx) return undefined;\n const scope: RequesterScope = ctx.scope ?? 'user';\n switch (scope) {\n case 'superuser':\n return undefined;\n case 'org':\n return ctx.orgUserIds && ctx.orgUserIds.length > 0\n ? inArray(this.table['userId'], ctx.orgUserIds as string[])\n : sql`false`;\n case 'user':\n default:\n return eq(this.table['userId'], ctx.userId);\n }\n }\n\n /**\n * Combine the ambient scope predicate (and, optionally, the soft-delete\n * guard) with a caller `extra` predicate into one `SQL`. Returns `undefined`\n * when nothing applies. Used by read + by-id write paths so a single\n * `.where(...)` carries every guard.\n */\n protected scopeAnd(\n extra?: SQL,\n opts?: { softDelete?: boolean },\n ): SQL | undefined {\n const conditions: SQL[] = [];\n if (opts?.softDelete) conditions.push(isNull(this.table['deletedAt']));\n const scope = this.scopePredicate();\n if (scope) conditions.push(scope);\n if (extra) conditions.push(extra);\n if (conditions.length === 0) return undefined;\n if (conditions.length === 1) return conditions[0];\n return and(...conditions);\n }\n\n /**\n * Merge timestamp fields into an input object.\n * - mode='create': adds createdAt and updatedAt\n * - mode='update': adds updatedAt only\n *\n * No-op when timestamps behavior is disabled.\n */\n protected withTimestamps(\n input: Record<string, unknown>,\n mode: 'create' | 'update',\n ): Record<string, unknown> {\n if (!this.behaviors.timestamps) return input;\n const now = new Date();\n if (mode === 'create') {\n return { ...input, createdAt: now, updatedAt: now };\n }\n return { ...input, updatedAt: now };\n }\n\n /**\n * Build a WHERE clause fragment that restricts results to rows whose\n * parent (identified by a belongs_to FK) is not soft-deleted.\n *\n * Use this in custom repository methods when you need \"rows reachable\n * from an active parent\". The default findAll / findById behavior is\n * NOT changed by this helper — opt in explicitly where needed.\n *\n * ADR-021 — Soft-delete cascade: Option A (filter at query time).\n * `on_delete` FK rules do not fire for soft-deletes; use this helper\n * instead of expecting cascade semantics on the DB level.\n *\n * Example:\n * async listActiveMessages(): Promise<Message[]> {\n * return this.list({\n * where: this.activeParentFilter(conversations, this.table['conversationId']),\n * });\n * }\n *\n * @param parentTable The Drizzle table object for the parent entity.\n * @param parentFkColumn The FK column on this (child) table that references parent.id.\n */\n protected activeParentFilter(\n parentTable: PgTableWithColumns<any>, // eslint-disable-line @typescript-eslint/no-explicit-any\n parentFkColumn: PgColumn,\n ): SQL {\n return sql`EXISTS (\n SELECT 1 FROM ${parentTable} p\n WHERE p.id = ${parentFkColumn}\n AND p.deleted_at IS NULL\n )`;\n }\n}\n","/**\n * Ambient requester context — AsyncLocalStorage-backed tenant scope.\n *\n * The alternative to threading `userId`/`organizationId` through every\n * repository/service signature. Set ONCE at each boundary the generated app\n * owns, read implicitly inside `BaseRepository` (see `scopePredicate`).\n *\n * ## Where to set it (boundaries)\n *\n * - HTTP / tRPC handlers — from the authenticated `ctx.user`\n * - OAuth callback controllers — from the authenticated session\n * - Queue/worker `process()` — from the job's owning user after the\n * job's record is loaded\n *\n * Each boundary wraps the rest of the request in `withRequester({ userId,\n * organizationId }, () => ...)`. The context propagates through every `await`\n * to all downstream repo/service calls without being passed explicitly.\n *\n * ## Where to read it\n *\n * - `BaseRepository.scopePredicate()` reads it (via `tryGetRequester` in\n * lenient mode, `requireRequester` in strict mode) and filters every read\n * by the ambient scope when the repo declares `userTracking: true`.\n *\n * ## Why AsyncLocalStorage over an explicit parameter\n *\n * Threading `userId` (and later `organizationId`) through dozens of method\n * signatures is pure parameter pollution. Ambient context also lets a repo\n * make the \"I forgot to scope\" mistake impossible at runtime: in strict mode\n * `requireRequester()` throws when no context is active, surfacing a missing\n * boundary call loudly rather than silently leaking cross-tenant data.\n *\n * ## Not-found semantics\n *\n * When a row exists but belongs to a different requester, scoped reads return\n * `null`/`[]` — identical to \"truly doesn't exist\". No existence oracle;\n * callers throw NotFound uniformly. Standard security practice.\n *\n * ## Testing\n *\n * Tests that exercise scoped repos must wrap the call in `withRequester(...)`.\n * In strict mode an unwrapped call hitting `requireRequester()` throws — by\n * design. In lenient mode (the default) an unwrapped call is simply unscoped.\n */\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\n/**\n * Data-visibility scope. The auth layer decides which scope a request is\n * allowed to claim; the repo trusts whatever the ambient context says.\n *\n * - `'user'`: filter every read by `user_id = ctx.userId`. Default.\n * - `'org'`: filter every read by membership in the requester's org, resolved\n * via `user_id IN (ctx.orgUserIds)` rather than via a per-entity\n * `organization_id` column. Works for every user-owned table and keeps repos\n * single-table — the org member list is pre-resolved at the boundary.\n * - `'superuser'`: no scope filter. Engineering / internal-tools only.\n *\n * AUTHORIZATION (who is allowed to claim each scope) lives in boundary\n * middleware, not in the repo. The repo trusts the ambient context — same\n * trust model as a threaded `userId`.\n */\nexport type RequesterScope = 'user' | 'org' | 'superuser';\n\nexport interface RequesterContext {\n /**\n * The user making the request. Always present — even in `'org'` and\n * `'superuser'` scopes it is the audit-trail \"who actually did this\".\n */\n readonly userId: string;\n /**\n * The organization the requester belongs to. Required when\n * `scope === 'org'`; may be null for `'user'` (users with no org) and for\n * `'superuser'` (cross-org reads).\n */\n readonly organizationId: string | null;\n /**\n * Data-visibility scope. Defaults to `'user'` when omitted.\n */\n readonly scope?: RequesterScope;\n /**\n * For `scope === 'org'`: the list of user IDs in the requester's org,\n * pre-resolved by the boundary middleware that established the `'org'`\n * scope (one `SELECT users.id WHERE organization_id = X` at the trust\n * boundary). Repos use this as a literal `IN (...)` filter — they never\n * JOIN to `users` themselves. Required when `scope === 'org'`.\n */\n readonly orgUserIds?: readonly string[];\n}\n\nconst als = new AsyncLocalStorage<RequesterContext>();\n\n/**\n * Set the ambient requester context for the duration of `fn`. The context\n * propagates through `await` boundaries to all downstream calls. Nesting is\n * fine — an inner `withRequester` overrides the outer for its callback.\n */\nexport function withRequester<T>(\n ctx: RequesterContext,\n fn: () => Promise<T>,\n): Promise<T> {\n return als.run(ctx, fn);\n}\n\n/**\n * Read the ambient requester context. Throws if no context is active — by\n * design. Used by repos in strict scope-enforcement mode; an unwrapped call\n * site is a missing boundary.\n */\nexport function requireRequester(): RequesterContext {\n const ctx = als.getStore();\n if (!ctx) {\n throw new Error(\n 'No requester context active. Wrap the entry point in ' +\n 'withRequester({ userId, organizationId }, fn). See tenant-context.ts.',\n );\n }\n return ctx;\n}\n\n/**\n * Read the ambient requester context without throwing. Returns `undefined`\n * when no context is active. Used by repos in lenient scope-enforcement mode\n * (the default) and by code paths that legitimately run outside a request.\n */\nexport function tryGetRequester(): RequesterContext | undefined {\n return als.getStore();\n}\n\n/**\n * Resolve the effective scope for the ambient context, defaulting to `'user'`.\n */\nexport function requireRequesterScope(): RequesterScope {\n return requireRequester().scope ?? 'user';\n}\n\n/**\n * Convenience helpers for setting scope explicitly. All three preserve\n * `userId` in the context (audit trail) regardless of scope.\n *\n * - `withUserScope`: regular end-user requests. Most call sites.\n * - `withOrgScope`: admin / org-shared resource access. The caller MUST verify\n * the requester's role permits `'org'` before calling — the helper does not\n * enforce authorization. `orgUserIds` is pre-resolved at the boundary.\n * - `withSuperuserScope`: engineering scripts / internal tools. `organizationId`\n * is null (cross-org is the point). Same authorization caveat applies.\n */\nexport function withUserScope<T>(\n userId: string,\n organizationId: string | null,\n fn: () => Promise<T>,\n): Promise<T> {\n return withRequester({ userId, organizationId, scope: 'user' }, fn);\n}\n\nexport function withOrgScope<T>(\n userId: string,\n organizationId: string,\n orgUserIds: readonly string[],\n fn: () => Promise<T>,\n): Promise<T> {\n return withRequester(\n { userId, organizationId, scope: 'org', orgUserIds },\n fn,\n );\n}\n\nexport function withSuperuserScope<T>(\n userId: string,\n fn: () => Promise<T>,\n): Promise<T> {\n return withRequester(\n { userId, organizationId: null, scope: 'superuser' },\n fn,\n );\n}\n"],"mappings":";AAQA,SAAS,MAAAA,KAAI,OAAAC,MAAK,YAAY;;;ACG9B,SAAS,KAAK,IAAI,SAAS,QAAQ,WAAW;;;ACiC9C,SAAS,yBAAyB;AA6ClC,IAAM,MAAM,IAAI,kBAAoC;AAmB7C,SAAS,mBAAqC;AACnD,QAAM,MAAM,IAAI,SAAS;AACzB,MAAI,CAAC,KAAK;AACR,UAAM,IAAI;AAAA,MACR;AAAA,IAEF;AAAA,EACF;AACA,SAAO;AACT;AAOO,SAAS,kBAAgD;AAC9D,SAAO,IAAI,SAAS;AACtB;;;AD7EO,IAAe,iBAAf,MAAuC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWzB,YAA4B;AAAA,IAC7C,YAAY;AAAA,IACZ,YAAY;AAAA,IACZ,cAAc;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAemB,mBAAyC;AAAA,EAEzC;AAAA,EAEnB,YAAY,IAAmB;AAC7B,SAAK,KAAK;AAAA,EACZ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASU,OAAO,IAA+B;AAC9C,WAAO,MAAM,KAAK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AO,IAAW,EAClB,mBAAmB;AAAA,MAClB,QAAQ,KAAK,MAAM,cAAwB;AAAA,MAC3C,KAAK,KAAK,CAAC;AAAA;AAAA,IACb,CAAC,EACA,UAAU;AAEb,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,sBAAsB,UAAkB,YAAwC;AACpF,UAAM,OAAO,MAAM,KAAK,UAAU,EAC/B;AAAA,MACCC;AAAA,QACEC,IAAG,KAAK,MAAM,UAAU,GAAG,QAAQ;AAAA,QACnCA,IAAG,KAAK,MAAM,YAAY,GAAG,UAAU;AAAA,MACzC;AAAA,IACF;AACF,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,eAAe,UAAsC;AACzD,UAAM,OAAO,MAAM,KAAK,UAAU,EAC/B,MAAMA,IAAG,KAAK,MAAM,UAAU,GAAG,QAAQ,CAAC;AAC7C,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,sBAAsB,UAAsC;AAChE,UAAM,OAAO,MAAM,KAAK,UAAU,EAC/B,MAAMA,IAAG,KAAK,MAAM,UAAU,GAAG,QAAQ,CAAC,EAC1C,QAAQ,KAAK,KAAK,MAAM,WAAW,CAAC,CAAC;AACxC,WAAO;AAAA,EACT;AACF;","names":["eq","and","and","eq"]}
|
|
@@ -1,8 +1,26 @@
|
|
|
1
1
|
// runtime/base-classes/synced-entity-repository.ts
|
|
2
|
-
import { and, eq as eq2, inArray as inArray2 } from "drizzle-orm";
|
|
2
|
+
import { and as and2, eq as eq2, inArray as inArray2 } from "drizzle-orm";
|
|
3
|
+
|
|
4
|
+
// runtime/base-classes/base-repository.ts
|
|
5
|
+
import { and, eq, inArray, isNull, sql } from "drizzle-orm";
|
|
6
|
+
|
|
7
|
+
// runtime/base-classes/tenant-context.ts
|
|
8
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
9
|
+
var als = new AsyncLocalStorage();
|
|
10
|
+
function requireRequester() {
|
|
11
|
+
const ctx = als.getStore();
|
|
12
|
+
if (!ctx) {
|
|
13
|
+
throw new Error(
|
|
14
|
+
"No requester context active. Wrap the entry point in withRequester({ userId, organizationId }, fn). See tenant-context.ts."
|
|
15
|
+
);
|
|
16
|
+
}
|
|
17
|
+
return ctx;
|
|
18
|
+
}
|
|
19
|
+
function tryGetRequester() {
|
|
20
|
+
return als.getStore();
|
|
21
|
+
}
|
|
3
22
|
|
|
4
23
|
// runtime/base-classes/base-repository.ts
|
|
5
|
-
import { eq, inArray, isNull, sql } from "drizzle-orm";
|
|
6
24
|
var BaseRepository = class {
|
|
7
25
|
// eslint-disable-line @typescript-eslint/no-explicit-any
|
|
8
26
|
/**
|
|
@@ -14,6 +32,20 @@ var BaseRepository = class {
|
|
|
14
32
|
softDelete: false,
|
|
15
33
|
userTracking: false
|
|
16
34
|
};
|
|
35
|
+
/**
|
|
36
|
+
* Ambient tenant-scope enforcement for `userTracking` repos (see
|
|
37
|
+
* `scopePredicate`). Only has effect when `behaviors.userTracking === true`.
|
|
38
|
+
*
|
|
39
|
+
* - `'lenient'` (default): when no ambient requester context is active,
|
|
40
|
+
* reads/writes are NOT scoped — preserves pre-scoping behavior, so adopting
|
|
41
|
+
* ambient scoping is additive. Scoping kicks in automatically once a
|
|
42
|
+
* boundary installs `withRequester(...)`.
|
|
43
|
+
* - `'strict'`: a missing ambient context throws (`requireRequester`),
|
|
44
|
+
* making a forgotten boundary fail loud instead of silently returning
|
|
45
|
+
* cross-tenant rows. Recommended for new multi-tenant consumers — override
|
|
46
|
+
* in a concrete repo or a family base class.
|
|
47
|
+
*/
|
|
48
|
+
scopeEnforcement = "lenient";
|
|
17
49
|
db;
|
|
18
50
|
constructor(db) {
|
|
19
51
|
this.db = db;
|
|
@@ -36,7 +68,7 @@ var BaseRepository = class {
|
|
|
36
68
|
* Returns null if not found (or soft-deleted when softDelete=true).
|
|
37
69
|
*/
|
|
38
70
|
async findById(id) {
|
|
39
|
-
const rows = await this.baseQuery(
|
|
71
|
+
const rows = await this.baseQuery(eq(this.table["id"], id)).limit(1);
|
|
40
72
|
return rows[0] ?? null;
|
|
41
73
|
}
|
|
42
74
|
/**
|
|
@@ -45,17 +77,14 @@ var BaseRepository = class {
|
|
|
45
77
|
*/
|
|
46
78
|
async findByIds(ids) {
|
|
47
79
|
if (ids.length === 0) return [];
|
|
48
|
-
const rows = await this.baseQuery(
|
|
80
|
+
const rows = await this.baseQuery(inArray(this.table["id"], ids));
|
|
49
81
|
return rows;
|
|
50
82
|
}
|
|
51
83
|
/**
|
|
52
84
|
* List entities with optional filtering, pagination, and ordering.
|
|
53
85
|
*/
|
|
54
86
|
async list(options) {
|
|
55
|
-
let query = this.baseQuery();
|
|
56
|
-
if (options?.where) {
|
|
57
|
-
query = query.where(options.where);
|
|
58
|
-
}
|
|
87
|
+
let query = this.baseQuery(options?.where);
|
|
59
88
|
if (options?.orderBy) {
|
|
60
89
|
query = query.orderBy(options.orderBy);
|
|
61
90
|
}
|
|
@@ -78,14 +107,17 @@ var BaseRepository = class {
|
|
|
78
107
|
if (this.behaviors.softDelete) {
|
|
79
108
|
conditions.push(isNull(this.table["deletedAt"]));
|
|
80
109
|
}
|
|
110
|
+
const scope = this.scopePredicate();
|
|
111
|
+
if (scope) {
|
|
112
|
+
conditions.push(scope);
|
|
113
|
+
}
|
|
81
114
|
if (where) {
|
|
82
115
|
conditions.push(where);
|
|
83
116
|
}
|
|
84
117
|
if (conditions.length === 1) {
|
|
85
118
|
query = query.where(conditions[0]);
|
|
86
119
|
} else if (conditions.length > 1) {
|
|
87
|
-
|
|
88
|
-
query = query.where(and2(...conditions));
|
|
120
|
+
query = query.where(and(...conditions));
|
|
89
121
|
}
|
|
90
122
|
const rows = await query;
|
|
91
123
|
return rows[0]?.count ?? 0;
|
|
@@ -114,7 +146,7 @@ var BaseRepository = class {
|
|
|
114
146
|
*/
|
|
115
147
|
async update(id, input, tx) {
|
|
116
148
|
const data = this.withTimestamps(input, "update");
|
|
117
|
-
const rows = await this.runner(tx).update(this.table).set(data).where(eq(this.table["id"], id)).returning();
|
|
149
|
+
const rows = await this.runner(tx).update(this.table).set(data).where(this.scopeAnd(eq(this.table["id"], id))).returning();
|
|
118
150
|
return rows[0];
|
|
119
151
|
}
|
|
120
152
|
/**
|
|
@@ -125,9 +157,9 @@ var BaseRepository = class {
|
|
|
125
157
|
async delete(id, tx) {
|
|
126
158
|
const runner = this.runner(tx);
|
|
127
159
|
if (this.behaviors.softDelete) {
|
|
128
|
-
await runner.update(this.table).set({ deletedAt: /* @__PURE__ */ new Date() }).where(eq(this.table["id"], id));
|
|
160
|
+
await runner.update(this.table).set({ deletedAt: /* @__PURE__ */ new Date() }).where(this.scopeAnd(eq(this.table["id"], id)));
|
|
129
161
|
} else {
|
|
130
|
-
await runner.delete(this.table).where(eq(this.table["id"], id));
|
|
162
|
+
await runner.delete(this.table).where(this.scopeAnd(eq(this.table["id"], id)));
|
|
131
163
|
}
|
|
132
164
|
}
|
|
133
165
|
/**
|
|
@@ -142,15 +174,64 @@ var BaseRepository = class {
|
|
|
142
174
|
// Protected Helpers
|
|
143
175
|
// ============================================================================
|
|
144
176
|
/**
|
|
145
|
-
* Base SELECT query that automatically
|
|
146
|
-
* when softDelete
|
|
177
|
+
* Base SELECT query that automatically applies the ambient guards —
|
|
178
|
+
* soft-delete exclusion (when `softDelete`) and tenant scope (when
|
|
179
|
+
* `userTracking` + an active requester context) — combined with an optional
|
|
180
|
+
* caller `extra` predicate into a SINGLE `WHERE`.
|
|
181
|
+
*
|
|
182
|
+
* Pass the leaf predicate as `extra` rather than chaining a second
|
|
183
|
+
* `.where(...)`: Drizzle's `.where()` OVERRIDES (does not AND) a prior
|
|
184
|
+
* `.where()` on a `$dynamic()` query, so a chained call would silently drop
|
|
185
|
+
* the soft-delete and scope guards. `baseQuery(extra)` is the safe form.
|
|
147
186
|
*/
|
|
148
|
-
baseQuery() {
|
|
187
|
+
baseQuery(extra) {
|
|
149
188
|
const query = this.db.select().from(this.table).$dynamic();
|
|
150
|
-
|
|
151
|
-
|
|
189
|
+
const where = this.scopeAnd(extra, { softDelete: this.behaviors.softDelete });
|
|
190
|
+
return where ? query.where(where) : query;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Build the ambient tenant-scope predicate for this repo's table.
|
|
194
|
+
*
|
|
195
|
+
* Returns `undefined` (no scoping) when:
|
|
196
|
+
* - `behaviors.userTracking` is false (repo is not user-owned), or
|
|
197
|
+
* - no ambient requester context is active AND `scopeEnforcement` is
|
|
198
|
+
* `'lenient'` (the default — preserves pre-scoping behavior).
|
|
199
|
+
*
|
|
200
|
+
* When a requester context is active, scopes by `user_id` per the ambient
|
|
201
|
+
* scope: `'user'` → `user_id = ctx.userId`; `'org'` → `user_id IN
|
|
202
|
+
* ctx.orgUserIds` (empty list matches nothing — fail-closed); `'superuser'`
|
|
203
|
+
* → no filter. See `tenant-context.ts` for the boundary-install contract.
|
|
204
|
+
*/
|
|
205
|
+
scopePredicate() {
|
|
206
|
+
if (!this.behaviors.userTracking) return void 0;
|
|
207
|
+
const ctx = this.scopeEnforcement === "strict" ? requireRequester() : tryGetRequester();
|
|
208
|
+
if (!ctx) return void 0;
|
|
209
|
+
const scope = ctx.scope ?? "user";
|
|
210
|
+
switch (scope) {
|
|
211
|
+
case "superuser":
|
|
212
|
+
return void 0;
|
|
213
|
+
case "org":
|
|
214
|
+
return ctx.orgUserIds && ctx.orgUserIds.length > 0 ? inArray(this.table["userId"], ctx.orgUserIds) : sql`false`;
|
|
215
|
+
case "user":
|
|
216
|
+
default:
|
|
217
|
+
return eq(this.table["userId"], ctx.userId);
|
|
152
218
|
}
|
|
153
|
-
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* Combine the ambient scope predicate (and, optionally, the soft-delete
|
|
222
|
+
* guard) with a caller `extra` predicate into one `SQL`. Returns `undefined`
|
|
223
|
+
* when nothing applies. Used by read + by-id write paths so a single
|
|
224
|
+
* `.where(...)` carries every guard.
|
|
225
|
+
*/
|
|
226
|
+
scopeAnd(extra, opts) {
|
|
227
|
+
const conditions = [];
|
|
228
|
+
if (opts?.softDelete) conditions.push(isNull(this.table["deletedAt"]));
|
|
229
|
+
const scope = this.scopePredicate();
|
|
230
|
+
if (scope) conditions.push(scope);
|
|
231
|
+
if (extra) conditions.push(extra);
|
|
232
|
+
if (conditions.length === 0) return void 0;
|
|
233
|
+
if (conditions.length === 1) return conditions[0];
|
|
234
|
+
return and(...conditions);
|
|
154
235
|
}
|
|
155
236
|
/**
|
|
156
237
|
* Merge timestamp fields into an input object.
|
|
@@ -295,7 +376,7 @@ var SyncedEntityRepository = class extends BaseRepository {
|
|
|
295
376
|
*/
|
|
296
377
|
async findByExternalIdProjected(externalId, provider) {
|
|
297
378
|
const rows = await this.db.select().from(this.table).where(
|
|
298
|
-
|
|
379
|
+
and2(
|
|
299
380
|
eq2(this.table["provider"], provider),
|
|
300
381
|
eq2(this.table["externalId"], externalId)
|
|
301
382
|
)
|
|
@@ -313,7 +394,7 @@ var SyncedEntityRepository = class extends BaseRepository {
|
|
|
313
394
|
const db = this.runner(tx);
|
|
314
395
|
const set = this.syncConfig.softDelete ? { deletedAt: /* @__PURE__ */ new Date(), updatedAt: /* @__PURE__ */ new Date() } : { externalId: null, provider: null, updatedAt: /* @__PURE__ */ new Date() };
|
|
315
396
|
const rows = await db.update(this.table).set(set).where(
|
|
316
|
-
|
|
397
|
+
and2(
|
|
317
398
|
eq2(this.table["provider"], provider),
|
|
318
399
|
eq2(this.table["externalId"], externalId)
|
|
319
400
|
)
|
|
@@ -382,7 +463,7 @@ var SyncedEntityRepository = class extends BaseRepository {
|
|
|
382
463
|
}
|
|
383
464
|
const refTable = fk.refTable === "self" ? this.table : fk.refTable;
|
|
384
465
|
const rows = await db.select({ id: refTable["id"] }).from(refTable).where(
|
|
385
|
-
|
|
466
|
+
and2(
|
|
386
467
|
eq2(refTable["provider"], provider),
|
|
387
468
|
eq2(refTable["externalId"], parentExternalId)
|
|
388
469
|
)
|