@burdenoff/be-sdk 2026.1102.1 → 2026.1102.2
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/dist/{chunk-XUS3NXR5.js → chunk-5ENWB2S6.js} +3 -3
- package/dist/{chunk-XUS3NXR5.js.map → chunk-5ENWB2S6.js.map} +1 -1
- package/dist/{chunk-WVOW3CJR.js → chunk-I57LWBZU.js} +128 -3
- package/dist/chunk-I57LWBZU.js.map +1 -0
- package/dist/{chunk-WSAWJC4D.js → chunk-QCOC2SF3.js} +3 -3
- package/dist/{chunk-WSAWJC4D.js.map → chunk-QCOC2SF3.js.map} +1 -1
- package/dist/{index-qwG_TaUg.d.ts → index-B7dknayX.d.ts} +25 -2
- package/dist/index.d.ts +1 -1
- package/dist/index.js +11 -11
- package/dist/prisma/index.js +2 -2
- package/dist/tracker/index.js +3 -3
- package/dist/validation/index.d.ts +1 -1
- package/dist/validation/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-WVOW3CJR.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/validation/index.ts","../src/validation/name.ts","../src/validation/username.ts","../src/validation/userFields.ts","../src/validation/rbac-coverage.ts","../src/validation/billing.ts"],"names":["NAME_MIN_LENGTH","NAME_MAX_LENGTH","NAME_ALLOWED_CHARS","TYPOGRAPHIC_APOSTROPHES","TYPOGRAPHIC_HYPHENS","lengthInCodePoints","s","length","validateName","name","trimmed","normalize","replace","trim","valid","code","message","test","value","USERNAME_MIN_LENGTH","USERNAME_MAX_LENGTH","USERNAME_ALLOWED_CHARS","validateUsername","username","errors","push","validateUserFields","input","options","requireAll","isBlank","v","firstName","field","lastName","e","valueOr","result","fallback","values","RBAC_GATED_SCOPE_TYPES","RBAC_SCOPE_TYPES","DEFAULT_RBAC_ROOT_TYPES","DEFAULT_MAX_RBAC_ARG_PATH_SEGMENTS","DEFAULT_BILLING_SCOPE_ARG","DEFAULT_ID_SCALARS","SCHEMA_EXTENSIONS","Set","SKIPPED_DIRECTORIES","PLACEHOLDER_FIELD","RbacCoverageError","Error","report","problems","join","collectSchemaFiles","path","statSync","isDirectory","out","entries","readdirSync","withFileTypes","sort","a","b","localeCompare","entry","full","has","startsWith","extname","loadRbacSchemaDocuments","paths","files","flatMap","map","file","document","parse","readFileSync","error","String","cause","isDocumentNode","kind","Kind","DOCUMENT","toSchemaDocuments","source","items","every","item","TypeError","rbacDirective","directives","find","d","readRbacDirectiveArgs","directive","args","arg","arguments","BOOLEAN","public","LIST","actorTypes","STRING","rootTypeNames","docs","configured","names","def","definitions","SCHEMA_DEFINITION","SCHEMA_EXTENSION","op","operationTypes","add","type","inputFieldsByType","Map","INPUT_OBJECT_TYPE_DEFINITION","INPUT_OBJECT_TYPE_EXTENSION","existing","get","fields","set","unwrapSingular","NON_NULL_TYPE","LIST_TYPE","rbacArgPathProblem","inputs","maxSegments","idScalars","segments","split","some","head","rest","typeName","walked","segment","next","f","malformedReason","rbac","scopeType","hasActionResource","Boolean","action","resource","includes","scopeArg","pinEntries","pin","Array","isArray","Object","keys","matchesEntry","coordinate","sortLines","lines","collectRootFields","roots","exempt","OBJECT_TYPE_DEFINITION","OBJECT_TYPE_EXTENSION","definition","root","scopeArgPath","undefined","argPathProblems","context","checks","label","resourceIdArg","problem","selfScopedPinProblems","rootFields","unreviewed","stale","selfScoped","filter","analyzeRbacCoverage","collected","rootTypes","exemptFields","pathContext","maxArgPathSegments","missing","malformed","unresolvedArgPaths","reason","pins","selfScopedFields","unreviewedSelfScoped","staleSelfScoped","minRootFields","c","m","p","ok","assertRbacCoverage","SUPPORTED_BILLING_CURRENCIES","freeze","supportedCurrencies","MAX_BILLING_AMOUNT","isSupportedBillingCurrency","currency","toUpperCase","validateBillingAmount","amount","Number","isFinite","allowZero"],"mappings":";;;;;;AAAA,IAAA,kBAAA,GAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;ACwCO,IAAMA,eAAAA,GAAkB;AACxB,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AA,IAAI,OAAOyL,WAAW,QAAA,IAAY,CAACC,OAAOC,QAAAA,CAASF,MAAAA,GAAS,OAAO;IAAEvM,KAAAA,EAAO,KAAA;IAAOC,IAAAA,EAAM;AAAa,GAAA;AACtG,EAAA,IAAIa,QAAQ4L,SAAAA,KAAc,IAAA,GAAOH,MAAAA,GAAS,CAAA,GAAIA,UAAU,CAAA,EAAG;AACzD,IAAA,OAAO;MAAEvM,KAAAA,EAAO,KAAA;MAAOC,IAAAA,EAAMa,OAAAA,CAAQ4L,SAAAA,KAAc,IAAA,GAAO,UAAA,GAAa;AAAe,KAAA;AACxF,EAAA;AACA,EAAA,IAAIH,MAAAA,GAASL,oBAAoB,OAAO;IAAElM,KAAAA,EAAO,KAAA;IAAOC,IAAAA,EAAM;AAAkB,GAAA;AAChF,EAAA,OAAO;IAAED,KAAAA,EAAO,IAAA;IAAMI,KAAAA,EAAOmM;AAAO,GAAA;AACtC;AAVgBD,MAAAA,CAAAA,qBAAAA,EAAAA,uBAAAA,CAAAA","file":"chunk-I57LWBZU.js","sourcesContent":["/**\n * Shared server-side identity and billing input validators.\n * Identity invariants mirror microfe-auth (BOFF-7261); billing currency support\n * and finite amount bounds originate in global-billing (BOFF-10764).\n */\n\nexport { validateName, lengthInCodePoints, NAME_MIN_LENGTH, NAME_MAX_LENGTH } from './name.js';\nexport type { NameErrorCode, NameValidationResult } from './name.js';\n\nexport { validateUsername, USERNAME_MIN_LENGTH, USERNAME_MAX_LENGTH } from './username.js';\nexport type { UsernameErrorCode, UsernameValidationResult } from './username.js';\n\nexport { validateUserFields } from './userFields.js';\nexport type { UserFieldKey, UserFieldError, ValidatedUserFields, UserFieldsValidationResult } from './userFields.js';\n\nexport {\n assertRbacCoverage,\n analyzeRbacCoverage,\n loadRbacSchemaDocuments,\n readRbacDirectiveArgs,\n rbacArgPathProblem,\n RbacCoverageError,\n RBAC_SCOPE_TYPES,\n RBAC_GATED_SCOPE_TYPES,\n DEFAULT_RBAC_ROOT_TYPES,\n DEFAULT_MAX_RBAC_ARG_PATH_SEGMENTS,\n} from './rbac-coverage.js';\nexport type {\n RbacCoverageOptions,\n RbacCoverageReport,\n RbacCoverageSource,\n RbacDirectiveArgs,\n RbacFieldPin,\n RbacRootField,\n RbacSchemaDocument,\n RbacScopeType,\n} from './rbac-coverage.js';\n\nexport {\n SUPPORTED_BILLING_CURRENCIES,\n MAX_BILLING_AMOUNT,\n isSupportedBillingCurrency,\n validateBillingAmount,\n} from './billing.js';\nexport type { SupportedBillingCurrency, BillingAmountErrorCode, BillingAmountValidationResult } from './billing.js';\n","/**\n * Validate a person's name (first or last).\n *\n * Mirrors `microfe-auth/src/auth/utils/validation.ts:validateName` from\n * the BOFF-7214 client-side PR (#59) so the server and the client apply\n * the same invariant. Do not edit one without editing the other — the\n * two must stay byte-identical or client-passes-but-server-rejects errors\n * will surface in production (BOFF-7261 acceptance criteria).\n *\n * Rules:\n * - 1–100 Unicode code points (NOT JavaScript `.length`, which counts\n * UTF-16 code units — see `lengthInCodePoints`).\n * - must contain at least one letter (`\\p{L}`)\n * - allowed characters: letters, marks, literal space, hyphen,\n * apostrophe, period, middle-dot (U+00B7, U+30FB), and zero-width\n * join controls (U+200C, U+200D)\n * - typographic apostrophes (U+2018 / U+2019 / U+02BC) and\n * typographic hyphens (U+2010 / U+2011) are folded to their ASCII\n * equivalents before storage\n * - NFC normalisation runs before trim/length so combining-mark\n * sequences (e.g. `e\\u0301` for `é`) fold to their precomposed form\n *\n * Accepts `string | undefined | null` because the GraphQL input types\n * declare these fields as optional. An absent value fails validation.\n *\n * On success the result carries the canonicalised `value` (NFC,\n * typographic apostrophes folded to ASCII, trimmed) so the caller can\n * persist the exact same string the validator approved — otherwise the\n * validated string and the value written to the database would diverge.\n *\n * Returns a structured result so the caller can map each error code to\n * a distinct i18n key.\n */\n\nexport type NameErrorCode = 'required' | 'too_long' | 'no_letter' | 'invalid_chars';\n\nexport type NameValidationResult =\n | { valid: true; value: string }\n | { valid: false; code: NameErrorCode; message: string };\n\nexport const NAME_MIN_LENGTH = 1;\nexport const NAME_MAX_LENGTH = 100;\n\n/**\n * Allowed characters for a name. Every character must be a letter,\n * mark, literal space, hyphen, apostrophe, period, middle-dot, or join\n * control. Must contain at least one letter.\n *\n * Note: a literal space, not `\\s` — `\\s` matches tabs/newlines/other\n * Unicode whitespace which has no business being inside a person's name.\n *\n * Middle-dot codepoints U+00B7 and U+30FB are allowed as-is, NOT folded\n * to `.` — they're orthographically distinct and silently rewriting the\n * user's name would corrupt their identity.\n */\nconst NAME_ALLOWED_CHARS = /^[\\p{L}\\p{M} '.\\-\\u00B7\\u30FB\\u200C\\u200D]+$/u;\nconst TYPOGRAPHIC_APOSTROPHES = /[\\u2018\\u2019\\u02BC]/g;\nconst TYPOGRAPHIC_HYPHENS = /[\\u2010\\u2011]/g;\n\n/**\n * Count Unicode code points in `s` instead of UTF-16 code units. Names\n * written in scripts that live in the supplementary plane (Adlam 𞤁𞤔𞤣,\n * many CJK extensions, etc.) have each letter encoded as two UTF-16 units,\n * so a 51-letter Adlam name would otherwise be miscounted as 102 and\n * rejected as too long.\n *\n * Code-point counting is sufficient for the name validator — grapheme-\n * cluster counting would also handle emoji ZWJ sequences, but the name\n * regex already disallows emoji.\n */\nexport function lengthInCodePoints(s: string): number {\n return [...s].length;\n}\n\nexport function validateName(name: string | undefined | null): NameValidationResult {\n const trimmed = (name ?? '')\n .normalize('NFC')\n .replace(TYPOGRAPHIC_APOSTROPHES, \"'\")\n .replace(TYPOGRAPHIC_HYPHENS, '-')\n .trim();\n\n if (lengthInCodePoints(trimmed) < NAME_MIN_LENGTH) {\n return { valid: false, code: 'required', message: 'Name is required' };\n }\n\n if (lengthInCodePoints(trimmed) > NAME_MAX_LENGTH) {\n return {\n valid: false,\n code: 'too_long',\n message: `Name must be ${NAME_MAX_LENGTH} characters or fewer`,\n };\n }\n\n if (!NAME_ALLOWED_CHARS.test(trimmed) || !/\\p{L}/u.test(trimmed)) {\n if (!/\\p{L}/u.test(trimmed)) {\n return {\n valid: false,\n code: 'no_letter',\n message: 'Name must contain at least one letter',\n };\n }\n return {\n valid: false,\n code: 'invalid_chars',\n message: 'Name can only contain letters, spaces, periods, hyphens, and apostrophes',\n };\n }\n\n return { valid: true, value: trimmed };\n}\n","/**\n * Validate a username.\n *\n * Mirrors `microfe-auth/src/auth/utils/validation.ts:validateUsername`\n * from the BOFF-7214 client-side PR (#59). Do not edit one without\n * editing the other.\n *\n * Rules:\n * - 3–30 Unicode code points (NOT JavaScript `.length`)\n * - allow-list `[a-zA-Z0-9_-]`\n * - must contain at least one letter (so `12345` fails — this is the\n * specific BOFF-7214 invariant; a pure-numeric username used to\n * pass the character allow-list alone)\n * - surrounding whitespace is trimmed before validation so a pasted\n * `\" alice_01 \"` doesn't fail with a misleading \"invalid chars\"\n * error\n *\n * On success the result carries the trimmed `value` so the caller\n * persists the same string the validator approved.\n *\n * Returns a structured result with a list of errors so the caller can\n * render every failing rule at once.\n */\n\nimport { lengthInCodePoints } from './name.js';\n\nexport type UsernameErrorCode = 'required' | 'too_short' | 'too_long' | 'invalid_chars' | 'no_letter';\n\nexport type UsernameValidationResult =\n | { valid: true; value: string }\n | {\n valid: false;\n errors: Array<{ code: UsernameErrorCode; message: string }>;\n };\n\nexport const USERNAME_MIN_LENGTH = 3;\nexport const USERNAME_MAX_LENGTH = 30;\nconst USERNAME_ALLOWED_CHARS = /^[a-zA-Z0-9_-]+$/;\n\nexport function validateUsername(username: string | undefined | null): UsernameValidationResult {\n const errors: Array<{ code: UsernameErrorCode; message: string }> = [];\n const value = (username ?? '').trim();\n\n if (lengthInCodePoints(value) === 0) {\n errors.push({ code: 'required', message: 'Username is required' });\n return { valid: false, errors };\n }\n\n if (lengthInCodePoints(value) < USERNAME_MIN_LENGTH) {\n errors.push({\n code: 'too_short',\n message: `Username must be at least ${USERNAME_MIN_LENGTH} characters`,\n });\n }\n\n if (lengthInCodePoints(value) > USERNAME_MAX_LENGTH) {\n errors.push({\n code: 'too_long',\n message: `Username must be ${USERNAME_MAX_LENGTH} characters or fewer`,\n });\n }\n\n if (!USERNAME_ALLOWED_CHARS.test(value)) {\n errors.push({\n code: 'invalid_chars',\n message: 'Username can only contain letters, numbers, underscores, and hyphens',\n });\n }\n\n // Must contain at least one letter — guards against all-numeric or\n // all-symbol usernames slipping through. Pure numeric values like\n // \"12345\" previously passed the character allow-list alone. Only\n // check this when the length is in range so a too-short value doesn't\n // get two errors.\n if (\n lengthInCodePoints(value) >= USERNAME_MIN_LENGTH &&\n lengthInCodePoints(value) <= USERNAME_MAX_LENGTH &&\n !/[a-zA-Z]/.test(value)\n ) {\n errors.push({\n code: 'no_letter',\n message: 'Username must contain at least one letter',\n });\n }\n\n return errors.length === 0 ? { valid: true, value } : { valid: false, errors };\n}\n","/**\n * Bundle validation across all three user-identity fields.\n *\n * Mirrors `microfe-auth/src/auth/utils/validation.ts:validateUserFields`\n * from the BOFF-7214 client-side PR (#59). Do not edit one without\n * editing the other.\n *\n * Use this on the server in `signUp`, `updateCurrentUserProfile`, and\n * `updateUser` so the BOFF-7214 invariant — `firstName` / `lastName`\n * contain a letter, `username` contains a letter — holds at every\n * mutation surface, not just signup (BOFF-7261).\n *\n * `requireAll` controls how blank fields are treated:\n * - `true` (default): used by `signUp` — every field must validate.\n * An empty field fails with `code: \"required\"`.\n * - `false`: used by `updateCurrentUserProfile` / `updateUser` — an\n * existing user whose optional `firstName` / `lastName` is unset\n * (e.g. provisioned via an identity provider) can still update\n * unrelated fields like phone or role. Blank fields are skipped.\n *\n * On success, the result carries the canonicalised values from each\n * individual validator (NFC, typographic apostrophes folded to ASCII,\n * trimmed) so the caller writes the same strings the validators approved\n * — no validate/submit divergence.\n */\n\nimport { validateName } from './name.js';\nimport { validateUsername } from './username.js';\n\nexport type UserFieldKey = 'firstName' | 'lastName' | 'username';\n\nexport interface UserFieldError {\n field: UserFieldKey;\n code: string;\n message: string;\n}\n\nexport interface ValidatedUserFields {\n firstName: string;\n lastName: string;\n username: string;\n}\n\nexport type UserFieldsValidationResult =\n | { valid: true; values: ValidatedUserFields }\n | { valid: false; errors: UserFieldError[] };\n\nexport function validateUserFields(\n input: {\n firstName?: string | null;\n lastName?: string | null;\n username?: string | null;\n },\n options: { requireAll?: boolean } = {}\n): UserFieldsValidationResult {\n const requireAll = options.requireAll ?? true;\n const errors: UserFieldError[] = [];\n\n const isBlank = (v: string | null | undefined): boolean => !v || v.trim().length === 0;\n\n const firstName = !isBlank(input.firstName) || requireAll ? validateName(input.firstName) : null;\n if (firstName && !firstName.valid) {\n errors.push({\n field: 'firstName',\n code: firstName.code,\n message: firstName.message,\n });\n }\n\n const lastName = !isBlank(input.lastName) || requireAll ? validateName(input.lastName) : null;\n if (lastName && !lastName.valid) {\n errors.push({\n field: 'lastName',\n code: lastName.code,\n message: lastName.message,\n });\n }\n\n const username = !isBlank(input.username) || requireAll ? validateUsername(input.username) : null;\n if (username && !username.valid) {\n for (const e of username.errors) {\n errors.push({ field: 'username', code: e.code, message: e.message });\n }\n }\n\n if (errors.length > 0) return { valid: false, errors };\n\n const valueOr = (result: { valid: true; value: string } | null, fallback: string | null | undefined): string =>\n result ? result.value : (fallback ?? '').trim();\n\n return {\n valid: true,\n values: {\n firstName: valueOr(firstName as { valid: true; value: string } | null, input.firstName),\n lastName: valueOr(lastName as { valid: true; value: string } | null, input.lastName),\n username: valueOr(username as { valid: true; value: string } | null, input.username),\n },\n };\n}\n","/**\n * Whole-schema `@rbac` coverage guard for subgraph services.\n *\n * Authorization on the platform is enforced at the API gateway, driven entirely by the\n * `@rbac` directive on each root-operation field (see\n * `~/products/dev/platform/context/identity/rbac/`). The gateway's rbac-middleware\n * fails CLOSED for HTTP Query/Mutation traffic, so a field without a usable `@rbac`\n * is denied for every caller (\"Field X is missing @rbac directive\"): an outage.\n * Subscriptions over the WebSocket transport are let through with only a warning,\n * so a missing `@rbac` there is a silent authorization hole.\n *\n * `assertRbacCoverage` is meant to be called from one unit test per svc. It parses\n * the svc's real SDL into a GraphQL AST (no regex) and checks, for every\n * Query/Mutation/Subscription field:\n *\n * 1. it carries an `@rbac` directive;\n * 2. the directive is well-formed the way the gateway reads it: `public: true`,\n * `scopeType: \"self\"`, an `actorTypes`-only gate, or `action` + `resource` +\n * a known `scopeType` (`entity` additionally needs `scopeArg`);\n * 3. `resourceIdArg` (and the `scopeArg` of `entity`/`billing` scopes) resolves to a\n * single ID/String through the field's arguments and input objects, at most two\n * segments deep — anything else silently degrades to a type-wide check or a deny;\n * 4. optionally, the set of `scopeType: \"self\"` fields equals a pinned, reviewed list,\n * because \"self\" is an authentication gate only and the resolver alone must scope\n * the data to the caller.\n *\n * Lifted from wspace-healthybowl-svc `src/__tests__/rbac-coverage.test.ts`\n * (BOFF-6052, BOFF-7476) so every svc runs one implementation.\n *\n * @example\n * ```ts\n * import { assertRbacCoverage } from '@burdenoff/be-sdk/validation';\n *\n * it('gates every root field with a well-formed @rbac', () => {\n * const report = assertRbacCoverage(join(__dirname, '../modules'), {\n * selfScopedFields: { myAgents: 'resolver filters by ctx.actorId' },\n * minRootFields: 200,\n * });\n * expect(report.rootFields.length).toBeGreaterThan(200);\n * });\n * ```\n */\nimport { readdirSync, readFileSync, statSync } from 'node:fs';\nimport { extname, join } from 'node:path';\nimport {\n Kind,\n parse,\n type DirectiveNode,\n type DocumentNode,\n type FieldDefinitionNode,\n type InputObjectTypeDefinitionNode,\n type InputObjectTypeExtensionNode,\n type InputValueDefinitionNode,\n type TypeNode,\n} from 'graphql';\n\n/** Scope types the gateway rbac-middleware understands for an action+resource check. */\nexport const RBAC_GATED_SCOPE_TYPES = ['wspace', 'global', 'entity', 'billing', 'organization'] as const;\n\n/** Every `scopeType` value the gateway accepts (the gated ones plus the `self` authentication gate). */\nexport const RBAC_SCOPE_TYPES = [...RBAC_GATED_SCOPE_TYPES, 'self'] as const;\n\nexport type RbacScopeType = (typeof RBAC_SCOPE_TYPES)[number];\n\n/** Default root operation types whose every field must be RBAC-gated. */\nexport const DEFAULT_RBAC_ROOT_TYPES = ['Query', 'Mutation', 'Subscription'] as const;\n\n/**\n * The most segments a `resourceIdArg`/`scopeArg` path can have and still resolve however\n * the client writes the request. The gateway's `extractFieldArguments` copies an inline\n * object argument one level deep and skips a nested object literal inside it, so\n * `input.nested.id` resolves only when `input` arrives as a variable.\n */\nexport const DEFAULT_MAX_RBAC_ARG_PATH_SEGMENTS = 2;\n\n/** The billing scope reads this argument when the directive sets no `scopeArg`. */\nconst DEFAULT_BILLING_SCOPE_ARG = 'billingAccountId';\n\nconst DEFAULT_ID_SCALARS = ['ID', 'String'] as const;\nconst SCHEMA_EXTENSIONS = new Set(['.gql', '.graphql']);\nconst SKIPPED_DIRECTORIES = new Set(['node_modules', 'dist', 'build', 'coverage']);\n\n/**\n * Placeholder root fields (`_empty`, `_emptyVibecontrols`, …) keep an otherwise-empty\n * root type valid SDL. They expose no data and need no gate.\n */\nconst PLACEHOLDER_FIELD = /^_empty[A-Za-z0-9]*$/;\n\n/** The `@rbac` arguments the gateway reads, as written in the SDL. */\nexport interface RbacDirectiveArgs {\n action?: string;\n resource?: string;\n resourceIdArg?: string;\n scopeType?: string;\n scopeArg?: string;\n public?: boolean;\n actorTypes?: string[];\n}\n\n/** One root-operation field found in the schema. */\nexport interface RbacRootField {\n /** Root type name, e.g. `Query`. */\n type: string;\n /** Field name, e.g. `myAgents`. */\n name: string;\n /** `Type.field`. */\n coordinate: string;\n /** Source file the field was parsed from, when the input came from disk. */\n file?: string;\n /** Parsed `@rbac` arguments, or `null` when the field has no `@rbac`. */\n rbac: RbacDirectiveArgs | null;\n}\n\n/** A pinned list of reviewed fields: field names or `Type.field` coordinates, optionally with the reason. */\nexport type RbacFieldPin = readonly string[] | Readonly<Record<string, string>>;\n\nexport interface RbacCoverageOptions {\n /** Root types to check. Defaults to Query/Mutation/Subscription plus any names a `schema { … }` block maps. */\n rootTypes?: readonly string[];\n /** Extra field names or `Type.field` coordinates to skip. `_empty*` placeholders are always skipped. */\n exemptFields?: readonly string[];\n /**\n * The reviewed set of `scopeType: \"self\"` fields. When given, every self-scoped field must\n * be listed and every entry must match a self-scoped field. Omit to skip the pin check.\n */\n selfScopedFields?: RbacFieldPin;\n /** Fail when fewer root fields than this are found (guards a wrong path \"passing\"). Default 1. */\n minRootFields?: number;\n /** Maximum `resourceIdArg`/`scopeArg` path segments. Default {@link DEFAULT_MAX_RBAC_ARG_PATH_SEGMENTS}. */\n maxArgPathSegments?: number;\n /** Scalars an id path may end on. Default `ID`, `String`. */\n idScalars?: readonly string[];\n}\n\n/** A schema loaded for analysis: the parsed document plus where it came from. */\nexport interface RbacSchemaDocument {\n document: DocumentNode;\n file?: string;\n}\n\nexport interface RbacCoverageReport {\n /** Every checked root field (placeholders and exemptions removed). */\n rootFields: RbacRootField[];\n /** `Type.field` of root fields without `@rbac`. */\n missing: string[];\n /** `Type.field: reason` for directives the gateway would deny as invalid. */\n malformed: string[];\n /** `Type.field: reason` for `resourceIdArg`/`scopeArg` paths that do not resolve to one id. */\n unresolvedArgPaths: string[];\n /** `Type.field` of self-scoped fields missing from `selfScopedFields`. */\n unreviewedSelfScoped: string[];\n /** Entries of `selfScopedFields` that match no self-scoped field. */\n staleSelfScoped: string[];\n /** Every problem above, one line each, plus a too-few-fields problem when applicable. */\n problems: string[];\n ok: boolean;\n}\n\n/** Thrown by {@link assertRbacCoverage}; carries the full report. */\nexport class RbacCoverageError extends Error {\n readonly report: RbacCoverageReport;\n\n constructor(report: RbacCoverageReport) {\n super(`RBAC coverage check failed (${report.problems.length} problem(s)):\\n - ${report.problems.join('\\n - ')}`);\n this.name = 'RbacCoverageError';\n this.report = report;\n }\n}\n\n/** Accepted inputs: schema file/directory paths, or already-parsed documents. */\nexport type RbacCoverageSource =\n | string\n | readonly string[]\n | DocumentNode\n | readonly DocumentNode[]\n | readonly RbacSchemaDocument[];\n\nfunction collectSchemaFiles(path: string): string[] {\n if (!statSync(path).isDirectory()) return [path];\n const out: string[] = [];\n const entries = readdirSync(path, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name, 'en'));\n for (const entry of entries) {\n const full = join(path, entry.name);\n if (entry.isDirectory()) {\n if (!SKIPPED_DIRECTORIES.has(entry.name) && !entry.name.startsWith('.')) out.push(...collectSchemaFiles(full));\n } else if (SCHEMA_EXTENSIONS.has(extname(entry.name))) {\n out.push(full);\n }\n }\n return out;\n}\n\n/**\n * Parse every `.gql`/`.graphql` file under the given paths. A path may be a single SDL file\n * (e.g. `.hive-schema.graphql`) or a directory, which is walked recursively (skipping\n * dot-directories, `node_modules`, `dist`, `build` and `coverage`).\n */\nexport function loadRbacSchemaDocuments(paths: string | readonly string[]): RbacSchemaDocument[] {\n const files = (typeof paths === 'string' ? [paths] : paths).flatMap(collectSchemaFiles);\n return files.map((file) => {\n try {\n return { file, document: parse(readFileSync(file, 'utf8')) };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to parse GraphQL schema ${file}: ${message}`, { cause: error });\n }\n });\n}\n\nfunction isDocumentNode(value: unknown): value is DocumentNode {\n return typeof value === 'object' && value !== null && (value as { kind?: unknown }).kind === Kind.DOCUMENT;\n}\n\nfunction toSchemaDocuments(source: RbacCoverageSource): RbacSchemaDocument[] {\n if (typeof source === 'string') return loadRbacSchemaDocuments(source);\n if (isDocumentNode(source)) return [{ document: source }];\n const items: readonly unknown[] = source;\n if (items.every((item): item is string => typeof item === 'string')) return loadRbacSchemaDocuments(items);\n return items.map((item) => {\n if (isDocumentNode(item)) return { document: item };\n if (typeof item === 'object' && item !== null && isDocumentNode((item as RbacSchemaDocument).document)) {\n return item as RbacSchemaDocument;\n }\n throw new TypeError('RbacCoverageSource arrays must contain only paths, DocumentNodes or RbacSchemaDocuments');\n });\n}\n\nfunction rbacDirective(field: FieldDefinitionNode): DirectiveNode | undefined {\n return (field.directives ?? []).find((d) => d.name.value === 'rbac');\n}\n\n/** Read the `@rbac` arguments of a field definition the way the gateway does (literal values only). */\nexport function readRbacDirectiveArgs(field: FieldDefinitionNode): RbacDirectiveArgs | null {\n const directive = rbacDirective(field);\n if (!directive) return null;\n const args: RbacDirectiveArgs = {};\n for (const arg of directive.arguments ?? []) {\n const name = arg.name.value;\n const value = arg.value;\n if (name === 'public') {\n if (value.kind === Kind.BOOLEAN) args.public = value.value;\n } else if (name === 'actorTypes') {\n if (value.kind === Kind.LIST) {\n args.actorTypes = value.values.flatMap((v) => (v.kind === Kind.STRING ? [v.value] : []));\n } else if (value.kind === Kind.STRING) {\n args.actorTypes = [value.value];\n }\n } else if (\n value.kind === Kind.STRING &&\n (name === 'action' ||\n name === 'resource' ||\n name === 'resourceIdArg' ||\n name === 'scopeType' ||\n name === 'scopeArg')\n ) {\n args[name] = value.value;\n }\n }\n return args;\n}\n\nfunction rootTypeNames(docs: readonly RbacSchemaDocument[], configured?: readonly string[]): Set<string> {\n if (configured) return new Set(configured);\n const names = new Set<string>(DEFAULT_RBAC_ROOT_TYPES);\n for (const { document } of docs) {\n for (const def of document.definitions) {\n if (def.kind === Kind.SCHEMA_DEFINITION || def.kind === Kind.SCHEMA_EXTENSION) {\n for (const op of def.operationTypes ?? []) names.add(op.type.name.value);\n }\n }\n }\n return names;\n}\n\nfunction inputFieldsByType(docs: readonly RbacSchemaDocument[]): Map<string, InputValueDefinitionNode[]> {\n const out = new Map<string, InputValueDefinitionNode[]>();\n for (const { document } of docs) {\n for (const def of document.definitions) {\n if (def.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION || def.kind === Kind.INPUT_OBJECT_TYPE_EXTENSION) {\n const input: InputObjectTypeDefinitionNode | InputObjectTypeExtensionNode = def;\n const existing = out.get(input.name.value) ?? [];\n existing.push(...(input.fields ?? []));\n out.set(input.name.value, existing);\n }\n }\n }\n return out;\n}\n\n/** The named type under any NonNull wrappers, or null when a List sits anywhere in between. */\nfunction unwrapSingular(type: TypeNode): string | null {\n if (type.kind === Kind.NON_NULL_TYPE) return unwrapSingular(type.type);\n if (type.kind === Kind.LIST_TYPE) return null;\n return type.name.value;\n}\n\ninterface PathContext {\n inputs: Map<string, InputValueDefinitionNode[]>;\n maxSegments: number;\n idScalars: ReadonlySet<string>;\n}\n\n/**\n * Mirrors the gateway's `extractFieldArguments` + `getValueAtPath`: the path is split on '.',\n * walked from the field's arguments through input objects, and used only when it lands on a\n * string. Returns why the path cannot resolve for every request shape, or null when it does.\n */\nexport function rbacArgPathProblem(\n field: FieldDefinitionNode,\n path: string,\n inputs: Map<string, readonly InputValueDefinitionNode[]>,\n options: { maxSegments?: number; idScalars?: readonly string[] } = {}\n): string | null {\n const maxSegments = options.maxSegments ?? DEFAULT_MAX_RBAC_ARG_PATH_SEGMENTS;\n const idScalars = new Set(options.idScalars ?? DEFAULT_ID_SCALARS);\n const segments = path.split('.');\n if (segments.some((s) => s.length === 0)) return `\"${path}\" has an empty segment`;\n if (segments.length > maxSegments) {\n return `\"${path}\" has ${segments.length} segments; the gateway reads at most ${maxSegments} (it drops nested object literals)`;\n }\n const [head, ...rest] = segments;\n const arg = (field.arguments ?? []).find((a) => a.name.value === head);\n if (!arg) return `no argument \"${head}\"`;\n let typeName = unwrapSingular(arg.type);\n let walked = head;\n for (const segment of rest) {\n if (typeName === null) return `\"${walked}\" is a list`;\n const fields = inputs.get(typeName);\n if (!fields) return `\"${walked}\" is ${typeName}, not an input object`;\n const next = fields.find((f) => f.name.value === segment);\n if (!next) return `${typeName} has no field \"${segment}\"`;\n typeName = unwrapSingular(next.type);\n walked = `${walked}.${segment}`;\n }\n if (typeName === null) return `\"${walked}\" is a list`;\n if (!idScalars.has(typeName)) return `\"${walked}\" is ${typeName}, not ${[...idScalars].join('/')}`;\n return null;\n}\n\n/** Why the gateway would deny this directive as invalid, or null when it is well-formed. */\nfunction malformedReason(rbac: RbacDirectiveArgs): string | null {\n if (rbac.public === true) return null;\n if (rbac.scopeType === 'self') return null;\n const hasActionResource = Boolean(rbac.action) && Boolean(rbac.resource);\n // An actorTypes-only gate is allowed by the gateway without an RBAC round-trip.\n if (!hasActionResource && rbac.actorTypes && rbac.actorTypes.length > 0) {\n if (rbac.action || rbac.resource) return 'actorTypes gate sets only one of action/resource';\n return null;\n }\n if (!hasActionResource) return 'missing action or resource (and not public, self or actorTypes-only)';\n if (!rbac.scopeType) return 'missing scopeType';\n if (!(RBAC_GATED_SCOPE_TYPES as readonly string[]).includes(rbac.scopeType)) {\n return `unknown scopeType \"${rbac.scopeType}\"`;\n }\n if (rbac.scopeType === 'entity' && !rbac.scopeArg) return 'entity scope requires scopeArg';\n return null;\n}\n\nfunction pinEntries(pin: RbacFieldPin): string[] {\n return Array.isArray(pin) ? [...(pin as readonly string[])] : Object.keys(pin);\n}\n\nfunction matchesEntry(field: RbacRootField, entry: string): boolean {\n return entry === field.name || entry === field.coordinate;\n}\n\n/** Deterministic, locale-independent ordering for report lines. */\nfunction sortLines(lines: string[]): string[] {\n return lines.sort((a, b) => a.localeCompare(b, 'en'));\n}\n\ninterface CollectedRootField {\n root: RbacRootField;\n definition: FieldDefinitionNode;\n}\n\nfunction collectRootFields(\n docs: readonly RbacSchemaDocument[],\n roots: ReadonlySet<string>,\n exempt: ReadonlySet<string>\n): CollectedRootField[] {\n const out: CollectedRootField[] = [];\n for (const { document, file } of docs) {\n for (const def of document.definitions) {\n if (def.kind !== Kind.OBJECT_TYPE_DEFINITION && def.kind !== Kind.OBJECT_TYPE_EXTENSION) continue;\n const type = def.name.value;\n if (!roots.has(type)) continue;\n for (const definition of def.fields ?? []) {\n const name = definition.name.value;\n const coordinate = `${type}.${name}`;\n if (PLACEHOLDER_FIELD.test(name) || exempt.has(name) || exempt.has(coordinate)) continue;\n const root: RbacRootField = { type, name, coordinate, rbac: readRbacDirectiveArgs(definition) };\n if (file) root.file = file;\n out.push({ root, definition });\n }\n }\n }\n return out;\n}\n\n/** The argument path a gated scope reads its scope id from; only `entity` and `billing` read one. */\nfunction scopeArgPath(rbac: RbacDirectiveArgs): string | undefined {\n if (rbac.public === true) return undefined;\n if (rbac.scopeType === 'entity') return rbac.scopeArg;\n if (rbac.scopeType === 'billing') return rbac.scopeArg ?? DEFAULT_BILLING_SCOPE_ARG;\n return undefined;\n}\n\nfunction argPathProblems(\n definition: FieldDefinitionNode,\n rbac: RbacDirectiveArgs,\n context: PathContext\n): { label: string; problem: string }[] {\n const options = { maxSegments: context.maxSegments, idScalars: [...context.idScalars] };\n const checks: { label: string; path: string | undefined }[] = [\n { label: 'resourceIdArg', path: rbac.resourceIdArg },\n { label: 'scopeArg', path: scopeArgPath(rbac) },\n ];\n return checks.flatMap(({ label, path }) => {\n if (path === undefined) return [];\n const problem = rbacArgPathProblem(definition, path, context.inputs, options);\n return problem ? [{ label, problem }] : [];\n });\n}\n\nfunction selfScopedPinProblems(\n rootFields: readonly RbacRootField[],\n pin: RbacFieldPin | undefined\n): { unreviewed: string[]; stale: string[] } {\n if (!pin) return { unreviewed: [], stale: [] };\n const entries = pinEntries(pin);\n const selfScoped = rootFields.filter((f) => f.rbac?.scopeType === 'self' && f.rbac.public !== true);\n return {\n unreviewed: selfScoped\n .filter((field) => !entries.some((entry) => matchesEntry(field, entry)))\n .map((field) => field.coordinate),\n stale: entries.filter((entry) => !selfScoped.some((field) => matchesEntry(field, entry))),\n };\n}\n\n/** Analyse the schema and return every coverage problem without throwing. */\nexport function analyzeRbacCoverage(source: RbacCoverageSource, options: RbacCoverageOptions = {}): RbacCoverageReport {\n const docs = toSchemaDocuments(source);\n const collected = collectRootFields(docs, rootTypeNames(docs, options.rootTypes), new Set(options.exemptFields));\n const pathContext: PathContext = {\n inputs: inputFieldsByType(docs),\n maxSegments: options.maxArgPathSegments ?? DEFAULT_MAX_RBAC_ARG_PATH_SEGMENTS,\n idScalars: new Set(options.idScalars ?? DEFAULT_ID_SCALARS),\n };\n\n const missing: string[] = [];\n const malformed: string[] = [];\n const unresolvedArgPaths: string[] = [];\n for (const { root, definition } of collected) {\n const { rbac, coordinate } = root;\n if (!rbac) {\n missing.push(coordinate);\n continue;\n }\n const reason = malformedReason(rbac);\n if (reason) malformed.push(`${coordinate}: ${reason}`);\n for (const { label, problem } of argPathProblems(definition, rbac, pathContext)) {\n unresolvedArgPaths.push(`${coordinate}: ${label} ${problem}`);\n }\n }\n\n const rootFields = collected.map(({ root }) => root);\n const pins = selfScopedPinProblems(rootFields, options.selfScopedFields);\n const unreviewedSelfScoped = sortLines(pins.unreviewed);\n const staleSelfScoped = sortLines(pins.stale);\n sortLines(missing);\n sortLines(malformed);\n sortLines(unresolvedArgPaths);\n\n const minRootFields = options.minRootFields ?? 1;\n const problems = [\n ...(rootFields.length < minRootFields\n ? [`found ${rootFields.length} root field(s), expected at least ${minRootFields} (wrong schema path?)`]\n : []),\n ...missing.map((c) => `${c}: missing @rbac directive`),\n ...malformed.map((m) => `malformed @rbac on ${m}`),\n ...unresolvedArgPaths.map((p) => `unresolvable @rbac path on ${p}`),\n ...unreviewedSelfScoped.map((c) => `${c}: scopeType \"self\" is not in the reviewed selfScopedFields list`),\n ...staleSelfScoped.map((e) => `selfScopedFields entry \"${e}\" matches no self-scoped root field (stale)`),\n ];\n\n return {\n rootFields,\n missing,\n malformed,\n unresolvedArgPaths,\n unreviewedSelfScoped,\n staleSelfScoped,\n problems,\n ok: problems.length === 0,\n };\n}\n\n/**\n * Assert full `@rbac` coverage. Throws {@link RbacCoverageError} listing every problem;\n * returns the report on success so callers can make further assertions on `rootFields`.\n */\nexport function assertRbacCoverage(source: RbacCoverageSource, options: RbacCoverageOptions = {}): RbacCoverageReport {\n const report = analyzeRbacCoverage(source, options);\n if (!report.ok) throw new RbacCoverageError(report);\n return report;\n}\n","/** Canonical billing policy extracted from global-billing input validation (BOFF-10764).\n * Currency support and the existing 1e9 ceiling are unchanged. This validates\n * major-unit values only; it does not round, convert FX or authorize payment.\n */\nexport const SUPPORTED_BILLING_CURRENCIES = Object.freeze([\n 'USD',\n 'EUR',\n 'GBP',\n 'INR',\n 'AUD',\n 'CAD',\n 'SGD',\n 'JPY',\n 'CNY',\n 'BRL',\n 'MXN',\n 'KRW',\n 'HKD',\n 'NOK',\n 'SEK',\n 'DKK',\n 'CHF',\n 'NZD',\n 'ZAR',\n 'AED',\n 'SAR',\n 'QAR',\n 'OMR',\n 'BHD',\n 'KWD',\n 'JOD',\n 'EGP',\n 'PKR',\n 'BDT',\n 'LKR',\n 'THB',\n 'MYR',\n 'IDR',\n 'PHP',\n 'VND',\n 'TWD',\n 'CZK',\n 'HUF',\n 'PLN',\n 'RON',\n 'RUB',\n 'TRY',\n 'ILS',\n 'NGN',\n 'GHS',\n 'KES',\n 'TZS',\n 'UGX',\n 'ETB',\n 'MAD',\n 'DZD',\n 'TND',\n 'BWP',\n 'MUR',\n 'MVR',\n 'BND',\n 'KHR',\n 'MMK',\n 'KZT',\n 'UZS',\n 'AZN',\n 'GEL',\n 'AMD',\n 'UAH',\n 'BGN',\n 'HRK',\n 'MKD',\n 'ALL',\n 'RSD',\n 'CLP',\n 'COP',\n 'PEN',\n 'ARS',\n 'BOB',\n 'PYG',\n 'UYU',\n 'GTQ',\n 'HNL',\n 'NIO',\n 'CRC',\n 'DOP',\n 'TTD',\n 'JMD',\n 'BBD',\n 'HTG',\n 'BZD',\n 'GYD',\n 'SRD',\n 'XCD',\n 'PAB',\n] as const);\nexport type SupportedBillingCurrency = (typeof SUPPORTED_BILLING_CURRENCIES)[number];\nconst supportedCurrencies: ReadonlySet<string> = new Set(SUPPORTED_BILLING_CURRENCIES);\nexport const MAX_BILLING_AMOUNT = 1_000_000_000;\n\n/** Case-insensitive, as in billing. Whitespace is not silently accepted. */\nexport function isSupportedBillingCurrency(currency: unknown): boolean {\n return typeof currency === 'string' && supportedCurrencies.has(currency.toUpperCase());\n}\n\nexport type BillingAmountErrorCode = 'not_finite' | 'not_positive' | 'negative' | 'exceeds_maximum';\nexport type BillingAmountValidationResult =\n | { valid: true; value: number }\n | { valid: false; code: BillingAmountErrorCode };\n\n/** Zero is rejected by default. Callers may explicitly permit unpaid amounts. */\nexport function validateBillingAmount(\n amount: unknown,\n options: { allowZero?: boolean } = {}\n): BillingAmountValidationResult {\n if (typeof amount !== 'number' || !Number.isFinite(amount)) return { valid: false, code: 'not_finite' };\n if (options.allowZero === true ? amount < 0 : amount <= 0) {\n return { valid: false, code: options.allowZero === true ? 'negative' : 'not_positive' };\n }\n if (amount > MAX_BILLING_AMOUNT) return { valid: false, code: 'exceeds_maximum' };\n return { valid: true, value: amount };\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { productSlugVariants, isSameProductSlug } from './chunk-OBBCR6WY.js';
|
|
2
1
|
import { withWorkspaceContextSync, withWorkspaceContext, setWorkspaceContext, runOperationWithRlsGuc, runOperationInCallerTransaction, resetCallerTransactionStateForTests, maybeTagConnection, maybeSetRlsGuc, injectWhereWorkspaceId, injectCreateFields, getWorkspaceContext, getScopedWorkspaceContext, getCallerTransaction, defaultWorkspaceExtensionConfig, buildTransactionContextStatement, addWorkspaceExtension } from './chunk-E4QNLVY4.js';
|
|
2
|
+
import { productSlugVariants, isSameProductSlug } from './chunk-OBBCR6WY.js';
|
|
3
3
|
import { isTransientAcquireError, installAcquireRetry, ensureServiceApplicationName, createPrismaClient, createPrismaAdapter, createConnectionPool, configurePrismaLogging, PrismaClientWrapper, addGraphExtension } from './chunk-K52ICDCP.js';
|
|
4
4
|
import { getGraphEventEmitter } from './chunk-TX2GDIWP.js';
|
|
5
5
|
import { logger } from './chunk-RU266375.js';
|
|
@@ -686,5 +686,5 @@ function createContextFromSDK(sdkContext) {
|
|
|
686
686
|
__name(createContextFromSDK, "createContextFromSDK");
|
|
687
687
|
|
|
688
688
|
export { buildContextWhereClause, buildContextWhereConditions, checkDatabaseHealth, contextMatches, createContextFromSDK, createDatabaseClient, createDatabaseClientFromEnv, extractFieldsFromModel, getAllModelNames, getDatabaseManager, getDatabaseProductName, getDatabaseStats, getDatabaseVersion, getDb, getModelFields, hasModel, initializeDatabase, initializeDatabaseWithConfig, isDatabaseInitialized, loadGeneratedFields, mergeContext, parseContext, prisma_exports, resetDatabaseManager, resolvePoolTuningFromEnv, testConnection, toContextJson };
|
|
689
|
-
//# sourceMappingURL=chunk-
|
|
690
|
-
//# sourceMappingURL=chunk-
|
|
689
|
+
//# sourceMappingURL=chunk-QCOC2SF3.js.map
|
|
690
|
+
//# sourceMappingURL=chunk-QCOC2SF3.js.map
|
|
@@ -1 +1 @@
|
|
|
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","queryTimeout","queryTimeoutMillis","statementTimeout","statementTimeoutMillis","idleInTransactionTimeout","idleInTransactionTimeoutMillis","lockTimeout","lockTimeoutMillis","createDatabaseClientFromEnv","overrides","databaseUrl","Error","isDevelopment","maxConnections","idleTimeoutMillis","connectionTimeoutMillis","enableQueryLogging","slowQueryThreshold","acquireRetriesRaw","acquireRetries","acquireRetryDelay","acquireRetryDelayMillis","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","slugs","productSlugVariants","OR","map","slug","toContextJson","contextInput","custom","filterNullValues","obj","filtered","key","value","entries","mergeContextField","merged","fieldValue","mergeContext","existingContext","newContext","Array","isArray","parseContext","contextJson","ctx","contextMatches","isSameProductSlug","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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OuB,KAAAA,EAAO;AAC1D,IAAA,OAAO,KAAA;AACT,EAAA;AAEA,EAAA,IAAIvB,MAAAA,CAAOwB,aAAa,IAAA,IAAQ,CAAC8B,kBAAkB3B,OAAAA,CAAQH,SAAAA,EAAWxB,MAAAA,CAAOwB,SAAS,CAAA,EAAG;AACvF,IAAA,OAAO,KAAA;AACT,EAAA;AACA,EAAA,IAAIxB,OAAOyB,cAAAA,IAAkB,IAAA,IAAQE,OAAAA,CAAQF,cAAAA,KAAmBzB,OAAOyB,cAAAA,EAAgB;AACrF,IAAA,OAAO,KAAA;AACT,EAAA;AAEA,EAAA,OAAO,IAAA;AACT;AA1BgB4B,MAAAA,CAAAA,cAAAA,EAAAA,gBAAAA,CAAAA;AAkCT,SAASE,qBAAqBC,UAAAA,EAOpC;AACC,EAAA,OAAO;AACLrC,IAAAA,WAAAA,EAAaqC,WAAWrC,WAAAA,IAAe,IAAA;AACvCE,IAAAA,MAAAA,EAAQmC,WAAWnC,MAAAA,IAAU,IAAA;AAC7BC,IAAAA,SAAAA,EAAWkC,WAAWlC,SAAAA,IAAa,IAAA;AACnCC,IAAAA,KAAAA,EAAOiC,WAAWjC,KAAAA,IAAS,IAAA;AAC3BC,IAAAA,SAAAA,EAAWgC,WAAWhC,SAAAA,IAAa,IAAA;AACnCC,IAAAA,cAAAA,EAAgB+B,WAAW/B,cAAAA,IAAkB;AAC/C,GAAA;AACF;AAhBgB8B,MAAAA,CAAAA,oBAAAA,EAAAA,sBAAAA,CAAAA","file":"chunk-WSAWJC4D.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 /** Client-side node-postgres query_timeout in ms, if opted in (pooler-safe). */\n queryTimeoutMillis?: number;\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_QUERY_TIMEOUT: client-side node-postgres query_timeout in ms (opt-in, pooler-safe)\n * - DATABASE_STATEMENT_TIMEOUT: server-side statement_timeout in ms (opt-in; DIRECT :5432 only — see note)\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 timeouts).\n *\n * NOTE: prefer `DATABASE_QUERY_TIMEOUT` for services whose `DATABASE_URL` points\n * at the built-in PgBouncer (`:6432`). `DATABASE_STATEMENT_TIMEOUT` and friends\n * are Postgres startup parameters that Azure PgBouncer does not pass through, so\n * they silently have no effect (or fail the connection) on the pooled path.\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 queryTimeout = parsePositiveIntEnv('DATABASE_QUERY_TIMEOUT');\n if (queryTimeout !== undefined) {\n tuning.queryTimeoutMillis = queryTimeout;\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_QUERY_TIMEOUT: opt-in client-side query timeout in ms — the\n * PgBouncer-safe query bound (default: OFF, preserving current behavior)\n * - DATABASE_STATEMENT_TIMEOUT / DATABASE_IDLE_IN_TRANSACTION_TIMEOUT / DATABASE_LOCK_TIMEOUT:\n * opt-in server-side timeouts in ms (default: OFF; DIRECT :5432 only — not\n * honored through the built-in PgBouncer :6432 runtime path)\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 // Transient acquire retry — env-tunable, and unlike the fields above zero is\n // meaningful (DATABASE_ACQUIRE_RETRIES=0 disables the retry entirely).\n const acquireRetriesRaw = process.env['DATABASE_ACQUIRE_RETRIES']?.trim();\n if (acquireRetriesRaw !== undefined && acquireRetriesRaw !== '' && config.acquireRetries === undefined) {\n const parsed = Number.parseInt(acquireRetriesRaw, 10);\n if (Number.isFinite(parsed) && parsed >= 0) {\n config.acquireRetries = parsed;\n }\n }\n const acquireRetryDelay = parsePositiveIntEnv('DATABASE_ACQUIRE_RETRY_DELAY');\n if (acquireRetryDelay !== undefined && config.acquireRetryDelayMillis === undefined) {\n config.acquireRetryDelayMillis = acquireRetryDelay;\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\nimport { isSameProductSlug, productSlugVariants } from '../product-alias/index.js';\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 * One entry of {@link buildContextWhereConditions}: a JSON-path predicate on `context`,\n * or an `OR` of them (used for a renamed product's slug twins).\n */\nexport type ContextWhereCondition = { context: PrismaJsonFilter } | { OR: Array<{ context: PrismaJsonFilter }> };\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): ContextWhereCondition[] {\n if (!contextFilter) {\n return [];\n }\n\n const conditions: ContextWhereCondition[] = [];\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 // A renamed product (botlit → botmanor) matches rows stored under either slug while\n // they are migrated; every other product keeps the exact single-slug predicate.\n const slugs = productSlugVariants(contextFilter.productId);\n if (slugs.length > 1) {\n conditions.push({\n OR: slugs.map((slug) => ({ context: { path: ['productId'], equals: slug } })),\n });\n } else {\n conditions.push({\n context: {\n path: ['productId'],\n equals: contextFilter.productId,\n },\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 // Renamed products (botlit → botmanor) match under either slug while rows are migrated.\n if (filter.productId != null && !isSameProductSlug(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"]}
|
|
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","queryTimeout","queryTimeoutMillis","statementTimeout","statementTimeoutMillis","idleInTransactionTimeout","idleInTransactionTimeoutMillis","lockTimeout","lockTimeoutMillis","createDatabaseClientFromEnv","overrides","databaseUrl","Error","isDevelopment","maxConnections","idleTimeoutMillis","connectionTimeoutMillis","enableQueryLogging","slowQueryThreshold","acquireRetriesRaw","acquireRetries","acquireRetryDelay","acquireRetryDelayMillis","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","slugs","productSlugVariants","OR","map","slug","toContextJson","contextInput","custom","filterNullValues","obj","filtered","key","value","entries","mergeContextField","merged","fieldValue","mergeContext","existingContext","newContext","Array","isArray","parseContext","contextJson","ctx","contextMatches","isSameProductSlug","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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,IAAA,OAAO,KAAA;AACT,EAAA;AACA,EAAA,IAAItB,OAAOuB,KAAAA,IAAS,IAAA,IAAQI,OAAAA,CAAQJ,KAAAA,KAAUvB,OAAOuB,KAAAA,EAAO;AAC1D,IAAA,OAAO,KAAA;AACT,EAAA;AAEA,EAAA,IAAIvB,MAAAA,CAAOwB,aAAa,IAAA,IAAQ,CAAC8B,kBAAkB3B,OAAAA,CAAQH,SAAAA,EAAWxB,MAAAA,CAAOwB,SAAS,CAAA,EAAG;AACvF,IAAA,OAAO,KAAA;AACT,EAAA;AACA,EAAA,IAAIxB,OAAOyB,cAAAA,IAAkB,IAAA,IAAQE,OAAAA,CAAQF,cAAAA,KAAmBzB,OAAOyB,cAAAA,EAAgB;AACrF,IAAA,OAAO,KAAA;AACT,EAAA;AAEA,EAAA,OAAO,IAAA;AACT;AA1BgB4B,MAAAA,CAAAA,cAAAA,EAAAA,gBAAAA,CAAAA;AAkCT,SAASE,qBAAqBC,UAAAA,EAOpC;AACC,EAAA,OAAO;AACLrC,IAAAA,WAAAA,EAAaqC,WAAWrC,WAAAA,IAAe,IAAA;AACvCE,IAAAA,MAAAA,EAAQmC,WAAWnC,MAAAA,IAAU,IAAA;AAC7BC,IAAAA,SAAAA,EAAWkC,WAAWlC,SAAAA,IAAa,IAAA;AACnCC,IAAAA,KAAAA,EAAOiC,WAAWjC,KAAAA,IAAS,IAAA;AAC3BC,IAAAA,SAAAA,EAAWgC,WAAWhC,SAAAA,IAAa,IAAA;AACnCC,IAAAA,cAAAA,EAAgB+B,WAAW/B,cAAAA,IAAkB;AAC/C,GAAA;AACF;AAhBgB8B,MAAAA,CAAAA,oBAAAA,EAAAA,sBAAAA,CAAAA","file":"chunk-QCOC2SF3.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 /** Client-side node-postgres query_timeout in ms, if opted in (pooler-safe). */\n queryTimeoutMillis?: number;\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_QUERY_TIMEOUT: client-side node-postgres query_timeout in ms (opt-in, pooler-safe)\n * - DATABASE_STATEMENT_TIMEOUT: server-side statement_timeout in ms (opt-in; DIRECT :5432 only — see note)\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 timeouts).\n *\n * NOTE: prefer `DATABASE_QUERY_TIMEOUT` for services whose `DATABASE_URL` points\n * at the built-in PgBouncer (`:6432`). `DATABASE_STATEMENT_TIMEOUT` and friends\n * are Postgres startup parameters that Azure PgBouncer does not pass through, so\n * they silently have no effect (or fail the connection) on the pooled path.\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 queryTimeout = parsePositiveIntEnv('DATABASE_QUERY_TIMEOUT');\n if (queryTimeout !== undefined) {\n tuning.queryTimeoutMillis = queryTimeout;\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_QUERY_TIMEOUT: opt-in client-side query timeout in ms — the\n * PgBouncer-safe query bound (default: OFF, preserving current behavior)\n * - DATABASE_STATEMENT_TIMEOUT / DATABASE_IDLE_IN_TRANSACTION_TIMEOUT / DATABASE_LOCK_TIMEOUT:\n * opt-in server-side timeouts in ms (default: OFF; DIRECT :5432 only — not\n * honored through the built-in PgBouncer :6432 runtime path)\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 // Transient acquire retry — env-tunable, and unlike the fields above zero is\n // meaningful (DATABASE_ACQUIRE_RETRIES=0 disables the retry entirely).\n const acquireRetriesRaw = process.env['DATABASE_ACQUIRE_RETRIES']?.trim();\n if (acquireRetriesRaw !== undefined && acquireRetriesRaw !== '' && config.acquireRetries === undefined) {\n const parsed = Number.parseInt(acquireRetriesRaw, 10);\n if (Number.isFinite(parsed) && parsed >= 0) {\n config.acquireRetries = parsed;\n }\n }\n const acquireRetryDelay = parsePositiveIntEnv('DATABASE_ACQUIRE_RETRY_DELAY');\n if (acquireRetryDelay !== undefined && config.acquireRetryDelayMillis === undefined) {\n config.acquireRetryDelayMillis = acquireRetryDelay;\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\nimport { isSameProductSlug, productSlugVariants } from '../product-alias/index.js';\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 * One entry of {@link buildContextWhereConditions}: a JSON-path predicate on `context`,\n * or an `OR` of them (used for a renamed product's slug twins).\n */\nexport type ContextWhereCondition = { context: PrismaJsonFilter } | { OR: Array<{ context: PrismaJsonFilter }> };\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): ContextWhereCondition[] {\n if (!contextFilter) {\n return [];\n }\n\n const conditions: ContextWhereCondition[] = [];\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 // A renamed product (botlit → botmanor) matches rows stored under either slug while\n // they are migrated; every other product keeps the exact single-slug predicate.\n const slugs = productSlugVariants(contextFilter.productId);\n if (slugs.length > 1) {\n conditions.push({\n OR: slugs.map((slug) => ({ context: { path: ['productId'], equals: slug } })),\n });\n } else {\n conditions.push({\n context: {\n path: ['productId'],\n equals: contextFilter.productId,\n },\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 // Renamed products (botlit → botmanor) match under either slug while rows are migrated.\n if (filter.productId != null && !isSameProductSlug(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"]}
|
|
@@ -113,8 +113,27 @@ declare function rbacArgPathProblem(field: FieldDefinitionNode, path: string, in
|
|
|
113
113
|
declare function analyzeRbacCoverage(source: RbacCoverageSource, options?: RbacCoverageOptions): RbacCoverageReport;
|
|
114
114
|
declare function assertRbacCoverage(source: RbacCoverageSource, options?: RbacCoverageOptions): RbacCoverageReport;
|
|
115
115
|
|
|
116
|
+
declare const SUPPORTED_BILLING_CURRENCIES: readonly ["USD", "EUR", "GBP", "INR", "AUD", "CAD", "SGD", "JPY", "CNY", "BRL", "MXN", "KRW", "HKD", "NOK", "SEK", "DKK", "CHF", "NZD", "ZAR", "AED", "SAR", "QAR", "OMR", "BHD", "KWD", "JOD", "EGP", "PKR", "BDT", "LKR", "THB", "MYR", "IDR", "PHP", "VND", "TWD", "CZK", "HUF", "PLN", "RON", "RUB", "TRY", "ILS", "NGN", "GHS", "KES", "TZS", "UGX", "ETB", "MAD", "DZD", "TND", "BWP", "MUR", "MVR", "BND", "KHR", "MMK", "KZT", "UZS", "AZN", "GEL", "AMD", "UAH", "BGN", "HRK", "MKD", "ALL", "RSD", "CLP", "COP", "PEN", "ARS", "BOB", "PYG", "UYU", "GTQ", "HNL", "NIO", "CRC", "DOP", "TTD", "JMD", "BBD", "HTG", "BZD", "GYD", "SRD", "XCD", "PAB"];
|
|
117
|
+
type SupportedBillingCurrency = (typeof SUPPORTED_BILLING_CURRENCIES)[number];
|
|
118
|
+
declare const MAX_BILLING_AMOUNT = 1000000000;
|
|
119
|
+
declare function isSupportedBillingCurrency(currency: unknown): boolean;
|
|
120
|
+
type BillingAmountErrorCode = 'not_finite' | 'not_positive' | 'negative' | 'exceeds_maximum';
|
|
121
|
+
type BillingAmountValidationResult = {
|
|
122
|
+
valid: true;
|
|
123
|
+
value: number;
|
|
124
|
+
} | {
|
|
125
|
+
valid: false;
|
|
126
|
+
code: BillingAmountErrorCode;
|
|
127
|
+
};
|
|
128
|
+
declare function validateBillingAmount(amount: unknown, options?: {
|
|
129
|
+
allowZero?: boolean;
|
|
130
|
+
}): BillingAmountValidationResult;
|
|
131
|
+
|
|
132
|
+
type index_BillingAmountErrorCode = BillingAmountErrorCode;
|
|
133
|
+
type index_BillingAmountValidationResult = BillingAmountValidationResult;
|
|
116
134
|
declare const index_DEFAULT_MAX_RBAC_ARG_PATH_SEGMENTS: typeof DEFAULT_MAX_RBAC_ARG_PATH_SEGMENTS;
|
|
117
135
|
declare const index_DEFAULT_RBAC_ROOT_TYPES: typeof DEFAULT_RBAC_ROOT_TYPES;
|
|
136
|
+
declare const index_MAX_BILLING_AMOUNT: typeof MAX_BILLING_AMOUNT;
|
|
118
137
|
declare const index_NAME_MAX_LENGTH: typeof NAME_MAX_LENGTH;
|
|
119
138
|
declare const index_NAME_MIN_LENGTH: typeof NAME_MIN_LENGTH;
|
|
120
139
|
type index_NameErrorCode = NameErrorCode;
|
|
@@ -131,6 +150,8 @@ type index_RbacFieldPin = RbacFieldPin;
|
|
|
131
150
|
type index_RbacRootField = RbacRootField;
|
|
132
151
|
type index_RbacSchemaDocument = RbacSchemaDocument;
|
|
133
152
|
type index_RbacScopeType = RbacScopeType;
|
|
153
|
+
declare const index_SUPPORTED_BILLING_CURRENCIES: typeof SUPPORTED_BILLING_CURRENCIES;
|
|
154
|
+
type index_SupportedBillingCurrency = SupportedBillingCurrency;
|
|
134
155
|
declare const index_USERNAME_MAX_LENGTH: typeof USERNAME_MAX_LENGTH;
|
|
135
156
|
declare const index_USERNAME_MIN_LENGTH: typeof USERNAME_MIN_LENGTH;
|
|
136
157
|
type index_UserFieldError = UserFieldError;
|
|
@@ -141,15 +162,17 @@ type index_UsernameValidationResult = UsernameValidationResult;
|
|
|
141
162
|
type index_ValidatedUserFields = ValidatedUserFields;
|
|
142
163
|
declare const index_analyzeRbacCoverage: typeof analyzeRbacCoverage;
|
|
143
164
|
declare const index_assertRbacCoverage: typeof assertRbacCoverage;
|
|
165
|
+
declare const index_isSupportedBillingCurrency: typeof isSupportedBillingCurrency;
|
|
144
166
|
declare const index_lengthInCodePoints: typeof lengthInCodePoints;
|
|
145
167
|
declare const index_loadRbacSchemaDocuments: typeof loadRbacSchemaDocuments;
|
|
146
168
|
declare const index_rbacArgPathProblem: typeof rbacArgPathProblem;
|
|
147
169
|
declare const index_readRbacDirectiveArgs: typeof readRbacDirectiveArgs;
|
|
170
|
+
declare const index_validateBillingAmount: typeof validateBillingAmount;
|
|
148
171
|
declare const index_validateName: typeof validateName;
|
|
149
172
|
declare const index_validateUserFields: typeof validateUserFields;
|
|
150
173
|
declare const index_validateUsername: typeof validateUsername;
|
|
151
174
|
declare namespace index {
|
|
152
|
-
export { index_DEFAULT_MAX_RBAC_ARG_PATH_SEGMENTS as DEFAULT_MAX_RBAC_ARG_PATH_SEGMENTS, index_DEFAULT_RBAC_ROOT_TYPES as DEFAULT_RBAC_ROOT_TYPES, index_NAME_MAX_LENGTH as NAME_MAX_LENGTH, index_NAME_MIN_LENGTH as NAME_MIN_LENGTH, type index_NameErrorCode as NameErrorCode, type index_NameValidationResult as NameValidationResult, index_RBAC_GATED_SCOPE_TYPES as RBAC_GATED_SCOPE_TYPES, index_RBAC_SCOPE_TYPES as RBAC_SCOPE_TYPES, index_RbacCoverageError as RbacCoverageError, type index_RbacCoverageOptions as RbacCoverageOptions, type index_RbacCoverageReport as RbacCoverageReport, type index_RbacCoverageSource as RbacCoverageSource, type index_RbacDirectiveArgs as RbacDirectiveArgs, type index_RbacFieldPin as RbacFieldPin, type index_RbacRootField as RbacRootField, type index_RbacSchemaDocument as RbacSchemaDocument, type index_RbacScopeType as RbacScopeType, index_USERNAME_MAX_LENGTH as USERNAME_MAX_LENGTH, index_USERNAME_MIN_LENGTH as USERNAME_MIN_LENGTH, type index_UserFieldError as UserFieldError, type index_UserFieldKey as UserFieldKey, type index_UserFieldsValidationResult as UserFieldsValidationResult, type index_UsernameErrorCode as UsernameErrorCode, type index_UsernameValidationResult as UsernameValidationResult, type index_ValidatedUserFields as ValidatedUserFields, index_analyzeRbacCoverage as analyzeRbacCoverage, index_assertRbacCoverage as assertRbacCoverage, index_lengthInCodePoints as lengthInCodePoints, index_loadRbacSchemaDocuments as loadRbacSchemaDocuments, index_rbacArgPathProblem as rbacArgPathProblem, index_readRbacDirectiveArgs as readRbacDirectiveArgs, index_validateName as validateName, index_validateUserFields as validateUserFields, index_validateUsername as validateUsername };
|
|
175
|
+
export { type index_BillingAmountErrorCode as BillingAmountErrorCode, type index_BillingAmountValidationResult as BillingAmountValidationResult, index_DEFAULT_MAX_RBAC_ARG_PATH_SEGMENTS as DEFAULT_MAX_RBAC_ARG_PATH_SEGMENTS, index_DEFAULT_RBAC_ROOT_TYPES as DEFAULT_RBAC_ROOT_TYPES, index_MAX_BILLING_AMOUNT as MAX_BILLING_AMOUNT, index_NAME_MAX_LENGTH as NAME_MAX_LENGTH, index_NAME_MIN_LENGTH as NAME_MIN_LENGTH, type index_NameErrorCode as NameErrorCode, type index_NameValidationResult as NameValidationResult, index_RBAC_GATED_SCOPE_TYPES as RBAC_GATED_SCOPE_TYPES, index_RBAC_SCOPE_TYPES as RBAC_SCOPE_TYPES, index_RbacCoverageError as RbacCoverageError, type index_RbacCoverageOptions as RbacCoverageOptions, type index_RbacCoverageReport as RbacCoverageReport, type index_RbacCoverageSource as RbacCoverageSource, type index_RbacDirectiveArgs as RbacDirectiveArgs, type index_RbacFieldPin as RbacFieldPin, type index_RbacRootField as RbacRootField, type index_RbacSchemaDocument as RbacSchemaDocument, type index_RbacScopeType as RbacScopeType, index_SUPPORTED_BILLING_CURRENCIES as SUPPORTED_BILLING_CURRENCIES, type index_SupportedBillingCurrency as SupportedBillingCurrency, index_USERNAME_MAX_LENGTH as USERNAME_MAX_LENGTH, index_USERNAME_MIN_LENGTH as USERNAME_MIN_LENGTH, type index_UserFieldError as UserFieldError, type index_UserFieldKey as UserFieldKey, type index_UserFieldsValidationResult as UserFieldsValidationResult, type index_UsernameErrorCode as UsernameErrorCode, type index_UsernameValidationResult as UsernameValidationResult, type index_ValidatedUserFields as ValidatedUserFields, index_analyzeRbacCoverage as analyzeRbacCoverage, index_assertRbacCoverage as assertRbacCoverage, index_isSupportedBillingCurrency as isSupportedBillingCurrency, index_lengthInCodePoints as lengthInCodePoints, index_loadRbacSchemaDocuments as loadRbacSchemaDocuments, index_rbacArgPathProblem as rbacArgPathProblem, index_readRbacDirectiveArgs as readRbacDirectiveArgs, index_validateBillingAmount as validateBillingAmount, index_validateName as validateName, index_validateUserFields as validateUserFields, index_validateUsername as validateUsername };
|
|
153
176
|
}
|
|
154
177
|
|
|
155
|
-
export { type
|
|
178
|
+
export { type RbacSchemaDocument as A, type BillingAmountErrorCode as B, type RbacScopeType as C, DEFAULT_MAX_RBAC_ARG_PATH_SEGMENTS as D, type SupportedBillingCurrency as E, isSupportedBillingCurrency as F, loadRbacSchemaDocuments as G, rbacArgPathProblem as H, readRbacDirectiveArgs as I, validateBillingAmount as J, MAX_BILLING_AMOUNT as M, NAME_MAX_LENGTH as N, RbacCoverageError as R, SUPPORTED_BILLING_CURRENCIES as S, USERNAME_MAX_LENGTH as U, type ValidatedUserFields as V, NAME_MIN_LENGTH as a, type NameErrorCode as b, type NameValidationResult as c, type RbacCoverageOptions as d, type RbacCoverageReport as e, type RbacCoverageSource as f, USERNAME_MIN_LENGTH as g, type UserFieldError as h, type UserFieldKey as i, type UserFieldsValidationResult as j, type UsernameErrorCode as k, type UsernameValidationResult as l, index as m, analyzeRbacCoverage as n, assertRbacCoverage as o, lengthInCodePoints as p, validateUserFields as q, validateUsername as r, type BillingAmountValidationResult as s, DEFAULT_RBAC_ROOT_TYPES as t, RBAC_GATED_SCOPE_TYPES as u, validateName as v, RBAC_SCOPE_TYPES as w, type RbacDirectiveArgs as x, type RbacFieldPin as y, type RbacRootField as z };
|