@getstrata/core 2.2.48 → 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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
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
+
3
10
  ## 2.2.48
4
11
 
5
12
  - Validate complete integer environment values instead of accepting partial numeric strings; retain documented defaults, signs and minimum checks.
@@ -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 };
@@ -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 };
@@ -84,7 +84,6 @@ declare class BaseRepository<TEntity extends object, PrimaryKey extends keyof TE
84
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[]>>;
85
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[]>;
86
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[]>>;
87
- private buildThroughWhere;
88
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>>;
89
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[]>>;
90
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,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 };
@@ -0,0 +1,20 @@
1
+ import type { TableDefinition } from "./table.ts";
2
+ import type { QueryOptions } from "./types.ts";
3
+ declare function buildHasManyThroughQuery<TEntity extends object>(table: TableDefinition<TEntity>, relation: {
4
+ throughTable: string;
5
+ firstKey: string;
6
+ secondLocalKey: string;
7
+ secondKey: string;
8
+ throughParentKey?: string;
9
+ }, parentIds: readonly unknown[], options: QueryOptions<TEntity>): {
10
+ text: string;
11
+ params: unknown[];
12
+ };
13
+ declare function buildPivotLookupQuery(relation: {
14
+ pivotTable: string;
15
+ foreignPivotKey: string;
16
+ }, parentIds: readonly unknown[]): {
17
+ text: string;
18
+ params: readonly unknown[];
19
+ };
20
+ export { buildHasManyThroughQuery, buildPivotLookupQuery };
@@ -1,6 +1,6 @@
1
1
  type Middleware = (request: Request, next: () => Promise<Response>) => Promise<Response>;
2
- type RouteHandler<TRequest extends Request = Request> = (request: TRequest) => Response | Promise<Response>;
3
- declare function composeMiddleware(...middleware: Middleware[]): <TRequest extends Request = Request>(handler: RouteHandler<TRequest>) => RouteHandler<TRequest>;
2
+ type RouteHandler<TRequest extends Request = Request, TArguments extends unknown[] = []> = (request: TRequest, ...arguments_: TArguments) => Response | Promise<Response>;
3
+ declare function composeMiddleware(...middleware: Middleware[]): <TRequest extends Request = Request, TArguments extends unknown[] = []>(handler: RouteHandler<TRequest, TArguments>) => RouteHandler<TRequest, TArguments>;
4
4
  declare function requestIdMiddleware(request: Request, next: () => Promise<Response>): Promise<Response>;
5
5
  declare function wrapRouteHandler<T>(handler: T, middleware: Middleware[]): T;
6
6
  declare function applyMiddlewareToRoutes<T extends Record<string, unknown>>(routes: T, middleware: Middleware[]): T;
@@ -1,4 +1,4 @@
1
1
  import { type Middleware } from "./middleware";
2
2
  /** Middleware consumes native Request; composition preserves the handler's request subtype. */
3
- declare function withMiddleware(...middleware: Middleware[]): <TRequest extends Request = Request>(handler: import("./middleware").RouteHandler<TRequest>) => import("./middleware").RouteHandler<TRequest>;
3
+ declare function withMiddleware(...middleware: Middleware[]): <TRequest extends Request = Request, TArguments extends unknown[] = []>(handler: import("./middleware").RouteHandler<TRequest, TArguments>) => import("./middleware").RouteHandler<TRequest, TArguments>;
4
4
  export { withMiddleware };
@@ -1,4 +1,5 @@
1
1
  import type { TLSOptions } from "bun";
