@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
@@ -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,4 +1,4 @@
1
- import type { SqlDatabaseConnection } from "./baseRepository";
1
+ import type { SqlDatabaseConnection } from "./connectionContracts";
2
2
  declare function resolveRepositoryConnection(): SqlDatabaseConnection;
3
3
  declare const repositoryConnection: SqlDatabaseConnection;
4
4
  export { repositoryConnection, resolveRepositoryConnection };
@@ -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 SqliteConnection = ActiveDatabaseHandle & {
5
5
  begin<T>(callback: (transaction: ActiveDatabaseHandle) => Promise<T>): Promise<T>;
@@ -1,6 +1,6 @@
1
1
  import { afterCommit } from "../events/deferredModelEvents.ts";
2
2
  import { type TransactionAcquisitionMetrics } from "./acquisitionMetrics.ts";
3
- import type { DatabaseConnection } from "./baseRepository.ts";
3
+ import type { DatabaseConnection } from "./connectionContracts.ts";
4
4
  import { hasActiveTransaction, requestTransactionRollback } from "./transactionControl.ts";
5
5
  /** Recognizes the callback handle without admitting an unrelated pool. */
6
6
  declare function isActiveTransactionConnection(connection: DatabaseConnection): boolean;
@@ -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 };
@@ -913,9 +913,6 @@ var init_databaseTenantContext = __esm(() => {
913
913
  init_tenancyConfig();
914
914
  });
915
915
 
916
- // ../../src/core/audit/exportAuditLogs.ts
917
- import { repositoryConnection as db } from "@getstrata/core/database/repositoryConnection";
918
-
919
916
  // ../../src/core/runtime/appEnv.ts
920
917
  var NON_PRODUCTION_APP_ENVS = new Set(["local", "development", "dev", "test", "testing", "ci"]);
