@cipherstash/stack 0.18.0 → 1.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/CHANGELOG.md +704 -0
  2. package/README.md +97 -79
  3. package/dist/adapter-kit.cjs +923 -0
  4. package/dist/adapter-kit.cjs.map +1 -0
  5. package/dist/adapter-kit.d.cts +82 -0
  6. package/dist/adapter-kit.d.ts +82 -0
  7. package/dist/adapter-kit.js +47 -0
  8. package/dist/adapter-kit.js.map +1 -0
  9. package/dist/base-operation-AOAIvsSB.d.cts +32 -0
  10. package/dist/base-operation-FXEzUXIq.d.ts +32 -0
  11. package/dist/{chunk-VPOTNP4K.js → chunk-3B5ZX3IS.js} +3 -1
  12. package/dist/chunk-3B5ZX3IS.js.map +1 -0
  13. package/dist/chunk-7333ZC6L.js +48 -0
  14. package/dist/chunk-7333ZC6L.js.map +1 -0
  15. package/dist/{chunk-XWPGAHBZ.js → chunk-BNO32ZMV.js} +1 -1
  16. package/dist/chunk-BNO32ZMV.js.map +1 -0
  17. package/dist/chunk-CLM7E4I6.js +4439 -0
  18. package/dist/chunk-CLM7E4I6.js.map +1 -0
  19. package/dist/{chunk-LLCCNKDL.js → chunk-HQANMV7R.js} +3 -3
  20. package/dist/{chunk-LLCCNKDL.js.map → chunk-HQANMV7R.js.map} +1 -1
  21. package/dist/chunk-JSG2AMDI.js +17 -0
  22. package/dist/chunk-JSG2AMDI.js.map +1 -0
  23. package/dist/chunk-OFQ555AX.js +191 -0
  24. package/dist/chunk-OFQ555AX.js.map +1 -0
  25. package/dist/chunk-PZ5AY32C.js +10 -0
  26. package/dist/chunk-PZ5AY32C.js.map +1 -0
  27. package/dist/chunk-V2Q3NYIH.js +494 -0
  28. package/dist/chunk-V2Q3NYIH.js.map +1 -0
  29. package/dist/chunk-X3JRXEIB.js +98 -0
  30. package/dist/chunk-X3JRXEIB.js.map +1 -0
  31. package/dist/{chunk-ZYOZHZMJ.js → chunk-ZTP5QJ27.js} +193 -169
  32. package/dist/chunk-ZTP5QJ27.js.map +1 -0
  33. package/dist/client.cjs +4124 -49
  34. package/dist/client.cjs.map +1 -1
  35. package/dist/client.d.cts +6 -5
  36. package/dist/client.d.ts +6 -5
  37. package/dist/client.js +3 -1
  38. package/dist/columns-D2_YzrCX.d.cts +622 -0
  39. package/dist/columns-rZc7fQHI.d.ts +622 -0
  40. package/dist/dynamodb/index.cjs +19 -12
  41. package/dist/dynamodb/index.cjs.map +1 -1
  42. package/dist/dynamodb/index.d.cts +3 -2
  43. package/dist/dynamodb/index.d.ts +3 -2
  44. package/dist/dynamodb/index.js +8 -10
  45. package/dist/dynamodb/index.js.map +1 -1
  46. package/dist/encryption/index.cjs +4496 -222
  47. package/dist/encryption/index.cjs.map +1 -1
  48. package/dist/encryption/index.d.cts +807 -6
  49. package/dist/encryption/index.d.ts +807 -6
  50. package/dist/encryption/index.js +15 -7
  51. package/dist/encryption/v3.cjs +7896 -0
  52. package/dist/encryption/v3.cjs.map +1 -0
  53. package/dist/encryption/v3.d.cts +103 -0
  54. package/dist/encryption/v3.d.ts +103 -0
  55. package/dist/encryption/v3.js +189 -0
  56. package/dist/encryption/v3.js.map +1 -0
  57. package/dist/eql/v3/index.cjs +663 -0
  58. package/dist/eql/v3/index.cjs.map +1 -0
  59. package/dist/eql/v3/index.d.cts +173 -0
  60. package/dist/eql/v3/index.d.ts +173 -0
  61. package/dist/eql/v3/index.js +99 -0
  62. package/dist/eql/v3/index.js.map +1 -0
  63. package/dist/errors/index.js +1 -0
  64. package/dist/identity/index.cjs +55 -35
  65. package/dist/identity/index.cjs.map +1 -1
  66. package/dist/identity/index.d.cts +54 -30
  67. package/dist/identity/index.d.ts +54 -30
  68. package/dist/identity/index.js +9 -177
  69. package/dist/identity/index.js.map +1 -1
  70. package/dist/index-BquA71_Y.d.ts +24 -0
  71. package/dist/index-fhWTOV0K.d.cts +24 -0
  72. package/dist/index.cjs +4547 -243
  73. package/dist/index.cjs.map +1 -1
  74. package/dist/index.d.cts +18 -19
  75. package/dist/index.d.ts +18 -19
  76. package/dist/index.js +20 -5
  77. package/dist/index.js.map +1 -1
  78. package/dist/schema/index.cjs +4128 -49
  79. package/dist/schema/index.cjs.map +1 -1
  80. package/dist/schema/index.d.cts +1 -1
  81. package/dist/schema/index.d.ts +1 -1
  82. package/dist/schema/index.js +3 -1
  83. package/dist/{types-public-BTxqjmtv.d.cts → types-public-QMjYNfQO.d.cts} +448 -251
  84. package/dist/{types-public-BTxqjmtv.d.ts → types-public-QMjYNfQO.d.ts} +448 -251
  85. package/dist/types-public.cjs.map +1 -1
  86. package/dist/types-public.d.cts +2 -2
  87. package/dist/types-public.d.ts +2 -2
  88. package/dist/types-public.js +2 -1
  89. package/dist/wasm-inline.d.ts +1643 -0
  90. package/dist/wasm-inline.js +4901 -0
  91. package/dist/wasm-inline.js.map +1 -0
  92. package/package.json +74 -52
  93. package/dist/chunk-VPOTNP4K.js.map +0 -1
  94. package/dist/chunk-XWPGAHBZ.js.map +0 -1
  95. package/dist/chunk-YWQXTZ5M.js +0 -383
  96. package/dist/chunk-YWQXTZ5M.js.map +0 -1
  97. package/dist/chunk-ZYOZHZMJ.js.map +0 -1
  98. package/dist/client-CIsfZ2zg.d.ts +0 -692
  99. package/dist/client-Dt98Rugc.d.cts +0 -692
  100. package/dist/drizzle/index.cjs +0 -1558
  101. package/dist/drizzle/index.cjs.map +0 -1
  102. package/dist/drizzle/index.d.cts +0 -358
  103. package/dist/drizzle/index.d.ts +0 -358
  104. package/dist/drizzle/index.js +0 -1215
  105. package/dist/drizzle/index.js.map +0 -1
  106. package/dist/supabase/index.cjs +0 -1526
  107. package/dist/supabase/index.cjs.map +0 -1
  108. package/dist/supabase/index.d.cts +0 -144
  109. package/dist/supabase/index.d.ts +0 -144
  110. package/dist/supabase/index.js +0 -899
  111. package/dist/supabase/index.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/encryption/v3.ts","../../src/schema/match-defaults.ts","../../src/eql/v3/columns.ts","../../src/errors/index.ts","../../../../node_modules/.pnpm/@byteslice+result@0.2.0/node_modules/@byteslice/result/dist/result.mjs","../../src/encryption/index.ts","../../../../node_modules/.pnpm/uuid@14.0.0/node_modules/uuid/dist-node/regex.js","../../../../node_modules/.pnpm/uuid@14.0.0/node_modules/uuid/dist-node/validate.js","../../../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js","../../../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js","../../../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js","../../../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/locales/en.js","../../../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js","../../../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js","../../../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js","../../../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js","../../src/schema/index.ts","../../../../node_modules/.pnpm/evlog@1.11.0_next@15.5.18_react-dom@19.2.3_react@19.2.3__react@19.2.3__react@19.2.3/node_modules/evlog/src/utils.ts","../../../../node_modules/.pnpm/evlog@1.11.0_next@15.5.18_react-dom@19.2.3_react@19.2.3__react@19.2.3__react@19.2.3/node_modules/evlog/src/logger.ts","../../src/utils/logger/index.ts","../../src/encryption/helpers/index.ts","../../src/encryption/helpers/type-guards.ts","../../src/encryption/operations/batch-encrypt-query.ts","../../src/encryption/helpers/error-code.ts","../../src/utils/config/index.ts","../../src/identity/index.ts","../../src/types.ts","../../src/encryption/helpers/infer-index-type.ts","../../src/encryption/helpers/validation.ts","../../src/encryption/operations/base-operation.ts","../../src/encryption/operations/bulk-decrypt.ts","../../src/encryption/helpers/model-helpers.ts","../../src/encryption/operations/bulk-decrypt-models.ts","../../src/encryption/operations/bulk-encrypt.ts","../../src/encryption/operations/bulk-encrypt-models.ts","../../src/encryption/operations/decrypt.ts","../../src/encryption/operations/decrypt-model.ts","../../src/encryption/operations/encrypt.ts","../../src/encryption/operations/encrypt-model.ts","../../src/encryption/operations/encrypt-query.ts","../../src/eql/v3/table.ts","../../src/eql/v3/types.ts"],"sourcesContent":["import type { Result } from '@byteslice/result'\nimport type {\n AnyV3Table,\n ColumnsOf,\n PlaintextForColumn,\n QueryableColumnsOf,\n QueryTypesForColumn,\n V3DecryptedModel,\n V3EncryptedModel,\n V3ModelInput,\n} from '@/eql/v3'\nimport { DATE_LIKE_CASTS } from '@/eql/v3/columns'\nimport { type EncryptionError, EncryptionErrorTypes } from '@/errors'\nimport type { LockContextInput } from '@/identity'\nimport type {\n BulkDecryptPayload,\n BulkEncryptPayload,\n ClientConfig,\n Encrypted,\n EncryptedReturnType,\n EncryptOptions,\n ScalarQueryTerm,\n} from '@/types'\nimport {\n type BatchEncryptQueryOperation,\n type BulkDecryptOperation,\n type BulkEncryptModelsOperation,\n type BulkEncryptOperation,\n type DecryptOperation,\n Encryption,\n type EncryptionClient,\n type EncryptModelOperation,\n type EncryptOperation,\n type EncryptQueryOperation,\n} from './index'\n\n/**\n * A strongly-typed view over an {@link EncryptionClient} for EQL v3 schemas.\n *\n * Every method derives its types from the concrete `table` / `column` builder\n * arguments (which carry their branded types at the call site), so:\n * - `encrypt` / `encryptQuery` pin the plaintext to the column's domain type\n * (`text → string`, `timestamp → Date`, …);\n * - `encryptQuery` additionally constrains `queryType` to the column's\n * capabilities and rejects storage-only columns outright;\n * - `encryptModel` / `bulkEncryptModels` validate schema-column fields against\n * their inferred plaintext type (passthrough fields are untouched) and return\n * a precise encrypted model;\n * - `decryptModel` / `bulkDecryptModels` return the precise plaintext model,\n * reconstructing `Date` values from the encrypt-config `cast_as`.\n *\n * @typeParam S - the tuple of registered v3 tables; `table` arguments must be a\n * member of this tuple.\n */\nexport interface TypedEncryptionClient<S extends readonly AnyV3Table[]> {\n encrypt<Table extends S[number], Col extends ColumnsOf<Table>>(\n plaintext: PlaintextForColumn<Col>,\n opts: { table: Table; column: Col },\n ): EncryptOperation\n\n encryptQuery<\n Table extends S[number],\n Col extends QueryableColumnsOf<Table>,\n QT extends QueryTypesForColumn<Col> = QueryTypesForColumn<Col>,\n >(\n plaintext: PlaintextForColumn<Col>,\n opts: {\n table: Table\n column: Col\n queryType?: QT\n returnType?: EncryptedReturnType\n },\n ): EncryptQueryOperation\n\n /**\n * Batch form: encrypt many query terms in one crossing. Mirrors the nominal\n * {@link EncryptionClient} overload — the per-term columns are heterogeneous,\n * so the terms are the base {@link ScalarQueryTerm} rather than a per-column\n * narrowed type. Consumed by the Drizzle `inArray`/`notInArray` operators.\n */\n encryptQuery(terms: readonly ScalarQueryTerm[]): BatchEncryptQueryOperation\n\n encryptModel<Table extends S[number], T extends Record<string, unknown>>(\n input: V3ModelInput<Table, T>,\n table: Table,\n ): EncryptModelOperation<V3EncryptedModel<Table, T>>\n\n bulkEncryptModels<Table extends S[number], T extends Record<string, unknown>>(\n input: Array<V3ModelInput<Table, T>>,\n table: Table,\n ): BulkEncryptModelsOperation<V3EncryptedModel<Table, T>>\n\n /**\n * Decrypt a single value. Cannot be strongly typed — a lone ciphertext carries\n * no column identity — so it resolves to the FFI plaintext union unchanged.\n */\n decrypt(encrypted: Encrypted): DecryptOperation\n\n /**\n * Decrypt a model, returning the precise plaintext shape for `table`. `Date`\n * columns are reconstructed from the encrypt-config `cast_as`.\n *\n * Pass `lockContext` to decrypt identity-bound data — the same context that\n * was supplied at encrypt time must be provided here.\n *\n * Unlike the encrypt operations this returns a plain `Promise<Result<…>>`\n * rather than a chainable operation, because it maps the resolved value.\n */\n decryptModel<Table extends S[number], T extends Record<string, unknown>>(\n input: T,\n table: Table,\n lockContext?: LockContextInput,\n ): Promise<Result<V3DecryptedModel<Table, T>, EncryptionError>>\n\n bulkDecryptModels<Table extends S[number], T extends Record<string, unknown>>(\n input: Array<T>,\n table: Table,\n lockContext?: LockContextInput,\n ): Promise<Result<Array<V3DecryptedModel<Table, T>>, EncryptionError>>\n\n // Parity passthroughs — not v3-strengthened, delegated as-is.\n bulkEncrypt(\n plaintexts: BulkEncryptPayload,\n opts: EncryptOptions,\n ): BulkEncryptOperation\n bulkDecrypt(payloads: BulkDecryptPayload): BulkDecryptOperation\n getEncryptConfig(): ReturnType<EncryptionClient['getEncryptConfig']>\n}\n\n/**\n * Build a per-row reconstructor of `Date` values from the table's\n * encrypt-config `cast_as`. The FFI returns `JsPlaintext`\n * (string/number/boolean/…) with no `Date`, so those columns arrive as their\n * serialized form and are rebuilt here. Safe (idempotent) if the FFI ever\n * returns `Date` directly: `new Date(date)` is a no-op.\n *\n * A factory rather than a `(row, table)` function so the table config —\n * row-invariant, but non-trivial to build — is derived once per call site,\n * not once per row on the bulk path.\n *\n * NOTE: only date-like casts need per-row reconstruction. `bigint` (int8)\n * needs none — protect-ffi 0.28 returns a native JS `bigint` on decrypt\n * (and bounds-checks/encodes it on encrypt), so those columns pass through\n * unchanged, exactly like `string`/`number`/`boolean`.\n */\nfunction rowReconstructor(\n table: AnyV3Table,\n): (row: Record<string, unknown>) => Record<string, unknown> {\n // The decrypted row is keyed by JS property name, but `cast_as` lives on the\n // config keyed by DB name — bridge the two via the table's property→DB map.\n const { columns } = table.build()\n const propToDb = table.buildColumnKeyMap()\n // Only date-like columns need per-row work; resolve them up front.\n const dateProperties = Object.entries(propToDb)\n .filter(([, dbName]) => {\n const castAs = columns[dbName]?.cast_as\n // Date-like casts share one source of truth with the type-level\n // reconstruction (`PlaintextFromKind`) — see `DATE_LIKE_CASTS`.\n return (DATE_LIKE_CASTS as readonly string[]).includes(castAs as string)\n })\n .map(([property]) => property)\n\n return (row) => {\n const out: Record<string, unknown> = { ...row }\n for (const property of dateProperties) {\n const value = out[property]\n if (value == null) continue\n out[property] = new Date(value as string | number | Date)\n }\n return out\n }\n}\n\n/**\n * Wrap an already-built {@link EncryptionClient} in a {@link TypedEncryptionClient}\n * for the given v3 schemas. Zero runtime cost for the encrypt/query paths (the\n * underlying operations are returned unchanged); the decrypt-model paths add a\n * per-column `Date` reconstruction step.\n *\n * The `schemas` are captured with a `const` type parameter so array-literal\n * widening does not collapse per-table inference.\n */\nexport function typedClient<const S extends readonly AnyV3Table[]>(\n client: EncryptionClient,\n ...schemas: S\n): TypedEncryptionClient<S> {\n // Precompute one row reconstructor per schema table at construction. This runs\n // each table's `build()` — which throws on duplicate DB column names — ONCE,\n // here, off the Result-returning decrypt path. `decryptModel`/\n // `bulkDecryptModels` therefore never call `build()` (whose throw would surface\n // as a promise rejection and break their `Promise<Result<…>>` contract) and no\n // longer rebuild the row-invariant config on every call.\n // Keyed by `tableName`, not table object identity: `AnyV3Table` is\n // structurally typed, so a table re-imported from another module (or rebuilt\n // after an HMR reload) satisfies `Table extends S[number]` yet is a different\n // object. Identity keying would fail those valid calls. `tableName` is the\n // semantic identity the FFI encrypt config and `build()` already key on.\n const reconstructors = new Map<\n string,\n (row: Record<string, unknown>) => Record<string, unknown>\n >()\n for (const table of schemas) {\n reconstructors.set(table.tableName, rowReconstructor(table))\n }\n\n // A table not among the schemas this client was initialized with has no\n // precomputed reconstructor. Return a Result failure rather than building one\n // inline, which could throw and reject the Result-shaped decrypt promise.\n const unknownTableFailure: { failure: EncryptionError } = {\n failure: {\n type: EncryptionErrorTypes.DecryptionError,\n message:\n '[eql/v3]: decryptModel received a table this client was not initialized with — pass a table given to EncryptionV3/typedClient',\n },\n }\n\n // Overloaded so the implementation is checked against BOTH forms directly —\n // no whole-value cast. The two public signatures mirror the interface member;\n // the hidden implementation signature is broad and forwards to the nominal\n // client (which routes to the batch operation when no `opts` are supplied).\n // Only the forwarded args are `as never`, exactly as the sibling wrappers\n // below: one forwarding body cannot re-derive the nominal client's per-column\n // signatures.\n function encryptQuery<\n Table extends S[number],\n Col extends QueryableColumnsOf<Table>,\n QT extends QueryTypesForColumn<Col> = QueryTypesForColumn<Col>,\n >(\n plaintext: PlaintextForColumn<Col>,\n opts: {\n table: Table\n column: Col\n queryType?: QT\n returnType?: EncryptedReturnType\n },\n ): EncryptQueryOperation\n function encryptQuery(\n terms: readonly ScalarQueryTerm[],\n ): BatchEncryptQueryOperation\n function encryptQuery(\n plaintextOrTerms: unknown,\n opts?: unknown,\n ): EncryptQueryOperation | BatchEncryptQueryOperation {\n return client.encryptQuery(plaintextOrTerms as never, opts as never)\n }\n\n return {\n encrypt: (plaintext, opts) =>\n client.encrypt(plaintext as never, opts as never),\n encryptQuery,\n encryptModel: (input, table) =>\n client.encryptModel(input as never, table as never) as never,\n bulkEncryptModels: (input, table) =>\n client.bulkEncryptModels(input as never, table as never) as never,\n decrypt: (encrypted) => client.decrypt(encrypted),\n decryptModel: async (input, table, lockContext) => {\n const reconstruct = reconstructors.get(table.tableName)\n if (!reconstruct) return unknownTableFailure as never\n const op = client.decryptModel(input as never)\n const result = await (lockContext ? op.withLockContext(lockContext) : op)\n if (result.failure) return result as never\n return { data: reconstruct(result.data) } as never\n },\n bulkDecryptModels: async (input, table, lockContext) => {\n const reconstruct = reconstructors.get(table.tableName)\n if (!reconstruct) return unknownTableFailure as never\n const op = client.bulkDecryptModels(input as never)\n const result = await (lockContext ? op.withLockContext(lockContext) : op)\n if (result.failure) return result as never\n return {\n data: result.data.map((row) =>\n reconstruct(row as Record<string, unknown>),\n ),\n } as never\n },\n bulkEncrypt: (plaintexts, opts) => client.bulkEncrypt(plaintexts, opts),\n bulkDecrypt: (payloads) => client.bulkDecrypt(payloads),\n getEncryptConfig: () => client.getEncryptConfig(),\n } satisfies TypedEncryptionClient<S>\n}\n\n/**\n * Build a {@link TypedEncryptionClient} for EQL v3 schemas — the strongly-typed\n * counterpart to {@link Encryption}. Mirrors its config, then retypes the client\n * against the provided v3 `schemas`.\n *\n * @example\n * ```typescript\n * import { EncryptionV3, encryptedTable, types } from \"@cipherstash/stack/v3\"\n *\n * const users = encryptedTable(\"users\", { email: types.TextSearch(\"email\") })\n * const client = await EncryptionV3({ schemas: [users] })\n *\n * await client.encrypt(\"a@b.com\", { table: users, column: users.email })\n * ```\n */\nexport async function EncryptionV3<\n const S extends readonly AnyV3Table[],\n>(config: {\n schemas: S\n config?: ClientConfig\n}): Promise<TypedEncryptionClient<S>> {\n const client = await Encryption({\n schemas: config.schemas as unknown as Parameters<\n typeof Encryption\n >[0]['schemas'],\n // Force the v3 EQL wire format. protect-ffi's newClient defaults to\n // eqlVersion 2; a v2-mode client cannot resolve v3 concrete-type columns\n // and fails every encrypt with \"Cannot convert undefined or null to\n // object\". This is a v3-only invariant, so it overrides any user value.\n config: { ...config.config, eqlVersion: 3 },\n })\n return typedClient(client, ...config.schemas)\n}\n\n// Single import surface: re-export the v3 `types` namespace + table API + type\n// helpers so `@cipherstash/stack/v3` provides everything needed to author and\n// use a schema.\nexport * from '@/eql/v3'\n","import type { MatchIndexOpts } from './index'\n\n/**\n * Fully-resolved match-index options: every field present and non-`undefined`.\n *\n * `MatchIndexOpts` (the user-facing tuning input) has all fields optional —\n * each is `.default(...).optional()` in the zod schema, so its inferred type is\n * `T | undefined`. This type pins the BUILT/resolved shape explicitly via\n * `NonNullable<...>`, which states the non-null intent directly and is robust\n * regardless of `Required<>`'s subtle, `exactOptionalPropertyTypes`-dependent\n * stripping semantics.\n */\nexport type BuiltMatchIndexOpts = {\n tokenizer: NonNullable<MatchIndexOpts['tokenizer']>\n token_filters: NonNullable<MatchIndexOpts['token_filters']>\n k: NonNullable<MatchIndexOpts['k']>\n m: NonNullable<MatchIndexOpts['m']>\n include_original: NonNullable<MatchIndexOpts['include_original']>\n}\n\n/**\n * Default match-index parameters — the single source of truth shared by the\n * v2 `freeTextSearch()` builder and the v3 domain builders.\n *\n * `include_original: true` is the v2 builder's historical default rather than\n * the zod-schema default of `false`. It is INERT: protect-ffi accepts the flag\n * and ignores it (measured across 0.24 and 0.29, EQL v2 and v3 — the emitted\n * bloom is trigram-only either way). It is kept here only so the v2 emitted\n * config does not move. The v3 domain builders override it to `false`, the\n * value a substring-search domain wants if ffi ever starts honouring it.\n *\n * In particular it does NOT let a value shorter than the tokenizer's\n * `token_length` be matched: such a value blooms to nothing under either\n * setting, which is exactly the fail-open {@link matchNeedleError} guards.\n *\n * This is a FACTORY (not a shared `const`) so every caller gets fresh, unaliased\n * nested objects (`tokenizer`, `token_filters` and the `{ kind: 'downcase' }`\n * inside it). A shared const would be shallow-copied by `{ ...DEFAULT }`, leaving\n * those nested objects aliased across every column — a caller mutating one built\n * config could then corrupt the defaults used by later columns.\n */\nexport function defaultMatchOpts(): BuiltMatchIndexOpts {\n return {\n tokenizer: { kind: 'ngram', token_length: 3 },\n token_filters: [{ kind: 'downcase' }],\n k: 6,\n m: 2048,\n include_original: true,\n }\n}\n\n/**\n * Deep-clone a built match block (`tokenizer` and `token_filters` are its only\n * nested values) so no emitted config or stored builder state ever aliases\n * another's nested objects — a caller mutating one cannot corrupt the other.\n */\nexport function cloneMatchOpts(opts: BuiltMatchIndexOpts): BuiltMatchIndexOpts {\n return {\n ...opts,\n tokenizer: { ...opts.tokenizer },\n token_filters: opts.token_filters.map((f) => ({ ...f })),\n }\n}\n\n/**\n * Resolve user-supplied `freeTextSearch(opts)` input into a fully-built match\n * block: each provided key replaces its default, omitted keys keep the default\n * (`opts?.x ?? default.x`). The single source of truth for that five-field merge\n * shared by the v2 `freeTextSearch()` builder and the v3 domain builders.\n *\n * The result is deep-cloned ({@link cloneMatchOpts}) so a caller mutating their\n * own `opts` object (or its nested `tokenizer`/`token_filters`) after this call\n * can never leak into the stored builder state or the emitted config — clone-on-\n * write for both builders, not just v3.\n */\nexport function resolveMatchOpts(opts?: MatchIndexOpts): BuiltMatchIndexOpts {\n const defaults = defaultMatchOpts()\n return cloneMatchOpts({\n tokenizer: opts?.tokenizer ?? defaults.tokenizer,\n token_filters: opts?.token_filters ?? defaults.token_filters,\n k: opts?.k ?? defaults.k,\n m: opts?.m ?? defaults.m,\n include_original: opts?.include_original ?? defaults.include_original,\n })\n}\n\n/**\n * The shortest needle a match index can answer, or `undefined` when its\n * tokenizer imposes no floor (`standard` splits on word boundaries, so any\n * non-empty needle yields at least one token).\n *\n * Accepts the loose {@link MatchIndexOpts} because a `ColumnSchema`'s built\n * `indexes.match` is typed from the zod schema, where `tokenizer` is optional.\n * An absent tokenizer resolves to the same default the schema itself applies\n * (`ngram`, `token_length: 3`) rather than skipping the floor — skipping would\n * reintroduce the fail-open this guard exists to close.\n */\nexport function matchNeedleMinLength(opts: MatchIndexOpts): number | undefined {\n const tokenizer = opts.tokenizer ?? defaultMatchOpts().tokenizer\n return tokenizer.kind === 'ngram' ? tokenizer.token_length : undefined\n}\n\n/**\n * Why a needle cannot be answered by this match index, or `undefined` when it\n * can. Callers throw their own error type with this as the reason.\n *\n * A needle that tokenizes to NOTHING has an empty bloom filter, and\n * `stored_bf @> '{}'` is true for every row (\"contains nothing, contained by\n * everything\"). Such a query is unanswerable rather than merely unmatched, so\n * it must fail loudly instead of silently returning the whole table. Two ways\n * to tokenize to nothing:\n *\n * - the empty needle, under ANY tokenizer;\n * - a needle shorter than the ngram tokenizer's `token_length`.\n *\n * The ngram floor counts Unicode CODEPOINTS, because that is what the tokenizer\n * counts. `needle.length` would count UTF-16 code units and wave through an\n * astral-plane needle: `'👍👍'` is 4 code units but only 2 codepoints, yields no\n * trigram, and (measured live) matched every row. Graphemes are the wrong unit\n * in the other direction — NFD `'éé'` is 4 codepoints but 2 grapheme clusters,\n * and does yield trigrams.\n *\n * Currently wired ONLY into the v3 Drizzle adapter (`eql/v3/drizzle/operators`).\n * It lives here, beside the shared match defaults, because v2 builds the same\n * bloom filters and needs the same floor — but v2's `like`/`ilike` path remains\n * unguarded and still fails open. Do not reuse this for v2 without first\n * measuring what its tokenizer actually receives: v2 needles carry SQL wildcards\n * (`'%ada%'`), so the floor may have to apply to the unwrapped term rather than\n * to the string the caller passed.\n */\nexport function matchNeedleError(\n needle: unknown,\n opts: MatchIndexOpts,\n): string | undefined {\n if (typeof needle !== 'string') return undefined\n\n // Codepoints, not UTF-16 code units — see above.\n const length = [...needle].length\n const min = matchNeedleMinLength(opts)\n\n if (length === 0) {\n return `free-text search needs a non-empty search term; an empty term produces no tokens and would match every row.`\n }\n if (min === undefined || length >= min) return undefined\n return `free-text search needs at least ${min} characters (the index tokenizer's token_length), but the search term ${JSON.stringify(needle)} has ${length}. A shorter term produces no tokens and would match every row.`\n}\n","import type { ColumnSchema } from '@/schema'\nimport { defaultMatchOpts } from '@/schema/match-defaults'\n\n/**\n * The query capabilities a v3 concrete domain exposes. These are SDK-facing\n * semantic flags describing what kinds of query terms a column can produce —\n * NOT the raw EQL index keys. They are metadata only and never emitted by\n * `build()`.\n *\n * - `equality`: exact-match lookups (EQL `hm`, or comparison via `ob`).\n * - `orderAndRange`: comparison / range lookups (EQL `op`, or `ob` on `_ord_ore` domains).\n * - `freeTextSearch`: tokenised substring match (EQL `bf`).\n * - `searchableJson`: encrypted-JSONB containment / selector lookups (EQL\n * `ste_vec`). Optional and mutually exclusive with the scalar flags — a\n * `public.eql_v3_json` document is queried by structure, not by scalar term.\n */\nexport type QueryCapabilities = Readonly<{\n equality: boolean\n orderAndRange: boolean\n freeTextSearch: boolean\n searchableJson?: boolean\n}>\n\n/**\n * The `cast_as` kinds whose decrypted plaintext reconstructs to a JS `Date`.\n *\n * SINGLE SOURCE OF TRUTH for the date-like set. Both the type-level\n * {@link PlaintextFromKind} and the runtime `rowReconstructor` (encryption/v3.ts)\n * derive their \"reconstructs to `Date`\" decision from this array, so the next\n * `Date`-backed cast is added in exactly one place — never hand-synced across a\n * type and a runtime guard that could silently drift.\n *\n * (`timestamp` reconstructs to `Date` just like `date`, but its `cast_as` tells\n * the FFI not to truncate the time-of-day.)\n */\nexport const DATE_LIKE_CASTS = ['date', 'timestamp'] as const\n/** A `cast_as` kind that reconstructs to `Date` — see {@link DATE_LIKE_CASTS}. */\nexport type DateLikeCast = (typeof DATE_LIKE_CASTS)[number]\n\n/** The plaintext (TypeScript) kind a v3 domain decrypts to. A subset of the\n * SDK `CastAs` enum, restricted to the scalar kinds v3 domains actually use. */\ntype PlaintextKind =\n | 'string'\n | 'number'\n | 'bigint'\n | 'boolean'\n | 'json'\n | DateLikeCast\n\n/**\n * The full, literal definition of a v3 domain. This is the LOAD-BEARING type:\n * the base column class carries a private field of this type so that every\n * concrete (otherwise-empty) subclass is discriminated by its literal\n * `eqlType`/`castAs`/`capabilities` — TypeScript empty subclasses are NOT\n * nominal, so without this a storage-only `boolean` column would be assignable to\n * a storage-only `date` column and plaintext inference would collapse.\n */\ntype V3DomainDefinition = Readonly<{\n eqlType: `public.${string}`\n castAs: PlaintextKind\n capabilities: QueryCapabilities\n}>\n\n/** Type-level mirror of {@link isQueryableCapabilities}: `false` for a\n * storage-only domain (all capability flags `false`), `true` otherwise. */\ntype QueryableFlag<D extends V3DomainDefinition> = D['capabilities'] extends {\n equality: false\n orderAndRange: false\n freeTextSearch: false\n searchableJson?: false | undefined\n}\n ? false\n : true\n\nconst STORAGE_ONLY = {\n equality: false,\n orderAndRange: false,\n freeTextSearch: false,\n} as const\n\nconst EQUALITY_ONLY = {\n equality: true,\n orderAndRange: false,\n freeTextSearch: false,\n} as const\n\nconst ORDER_AND_RANGE = {\n equality: true,\n orderAndRange: true,\n freeTextSearch: false,\n} as const\n\nconst MATCH_ONLY = {\n equality: false,\n orderAndRange: false,\n freeTextSearch: true,\n} as const\n\nconst TEXT_SEARCH = {\n equality: true,\n orderAndRange: true,\n freeTextSearch: true,\n} as const\n\n/**\n * The concrete EQL v3 domain name for a full-capability text column.\n * Recorded as metadata for future DDL / query-dialect increments; it is\n * intentionally absent from the emitted encrypt config.\n */\nexport const TEXT_SEARCH_EQL_TYPE = 'public.eql_v3_text_search'\n\n// Per-domain literal definitions. Each concrete column subclass is parameterised\n// by `typeof <CONST>`; the literal `eqlType`/`castAs`/`capabilities` on each is\n// what makes the otherwise-empty subclasses nominally distinct (see\n// V3DomainDefinition). Order mirrors eql-bindings `CATALOG` order.\n//\n// Exported for the `types` namespace factory (see ./types); they are internal\n// building blocks and are intentionally NOT re-exported from the public barrel.\nexport const INTEGER = {\n eqlType: 'public.eql_v3_integer',\n castAs: 'number',\n capabilities: STORAGE_ONLY,\n} as const\nexport const INTEGER_EQ = {\n eqlType: 'public.eql_v3_integer_eq',\n castAs: 'number',\n capabilities: EQUALITY_ONLY,\n} as const\nexport const INTEGER_ORD_ORE = {\n eqlType: 'public.eql_v3_integer_ord_ore',\n castAs: 'number',\n capabilities: ORDER_AND_RANGE,\n} as const\nexport const INTEGER_ORD = {\n eqlType: 'public.eql_v3_integer_ord',\n castAs: 'number',\n capabilities: ORDER_AND_RANGE,\n} as const\n\nexport const SMALLINT = {\n eqlType: 'public.eql_v3_smallint',\n castAs: 'number',\n capabilities: STORAGE_ONLY,\n} as const\nexport const SMALLINT_EQ = {\n eqlType: 'public.eql_v3_smallint_eq',\n castAs: 'number',\n capabilities: EQUALITY_ONLY,\n} as const\nexport const SMALLINT_ORD_ORE = {\n eqlType: 'public.eql_v3_smallint_ord_ore',\n castAs: 'number',\n capabilities: ORDER_AND_RANGE,\n} as const\nexport const SMALLINT_ORD = {\n eqlType: 'public.eql_v3_smallint_ord',\n castAs: 'number',\n capabilities: ORDER_AND_RANGE,\n} as const\n\n// bigint (int8) domains. Plaintext is a JS `bigint` (always decrypts to\n// `bigint`); bounds are the full i64 range. protect-ffi round-trips an in-range\n// native bigint losslessly, and values outside the signed 64-bit range are\n// rejected client-side by `assertValidNumericValue` before they reach the FFI\n// (`*_ord_ope` variants are out of scope — CIP-3403.)\nexport const BIGINT = {\n eqlType: 'public.eql_v3_bigint',\n castAs: 'bigint',\n capabilities: STORAGE_ONLY,\n} as const\nexport const BIGINT_EQ = {\n eqlType: 'public.eql_v3_bigint_eq',\n castAs: 'bigint',\n capabilities: EQUALITY_ONLY,\n} as const\nexport const BIGINT_ORD_ORE = {\n eqlType: 'public.eql_v3_bigint_ord_ore',\n castAs: 'bigint',\n capabilities: ORDER_AND_RANGE,\n} as const\nexport const BIGINT_ORD = {\n eqlType: 'public.eql_v3_bigint_ord',\n castAs: 'bigint',\n capabilities: ORDER_AND_RANGE,\n} as const\n\nexport const DATE = {\n eqlType: 'public.eql_v3_date',\n castAs: 'date',\n capabilities: STORAGE_ONLY,\n} as const\nexport const DATE_EQ = {\n eqlType: 'public.eql_v3_date_eq',\n castAs: 'date',\n capabilities: EQUALITY_ONLY,\n} as const\nexport const DATE_ORD_ORE = {\n eqlType: 'public.eql_v3_date_ord_ore',\n castAs: 'date',\n capabilities: ORDER_AND_RANGE,\n} as const\nexport const DATE_ORD = {\n eqlType: 'public.eql_v3_date_ord',\n castAs: 'date',\n capabilities: ORDER_AND_RANGE,\n} as const\n\nexport const TIMESTAMP = {\n eqlType: 'public.eql_v3_timestamp',\n castAs: 'timestamp',\n capabilities: STORAGE_ONLY,\n} as const\nexport const TIMESTAMP_EQ = {\n eqlType: 'public.eql_v3_timestamp_eq',\n castAs: 'timestamp',\n capabilities: EQUALITY_ONLY,\n} as const\nexport const TIMESTAMP_ORD_ORE = {\n eqlType: 'public.eql_v3_timestamp_ord_ore',\n castAs: 'timestamp',\n capabilities: ORDER_AND_RANGE,\n} as const\nexport const TIMESTAMP_ORD = {\n eqlType: 'public.eql_v3_timestamp_ord',\n castAs: 'timestamp',\n capabilities: ORDER_AND_RANGE,\n} as const\n\nexport const NUMERIC = {\n eqlType: 'public.eql_v3_numeric',\n castAs: 'number',\n capabilities: STORAGE_ONLY,\n} as const\nexport const NUMERIC_EQ = {\n eqlType: 'public.eql_v3_numeric_eq',\n castAs: 'number',\n capabilities: EQUALITY_ONLY,\n} as const\nexport const NUMERIC_ORD_ORE = {\n eqlType: 'public.eql_v3_numeric_ord_ore',\n castAs: 'number',\n capabilities: ORDER_AND_RANGE,\n} as const\nexport const NUMERIC_ORD = {\n eqlType: 'public.eql_v3_numeric_ord',\n castAs: 'number',\n capabilities: ORDER_AND_RANGE,\n} as const\n\nexport const TEXT = {\n eqlType: 'public.eql_v3_text',\n castAs: 'string',\n capabilities: STORAGE_ONLY,\n} as const\nexport const TEXT_EQ = {\n eqlType: 'public.eql_v3_text_eq',\n castAs: 'string',\n capabilities: EQUALITY_ONLY,\n} as const\nexport const TEXT_MATCH = {\n eqlType: 'public.eql_v3_text_match',\n castAs: 'string',\n capabilities: MATCH_ONLY,\n} as const\nexport const TEXT_ORD_ORE = {\n eqlType: 'public.eql_v3_text_ord_ore',\n castAs: 'string',\n capabilities: ORDER_AND_RANGE,\n} as const\nexport const TEXT_ORD = {\n eqlType: 'public.eql_v3_text_ord',\n castAs: 'string',\n capabilities: ORDER_AND_RANGE,\n} as const\n\nexport const BOOLEAN = {\n eqlType: 'public.eql_v3_boolean',\n castAs: 'boolean',\n capabilities: STORAGE_ONLY,\n} as const\n\nexport const REAL = {\n eqlType: 'public.eql_v3_real',\n castAs: 'number',\n capabilities: STORAGE_ONLY,\n} as const\nexport const REAL_EQ = {\n eqlType: 'public.eql_v3_real_eq',\n castAs: 'number',\n capabilities: EQUALITY_ONLY,\n} as const\nexport const REAL_ORD_ORE = {\n eqlType: 'public.eql_v3_real_ord_ore',\n castAs: 'number',\n capabilities: ORDER_AND_RANGE,\n} as const\nexport const REAL_ORD = {\n eqlType: 'public.eql_v3_real_ord',\n castAs: 'number',\n capabilities: ORDER_AND_RANGE,\n} as const\n\nexport const DOUBLE = {\n eqlType: 'public.eql_v3_double',\n castAs: 'number',\n capabilities: STORAGE_ONLY,\n} as const\nexport const DOUBLE_EQ = {\n eqlType: 'public.eql_v3_double_eq',\n castAs: 'number',\n capabilities: EQUALITY_ONLY,\n} as const\nexport const DOUBLE_ORD_ORE = {\n eqlType: 'public.eql_v3_double_ord_ore',\n castAs: 'number',\n capabilities: ORDER_AND_RANGE,\n} as const\nexport const DOUBLE_ORD = {\n eqlType: 'public.eql_v3_double_ord',\n castAs: 'number',\n capabilities: ORDER_AND_RANGE,\n} as const\n\n/**\n * Translate a domain's semantic {@link QueryCapabilities} (plus its plaintext\n * `castAs`, which decides how equality is answered, and its ordering flavour)\n * into the concrete EQL index block emitted by `build()`.\n *\n * - `unique` (the `hm` HMAC index) whenever equality is answered via HMAC:\n * equality-only domains of ANY type, AND text order domains. Text equality is\n * HMAC-based — the `public.eql_v3_text_ord` / `public.eql_v3_text_ord_ore` SQL domains\n * REQUIRE `hm` in the stored ciphertext (their `eql_v3.eq_term` extracts it).\n * - ONE ordering index for any order/range domain, selected by the domain's\n * name (eql-3.0.0): plain `_ord` domains (and `text_search`) are OPE-backed —\n * `ope`, the `op` CLLW-OPE term — while `_ord_ore` domains keep block-ORE —\n * `ore`, the `ob` term. The two terms are not cross-comparable, and each\n * domain's SQL CHECK requires exactly its own. For numeric/date order\n * domains the ordering term also answers equality (via the SQL `=`\n * operator), so those emit no `hm`. Text order domains emit BOTH `unique`\n * and the ordering index.\n * - `match` (the `bf` bloom-filter index) for free-text search, deep-cloned from\n * the per-call defaults so no nested object is ever shared across columns, and\n * emitted with `include_original: false` (see below).\n */\nfunction indexesForCapabilities(\n capabilities: QueryCapabilities,\n castAs: PlaintextKind,\n ordering: 'ope' | 'ore',\n): ColumnSchema['indexes'] {\n const indexes: ColumnSchema['indexes'] = {}\n\n // Text equality is always HMAC-based, so a text order domain (`string` +\n // order/range) still needs `unique`; numeric/date order domains answer\n // equality via their ordering term and must NOT emit `unique`.\n if (\n capabilities.equality &&\n (!capabilities.orderAndRange || castAs === 'string')\n ) {\n indexes.unique = { token_filters: [] }\n }\n\n if (capabilities.orderAndRange) {\n indexes[ordering] = {}\n }\n\n if (capabilities.freeTextSearch) {\n // The factory returns fresh, unaliased nested objects per call, so no\n // column's emitted match block ever shares state with another's.\n //\n // `include_original` is overridden off the v2 builder's `true`. protect-ffi\n // ignores the flag entirely (measured across 0.24 and 0.29, EQL v2 and v3:\n // the emitted bloom is trigram-only either way, and a value shorter than\n // `token_length` blooms to nothing regardless), so this is inert today. It\n // is set to the value a substring-search domain actually wants — matching\n // the zod schema's own default — so that a protect-ffi release which starts\n // honouring the flag cannot silently break `contains`.\n indexes.match = { ...defaultMatchOpts(), include_original: false }\n }\n\n if (capabilities.searchableJson) {\n // Encrypted-JSONB index (the protect-ffi config kind is named `ste_vec`).\n // `prefix: 'enabled'` is a sentinel the table's `build()` rewrites to\n // `${tableName}/${columnName}` — the same scheme v2 `searchableJson` uses —\n // so each document's selectors are scoped to their column.\n //\n // `array_index_mode` indexes array elements by identity (`item`) and enables\n // `$[*]` wildcard selectors, but deliberately drops `position`: `@>`\n // containment must be a subset test (jsonb `@>` semantics), so `{roles:['x']}`\n // matches any document whose `roles` array contains `x` REGARDLESS of index.\n // With positional terms emitted (v2 `searchableJson`'s `'all'`), the needle\n // for `x`-at-index-0 would miss a document holding `x` at index 1.\n //\n // `mode: 'compat'` is REQUIRED for eql-3.0.0: `public.eql_v3_json` orders the\n // document's entries by the CLLW-OPE `op` term, so the index must emit `op`\n // (compat) terms. `'standard'` emits v2's CLLW-ORE `oc` terms, which the v3\n // domain rejects at encrypt time.\n indexes.ste_vec = {\n prefix: 'enabled',\n array_index_mode: { item: true, wildcard: true, position: false },\n mode: 'compat',\n }\n }\n\n return indexes\n}\n\n/**\n * The ordering flavour a domain's name pins (eql-3.0.0): `_ord_ore` domains\n * are block-ORE (`ore` index, `ob` term); every other ordering domain —\n * `_ord` and `text_search` — is CLLW-OPE (`ope` index, `op` term).\n */\nfunction orderingForEqlType(eqlType: string): 'ope' | 'ore' {\n return eqlType.endsWith('_ord_ore') ? 'ore' : 'ope'\n}\n\n/** Whether a domain's capabilities make it queryable at all (any flag set). */\nfunction isQueryableCapabilities(capabilities: QueryCapabilities): boolean {\n return (\n capabilities.equality ||\n capabilities.orderAndRange ||\n capabilities.freeTextSearch ||\n (capabilities.searchableJson ?? false)\n )\n}\n\n/**\n * Shared base for every v3 concrete domain column. Parameterised by the FULL\n * literal {@link V3DomainDefinition} (not by capabilities alone): the private\n * `definition` field carries the literal `eqlType`/`castAs`/`capabilities`, so\n * two otherwise-empty subclasses (e.g. `EncryptedBooleanColumn` and\n * `EncryptedDateColumn`, both storage-only) are NOT mutually assignable. This\n * nominality is what keeps plaintext inference precise.\n */\nexport class EncryptedV3Column<D extends V3DomainDefinition> {\n constructor(\n private readonly columnName: string,\n private readonly definition: D,\n ) {}\n\n getName(): string {\n return this.columnName\n }\n\n /** The concrete EQL v3 domain name. Metadata only; not emitted by `build()`. */\n getEqlType(): D['eqlType'] {\n return this.definition.eqlType\n }\n\n /** The semantic query capabilities this domain exposes. Metadata only. */\n getQueryCapabilities(): D['capabilities'] {\n return this.definition.capabilities\n }\n\n /** `true` when this domain can produce at least one kind of query term. */\n isQueryable(): QueryableFlag<D> {\n return isQueryableCapabilities(\n this.definition.capabilities,\n ) as QueryableFlag<D>\n }\n\n /** Emit the encrypt-config column: `cast_as` plus capability-derived indexes. */\n build(): ColumnSchema {\n return {\n cast_as: this.definition.castAs,\n indexes: indexesForCapabilities(\n this.definition.capabilities,\n this.definition.castAs,\n orderingForEqlType(this.definition.eqlType),\n ),\n }\n }\n}\n\nconst TEXT_SEARCH_DOMAIN = {\n eqlType: TEXT_SEARCH_EQL_TYPE,\n castAs: 'string',\n capabilities: TEXT_SEARCH,\n} as const\n\n/**\n * Builder for a `public.eql_v3_text_search` column.\n *\n * The concrete type inherently enables equality + order/range + free-text\n * match — there are no capability-enabling or tuning methods. The match index\n * is always emitted with the default configuration.\n *\n * NOTE — querying: a `text_search` column emits all three indexes (`unique`,\n * `ope`, `match`), and the shared index-inference picks them by fixed priority\n * `unique > match > ordering`. So `encryptQuery(value, { column, table })` with NO\n * explicit `queryType` builds an EQUALITY term (via `unique`), NOT a free-text\n * match — a substring like `'joh'` then matches nothing. To run a free-text\n * match query you MUST pass `queryType: 'freeTextSearch'`:\n *\n * ```typescript\n * // equality (default): exact value only\n * client.encryptQuery('john@example.com', { column: users.email, table: users })\n * // free-text match: substring/token search\n * client.encryptQuery('joh', { column: users.email, table: users, queryType: 'freeTextSearch' })\n * ```\n */\nexport class EncryptedTextSearchColumn extends EncryptedV3Column<\n typeof TEXT_SEARCH_DOMAIN\n> {\n constructor(columnName: string) {\n super(columnName, TEXT_SEARCH_DOMAIN)\n }\n}\n\n// ---------------------------------------------------------------------------\n// Concrete domain columns\n//\n// Every concrete class is an empty subclass parameterised by its literal domain\n// definition (see EncryptedV3Column). The `types` namespace (see ./types)\n// constructs these with the SAME literal constant so the instance's private\n// `definition` field carries full literal type data — that is what keeps\n// distinct domains nominally incompatible.\n// ---------------------------------------------------------------------------\n\n// integer\nexport class EncryptedIntegerColumn extends EncryptedV3Column<typeof INTEGER> {}\nexport class EncryptedIntegerEqColumn extends EncryptedV3Column<\n typeof INTEGER_EQ\n> {}\nexport class EncryptedIntegerOrdOreColumn extends EncryptedV3Column<\n typeof INTEGER_ORD_ORE\n> {}\nexport class EncryptedIntegerOrdColumn extends EncryptedV3Column<\n typeof INTEGER_ORD\n> {}\n\n// smallint\nexport class EncryptedSmallintColumn extends EncryptedV3Column<\n typeof SMALLINT\n> {}\nexport class EncryptedSmallintEqColumn extends EncryptedV3Column<\n typeof SMALLINT_EQ\n> {}\nexport class EncryptedSmallintOrdOreColumn extends EncryptedV3Column<\n typeof SMALLINT_ORD_ORE\n> {}\nexport class EncryptedSmallintOrdColumn extends EncryptedV3Column<\n typeof SMALLINT_ORD\n> {}\n\n// bigint (int8) — plaintext is a JS `bigint`, round-tripped losslessly by the\n// native protect-ffi boundary (see the BIGINT domain definitions above).\nexport class EncryptedBigintColumn extends EncryptedV3Column<typeof BIGINT> {}\nexport class EncryptedBigintEqColumn extends EncryptedV3Column<\n typeof BIGINT_EQ\n> {}\nexport class EncryptedBigintOrdOreColumn extends EncryptedV3Column<\n typeof BIGINT_ORD_ORE\n> {}\nexport class EncryptedBigintOrdColumn extends EncryptedV3Column<\n typeof BIGINT_ORD\n> {}\n\n// date\nexport class EncryptedDateColumn extends EncryptedV3Column<typeof DATE> {}\nexport class EncryptedDateEqColumn extends EncryptedV3Column<typeof DATE_EQ> {}\nexport class EncryptedDateOrdOreColumn extends EncryptedV3Column<\n typeof DATE_ORD_ORE\n> {}\nexport class EncryptedDateOrdColumn extends EncryptedV3Column<\n typeof DATE_ORD\n> {}\n\n// timestamp\nexport class EncryptedTimestampColumn extends EncryptedV3Column<\n typeof TIMESTAMP\n> {}\nexport class EncryptedTimestampEqColumn extends EncryptedV3Column<\n typeof TIMESTAMP_EQ\n> {}\nexport class EncryptedTimestampOrdOreColumn extends EncryptedV3Column<\n typeof TIMESTAMP_ORD_ORE\n> {}\nexport class EncryptedTimestampOrdColumn extends EncryptedV3Column<\n typeof TIMESTAMP_ORD\n> {}\n\n// numeric\nexport class EncryptedNumericColumn extends EncryptedV3Column<typeof NUMERIC> {}\nexport class EncryptedNumericEqColumn extends EncryptedV3Column<\n typeof NUMERIC_EQ\n> {}\nexport class EncryptedNumericOrdOreColumn extends EncryptedV3Column<\n typeof NUMERIC_ORD_ORE\n> {}\nexport class EncryptedNumericOrdColumn extends EncryptedV3Column<\n typeof NUMERIC_ORD\n> {}\n\n// text (text_search is defined above with its match-tuning override)\nexport class EncryptedTextColumn extends EncryptedV3Column<typeof TEXT> {}\nexport class EncryptedTextEqColumn extends EncryptedV3Column<typeof TEXT_EQ> {}\nexport class EncryptedTextMatchColumn extends EncryptedV3Column<\n typeof TEXT_MATCH\n> {}\nexport class EncryptedTextOrdOreColumn extends EncryptedV3Column<\n typeof TEXT_ORD_ORE\n> {}\nexport class EncryptedTextOrdColumn extends EncryptedV3Column<\n typeof TEXT_ORD\n> {}\n\n// boolean\nexport class EncryptedBooleanColumn extends EncryptedV3Column<typeof BOOLEAN> {}\n\n// real\nexport class EncryptedRealColumn extends EncryptedV3Column<typeof REAL> {}\nexport class EncryptedRealEqColumn extends EncryptedV3Column<typeof REAL_EQ> {}\nexport class EncryptedRealOrdOreColumn extends EncryptedV3Column<\n typeof REAL_ORD_ORE\n> {}\nexport class EncryptedRealOrdColumn extends EncryptedV3Column<\n typeof REAL_ORD\n> {}\n\n// double\nexport class EncryptedDoubleColumn extends EncryptedV3Column<typeof DOUBLE> {}\nexport class EncryptedDoubleEqColumn extends EncryptedV3Column<\n typeof DOUBLE_EQ\n> {}\nexport class EncryptedDoubleOrdOreColumn extends EncryptedV3Column<\n typeof DOUBLE_ORD_ORE\n> {}\nexport class EncryptedDoubleOrdColumn extends EncryptedV3Column<\n typeof DOUBLE_ORD\n> {}\n\n// json\nconst JSON_DOMAIN = {\n eqlType: 'public.eql_v3_json',\n castAs: 'json',\n capabilities: {\n equality: false,\n orderAndRange: false,\n freeTextSearch: false,\n searchableJson: true,\n },\n} as const\n\n/**\n * Builder for a `public.eql_v3_json` column — an encrypted JSONB document\n * (a {@link JsonDocument}: object, array, or null). It round-trips through\n * `encrypt`/`decrypt`, and containment queries use the encrypted-JSONB index\n * emitted by `build()`. (The stored payload is protect-ffi's `SteVecDocument`,\n * and the config index kind is `ste_vec` — both protect-ffi names.)\n */\nexport class EncryptedJsonColumn extends EncryptedV3Column<typeof JSON_DOMAIN> {\n constructor(columnName: string) {\n super(columnName, JSON_DOMAIN)\n }\n}\n\n/**\n * Union of every v3 concrete column type. Used as the value type for v3 table\n * columns so a table may mix any generated domains.\n */\nexport type AnyEncryptedV3Column =\n | EncryptedIntegerColumn\n | EncryptedIntegerEqColumn\n | EncryptedIntegerOrdOreColumn\n | EncryptedIntegerOrdColumn\n | EncryptedSmallintColumn\n | EncryptedSmallintEqColumn\n | EncryptedSmallintOrdOreColumn\n | EncryptedSmallintOrdColumn\n | EncryptedBigintColumn\n | EncryptedBigintEqColumn\n | EncryptedBigintOrdOreColumn\n | EncryptedBigintOrdColumn\n | EncryptedDateColumn\n | EncryptedDateEqColumn\n | EncryptedDateOrdOreColumn\n | EncryptedDateOrdColumn\n | EncryptedTimestampColumn\n | EncryptedTimestampEqColumn\n | EncryptedTimestampOrdOreColumn\n | EncryptedTimestampOrdColumn\n | EncryptedNumericColumn\n | EncryptedNumericEqColumn\n | EncryptedNumericOrdOreColumn\n | EncryptedNumericOrdColumn\n | EncryptedTextColumn\n | EncryptedTextEqColumn\n | EncryptedTextMatchColumn\n | EncryptedTextOrdOreColumn\n | EncryptedTextOrdColumn\n | EncryptedTextSearchColumn\n | EncryptedBooleanColumn\n | EncryptedRealColumn\n | EncryptedRealEqColumn\n | EncryptedRealOrdOreColumn\n | EncryptedRealOrdColumn\n | EncryptedDoubleColumn\n | EncryptedDoubleEqColumn\n | EncryptedDoubleOrdOreColumn\n | EncryptedDoubleOrdColumn\n | EncryptedJsonColumn\n\n/**\n * A factory that builds a concrete v3 column for a given DB column name.\n *\n * Declared here rather than beside `DOMAIN_REGISTRY` so that `./types` can\n * constrain its own export against it without importing from `./domain-registry`,\n * which imports `./types` back as a value.\n */\nexport type V3ColumnFactory = (name: string) => AnyEncryptedV3Column\n\n/**\n * Shape of v3 table columns: every value is a v3 concrete column builder.\n * (Nested fields are deferred to later increments.)\n */\nexport type EncryptedV3TableColumn = {\n [key: string]: AnyEncryptedV3Column\n}\n\n/** A JSON value at any depth. Used for the values NESTED inside a document. */\nexport type JsonValue =\n | string\n | number\n | boolean\n | null\n | JsonValue[]\n | { [key: string]: JsonValue }\n\n/**\n * The plaintext a `public.eql_v3_json` column encrypts and reconstructs: a JSON\n * DOCUMENT — an object, an array, or `null`. NOT a bare top-level scalar:\n * protect-ffi's `json` cast rejects a top-level string/number/boolean\n * (\"Cannot convert … to Json\"), because a scalar belongs in a scalar domain\n * (`types.TextEq`, `types.IntegerEq`, …). Nested scalars are ordinary\n * {@link JsonValue}s and are fully supported.\n */\nexport type JsonDocument = null | JsonValue[] | { [key: string]: JsonValue }\n\n/** Map a domain's {@link PlaintextKind} to its TypeScript plaintext type. */\ntype PlaintextFromKind<K extends PlaintextKind> = K extends 'string'\n ? string\n : K extends 'number'\n ? number\n : K extends 'bigint'\n ? bigint\n : K extends 'boolean'\n ? boolean\n : K extends DateLikeCast\n ? Date\n : K extends 'json'\n ? JsonDocument\n : never\n\n/**\n * The plaintext type for a single v3 column, read from the literal domain\n * definition carried on the base class's private field. This is stable across\n * empty subclasses that share the same base generic — a subclass-name\n * conditional would collapse because those subclasses are structurally\n * assignable to one another.\n */\nexport type PlaintextForColumn<C> =\n C extends EncryptedV3Column<infer D> ? PlaintextFromKind<D['castAs']> : never\n\n/**\n * The user-facing `queryType` names a v3 column supports, derived 1:1 from its\n * capability flags. Resolves to `never` for a storage-only column (all flags\n * `false`) and for any non-v3 value. The names mirror the {@link QueryCapabilities}\n * keys and the first three {@link import('@/types').QueryTypeName} members.\n */\nexport type QueryTypesForColumn<C> =\n C extends EncryptedV3Column<infer D>\n ?\n | (D['capabilities']['equality'] extends true ? 'equality' : never)\n | (D['capabilities']['orderAndRange'] extends true\n ? 'orderAndRange'\n : never)\n | (D['capabilities']['freeTextSearch'] extends true\n ? 'freeTextSearch'\n : never)\n : never\n\n/**\n * The concrete EQL v3 type string for a single column, read from the literal\n * domain definition carried on the base class's private field (mirrors\n * {@link PlaintextForColumn}). Distributes over a union of columns, so\n * `EqlTypeForColumn<AnyEncryptedV3Column>` yields the union of every domain's\n * `eqlType` — the canonical, source-of-truth key set for a type-driven test\n * matrix keyed by domain.\n */\nexport type EqlTypeForColumn<C> =\n C extends EncryptedV3Column<infer D> ? D['eqlType'] : never\n","import type { ProtectErrorCode } from '@cipherstash/protect-ffi'\n\nexport const EncryptionErrorTypes = {\n ClientInitError: 'ClientInitError',\n EncryptionError: 'EncryptionError',\n DecryptionError: 'DecryptionError',\n LockContextError: 'LockContextError',\n CtsTokenError: 'CtsTokenError',\n}\n\n/**\n * Base error interface returned by all encryption operations.\n *\n * Every operation that can fail returns `Result<T, EncryptionError>`.\n * Use the `type` field to narrow to a specific error kind, or use\n * {@link StackError} for an exhaustive discriminated union.\n *\n * @example\n * ```typescript\n * const result = await client.encrypt(value, opts)\n * if (result.failure) {\n * switch (result.failure.type) {\n * case EncryptionErrorTypes.EncryptionError:\n * console.error('Encryption failed:', result.failure.message)\n * break\n * case EncryptionErrorTypes.LockContextError:\n * console.error('Lock context issue:', result.failure.message)\n * break\n * }\n * }\n * ```\n */\nexport interface EncryptionError {\n type: (typeof EncryptionErrorTypes)[keyof typeof EncryptionErrorTypes]\n message: string\n code?: ProtectErrorCode\n}\n\n// ---------------------------------------------------------------------------\n// Specific error types (discriminated union members)\n// ---------------------------------------------------------------------------\n\nexport interface ClientInitError {\n type: typeof EncryptionErrorTypes.ClientInitError\n message: string\n}\n\nexport interface EncryptionOperationError {\n type: typeof EncryptionErrorTypes.EncryptionError\n message: string\n code?: ProtectErrorCode\n}\n\nexport interface DecryptionOperationError {\n type: typeof EncryptionErrorTypes.DecryptionError\n message: string\n code?: ProtectErrorCode\n}\n\nexport interface LockContextError {\n type: typeof EncryptionErrorTypes.LockContextError\n message: string\n}\n\nexport interface CtsTokenError {\n type: typeof EncryptionErrorTypes.CtsTokenError\n message: string\n}\n\n/**\n * Discriminated union of all specific error types.\n *\n * Use `StackError` when you need exhaustive error handling via `switch` on the `type` field.\n *\n * @example\n * ```typescript\n * function handleError(error: StackError) {\n * switch (error.type) {\n * case 'ClientInitError':\n * // re-initialize client\n * break\n * case 'EncryptionError':\n * case 'DecryptionError':\n * // log and retry\n * break\n * case 'LockContextError':\n * // re-authenticate\n * break\n * case 'CtsTokenError':\n * // refresh token\n * break\n * default:\n * error satisfies never\n * }\n * }\n * ```\n */\nexport type StackError =\n | ClientInitError\n | EncryptionOperationError\n | DecryptionOperationError\n | LockContextError\n | CtsTokenError\n\n// ---------------------------------------------------------------------------\n// Error utilities\n// ---------------------------------------------------------------------------\n\n/**\n * Safely extract an error message from an unknown thrown value.\n * Unlike `(error as Error).message`, this handles non-Error values gracefully.\n */\nexport function getErrorMessage(error: unknown): string {\n if (error instanceof Error) return error.message\n if (typeof error === 'string') return error\n return String(error)\n}\n","// src/result.ts\nfunction ensureError(ex) {\n return ex instanceof Error ? ex : new Error(\"Something went wrong\");\n}\nasync function withResult(operation, onError, hooks) {\n try {\n return { data: await operation() };\n } catch (ex) {\n const error = hooks?.onException?.(ex) ?? ensureError(ex);\n return { failure: onError(error) };\n }\n}\nexport {\n withResult\n};\n","import { type Result, withResult } from '@byteslice/result'\nimport { newClient } from '@cipherstash/protect-ffi'\nimport { validate as uuidValidate } from 'uuid'\nimport { type EncryptionError, EncryptionErrorTypes } from '@/errors'\n// `LockContext` is imported type-only so the TSDoc {@link} references in the\n// comments below resolve; it is erased at compile time.\nimport type { LockContext } from '@/identity'\nimport {\n buildEncryptConfig,\n type EncryptConfig,\n encryptConfigSchema,\n // Imported type-only for the TSDoc {@link} references in the comments below.\n type encryptedColumn,\n type encryptedField,\n type encryptedTable,\n} from '@/schema'\nimport type {\n AuthStrategy,\n BuildableTable,\n BulkDecryptPayload,\n BulkEncryptPayload,\n Client,\n Encrypted,\n EncryptedFromBuildableTable,\n EncryptionClientConfig,\n EncryptOptions,\n EncryptQueryOptions,\n KeysetIdentifier,\n Plaintext,\n ScalarQueryTerm,\n} from '@/types'\nimport { logger } from '@/utils/logger'\nimport { toFfiKeysetIdentifier } from './helpers'\nimport { isScalarQueryTermArray } from './helpers/type-guards'\nimport { BatchEncryptQueryOperation } from './operations/batch-encrypt-query'\nimport { BulkDecryptOperation } from './operations/bulk-decrypt'\nimport { BulkDecryptModelsOperation } from './operations/bulk-decrypt-models'\nimport { BulkEncryptOperation } from './operations/bulk-encrypt'\nimport { BulkEncryptModelsOperation } from './operations/bulk-encrypt-models'\nimport { DecryptOperation } from './operations/decrypt'\nimport { DecryptModelOperation } from './operations/decrypt-model'\nimport { EncryptOperation } from './operations/encrypt'\nimport { EncryptModelOperation } from './operations/encrypt-model'\nimport { EncryptQueryOperation } from './operations/encrypt-query'\n\n// Re-export the operation classes returned by EncryptionClient methods so they\n// are part of the public API and appear in the generated reference, allowing\n// TSDoc {@link} references and method return types to resolve to real pages.\nexport {\n BatchEncryptQueryOperation,\n BulkDecryptModelsOperation,\n BulkDecryptOperation,\n BulkEncryptModelsOperation,\n BulkEncryptOperation,\n DecryptModelOperation,\n DecryptOperation,\n EncryptModelOperation,\n EncryptOperation,\n EncryptQueryOperation,\n}\n\nexport const noClientError = () =>\n new Error(\n 'The Encryption client has not been initialized. Please call init() before using the client.',\n )\n\n/**\n * Resolve the EQL wire version for a client from its schema set.\n *\n * One FFI client emits exactly one wire format, so the whole schema set must\n * agree. EQL v3 tables (from `@cipherstash/stack/v3`) are detected by their\n * `buildColumnKeyMap()` marker — v2 tables don't have one:\n *\n * - every schema is v3 → `3`;\n * - no schema is v3 → `undefined`, leaving the FFI's v2 default (and its\n * byte-identical v2 output) untouched;\n * - a mix of the two → throws: the v2 tables target `eql_v2_encrypted`\n * columns and the v3 tables target `eql_v3` domains, so no single wire\n * format serves both. Split them across two clients.\n *\n * An explicit `config.eqlVersion` bypasses detection (the wire format is\n * then unambiguous — e.g. writing v2-wire from a v3 schema set during a\n * migration), but a mixed schema set still throws.\n *\n * @internal exported for unit-test coverage of the detection matrix.\n */\nexport function resolveEqlVersion(\n schemas: readonly BuildableTable[],\n explicit?: 2 | 3,\n): 2 | 3 | undefined {\n const v3Count = schemas.filter(\n (schema) => typeof schema.buildColumnKeyMap === 'function',\n ).length\n\n if (v3Count > 0 && v3Count < schemas.length) {\n throw new Error(\n '[encryption]: cannot mix EQL v2 and EQL v3 tables in one client — one client emits exactly one wire format. Create separate clients for the v2 and v3 schemas.',\n )\n }\n\n if (explicit !== undefined) {\n return explicit\n }\n\n return v3Count === 0 ? undefined : 3\n}\n\n/** The EncryptionClient is the main entry point for interacting with the CipherStash Encryption library.\n * It provides methods for encrypting and decrypting individual values, as well as models (objects) and bulk operations.\n *\n * The client must be initialized using the {@link Encryption} function before it can be used.\n */\nexport class EncryptionClient {\n private client: Client\n private encryptConfig: EncryptConfig | undefined\n\n /**\n * Initializes the EncryptionClient with the provided configuration.\n * @internal\n * @param config - The configuration object for initializing the client.\n * @returns A promise that resolves to a {@link Result} containing the initialized EncryptionClient or an {@link EncryptionError}.\n **/\n async init(config: {\n encryptConfig: EncryptConfig\n workspaceCrn?: string\n accessKey?: string\n clientId?: string\n clientKey?: string\n keyset?: KeysetIdentifier\n authStrategy?: AuthStrategy\n eqlVersion?: 2 | 3\n }): Promise<Result<EncryptionClient, EncryptionError>> {\n return await withResult(\n async () => {\n const validated: EncryptConfig = encryptConfigSchema.parse(\n config.encryptConfig,\n )\n\n logger.debug(\n 'Initializing the Encryption client with the following config:',\n {\n encryptConfig: validated,\n },\n )\n\n // newClient handles env var fallback internally via withEnvCredentials,\n // so we pass config values through without manual fallback here.\n // When `authStrategy` is supplied, protect-ffi invokes its getToken()\n // on every ZeroKMS request instead of building an AutoStrategy\n // from the credentials in clientOpts (the clientKey is still used\n // for encryption). Passing `strategy: undefined` is equivalent to\n // omitting it, so the default credentials path is unaffected.\n // `eqlVersion` selects the wire format `encrypt`/`encryptQuery`\n // emit (protect-ffi 0.27+); `eqlVersion: undefined` is likewise\n // equivalent to omitting it, leaving the FFI's v2 default — and\n // its byte-identical v2 output — untouched.\n this.client = await newClient({\n encryptConfig: validated,\n clientOpts: {\n workspaceCrn: config.workspaceCrn,\n accessKey: config.accessKey,\n clientId: config.clientId,\n clientKey: config.clientKey,\n keyset: toFfiKeysetIdentifier(config.keyset),\n },\n strategy: config.authStrategy,\n eqlVersion: config.eqlVersion,\n })\n\n this.encryptConfig = validated\n\n logger.debug('Successfully initialized the Encryption client.')\n return this\n },\n (error: unknown) => ({\n type: EncryptionErrorTypes.ClientInitError,\n message: (error as Error).message,\n }),\n )\n }\n\n /**\n * Encrypt a value - returns a promise which resolves to an encrypted value.\n *\n * @param plaintext - The plaintext value to be encrypted.\n * @param opts - Options specifying the column (or nested field) and table for encryption. See {@link EncryptOptions}.\n * @returns An EncryptOperation that can be awaited or chained with additional methods.\n *\n * @example\n * The following example demonstrates how to encrypt a value using the Encryption client.\n * It includes defining an encryption schema with {@link encryptedTable} and {@link encryptedColumn},\n * initializing the client with {@link Encryption}, and performing the encryption.\n *\n * `encrypt` returns an {@link EncryptOperation} which can be awaited to get a {@link Result}\n * which can either be the encrypted value or an {@link EncryptionError}.\n *\n * ```typescript\n * // Define encryption schema\n * import { Encryption } from \"@cipherstash/stack\"\n * import { encryptedTable, encryptedColumn } from \"@cipherstash/stack/schema\"\n * const userSchema = encryptedTable(\"users\", {\n * email: encryptedColumn(\"email\"),\n * });\n *\n * // Initialize Encryption client\n * const client = await Encryption({ schemas: [userSchema] })\n *\n * // Encrypt a value\n * const encryptedResult = await client.encrypt(\n * \"person@example.com\",\n * { column: userSchema.email, table: userSchema }\n * )\n *\n * // Handle encryption result\n * if (encryptedResult.failure) {\n * throw new Error(`Encryption failed: ${encryptedResult.failure.message}`);\n * }\n *\n * console.log(\"Encrypted data:\", encryptedResult.data);\n * ```\n *\n * @example\n * When encrypting data, a {@link LockContext} can be provided to tie the encryption to a specific user or session.\n * This ensures that the same lock context is required for decryption.\n *\n * The following example demonstrates how to create a lock context using a user's JWT token\n * and use it during encryption.\n *\n * ```typescript\n * // Define encryption schema and initialize client as above\n *\n * // Create a lock for the user's `sub` claim from their JWT\n * const lc = new LockContext();\n * const lockContext = await lc.identify(userJwt);\n *\n * if (lockContext.failure) {\n * // Handle the failure\n * }\n *\n * // Encrypt a value with the lock context\n * // Decryption will then require the same lock context\n * const encryptedResult = await client.encrypt(\n * \"person@example.com\",\n * { column: userSchema.email, table: userSchema }\n * )\n * .withLockContext(lockContext)\n * ```\n *\n * @see {@link EncryptOptions}\n * @see {@link Result}\n * @see {@link encryptedTable}\n * @see {@link encryptedColumn}\n * @see {@link encryptedField}\n * @see {@link LockContext}\n * @see {@link EncryptOperation}\n */\n encrypt(plaintext: Plaintext, opts: EncryptOptions): EncryptOperation {\n return new EncryptOperation(this.client, plaintext, opts)\n }\n\n /**\n * Encrypt a query value - returns a promise which resolves to an encrypted query value.\n *\n * @param plaintext - The plaintext value to be encrypted for querying.\n * @param opts - Options specifying the column, table, and optional queryType for encryption.\n * @returns An EncryptQueryOperation that can be awaited or chained with additional methods.\n *\n * @example\n * The following example demonstrates how to encrypt a query value using the Encryption client.\n *\n * ```typescript\n * // Define encryption schema\n * import { Encryption } from \"@cipherstash/stack\"\n * import { encryptedTable, encryptedColumn } from \"@cipherstash/stack/schema\"\n * const userSchema = encryptedTable(\"users\", {\n * email: encryptedColumn(\"email\").equality(),\n * });\n *\n * // Initialize Encryption client\n * const client = await Encryption({ schemas: [userSchema] })\n *\n * // Encrypt a query value\n * const encryptedResult = await client.encryptQuery(\n * \"person@example.com\",\n * { column: userSchema.email, table: userSchema, queryType: 'equality' }\n * )\n *\n * // Handle encryption result\n * if (encryptedResult.failure) {\n * throw new Error(`Encryption failed: ${encryptedResult.failure.message}`);\n * }\n *\n * console.log(\"Encrypted query:\", encryptedResult.data);\n * ```\n *\n * @example\n * The queryType can be auto-inferred from the column's configured indexes:\n *\n * ```typescript\n * // When queryType is omitted, it will be inferred from the column's indexes\n * const encryptedResult = await client.encryptQuery(\n * \"person@example.com\",\n * { column: userSchema.email, table: userSchema }\n * )\n * ```\n *\n * @see {@link EncryptQueryOperation}\n *\n * **JSONB columns (searchableJson):**\n * When `queryType` is omitted on a `searchableJson()` column, the query operation is inferred:\n * - String plaintext → `steVecSelector` (JSONPath queries like `'$.user.email'`)\n * - Object/Array plaintext → `steVecTerm` (containment queries like `{ role: 'admin' }`)\n */\n encryptQuery(\n plaintext: Plaintext,\n opts: EncryptQueryOptions,\n ): EncryptQueryOperation\n\n /**\n * Encrypt multiple values for use in queries (batch operation).\n * @param terms - Array of query terms to encrypt\n */\n encryptQuery(terms: readonly ScalarQueryTerm[]): BatchEncryptQueryOperation\n\n encryptQuery(\n plaintextOrTerms: Plaintext | readonly ScalarQueryTerm[],\n opts?: EncryptQueryOptions,\n ): EncryptQueryOperation | BatchEncryptQueryOperation {\n // Discriminate between ScalarQueryTerm[] and Plaintext (which can also be an\n // array) using a type guard function. Only route to batch mode when no opts\n // are supplied — an explicit EncryptQueryOptions forces the single-plaintext\n // path even if the plaintext value happens to be an array.\n if (!opts && isScalarQueryTermArray(plaintextOrTerms)) {\n return new BatchEncryptQueryOperation(this.client, plaintextOrTerms)\n }\n\n // Handle empty arrays: if opts provided, treat as single value; otherwise batch mode\n // This maintains backward compatibility for encryptQuery([]) while allowing\n // encryptQuery([], opts) to encrypt an empty array as a single value\n if (\n Array.isArray(plaintextOrTerms) &&\n plaintextOrTerms.length === 0 &&\n !opts\n ) {\n return new BatchEncryptQueryOperation(\n this.client,\n [] as readonly ScalarQueryTerm[],\n )\n }\n\n if (!opts) {\n throw new Error('EncryptQueryOptions are required')\n }\n\n return new EncryptQueryOperation(\n this.client,\n plaintextOrTerms as Plaintext,\n opts,\n )\n }\n\n /**\n * Decryption - returns a promise which resolves to a decrypted value.\n *\n * @param encryptedData - The encrypted data to be decrypted.\n * @returns A DecryptOperation that can be awaited or chained with additional methods.\n *\n * @example\n * The following example demonstrates how to decrypt a value that was previously encrypted using the {@link encrypt} method.\n * It includes encrypting a value first, then decrypting it, and handling the result.\n *\n * ```typescript\n * const encryptedData = await client.encrypt(\n * \"person@example.com\",\n * { column: \"email\", table: \"users\" }\n * )\n * const decryptResult = await client.decrypt(encryptedData)\n * if (decryptResult.failure) {\n * throw new Error(`Decryption failed: ${decryptResult.failure.message}`);\n * }\n * console.log(\"Decrypted data:\", decryptResult.data);\n * ```\n *\n * @example\n * Provide a lock context when decrypting:\n * ```typescript\n * await client.decrypt(encryptedData)\n * .withLockContext(lockContext)\n * ```\n *\n * @remarks\n * The public input type rejects null, but at runtime `decrypt` will\n * short-circuit and return null when given a null ciphertext\n * (defense in depth for legacy / manually-NULLed DB rows reached via\n * casts or dynamic field walking). The narrow return type holds for\n * any caller that respects the input contract.\n *\n * @see {@link LockContext}\n * @see {@link DecryptOperation}\n */\n decrypt(encryptedData: Encrypted): DecryptOperation {\n return new DecryptOperation(this.client, encryptedData)\n }\n\n /**\n * Encrypt a model (object) based on the table schema.\n *\n * Only fields whose keys match columns defined in the table schema are encrypted.\n * All other fields are passed through unchanged. Returns a thenable operation\n * that supports `.withLockContext()` for identity-aware encryption.\n *\n * The return type is **schema-aware**: fields matching the table schema are\n * typed as `Encrypted`, while other fields retain their original types. For\n * best results, let TypeScript infer the type parameters from the arguments\n * rather than providing an explicit type argument.\n *\n * @param input - The model object with plaintext values to encrypt.\n * @param table - The table schema defining which fields to encrypt.\n * @returns An `EncryptModelOperation` that can be awaited to get a `Result`\n * containing the model with schema-defined fields typed as `Encrypted`,\n * or an `EncryptionError`.\n *\n * @example\n * ```typescript\n * import { Encryption } from \"@cipherstash/stack\"\n * import { encryptedTable, encryptedColumn } from \"@cipherstash/stack/schema\"\n *\n * type User = { id: string; email: string; createdAt: Date }\n *\n * const usersSchema = encryptedTable(\"users\", {\n * email: encryptedColumn(\"email\").equality(),\n * })\n *\n * const client = await Encryption({ schemas: [usersSchema] })\n *\n * // Let TypeScript infer the return type from the schema.\n * // result.data.email is typed as `Encrypted`, result.data.id stays `string`.\n * const result = await client.encryptModel(\n * { id: \"user_123\", email: \"alice@example.com\", createdAt: new Date() },\n * usersSchema,\n * )\n *\n * if (result.failure) {\n * console.error(result.failure.message)\n * } else {\n * console.log(result.data.id) // string\n * console.log(result.data.email) // Encrypted\n * }\n * ```\n */\n encryptModel<T extends Record<string, unknown>, Table extends BuildableTable>(\n input: T,\n table: Table,\n ): EncryptModelOperation<EncryptedFromBuildableTable<T, Table>> {\n return new EncryptModelOperation(\n this.client,\n input as Record<string, unknown>,\n table,\n )\n }\n\n /**\n * Decrypt a model (object) whose fields contain encrypted values.\n *\n * Identifies encrypted fields automatically and decrypts them, returning the\n * model with plaintext values. Returns a thenable operation that supports\n * `.withLockContext()` for identity-aware decryption.\n *\n * @param input - The model object with encrypted field values.\n * @returns A `DecryptModelOperation<T>` that can be awaited to get a `Result`\n * containing the model with decrypted plaintext fields, or an `EncryptionError`.\n *\n * @example\n * ```typescript\n * // Decrypt a previously encrypted model\n * const decrypted = await client.decryptModel<User>(encryptedUser)\n *\n * if (decrypted.failure) {\n * console.error(decrypted.failure.message)\n * } else {\n * console.log(decrypted.data.email) // \"alice@example.com\"\n * }\n *\n * // With a lock context\n * const decrypted = await client\n * .decryptModel<User>(encryptedUser)\n * .withLockContext(lockContext)\n * ```\n */\n decryptModel<T extends Record<string, unknown>>(\n input: T,\n ): DecryptModelOperation<T> {\n return new DecryptModelOperation(this.client, input)\n }\n\n /**\n * Encrypt multiple models (objects) in a single bulk operation.\n *\n * Performs a single call to ZeroKMS regardless of the number of models,\n * while still using a unique key for each encrypted value. Only fields\n * matching the table schema are encrypted; other fields pass through unchanged.\n *\n * The return type is **schema-aware**: fields matching the table schema are\n * typed as `Encrypted`, while other fields retain their original types. For\n * best results, let TypeScript infer the type parameters from the arguments.\n *\n * @param input - An array of model objects with plaintext values to encrypt.\n * @param table - The table schema defining which fields to encrypt.\n * @returns A `BulkEncryptModelsOperation` that can be awaited to get a `Result`\n * containing an array of models with schema-defined fields typed as `Encrypted`,\n * or an `EncryptionError`.\n *\n * @example\n * ```typescript\n * import { Encryption } from \"@cipherstash/stack\"\n * import { encryptedTable, encryptedColumn } from \"@cipherstash/stack/schema\"\n *\n * type User = { id: string; email: string }\n *\n * const usersSchema = encryptedTable(\"users\", {\n * email: encryptedColumn(\"email\"),\n * })\n *\n * const client = await Encryption({ schemas: [usersSchema] })\n *\n * // Let TypeScript infer the return type from the schema.\n * // Each item's email is typed as `Encrypted`, id stays `string`.\n * const result = await client.bulkEncryptModels(\n * [\n * { id: \"1\", email: \"alice@example.com\" },\n * { id: \"2\", email: \"bob@example.com\" },\n * ],\n * usersSchema,\n * )\n *\n * if (!result.failure) {\n * console.log(result.data) // array of models with encrypted email fields\n * }\n * ```\n */\n bulkEncryptModels<\n T extends Record<string, unknown>,\n Table extends BuildableTable,\n >(\n input: Array<T>,\n table: Table,\n ): BulkEncryptModelsOperation<EncryptedFromBuildableTable<T, Table>> {\n return new BulkEncryptModelsOperation(\n this.client,\n input as Array<Record<string, unknown>>,\n table,\n )\n }\n\n /**\n * Decrypt multiple models (objects) in a single bulk operation.\n *\n * Performs a single call to ZeroKMS regardless of the number of models,\n * restoring all encrypted fields to their original plaintext values.\n *\n * @param input - An array of model objects with encrypted field values.\n * @returns A `BulkDecryptModelsOperation<T>` that can be awaited to get a `Result`\n * containing an array of models with decrypted plaintext fields, or an `EncryptionError`.\n *\n * @example\n * ```typescript\n * const encryptedUsers = encryptedResult.data // from bulkEncryptModels\n *\n * const result = await client.bulkDecryptModels<User>(encryptedUsers)\n *\n * if (!result.failure) {\n * for (const user of result.data) {\n * console.log(user.email) // plaintext email\n * }\n * }\n *\n * // With a lock context\n * const result = await client\n * .bulkDecryptModels<User>(encryptedUsers)\n * .withLockContext(lockContext)\n * ```\n */\n bulkDecryptModels<T extends Record<string, unknown>>(\n input: Array<T>,\n ): BulkDecryptModelsOperation<T> {\n return new BulkDecryptModelsOperation(this.client, input)\n }\n\n /**\n * Encrypt multiple plaintext values in a single bulk operation.\n *\n * Each value is encrypted with its own unique key via a single call to ZeroKMS.\n * Values can include optional `id` fields for correlating results back to\n * your application data.\n *\n * @param plaintexts - An array of objects with `plaintext` (and optional `id`) fields.\n * @param opts - Options specifying the target column (or nested {@link encryptedField}) and table. See {@link EncryptOptions}.\n * @returns A `BulkEncryptOperation` that can be awaited to get a `Result`\n * containing an array of `{ id?, data: Encrypted }` objects, or an `EncryptionError`.\n *\n * @example\n * ```typescript\n * import { Encryption } from \"@cipherstash/stack\"\n * import { encryptedTable, encryptedColumn } from \"@cipherstash/stack/schema\"\n *\n * const users = encryptedTable(\"users\", {\n * email: encryptedColumn(\"email\"),\n * })\n * const client = await Encryption({ schemas: [users] })\n *\n * const result = await client.bulkEncrypt(\n * [\n * { id: \"u1\", plaintext: \"alice@example.com\" },\n * { id: \"u2\", plaintext: \"bob@example.com\" },\n * ],\n * { column: users.email, table: users },\n * )\n *\n * if (!result.failure) {\n * // result.data = [{ id: \"u1\", data: Encrypted }, { id: \"u2\", data: Encrypted }, ...]\n * console.log(result.data)\n * }\n * ```\n */\n bulkEncrypt(\n plaintexts: BulkEncryptPayload,\n opts: EncryptOptions,\n ): BulkEncryptOperation {\n return new BulkEncryptOperation(this.client, plaintexts, opts)\n }\n\n /**\n * Decrypt multiple encrypted values in a single bulk operation.\n *\n * Performs a single call to ZeroKMS to decrypt all values. The result uses\n * a multi-status pattern: each item in the returned array has either a `data`\n * field (success) or an `error` field (failure), allowing graceful handling\n * of partial failures.\n *\n * @param encryptedPayloads - An array of objects with `data` (encrypted payload) and optional `id` fields.\n * @returns A `BulkDecryptOperation` that can be awaited to get a `Result`\n * containing an array of `{ id?, data: plaintext }` or `{ id?, error: string }` objects,\n * or an `EncryptionError` if the entire operation fails.\n *\n * @example\n * ```typescript\n * const encrypted = await client.bulkEncrypt(plaintexts, { column: users.email, table: users })\n *\n * const result = await client.bulkDecrypt(encrypted.data)\n *\n * if (!result.failure) {\n * for (const item of result.data) {\n * if (\"data\" in item) {\n * console.log(`${item.id}: ${item.data}`)\n * } else {\n * console.error(`${item.id} failed: ${item.error}`)\n * }\n * }\n * }\n * ```\n */\n bulkDecrypt(encryptedPayloads: BulkDecryptPayload): BulkDecryptOperation {\n return new BulkDecryptOperation(this.client, encryptedPayloads)\n }\n\n /**\n * Get the encrypt config object.\n *\n * @returns The encrypt config object.\n */\n getEncryptConfig(): EncryptConfig | undefined {\n return this.encryptConfig\n }\n}\n\n// Emit the `config.strategy` → `config.authStrategy` rename warning at most\n// once per process so repeated `Encryption()` calls don't spam the console.\nlet warnedStrategyDeprecated = false\nfunction warnStrategyDeprecated(): void {\n if (warnedStrategyDeprecated) return\n warnedStrategyDeprecated = true\n console.warn(\n '[encryption]: `config.strategy` is deprecated and will be removed in a future release — use `config.authStrategy` instead.',\n )\n}\n\n/**\n * Reset the once-per-process deprecation-warning latch. Test-only hook so\n * suites can assert the warning fires deterministically, independent of test\n * ordering. Not re-exported from the package entry, so it stays off the public\n * API surface.\n * @internal\n */\nexport function __resetStrategyDeprecationWarningForTests(): void {\n warnedStrategyDeprecated = false\n}\n\n/**\n * Creates and initializes an Encryption client for encrypting and decrypting data with CipherStash.\n *\n * Provide at least one schema (from {@link encryptedTable}) so the client knows which tables and\n * columns to use:\n *\n * ```typescript\n * import { Encryption, encryptedTable, encryptedColumn } from \"@cipherstash/stack\"\n *\n * const users = encryptedTable(\"users\", { email: encryptedColumn(\"email\") })\n * const client = await Encryption({ schemas: [users] })\n * const result = await client.encrypt(\"alice@example.com\", { column: users.email, table: users })\n * ```\n *\n * ## Authentication\n *\n * The snippets in this section reuse the `users` schema from the example above, and\n * `workspaceCrn` / `accessKey` stand in for your own workspace credentials (from the\n * [dashboard](https://dashboard.cipherstash.com) or the `CS_*` variables below).\n *\n * By default the client uses the `auto` auth strategy. `auto` first looks for the `CS_*`\n * environment variables (see below) and, if they are not set, falls back to the local **dev\n * profile** on your machine. The dev profile also supplies the client key, so during local\n * development you generally don't need to set any environment variables at all.\n *\n * ### Local development — create a dev profile\n *\n * Log in once to create the dev profile that `auto` picks up automatically:\n *\n * ```bash\n * npx stash auth login\n * ```\n *\n * ### Production / CI — environment variables\n *\n * In production and CI you typically authenticate with the four `CS_*` environment variables\n * instead of a dev profile. Developers can obtain these values from the\n * [CipherStash dashboard](https://dashboard.cipherstash.com):\n *\n * | Environment variable | Description |\n * | ---------------------- | ------------------------------------------------------------------------------ |\n * | `CS_WORKSPACE_CRN` | The workspace Cloud Resource Name (CRN) that identifies your workspace. |\n * | `CS_CLIENT_ID` | The client identifier issued when you create an access key. |\n * | `CS_CLIENT_KEY` | The client key material combined with ZeroKMS to perform encryption. |\n * | `CS_CLIENT_ACCESS_KEY` | The API access key used to authenticate requests to CipherStash. |\n *\n * When these are set, `auto` uses them in preference to the local dev profile.\n *\n * ### Custom auth strategies — `config.authStrategy`\n *\n * For finer control, pass an explicit strategy via `config.authStrategy` (from `@cipherstash/auth`,\n * re-exported by `@cipherstash/stack`). See the `@cipherstash/auth` package for the full list. Two\n * common choices:\n *\n * `AccessKeyStrategy` — like `auto`, but only ever uses an access key; it never falls back to the\n * local dev profile. Ideal for services and CI:\n *\n * ```typescript\n * import { Encryption, AccessKeyStrategy } from \"@cipherstash/stack\"\n *\n * const client = await Encryption({\n * schemas: [users],\n * config: {\n * authStrategy: AccessKeyStrategy.create(workspaceCrn, accessKey),\n * },\n * })\n * ```\n *\n * `OidcFederationStrategy` — authenticate end users through your own identity provider (Supabase,\n * Clerk, Auth0 or Okta) by federating their OIDC JWT into a CipherStash token. Add the provider to\n * your workspace first at\n * [dashboard.cipherstash.com/workspaces/_/oidc-providers](https://dashboard.cipherstash.com/workspaces/_/oidc-providers)\n * (the `_` in the URL resolves to whichever workspace you select):\n *\n * ```typescript\n * import { Encryption, OidcFederationStrategy } from \"@cipherstash/stack\"\n *\n * // Authenticate every ZeroKMS request as the signed-in user.\n * const client = await Encryption({\n * schemas: [users],\n * config: {\n * authStrategy: OidcFederationStrategy.create(workspaceCrn, () => getUserJwt()),\n * },\n * })\n * ```\n *\n * ### Lock context (identity-bound encryption)\n *\n * Lock context is an **additional** capability layered on top of `OidcFederationStrategy`: it\n * requires that strategy, but `OidcFederationStrategy` does not require lock context. It binds a\n * value to a claim from the user's JWT (typically `sub`) so that only the user who encrypted a\n * value can decrypt it:\n *\n * ```typescript\n * // Bind the data key to the user's `sub` claim.\n * const result = await client\n * .encrypt(\"alice@example.com\", { column: users.email, table: users })\n * .withLockContext({ identityClaim: [\"sub\"] })\n * ```\n *\n * Because the lock is tied to a specific end user's identity, `AccessKeyStrategy` (which\n * authenticates a service, not a user) is not valid for lock context — there is no user `sub`\n * claim to bind to.\n *\n * ## Keysets (multi-tenant isolation)\n *\n * Pass `config.keyset` to encrypt under a specific **keyset** — a named or UUID-identified keyspace\n * that gives each tenant its own cryptographic isolation, so data encrypted under one keyset cannot\n * be decrypted under another. Create and manage keysets in the\n * [dashboard](https://dashboard.cipherstash.com/workspaces/_/keysets) (the `_` in the URL resolves\n * to whichever workspace you select); omit `config.keyset` to use the workspace's default keyset.\n *\n * ```typescript\n * // `users` is the schema from the first example above.\n * const client = await Encryption({\n * schemas: [users],\n * config: {\n * keyset: { name: \"tenant-a\" }, // or { id: \"<uuid>\" }\n * },\n * })\n * ```\n *\n * A client is bound to a single keyset for its lifetime, so multi-tenant applications use **one\n * `Encryption()` client per tenant**. Keysets are orthogonal to `authStrategy` and lock context —\n * they isolate a whole tenant's *keyspace* (coarse, fixed per client), whereas lock context binds\n * an individual value to a user's identity claim (fine-grained, per operation) — and can be\n * combined with both.\n *\n * @param config - Initialization options. Must include `schemas`; optionally include `config` for\n * credentials and authentication. Logging is configured via the `STASH_STACK_LOG` environment\n * variable (`debug | info | error`, default: `error`).\n * @returns A Promise that resolves to an initialized {@link EncryptionClient} ready for\n * {@link EncryptionClient.encrypt}, {@link EncryptionClient.decrypt}, and related operations.\n *\n * @throws Throws if `schemas` is empty, or if a keyset `id` is supplied but is not a valid UUID.\n * Also throws if the client fails to initialize (e.g. invalid credentials or config).\n *\n * @see {@link EncryptionClientConfig} for full config options.\n * @see {@link ClientConfig.authStrategy} for the auth strategy field.\n * @see {@link EncryptionClient} for available methods after initialization.\n */\nexport const Encryption = async (\n config: EncryptionClientConfig,\n): Promise<EncryptionClient> => {\n const { schemas, config: clientConfig } = config\n\n if (!schemas.length) {\n throw new Error(\n '[encryption]: At least one encryptedTable must be provided to initialize the encryption client',\n )\n }\n\n if (\n clientConfig?.keyset &&\n 'id' in clientConfig.keyset &&\n !uuidValidate(clientConfig.keyset.id)\n ) {\n throw new Error(\n '[encryption]: Invalid UUID provided for keyset id. Must be a valid UUID.',\n )\n }\n\n // Resolve the auth strategy, honouring the deprecated `strategy` alias.\n // Warn whenever the deprecated field is present at all — even alongside\n // `authStrategy` — so the leftover field gets cleaned up. `authStrategy`\n // still wins when both are set.\n if (clientConfig?.strategy) {\n warnStrategyDeprecated()\n }\n const authStrategy = clientConfig?.authStrategy ?? clientConfig?.strategy\n\n const client = new EncryptionClient()\n const encryptConfig = buildEncryptConfig(...schemas)\n\n // Resolve the wire format for this client: an explicit\n // `config.eqlVersion` wins; otherwise it is auto-detected from the\n // schema set (v3 tables → 3, v2 tables → the FFI's v2 default). A mixed\n // v2 + v3 schema set throws — one client emits exactly one wire format.\n const eqlVersion = resolveEqlVersion(schemas, clientConfig?.eqlVersion)\n\n const result = await client.init({\n encryptConfig,\n ...clientConfig,\n authStrategy,\n eqlVersion,\n })\n\n if (result.failure) {\n throw new Error(`[encryption]: ${result.failure.message}`)\n }\n\n return result.data\n}\n","export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;\n","import REGEX from './regex.js';\nfunction validate(uuid) {\n return typeof uuid === 'string' && REGEX.test(uuid);\n}\nexport default validate;\n","export * from \"./errors.js\";\nexport * from \"./helpers/parseUtil.js\";\nexport * from \"./helpers/typeAliases.js\";\nexport * from \"./helpers/util.js\";\nexport * from \"./types.js\";\nexport * from \"./ZodError.js\";\n","export var util;\n(function (util) {\n util.assertEqual = (_) => { };\n function assertIs(_arg) { }\n util.assertIs = assertIs;\n function assertNever(_x) {\n throw new Error();\n }\n util.assertNever = assertNever;\n util.arrayToEnum = (items) => {\n const obj = {};\n for (const item of items) {\n obj[item] = item;\n }\n return obj;\n };\n util.getValidEnumValues = (obj) => {\n const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== \"number\");\n const filtered = {};\n for (const k of validKeys) {\n filtered[k] = obj[k];\n }\n return util.objectValues(filtered);\n };\n util.objectValues = (obj) => {\n return util.objectKeys(obj).map(function (e) {\n return obj[e];\n });\n };\n util.objectKeys = typeof Object.keys === \"function\" // eslint-disable-line ban/ban\n ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban\n : (object) => {\n const keys = [];\n for (const key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n keys.push(key);\n }\n }\n return keys;\n };\n util.find = (arr, checker) => {\n for (const item of arr) {\n if (checker(item))\n return item;\n }\n return undefined;\n };\n util.isInteger = typeof Number.isInteger === \"function\"\n ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban\n : (val) => typeof val === \"number\" && Number.isFinite(val) && Math.floor(val) === val;\n function joinValues(array, separator = \" | \") {\n return array.map((val) => (typeof val === \"string\" ? `'${val}'` : val)).join(separator);\n }\n util.joinValues = joinValues;\n util.jsonStringifyReplacer = (_, value) => {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n return value;\n };\n})(util || (util = {}));\nexport var objectUtil;\n(function (objectUtil) {\n objectUtil.mergeShapes = (first, second) => {\n return {\n ...first,\n ...second, // second overwrites first\n };\n };\n})(objectUtil || (objectUtil = {}));\nexport const ZodParsedType = util.arrayToEnum([\n \"string\",\n \"nan\",\n \"number\",\n \"integer\",\n \"float\",\n \"boolean\",\n \"date\",\n \"bigint\",\n \"symbol\",\n \"function\",\n \"undefined\",\n \"null\",\n \"array\",\n \"object\",\n \"unknown\",\n \"promise\",\n \"void\",\n \"never\",\n \"map\",\n \"set\",\n]);\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return ZodParsedType.undefined;\n case \"string\":\n return ZodParsedType.string;\n case \"number\":\n return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;\n case \"boolean\":\n return ZodParsedType.boolean;\n case \"function\":\n return ZodParsedType.function;\n case \"bigint\":\n return ZodParsedType.bigint;\n case \"symbol\":\n return ZodParsedType.symbol;\n case \"object\":\n if (Array.isArray(data)) {\n return ZodParsedType.array;\n }\n if (data === null) {\n return ZodParsedType.null;\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return ZodParsedType.promise;\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return ZodParsedType.map;\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return ZodParsedType.set;\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return ZodParsedType.date;\n }\n return ZodParsedType.object;\n default:\n return ZodParsedType.unknown;\n }\n};\n","import { util } from \"./helpers/util.js\";\nexport const ZodIssueCode = util.arrayToEnum([\n \"invalid_type\",\n \"invalid_literal\",\n \"custom\",\n \"invalid_union\",\n \"invalid_union_discriminator\",\n \"invalid_enum_value\",\n \"unrecognized_keys\",\n \"invalid_arguments\",\n \"invalid_return_type\",\n \"invalid_date\",\n \"invalid_string\",\n \"too_small\",\n \"too_big\",\n \"invalid_intersection_types\",\n \"not_multiple_of\",\n \"not_finite\",\n]);\nexport const quotelessJson = (obj) => {\n const json = JSON.stringify(obj, null, 2);\n return json.replace(/\"([^\"]+)\":/g, \"$1:\");\n};\nexport class ZodError extends Error {\n get errors() {\n return this.issues;\n }\n constructor(issues) {\n super();\n this.issues = [];\n this.addIssue = (sub) => {\n this.issues = [...this.issues, sub];\n };\n this.addIssues = (subs = []) => {\n this.issues = [...this.issues, ...subs];\n };\n const actualProto = new.target.prototype;\n if (Object.setPrototypeOf) {\n // eslint-disable-next-line ban/ban\n Object.setPrototypeOf(this, actualProto);\n }\n else {\n this.__proto__ = actualProto;\n }\n this.name = \"ZodError\";\n this.issues = issues;\n }\n format(_mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\") {\n issue.unionErrors.map(processError);\n }\n else if (issue.code === \"invalid_return_type\") {\n processError(issue.returnTypeError);\n }\n else if (issue.code === \"invalid_arguments\") {\n processError(issue.argumentsError);\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n // if (typeof el === \"string\") {\n // curr[el] = curr[el] || { _errors: [] };\n // } else if (typeof el === \"number\") {\n // const errorArray: any = [];\n // errorArray._errors = [];\n // curr[el] = curr[el] || errorArray;\n // }\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(this);\n return fieldErrors;\n }\n static assert(value) {\n if (!(value instanceof ZodError)) {\n throw new Error(`Not a ZodError: ${value}`);\n }\n }\n toString() {\n return this.message;\n }\n get message() {\n return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);\n }\n get isEmpty() {\n return this.issues.length === 0;\n }\n flatten(mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of this.issues) {\n if (sub.path.length > 0) {\n const firstEl = sub.path[0];\n fieldErrors[firstEl] = fieldErrors[firstEl] || [];\n fieldErrors[firstEl].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n }\n get formErrors() {\n return this.flatten();\n }\n}\nZodError.create = (issues) => {\n const error = new ZodError(issues);\n return error;\n};\n","import { ZodIssueCode } from \"../ZodError.js\";\nimport { util, ZodParsedType } from \"../helpers/util.js\";\nconst errorMap = (issue, _ctx) => {\n let message;\n switch (issue.code) {\n case ZodIssueCode.invalid_type:\n if (issue.received === ZodParsedType.undefined) {\n message = \"Required\";\n }\n else {\n message = `Expected ${issue.expected}, received ${issue.received}`;\n }\n break;\n case ZodIssueCode.invalid_literal:\n message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;\n break;\n case ZodIssueCode.unrecognized_keys:\n message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, \", \")}`;\n break;\n case ZodIssueCode.invalid_union:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_union_discriminator:\n message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;\n break;\n case ZodIssueCode.invalid_enum_value:\n message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;\n break;\n case ZodIssueCode.invalid_arguments:\n message = `Invalid function arguments`;\n break;\n case ZodIssueCode.invalid_return_type:\n message = `Invalid function return type`;\n break;\n case ZodIssueCode.invalid_date:\n message = `Invalid date`;\n break;\n case ZodIssueCode.invalid_string:\n if (typeof issue.validation === \"object\") {\n if (\"includes\" in issue.validation) {\n message = `Invalid input: must include \"${issue.validation.includes}\"`;\n if (typeof issue.validation.position === \"number\") {\n message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;\n }\n }\n else if (\"startsWith\" in issue.validation) {\n message = `Invalid input: must start with \"${issue.validation.startsWith}\"`;\n }\n else if (\"endsWith\" in issue.validation) {\n message = `Invalid input: must end with \"${issue.validation.endsWith}\"`;\n }\n else {\n util.assertNever(issue.validation);\n }\n }\n else if (issue.validation !== \"regex\") {\n message = `Invalid ${issue.validation}`;\n }\n else {\n message = \"Invalid\";\n }\n break;\n case ZodIssueCode.too_small:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n else if (issue.type === \"bigint\")\n message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.too_big:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n else if (issue.type === \"bigint\")\n message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.custom:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_intersection_types:\n message = `Intersection results could not be merged`;\n break;\n case ZodIssueCode.not_multiple_of:\n message = `Number must be a multiple of ${issue.multipleOf}`;\n break;\n case ZodIssueCode.not_finite:\n message = \"Number must be finite\";\n break;\n default:\n message = _ctx.defaultError;\n util.assertNever(issue);\n }\n return { message };\n};\nexport default errorMap;\n","import defaultErrorMap from \"./locales/en.js\";\nlet overrideErrorMap = defaultErrorMap;\nexport { defaultErrorMap };\nexport function setErrorMap(map) {\n overrideErrorMap = map;\n}\nexport function getErrorMap() {\n return overrideErrorMap;\n}\n","import { getErrorMap } from \"../errors.js\";\nimport defaultErrorMap from \"../locales/en.js\";\nexport const makeIssue = (params) => {\n const { data, path, errorMaps, issueData } = params;\n const fullPath = [...path, ...(issueData.path || [])];\n const fullIssue = {\n ...issueData,\n path: fullPath,\n };\n if (issueData.message !== undefined) {\n return {\n ...issueData,\n path: fullPath,\n message: issueData.message,\n };\n }\n let errorMessage = \"\";\n const maps = errorMaps\n .filter((m) => !!m)\n .slice()\n .reverse();\n for (const map of maps) {\n errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;\n }\n return {\n ...issueData,\n path: fullPath,\n message: errorMessage,\n };\n};\nexport const EMPTY_PATH = [];\nexport function addIssueToContext(ctx, issueData) {\n const overrideMap = getErrorMap();\n const issue = makeIssue({\n issueData: issueData,\n data: ctx.data,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap, // contextual error map is first priority\n ctx.schemaErrorMap, // then schema-bound map if available\n overrideMap, // then global override map\n overrideMap === defaultErrorMap ? undefined : defaultErrorMap, // then global default map\n ].filter((x) => !!x),\n });\n ctx.common.issues.push(issue);\n}\nexport class ParseStatus {\n constructor() {\n this.value = \"valid\";\n }\n dirty() {\n if (this.value === \"valid\")\n this.value = \"dirty\";\n }\n abort() {\n if (this.value !== \"aborted\")\n this.value = \"aborted\";\n }\n static mergeArray(status, results) {\n const arrayValue = [];\n for (const s of results) {\n if (s.status === \"aborted\")\n return INVALID;\n if (s.status === \"dirty\")\n status.dirty();\n arrayValue.push(s.value);\n }\n return { status: status.value, value: arrayValue };\n }\n static async mergeObjectAsync(status, pairs) {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n });\n }\n return ParseStatus.mergeObjectSync(status, syncPairs);\n }\n static mergeObjectSync(status, pairs) {\n const finalObject = {};\n for (const pair of pairs) {\n const { key, value } = pair;\n if (key.status === \"aborted\")\n return INVALID;\n if (value.status === \"aborted\")\n return INVALID;\n if (key.status === \"dirty\")\n status.dirty();\n if (value.status === \"dirty\")\n status.dirty();\n if (key.value !== \"__proto__\" && (typeof value.value !== \"undefined\" || pair.alwaysSet)) {\n finalObject[key.value] = value.value;\n }\n }\n return { status: status.value, value: finalObject };\n }\n}\nexport const INVALID = Object.freeze({\n status: \"aborted\",\n});\nexport const DIRTY = (value) => ({ status: \"dirty\", value });\nexport const OK = (value) => ({ status: \"valid\", value });\nexport const isAborted = (x) => x.status === \"aborted\";\nexport const isDirty = (x) => x.status === \"dirty\";\nexport const isValid = (x) => x.status === \"valid\";\nexport const isAsync = (x) => typeof Promise !== \"undefined\" && x instanceof Promise;\n","export var errorUtil;\n(function (errorUtil) {\n errorUtil.errToObj = (message) => typeof message === \"string\" ? { message } : message || {};\n // biome-ignore lint:\n errorUtil.toString = (message) => typeof message === \"string\" ? message : message?.message;\n})(errorUtil || (errorUtil = {}));\n","import { ZodError, ZodIssueCode, } from \"./ZodError.js\";\nimport { defaultErrorMap, getErrorMap } from \"./errors.js\";\nimport { errorUtil } from \"./helpers/errorUtil.js\";\nimport { DIRTY, INVALID, OK, ParseStatus, addIssueToContext, isAborted, isAsync, isDirty, isValid, makeIssue, } from \"./helpers/parseUtil.js\";\nimport { util, ZodParsedType, getParsedType } from \"./helpers/util.js\";\nclass ParseInputLazyPath {\n constructor(parent, value, path, key) {\n this._cachedPath = [];\n this.parent = parent;\n this.data = value;\n this._path = path;\n this._key = key;\n }\n get path() {\n if (!this._cachedPath.length) {\n if (Array.isArray(this._key)) {\n this._cachedPath.push(...this._path, ...this._key);\n }\n else {\n this._cachedPath.push(...this._path, this._key);\n }\n }\n return this._cachedPath;\n }\n}\nconst handleResult = (ctx, result) => {\n if (isValid(result)) {\n return { success: true, data: result.value };\n }\n else {\n if (!ctx.common.issues.length) {\n throw new Error(\"Validation failed but no issues detected.\");\n }\n return {\n success: false,\n get error() {\n if (this._error)\n return this._error;\n const error = new ZodError(ctx.common.issues);\n this._error = error;\n return this._error;\n },\n };\n }\n};\nfunction processCreateParams(params) {\n if (!params)\n return {};\n const { errorMap, invalid_type_error, required_error, description } = params;\n if (errorMap && (invalid_type_error || required_error)) {\n throw new Error(`Can't use \"invalid_type_error\" or \"required_error\" in conjunction with custom error map.`);\n }\n if (errorMap)\n return { errorMap: errorMap, description };\n const customMap = (iss, ctx) => {\n const { message } = params;\n if (iss.code === \"invalid_enum_value\") {\n return { message: message ?? ctx.defaultError };\n }\n if (typeof ctx.data === \"undefined\") {\n return { message: message ?? required_error ?? ctx.defaultError };\n }\n if (iss.code !== \"invalid_type\")\n return { message: ctx.defaultError };\n return { message: message ?? invalid_type_error ?? ctx.defaultError };\n };\n return { errorMap: customMap, description };\n}\nexport class ZodType {\n get description() {\n return this._def.description;\n }\n _getType(input) {\n return getParsedType(input.data);\n }\n _getOrReturnCtx(input, ctx) {\n return (ctx || {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n });\n }\n _processInputParams(input) {\n return {\n status: new ParseStatus(),\n ctx: {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n },\n };\n }\n _parseSync(input) {\n const result = this._parse(input);\n if (isAsync(result)) {\n throw new Error(\"Synchronous parse encountered promise.\");\n }\n return result;\n }\n _parseAsync(input) {\n const result = this._parse(input);\n return Promise.resolve(result);\n }\n parse(data, params) {\n const result = this.safeParse(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n safeParse(data, params) {\n const ctx = {\n common: {\n issues: [],\n async: params?.async ?? false,\n contextualErrorMap: params?.errorMap,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const result = this._parseSync({ data, path: ctx.path, parent: ctx });\n return handleResult(ctx, result);\n }\n \"~validate\"(data) {\n const ctx = {\n common: {\n issues: [],\n async: !!this[\"~standard\"].async,\n },\n path: [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n if (!this[\"~standard\"].async) {\n try {\n const result = this._parseSync({ data, path: [], parent: ctx });\n return isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n };\n }\n catch (err) {\n if (err?.message?.toLowerCase()?.includes(\"encountered\")) {\n this[\"~standard\"].async = true;\n }\n ctx.common = {\n issues: [],\n async: true,\n };\n }\n }\n return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n });\n }\n async parseAsync(data, params) {\n const result = await this.safeParseAsync(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n async safeParseAsync(data, params) {\n const ctx = {\n common: {\n issues: [],\n contextualErrorMap: params?.errorMap,\n async: true,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });\n const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));\n return handleResult(ctx, result);\n }\n refine(check, message) {\n const getIssueProperties = (val) => {\n if (typeof message === \"string\" || typeof message === \"undefined\") {\n return { message };\n }\n else if (typeof message === \"function\") {\n return message(val);\n }\n else {\n return message;\n }\n };\n return this._refinement((val, ctx) => {\n const result = check(val);\n const setError = () => ctx.addIssue({\n code: ZodIssueCode.custom,\n ...getIssueProperties(val),\n });\n if (typeof Promise !== \"undefined\" && result instanceof Promise) {\n return result.then((data) => {\n if (!data) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n if (!result) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n refinement(check, refinementData) {\n return this._refinement((val, ctx) => {\n if (!check(val)) {\n ctx.addIssue(typeof refinementData === \"function\" ? refinementData(val, ctx) : refinementData);\n return false;\n }\n else {\n return true;\n }\n });\n }\n _refinement(refinement) {\n return new ZodEffects({\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"refinement\", refinement },\n });\n }\n superRefine(refinement) {\n return this._refinement(refinement);\n }\n constructor(def) {\n /** Alias of safeParseAsync */\n this.spa = this.safeParseAsync;\n this._def = def;\n this.parse = this.parse.bind(this);\n this.safeParse = this.safeParse.bind(this);\n this.parseAsync = this.parseAsync.bind(this);\n this.safeParseAsync = this.safeParseAsync.bind(this);\n this.spa = this.spa.bind(this);\n this.refine = this.refine.bind(this);\n this.refinement = this.refinement.bind(this);\n this.superRefine = this.superRefine.bind(this);\n this.optional = this.optional.bind(this);\n this.nullable = this.nullable.bind(this);\n this.nullish = this.nullish.bind(this);\n this.array = this.array.bind(this);\n this.promise = this.promise.bind(this);\n this.or = this.or.bind(this);\n this.and = this.and.bind(this);\n this.transform = this.transform.bind(this);\n this.brand = this.brand.bind(this);\n this.default = this.default.bind(this);\n this.catch = this.catch.bind(this);\n this.describe = this.describe.bind(this);\n this.pipe = this.pipe.bind(this);\n this.readonly = this.readonly.bind(this);\n this.isNullable = this.isNullable.bind(this);\n this.isOptional = this.isOptional.bind(this);\n this[\"~standard\"] = {\n version: 1,\n vendor: \"zod\",\n validate: (data) => this[\"~validate\"](data),\n };\n }\n optional() {\n return ZodOptional.create(this, this._def);\n }\n nullable() {\n return ZodNullable.create(this, this._def);\n }\n nullish() {\n return this.nullable().optional();\n }\n array() {\n return ZodArray.create(this);\n }\n promise() {\n return ZodPromise.create(this, this._def);\n }\n or(option) {\n return ZodUnion.create([this, option], this._def);\n }\n and(incoming) {\n return ZodIntersection.create(this, incoming, this._def);\n }\n transform(transform) {\n return new ZodEffects({\n ...processCreateParams(this._def),\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"transform\", transform },\n });\n }\n default(def) {\n const defaultValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodDefault({\n ...processCreateParams(this._def),\n innerType: this,\n defaultValue: defaultValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n });\n }\n brand() {\n return new ZodBranded({\n typeName: ZodFirstPartyTypeKind.ZodBranded,\n type: this,\n ...processCreateParams(this._def),\n });\n }\n catch(def) {\n const catchValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodCatch({\n ...processCreateParams(this._def),\n innerType: this,\n catchValue: catchValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n });\n }\n describe(description) {\n const This = this.constructor;\n return new This({\n ...this._def,\n description,\n });\n }\n pipe(target) {\n return ZodPipeline.create(this, target);\n }\n readonly() {\n return ZodReadonly.create(this);\n }\n isOptional() {\n return this.safeParse(undefined).success;\n }\n isNullable() {\n return this.safeParse(null).success;\n }\n}\nconst cuidRegex = /^c[^\\s-]{8,}$/i;\nconst cuid2Regex = /^[0-9a-z]+$/;\nconst ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;\n// const uuidRegex =\n// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;\nconst uuidRegex = /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/i;\nconst nanoidRegex = /^[a-z0-9_-]{21}$/i;\nconst jwtRegex = /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/;\nconst durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n// from https://stackoverflow.com/a/46181/1550155\n// old version: too slow, didn't support unicode\n// const emailRegex = /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i;\n//old email regex\n// const emailRegex = /^(([^<>()[\\].,;:\\s@\"]+(\\.[^<>()[\\].,;:\\s@\"]+)*)|(\".+\"))@((?!-)([^<>()[\\].,;:\\s@\"]+\\.)+[^<>()[\\].,;:\\s@\"]{1,})[^-<>()[\\].,;:\\s@\"]$/i;\n// eslint-disable-next-line\n// const emailRegex =\n// /^(([^<>()[\\]\\\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\])|(\\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\\.[A-Za-z]{2,})+))$/;\n// const emailRegex =\n// /^[a-zA-Z0-9\\.\\!\\#\\$\\%\\&\\'\\*\\+\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~\\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// const emailRegex =\n// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$/i;\nconst emailRegex = /^(?!\\.)(?!.*\\.\\.)([A-Z0-9_'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i;\n// const emailRegex =\n// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\\.[a-z0-9\\-]+)*$/i;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emojiRegex = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nlet emojiRegex;\n// faster, simpler, safer\nconst ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nconst ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/;\n// const ipv6Regex =\n// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;\nconst ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3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,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nconst base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\n// https://base64.guru/standards/base64url\nconst base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;\n// simple\n// const dateRegexSource = `\\\\d{4}-\\\\d{2}-\\\\d{2}`;\n// no leap year validation\n// const dateRegexSource = `\\\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\\\d|2\\\\d))`;\n// with leap year validation\nconst dateRegexSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateRegex = new RegExp(`^${dateRegexSource}$`);\nfunction timeRegexSource(args) {\n let secondsRegexSource = `[0-5]\\\\d`;\n if (args.precision) {\n secondsRegexSource = `${secondsRegexSource}\\\\.\\\\d{${args.precision}}`;\n }\n else if (args.precision == null) {\n secondsRegexSource = `${secondsRegexSource}(\\\\.\\\\d+)?`;\n }\n const secondsQuantifier = args.precision ? \"+\" : \"?\"; // require seconds if precision is nonzero\n return `([01]\\\\d|2[0-3]):[0-5]\\\\d(:${secondsRegexSource})${secondsQuantifier}`;\n}\nfunction timeRegex(args) {\n return new RegExp(`^${timeRegexSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetimeRegex(args) {\n let regex = `${dateRegexSource}T${timeRegexSource(args)}`;\n const opts = [];\n opts.push(args.local ? `Z?` : `Z`);\n if (args.offset)\n opts.push(`([+-]\\\\d{2}:?\\\\d{2})`);\n regex = `${regex}(${opts.join(\"|\")})`;\n return new RegExp(`^${regex}$`);\n}\nfunction isValidIP(ip, version) {\n if ((version === \"v4\" || !version) && ipv4Regex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6Regex.test(ip)) {\n return true;\n }\n return false;\n}\nfunction isValidJWT(jwt, alg) {\n if (!jwtRegex.test(jwt))\n return false;\n try {\n const [header] = jwt.split(\".\");\n if (!header)\n return false;\n // Convert base64url to base64\n const base64 = header\n .replace(/-/g, \"+\")\n .replace(/_/g, \"/\")\n .padEnd(header.length + ((4 - (header.length % 4)) % 4), \"=\");\n const decoded = JSON.parse(atob(base64));\n if (typeof decoded !== \"object\" || decoded === null)\n return false;\n if (\"typ\" in decoded && decoded?.typ !== \"JWT\")\n return false;\n if (!decoded.alg)\n return false;\n if (alg && decoded.alg !== alg)\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nfunction isValidCidr(ip, version) {\n if ((version === \"v4\" || !version) && ipv4CidrRegex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6CidrRegex.test(ip)) {\n return true;\n }\n return false;\n}\nexport class ZodString extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = String(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.string) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.string,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.length < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.length > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"length\") {\n const tooBig = input.data.length > check.value;\n const tooSmall = input.data.length < check.value;\n if (tooBig || tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n if (tooBig) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n else if (tooSmall) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n status.dirty();\n }\n }\n else if (check.kind === \"email\") {\n if (!emailRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"email\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"emoji\") {\n if (!emojiRegex) {\n emojiRegex = new RegExp(_emojiRegex, \"u\");\n }\n if (!emojiRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"emoji\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"uuid\") {\n if (!uuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"uuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"nanoid\") {\n if (!nanoidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"nanoid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid\") {\n if (!cuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid2\") {\n if (!cuid2Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid2\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ulid\") {\n if (!ulidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ulid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"url\") {\n try {\n new URL(input.data);\n }\n catch {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"regex\") {\n check.regex.lastIndex = 0;\n const testResult = check.regex.test(input.data);\n if (!testResult) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"regex\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"trim\") {\n input.data = input.data.trim();\n }\n else if (check.kind === \"includes\") {\n if (!input.data.includes(check.value, check.position)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { includes: check.value, position: check.position },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"toLowerCase\") {\n input.data = input.data.toLowerCase();\n }\n else if (check.kind === \"toUpperCase\") {\n input.data = input.data.toUpperCase();\n }\n else if (check.kind === \"startsWith\") {\n if (!input.data.startsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { startsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"endsWith\") {\n if (!input.data.endsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { endsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"datetime\") {\n const regex = datetimeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"datetime\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"date\") {\n const regex = dateRegex;\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"date\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"time\") {\n const regex = timeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"time\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"duration\") {\n if (!durationRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"duration\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ip\") {\n if (!isValidIP(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ip\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"jwt\") {\n if (!isValidJWT(input.data, check.alg)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"jwt\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cidr\") {\n if (!isValidCidr(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cidr\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64\") {\n if (!base64Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64url\") {\n if (!base64urlRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _regex(regex, validation, message) {\n return this.refinement((data) => regex.test(data), {\n validation,\n code: ZodIssueCode.invalid_string,\n ...errorUtil.errToObj(message),\n });\n }\n _addCheck(check) {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n email(message) {\n return this._addCheck({ kind: \"email\", ...errorUtil.errToObj(message) });\n }\n url(message) {\n return this._addCheck({ kind: \"url\", ...errorUtil.errToObj(message) });\n }\n emoji(message) {\n return this._addCheck({ kind: \"emoji\", ...errorUtil.errToObj(message) });\n }\n uuid(message) {\n return this._addCheck({ kind: \"uuid\", ...errorUtil.errToObj(message) });\n }\n nanoid(message) {\n return this._addCheck({ kind: \"nanoid\", ...errorUtil.errToObj(message) });\n }\n cuid(message) {\n return this._addCheck({ kind: \"cuid\", ...errorUtil.errToObj(message) });\n }\n cuid2(message) {\n return this._addCheck({ kind: \"cuid2\", ...errorUtil.errToObj(message) });\n }\n ulid(message) {\n return this._addCheck({ kind: \"ulid\", ...errorUtil.errToObj(message) });\n }\n base64(message) {\n return this._addCheck({ kind: \"base64\", ...errorUtil.errToObj(message) });\n }\n base64url(message) {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return this._addCheck({\n kind: \"base64url\",\n ...errorUtil.errToObj(message),\n });\n }\n jwt(options) {\n return this._addCheck({ kind: \"jwt\", ...errorUtil.errToObj(options) });\n }\n ip(options) {\n return this._addCheck({ kind: \"ip\", ...errorUtil.errToObj(options) });\n }\n cidr(options) {\n return this._addCheck({ kind: \"cidr\", ...errorUtil.errToObj(options) });\n }\n datetime(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"datetime\",\n precision: null,\n offset: false,\n local: false,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"datetime\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n offset: options?.offset ?? false,\n local: options?.local ?? false,\n ...errorUtil.errToObj(options?.message),\n });\n }\n date(message) {\n return this._addCheck({ kind: \"date\", message });\n }\n time(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"time\",\n precision: null,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"time\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n ...errorUtil.errToObj(options?.message),\n });\n }\n duration(message) {\n return this._addCheck({ kind: \"duration\", ...errorUtil.errToObj(message) });\n }\n regex(regex, message) {\n return this._addCheck({\n kind: \"regex\",\n regex: regex,\n ...errorUtil.errToObj(message),\n });\n }\n includes(value, options) {\n return this._addCheck({\n kind: \"includes\",\n value: value,\n position: options?.position,\n ...errorUtil.errToObj(options?.message),\n });\n }\n startsWith(value, message) {\n return this._addCheck({\n kind: \"startsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n endsWith(value, message) {\n return this._addCheck({\n kind: \"endsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n min(minLength, message) {\n return this._addCheck({\n kind: \"min\",\n value: minLength,\n ...errorUtil.errToObj(message),\n });\n }\n max(maxLength, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxLength,\n ...errorUtil.errToObj(message),\n });\n }\n length(len, message) {\n return this._addCheck({\n kind: \"length\",\n value: len,\n ...errorUtil.errToObj(message),\n });\n }\n /**\n * Equivalent to `.min(1)`\n */\n nonempty(message) {\n return this.min(1, errorUtil.errToObj(message));\n }\n trim() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"trim\" }],\n });\n }\n toLowerCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toLowerCase\" }],\n });\n }\n toUpperCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toUpperCase\" }],\n });\n }\n get isDatetime() {\n return !!this._def.checks.find((ch) => ch.kind === \"datetime\");\n }\n get isDate() {\n return !!this._def.checks.find((ch) => ch.kind === \"date\");\n }\n get isTime() {\n return !!this._def.checks.find((ch) => ch.kind === \"time\");\n }\n get isDuration() {\n return !!this._def.checks.find((ch) => ch.kind === \"duration\");\n }\n get isEmail() {\n return !!this._def.checks.find((ch) => ch.kind === \"email\");\n }\n get isURL() {\n return !!this._def.checks.find((ch) => ch.kind === \"url\");\n }\n get isEmoji() {\n return !!this._def.checks.find((ch) => ch.kind === \"emoji\");\n }\n get isUUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"uuid\");\n }\n get isNANOID() {\n return !!this._def.checks.find((ch) => ch.kind === \"nanoid\");\n }\n get isCUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid\");\n }\n get isCUID2() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid2\");\n }\n get isULID() {\n return !!this._def.checks.find((ch) => ch.kind === \"ulid\");\n }\n get isIP() {\n return !!this._def.checks.find((ch) => ch.kind === \"ip\");\n }\n get isCIDR() {\n return !!this._def.checks.find((ch) => ch.kind === \"cidr\");\n }\n get isBase64() {\n return !!this._def.checks.find((ch) => ch.kind === \"base64\");\n }\n get isBase64url() {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return !!this._def.checks.find((ch) => ch.kind === \"base64url\");\n }\n get minLength() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxLength() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodString.create = (params) => {\n return new ZodString({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodString,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\n// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034\nfunction floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepDecCount = (step.toString().split(\".\")[1] || \"\").length;\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nexport class ZodNumber extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n this.step = this.multipleOf;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = Number(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.number) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.number,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"int\") {\n if (!util.isInteger(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: \"integer\",\n received: \"float\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (floatSafeRemainder(input.data, check.value) !== 0) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"finite\") {\n if (!Number.isFinite(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_finite,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodNumber({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodNumber({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n int(message) {\n return this._addCheck({\n kind: \"int\",\n message: errorUtil.toString(message),\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value: value,\n message: errorUtil.toString(message),\n });\n }\n finite(message) {\n return this._addCheck({\n kind: \"finite\",\n message: errorUtil.toString(message),\n });\n }\n safe(message) {\n return this._addCheck({\n kind: \"min\",\n inclusive: true,\n value: Number.MIN_SAFE_INTEGER,\n message: errorUtil.toString(message),\n })._addCheck({\n kind: \"max\",\n inclusive: true,\n value: Number.MAX_SAFE_INTEGER,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n get isInt() {\n return !!this._def.checks.find((ch) => ch.kind === \"int\" || (ch.kind === \"multipleOf\" && util.isInteger(ch.value)));\n }\n get isFinite() {\n let max = null;\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"finite\" || ch.kind === \"int\" || ch.kind === \"multipleOf\") {\n return true;\n }\n else if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n else if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return Number.isFinite(min) && Number.isFinite(max);\n }\n}\nZodNumber.create = (params) => {\n return new ZodNumber({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodNumber,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nexport class ZodBigInt extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n }\n _parse(input) {\n if (this._def.coerce) {\n try {\n input.data = BigInt(input.data);\n }\n catch {\n return this._getInvalidInput(input);\n }\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.bigint) {\n return this._getInvalidInput(input);\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n type: \"bigint\",\n minimum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n type: \"bigint\",\n maximum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (input.data % check.value !== BigInt(0)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _getInvalidInput(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.bigint,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodBigInt({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodBigInt({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodBigInt.create = (params) => {\n return new ZodBigInt({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodBigInt,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\nexport class ZodBoolean extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = Boolean(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.boolean) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.boolean,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodBoolean.create = (params) => {\n return new ZodBoolean({\n typeName: ZodFirstPartyTypeKind.ZodBoolean,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nexport class ZodDate extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = new Date(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.date) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.date,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (Number.isNaN(input.data.getTime())) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_date,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.getTime() < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n message: check.message,\n inclusive: true,\n exact: false,\n minimum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.getTime() > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n message: check.message,\n inclusive: true,\n exact: false,\n maximum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return {\n status: status.value,\n value: new Date(input.data.getTime()),\n };\n }\n _addCheck(check) {\n return new ZodDate({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n min(minDate, message) {\n return this._addCheck({\n kind: \"min\",\n value: minDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n max(maxDate, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n get minDate() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min != null ? new Date(min) : null;\n }\n get maxDate() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max != null ? new Date(max) : null;\n }\n}\nZodDate.create = (params) => {\n return new ZodDate({\n checks: [],\n coerce: params?.coerce || false,\n typeName: ZodFirstPartyTypeKind.ZodDate,\n ...processCreateParams(params),\n });\n};\nexport class ZodSymbol extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.symbol) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.symbol,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodSymbol.create = (params) => {\n return new ZodSymbol({\n typeName: ZodFirstPartyTypeKind.ZodSymbol,\n ...processCreateParams(params),\n });\n};\nexport class ZodUndefined extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.undefined,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodUndefined.create = (params) => {\n return new ZodUndefined({\n typeName: ZodFirstPartyTypeKind.ZodUndefined,\n ...processCreateParams(params),\n });\n};\nexport class ZodNull extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.null) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.null,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodNull.create = (params) => {\n return new ZodNull({\n typeName: ZodFirstPartyTypeKind.ZodNull,\n ...processCreateParams(params),\n });\n};\nexport class ZodAny extends ZodType {\n constructor() {\n super(...arguments);\n // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.\n this._any = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodAny.create = (params) => {\n return new ZodAny({\n typeName: ZodFirstPartyTypeKind.ZodAny,\n ...processCreateParams(params),\n });\n};\nexport class ZodUnknown extends ZodType {\n constructor() {\n super(...arguments);\n // required\n this._unknown = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodUnknown.create = (params) => {\n return new ZodUnknown({\n typeName: ZodFirstPartyTypeKind.ZodUnknown,\n ...processCreateParams(params),\n });\n};\nexport class ZodNever extends ZodType {\n _parse(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.never,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n}\nZodNever.create = (params) => {\n return new ZodNever({\n typeName: ZodFirstPartyTypeKind.ZodNever,\n ...processCreateParams(params),\n });\n};\nexport class ZodVoid extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.void,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodVoid.create = (params) => {\n return new ZodVoid({\n typeName: ZodFirstPartyTypeKind.ZodVoid,\n ...processCreateParams(params),\n });\n};\nexport class ZodArray extends ZodType {\n _parse(input) {\n const { ctx, status } = this._processInputParams(input);\n const def = this._def;\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (def.exactLength !== null) {\n const tooBig = ctx.data.length > def.exactLength.value;\n const tooSmall = ctx.data.length < def.exactLength.value;\n if (tooBig || tooSmall) {\n addIssueToContext(ctx, {\n code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,\n minimum: (tooSmall ? def.exactLength.value : undefined),\n maximum: (tooBig ? def.exactLength.value : undefined),\n type: \"array\",\n inclusive: true,\n exact: true,\n message: def.exactLength.message,\n });\n status.dirty();\n }\n }\n if (def.minLength !== null) {\n if (ctx.data.length < def.minLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.minLength.message,\n });\n status.dirty();\n }\n }\n if (def.maxLength !== null) {\n if (ctx.data.length > def.maxLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.maxLength.message,\n });\n status.dirty();\n }\n }\n if (ctx.common.async) {\n return Promise.all([...ctx.data].map((item, i) => {\n return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n })).then((result) => {\n return ParseStatus.mergeArray(status, result);\n });\n }\n const result = [...ctx.data].map((item, i) => {\n return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n });\n return ParseStatus.mergeArray(status, result);\n }\n get element() {\n return this._def.type;\n }\n min(minLength, message) {\n return new ZodArray({\n ...this._def,\n minLength: { value: minLength, message: errorUtil.toString(message) },\n });\n }\n max(maxLength, message) {\n return new ZodArray({\n ...this._def,\n maxLength: { value: maxLength, message: errorUtil.toString(message) },\n });\n }\n length(len, message) {\n return new ZodArray({\n ...this._def,\n exactLength: { value: len, message: errorUtil.toString(message) },\n });\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodArray.create = (schema, params) => {\n return new ZodArray({\n type: schema,\n minLength: null,\n maxLength: null,\n exactLength: null,\n typeName: ZodFirstPartyTypeKind.ZodArray,\n ...processCreateParams(params),\n });\n};\nfunction deepPartialify(schema) {\n if (schema instanceof ZodObject) {\n const newShape = {};\n for (const key in schema.shape) {\n const fieldSchema = schema.shape[key];\n newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));\n }\n return new ZodObject({\n ...schema._def,\n shape: () => newShape,\n });\n }\n else if (schema instanceof ZodArray) {\n return new ZodArray({\n ...schema._def,\n type: deepPartialify(schema.element),\n });\n }\n else if (schema instanceof ZodOptional) {\n return ZodOptional.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodNullable) {\n return ZodNullable.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodTuple) {\n return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));\n }\n else {\n return schema;\n }\n}\nexport class ZodObject extends ZodType {\n constructor() {\n super(...arguments);\n this._cached = null;\n /**\n * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.\n * If you want to pass through unknown properties, use `.passthrough()` instead.\n */\n this.nonstrict = this.passthrough;\n // extend<\n // Augmentation extends ZodRawShape,\n // NewOutput extends util.flatten<{\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // }>,\n // NewInput extends util.flatten<{\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }>\n // >(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<T, Augmentation>,\n // UnknownKeys,\n // Catchall,\n // NewOutput,\n // NewInput\n // > {\n // return new ZodObject({\n // ...this._def,\n // shape: () => ({\n // ...this._def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // }\n /**\n * @deprecated Use `.extend` instead\n * */\n this.augment = this.extend;\n }\n _getCached() {\n if (this._cached !== null)\n return this._cached;\n const shape = this._def.shape();\n const keys = util.objectKeys(shape);\n this._cached = { shape, keys };\n return this._cached;\n }\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.object) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const { status, ctx } = this._processInputParams(input);\n const { shape, keys: shapeKeys } = this._getCached();\n const extraKeys = [];\n if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === \"strip\")) {\n for (const key in ctx.data) {\n if (!shapeKeys.includes(key)) {\n extraKeys.push(key);\n }\n }\n }\n const pairs = [];\n for (const key of shapeKeys) {\n const keyValidator = shape[key];\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (this._def.catchall instanceof ZodNever) {\n const unknownKeys = this._def.unknownKeys;\n if (unknownKeys === \"passthrough\") {\n for (const key of extraKeys) {\n pairs.push({\n key: { status: \"valid\", value: key },\n value: { status: \"valid\", value: ctx.data[key] },\n });\n }\n }\n else if (unknownKeys === \"strict\") {\n if (extraKeys.length > 0) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.unrecognized_keys,\n keys: extraKeys,\n });\n status.dirty();\n }\n }\n else if (unknownKeys === \"strip\") {\n }\n else {\n throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);\n }\n }\n else {\n // run catchall validation\n const catchall = this._def.catchall;\n for (const key of extraKeys) {\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)\n ),\n alwaysSet: key in ctx.data,\n });\n }\n }\n if (ctx.common.async) {\n return Promise.resolve()\n .then(async () => {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n alwaysSet: pair.alwaysSet,\n });\n }\n return syncPairs;\n })\n .then((syncPairs) => {\n return ParseStatus.mergeObjectSync(status, syncPairs);\n });\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get shape() {\n return this._def.shape();\n }\n strict(message) {\n errorUtil.errToObj;\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strict\",\n ...(message !== undefined\n ? {\n errorMap: (issue, ctx) => {\n const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;\n if (issue.code === \"unrecognized_keys\")\n return {\n message: errorUtil.errToObj(message).message ?? defaultError,\n };\n return {\n message: defaultError,\n };\n },\n }\n : {}),\n });\n }\n strip() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strip\",\n });\n }\n passthrough() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"passthrough\",\n });\n }\n // const AugmentFactory =\n // <Def extends ZodObjectDef>(def: Def) =>\n // <Augmentation extends ZodRawShape>(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<ReturnType<Def[\"shape\"]>, Augmentation>,\n // Def[\"unknownKeys\"],\n // Def[\"catchall\"]\n // > => {\n // return new ZodObject({\n // ...def,\n // shape: () => ({\n // ...def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // };\n extend(augmentation) {\n return new ZodObject({\n ...this._def,\n shape: () => ({\n ...this._def.shape(),\n ...augmentation,\n }),\n });\n }\n /**\n * Prior to zod@1.0.12 there was a bug in the\n * inferred type of merged objects. Please\n * upgrade if you are experiencing issues.\n */\n merge(merging) {\n const merged = new ZodObject({\n unknownKeys: merging._def.unknownKeys,\n catchall: merging._def.catchall,\n shape: () => ({\n ...this._def.shape(),\n ...merging._def.shape(),\n }),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n });\n return merged;\n }\n // merge<\n // Incoming extends AnyZodObject,\n // Augmentation extends Incoming[\"shape\"],\n // NewOutput extends {\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // },\n // NewInput extends {\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }\n // >(\n // merging: Incoming\n // ): ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"],\n // NewOutput,\n // NewInput\n // > {\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n setKey(key, schema) {\n return this.augment({ [key]: schema });\n }\n // merge<Incoming extends AnyZodObject>(\n // merging: Incoming\n // ): //ZodObject<T & Incoming[\"_shape\"], UnknownKeys, Catchall> = (merging) => {\n // ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"]\n // > {\n // // const mergedShape = objectUtil.mergeShapes(\n // // this._def.shape(),\n // // merging._def.shape()\n // // );\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n catchall(index) {\n return new ZodObject({\n ...this._def,\n catchall: index,\n });\n }\n pick(mask) {\n const shape = {};\n for (const key of util.objectKeys(mask)) {\n if (mask[key] && this.shape[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n omit(mask) {\n const shape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (!mask[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n /**\n * @deprecated\n */\n deepPartial() {\n return deepPartialify(this);\n }\n partial(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n const fieldSchema = this.shape[key];\n if (mask && !mask[key]) {\n newShape[key] = fieldSchema;\n }\n else {\n newShape[key] = fieldSchema.optional();\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n required(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (mask && !mask[key]) {\n newShape[key] = this.shape[key];\n }\n else {\n const fieldSchema = this.shape[key];\n let newField = fieldSchema;\n while (newField instanceof ZodOptional) {\n newField = newField._def.innerType;\n }\n newShape[key] = newField;\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n keyof() {\n return createZodEnum(util.objectKeys(this.shape));\n }\n}\nZodObject.create = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.strictCreate = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strict\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.lazycreate = (shape, params) => {\n return new ZodObject({\n shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nexport class ZodUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const options = this._def.options;\n function handleResults(results) {\n // return first issue-free validation if it exists\n for (const result of results) {\n if (result.result.status === \"valid\") {\n return result.result;\n }\n }\n for (const result of results) {\n if (result.result.status === \"dirty\") {\n // add issues from dirty option\n ctx.common.issues.push(...result.ctx.common.issues);\n return result.result;\n }\n }\n // return invalid\n const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return Promise.all(options.map(async (option) => {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n return {\n result: await option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n }),\n ctx: childCtx,\n };\n })).then(handleResults);\n }\n else {\n let dirty = undefined;\n const issues = [];\n for (const option of options) {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n const result = option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n });\n if (result.status === \"valid\") {\n return result;\n }\n else if (result.status === \"dirty\" && !dirty) {\n dirty = { result, ctx: childCtx };\n }\n if (childCtx.common.issues.length) {\n issues.push(childCtx.common.issues);\n }\n }\n if (dirty) {\n ctx.common.issues.push(...dirty.ctx.common.issues);\n return dirty.result;\n }\n const unionErrors = issues.map((issues) => new ZodError(issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n }\n get options() {\n return this._def.options;\n }\n}\nZodUnion.create = (types, params) => {\n return new ZodUnion({\n options: types,\n typeName: ZodFirstPartyTypeKind.ZodUnion,\n ...processCreateParams(params),\n });\n};\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\n////////// //////////\n////////// ZodDiscriminatedUnion //////////\n////////// //////////\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\nconst getDiscriminator = (type) => {\n if (type instanceof ZodLazy) {\n return getDiscriminator(type.schema);\n }\n else if (type instanceof ZodEffects) {\n return getDiscriminator(type.innerType());\n }\n else if (type instanceof ZodLiteral) {\n return [type.value];\n }\n else if (type instanceof ZodEnum) {\n return type.options;\n }\n else if (type instanceof ZodNativeEnum) {\n // eslint-disable-next-line ban/ban\n return util.objectValues(type.enum);\n }\n else if (type instanceof ZodDefault) {\n return getDiscriminator(type._def.innerType);\n }\n else if (type instanceof ZodUndefined) {\n return [undefined];\n }\n else if (type instanceof ZodNull) {\n return [null];\n }\n else if (type instanceof ZodOptional) {\n return [undefined, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodNullable) {\n return [null, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodBranded) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodReadonly) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodCatch) {\n return getDiscriminator(type._def.innerType);\n }\n else {\n return [];\n }\n};\nexport class ZodDiscriminatedUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const discriminator = this.discriminator;\n const discriminatorValue = ctx.data[discriminator];\n const option = this.optionsMap.get(discriminatorValue);\n if (!option) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union_discriminator,\n options: Array.from(this.optionsMap.keys()),\n path: [discriminator],\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n else {\n return option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n get discriminator() {\n return this._def.discriminator;\n }\n get options() {\n return this._def.options;\n }\n get optionsMap() {\n return this._def.optionsMap;\n }\n /**\n * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.\n * However, it only allows a union of objects, all of which need to share a discriminator property. This property must\n * have a different value for each object in the union.\n * @param discriminator the name of the discriminator property\n * @param types an array of object schemas\n * @param params\n */\n static create(discriminator, options, params) {\n // Get all the valid discriminator values\n const optionsMap = new Map();\n // try {\n for (const type of options) {\n const discriminatorValues = getDiscriminator(type.shape[discriminator]);\n if (!discriminatorValues.length) {\n throw new Error(`A discriminator value for key \\`${discriminator}\\` could not be extracted from all schema options`);\n }\n for (const value of discriminatorValues) {\n if (optionsMap.has(value)) {\n throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);\n }\n optionsMap.set(value, type);\n }\n }\n return new ZodDiscriminatedUnion({\n typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,\n discriminator,\n options,\n optionsMap,\n ...processCreateParams(params),\n });\n }\n}\nfunction mergeValues(a, b) {\n const aType = getParsedType(a);\n const bType = getParsedType(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {\n const bKeys = util.objectKeys(b);\n const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {\n if (a.length !== b.length) {\n return { valid: false };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {\n return { valid: true, data: a };\n }\n else {\n return { valid: false };\n }\n}\nexport class ZodIntersection extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const handleParsed = (parsedLeft, parsedRight) => {\n if (isAborted(parsedLeft) || isAborted(parsedRight)) {\n return INVALID;\n }\n const merged = mergeValues(parsedLeft.value, parsedRight.value);\n if (!merged.valid) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_intersection_types,\n });\n return INVALID;\n }\n if (isDirty(parsedLeft) || isDirty(parsedRight)) {\n status.dirty();\n }\n return { status: status.value, value: merged.data };\n };\n if (ctx.common.async) {\n return Promise.all([\n this._def.left._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n this._def.right._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n ]).then(([left, right]) => handleParsed(left, right));\n }\n else {\n return handleParsed(this._def.left._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }), this._def.right._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }));\n }\n }\n}\nZodIntersection.create = (left, right, params) => {\n return new ZodIntersection({\n left: left,\n right: right,\n typeName: ZodFirstPartyTypeKind.ZodIntersection,\n ...processCreateParams(params),\n });\n};\n// type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]];\nexport class ZodTuple extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (ctx.data.length < this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n return INVALID;\n }\n const rest = this._def.rest;\n if (!rest && ctx.data.length > this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n status.dirty();\n }\n const items = [...ctx.data]\n .map((item, itemIndex) => {\n const schema = this._def.items[itemIndex] || this._def.rest;\n if (!schema)\n return null;\n return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));\n })\n .filter((x) => !!x); // filter nulls\n if (ctx.common.async) {\n return Promise.all(items).then((results) => {\n return ParseStatus.mergeArray(status, results);\n });\n }\n else {\n return ParseStatus.mergeArray(status, items);\n }\n }\n get items() {\n return this._def.items;\n }\n rest(rest) {\n return new ZodTuple({\n ...this._def,\n rest,\n });\n }\n}\nZodTuple.create = (schemas, params) => {\n if (!Array.isArray(schemas)) {\n throw new Error(\"You must pass an array of schemas to z.tuple([ ... ])\");\n }\n return new ZodTuple({\n items: schemas,\n typeName: ZodFirstPartyTypeKind.ZodTuple,\n rest: null,\n ...processCreateParams(params),\n });\n};\nexport class ZodRecord extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const pairs = [];\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n for (const key in ctx.data) {\n pairs.push({\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),\n value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (ctx.common.async) {\n return ParseStatus.mergeObjectAsync(status, pairs);\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get element() {\n return this._def.valueType;\n }\n static create(first, second, third) {\n if (second instanceof ZodType) {\n return new ZodRecord({\n keyType: first,\n valueType: second,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(third),\n });\n }\n return new ZodRecord({\n keyType: ZodString.create(),\n valueType: first,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(second),\n });\n }\n}\nexport class ZodMap extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.map) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.map,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n const pairs = [...ctx.data.entries()].map(([key, value], index) => {\n return {\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, \"key\"])),\n value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, \"value\"])),\n };\n });\n if (ctx.common.async) {\n const finalMap = new Map();\n return Promise.resolve().then(async () => {\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n });\n }\n else {\n const finalMap = new Map();\n for (const pair of pairs) {\n const key = pair.key;\n const value = pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n }\n }\n}\nZodMap.create = (keyType, valueType, params) => {\n return new ZodMap({\n valueType,\n keyType,\n typeName: ZodFirstPartyTypeKind.ZodMap,\n ...processCreateParams(params),\n });\n};\nexport class ZodSet extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.set) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.set,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const def = this._def;\n if (def.minSize !== null) {\n if (ctx.data.size < def.minSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.minSize.message,\n });\n status.dirty();\n }\n }\n if (def.maxSize !== null) {\n if (ctx.data.size > def.maxSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.maxSize.message,\n });\n status.dirty();\n }\n }\n const valueType = this._def.valueType;\n function finalizeSet(elements) {\n const parsedSet = new Set();\n for (const element of elements) {\n if (element.status === \"aborted\")\n return INVALID;\n if (element.status === \"dirty\")\n status.dirty();\n parsedSet.add(element.value);\n }\n return { status: status.value, value: parsedSet };\n }\n const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));\n if (ctx.common.async) {\n return Promise.all(elements).then((elements) => finalizeSet(elements));\n }\n else {\n return finalizeSet(elements);\n }\n }\n min(minSize, message) {\n return new ZodSet({\n ...this._def,\n minSize: { value: minSize, message: errorUtil.toString(message) },\n });\n }\n max(maxSize, message) {\n return new ZodSet({\n ...this._def,\n maxSize: { value: maxSize, message: errorUtil.toString(message) },\n });\n }\n size(size, message) {\n return this.min(size, message).max(size, message);\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodSet.create = (valueType, params) => {\n return new ZodSet({\n valueType,\n minSize: null,\n maxSize: null,\n typeName: ZodFirstPartyTypeKind.ZodSet,\n ...processCreateParams(params),\n });\n};\nexport class ZodFunction extends ZodType {\n constructor() {\n super(...arguments);\n this.validate = this.implement;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.function) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.function,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n function makeArgsIssue(args, error) {\n return makeIssue({\n data: args,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_arguments,\n argumentsError: error,\n },\n });\n }\n function makeReturnsIssue(returns, error) {\n return makeIssue({\n data: returns,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_return_type,\n returnTypeError: error,\n },\n });\n }\n const params = { errorMap: ctx.common.contextualErrorMap };\n const fn = ctx.data;\n if (this._def.returns instanceof ZodPromise) {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(async function (...args) {\n const error = new ZodError([]);\n const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {\n error.addIssue(makeArgsIssue(args, e));\n throw error;\n });\n const result = await Reflect.apply(fn, this, parsedArgs);\n const parsedReturns = await me._def.returns._def.type\n .parseAsync(result, params)\n .catch((e) => {\n error.addIssue(makeReturnsIssue(result, e));\n throw error;\n });\n return parsedReturns;\n });\n }\n else {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(function (...args) {\n const parsedArgs = me._def.args.safeParse(args, params);\n if (!parsedArgs.success) {\n throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);\n }\n const result = Reflect.apply(fn, this, parsedArgs.data);\n const parsedReturns = me._def.returns.safeParse(result, params);\n if (!parsedReturns.success) {\n throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);\n }\n return parsedReturns.data;\n });\n }\n }\n parameters() {\n return this._def.args;\n }\n returnType() {\n return this._def.returns;\n }\n args(...items) {\n return new ZodFunction({\n ...this._def,\n args: ZodTuple.create(items).rest(ZodUnknown.create()),\n });\n }\n returns(returnType) {\n return new ZodFunction({\n ...this._def,\n returns: returnType,\n });\n }\n implement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n strictImplement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n static create(args, returns, params) {\n return new ZodFunction({\n args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())),\n returns: returns || ZodUnknown.create(),\n typeName: ZodFirstPartyTypeKind.ZodFunction,\n ...processCreateParams(params),\n });\n }\n}\nexport class ZodLazy extends ZodType {\n get schema() {\n return this._def.getter();\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const lazySchema = this._def.getter();\n return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });\n }\n}\nZodLazy.create = (getter, params) => {\n return new ZodLazy({\n getter: getter,\n typeName: ZodFirstPartyTypeKind.ZodLazy,\n ...processCreateParams(params),\n });\n};\nexport class ZodLiteral extends ZodType {\n _parse(input) {\n if (input.data !== this._def.value) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_literal,\n expected: this._def.value,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n get value() {\n return this._def.value;\n }\n}\nZodLiteral.create = (value, params) => {\n return new ZodLiteral({\n value: value,\n typeName: ZodFirstPartyTypeKind.ZodLiteral,\n ...processCreateParams(params),\n });\n};\nfunction createZodEnum(values, params) {\n return new ZodEnum({\n values,\n typeName: ZodFirstPartyTypeKind.ZodEnum,\n ...processCreateParams(params),\n });\n}\nexport class ZodEnum extends ZodType {\n _parse(input) {\n if (typeof input.data !== \"string\") {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(this._def.values);\n }\n if (!this._cache.has(input.data)) {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get options() {\n return this._def.values;\n }\n get enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Values() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n extract(values, newDef = this._def) {\n return ZodEnum.create(values, {\n ...this._def,\n ...newDef,\n });\n }\n exclude(values, newDef = this._def) {\n return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {\n ...this._def,\n ...newDef,\n });\n }\n}\nZodEnum.create = createZodEnum;\nexport class ZodNativeEnum extends ZodType {\n _parse(input) {\n const nativeEnumValues = util.getValidEnumValues(this._def.values);\n const ctx = this._getOrReturnCtx(input);\n if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(util.getValidEnumValues(this._def.values));\n }\n if (!this._cache.has(input.data)) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get enum() {\n return this._def.values;\n }\n}\nZodNativeEnum.create = (values, params) => {\n return new ZodNativeEnum({\n values: values,\n typeName: ZodFirstPartyTypeKind.ZodNativeEnum,\n ...processCreateParams(params),\n });\n};\nexport class ZodPromise extends ZodType {\n unwrap() {\n return this._def.type;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.promise,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);\n return OK(promisified.then((data) => {\n return this._def.type.parseAsync(data, {\n path: ctx.path,\n errorMap: ctx.common.contextualErrorMap,\n });\n }));\n }\n}\nZodPromise.create = (schema, params) => {\n return new ZodPromise({\n type: schema,\n typeName: ZodFirstPartyTypeKind.ZodPromise,\n ...processCreateParams(params),\n });\n};\nexport class ZodEffects extends ZodType {\n innerType() {\n return this._def.schema;\n }\n sourceType() {\n return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects\n ? this._def.schema.sourceType()\n : this._def.schema;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const effect = this._def.effect || null;\n const checkCtx = {\n addIssue: (arg) => {\n addIssueToContext(ctx, arg);\n if (arg.fatal) {\n status.abort();\n }\n else {\n status.dirty();\n }\n },\n get path() {\n return ctx.path;\n },\n };\n checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);\n if (effect.type === \"preprocess\") {\n const processed = effect.transform(ctx.data, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(processed).then(async (processed) => {\n if (status.value === \"aborted\")\n return INVALID;\n const result = await this._def.schema._parseAsync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n });\n }\n else {\n if (status.value === \"aborted\")\n return INVALID;\n const result = this._def.schema._parseSync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n }\n }\n if (effect.type === \"refinement\") {\n const executeRefinement = (acc) => {\n const result = effect.refinement(acc, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(result);\n }\n if (result instanceof Promise) {\n throw new Error(\"Async refinement encountered during synchronous parse operation. Use .parseAsync instead.\");\n }\n return acc;\n };\n if (ctx.common.async === false) {\n const inner = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n // return value is ignored\n executeRefinement(inner.value);\n return { status: status.value, value: inner.value };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n return executeRefinement(inner.value).then(() => {\n return { status: status.value, value: inner.value };\n });\n });\n }\n }\n if (effect.type === \"transform\") {\n if (ctx.common.async === false) {\n const base = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (!isValid(base))\n return INVALID;\n const result = effect.transform(base.value, checkCtx);\n if (result instanceof Promise) {\n throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);\n }\n return { status: status.value, value: result };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {\n if (!isValid(base))\n return INVALID;\n return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({\n status: status.value,\n value: result,\n }));\n });\n }\n }\n util.assertNever(effect);\n }\n}\nZodEffects.create = (schema, effect, params) => {\n return new ZodEffects({\n schema,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect,\n ...processCreateParams(params),\n });\n};\nZodEffects.createWithPreprocess = (preprocess, schema, params) => {\n return new ZodEffects({\n schema,\n effect: { type: \"preprocess\", transform: preprocess },\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n ...processCreateParams(params),\n });\n};\nexport { ZodEffects as ZodTransformer };\nexport class ZodOptional extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.undefined) {\n return OK(undefined);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodOptional.create = (type, params) => {\n return new ZodOptional({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodOptional,\n ...processCreateParams(params),\n });\n};\nexport class ZodNullable extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.null) {\n return OK(null);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodNullable.create = (type, params) => {\n return new ZodNullable({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodNullable,\n ...processCreateParams(params),\n });\n};\nexport class ZodDefault extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n let data = ctx.data;\n if (ctx.parsedType === ZodParsedType.undefined) {\n data = this._def.defaultValue();\n }\n return this._def.innerType._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n removeDefault() {\n return this._def.innerType;\n }\n}\nZodDefault.create = (type, params) => {\n return new ZodDefault({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n defaultValue: typeof params.default === \"function\" ? params.default : () => params.default,\n ...processCreateParams(params),\n });\n};\nexport class ZodCatch extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n // newCtx is used to not collect issues from inner types in ctx\n const newCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n };\n const result = this._def.innerType._parse({\n data: newCtx.data,\n path: newCtx.path,\n parent: {\n ...newCtx,\n },\n });\n if (isAsync(result)) {\n return result.then((result) => {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n });\n }\n else {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n }\n }\n removeCatch() {\n return this._def.innerType;\n }\n}\nZodCatch.create = (type, params) => {\n return new ZodCatch({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n catchValue: typeof params.catch === \"function\" ? params.catch : () => params.catch,\n ...processCreateParams(params),\n });\n};\nexport class ZodNaN extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.nan) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.nan,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n}\nZodNaN.create = (params) => {\n return new ZodNaN({\n typeName: ZodFirstPartyTypeKind.ZodNaN,\n ...processCreateParams(params),\n });\n};\nexport const BRAND = Symbol(\"zod_brand\");\nexport class ZodBranded extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const data = ctx.data;\n return this._def.type._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n unwrap() {\n return this._def.type;\n }\n}\nexport class ZodPipeline extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.common.async) {\n const handleAsync = async () => {\n const inResult = await this._def.in._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return DIRTY(inResult.value);\n }\n else {\n return this._def.out._parseAsync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n };\n return handleAsync();\n }\n else {\n const inResult = this._def.in._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return {\n status: \"dirty\",\n value: inResult.value,\n };\n }\n else {\n return this._def.out._parseSync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n }\n static create(a, b) {\n return new ZodPipeline({\n in: a,\n out: b,\n typeName: ZodFirstPartyTypeKind.ZodPipeline,\n });\n }\n}\nexport class ZodReadonly extends ZodType {\n _parse(input) {\n const result = this._def.innerType._parse(input);\n const freeze = (data) => {\n if (isValid(data)) {\n data.value = Object.freeze(data.value);\n }\n return data;\n };\n return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodReadonly.create = (type, params) => {\n return new ZodReadonly({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodReadonly,\n ...processCreateParams(params),\n });\n};\n////////////////////////////////////////\n////////////////////////////////////////\n////////// //////////\n////////// z.custom //////////\n////////// //////////\n////////////////////////////////////////\n////////////////////////////////////////\nfunction cleanParams(params, data) {\n const p = typeof params === \"function\" ? params(data) : typeof params === \"string\" ? { message: params } : params;\n const p2 = typeof p === \"string\" ? { message: p } : p;\n return p2;\n}\nexport function custom(check, _params = {}, \n/**\n * @deprecated\n *\n * Pass `fatal` into the params object instead:\n *\n * ```ts\n * z.string().custom((val) => val.length > 5, { fatal: false })\n * ```\n *\n */\nfatal) {\n if (check)\n return ZodAny.create().superRefine((data, ctx) => {\n const r = check(data);\n if (r instanceof Promise) {\n return r.then((r) => {\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n });\n }\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n return;\n });\n return ZodAny.create();\n}\nexport { ZodType as Schema, ZodType as ZodSchema };\nexport const late = {\n object: ZodObject.lazycreate,\n};\nexport var ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n ZodFirstPartyTypeKind[\"ZodString\"] = \"ZodString\";\n ZodFirstPartyTypeKind[\"ZodNumber\"] = \"ZodNumber\";\n ZodFirstPartyTypeKind[\"ZodNaN\"] = \"ZodNaN\";\n ZodFirstPartyTypeKind[\"ZodBigInt\"] = \"ZodBigInt\";\n ZodFirstPartyTypeKind[\"ZodBoolean\"] = \"ZodBoolean\";\n ZodFirstPartyTypeKind[\"ZodDate\"] = \"ZodDate\";\n ZodFirstPartyTypeKind[\"ZodSymbol\"] = \"ZodSymbol\";\n ZodFirstPartyTypeKind[\"ZodUndefined\"] = \"ZodUndefined\";\n ZodFirstPartyTypeKind[\"ZodNull\"] = \"ZodNull\";\n ZodFirstPartyTypeKind[\"ZodAny\"] = \"ZodAny\";\n ZodFirstPartyTypeKind[\"ZodUnknown\"] = \"ZodUnknown\";\n ZodFirstPartyTypeKind[\"ZodNever\"] = \"ZodNever\";\n ZodFirstPartyTypeKind[\"ZodVoid\"] = \"ZodVoid\";\n ZodFirstPartyTypeKind[\"ZodArray\"] = \"ZodArray\";\n ZodFirstPartyTypeKind[\"ZodObject\"] = \"ZodObject\";\n ZodFirstPartyTypeKind[\"ZodUnion\"] = \"ZodUnion\";\n ZodFirstPartyTypeKind[\"ZodDiscriminatedUnion\"] = \"ZodDiscriminatedUnion\";\n ZodFirstPartyTypeKind[\"ZodIntersection\"] = \"ZodIntersection\";\n ZodFirstPartyTypeKind[\"ZodTuple\"] = \"ZodTuple\";\n ZodFirstPartyTypeKind[\"ZodRecord\"] = \"ZodRecord\";\n ZodFirstPartyTypeKind[\"ZodMap\"] = \"ZodMap\";\n ZodFirstPartyTypeKind[\"ZodSet\"] = \"ZodSet\";\n ZodFirstPartyTypeKind[\"ZodFunction\"] = \"ZodFunction\";\n ZodFirstPartyTypeKind[\"ZodLazy\"] = \"ZodLazy\";\n ZodFirstPartyTypeKind[\"ZodLiteral\"] = \"ZodLiteral\";\n ZodFirstPartyTypeKind[\"ZodEnum\"] = \"ZodEnum\";\n ZodFirstPartyTypeKind[\"ZodEffects\"] = \"ZodEffects\";\n ZodFirstPartyTypeKind[\"ZodNativeEnum\"] = \"ZodNativeEnum\";\n ZodFirstPartyTypeKind[\"ZodOptional\"] = \"ZodOptional\";\n ZodFirstPartyTypeKind[\"ZodNullable\"] = \"ZodNullable\";\n ZodFirstPartyTypeKind[\"ZodDefault\"] = \"ZodDefault\";\n ZodFirstPartyTypeKind[\"ZodCatch\"] = \"ZodCatch\";\n ZodFirstPartyTypeKind[\"ZodPromise\"] = \"ZodPromise\";\n ZodFirstPartyTypeKind[\"ZodBranded\"] = \"ZodBranded\";\n ZodFirstPartyTypeKind[\"ZodPipeline\"] = \"ZodPipeline\";\n ZodFirstPartyTypeKind[\"ZodReadonly\"] = \"ZodReadonly\";\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\n// requires TS 4.4+\nclass Class {\n constructor(..._) { }\n}\nconst instanceOfType = (\n// const instanceOfType = <T extends new (...args: any[]) => any>(\ncls, params = {\n message: `Input not instance of ${cls.name}`,\n}) => custom((data) => data instanceof cls, params);\nconst stringType = ZodString.create;\nconst numberType = ZodNumber.create;\nconst nanType = ZodNaN.create;\nconst bigIntType = ZodBigInt.create;\nconst booleanType = ZodBoolean.create;\nconst dateType = ZodDate.create;\nconst symbolType = ZodSymbol.create;\nconst undefinedType = ZodUndefined.create;\nconst nullType = ZodNull.create;\nconst anyType = ZodAny.create;\nconst unknownType = ZodUnknown.create;\nconst neverType = ZodNever.create;\nconst voidType = ZodVoid.create;\nconst arrayType = ZodArray.create;\nconst objectType = ZodObject.create;\nconst strictObjectType = ZodObject.strictCreate;\nconst unionType = ZodUnion.create;\nconst discriminatedUnionType = ZodDiscriminatedUnion.create;\nconst intersectionType = ZodIntersection.create;\nconst tupleType = ZodTuple.create;\nconst recordType = ZodRecord.create;\nconst mapType = ZodMap.create;\nconst setType = ZodSet.create;\nconst functionType = ZodFunction.create;\nconst lazyType = ZodLazy.create;\nconst literalType = ZodLiteral.create;\nconst enumType = ZodEnum.create;\nconst nativeEnumType = ZodNativeEnum.create;\nconst promiseType = ZodPromise.create;\nconst effectsType = ZodEffects.create;\nconst optionalType = ZodOptional.create;\nconst nullableType = ZodNullable.create;\nconst preprocessType = ZodEffects.createWithPreprocess;\nconst pipelineType = ZodPipeline.create;\nconst ostring = () => stringType().optional();\nconst onumber = () => numberType().optional();\nconst oboolean = () => booleanType().optional();\nexport const coerce = {\n string: ((arg) => ZodString.create({ ...arg, coerce: true })),\n number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),\n boolean: ((arg) => ZodBoolean.create({\n ...arg,\n coerce: true,\n })),\n bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),\n date: ((arg) => ZodDate.create({ ...arg, coerce: true })),\n};\nexport { anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, dateType as date, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, instanceOfType as instanceof, intersectionType as intersection, lazyType as lazy, literalType as literal, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, recordType as record, setType as set, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, voidType as void, };\nexport const NEVER = INVALID;\n","import { z } from 'zod'\nimport type { BuildableTable, Encrypted } from '@/types'\nimport { resolveMatchOpts } from './match-defaults'\n\n// ------------------------\n// Zod schemas\n// ------------------------\n\n/**\n * Allowed cast types for CipherStash schema fields.\n *\n * **Possible values:**\n * - `\"bigint\"`\n * - `\"boolean\"`\n * - `\"date\"`\n * - `\"timestamp\"`\n * - `\"number\"`\n * - `\"string\"`\n * - `\"json\"`\n * - `\"text\"`\n *\n * @remarks\n * This is a Zod enum used at runtime to validate schema definitions.\n * Use {@link CastAs} when typing your own code.\n *\n * @internal\n */\n/**\n * EQL cast types — the PostgreSQL-aligned types that EQL actually accepts.\n * These are stored in the `cast_as` field of the EncryptConfig.\n */\nexport const eqlCastAsEnum = z\n .enum([\n 'text',\n 'int',\n 'small_int',\n 'big_int',\n 'real',\n 'double',\n 'boolean',\n 'date',\n 'timestamp',\n 'jsonb',\n ])\n .default('text')\n\n/**\n * SDK-facing data types — developer-friendly aliases accepted by `dataType()`.\n *\n * `timestamp` is distinct from `date`: `date` is calendar-date only (time-of-day\n * truncated to midnight), while `timestamp` preserves the full date+time. v3\n * `timestamp` domains set `cast_as: 'timestamp'` so the FFI keeps the instant.\n */\nexport const castAsEnum = z\n .enum([\n 'bigint',\n 'boolean',\n 'date',\n 'timestamp',\n 'number',\n 'string',\n 'json',\n 'text',\n ])\n .default('text')\n\n/**\n * Map SDK-facing data types to EQL `cast_as` values.\n *\n * The SDK accepts developer-friendly types like `'string'` and `'number'`,\n * but EQL expects PostgreSQL-aligned types like `'text'` and `'double'`.\n */\nexport function toEqlCastAs(value: CastAs): EqlCastAs {\n switch (value) {\n case 'string':\n return 'text'\n case 'text':\n return 'text'\n case 'number':\n return 'double'\n case 'bigint':\n return 'big_int'\n case 'boolean':\n return 'boolean'\n case 'date':\n return 'date'\n case 'timestamp':\n return 'timestamp'\n case 'json':\n return 'jsonb'\n }\n}\n\nconst tokenFilterSchema = z.object({\n kind: z.literal('downcase'),\n})\n\nconst tokenizerSchema = z\n .union([\n z.object({\n kind: z.literal('standard'),\n }),\n z.object({\n kind: z.literal('ngram'),\n token_length: z.number(),\n }),\n ])\n .default({ kind: 'ngram', token_length: 3 })\n .optional()\n\nconst oreIndexOptsSchema = z.object({})\n\n// The OPE (CLLW-OPE, `op` term) ordering index — protect-ffi 0.29+. Emitted by\n// the EQL v3 `_ord` domains; the `_ord_ore` domains keep `ore` (block-ORE,\n// `ob`). v2 columns never emit it.\nconst opeIndexOptsSchema = z.object({})\n\nconst uniqueIndexOptsSchema = z.object({\n token_filters: z.array(tokenFilterSchema).default([]).optional(),\n})\n\nconst matchIndexOptsSchema = z.object({\n tokenizer: tokenizerSchema,\n token_filters: z.array(tokenFilterSchema).default([]).optional(),\n k: z.number().default(6).optional(),\n m: z.number().default(2048).optional(),\n include_original: z.boolean().default(false).optional(),\n})\n\nconst arrayIndexModeSchema = z.union([\n z.literal('all'),\n z.literal('none'),\n z.object({\n item: z.boolean().optional(),\n wildcard: z.boolean().optional(),\n position: z.boolean().optional(),\n }),\n])\n\nconst steVecIndexOptsSchema = z.object({\n prefix: z.string(),\n array_index_mode: arrayIndexModeSchema.optional(),\n mode: z.enum(['compat', 'standard']).optional(),\n})\n\nconst indexesSchema = z\n .object({\n ore: oreIndexOptsSchema.optional(),\n ope: opeIndexOptsSchema.optional(),\n unique: uniqueIndexOptsSchema.optional(),\n match: matchIndexOptsSchema.optional(),\n ste_vec: steVecIndexOptsSchema.optional(),\n })\n .default({})\n\nconst columnSchema = z\n .object({\n cast_as: castAsEnum,\n indexes: indexesSchema,\n })\n .default({})\n\nconst tableSchema = z.record(columnSchema).default({})\n\nconst tablesSchema = z.record(tableSchema).default({})\n\n/** @internal */\nexport const encryptConfigSchema = z.object({\n v: z.number(),\n tables: tablesSchema,\n})\n\n// ------------------------\n// Type definitions\n// ------------------------\n\n/**\n * Type-safe alias for {@link castAsEnum} used to specify the *unencrypted* data type of a column or value.\n * This is important because once encrypted, all data is stored as binary blobs.\n *\n * @see {@link castAsEnum} for possible values.\n */\nexport type CastAs = z.infer<typeof castAsEnum>\nexport type EqlCastAs = z.infer<typeof eqlCastAsEnum>\nexport type TokenFilter = z.infer<typeof tokenFilterSchema>\nexport type MatchIndexOpts = z.infer<typeof matchIndexOptsSchema>\nexport type SteVecIndexOpts = z.infer<typeof steVecIndexOptsSchema>\nexport type UniqueIndexOpts = z.infer<typeof uniqueIndexOptsSchema>\nexport type OreIndexOpts = z.infer<typeof oreIndexOptsSchema>\nexport type OpeIndexOpts = z.infer<typeof opeIndexOptsSchema>\nexport type ColumnSchema = z.infer<typeof columnSchema>\n\n/**\n * Shape of table columns: either top-level {@link EncryptedColumn} or nested\n * objects whose leaves are {@link EncryptedField}. Used with {@link encryptedTable}.\n */\nexport type EncryptedTableColumn = {\n [key: string]:\n | EncryptedColumn\n | {\n [key: string]:\n | EncryptedField\n | {\n [key: string]:\n | EncryptedField\n | {\n [key: string]: EncryptedField\n }\n }\n }\n}\nexport type EncryptConfig = z.infer<typeof encryptConfigSchema>\n\n// ------------------------\n// Interface definitions\n// ------------------------\n\n/**\n * Builder for a nested encrypted field (encrypted but not searchable).\n * Create with {@link encryptedField}. Use inside nested objects in {@link encryptedTable};\n * supports `.dataType()` for plaintext type. No index methods (equality, orderAndRange, etc.).\n */\nexport class EncryptedField {\n private valueName: string\n private castAsValue: CastAs\n\n constructor(valueName: string) {\n this.valueName = valueName\n this.castAsValue = 'string'\n }\n\n /**\n * Set or override the plaintext data type for this field.\n *\n * By default all values are treated as `'string'`. Use this method to specify\n * a different type so the encryption layer knows how to encode the plaintext\n * before encrypting.\n *\n * @param castAs - The plaintext data type: `'string'`, `'number'`, `'boolean'`, `'date'`, `'timestamp'`, `'text'`, `'bigint'`, or `'json'`. Use `'timestamp'` (not `'date'`) to preserve time-of-day — `'date'` truncates to midnight.\n * @returns This `EncryptedField` instance for method chaining.\n *\n * @example\n * ```typescript\n * import { encryptedField } from \"@cipherstash/stack/schema\"\n *\n * const age = encryptedField(\"age\").dataType(\"number\")\n * ```\n */\n dataType(castAs: CastAs) {\n this.castAsValue = castAs\n return this\n }\n\n build() {\n return {\n cast_as: this.castAsValue,\n indexes: {},\n }\n }\n\n getName() {\n return this.valueName\n }\n}\n\nexport class EncryptedColumn {\n private columnName: string\n private castAsValue: CastAs\n private indexesValue: {\n ore?: OreIndexOpts\n // Never set by the v2 fluent builder (the OPE index is EQL v3-only);\n // declared so `build()` stays assignable to the shared indexes shape.\n ope?: OpeIndexOpts\n unique?: UniqueIndexOpts\n match?: Required<MatchIndexOpts>\n ste_vec?: SteVecIndexOpts\n } = {}\n\n constructor(columnName: string) {\n this.columnName = columnName\n this.castAsValue = 'string'\n }\n\n /**\n * Set or override the plaintext data type for this column.\n *\n * By default all columns are treated as `'string'`. Use this method to specify\n * a different type so the encryption layer knows how to encode the plaintext\n * before encrypting.\n *\n * @param castAs - The plaintext data type: `'string'`, `'number'`, `'boolean'`, `'date'`, `'timestamp'`, `'text'`, `'bigint'`, or `'json'`. Use `'timestamp'` (not `'date'`) to preserve time-of-day — `'date'` truncates to midnight.\n * @returns This `EncryptedColumn` instance for method chaining.\n *\n * @example\n * ```typescript\n * import { encryptedColumn } from \"@cipherstash/stack/schema\"\n *\n * const dateOfBirth = encryptedColumn(\"date_of_birth\").dataType(\"date\")\n * ```\n */\n dataType(castAs: CastAs) {\n this.castAsValue = castAs\n return this\n }\n\n /**\n * Enable Order-Revealing Encryption (ORE) indexing on this column.\n *\n * ORE allows sorting, comparison, and range queries on encrypted data.\n * Use with `encryptQuery` and `queryType: 'orderAndRange'`.\n *\n * @returns This `EncryptedColumn` instance for method chaining.\n *\n * @example\n * ```typescript\n * import { encryptedTable, encryptedColumn } from \"@cipherstash/stack/schema\"\n *\n * const users = encryptedTable(\"users\", {\n * email: encryptedColumn(\"email\").orderAndRange(),\n * })\n * ```\n */\n orderAndRange() {\n this.indexesValue.ore = {}\n return this\n }\n\n /**\n * Enable an exact-match (unique) index on this column.\n *\n * Allows equality queries on encrypted data. Use with `encryptQuery`\n * and `queryType: 'equality'`.\n *\n * @param tokenFilters - Optional array of token filters (e.g. `[{ kind: 'downcase' }]`).\n * When omitted, no token filters are applied.\n * @returns This `EncryptedColumn` instance for method chaining.\n *\n * @example\n * ```typescript\n * import { encryptedTable, encryptedColumn } from \"@cipherstash/stack/schema\"\n *\n * const users = encryptedTable(\"users\", {\n * email: encryptedColumn(\"email\").equality(),\n * })\n * ```\n */\n equality(tokenFilters?: TokenFilter[]) {\n this.indexesValue.unique = {\n token_filters: tokenFilters ?? [],\n }\n return this\n }\n\n /**\n * Enable a full-text / fuzzy search (match) index on this column.\n *\n * Uses n-gram tokenization by default for substring and fuzzy matching.\n * Use with `encryptQuery` and `queryType: 'freeTextSearch'`.\n *\n * @param opts - Optional match index configuration. Defaults to 3-character ngram\n * tokenization with a downcase filter, `k=6`, `m=2048`, and `include_original=true`.\n * @returns This `EncryptedColumn` instance for method chaining.\n *\n * @example\n * ```typescript\n * import { encryptedTable, encryptedColumn } from \"@cipherstash/stack/schema\"\n *\n * const users = encryptedTable(\"users\", {\n * email: encryptedColumn(\"email\").freeTextSearch(),\n * })\n *\n * // With custom options\n * const posts = encryptedTable(\"posts\", {\n * body: encryptedColumn(\"body\").freeTextSearch({\n * tokenizer: { kind: \"ngram\", token_length: 4 },\n * k: 8,\n * m: 4096,\n * }),\n * })\n * ```\n */\n freeTextSearch(opts?: MatchIndexOpts) {\n // Shared merge+clone (schema/match-defaults) — one source of truth with the\n // EQL v3 domain builders. `resolveMatchOpts` deep-clones, so a caller\n // mutating their own `opts` (or its nested tokenizer/token_filters) after\n // this call cannot leak into the stored schema.\n this.indexesValue.match = resolveMatchOpts(opts)\n return this\n }\n\n /**\n * Configure this column for searchable encrypted JSON (STE-Vec).\n *\n * Enables encrypted JSONPath selector queries (e.g. `'$.user.email'`) and\n * containment queries (e.g. `{ role: 'admin' }`). Automatically sets the\n * data type to `'json'`.\n *\n * When used with `encryptQuery`, the query operation is auto-inferred from\n * the plaintext type: strings become selector queries, objects/arrays become\n * containment queries.\n *\n * @returns This `EncryptedColumn` instance for method chaining.\n *\n * @example\n * ```typescript\n * import { encryptedTable, encryptedColumn } from \"@cipherstash/stack/schema\"\n *\n * const documents = encryptedTable(\"documents\", {\n * metadata: encryptedColumn(\"metadata\").searchableJson(),\n * })\n * ```\n */\n searchableJson() {\n this.castAsValue = 'json'\n // `mode: 'standard'` pins the per-entry ordering term to CLLW-ORE (`oc`),\n // the only encoding the eql_v2 SQL compares. protect-ffi 0.29 flipped the\n // library default to `compat` (CLLW-OPE, `op`) for EQL v3; without the pin\n // every v2 containment query silently matches nothing — and existing v2\n // rows encrypted under `standard` are not cross-comparable with `compat`\n // anyway, so this also keeps the v2 wire format byte-stable.\n this.indexesValue.ste_vec = {\n prefix: 'enabled',\n array_index_mode: 'all',\n mode: 'standard',\n }\n return this\n }\n\n build() {\n return {\n cast_as: this.castAsValue,\n indexes: this.indexesValue,\n }\n }\n\n getName() {\n return this.columnName\n }\n}\n\ninterface TableDefinition {\n tableName: string\n columns: Record<string, ColumnSchema>\n}\n\nexport class EncryptedTable<T extends EncryptedTableColumn> {\n /** @internal Type-level brand so TypeScript can infer `T` from `EncryptedTable<T>`. */\n declare readonly _columnType: T\n\n constructor(\n public readonly tableName: string,\n public readonly columnBuilders: T,\n ) {}\n\n /**\n * Compile this table schema into a `TableDefinition` used internally by the encryption client.\n *\n * Iterates over all column builders, calls `.build()` on each, and assembles\n * the final `{ tableName, columns }` structure. For `searchableJson()` columns,\n * the STE-Vec prefix is automatically set to `\"<tableName>/<columnName>\"`.\n *\n * @returns A `TableDefinition` containing the table name and built column configs.\n *\n * @example\n * ```typescript\n * const users = encryptedTable(\"users\", {\n * email: encryptedColumn(\"email\").equality(),\n * })\n *\n * const definition = users.build()\n * // { tableName: \"users\", columns: { email: { cast_as: \"string\", indexes: { unique: ... } } } }\n * ```\n */\n build(): TableDefinition {\n const builtColumns: Record<string, ColumnSchema> = {}\n\n const processColumn = (\n builder:\n | EncryptedColumn\n | Record<\n string,\n | EncryptedField\n | Record<\n string,\n | EncryptedField\n | Record<\n string,\n EncryptedField | Record<string, EncryptedField>\n >\n >\n >,\n colName: string,\n ) => {\n if (builder instanceof EncryptedColumn) {\n const builtColumn = builder.build()\n\n // Hanlde building the ste_vec index for JSON columns so users don't have to pass the prefix.\n if (\n builtColumn.cast_as === 'json' &&\n builtColumn.indexes.ste_vec?.prefix === 'enabled'\n ) {\n builtColumns[colName] = {\n ...builtColumn,\n indexes: {\n ...builtColumn.indexes,\n ste_vec: {\n ...builtColumn.indexes.ste_vec,\n prefix: `${this.tableName}/${colName}`,\n },\n },\n }\n } else {\n builtColumns[colName] = builtColumn\n }\n } else {\n for (const [key, value] of Object.entries(builder)) {\n if (value instanceof EncryptedField) {\n builtColumns[value.getName()] = value.build()\n } else {\n processColumn(value, key)\n }\n }\n }\n }\n\n for (const [colName, builder] of Object.entries(this.columnBuilders)) {\n processColumn(builder, colName)\n }\n\n return {\n tableName: this.tableName,\n columns: builtColumns,\n }\n }\n}\n\n// ------------------------\n// Schema type inference helpers\n// ------------------------\n\n/**\n * Infer the plaintext (decrypted) type from a EncryptedTable schema.\n *\n * @example\n * ```typescript\n * const users = encryptedTable(\"users\", {\n * email: encryptedColumn(\"email\").equality(),\n * name: encryptedColumn(\"name\"),\n * })\n *\n * type UserPlaintext = InferPlaintext<typeof users>\n * // => { email: string; name: string }\n * ```\n */\nexport type InferPlaintext<T extends EncryptedTable<any>> =\n T extends EncryptedTable<infer C>\n ? {\n [K in keyof C as C[K] extends EncryptedColumn | EncryptedField\n ? K\n : never]: string\n }\n : never\n\n/**\n * Infer the encrypted type from a EncryptedTable schema.\n *\n * @example\n * ```typescript\n * const users = encryptedTable(\"users\", {\n * email: encryptedColumn(\"email\").equality(),\n * })\n *\n * type UserEncrypted = InferEncrypted<typeof users>\n * // => { email: Encrypted }\n * ```\n */\nexport type InferEncrypted<T extends EncryptedTable<any>> =\n T extends EncryptedTable<infer C>\n ? {\n [K in keyof C as C[K] extends EncryptedColumn | EncryptedField\n ? K\n : never]: Encrypted\n }\n : never\n\n// ------------------------\n// User facing functions\n// ------------------------\n\n/**\n * Define an encrypted table schema.\n *\n * Creates a `EncryptedTable` that maps a database table name to a set of encrypted\n * column definitions. Pass the resulting object to `Encryption({ schemas: [...] })`\n * when initializing the client.\n *\n * The returned object is also a proxy that exposes each column builder directly,\n * so you can reference columns as `users.email` when calling `encrypt`, `decrypt`,\n * and `encryptQuery`.\n *\n * @param tableName - The name of the database table this schema represents.\n * @param columns - An object whose keys are logical column names and values are\n * {@link EncryptedColumn} from {@link encryptedColumn}, or nested objects whose\n * leaves are {@link EncryptedField} from {@link encryptedField}.\n * @returns A `EncryptedTable<T> & T` that can be used as both a schema definition\n * and a column accessor.\n *\n * @example\n * ```typescript\n * import { encryptedTable, encryptedColumn } from \"@cipherstash/stack/schema\"\n *\n * const users = encryptedTable(\"users\", {\n * email: encryptedColumn(\"email\").equality().freeTextSearch(),\n * address: encryptedColumn(\"address\"),\n * })\n *\n * // Use as schema\n * const client = await Encryption({ schemas: [users] })\n *\n * // Use as column accessor\n * await client.encrypt(\"hello@example.com\", { column: users.email, table: users })\n * ```\n */\nexport function encryptedTable<T extends EncryptedTableColumn>(\n tableName: string,\n columns: T,\n): EncryptedTable<T> & T {\n const tableBuilder = new EncryptedTable(\n tableName,\n columns,\n ) as EncryptedTable<T> & T\n\n for (const [colName, colBuilder] of Object.entries(columns)) {\n ;(tableBuilder as EncryptedTableColumn)[colName] = colBuilder\n }\n\n return tableBuilder\n}\n\n/**\n * Define an encrypted column within a table schema.\n *\n * Creates a `EncryptedColumn` builder for the given column name. Chain index\n * methods (`.equality()`, `.freeTextSearch()`, `.orderAndRange()`,\n * `.searchableJson()`) and/or `.dataType()` to configure searchable encryption\n * and the plaintext data type.\n *\n * @param columnName - The name of the database column to encrypt.\n * @returns A new `EncryptedColumn` builder.\n *\n * @example\n * ```typescript\n * import { encryptedTable, encryptedColumn } from \"@cipherstash/stack/schema\"\n *\n * const users = encryptedTable(\"users\", {\n * email: encryptedColumn(\"email\").equality().freeTextSearch().orderAndRange(),\n * })\n * ```\n */\nexport function encryptedColumn(columnName: string) {\n return new EncryptedColumn(columnName)\n}\n\n/**\n * Define an encrypted field for use in nested or structured schemas.\n *\n * `encryptedField` is similar to {@link encryptedColumn} but creates an {@link EncryptedField}\n * for nested fields that are encrypted but not searchable (no indexes). Use `.dataType()`\n * to specify the plaintext type.\n *\n * @param valueName - The name of the value field.\n * @returns A new `EncryptedField` builder.\n *\n * @example\n * ```typescript\n * import { encryptedTable, encryptedField } from \"@cipherstash/stack/schema\"\n *\n * const orders = encryptedTable(\"orders\", {\n * details: {\n * amount: encryptedField(\"amount\").dataType(\"number\"),\n * currency: encryptedField(\"currency\"),\n * },\n * })\n * ```\n */\nexport function encryptedField(valueName: string) {\n return new EncryptedField(valueName)\n}\n\n/**\n * Build an encrypt config from a list of encrypted tables.\n *\n * @param protectTables - The list of encrypted tables to build the config from.\n * @returns An encrypt config object.\n *\n * @example\n * ```typescript\n * import { buildEncryptConfig } from \"@cipherstash/stack/schema\"\n *\n * const users = encryptedTable(\"users\", {\n * email: encryptedColumn(\"email\").equality(),\n * })\n *\n * const orders = encryptedTable(\"orders\", {\n * amount: encryptedColumn(\"amount\").dataType(\"number\"),\n * })\n *\n * const config = buildEncryptConfig(users, orders)\n * console.log(config)\n * ```\n */\nexport function buildEncryptConfig(\n ...protectTables: Array<BuildableTable>\n): EncryptConfig {\n const config: EncryptConfig = {\n v: 1,\n tables: {},\n }\n\n for (const tb of protectTables) {\n const tableDef = tb.build()\n config.tables[tableDef.tableName] = tableDef.columns\n }\n\n return config\n}\n","import type { EnvironmentContext, LogLevel } from './types'\n\nexport function formatDuration(ms: number): string {\n if (ms < 1000) {\n return `${Math.round(ms)}ms`\n }\n return `${(ms / 1000).toFixed(2)}s`\n}\n\nexport function isServer(): boolean {\n return typeof window === 'undefined'\n}\n\nexport function isClient(): boolean {\n return typeof window !== 'undefined'\n}\n\nexport function isDev(): boolean {\n if (typeof process !== 'undefined') {\n return process.env.NODE_ENV !== 'production'\n }\n if (typeof window !== 'undefined') {\n return true\n }\n return false\n}\n\nexport function detectEnvironment(): Partial<EnvironmentContext> {\n const env = typeof process !== 'undefined' ? process.env : {}\n const defaultEnvironment = isDev() ? 'development' : 'production'\n\n return {\n environment: env.NODE_ENV || defaultEnvironment,\n service: env.SERVICE_NAME || 'app',\n version: env.APP_VERSION,\n commitHash: env.COMMIT_SHA\n || env.GITHUB_SHA\n || env.VERCEL_GIT_COMMIT_SHA\n || env.CF_PAGES_COMMIT_SHA,\n region: env.VERCEL_REGION\n || env.AWS_REGION\n || env.FLY_REGION\n || env.CF_REGION,\n }\n}\n\nexport function getConsoleMethod(level: LogLevel): LogLevel {\n return level\n}\n\nexport const colors = {\n reset: '\\x1B[0m',\n bold: '\\x1B[1m',\n dim: '\\x1B[2m',\n red: '\\x1B[31m',\n green: '\\x1B[32m',\n yellow: '\\x1B[33m',\n blue: '\\x1B[34m',\n magenta: '\\x1B[35m',\n cyan: '\\x1B[36m',\n white: '\\x1B[37m',\n gray: '\\x1B[90m',\n} as const\n\nexport function getLevelColor(level: string): string {\n switch (level) {\n case 'error':\n return colors.red\n case 'warn':\n return colors.yellow\n case 'info':\n return colors.cyan\n case 'debug':\n return colors.gray\n default:\n return colors.white\n }\n}\n\n/** Headers that should never be passed to hooks for security */\nexport const SENSITIVE_HEADERS = [\n 'authorization',\n 'cookie',\n 'set-cookie',\n 'x-api-key',\n 'x-auth-token',\n 'proxy-authorization',\n]\n\nexport function filterSafeHeaders(headers: Record<string, string>): Record<string, string> {\n const safeHeaders: Record<string, string> = {}\n\n for (const [key, value] of Object.entries(headers)) {\n if (!SENSITIVE_HEADERS.includes(key.toLowerCase())) {\n safeHeaders[key] = value\n }\n }\n\n return safeHeaders\n}\n\n/**\n * Match a path against a glob pattern.\n * Supports * (any chars except /) and ** (any chars including /).\n */\nexport function matchesPattern(path: string, pattern: string): boolean {\n const regexPattern = pattern\n .replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&') // Escape special regex chars except * and ?\n .replace(/\\*\\*/g, '{{GLOBSTAR}}') // Temp placeholder for **\n .replace(/\\*/g, '[^/]*') // * matches anything except /\n .replace(/{{GLOBSTAR}}/g, '.*') // ** matches anything including /\n .replace(/\\?/g, '[^/]') // ? matches single char except /\n\n const regex = new RegExp(`^${regexPattern}$`)\n return regex.test(path)\n}\n","import type { DrainContext, EnvironmentContext, FieldContext, Log, LogLevel, LoggerConfig, RequestLogger, RequestLoggerOptions, SamplingConfig, TailSamplingContext, WideEvent } from './types'\nimport { colors, detectEnvironment, formatDuration, getConsoleMethod, getLevelColor, isDev, matchesPattern } from './utils'\n\nfunction isPlainObject(val: unknown): val is Record<string, unknown> {\n return val !== null && typeof val === 'object' && !Array.isArray(val)\n}\n\nfunction deepDefaults(base: Record<string, unknown>, defaults: Record<string, unknown>): Record<string, unknown> {\n const result = { ...base }\n for (const key in defaults) {\n const baseVal = result[key]\n const defaultVal = defaults[key]\n if (baseVal === undefined || baseVal === null) {\n result[key] = defaultVal\n } else if (isPlainObject(baseVal) && isPlainObject(defaultVal)) {\n result[key] = deepDefaults(baseVal, defaultVal)\n }\n }\n return result\n}\n\nlet globalEnv: EnvironmentContext = {\n service: 'app',\n environment: 'development',\n}\n\nlet globalPretty = isDev()\nlet globalSampling: SamplingConfig = {}\nlet globalStringify = true\nlet globalDrain: ((ctx: DrainContext) => void | Promise<void>) | undefined\nlet globalEnabled = true\n\n/**\n * Initialize the logger with configuration.\n * Call this once at application startup.\n */\nexport function initLogger(config: LoggerConfig = {}): void {\n globalEnabled = config.enabled ?? true\n const detected = detectEnvironment()\n\n globalEnv = {\n service: config.env?.service ?? detected.service ?? 'app',\n environment: config.env?.environment ?? detected.environment ?? 'development',\n version: config.env?.version ?? detected.version,\n commitHash: config.env?.commitHash ?? detected.commitHash,\n region: config.env?.region ?? detected.region,\n }\n\n globalPretty = config.pretty ?? isDev()\n globalSampling = config.sampling ?? {}\n globalStringify = config.stringify ?? true\n globalDrain = config.drain\n}\n\n/**\n * Check if logging is globally enabled.\n */\nexport function isEnabled(): boolean {\n return globalEnabled\n}\n\n/**\n * Determine if a log at the given level should be emitted based on sampling config.\n * Error level defaults to 100% (always logged) unless explicitly configured otherwise.\n */\nfunction shouldSample(level: LogLevel): boolean {\n const { rates } = globalSampling\n if (!rates) {\n return true // No sampling configured, log everything\n }\n\n // Error defaults to 100% unless explicitly set\n const percentage = level === 'error' && rates.error === undefined\n ? 100\n : rates[level] ?? 100\n\n // 0% = never log, 100% = always log\n if (percentage <= 0) return false\n if (percentage >= 100) return true\n\n return Math.random() * 100 < percentage\n}\n\n/**\n * Evaluate tail sampling conditions to determine if a log should be force-kept.\n * Returns true if ANY condition matches (OR logic).\n */\nexport function shouldKeep(ctx: TailSamplingContext): boolean {\n const { keep } = globalSampling\n if (!keep?.length) return false\n\n return keep.some((condition) => {\n if (condition.status !== undefined && ctx.status !== undefined && ctx.status >= condition.status) {\n return true\n }\n if (condition.duration !== undefined && ctx.duration !== undefined && ctx.duration >= condition.duration) {\n return true\n }\n if (condition.path && ctx.path && matchesPattern(ctx.path, condition.path)) {\n return true\n }\n return false\n })\n}\n\nfunction emitWideEvent(level: LogLevel, event: Record<string, unknown>, skipSamplingCheck = false): WideEvent | null {\n if (!globalEnabled) return null\n\n if (!skipSamplingCheck && !shouldSample(level)) {\n return null\n }\n\n const formatted: WideEvent = {\n timestamp: new Date().toISOString(),\n level,\n ...globalEnv,\n ...event,\n }\n\n if (globalPretty) {\n prettyPrintWideEvent(formatted)\n } else if (globalStringify) {\n console[getConsoleMethod(level)](JSON.stringify(formatted))\n } else {\n console[getConsoleMethod(level)](formatted)\n }\n\n if (globalDrain) {\n Promise.resolve(globalDrain({ event: formatted })).catch((err) => {\n console.error('[evlog] drain failed:', err)\n })\n }\n\n return formatted\n}\n\nfunction emitTaggedLog(level: LogLevel, tag: string, message: string): void {\n if (!globalEnabled) return\n\n if (globalPretty) {\n if (!shouldSample(level)) {\n return\n }\n const color = getLevelColor(level)\n const timestamp = new Date().toISOString().slice(11, 23)\n console.log(`${colors.dim}${timestamp}${colors.reset} ${color}[${tag}]${colors.reset} ${message}`)\n return\n }\n emitWideEvent(level, { tag, message })\n}\n\nfunction formatValue(value: unknown): string {\n if (value === null || value === undefined) {\n return String(value)\n }\n if (typeof value === 'object') {\n // Flatten object to key=value pairs\n const pairs: string[] = []\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n if (v !== undefined && v !== null) {\n if (typeof v === 'object') {\n // For nested objects, show as JSON\n pairs.push(`${k}=${JSON.stringify(v)}`)\n } else {\n pairs.push(`${k}=${v}`)\n }\n }\n }\n return pairs.join(' ')\n }\n return String(value)\n}\n\nfunction prettyPrintWideEvent(event: Record<string, unknown>): void {\n const { timestamp, level, service, environment, version, ...rest } = event\n const levelColor = getLevelColor(level as string)\n const ts = (timestamp as string).slice(11, 23)\n\n let header = `${colors.dim}${ts}${colors.reset} ${levelColor}${(level as string).toUpperCase()}${colors.reset}`\n header += ` ${colors.cyan}[${service}]${colors.reset}`\n\n if (rest.method && rest.path) {\n header += ` ${rest.method} ${rest.path}`\n delete rest.method\n delete rest.path\n }\n\n if (rest.status) {\n const statusColor = (rest.status as number) >= 400 ? colors.red : colors.green\n header += ` ${statusColor}${rest.status}${colors.reset}`\n delete rest.status\n }\n\n if (rest.duration) {\n header += ` ${colors.dim}in ${rest.duration}${colors.reset}`\n delete rest.duration\n }\n\n console.log(header)\n\n const entries = Object.entries(rest).filter(([_, v]) => v !== undefined)\n const lastIndex = entries.length - 1\n\n entries.forEach(([key, value], index) => {\n const isLast = index === lastIndex\n const prefix = isLast ? '└─' : '├─'\n const formatted = formatValue(value)\n console.log(` ${colors.dim}${prefix}${colors.reset} ${colors.cyan}${key}:${colors.reset} ${formatted}`)\n })\n}\n\nfunction createLogMethod(level: LogLevel) {\n return function logMethod(tagOrEvent: string | Record<string, unknown>, message?: string): void {\n if (typeof tagOrEvent === 'string' && message !== undefined) {\n emitTaggedLog(level, tagOrEvent, message)\n } else if (typeof tagOrEvent === 'object') {\n emitWideEvent(level, tagOrEvent)\n } else {\n emitTaggedLog(level, 'log', String(tagOrEvent))\n }\n }\n}\n\n/**\n * Simple logging API - as easy as console.log\n *\n * @example\n * ```ts\n * log.info('auth', 'User logged in')\n * log.error({ action: 'payment', error: 'failed' })\n * ```\n */\nconst _log: Log = {\n info: createLogMethod('info'),\n error: createLogMethod('error'),\n warn: createLogMethod('warn'),\n debug: createLogMethod('debug'),\n}\n\nexport { _log as log }\n\nconst noopLogger: RequestLogger = {\n set() {},\n error() {},\n info() {},\n warn() {},\n emit() {\n return null\n },\n getContext() {\n return {}\n },\n}\n\n/**\n * Create a request-scoped logger for building wide events.\n *\n * @example\n * ```ts\n * const log = createRequestLogger({ method: 'POST', path: '/checkout' })\n * log.set({ user: { id: '123' } })\n * log.set({ cart: { items: 3 } })\n * log.emit()\n * ```\n */\nexport function createRequestLogger<T extends object = Record<string, unknown>>(options: RequestLoggerOptions = {}): RequestLogger<T> {\n if (!globalEnabled) return noopLogger as RequestLogger<T>\n\n const startTime = Date.now()\n let context: Record<string, unknown> = {\n method: options.method,\n path: options.path,\n requestId: options.requestId,\n }\n let hasError = false\n let hasWarn = false\n\n function addRequestLog(level: 'info' | 'warn', message: string): void {\n const entry = {\n level,\n message,\n timestamp: new Date().toISOString(),\n }\n\n const requestLogs = Array.isArray(context.requestLogs)\n ? [...context.requestLogs, entry]\n : [entry]\n\n context = {\n ...context,\n requestLogs,\n }\n }\n\n return {\n set(data: FieldContext<T>): void {\n context = deepDefaults(data as Record<string, unknown>, context) as Record<string, unknown>\n },\n\n error(error: Error | string, errorContext?: FieldContext<T>): void {\n hasError = true\n const err = typeof error === 'string' ? new Error(error) : error\n\n const errorData = {\n ...(errorContext as Record<string, unknown>),\n error: {\n name: err.name,\n message: err.message,\n stack: err.stack,\n ...('status' in err && { status: (err as Record<string, unknown>).status }),\n ...('statusText' in err && { statusText: (err as Record<string, unknown>).statusText }),\n ...('statusCode' in err && { statusCode: (err as Record<string, unknown>).statusCode }),\n ...('statusMessage' in err && { statusMessage: (err as Record<string, unknown>).statusMessage }),\n ...('data' in err && { data: (err as Record<string, unknown>).data }),\n ...('cause' in err && { cause: (err as unknown as Record<string, unknown>).cause }),\n },\n }\n context = deepDefaults(errorData, context) as Record<string, unknown>\n },\n\n info(message: string, infoContext?: FieldContext<T>): void {\n addRequestLog('info', message)\n if (infoContext) {\n const { requestLogs: _, ...rest } = infoContext as Record<string, unknown>\n context = deepDefaults(rest, context) as Record<string, unknown>\n }\n },\n\n warn(message: string, warnContext?: FieldContext<T>): void {\n hasWarn = true\n addRequestLog('warn', message)\n if (warnContext) {\n const { requestLogs: _, ...rest } = warnContext as Record<string, unknown>\n context = deepDefaults(rest, context) as Record<string, unknown>\n }\n },\n\n emit(overrides?: FieldContext<T> & { _forceKeep?: boolean }): WideEvent | null {\n const durationMs = Date.now() - startTime\n const duration = formatDuration(durationMs)\n const level: LogLevel = hasError ? 'error' : hasWarn ? 'warn' : 'info'\n\n // Extract _forceKeep from overrides (set by evlog:emit:keep hook)\n const { _forceKeep, ...restOverrides } = (overrides ?? {}) as Record<string, unknown> & { _forceKeep?: boolean }\n\n // Build tail sampling context\n const tailCtx: TailSamplingContext = {\n status: (context.status ?? restOverrides.status) as number | undefined,\n duration: durationMs,\n path: context.path as string | undefined,\n method: context.method as string | undefined,\n context: { ...context, ...restOverrides },\n }\n\n // Tail sampling: force keep if hook or built-in conditions match\n const forceKeep = _forceKeep || shouldKeep(tailCtx)\n\n // Apply head sampling only if not force-kept\n if (!forceKeep && !shouldSample(level)) {\n return null\n }\n\n return emitWideEvent(level, {\n ...context,\n ...restOverrides,\n duration,\n }, true)\n },\n\n getContext(): FieldContext<T> & Record<string, unknown> {\n return { ...context }\n },\n }\n}\n\n/**\n * Get the current environment context.\n */\nexport function getEnvironment(): EnvironmentContext {\n return { ...globalEnv }\n}\n","import { createRequestLogger, initLogger } from 'evlog'\n\n/**\n * Log level for the Stack logger.\n *\n * Configured via the `STASH_STACK_LOG` environment variable.\n *\n * - `'error'` — Only errors (default when `STASH_STACK_LOG` is not set).\n * - `'info'` — Info and errors.\n * - `'debug'` — Debug, info, and errors.\n */\nexport type LogLevel = 'debug' | 'info' | 'error'\n\nconst validLevels: readonly LogLevel[] = ['debug', 'info', 'error'] as const\n\nfunction levelFromEnv(): LogLevel {\n const env = process.env.STASH_STACK_LOG\n if (env && validLevels.includes(env as LogLevel)) return env as LogLevel\n return 'error'\n}\n\nfunction samplingRatesForLevel(level: LogLevel): Record<string, number> {\n // evlog uses sampling rates: 100 = always emit, 0 = never emit\n switch (level) {\n case 'debug':\n return { debug: 100, info: 100, warn: 100, error: 100 }\n case 'info':\n return { debug: 0, info: 100, warn: 100, error: 100 }\n case 'error':\n default:\n return { debug: 0, info: 0, warn: 0, error: 100 }\n }\n}\n\nlet initialized = false\n\n/**\n * Initialize the Stack logger.\n *\n * The log level is read from the `STASH_STACK_LOG` environment variable.\n * When the variable is not set, the default is `'error'` (errors only).\n *\n * @internal\n */\nexport function initStackLogger(): void {\n if (initialized) return\n initialized = true\n\n const level = levelFromEnv()\n const rates = samplingRatesForLevel(level)\n\n initLogger({\n env: { service: '@cipherstash/stack' },\n enabled: true,\n sampling: { rates },\n })\n}\n\n// Auto-init with defaults on first import\ninitStackLogger()\n\nexport { createRequestLogger }\n\n// Stringify only the first arg (the message string); drop subsequent args\n// which may contain sensitive objects (e.g. encryptConfig, plaintext).\nfunction safeMessage(args: unknown[]): string {\n return typeof args[0] === 'string' ? args[0] : ''\n}\n\n// Logger for simple one-off logs used across Stack interfaces.\nexport const logger = {\n debug(...args: unknown[]) {\n const log = createRequestLogger()\n log.set({\n level: 'debug',\n source: '@cipherstash/stack',\n message: safeMessage(args),\n })\n log.emit()\n },\n info(...args: unknown[]) {\n const log = createRequestLogger()\n log.set({ source: '@cipherstash/stack' })\n log.info(safeMessage(args))\n log.emit()\n },\n warn(...args: unknown[]) {\n const log = createRequestLogger()\n log.warn(safeMessage(args))\n log.emit()\n },\n error(...args: unknown[]) {\n const log = createRequestLogger()\n log.error(safeMessage(args))\n log.emit()\n },\n}\n","import type {\n Encrypted as CipherStashEncrypted,\n EncryptedQuery as CipherStashEncryptedQuery,\n EncryptedV3Query as CipherStashEncryptedV3Query,\n KeysetIdentifier as KeysetIdentifierFfi,\n} from '@cipherstash/protect-ffi'\nimport type { Encrypted, EncryptedQueryResult, KeysetIdentifier } from '@/types'\n\n/**\n * The shape `encryptQuery` / `encryptQueryBulk` can return: a full storage\n * payload (returned for v2 `ste_vec_term` containment queries), a query-only\n * payload with no ciphertext (scalar `unique`/`match`/`ore` lookups and\n * `ste_vec_selector` path queries), or — under `eqlVersion: 3` — the\n * `eql_v3.jsonb_query` containment needle.\n *\n * TODO: duplicated in `@cipherstash/protect` — see\n * `packages/protect/src/helpers/index.ts`. Both copies should be removed once\n * `@cipherstash/protect-ffi` exports a named alias for the `encryptQuery`\n * return type (https://github.com/cipherstash/stack/pull/473).\n */\ntype EncryptedQueryTerm =\n | CipherStashEncrypted\n | CipherStashEncryptedQuery\n | CipherStashEncryptedV3Query\n\nexport type EncryptedPgComposite = {\n data: Encrypted\n}\n\n/**\n * Helper function to transform an encrypted payload into a PostgreSQL composite type.\n * Use this when inserting data via Supabase or similar clients.\n */\nexport function encryptedToPgComposite(obj: Encrypted): EncryptedPgComposite {\n return {\n data: obj,\n }\n}\n\n/**\n * Helper function to transform an encrypted payload into a PostgreSQL composite literal string.\n * Use this when querying with `.eq()` or similar equality operations in Supabase.\n *\n * @example\n * ```typescript\n * const literal = encryptedToCompositeLiteral(encrypted)\n * await supabase.from('table').select().eq('column', literal)\n * ```\n */\nexport function encryptedToCompositeLiteral(obj: EncryptedQueryTerm): string {\n return `(${JSON.stringify(JSON.stringify(obj))})`\n}\n\n/**\n * Helper function to transform an encrypted payload into an escaped PostgreSQL composite literal string.\n * Use this when you need the composite literal format to be escaped as a string value.\n *\n * @example\n * ```typescript\n * const escapedLiteral = encryptedToEscapedCompositeLiteral(encrypted)\n * ```\n */\nexport function encryptedToEscapedCompositeLiteral(\n obj: EncryptedQueryTerm,\n): string {\n return JSON.stringify(encryptedToCompositeLiteral(obj))\n}\n\n/**\n * Format an encrypted result based on the requested return type.\n *\n * - `'composite-literal'` → PostgreSQL composite literal string `(\"json\")`\n * - `'escaped-composite-literal'` → escaped variant `\"(\\\"json\\\")\"`\n * - default (`'eql'` or omitted) → raw encrypted object\n */\nexport function formatEncryptedResult(\n encrypted: EncryptedQueryTerm,\n returnType?: string,\n): EncryptedQueryResult {\n if (returnType === 'composite-literal') {\n return encryptedToCompositeLiteral(encrypted)\n }\n if (returnType === 'escaped-composite-literal') {\n return encryptedToEscapedCompositeLiteral(encrypted)\n }\n return encrypted\n}\n\n/**\n * Helper function to transform a model's encrypted fields into PostgreSQL composite types\n */\nexport function modelToEncryptedPgComposites<T extends Record<string, unknown>>(\n model: T,\n): T {\n const result: Record<string, unknown> = {}\n\n for (const [key, value] of Object.entries(model)) {\n if (isEncryptedPayload(value)) {\n result[key] = encryptedToPgComposite(value)\n } else {\n result[key] = value\n }\n }\n\n return result as T\n}\n\n/**\n * Helper function to transform multiple models' encrypted fields into PostgreSQL composite types\n */\nexport function bulkModelsToEncryptedPgComposites<\n T extends Record<string, unknown>,\n>(models: T[]): T[] {\n return models.map((model) => modelToEncryptedPgComposites(model))\n}\n\nexport function toFfiKeysetIdentifier(\n keyset: KeysetIdentifier | undefined,\n): KeysetIdentifierFfi | undefined {\n if (!keyset) return undefined\n\n if ('name' in keyset) {\n return { Name: keyset.name }\n }\n\n return { Uuid: keyset.id }\n}\n\n/**\n * Helper function to check if a value is an encrypted payload\n */\nexport function isEncryptedPayload(value: unknown): value is Encrypted {\n if (value === null) return false\n if (typeof value !== 'object') return false\n\n const obj = value as Record<string, unknown>\n\n // Must have version field (number)\n if (!('v' in obj) || typeof obj.v !== 'number') return false\n\n // Must have index field (object)\n if (!('i' in obj) || typeof obj.i !== 'object') return false\n\n // Must have either ciphertext (c) or searchable vector (sv)\n if (!('c' in obj) && !('sv' in obj)) return false\n\n return true\n}\n\nexport {\n buildNestedObject,\n parseJsonbPath,\n toJsonPath,\n} from './jsonb'\n","import type { ScalarQueryTerm } from '../../types'\n\n/**\n * Type guard to check if a value is an array of ScalarQueryTerm objects.\n * Used to discriminate between single value and bulk encryption in encryptQuery overloads.\n */\nexport function isScalarQueryTermArray(\n value: unknown,\n): value is readonly ScalarQueryTerm[] {\n return (\n Array.isArray(value) &&\n value.length > 0 &&\n typeof value[0] === 'object' &&\n value[0] !== null &&\n 'column' in value[0] &&\n 'table' in value[0]\n )\n}\n","import { type Result, withResult } from '@byteslice/result'\nimport type {\n Encrypted as CipherStashEncrypted,\n EncryptedQuery as CipherStashEncryptedQuery,\n EncryptedV3Query as CipherStashEncryptedV3Query,\n} from '@cipherstash/protect-ffi'\nimport {\n encryptQueryBulk as ffiEncryptQueryBulk,\n type JsPlaintext,\n type QueryPayload,\n} from '@cipherstash/protect-ffi'\nimport { formatEncryptedResult } from '@/encryption/helpers'\nimport { getErrorCode } from '@/encryption/helpers/error-code'\nimport { type EncryptionError, EncryptionErrorTypes } from '@/errors'\nimport {\n type Context,\n type LockContextInput,\n resolveLockContext,\n} from '@/identity'\nimport type { Client, EncryptedQueryResult, ScalarQueryTerm } from '@/types'\nimport { createRequestLogger } from '@/utils/logger'\nimport { resolveIndexType } from '../helpers/infer-index-type'\nimport {\n assertValidNumericValue,\n assertValueIndexCompatibility,\n} from '../helpers/validation'\nimport { noClientError } from '../index'\nimport { EncryptionOperation } from './base-operation'\n\n// Separates null/undefined values from non-null terms in the input array\n// so they bypass the FFI call. Original indices are tracked so the\n// reassembled result preserves position.\nfunction filterNullTerms(terms: readonly ScalarQueryTerm[]): {\n nonNullTerms: { term: ScalarQueryTerm; originalIndex: number }[]\n} {\n const nonNullTerms: { term: ScalarQueryTerm; originalIndex: number }[] = []\n terms.forEach((term, index) => {\n if (term.value !== null && term.value !== undefined) {\n nonNullTerms.push({ term, originalIndex: index })\n }\n })\n return { nonNullTerms }\n}\n\n/**\n * Validates and transforms a single term into a QueryPayload.\n * Throws an error if the value is NaN or Infinity.\n * Optionally includes lockContext if provided.\n */\nfunction buildQueryPayload(\n term: ScalarQueryTerm,\n lockContext?: Context,\n): QueryPayload {\n assertValidNumericValue(term.value)\n\n const { indexType, queryOp } = resolveIndexType(\n term.column,\n term.queryType,\n term.value,\n )\n\n // Validate value/index compatibility\n assertValueIndexCompatibility(term.value, indexType, term.column.getName())\n\n const payload: QueryPayload = {\n plaintext: term.value as JsPlaintext,\n column: term.column.getName(),\n table: term.table.tableName,\n indexType,\n queryOp,\n }\n\n if (lockContext != null) {\n payload.lockContext = lockContext\n }\n\n return payload\n}\n\n/**\n * Reassembles the result array, slotting null at the original indices of\n * filtered-out terms and formatting encrypted values for non-null terms.\n */\nfunction assembleResults(\n totalLength: number,\n // Typed as the FFI bulk-query return so it tracks the upstream union. As of\n // protect-ffi 0.27 that union also includes `SteVecQuery`, but scalar query\n // terms (all this operation builds) never produce a ste_vec result, so each\n // element is narrowed back to the scalar shape `formatEncryptedResult` takes.\n encryptedValues: Awaited<ReturnType<typeof ffiEncryptQueryBulk>>,\n nonNullTerms: { term: ScalarQueryTerm; originalIndex: number }[],\n): EncryptedQueryResult[] {\n const results: EncryptedQueryResult[] = new Array(totalLength).fill(null)\n nonNullTerms.forEach(({ term, originalIndex }, i) => {\n results[originalIndex] = formatEncryptedResult(\n encryptedValues[i] as CipherStashEncrypted | CipherStashEncryptedQuery,\n term.returnType,\n )\n })\n return results\n}\n\nexport class BatchEncryptQueryOperation extends EncryptionOperation<\n EncryptedQueryResult[]\n> {\n constructor(\n private client: Client,\n private terms: readonly ScalarQueryTerm[],\n ) {\n super()\n }\n\n public withLockContext(\n lockContext: LockContextInput,\n ): BatchEncryptQueryOperationWithLockContext {\n return new BatchEncryptQueryOperationWithLockContext(\n this.client,\n this.terms,\n lockContext,\n this.auditMetadata,\n )\n }\n\n public async execute(): Promise<\n Result<EncryptedQueryResult[], EncryptionError>\n > {\n const log = createRequestLogger()\n log.set({\n op: 'batchEncryptQuery',\n count: this.terms.length,\n lockContext: false,\n })\n\n if (this.terms.length === 0) {\n log.emit()\n return { data: [] }\n }\n\n const { nonNullTerms } = filterNullTerms(this.terms)\n\n if (nonNullTerms.length === 0) {\n log.emit()\n return { data: this.terms.map(() => null) }\n }\n\n const result = await withResult(\n async () => {\n if (!this.client) throw noClientError()\n\n const { metadata } = this.getAuditData()\n\n const queries: QueryPayload[] = nonNullTerms.map(({ term }) =>\n buildQueryPayload(term),\n )\n\n const encrypted = await ffiEncryptQueryBulk(this.client, {\n queries,\n unverifiedContext: metadata,\n })\n\n return assembleResults(this.terms.length, encrypted, nonNullTerms)\n },\n (error: unknown) => {\n log.set({ errorCode: getErrorCode(error) ?? 'unknown' })\n return {\n type: EncryptionErrorTypes.EncryptionError,\n message: (error as Error).message,\n code: getErrorCode(error),\n }\n },\n )\n log.emit()\n return result\n }\n}\n\nexport class BatchEncryptQueryOperationWithLockContext extends EncryptionOperation<\n EncryptedQueryResult[]\n> {\n constructor(\n private client: Client,\n private terms: readonly ScalarQueryTerm[],\n private lockContext: LockContextInput,\n auditMetadata?: Record<string, unknown>,\n ) {\n super()\n this.auditMetadata = auditMetadata\n }\n\n public async execute(): Promise<\n Result<EncryptedQueryResult[], EncryptionError>\n > {\n const log = createRequestLogger()\n log.set({\n op: 'batchEncryptQuery',\n count: this.terms.length,\n lockContext: true,\n })\n\n if (this.terms.length === 0) {\n log.emit()\n return { data: [] }\n }\n\n const { nonNullTerms } = filterNullTerms(this.terms)\n\n if (nonNullTerms.length === 0) {\n log.emit()\n return { data: this.terms.map(() => null) }\n }\n\n const result = await withResult(\n async () => {\n if (!this.client) throw noClientError()\n\n const context = resolveLockContext(this.lockContext)\n\n const { metadata } = this.getAuditData()\n\n const queries: QueryPayload[] = nonNullTerms.map(({ term }) =>\n buildQueryPayload(term, context),\n )\n\n const encrypted = await ffiEncryptQueryBulk(this.client, {\n queries,\n unverifiedContext: metadata,\n })\n\n return assembleResults(this.terms.length, encrypted, nonNullTerms)\n },\n (error: unknown) => {\n log.set({ errorCode: getErrorCode(error) ?? 'unknown' })\n return {\n type: EncryptionErrorTypes.EncryptionError,\n message: (error as Error).message,\n code: getErrorCode(error),\n }\n },\n )\n log.emit()\n return result\n }\n}\n","import {\n ProtectError as FfiProtectError,\n type ProtectErrorCode,\n} from '@cipherstash/protect-ffi'\n\n/**\n * Extracts FFI error code from an error if it's an FFI error, otherwise returns undefined.\n * Used to preserve specific error codes in ProtectError responses.\n */\nexport function getErrorCode(error: unknown): ProtectErrorCode | undefined {\n return error instanceof FfiProtectError ? error.code : undefined\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\n\n/**\n * A lightweight function that parses a TOML-like string\n * and returns the `workspace_crn` value found under `[auth]`.\n *\n * @param tomlString The contents of the TOML file as a string.\n * @returns The workspace_crn if found, otherwise undefined.\n */\nfunction getWorkspaceCrn(tomlString: string): string | undefined {\n let currentSection = ''\n let workspaceCrn: string | undefined\n\n const lines = tomlString.split(/\\r?\\n/)\n\n for (const line of lines) {\n const trimmedLine = line.trim()\n\n if (!trimmedLine || trimmedLine.startsWith('#')) {\n continue\n }\n\n const sectionMatch = trimmedLine.match(/^\\[([^\\]]+)\\]$/)\n if (sectionMatch) {\n currentSection = sectionMatch[1]\n continue\n }\n\n const kvMatch = trimmedLine.match(/^(\\w+)\\s*=\\s*\"([^\"]+)\"$/)\n if (kvMatch) {\n const [_, key, value] = kvMatch\n\n if (currentSection === 'auth' && key === 'workspace_crn') {\n workspaceCrn = value\n break\n }\n }\n }\n\n return workspaceCrn\n}\n\n/**\n * Extracts the workspace ID from a CRN string.\n * CRN format: crn:region.aws:ID\n *\n * @param crn The CRN string to extract from\n * @returns The workspace ID portion of the CRN\n */\nexport function extractWorkspaceIdFromCrn(crn: string): string {\n const match = crn.match(/crn:[^:]+:([^:]+)$/)\n if (!match) {\n throw new Error('Invalid CRN format')\n }\n return match[1]\n}\n\nexport function loadWorkSpaceId(suppliedCrn?: string): string {\n const configPath = path.join(process.cwd(), 'cipherstash.toml')\n\n if (suppliedCrn) {\n return extractWorkspaceIdFromCrn(suppliedCrn)\n }\n\n if (!fs.existsSync(configPath) && !process.env.CS_WORKSPACE_CRN) {\n throw new Error(\n 'You have not defined a workspace CRN in your config file, or the CS_WORKSPACE_CRN environment variable.',\n )\n }\n\n // Environment variables take precedence over config files\n if (process.env.CS_WORKSPACE_CRN) {\n return extractWorkspaceIdFromCrn(process.env.CS_WORKSPACE_CRN)\n }\n\n if (!fs.existsSync(configPath)) {\n throw new Error(\n 'You have not defined a workspace CRN in your config file, or the CS_WORKSPACE_CRN environment variable.',\n )\n }\n\n const tomlString = fs.readFileSync(configPath, 'utf8')\n const workspaceCrn = getWorkspaceCrn(tomlString)\n\n if (!workspaceCrn) {\n throw new Error(\n 'You have not defined a workspace CRN in your config file, or the CS_WORKSPACE_CRN environment variable.',\n )\n }\n\n return extractWorkspaceIdFromCrn(workspaceCrn)\n}\n","import { type Result, withResult } from '@byteslice/result'\nimport { type EncryptionError, EncryptionErrorTypes } from '@/errors'\nimport { loadWorkSpaceId } from '@/utils/config'\nimport { logger } from '@/utils/logger'\n\nexport type CtsRegions = 'ap-southeast-2'\n\nexport type IdentifyOptions = {\n fetchFromCts?: boolean\n}\n\nexport type CtsToken = {\n accessToken: string\n expiry: number\n}\n\nexport type Context = {\n identityClaim: string[]\n}\n\nexport type LockContextOptions = {\n context?: Context\n ctsToken?: CtsToken\n}\n\nexport type GetLockContextResponse = {\n ctsToken?: CtsToken\n context: Context\n}\n\n/**\n * The accepted argument to `.withLockContext()` — either a {@link LockContext}\n * or a plain identity-claim spec (e.g. `{ identityClaim: ['sub'] }`).\n */\nexport type LockContextInput = LockContext | Context\n\n/**\n * Resolve a {@link LockContextInput} to the {@link Context} (identity claim)\n * that protect-ffi expects. Synchronous — no token round-trip.\n */\nexport function resolveLockContext(input: LockContextInput): Context {\n // Use a structural check as well as `instanceof` so a `LockContext`\n // constructed in another realm (or from a duplicate module instance) is still\n // resolved rather than slipping through as a raw `Context`.\n return input instanceof LockContext || 'identityContext' in input\n ? (input as LockContext).identityContext\n : input\n}\n\n/**\n * Binds an encryption/decryption operation to a user's identity by selecting\n * which JWT claim(s) ZeroKMS bakes into the data key's tag (the *lock context*).\n *\n * The claim **value** is resolved by ZeroKMS from the token that authenticates\n * the request — so to bind to a real end user, authenticate the client as that\n * user with an `OidcFederationStrategy` (from `@cipherstash/auth`) and pass the\n * claim to `.withLockContext()`. The same context must be supplied to decrypt.\n *\n * You can pass a plain `{ identityClaim }` directly — constructing a\n * `LockContext` is optional.\n *\n * @example\n * ```typescript\n * import { Encryption } from \"@cipherstash/stack\"\n * import { OidcFederationStrategy } from \"@cipherstash/auth\"\n *\n * // Authenticate the client as the end user (replaces the old identify() flow).\n * const client = await Encryption({\n * schemas,\n * config: {\n * authStrategy: OidcFederationStrategy.create(workspaceCrn, () => getJwt()),\n * },\n * })\n *\n * // Bind the key to the user's `sub` claim — no token, no identify().\n * const result = await client\n * .encrypt(value, { column: users.email, table: users })\n * .withLockContext({ identityClaim: [\"sub\"] })\n * ```\n */\nexport class LockContext {\n private ctsToken: CtsToken | undefined\n private workspaceId: string\n private context: Context\n\n constructor({\n context = { identityClaim: ['sub'] },\n ctsToken,\n }: LockContextOptions = {}) {\n const workspaceId = loadWorkSpaceId()\n\n if (!workspaceId) {\n throw new Error(\n 'You have not defined a workspace ID in your config file, or the CS_WORKSPACE_CRN environment variable.',\n )\n }\n\n if (ctsToken) {\n this.ctsToken = ctsToken\n }\n\n this.workspaceId = workspaceId\n this.context = context\n logger.debug('Successfully initialized the EQL lock context.')\n }\n\n /**\n * The identity-claim context this lock context binds to, e.g.\n * `{ identityClaim: ['sub'] }`. Resolved synchronously — `.withLockContext()`\n * uses this directly; no CTS token is required.\n */\n get identityContext(): Context {\n return this.context\n }\n\n /**\n * Exchange a user's JWT for a CTS token and bind it to this lock context.\n *\n * @deprecated Per-operation CTS tokens were removed in protect-ffi 0.25.\n * Authenticate the client as the user with an `OidcFederationStrategy`\n * (`config.authStrategy`) instead, and pass the claim to `.withLockContext()`.\n * The token fetched here is no longer used by encryption operations. This\n * method is kept for backwards compatibility and will be removed in a\n * future major release.\n *\n * @param jwtToken - A valid OIDC / JWT token for the current user.\n * @returns A `Result` containing this `LockContext` or an error.\n */\n async identify(\n jwtToken: string,\n ): Promise<Result<LockContext, EncryptionError>> {\n const workspaceId = this.workspaceId\n\n const ctsEndpoint =\n process.env.CS_CTS_ENDPOINT ||\n 'https://ap-southeast-2.aws.auth.viturhosted.net'\n\n const ctsFetchResult = await withResult(\n () =>\n fetch(`${ctsEndpoint}/api/authorize`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n workspaceId,\n oidcToken: jwtToken,\n }),\n }),\n (error) => ({\n type: EncryptionErrorTypes.CtsTokenError,\n message: error.message,\n }),\n )\n\n if (ctsFetchResult.failure) {\n return ctsFetchResult\n }\n\n const identifiedLockContext = await withResult(\n async () => {\n const ctsToken = (await ctsFetchResult.data.json()) as CtsToken\n\n if (!ctsToken.accessToken) {\n throw new Error(\n 'The response from the CipherStash API did not contain an access token. Please contact support.',\n )\n }\n\n this.ctsToken = ctsToken\n return this\n },\n (error) => ({\n type: EncryptionErrorTypes.CtsTokenError,\n message: error.message,\n }),\n )\n\n return identifiedLockContext\n }\n\n /**\n * Retrieve the identity context (and CTS token, if one was set).\n *\n * @deprecated Encryption operations no longer consume a CTS token — they read\n * the identity claim directly via {@link identityContext}. Pass the claim to\n * `.withLockContext()` and authenticate the client with an\n * `OidcFederationStrategy` instead. Kept for backwards compatibility; the\n * returned `ctsToken` is `undefined` unless one was supplied to the\n * constructor or {@link identify} was called.\n */\n getLockContext(): Promise<Result<GetLockContextResponse, EncryptionError>> {\n return withResult(\n () => ({\n context: this.context,\n // Only include `ctsToken` when one was actually set, so the\n // returned shape matches the optional `ctsToken?` type rather\n // than carrying an explicit `undefined`.\n ...(this.ctsToken ? { ctsToken: this.ctsToken } : {}),\n }),\n (error) => ({\n type: EncryptionErrorTypes.CtsTokenError,\n message: error.message,\n }),\n )\n }\n}\n","import type {\n AuthStrategy,\n Encrypted as CipherStashEncrypted,\n EncryptedPayload as CipherStashEncryptedPayload,\n EncryptedQuery as CipherStashEncryptedQuery,\n EncryptedV3Query as CipherStashEncryptedV3Query,\n JsPlaintext,\n newClient,\n QueryOpName,\n} from '@cipherstash/protect-ffi'\nimport type {\n ColumnSchema,\n EncryptedColumn,\n EncryptedField,\n EncryptedTableColumn,\n // Imported type-only for the TSDoc {@link} references in the comments below.\n encryptedColumn,\n encryptedField,\n} from '@/schema'\n\n/**\n * A pluggable authentication strategy for ZeroKMS requests. Any object\n * with a `getToken(): Promise<{ token: string }>` method satisfies it —\n * notably the strategies from `@cipherstash/auth`: `OidcFederationStrategy`\n * (per-user, identity-bound encryption) and `AccessKeyStrategy`\n * (service-to-service / CI). When supplied to {@link ClientConfig.authStrategy},\n * `getToken()` is invoked on every ZeroKMS request, taking precedence over\n * the default `auto` strategy.\n *\n * @see ClientConfig.authStrategy\n */\nexport type { AuthStrategy }\n\n// ---------------------------------------------------------------------------\n// Branded type utilities\n// ---------------------------------------------------------------------------\n\n/** Brand symbol for nominal typing */\ndeclare const __brand: unique symbol\n\n/** Creates a branded type that is structurally incompatible with the base type */\ntype Brand<T, B extends string> = T & { readonly [__brand]: B }\n\n// ---------------------------------------------------------------------------\n// Core types\n// ---------------------------------------------------------------------------\n\nexport type Client = Awaited<ReturnType<typeof newClient>> | undefined\n\n/** A branded type representing encrypted data. Cannot be accidentally used as plaintext. */\nexport type EncryptedValue = Brand<CipherStashEncrypted, 'encrypted'>\n\n/** Structural type representing encrypted data stored in the database. Always\n * carries a ciphertext. Covers BOTH wire formats: the EQL v2.3 payloads\n * (`k: \"ct\"` / `k: \"sv\"`) and the EQL v3 payloads (flat `{v: 3, i, c, …}`\n * scalars and `{v: 3, k: \"sv\", i, sv}` SteVec documents). Which format\n * `encrypt` produces is selected by the client's\n * {@link ClientConfig.eqlVersion}; `decrypt` accepts both regardless.\n * v3 scalars carry no `k` discriminator, so narrow with `'k' in payload`\n * before reading it. See also `EncryptedValue` for branded nominal typing,\n * and {@link EncryptedQuery} for the search-term shape returned by\n * `encryptQuery`. */\nexport type Encrypted = CipherStashEncryptedPayload\n\n/** Structural type representing an encrypted query term (search needle)\n * returned by `encryptQuery` / `encryptQueryBulk` for scalar\n * (`unique` / `match` / `ore`) lookups and `ste_vec_selector` JSON path\n * queries, plus — under `eqlVersion: 3` — the `eql_v3.jsonb_query`\n * containment needle. Carries no ciphertext — matched against stored\n * values, never decrypted. v2 JSON containment queries (`ste_vec_term`)\n * return a storage-shaped {@link Encrypted} payload instead. */\nexport type EncryptedQuery =\n | CipherStashEncryptedQuery\n | CipherStashEncryptedV3Query\n\n/**\n * Plaintext values the SDK accepts for encryption.\n *\n * Widens the FFI's `JsPlaintext` (`string | number | boolean |\n * Record<string, unknown> | JsPlaintext[]`) with `Date` and `bigint`. `Date`\n * is a supported cast target that is omitted from the FFI's `JsPlaintext` INPUT\n * union, but it serializes at the boundary via `toJSON` (ISO string), so it is\n * accepted on the way in.\n *\n * `bigint` is the plaintext for the v3 int8/bigint domains (see `eql/v3`),\n * which always decrypt to a JS `bigint`. protect-ffi 0.28 marshals a native\n * `bigint` across the Neon boundary losslessly. i64 bounds\n * (`-2^63 … 2^63 - 1`) are enforced at the protect-ffi boundary, not here —\n * out-of-range values surface as encryption errors from the FFI.\n *\n * When the upstream FFI `JsPlaintext` includes `Date` and `bigint`, both extra\n * arms can collapse back into `JsPlaintext`.\n */\nexport type Plaintext = JsPlaintext | Date | bigint\n\n// ---------------------------------------------------------------------------\n// Client configuration\n// ---------------------------------------------------------------------------\n\nexport type KeysetIdentifier = { name: string } | { id: string }\n\nexport type ClientConfig = {\n /**\n * The CipherStash workspace CRN (Cloud Resource Name).\n * Format: `crn:<region>.aws:<workspace-id>`.\n * Can also be set via the `CS_WORKSPACE_CRN` environment variable.\n */\n workspaceCrn?: string\n\n /**\n * The API access key used for authenticating with the CipherStash API.\n * Can also be set via the `CS_CLIENT_ACCESS_KEY` environment variable.\n * Obtain this from the CipherStash dashboard after creating a workspace.\n */\n accessKey?: string\n\n /**\n * The client identifier used to authenticate with CipherStash services.\n * Can also be set via the `CS_CLIENT_ID` environment variable.\n * Generated during workspace onboarding in the CipherStash dashboard.\n */\n clientId?: string\n\n /**\n * The client key material used in combination with ZeroKMS for encryption operations.\n * Can also be set via the `CS_CLIENT_KEY` environment variable.\n * Generated during workspace onboarding in the CipherStash dashboard.\n */\n clientKey?: string\n\n /**\n * An optional keyset identifier for multi-tenant encryption.\n * Each keyset provides cryptographic isolation, giving each tenant its own keyspace.\n * Specify by name (`{ name: \"tenant-a\" }`) or UUID (`{ id: \"...\" }`).\n * Keysets are created and managed in the\n * [dashboard](https://dashboard.cipherstash.com/workspaces/_/keysets); omit to\n * use the workspace's default keyset. A client is bound to one keyset for its\n * lifetime, so use one client per tenant.\n *\n * @see {@link Encryption} for the full keysets walkthrough.\n */\n keyset?: KeysetIdentifier\n\n /**\n * An optional authentication strategy for ZeroKMS requests, from\n * `@cipherstash/auth` (re-exported by `@cipherstash/stack`). When provided,\n * its `getToken()` is invoked on every ZeroKMS request and takes precedence\n * over the default `auto` strategy (the `clientKey` is still required for\n * encryption). Use:\n *\n * - `OidcFederationStrategy` for per-user, identity-bound encryption —\n * federates an end user's OIDC JWT into a CTS service token, so requests\n * authenticate as that user. Pair with `.withLockContext({ identityClaim })`\n * to bind the data key to a claim. This replaces the older\n * `LockContext.identify()` ceremony.\n * - `AccessKeyStrategy` for service-to-service / CI, or any custom\n * `{ getToken() }` object for bespoke token acquisition / caching.\n *\n * Leave unset to use the default `auto` strategy, which reads credentials\n * from the `CS_*` environment variables and falls back to the local dev\n * profile created by `npx stash auth login`.\n *\n * @see {@link AuthStrategy}\n * @see {@link Encryption} for a full walkthrough of the authentication options.\n */\n authStrategy?: AuthStrategy\n\n /**\n * @deprecated Renamed to {@link ClientConfig.authStrategy}. Still honoured for\n * backwards compatibility — passing it logs a deprecation warning at runtime —\n * but it will be removed in a future release. Set `authStrategy` instead.\n */\n strategy?: AuthStrategy\n\n /**\n * The EQL wire version the client emits — one FFI client always emits\n * exactly one wire format.\n *\n * - `2` (the protect-ffi default): payloads target the\n * `eql_v2_encrypted` column type.\n * - `3`: payloads target the per-capability `eql_v3` domains\n * (`eql_v3.text_eq`, `eql_v3.integer_ord_ore`, `eql_v3.json`, …),\n * derived from each column's `cast_as` and indexes.\n *\n * When omitted, {@link Encryption} auto-detects from the schema set:\n * EQL v3 tables (from `@cipherstash/stack/v3`, marked by\n * `buildColumnKeyMap()`) select `3`; v2 tables leave the FFI default\n * (`2`) untouched. Mixing v2 and v3 tables in one client is an error —\n * split them across two clients instead.\n *\n * `decrypt` accepts BOTH formats regardless of this setting, so v2 and\n * v3 data can coexist during a migration.\n *\n * Under `3`, `encryptQuery` returns EQL v3 query operands (protect-ffi\n * 0.29+): term-only scalar operands for the `eql_v3.query_<name>` twins,\n * the `eql_v3.query_jsonb` containment needle, and bare selector-hash\n * strings for JSON path queries.\n */\n eqlVersion?: 2 | 3\n}\n\ntype AtLeastOneCsTable<T> = [T, ...T[]]\n\n/** Structural contract for a column builder the client can consume for STORAGE\n * (`encrypt`). Satisfied by v2 `EncryptedColumn` / `EncryptedField` AND v3\n * `EncryptedTextSearchColumn` — fields ARE encryptable, so this stays wide. */\nexport interface BuildableColumn {\n getName(): string\n build(): ColumnSchema\n}\n\n/** Structural contract for a column the client can consume for QUERIES\n * (`encryptQuery` / search terms). Narrower than `BuildableColumn`: it must\n * EXCLUDE non-queryable `EncryptedField` (a field has no indexes). A v2\n * `EncryptedColumn` qualifies via the nominal arm; a v3 queryable concrete\n * type qualifies via the `getEqlType()` structural arm; `EncryptedField` (no\n * `getEqlType`, not an `EncryptedColumn`) is rejected. */\nexport interface BuildableV3QueryableColumn extends BuildableColumn {\n getEqlType(): string\n getQueryCapabilities(): {\n equality: boolean\n orderAndRange: boolean\n freeTextSearch: boolean\n }\n isQueryable(): true\n}\n\nexport type BuildableQueryColumn = EncryptedColumn | BuildableV3QueryableColumn\n\n/** Structural contract for a table builder the client can consume. Satisfied by\n * v2 and v3 `EncryptedTable` alike. */\nexport interface BuildableTable {\n tableName: string\n build(): { tableName: string; columns: Record<string, ColumnSchema> }\n /**\n * Optional map from a model field's JS property name to its encrypt-config\n * column name (the DB name). Present when the two can differ — v3 tables key\n * their config by DB name (`column.getName()`) while models are written with\n * JS property keys, so the model path must match by property but address the\n * FFI/config by DB name.\n *\n * Absent on v2 tables, whose `build()` already keys columns by the JS property\n * name; the model path then matches and addresses by that same key.\n */\n buildColumnKeyMap?(): Record<string, string>\n}\n\nexport type EncryptionClientConfig = {\n schemas: AtLeastOneCsTable<BuildableTable>\n config?: ClientConfig\n}\n\n/**\n * The literal column map of a buildable table, read from its type-level\n * `_columnType` brand. Both v2 and v3 `EncryptedTable` carry this brand, so this\n * recovers the literal column keys structurally.\n *\n * This deliberately uses the `_columnType` brand rather than `build().columns`:\n * `BuildableTable.build()` is typed to return `Record<string, ColumnSchema>`,\n * which erases the literal keys and would mark EVERY model field as encrypted.\n *\n * The fallbacks resolve to `Record<never, never>` (a no-key type), NOT `never`:\n * a value typed as the bare structural `BuildableTable` carries no `_columnType`\n * brand, and `keyof never` is `string | number | symbol` — which would wrongly\n * mark EVERY model field as encrypted. `keyof Record<never, never>` is `never`,\n * so `EncryptedFromBuildableTable` degrades gracefully to the model unchanged.\n */\nexport type BuildableTableColumns<T extends BuildableTable> = T extends {\n readonly _columnType: infer C\n}\n ? C extends Record<string, unknown>\n ? C\n : Record<never, never>\n : Record<never, never>\n\n/**\n * Maps a plaintext model type to its encrypted form using a buildable table.\n *\n * Fields whose keys match a column defined in `Table` (via its `_columnType`\n * brand) become `Encrypted` (`Encrypted | null` when the source field is\n * nullable); all other fields retain their original types from `T`. Works for\n * both v2 and v3 tables. See {@link EncryptedFromSchema} for the v2-specific\n * variant retained for backward compatibility.\n */\nexport type EncryptedFromBuildableTable<T, Table extends BuildableTable> = {\n [K in keyof T]: [K] extends [keyof BuildableTableColumns<Table>]\n ? null extends T[K]\n ? Encrypted | null\n : Encrypted\n : T[K]\n}\n\n// ---------------------------------------------------------------------------\n// Encrypt / decrypt operation options and results\n// ---------------------------------------------------------------------------\n\n/**\n * Options for single-value encrypt operations.\n * Use a column from your table schema (from {@link encryptedColumn}) or a nested\n * field (from {@link encryptedField}) as the target for encryption.\n */\nexport type EncryptOptions = {\n /** The column or nested field to encrypt into. From {@link EncryptedColumn} or {@link EncryptedField}. */\n column: BuildableColumn // storage: fields are encryptable, so stays wide\n table: BuildableTable\n}\n\n/** Format for encrypted query/search term return values */\nexport type EncryptedReturnType =\n | 'eql'\n | 'composite-literal'\n | 'escaped-composite-literal'\n\nexport type SearchTerm = {\n value: Plaintext\n column: BuildableQueryColumn // query: excludes non-queryable EncryptedField\n table: BuildableTable\n returnType?: EncryptedReturnType\n}\n\n/** Encrypted search term result. `eql` return type yields either a storage\n * payload (`Encrypted`, for `ste_vec_term`) or a query-only term\n * (`EncryptedQuery`, for scalar lookups and `ste_vec_selector`); the\n * `composite-literal` return types yield a string. */\nexport type EncryptedSearchTerm = Encrypted | EncryptedQuery | string\n\n/** Result of encryptQuery (single or batch). `eql` return type yields either a\n * storage payload (`Encrypted`) or a query-only term (`EncryptedQuery`); the\n * `composite-literal` return types yield a string. */\n// null elements appear in the batch path when a term has a null/undefined\n// value — the operation preserves position so callers can correlate results\n// with their input array.\nexport type EncryptedQueryResult = Encrypted | EncryptedQuery | string | null\n\n// ---------------------------------------------------------------------------\n// Model field types (encrypted vs decrypted views)\n// ---------------------------------------------------------------------------\n\nexport type EncryptedFields<T> = {\n [K in keyof T as NonNullable<T[K]> extends Encrypted ? K : never]: T[K]\n}\n\nexport type OtherFields<T> = {\n [K in keyof T as NonNullable<T[K]> extends Encrypted ? never : K]: T[K]\n}\n\nexport type DecryptedFields<T> = {\n [K in keyof T as NonNullable<T[K]> extends Encrypted\n ? K\n : never]: null extends T[K] ? string | null : string\n}\n\n/** Model with encrypted fields replaced by plaintext (decrypted) values */\nexport type Decrypted<T> = OtherFields<T> & DecryptedFields<T>\n\n/**\n * Maps a plaintext model type to its encrypted form using the table schema.\n *\n * Fields whose keys match columns defined in `S` become `Encrypted`;\n * all other fields retain their original types from `T`.\n *\n * When `S` is the widened `EncryptedTableColumn` (e.g. when a user passes an\n * explicit `<User>` type argument without specifying `S`), the type degrades\n * gracefully to `T` — preserving backward compatibility.\n *\n * @typeParam T - The plaintext model type (e.g. `{ id: string; email: string }`)\n * @typeParam S - The table schema column definition, inferred from the `table` argument\n *\n * @example\n * ```typescript\n * type User = { id: string; email: string }\n * // With a schema that defines `email`:\n * type Encrypted = EncryptedFromSchema<User, { email: EncryptedColumn }>\n * // => { id: string; email: Encrypted }\n * ```\n */\nexport type EncryptedFromSchema<T, S extends EncryptedTableColumn> = {\n [K in keyof T]: [K] extends [keyof S]\n ? [S[K & keyof S]] extends [EncryptedColumn | EncryptedField]\n ? null extends T[K]\n ? Encrypted | null\n : Encrypted\n : T[K]\n : T[K]\n}\n\n// ---------------------------------------------------------------------------\n// Bulk operations\n// ---------------------------------------------------------------------------\n\n// Bulk payloads admit null elements — bulk operations pass them through\n// untouched (encrypt(null) -> null, decrypt(null) -> null) so callers can\n// process mixed nullable arrays without filtering ahead of time. The\n// runtime guards in the operation classes preserve the null in the\n// position-stable output.\nexport type BulkEncryptPayload = Array<{\n id?: string\n plaintext: Plaintext | null\n}>\n\nexport type BulkEncryptedData = Array<{ id?: string; data: Encrypted | null }>\nexport type BulkDecryptPayload = Array<{ id?: string; data: Encrypted | null }>\nexport type BulkDecryptedData = Array<DecryptionResult<JsPlaintext | null>>\n\ntype DecryptionSuccess<T> = { error?: never; data: T; id?: string }\ntype DecryptionError<T> = { error: T; id?: string; data?: never }\n\n/**\n * Result type for individual items in bulk decrypt operations.\n * Uses `error`/`data` fields (not `failure`/`data`) since bulk operations\n * can have per-item failures.\n */\nexport type DecryptionResult<T> = DecryptionSuccess<T> | DecryptionError<T>\n\n// ---------------------------------------------------------------------------\n// Query types (for searchable encryption / encryptQuery)\n// ---------------------------------------------------------------------------\n\n/**\n * User-facing query type names for encrypting query values.\n *\n * - `'equality'`: Exact match. [Exact Queries](https://cipherstash.com/docs/stack/cipherstash/encryption/searchable-encryption)\n * - `'freeTextSearch'`: Text search. [Match Queries](https://cipherstash.com/docs/stack/cipherstash/encryption/searchable-encryption)\n * - `'orderAndRange'`: Comparison and range. [Range Queries](https://cipherstash.com/docs/stack/cipherstash/encryption/searchable-encryption)\n * - `'steVecSelector'`: JSONPath selector (e.g. `'$.user.email'`)\n * - `'steVecTerm'`: Containment (e.g. `{ role: 'admin' }`)\n * - `'searchableJson'`: Auto-infers selector or term from plaintext type (recommended)\n */\nexport type QueryTypeName =\n | 'orderAndRange'\n | 'freeTextSearch'\n | 'equality'\n | 'steVecSelector'\n | 'steVecTerm'\n | 'searchableJson'\n\n/** @internal */\nexport type FfiIndexTypeName = 'ore' | 'ope' | 'match' | 'unique' | 'ste_vec'\n\nexport const queryTypes = {\n orderAndRange: 'orderAndRange',\n freeTextSearch: 'freeTextSearch',\n equality: 'equality',\n steVecSelector: 'steVecSelector',\n steVecTerm: 'steVecTerm',\n searchableJson: 'searchableJson',\n} as const satisfies Record<string, QueryTypeName>\n\n/** @internal */\nexport const queryTypeToFfi: Record<QueryTypeName, FfiIndexTypeName> = {\n // v3 `_ord` domains carry `ope` instead — `resolveIndexType` swaps this\n // static default for the ordering index the column actually configures.\n orderAndRange: 'ore',\n freeTextSearch: 'match',\n equality: 'unique',\n steVecSelector: 'ste_vec',\n steVecTerm: 'ste_vec',\n searchableJson: 'ste_vec',\n}\n\n/** @internal */\nexport const queryTypeToQueryOp: Partial<Record<QueryTypeName, QueryOpName>> = {\n steVecSelector: 'ste_vec_selector',\n steVecTerm: 'ste_vec_term',\n}\n\n/** @internal */\nexport type QueryTermBase = {\n column: BuildableQueryColumn // query: excludes non-queryable EncryptedField\n table: BuildableTable\n queryType?: QueryTypeName\n returnType?: EncryptedReturnType\n}\n\nexport type EncryptQueryOptions = QueryTermBase\n\nexport type ScalarQueryTerm = QueryTermBase & {\n value: Plaintext\n}\n","import type { QueryOpName } from '@cipherstash/protect-ffi'\nimport type {\n BuildableQueryColumn,\n FfiIndexTypeName,\n Plaintext,\n QueryTypeName,\n} from '../../types'\nimport { queryTypeToFfi, queryTypeToQueryOp } from '../../types'\n\n/**\n * Infer the primary index type from a column's configured indexes.\n * Priority: unique > match > ore/ope > ste_vec (for scalar queries; a column\n * carries at most one of `ore`/`ope` — the ordering flavour is pinned by its\n * EQL v3 domain).\n */\nexport function inferIndexType(column: BuildableQueryColumn): FfiIndexTypeName {\n const config = column.build()\n const indexes = config.indexes\n\n if (!indexes || Object.keys(indexes).length === 0) {\n throw new Error(`Column \"${column.getName()}\" has no indexes configured`)\n }\n\n // Priority order for inference\n if (indexes.unique) return 'unique'\n if (indexes.match) return 'match'\n if (indexes.ore) return 'ore'\n if (indexes.ope) return 'ope'\n if (indexes.ste_vec) return 'ste_vec'\n\n throw new Error(\n `Column \"${column.getName()}\" has no suitable index for queries`,\n )\n}\n\n/**\n * Infer the FFI query operation from plaintext type for STE Vec queries.\n * - String → ste_vec_selector (JSONPath queries like '$.user.email')\n * - Object/Array/Number/Boolean → ste_vec_term (containment queries)\n */\nexport function inferQueryOpFromPlaintext(plaintext: Plaintext): QueryOpName {\n if (typeof plaintext === 'string') {\n return 'ste_vec_selector'\n }\n // Objects (incl. Date), arrays, numbers, booleans are all valid JSONB\n // containment values\n if (\n typeof plaintext === 'object' ||\n typeof plaintext === 'number' ||\n typeof plaintext === 'boolean'\n ) {\n return 'ste_vec_term'\n }\n // This should never happen with valid JsPlaintext, but keep for safety\n return 'ste_vec_term'\n}\n\n/**\n * Validate that the specified index type is configured on the column\n */\nexport function validateIndexType(\n column: BuildableQueryColumn,\n indexType: FfiIndexTypeName,\n): void {\n const config = column.build()\n const indexes = config.indexes ?? {}\n\n const indexMap: Record<string, boolean> = {\n unique: !!indexes.unique,\n match: !!indexes.match,\n ore: !!indexes.ore,\n ope: !!indexes.ope,\n ste_vec: !!indexes.ste_vec,\n }\n\n if (!indexMap[indexType]) {\n throw new Error(\n `Index type \"${indexType}\" is not configured on column \"${column.getName()}\"`,\n )\n }\n}\n\n/**\n * v3-only: an order-capable column answers EQUALITY via its ordering index\n * (`ope`/`op` on `_ord` domains, `ore`/`ob` on `_ord_ore` domains).\n *\n * The v3 capability contract (`src/eql/v3`) documents `equality` as \"exact-match\n * lookups (EQL `hm`, or comparison via the ordering term)\", so an order-capable\n * column with only an ordering index still supports equality — the\n * equality-vs-range distinction is made by the SQL comparison operator (`=` vs\n * `>=`), NOT by the ciphertext (the FFI emits the same ordering term either\n * way). The default `equality → unique` mapping would wrongly reject these\n * columns. Returns the ordering index to use, or `null` when equality does not\n * resolve through one.\n *\n * Gated on `getQueryCapabilities`, which only v3 queryable columns expose — a v2\n * `EncryptedColumn` lacks it and so never matches, preserving v2's\n * equality-without-unique throw unchanged (the no-v2-change constraint).\n */\nfunction equalityOrderingIndex(\n column: BuildableQueryColumn,\n): 'ore' | 'ope' | null {\n if (!('getQueryCapabilities' in column)) return null\n if (!column.getQueryCapabilities().equality) return null\n const indexes = column.build().indexes ?? {}\n if (indexes.unique) return null\n if (indexes.ore) return 'ore'\n if (indexes.ope) return 'ope'\n return null\n}\n\n/**\n * Resolve the index type and query operation for a query.\n * Validates the index type is configured on the column when queryType is explicit.\n * For ste_vec columns without explicit queryType, infers queryOp from plaintext shape.\n *\n * @param column - The column to resolve the index type for\n * @param queryType - Optional explicit query type (if provided, validates against column config)\n * @param plaintext - Optional plaintext value for queryOp inference on ste_vec columns\n * @returns The FFI index type name and optional query operation name\n * @throws Error if ste_vec is inferred but queryOp cannot be determined\n */\nexport function resolveIndexType(\n column: BuildableQueryColumn,\n queryType?: QueryTypeName,\n plaintext?: Plaintext | null,\n): { indexType: FfiIndexTypeName; queryOp?: QueryOpName } {\n let indexType = queryType ? queryTypeToFfi[queryType] : inferIndexType(column)\n\n if (queryType) {\n // An order-capable v3 column answers equality via its ordering index (`op`\n // or `ob`) — the same term `orderAndRange` emits, distinguished only by the\n // SQL `=` operator. Resolve to that index (queryOp undefined) instead of\n // throwing on the missing `unique` index. v2 columns never enter here.\n if (queryType === 'equality') {\n const ordering = equalityOrderingIndex(column)\n if (ordering) return { indexType: ordering }\n }\n\n // `orderAndRange` maps statically to `ore`; v3 `_ord` domains configure\n // `ope` instead. Swap to the ordering index the column actually carries.\n if (queryType === 'orderAndRange' && indexType === 'ore') {\n const indexes = column.build().indexes ?? {}\n if (!indexes.ore && indexes.ope) indexType = 'ope'\n }\n\n validateIndexType(column, indexType)\n\n // For searchableJson, infer queryOp from plaintext type (not from mapping)\n if (queryType === 'searchableJson') {\n if (plaintext === undefined || plaintext === null) {\n return { indexType }\n }\n return { indexType, queryOp: inferQueryOpFromPlaintext(plaintext) }\n }\n\n return { indexType, queryOp: queryTypeToQueryOp[queryType] }\n }\n\n // ste_vec inferred without explicit queryType → must infer from plaintext\n if (indexType === 'ste_vec') {\n if (plaintext === undefined || plaintext === null) {\n // Null plaintext handled by caller (returns null early) - no inference needed\n return { indexType }\n }\n return { indexType, queryOp: inferQueryOpFromPlaintext(plaintext) }\n }\n\n // Non-ste_vec → no queryOp needed\n return { indexType }\n}\n","import type { Result } from '@byteslice/result'\nimport { type EncryptionError, EncryptionErrorTypes } from '@/errors'\nimport type { FfiIndexTypeName } from '@/types'\n\n/**\n * Inclusive bounds of a signed 64-bit integer (`int8`) — the range every\n * `bigint` domain (`public.eql_v3_bigint`, `bigint_eq`, `bigint_ord_ore`,\n * `bigint_ord`) maps to on the Postgres side. A `bigint` outside this range\n * cannot be expressed as an `int8`, so it must be rejected before it reaches\n * protect-ffi (whose behaviour on an out-of-range value is unobservable here).\n * This is the `bigint` analog of the NaN/±Infinity guard for `number` domains:\n * a deterministic, client-side rejection of a plaintext the target type cannot\n * hold.\n */\nconst INT64_MIN = -9223372036854775808n\nconst INT64_MAX = 9223372036854775807n\n\n/** True when `value` is a `bigint` outside the signed 64-bit range. */\nfunction isBigintOutOfInt64Range(value: unknown): value is bigint {\n return typeof value === 'bigint' && (value < INT64_MIN || value > INT64_MAX)\n}\n\n/**\n * Validates that a value is not NaN/Infinity and, for `bigint`, is within the\n * signed 64-bit (`int8`) range.\n * Returns a failure Result if validation fails, undefined otherwise.\n * Use this in async flows that return Result types.\n *\n * Uses `never` as the success type so the result can be assigned to any Result<T, EncryptionError>.\n *\n * @internal\n */\nexport function validateNumericValue(\n value: unknown,\n): Result<never, EncryptionError> | undefined {\n if (typeof value === 'number' && Number.isNaN(value)) {\n return {\n failure: {\n type: EncryptionErrorTypes.EncryptionError,\n message: '[encryption]: Cannot encrypt NaN value',\n },\n }\n }\n if (typeof value === 'number' && !Number.isFinite(value)) {\n return {\n failure: {\n type: EncryptionErrorTypes.EncryptionError,\n message: '[encryption]: Cannot encrypt Infinity value',\n },\n }\n }\n if (isBigintOutOfInt64Range(value)) {\n return {\n failure: {\n type: EncryptionErrorTypes.EncryptionError,\n message: '[encryption]: Cannot encrypt bigint value out of int64 range',\n },\n }\n }\n return undefined\n}\n\n/**\n * Validates that a value is not NaN/Infinity and, for `bigint`, is within the\n * signed 64-bit (`int8`) range.\n * Throws an error if validation fails.\n * Use this in sync flows where exceptions are caught.\n *\n * @internal\n */\nexport function assertValidNumericValue(value: unknown): void {\n if (typeof value === 'number' && Number.isNaN(value)) {\n throw new Error('[encryption]: Cannot encrypt NaN value')\n }\n if (typeof value === 'number' && !Number.isFinite(value)) {\n throw new Error('[encryption]: Cannot encrypt Infinity value')\n }\n if (isBigintOutOfInt64Range(value)) {\n throw new Error(\n '[encryption]: Cannot encrypt bigint value out of int64 range',\n )\n }\n}\n\n/**\n * Validates that the value type is compatible with the index type.\n * Match index (freeTextSearch) only supports string values.\n * Returns a failure Result if validation fails, undefined otherwise.\n * Use this in async flows that return Result types.\n *\n * @internal\n */\nexport function validateValueIndexCompatibility(\n value: unknown,\n indexType: FfiIndexTypeName,\n columnName: string,\n): Result<never, EncryptionError> | undefined {\n if (\n (typeof value === 'number' || typeof value === 'bigint') &&\n indexType === 'match'\n ) {\n return {\n failure: {\n type: EncryptionErrorTypes.EncryptionError,\n message: `[encryption]: Cannot use 'match' index with numeric value on column \"${columnName}\". The 'freeTextSearch' index only supports string values. Configure the column with 'orderAndRange()' or 'equality()' for numeric queries.`,\n },\n }\n }\n return undefined\n}\n\n/**\n * Validates that the value type is compatible with the index type.\n * Match index (freeTextSearch) only supports string values.\n * Throws an error if validation fails.\n * Use this in sync flows where exceptions are caught.\n *\n * @internal\n */\nexport function assertValueIndexCompatibility(\n value: unknown,\n indexType: FfiIndexTypeName,\n columnName: string,\n): void {\n if (\n (typeof value === 'number' || typeof value === 'bigint') &&\n indexType === 'match'\n ) {\n throw new Error(\n `[encryption]: Cannot use 'match' index with numeric value on column \"${columnName}\". The 'freeTextSearch' index only supports string values. Configure the column with 'orderAndRange()' or 'equality()' for numeric queries.`,\n )\n }\n}\n","import type { Result } from '@byteslice/result'\nimport type { EncryptionError } from '@/errors'\n\nexport type AuditConfig = {\n metadata?: Record<string, unknown>\n}\n\nexport type AuditData = {\n metadata?: Record<string, unknown>\n}\n\nexport abstract class EncryptionOperation<T> {\n protected auditMetadata?: Record<string, unknown>\n\n /**\n * Attach audit metadata to this operation. Can be chained.\n * @param config Configuration for ZeroKMS audit logging\n * @param config.metadata Arbitrary JSON object for appending metadata to the audit log\n */\n audit(config: AuditConfig): this {\n this.auditMetadata = config.metadata\n return this\n }\n\n /**\n * Get the audit data for this operation.\n */\n public getAuditData(): AuditData {\n return {\n metadata: this.auditMetadata,\n }\n }\n\n /**\n * Execute the operation and return a Result\n */\n abstract execute(): Promise<Result<T, EncryptionError>>\n\n /**\n * Make the operation thenable\n */\n public then<TResult1 = Result<T, EncryptionError>, TResult2 = never>(\n onfulfilled?:\n | ((\n value: Result<T, EncryptionError>,\n ) => TResult1 | PromiseLike<TResult1>)\n | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n return this.execute().then(onfulfilled, onrejected)\n }\n}\n","import { type Result, withResult } from '@byteslice/result'\nimport {\n type Encrypted as CipherStashEncrypted,\n type DecryptResult,\n decryptBulkFallible,\n} from '@cipherstash/protect-ffi'\nimport { getErrorCode } from '@/encryption/helpers/error-code'\nimport { type EncryptionError, EncryptionErrorTypes } from '@/errors'\nimport {\n type Context,\n type LockContextInput,\n resolveLockContext,\n} from '@/identity'\nimport type { BulkDecryptedData, BulkDecryptPayload, Client } from '@/types'\nimport { createRequestLogger } from '@/utils/logger'\nimport { noClientError } from '../index'\nimport { EncryptionOperation } from './base-operation'\n\n// Drops nulls so they don't reach protect-ffi's bulk decrypt. The\n// dropped positions are re-inserted as null in `mapDecryptedDataToResult`.\nconst createDecryptPayloads = (\n encryptedPayloads: BulkDecryptPayload,\n lockContext?: Context,\n) => {\n return encryptedPayloads\n .filter(({ data }) => data !== null)\n .map(({ id, data }) => ({\n id,\n ciphertext: data as CipherStashEncrypted,\n ...(lockContext && { lockContext }),\n }))\n}\n\nconst createNullResult = (\n encryptedPayloads: BulkDecryptPayload,\n): BulkDecryptedData => encryptedPayloads.map(({ id }) => ({ id, data: null }))\n\nconst mapDecryptedDataToResult = (\n encryptedPayloads: BulkDecryptPayload,\n decryptedData: DecryptResult[],\n): BulkDecryptedData => {\n const result: BulkDecryptedData = new Array(encryptedPayloads.length)\n let decryptedIndex = 0\n for (let i = 0; i < encryptedPayloads.length; i++) {\n if (encryptedPayloads[i].data === null) {\n result[i] = { id: encryptedPayloads[i].id, data: null }\n } else {\n const decryptResult = decryptedData[decryptedIndex]\n if ('error' in decryptResult) {\n result[i] = { id: encryptedPayloads[i].id, error: decryptResult.error }\n } else {\n result[i] = { id: encryptedPayloads[i].id, data: decryptResult.data }\n }\n decryptedIndex++\n }\n }\n return result\n}\n\nexport class BulkDecryptOperation extends EncryptionOperation<BulkDecryptedData> {\n private client: Client\n private encryptedPayloads: BulkDecryptPayload\n\n constructor(client: Client, encryptedPayloads: BulkDecryptPayload) {\n super()\n this.client = client\n this.encryptedPayloads = encryptedPayloads\n }\n\n public withLockContext(\n lockContext: LockContextInput,\n ): BulkDecryptOperationWithLockContext {\n return new BulkDecryptOperationWithLockContext(this, lockContext)\n }\n\n public async execute(): Promise<Result<BulkDecryptedData, EncryptionError>> {\n const log = createRequestLogger()\n log.set({\n op: 'bulkDecrypt',\n count: this.encryptedPayloads?.length ?? 0,\n lockContext: false,\n })\n\n const result = await withResult(\n async () => {\n if (!this.client) throw noClientError()\n if (!this.encryptedPayloads || this.encryptedPayloads.length === 0)\n return []\n\n const nonNullPayloads = createDecryptPayloads(this.encryptedPayloads)\n\n if (nonNullPayloads.length === 0) {\n return createNullResult(this.encryptedPayloads)\n }\n\n const { metadata } = this.getAuditData()\n\n const decryptedData = await decryptBulkFallible(this.client, {\n ciphertexts: nonNullPayloads,\n unverifiedContext: metadata,\n })\n\n return mapDecryptedDataToResult(this.encryptedPayloads, decryptedData)\n },\n (error: unknown) => {\n log.set({ errorCode: getErrorCode(error) ?? 'unknown' })\n return {\n type: EncryptionErrorTypes.DecryptionError,\n message: (error as Error).message,\n code: getErrorCode(error),\n }\n },\n )\n log.emit()\n return result\n }\n\n public getOperation(): {\n client: Client\n encryptedPayloads: BulkDecryptPayload\n } {\n return {\n client: this.client,\n encryptedPayloads: this.encryptedPayloads,\n }\n }\n}\n\nexport class BulkDecryptOperationWithLockContext extends EncryptionOperation<BulkDecryptedData> {\n private operation: BulkDecryptOperation\n private lockContext: LockContextInput\n\n constructor(operation: BulkDecryptOperation, lockContext: LockContextInput) {\n super()\n this.operation = operation\n this.lockContext = lockContext\n const auditData = operation.getAuditData()\n if (auditData) {\n this.audit(auditData)\n }\n }\n\n public async execute(): Promise<Result<BulkDecryptedData, EncryptionError>> {\n const { client, encryptedPayloads } = this.operation.getOperation()\n\n const log = createRequestLogger()\n log.set({\n op: 'bulkDecrypt',\n count: encryptedPayloads?.length ?? 0,\n lockContext: true,\n })\n\n const result = await withResult(\n async () => {\n if (!client) throw noClientError()\n if (!encryptedPayloads || encryptedPayloads.length === 0) return []\n\n const lockContext = resolveLockContext(this.lockContext)\n\n const nonNullPayloads = createDecryptPayloads(\n encryptedPayloads,\n lockContext,\n )\n\n if (nonNullPayloads.length === 0) {\n return createNullResult(encryptedPayloads)\n }\n\n const { metadata } = this.getAuditData()\n\n const decryptedData = await decryptBulkFallible(client, {\n ciphertexts: nonNullPayloads,\n unverifiedContext: metadata,\n })\n\n return mapDecryptedDataToResult(encryptedPayloads, decryptedData)\n },\n (error: unknown) => {\n log.set({ errorCode: getErrorCode(error) ?? 'unknown' })\n return {\n type: EncryptionErrorTypes.DecryptionError,\n message: (error as Error).message,\n code: getErrorCode(error),\n }\n },\n )\n log.emit()\n return result\n }\n}\n","import {\n type Encrypted as CipherStashEncrypted,\n decryptBulk,\n encryptBulk,\n} from '@cipherstash/protect-ffi'\nimport { isEncryptedPayload } from '@/encryption/helpers'\nimport { assertValidNumericValue } from '@/encryption/helpers/validation'\nimport type { AuditData } from '@/encryption/operations/base-operation'\nimport type { Context } from '@/identity'\nimport type { BuildableTable, Client, Decrypted, Encrypted } from '@/types'\n\n/**\n * Sets a value at a nested path in an object, creating intermediate objects as needed.\n * Includes prototype pollution protection.\n */\nfunction setNestedValue(\n obj: Record<string, unknown>,\n path: string[],\n value: unknown,\n): void {\n const FORBIDDEN_KEYS = ['__proto__', 'prototype', 'constructor']\n let current: Record<string, unknown> = obj\n for (let i = 0; i < path.length - 1; i++) {\n const part = path[i]\n if (FORBIDDEN_KEYS.includes(part)) {\n throw new Error(`[encryption]: Forbidden key \"${part}\" in field path`)\n }\n if (\n !(part in current) ||\n typeof current[part] !== 'object' ||\n current[part] === null\n ) {\n current[part] = {}\n }\n current = current[part] as Record<string, unknown>\n }\n const lastKey = path[path.length - 1]\n if (FORBIDDEN_KEYS.includes(lastKey)) {\n throw new Error(`[encryption]: Forbidden key \"${lastKey}\" in field path`)\n }\n current[lastKey] = value\n}\n\n/**\n * Helper function to extract encrypted fields from a model\n */\nexport function extractEncryptedFields<T extends Record<string, unknown>>(\n model: T,\n): Record<string, Encrypted> {\n const result: Record<string, Encrypted> = {}\n\n for (const [key, value] of Object.entries(model)) {\n if (isEncryptedPayload(value)) {\n result[key] = value\n }\n }\n\n return result\n}\n\n/**\n * Helper function to extract non-encrypted fields from a model\n */\nexport function extractOtherFields<T extends Record<string, unknown>>(\n model: T,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {}\n\n for (const [key, value] of Object.entries(model)) {\n if (!isEncryptedPayload(value)) {\n result[key] = value\n }\n }\n\n return result\n}\n\n/**\n * Helper function to merge encrypted and non-encrypted fields into a model\n */\nexport function mergeFields<T>(\n otherFields: Record<string, unknown>,\n encryptedFields: Record<string, Encrypted>,\n): T {\n return { ...otherFields, ...encryptedFields } as T\n}\n\n/**\n * Base interface for bulk operation payloads\n */\ninterface BulkOperationPayload {\n id: string\n [key: string]: unknown\n}\n\n/**\n * Interface for bulk operation key mapping\n */\ninterface BulkOperationKeyMap {\n modelIndex: number\n fieldKey: string\n}\n\n/**\n * Helper function to handle single model bulk operations with mapping\n */\nasync function handleSingleModelBulkOperation<\n T extends BulkOperationPayload,\n R,\n>(\n items: T[],\n operation: (items: T[]) => Promise<R[]>,\n keyMap: Record<string, string>,\n): Promise<Record<string, R>> {\n if (items.length === 0) {\n return {}\n }\n\n const results = await operation(items)\n const mappedResults: Record<string, R> = {}\n\n results.forEach((result, index) => {\n const originalKey = keyMap[index.toString()]\n mappedResults[originalKey] = result\n })\n\n return mappedResults\n}\n\n/**\n * Helper function to handle multiple model bulk operations with mapping\n */\nasync function handleMultiModelBulkOperation<T extends BulkOperationPayload, R>(\n items: T[],\n operation: (items: T[]) => Promise<R[]>,\n keyMap: Record<string, BulkOperationKeyMap>,\n): Promise<Record<string, R>> {\n if (items.length === 0) {\n return {}\n }\n\n const results = await operation(items)\n const mappedResults: Record<string, R> = {}\n\n results.forEach((result, index) => {\n const key = index.toString()\n const { modelIndex, fieldKey } = keyMap[key]\n mappedResults[`${modelIndex}-${fieldKey}`] = result\n })\n\n return mappedResults\n}\n\n/**\n * Helper function to prepare fields for decryption\n */\nfunction prepareFieldsForDecryption<T extends Record<string, unknown>>(\n model: T,\n): {\n otherFields: Record<string, unknown>\n operationFields: Record<string, unknown>\n keyMap: Record<string, string>\n nullFields: Record<string, null | undefined>\n} {\n const otherFields = { ...model } as Record<string, unknown>\n const operationFields: Record<string, unknown> = {}\n const nullFields: Record<string, null | undefined> = {}\n const keyMap: Record<string, string> = {}\n let index = 0\n\n const processNestedFields = (obj: Record<string, unknown>, prefix = '') => {\n for (const [key, value] of Object.entries(obj)) {\n const fullKey = prefix ? `${prefix}.${key}` : key\n\n if (value === null || value === undefined) {\n nullFields[fullKey] = value\n continue\n }\n\n if (typeof value === 'object' && !isEncryptedPayload(value)) {\n // Recursively process nested objects\n processNestedFields(value as Record<string, unknown>, fullKey)\n } else if (isEncryptedPayload(value)) {\n // This is an encrypted field\n const id = index.toString()\n keyMap[id] = fullKey\n operationFields[fullKey] = value\n index++\n\n // Remove from otherFields\n const parts = fullKey.split('.')\n let current = otherFields\n for (let i = 0; i < parts.length - 1; i++) {\n current = current[parts[i]] as Record<string, unknown>\n }\n delete current[parts[parts.length - 1]]\n }\n }\n }\n\n processNestedFields(model)\n return { otherFields, operationFields, keyMap, nullFields }\n}\n\n/**\n * Helper function to prepare fields for encryption\n */\n/**\n * Resolve how a table's model fields map onto encrypt-config columns.\n *\n * `columnPaths` are the keys used to MATCH a user model's fields (the JS\n * property names); `toColumnName` maps a matched field to the name the FFI /\n * encrypt config is keyed by (the DB name).\n *\n * When a table exposes `buildColumnKeyMap()` (v3), those two can differ, so we\n * match by property but address by DB name. Otherwise (v2) `build()` already\n * keys columns by the property name, so both are that same key (identity map).\n */\nexport function resolveEncryptColumnMap(table: BuildableTable): {\n columnPaths: string[]\n toColumnName: (path: string) => string\n} {\n const keyMap = table.buildColumnKeyMap?.()\n if (keyMap) {\n return {\n columnPaths: Object.keys(keyMap),\n toColumnName: (path) => keyMap[path] ?? path,\n }\n }\n const columnPaths = Object.keys(table.build().columns)\n return { columnPaths, toColumnName: (path) => path }\n}\n\nfunction prepareFieldsForEncryption<T extends Record<string, unknown>>(\n model: T,\n table: BuildableTable,\n): {\n otherFields: Record<string, unknown>\n operationFields: Record<string, unknown>\n keyMap: Record<string, string>\n nullFields: Record<string, null | undefined>\n} {\n const otherFields = { ...model } as Record<string, unknown>\n const operationFields: Record<string, unknown> = {}\n const nullFields: Record<string, null | undefined> = {}\n const keyMap: Record<string, string> = {}\n let index = 0\n\n const processNestedFields = (\n obj: Record<string, unknown>,\n prefix = '',\n columnPaths: string[] = [],\n ) => {\n for (const [key, value] of Object.entries(obj)) {\n const fullKey = prefix ? `${prefix}.${key}` : key\n\n if (value === null || value === undefined) {\n nullFields[fullKey] = value\n continue\n }\n\n if (\n typeof value === 'object' &&\n !isEncryptedPayload(value) &&\n !columnPaths.includes(fullKey)\n ) {\n // Only process nested objects if they're in the schema\n if (columnPaths.some((path) => path.startsWith(fullKey))) {\n processNestedFields(\n value as Record<string, unknown>,\n fullKey,\n columnPaths,\n )\n }\n } else if (columnPaths.includes(fullKey)) {\n // Only process fields that are explicitly defined in the schema.\n // Reject an out-of-range numeric plaintext (NaN/±Infinity for `number`,\n // outside i64 for `bigint`) here — the single-value/query paths guard\n // at their own boundary, but the model path builds the FFI payload\n // directly, so validate per field before it reaches protect-ffi.\n assertValidNumericValue(value)\n const id = index.toString()\n keyMap[id] = fullKey\n operationFields[fullKey] = value\n index++\n\n // Remove from otherFields\n const parts = fullKey.split('.')\n let current = otherFields\n for (let i = 0; i < parts.length - 1; i++) {\n current = current[parts[i]] as Record<string, unknown>\n }\n delete current[parts[parts.length - 1]]\n }\n }\n }\n\n // Get all column paths from the table schema (matched by JS property name).\n const { columnPaths } = resolveEncryptColumnMap(table)\n processNestedFields(model, '', columnPaths)\n\n return { otherFields, operationFields, keyMap, nullFields }\n}\n\n/**\n * Helper function to convert a model with encrypted fields to a decrypted model\n */\nexport async function decryptModelFields<T extends Record<string, unknown>>(\n model: T,\n client: Client,\n auditData?: AuditData,\n): Promise<Decrypted<T>> {\n if (!client) {\n throw new Error('Client not initialized')\n }\n\n const { otherFields, operationFields, keyMap, nullFields } =\n prepareFieldsForDecryption(model)\n\n const bulkDecryptPayload = Object.entries(operationFields).map(\n ([key, value]) => ({\n id: key,\n ciphertext: value as CipherStashEncrypted,\n }),\n )\n\n const decryptedFields = await handleSingleModelBulkOperation(\n bulkDecryptPayload,\n (items) =>\n decryptBulk(client, {\n ciphertexts: items,\n unverifiedContext: auditData?.metadata,\n }),\n keyMap,\n )\n\n // Reconstruct the object with proper nesting\n const result: Record<string, unknown> = { ...otherFields }\n\n // First, reconstruct the null/undefined fields\n for (const [key, value] of Object.entries(nullFields)) {\n const parts = key.split('.')\n setNestedValue(result, parts, value)\n }\n\n // Then, reconstruct the decrypted fields\n for (const [key, value] of Object.entries(decryptedFields)) {\n const parts = key.split('.')\n setNestedValue(result, parts, value)\n }\n\n return result as Decrypted<T>\n}\n\n/**\n * Helper function to convert a decrypted model to a model with encrypted fields\n */\nexport async function encryptModelFields(\n model: Record<string, unknown>,\n table: BuildableTable,\n client: Client,\n auditData?: AuditData,\n): Promise<Record<string, unknown>> {\n if (!client) {\n throw new Error('Client not initialized')\n }\n\n const { otherFields, operationFields, keyMap, nullFields } =\n prepareFieldsForEncryption(model, table)\n\n const { toColumnName } = resolveEncryptColumnMap(table)\n const bulkEncryptPayload = Object.entries(operationFields).map(\n ([key, value]) => ({\n id: key,\n plaintext: value as string,\n table: table.tableName,\n column: toColumnName(key),\n }),\n )\n\n const encryptedData = await handleSingleModelBulkOperation(\n bulkEncryptPayload,\n (items) =>\n encryptBulk(client, {\n plaintexts: items,\n unverifiedContext: auditData?.metadata,\n }),\n keyMap,\n )\n\n // Reconstruct the object with proper nesting\n const result: Record<string, unknown> = { ...otherFields }\n\n // First, reconstruct the null/undefined fields\n for (const [key, value] of Object.entries(nullFields)) {\n const parts = key.split('.')\n setNestedValue(result, parts, value)\n }\n\n // Then, reconstruct the encrypted fields\n for (const [key, value] of Object.entries(encryptedData)) {\n const parts = key.split('.')\n setNestedValue(result, parts, value)\n }\n\n return result\n}\n\n/**\n * Helper function to convert a model with encrypted fields to a decrypted model with lock context\n */\nexport async function decryptModelFieldsWithLockContext<\n T extends Record<string, unknown>,\n>(\n model: T,\n client: Client,\n lockContext: Context,\n auditData?: AuditData,\n): Promise<Decrypted<T>> {\n if (!client) {\n throw new Error('Client not initialized')\n }\n\n if (!lockContext) {\n throw new Error('Lock context is not initialized')\n }\n\n const { otherFields, operationFields, keyMap, nullFields } =\n prepareFieldsForDecryption(model)\n\n const bulkDecryptPayload = Object.entries(operationFields).map(\n ([key, value]) => ({\n id: key,\n ciphertext: value as CipherStashEncrypted,\n lockContext,\n }),\n )\n\n const decryptedFields = await handleSingleModelBulkOperation(\n bulkDecryptPayload,\n (items) =>\n decryptBulk(client, {\n ciphertexts: items,\n unverifiedContext: auditData?.metadata,\n }),\n keyMap,\n )\n\n // Reconstruct the object with proper nesting\n const result: Record<string, unknown> = { ...otherFields }\n\n // First, reconstruct the null/undefined fields\n for (const [key, value] of Object.entries(nullFields)) {\n const parts = key.split('.')\n setNestedValue(result, parts, value)\n }\n\n // Then, reconstruct the decrypted fields\n for (const [key, value] of Object.entries(decryptedFields)) {\n const parts = key.split('.')\n setNestedValue(result, parts, value)\n }\n\n return result as Decrypted<T>\n}\n\n/**\n * Helper function to convert a decrypted model to a model with encrypted fields with lock context\n */\nexport async function encryptModelFieldsWithLockContext(\n model: Record<string, unknown>,\n table: BuildableTable,\n client: Client,\n lockContext: Context,\n auditData?: AuditData,\n): Promise<Record<string, unknown>> {\n if (!client) {\n throw new Error('Client not initialized')\n }\n\n if (!lockContext) {\n throw new Error('Lock context is not initialized')\n }\n\n const { otherFields, operationFields, keyMap, nullFields } =\n prepareFieldsForEncryption(model, table)\n\n const { toColumnName } = resolveEncryptColumnMap(table)\n const bulkEncryptPayload = Object.entries(operationFields).map(\n ([key, value]) => ({\n id: key,\n plaintext: value as string,\n table: table.tableName,\n column: toColumnName(key),\n lockContext,\n }),\n )\n\n const encryptedData = await handleSingleModelBulkOperation(\n bulkEncryptPayload,\n (items) =>\n encryptBulk(client, {\n plaintexts: items,\n unverifiedContext: auditData?.metadata,\n }),\n keyMap,\n )\n\n // Reconstruct the object with proper nesting\n const result: Record<string, unknown> = { ...otherFields }\n\n // First, reconstruct the null/undefined fields\n for (const [key, value] of Object.entries(nullFields)) {\n const parts = key.split('.')\n setNestedValue(result, parts, value)\n }\n\n // Then, reconstruct the encrypted fields\n for (const [key, value] of Object.entries(encryptedData)) {\n const parts = key.split('.')\n setNestedValue(result, parts, value)\n }\n\n return result\n}\n\n/**\n * Helper function to prepare multiple models for bulk operation\n */\nfunction prepareBulkModelsForOperation<T extends Record<string, unknown>>(\n models: T[],\n table?: BuildableTable,\n): {\n otherFields: Record<string, unknown>[]\n operationFields: Record<string, unknown>[]\n keyMap: Record<string, { modelIndex: number; fieldKey: string }>\n nullFields: Record<string, null | undefined>[]\n} {\n const otherFields: Record<string, unknown>[] = []\n const operationFields: Record<string, unknown>[] = []\n const nullFields: Record<string, null | undefined>[] = []\n const keyMap: Record<string, { modelIndex: number; fieldKey: string }> = {}\n let index = 0\n\n for (let modelIndex = 0; modelIndex < models.length; modelIndex++) {\n const model = models[modelIndex]\n const modelOtherFields = { ...model } as Record<string, unknown>\n const modelOperationFields: Record<string, unknown> = {}\n const modelNullFields: Record<string, null | undefined> = {}\n\n const processNestedFields = (\n obj: Record<string, unknown>,\n prefix = '',\n columnPaths: string[] = [],\n ) => {\n for (const [key, value] of Object.entries(obj)) {\n const fullKey = prefix ? `${prefix}.${key}` : key\n\n if (value === null || value === undefined) {\n modelNullFields[fullKey] = value\n continue\n }\n\n if (\n typeof value === 'object' &&\n !isEncryptedPayload(value) &&\n !columnPaths.includes(fullKey)\n ) {\n // Only process nested objects if they're in the schema\n if (columnPaths.some((path) => path.startsWith(fullKey))) {\n processNestedFields(\n value as Record<string, unknown>,\n fullKey,\n columnPaths,\n )\n }\n } else if (columnPaths.includes(fullKey)) {\n // Only process fields that are explicitly defined in the schema.\n // Reject an out-of-range numeric plaintext (NaN/±Infinity for\n // `number`, outside i64 for `bigint`) before it reaches the bulk FFI\n // payload — the bulk path builds that payload directly. This arm runs\n // only for encryption (`if (table)`); the decrypt walker below does\n // not validate.\n assertValidNumericValue(value)\n const id = index.toString()\n keyMap[id] = { modelIndex, fieldKey: fullKey }\n modelOperationFields[fullKey] = value\n index++\n\n // Remove from otherFields\n const parts = fullKey.split('.')\n let current = modelOtherFields\n for (let i = 0; i < parts.length - 1; i++) {\n current = current[parts[i]] as Record<string, unknown>\n }\n delete current[parts[parts.length - 1]]\n }\n }\n }\n\n if (table) {\n // Get all column paths from the table schema (matched by JS property name).\n const { columnPaths } = resolveEncryptColumnMap(table)\n processNestedFields(model, '', columnPaths)\n } else {\n // For decryption, process all encrypted fields\n const processEncryptedFields = (\n obj: Record<string, unknown>,\n prefix = '',\n columnPaths: string[] = [],\n ) => {\n for (const [key, value] of Object.entries(obj)) {\n const fullKey = prefix ? `${prefix}.${key}` : key\n\n if (value === null || value === undefined) {\n modelNullFields[fullKey] = value\n continue\n }\n\n if (\n typeof value === 'object' &&\n !isEncryptedPayload(value) &&\n !columnPaths.includes(fullKey)\n ) {\n // Recursively process nested objects\n processEncryptedFields(\n value as Record<string, unknown>,\n fullKey,\n columnPaths,\n )\n } else if (isEncryptedPayload(value)) {\n // This is an encrypted field\n const id = index.toString()\n keyMap[id] = { modelIndex, fieldKey: fullKey }\n modelOperationFields[fullKey] = value\n index++\n\n // Remove from otherFields\n const parts = fullKey.split('.')\n let current = modelOtherFields\n for (let i = 0; i < parts.length - 1; i++) {\n current = current[parts[i]] as Record<string, unknown>\n }\n delete current[parts[parts.length - 1]]\n }\n }\n }\n processEncryptedFields(model)\n }\n\n otherFields.push(modelOtherFields)\n operationFields.push(modelOperationFields)\n nullFields.push(modelNullFields)\n }\n\n return { otherFields, operationFields, keyMap, nullFields }\n}\n\n/**\n * Collect the per-model fields out of a bulk-operation result map keyed by\n * `${modelIndex}-${fieldKey}` ids, splitting each id at the FIRST hyphen\n * only. Field keys may themselves contain hyphens (a `some-field` column, or\n * a nested `profile.some-field` path), so a naive `split('-')` would truncate\n * the field key at its first hyphen and silently drop the value during model\n * reconstruction.\n */\nfunction fieldsForModelIndex(\n fields: Record<string, unknown>,\n modelIndex: number,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {}\n for (const [id, value] of Object.entries(fields)) {\n const sep = id.indexOf('-')\n if (Number.parseInt(id.slice(0, sep), 10) !== modelIndex) continue\n result[id.slice(sep + 1)] = value\n }\n return result\n}\n\n/**\n * Helper function to convert multiple decrypted models to models with encrypted fields\n */\nexport async function bulkEncryptModels(\n models: Record<string, unknown>[],\n table: BuildableTable,\n client: Client,\n auditData?: AuditData,\n): Promise<Record<string, unknown>[]> {\n if (!client) {\n throw new Error('Client not initialized')\n }\n\n if (!models || models.length === 0) {\n return []\n }\n\n const { otherFields, operationFields, keyMap, nullFields } =\n prepareBulkModelsForOperation(models, table)\n\n const { toColumnName } = resolveEncryptColumnMap(table)\n const bulkEncryptPayload = operationFields.flatMap((fields, modelIndex) =>\n Object.entries(fields).map(([key, value]) => ({\n id: `${modelIndex}-${key}`,\n plaintext: value as string,\n table: table.tableName,\n column: toColumnName(key),\n })),\n )\n\n const encryptedData = await handleMultiModelBulkOperation(\n bulkEncryptPayload,\n (items) =>\n encryptBulk(client, {\n plaintexts: items,\n unverifiedContext: auditData?.metadata,\n }),\n keyMap,\n )\n\n return models.map((_, modelIndex) => {\n const result: Record<string, unknown> = { ...otherFields[modelIndex] }\n\n // First, reconstruct the null/undefined fields\n for (const [key, value] of Object.entries(nullFields[modelIndex])) {\n const parts = key.split('.')\n setNestedValue(result, parts, value)\n }\n\n // Then, reconstruct the encrypted fields\n const modelData = fieldsForModelIndex(encryptedData, modelIndex)\n\n for (const [key, value] of Object.entries(modelData)) {\n const parts = key.split('.')\n setNestedValue(result, parts, value)\n }\n\n return result\n })\n}\n\n/**\n * Helper function to convert multiple models with encrypted fields to decrypted models\n */\nexport async function bulkDecryptModels<T extends Record<string, unknown>>(\n models: T[],\n client: Client,\n auditData?: AuditData,\n): Promise<Decrypted<T>[]> {\n if (!client) {\n throw new Error('Client not initialized')\n }\n\n if (!models || models.length === 0) {\n return []\n }\n\n const { otherFields, operationFields, keyMap, nullFields } =\n prepareBulkModelsForOperation(models)\n\n const bulkDecryptPayload = operationFields.flatMap((fields, modelIndex) =>\n Object.entries(fields).map(([key, value]) => ({\n id: `${modelIndex}-${key}`,\n ciphertext: value as CipherStashEncrypted,\n })),\n )\n\n const decryptedFields = await handleMultiModelBulkOperation(\n bulkDecryptPayload,\n (items) =>\n decryptBulk(client, {\n ciphertexts: items,\n unverifiedContext: auditData?.metadata,\n }),\n keyMap,\n )\n\n return models.map((_, modelIndex) => {\n const result: Record<string, unknown> = { ...otherFields[modelIndex] }\n\n // First, reconstruct the null/undefined fields\n for (const [key, value] of Object.entries(nullFields[modelIndex])) {\n const parts = key.split('.')\n setNestedValue(result, parts, value)\n }\n\n // Then, reconstruct the decrypted fields\n const modelData = fieldsForModelIndex(decryptedFields, modelIndex)\n\n for (const [key, value] of Object.entries(modelData)) {\n const parts = key.split('.')\n setNestedValue(result, parts, value)\n }\n\n return result as Decrypted<T>\n })\n}\n\n/**\n * Helper function to convert multiple models with encrypted fields to decrypted models with lock context\n */\nexport async function bulkDecryptModelsWithLockContext<\n T extends Record<string, unknown>,\n>(\n models: T[],\n client: Client,\n lockContext: Context,\n auditData?: AuditData,\n): Promise<Decrypted<T>[]> {\n if (!client) {\n throw new Error('Client not initialized')\n }\n\n if (!lockContext) {\n throw new Error('Lock context is not initialized')\n }\n\n const { otherFields, operationFields, keyMap, nullFields } =\n prepareBulkModelsForOperation(models)\n\n const bulkDecryptPayload = operationFields.flatMap((fields, modelIndex) =>\n Object.entries(fields).map(([key, value]) => ({\n id: `${modelIndex}-${key}`,\n ciphertext: value as CipherStashEncrypted,\n lockContext,\n })),\n )\n\n const decryptedFields = await handleMultiModelBulkOperation(\n bulkDecryptPayload,\n (items) =>\n decryptBulk(client, {\n ciphertexts: items,\n unverifiedContext: auditData?.metadata,\n }),\n keyMap,\n )\n\n // Reconstruct models\n return models.map((_, modelIndex) => {\n const result: Record<string, unknown> = { ...otherFields[modelIndex] }\n\n // First, reconstruct the null/undefined fields\n for (const [key, value] of Object.entries(nullFields[modelIndex])) {\n const parts = key.split('.')\n setNestedValue(result, parts, value)\n }\n\n // Then, reconstruct the decrypted fields\n const modelData = fieldsForModelIndex(decryptedFields, modelIndex)\n\n for (const [key, value] of Object.entries(modelData)) {\n const parts = key.split('.')\n setNestedValue(result, parts, value)\n }\n\n return result as Decrypted<T>\n })\n}\n\n/**\n * Helper function to convert multiple decrypted models to models with encrypted fields with lock context\n */\nexport async function bulkEncryptModelsWithLockContext(\n models: Record<string, unknown>[],\n table: BuildableTable,\n client: Client,\n lockContext: Context,\n auditData?: AuditData,\n): Promise<Record<string, unknown>[]> {\n if (!client) {\n throw new Error('Client not initialized')\n }\n\n if (!lockContext) {\n throw new Error('Lock context is not initialized')\n }\n\n const { otherFields, operationFields, keyMap, nullFields } =\n prepareBulkModelsForOperation(models, table)\n\n const { toColumnName } = resolveEncryptColumnMap(table)\n const bulkEncryptPayload = operationFields.flatMap((fields, modelIndex) =>\n Object.entries(fields).map(([key, value]) => ({\n id: `${modelIndex}-${key}`,\n plaintext: value as string,\n table: table.tableName,\n column: toColumnName(key),\n lockContext,\n })),\n )\n\n const encryptedData = await handleMultiModelBulkOperation(\n bulkEncryptPayload,\n (items) =>\n encryptBulk(client, {\n plaintexts: items,\n unverifiedContext: auditData?.metadata,\n }),\n keyMap,\n )\n\n // Reconstruct models\n return models.map((_, modelIndex) => {\n const result: Record<string, unknown> = { ...otherFields[modelIndex] }\n\n // First, reconstruct the null/undefined fields\n for (const [key, value] of Object.entries(nullFields[modelIndex])) {\n const parts = key.split('.')\n setNestedValue(result, parts, value)\n }\n\n // Then, reconstruct the encrypted fields\n const modelData = fieldsForModelIndex(encryptedData, modelIndex)\n\n for (const [key, value] of Object.entries(modelData)) {\n const parts = key.split('.')\n setNestedValue(result, parts, value)\n }\n\n return result\n })\n}\n","import { type Result, withResult } from '@byteslice/result'\nimport { getErrorCode } from '@/encryption/helpers/error-code'\nimport { type EncryptionError, EncryptionErrorTypes } from '@/errors'\nimport { type LockContextInput, resolveLockContext } from '@/identity'\nimport type { Client, Decrypted } from '@/types'\nimport { createRequestLogger } from '@/utils/logger'\nimport {\n bulkDecryptModels,\n bulkDecryptModelsWithLockContext,\n} from '../helpers/model-helpers'\nimport { noClientError } from '../index'\nimport { EncryptionOperation } from './base-operation'\n\nexport class BulkDecryptModelsOperation<\n T extends Record<string, unknown>,\n> extends EncryptionOperation<Decrypted<T>[]> {\n private client: Client\n private models: T[]\n\n constructor(client: Client, models: T[]) {\n super()\n this.client = client\n this.models = models\n }\n\n public withLockContext(\n lockContext: LockContextInput,\n ): BulkDecryptModelsOperationWithLockContext<T> {\n return new BulkDecryptModelsOperationWithLockContext(this, lockContext)\n }\n\n public async execute(): Promise<Result<Decrypted<T>[], EncryptionError>> {\n const log = createRequestLogger()\n log.set({\n op: 'bulkDecryptModels',\n count: this.models.length,\n lockContext: false,\n })\n\n const result = await withResult(\n async () => {\n if (!this.client) {\n throw noClientError()\n }\n\n const auditData = this.getAuditData()\n\n return await bulkDecryptModels<T>(this.models, this.client, auditData)\n },\n (error: unknown) => {\n log.set({ errorCode: getErrorCode(error) ?? 'unknown' })\n return {\n type: EncryptionErrorTypes.DecryptionError,\n message: (error as Error).message,\n code: getErrorCode(error),\n }\n },\n )\n log.emit()\n return result\n }\n\n public getOperation(): {\n client: Client\n models: T[]\n } {\n return {\n client: this.client,\n models: this.models,\n }\n }\n}\n\nexport class BulkDecryptModelsOperationWithLockContext<\n T extends Record<string, unknown>,\n> extends EncryptionOperation<Decrypted<T>[]> {\n private operation: BulkDecryptModelsOperation<T>\n private lockContext: LockContextInput\n\n constructor(\n operation: BulkDecryptModelsOperation<T>,\n lockContext: LockContextInput,\n ) {\n super()\n this.operation = operation\n this.lockContext = lockContext\n const auditData = operation.getAuditData()\n if (auditData) {\n this.audit(auditData)\n }\n }\n\n public async execute(): Promise<Result<Decrypted<T>[], EncryptionError>> {\n const { client, models } = this.operation.getOperation()\n\n const log = createRequestLogger()\n log.set({\n op: 'bulkDecryptModels',\n count: models.length,\n lockContext: true,\n })\n\n const result = await withResult(\n async () => {\n if (!client) {\n throw noClientError()\n }\n\n const context = resolveLockContext(this.lockContext)\n\n const auditData = this.getAuditData()\n\n return await bulkDecryptModelsWithLockContext<T>(\n models,\n client,\n context,\n auditData,\n )\n },\n (error: unknown) => {\n log.set({ errorCode: getErrorCode(error) ?? 'unknown' })\n return {\n type: EncryptionErrorTypes.DecryptionError,\n message: (error as Error).message,\n code: getErrorCode(error),\n }\n },\n )\n log.emit()\n return result\n }\n}\n","import { type Result, withResult } from '@byteslice/result'\nimport { encryptBulk, type JsPlaintext } from '@cipherstash/protect-ffi'\nimport { getErrorCode } from '@/encryption/helpers/error-code'\nimport { assertValidNumericValue } from '@/encryption/helpers/validation'\nimport { type EncryptionError, EncryptionErrorTypes } from '@/errors'\nimport {\n type Context,\n type LockContextInput,\n resolveLockContext,\n} from '@/identity'\nimport type {\n BuildableColumn,\n BuildableTable,\n BulkEncryptedData,\n BulkEncryptPayload,\n Client,\n Encrypted,\n EncryptOptions,\n} from '@/types'\nimport { createRequestLogger } from '@/utils/logger'\nimport { noClientError } from '../index'\nimport { EncryptionOperation } from './base-operation'\n\n// Drops nulls so they don't reach protect-ffi (which would otherwise\n// produce a SteVec wrapping the JSON null). The dropped positions are\n// re-inserted as null in `mapEncryptedDataToResult`.\n//\n// Each surviving plaintext is validated exactly as `EncryptOperation` validates\n// its single operand: NaN / ±Infinity / out-of-int64 `bigint` are rejected\n// client-side, because protect-ffi's behaviour on such a value is unobservable.\n// Callers that batch instead of looping (the v3 Drizzle `inArray`, for one)\n// must not lose that guard by choosing the bulk path.\nconst createEncryptPayloads = (\n plaintexts: BulkEncryptPayload,\n column: BuildableColumn,\n table: BuildableTable,\n lockContext?: Context,\n) => {\n return plaintexts\n .filter(({ plaintext }) => plaintext !== null)\n .map(({ id, plaintext }) => {\n assertValidNumericValue(plaintext)\n return {\n id,\n plaintext: plaintext as JsPlaintext,\n column: column.getName(),\n table: table.tableName,\n ...(lockContext && { lockContext }),\n }\n })\n}\n\nconst createNullResult = (plaintexts: BulkEncryptPayload): BulkEncryptedData =>\n plaintexts.map(({ id }) => ({ id, data: null }))\n\nconst mapEncryptedDataToResult = (\n plaintexts: BulkEncryptPayload,\n encryptedData: Encrypted[],\n): BulkEncryptedData => {\n const result: BulkEncryptedData = new Array(plaintexts.length)\n let encryptedIndex = 0\n for (let i = 0; i < plaintexts.length; i++) {\n if (plaintexts[i].plaintext === null) {\n result[i] = { id: plaintexts[i].id, data: null }\n } else {\n result[i] = { id: plaintexts[i].id, data: encryptedData[encryptedIndex] }\n encryptedIndex++\n }\n }\n return result\n}\n\nexport class BulkEncryptOperation extends EncryptionOperation<BulkEncryptedData> {\n private client: Client\n private plaintexts: BulkEncryptPayload\n private column: BuildableColumn\n private table: BuildableTable\n\n constructor(\n client: Client,\n plaintexts: BulkEncryptPayload,\n opts: EncryptOptions,\n ) {\n super()\n this.client = client\n this.plaintexts = plaintexts\n this.column = opts.column\n this.table = opts.table\n }\n\n public withLockContext(\n lockContext: LockContextInput,\n ): BulkEncryptOperationWithLockContext {\n return new BulkEncryptOperationWithLockContext(this, lockContext)\n }\n\n public async execute(): Promise<Result<BulkEncryptedData, EncryptionError>> {\n const log = createRequestLogger()\n log.set({\n op: 'bulkEncrypt',\n table: this.table.tableName,\n column: this.column.getName(),\n count: this.plaintexts?.length ?? 0,\n lockContext: false,\n })\n\n const result = await withResult(\n async () => {\n if (!this.client) {\n throw noClientError()\n }\n if (!this.plaintexts || this.plaintexts.length === 0) {\n return []\n }\n\n const nonNullPayloads = createEncryptPayloads(\n this.plaintexts,\n this.column,\n this.table,\n )\n\n if (nonNullPayloads.length === 0) {\n return createNullResult(this.plaintexts)\n }\n\n const { metadata } = this.getAuditData()\n\n const encryptedData = await encryptBulk(this.client, {\n plaintexts: nonNullPayloads,\n unverifiedContext: metadata,\n })\n\n return mapEncryptedDataToResult(this.plaintexts, encryptedData)\n },\n (error: unknown) => {\n log.set({ errorCode: getErrorCode(error) ?? 'unknown' })\n return {\n type: EncryptionErrorTypes.EncryptionError,\n message: (error as Error).message,\n code: getErrorCode(error),\n }\n },\n )\n log.emit()\n return result\n }\n\n public getOperation(): {\n client: Client\n plaintexts: BulkEncryptPayload\n column: BuildableColumn\n table: BuildableTable\n } {\n return {\n client: this.client,\n plaintexts: this.plaintexts,\n column: this.column,\n table: this.table,\n }\n }\n}\n\nexport class BulkEncryptOperationWithLockContext extends EncryptionOperation<BulkEncryptedData> {\n private operation: BulkEncryptOperation\n private lockContext: LockContextInput\n\n constructor(operation: BulkEncryptOperation, lockContext: LockContextInput) {\n super()\n this.operation = operation\n this.lockContext = lockContext\n const auditData = operation.getAuditData()\n if (auditData) {\n this.audit(auditData)\n }\n }\n\n public async execute(): Promise<Result<BulkEncryptedData, EncryptionError>> {\n const { client, plaintexts, column, table } = this.operation.getOperation()\n\n const log = createRequestLogger()\n log.set({\n op: 'bulkEncrypt',\n table: table.tableName,\n column: column.getName(),\n count: plaintexts?.length ?? 0,\n lockContext: true,\n })\n\n const result = await withResult(\n async () => {\n if (!client) {\n throw noClientError()\n }\n if (!plaintexts || plaintexts.length === 0) {\n return []\n }\n\n const lockContext = resolveLockContext(this.lockContext)\n\n const nonNullPayloads = createEncryptPayloads(\n plaintexts,\n column,\n table,\n lockContext,\n )\n\n if (nonNullPayloads.length === 0) {\n return createNullResult(plaintexts)\n }\n\n const { metadata } = this.getAuditData()\n\n const encryptedData = await encryptBulk(client, {\n plaintexts: nonNullPayloads,\n unverifiedContext: metadata,\n })\n\n return mapEncryptedDataToResult(plaintexts, encryptedData)\n },\n (error: unknown) => {\n log.set({ errorCode: getErrorCode(error) ?? 'unknown' })\n return {\n type: EncryptionErrorTypes.EncryptionError,\n message: (error as Error).message,\n code: getErrorCode(error),\n }\n },\n )\n log.emit()\n return result\n }\n}\n","import { type Result, withResult } from '@byteslice/result'\nimport { getErrorCode } from '@/encryption/helpers/error-code'\nimport { type EncryptionError, EncryptionErrorTypes } from '@/errors'\nimport { type LockContextInput, resolveLockContext } from '@/identity'\nimport type { BuildableTable, Client } from '@/types'\nimport { createRequestLogger } from '@/utils/logger'\nimport {\n bulkEncryptModels,\n bulkEncryptModelsWithLockContext,\n} from '../helpers/model-helpers'\nimport { noClientError } from '../index'\nimport { EncryptionOperation } from './base-operation'\n\nexport class BulkEncryptModelsOperation<\n T extends Record<string, unknown>,\n> extends EncryptionOperation<T[]> {\n private client: Client\n private models: Record<string, unknown>[]\n private table: BuildableTable\n\n constructor(\n client: Client,\n models: Record<string, unknown>[],\n table: BuildableTable,\n ) {\n super()\n this.client = client\n this.models = models\n this.table = table\n }\n\n public withLockContext(\n lockContext: LockContextInput,\n ): BulkEncryptModelsOperationWithLockContext<T> {\n return new BulkEncryptModelsOperationWithLockContext(this, lockContext)\n }\n\n public async execute(): Promise<Result<T[], EncryptionError>> {\n const log = createRequestLogger()\n log.set({\n op: 'bulkEncryptModels',\n table: this.table.tableName,\n count: this.models.length,\n lockContext: false,\n })\n\n const result = await withResult(\n async () => {\n if (!this.client) {\n throw noClientError()\n }\n\n const auditData = this.getAuditData()\n\n return (await bulkEncryptModels(\n this.models,\n this.table,\n this.client,\n auditData,\n )) as T[]\n },\n (error: unknown) => {\n log.set({ errorCode: getErrorCode(error) ?? 'unknown' })\n return {\n type: EncryptionErrorTypes.EncryptionError,\n message: (error as Error).message,\n code: getErrorCode(error),\n }\n },\n )\n log.emit()\n return result\n }\n\n public getOperation(): {\n client: Client\n models: Record<string, unknown>[]\n table: BuildableTable\n } {\n return {\n client: this.client,\n models: this.models,\n table: this.table,\n }\n }\n}\n\nexport class BulkEncryptModelsOperationWithLockContext<\n T extends Record<string, unknown>,\n> extends EncryptionOperation<T[]> {\n private operation: BulkEncryptModelsOperation<T>\n private lockContext: LockContextInput\n\n constructor(\n operation: BulkEncryptModelsOperation<T>,\n lockContext: LockContextInput,\n ) {\n super()\n this.operation = operation\n this.lockContext = lockContext\n const auditData = operation.getAuditData()\n if (auditData) {\n this.audit(auditData)\n }\n }\n\n public async execute(): Promise<Result<T[], EncryptionError>> {\n const { client, models, table } = this.operation.getOperation()\n\n const log = createRequestLogger()\n log.set({\n op: 'bulkEncryptModels',\n table: table.tableName,\n count: models.length,\n lockContext: true,\n })\n\n const result = await withResult(\n async () => {\n if (!client) {\n throw noClientError()\n }\n\n const context = resolveLockContext(this.lockContext)\n\n const auditData = this.getAuditData()\n\n return (await bulkEncryptModelsWithLockContext(\n models,\n table,\n client,\n context,\n auditData,\n )) as T[]\n },\n (error: unknown) => {\n log.set({ errorCode: getErrorCode(error) ?? 'unknown' })\n return {\n type: EncryptionErrorTypes.EncryptionError,\n message: (error as Error).message,\n code: getErrorCode(error),\n }\n },\n )\n log.emit()\n return result\n }\n}\n","import { type Result, withResult } from '@byteslice/result'\nimport {\n decrypt as ffiDecrypt,\n type JsPlaintext,\n} from '@cipherstash/protect-ffi'\nimport { getErrorCode } from '@/encryption/helpers/error-code'\nimport { type EncryptionError, EncryptionErrorTypes } from '@/errors'\nimport { type LockContextInput, resolveLockContext } from '@/identity'\nimport type { Client, Encrypted } from '@/types'\nimport { createRequestLogger } from '@/utils/logger'\nimport { noClientError } from '../index'\nimport { EncryptionOperation } from './base-operation'\n\n/**\n * Decrypts an encrypted payload using the provided client.\n * This is the type returned by the {@link EncryptionClient.decrypt | decrypt} method of the {@link EncryptionClient}.\n */\nexport class DecryptOperation extends EncryptionOperation<JsPlaintext> {\n private client: Client\n // Internally widened to allow null so the runtime guard below can\n // short-circuit on legacy / manually-NULLed rows. The public\n // `Encryption.decrypt()` signature still rejects null at the type\n // layer; this is defense in depth for direct construction.\n private encryptedData: Encrypted | null\n\n constructor(client: Client, encryptedData: Encrypted | null) {\n super()\n this.client = client\n this.encryptedData = encryptedData\n }\n\n public withLockContext(\n lockContext: LockContextInput,\n ): DecryptOperationWithLockContext {\n return new DecryptOperationWithLockContext(this, lockContext)\n }\n\n public async execute(): Promise<Result<JsPlaintext, EncryptionError>> {\n const log = createRequestLogger()\n log.set({\n op: 'decrypt',\n lockContext: false,\n })\n\n const result = await withResult(\n async () => {\n if (!this.client) {\n throw noClientError()\n }\n\n if (this.encryptedData === null) {\n // See encrypt.ts for the same defense-in-depth pattern.\n return null as unknown as JsPlaintext\n }\n\n const { metadata } = this.getAuditData()\n\n return await ffiDecrypt(this.client, {\n ciphertext: this.encryptedData,\n unverifiedContext: metadata,\n })\n },\n (error: unknown) => {\n log.set({ errorCode: getErrorCode(error) ?? 'unknown' })\n return {\n type: EncryptionErrorTypes.DecryptionError,\n message: (error as Error).message,\n code: getErrorCode(error),\n }\n },\n )\n log.emit()\n return result\n }\n\n public getOperation(): {\n client: Client\n encryptedData: Encrypted | null\n auditData?: Record<string, unknown>\n } {\n return {\n client: this.client,\n encryptedData: this.encryptedData,\n auditData: this.getAuditData(),\n }\n }\n}\n\nexport class DecryptOperationWithLockContext extends EncryptionOperation<JsPlaintext> {\n private operation: DecryptOperation\n private lockContext: LockContextInput\n\n constructor(operation: DecryptOperation, lockContext: LockContextInput) {\n super()\n this.operation = operation\n this.lockContext = lockContext\n const auditData = operation.getAuditData()\n if (auditData) {\n this.audit(auditData)\n }\n }\n\n public async execute(): Promise<Result<JsPlaintext, EncryptionError>> {\n const log = createRequestLogger()\n log.set({\n op: 'decrypt',\n lockContext: true,\n })\n\n const result = await withResult(\n async () => {\n const { client, encryptedData } = this.operation.getOperation()\n\n if (!client) {\n throw noClientError()\n }\n\n if (encryptedData === null) {\n return null as unknown as JsPlaintext\n }\n\n const { metadata } = this.getAuditData()\n\n const lockContext = resolveLockContext(this.lockContext)\n\n return await ffiDecrypt(client, {\n ciphertext: encryptedData,\n unverifiedContext: metadata,\n lockContext,\n })\n },\n (error: unknown) => {\n log.set({ errorCode: getErrorCode(error) ?? 'unknown' })\n return {\n type: EncryptionErrorTypes.DecryptionError,\n message: (error as Error).message,\n code: getErrorCode(error),\n }\n },\n )\n log.emit()\n return result\n }\n}\n","import { type Result, withResult } from '@byteslice/result'\nimport { getErrorCode } from '@/encryption/helpers/error-code'\nimport { type EncryptionError, EncryptionErrorTypes } from '@/errors'\nimport { type LockContextInput, resolveLockContext } from '@/identity'\nimport type { Client, Decrypted } from '@/types'\nimport { createRequestLogger } from '@/utils/logger'\nimport {\n decryptModelFields,\n decryptModelFieldsWithLockContext,\n} from '../helpers/model-helpers'\nimport { noClientError } from '../index'\nimport { EncryptionOperation } from './base-operation'\n\nexport class DecryptModelOperation<\n T extends Record<string, unknown>,\n> extends EncryptionOperation<Decrypted<T>> {\n private client: Client\n private model: T\n\n constructor(client: Client, model: T) {\n super()\n this.client = client\n this.model = model\n }\n\n public withLockContext(\n lockContext: LockContextInput,\n ): DecryptModelOperationWithLockContext<T> {\n return new DecryptModelOperationWithLockContext(this, lockContext)\n }\n\n public async execute(): Promise<Result<Decrypted<T>, EncryptionError>> {\n const log = createRequestLogger()\n log.set({\n op: 'decryptModel',\n lockContext: false,\n })\n\n const result = await withResult(\n async () => {\n if (!this.client) {\n throw noClientError()\n }\n\n const auditData = this.getAuditData()\n\n return await decryptModelFields<T>(this.model, this.client, auditData)\n },\n (error: unknown) => {\n log.set({ errorCode: getErrorCode(error) ?? 'unknown' })\n return {\n type: EncryptionErrorTypes.DecryptionError,\n message: (error as Error).message,\n code: getErrorCode(error),\n }\n },\n )\n log.emit()\n return result\n }\n\n public getOperation(): {\n client: Client\n model: T\n } {\n return {\n client: this.client,\n model: this.model,\n }\n }\n}\n\nexport class DecryptModelOperationWithLockContext<\n T extends Record<string, unknown>,\n> extends EncryptionOperation<Decrypted<T>> {\n private operation: DecryptModelOperation<T>\n private lockContext: LockContextInput\n\n constructor(\n operation: DecryptModelOperation<T>,\n lockContext: LockContextInput,\n ) {\n super()\n this.operation = operation\n this.lockContext = lockContext\n const auditData = operation.getAuditData()\n if (auditData) {\n this.audit(auditData)\n }\n }\n\n public async execute(): Promise<Result<Decrypted<T>, EncryptionError>> {\n const log = createRequestLogger()\n log.set({\n op: 'decryptModel',\n lockContext: true,\n })\n\n const result = await withResult(\n async () => {\n const { client, model } = this.operation.getOperation()\n\n if (!client) {\n throw noClientError()\n }\n\n const context = resolveLockContext(this.lockContext)\n\n const auditData = this.getAuditData()\n\n return await decryptModelFieldsWithLockContext<T>(\n model,\n client,\n context,\n auditData,\n )\n },\n (error: unknown) => {\n log.set({ errorCode: getErrorCode(error) ?? 'unknown' })\n return {\n type: EncryptionErrorTypes.DecryptionError,\n message: (error as Error).message,\n code: getErrorCode(error),\n }\n },\n )\n log.emit()\n return result\n }\n}\n","import { type Result, withResult } from '@byteslice/result'\nimport {\n encrypt as ffiEncrypt,\n type JsPlaintext,\n} from '@cipherstash/protect-ffi'\nimport { getErrorCode } from '@/encryption/helpers/error-code'\nimport { assertValidNumericValue } from '@/encryption/helpers/validation'\nimport { type EncryptionError, EncryptionErrorTypes } from '@/errors'\nimport { type LockContextInput, resolveLockContext } from '@/identity'\nimport type {\n BuildableColumn,\n BuildableTable,\n Client,\n Encrypted,\n EncryptOptions,\n Plaintext,\n} from '@/types'\nimport { createRequestLogger } from '@/utils/logger'\nimport { noClientError } from '../index'\nimport { EncryptionOperation } from './base-operation'\n\nexport class EncryptOperation extends EncryptionOperation<Encrypted> {\n private client: Client\n // Internally widened to allow null so the runtime guard below can\n // short-circuit. The public `Encryption.encrypt()` signature still\n // rejects null at the type layer; this is defense in depth for callers\n // that reach this class through casts or dynamic field walking.\n private plaintext: Plaintext | null\n private column: BuildableColumn\n private table: BuildableTable\n\n constructor(\n client: Client,\n plaintext: Plaintext | null,\n opts: EncryptOptions,\n ) {\n super()\n this.client = client\n this.plaintext = plaintext\n this.column = opts.column\n this.table = opts.table\n }\n\n public withLockContext(\n lockContext: LockContextInput,\n ): EncryptOperationWithLockContext {\n return new EncryptOperationWithLockContext(this, lockContext)\n }\n\n public async execute(): Promise<Result<Encrypted, EncryptionError>> {\n const log = createRequestLogger()\n log.set({\n op: 'encrypt',\n table: this.table.tableName,\n column: this.column.getName(),\n lockContext: false,\n })\n\n const result = await withResult(\n async () => {\n if (!this.client) {\n throw noClientError()\n }\n\n if (this.plaintext === null) {\n // Defense in depth: the public `Encryption.encrypt()` signature\n // rejects null, but null can still arrive here via casts or\n // dynamic field walking. Return null directly so the result\n // matches DB NULL semantics rather than encrypting JSON null\n // into a SteVec. The cast acknowledges the type-narrow\n // contract at the public boundary.\n return null as unknown as Encrypted\n }\n\n assertValidNumericValue(this.plaintext)\n\n const { metadata } = this.getAuditData()\n\n return await ffiEncrypt(this.client, {\n // `Plaintext` widens the FFI `JsPlaintext` with `Date` (serialized via\n // `toJSON` at the boundary); cast until the upstream `JsPlaintext` input\n // union is corrected to include it.\n plaintext: this.plaintext as JsPlaintext,\n column: this.column.getName(),\n table: this.table.tableName,\n unverifiedContext: metadata,\n })\n },\n (error: unknown) => {\n log.set({ errorCode: getErrorCode(error) ?? 'unknown' })\n return {\n type: EncryptionErrorTypes.EncryptionError,\n message: (error as Error).message,\n code: getErrorCode(error),\n }\n },\n )\n log.emit()\n return result\n }\n\n public getOperation(): {\n client: Client\n plaintext: Plaintext | null\n column: BuildableColumn\n table: BuildableTable\n } {\n return {\n client: this.client,\n plaintext: this.plaintext,\n column: this.column,\n table: this.table,\n }\n }\n}\n\nexport class EncryptOperationWithLockContext extends EncryptionOperation<Encrypted> {\n private operation: EncryptOperation\n private lockContext: LockContextInput\n\n constructor(operation: EncryptOperation, lockContext: LockContextInput) {\n super()\n this.operation = operation\n this.lockContext = lockContext\n const auditData = operation.getAuditData()\n if (auditData) {\n this.audit(auditData)\n }\n }\n\n public async execute(): Promise<Result<Encrypted, EncryptionError>> {\n const { client, plaintext, column, table } = this.operation.getOperation()\n\n const log = createRequestLogger()\n log.set({\n op: 'encrypt',\n table: table.tableName,\n column: column.getName(),\n lockContext: true,\n })\n\n const result = await withResult(\n async () => {\n if (!client) {\n throw noClientError()\n }\n\n if (plaintext === null) {\n return null as unknown as Encrypted\n }\n\n assertValidNumericValue(plaintext)\n\n const { metadata } = this.getAuditData()\n const lockContext = resolveLockContext(this.lockContext)\n\n return await ffiEncrypt(client, {\n plaintext: plaintext as JsPlaintext,\n column: column.getName(),\n table: table.tableName,\n lockContext,\n unverifiedContext: metadata,\n })\n },\n (error: unknown) => {\n log.set({ errorCode: getErrorCode(error) ?? 'unknown' })\n return {\n type: EncryptionErrorTypes.EncryptionError,\n message: (error as Error).message,\n code: getErrorCode(error),\n }\n },\n )\n log.emit()\n return result\n }\n}\n","import { type Result, withResult } from '@byteslice/result'\nimport { getErrorCode } from '@/encryption/helpers/error-code'\nimport { type EncryptionError, EncryptionErrorTypes } from '@/errors'\nimport { type LockContextInput, resolveLockContext } from '@/identity'\nimport type { BuildableTable, Client } from '@/types'\nimport { createRequestLogger } from '@/utils/logger'\nimport {\n encryptModelFields,\n encryptModelFieldsWithLockContext,\n} from '../helpers/model-helpers'\nimport { noClientError } from '../index'\nimport { EncryptionOperation } from './base-operation'\n\nexport class EncryptModelOperation<\n T extends Record<string, unknown>,\n> extends EncryptionOperation<T> {\n private client: Client\n private model: Record<string, unknown>\n private table: BuildableTable\n\n constructor(\n client: Client,\n model: Record<string, unknown>,\n table: BuildableTable,\n ) {\n super()\n this.client = client\n this.model = model\n this.table = table\n }\n\n public withLockContext(\n lockContext: LockContextInput,\n ): EncryptModelOperationWithLockContext<T> {\n return new EncryptModelOperationWithLockContext(this, lockContext)\n }\n\n public async execute(): Promise<Result<T, EncryptionError>> {\n const log = createRequestLogger()\n log.set({\n op: 'encryptModel',\n table: this.table.tableName,\n lockContext: false,\n })\n\n const result = await withResult(\n async () => {\n if (!this.client) {\n throw noClientError()\n }\n\n const auditData = this.getAuditData()\n\n return (await encryptModelFields(\n this.model,\n this.table,\n this.client,\n auditData,\n )) as T\n },\n (error: unknown) => {\n log.set({ errorCode: getErrorCode(error) ?? 'unknown' })\n return {\n type: EncryptionErrorTypes.EncryptionError,\n message: (error as Error).message,\n code: getErrorCode(error),\n }\n },\n )\n log.emit()\n return result\n }\n\n public getOperation(): {\n client: Client\n model: Record<string, unknown>\n table: BuildableTable\n } {\n return {\n client: this.client,\n model: this.model,\n table: this.table,\n }\n }\n}\n\nexport class EncryptModelOperationWithLockContext<\n T extends Record<string, unknown>,\n> extends EncryptionOperation<T> {\n private operation: EncryptModelOperation<T>\n private lockContext: LockContextInput\n\n constructor(\n operation: EncryptModelOperation<T>,\n lockContext: LockContextInput,\n ) {\n super()\n this.operation = operation\n this.lockContext = lockContext\n const auditData = operation.getAuditData()\n if (auditData) {\n this.audit(auditData)\n }\n }\n\n public async execute(): Promise<Result<T, EncryptionError>> {\n const { client, model, table } = this.operation.getOperation()\n\n const log = createRequestLogger()\n log.set({\n op: 'encryptModel',\n table: table.tableName,\n lockContext: true,\n })\n\n const result = await withResult(\n async () => {\n if (!client) {\n throw noClientError()\n }\n\n const context = resolveLockContext(this.lockContext)\n\n const auditData = this.getAuditData()\n\n return (await encryptModelFieldsWithLockContext(\n model,\n table,\n client,\n context,\n auditData,\n )) as T\n },\n (error: unknown) => {\n log.set({ errorCode: getErrorCode(error) ?? 'unknown' })\n return {\n type: EncryptionErrorTypes.EncryptionError,\n message: (error as Error).message,\n code: getErrorCode(error),\n }\n },\n )\n log.emit()\n return result\n }\n}\n","import { type Result, withResult } from '@byteslice/result'\nimport {\n encryptQuery as ffiEncryptQuery,\n type JsPlaintext,\n} from '@cipherstash/protect-ffi'\nimport { formatEncryptedResult } from '@/encryption/helpers'\nimport { getErrorCode } from '@/encryption/helpers/error-code'\nimport { type EncryptionError, EncryptionErrorTypes } from '@/errors'\nimport { type LockContextInput, resolveLockContext } from '@/identity'\nimport type {\n Client,\n EncryptedQueryResult,\n EncryptQueryOptions,\n Plaintext,\n} from '@/types'\nimport { createRequestLogger } from '@/utils/logger'\nimport { resolveIndexType } from '../helpers/infer-index-type'\nimport {\n assertValueIndexCompatibility,\n validateNumericValue,\n} from '../helpers/validation'\nimport { noClientError } from '../index'\nimport { EncryptionOperation } from './base-operation'\n\nexport class EncryptQueryOperation extends EncryptionOperation<EncryptedQueryResult> {\n constructor(\n private client: Client,\n private plaintext: Plaintext | null | undefined,\n private opts: EncryptQueryOptions,\n ) {\n super()\n }\n\n public withLockContext(\n lockContext: LockContextInput,\n ): EncryptQueryOperationWithLockContext {\n return new EncryptQueryOperationWithLockContext(\n this.client,\n this.plaintext,\n this.opts,\n lockContext,\n this.auditMetadata,\n )\n }\n\n public async execute(): Promise<\n Result<EncryptedQueryResult, EncryptionError>\n > {\n const log = createRequestLogger()\n log.set({\n op: 'encryptQuery',\n table: this.opts.table.tableName,\n column: this.opts.column.getName(),\n queryType: this.opts.queryType,\n lockContext: false,\n })\n\n if (this.plaintext === null || this.plaintext === undefined) {\n log.emit()\n return { data: null }\n }\n\n const plaintext: Plaintext = this.plaintext\n\n const validationError = validateNumericValue(plaintext)\n if (validationError?.failure) {\n log.emit()\n return { failure: validationError.failure }\n }\n\n const result = await withResult(\n async () => {\n if (!this.client) throw noClientError()\n\n const { metadata } = this.getAuditData()\n\n const { indexType, queryOp } = resolveIndexType(\n this.opts.column,\n this.opts.queryType,\n plaintext,\n )\n\n // Validate value/index compatibility\n assertValueIndexCompatibility(\n plaintext,\n indexType,\n this.opts.column.getName(),\n )\n\n const encrypted = await ffiEncryptQuery(this.client, {\n // `Plaintext` widens the FFI `JsPlaintext` with `Date` (serialized via\n // `toJSON` at the boundary); cast until the upstream input union is\n // corrected to include it.\n plaintext: plaintext as JsPlaintext,\n column: this.opts.column.getName(),\n table: this.opts.table.tableName,\n indexType,\n queryOp,\n unverifiedContext: metadata,\n })\n\n return formatEncryptedResult(encrypted, this.opts.returnType)\n },\n (error: unknown) => {\n log.set({ errorCode: getErrorCode(error) ?? 'unknown' })\n return {\n type: EncryptionErrorTypes.EncryptionError,\n message: (error as Error).message,\n code: getErrorCode(error),\n }\n },\n )\n log.emit()\n return result\n }\n\n public getOperation() {\n return { client: this.client, plaintext: this.plaintext, ...this.opts }\n }\n}\n\nexport class EncryptQueryOperationWithLockContext extends EncryptionOperation<EncryptedQueryResult> {\n constructor(\n private client: Client,\n private plaintext: Plaintext | null | undefined,\n private opts: EncryptQueryOptions,\n private lockContext: LockContextInput,\n auditMetadata?: Record<string, unknown>,\n ) {\n super()\n this.auditMetadata = auditMetadata\n }\n\n public async execute(): Promise<\n Result<EncryptedQueryResult, EncryptionError>\n > {\n const log = createRequestLogger()\n log.set({\n op: 'encryptQuery',\n table: this.opts.table.tableName,\n column: this.opts.column.getName(),\n queryType: this.opts.queryType,\n lockContext: true,\n })\n\n if (this.plaintext === null || this.plaintext === undefined) {\n log.emit()\n return { data: null }\n }\n\n const plaintext: Plaintext = this.plaintext\n\n const validationError = validateNumericValue(plaintext)\n if (validationError?.failure) {\n log.emit()\n return { failure: validationError.failure }\n }\n\n const result = await withResult(\n async () => {\n if (!this.client) throw noClientError()\n\n const context = resolveLockContext(this.lockContext)\n\n const { metadata } = this.getAuditData()\n\n const { indexType, queryOp } = resolveIndexType(\n this.opts.column,\n this.opts.queryType,\n plaintext,\n )\n\n // Validate value/index compatibility\n assertValueIndexCompatibility(\n plaintext,\n indexType,\n this.opts.column.getName(),\n )\n\n const encrypted = await ffiEncryptQuery(this.client, {\n // `Plaintext` widens the FFI `JsPlaintext` with `Date` (serialized via\n // `toJSON` at the boundary); cast until the upstream input union is\n // corrected to include it.\n plaintext: plaintext as JsPlaintext,\n column: this.opts.column.getName(),\n table: this.opts.table.tableName,\n indexType,\n queryOp,\n lockContext: context,\n unverifiedContext: metadata,\n })\n\n return formatEncryptedResult(encrypted, this.opts.returnType)\n },\n (error: unknown) => {\n log.set({ errorCode: getErrorCode(error) ?? 'unknown' })\n return {\n type: EncryptionErrorTypes.EncryptionError,\n message: (error as Error).message,\n code: getErrorCode(error),\n }\n },\n )\n log.emit()\n return result\n }\n}\n","import type { ColumnSchema, EncryptConfig } from '@/schema'\nimport type { Encrypted } from '@/types'\nimport type {\n EncryptedV3TableColumn,\n PlaintextForColumn,\n QueryTypesForColumn,\n} from './columns'\n\ninterface TableDefinition {\n tableName: string\n columns: Record<string, ColumnSchema>\n}\n\n/**\n * A v3 encrypted table. Mirrors the v2 `EncryptedTable` but only accepts v3\n * column builders. Emits the same `{ tableName, columns }` definition shape.\n */\nexport class EncryptedTable<T extends EncryptedV3TableColumn> {\n /** @internal Type-level brand so TypeScript can infer `T` from `EncryptedTable<T>`. */\n declare readonly _columnType: T\n\n constructor(\n public readonly tableName: string,\n public readonly columnBuilders: T,\n ) {}\n\n build(): TableDefinition {\n // NULL PROTOTYPE — load-bearing, for the same reason as\n // {@link buildColumnKeyMap}. Keys are DB column names, which the database\n // supplies. On a plain object literal, `builtColumns['__proto__'] = schema`\n // REPARENTS the object rather than adding an own key, so the column never\n // reaches the encrypt config — `decryptModel` then skips it and its\n // ciphertext is returned undecrypted. `encryptedTable()` rejects such names\n // as JS properties, but nothing constrains a table's DB column names.\n const builtColumns: Record<string, ColumnSchema> = Object.create(null)\n for (const builder of Object.values(this.columnBuilders)) {\n // Key by the column's DB name (`getName()`), NOT the JS property name.\n // `encrypt`/`decrypt` look columns up in the config by `column.getName()`,\n // so a camelCase JS key mapping to a snake_case DB column (e.g.\n // `createdOn: types.Date('created_on')`) must register under\n // `created_on` or the FFI reports \"column not found in Encrypt config\".\n const name = builder.getName()\n // Two JS properties resolving to the same DB name would silently overwrite\n // here (later wins), dropping the first column's config. Fail loudly —\n // matching the duplicate-tableName guard in buildEncryptConfig and the\n // reserved-key guard in encryptedTable.\n if (Object.hasOwn(builtColumns, name)) {\n throw new Error(\n `[eql/v3]: duplicate column name \"${name}\" in table \"${this.tableName}\" — two columns resolve to the same DB name`,\n )\n }\n builtColumns[name] = builder.build()\n }\n return {\n tableName: this.tableName,\n columns: builtColumns,\n }\n }\n\n /**\n * Map each column's JS property name to its DB column name (`getName()`).\n * The model path matches user models by property name but must address the\n * encrypt config and FFI by DB name — `build()` keys columns by DB name, so\n * the two only agree when property == name. This recovers the mapping that\n * `build()` discards.\n *\n * NULL PROTOTYPE — load-bearing. Callers index this map by a column name that\n * ultimately comes from the database (`addJsonbCastsV3`, `filterColumnName`,\n * the mutation transform). On a plain object literal, a column named\n * `constructor` / `toString` / `valueOf` / `__proto__` resolves to an\n * inherited `Object.prototype` member, which is truthy — so a *plaintext*\n * column with such a name would be mistaken for a mapped encrypted column and\n * its `Object.prototype` value interpolated into the emitted select string.\n * `encryptedTable()` rejects such names as JS *properties*, but nothing\n * constrains the DB column names a table may contain.\n */\n buildColumnKeyMap(): Record<string, string> {\n const map = Object.create(null) as Record<string, string>\n for (const [property, builder] of Object.entries(this.columnBuilders)) {\n map[property] = builder.getName()\n }\n return map\n }\n}\n\n/**\n * Own instance members of {@link EncryptedTable} that a column name must not\n * shadow. Because {@link encryptedTable} copies column builders onto the\n * instance for accessor access (`users.email`), a column named e.g. `build`\n * would otherwise overwrite the method that {@link buildEncryptConfig} relies\n * on. `_columnType` is a type-only `declare` (no runtime property) so it is\n * listed explicitly here rather than caught by the `in` check below.\n */\nconst RESERVED_TABLE_KEYS = new Set([\n 'tableName',\n 'columnBuilders',\n '_columnType',\n 'build',\n 'buildColumnKeyMap',\n])\n\n/**\n * Whether a column name would collide with a reserved property on the table\n * object — either an own member ({@link RESERVED_TABLE_KEYS}) or any inherited\n * `Object.prototype` member (`constructor`, `toString`, `valueOf`,\n * `hasOwnProperty`, …). The `in` check covers the prototype chain so assigning\n * the column as an own property can never shadow a prototype method/accessor.\n */\nfunction isReservedTableKey(tableBuilder: object, colName: string): boolean {\n return RESERVED_TABLE_KEYS.has(colName) || colName in tableBuilder\n}\n\n/**\n * Define a v3 encrypted table. Intentionally shadows the v2 `encryptedTable`\n * name but lives on the `/eql/v3` subpath — the importer picks the model by\n * import path. The returned object is also a column accessor (`users.email`).\n */\nexport function encryptedTable<T extends EncryptedV3TableColumn>(\n tableName: string,\n columns: T,\n): EncryptedTable<T> & T {\n const tableBuilder = new EncryptedTable(\n tableName,\n columns,\n ) as EncryptedTable<T> & T\n\n for (const [colName, colBuilder] of Object.entries(columns)) {\n if (isReservedTableKey(tableBuilder, colName)) {\n throw new Error(\n `Column name \"${colName}\" collides with a reserved EncryptedTable property`,\n )\n }\n ;(tableBuilder as EncryptedV3TableColumn)[colName] = colBuilder\n }\n\n return tableBuilder\n}\n\n/**\n * Build an `EncryptConfig` (`v: 1`) from one or more v3 tables. Emits the same\n * shape as v2's `buildEncryptConfig`.\n */\nexport function buildEncryptConfig(\n ...tables: Array<EncryptedTable<EncryptedV3TableColumn>>\n): EncryptConfig {\n const config: EncryptConfig = {\n v: 1,\n tables: {},\n }\n\n for (const tb of tables) {\n const tableDef = tb.build()\n // Config tables are keyed by name, so a duplicate would silently overwrite\n // the earlier table. Fail loudly instead. (v3-only additive guard; v2's\n // buildEncryptConfig keeps its existing silent-overwrite behavior.)\n if (Object.hasOwn(config.tables, tableDef.tableName)) {\n throw new Error(\n `[eql/v3]: duplicate table name \"${tableDef.tableName}\" passed to buildEncryptConfig — each table must have a unique name`,\n )\n }\n config.tables[tableDef.tableName] = tableDef.columns\n }\n\n return config\n}\n\n/**\n * Infer the plaintext (decrypted) shape from a v3 table schema. Each column maps\n * to the TypeScript type of its domain's `castAs` kind.\n */\nexport type InferPlaintext<T extends EncryptedTable<EncryptedV3TableColumn>> =\n T extends EncryptedTable<infer C>\n ? { [K in keyof C]: PlaintextForColumn<C[K]> }\n : never\n\n/**\n * Infer the encrypted shape from a v3 table schema. See {@link InferPlaintext}\n * for why no key-remap filter is needed in the flat single-type model.\n */\nexport type InferEncrypted<T extends EncryptedTable<EncryptedV3TableColumn>> =\n T extends EncryptedTable<infer C> ? { [K in keyof C]: Encrypted } : never\n\n// ---------------------------------------------------------------------------\n// Typed-client surface helpers (@cipherstash/stack/v3)\n// ---------------------------------------------------------------------------\n\n/** Any v3 table, regardless of its column map. */\nexport type AnyV3Table = EncryptedTable<EncryptedV3TableColumn>\n\n/** Union of the concrete column builders declared on a v3 table. */\nexport type ColumnsOf<T extends AnyV3Table> =\n T extends EncryptedTable<infer C> ? C[keyof C] : never\n\n/**\n * Union of the *queryable* column builders on a v3 table. Storage-only columns\n * (whose {@link QueryTypesForColumn} is `never`) are filtered out, so they can't\n * be passed to a query method.\n */\nexport type QueryableColumnsOf<T extends AnyV3Table> =\n T extends EncryptedTable<infer C>\n ? {\n [K in keyof C]: [QueryTypesForColumn<C[K]>] extends [never]\n ? never\n : C[K]\n }[keyof C]\n : never\n\n/**\n * The accepted input model for {@link import('@/encryption/v3').TypedEncryptionClient.encryptModel}.\n * `T` is inferred from the argument: keys that name a schema column are pinned to\n * the column's plaintext type (nullable if the field is nullable), so a wrong-typed\n * field fails assignability; all other keys pass through unchanged.\n */\nexport type V3ModelInput<Table extends AnyV3Table, T> = {\n [K in keyof T]: K extends keyof InferPlaintext<Table>\n ? null extends T[K]\n ? InferPlaintext<Table>[K] | null\n : InferPlaintext<Table>[K]\n : T[K]\n}\n\n/** The encrypted result model: schema columns become `Encrypted`, others pass through. */\nexport type V3EncryptedModel<Table extends AnyV3Table, T> = {\n [K in keyof T]: K extends keyof InferPlaintext<Table>\n ? null extends T[K]\n ? Encrypted | null\n : Encrypted\n : T[K]\n}\n\n/**\n * The decrypted result model: schema columns become their plaintext type, others\n * pass through. Structurally identical to {@link V3ModelInput} — decrypt yields\n * the same plaintext shape encrypt accepts — so it is aliased rather than\n * re-declared to keep the input and output shapes from silently drifting when\n * one copy is edited. The distinct name is kept for call-site readability.\n */\nexport type V3DecryptedModel<Table extends AnyV3Table, T> = V3ModelInput<\n Table,\n T\n>\n","import {\n BIGINT,\n BIGINT_EQ,\n BIGINT_ORD,\n BIGINT_ORD_ORE,\n BOOLEAN,\n DATE,\n DATE_EQ,\n DATE_ORD,\n DATE_ORD_ORE,\n DOUBLE,\n DOUBLE_EQ,\n DOUBLE_ORD,\n DOUBLE_ORD_ORE,\n EncryptedBigintColumn,\n EncryptedBigintEqColumn,\n EncryptedBigintOrdColumn,\n EncryptedBigintOrdOreColumn,\n EncryptedBooleanColumn,\n EncryptedDateColumn,\n EncryptedDateEqColumn,\n EncryptedDateOrdColumn,\n EncryptedDateOrdOreColumn,\n EncryptedDoubleColumn,\n EncryptedDoubleEqColumn,\n EncryptedDoubleOrdColumn,\n EncryptedDoubleOrdOreColumn,\n EncryptedIntegerColumn,\n EncryptedIntegerEqColumn,\n EncryptedIntegerOrdColumn,\n EncryptedIntegerOrdOreColumn,\n EncryptedJsonColumn,\n EncryptedNumericColumn,\n EncryptedNumericEqColumn,\n EncryptedNumericOrdColumn,\n EncryptedNumericOrdOreColumn,\n EncryptedRealColumn,\n EncryptedRealEqColumn,\n EncryptedRealOrdColumn,\n EncryptedRealOrdOreColumn,\n EncryptedSmallintColumn,\n EncryptedSmallintEqColumn,\n EncryptedSmallintOrdColumn,\n EncryptedSmallintOrdOreColumn,\n EncryptedTextColumn,\n EncryptedTextEqColumn,\n EncryptedTextMatchColumn,\n EncryptedTextOrdColumn,\n EncryptedTextOrdOreColumn,\n EncryptedTextSearchColumn,\n EncryptedTimestampColumn,\n EncryptedTimestampEqColumn,\n EncryptedTimestampOrdColumn,\n EncryptedTimestampOrdOreColumn,\n INTEGER,\n INTEGER_EQ,\n INTEGER_ORD,\n INTEGER_ORD_ORE,\n NUMERIC,\n NUMERIC_EQ,\n NUMERIC_ORD,\n NUMERIC_ORD_ORE,\n REAL,\n REAL_EQ,\n REAL_ORD,\n REAL_ORD_ORE,\n SMALLINT,\n SMALLINT_EQ,\n SMALLINT_ORD,\n SMALLINT_ORD_ORE,\n TEXT,\n TEXT_EQ,\n TEXT_MATCH,\n TEXT_ORD,\n TEXT_ORD_ORE,\n TIMESTAMP,\n TIMESTAMP_EQ,\n TIMESTAMP_ORD,\n TIMESTAMP_ORD_ORE,\n type V3ColumnFactory,\n} from './columns'\n\n/**\n * The v3 column-type namespace. Each member is a public, semantic factory name\n * for a concrete EQL v3 column. Most members mirror the underlying domain name;\n * JS-friendly scalar names map to Postgres concrete domains, e.g.\n * `types.IntegerOrd` builds a `public.eql_v3_integer_ord` column and `types.Boolean`\n * builds a `public.eql_v3_boolean` column.\n *\n * If these factory names stop matching the emitted capability/domain surface,\n * the stack package is out of sync with the underlying EQL build. That is a\n * version mismatch, not a harmless naming drift.\n *\n * Each factory returns the CONCRETE column class instance (never the widened\n * `AnyEncryptedV3Column`) so per-column plaintext / query-capability inference\n * stays precise.\n *\n * ```ts\n * import { encryptedTable, types } from '@cipherstash/stack/eql/v3'\n *\n * const events = encryptedTable('events', {\n * actor: types.TextEq('actor'), // equality\n * weight: types.IntegerOrd('weight'), // order + range\n * createdAt: types.Timestamp('created_at'), // storage only\n * })\n * ```\n *\n * `types.TextSearch` is fully described by its type — like every other domain,\n * it has no capability-bearing or tuning chain. Its match index is always\n * emitted with the default configuration; run a free-text query by passing\n * `queryType: 'freeTextSearch'` to `encryptQuery`.\n */\nexport const types = {\n // integer\n Integer: (name: string) => new EncryptedIntegerColumn(name, INTEGER),\n IntegerEq: (name: string) => new EncryptedIntegerEqColumn(name, INTEGER_EQ),\n IntegerOrdOre: (name: string) =>\n new EncryptedIntegerOrdOreColumn(name, INTEGER_ORD_ORE),\n IntegerOrd: (name: string) =>\n new EncryptedIntegerOrdColumn(name, INTEGER_ORD),\n\n // smallint\n Smallint: (name: string) => new EncryptedSmallintColumn(name, SMALLINT),\n SmallintEq: (name: string) =>\n new EncryptedSmallintEqColumn(name, SMALLINT_EQ),\n SmallintOrdOre: (name: string) =>\n new EncryptedSmallintOrdOreColumn(name, SMALLINT_ORD_ORE),\n SmallintOrd: (name: string) =>\n new EncryptedSmallintOrdColumn(name, SMALLINT_ORD),\n\n // bigint (int8) — plaintext is a JS `bigint`, round-tripped losslessly by\n // the native protect-ffi boundary (see ./columns)\n Bigint: (name: string) => new EncryptedBigintColumn(name, BIGINT),\n BigintEq: (name: string) => new EncryptedBigintEqColumn(name, BIGINT_EQ),\n BigintOrdOre: (name: string) =>\n new EncryptedBigintOrdOreColumn(name, BIGINT_ORD_ORE),\n BigintOrd: (name: string) => new EncryptedBigintOrdColumn(name, BIGINT_ORD),\n\n // date\n Date: (name: string) => new EncryptedDateColumn(name, DATE),\n DateEq: (name: string) => new EncryptedDateEqColumn(name, DATE_EQ),\n DateOrdOre: (name: string) =>\n new EncryptedDateOrdOreColumn(name, DATE_ORD_ORE),\n DateOrd: (name: string) => new EncryptedDateOrdColumn(name, DATE_ORD),\n\n // timestamp\n Timestamp: (name: string) => new EncryptedTimestampColumn(name, TIMESTAMP),\n TimestampEq: (name: string) =>\n new EncryptedTimestampEqColumn(name, TIMESTAMP_EQ),\n TimestampOrdOre: (name: string) =>\n new EncryptedTimestampOrdOreColumn(name, TIMESTAMP_ORD_ORE),\n TimestampOrd: (name: string) =>\n new EncryptedTimestampOrdColumn(name, TIMESTAMP_ORD),\n\n // numeric\n Numeric: (name: string) => new EncryptedNumericColumn(name, NUMERIC),\n NumericEq: (name: string) => new EncryptedNumericEqColumn(name, NUMERIC_EQ),\n NumericOrdOre: (name: string) =>\n new EncryptedNumericOrdOreColumn(name, NUMERIC_ORD_ORE),\n NumericOrd: (name: string) =>\n new EncryptedNumericOrdColumn(name, NUMERIC_ORD),\n\n // text\n Text: (name: string) => new EncryptedTextColumn(name, TEXT),\n TextEq: (name: string) => new EncryptedTextEqColumn(name, TEXT_EQ),\n TextMatch: (name: string) => new EncryptedTextMatchColumn(name, TEXT_MATCH),\n TextOrdOre: (name: string) =>\n new EncryptedTextOrdOreColumn(name, TEXT_ORD_ORE),\n TextOrd: (name: string) => new EncryptedTextOrdColumn(name, TEXT_ORD),\n TextSearch: (name: string) => new EncryptedTextSearchColumn(name),\n\n // boolean\n Boolean: (name: string) => new EncryptedBooleanColumn(name, BOOLEAN),\n\n // real\n Real: (name: string) => new EncryptedRealColumn(name, REAL),\n RealEq: (name: string) => new EncryptedRealEqColumn(name, REAL_EQ),\n RealOrdOre: (name: string) =>\n new EncryptedRealOrdOreColumn(name, REAL_ORD_ORE),\n RealOrd: (name: string) => new EncryptedRealOrdColumn(name, REAL_ORD),\n\n // double\n Double: (name: string) => new EncryptedDoubleColumn(name, DOUBLE),\n DoubleEq: (name: string) => new EncryptedDoubleEqColumn(name, DOUBLE_EQ),\n DoubleOrdOre: (name: string) =>\n new EncryptedDoubleOrdOreColumn(name, DOUBLE_ORD_ORE),\n DoubleOrd: (name: string) => new EncryptedDoubleOrdColumn(name, DOUBLE_ORD),\n\n // json (encrypted JSONB document, ste_vec containment)\n Json: (name: string) => new EncryptedJsonColumn(name),\n // `satisfies` is load-bearing, not decoration: `DOMAIN_REGISTRY` derives itself\n // by calling every value here at module load. A non-factory export would throw\n // during module evaluation and take the supabase introspect/schema-build/verify\n // path down with it. This turns that into a compile error at the offending line.\n // `as const` applies first, so literal key inference is preserved.\n} as const satisfies Record<string, V3ColumnFactory>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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,IACF;AAAA,IACA,aAAa,CAAC,YAAY,SAAS,OAAO,YAAY,YAAY,IAAI;AAAA,IACtE,aAAa,CAAC,aAAa,OAAO,YAAY,QAAQ;AAAA,IACtD,kBAAkB,MAAM,OAAO,iBAAiB;AAAA,EAClD;AACF;AAiBA,eAAsB,aAEpB,QAGoC;AACpC,QAAM,SAAS,MAAM,WAAW;AAAA,IAC9B,SAAS,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA,IAOhB,QAAQ,EAAE,GAAG,OAAO,QAAQ,YAAY,EAAE;AAAA,EAC5C,CAAC;AACD,SAAO,YAAY,QAAQ,GAAG,OAAO,OAAO;AAC9C;","names":["buildEncryptConfig","import_protect_ffi","util","objectUtil","path","errorUtil","path","errorMap","ctx","result","issues","types","elements","processed","result","r","ZodFirstPartyTypeKind","path","import_protect_ffi","FfiProtectError","path","fs","ffiEncryptQueryBulk","import_protect_ffi","import_protect_ffi","path","path","columnPaths","import_protect_ffi","createNullResult","import_protect_ffi","ffiDecrypt","import_protect_ffi","ffiEncrypt","import_protect_ffi","ffiEncryptQuery","buildEncryptConfig"]}