2
+ import { assertSafeSmtpAddress, assertSafeSmtpField, buildSmtpPayload, smtpEnvelopeAddress } from "./smtpMessage.ts";
2
3
  interface MailMessage {
3
4
  to: string;
4
5
  subject: string;
@@ -21,12 +22,8 @@ interface SmtpConfig {
21
22
  }
22
23
  type SmtpTransport = (config: SmtpConfig, message: MailMessage) => Promise<void>;
23
24
  declare function resolveSmtpConfig(): SmtpConfig;
24
- declare function assertSafeSmtpField(value: string, field: string): string;
25
- declare function smtpEnvelopeAddress(value: string, field: string): string;
26
- declare function assertSafeSmtpAddress(value: string, field: string): string;
27
25
  declare function redactMailBody(body: string): string;
28
26
  declare function defaultSmtpTransport(config: SmtpConfig, message: MailMessage): Promise<void>;
29
- declare function buildSmtpPayload(from: string, message: MailMessage): string;
30
27
  declare class LogMailDriver implements MailDriver {
31
28
  send(message: MailMessage): Promise<void>;
32
29
  }
@@ -0,0 +1,7 @@
1
+ import type { MailMessage } from "./mailer.ts";
2
+ declare function assertSafeSmtpField(value: string, field: string): string;
3
+ declare function smtpEnvelopeAddress(value: string, field: string): string;
4
+ declare function assertSafeSmtpAddress(value: string, field: string): string;
5
+ declare function encodeBase64(value: string): string;
6
+ declare function buildSmtpPayload(from: string, message: MailMessage): string;
7
+ export { assertSafeSmtpAddress, assertSafeSmtpField, buildSmtpPayload, encodeBase64, smtpEnvelopeAddress, };
@@ -0,0 +1,5 @@
1
+ declare const RESERVE_JOB = "\nlocal function checkType(key, expected)\n local actual = redis.call('TYPE', key).ok\n if actual ~= 'none' and actual ~= expected then\n return redis.error_reply('Unexpected queue key type: ' .. key)\n end\nend\nlocal function nowMs()\n local time = redis.call('TIME')\n return tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)\nend\n\nlocal err = checkType(KEYS[1], 'list') or checkType(KEYS[2], 'list') or checkType(KEYS[3], 'hash')\nif err then return err end\nlocal payload = redis.call('LINDEX', KEYS[1], -1)\nif not payload then return nil end\nlocal record = cjson.encode({strataReservation=1, id=ARGV[1], owner=ARGV[2], payload=payload})\nlocal lease = cjson.encode({owner=ARGV[2], expiresAt=nowMs()+tonumber(ARGV[3])})\nredis.call('LPUSH', KEYS[2], record)\nredis.call('HSET', KEYS[3], ARGV[1], lease)\nredis.call('RPOP', KEYS[1])\nreturn record\n";
2
+ declare const RENEW_OR_ACK = "\nlocal function checkType(key, expected)\n local actual = redis.call('TYPE', key).ok\n if actual ~= 'none' and actual ~= expected then\n return redis.error_reply('Unexpected queue key type: ' .. key)\n end\nend\nlocal function nowMs()\n local time = redis.call('TIME')\n return tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)\nend\n\nlocal err = checkType(KEYS[1], 'list') or checkType(KEYS[2], 'hash') or checkType(KEYS[3], 'list')\nif err then return err end\nlocal raw = redis.call('HGET', KEYS[2], ARGV[1])\nif not raw then return 0 end\nlocal ok, lease = pcall(cjson.decode, raw)\nlocal now = nowMs()\nif not ok or type(lease) ~= 'table' or lease.owner ~= ARGV[2] or not tonumber(lease.expiresAt) or tonumber(lease.expiresAt) <= now then\n return 0\nend\nif ARGV[4] == 'renew' then\n redis.call('HSET', KEYS[2], ARGV[1], cjson.encode({owner=ARGV[2], expiresAt=now+tonumber(ARGV[5])}))\n return 1\nend\nif ARGV[4] == 'quarantine' then redis.call('LPUSH', KEYS[3], ARGV[6]) end\nlocal removed = redis.call('LREM', KEYS[1], 1, ARGV[3])\nredis.call('HDEL', KEYS[2], ARGV[1])\nreturn removed\n";
3
+ declare const RECLAIM_JOBS = "\nlocal function checkType(key, expected)\n local actual = redis.call('TYPE', key).ok\n if actual ~= 'none' and actual ~= expected then\n return redis.error_reply('Unexpected queue key type: ' .. key)\n end\nend\nlocal function nowMs()\n local time = redis.call('TIME')\n return tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)\nend\n\nlocal err = checkType(KEYS[1], 'list') or checkType(KEYS[2], 'list') or checkType(KEYS[3], 'hash')\nif err then return err end\nlocal now = nowMs()\nlocal reclaimed = 0\nfor _, record in ipairs(redis.call('LRANGE', KEYS[2], 0, -1)) do\n local payload, field = record, record\n local modern = false\n local ok, reservation = pcall(cjson.decode, record)\n if ok and type(reservation) == 'table' and reservation.strataReservation == 1 then\n payload, field, modern = reservation.payload, reservation.id, true\n end\n local raw = redis.call('HGET', KEYS[3], field)\n local expired = true\n if raw then\n if modern then\n local leaseOk, lease = pcall(cjson.decode, raw)\n expired = not leaseOk or type(lease) ~= 'table' or not tonumber(lease.expiresAt) or tonumber(lease.expiresAt) <= now\n else\n local reservedAt = tonumber(raw)\n expired = not reservedAt or now - reservedAt >= tonumber(ARGV[1])\n end\n end\n if expired then\n redis.call('LPUSH', KEYS[1], payload)\n redis.call('LREM', KEYS[2], 1, record)\n redis.call('HDEL', KEYS[3], field)\n reclaimed = reclaimed + 1\n end\nend\nreturn reclaimed\n";
4
+ declare const POLL_LIST_PRIORITIES = "\nlocal function checkType(key, expected)\n local actual = redis.call('TYPE', key).ok\n if actual ~= 'none' and actual ~= expected then\n return redis.error_reply('Unexpected queue key type: ' .. key)\n end\nend\nlocal function nowMs()\n local time = redis.call('TIME')\n return tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)\nend\n\nlocal owner = ARGV[1]\nlocal visibility = ARGV[2]\nlocal reservationId = ARGV[3]\nlocal reclaim = ARGV[4] == '1'\nlocal function reclaimQueue(listKey, processingKey, leaseKey)\n local err = checkType(listKey, 'list') or checkType(processingKey, 'list') or checkType(leaseKey, 'hash')\n if err then return err end\n local now = nowMs()\n for _, record in ipairs(redis.call('LRANGE', processingKey, 0, -1)) do\n local payload, field = record, record\n local modern = false\n local ok, reservation = pcall(cjson.decode, record)\n if ok and type(reservation) == 'table' and reservation.strataReservation == 1 then\n payload, field, modern = reservation.payload, reservation.id, true\n end\n local raw = redis.call('HGET', leaseKey, field)\n local expired = true\n if raw then\n if modern then\n local leaseOk, lease = pcall(cjson.decode, raw)\n expired = not leaseOk or type(lease) ~= 'table' or not tonumber(lease.expiresAt) or tonumber(lease.expiresAt) <= now\n else\n local reservedAt = tonumber(raw)\n expired = not reservedAt or now - reservedAt >= tonumber(visibility)\n end\n end\n if expired then\n redis.call('LPUSH', listKey, payload)\n redis.call('LREM', processingKey, 1, record)\n redis.call('HDEL', leaseKey, field)\n end\n end\nend\nlocal function reserveQueue(listKey, processingKey, leaseKey)\n local err = checkType(listKey, 'list') or checkType(processingKey, 'list') or checkType(leaseKey, 'hash')\n if err then return err end\n local payload = redis.call('LINDEX', listKey, -1)\n if not payload then return nil end\n local record = cjson.encode({strataReservation=1, id=reservationId, owner=owner, payload=payload})\n local lease = cjson.encode({owner=owner, expiresAt=nowMs()+tonumber(visibility)})\n redis.call('LPUSH', processingKey, record)\n redis.call('HSET', leaseKey, reservationId, lease)\n redis.call('RPOP', listKey)\n return record\nend\nlocal count = #KEYS / 3\nif reclaim then\n for i = 1, count do\n local err = reclaimQueue(KEYS[(i - 1) * 3 + 1], KEYS[(i - 1) * 3 + 2], KEYS[(i - 1) * 3 + 3])\n if err then return err end\n end\nend\nfor i = 1, count do\n local record = reserveQueue(KEYS[(i - 1) * 3 + 1], KEYS[(i - 1) * 3 + 2], KEYS[(i - 1) * 3 + 3])\n if type(record) == 'string' then return {'1', tostring(i), record} end\n if record then return record end\nend\nreturn {'0'}\n";
5
+ export { POLL_LIST_PRIORITIES, RECLAIM_JOBS, RENEW_OR_ACK, RESERVE_JOB };
@@ -0,0 +1,11 @@
1
+ declare const ENQUEUE_CONTROLLED = "\nlocal kind = redis.call('TYPE', KEYS[1]).ok\nif kind ~= 'none' and kind ~= 'stream' then return redis.error_reply('Invalid stream admission key type') end\nif redis.call('EXISTS', KEYS[2]) ~= 0 then return redis.error_reply('Streams control identity already exists') end\nredis.call('XADD', KEYS[1], '*', 'payload', ARGV[1])\nredis.call('HSET', KEYS[2], 'state', 'active')\nreturn 1\n";
2
+ declare const CANCEL_STREAM = "\nlocal state = redis.call('HGET', KEYS[1], 'state')\nif not state then return 0 end\nlocal kind = redis.call('TYPE', KEYS[2]).ok\nif kind ~= 'none' and kind ~= 'zset' then return redis.error_reply('Invalid stream retry key type') end\nlocal payload = redis.call('HGET', KEYS[1], 'retryPayload')\nif payload and redis.call('ZSCORE', KEYS[2], payload) then redis.call('ZADD', KEYS[2], 0, payload) end\nredis.call('HSET', KEYS[1], 'state', 'cancelled')\nreturn 1\n";
3
+ declare const SCHEDULE_RETRY = "\nlocal pending = redis.call('XPENDING', KEYS[1], ARGV[1], ARGV[2], ARGV[2], 1)\nif #pending == 0 or pending[1][2] ~= ARGV[3] or tonumber(pending[1][3]) >= tonumber(ARGV[4]) then return 0 end\nlocal kind = redis.call('TYPE', KEYS[2]).ok\nif kind ~= 'none' and kind ~= 'zset' then return redis.error_reply('Invalid stream retry key type') end\nif ARGV[8] == '1' then\n local state = redis.call('HGET', KEYS[3], 'state')\n if state == 'cancelled' then return redis.error_reply('Streams job cancelled') end\n if state ~= 'active' then return redis.error_reply('Missing or invalid Streams control state') end\nend\nlocal now = redis.call('TIME')\nlocal due = tonumber(now[1])*1000 + math.floor(tonumber(now[2])/1000) + tonumber(ARGV[5])\nif ARGV[7] ~= '' then due = math.min(due, tonumber(ARGV[7])) end\nredis.call('ZADD', KEYS[2], due, ARGV[6])\nif ARGV[8] == '1' then redis.call('HSET', KEYS[3], 'retryPayload', ARGV[6]) end\nredis.call('XACK', KEYS[1], ARGV[1], ARGV[2])\nredis.call('XDEL', KEYS[1], ARGV[2])\nif #redis.call('XPENDING', KEYS[1], ARGV[1], '-', '+', 1, ARGV[3]) == 0 then redis.call('XGROUP', 'DELCONSUMER', KEYS[1], ARGV[1], ARGV[3]) end\nreturn 1\n";
4
+ declare const PROMOTE_RETRIES = "\nlocal kinds = {'stream','zset'}\nfor i=1,2 do\n local kind = redis.call('TYPE', KEYS[i]).ok\n if kind ~= 'none' and kind ~= kinds[i] then return redis.error_reply('Invalid stream retry promotion key type') end\nend\nlocal now = redis.call('TIME')\nlocal due = tonumber(now[1])*1000 + math.floor(tonumber(now[2])/1000)\nlocal entries = redis.call('ZRANGE', KEYS[2], '-inf', due, 'BYSCORE', 'LIMIT', 0, 100)\nfor _, payload in ipairs(entries) do\n redis.call('XADD', KEYS[1], '*', 'payload', payload)\n redis.call('ZREM', KEYS[2], payload)\nend\nreturn #entries\n";
5
+ declare const POLL_STREAM_PRIORITIES = "\nlocal group = ARGV[1]\nlocal owner = ARGV[2]\nlocal visibility = ARGV[3]\nlocal function payloadOf(fields)\n for index = 1, #fields, 2 do\n if fields[index] == 'payload' and type(fields[index + 1]) == 'string' then return fields[index + 1] end\n end\n return ''\nend\nlocal cursors = {}\nfor i = 1, #KEYS / 2 do cursors[i] = ARGV[3 + i] end\nfor i = 1, #KEYS / 2 do\n local stream = KEYS[(i - 1) * 2 + 1]\n local retries = KEYS[(i - 1) * 2 + 2]\n local cursor = ARGV[3 + i]\n local streamKind = redis.call('TYPE', stream).ok\n local retryKind = redis.call('TYPE', retries).ok\n if streamKind ~= 'none' and streamKind ~= 'stream' then return redis.error_reply('Invalid stream retry promotion key type') end\n if retryKind ~= 'none' and retryKind ~= 'zset' then return redis.error_reply('Invalid stream retry promotion key type') end\n if streamKind == 'stream' then\n local now = redis.call('TIME')\n local due = tonumber(now[1]) * 1000 + math.floor(tonumber(now[2]) / 1000)\n local ready = redis.call('ZRANGE', retries, '-inf', due, 'BYSCORE', 'LIMIT', 0, 100)\n for _, payload in ipairs(ready) do\n redis.call('XADD', stream, '*', 'payload', payload)\n redis.call('ZREM', retries, payload)\n end\n local window = redis.call('XPENDING', stream, group, cursor, '+', 10)\n local claimed = redis.call('XAUTOCLAIM', stream, group, owner, visibility, cursor, 'COUNT', 1)\n for _, entry in ipairs(window) do\n if entry[2] ~= owner and #redis.call('XPENDING', stream, group, '-', '+', 1, entry[2]) == 0 then\n redis.call('XGROUP', 'DELCONSUMER', stream, group, entry[2])\n end\n end\n if #redis.call('XPENDING', stream, group, '-', '+', 1, owner) == 0 then\n redis.call('XGROUP', 'DELCONSUMER', stream, group, owner)\n end\n cursors[i] = claimed[1]\n if #claimed[2] > 0 then\n return {'1', tostring(i), claimed[2][1][1], payloadOf(claimed[2][1][2]), unpack(cursors)}\n end\n local fresh = redis.call('XREADGROUP', 'GROUP', group, owner, 'COUNT', 1, 'STREAMS', stream, '>')\n if not fresh and #redis.call('XPENDING', stream, group, '-', '+', 1, owner) == 0 then\n redis.call('XGROUP', 'DELCONSUMER', stream, group, owner)\n end\n if fresh and #fresh > 0 and #fresh[1][2] > 0 then\n return {'1', tostring(i), fresh[1][2][1][1], payloadOf(fresh[1][2][1][2]), unpack(cursors)}\n end\n end\nend\nreturn {'0', unpack(cursors)}\n";
6
+ declare const ASSERT_DRAINED = "\nif redis.call('LLEN', KEYS[1]) > 0 or redis.call('LLEN', KEYS[2]) > 0 or redis.call('HLEN', KEYS[3]) > 0 then\n return redis.error_reply('Legacy queue state requires maintenance conversion before Streams activation')\nend\nreturn 1\n";
7
+ declare const UPDATE_STREAM = "\nlocal pending = redis.call('XPENDING', KEYS[1], ARGV[1], ARGV[2], ARGV[2], 1)\nif #pending == 0 or pending[1][2] ~= ARGV[3] or tonumber(pending[1][3]) >= tonumber(ARGV[4]) then return 0 end\nif ARGV[7] == '1' then\n local kind = redis.call('TYPE', KEYS[3]).ok\n if kind ~= 'none' and kind ~= 'hash' then return redis.error_reply('Invalid stream control key type') end\nend\nif ARGV[5] == 'renew' then\n local claimed = redis.call('XCLAIM', KEYS[1], ARGV[1], ARGV[3], 0, ARGV[2], 'JUSTID')\n return #claimed\nend\nif ARGV[5] == 'quarantine' then\n local kind = redis.call('TYPE', KEYS[2]).ok\n if kind ~= 'none' and kind ~= 'stream' then return redis.error_reply('Invalid stream quarantine key type') end\n redis.call('XADD', KEYS[2], '*', 'sourceId', ARGV[2], 'payload', ARGV[6])\nend\nlocal acknowledged = redis.call('XACK', KEYS[1], ARGV[1], ARGV[2])\nif acknowledged == 1 then\n redis.call('XDEL', KEYS[1], ARGV[2])\n if ARGV[7] == '1' then redis.call('DEL', KEYS[3]) end\nend\nif #redis.call('XPENDING', KEYS[1], ARGV[1], '-', '+', 1, ARGV[3]) == 0 then redis.call('XGROUP', 'DELCONSUMER', KEYS[1], ARGV[1], ARGV[3]) end\nreturn acknowledged\n";
8
+ declare const CLAIM_STREAM = "\nlocal window = redis.call('XPENDING', KEYS[1], ARGV[1], ARGV[4], '+', 10)\nlocal claimed = redis.call('XAUTOCLAIM', KEYS[1], ARGV[1], ARGV[2], ARGV[3], ARGV[4], 'COUNT', 1)\nfor _, entry in ipairs(window) do\n if entry[2] ~= ARGV[2] and #redis.call('XPENDING', KEYS[1], ARGV[1], '-', '+', 1, entry[2]) == 0 then redis.call('XGROUP', 'DELCONSUMER', KEYS[1], ARGV[1], entry[2]) end\nend\nif #redis.call('XPENDING', KEYS[1], ARGV[1], '-', '+', 1, ARGV[2]) == 0 then redis.call('XGROUP', 'DELCONSUMER', KEYS[1], ARGV[1], ARGV[2]) end\nreturn claimed\n";
9
+ declare const READ_STREAM = "\nlocal entries = redis.call('XREADGROUP', 'GROUP', ARGV[1], ARGV[2], 'COUNT', 1, 'STREAMS', KEYS[1], '>')\nif not entries and #redis.call('XPENDING', KEYS[1], ARGV[1], '-', '+', 1, ARGV[2]) == 0 then redis.call('XGROUP', 'DELCONSUMER', KEYS[1], ARGV[1], ARGV[2]) end\nreturn entries\n";
10
+ declare const CONVERT_LIST = "\nlocal kinds = {'list','list','hash','stream'}\nfor i=1,4 do\n local kind = redis.call('TYPE', KEYS[i]).ok\n if kind ~= 'none' and kind ~= kinds[i] then return redis.error_reply('Invalid queue conversion key type') end\nend\nif redis.call('LLEN', KEYS[2]) > 0 or redis.call('HLEN', KEYS[3]) > 0 then return redis.error_reply('Drain or recover processing reservations before queue conversion') end\nlocal converted = 0\nfor i=1,tonumber(ARGV[1]) do\n local payload = redis.call('LINDEX', KEYS[1], -1)\n if not payload then break end\n redis.call('XADD', KEYS[4], '*', 'payload', payload)\n redis.call('RPOP', KEYS[1])\n converted = converted + 1\nend\nreturn converted\n";
11
+ export { ASSERT_DRAINED, CANCEL_STREAM, CLAIM_STREAM, CONVERT_LIST, ENQUEUE_CONTROLLED, POLL_STREAM_PRIORITIES, PROMOTE_RETRIES, READ_STREAM, SCHEDULE_RETRY, UPDATE_STREAM, };
@@ -0,0 +1,2 @@
1
+ declare const LEASE_SCRIPT = "\nfor _, key in ipairs(KEYS) do\n local kind = redis.call('TYPE', key).ok\n if kind ~= 'none' and kind ~= 'string' then return redis.error_reply('Unexpected scheduler key type') end\nend\nlocal action = ARGV[1]\nlocal token = ARGV[2]\nlocal ttl = tonumber(ARGV[3])\nif action == 'acquire' then\n if redis.call('EXISTS', KEYS[3]) == 1 or redis.call('EXISTS', KEYS[1]) == 1 or redis.call('EXISTS', KEYS[2]) == 1 then return 0 end\n redis.call('SET', KEYS[1], token, 'PX', ttl)\n redis.call('SET', KEYS[2], token, 'PX', ttl)\n return 1\nend\nif redis.call('GET', KEYS[1]) ~= token or redis.call('GET', KEYS[2]) ~= token then return 0 end\nif action == 'renew' then\n redis.call('PEXPIRE', KEYS[1], ttl)\n redis.call('PEXPIRE', KEYS[2], ttl)\nelseif action == 'complete' then\n redis.call('SET', KEYS[3], 'completed', 'PX', ttl)\n redis.call('DEL', KEYS[1], KEYS[2])\nelseif action == 'release' then\n redis.call('DEL', KEYS[1], KEYS[2])\nelse return redis.error_reply('Unexpected scheduler action') end\nreturn 1\n";
2
+ export { LEASE_SCRIPT };