@getstrata/core 2.2.47 → 2.2.49

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.
Files changed (53) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/core/audit/exportStore.d.ts +17 -0
  3. package/dist/core/auth/membershipService.d.ts +3 -23
  4. package/dist/core/auth/membershipServiceImplementation.d.ts +22 -0
  5. package/dist/core/auth/resolveMembershipService.d.ts +1 -1
  6. package/dist/core/cache/redisCacheScript.d.ts +2 -0
  7. package/dist/core/contracts/container.d.ts +2 -0
  8. package/dist/core/database/baseRepository.d.ts +3 -21
  9. package/dist/core/database/boundConnection.d.ts +1 -1
  10. package/dist/core/database/bunSql.d.ts +1 -1
  11. package/dist/core/database/connection.d.ts +1 -1
  12. package/dist/core/database/connectionContracts.d.ts +21 -0
  13. package/dist/core/database/defaultConnection.d.ts +1 -1
  14. package/dist/core/database/index.d.ts +1 -1
  15. package/dist/core/database/isolatedReadOnlyObservation.d.ts +1 -1
  16. package/dist/core/database/model.d.ts +6 -113
  17. package/dist/core/database/modelAttributes.d.ts +17 -0
  18. package/dist/core/database/modelQuery.d.ts +139 -0
  19. package/dist/core/database/modelRegistry.d.ts +34 -0
  20. package/dist/core/database/mysqlConnection.d.ts +1 -1
  21. package/dist/core/database/queryProxy.d.ts +1 -1
  22. package/dist/core/database/relationQueries.d.ts +20 -0
  23. package/dist/core/database/repositoryConnection.d.ts +1 -1
  24. package/dist/core/database/sqliteConnection.d.ts +1 -1
  25. package/dist/core/database/transaction.d.ts +1 -1
  26. package/dist/core/http/middleware.d.ts +2 -2
  27. package/dist/core/http/routeMiddleware.d.ts +1 -1
  28. package/dist/core/mail/mailer.d.ts +1 -4
  29. package/dist/core/mail/smtpMessage.d.ts +7 -0
  30. package/dist/core/queue/redisListScripts.d.ts +5 -0
  31. package/dist/core/queue/redisStreamsScripts.d.ts +11 -0
  32. package/dist/core/scheduler/leaseScript.d.ts +2 -0
  33. package/dist/entries/audit/exportAuditLogs.js +63 -58
  34. package/dist/entries/auth/basicAuthGuard.js +14 -2
  35. package/dist/entries/auth/jwtGuard.js +14 -2
  36. package/dist/entries/auth/membershipService.js +13 -14
  37. package/dist/entries/auth/scimAuthMiddleware.js +34 -20
  38. package/dist/entries/auth/sessionGuard.js +14 -2
  39. package/dist/entries/cache/createCacheStore.js +2 -1
  40. package/dist/entries/config/envSchema.js +2 -1
  41. package/dist/entries/contracts/container.js +14 -2
  42. package/dist/entries/contracts/serviceTokens.js +14 -2
  43. package/dist/entries/facades.js +103 -101
  44. package/dist/entries/http/routeMiddleware.js +3 -3
  45. package/dist/entries/jobs/exportAuditLogsJob.js +63 -58
  46. package/dist/entries/mail/mailer.js +103 -101
  47. package/dist/entries/queue/createAppQueue.js +277 -271
  48. package/dist/entries/queue/publicQueue.js +277 -271
  49. package/dist/entries/queue/queueMetrics.js +277 -271
  50. package/dist/entries/queue/redisQueue.js +277 -271
  51. package/dist/framework/public-api.d.ts +1 -1
  52. package/dist/index.js +1603 -1535
  53. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # @getstrata/core changelog
2
2
 
3
+ ## 2.2.49
4
+
5
+ - Restore documented protected dirty-attribute write hooks and related-model forwarding types, preserving custom repositories, transactional events, scopes and serialization behavior.
6
+ - Separate private model attribute/registration/query/projection state and relation SQL compilation. Keep existing public/protected entrypoints, driver behavior and eager-loading runtime semantics.
7
+ - Release exporter-owned audit SQL scopes before HTTP delivery and acknowledge only the accepted snapshot; preserve caller-owned transactions, pending failures and at-least-once delivery.
8
+ - Move Redis list/Streams/cache/scheduler Lua protocols and SMTP MIME/address assembly into private owners without changing script/wire bytes, leases, fencing, retries, socket behavior or public imports.
9
+
10
+ ## 2.2.48
11
+
12
+ - Validate complete integer environment values instead of accepting partial numeric strings; retain documented defaults, signs and minimum checks.
13
+ - Add the protected `BaseRepository.cloneWithConnection()` construction hook for custom repositories with native private state. Keep the default legacy rebinding behavior and avoid rerunning application constructors implicitly; concrete subclasses own their construction override.
14
+ - Separate database connection capability contracts and membership lookup internals while retaining existing exports, constructors and service identity.
15
+ - Report synchronous dependency-resolution cycles with their service path and clean resolution state after failure, preserving singleton and transient behavior.
16
+
3
17
  ## 2.2.47
4
18
 
5
19
  - Align the package version with the starter/CLI correction batch; no core runtime behavior changes.
@@ -0,0 +1,17 @@
1
+ type PendingAuditLog = {
2
+ id: number;
3
+ user_id: number | null;
4
+ action: string;
5
+ subject_type: string;
6
+ subject_id: number | null;
7
+ payload: Record<string, unknown>;
8
+ ip_address: string | null;
9
+ user_agent: string | null;
10
+ checksum: string | null;
11
+ tenant_id: number | null;
12
+ trace_id: string | null;
13
+ created_at: Date;
14
+ };
15
+ declare function readPendingAuditLogs(batchSize: number): Promise<PendingAuditLog[]>;
16
+ declare function acknowledgeAuditLogs(ids: readonly number[]): Promise<void>;
17
+ export { acknowledgeAuditLogs, readPendingAuditLogs };
@@ -1,23 +1,3 @@
1
- import type { MembershipLookup, OrganizationMemberRole } from "../contracts/membership";
2
- import { type AuthUser } from "./authContext";
3
- type MembershipRepositoryLike = MembershipLookup;
4
- declare class MembershipService {
5
- private readonly members;
6
- constructor(members?: MembershipRepositoryLike);
7
- listOrganizationIdsForUser(userId: number): Promise<number[]>;
8
- getOrgRole(userId: number, organizationId: number): Promise<OrganizationMemberRole | null>;
9
- requireOrgAccess(organizationId: number, minimumRole?: OrganizationMemberRole, user?: AuthUser | null): Promise<OrganizationMemberRole>;
10
- filterAccessibleOrganizationIds(organizationIds: number[], user?: AuthUser | null): Promise<number[]>;
11
- addOwnerOnOrganizationCreate(organizationId: number, userId: number): Promise<void>;
12
- listMembersForOrganization(organizationId: number): Promise<import("../contracts/membership").MembershipRecord[]>;
13
- addMember(input: {
14
- organizationId: number;
15
- userId: number;
16
- role?: OrganizationMemberRole;
17
- }): Promise<import("../contracts/membership").MembershipRecord>;
18
- removeMember(organizationId: number, userId: number): Promise<unknown>;
19
- updateMemberRole(organizationId: number, userId: number, role: OrganizationMemberRole): Promise<import("../contracts/membership").MembershipRecord>;
20
- }
21
- export type { MembershipRepositoryLike };
22
- export default MembershipService;
23
- export { resolveMembershipService } from "./resolveMembershipService.ts";
1
+ export type { MembershipRepositoryLike } from "./membershipServiceImplementation";
2
+ export { default } from "./membershipServiceImplementation";
3
+ export { resolveMembershipService } from "./resolveMembershipService";
@@ -0,0 +1,22 @@
1
+ import type { MembershipLookup, OrganizationMemberRole } from "../contracts/membership";
2
+ import { type AuthUser } from "./authContext";
3
+ type MembershipRepositoryLike = MembershipLookup;
4
+ declare class MembershipService {
5
+ private readonly members;
6
+ constructor(members?: MembershipRepositoryLike);
7
+ listOrganizationIdsForUser(userId: number): Promise<number[]>;
8
+ getOrgRole(userId: number, organizationId: number): Promise<OrganizationMemberRole | null>;
9
+ requireOrgAccess(organizationId: number, minimumRole?: OrganizationMemberRole, user?: AuthUser | null): Promise<OrganizationMemberRole>;
10
+ filterAccessibleOrganizationIds(organizationIds: number[], user?: AuthUser | null): Promise<number[]>;
11
+ addOwnerOnOrganizationCreate(organizationId: number, userId: number): Promise<void>;
12
+ listMembersForOrganization(organizationId: number): Promise<import("../contracts/membership").MembershipRecord[]>;
13
+ addMember(input: {
14
+ organizationId: number;
15
+ userId: number;
16
+ role?: OrganizationMemberRole;
17
+ }): Promise<import("../contracts/membership").MembershipRecord>;
18
+ removeMember(organizationId: number, userId: number): Promise<unknown>;
19
+ updateMemberRole(organizationId: number, userId: number, role: OrganizationMemberRole): Promise<import("../contracts/membership").MembershipRecord>;
20
+ }
21
+ export type { MembershipRepositoryLike };
22
+ export default MembershipService;
@@ -1,3 +1,3 @@
1
- import MembershipService from "./membershipService";
1
+ import MembershipService from "./membershipServiceImplementation";
2
2
  declare function resolveMembershipService(): MembershipService;