921
918
  function normalizeEnvValue(value) {
@@ -1338,8 +1335,39 @@ function assertSafeOutboundUrl(rawUrl, options = {}) {
1338
1335
  return parsed;
1339
1336
  }
1340
1337
 
1341
- // ../../src/core/audit/exportAuditLogs.ts
1338
+ // ../../src/core/audit/exportStore.ts
1342
1339
  init_databaseTenantContext();
1340
+ import { repositoryConnection as db } from "@getstrata/core/database/repositoryConnection";
1341
+ async function readPendingAuditLogs(batchSize) {
1342
+ return await runWithMigrationBypass(async () => {
1343
+ return await db`
1344
+ SELECT
1345
+ id,
1346
+ user_id,
1347
+ action,
1348
+ subject_type,
1349
+ subject_id,
1350
+ payload,
1351
+ ip_address,
1352
+ user_agent,
1353
+ checksum,
1354
+ tenant_id,
1355
+ trace_id,
1356
+ created_at
1357
+ FROM audit_log
1358
+ WHERE exported_at IS NULL
1359
+ ORDER BY id
1360
+ LIMIT ${batchSize}
1361
+ `;
1362
+ });
1363
+ }
1364
+ async function acknowledgeAuditLogs(ids) {
1365
+ await runWithMigrationBypass(async () => {
1366
+ for (const id of ids) {
1367
+ await db`UPDATE audit_log SET exported_at = NOW() WHERE id = ${id}`;
1368
+ }
1369
+ });
1370
+ }
1343
1371
 
1344
1372
  // ../../src/core/audit/siemFormatter.ts
1345
1373
  function formatSiemAuditEvent(input) {
@@ -1393,61 +1421,38 @@ async function exportPendingAuditLogs() {
1393
1421
  if (!config) {
1394
1422
  return 0;
1395
1423
  }
1396
- return await runWithMigrationBypass(async () => {
1397
- const rows = await db`
1398
- SELECT
1399
- id,
1400
- user_id,
1401
- action,
1402
- subject_type,
1403
- subject_id,
1404
- payload,
1405
- ip_address,
1406
- user_agent,
1407
- checksum,
1408
- tenant_id,
1409
- trace_id,
1410
- created_at
1411
- FROM audit_log
1412
- WHERE exported_at IS NULL
1413
- ORDER BY id
1414
- LIMIT ${config.batchSize}
1415
- `;
1416
- if (rows.length === 0) {
1417
- return 0;
1418
- }
1419
- const events = rows.map((row) => formatSiemAuditEvent({
1420
- action: row.action,
1421
- subject_type: row.subject_type,
1422
- subject_id: row.subject_id,
1423
- user_id: row.user_id,
1424
- tenant_id: row.tenant_id,
1425
- trace_id: row.trace_id,
1426
- ip_address: row.ip_address,
1427
- user_agent: row.user_agent,
1428
- checksum: row.checksum,
1429
- payload: row.payload,
1430
- created_at: row.created_at
1431
- }));
1432
- const body = config.format === "cef" ? events.map((event) => formatCefLine(event)).join(`
1424
+ const rows = await readPendingAuditLogs(config.batchSize);
1425
+ if (rows.length === 0) {
1426
+ return 0;
1427
+ }
1428
+ const events = rows.map((row) => formatSiemAuditEvent({
1429
+ action: row.action,
1430
+ subject_type: row.subject_type,
1431
+ subject_id: row.subject_id,
1432
+ user_id: row.user_id,
1433
+ tenant_id: row.tenant_id,
1434
+ trace_id: row.trace_id,
1435
+ ip_address: row.ip_address,
1436
+ user_agent: row.user_agent,
1437
+ checksum: row.checksum,
1438
+ payload: row.payload,
1439
+ created_at: row.created_at
1440
+ }));
1441
+ const body = config.format === "cef" ? events.map((event) => formatCefLine(event)).join(`
1433
1442
  `) : JSON.stringify({ events });
1434
- const response = await safeFetch(config.endpoint, {
1435
- method: "POST",
1436
- headers: {
1437
- "content-type": config.format === "cef" ? "text/plain" : "application/json",
1438
- ...process.env.SIEM_EXPORT_TOKEN ? { authorization: `Bearer ${process.env.SIEM_EXPORT_TOKEN}` } : {}
1439
- },
1440
- body
1441
- }, { allowHttp: appEnv() !== "production" });
1442
- if (!response.ok) {
1443
- throw new Error(`SIEM export failed with status ${response.status}.`);
1444
- }
1445
- const ids = rows.map((row) => row.id);
1446
- for (const id of ids) {
1447
- await db`UPDATE audit_log SET exported_at = NOW() WHERE id = ${id}`;
1448
- }
1449
- return rows.length;
1450
- });
1443
+ const response = await safeFetch(config.endpoint, {
1444
+ method: "POST",
1445
+ headers: {
1446
+ "content-type": config.format === "cef" ? "text/plain" : "application/json",
1447
+ ...process.env.SIEM_EXPORT_TOKEN ? { authorization: `Bearer ${process.env.SIEM_EXPORT_TOKEN}` } : {}
1448
+ },
1449
+ body
1450
+ }, { allowHttp: appEnv() !== "production" });
1451
+ if (!response.ok) {
1452
+ throw new Error(`SIEM export failed with status ${response.status}.`);
1453
+ }
1454
+ await acknowledgeAuditLogs(rows.map((row) => row.id));
1455
+ return rows.length;
1451
1456
  }
1452
1457
  export {
1453
1458
  exportPendingAuditLogs,
@@ -924,6 +924,7 @@ class ServiceContainer {
924
924
  services = new Map;
925
925
  singletonFactories = new Map;
926
926
  bindings = new Map;
927
+ resolutionPath = [];
927
928
  set(key, value) {
928
929
  this.singletonFactories.delete(key);
929
930
  this.bindings.delete(key);
@@ -946,16 +947,27 @@ class ServiceContainer {
946
947
  }
947
948
  const singletonFactory = this.singletonFactories.get(key);
948
949
  if (singletonFactory) {
949
- const value = singletonFactory(this);
950
+ const value = this.resolveFactory(key, singletonFactory);
950
951
  this.services.set(key, value);
951
952
  return value;
952
953
  }
953
954
  const binding = this.bindings.get(key);
954
955
  if (binding) {
955
- return binding(this);
956
+ return this.resolveFactory(key, binding);
956
957
  }
957
958
  throw new Error(`Service "${key}" is not registered.`);
958
959
  }
960
+ resolveFactory(key, factory) {
961
+ if (this.resolutionPath.includes(key)) {
962
+ throw new Error(`Circular service dependency: ${[...this.resolutionPath, key].join(" -> ")}.`);
963
+ }
964
+ this.resolutionPath.push(key);
965
+ try {
966
+ return factory(this);
967
+ } finally {
968
+ this.resolutionPath.pop();
969
+ }
970
+ }
959
971
  resolve(key) {
960
972
  return this.get(key);
961
973
  }
@@ -10,6 +10,7 @@ class ServiceContainer {
10
10
  services = new Map;
11
11
  singletonFactories = new Map;
12
12
  bindings = new Map;
13
+ resolutionPath = [];
13
14
  set(key, value) {
14
15
  this.singletonFactories.delete(key);
15
16
  this.bindings.delete(key);
@@ -32,16 +33,27 @@ class ServiceContainer {
32
33
  }
33
34
  const singletonFactory = this.singletonFactories.get(key);
34
35
  if (singletonFactory) {
35
- const value = singletonFactory(this);
36
+ const value = this.resolveFactory(key, singletonFactory);
36
37
  this.services.set(key, value);
37
38
  return value;
38
39
  }
39
40
  const binding = this.bindings.get(key);
40
41
  if (binding) {
41
- return binding(this);
42
+ return this.resolveFactory(key, binding);
42
43
  }
43
44
  throw new Error(`Service "${key}" is not registered.`);
44
45
  }
46
+ resolveFactory(key, factory) {
47
+ if (this.resolutionPath.includes(key)) {
48
+ throw new Error(`Circular service dependency: ${[...this.resolutionPath, key].join(" -> ")}.`);
49
+ }
50
+ this.resolutionPath.push(key);
51
+ try {
52
+ return factory(this);
53
+ } finally {
54
+ this.resolutionPath.pop();
55
+ }
56
+ }
45
57
  resolve(key) {
46
58
  return this.get(key);
47
59
  }
@@ -26,7 +26,7 @@ function createAsyncContextStore(key) {
26
26
  }
27
27
  var init_asyncContextStore = () => {};
28
28
 
29
- // ../../src/core/auth/membershipService.ts
29
+ // ../../src/core/auth/membershipServiceImplementation.ts
30
30
  import { resolveMembershipLookup } from "@getstrata/core/auth/membershipContext";
31
31
  import { ForbiddenError as ForbiddenError2 } from "@getstrata/core/errors/http";
32
32
 
@@ -71,17 +71,7 @@ function resolveUserId(user) {
71
71
  return userId;
72
72
  }
73
73
 
74
- // ../../src/core/auth/resolveMembershipService.ts
75
- import { resolveApplicationDependencies } from "@getstrata/core/runtime/applicationRegistry";
76
- function resolveMembershipService() {
77
- const dependencies = resolveApplicationDependencies();
78
- if (dependencies.container.has("core.membership")) {
79
- return dependencies.container.resolve("core.membership");
80
- }
81
- return new membershipService_default;
82
- }
83
-
84
- // ../../src/core/auth/membershipService.ts
74
+ // ../../src/core/auth/membershipServiceImplementation.ts
85
75
  class MembershipService {
86
76
  members;
87
77
  constructor(members = resolveMembershipLookup()) {
@@ -138,8 +128,17 @@ class MembershipService {
138
128
  return this.members.updateMemberRole(organizationId, userId, role);
139
129
  }
140
130
  }
141
- var membershipService_default = MembershipService;
131
+ var membershipServiceImplementation_default = MembershipService;
132
+ // ../../src/core/auth/resolveMembershipService.ts
133
+ import { resolveApplicationDependencies } from "@getstrata/core/runtime/applicationRegistry";
134
+ function resolveMembershipService() {
135
+ const dependencies = resolveApplicationDependencies();
136
+ if (dependencies.container.has("core.membership")) {
137
+ return dependencies.container.resolve("core.membership");
138
+ }
139
+ return new membershipServiceImplementation_default;
140
+ }
142
141
  export {
143
- membershipService_default as default,
142
+ membershipServiceImplementation_default as default,
144
143
  resolveMembershipService
145
144
  };
@@ -1782,6 +1782,33 @@ function buildConditionalWriteQuery(table, operation, changes, options, returnin
1782
1782
  };
1783
1783
  }
1784
1784
 
1785
+ // ../../src/core/database/relationQueries.ts
1786
+ init_dialect();
1787
+ function buildThroughWhere(table, options, parentIds) {
1788
+ const parameters = [...parentIds];
1789
+ const { clause } = buildQueryWhereClause(table, options, options.whereNodes, parameters);
1790
+ return {
1791
+ text: clause ? ` AND (${clause.replace(/^ WHERE /, "")})` : "",
1792
+ params: parameters.slice(parentIds.length)
1793
+ };
1794
+ }
1795
+ function buildHasManyThroughQuery(table, relation, parentIds, options) {
1796
+ const throughParentKey = relation.throughParentKey ?? "__through_parent_id";
1797
+ const farTable = table.name;
1798
+ const columns = table.columns.map((column) => `${qualifyColumn(farTable, column)}`).join(", ");
1799
+ const placeholders = parentIds.map((_, index) => currentSqlDialect().placeholder(index + 1)).join(", ");
1800
+ const { text: extraWhere, params: extraParams } = buildThroughWhere(table, options, parentIds);
1801
+ const sql = `SELECT ${columns}, ${qualifyColumn(relation.throughTable, relation.firstKey)} AS ${throughParentKey} FROM ${quoteIdentifier(farTable)} INNER JOIN ${quoteIdentifier(relation.throughTable)} ON ${qualifyColumn(relation.throughTable, relation.secondLocalKey)} = ${qualifyColumn(farTable, relation.secondKey)}${buildJoinClause(options.joins)} WHERE ${qualifyColumn(relation.throughTable, relation.firstKey)} IN (${placeholders})${extraWhere}`;
1802
+ return { text: sql, params: [...parentIds, ...extraParams] };
1803
+ }
1804
+ function buildPivotLookupQuery(relation, parentIds) {
1805
+ const placeholders = parentIds.map((_, index) => currentSqlDialect().placeholder(index + 1)).join(", ");
1806
+ return {
1807
+ text: `SELECT * FROM ${relation.pivotTable} WHERE ${String(relation.foreignPivotKey)} IN (${placeholders})`,
1808
+ params: parentIds
1809
+ };
1810
+ }
1811
+
1785
1812
  // ../../src/core/database/relationships.ts
1786
1813
  function hasMany(definition) {
1787
1814
  return {
@@ -2990,6 +3017,9 @@ class BaseRepository {
2990
3017
  return order.direction;
2991
3018
  }
2992
3019
  withConnection(connection) {
3020
+ return this.cloneWithConnection(connection);
3021
+ }
3022
+ cloneWithConnection(connection) {
2993
3023
  const clone = Object.create(Object.getPrototypeOf(this));
2994
3024
  Object.assign(clone, this);
2995
3025
  clone.connection = connection;
@@ -3085,26 +3115,10 @@ class BaseRepository {
3085
3115
  throw new Error("A related model scope joins the through table twice; use an explicitly aliased correlated predicate instead.");
3086
3116
  }
3087
3117
  const parentIds = [...new Set(parents.map((parent) => parent[relation.localKey]))];
3088
- const throughParentKey = relation.throughParentKey ?? "__through_parent_id";
3089
- const farTable = this.table.name;
3090
- const columns = this.table.columns.map((column) => `${qualifyColumn(farTable, column)}`).join(", ");
3091
- const placeholders = parentIds.map((_, index) => currentSqlDialect().placeholder(index + 1)).join(", ");
3092
- const { text: extraWhere, params: extraParams } = this.buildThroughWhere(options, parentIds);
3093
- const sql = `SELECT ${columns}, ${qualifyColumn(relation.throughTable, relation.firstKey)} AS ${throughParentKey} FROM ${quoteIdentifier(farTable)} INNER JOIN ${quoteIdentifier(relation.throughTable)} ON ${qualifyColumn(relation.throughTable, relation.secondLocalKey)} = ${qualifyColumn(farTable, relation.secondKey)}${buildJoinClause(options.joins)} WHERE ${qualifyColumn(relation.throughTable, relation.firstKey)} IN (${placeholders})${extraWhere}`;
3094
- const children = await this.connection.unsafe(sql, [
3095
- ...parentIds,
3096
- ...extraParams
3097
- ]);
3118
+ const { text, params } = buildHasManyThroughQuery(this.table, relation, parentIds, options);
3119
+ const children = await this.connection.unsafe(text, params);
3098
3120
  return indexHasManyThroughRelation(parents, children, relation);
3099
3121
  }
3100
- buildThroughWhere(options, parentIds) {
3101
- const parameters = [...parentIds];
3102
- const { clause } = buildQueryWhereClause(this.table, options, options.whereNodes, parameters);
3103
- return {
3104
- text: clause ? ` AND (${clause.replace(/^ WHERE /, "")})` : "",
3105
- params: parameters.slice(parentIds.length)
3106
- };
3107
- }
3108
3122
  async loadBelongsToForParents(children, relation, parentRepository, options = {}) {
3109
3123
  if (children.length === 0) {
3110
3124
  return new Map;
@@ -3170,8 +3184,8 @@ class BaseRepository {
3170
3184
  return indexBelongsToManyRelation(parents, [], [], relation);
3171
3185
  }
3172
3186
  const parentIds = [...new Set(parents.map((parent) => parent[relation.parentKey]))];
3173
- const placeholders = parentIds.map((_, index) => currentSqlDialect().placeholder(index + 1)).join(", ");
3174
- const pivotRows = await this.connection.unsafe(`SELECT * FROM ${relation.pivotTable} WHERE ${String(relation.foreignPivotKey)} IN (${placeholders})`, parentIds);
3187
+ const { text, params } = buildPivotLookupQuery(relation, parentIds);
3188
+ const pivotRows = await this.connection.unsafe(text, params);
3175
3189
  if (pivotRows.length === 0) {
3176
3190
  return indexBelongsToManyRelation(parents, [], [], relation);
3177
3191
  }
@@ -10,6 +10,7 @@ class ServiceContainer {
10
10
  services = new Map;
11
11
  singletonFactories = new Map;
12
12
  bindings = new Map;
13
+ resolutionPath = [];
13
14
  set(key, value) {
14
15
  this.singletonFactories.delete(key);
15
16
  this.bindings.delete(key);
@@ -32,16 +33,27 @@ class ServiceContainer {
32
33
  }
33
34
  const singletonFactory = this.singletonFactories.get(key);
34
35
  if (singletonFactory) {
35
- const value = singletonFactory(this);
36
+ const value = this.resolveFactory(key, singletonFactory);
36
37
  this.services.set(key, value);
37
38
  return value;
38
39
  }
39
40
  const binding = this.bindings.get(key);
40
41
  if (binding) {
41
- return binding(this);
42
+ return this.resolveFactory(key, binding);
42
43
  }
43
44
  throw new Error(`Service "${key}" is not registered.`);
44
45
  }
46
+ resolveFactory(key, factory) {
47
+ if (this.resolutionPath.includes(key)) {
48
+ throw new Error(`Circular service dependency: ${[...this.resolutionPath, key].join(" -> ")}.`);
49
+ }
50
+ this.resolutionPath.push(key);
51
+ try {
52
+ return factory(this);
53
+ } finally {
54
+ this.resolutionPath.pop();
55
+ }
56
+ }
45
57
  resolve(key) {
46
58
  return this.get(key);
47
59
  }
@@ -88,7 +88,7 @@ function sdkClientClassName() {
88
88
  return fromName ? `${fromName}Client` : "AppClient";
89
89
  }
90
90
 
91
- // ../../src/core/cache/redisCacheStore.ts
91
+ // ../../src/core/cache/redisCacheScript.ts
92
92
  var CACHE_SCRIPT = `
93
93
  local expected = {'hash', 'zset', 'zset', 'hash', 'zset'}
94
94
  for i, key in ipairs(KEYS) do
@@ -288,6 +288,7 @@ end
288
288
  return redis.error_reply('Unknown cache operation')
289
289
  `;
290
290
 
291
+ // ../../src/core/cache/redisCacheStore.ts
291
292
  class RedisCacheStore {
292
293
  redisUrl;
293
294
  ttlMs;
@@ -15,9 +15,10 @@ function validateEnv(schema, env = process.env) {
15
15
  continue;
16
16
  }
17
17
  if (rule.integer) {
18
+ const completeInteger = /^[+-]?\d+$/.test(value.trim());
18
19
  const parsed = Number.parseInt(value, 10);
19
20
  const minimum = rule.minimum ?? Number.NEGATIVE_INFINITY;
20
- if (!Number.isInteger(parsed) || parsed < minimum) {
21
+ if (!completeInteger || !Number.isInteger(parsed) || parsed < minimum) {
21
22
  const comparison = minimum === Number.NEGATIVE_INFINITY ? "an integer" : `an integer >= ${minimum}`;
22
23
  throw new Error(`Environment variable "${name}" must be ${comparison}.`);
23
24
  }
@@ -10,6 +10,7 @@ class ServiceContainer {
10
10
  services = new Map;
11
11
  singletonFactories = new Map;
12
12
  bindings = new Map;
13
+ resolutionPath = [];
13
14
  set(key, value) {
14
15
  this.singletonFactories.delete(key);
15
16
  this.bindings.delete(key);
@@ -32,16 +33,27 @@ class ServiceContainer {
32
33
  }
33
34
  const singletonFactory = this.singletonFactories.get(key);
34
35
  if (singletonFactory) {
35
- const value = singletonFactory(this);
36
+ const value = this.resolveFactory(key, singletonFactory);
36
37
  this.services.set(key, value);
37
38
  return value;
38
39
  }
39
40
  const binding = this.bindings.get(key);
40
41
  if (binding) {
41
- return binding(this);
42
+ return this.resolveFactory(key, binding);
42
43
  }
43
44
  throw new Error(`Service "${key}" is not registered.`);
44
45
  }
46
+ resolveFactory(key, factory) {
47
+ if (this.resolutionPath.includes(key)) {
48
+ throw new Error(`Circular service dependency: ${[...this.resolutionPath, key].join(" -> ")}.`);
49
+ }
50
+ this.resolutionPath.push(key);
51
+ try {
52
+ return factory(this);
53
+ } finally {
54
+ this.resolutionPath.pop();
55
+ }
56
+ }
45
57
  resolve(key) {
46
58
  return this.get(key);
47
59
  }
@@ -10,6 +10,7 @@ class ServiceContainer {
10
10
  services = new Map;
11
11
  singletonFactories = new Map;
12
12
  bindings = new Map;
13
+ resolutionPath = [];
13
14
  set(key, value) {
14
15
  this.singletonFactories.delete(key);
15
16
  this.bindings.delete(key);
@@ -32,16 +33,27 @@ class ServiceContainer {
32
33
  }
33
34
  const singletonFactory = this.singletonFactories.get(key);
34
35
  if (singletonFactory) {
35
- const value = singletonFactory(this);
36
+ const value = this.resolveFactory(key, singletonFactory);
36
37
  this.services.set(key, value);
37
38
  return value;
38
39
  }
39
40
  const binding = this.bindings.get(key);
40
41
  if (binding) {
41
- return binding(this);
42
+ return this.resolveFactory(key, binding);
42
43
  }
43
44
  throw new Error(`Service "${key}" is not registered.`);
44
45
  }
46
+ resolveFactory(key, factory) {
47
+ if (this.resolutionPath.includes(key)) {
48
+ throw new Error(`Circular service dependency: ${[...this.resolutionPath, key].join(" -> ")}.`);
49
+ }
50
+ this.resolutionPath.push(key);
51
+ try {
52
+ return factory(this);
53
+ } finally {
54
+ this.resolutionPath.pop();
55
+ }
56
+ }
45
57
  resolve(key) {
46
58
  return this.get(key);
47
59
  }