@burdenoff/be-sdk 2026.705.2 → 2026.705.4
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/configs/eslint/index.js +19 -0
- package/dist/{chunk-MD3RHPFS.js → chunk-HIH4SVR3.js} +4 -3
- package/dist/chunk-HIH4SVR3.js.map +1 -0
- package/dist/{chunk-QLXIIF4I.js → chunk-MXLCLLCI.js} +67 -5
- package/dist/chunk-MXLCLLCI.js.map +1 -0
- package/dist/{chunk-UCLDHOZC.js → chunk-YCKM7FS7.js} +12 -4
- package/dist/chunk-YCKM7FS7.js.map +1 -0
- package/dist/{index-DqvNf9U0.d.ts → index-D3lGLwby.d.ts} +5 -2
- package/dist/{index-DgWLSDv2.d.ts → index-lcW5eSTp.d.ts} +7 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +10 -10
- package/dist/platform/index.d.ts +1 -1
- package/dist/platform/index.js +1 -1
- package/dist/prisma/index.d.ts +1 -1
- package/dist/prisma/index.js +2 -2
- package/dist/server/index.js +2 -2
- package/package.json +1 -1
- package/dist/chunk-MD3RHPFS.js.map +0 -1
- package/dist/chunk-QLXIIF4I.js.map +0 -1
- package/dist/chunk-UCLDHOZC.js.map +0 -1
|
@@ -30,6 +30,7 @@ __export(platform_exports, {
|
|
|
30
30
|
paginate: () => paginate,
|
|
31
31
|
rateLimitIncr: () => rateLimitIncr,
|
|
32
32
|
resolveReferenceLoader: () => resolveReferenceLoader,
|
|
33
|
+
toPrismaPage: () => toPrismaPage,
|
|
33
34
|
withLeaderLock: () => withLeaderLock
|
|
34
35
|
});
|
|
35
36
|
|
|
@@ -375,8 +376,15 @@ function buildOffsetPage(items, total, pagination) {
|
|
|
375
376
|
};
|
|
376
377
|
}
|
|
377
378
|
__name(buildOffsetPage, "buildOffsetPage");
|
|
379
|
+
function toPrismaPage(pagination) {
|
|
380
|
+
return {
|
|
381
|
+
take: pagination.limit,
|
|
382
|
+
skip: pagination.offset
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
__name(toPrismaPage, "toPrismaPage");
|
|
378
386
|
async function paginate(model, input, opts = {}) {
|
|
379
|
-
const take =
|
|
387
|
+
const take = clampGraphqlLimit(input.take ?? void 0, opts);
|
|
380
388
|
const items = await model.findMany({
|
|
381
389
|
take: take + 1,
|
|
382
390
|
skip: input.cursor ? 1 : 0,
|
|
@@ -568,6 +576,6 @@ var LLMRouter = class {
|
|
|
568
576
|
}
|
|
569
577
|
};
|
|
570
578
|
|
|
571
|
-
export { CircuitBreakerOpenError, DEFAULT_GRAPHQL_PAGE_LIMIT, LLMRouter, MAX_GRAPHQL_PAGE_LIMIT, __resetHttpClientBreakers, buildCacheKey, buildConnection, buildLoaders, buildOffsetPage, clampGraphqlLimit, clampLimit, clampOffset, createHttpClient, decodeCursor, dropOldPartitions, encodeCursor, ensureMonthlyPartitions, getNamespaceVersion, httpClient, invalidateNamespace, monthlyPartitionName, normalizeCursorPagination, normalizeOffsetPagination, paginate, platform_exports, rateLimitIncr, resolveReferenceLoader, withLeaderLock };
|
|
572
|
-
//# sourceMappingURL=chunk-
|
|
573
|
-
//# sourceMappingURL=chunk-
|
|
579
|
+
export { CircuitBreakerOpenError, DEFAULT_GRAPHQL_PAGE_LIMIT, LLMRouter, MAX_GRAPHQL_PAGE_LIMIT, __resetHttpClientBreakers, buildCacheKey, buildConnection, buildLoaders, buildOffsetPage, clampGraphqlLimit, clampLimit, clampOffset, createHttpClient, decodeCursor, dropOldPartitions, encodeCursor, ensureMonthlyPartitions, getNamespaceVersion, httpClient, invalidateNamespace, monthlyPartitionName, normalizeCursorPagination, normalizeOffsetPagination, paginate, platform_exports, rateLimitIncr, resolveReferenceLoader, toPrismaPage, withLeaderLock };
|
|
580
|
+
//# sourceMappingURL=chunk-YCKM7FS7.js.map
|
|
581
|
+
//# sourceMappingURL=chunk-YCKM7FS7.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/platform/index.ts","../src/platform/httpClient.ts","../src/platform/leaderLock.ts","../src/platform/rateLimit.ts","../src/platform/paginator.ts","../src/platform/dataLoaderFactory.ts","../src/platform/cacheInvalidation.ts","../src/platform/pgPartition.ts","../src/platform/llmClient.ts"],"names":["breakers","Map","hostOf","url","URL","host","getBreaker","b","get","failures","openedAt","state","set","defaultRetryOn","status","jitter","delay","Math","floor","random","sleep","ms","Promise","r","setTimeout","CircuitBreakerOpenError","Error","name","__resetHttpClientBreakers","clear","executeOnce","init","timeoutMs","signal","AbortSignal","timeout","fetch","httpClient","config","fullUrl","baseUrl","test","replace","breaker","breakerThreshold","threshold","cooldownMs","Date","now","logger","info","attempts","retry","initialDelay","initialDelayMs","maxDelay","maxDelayMs","retryOn","defaultTimeoutMs","headers","defaultHeaders","lastErr","attempt","response","warn","min","err","error","String","createHttpClient","RELEASE_LUA","RENEW_LUA","generateToken","toString","slice","process","pid","withLeaderLock","redis","fn","options","key","token","ttlMs","renewMs","max","ttlSeconds","ceil","acquired","stopped","renewTimer","setInterval","eval","catch","unref","result","clearInterval","rateLimitIncr","input","fullKey","count","incr","pexpire","windowMs","ttl","pttl","resetAt","remaining","limit","allowed","DEFAULT_GRAPHQL_PAGE_LIMIT","MAX_GRAPHQL_PAGE_LIMIT","clampLimit","opts","def","defaultLimit","maxLimit","minLimit","Number","isNaN","clampOffset","clampGraphqlLimit","normalizeOffsetPagination","offset","normalizeCursorPagination","first","after","trim","length","take","encodeCursor","payload","Buffer","from","JSON","stringify","decodeCursor","cursor","decoded","parse","Array","isArray","value","Object","entries","keys","buildConnection","items","nodes","edges","map","node","cursorForNode","firstEdge","lastEdge","at","pageInfo","hasNextPage","hasPreviousPage","startCursor","endCursor","totalCount","buildOffsetPage","total","pagination","nextOffset","hasMore","toPrismaPage","skip","paginate","model","undefined","findMany","id","where","orderBy","trimmed","nextCursor","buildLoaders","ctx","builder","resolveReferenceLoader","loaderName","keyField","reference","loader","loaders","load","VERSION_PREFIX","getNamespaceVersion","namespace","v","n","parseInt","isFinite","buildCacheKey","parts","ver","join","invalidateNamespace","pad2","monthlyPartitionName","table","year","month","ensureMonthlyPartitions","prisma","created","cur","UTC","getUTCFullYear","getUTCMonth","end","to","y","m","next","partition","lower","upper","$executeRawUnsafe","push","setUTCMonth","dropOldPartitions","rows","$queryRawUnsafe","dropped","cutoffYear","beforeDate","cutoffMonth","row","partitionRe","exec","partition_name","mo","DEFAULTS","maxAttempts","maxOutputTokensCap","LLMRouter","adapters","register","adapter","resolveChain","envChain","env","split","s","filter","Boolean","complete","req","cappedReq","maxTokens","chain","providerName","ctrl","AbortController","t","abort","provider","clearTimeout"],"mappings":";;;;AAAA,IAAA,gBAAA,GAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACgDA,IAAMA,QAAAA,uBAAeC,GAAAA,EAAAA;AAErB,SAASC,OAAOC,GAAAA,EAAW;AACzB,EAAA,IAAI;AACF,IAAA,OAAO,IAAIC,GAAAA,CAAID,GAAAA,CAAAA,CAAKE,IAAAA;EACtB,CAAA,CAAA,MAAQ;AACN,IAAA,OAAOF,GAAAA;AACT,EAAA;AACF;AANSD,MAAAA,CAAAA,MAAAA,EAAAA,QAAAA,CAAAA;AAQT,SAASI,WAAWD,IAAAA,EAAY;AAC9B,EAAA,IAAIE,CAAAA,GAAIP,QAAAA,CAASQ,GAAAA,CAAIH,IAAAA,CAAAA;AACrB,EAAA,IAAI,CAACE,CAAAA,EAAG;AACNA,IAAAA,CAAAA,GAAI;MAAEE,QAAAA,EAAU,CAAA;MAAGC,QAAAA,EAAU,IAAA;MAAMC,KAAAA,EAAO;AAAS,KAAA;AACnDX,IAAAA,QAAAA,CAASY,GAAAA,CAAIP,MAAME,CAAAA,CAAAA;AACrB,EAAA;AACA,EAAA,OAAOA,CAAAA;AACT;AAPSD,MAAAA,CAAAA,UAAAA,EAAAA,YAAAA,CAAAA;AAST,SAASO,eAAeC,MAAAA,EAAc;AACpC,EAAA,OAAOA,MAAAA,KAAW,OAAOA,MAAAA,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AWI,KAAK9N,MAAM,CAAA;AAC9D,QAAA,OAAO8B,QAAAA;AACT,MAAA,CAAA,CAAA,OAASG,GAAAA,EAAK;AACZL,QAAAA,OAAAA,GAAUK,GAAAA;AACVjB,QAAAA,MAAAA,CAAOe,KAAK,0BAAA,EAA4B;AAAEmM,UAAAA,QAAAA,EAAUlB,OAAAA,CAAQtN,IAAAA;AAAMmC,UAAAA,OAAAA;AAASI,UAAAA,GAAAA,EAAKE,OAAOF,GAAAA;SAAK,CAAA;AAC5F,QAAA,IAAIJ,OAAAA,GAAU,IAAA,CAAKmD,IAAAA,CAAK2H,WAAAA,GAAc,CAAA,EAAG;AACvC,UAAA,MAAM5N,KAAAA,GAAQ,IAAA,CAAKiG,IAAAA,CAAK3D,cAAAA,GAAiB,CAAA,IAAKQ,OAAAA;AAC9C,UAAA,MAAM1C,MAAAA,CAAML,OAAAA,CAAOC,KAAAA,CAAAA,CAAAA;AACrB,QAAA;MACF,CAAA,SAAA;AACEoP,QAAAA,YAAAA,CAAaH,CAAAA,CAAAA;AACf,MAAA;AACF,IAAA;AACA,IAAA,MAAMpM,OAAAA,YAAmBnC,QAAQmC,OAAAA,GAAU,IAAInC,MAAM,CAAA,oBAAA,EAAuB,IAAA,CAAKuF,IAAAA,CAAK2H,WAAW,CAAA,SAAA,CAAW,CAAA;AAC9G,EAAA;AACF","file":"chunk-YCKM7FS7.js","sourcesContent":["/**\n * @burdenoff/be-sdk/platform\n *\n * Reusable platform primitives consumed fleet-wide by Burdenoff svcs.\n */\nexport { httpClient, createHttpClient, CircuitBreakerOpenError, __resetHttpClientBreakers } from './httpClient.js';\nexport type { HttpClientConfig, HttpClientInit, RetryConfig, BreakerConfig } from './httpClient.js';\n\nexport { withLeaderLock } from './leaderLock.js';\nexport type { LeaderLockRedis, LeaderLockOptions, LeaderLockResult } from './leaderLock.js';\n\nexport { rateLimitIncr } from './rateLimit.js';\nexport type { RateLimitRedis, RateLimitInput, RateLimitResult } from './rateLimit.js';\n\nexport {\n DEFAULT_GRAPHQL_PAGE_LIMIT,\n MAX_GRAPHQL_PAGE_LIMIT,\n buildConnection,\n buildOffsetPage,\n clampGraphqlLimit,\n clampLimit,\n clampOffset,\n decodeCursor,\n encodeCursor,\n normalizeCursorPagination,\n normalizeOffsetPagination,\n paginate,\n toPrismaPage,\n} from './paginator.js';\nexport type { ClampLimitOptions, PaginateInput, PaginateResult, PrismaModelLike } from './paginator.js';\nexport type {\n BuildConnectionOptions,\n ConnectionEdge,\n ConnectionResult,\n CursorPaginationInput,\n CursorPayload,\n CursorPayloadValue,\n NormalizedCursorPagination,\n NormalizedOffsetPagination,\n OffsetPageResult,\n OffsetPaginationInput,\n PageInfo,\n} from './paginator.js';\n\nexport { buildLoaders, resolveReferenceLoader } from './dataLoaderFactory.js';\nexport type { DataLoaderLike, LoaderMap, LoaderBuilder, ReferenceObject } from './dataLoaderFactory.js';\n\nexport { buildCacheKey, getNamespaceVersion, invalidateNamespace } from './cacheInvalidation.js';\nexport type { CacheVersionRedis } from './cacheInvalidation.js';\n\nexport { monthlyPartitionName, ensureMonthlyPartitions, dropOldPartitions } from './pgPartition.js';\nexport type { PrismaRawClient, EnsureMonthlyOptions, DropOldOptions } from './pgPartition.js';\n\nexport { LLMRouter } from './llmClient.js';\nexport type { LLMRequest, LLMResponse, LLMProviderAdapter, LLMRouterOptions } from './llmClient.js';\n","/**\n * httpClient — hardened wrapper around global `fetch` with:\n * - per-request AbortSignal.timeout (default 5s)\n * - retries (default 3) with exponential backoff + full jitter\n * - per-host circuit breaker (opens at 5 consecutive 5xx, half-open after 30s)\n * - structured logging via existing be-sdk logger\n *\n * No required upstream dependency — we use the runtime `fetch` so the same\n * code path works on Bun and Node 20+. Consumers may pass an undici Agent\n * via `init.dispatcher` if they need keep-alive pooling; we forward unknown\n * init fields through.\n */\n\nimport { logger } from '../logger/index.js';\n\nexport interface RetryConfig {\n /** Total attempts including the first (default 3) */\n attempts?: number;\n /** Initial backoff in ms (default 100) */\n initialDelayMs?: number;\n /** Maximum backoff in ms (default 2000) */\n maxDelayMs?: number;\n /** Status codes that trigger a retry (default 408, 425, 429, 5xx) */\n retryOn?: (status: number) => boolean;\n}\n\nexport interface BreakerConfig {\n /** Consecutive 5xx failures to open breaker (default 5) */\n threshold?: number;\n /** Time in ms before HALF_OPEN trial (default 30000) */\n cooldownMs?: number;\n}\n\nexport interface HttpClientConfig {\n baseUrl?: string;\n defaultTimeoutMs?: number;\n retry?: RetryConfig;\n breaker?: BreakerConfig;\n /** Default headers merged into every request */\n defaultHeaders?: Record<string, string>;\n}\n\ninterface BreakerState {\n failures: number;\n openedAt: number | null;\n state: 'CLOSED' | 'OPEN' | 'HALF_OPEN';\n}\n\nconst breakers = new Map<string, BreakerState>();\n\nfunction hostOf(url: string): string {\n try {\n return new URL(url).host;\n } catch {\n return url;\n }\n}\n\nfunction getBreaker(host: string): BreakerState {\n let b = breakers.get(host);\n if (!b) {\n b = { failures: 0, openedAt: null, state: 'CLOSED' };\n breakers.set(host, b);\n }\n return b;\n}\n\nfunction defaultRetryOn(status: number): boolean {\n return status === 408 || status === 425 || status === 429 || (status >= 500 && status <= 599);\n}\n\nfunction jitter(delay: number): number {\n return Math.floor(Math.random() * delay);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((r) => setTimeout(r, ms));\n}\n\nexport class CircuitBreakerOpenError extends Error {\n constructor(host: string) {\n super(`circuit breaker OPEN for host=${host}`);\n this.name = 'CircuitBreakerOpenError';\n }\n}\n\nexport interface HttpClientInit extends RequestInit {\n timeoutMs?: number;\n retry?: RetryConfig;\n}\n\n/**\n * Reset all breaker state (test helper).\n */\nexport function __resetHttpClientBreakers(): void {\n breakers.clear();\n}\n\nasync function executeOnce(url: string, init: HttpClientInit, timeoutMs: number): Promise<Response> {\n const signal = init.signal ?? AbortSignal.timeout(timeoutMs);\n return fetch(url, { ...init, signal });\n}\n\nexport async function httpClient(\n url: string,\n init: HttpClientInit = {},\n config: HttpClientConfig = {}\n): Promise<Response> {\n const fullUrl =\n config.baseUrl && !/^https?:\\/\\//i.test(url)\n ? `${config.baseUrl.replace(/\\/$/, '')}/${url.replace(/^\\//, '')}`\n : url;\n const host = hostOf(fullUrl);\n const breaker = getBreaker(host);\n const breakerThreshold = config.breaker?.threshold ?? 5;\n const cooldownMs = config.breaker?.cooldownMs ?? 30_000;\n\n if (breaker.state === 'OPEN') {\n if (breaker.openedAt && Date.now() - breaker.openedAt >= cooldownMs) {\n breaker.state = 'HALF_OPEN';\n logger.info('httpClient.breaker.halfOpen', { host });\n } else {\n throw new CircuitBreakerOpenError(host);\n }\n }\n\n const attempts = init.retry?.attempts ?? config.retry?.attempts ?? 3;\n const initialDelay = init.retry?.initialDelayMs ?? config.retry?.initialDelayMs ?? 100;\n const maxDelay = init.retry?.maxDelayMs ?? config.retry?.maxDelayMs ?? 2_000;\n const retryOn = init.retry?.retryOn ?? config.retry?.retryOn ?? defaultRetryOn;\n const timeoutMs = init.timeoutMs ?? config.defaultTimeoutMs ?? 5_000;\n\n const headers = { ...(config.defaultHeaders ?? {}), ...((init.headers as Record<string, string> | undefined) ?? {}) };\n\n let lastErr: unknown;\n for (let attempt = 1; attempt <= attempts; attempt++) {\n try {\n const response = await executeOnce(fullUrl, { ...init, headers }, timeoutMs);\n if (response.status >= 500) {\n breaker.failures += 1;\n if (breaker.failures >= breakerThreshold) {\n breaker.state = 'OPEN';\n breaker.openedAt = Date.now();\n logger.warn('httpClient.breaker.open', { host, failures: breaker.failures });\n }\n if (attempt < attempts && retryOn(response.status)) {\n const delay = Math.min(initialDelay * 2 ** (attempt - 1), maxDelay);\n await sleep(jitter(delay));\n continue;\n }\n return response;\n }\n // success path\n breaker.failures = 0;\n if (breaker.state === 'HALF_OPEN') {\n breaker.state = 'CLOSED';\n breaker.openedAt = null;\n logger.info('httpClient.breaker.closed', { host });\n }\n if (attempt < attempts && retryOn(response.status)) {\n const delay = Math.min(initialDelay * 2 ** (attempt - 1), maxDelay);\n await sleep(jitter(delay));\n continue;\n }\n return response;\n } catch (err) {\n lastErr = err;\n breaker.failures += 1;\n if (breaker.failures >= breakerThreshold) {\n breaker.state = 'OPEN';\n breaker.openedAt = Date.now();\n logger.warn('httpClient.breaker.open', { host, failures: breaker.failures });\n }\n if (attempt >= attempts) break;\n const delay = Math.min(initialDelay * 2 ** (attempt - 1), maxDelay);\n await sleep(jitter(delay));\n }\n }\n\n logger.error('httpClient.exhausted', { url: fullUrl, attempts, host });\n throw lastErr instanceof Error ? lastErr : new Error(`httpClient failed: ${String(lastErr)}`);\n}\n\nexport function createHttpClient(\n config: HttpClientConfig = {}\n): (url: string, init?: HttpClientInit) => Promise<Response> {\n return (url: string, init: HttpClientInit = {}) => httpClient(url, init, config);\n}\n","/**\n * withLeaderLock — Redis-based leader election.\n *\n * Acquires `SET NX EX` on `besdk:leader:{name}`. If acquired, runs fn() and\n * auto-renews the lease every `renewMs` (default ttlMs/3). On exit (success\n * or throw) the holder DELs the key only if it still owns it (token check\n * via a Redis LUA script — Redis-side, NOT JS eval).\n * If the lock cannot be acquired, fn() is NOT called and the function\n * resolves with `{ acquired: false }`.\n *\n * Redis client is duck-typed (ioredis-compatible) so consumers can pass\n * either ioredis or the be-sdk cache provider's underlying client.\n */\n\nimport { logger } from '../logger/index.js';\n\nexport interface LeaderLockRedis {\n /** ioredis: set(key, val, 'EX', seconds, 'NX') -> 'OK' | null */\n set(key: string, value: string, ex: 'EX', seconds: number, nx: 'NX'): Promise<'OK' | null>;\n /** Redis LUA EVAL for compare-and-delete / compare-and-renew (server-side script) */\n eval(script: string, numKeys: number, ...args: string[]): Promise<unknown>;\n}\n\nexport interface LeaderLockOptions {\n ttlMs: number;\n renewMs?: number;\n}\n\nexport interface LeaderLockResult<T> {\n acquired: boolean;\n result?: T;\n}\n\nconst RELEASE_LUA = `\nif redis.call(\"get\", KEYS[1]) == ARGV[1] then\n return redis.call(\"del\", KEYS[1])\nelse\n return 0\nend\n`;\n\nconst RENEW_LUA = `\nif redis.call(\"get\", KEYS[1]) == ARGV[1] then\n return redis.call(\"pexpire\", KEYS[1], ARGV[2])\nelse\n return 0\nend\n`;\n\nfunction generateToken(): string {\n return `${Date.now()}-${Math.random().toString(36).slice(2)}-${process.pid}`;\n}\n\nexport async function withLeaderLock<T>(\n redis: LeaderLockRedis,\n name: string,\n fn: () => Promise<T>,\n options: LeaderLockOptions\n): Promise<LeaderLockResult<T>> {\n const key = `besdk:leader:${name}`;\n const token = generateToken();\n const ttlMs = options.ttlMs;\n const renewMs = options.renewMs ?? Math.max(1_000, Math.floor(ttlMs / 3));\n const ttlSeconds = Math.max(1, Math.ceil(ttlMs / 1000));\n\n const acquired = await redis.set(key, token, 'EX', ttlSeconds, 'NX');\n if (acquired !== 'OK') {\n return { acquired: false };\n }\n\n logger.info('leaderLock.acquired', { name, token, ttlMs });\n\n let stopped = false;\n const renewTimer = setInterval(() => {\n if (stopped) return;\n redis.eval(RENEW_LUA, 1, key, token, String(ttlMs)).catch((err: unknown) => {\n logger.warn('leaderLock.renew.failed', { name, err: String(err) });\n });\n }, renewMs);\n // Don't keep the process alive just for this timer.\n if (typeof (renewTimer as unknown as { unref?: () => void }).unref === 'function') {\n (renewTimer as unknown as { unref: () => void }).unref();\n }\n\n try {\n const result = await fn();\n return { acquired: true, result };\n } finally {\n stopped = true;\n clearInterval(renewTimer);\n try {\n await redis.eval(RELEASE_LUA, 1, key, token);\n logger.info('leaderLock.released', { name, token });\n } catch (err) {\n logger.warn('leaderLock.release.failed', { name, err: String(err) });\n }\n }\n}\n","/**\n * rateLimitIncr — atomic INCR-based rate limit using EXPIRE NX.\n *\n * Strategy:\n * 1. INCR key\n * 2. If returned value === 1 (i.e. first increment), EXPIRE key with windowMs\n * 3. Compute remaining + resetAt\n *\n * This is two round-trips in the worst case. A future Lua/EVALSHA variant\n * can collapse it into a single round-trip; the public API is stable.\n *\n * Returns `allowed=false` if `count > limit`. The key is `besdk:rl:{key}`.\n */\n\nexport interface RateLimitRedis {\n incr(key: string): Promise<number>;\n pexpire(key: string, ms: number): Promise<number | 'OK'>;\n pttl(key: string): Promise<number>;\n}\n\nexport interface RateLimitInput {\n key: string;\n limit: number;\n windowMs: number;\n}\n\nexport interface RateLimitResult {\n allowed: boolean;\n count: number;\n remaining: number;\n resetAt: number;\n}\n\nexport async function rateLimitIncr(redis: RateLimitRedis, input: RateLimitInput): Promise<RateLimitResult> {\n const fullKey = `besdk:rl:${input.key}`;\n const count = await redis.incr(fullKey);\n if (count === 1) {\n await redis.pexpire(fullKey, input.windowMs);\n }\n let ttl = -1;\n try {\n ttl = await redis.pttl(fullKey);\n } catch {\n ttl = input.windowMs;\n }\n const resetAt = Date.now() + (ttl > 0 ? ttl : input.windowMs);\n const remaining = Math.max(0, input.limit - count);\n return {\n allowed: count <= input.limit,\n count,\n remaining,\n resetAt,\n };\n}\n","/**\n * Paginator — Relay-style cursor pagination + safe limit clamping.\n *\n * Use `clampLimit` at resolver entry to enforce sane defaults/maxes.\n * Use `paginate` to translate a Relay-style { first, after } into a\n * Prisma-ready { take, skip, cursor } and return a connection-shaped\n * result.\n */\n\nexport interface ClampLimitOptions {\n defaultLimit?: number;\n maxLimit?: number;\n minLimit?: number;\n}\n\nexport const DEFAULT_GRAPHQL_PAGE_LIMIT = 50;\nexport const MAX_GRAPHQL_PAGE_LIMIT = 100;\n\nexport function clampLimit(input: number | undefined | null, opts: ClampLimitOptions = {}): number {\n const def = opts.defaultLimit ?? 50;\n const max = opts.maxLimit ?? 200;\n const min = opts.minLimit ?? 1;\n if (input == null || Number.isNaN(input)) return def;\n return Math.min(Math.max(Math.floor(input), min), max);\n}\n\nexport function clampOffset(input: number | undefined | null): number {\n if (input == null || Number.isNaN(input)) return 0;\n return Math.max(0, Math.floor(input));\n}\n\nexport function clampGraphqlLimit(input: number | undefined | null, opts: ClampLimitOptions = {}): number {\n return clampLimit(input, {\n defaultLimit: opts.defaultLimit ?? DEFAULT_GRAPHQL_PAGE_LIMIT,\n maxLimit: opts.maxLimit ?? MAX_GRAPHQL_PAGE_LIMIT,\n minLimit: opts.minLimit ?? 1,\n });\n}\n\nexport interface OffsetPaginationInput {\n limit?: number | null;\n offset?: number | null;\n}\n\nexport interface NormalizedOffsetPagination {\n limit: number;\n offset: number;\n}\n\nexport function normalizeOffsetPagination(\n input: OffsetPaginationInput | null | undefined,\n opts: ClampLimitOptions = {}\n): NormalizedOffsetPagination {\n return {\n limit: clampGraphqlLimit(input?.limit, opts),\n offset: clampOffset(input?.offset),\n };\n}\n\nexport interface CursorPaginationInput {\n first?: number | null;\n after?: string | null;\n}\n\nexport interface NormalizedCursorPagination {\n first: number;\n after: string | null;\n take: number;\n}\n\nexport function normalizeCursorPagination(\n input: CursorPaginationInput | null | undefined,\n opts: ClampLimitOptions = {}\n): NormalizedCursorPagination {\n const first = clampGraphqlLimit(input?.first, opts);\n const after = typeof input?.after === 'string' && input.after.trim().length > 0 ? input.after : null;\n return { first, after, take: first + 1 };\n}\n\nexport type CursorPayloadValue = string | number | boolean | null;\nexport type CursorPayload = Record<string, CursorPayloadValue>;\n\nexport function encodeCursor(payload: CursorPayload): string {\n return Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url');\n}\n\nexport function decodeCursor(cursor: string | null | undefined): CursorPayload | null {\n if (typeof cursor !== 'string' || cursor.trim().length === 0) return null;\n\n try {\n const decoded: unknown = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));\n if (decoded == null || typeof decoded !== 'object' || Array.isArray(decoded)) return null;\n\n const payload: CursorPayload = {};\n for (const [key, value] of Object.entries(decoded)) {\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || value == null) {\n payload[key] = value;\n }\n }\n\n return Object.keys(payload).length > 0 ? payload : null;\n } catch {\n return null;\n }\n}\n\nexport interface PageInfo {\n hasNextPage: boolean;\n hasPreviousPage: boolean;\n startCursor: string | null;\n endCursor: string | null;\n}\n\nexport interface ConnectionEdge<TItem> {\n node: TItem;\n cursor: string;\n}\n\nexport interface ConnectionResult<TItem> {\n edges: ConnectionEdge<TItem>[];\n nodes: TItem[];\n pageInfo: PageInfo;\n totalCount?: number | null;\n}\n\nexport interface BuildConnectionOptions<TItem> {\n limit: number;\n cursorForNode: (item: TItem) => string;\n hasPreviousPage?: boolean;\n totalCount?: number | null;\n}\n\nexport function buildConnection<TItem>(items: TItem[], opts: BuildConnectionOptions<TItem>): ConnectionResult<TItem> {\n const nodes = items.length > opts.limit ? items.slice(0, opts.limit) : items;\n const edges = nodes.map((node) => ({ node, cursor: opts.cursorForNode(node) }));\n const firstEdge = edges[0];\n const lastEdge = edges.at(-1);\n\n return {\n edges,\n nodes,\n pageInfo: {\n hasNextPage: items.length > opts.limit,\n hasPreviousPage: opts.hasPreviousPage ?? false,\n startCursor: firstEdge?.cursor ?? null,\n endCursor: lastEdge?.cursor ?? null,\n },\n totalCount: opts.totalCount,\n };\n}\n\nexport interface OffsetPageResult<TItem> {\n items: TItem[];\n total: number;\n limit: number;\n offset: number;\n hasMore: boolean;\n nextOffset: number | null;\n}\n\nexport function buildOffsetPage<TItem>(\n items: TItem[],\n total: number,\n pagination: NormalizedOffsetPagination\n): OffsetPageResult<TItem> {\n const nextOffset = pagination.offset + items.length;\n const hasMore = nextOffset < total;\n\n return {\n items,\n total,\n limit: pagination.limit,\n offset: pagination.offset,\n hasMore,\n nextOffset: hasMore ? nextOffset : null,\n };\n}\n\n// ============================================================================\n// Prisma convenience helpers\n// ============================================================================\n\n/**\n * Convert a normalized offset pagination result to Prisma's `take`/`skip` args.\n *\n * ```ts\n * const pg = normalizeOffsetPagination(args);\n * const rows = await prisma.tag.findMany({ ...toPrismaPage(pg), where });\n * ```\n *\n * `limit` is clamped to MAX_GRAPHQL_PAGE_LIMIT (100) by `normalizeOffsetPagination`.\n * Always call normalizeOffsetPagination first — never pass a raw limit directly.\n */\nexport function toPrismaPage(pagination: NormalizedOffsetPagination): { take: number; skip: number } {\n return { take: pagination.limit, skip: pagination.offset };\n}\n\nexport interface PaginateInput<TWhere, TOrderBy> {\n take?: number | null;\n cursor?: string | null;\n where?: TWhere;\n orderBy?: TOrderBy;\n}\n\nexport interface PaginateResult<TItem> {\n items: TItem[];\n hasMore: boolean;\n nextCursor: string | null;\n}\n\nexport interface PrismaModelLike<TItem, TWhere, TOrderBy> {\n findMany(args: {\n take?: number;\n skip?: number;\n cursor?: { id: string };\n where?: TWhere;\n orderBy?: TOrderBy;\n }): Promise<TItem[]>;\n}\n\nexport async function paginate<TItem extends { id: string }, TWhere = unknown, TOrderBy = unknown>(\n model: PrismaModelLike<TItem, TWhere, TOrderBy>,\n input: PaginateInput<TWhere, TOrderBy>,\n opts: ClampLimitOptions = {}\n): Promise<PaginateResult<TItem>> {\n // Use GraphQL-aware cap (max=100) so paginate() is safe to call directly from resolvers.\n const take = clampGraphqlLimit(input.take ?? undefined, opts);\n // fetch +1 to detect hasMore\n const items = await model.findMany({\n take: take + 1,\n skip: input.cursor ? 1 : 0,\n cursor: input.cursor ? { id: input.cursor } : undefined,\n where: input.where,\n orderBy: input.orderBy,\n });\n const hasMore = items.length > take;\n const trimmed = hasMore ? items.slice(0, take) : items;\n const nextCursor = hasMore && trimmed.length > 0 ? (trimmed[trimmed.length - 1] as { id: string }).id : null;\n return { items: trimmed, hasMore, nextCursor };\n}\n","/**\n * DataLoaderFactory — per-request DataLoader collection.\n *\n * Each GraphQL request creates a fresh loader set scoped to its context\n * (db, workspaceId, requestId). Loaders are addressed by name and reused\n * within the request to coalesce N+1 fan-outs into a single batched query.\n *\n * Also ships `resolveReferenceLoader` — a convenience for Apollo Federation\n * `__resolveReference` resolvers so entity hydration stays N+1-free.\n *\n * This module is intentionally framework-agnostic; consumers may pair it\n * with the existing `SimpleDataLoader` in `src/dataloader/index.ts` or the\n * upstream `dataloader` npm package.\n */\n\nexport interface DataLoaderLike<K, V> {\n load(key: K): Promise<V>;\n loadMany(keys: readonly K[]): Promise<(V | Error)[]>;\n clear(key: K): this;\n clearAll(): this;\n prime(key: K, value: V): this;\n}\n\nexport type LoaderMap = Record<string, DataLoaderLike<unknown, unknown>>;\n\nexport type LoaderBuilder<Ctx, M extends LoaderMap> = (ctx: Ctx) => M;\n\n/**\n * Build a fresh loader collection from a context.\n *\n * @example\n * const loaders = buildLoaders(ctx, (c) => ({\n * userById: createSimpleLoader(async ids => c.db.user.findMany({ where: { id: { in: [...ids] } } }), u => u.id),\n * tagById: createSimpleLoader(...),\n * }));\n * await loaders.userById.load('user-123');\n */\nexport function buildLoaders<Ctx, M extends LoaderMap>(ctx: Ctx, builder: LoaderBuilder<Ctx, M>): M {\n return builder(ctx);\n}\n\n/**\n * `__resolveReference` helper for Apollo Federation.\n *\n * Given a context that contains a `loaders` map, returns a resolver\n * function bound to a specific loader name. Field references shaped as\n * `{ id: string }` (or `{ __keyField: string }`) are forwarded to\n * `loader.load(...)`.\n */\nexport interface ReferenceObject {\n id?: string;\n [key: string]: unknown;\n}\n\nexport function resolveReferenceLoader<T, Ctx extends { loaders: LoaderMap }>(\n loaderName: string,\n keyField: string = 'id'\n): (reference: ReferenceObject, ctx: Ctx) => Promise<T | null> {\n return async (reference, ctx) => {\n const loader = ctx.loaders[loaderName] as DataLoaderLike<string, T> | undefined;\n if (!loader) {\n throw new Error(`resolveReferenceLoader: loader \"${loaderName}\" not found on ctx.loaders`);\n }\n const key = reference[keyField];\n if (typeof key !== 'string') {\n return null;\n }\n return loader.load(key);\n };\n}\n","/**\n * Versioned-key cache invalidation helper.\n *\n * Pattern:\n * - Store `v:{namespace}` integer in Redis\n * - Compose keys as `${namespace}:v${ver}:${rest}`\n * - Invalidate via INCR `v:{namespace}` — no KEYS / SCAN required\n *\n * Use this instead of cacheClearPattern() for Azure Managed Redis (O(N)\n * blocking on KEYS is unsafe in prod).\n */\n\nexport interface CacheVersionRedis {\n get(key: string): Promise<string | null>;\n incr(key: string): Promise<number>;\n}\n\nconst VERSION_PREFIX = 'besdk:cv:';\n\nexport async function getNamespaceVersion(redis: CacheVersionRedis, namespace: string): Promise<number> {\n const v = await redis.get(`${VERSION_PREFIX}${namespace}`);\n if (!v) return 1;\n const n = Number.parseInt(v, 10);\n return Number.isFinite(n) && n > 0 ? n : 1;\n}\n\nexport async function buildCacheKey(redis: CacheVersionRedis, namespace: string, ...parts: string[]): Promise<string> {\n const ver = await getNamespaceVersion(redis, namespace);\n return `${namespace}:v${ver}:${parts.join(':')}`;\n}\n\nexport async function invalidateNamespace(redis: CacheVersionRedis, namespace: string): Promise<number> {\n return redis.incr(`${VERSION_PREFIX}${namespace}`);\n}\n","/**\n * PG declarative partition + retention DSL.\n *\n * Helpers:\n * - ensureMonthlyPartitions(prisma, { table, from, to })\n * - dropOldPartitions(prisma, { table, beforeDate })\n *\n * Used by retention jobs / migrations to keep append-only tables\n * (ActivityLog, Message, TrackingEvent, ApplicationUsage, AuditLog)\n * bounded. Caller is responsible for ensuring the parent table is\n * already declared as PARTITION BY RANGE (created_at).\n */\n\nexport interface PrismaRawClient {\n $executeRawUnsafe(query: string, ...values: unknown[]): Promise<unknown>;\n $queryRawUnsafe<T = unknown>(query: string, ...values: unknown[]): Promise<T>;\n}\n\nfunction pad2(n: number): string {\n return n < 10 ? `0${n}` : `${n}`;\n}\n\nexport function monthlyPartitionName(table: string, year: number, month: number): string {\n return `${table}_y${year}m${pad2(month)}`;\n}\n\nexport interface EnsureMonthlyOptions {\n table: string;\n from: Date;\n to: Date;\n}\n\nexport async function ensureMonthlyPartitions(prisma: PrismaRawClient, opts: EnsureMonthlyOptions): Promise<string[]> {\n const created: string[] = [];\n const cur = new Date(Date.UTC(opts.from.getUTCFullYear(), opts.from.getUTCMonth(), 1));\n const end = new Date(Date.UTC(opts.to.getUTCFullYear(), opts.to.getUTCMonth(), 1));\n while (cur <= end) {\n const y = cur.getUTCFullYear();\n const m = cur.getUTCMonth() + 1;\n const next = new Date(Date.UTC(y, m, 1));\n const partition = monthlyPartitionName(opts.table, y, m);\n const lower = `${y}-${pad2(m)}-01`;\n const upper = `${next.getUTCFullYear()}-${pad2(next.getUTCMonth() + 1)}-01`;\n await prisma.$executeRawUnsafe(\n `CREATE TABLE IF NOT EXISTS \"${partition}\" PARTITION OF \"${opts.table}\" FOR VALUES FROM ('${lower}') TO ('${upper}');`\n );\n created.push(partition);\n cur.setUTCMonth(cur.getUTCMonth() + 1);\n }\n return created;\n}\n\nexport interface DropOldOptions {\n table: string;\n beforeDate: Date;\n}\n\ninterface PartitionRow {\n partition_name: string;\n}\n\nexport async function dropOldPartitions(prisma: PrismaRawClient, opts: DropOldOptions): Promise<string[]> {\n // Find inherited tables of the parent, parse year/month from suffix, drop ones before threshold.\n const rows = await prisma.$queryRawUnsafe<PartitionRow[]>(\n `SELECT child.relname AS partition_name\n FROM pg_inherits\n JOIN pg_class parent ON pg_inherits.inhparent = parent.oid\n JOIN pg_class child ON pg_inherits.inhrelid = child.oid\n WHERE parent.relname = $1`,\n opts.table\n );\n const dropped: string[] = [];\n const cutoffYear = opts.beforeDate.getUTCFullYear();\n const cutoffMonth = opts.beforeDate.getUTCMonth() + 1;\n for (const row of rows) {\n const partitionRe = /_y(\\d{4})m(\\d{2})$/;\n const m = partitionRe.exec(row.partition_name);\n if (!m) continue;\n const y = Number(m[1]);\n const mo = Number(m[2]);\n if (y < cutoffYear || (y === cutoffYear && mo < cutoffMonth)) {\n await prisma.$executeRawUnsafe(`DROP TABLE IF EXISTS \"${row.partition_name}\";`);\n dropped.push(row.partition_name);\n }\n }\n return dropped;\n}\n","/**\n * Multi-provider LLM wrapper with timeout, retries, jitter, provider\n * fallback chain, token cap, and streaming passthrough.\n *\n * No hard dependency on a specific SDK — consumers register adapters.\n * Provider chain order is controlled by env `LLM_PROVIDER_CHAIN`\n * (comma-separated, e.g. `anthropic,openai,openrouter`).\n *\n * The wrapper is intentionally minimal — callers should construct it\n * once at boot, register adapters, and inject the singleton.\n */\n\nimport { logger } from '../logger/index.js';\n\nexport interface LLMRequest {\n model?: string;\n messages: Array<{ role: 'system' | 'user' | 'assistant'; content: string }>;\n maxTokens?: number;\n temperature?: number;\n stream?: boolean;\n /** Override timeout for this request. */\n timeoutMs?: number;\n}\n\nexport interface LLMResponse {\n provider: string;\n content: string;\n inputTokens?: number;\n outputTokens?: number;\n raw?: unknown;\n}\n\nexport interface LLMProviderAdapter {\n name: string;\n complete(req: LLMRequest, signal: AbortSignal): Promise<LLMResponse>;\n}\n\nexport interface LLMRouterOptions {\n /** Default per-attempt timeout (ms). */\n timeoutMs?: number;\n /** Max attempts across providers. */\n maxAttempts?: number;\n /** Initial backoff (ms). */\n initialDelayMs?: number;\n /** Hard cap on output tokens regardless of caller request. */\n maxOutputTokensCap?: number;\n}\n\nconst DEFAULTS: Required<LLMRouterOptions> = {\n timeoutMs: 30_000,\n maxAttempts: 3,\n initialDelayMs: 500,\n maxOutputTokensCap: 4096,\n};\n\nfunction jitter(n: number): number {\n return Math.floor(Math.random() * n);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((r) => setTimeout(r, ms));\n}\n\nexport class LLMRouter {\n private readonly adapters: Map<string, LLMProviderAdapter> = new Map();\n private readonly opts: Required<LLMRouterOptions>;\n\n constructor(opts: LLMRouterOptions = {}) {\n this.opts = { ...DEFAULTS, ...opts };\n }\n\n register(adapter: LLMProviderAdapter): void {\n this.adapters.set(adapter.name, adapter);\n }\n\n private resolveChain(): string[] {\n const envChain = process.env['LLM_PROVIDER_CHAIN']?.trim();\n if (envChain) {\n return envChain\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean);\n }\n return Array.from(this.adapters.keys());\n }\n\n async complete(req: LLMRequest): Promise<LLMResponse> {\n const cappedReq: LLMRequest = {\n ...req,\n maxTokens: Math.min(req.maxTokens ?? this.opts.maxOutputTokensCap, this.opts.maxOutputTokensCap),\n };\n const chain = this.resolveChain();\n if (chain.length === 0) {\n throw new Error('LLMRouter: no providers registered');\n }\n\n let lastErr: unknown = null;\n for (let attempt = 0; attempt < this.opts.maxAttempts; attempt++) {\n const providerName = chain[attempt % chain.length];\n const adapter = providerName ? this.adapters.get(providerName) : undefined;\n if (!adapter) {\n logger.warn('llmRouter.provider.notRegistered', { providerName });\n continue;\n }\n const timeoutMs = req.timeoutMs ?? this.opts.timeoutMs;\n const ctrl = new AbortController();\n const t = setTimeout(() => ctrl.abort(), timeoutMs);\n try {\n const response = await adapter.complete(cappedReq, ctrl.signal);\n return response;\n } catch (err) {\n lastErr = err;\n logger.warn('llmRouter.attempt.failed', { provider: adapter.name, attempt, err: String(err) });\n if (attempt < this.opts.maxAttempts - 1) {\n const delay = this.opts.initialDelayMs * 2 ** attempt;\n await sleep(jitter(delay));\n }\n } finally {\n clearTimeout(t);\n }\n }\n throw lastErr instanceof Error ? lastErr : new Error(`LLMRouter exhausted ${this.opts.maxAttempts} attempts`);\n }\n}\n"]}
|
|
@@ -30,12 +30,14 @@ interface WorkspaceExtensionConfig {
|
|
|
30
30
|
allowedUnguardedOperations?: string[];
|
|
31
31
|
debug?: boolean;
|
|
32
32
|
enableApplicationNameTagging?: boolean;
|
|
33
|
+
enableRlsGucTagging?: boolean;
|
|
33
34
|
}
|
|
34
35
|
declare function injectWhereWorkspaceId(where: Record<string, unknown> | undefined, wsCtx?: WorkspaceContext): Record<string, unknown> | undefined;
|
|
35
36
|
type RawPrismaForTagging = {
|
|
36
37
|
$executeRawUnsafe: (query: string, ...values: unknown[]) => Promise<number>;
|
|
37
38
|
};
|
|
38
39
|
declare function maybeTagConnection(rawPrisma: RawPrismaForTagging, wsCtx: WorkspaceContext): Promise<void>;
|
|
40
|
+
declare function maybeSetRlsGuc(rawPrisma: RawPrismaForTagging, wsCtx: WorkspaceContext): Promise<void>;
|
|
39
41
|
declare function addWorkspaceExtension<T>(baseClient: T, config?: WorkspaceExtensionConfig): T;
|
|
40
42
|
|
|
41
43
|
interface DatabaseClientConfig extends PrismaClientConfig {
|
|
@@ -198,6 +200,7 @@ declare const index_initializeDatabaseWithConfig: typeof initializeDatabaseWithC
|
|
|
198
200
|
declare const index_injectWhereWorkspaceId: typeof injectWhereWorkspaceId;
|
|
199
201
|
declare const index_isDatabaseInitialized: typeof isDatabaseInitialized;
|
|
200
202
|
declare const index_loadGeneratedFields: typeof loadGeneratedFields;
|
|
203
|
+
declare const index_maybeSetRlsGuc: typeof maybeSetRlsGuc;
|
|
201
204
|
declare const index_maybeTagConnection: typeof maybeTagConnection;
|
|
202
205
|
declare const index_mergeContext: typeof mergeContext;
|
|
203
206
|
declare const index_parseContext: typeof parseContext;
|
|
@@ -209,7 +212,7 @@ declare const index_toContextJson: typeof toContextJson;
|
|
|
209
212
|
declare const index_withWorkspaceContext: typeof withWorkspaceContext;
|
|
210
213
|
declare const index_withWorkspaceContextSync: typeof withWorkspaceContextSync;
|
|
211
214
|
declare namespace index {
|
|
212
|
-
export { index_ConnectionState as ConnectionState, type index_ContextFilterInput as ContextFilterInput, type index_DatabaseClient as DatabaseClient, type index_DatabaseClientConfig as DatabaseClientConfig, index_DatabaseHealth as DatabaseHealth, index_DatabaseReturnType as DatabaseReturnType, type index_FieldExtractionOptions as FieldExtractionOptions, type index_FieldExtractionResult as FieldExtractionResult, type index_InputJsonValue as InputJsonValue, type index_JsonValue as JsonValue, type index_ModelFieldsMap as ModelFieldsMap, type index_OperationContext as OperationContext, type index_PoolTuningEnv as PoolTuningEnv, index_PrismaClientBase as PrismaClientBase, index_PrismaClientConfig as PrismaClientConfig, index_PrismaClientConstructorOptions as PrismaClientConstructorOptions, index_PrismaClientWrapper as PrismaClientWrapper, index_PrismaEvent as PrismaEvent, type index_PrismaJsonFilter as PrismaJsonFilter, index_PrismaLogDefinition as PrismaLogDefinition, index_PrismaLogEvent as PrismaLogEvent, index_PrismaLogLevel as PrismaLogLevel, index_PrismaQueryEvent as PrismaQueryEvent, index_PrismaTransactionOptions as PrismaTransactionOptions, type index_WorkspaceContext as WorkspaceContext, type index_WorkspaceExtensionConfig as WorkspaceExtensionConfig, index_addWorkspaceExtension as addWorkspaceExtension, index_buildContextWhereClause as buildContextWhereClause, index_buildContextWhereConditions as buildContextWhereConditions, index_checkDatabaseHealth as checkDatabaseHealth, index_configurePrismaLogging as configurePrismaLogging, index_contextMatches as contextMatches, index_createConnectionPool as createConnectionPool, index_createContextFromSDK as createContextFromSDK, index_createDatabaseClient as createDatabaseClient, index_createDatabaseClientFromEnv as createDatabaseClientFromEnv, index_createPrismaAdapter as createPrismaAdapter, index_createPrismaClient as createPrismaClient, index_ensureServiceApplicationName as ensureServiceApplicationName, index_extractFieldsFromModel as extractFieldsFromModel, index_getAllModelNames as getAllModelNames, index_getDatabaseManager as getDatabaseManager, index_getDatabaseProductName as getDatabaseProductName, index_getDatabaseStats as getDatabaseStats, index_getDatabaseVersion as getDatabaseVersion, index_getDb as getDb, index_getModelFields as getModelFields, index_getWorkspaceContext as getWorkspaceContext, index_hasModel as hasModel, index_initializeDatabase as initializeDatabase, index_initializeDatabaseWithConfig as initializeDatabaseWithConfig, index_injectWhereWorkspaceId as injectWhereWorkspaceId, index_isDatabaseInitialized as isDatabaseInitialized, index_loadGeneratedFields as loadGeneratedFields, index_maybeTagConnection as maybeTagConnection, index_mergeContext as mergeContext, index_parseContext as parseContext, index_resetDatabaseManager as resetDatabaseManager, index_resolvePoolTuningFromEnv as resolvePoolTuningFromEnv, index_setWorkspaceContext as setWorkspaceContext, index_testConnection as testConnection, index_toContextJson as toContextJson, index_withWorkspaceContext as withWorkspaceContext, index_withWorkspaceContextSync as withWorkspaceContextSync };
|
|
215
|
+
export { index_ConnectionState as ConnectionState, type index_ContextFilterInput as ContextFilterInput, type index_DatabaseClient as DatabaseClient, type index_DatabaseClientConfig as DatabaseClientConfig, index_DatabaseHealth as DatabaseHealth, index_DatabaseReturnType as DatabaseReturnType, type index_FieldExtractionOptions as FieldExtractionOptions, type index_FieldExtractionResult as FieldExtractionResult, type index_InputJsonValue as InputJsonValue, type index_JsonValue as JsonValue, type index_ModelFieldsMap as ModelFieldsMap, type index_OperationContext as OperationContext, type index_PoolTuningEnv as PoolTuningEnv, index_PrismaClientBase as PrismaClientBase, index_PrismaClientConfig as PrismaClientConfig, index_PrismaClientConstructorOptions as PrismaClientConstructorOptions, index_PrismaClientWrapper as PrismaClientWrapper, index_PrismaEvent as PrismaEvent, type index_PrismaJsonFilter as PrismaJsonFilter, index_PrismaLogDefinition as PrismaLogDefinition, index_PrismaLogEvent as PrismaLogEvent, index_PrismaLogLevel as PrismaLogLevel, index_PrismaQueryEvent as PrismaQueryEvent, index_PrismaTransactionOptions as PrismaTransactionOptions, type index_WorkspaceContext as WorkspaceContext, type index_WorkspaceExtensionConfig as WorkspaceExtensionConfig, index_addWorkspaceExtension as addWorkspaceExtension, index_buildContextWhereClause as buildContextWhereClause, index_buildContextWhereConditions as buildContextWhereConditions, index_checkDatabaseHealth as checkDatabaseHealth, index_configurePrismaLogging as configurePrismaLogging, index_contextMatches as contextMatches, index_createConnectionPool as createConnectionPool, index_createContextFromSDK as createContextFromSDK, index_createDatabaseClient as createDatabaseClient, index_createDatabaseClientFromEnv as createDatabaseClientFromEnv, index_createPrismaAdapter as createPrismaAdapter, index_createPrismaClient as createPrismaClient, index_ensureServiceApplicationName as ensureServiceApplicationName, index_extractFieldsFromModel as extractFieldsFromModel, index_getAllModelNames as getAllModelNames, index_getDatabaseManager as getDatabaseManager, index_getDatabaseProductName as getDatabaseProductName, index_getDatabaseStats as getDatabaseStats, index_getDatabaseVersion as getDatabaseVersion, index_getDb as getDb, index_getModelFields as getModelFields, index_getWorkspaceContext as getWorkspaceContext, index_hasModel as hasModel, index_initializeDatabase as initializeDatabase, index_initializeDatabaseWithConfig as initializeDatabaseWithConfig, index_injectWhereWorkspaceId as injectWhereWorkspaceId, index_isDatabaseInitialized as isDatabaseInitialized, index_loadGeneratedFields as loadGeneratedFields, index_maybeSetRlsGuc as maybeSetRlsGuc, index_maybeTagConnection as maybeTagConnection, index_mergeContext as mergeContext, index_parseContext as parseContext, index_resetDatabaseManager as resetDatabaseManager, index_resolvePoolTuningFromEnv as resolvePoolTuningFromEnv, index_setWorkspaceContext as setWorkspaceContext, index_testConnection as testConnection, index_toContextJson as toContextJson, index_withWorkspaceContext as withWorkspaceContext, index_withWorkspaceContextSync as withWorkspaceContextSync };
|
|
213
216
|
}
|
|
214
217
|
|
|
215
|
-
export { isDatabaseInitialized as A, loadGeneratedFields as B, type ContextFilterInput as C, type DatabaseClient as D,
|
|
218
|
+
export { isDatabaseInitialized as A, loadGeneratedFields as B, type ContextFilterInput as C, type DatabaseClient as D, maybeSetRlsGuc as E, type FieldExtractionOptions as F, maybeTagConnection as G, mergeContext as H, type InputJsonValue as I, type JsonValue as J, parseContext as K, resetDatabaseManager as L, type ModelFieldsMap as M, resolvePoolTuningFromEnv as N, type OperationContext as O, type PoolTuningEnv as P, setWorkspaceContext as Q, testConnection as R, toContextJson as S, withWorkspaceContext as T, withWorkspaceContextSync as U, type WorkspaceContext as W, type DatabaseClientConfig as a, type FieldExtractionResult as b, type PrismaJsonFilter as c, type WorkspaceExtensionConfig as d, addWorkspaceExtension as e, buildContextWhereClause as f, buildContextWhereConditions as g, checkDatabaseHealth as h, index as i, contextMatches as j, createContextFromSDK as k, createDatabaseClient as l, createDatabaseClientFromEnv as m, extractFieldsFromModel as n, getAllModelNames as o, getDatabaseManager as p, getDatabaseProductName as q, getDatabaseStats as r, getDatabaseVersion as s, getDb as t, getModelFields as u, getWorkspaceContext as v, hasModel as w, initializeDatabase as x, initializeDatabaseWithConfig as y, injectWhereWorkspaceId as z };
|
|
@@ -123,6 +123,10 @@ interface OffsetPageResult<TItem> {
|
|
|
123
123
|
nextOffset: number | null;
|
|
124
124
|
}
|
|
125
125
|
declare function buildOffsetPage<TItem>(items: TItem[], total: number, pagination: NormalizedOffsetPagination): OffsetPageResult<TItem>;
|
|
126
|
+
declare function toPrismaPage(pagination: NormalizedOffsetPagination): {
|
|
127
|
+
take: number;
|
|
128
|
+
skip: number;
|
|
129
|
+
};
|
|
126
130
|
interface PaginateInput<TWhere, TOrderBy> {
|
|
127
131
|
take?: number | null;
|
|
128
132
|
cursor?: string | null;
|
|
@@ -294,9 +298,10 @@ declare const index_normalizeOffsetPagination: typeof normalizeOffsetPagination;
|
|
|
294
298
|
declare const index_paginate: typeof paginate;
|
|
295
299
|
declare const index_rateLimitIncr: typeof rateLimitIncr;
|
|
296
300
|
declare const index_resolveReferenceLoader: typeof resolveReferenceLoader;
|
|
301
|
+
declare const index_toPrismaPage: typeof toPrismaPage;
|
|
297
302
|
declare const index_withLeaderLock: typeof withLeaderLock;
|
|
298
303
|
declare namespace index {
|
|
299
|
-
export { type index_BreakerConfig as BreakerConfig, type index_BuildConnectionOptions as BuildConnectionOptions, type index_CacheVersionRedis as CacheVersionRedis, index_CircuitBreakerOpenError as CircuitBreakerOpenError, type index_ClampLimitOptions as ClampLimitOptions, type index_ConnectionEdge as ConnectionEdge, type index_ConnectionResult as ConnectionResult, type index_CursorPaginationInput as CursorPaginationInput, type index_CursorPayload as CursorPayload, type index_CursorPayloadValue as CursorPayloadValue, index_DEFAULT_GRAPHQL_PAGE_LIMIT as DEFAULT_GRAPHQL_PAGE_LIMIT, type index_DataLoaderLike as DataLoaderLike, type index_DropOldOptions as DropOldOptions, type index_EnsureMonthlyOptions as EnsureMonthlyOptions, type index_HttpClientConfig as HttpClientConfig, type index_HttpClientInit as HttpClientInit, type index_LLMProviderAdapter as LLMProviderAdapter, type index_LLMRequest as LLMRequest, type index_LLMResponse as LLMResponse, index_LLMRouter as LLMRouter, type index_LLMRouterOptions as LLMRouterOptions, type index_LeaderLockOptions as LeaderLockOptions, type index_LeaderLockRedis as LeaderLockRedis, type index_LeaderLockResult as LeaderLockResult, type index_LoaderBuilder as LoaderBuilder, type index_LoaderMap as LoaderMap, index_MAX_GRAPHQL_PAGE_LIMIT as MAX_GRAPHQL_PAGE_LIMIT, type index_NormalizedCursorPagination as NormalizedCursorPagination, type index_NormalizedOffsetPagination as NormalizedOffsetPagination, type index_OffsetPageResult as OffsetPageResult, type index_OffsetPaginationInput as OffsetPaginationInput, type index_PageInfo as PageInfo, type index_PaginateInput as PaginateInput, type index_PaginateResult as PaginateResult, type index_PrismaModelLike as PrismaModelLike, type index_PrismaRawClient as PrismaRawClient, type index_RateLimitInput as RateLimitInput, type index_RateLimitRedis as RateLimitRedis, type index_RateLimitResult as RateLimitResult, type index_ReferenceObject as ReferenceObject, type index_RetryConfig as RetryConfig, index___resetHttpClientBreakers as __resetHttpClientBreakers, index_buildCacheKey as buildCacheKey, index_buildConnection as buildConnection, index_buildLoaders as buildLoaders, index_buildOffsetPage as buildOffsetPage, index_clampGraphqlLimit as clampGraphqlLimit, index_clampLimit as clampLimit, index_clampOffset as clampOffset, index_createHttpClient as createHttpClient, index_decodeCursor as decodeCursor, index_dropOldPartitions as dropOldPartitions, index_encodeCursor as encodeCursor, index_ensureMonthlyPartitions as ensureMonthlyPartitions, index_getNamespaceVersion as getNamespaceVersion, index_httpClient as httpClient, index_invalidateNamespace as invalidateNamespace, index_monthlyPartitionName as monthlyPartitionName, index_normalizeCursorPagination as normalizeCursorPagination, index_normalizeOffsetPagination as normalizeOffsetPagination, index_paginate as paginate, index_rateLimitIncr as rateLimitIncr, index_resolveReferenceLoader as resolveReferenceLoader, index_withLeaderLock as withLeaderLock };
|
|
304
|
+
export { type index_BreakerConfig as BreakerConfig, type index_BuildConnectionOptions as BuildConnectionOptions, type index_CacheVersionRedis as CacheVersionRedis, index_CircuitBreakerOpenError as CircuitBreakerOpenError, type index_ClampLimitOptions as ClampLimitOptions, type index_ConnectionEdge as ConnectionEdge, type index_ConnectionResult as ConnectionResult, type index_CursorPaginationInput as CursorPaginationInput, type index_CursorPayload as CursorPayload, type index_CursorPayloadValue as CursorPayloadValue, index_DEFAULT_GRAPHQL_PAGE_LIMIT as DEFAULT_GRAPHQL_PAGE_LIMIT, type index_DataLoaderLike as DataLoaderLike, type index_DropOldOptions as DropOldOptions, type index_EnsureMonthlyOptions as EnsureMonthlyOptions, type index_HttpClientConfig as HttpClientConfig, type index_HttpClientInit as HttpClientInit, type index_LLMProviderAdapter as LLMProviderAdapter, type index_LLMRequest as LLMRequest, type index_LLMResponse as LLMResponse, index_LLMRouter as LLMRouter, type index_LLMRouterOptions as LLMRouterOptions, type index_LeaderLockOptions as LeaderLockOptions, type index_LeaderLockRedis as LeaderLockRedis, type index_LeaderLockResult as LeaderLockResult, type index_LoaderBuilder as LoaderBuilder, type index_LoaderMap as LoaderMap, index_MAX_GRAPHQL_PAGE_LIMIT as MAX_GRAPHQL_PAGE_LIMIT, type index_NormalizedCursorPagination as NormalizedCursorPagination, type index_NormalizedOffsetPagination as NormalizedOffsetPagination, type index_OffsetPageResult as OffsetPageResult, type index_OffsetPaginationInput as OffsetPaginationInput, type index_PageInfo as PageInfo, type index_PaginateInput as PaginateInput, type index_PaginateResult as PaginateResult, type index_PrismaModelLike as PrismaModelLike, type index_PrismaRawClient as PrismaRawClient, type index_RateLimitInput as RateLimitInput, type index_RateLimitRedis as RateLimitRedis, type index_RateLimitResult as RateLimitResult, type index_ReferenceObject as ReferenceObject, type index_RetryConfig as RetryConfig, index___resetHttpClientBreakers as __resetHttpClientBreakers, index_buildCacheKey as buildCacheKey, index_buildConnection as buildConnection, index_buildLoaders as buildLoaders, index_buildOffsetPage as buildOffsetPage, index_clampGraphqlLimit as clampGraphqlLimit, index_clampLimit as clampLimit, index_clampOffset as clampOffset, index_createHttpClient as createHttpClient, index_decodeCursor as decodeCursor, index_dropOldPartitions as dropOldPartitions, index_encodeCursor as encodeCursor, index_ensureMonthlyPartitions as ensureMonthlyPartitions, index_getNamespaceVersion as getNamespaceVersion, index_httpClient as httpClient, index_invalidateNamespace as invalidateNamespace, index_monthlyPartitionName as monthlyPartitionName, index_normalizeCursorPagination as normalizeCursorPagination, index_normalizeOffsetPagination as normalizeOffsetPagination, index_paginate as paginate, index_rateLimitIncr as rateLimitIncr, index_resolveReferenceLoader as resolveReferenceLoader, index_toPrismaPage as toPrismaPage, index_withLeaderLock as withLeaderLock };
|
|
300
305
|
}
|
|
301
306
|
|
|
302
|
-
export { encodeCursor as $, type PrismaRawClient as A, type BreakerConfig as B, type CacheVersionRedis as C, DEFAULT_GRAPHQL_PAGE_LIMIT as D, type EnsureMonthlyOptions as E, type RateLimitRedis as F, type RateLimitResult as G, type HttpClientConfig as H, type ReferenceObject as I, type RetryConfig as J, buildCacheKey as K, type LLMProviderAdapter as L, MAX_GRAPHQL_PAGE_LIMIT as M, type NormalizedCursorPagination as N, type OffsetPageResult as O, type PageInfo as P, buildConnection as Q, type RateLimitInput as R, buildLoaders as S, buildOffsetPage as T, clampGraphqlLimit as U, clampLimit as V, clampOffset as W, createHttpClient as X, decodeCursor as Y, dropOldPartitions as Z, __resetHttpClientBreakers as _, type BuildConnectionOptions as a, ensureMonthlyPartitions as a0, getNamespaceVersion as a1, httpClient as a2, invalidateNamespace as a3, monthlyPartitionName as a4, normalizeCursorPagination as a5, normalizeOffsetPagination as a6, paginate as a7, rateLimitIncr as a8, resolveReferenceLoader as a9,
|
|
307
|
+
export { encodeCursor as $, type PrismaRawClient as A, type BreakerConfig as B, type CacheVersionRedis as C, DEFAULT_GRAPHQL_PAGE_LIMIT as D, type EnsureMonthlyOptions as E, type RateLimitRedis as F, type RateLimitResult as G, type HttpClientConfig as H, type ReferenceObject as I, type RetryConfig as J, buildCacheKey as K, type LLMProviderAdapter as L, MAX_GRAPHQL_PAGE_LIMIT as M, type NormalizedCursorPagination as N, type OffsetPageResult as O, type PageInfo as P, buildConnection as Q, type RateLimitInput as R, buildLoaders as S, buildOffsetPage as T, clampGraphqlLimit as U, clampLimit as V, clampOffset as W, createHttpClient as X, decodeCursor as Y, dropOldPartitions as Z, __resetHttpClientBreakers as _, type BuildConnectionOptions as a, ensureMonthlyPartitions as a0, getNamespaceVersion as a1, httpClient as a2, invalidateNamespace as a3, monthlyPartitionName as a4, normalizeCursorPagination as a5, normalizeOffsetPagination as a6, paginate as a7, rateLimitIncr as a8, resolveReferenceLoader as a9, toPrismaPage as aa, withLeaderLock as ab, CircuitBreakerOpenError as b, type ClampLimitOptions as c, type ConnectionEdge as d, type ConnectionResult as e, type CursorPaginationInput as f, type CursorPayload as g, type CursorPayloadValue as h, index as i, type DataLoaderLike as j, type DropOldOptions as k, type HttpClientInit as l, type LLMRequest as m, type LLMResponse as n, LLMRouter as o, type LLMRouterOptions as p, type LeaderLockOptions as q, type LeaderLockRedis as r, type LeaderLockResult as s, type LoaderBuilder as t, type LoaderMap as u, type NormalizedOffsetPagination as v, type OffsetPaginationInput as w, type PaginateInput as x, type PaginateResult as y, type PrismaModelLike as z };
|
package/dist/index.d.ts
CHANGED
|
@@ -23,7 +23,7 @@ export { i as Cache } from './index-DkObbJD_.js';
|
|
|
23
23
|
export { i as Middleware } from './index-DSOpj8DI.js';
|
|
24
24
|
export { i as Observability } from './index-4gKQKZ2B.js';
|
|
25
25
|
export { i as GraphQL } from './index-joONjwLt.js';
|
|
26
|
-
export { i as Prisma } from './index-
|
|
26
|
+
export { i as Prisma } from './index-D3lGLwby.js';
|
|
27
27
|
export { i as Utils } from './index-PaojfSdd.js';
|
|
28
28
|
export { i as I18n, I as I18nCapableContext, T as Translator, c as createTranslator, g as getLanguage, a as getLocale, h as hasI18n, t } from './index-D4l1u8VR.js';
|
|
29
29
|
export { i as Export } from './index-B4ciT3OZ.js';
|
|
@@ -35,7 +35,7 @@ export { i as Crypto } from './index-e_18DzAg.js';
|
|
|
35
35
|
export { i as Gateway } from './index-Dy6neH2G.js';
|
|
36
36
|
export { i as FeatureFlags } from './index-BdPnlJ8_.js';
|
|
37
37
|
export { i as Captcha, R as RecaptchaVerifyOptions, a as RecaptchaVerifyResult, b as isCaptchaEnabled, v as verifyCaptcha, c as verifyCaptchaIfEnabled } from './index-B70b5mYS.js';
|
|
38
|
-
export { i as Platform } from './index-
|
|
38
|
+
export { i as Platform } from './index-lcW5eSTp.js';
|
|
39
39
|
export { C as CircuitBreakerConfig, h as DEFAULT_CIRCUIT_BREAKER_CONFIG, i as DEFAULT_GATEWAY_RETRY_CONFIG, D as DEFAULT_GATEWAY_ROUTING, b as DEFAULT_LAYER_RESOURCES, c as DEFAULT_LAYER_STREAMS, f as GatewayRequestHeaders, g as GatewayRetryConfig, G as GatewayRoutingConfig, L as LayerConfig, a as LayerFullConfig, d as LayerGatewayConfig, e as LayerResourceUrls, S as ServiceLayer } from './layer-GNAVXBMf.js';
|
|
40
40
|
import './types-CXVleyWq.js';
|
|
41
41
|
import 'graphql';
|
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { ActivityModule, UsageModule, TrackerModule } from './chunk-XN3DNXXV.js';
|
|
2
2
|
export { ActivityModule, TrackerModule, UsageModule } from './chunk-XN3DNXXV.js';
|
|
3
|
-
export { prisma_exports as Prisma } from './chunk-
|
|
3
|
+
export { prisma_exports as Prisma } from './chunk-HIH4SVR3.js';
|
|
4
|
+
export { RESOURCE_CAP_DEFAULTS, ResourceCapExceededError, ResourceCapsModule, getResourceCaps } from './chunk-VDDOGIWY.js';
|
|
4
5
|
import { RBACModule } from './chunk-S32JOMMW.js';
|
|
5
6
|
export { RBACModule, createRBACDirective, createRBACDirectiveForLayer, createRBACDirectiveFromEnv } from './chunk-S32JOMMW.js';
|
|
6
|
-
|
|
7
|
-
import './chunk-QLXIIF4I.js';
|
|
7
|
+
import './chunk-MXLCLLCI.js';
|
|
8
8
|
export { sharing_exports as Sharing } from './chunk-XD5ZK727.js';
|
|
9
9
|
export { TemporalClient, TemporalClientFactory, TemporalModule, TemporalWorker, TemporalWorkerFactory, TemporalWorkerManager } from './chunk-IC7YDBGE.js';
|
|
10
10
|
export { instrumentation_exports as Instrumentation } from './chunk-ACYGOENW.js';
|
|
@@ -13,11 +13,9 @@ export { middleware_exports as Middleware } from './chunk-2HANKZZM.js';
|
|
|
13
13
|
import { TenantNotificationsModule, NotificationsModule } from './chunk-ZMCD5XAK.js';
|
|
14
14
|
export { tenant_notifications_exports as Notifications, NotificationsModule } from './chunk-ZMCD5XAK.js';
|
|
15
15
|
export { observability_exports as Observability } from './chunk-5LXDPGDH.js';
|
|
16
|
-
export { platform_exports as Platform } from './chunk-
|
|
16
|
+
export { platform_exports as Platform } from './chunk-YCKM7FS7.js';
|
|
17
17
|
export { export_exports as Export } from './chunk-5BCCI2FV.js';
|
|
18
18
|
export { feature_flags_exports as FeatureFlags } from './chunk-MNKU7I2G.js';
|
|
19
|
-
export { graphql_exports as GraphQL } from './chunk-X4NELQLV.js';
|
|
20
|
-
import './chunk-QLVKMWFA.js';
|
|
21
19
|
import { GraphModule } from './chunk-STLDHYPB.js';
|
|
22
20
|
export { graph_exports as Graph, GraphModule } from './chunk-STLDHYPB.js';
|
|
23
21
|
import './chunk-Q23NPVWQ.js';
|
|
@@ -25,7 +23,10 @@ import { EventsModule } from './chunk-H3AXO5SY.js';
|
|
|
25
23
|
export { event_queue_exports as EventQueue, EventsModule } from './chunk-H3AXO5SY.js';
|
|
26
24
|
import './chunk-OHEPNJ2X.js';
|
|
27
25
|
import { QueueType, EventQueueFactory } from './chunk-MQCVQCFA.js';
|
|
26
|
+
export { graphql_exports as GraphQL } from './chunk-X4NELQLV.js';
|
|
27
|
+
import './chunk-QLVKMWFA.js';
|
|
28
28
|
import './chunk-MHNA7IS7.js';
|
|
29
|
+
export { i18n_exports as I18n, createTranslator, getLanguage, getLocale, hasI18n, t } from './chunk-ULFFX3YE.js';
|
|
29
30
|
export { init_exports as Init } from './chunk-5WRBQUS3.js';
|
|
30
31
|
import { GatewayClient, GatewayError, GatewayErrorType } from './chunk-IDKU7OGF.js';
|
|
31
32
|
export { gateway_exports as Gateway } from './chunk-IDKU7OGF.js';
|
|
@@ -34,21 +35,20 @@ export { layer_exports as Layer } from './chunk-UIMPJNWC.js';
|
|
|
34
35
|
import './chunk-VFCMR5GX.js';
|
|
35
36
|
import { ContextManager } from './chunk-RZOFS2BQ.js';
|
|
36
37
|
export { ContextManager } from './chunk-RZOFS2BQ.js';
|
|
37
|
-
export {
|
|
38
|
+
export { cache_exports as Cache } from './chunk-UYE4IEPT.js';
|
|
38
39
|
import { AuthModule } from './chunk-RXMOV3YE.js';
|
|
39
40
|
export { AuthModule } from './chunk-RXMOV3YE.js';
|
|
40
41
|
export { utils_exports as Utils } from './chunk-B7I4TABG.js';
|
|
41
|
-
export { cache_exports as Cache } from './chunk-UYE4IEPT.js';
|
|
42
42
|
export { captcha_exports as Captcha, isCaptchaEnabled, verifyCaptcha, verifyCaptchaIfEnabled } from './chunk-YMZEUTD2.js';
|
|
43
43
|
export { createInternalClient, createInternalClientForTenant, createInternalClientForWorkspaces } from './chunk-VI4VSNTI.js';
|
|
44
|
-
export { crypto_exports as Crypto } from './chunk-SBS4S2PJ.js';
|
|
45
|
-
export { dataloader_exports as DataLoader } from './chunk-NUB5GQTU.js';
|
|
46
44
|
import { DatabaseModule } from './chunk-A6DGEZJ4.js';
|
|
47
45
|
export { DatabaseModule } from './chunk-A6DGEZJ4.js';
|
|
48
46
|
import { APIError, NetworkError, TimeoutError, ValidationError } from './chunk-QGBXVNRM.js';
|
|
49
47
|
export { DEFAULT_CIRCUIT_BREAKER_CONFIG, DEFAULT_GATEWAY_RETRY_CONFIG, DEFAULT_GATEWAY_ROUTING, DEFAULT_LAYER_RESOURCES, DEFAULT_LAYER_STREAMS } from './chunk-YFOHAHZE.js';
|
|
50
48
|
import { logger } from './chunk-CBZNP6RF.js';
|
|
51
49
|
export { logger_exports as Logger } from './chunk-CBZNP6RF.js';
|
|
50
|
+
export { crypto_exports as Crypto } from './chunk-SBS4S2PJ.js';
|
|
51
|
+
export { dataloader_exports as DataLoader } from './chunk-NUB5GQTU.js';
|
|
52
52
|
import { __name } from './chunk-XE4OXN2W.js';
|
|
53
53
|
import { GraphQLClient } from 'graphql-request';
|
|
54
54
|
|
package/dist/platform/index.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { B as BreakerConfig, a as BuildConnectionOptions, C as CacheVersionRedis, b as CircuitBreakerOpenError, c as ClampLimitOptions, d as ConnectionEdge, e as ConnectionResult, f as CursorPaginationInput, g as CursorPayload, h as CursorPayloadValue, D as DEFAULT_GRAPHQL_PAGE_LIMIT, j as DataLoaderLike, k as DropOldOptions, E as EnsureMonthlyOptions, H as HttpClientConfig, l as HttpClientInit, L as LLMProviderAdapter, m as LLMRequest, n as LLMResponse, o as LLMRouter, p as LLMRouterOptions, q as LeaderLockOptions, r as LeaderLockRedis, s as LeaderLockResult, t as LoaderBuilder, u as LoaderMap, M as MAX_GRAPHQL_PAGE_LIMIT, N as NormalizedCursorPagination, v as NormalizedOffsetPagination, O as OffsetPageResult, w as OffsetPaginationInput, P as PageInfo, x as PaginateInput, y as PaginateResult, z as PrismaModelLike, A as PrismaRawClient, R as RateLimitInput, F as RateLimitRedis, G as RateLimitResult, I as ReferenceObject, J as RetryConfig, _ as __resetHttpClientBreakers, K as buildCacheKey, Q as buildConnection, S as buildLoaders, T as buildOffsetPage, U as clampGraphqlLimit, V as clampLimit, W as clampOffset, X as createHttpClient, Y as decodeCursor, Z as dropOldPartitions, $ as encodeCursor, a0 as ensureMonthlyPartitions, a1 as getNamespaceVersion, a2 as httpClient, a3 as invalidateNamespace, a4 as monthlyPartitionName, a5 as normalizeCursorPagination, a6 as normalizeOffsetPagination, a7 as paginate, a8 as rateLimitIncr, a9 as resolveReferenceLoader, aa as withLeaderLock } from '../index-
|
|
1
|
+
export { B as BreakerConfig, a as BuildConnectionOptions, C as CacheVersionRedis, b as CircuitBreakerOpenError, c as ClampLimitOptions, d as ConnectionEdge, e as ConnectionResult, f as CursorPaginationInput, g as CursorPayload, h as CursorPayloadValue, D as DEFAULT_GRAPHQL_PAGE_LIMIT, j as DataLoaderLike, k as DropOldOptions, E as EnsureMonthlyOptions, H as HttpClientConfig, l as HttpClientInit, L as LLMProviderAdapter, m as LLMRequest, n as LLMResponse, o as LLMRouter, p as LLMRouterOptions, q as LeaderLockOptions, r as LeaderLockRedis, s as LeaderLockResult, t as LoaderBuilder, u as LoaderMap, M as MAX_GRAPHQL_PAGE_LIMIT, N as NormalizedCursorPagination, v as NormalizedOffsetPagination, O as OffsetPageResult, w as OffsetPaginationInput, P as PageInfo, x as PaginateInput, y as PaginateResult, z as PrismaModelLike, A as PrismaRawClient, R as RateLimitInput, F as RateLimitRedis, G as RateLimitResult, I as ReferenceObject, J as RetryConfig, _ as __resetHttpClientBreakers, K as buildCacheKey, Q as buildConnection, S as buildLoaders, T as buildOffsetPage, U as clampGraphqlLimit, V as clampLimit, W as clampOffset, X as createHttpClient, Y as decodeCursor, Z as dropOldPartitions, $ as encodeCursor, a0 as ensureMonthlyPartitions, a1 as getNamespaceVersion, a2 as httpClient, a3 as invalidateNamespace, a4 as monthlyPartitionName, a5 as normalizeCursorPagination, a6 as normalizeOffsetPagination, a7 as paginate, a8 as rateLimitIncr, a9 as resolveReferenceLoader, aa as toPrismaPage, ab as withLeaderLock } from '../index-lcW5eSTp.js';
|
package/dist/platform/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { CircuitBreakerOpenError, DEFAULT_GRAPHQL_PAGE_LIMIT, LLMRouter, MAX_GRAPHQL_PAGE_LIMIT, __resetHttpClientBreakers, buildCacheKey, buildConnection, buildLoaders, buildOffsetPage, clampGraphqlLimit, clampLimit, clampOffset, createHttpClient, decodeCursor, dropOldPartitions, encodeCursor, ensureMonthlyPartitions, getNamespaceVersion, httpClient, invalidateNamespace, monthlyPartitionName, normalizeCursorPagination, normalizeOffsetPagination, paginate, rateLimitIncr, resolveReferenceLoader, withLeaderLock } from '../chunk-
|
|
1
|
+
export { CircuitBreakerOpenError, DEFAULT_GRAPHQL_PAGE_LIMIT, LLMRouter, MAX_GRAPHQL_PAGE_LIMIT, __resetHttpClientBreakers, buildCacheKey, buildConnection, buildLoaders, buildOffsetPage, clampGraphqlLimit, clampLimit, clampOffset, createHttpClient, decodeCursor, dropOldPartitions, encodeCursor, ensureMonthlyPartitions, getNamespaceVersion, httpClient, invalidateNamespace, monthlyPartitionName, normalizeCursorPagination, normalizeOffsetPagination, paginate, rateLimitIncr, resolveReferenceLoader, toPrismaPage, withLeaderLock } from '../chunk-YCKM7FS7.js';
|
|
2
2
|
import '../chunk-CBZNP6RF.js';
|
|
3
3
|
import '../chunk-XE4OXN2W.js';
|
|
4
4
|
//# sourceMappingURL=index.js.map
|
package/dist/prisma/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { C as ContextFilterInput, D as DatabaseClient, a as DatabaseClientConfig, F as FieldExtractionOptions, b as FieldExtractionResult, I as InputJsonValue, J as JsonValue, M as ModelFieldsMap, O as OperationContext, P as PoolTuningEnv, c as PrismaJsonFilter, W as WorkspaceContext, d as WorkspaceExtensionConfig, e as addWorkspaceExtension, f as buildContextWhereClause, g as buildContextWhereConditions, h as checkDatabaseHealth, j as contextMatches, k as createContextFromSDK, l as createDatabaseClient, m as createDatabaseClientFromEnv, n as extractFieldsFromModel, o as getAllModelNames, p as getDatabaseManager, q as getDatabaseProductName, r as getDatabaseStats, s as getDatabaseVersion, t as getDb, u as getModelFields, v as getWorkspaceContext, w as hasModel, x as initializeDatabase, y as initializeDatabaseWithConfig, z as injectWhereWorkspaceId, A as isDatabaseInitialized, B as loadGeneratedFields, E as
|
|
1
|
+
export { C as ContextFilterInput, D as DatabaseClient, a as DatabaseClientConfig, F as FieldExtractionOptions, b as FieldExtractionResult, I as InputJsonValue, J as JsonValue, M as ModelFieldsMap, O as OperationContext, P as PoolTuningEnv, c as PrismaJsonFilter, W as WorkspaceContext, d as WorkspaceExtensionConfig, e as addWorkspaceExtension, f as buildContextWhereClause, g as buildContextWhereConditions, h as checkDatabaseHealth, j as contextMatches, k as createContextFromSDK, l as createDatabaseClient, m as createDatabaseClientFromEnv, n as extractFieldsFromModel, o as getAllModelNames, p as getDatabaseManager, q as getDatabaseProductName, r as getDatabaseStats, s as getDatabaseVersion, t as getDb, u as getModelFields, v as getWorkspaceContext, w as hasModel, x as initializeDatabase, y as initializeDatabaseWithConfig, z as injectWhereWorkspaceId, A as isDatabaseInitialized, B as loadGeneratedFields, E as maybeSetRlsGuc, G as maybeTagConnection, H as mergeContext, K as parseContext, L as resetDatabaseManager, N as resolvePoolTuningFromEnv, Q as setWorkspaceContext, R as testConnection, S as toContextJson, T as withWorkspaceContext, U as withWorkspaceContextSync } from '../index-D3lGLwby.js';
|
|
2
2
|
export { C as ConnectionState, d as DatabaseHealth, D as DatabaseReturnType, P as PrismaClientBase, c as PrismaClientConfig, a as PrismaClientConstructorOptions, b as PrismaClientWrapper, e as PrismaEvent, f as PrismaLogDefinition, g as PrismaLogEvent, h as PrismaLogLevel, i as PrismaQueryEvent, j as PrismaTransactionOptions, k as configurePrismaLogging, l as createConnectionPool, m as createPrismaAdapter, n as createPrismaClient, o as ensureServiceApplicationName } from '../client-ODOgzzs0.js';
|
|
3
3
|
import '../prisma-extension-krXnYnrN.js';
|
|
4
4
|
import '@prisma/adapter-pg';
|
package/dist/prisma/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export { buildContextWhereClause, buildContextWhereConditions, checkDatabaseHealth, contextMatches, createContextFromSDK, createDatabaseClient, createDatabaseClientFromEnv, extractFieldsFromModel, getAllModelNames, getDatabaseManager, getDatabaseProductName, getDatabaseStats, getDatabaseVersion, getDb, getModelFields, hasModel, initializeDatabase, initializeDatabaseWithConfig, isDatabaseInitialized, loadGeneratedFields, mergeContext, parseContext, resetDatabaseManager, resolvePoolTuningFromEnv, testConnection, toContextJson } from '../chunk-
|
|
2
|
-
export { addWorkspaceExtension, getWorkspaceContext, injectWhereWorkspaceId, maybeTagConnection, setWorkspaceContext, withWorkspaceContext, withWorkspaceContextSync } from '../chunk-
|
|
1
|
+
export { buildContextWhereClause, buildContextWhereConditions, checkDatabaseHealth, contextMatches, createContextFromSDK, createDatabaseClient, createDatabaseClientFromEnv, extractFieldsFromModel, getAllModelNames, getDatabaseManager, getDatabaseProductName, getDatabaseStats, getDatabaseVersion, getDb, getModelFields, hasModel, initializeDatabase, initializeDatabaseWithConfig, isDatabaseInitialized, loadGeneratedFields, mergeContext, parseContext, resetDatabaseManager, resolvePoolTuningFromEnv, testConnection, toContextJson } from '../chunk-HIH4SVR3.js';
|
|
2
|
+
export { addWorkspaceExtension, getWorkspaceContext, injectWhereWorkspaceId, maybeSetRlsGuc, maybeTagConnection, setWorkspaceContext, withWorkspaceContext, withWorkspaceContextSync } from '../chunk-MXLCLLCI.js';
|
|
3
3
|
export { PrismaClientWrapper, configurePrismaLogging, createConnectionPool, createPrismaAdapter, createPrismaClient, ensureServiceApplicationName } from '../chunk-Q23NPVWQ.js';
|
|
4
4
|
import '../chunk-OHEPNJ2X.js';
|
|
5
5
|
import '../chunk-MQCVQCFA.js';
|
package/dist/server/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { createHumanReadableErrorPlugin, formatHttpError, normalizeGraphQLResponse, createHttpErrorResponse } from '../chunk-OQLDXOZ3.js';
|
|
2
2
|
export { UserFacingGraphQLError, createHttpErrorResponse, createHumanReadableErrorPlugin, createWorkspaceGuardPlugin, formatHttpError, normalizeError, normalizeExecutionResultErrors, normalizeGraphQLResponse, normalizeGraphQLResponsePayload, toUserFacingGraphQLError } from '../chunk-OQLDXOZ3.js';
|
|
3
|
-
import { setWorkspaceContext } from '../chunk-
|
|
4
|
-
import { ContextManager } from '../chunk-RZOFS2BQ.js';
|
|
3
|
+
import { setWorkspaceContext } from '../chunk-MXLCLLCI.js';
|
|
5
4
|
import { I18n } from '../chunk-ULFFX3YE.js';
|
|
5
|
+
import { ContextManager } from '../chunk-RZOFS2BQ.js';
|
|
6
6
|
import { logger } from '../chunk-CBZNP6RF.js';
|
|
7
7
|
import { __name } from '../chunk-XE4OXN2W.js';
|
|
8
8
|
import crypto from 'crypto';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@burdenoff/be-sdk",
|
|
3
|
-
"version": "2026.705.
|
|
3
|
+
"version": "2026.705.4",
|
|
4
4
|
"description": "Backend SDK for Burdenoff products providing unified access to notifications, RBAC, activity tracking, usage monitoring, and more",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/prisma/index.ts","../src/prisma/factory.ts","../src/prisma/manager.ts","../src/prisma/health.ts","../src/prisma/fields.ts","../src/prisma/context.ts"],"names":["resolveWorkspaceExtensionDefault","productName","explicit","process","env","layer","toLowerCase","name","startsWith","createDatabaseClient","PrismaClientConstructor","config","enableGraphExtension","graphEventEmitter","enableWorkspaceExtension","workspaceExtensionConfig","registerShutdownHandlers","prismaConfig","prismaConfigWithDefaults","applicationName","ensureServiceApplicationName","wrapper","createPrismaClient","baseClient","getClient","extendedClient","eventEmitter","getGraphEventEmitter","graphConfig","enabled","addGraphExtension","logger","info","addWorkspaceExtension","db","debug","connect","retries","delay","disconnect","parsePositiveIntEnv","raw","trim","undefined","parsed","Number","parseInt","isFinite","resolvePoolTuningFromEnv","tuning","statementTimeout","statementTimeoutMillis","idleInTransactionTimeout","idleInTransactionTimeoutMillis","lockTimeout","lockTimeoutMillis","createDatabaseClientFromEnv","overrides","databaseUrl","Error","isDevelopment","maxConnections","idleTimeoutMillis","connectionTimeoutMillis","enableQueryLogging","slowQueryThreshold","state","initialized","client","initializeDatabase","initializeDatabaseWithConfig","getDb","getDatabaseManager","isDatabaseInitialized","getDatabaseProductName","resetDatabaseManager","error","warn","checkDatabaseHealth","start","Date","now","$queryRaw","latency","healthy","errorMessage","message","String","testConnection","getDatabaseVersion","result","version","getDatabaseStats","health","Promise","all","timestamp","requireFn","createRequire","url","loadGeneratedFields","generatedFieldsPath","generated","default","path","extractFieldsFromModel","modelName","modelFieldsMap","options","modelFields","Object","keys","join","excludeFields","includeRelations","customFilter","fields","relations","excluded","length","filter","field","includes","push","fieldName","isRelation","shouldInclude","type","metadata","totalFields","excludedCount","excludedFields","relationFields","getModelFields","hasModel","getAllModelNames","buildContextWhereClause","contextFilter","conditions","workspaceId","equals","userId","projectId","appId","productId","organizationId","buildContextWhereConditions","context","toContextJson","contextInput","custom","filterNullValues","obj","filtered","key","value","entries","mergeContextField","merged","fieldValue","mergeContext","existingContext","newContext","Array","isArray","parseContext","contextJson","ctx","contextMatches","createContextFromSDK","sdkContext"],"mappings":";;;;;;;;AAAA,IAAA,cAAA,GAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC8GA,SAASA,iCAAiCC,WAAAA,EAAmB;AAC3D,EAAA,MAAMC,QAAAA,GAAWC,OAAAA,CAAQC,GAAAA,CAAI,6BAAA,CAAA;AAC7B,EAAA,IAAIF,QAAAA,KAAa,QAAQ,OAAO,IAAA;AAChC,EAAA,IAAIA,QAAAA,KAAa,SAAS,OAAO,KAAA;AAEjC,EAAA,MAAMG,KAAAA,GAAQF,OAAAA,CAAQC,GAAAA,CAAI,iBAAA,GAAoBE,WAAAA,EAAAA;AAC9C,EAAA,IAAID,KAAAA,KAAU,UAAU,OAAO,KAAA;AAC/B,EAAA,IAAIA,KAAAA,KAAU,UAAU,OAAO,IAAA;AAE/B,EAAA,MAAME,IAAAA,GAAON,YAAYK,WAAAA,EAAW;AACpC,EAAA,IAAIC,IAAAA,CAAKC,WAAW,SAAA,CAAA,IAAcD,KAAKC,UAAAA,CAAW,SAAA,GAAY,OAAO,KAAA;AACrE,EAAA,OAAO,IAAA;AACT;AAZSR,MAAAA,CAAAA,gCAAAA,EAAAA,kCAAAA,CAAAA;AAsDF,SAASS,oBAAAA,CACdC,yBACAC,MAAAA,EAA4B;AAE5B,EAAA,MAAM,EACJV,WAAAA,EACAW,oBAAAA,GAAuBT,QAAQC,GAAAA,CAAI,0BAAA,MAAgC,OAAA,EACnES,iBAAAA,EACAC,wBAAAA,GAA2Bd,gCAAAA,CAAiCC,WAAAA,CAAAA,EAC5Dc,wBAAAA,EACAC,2BAA2B,IAAA,EAC3B,GAAGC,cAAAA,GACDN,MAAAA;AAOJ,EAAA,MAAMO,wBAAAA,GAA+C;IACnD,GAAGD,YAAAA;IACHE,eAAAA,EAAiBF,YAAAA,CAAaE,eAAAA,IAAmB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AAmBzB,OAAOyB,cAAAA,EAAgB;AACrF,IAAA,OAAO,KAAA;AACT,EAAA;AAEA,EAAA,OAAO,IAAA;AACT;AAzBgBuB,MAAAA,CAAAA,cAAAA,EAAAA,gBAAAA,CAAAA;AAiCT,SAASC,qBAAqBC,UAAAA,EAOpC;AACC,EAAA,OAAO;AACL/B,IAAAA,WAAAA,EAAa+B,WAAW/B,WAAAA,IAAe,IAAA;AACvCE,IAAAA,MAAAA,EAAQ6B,WAAW7B,MAAAA,IAAU,IAAA;AAC7BC,IAAAA,SAAAA,EAAW4B,WAAW5B,SAAAA,IAAa,IAAA;AACnCC,IAAAA,KAAAA,EAAO2B,WAAW3B,KAAAA,IAAS,IAAA;AAC3BC,IAAAA,SAAAA,EAAW0B,WAAW1B,SAAAA,IAAa,IAAA;AACnCC,IAAAA,cAAAA,EAAgByB,WAAWzB,cAAAA,IAAkB;AAC/C,GAAA;AACF;AAhBgBwB,MAAAA,CAAAA,oBAAAA,EAAAA,sBAAAA,CAAAA","file":"chunk-MD3RHPFS.js","sourcesContent":["/**\n * Prisma Module for Burdenoff Backend SDK\n *\n * Provides Prisma 7 utilities including:\n * - Singleton database manager for microservices\n * - Unified database client factory with graph extension\n * - Prisma client configuration with PostgreSQL adapter\n * - Connection pooling and management\n * - Health checks and monitoring\n * - Graceful shutdown handling\n * - Field extraction utilities for graph sync\n * - Context filtering utilities for multi-tenant queries\n * - Workspace extension for automatic workspaceId injection\n *\n * @module prisma\n * @category Database\n */\n\nexport * from './manager.js';\nexport * from './factory.js';\nexport * from './client.js';\nexport type * from './types.js';\nexport * from './health.js';\nexport * from './fields.js';\nexport * from './context.js';\nexport * from './workspace-extension.js';\n","/**\n * Database Client Factory\n *\n * Provides a unified factory for creating fully-configured database clients\n * with Prisma 7, PostgreSQL adapter, graph extension, and graceful shutdown.\n *\n * This module consolidates all database setup into a single call, reducing\n * boilerplate across all backend services.\n *\n * @module prisma/factory\n * @category Database\n */\n\nimport { logger } from '../logger/index.js';\nimport {\n createPrismaClient,\n ensureServiceApplicationName,\n type PrismaClientBase,\n type PrismaClientWrapper,\n type PrismaClientConstructorOptions,\n} from './client.js';\nimport type { PrismaClientConfig } from './types.js';\nimport { addGraphExtension, type GraphMiddlewareConfig, type GraphEventEmitter } from '../graph/middleware/index.js';\nimport { getGraphEventEmitter } from '../event-queue/graph-emitter.js';\nimport { addWorkspaceExtension, type WorkspaceExtensionConfig } from './workspace-extension.js';\n\n/**\n * Configuration for creating a database client\n */\nexport interface DatabaseClientConfig extends PrismaClientConfig {\n /**\n * Product name for graph events (e.g., 'module-tags', 'workspaces')\n */\n productName: string;\n\n /**\n * Enable graph extension for entity sync\n * @default true (reads from GRAPH_MIDDLEWARE_ENABLED env var)\n */\n enableGraphExtension?: boolean;\n\n /**\n * Custom graph event emitter (defaults to NATS-based emitter)\n */\n graphEventEmitter?: GraphEventEmitter;\n\n /**\n * Enable workspace extension for automatic workspaceId injection.\n *\n * Default is layer-aware:\n * - Global-layer services (`productName` starting with `global-` or `global_`,\n * or `WORKSPACE_LAYER=global`) default to `false`. Global-layer tables\n * (Tenant, Organization, Workspace, PlatformProduct, etc.) are intentionally\n * not workspace-scoped — enforcing workspaceId on them would block legitimate\n * queries like `myOrganizations`, `myWorkspaces`, `myAccessibleProducts`.\n * - All other services (wspace layer, product backends) default to `true`.\n *\n * `WORKSPACE_EXTENSION_ENABLED` env var always wins when explicitly set\n * (`true` or `false`). Pass the field on `config` for code-level override.\n */\n enableWorkspaceExtension?: boolean;\n\n /**\n * Configuration for the workspace extension\n */\n workspaceExtensionConfig?: WorkspaceExtensionConfig;\n\n /**\n * Register process shutdown handlers for graceful shutdown\n * @default true\n */\n registerShutdownHandlers?: boolean;\n}\n\n/**\n * Result of creating a database client\n */\nexport interface DatabaseClient<T extends PrismaClientBase> {\n /**\n * The extended Prisma client for database operations\n * Use this for all queries: db.model.operation()\n */\n db: T & { client: T };\n\n /**\n * The Prisma client wrapper with connection management utilities\n */\n wrapper: PrismaClientWrapper<T>;\n\n /**\n * Connect to the database with retry logic\n */\n connect: (retries?: number, delay?: number) => Promise<void>;\n\n /**\n * Disconnect from the database\n */\n disconnect: () => Promise<void>;\n}\n\n/**\n * Layer-aware default for the workspace extension.\n *\n * Global-layer services (productName starting with `global-`/`global_`, or\n * `WORKSPACE_LAYER=global`) opt out by default because their tables don't carry\n * a workspaceId column — enforcement would break queries like `myOrganizations`,\n * `myAccessibleProducts`, `contentPages`.\n *\n * `WORKSPACE_EXTENSION_ENABLED` is respected as an explicit override.\n */\nfunction resolveWorkspaceExtensionDefault(productName: string): boolean {\n const explicit = process.env['WORKSPACE_EXTENSION_ENABLED'];\n if (explicit === 'true') return true;\n if (explicit === 'false') return false;\n\n const layer = process.env['WORKSPACE_LAYER']?.toLowerCase();\n if (layer === 'global') return false;\n if (layer === 'wspace') return true;\n\n const name = productName.toLowerCase();\n if (name.startsWith('global-') || name.startsWith('global_')) return false;\n return true;\n}\n\n/**\n * Create a fully-configured database client with graph extension\n *\n * This is the recommended way to create a database connection in all backend services.\n * It handles:\n * - Prisma client creation with PostgreSQL adapter\n * - Connection pooling configuration\n * - Query logging (in development)\n * - Graph extension for entity sync (via NATS or in-memory)\n * - Graceful shutdown handlers\n *\n * @example\n * ```typescript\n * // In your service's db.ts\n * import { PrismaClient } from './generated/prisma/client.js';\n * import { createDatabaseClient } from '@burdenoff/be-sdk/prisma';\n *\n * const { db, wrapper, connect, disconnect } = createDatabaseClient(PrismaClient, {\n * productName: 'my-service',\n * databaseUrl: process.env.DATABASE_URL!,\n * });\n *\n * export { db, wrapper, connect, disconnect };\n * export type ExtendedPrismaClient = typeof db;\n * ```\n *\n * @example\n * ```typescript\n * // With custom configuration\n * const { db } = createDatabaseClient(PrismaClient, {\n * productName: 'workspaces',\n * databaseUrl: process.env.DATABASE_URL!,\n * maxConnections: 50,\n * enableQueryLogging: true,\n * slowQueryThreshold: 200,\n * enableGraphExtension: true,\n * registerShutdownHandlers: true,\n * });\n * ```\n */\nexport function createDatabaseClient<T extends PrismaClientBase>(\n PrismaClientConstructor: new (options: PrismaClientConstructorOptions) => T,\n config: DatabaseClientConfig\n): DatabaseClient<T> {\n const {\n productName,\n enableGraphExtension = process.env['GRAPH_MIDDLEWARE_ENABLED'] !== 'false',\n graphEventEmitter,\n enableWorkspaceExtension = resolveWorkspaceExtensionDefault(productName),\n workspaceExtensionConfig,\n registerShutdownHandlers = true,\n ...prismaConfig\n } = config;\n\n // Tag every service's pool with `svc=<productName>` by default so its\n // connections are attributable in pg_stat_activity / pg_stat_statements\n // (the on-ramp to per-workspace observability and shard routing). This is\n // pure diagnostic metadata with no effect on behavior; explicit\n // `applicationName` on the config always wins.\n const prismaConfigWithDefaults: PrismaClientConfig = {\n ...prismaConfig,\n applicationName: prismaConfig.applicationName ?? `svc=${productName}`,\n };\n\n // Belt-and-suspenders: also set the PGAPPNAME env fallback so any additional\n // pools this service opens outside be-sdk still carry the per-service tag.\n ensureServiceApplicationName(productName);\n\n // Create Prisma client wrapper\n const wrapper = createPrismaClient(PrismaClientConstructor, prismaConfigWithDefaults);\n\n // Get the base client\n const baseClient = wrapper.getClient();\n\n // Extension chaining order:\n // 1. Graph extension (event emission on CRUD) - runs first\n // 2. Workspace extension (auto-inject workspaceId) - runs second\n //\n // The workspace extension should run BEFORE graph extension in the\n // interception chain so that graph events include the injected workspaceId.\n // In Prisma $extends, the LAST extension added runs FIRST (outermost wrapper).\n // So we add graph first, then workspace on top.\n\n let extendedClient: T;\n\n // Step 1: Add graph extension\n if (enableGraphExtension) {\n const eventEmitter = graphEventEmitter ?? getGraphEventEmitter();\n\n const graphConfig: GraphMiddlewareConfig = {\n enabled: true,\n productName,\n eventEmitter,\n };\n\n extendedClient = addGraphExtension(baseClient, graphConfig);\n\n logger.info('[Database] Graph extension enabled', { productName });\n } else {\n extendedClient = baseClient;\n logger.info('[Database] Graph extension disabled');\n }\n\n // Step 2: Add workspace extension (wraps on top of graph)\n if (enableWorkspaceExtension) {\n extendedClient = addWorkspaceExtension(extendedClient, workspaceExtensionConfig);\n\n logger.info('[Database] Workspace extension enabled', { productName });\n } else {\n logger.info('[Database] Workspace extension disabled');\n }\n\n // Add backwards compatibility alias\n const db = extendedClient as T & { client: T };\n (db as unknown as Record<string, unknown>)['client'] = db;\n\n // Register shutdown handlers if requested\n if (registerShutdownHandlers) {\n wrapper.registerShutdownHandlers();\n logger.debug('[Database] Shutdown handlers registered');\n }\n\n return {\n db,\n wrapper,\n connect: (retries?: number, delay?: number) => wrapper.connect(retries, delay),\n disconnect: () => wrapper.disconnect(),\n };\n}\n\n/**\n * Pool-tuning options resolved from environment variables.\n */\nexport interface PoolTuningEnv {\n /** Postgres application_name (defaults to `svc=<productName>`). */\n applicationName: string;\n /** Server-side statement_timeout in ms, if opted in. */\n statementTimeoutMillis?: number;\n /** Server-side idle_in_transaction_session_timeout in ms, if opted in. */\n idleInTransactionTimeoutMillis?: number;\n /** Server-side lock_timeout in ms, if opted in. */\n lockTimeoutMillis?: number;\n}\n\n/**\n * Parse a strictly-positive integer environment variable.\n *\n * Returns `undefined` for unset, empty, non-numeric, zero, or negative values —\n * so a misconfigured or absent env var can never silently enable an aggressive\n * (or nonsensical) timeout. This is what keeps the DB-enforced timeouts OFF by\n * default and therefore behavior-preserving.\n */\nfunction parsePositiveIntEnv(name: string): number | undefined {\n const raw = process.env[name];\n if (raw == null || raw.trim() === '') {\n return undefined;\n }\n const parsed = Number.parseInt(raw.trim(), 10);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;\n}\n\n/**\n * Resolve pool tuning (application_name + opt-in DB timeouts) from env vars:\n * - DATABASE_APPLICATION_NAME: overrides the default `svc=<productName>` tag\n * - DATABASE_STATEMENT_TIMEOUT: server-side statement_timeout in ms (opt-in)\n * - DATABASE_IDLE_IN_TRANSACTION_TIMEOUT: idle_in_transaction_session_timeout in ms (opt-in)\n * - DATABASE_LOCK_TIMEOUT: lock_timeout in ms (opt-in)\n *\n * Timeouts are omitted entirely unless explicitly set to a positive integer, so\n * the default is exactly today's behavior (no server-enforced timeouts).\n */\nexport function resolvePoolTuningFromEnv(productName: string): PoolTuningEnv {\n const tuning: PoolTuningEnv = {\n applicationName: process.env['DATABASE_APPLICATION_NAME']?.trim() || `svc=${productName}`,\n };\n\n const statementTimeout = parsePositiveIntEnv('DATABASE_STATEMENT_TIMEOUT');\n if (statementTimeout !== undefined) {\n tuning.statementTimeoutMillis = statementTimeout;\n }\n\n const idleInTransactionTimeout = parsePositiveIntEnv('DATABASE_IDLE_IN_TRANSACTION_TIMEOUT');\n if (idleInTransactionTimeout !== undefined) {\n tuning.idleInTransactionTimeoutMillis = idleInTransactionTimeout;\n }\n\n const lockTimeout = parsePositiveIntEnv('DATABASE_LOCK_TIMEOUT');\n if (lockTimeout !== undefined) {\n tuning.lockTimeoutMillis = lockTimeout;\n }\n\n return tuning;\n}\n\n/**\n * Create a database client from environment variables\n *\n * Convenience function that reads configuration from standard environment variables:\n * - DATABASE_URL: Connection string (required)\n * - DATABASE_MAX_CONNECTIONS: Max pool connections (default: 20)\n * - DATABASE_APPLICATION_NAME: Postgres application_name (default: `svc=<productName>`)\n * - DATABASE_STATEMENT_TIMEOUT / DATABASE_IDLE_IN_TRANSACTION_TIMEOUT / DATABASE_LOCK_TIMEOUT:\n * opt-in server-side timeouts in ms (default: OFF, preserving current behavior)\n * - NODE_ENV: Environment for logging settings\n * - GRAPH_MIDDLEWARE_ENABLED: Enable graph sync (default: true)\n *\n * @example\n * ```typescript\n * import { PrismaClient } from './generated/prisma/client.js';\n * import { createDatabaseClientFromEnv } from '@burdenoff/be-sdk/prisma';\n *\n * const { db } = createDatabaseClientFromEnv(PrismaClient, 'module-tags');\n * export { db };\n * ```\n */\nexport function createDatabaseClientFromEnv<T extends PrismaClientBase>(\n PrismaClientConstructor: new (options: PrismaClientConstructorOptions) => T,\n productName: string,\n overrides?: Partial<DatabaseClientConfig>\n): DatabaseClient<T> {\n const databaseUrl = process.env['DATABASE_URL'];\n if (!databaseUrl) {\n throw new Error('DATABASE_URL environment variable is required');\n }\n\n const isDevelopment = process.env['NODE_ENV'] === 'development';\n\n const config: DatabaseClientConfig = {\n productName,\n databaseUrl,\n maxConnections: parseInt(process.env['DATABASE_MAX_CONNECTIONS'] || '20', 10),\n idleTimeoutMillis: parseInt(process.env['DATABASE_IDLE_TIMEOUT'] || '30000', 10),\n connectionTimeoutMillis: parseInt(process.env['DATABASE_CONNECTION_TIMEOUT'] || '10000', 10),\n ...resolvePoolTuningFromEnv(productName),\n enableQueryLogging: isDevelopment,\n slowQueryThreshold: isDevelopment ? 100 : 500,\n ...overrides,\n };\n\n return createDatabaseClient(PrismaClientConstructor, config);\n}\n","/**\n * Database Singleton Manager\n *\n * Provides a singleton pattern for database connections across microservices.\n * Services initialize once at startup and access the db instance globally.\n *\n * This eliminates the need for individual db.ts files in each microservice.\n *\n * @module prisma/manager\n * @category Database\n *\n * @example\n * ```typescript\n * // In your service's index.ts (startup)\n * import { PrismaClient } from './generated/prisma/client.js';\n * import { initializeDatabase } from '@burdenoff/be-sdk/prisma';\n *\n * // Initialize once at startup\n * const { db, connect } = initializeDatabase(PrismaClient, 'module-tags');\n * await connect();\n *\n * // In any other file\n * import { getDb } from '@burdenoff/be-sdk/prisma';\n * const db = getDb();\n * await db.client.user.findMany();\n * ```\n */\n\nimport { logger } from '../logger/index.js';\nimport {\n createDatabaseClient,\n createDatabaseClientFromEnv,\n type DatabaseClient,\n type DatabaseClientConfig,\n} from './factory.js';\nimport type { PrismaClientBase, PrismaClientConstructorOptions, DatabaseReturnType } from './client.js';\n\n/**\n * Global database manager state\n */\ninterface DatabaseManagerState {\n initialized: boolean;\n productName: string | null;\n client: DatabaseClient<PrismaClientBase> | null;\n}\n\n/**\n * Singleton state for the database manager\n */\nconst state: DatabaseManagerState = {\n initialized: false,\n productName: null,\n client: null,\n};\n\n/**\n * Initialize the database singleton\n *\n * Call this once at application startup with your service's PrismaClient.\n * After initialization, use `getDb()` to access the database anywhere.\n *\n * @param PrismaClientConstructor - The generated PrismaClient class from your service\n * @param productName - Product name for graph events (e.g., 'module-tags', 'workspaces')\n * @param config - Optional configuration overrides\n * @returns The database client with db, wrapper, connect, disconnect\n *\n * @throws Error if already initialized with a different product\n *\n * @example\n * ```typescript\n * import { PrismaClient } from './generated/prisma/client.js';\n * import { initializeDatabase } from '@burdenoff/be-sdk/prisma';\n *\n * const { db, connect, disconnect } = initializeDatabase(PrismaClient, 'module-tags');\n * await connect();\n * ```\n */\nexport function initializeDatabase<T extends PrismaClientBase>(\n PrismaClientConstructor: new (options: PrismaClientConstructorOptions) => T,\n productName: string,\n config?: Partial<DatabaseClientConfig>\n): DatabaseClient<T> {\n // Check if already initialized\n if (state.initialized) {\n if (state.productName !== productName) {\n throw new Error(\n `Database already initialized for product \"${state.productName}\". ` +\n `Cannot reinitialize for \"${productName}\".`\n );\n }\n logger.debug('[DatabaseManager] Already initialized, returning existing client', { productName });\n return state.client as DatabaseClient<T>;\n }\n\n // Create the database client using env-based factory\n const client = createDatabaseClientFromEnv(PrismaClientConstructor, productName, config);\n\n // Store in singleton state\n state.initialized = true;\n state.productName = productName;\n state.client = client;\n\n logger.info('[DatabaseManager] Database initialized', { productName });\n\n return client;\n}\n\n/**\n * Initialize the database with explicit configuration\n *\n * Use this when you need full control over database configuration\n * rather than reading from environment variables.\n *\n * @param PrismaClientConstructor - The generated PrismaClient class\n * @param config - Full database configuration\n * @returns The database client\n *\n * @example\n * ```typescript\n * const { db } = initializeDatabaseWithConfig(PrismaClient, {\n * productName: 'module-tags',\n * databaseUrl: 'postgresql://...',\n * maxConnections: 50,\n * enableGraphExtension: false,\n * });\n * ```\n */\nexport function initializeDatabaseWithConfig<T extends PrismaClientBase>(\n PrismaClientConstructor: new (options: PrismaClientConstructorOptions) => T,\n config: DatabaseClientConfig\n): DatabaseClient<T> {\n const { productName } = config;\n\n // Check if already initialized\n if (state.initialized) {\n if (state.productName !== productName) {\n throw new Error(\n `Database already initialized for product \"${state.productName}\". ` +\n `Cannot reinitialize for \"${productName}\".`\n );\n }\n logger.debug('[DatabaseManager] Already initialized, returning existing client', { productName });\n return state.client as DatabaseClient<T>;\n }\n\n // Create the database client\n const client = createDatabaseClient(PrismaClientConstructor, config);\n\n // Store in singleton state\n state.initialized = true;\n state.productName = productName;\n state.client = client;\n\n logger.info('[DatabaseManager] Database initialized with custom config', { productName });\n\n return client;\n}\n\n/**\n * Get the initialized database client\n *\n * Use this anywhere in your application to access the database.\n * Must call `initializeDatabase()` first at application startup.\n *\n * The returned client provides dynamic model access - you can access any\n * model property (e.g., `db.client.user`, `db.client.universalTag`) and\n * TypeScript will allow common Prisma operations (findMany, create, etc.).\n *\n * @returns The extended Prisma client (db) with dynamic model access\n * @throws Error if database not initialized\n *\n * @example\n * ```typescript\n * import { getDb } from '@burdenoff/be-sdk/prisma';\n *\n * const db = getDb();\n * // Dynamic model access works without importing service-specific types\n * const tags = await db.client.universalTag.findMany();\n * const users = await db.client.user.findMany({ where: { active: true } });\n * ```\n */\nexport function getDb<T extends PrismaClientBase = PrismaClientBase>(): DatabaseReturnType<T> {\n if (!state.initialized || !state.client) {\n throw new Error('Database not initialized. Call initializeDatabase() at application startup before using getDb().');\n }\n return state.client.db as unknown as DatabaseReturnType<T>;\n}\n\n/**\n * Get the full database manager\n *\n * Returns the complete database client including wrapper, connect, and disconnect functions.\n * Useful when you need access to connection management utilities.\n *\n * @returns The full database client\n * @throws Error if database not initialized\n *\n * @example\n * ```typescript\n * import { getDatabaseManager } from '@burdenoff/be-sdk/prisma';\n *\n * const { db, wrapper, connect, disconnect } = getDatabaseManager();\n * await connect();\n * ```\n */\nexport function getDatabaseManager<T extends PrismaClientBase = PrismaClientBase>(): DatabaseClient<T> {\n if (!state.initialized || !state.client) {\n throw new Error(\n 'Database not initialized. Call initializeDatabase() at application startup before using getDatabaseManager().'\n );\n }\n return state.client as DatabaseClient<T>;\n}\n\n/**\n * Check if database is initialized\n *\n * @returns True if database has been initialized\n *\n * @example\n * ```typescript\n * if (!isDatabaseInitialized()) {\n * await initializeDatabase(PrismaClient, 'my-service');\n * }\n * ```\n */\nexport function isDatabaseInitialized(): boolean {\n return state.initialized;\n}\n\n/**\n * Get the product name of the initialized database\n *\n * @returns The product name or null if not initialized\n */\nexport function getDatabaseProductName(): string | null {\n return state.productName;\n}\n\n/**\n * Reset the database manager (for testing purposes only)\n *\n * WARNING: This disconnects and resets the database manager.\n * Only use this in test environments for cleanup between tests.\n *\n * @internal\n */\nexport async function resetDatabaseManager(): Promise<void> {\n if (state.client) {\n try {\n await state.client.disconnect();\n } catch (error) {\n logger.warn('[DatabaseManager] Error during disconnect on reset', { error });\n }\n }\n\n state.initialized = false;\n state.productName = null;\n state.client = null;\n\n logger.debug('[DatabaseManager] Database manager reset');\n}\n","/**\n * Prisma Health Check Utilities\n */\n\nimport { logger } from '../logger/index.js';\nimport type { DatabaseHealth } from './types.js';\nimport type { PrismaClientBase } from './client.js';\n\n/**\n * Check database health\n */\nexport async function checkDatabaseHealth<T extends PrismaClientBase>(client: T): Promise<DatabaseHealth> {\n try {\n const start = Date.now();\n await client.$queryRaw`SELECT 1`;\n const latency = Date.now() - start;\n\n return { healthy: true, latency };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logger.error('[Prisma] Health check failed', { error: errorMessage });\n\n return {\n healthy: false,\n error: errorMessage,\n };\n }\n}\n\n/**\n * Test database connection\n */\nexport async function testConnection<T extends PrismaClientBase>(client: T): Promise<boolean> {\n try {\n await client.$queryRaw`SELECT 1`;\n return true;\n } catch (error) {\n logger.error('[Prisma] Connection test failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n return false;\n }\n}\n\n/**\n * Get database version\n */\nexport async function getDatabaseVersion<T extends PrismaClientBase>(client: T): Promise<string | null> {\n try {\n const result = await client.$queryRaw<Array<{ version?: string }>>`SELECT version()`;\n return result[0]?.version ?? null;\n } catch (error) {\n logger.error('[Prisma] Failed to get database version', {\n error: error instanceof Error ? error.message : String(error),\n });\n return null;\n }\n}\n\n/**\n * Get database stats\n */\nexport async function getDatabaseStats<T extends PrismaClientBase>(\n client: T\n): Promise<{\n health: DatabaseHealth;\n version: string | null;\n timestamp: Date;\n}> {\n const [health, version] = await Promise.all([checkDatabaseHealth(client), getDatabaseVersion(client)]);\n\n return {\n health,\n version,\n timestamp: new Date(),\n };\n}\n","/**\n * Prisma Field Extraction Utilities\n *\n * Provides utilities for extracting model fields from Prisma schema.\n * In Prisma 7, DMMF is not available at runtime, so this module provides\n * build-time field extraction through a generator.\n *\n * @module prisma/fields\n */\n\nimport { createRequire } from 'node:module';\nimport { logger } from '../logger/index.js';\n\nconst requireFn = createRequire(import.meta.url);\n\n/**\n * Field extraction options\n */\nexport interface FieldExtractionOptions {\n /** Fields to exclude from extraction */\n excludeFields?: string[];\n /** Whether to include relation fields */\n includeRelations?: boolean;\n /** Custom filter function */\n customFilter?: (field: { name: string; type: string; isRelation: boolean }) => boolean;\n}\n\n/**\n * Field extraction result\n */\nexport interface FieldExtractionResult {\n /** Extracted field names */\n fields: string[];\n /** Metadata about the extraction */\n metadata: {\n /** Total number of fields found */\n totalFields: number;\n /** Number of fields excluded */\n excludedCount: number;\n /** Names of excluded fields */\n excludedFields: string[];\n /** Number of relation fields */\n relationFields: number;\n };\n}\n\n/**\n * Model fields mapping\n * This will be generated at build time by the Prisma generator\n */\nexport type ModelFieldsMap = Record<\n string,\n {\n fields: string[];\n relations: string[];\n }\n>;\n\n/**\n * Import generated fields from the consuming package\n * This function should be used by backends to load their generated fields\n */\nexport function loadGeneratedFields(generatedFieldsPath: string): ModelFieldsMap {\n try {\n // Dynamic import of generated fields using createRequire\n const generated = requireFn(generatedFieldsPath) as { default: ModelFieldsMap };\n return generated.default || generated;\n } catch (error) {\n logger.error('[Prisma] Failed to load generated fields', {\n error: error instanceof Error ? error.message : String(error),\n path: generatedFieldsPath,\n });\n throw new Error(`Failed to load generated fields from ${generatedFieldsPath}`);\n }\n}\n\n/**\n * Extract fields from generated model fields with options\n */\nexport function extractFieldsFromModel(\n modelName: string,\n modelFieldsMap: ModelFieldsMap,\n options: FieldExtractionOptions = {}\n): FieldExtractionResult {\n const modelFields = modelFieldsMap[modelName];\n\n if (!modelFields) {\n throw new Error(\n `Model \"${modelName}\" not found in generated fields. ` +\n `Available models: ${Object.keys(modelFieldsMap).join(', ')}`\n );\n }\n\n const { excludeFields = [], includeRelations = false, customFilter } = options;\n\n // Start with scalar fields\n let fields = [...modelFields.fields];\n\n // Add relations if requested\n if (includeRelations) {\n fields = [...fields, ...modelFields.relations];\n }\n\n // Track excluded fields\n const excluded: string[] = [];\n\n // Apply exclusions\n if (excludeFields.length > 0) {\n fields = fields.filter((field) => {\n if (excludeFields.includes(field)) {\n excluded.push(field);\n return false;\n }\n return true;\n });\n }\n\n // Apply custom filter\n if (customFilter) {\n fields = fields.filter((fieldName) => {\n const isRelation = modelFields.relations.includes(fieldName);\n const shouldInclude = customFilter({\n name: fieldName,\n type: 'unknown', // Type information not available without full DMMF\n isRelation,\n });\n\n if (!shouldInclude) {\n excluded.push(fieldName);\n }\n\n return shouldInclude;\n });\n }\n\n return {\n fields,\n metadata: {\n totalFields: modelFields.fields.length + modelFields.relations.length,\n excludedCount: excluded.length,\n excludedFields: excluded,\n relationFields: modelFields.relations.length,\n },\n };\n}\n\n/**\n * Get all field names for a model (without options)\n */\nexport function getModelFields(modelName: string, modelFieldsMap: ModelFieldsMap, includeRelations = false): string[] {\n const result = extractFieldsFromModel(modelName, modelFieldsMap, { includeRelations });\n return result.fields;\n}\n\n/**\n * Check if a model exists in the generated fields\n */\nexport function hasModel(modelName: string, modelFieldsMap: ModelFieldsMap): boolean {\n return modelName in modelFieldsMap;\n}\n\n/**\n * Get all available model names\n */\nexport function getAllModelNames(modelFieldsMap: ModelFieldsMap): string[] {\n return Object.keys(modelFieldsMap);\n}\n","/**\n * Prisma Context Filtering Utilities\n *\n * Utilities for handling operation context in queries, mutations, and filtering.\n * Context JSON enables multi-dimensional data isolation across workspaces, users, projects, etc.\n *\n * @module prisma/context\n * @category Database\n */\n\n/**\n * Context filter input for querying entities by context\n */\nexport interface ContextFilterInput {\n workspaceId?: string | null;\n userId?: string | null;\n projectId?: string | null;\n appId?: string | null;\n /** Product identifier (e.g. \"vibecontrols\", \"workspaces\"). Stamped on cross-product\n * records so admin filters can scope by originating product. */\n productId?: string | null;\n /** Organization identifier within the tenant. */\n organizationId?: string | null;\n}\n\n/**\n * Operation context for create/update operations\n */\nexport interface OperationContext extends ContextFilterInput {\n custom?: Record<string, unknown> | null;\n}\n\n/**\n * Prisma JSON filter type (simplified for context filtering)\n * This type is designed to be compatible with Prisma's JsonNullableFilter\n * Uses Record<string, unknown> for maximum compatibility with various Prisma versions\n */\nexport type PrismaJsonFilter = Record<string, unknown>;\n\n/**\n * JSON value type for Prisma (includes null for reading from DB)\n */\nexport type JsonValue = string | number | boolean | null | { [key: string]: JsonValue } | JsonValue[];\n\n/**\n * Input JSON value type for Prisma (excludes null for writing to DB)\n * Compatible with Prisma's InputJsonValue type\n */\nexport type InputJsonValue = string | number | boolean | { [key: string]: InputJsonValue } | InputJsonValue[];\n\n/**\n * Build Prisma where condition for context filtering.\n * Uses PostgreSQL JSONB containment operators for efficient queries.\n *\n * @param contextFilter - The context filter input\n * @returns Prisma where clause for context field, or undefined if no filter provided\n *\n * @example\n * ```typescript\n * const contextWhere = buildContextWhereClause({\n * workspaceId: '123',\n * projectId: '456'\n * });\n * // Returns: { path: ['workspaceId'], equals: '123' }\n * ```\n */\nexport function buildContextWhereClause(\n contextFilter: ContextFilterInput | null | undefined\n): PrismaJsonFilter | undefined {\n if (!contextFilter) {\n return undefined;\n }\n\n // Build array of path conditions for each non-null field\n const conditions: PrismaJsonFilter[] = [];\n\n if (contextFilter.workspaceId != null) {\n conditions.push({\n path: ['workspaceId'],\n equals: contextFilter.workspaceId,\n });\n }\n\n if (contextFilter.userId != null) {\n conditions.push({\n path: ['userId'],\n equals: contextFilter.userId,\n });\n }\n\n if (contextFilter.projectId != null) {\n conditions.push({\n path: ['projectId'],\n equals: contextFilter.projectId,\n });\n }\n\n if (contextFilter.appId != null) {\n conditions.push({\n path: ['appId'],\n equals: contextFilter.appId,\n });\n }\n\n if (contextFilter.productId != null) {\n conditions.push({\n path: ['productId'],\n equals: contextFilter.productId,\n });\n }\n\n if (contextFilter.organizationId != null) {\n conditions.push({\n path: ['organizationId'],\n equals: contextFilter.organizationId,\n });\n }\n\n // If no conditions, return undefined\n if (conditions.length === 0) {\n return undefined;\n }\n\n // If single condition, return it directly\n if (conditions.length === 1) {\n return conditions[0];\n }\n\n // For multiple conditions, return the first one\n // Caller should use buildContextWhereConditions for multiple AND conditions\n return conditions[0];\n}\n\n/**\n * Build context where conditions as an array for use in AND clause.\n * This is useful when you need to filter by multiple context fields.\n *\n * @param contextFilter - The context filter input\n * @returns Array of Prisma where conditions, each targeting the context field\n *\n * @example\n * ```typescript\n * const conditions = buildContextWhereConditions({\n * workspaceId: '123',\n * projectId: '456'\n * });\n * // Use in Prisma query:\n * prisma.entity.findMany({\n * where: { AND: conditions }\n * });\n * ```\n */\nexport function buildContextWhereConditions(\n contextFilter: ContextFilterInput | null | undefined\n): Array<{ context: PrismaJsonFilter }> {\n if (!contextFilter) {\n return [];\n }\n\n const conditions: Array<{ context: PrismaJsonFilter }> = [];\n\n if (contextFilter.workspaceId != null) {\n conditions.push({\n context: {\n path: ['workspaceId'],\n equals: contextFilter.workspaceId,\n },\n });\n }\n\n if (contextFilter.userId != null) {\n conditions.push({\n context: {\n path: ['userId'],\n equals: contextFilter.userId,\n },\n });\n }\n\n if (contextFilter.projectId != null) {\n conditions.push({\n context: {\n path: ['projectId'],\n equals: contextFilter.projectId,\n },\n });\n }\n\n if (contextFilter.appId != null) {\n conditions.push({\n context: {\n path: ['appId'],\n equals: contextFilter.appId,\n },\n });\n }\n\n if (contextFilter.productId != null) {\n conditions.push({\n context: {\n path: ['productId'],\n equals: contextFilter.productId,\n },\n });\n }\n\n if (contextFilter.organizationId != null) {\n conditions.push({\n context: {\n path: ['organizationId'],\n equals: contextFilter.organizationId,\n },\n });\n }\n\n return conditions;\n}\n\n/**\n * Convert context input to Prisma JSON format for create/update operations.\n *\n * @param contextInput - The context input\n * @returns JSON value for the context field, or undefined if empty\n *\n * @example\n * ```typescript\n * const contextJson = toContextJson({\n * workspaceId: '123',\n * userId: '456'\n * });\n * // Use in Prisma create:\n * prisma.entity.create({\n * data: { context: contextJson }\n * });\n * ```\n */\nexport function toContextJson(contextInput: OperationContext | null | undefined): InputJsonValue | undefined {\n if (!contextInput) {\n return undefined;\n }\n\n // Remove null values and build clean context object\n const context: Record<string, InputJsonValue> = {};\n\n if (contextInput.workspaceId != null) {\n context['workspaceId'] = contextInput.workspaceId;\n }\n if (contextInput.userId != null) {\n context['userId'] = contextInput.userId;\n }\n if (contextInput.projectId != null) {\n context['projectId'] = contextInput.projectId;\n }\n if (contextInput.appId != null) {\n context['appId'] = contextInput.appId;\n }\n if (contextInput.productId != null) {\n context['productId'] = contextInput.productId;\n }\n if (contextInput.organizationId != null) {\n context['organizationId'] = contextInput.organizationId;\n }\n if (contextInput.custom != null) {\n context['custom'] = contextInput.custom as InputJsonValue;\n }\n\n // Return undefined if no fields set\n if (Object.keys(context).length === 0) {\n return undefined;\n }\n\n return context;\n}\n\n/**\n * Filter out null values from an object for Prisma compatibility\n */\nfunction filterNullValues(obj: Record<string, unknown>): Record<string, InputJsonValue> {\n const filtered: Record<string, InputJsonValue> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (value !== null) {\n filtered[key] = value as InputJsonValue;\n }\n }\n return filtered;\n}\n\n/**\n * Merge a single field into the merged context object\n */\nfunction mergeContextField(\n merged: Record<string, InputJsonValue>,\n fieldName: string,\n fieldValue: string | Record<string, unknown> | null | undefined\n): void {\n if (fieldValue === undefined) {\n return; // Don't touch this field\n }\n\n if (fieldValue === null) {\n delete merged[fieldName]; // Explicitly remove\n } else {\n merged[fieldName] = fieldValue as InputJsonValue; // Set new value\n }\n}\n\n/**\n * Merge existing context with new context input.\n * New values override existing ones, but undefined values are preserved from existing.\n *\n * @param existingContext - The existing context JSON from database\n * @param newContext - The new context input\n * @returns Merged context as InputJsonValue (suitable for Prisma writes)\n *\n * @example\n * ```typescript\n * const merged = mergeContext(\n * { workspaceId: '123', userId: 'old' },\n * { userId: 'new', projectId: '456' }\n * );\n * // Result: { workspaceId: '123', userId: 'new', projectId: '456' }\n * ```\n */\nexport function mergeContext(\n existingContext: JsonValue | null | undefined,\n newContext: OperationContext | null | undefined\n): InputJsonValue | undefined {\n // If no new context, return existing (excluding null values)\n if (!newContext) {\n if (!existingContext) {\n return undefined;\n }\n // Filter out null values from existing context for Prisma compatibility\n if (typeof existingContext === 'object' && !Array.isArray(existingContext)) {\n const filtered = filterNullValues(existingContext);\n return Object.keys(filtered).length > 0 ? filtered : undefined;\n }\n return existingContext as InputJsonValue;\n }\n\n // If no existing context, convert new to JSON\n if (!existingContext || typeof existingContext !== 'object' || Array.isArray(existingContext)) {\n return toContextJson(newContext);\n }\n\n // Merge existing with new\n const merged = filterNullValues(existingContext);\n\n // Merge each field from new context\n mergeContextField(merged, 'workspaceId', newContext.workspaceId);\n mergeContextField(merged, 'userId', newContext.userId);\n mergeContextField(merged, 'projectId', newContext.projectId);\n mergeContextField(merged, 'appId', newContext.appId);\n mergeContextField(merged, 'productId', newContext.productId);\n mergeContextField(merged, 'organizationId', newContext.organizationId);\n mergeContextField(merged, 'custom', newContext.custom);\n\n return Object.keys(merged).length > 0 ? merged : undefined;\n}\n\n/**\n * Parse context JSON from database to OperationContext interface.\n *\n * @param contextJson - The context JSON from database\n * @returns Parsed OperationContext or null\n *\n * @example\n * ```typescript\n * const context = parseContext(entity.context);\n * if (context?.workspaceId) {\n * // Use workspace-specific logic\n * }\n * ```\n */\nexport function parseContext(contextJson: JsonValue | null | undefined): OperationContext | null {\n if (!contextJson || typeof contextJson !== 'object' || Array.isArray(contextJson)) {\n return null;\n }\n\n const ctx = contextJson as Record<string, unknown>;\n\n return {\n workspaceId: typeof ctx['workspaceId'] === 'string' ? ctx['workspaceId'] : null,\n userId: typeof ctx['userId'] === 'string' ? ctx['userId'] : null,\n projectId: typeof ctx['projectId'] === 'string' ? ctx['projectId'] : null,\n appId: typeof ctx['appId'] === 'string' ? ctx['appId'] : null,\n productId: typeof ctx['productId'] === 'string' ? ctx['productId'] : null,\n organizationId: typeof ctx['organizationId'] === 'string' ? ctx['organizationId'] : null,\n custom: typeof ctx['custom'] === 'object' ? (ctx['custom'] as Record<string, unknown>) : null,\n };\n}\n\n/**\n * Check if context matches filter criteria\n *\n * @param context - The context to check\n * @param filter - The filter criteria\n * @returns True if context matches all filter criteria\n */\nexport function contextMatches(context: OperationContext | null | undefined, filter: ContextFilterInput): boolean {\n if (!context) {\n return false;\n }\n\n if (filter.workspaceId != null && context.workspaceId !== filter.workspaceId) {\n return false;\n }\n if (filter.userId != null && context.userId !== filter.userId) {\n return false;\n }\n if (filter.projectId != null && context.projectId !== filter.projectId) {\n return false;\n }\n if (filter.appId != null && context.appId !== filter.appId) {\n return false;\n }\n if (filter.productId != null && context.productId !== filter.productId) {\n return false;\n }\n if (filter.organizationId != null && context.organizationId !== filter.organizationId) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Create a default context from SDK context\n *\n * @param sdkContext - The SDK context (from AsyncLocalStorage)\n * @returns Operation context with workspace and user info\n */\nexport function createContextFromSDK(sdkContext: {\n workspaceId?: string;\n userId?: string;\n projectId?: string;\n appId?: string;\n productId?: string;\n organizationId?: string;\n}): OperationContext {\n return {\n workspaceId: sdkContext.workspaceId ?? null,\n userId: sdkContext.userId ?? null,\n projectId: sdkContext.projectId ?? null,\n appId: sdkContext.appId ?? null,\n productId: sdkContext.productId ?? null,\n organizationId: sdkContext.organizationId ?? null,\n };\n}\n"]}
|