3
3
  export { resolveMembershipService };
@@ -0,0 +1,2 @@
1
+ declare const CACHE_SCRIPT = "\nlocal expected = {'hash', 'zset', 'zset', 'hash', 'zset'}\nfor i, key in ipairs(KEYS) do\n local kind = redis.call('TYPE', key).ok\n if kind ~= 'none' and kind ~= expected[i] then return redis.error_reply('Unexpected cache key type') end\nend\n-- Redis eviction can remove one container without its companions. Never read\n-- orphaned values or leases after losing the expiry/order/generation indexes.\nlocal entries = redis.call('HLEN', KEYS[1])\nlocal order = redis.call('ZCARD', KEYS[3])\nif redis.call('ZCARD', KEYS[2]) ~= order or entries ~= (order > 0 and order + 1 or 0) then\n redis.call('DEL', KEYS[1], KEYS[2], KEYS[3])\nend\nif redis.call('HLEN', KEYS[4]) ~= redis.call('ZCARD', KEYS[5]) then\n redis.call('DEL', KEYS[4], KEYS[5])\nend\nlocal r = cjson.decode(ARGV[1])\nlocal time = redis.call('TIME')\nlocal now = tonumber(time[1]) * 1000 + tonumber(time[2]) / 1000\nlocal function removeEntry(key)\n local removed = redis.call('HDEL', KEYS[1], 'e:' .. key)\n redis.call('ZREM', KEYS[2], key)\n redis.call('ZREM', KEYS[3], key)\n return removed\nend\nlocal function removeMeta(field)\n redis.call('HDEL', KEYS[4], field)\n redis.call('ZREM', KEYS[5], field)\nend\nfor _, key in ipairs(redis.call('ZRANGEBYSCORE', KEYS[2], '-inf', now, 'LIMIT', 0, r.capacity)) do removeEntry(key) end\nfor _, field in ipairs(redis.call('ZRANGEBYSCORE', KEYS[5], '-inf', now, 'LIMIT', 0, r.metadataLimit)) do removeMeta(field) end\nlocal function expireContainers()\n local last = redis.call('ZREVRANGE', KEYS[2], 0, 0, 'WITHSCORES')\n if #last == 0 then\n redis.call('DEL', KEYS[1], KEYS[2], KEYS[3])\n elseif last[2] == 'inf' then\n for i = 1, 3 do redis.call('PERSIST', KEYS[i]) end\n else\n local ttl = math.max(1, math.ceil(tonumber(last[2]) - now))\n for i = 1, 3 do redis.call('PEXPIRE', KEYS[i], ttl) end\n end\n for i = 4, 5 do redis.call('PEXPIRE', KEYS[i], r.metadataTtlMs) end\nend\nlocal function response(value)\n expireContainers()\n return cjson.encode(value)\nend\nlocal function addTags(existing, added)\n local seen = {}\n local result = {}\n for _, tags in ipairs({existing, added}) do\n for _, tag in ipairs(tags) do\n if not seen[tag] then seen[tag] = true; table.insert(result, tag) end\n end\n end\n if #result > 32 then error('Cache entries support at most 32 tags') end\n return result\nend\nlocal function touch(key)\n local sequence = redis.call('HINCRBY', KEYS[1], '_sequence', 1)\n redis.call('ZADD', KEYS[3], sequence, key)\nend\nlocal function read(key, tags)\n local raw = redis.call('HGET', KEYS[1], 'e:' .. key)\n if not raw then return nil end\n local entry = cjson.decode(raw)\n if #tags > 0 then\n entry.tags = addTags(entry.tags, tags)\n redis.call('HSET', KEYS[1], 'e:' .. key, cjson.encode(entry))\n end\n touch(key)\n return entry.payload\nend\nlocal function write(key, payload, tags)\n local entry = {payload=payload, tags=tags}\n redis.call('HSET', KEYS[1], 'e:' .. key, cjson.encode(entry))\n redis.call('ZADD', KEYS[2], r.ttlMs == 0 and '+inf' or now + r.ttlMs, key)\n touch(key)\n local overflow = redis.call('ZCARD', KEYS[3]) - r.capacity\n if overflow > 0 then\n for _, victim in ipairs(redis.call('ZRANGE', KEYS[3], 0, overflow - 1)) do removeEntry(victim) end\n end\nend\nlocal leaseField = 'l:' .. r.key\nlocal function lease()\n local raw = redis.call('HGET', KEYS[4], leaseField)\n if not raw then return nil end\n local value = cjson.decode(raw)\n if value.expires <= now or value.deadline <= now then removeMeta(leaseField); return nil end\n return value\nend\nlocal function metadataSpace(count)\n if redis.call('HLEN', KEYS[4]) + count > r.metadataLimit then\n -- Pressure sheds generation/lease state. Every old owner is fenced; cached\n -- entries remain valid because invalidation removes matching entries atomically.\n redis.call('DEL', KEYS[4], KEYS[5])\n end\nend\nlocal function putMeta(field, value, expires)\n redis.call('HSET', KEYS[4], field, value)\n redis.call('ZADD', KEYS[5], expires, field)\nend\nlocal function scopes()\n local fields = {}\n for _, tag in ipairs(r.tags) do table.insert(fields, 'g:tag:' .. tag) end\n for _, prefix in ipairs(r.prefixes) do table.insert(fields, 'g:prefix:' .. prefix) end\n return fields\nend\nlocal function matches(key, tags)\n if r.op == 'invalidate' then return key == r.key end\n if r.op == 'prefix' then return key == r.key or string.sub(key, 1, #r.key + 1) == r.key .. '?' end\n if r.op == 'tags' then\n for _, existing in ipairs(tags) do\n for _, wanted in ipairs(r.tags) do if wanted == existing then return true end end\n end\n end\n return false\nend\nif r.op == 'clear' then\n redis.call('DEL', unpack(KEYS))\n return cjson.encode({removed=0})\nelseif r.op == 'get' then\n local payload = read(r.key, r.tags)\n return response(payload and {kind='value', payload=payload} or {kind='missing'})\nelseif r.op == 'set' then\n local old = redis.call('HGET', KEYS[1], 'e:' .. r.key)\n local tags = old and cjson.decode(old).tags or {}\n write(r.key, r.payload, tags)\n removeMeta(leaseField)\n return response({written=true})\nelseif r.op == 'attach' then\n read(r.key, r.tags)\n return response({written=true})\nelseif r.op == 'size' then\n return response({size=redis.call('ZCARD', KEYS[3])})\nelseif r.op == 'tags' or r.op == 'prefix' or r.op == 'invalidate' then\n local generationFields = {}\n if r.op == 'tags' then\n for _, tag in ipairs(r.tags) do table.insert(generationFields, 'g:tag:' .. tag) end\n elseif r.op == 'prefix' then table.insert(generationFields, 'g:prefix:' .. r.key) end\n metadataSpace(#generationFields)\n for _, field in ipairs(generationFields) do putMeta(field, r.owner, now + r.metadataTtlMs) end\n local removed = 0\n for _, key in ipairs(redis.call('ZRANGE', KEYS[3], 0, -1)) do\n local raw = redis.call('HGET', KEYS[1], 'e:' .. key)\n if raw and matches(key, cjson.decode(raw).tags) then removed = removed + removeEntry(key) end\n end\n for _, field in ipairs(redis.call('HKEYS', KEYS[4])) do\n if string.sub(field, 1, 2) == 'l:' then\n local value = cjson.decode(redis.call('HGET', KEYS[4], field))\n if matches(string.sub(field, 3), value.tags) then removeMeta(field) end\n end\n end\n return response({removed=removed})\nelseif r.op == 'claim' then\n local payload = read(r.key, r.tags)\n if payload then return response({kind='value', payload=payload}) end\n local current = lease()\n if current then\n local shared = addTags(current.tags, r.tags)\n if #shared == #current.tags then return response({kind='wait'}) end\n -- A newly requested tag must not inherit a fill started before that tag's\n -- invalidation. Restart with the union of tags and a new owner.\n r.tags = shared\n removeMeta(leaseField)\n end\n local active = 0\n for _, field in ipairs(redis.call('HKEYS', KEYS[4])) do if string.sub(field, 1, 2) == 'l:' then active = active + 1 end end\n if active >= r.capacity then return response({kind='wait'}) end\n local fields = scopes()\n metadataSpace(#fields + 1)\n local generations = {}\n for _, field in ipairs(fields) do\n local token = redis.call('HGET', KEYS[4], field) or r.owner\n putMeta(field, token, now + r.metadataTtlMs)\n generations[field] = token\n end\n local value = {owner=r.owner, tags=r.tags, generations=generations, deadline=now + r.fillTimeoutMs, expires=now + r.leaseMs}\n putMeta(leaseField, cjson.encode(value), value.expires)\n return response({kind='owner'})\nelseif r.op == 'renew' or r.op == 'publish' or r.op == 'release' then\n local current = lease()\n if not current or current.owner ~= r.owner then return response({owned=false}) end\n if r.op == 'release' then removeMeta(leaseField); return response({owned=true}) end\n for field, token in pairs(current.generations) do\n if redis.call('HGET', KEYS[4], field) ~= token then removeMeta(leaseField); return response({owned=false}) end\n end\n if r.op == 'renew' then\n current.expires = math.min(current.deadline, now + r.leaseMs)\n putMeta(leaseField, cjson.encode(current), current.expires)\n else\n write(r.key, r.payload, current.tags)\n removeMeta(leaseField)\n end\n return response({owned=true})\nend\nreturn redis.error_reply('Unknown cache operation')\n";
2
+ export { CACHE_SCRIPT };
@@ -18,6 +18,7 @@ declare class ServiceContainer implements ServiceContainerLike {
18
18
  private readonly services;
19
19
  private readonly singletonFactories;
20
20
  private readonly bindings;
21
+ private readonly resolutionPath;
21
22
  set<T>(key: ServiceToken<T>, value: NoInfer<T>): T;
22
23
  set<T>(key: LegacyServiceKey, value: T): T;
23
24
  singleton<T>(key: ServiceToken<T>, factory: ServiceFactory<NoInfer<T>>): void;
@@ -26,6 +27,7 @@ declare class ServiceContainer implements ServiceContainerLike {
26
27
  bind<T>(key: LegacyServiceKey, factory: ServiceFactory<T>): void;
27
28
  get<T>(key: ServiceToken<T>): T;
28
29
  get<T>(key: LegacyServiceKey): T;
30
+ private resolveFactory;
29
31
  resolve<T>(key: ServiceToken<T>): T;
30
32
  resolve<T>(key: LegacyServiceKey): T;
31
33
  make<T>(key: ServiceToken<T>): T;
@@ -1,5 +1,6 @@
1
1
  import type { KeysetCursor, KeysetOptions } from "../pagination/index.ts";
2
2
  import { type CursorPaginatedResult, type PaginatedResult } from "../pagination/index.ts";
3
+ import type { DatabaseConnection, SqlDatabaseConnection } from "./connectionContracts";
3
4
  import { type BelongsToManyRelation, type BelongsToRelation, type HasManyRelation, type HasManyThroughRelation, type MorphManyRelation, type MorphOneRelation, type MorphToRelation } from "./relationships.ts";
4
5
  import { RepositoryQuery } from "./repositoryQuery.ts";
5
6
  import type { TableDefinition } from "./table.ts";
@@ -8,26 +9,6 @@ import type { WhereNode } from "./whereBuilder.ts";
8
9
  type ExtendedQueryOptions<TEntity extends object> = QueryOptions<TEntity> & {
9
10
  whereNodes?: WhereNode<TEntity>[];
10
11
  };
11
- interface DatabaseConnection {
12
- unsafe<T>(query: string, params?: readonly unknown[]): Promise<T[]>;
13
- begin?<T>(callback: (transaction: DatabaseConnection) => Promise<T>): Promise<T>;
14
- /** Optional native cancellable pool checkout; absence must not be silently emulated. */
15
- reserve?(options: {
16
- signal?: AbortSignal;
17
- }): Promise<DatabaseConnection & {
18
- release(): void | Promise<void>;
19
- }>;
20
- /** Optional independent, interruptible read-only observation; no business transaction or pool slot. */
21
- observeReadOnly?<T>(operation: (connection: DatabaseConnection) => Promise<T>, options: {
22
- signal: AbortSignal;
23
- timeoutMs: number;
24
- }): Promise<T>;
25
- /** SQLite closes synchronously; pooled drivers return a promise. */
26
- close?(): void | Promise<void>;
27
- }
28
- interface SqlDatabaseConnection extends DatabaseConnection {
29
- (strings: TemplateStringsArray, ...values: unknown[]): Promise<unknown[]>;
30
- }
31
12
  type ErrorFactory<TValue> = (value: TValue) => Error;
32
13
  declare class BaseRepository<TEntity extends object, PrimaryKey extends keyof TEntity & string> {
33
14
  protected readonly table: TableDefinition<TEntity, PrimaryKey>;
@@ -75,6 +56,8 @@ declare class BaseRepository<TEntity extends object, PrimaryKey extends keyof TE
75
56
  restoreById(id: TEntity[PrimaryKey]): Promise<TEntity | null>;
76
57
  private primaryKeySeekDirection;
77
58
  withConnection(connection: DatabaseConnection): this;
59
+ /** Override when constructor initialization or native private fields must be preserved. */
60
+ protected cloneWithConnection(connection: DatabaseConnection): this;
78
61
  getConnection(): DatabaseConnection;
79
62
  getTable(): TableDefinition<TEntity, PrimaryKey>;
80
63
  query(where?: QueryWhere<TEntity>): RepositoryQuery<TEntity, PrimaryKey>;
@@ -101,7 +84,6 @@ declare class BaseRepository<TEntity extends object, PrimaryKey extends keyof TE
101
84
  loadHasManyForParents<TParent extends object, LocalKey extends keyof TParent & string, ForeignKey extends keyof TEntity & string>(parents: readonly TParent[], relation: HasManyRelation<TParent, TEntity, LocalKey, ForeignKey>, options?: Omit<QueryOptions<TEntity>, "where">): Promise<Map<TParent[LocalKey], TEntity[]>>;
102
85
  findHasManyThrough<TParent extends object, LocalKey extends keyof TParent & string, FirstKey extends string, SecondLocalKey extends string, SecondKey extends keyof TEntity & string>(parentId: unknown, relation: HasManyThroughRelation<TParent, TEntity, LocalKey, FirstKey, SecondLocalKey, SecondKey>, options?: QueryOptions<TEntity>): Promise<TEntity[]>;
103
86
  loadHasManyThroughForParents<TParent extends object, LocalKey extends keyof TParent & string, FirstKey extends string, SecondLocalKey extends string, SecondKey extends keyof TEntity & string>(parents: readonly TParent[], relation: HasManyThroughRelation<TParent, TEntity, LocalKey, FirstKey, SecondLocalKey, SecondKey>, options?: QueryOptions<TEntity>): Promise<Map<TParent[LocalKey], TEntity[]>>;
104
- private buildThroughWhere;
105
87
  loadBelongsToForParents<TChild extends object, TParent extends object, ForeignKey extends keyof TChild & string, OwnerKey extends keyof TParent & string>(children: readonly TChild[], relation: BelongsToRelation<TChild, TParent, ForeignKey, OwnerKey>, parentRepository: BaseRepository<TParent, OwnerKey>, options?: Omit<QueryOptions<TParent>, "where">): Promise<Map<TChild[ForeignKey], TParent>>;
106
88
  loadMorphManyForParents<TParent extends object, LocalKey extends keyof TParent & string, MorphTypeKey extends keyof TEntity & string, MorphIdKey extends keyof TEntity & string>(parents: readonly TParent[], relation: MorphManyRelation<TParent, TEntity, LocalKey, MorphTypeKey, MorphIdKey>, options?: Omit<QueryOptions<TEntity>, "where">): Promise<Map<TParent[LocalKey], TEntity[]>>;
107
89
  loadMorphOneForParents<TParent extends object, LocalKey extends keyof TParent & string, MorphTypeKey extends keyof TEntity & string, MorphIdKey extends keyof TEntity & string>(parents: readonly TParent[], relation: MorphOneRelation<TParent, TEntity, LocalKey, MorphTypeKey, MorphIdKey>, options?: Omit<QueryOptions<TEntity>, "where">): Promise<Map<TParent[LocalKey], TEntity | undefined>>;
@@ -1,4 +1,4 @@
1
- import type { DatabaseConnection } from "./baseRepository";
1
+ import type { DatabaseConnection } from "./connectionContracts";
2
2
  declare function bindDatabaseConnection(connection: DatabaseConnection): void;
3
3
  declare function getBoundDatabaseConnection(): DatabaseConnection | null;
4
4
  declare function resetBoundDatabaseConnection(): void;
@@ -1,5 +1,5 @@
1
1
  import { SQL } from "bun";
2
- import type { DatabaseConnection } from "./baseRepository";
2
+ import type { DatabaseConnection } from "./connectionContracts";
3
3
  interface CreateBunSqlPoolOptions {
4
4
  url: string;
5
5
  max?: number;
@@ -1,4 +1,4 @@
1
- import type { DatabaseConnection } from "./baseRepository.ts";
1
+ import type { DatabaseConnection } from "./connectionContracts.ts";
2
2
  type UnsafeQueryable = {
3
3
  unsafe<T>(query: string, params?: readonly unknown[]): Promise<T[]>;
4
4
  };
@@ -0,0 +1,21 @@
1
+ interface DatabaseConnection {
2
+ unsafe<T>(query: string, params?: readonly unknown[]): Promise<T[]>;
3
+ begin?<T>(callback: (transaction: DatabaseConnection) => Promise<T>): Promise<T>;
4
+ /** Optional native cancellable pool checkout; absence must not be silently emulated. */
5
+ reserve?(options: {
6
+ signal?: AbortSignal;
7
+ }): Promise<DatabaseConnection & {
8
+ release(): void | Promise<void>;
9
+ }>;
10
+ /** Optional independent, interruptible read-only observation; no business transaction or pool slot. */
11
+ observeReadOnly?<T>(operation: (connection: DatabaseConnection) => Promise<T>, options: {
12
+ signal: AbortSignal;
13
+ timeoutMs: number;
14
+ }): Promise<T>;
15
+ /** SQLite closes synchronously; pooled drivers return a promise. */
16
+ close?(): void | Promise<void>;
17
+ }
18
+ interface SqlDatabaseConnection extends DatabaseConnection {
19
+ (strings: TemplateStringsArray, ...values: unknown[]): Promise<unknown[]>;
20
+ }
21
+ export type { DatabaseConnection, SqlDatabaseConnection };
@@ -1,4 +1,4 @@
1
- import type { SqlDatabaseConnection } from "./baseRepository";
1
+ import type { SqlDatabaseConnection } from "./connectionContracts";
2
2
  declare function registerDefaultDatabasePool(connection: SqlDatabaseConnection): void;
3
3
  declare function getDefaultDatabasePool(): SqlDatabaseConnection;
4
4
  declare function getDefaultDatabaseQuery(): SqlDatabaseConnection;
@@ -1,8 +1,8 @@
1
- export type { DatabaseConnection } from "./baseRepository.ts";
2
1
  export { default as BaseRepository } from "./baseRepository.ts";
3
2
  export { createDatabaseConnection } from "./connection.ts";
4
3
  export type { ActiveDatabaseHandle } from "./connectionContext.ts";
5
4
  export { getActiveDatabaseConnection, hasActiveDatabaseConnection, runWithDatabaseConnection, } from "./connectionContext.ts";
5
+ export type { DatabaseConnection } from "./connectionContracts.ts";
6
6
  export type { SqlDialect } from "./dialect.ts";
7
7
  export { currentSqlDialect, dialectFor, resetSqlDialect, runWithSqlDialect, useSqlDialect, } from "./dialect.ts";
8
8
  export { mapDatabaseError, withDatabaseErrorHandling } from "./errors.ts";
@@ -1,4 +1,4 @@
1
- import type { DatabaseConnection } from "./baseRepository";
1
+ import type { DatabaseConnection } from "./connectionContracts";
2
2
  interface ReadOnlyObservationOptions {
3
3
  signal: AbortSignal;
4
4
  timeoutMs: number;
@@ -1,130 +1,23 @@
1
- import type { CursorPaginatedResult, KeysetCursor, KeysetOptions } from "../pagination/index.ts";
1
+ import type { KeysetOptions } from "../pagination/index.ts";
2
2
  import BaseRepository from "./baseRepository.ts";
3
+ import { applyCasts, type CastType, dehydrateValue, filterMassAssignable, hydrateValue, type LoadedAttributes, type ModelCasts } from "./modelAttributes.ts";
4
+ import { type ModelAttributes, type ModelIdentifier, type ModelProjection, ModelQuery, type RelationNameInput } from "./modelQuery.ts";
5
+ import { type GlobalScopeFn, type ModelObserver, registerModelClass } from "./modelRegistry.ts";
3
6
  import type { AnyRelationQuery, RelatedModelClass } from "./relationQuery.ts";
4
7
  import { BelongsToManyRelationQuery, BelongsToRelationQuery, HasManyRelationQuery, HasManyThroughRelationQuery, HasOneRelationQuery, MorphManyRelationQuery, MorphOneRelationQuery, MorphToRelationQuery } from "./relationQuery.ts";
5
8
  import type { BelongsToManyRelation, BelongsToRelation, HasManyRelation, HasOneRelation } from "./relationships.ts";
6
9
  import type { RepositoryQuery } from "./repositoryQuery.ts";
7
10
  import type { TableDefinition } from "./table.ts";
8
- import type { ModelWhere, ModelWriteValues, QueryLockOptions, QueryOptions, QueryWhere } from "./types.ts";
9
- type CastType = "date" | "datetime" | "json" | "bool" | "boolean" | "integer" | "int" | "hashed";
10
- type LoadedAttributes = Record<string, unknown>;
11
- type ModelCasts = Partial<Record<string, CastType>>;
12
- type GlobalScopeFn<TEntity extends object, PrimaryKey extends keyof TEntity & string> = (query: RepositoryQuery<TEntity, PrimaryKey>) => RepositoryQuery<TEntity, PrimaryKey>;
11
+ import type { ModelWhere, ModelWriteValues, QueryOptions } from "./types.ts";
13
12
  type ModelClassType<TEntity extends object, PrimaryKey extends keyof TEntity & string> = typeof Model & (new (attributes: TEntity, repository: BaseRepository<TEntity, PrimaryKey>, exists?: boolean) => Model<TEntity, PrimaryKey>);
14
13
  interface ModelConstructor<TEntity extends object, PrimaryKey extends keyof TEntity & string, TModel extends Model<TEntity, PrimaryKey>> extends ModelClassType<TEntity, PrimaryKey> {
15
14
  new (attributes: TEntity, repository: BaseRepository<TEntity, PrimaryKey>, exists?: boolean): TModel;
16
15
  }
17
- type AnyModel = Model<Record<string, unknown>, "id">;
18
- type ModelAttributes<TModel> = TModel extends {
19
- toObject(): infer TRecord extends object;
20
- } ? TRecord : Record<string, unknown>;
21
- type ModelIdentifier<TModel> = TModel extends {
22
- readonly id: infer TKey;
23
- } ? TKey : unknown;
24
- type WithModelCount<TModel, TCount extends string> = {
25
- toObject(): Omit<ModelAttributes<TModel>, TCount> & Record<TCount, unknown>;
26
- get<K extends keyof (Omit<ModelAttributes<TModel>, TCount> & Record<TCount, unknown>)>(key: K): (Omit<ModelAttributes<TModel>, TCount> & Record<TCount, unknown>)[K];
27
- } & TModel;
28
- type ModelQueryResult<TModel, TCounts extends string> = [TCounts] extends [never] ? TModel : WithModelCount<TModel, TCounts>;
29
16
  type RelatedRef<TRelated extends object, RelatedKey extends keyof TRelated & string> = RelatedModelClass<TRelated, RelatedKey> | string | (() => RelatedModelClass<TRelated, RelatedKey>);
30
- type RelationNameInput = string | readonly string[];
31
- type ModelObserver = {
32
- retrieved?: (model: AnyModel) => unknown;
33
- creating?: (model: AnyModel) => unknown;
34
- created?: (model: AnyModel) => unknown;
35
- updating?: (model: AnyModel) => unknown;
36
- updated?: (model: AnyModel) => unknown;
37
- saving?: (model: AnyModel) => unknown;
38
- saved?: (model: AnyModel) => unknown;
39
- deleting?: (model: AnyModel) => unknown;
40
- deleted?: (model: AnyModel) => unknown;
41
- };
42
17
  /** Typed model base with a lazily created framework repository and active connection. */
43
18
  declare function defineModel<TEntity extends object, PrimaryKey extends keyof TEntity & string>(table: TableDefinition<TEntity, PrimaryKey>): typeof Model<TEntity, PrimaryKey>;
44
19
  /** Register all relationship names before initializing any model's boot hooks. */
45
20
  declare function bootModels(models: readonly object[]): void;
46
- /** Alias for `hasMany("Name")` when `Name` is not `constructor.name` or `$morphClass`. */
47
- declare function registerModelClass(name: string, model: object): void;
48
- declare function hydrateValue(value: unknown, cast: CastType): unknown;
49
- declare function dehydrateValue(value: unknown, cast: "hashed"): Promise<unknown>;
50
- declare function dehydrateValue(value: unknown, cast: Exclude<CastType, "hashed">): unknown;
51
- declare function dehydrateValue(value: unknown, cast: CastType): unknown;
52
- declare function filterMassAssignable(fillable: readonly string[] | undefined, guarded: readonly string[] | true | undefined, input: LoadedAttributes): LoadedAttributes;
53
- declare function applyCasts(values: LoadedAttributes, casts: ModelCasts, direction: "hydrate"): LoadedAttributes;
54
- declare function applyCasts(values: LoadedAttributes, casts: ModelCasts, direction: "dehydrate"): Promise<LoadedAttributes>;
55
- declare function applyCasts(values: LoadedAttributes, casts: ModelCasts, direction: "hydrate" | "dehydrate"): LoadedAttributes | Promise<LoadedAttributes>;
56
- /** Read-only plain records; partial selection never acquires model mutation methods. */
57
- declare class ModelProjection<TEntity extends object, K extends keyof TEntity & string> {
58
- private readonly load;
59
- private readonly page;
60
- constructor(load: (limit?: number) => Promise<Array<Pick<TEntity, K>>>, page: (options: KeysetOptions<TEntity>) => Promise<CursorPaginatedResult<Pick<TEntity, K>, KeysetCursor>>);
61
- keysetPaginate(options: KeysetOptions<TEntity>): Promise<CursorPaginatedResult<Pick<TEntity, K>, KeysetCursor>>;
62
- get(): Promise<Array<Pick<TEntity, K>>>;
63
- first(): Promise<Pick<TEntity, K> | null>;
64
- }
65
- declare class ModelQuery<TModel extends object = AnyModel, TCounts extends string = never> {
66
- private readonly modelClass;
67
- readonly query: RepositoryQuery<Record<string, unknown>, "id">;
68
- private readonly eager;
69
- constructor(modelClass: object, query: RepositoryQuery<Record<string, unknown>, "id">);
70
- with(...relations: RelationNameInput[]): this;
71
- where(input: ModelWhere<ModelAttributes<TModel>> | ((builder: import("./whereBuilder.ts").WhereBuilder<ModelAttributes<TModel>, ModelWhere<ModelAttributes<TModel>>>) => void)): this;
72
- orWhere(input: ModelWhere<ModelAttributes<TModel>> | ((builder: import("./whereBuilder.ts").WhereBuilder<ModelAttributes<TModel>, ModelWhere<ModelAttributes<TModel>>>) => void)): this;
73
- /** Qualified/dynamic filters retain existing SQL semantics through an explicit escape hatch. */
74
- whereDynamic(input: QueryWhere<object>): this;
75
- select<K extends keyof ModelAttributes<TModel> & string>(...columns: readonly K[]): ModelProjection<ModelAttributes<TModel>, K>;
76
- lockForUpdate(options?: QueryLockOptions): this;
77
- sharedLock(options?: QueryLockOptions): this;
78
- orderBy(orderBy: QueryOptions<ModelAttributes<TModel>>["orderBy"]): this;
79
- limit(limit: number): this;
80
- offset(offset: number): this;
81
- whereNull(column: keyof ModelAttributes<TModel> & string): this;
82
- whereNotNull(column: keyof ModelAttributes<TModel> & string): this;
83
- whereIn<K extends keyof ModelAttributes<TModel> & string>(column: K, values: readonly ModelAttributes<TModel>[K][]): this;
84
- whereNotIn<K extends keyof ModelAttributes<TModel> & string>(column: K, values: readonly ModelAttributes<TModel>[K][]): this;
85
- groupBy(groupBy: QueryOptions<object>["groupBy"]): this;
86
- having(having: QueryWhere<object>): this;
87
- join(left: `${string}.${string}`, right: `${string}.${string}`): this;
88
- leftJoin(left: `${string}.${string}`, right: `${string}.${string}`): this;
89
- paginate(options: {
90
- page: number;
91
- perPage: number;
92
- }): Promise<{
93
- data: ModelQueryResult<TModel, TCounts>[];
94
- meta: Awaited<ReturnType<RepositoryQuery<Record<string, unknown>, "id">["paginate"]>>["meta"];
95
- }>;
96
- whereExists(sql: string, params?: readonly unknown[]): this;
97
- whereNotExists(sql: string, params?: readonly unknown[]): this;
98
- whereHas(name: string, constrain?: (query: AnyRelationQuery) => void): this;
99
- has(name: string): this;
100
- doesntHave(name: string): this;
101
- whereDoesntHave(name: string, constrain?: (query: AnyRelationQuery) => void): this;
102
- withHasMany(...args: Parameters<RepositoryQuery<Record<string, unknown>, "id">["withHasMany"]>): this;
103
- withBelongsTo(...args: Parameters<RepositoryQuery<Record<string, unknown>, "id">["withBelongsTo"]>): this;
104
- withBelongsToMany(...args: Parameters<RepositoryQuery<Record<string, unknown>, "id">["withBelongsToMany"]>): this;
105
- withMorphMany(...args: Parameters<RepositoryQuery<Record<string, unknown>, "id">["withMorphMany"]>): this;
106
- withMorphOne(...args: Parameters<RepositoryQuery<Record<string, unknown>, "id">["withMorphOne"]>): this;
107
- withMorphTo(...args: Parameters<RepositoryQuery<Record<string, unknown>, "id">["withMorphTo"]>): this;
108
- withHasManyThrough(...args: Parameters<RepositoryQuery<Record<string, unknown>, "id">["withHasManyThrough"]>): this;
109
- withTrashed(): this;
110
- onlyTrashed(): this;
111
- get(): Promise<ModelQueryResult<TModel, TCounts>[]>;
112
- keysetPaginate(options: KeysetOptions<ModelAttributes<TModel>>): Promise<{
113
- meta: import("../pagination/index.ts").CursorPaginationMeta<KeysetCursor>;
114
- data: ModelQueryResult<TModel, TCounts>[];
115
- }>;
116
- private hydrateRows;
117
- first(): Promise<ModelQueryResult<TModel, TCounts> | null>;
118
- count(): Promise<number>;
119
- pluck(column: string): Promise<unknown[]>;
120
- pluck(column: string, keyBy: string): Promise<Map<unknown, unknown>>;
121
- value(column: string): Promise<unknown>;
122
- find(id: ModelIdentifier<TModel>): Promise<ModelQueryResult<TModel, TCounts> | null>;
123
- findOrFail(id: ModelIdentifier<TModel>, errorFactory?: (id: unknown) => Error): Promise<ModelQueryResult<TModel, TCounts>>;
124
- then(onfulfilled?: ((value: ModelQueryResult<TModel, TCounts>[]) => unknown) | null, onrejected?: ((reason: unknown) => unknown) | null): Promise<unknown>;
125
- withCount<TName extends string, TAlias extends string = `${TName}_count`>(name: TName, alias?: TAlias): ModelQuery<TModel, TCounts | TAlias>;
126
- private constrainExists;
127
- }
128
21
  declare class Model<TEntity extends object, PrimaryKey extends keyof TEntity & string> {
129
22
  protected attributes: TEntity;
130
23
  protected readonly repository: BaseRepository<TEntity, PrimaryKey>;
@@ -196,7 +89,7 @@ declare class Model<TEntity extends object, PrimaryKey extends keyof TEntity & s
196
89
  static keysetPaginate<TModel extends object>(this: {
197
90
  prototype: TModel;
198
91
  }, options: KeysetOptions<ModelAttributes<TModel>>): Promise<{
199
- meta: import("../pagination/index.ts").CursorPaginationMeta<KeysetCursor>;
92
+ meta: import("../pagination/index.ts").CursorPaginationMeta<import("../pagination/index.ts").KeysetCursor>;
200
93
  data: TModel[];
201
94
  }>;
202
95
  static cursorPaginate<TModel extends object>(this: {
@@ -0,0 +1,17 @@
1
+ type CastType = "date" | "datetime" | "json" | "bool" | "boolean" | "integer" | "int" | "hashed";
2
+ type LoadedAttributes = Record<string, unknown>;
3
+ type ModelCasts = Partial<Record<string, CastType>>;
4
+ declare function snapshotAttributes(values: LoadedAttributes): LoadedAttributes;
5
+ declare function changedAttributes(values: LoadedAttributes, original: LoadedAttributes): LoadedAttributes;
6
+ declare function hydrateValue(value: unknown, cast: CastType): unknown;
7
+ declare function dehydrateValue(value: unknown, cast: "hashed"): Promise<unknown>;
8
+ declare function dehydrateValue(value: unknown, cast: Exclude<CastType, "hashed">): unknown;
9
+ declare function dehydrateValue(value: unknown, cast: CastType): unknown;
10
+ declare function filterMassAssignable(fillable: readonly string[] | undefined, guarded: readonly string[] | true | undefined, input: LoadedAttributes): LoadedAttributes;
11
+ declare function applyCasts(values: LoadedAttributes, casts: ModelCasts, direction: "hydrate"): LoadedAttributes;
12
+ declare function applyCasts(values: LoadedAttributes, casts: ModelCasts, direction: "dehydrate"): Promise<LoadedAttributes>;
13
+ declare function applyCasts(values: LoadedAttributes, casts: ModelCasts, direction: "hydrate" | "dehydrate"): LoadedAttributes | Promise<LoadedAttributes>;
14
+ declare function applyTimestampsOnCreate(columns: readonly string[], values: LoadedAttributes, enabled: boolean): LoadedAttributes;
15
+ declare function applyTimestampsOnUpdate(columns: readonly string[], values: LoadedAttributes, enabled: boolean): LoadedAttributes;
16
+ export type { CastType, LoadedAttributes, ModelCasts };
17
+ export { applyCasts, applyTimestampsOnCreate, applyTimestampsOnUpdate, changedAttributes, dehydrateValue, filterMassAssignable, hydrateValue, snapshotAttributes, };
@@ -0,0 +1,139 @@
1
+ import type { CursorPaginatedResult, KeysetCursor, KeysetOptions } from "../pagination/index.ts";
2
+ import type BaseRepository from "./baseRepository.ts";
3
+ import type { Model } from "./model.ts";
4
+ import type { AnyRelationQuery } from "./relationQuery.ts";
5
+ import type { BelongsToManyRelation, BelongsToRelation, HasManyRelation, HasManyThroughRelation, MorphManyRelation, MorphOneRelation, MorphToRelation } from "./relationships.ts";
6
+ import type { RepositoryQuery } from "./repositoryQuery.ts";
7
+ import type { ModelWhere, QueryLockOptions, QueryOptions, QueryWhere } from "./types.ts";
8
+ type AnyModel = Model<Record<string, unknown>, "id">;
9
+ type ModelAttributes<TModel> = TModel extends {
10
+ toObject(): infer TRecord extends object;
11
+ } ? TRecord : Record<string, unknown>;
12
+ type ModelIdentifier<TModel> = TModel extends {
13
+ readonly id: infer TKey;
14
+ } ? TKey : unknown;
15
+ type WithModelCount<TModel, TCount extends string> = {
16
+ toObject(): Omit<ModelAttributes<TModel>, TCount> & Record<TCount, unknown>;
17
+ get<K extends keyof (Omit<ModelAttributes<TModel>, TCount> & Record<TCount, unknown>)>(key: K): (Omit<ModelAttributes<TModel>, TCount> & Record<TCount, unknown>)[K];
18
+ } & TModel;
19
+ type ModelQueryResult<TModel, TCounts extends string> = [TCounts] extends [never] ? TModel : WithModelCount<TModel, TCounts>;
20
+ type RelationNameInput = string | readonly string[];
21
+ declare function flattenRelationNames(relations: ReadonlyArray<RelationNameInput>): string[];
22
+ declare function loadNested(model: {
23
+ load: (...names: string[]) => Promise<unknown>;
24
+ loaded: (name: string) => unknown;
25
+ constructor: object;
26
+ getRepository: () => BaseRepository<Record<string, unknown>, "id">;
27
+ toObject: () => object;
28
+ setLoaded: (name: string, value: unknown) => unknown;
29
+ }, path: string): Promise<void>;
30
+ /** Read-only plain records; partial selection never acquires model mutation methods. */
31
+ declare class ModelProjection<TEntity extends object, K extends keyof TEntity & string> {
32
+ private readonly load;
33
+ private readonly page;
34
+ constructor(load: (limit?: number) => Promise<Array<Pick<TEntity, K>>>, page: (options: KeysetOptions<TEntity>) => Promise<CursorPaginatedResult<Pick<TEntity, K>, KeysetCursor>>);
35
+ keysetPaginate(options: KeysetOptions<TEntity>): Promise<CursorPaginatedResult<Pick<TEntity, K>, KeysetCursor>>;
36
+ get(): Promise<Array<Pick<TEntity, K>>>;
37
+ first(): Promise<Pick<TEntity, K> | null>;
38
+ }
39
+ declare class ModelQuery<TModel extends object = AnyModel, TCounts extends string = never> {
40
+ private readonly modelClass;
41
+ readonly query: RepositoryQuery<Record<string, unknown>, "id">;
42
+ private readonly eager;
43
+ constructor(modelClass: object, query: RepositoryQuery<Record<string, unknown>, "id">);
44
+ with(...relations: RelationNameInput[]): this;
45
+ where(input: ModelWhere<ModelAttributes<TModel>> | ((builder: import("./whereBuilder.ts").WhereBuilder<ModelAttributes<TModel>, ModelWhere<ModelAttributes<TModel>>>) => void)): this;
46
+ orWhere(input: ModelWhere<ModelAttributes<TModel>> | ((builder: import("./whereBuilder.ts").WhereBuilder<ModelAttributes<TModel>, ModelWhere<ModelAttributes<TModel>>>) => void)): this;
47
+ /** Qualified/dynamic filters retain existing SQL semantics through an explicit escape hatch. */
48
+ whereDynamic(input: QueryWhere<object>): this;
49
+ select<K extends keyof ModelAttributes<TModel> & string>(...columns: readonly K[]): ModelProjection<ModelAttributes<TModel>, K>;
50
+ lockForUpdate(options?: QueryLockOptions): this;
51
+ sharedLock(options?: QueryLockOptions): this;
52
+ orderBy(orderBy: QueryOptions<ModelAttributes<TModel>>["orderBy"]): this;
53
+ limit(limit: number): this;
54
+ offset(offset: number): this;
55
+ whereNull(column: keyof ModelAttributes<TModel> & string): this;
56
+ whereNotNull(column: keyof ModelAttributes<TModel> & string): this;
57
+ whereIn<K extends keyof ModelAttributes<TModel> & string>(column: K, values: readonly ModelAttributes<TModel>[K][]): this;
58
+ whereNotIn<K extends keyof ModelAttributes<TModel> & string>(column: K, values: readonly ModelAttributes<TModel>[K][]): this;
59
+ groupBy(groupBy: QueryOptions<object>["groupBy"]): this;
60
+ having(having: QueryWhere<object>): this;
61
+ join(left: `${string}.${string}`, right: `${string}.${string}`): this;
62
+ leftJoin(left: `${string}.${string}`, right: `${string}.${string}`): this;
63
+ paginate(options: {
64
+ page: number;
65
+ perPage: number;
66
+ }): Promise<{
67
+ data: ModelQueryResult<TModel, TCounts>[];
68
+ meta: Awaited<ReturnType<RepositoryQuery<Record<string, unknown>, "id">["paginate"]>>["meta"];
69
+ }>;
70
+ whereExists(sql: string, params?: readonly unknown[]): this;
71
+ whereNotExists(sql: string, params?: readonly unknown[]): this;
72
+ whereHas(name: string, constrain?: (query: AnyRelationQuery) => void): this;
73
+ has(name: string): this;
74
+ doesntHave(name: string): this;
75
+ whereDoesntHave(name: string, constrain?: (query: AnyRelationQuery) => void): this;
76
+ withHasMany<TChild extends object, LocalKey extends keyof Record<string, unknown> & string, ForeignKey extends keyof TChild & string, Alias extends string>(...args: [
77
+ as: Alias,
78
+ relation: HasManyRelation<Record<string, unknown>, TChild, LocalKey, ForeignKey>,
79
+ childRepository: BaseRepository<TChild, keyof TChild & string>,
80
+ options?: Omit<QueryOptions<TChild>, "where">
81
+ ]): this;
82
+ withBelongsTo<TParent extends object, ForeignKey extends keyof Record<string, unknown> & string, OwnerKey extends keyof TParent & string, Alias extends string>(...args: [
83
+ as: Alias,
84
+ relation: BelongsToRelation<Record<string, unknown>, TParent, ForeignKey, OwnerKey>,
85
+ parentRepository: BaseRepository<TParent, OwnerKey>,
86
+ options?: Omit<QueryOptions<TParent>, "where">
87
+ ]): this;
88
+ withBelongsToMany<TRelated extends object, Pivot extends object, ParentKey extends keyof Record<string, unknown> & string, RelatedKey extends keyof TRelated & string, ForeignPivotKey extends keyof Pivot & string, RelatedPivotKey extends keyof Pivot & string, Alias extends string>(...args: [
89
+ as: Alias,
90
+ relation: BelongsToManyRelation<Record<string, unknown>, TRelated, Pivot, ParentKey, RelatedKey, ForeignPivotKey, RelatedPivotKey>,
91
+ relatedRepository: BaseRepository<TRelated, RelatedKey>,
92
+ options?: Omit<QueryOptions<TRelated>, "where">
93
+ ]): this;
94
+ withMorphMany<TChild extends object, LocalKey extends keyof Record<string, unknown> & string, MorphTypeKey extends keyof TChild & string, MorphIdKey extends keyof TChild & string, Alias extends string>(...args: [
95
+ as: Alias,
96
+ relation: MorphManyRelation<Record<string, unknown>, TChild, LocalKey, MorphTypeKey, MorphIdKey>,
97
+ childRepository: BaseRepository<TChild, keyof TChild & string>,
98
+ options?: Omit<QueryOptions<TChild>, "where">
99
+ ]): this;
100
+ withMorphOne<TChild extends object, LocalKey extends keyof Record<string, unknown> & string, MorphTypeKey extends keyof TChild & string, MorphIdKey extends keyof TChild & string, Alias extends string>(...args: [
101
+ as: Alias,
102
+ relation: MorphOneRelation<Record<string, unknown>, TChild, LocalKey, MorphTypeKey, MorphIdKey>,
103
+ childRepository: BaseRepository<TChild, keyof TChild & string>,
104
+ options?: Omit<QueryOptions<TChild>, "where">
105
+ ]): this;
106
+ withMorphTo<TParent extends object, MorphTypeKey extends keyof Record<string, unknown> & string, MorphIdKey extends keyof Record<string, unknown> & string, Alias extends string>(...args: [
107
+ as: Alias,
108
+ relation: MorphToRelation<Record<string, unknown>, MorphTypeKey, MorphIdKey>,
109
+ repositoriesByType: ReadonlyMap<string, BaseRepository<TParent, keyof TParent & string>>,
110
+ options?: Omit<QueryOptions<TParent>, "where">,
111
+ optionsByType?: ReadonlyMap<string, QueryOptions<TParent>>
112
+ ]): this;
113
+ withHasManyThrough<TFar extends object, LocalKey extends keyof Record<string, unknown> & string, SecondKey extends keyof TFar & string, Alias extends string>(...args: [
114
+ as: Alias,
115
+ relation: HasManyThroughRelation<Record<string, unknown>, TFar, LocalKey, string, string, SecondKey>,
116
+ farRepository: BaseRepository<TFar, keyof TFar & string>,
117
+ options?: Omit<QueryOptions<TFar>, "where">
118
+ ]): this;
119
+ withTrashed(): this;
120
+ onlyTrashed(): this;
121
+ get(): Promise<ModelQueryResult<TModel, TCounts>[]>;
122
+ keysetPaginate(options: KeysetOptions<ModelAttributes<TModel>>): Promise<{
123
+ meta: import("../pagination/index.ts").CursorPaginationMeta<KeysetCursor>;
124
+ data: ModelQueryResult<TModel, TCounts>[];
125
+ }>;
126
+ private hydrateRows;
127
+ first(): Promise<ModelQueryResult<TModel, TCounts> | null>;
128
+ count(): Promise<number>;
129
+ pluck(column: string): Promise<unknown[]>;
130
+ pluck(column: string, keyBy: string): Promise<Map<unknown, unknown>>;
131
+ value(column: string): Promise<unknown>;
132
+ find(id: ModelIdentifier<TModel>): Promise<ModelQueryResult<TModel, TCounts> | null>;
133
+ findOrFail(id: ModelIdentifier<TModel>, errorFactory?: (id: unknown) => Error): Promise<ModelQueryResult<TModel, TCounts>>;
134
+ then(onfulfilled?: ((value: ModelQueryResult<TModel, TCounts>[]) => unknown) | null, onrejected?: ((reason: unknown) => unknown) | null): Promise<unknown>;
135
+ withCount<TName extends string, TAlias extends string = `${TName}_count`>(name: TName, alias?: TAlias): ModelQuery<TModel, TCounts | TAlias>;
136
+ private constrainExists;
137
+ }
138
+ export type { AnyModel, ModelAttributes, ModelIdentifier, RelationNameInput };
139
+ export { flattenRelationNames, loadNested, ModelProjection, ModelQuery };
@@ -0,0 +1,34 @@
1
+ import type BaseRepository from "./baseRepository.ts";
2
+ import type { Model } from "./model.ts";
3
+ import type { RepositoryQuery } from "./repositoryQuery.ts";
4
+ type GlobalScopeFn<TEntity extends object, PrimaryKey extends keyof TEntity & string> = (query: RepositoryQuery<TEntity, PrimaryKey>) => RepositoryQuery<TEntity, PrimaryKey>;
5
+ type AnyModel = Model<Record<string, unknown>, "id">;
6
+ type ModelObserver = {
7
+ retrieved?: (model: AnyModel) => unknown;
8
+ creating?: (model: AnyModel) => unknown;
9
+ created?: (model: AnyModel) => unknown;
10
+ updating?: (model: AnyModel) => unknown;
11
+ updated?: (model: AnyModel) => unknown;
12
+ saving?: (model: AnyModel) => unknown;
13
+ saved?: (model: AnyModel) => unknown;
14
+ deleting?: (model: AnyModel) => unknown;
15
+ deleted?: (model: AnyModel) => unknown;
16
+ };
17
+ declare function runObservers(model: AnyModel, hook: keyof ModelObserver): Promise<boolean>;
18
+ declare function nameModel(model: object): void;
19
+ declare function resolveModelRepository(model: object): BaseRepository<Record<string, unknown>, "id">;
20
+ /** Alias for `hasMany("Name")` when `Name` is not `constructor.name` or `$morphClass`. */
21
+ declare function registerModelClass(name: string, model: object): void;
22
+ declare function registerModelRepositoryFactory(model: object, factory: () => object): void;
23
+ declare function bindModelRepository(model: object, repository: BaseRepository<Record<string, unknown>, "id">): void;
24
+ declare function findNamedModel(name: string): object | undefined;
25
+ declare function getModelObservers(model: object): ModelObserver[] | undefined;
26
+ declare function restoreModelObservers(model: object, observers: ModelObserver[] | undefined): void;
27
+ declare function observeModel(model: object, observer: ModelObserver): void;
28
+ export type { ModelObserver };
29
+ export { bindModelRepository, findNamedModel, getModelObservers, nameModel, observeModel, registerModelClass, registerModelRepositoryFactory, resolveModelRepository, restoreModelObservers, runObservers, };
30
+ declare function ensureBooted(model: object): void;
31
+ declare function getGlobalScopes(model: object): GlobalScopeFn<Record<string, unknown>, "id">[];
32
+ declare function addModelGlobalScope<TEntity extends object, PrimaryKey extends keyof TEntity & string>(model: object, scope: GlobalScopeFn<TEntity, PrimaryKey>): void;
33
+ export type { GlobalScopeFn };
34
+ export { addModelGlobalScope, ensureBooted, getGlobalScopes };
@@ -1,5 +1,5 @@
1
- import type { DatabaseConnection } from "./baseRepository.ts";
2
1
  import { type ActiveDatabaseHandle } from "./connectionContext.ts";
2
+ import type { DatabaseConnection } from "./connectionContracts.ts";
3
3
  import { type ReadOnlyObservationOptions } from "./isolatedReadOnlyObservation.ts";
4
4
  type MysqlExecutable = {
5
5
  execute: (sql: string, params?: unknown[]) => Promise<[unknown, unknown]>;
@@ -1,3 +1,3 @@
1
- import type { SqlDatabaseConnection } from "./baseRepository";
1
+ import type { SqlDatabaseConnection } from "./connectionContracts";
2
2
  declare function createDatabaseQueryProxy(pool: SqlDatabaseConnection): SqlDatabaseConnection;
3
3
  export { createDatabaseQueryProxy };