@kortex-ai/hub-client 0.0.1

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/shared/errors/neverthrow.ts","../../src/shared/services/http/util.ts","../../src/shared/services/http/http.service.ts","../../src/shared/types/convex/message/message-content.ts","../../node_modules/.pnpm/convex@1.31.6_react@19.2.0/node_modules/convex/src/values/base64.ts","../../node_modules/.pnpm/convex@1.31.6_react@19.2.0/node_modules/convex/src/common/index.ts","../../node_modules/.pnpm/convex@1.31.6_react@19.2.0/node_modules/convex/src/values/value.ts","../../node_modules/.pnpm/convex@1.31.6_react@19.2.0/node_modules/convex/src/values/validators.ts","../../node_modules/.pnpm/convex@1.31.6_react@19.2.0/node_modules/convex/src/values/validator.ts","../../node_modules/.pnpm/convex@1.31.6_react@19.2.0/node_modules/convex/src/values/compare_utf8.ts","../../node_modules/.pnpm/convex-helpers@0.1.111_@sta_93c457dc952a51f4edfd5f2327f1d7a5/node_modules/convex-helpers/validators.js","../../node_modules/.pnpm/convex-helpers@0.1.111_@sta_93c457dc952a51f4edfd5f2327f1d7a5/node_modules/convex-helpers/server/zod4.js","../../src/shared/types/convex/base.ts","../../src/shared/types/convex/notification/notification.ts","../../src/shared/types/convex/notification/bare-notification.ts","../src/schemas.ts","../src/client.ts"],"names":["z","bytes","value","v","literal","z2","zCore"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeO,SAAS,GAAM,IAAA,EAAmC;AACvD,EAAA,OAAO,EAAE,IAAA,EAAiB,KAAA,EAAO,IAAA,EAAK;AACxC;AAEO,SAAS,IAAO,KAAA,EAA4B;AACjD,EAAA,OAAO,EAAE,IAAA,EAAM,IAAA,EAAM,KAAA,EAAM;AAC7B;;;ACrBO,SAAS,0BAAA,CACd,MACA,OAAA,EACuD;AAEvD,EAAA,MAAM,UAAA,GAAa,OAAO,QAAA,KAAa,WAAA,IAAe,IAAA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,KAAA,CAAM,OAAO,CAAA;AACjD,MAAA,OAAO,IAAA,CAAK,OAAA,CAA6B,6BAAA,EAA+B,SAAS,CAAA;AAAA,IACnF,SAAS,KAAA,EAAO;AACd,MAAA,OAAO,GAAA,CAAI,EAAE,OAAA,EAAS,KAAA,YAAiB,QAAQ,KAAA,CAAM,OAAA,GAAU,oBAAoB,CAAA;AAAA,IACrF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,mBACJ,OAAA,EAC6D;AAC7D,IAAA,IAAI;AACF,MAAA,MAAM,SAAA,GAAY,wBAAA,CAAyB,KAAA,CAAM,OAAO,CAAA;AACxD,MAAA,OAAO,IAAA,CAAK,OAAA,CAAoC,oCAAA,EAAsC,SAAS,CAAA;AAAA,IACjG,SAAS,KAAA,EAAO;AACd,MAAA,OAAO,GAAA,CAAI,EAAE,OAAA,EAAS,KAAA,YAAiB,QAAQ,KAAA,CAAM,OAAA,GAAU,oBAAoB,CAAA;AAAA,IACrF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,mBACJ,OAAA,EAC6D;AAC7D,IAAA,IAAI;AACF,MAAA,MAAM,SAAA,GAAY,wBAAA,CAAyB,KAAA,CAAM,OAAO,CAAA;AACxD,MAAA,OAAO,IAAA,CAAK,OAAA,CAAoC,mCAAA,EAAqC,SAAS,CAAA;AAAA,IAChG,SAAS,KAAA,EAAO;AACd,MAAA,OAAO,GAAA,CAAI,EAAE,OAAA,EAAS,KAAA,YAAiB,QAAQ,KAAA,CAAM,OAAA,GAAU,oBAAoB,CAAA;AAAA,IACrF;AAAA,EACF;AACF","file":"index.js","sourcesContent":["type Success<T> = {\n data: T\n error: null\n}\n\ntype Failure<E> = {\n data: null\n error: E\n}\n\nexport type Result<T, E = Error> = Success<T> | Failure<E>\n\n// If a function's return type is Result<void, E> you can return ok() without arguments.\nexport function ok(): Result<void, never>\nexport function ok<T>(data: T): Result<T, never>\nexport function ok<T>(data?: T): Result<T | void, never> {\n return { data: data as T, error: null }\n}\n\nexport function err<E>(error: E): Result<never, E> {\n return { data: null, error }\n}\n","export function prepareFetchBodyAndHeaders(\n body?: any,\n headers?: Record<string, string>,\n): { body?: BodyInit; headers?: Record<string, string> } {\n // Check for specific types of bodies.\n const isFormData = typeof FormData !== 'undefined' && body instanceof FormData\n const isBlob = typeof Blob !== 'undefined' && body instanceof Blob\n const isArrayBuffer =\n typeof ArrayBuffer !== 'undefined' &&\n (body instanceof ArrayBuffer || (ArrayBuffer.isView && ArrayBuffer.isView(body)))\n\n // If not FormData, Blob, or ArrayBuffer, stringify the body.\n const shouldStringify = !isFormData && !isBlob && !isArrayBuffer && typeof body === 'object'\n const headersObj: Record<string, string> = { ...(headers ?? {}) }\n\n // Automatically set Content-Type header if not provided.\n if (!headersObj['Content-Type']) {\n if (shouldStringify) {\n headersObj['Content-Type'] = 'application/json'\n } else if (isBlob) {\n const blobType = (body as Blob).type\n if (blobType) headersObj['Content-Type'] = blobType\n }\n // For ArrayBuffer/typed arrays we intentionally don't set Content-Type.\n }\n\n const finalBody = isFormData || isBlob || isArrayBuffer ? body : shouldStringify ? JSON.stringify(body) : body\n\n return {\n body: finalBody,\n headers: Object.keys(headersObj).length ? headersObj : undefined,\n }\n}\n","import { err, ok, Result } from '@/shared/errors/neverthrow'\nimport { prepareFetchBodyAndHeaders } from './util'\n\nexport type HttpError = {\n message: string\n}\n\nexport class HttpService {\n static async get<T>(\n url: string,\n params?: Record<string, any>,\n headers?: Record<string, string>,\n responseType?: 'json' | 'blob' | 'text', // Default is json\n ): Promise<Result<T, HttpError>> {\n try {\n const queryParams = new URLSearchParams(params)\n const apiUrl = queryParams.toString() ? `${url}?${queryParams.toString()}` : url\n\n const response = await fetch(apiUrl, {\n method: 'GET',\n headers: headers,\n })\n\n if (!response.ok) {\n const message = await response.text()\n return err({ message })\n }\n\n // Generalized response handling\n if (responseType === 'blob') {\n return ok((await response.blob()) as T)\n }\n if (responseType === 'text') {\n return ok((await response.text()) as T)\n }\n return ok(await response.json())\n } catch (error: any) {\n return err({ message: error.message })\n }\n }\n\n static async post<T>(\n url: string,\n body?: any,\n headers?: Record<string, string>,\n credentials?: RequestCredentials,\n ): Promise<Result<T, HttpError>> {\n try {\n const { body: finalBody, headers: finalHeaders } = prepareFetchBodyAndHeaders(body, headers)\n\n const response: Response = await fetch(url, {\n method: 'POST',\n headers: finalHeaders,\n body: finalBody as BodyInit,\n credentials: credentials,\n })\n\n if (!response.ok) {\n const message = await response.text()\n return err({ message })\n }\n\n return ok(await response.json())\n } catch (error: any) {\n return err({ message: error.message })\n }\n }\n\n static async put<T>(url: string, body?: any, headers?: Record<string, string>): Promise<Result<T, HttpError>> {\n try {\n const { body: finalBody, headers: finalHeaders } = prepareFetchBodyAndHeaders(body, headers)\n\n const response: Response = await fetch(url, {\n method: 'PUT',\n headers: finalHeaders,\n body: finalBody as BodyInit,\n })\n\n if (!response.ok) {\n const message = await response.text()\n return err({ message })\n }\n\n return ok(await response.json())\n } catch (error: any) {\n return err({ message: error.message })\n }\n }\n\n static async delete<T>(\n url: string,\n params?: Record<string, any>,\n headers?: Record<string, string>,\n ): Promise<Result<T, HttpError>> {\n try {\n const queryParams = new URLSearchParams(params)\n const apiUrl = queryParams.toString() ? `${url}?${queryParams.toString()}` : url\n\n const response: Response = await fetch(apiUrl, {\n method: 'DELETE',\n headers: headers,\n })\n\n if (!response.ok) {\n const message = await response.text()\n return err({ message })\n }\n\n return ok(await response.json())\n } catch (error: any) {\n return err({ message: error.message })\n }\n }\n}\n","import z from 'zod'\n\nexport const TextContent = z.object({\n text: z.string(),\n})\n\nexport const ImageContent = z.object({\n id: z.string(),\n mime_type: z.string(),\n sha256: z.string(),\n caption: z.string().nullable(),\n})\n\nexport const VideoContent = z.object({\n id: z.string(),\n mime_type: z.string(),\n sha256: z.string(),\n caption: z.string().nullable(),\n})\n\nexport const StickerContent = z.object({\n id: z.string(),\n mime_type: z.string(),\n sha256: z.string(),\n animated: z.boolean().nullable(),\n})\n\nexport const AudioContent = z.object({\n id: z.string(),\n mime_type: z.string(),\n sha256: z.string(),\n voice: z.boolean(),\n})\n\nexport const DocumentContent = z.object({\n id: z.string(),\n mime_type: z.string(),\n sha256: z.string(),\n filename: z.string(),\n caption: z.string().nullable(),\n})\n\nexport const LocationContent = z.object({\n latitude: z.number(),\n longitude: z.number(),\n name: z.string().nullable(),\n address: z.string().nullable(),\n url: z.string().nullable(),\n})\n\nexport const ContactContent = z.object({\n name: z.object({\n formatted_name: z.string().nullable(),\n first_name: z.string().nullable(),\n last_name: z.string().nullable(),\n middle_name: z.string().nullable(),\n suffix: z.string().nullable(),\n prefix: z.string().nullable(),\n }),\n phones: z\n .array(\n z.object({\n phone: z.string().nullable(),\n type: z.string().nullable(),\n wa_id: z.string().nullable(),\n }),\n )\n .nullable(),\n})\n\nexport const ReactionContent = z.object({\n emoji: z.string().nullable(),\n})\n\nexport const TemplateContent = z.object({\n name: z.string(),\n language: z.string(),\n renderedText: z.string(), // The rendered template text with variables filled in.\n header_variable: z.string().optional(), // Single variable for header component (only {{1}} is supported). Not saved in DB.\n body_variables: z.array(z.string()).optional(), // Variables for the body component {{1}}, {{2}}, etc. Not saved in DB.\n button_variables: z.array(z.string()).max(2).optional(), // Variables for URL buttons in order. Each URL button can have max 1 variable. Not saved in DB.\n})\n\n// Export specific content types\nexport type TextMessageContent = z.infer<typeof TextContent>\nexport type ImageMessageContent = z.infer<typeof ImageContent>\nexport type VideoMessageContent = z.infer<typeof VideoContent>\nexport type StickerMessageContent = z.infer<typeof StickerContent>\nexport type AudioMessageContent = z.infer<typeof AudioContent>\nexport type DocumentMessageContent = z.infer<typeof DocumentContent>\nexport type LocationMessageContent = z.infer<typeof LocationContent>\nexport type ContactMessageContent = z.infer<typeof ContactContent>\nexport type ReactionMessageContent = z.infer<typeof ReactionContent>\nexport type TemplateMessageContent = z.infer<typeof TemplateContent>\n\nexport type MessageContent =\n | z.infer<typeof TextContent>\n | z.infer<typeof ImageContent>\n | z.infer<typeof VideoContent>\n | z.infer<typeof StickerContent>\n | z.infer<typeof AudioContent>\n | z.infer<typeof DocumentContent>\n | z.infer<typeof LocationContent>\n | z.infer<typeof ContactContent>\n | z.infer<typeof ReactionContent>\n | z.infer<typeof TemplateContent>\n\nexport type ZodContentSchema =\n | typeof TextContent\n | typeof ImageContent\n | typeof VideoContent\n | typeof StickerContent\n | typeof AudioContent\n | typeof DocumentContent\n | typeof LocationContent\n | typeof ContactContent\n | typeof ReactionContent\n | typeof TemplateContent\n","/*\nhttps://github.com/beatgammit/base64-js/blob/88957c9943c7e2a0f03cdf73e71d579e433627d3/index.js\nCopyright (c) 2014 Jameson Little\nThe MIT License (MIT)\n*/\n\n// Vendored because this library has no ESM build, and some environments\n// (SvelteKit) are happiest when all dependencies are ESM.\n\nvar lookup: string[] = [];\nvar revLookup: number[] = [];\nvar Arr = Uint8Array;\n\nvar code = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i];\n revLookup[code.charCodeAt(i)] = i;\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup[\"-\".charCodeAt(0)] = 62;\nrevLookup[\"_\".charCodeAt(0)] = 63;\n\nfunction getLens(b64: string) {\n var len = b64.length;\n\n if (len % 4 > 0) {\n throw new Error(\"Invalid string. Length must be a multiple of 4\");\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf(\"=\");\n if (validLen === -1) validLen = len;\n\n var placeHoldersLen = validLen === len ? 0 : 4 - (validLen % 4);\n\n return [validLen, placeHoldersLen];\n}\n\n// base64 is 4/3 + up to two characters of the original data\n/** @public */\nexport function byteLength(b64: string): number {\n var lens = getLens(b64);\n var validLen = lens[0];\n var placeHoldersLen = lens[1];\n return ((validLen + placeHoldersLen) * 3) / 4 - placeHoldersLen;\n}\n\nfunction _byteLength(_b64: string, validLen: number, placeHoldersLen: number) {\n return ((validLen + placeHoldersLen) * 3) / 4 - placeHoldersLen;\n}\n\n/** @public */\nexport function toByteArray(b64: string): Uint8Array {\n var tmp;\n var lens = getLens(b64);\n var validLen = lens[0];\n var placeHoldersLen = lens[1];\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));\n\n var curByte = 0;\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0 ? validLen - 4 : validLen;\n\n var i;\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)];\n arr[curByte++] = (tmp >> 16) & 0xff;\n arr[curByte++] = (tmp >> 8) & 0xff;\n arr[curByte++] = tmp & 0xff;\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4);\n arr[curByte++] = tmp & 0xff;\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2);\n arr[curByte++] = (tmp >> 8) & 0xff;\n arr[curByte++] = tmp & 0xff;\n }\n\n return arr;\n}\n\nfunction tripletToBase64(num: number) {\n return (\n lookup[(num >> 18) & 0x3f] +\n lookup[(num >> 12) & 0x3f] +\n lookup[(num >> 6) & 0x3f] +\n lookup[num & 0x3f]\n );\n}\n\nfunction encodeChunk(uint8: Uint8Array, start: number, end: number) {\n var tmp;\n var output = [];\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xff0000) +\n ((uint8[i + 1] << 8) & 0xff00) +\n (uint8[i + 2] & 0xff);\n output.push(tripletToBase64(tmp));\n }\n return output.join(\"\");\n}\n\n/** @public */\nexport function fromByteArray(uint8: Uint8Array): string {\n var tmp;\n var len = uint8.length;\n var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes\n var parts = [];\n var maxChunkLength = 16383; // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(\n encodeChunk(\n uint8,\n i,\n i + maxChunkLength > len2 ? len2 : i + maxChunkLength,\n ),\n );\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1];\n parts.push(lookup[tmp >> 2] + lookup[(tmp << 4) & 0x3f] + \"==\");\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1];\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3f] +\n lookup[(tmp << 2) & 0x3f] +\n \"=\",\n );\n }\n\n return parts.join(\"\");\n}\n\nexport function fromByteArrayUrlSafeNoPadding(uint8: Uint8Array): string {\n return fromByteArray(uint8)\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\")\n .replace(/=/g, \"\");\n}\n","import type { Value } from \"../values/value.js\";\n\n/**\n * Validate that the arguments to a Convex function are an object, defaulting\n * `undefined` to `{}`.\n */\nexport function parseArgs(\n args: Record<string, Value> | undefined,\n): Record<string, Value> {\n if (args === undefined) {\n return {};\n }\n if (!isSimpleObject(args)) {\n throw new Error(\n `The arguments to a Convex function must be an object. Received: ${\n args as any\n }`,\n );\n }\n return args;\n}\n\nexport function validateDeploymentUrl(deploymentUrl: string) {\n // Don't use things like `new URL(deploymentUrl).hostname` since these aren't\n // supported by React Native's JS environment\n if (typeof deploymentUrl === \"undefined\") {\n throw new Error(\n `Client created with undefined deployment address. If you used an environment variable, check that it's set.`,\n );\n }\n if (typeof deploymentUrl !== \"string\") {\n throw new Error(\n `Invalid deployment address: found ${deploymentUrl as any}\".`,\n );\n }\n if (\n !(deploymentUrl.startsWith(\"http:\") || deploymentUrl.startsWith(\"https:\"))\n ) {\n throw new Error(\n `Invalid deployment address: Must start with \"https://\" or \"http://\". Found \"${deploymentUrl}\".`,\n );\n }\n\n // Most clients should connect to \".convex.cloud\". But we also support localhost and\n // custom custom. We validate the deployment url is a valid url, which is the most\n // common failure pattern.\n try {\n new URL(deploymentUrl);\n } catch {\n throw new Error(\n `Invalid deployment address: \"${deploymentUrl}\" is not a valid URL. If you believe this URL is correct, use the \\`skipConvexDeploymentUrlCheck\\` option to bypass this.`,\n );\n }\n\n // If a user uses .convex.site, this is very likely incorrect.\n if (deploymentUrl.endsWith(\".convex.site\")) {\n throw new Error(\n `Invalid deployment address: \"${deploymentUrl}\" ends with .convex.site, which is used for HTTP Actions. Convex deployment URLs typically end with .convex.cloud? If you believe this URL is correct, use the \\`skipConvexDeploymentUrlCheck\\` option to bypass this.`,\n );\n }\n}\n\n/**\n * Check whether a value is a plain old JavaScript object.\n */\nexport function isSimpleObject(value: unknown) {\n const isObject = typeof value === \"object\";\n const prototype = Object.getPrototypeOf(value);\n const isSimple =\n prototype === null ||\n prototype === Object.prototype ||\n // Objects generated from other contexts (e.g. across Node.js `vm` modules) will not satisfy the previous\n // conditions but are still simple objects.\n prototype?.constructor?.name === \"Object\";\n return isObject && isSimple;\n}\n","/**\n * Utilities for working with values stored in Convex.\n *\n * You can see the full set of supported types at\n * [Types](https://docs.convex.dev/using/types).\n * @module\n */\nimport * as Base64 from \"./base64.js\";\nimport { isSimpleObject } from \"../common/index.js\";\n\nconst LITTLE_ENDIAN = true;\n// This code is used by code that may not have bigint literals.\nconst MIN_INT64 = BigInt(\"-9223372036854775808\");\nconst MAX_INT64 = BigInt(\"9223372036854775807\");\nconst ZERO = BigInt(\"0\");\nconst EIGHT = BigInt(\"8\");\nconst TWOFIFTYSIX = BigInt(\"256\");\n\n/**\n * The type of JavaScript values serializable to JSON.\n *\n * @public\n */\nexport type JSONValue =\n | null\n | boolean\n | number\n | string\n | JSONValue[]\n | { [key: string]: JSONValue };\n\n/**\n * An identifier for a document in Convex.\n *\n * Convex documents are uniquely identified by their `Id`, which is accessible\n * on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/database/document-ids).\n *\n * Documents can be loaded using `db.get(tableName, id)` in query and mutation functions.\n *\n * IDs are base 32 encoded strings which are URL safe.\n *\n * IDs are just strings at runtime, but this type can be used to distinguish them from other\n * strings at compile time.\n *\n * If you're using code generation, use the `Id` type generated for your data model in\n * `convex/_generated/dataModel.d.ts`.\n *\n * @typeParam TableName - A string literal type of the table name (like \"users\").\n *\n * @public\n */\nexport type Id<TableName extends string> = string & { __tableName: TableName };\n\n/**\n * A value supported by Convex.\n *\n * Values can be:\n * - stored inside of documents.\n * - used as arguments and return types to queries and mutation functions.\n *\n * You can see the full set of supported types at\n * [Types](https://docs.convex.dev/using/types).\n *\n * @public\n */\nexport type Value =\n | null\n | bigint\n | number\n | boolean\n | string\n | ArrayBuffer\n | Value[]\n | { [key: string]: undefined | Value };\n\n/**\n * The types of {@link Value} that can be used to represent numbers.\n *\n * @public\n */\nexport type NumericValue = bigint | number;\n\nfunction isSpecial(n: number) {\n return Number.isNaN(n) || !Number.isFinite(n) || Object.is(n, -0);\n}\n\nexport function slowBigIntToBase64(value: bigint): string {\n // the conversion is easy if we pretend it's unsigned\n if (value < ZERO) {\n value -= MIN_INT64 + MIN_INT64;\n }\n let hex = value.toString(16);\n if (hex.length % 2 === 1) hex = \"0\" + hex;\n\n const bytes = new Uint8Array(new ArrayBuffer(8));\n let i = 0;\n for (const hexByte of hex.match(/.{2}/g)!.reverse()) {\n bytes.set([parseInt(hexByte, 16)], i++);\n value >>= EIGHT;\n }\n return Base64.fromByteArray(bytes);\n}\n\nexport function slowBase64ToBigInt(encoded: string): bigint {\n const integerBytes = Base64.toByteArray(encoded);\n if (integerBytes.byteLength !== 8) {\n throw new Error(\n `Received ${integerBytes.byteLength} bytes, expected 8 for $integer`,\n );\n }\n let value = ZERO;\n let power = ZERO;\n for (const byte of integerBytes) {\n value += BigInt(byte) * TWOFIFTYSIX ** power;\n power++;\n }\n if (value > MAX_INT64) {\n value += MIN_INT64 + MIN_INT64;\n }\n return value;\n}\n\nexport function modernBigIntToBase64(value: bigint): string {\n if (value < MIN_INT64 || MAX_INT64 < value) {\n throw new Error(\n `BigInt ${value} does not fit into a 64-bit signed integer.`,\n );\n }\n const buffer = new ArrayBuffer(8);\n new DataView(buffer).setBigInt64(0, value, true);\n return Base64.fromByteArray(new Uint8Array(buffer));\n}\n\nexport function modernBase64ToBigInt(encoded: string): bigint {\n const integerBytes = Base64.toByteArray(encoded);\n if (integerBytes.byteLength !== 8) {\n throw new Error(\n `Received ${integerBytes.byteLength} bytes, expected 8 for $integer`,\n );\n }\n const intBytesView = new DataView(integerBytes.buffer);\n return intBytesView.getBigInt64(0, true);\n}\n\n// Fall back to a slower version on Safari 14 which lacks these APIs.\nexport const bigIntToBase64 = (DataView.prototype as any).setBigInt64\n ? modernBigIntToBase64\n : slowBigIntToBase64;\nexport const base64ToBigInt = (DataView.prototype as any).getBigInt64\n ? modernBase64ToBigInt\n : slowBase64ToBigInt;\n\nconst MAX_IDENTIFIER_LEN = 1024;\n\nfunction validateObjectField(k: string) {\n if (k.length > MAX_IDENTIFIER_LEN) {\n throw new Error(\n `Field name ${k} exceeds maximum field name length ${MAX_IDENTIFIER_LEN}.`,\n );\n }\n if (k.startsWith(\"$\")) {\n throw new Error(`Field name ${k} starts with a '$', which is reserved.`);\n }\n for (let i = 0; i < k.length; i += 1) {\n const charCode = k.charCodeAt(i);\n // Non-control ASCII characters\n if (charCode < 32 || charCode >= 127) {\n throw new Error(\n `Field name ${k} has invalid character '${k[i]}': Field names can only contain non-control ASCII characters`,\n );\n }\n }\n}\n\n/**\n * Parse a Convex value from its JSON representation.\n *\n * This function will deserialize serialized Int64s to `BigInt`s, Bytes to `ArrayBuffer`s etc.\n *\n * To learn more about Convex values, see [Types](https://docs.convex.dev/using/types).\n *\n * @param value - The JSON representation of a Convex value previously created with {@link convexToJson}.\n * @returns The JavaScript representation of the Convex value.\n *\n * @public\n */\nexport function jsonToConvex(value: JSONValue): Value {\n if (value === null) {\n return value;\n }\n if (typeof value === \"boolean\") {\n return value;\n }\n if (typeof value === \"number\") {\n return value;\n }\n if (typeof value === \"string\") {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((value) => jsonToConvex(value));\n }\n if (typeof value !== \"object\") {\n throw new Error(`Unexpected type of ${value as any}`);\n }\n const entries = Object.entries(value);\n if (entries.length === 1) {\n const key = entries[0][0];\n if (key === \"$bytes\") {\n if (typeof value.$bytes !== \"string\") {\n throw new Error(`Malformed $bytes field on ${value as any}`);\n }\n return Base64.toByteArray(value.$bytes).buffer;\n }\n if (key === \"$integer\") {\n if (typeof value.$integer !== \"string\") {\n throw new Error(`Malformed $integer field on ${value as any}`);\n }\n return base64ToBigInt(value.$integer);\n }\n if (key === \"$float\") {\n if (typeof value.$float !== \"string\") {\n throw new Error(`Malformed $float field on ${value as any}`);\n }\n const floatBytes = Base64.toByteArray(value.$float);\n if (floatBytes.byteLength !== 8) {\n throw new Error(\n `Received ${floatBytes.byteLength} bytes, expected 8 for $float`,\n );\n }\n const floatBytesView = new DataView(floatBytes.buffer);\n const float = floatBytesView.getFloat64(0, LITTLE_ENDIAN);\n if (!isSpecial(float)) {\n throw new Error(`Float ${float} should be encoded as a number`);\n }\n return float;\n }\n if (key === \"$set\") {\n throw new Error(\n `Received a Set which is no longer supported as a Convex type.`,\n );\n }\n if (key === \"$map\") {\n throw new Error(\n `Received a Map which is no longer supported as a Convex type.`,\n );\n }\n }\n const out: { [key: string]: Value } = {};\n for (const [k, v] of Object.entries(value)) {\n validateObjectField(k);\n out[k] = jsonToConvex(v);\n }\n return out;\n}\n\nconst MAX_VALUE_FOR_ERROR_LEN = 16384;\n\nexport function stringifyValueForError(value: any) {\n const str = JSON.stringify(value, (_key, value) => {\n if (value === undefined) {\n // By default `JSON.stringify` converts undefined, functions, symbols,\n // Infinity, and NaN to null which produces a confusing error message.\n // We deal with `undefined` specifically because it's the most common.\n // Ideally we'd use a pretty-printing library that prints `undefined`\n // (no quotes), but it might not be worth the bundle size cost.\n return \"undefined\";\n }\n if (typeof value === \"bigint\") {\n // `JSON.stringify` throws on bigints by default.\n return `${value.toString()}n`;\n }\n return value;\n });\n if (str.length > MAX_VALUE_FOR_ERROR_LEN) {\n const rest = \"[...truncated]\";\n let truncateAt = MAX_VALUE_FOR_ERROR_LEN - rest.length;\n const codePoint = str.codePointAt(truncateAt - 1);\n if (codePoint !== undefined && codePoint > 0xffff) {\n // don't split a surrogate pair in half\n truncateAt -= 1;\n }\n return str.substring(0, truncateAt) + rest;\n }\n return str;\n}\n\nfunction convexToJsonInternal(\n value: Value,\n originalValue: Value,\n context: string,\n includeTopLevelUndefined: boolean,\n): JSONValue {\n if (value === undefined) {\n const contextText =\n context &&\n ` (present at path ${context} in original object ${stringifyValueForError(\n originalValue,\n )})`;\n throw new Error(\n `undefined is not a valid Convex value${contextText}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`,\n );\n }\n if (value === null) {\n return value;\n }\n if (typeof value === \"bigint\") {\n if (value < MIN_INT64 || MAX_INT64 < value) {\n throw new Error(\n `BigInt ${value} does not fit into a 64-bit signed integer.`,\n );\n }\n return { $integer: bigIntToBase64(value) };\n }\n if (typeof value === \"number\") {\n if (isSpecial(value)) {\n const buffer = new ArrayBuffer(8);\n new DataView(buffer).setFloat64(0, value, LITTLE_ENDIAN);\n return { $float: Base64.fromByteArray(new Uint8Array(buffer)) };\n } else {\n return value;\n }\n }\n if (typeof value === \"boolean\") {\n return value;\n }\n if (typeof value === \"string\") {\n return value;\n }\n if (value instanceof ArrayBuffer) {\n return { $bytes: Base64.fromByteArray(new Uint8Array(value)) };\n }\n if (Array.isArray(value)) {\n return value.map((value, i) =>\n convexToJsonInternal(value, originalValue, context + `[${i}]`, false),\n );\n }\n if (value instanceof Set) {\n throw new Error(\n errorMessageForUnsupportedType(context, \"Set\", [...value], originalValue),\n );\n }\n if (value instanceof Map) {\n throw new Error(\n errorMessageForUnsupportedType(context, \"Map\", [...value], originalValue),\n );\n }\n\n if (!isSimpleObject(value)) {\n const theType = value?.constructor?.name;\n const typeName = theType ? `${theType} ` : \"\";\n throw new Error(\n errorMessageForUnsupportedType(context, typeName, value, originalValue),\n );\n }\n\n const out: { [key: string]: JSONValue } = {};\n const entries = Object.entries(value);\n entries.sort(([k1, _v1], [k2, _v2]) => (k1 === k2 ? 0 : k1 < k2 ? -1 : 1));\n for (const [k, v] of entries) {\n if (v !== undefined) {\n validateObjectField(k);\n out[k] = convexToJsonInternal(v, originalValue, context + `.${k}`, false);\n } else if (includeTopLevelUndefined) {\n validateObjectField(k);\n out[k] = convexOrUndefinedToJsonInternal(\n v,\n originalValue,\n context + `.${k}`,\n );\n }\n }\n return out;\n}\n\nfunction errorMessageForUnsupportedType(\n context: string,\n typeName: string,\n value: any,\n originalValue: any,\n) {\n if (context) {\n return `${typeName}${stringifyValueForError(\n value,\n )} is not a supported Convex type (present at path ${context} in original object ${stringifyValueForError(\n originalValue,\n )}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`;\n } else {\n return `${typeName}${stringifyValueForError(\n value,\n )} is not a supported Convex type.`;\n }\n}\n\n// convexOrUndefinedToJsonInternal wrapper exists so we can pipe through the\n// `originalValue` and `context` through for better error messaging.\nfunction convexOrUndefinedToJsonInternal(\n value: Value | undefined,\n originalValue: Value | undefined,\n context: string,\n): JSONValue {\n if (value === undefined) {\n return { $undefined: null };\n } else {\n if (originalValue === undefined) {\n // This should not happen.\n throw new Error(\n `Programming error. Current value is ${stringifyValueForError(\n value,\n )} but original value is undefined`,\n );\n }\n return convexToJsonInternal(value, originalValue, context, false);\n }\n}\n\n/**\n * Convert a Convex value to its JSON representation.\n *\n * Use {@link jsonToConvex} to recreate the original value.\n *\n * To learn more about Convex values, see [Types](https://docs.convex.dev/using/types).\n *\n * @param value - A Convex value to convert into JSON.\n * @returns The JSON representation of `value`.\n *\n * @public\n */\nexport function convexToJson(value: Value): JSONValue {\n return convexToJsonInternal(value, value, \"\", false);\n}\n\n// Convert a Convex value or `undefined` into its JSON representation.\n// `undefined` is used in filters to represent a missing object field.\nexport function convexOrUndefinedToJson(value: Value | undefined): JSONValue {\n return convexOrUndefinedToJsonInternal(value, value, \"\");\n}\n\n/**\n * Similar to convexToJson but also serializes top level undefined fields\n * using convexOrUndefinedToJson().\n *\n * @param value - A Convex value to convert into JSON.\n * @returns The JSON representation of `value`.\n */\nexport function patchValueToJson(value: Value): JSONValue {\n return convexToJsonInternal(value, value, \"\", true);\n}\n","import { Expand } from \"../type_utils.js\";\nimport { GenericId } from \"./index.js\";\nimport { GenericValidator, ObjectType } from \"./validator.js\";\nimport { JSONValue, convexToJson } from \"./value.js\";\n\ntype TableNameFromType<T> =\n T extends GenericId<infer TableName> ? TableName : string;\n\nconst UNDEFINED_VALIDATOR_ERROR_URL =\n \"https://docs.convex.dev/error#undefined-validator\";\n\nfunction throwUndefinedValidatorError(\n context: string,\n fieldName?: string,\n): never {\n const fieldInfo = fieldName !== undefined ? ` for field \"${fieldName}\"` : \"\";\n throw new Error(\n `A validator is undefined${fieldInfo} in ${context}. ` +\n `This is often caused by circular imports. ` +\n `See ${UNDEFINED_VALIDATOR_ERROR_URL} for details.`,\n );\n}\n\n/**\n * Avoid using `instanceof BaseValidator`; this is inheritence for code reuse\n * not type heirarchy.\n */\nabstract class BaseValidator<\n Type,\n IsOptional extends OptionalProperty = \"required\",\n FieldPaths extends string = never,\n> {\n /**\n * Only for TypeScript, the TS type of the JS values validated\n * by this validator.\n */\n readonly type!: Type;\n /**\n * Only for TypeScript, if this an Object validator, then\n * this is the TS type of its property names.\n */\n readonly fieldPaths!: FieldPaths;\n\n /**\n * Whether this is an optional Object property value validator.\n */\n readonly isOptional: IsOptional;\n\n /**\n * Always `\"true\"`.\n */\n readonly isConvexValidator: true;\n\n constructor({ isOptional }: { isOptional: IsOptional }) {\n this.isOptional = isOptional;\n this.isConvexValidator = true;\n }\n /** @internal */\n abstract get json(): ValidatorJSON;\n /** @internal */\n abstract asOptional(): Validator<Type | undefined, \"optional\", FieldPaths>;\n}\n\n/**\n * The type of the `v.id(tableName)` validator.\n */\nexport class VId<\n Type,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The name of the table that the validated IDs must belong to.\n */\n readonly tableName: TableNameFromType<Type>;\n\n /**\n * The kind of validator, `\"id\"`.\n */\n readonly kind = \"id\" as const;\n\n /**\n * Usually you'd use `v.id(tableName)` instead.\n */\n constructor({\n isOptional,\n tableName,\n }: {\n isOptional: IsOptional;\n tableName: TableNameFromType<Type>;\n }) {\n super({ isOptional });\n if (typeof tableName !== \"string\") {\n throw new Error(\"v.id(tableName) requires a string\");\n }\n this.tableName = tableName;\n }\n /** @internal */\n get json(): ValidatorJSON {\n return { type: \"id\", tableName: this.tableName };\n }\n /** @internal */\n asOptional() {\n return new VId<Type | undefined, \"optional\">({\n isOptional: \"optional\",\n tableName: this.tableName,\n });\n }\n}\n\n/**\n * The type of the `v.float64()` validator.\n */\nexport class VFloat64<\n Type = number,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"float64\"`.\n */\n readonly kind = \"float64\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n // Server expects the old name `number` string instead of `float64`.\n return { type: \"number\" };\n }\n /** @internal */\n asOptional() {\n return new VFloat64<Type | undefined, \"optional\">({\n isOptional: \"optional\",\n });\n }\n}\n\n/**\n * The type of the `v.int64()` validator.\n */\nexport class VInt64<\n Type = bigint,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"int64\"`.\n */\n readonly kind = \"int64\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n // Server expects the old name `bigint`.\n return { type: \"bigint\" };\n }\n /** @internal */\n asOptional() {\n return new VInt64<Type | undefined, \"optional\">({ isOptional: \"optional\" });\n }\n}\n\n/**\n * The type of the `v.boolean()` validator.\n */\nexport class VBoolean<\n Type = boolean,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"boolean\"`.\n */\n readonly kind = \"boolean\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n return { type: this.kind };\n }\n /** @internal */\n asOptional() {\n return new VBoolean<Type | undefined, \"optional\">({\n isOptional: \"optional\",\n });\n }\n}\n\n/**\n * The type of the `v.bytes()` validator.\n */\nexport class VBytes<\n Type = ArrayBuffer,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"bytes\"`.\n */\n readonly kind = \"bytes\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n return { type: this.kind };\n }\n /** @internal */\n asOptional() {\n return new VBytes<Type | undefined, \"optional\">({ isOptional: \"optional\" });\n }\n}\n\n/**\n * The type of the `v.string()` validator.\n */\nexport class VString<\n Type = string,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"string\"`.\n */\n readonly kind = \"string\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n return { type: this.kind };\n }\n /** @internal */\n asOptional() {\n return new VString<Type | undefined, \"optional\">({\n isOptional: \"optional\",\n });\n }\n}\n\n/**\n * The type of the `v.null()` validator.\n */\nexport class VNull<\n Type = null,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"null\"`.\n */\n readonly kind = \"null\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n return { type: this.kind };\n }\n /** @internal */\n asOptional() {\n return new VNull<Type | undefined, \"optional\">({ isOptional: \"optional\" });\n }\n}\n\n/**\n * The type of the `v.any()` validator.\n */\nexport class VAny<\n Type = any,\n IsOptional extends OptionalProperty = \"required\",\n FieldPaths extends string = string,\n> extends BaseValidator<Type, IsOptional, FieldPaths> {\n /**\n * The kind of validator, `\"any\"`.\n */\n readonly kind = \"any\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n return {\n type: this.kind,\n };\n }\n /** @internal */\n asOptional() {\n return new VAny<Type | undefined, \"optional\", FieldPaths>({\n isOptional: \"optional\",\n });\n }\n}\n\n/**\n * The type of the `v.object()` validator.\n */\nexport class VObject<\n Type,\n Fields extends Record<string, GenericValidator>,\n IsOptional extends OptionalProperty = \"required\",\n FieldPaths extends string = {\n [Property in keyof Fields]:\n | JoinFieldPaths<Property & string, Fields[Property][\"fieldPaths\"]>\n | Property;\n }[keyof Fields] &\n string,\n> extends BaseValidator<Type, IsOptional, FieldPaths> {\n /**\n * An object with the validator for each property.\n */\n readonly fields: Fields;\n\n /**\n * The kind of validator, `\"object\"`.\n */\n readonly kind = \"object\" as const;\n\n /**\n * Usually you'd use `v.object({ ... })` instead.\n */\n constructor({\n isOptional,\n fields,\n }: {\n isOptional: IsOptional;\n fields: Fields;\n }) {\n super({ isOptional });\n globalThis.Object.entries(fields).forEach(([fieldName, validator]) => {\n if (validator === undefined) {\n throwUndefinedValidatorError(\"v.object()\", fieldName);\n }\n if (!validator.isConvexValidator) {\n throw new Error(\"v.object() entries must be validators\");\n }\n });\n this.fields = fields;\n }\n /** @internal */\n get json(): ValidatorJSON {\n return {\n type: this.kind,\n value: globalThis.Object.fromEntries(\n globalThis.Object.entries(this.fields).map(([k, v]) => [\n k,\n {\n fieldType: v.json,\n optional: v.isOptional === \"optional\" ? true : false,\n },\n ]),\n ),\n };\n }\n /** @internal */\n asOptional() {\n return new VObject<Type | undefined, Fields, \"optional\", FieldPaths>({\n isOptional: \"optional\",\n fields: this.fields,\n });\n }\n\n /**\n * Create a new VObject with the specified fields omitted.\n * @param fields The field names to omit from this VObject.\n */\n omit<K extends keyof Fields & string>(\n ...fields: K[]\n ): VObject<Expand<Omit<Type, K>>, Expand<Omit<Fields, K>>, IsOptional> {\n const newFields = { ...this.fields };\n for (const field of fields) {\n delete newFields[field];\n }\n return new VObject({\n isOptional: this.isOptional,\n fields: newFields as any,\n });\n }\n\n /**\n * Create a new VObject with only the specified fields.\n * @param fields The field names to pick from this VObject.\n */\n pick<K extends keyof Fields & string>(\n ...fields: K[]\n ): VObject<\n Expand<Pick<Type, Extract<keyof Type, K>>>,\n Expand<Pick<Fields, K>>,\n IsOptional\n > {\n const newFields: Record<string, GenericValidator> = {};\n for (const field of fields) {\n newFields[field] = this.fields[field];\n }\n return new VObject({\n isOptional: this.isOptional,\n fields: newFields as Expand<Pick<Fields, K>>,\n });\n }\n\n /**\n * Create a new VObject with all fields marked as optional.\n */\n partial(): VObject<\n { [K in keyof Type]?: Type[K] },\n { [K in keyof Fields]: VOptional<Fields[K]> },\n IsOptional\n > {\n const newFields: Record<string, GenericValidator> = {};\n for (const [key, validator] of globalThis.Object.entries(this.fields)) {\n newFields[key] = validator.asOptional();\n }\n return new VObject({\n isOptional: this.isOptional,\n fields: newFields as {\n [K in keyof Fields]: VOptional<Fields[K]>;\n },\n });\n }\n\n /**\n * Create a new VObject with additional fields merged in.\n * @param fields An object with additional validators to merge into this VObject.\n */\n extend<NewFields extends Record<string, GenericValidator>>(\n fields: NewFields,\n ): VObject<\n Expand<Type & ObjectType<NewFields>>,\n Expand<Fields & NewFields>,\n IsOptional\n > {\n return new VObject({\n isOptional: this.isOptional,\n fields: { ...this.fields, ...fields } as Expand<Fields & NewFields>,\n });\n }\n}\n\n/**\n * The type of the `v.literal()` validator.\n */\nexport class VLiteral<\n Type,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The value that the validated values must be equal to.\n */\n readonly value: Type;\n\n /**\n * The kind of validator, `\"literal\"`.\n */\n readonly kind = \"literal\" as const;\n\n /**\n * Usually you'd use `v.literal(value)` instead.\n */\n constructor({ isOptional, value }: { isOptional: IsOptional; value: Type }) {\n super({ isOptional });\n if (\n typeof value !== \"string\" &&\n typeof value !== \"boolean\" &&\n typeof value !== \"number\" &&\n typeof value !== \"bigint\"\n ) {\n throw new Error(\"v.literal(value) must be a string, number, or boolean\");\n }\n this.value = value;\n }\n /** @internal */\n get json(): ValidatorJSON {\n return {\n type: this.kind,\n value: convexToJson(this.value as string | boolean | number | bigint),\n };\n }\n /** @internal */\n asOptional() {\n return new VLiteral<Type | undefined, \"optional\">({\n isOptional: \"optional\",\n value: this.value,\n });\n }\n}\n\n/**\n * The type of the `v.array()` validator.\n */\nexport class VArray<\n Type,\n Element extends Validator<any, \"required\", any>,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The validator for the elements of the array.\n */\n readonly element: Element;\n\n /**\n * The kind of validator, `\"array\"`.\n */\n readonly kind = \"array\" as const;\n\n /**\n * Usually you'd use `v.array(element)` instead.\n */\n constructor({\n isOptional,\n element,\n }: {\n isOptional: IsOptional;\n element: Element;\n }) {\n super({ isOptional });\n if (element === undefined) {\n throwUndefinedValidatorError(\"v.array()\");\n }\n this.element = element;\n }\n /** @internal */\n get json(): ValidatorJSON {\n return {\n type: this.kind,\n value: this.element.json,\n };\n }\n /** @internal */\n asOptional() {\n return new VArray<Type | undefined, Element, \"optional\">({\n isOptional: \"optional\",\n element: this.element,\n });\n }\n}\n\n/**\n * The type of the `v.record()` validator.\n */\nexport class VRecord<\n Type,\n Key extends Validator<string, \"required\", any>,\n Value extends Validator<any, \"required\", any>,\n IsOptional extends OptionalProperty = \"required\",\n FieldPaths extends string = string,\n> extends BaseValidator<Type, IsOptional, FieldPaths> {\n /**\n * The validator for the keys of the record.\n */\n readonly key: Key;\n\n /**\n * The validator for the values of the record.\n */\n readonly value: Value;\n\n /**\n * The kind of validator, `\"record\"`.\n */\n readonly kind = \"record\" as const;\n\n /**\n * Usually you'd use `v.record(key, value)` instead.\n */\n constructor({\n isOptional,\n key,\n value,\n }: {\n isOptional: IsOptional;\n key: Key;\n value: Value;\n }) {\n super({ isOptional });\n if (key === undefined) {\n throwUndefinedValidatorError(\"v.record()\", \"key\");\n }\n if (value === undefined) {\n throwUndefinedValidatorError(\"v.record()\", \"value\");\n }\n if ((key.isOptional as OptionalProperty) === \"optional\") {\n throw new Error(\"Record validator cannot have optional keys\");\n }\n if ((value.isOptional as OptionalProperty) === \"optional\") {\n throw new Error(\"Record validator cannot have optional values\");\n }\n if (!key.isConvexValidator || !value.isConvexValidator) {\n throw new Error(\"Key and value of v.record() but be validators\");\n }\n this.key = key;\n this.value = value;\n }\n /** @internal */\n get json(): ValidatorJSON {\n return {\n type: this.kind,\n // This cast is needed because TypeScript thinks the key type is too wide\n keys: this.key.json as RecordKeyValidatorJSON,\n values: {\n fieldType: this.value.json,\n optional: false,\n },\n };\n }\n /** @internal */\n asOptional() {\n return new VRecord<Type | undefined, Key, Value, \"optional\", FieldPaths>({\n isOptional: \"optional\",\n key: this.key,\n value: this.value,\n });\n }\n}\n\n/**\n * The type of the `v.union()` validator.\n */\nexport class VUnion<\n Type,\n T extends Validator<any, \"required\", any>[],\n IsOptional extends OptionalProperty = \"required\",\n FieldPaths extends string = T[number][\"fieldPaths\"],\n> extends BaseValidator<Type, IsOptional, FieldPaths> {\n /**\n * The array of validators, one of which must match the value.\n */\n readonly members: T;\n\n /**\n * The kind of validator, `\"union\"`.\n */\n readonly kind = \"union\" as const;\n\n /**\n * Usually you'd use `v.union(...members)` instead.\n */\n constructor({ isOptional, members }: { isOptional: IsOptional; members: T }) {\n super({ isOptional });\n members.forEach((member, index) => {\n if (member === undefined) {\n throwUndefinedValidatorError(\"v.union()\", `member at index ${index}`);\n }\n if (!member.isConvexValidator) {\n throw new Error(\"All members of v.union() must be validators\");\n }\n });\n this.members = members;\n }\n /** @internal */\n get json(): ValidatorJSON {\n return {\n type: this.kind,\n value: this.members.map((v) => v.json),\n };\n }\n /** @internal */\n asOptional() {\n return new VUnion<Type | undefined, T, \"optional\">({\n isOptional: \"optional\",\n members: this.members,\n });\n }\n}\n\n// prettier-ignore\nexport type VOptional<T extends Validator<any, OptionalProperty, any>> =\n T extends VId<infer Type, OptionalProperty> ? VId<Type | undefined, \"optional\">\n : T extends VString<infer Type, OptionalProperty>\n ? VString<Type | undefined, \"optional\">\n : T extends VFloat64<infer Type, OptionalProperty>\n ? VFloat64<Type | undefined, \"optional\">\n : T extends VInt64<infer Type, OptionalProperty>\n ? VInt64<Type | undefined, \"optional\">\n : T extends VBoolean<infer Type, OptionalProperty>\n ? VBoolean<Type | undefined, \"optional\">\n : T extends VNull<infer Type, OptionalProperty>\n ? VNull<Type | undefined, \"optional\">\n : T extends VAny<infer Type, OptionalProperty>\n ? VAny<Type | undefined, \"optional\">\n : T extends VLiteral<infer Type, OptionalProperty>\n ? VLiteral<Type | undefined, \"optional\">\n : T extends VBytes<infer Type, OptionalProperty>\n ? VBytes<Type | undefined, \"optional\">\n : T extends VObject< infer Type, infer Fields, OptionalProperty, infer FieldPaths>\n ? VObject<Type | undefined, Fields, \"optional\", FieldPaths>\n : T extends VArray<infer Type, infer Element, OptionalProperty>\n ? VArray<Type | undefined, Element, \"optional\">\n : T extends VRecord< infer Type, infer Key, infer Value, OptionalProperty, infer FieldPaths>\n ? VRecord<Type | undefined, Key, Value, \"optional\", FieldPaths>\n : T extends VUnion<infer Type, infer Members, OptionalProperty, infer FieldPaths>\n ? VUnion<Type | undefined, Members, \"optional\", FieldPaths>\n : never\n\n/**\n * Type representing whether a property in an object is optional or required.\n *\n * @public\n */\nexport type OptionalProperty = \"optional\" | \"required\";\n\n/**\n * A validator for a Convex value.\n *\n * This should be constructed using the validator builder, {@link v}.\n *\n * A validator encapsulates:\n * - The TypeScript type of this value.\n * - Whether this field should be optional if it's included in an object.\n * - The TypeScript type for the set of index field paths that can be used to\n * build indexes on this value.\n * - A JSON representation of the validator.\n *\n * Specific types of validators contain additional information: for example\n * an `ArrayValidator` contains an `element` property with the validator\n * used to validate each element of the list. Use the shared 'kind' property\n * to identity the type of validator.\n *\n * More validators can be added in future releases so an exhaustive\n * switch statement on validator `kind` should be expected to break\n * in future releases of Convex.\n *\n * @public\n */\nexport type Validator<\n Type,\n IsOptional extends OptionalProperty = \"required\",\n FieldPaths extends string = never,\n> =\n | VId<Type, IsOptional>\n | VString<Type, IsOptional>\n | VFloat64<Type, IsOptional>\n | VInt64<Type, IsOptional>\n | VBoolean<Type, IsOptional>\n | VNull<Type, IsOptional>\n | VAny<Type, IsOptional>\n | VLiteral<Type, IsOptional>\n | VBytes<Type, IsOptional>\n | VObject<\n Type,\n Record<string, Validator<any, OptionalProperty, any>>,\n IsOptional,\n FieldPaths\n >\n | VArray<Type, Validator<any, \"required\", any>, IsOptional>\n | VRecord<\n Type,\n Validator<string, \"required\", any>,\n Validator<any, \"required\", any>,\n IsOptional,\n FieldPaths\n >\n | VUnion<Type, Validator<any, \"required\", any>[], IsOptional, FieldPaths>;\n\n/**\n * Join together two index field paths.\n *\n * This is used within the validator builder, {@link v}.\n * @public\n */\nexport type JoinFieldPaths<\n Start extends string,\n End extends string,\n> = `${Start}.${End}`;\n\nexport type ObjectFieldType = { fieldType: ValidatorJSON; optional: boolean };\n\nexport type ValidatorJSON =\n | { type: \"null\" }\n | { type: \"number\" }\n | { type: \"bigint\" }\n | { type: \"boolean\" }\n | { type: \"string\" }\n | { type: \"bytes\" }\n | { type: \"any\" }\n | { type: \"literal\"; value: JSONValue }\n | { type: \"id\"; tableName: string }\n | { type: \"array\"; value: ValidatorJSON }\n | {\n type: \"record\";\n keys: RecordKeyValidatorJSON;\n values: RecordValueValidatorJSON;\n }\n | { type: \"object\"; value: Record<string, ObjectFieldType> }\n | { type: \"union\"; value: ValidatorJSON[] };\n\nexport type RecordKeyValidatorJSON =\n | { type: \"string\" }\n | { type: \"id\"; tableName: string }\n | { type: \"union\"; value: RecordKeyValidatorJSON[] };\n\nexport type RecordValueValidatorJSON = ObjectFieldType & { optional: false };\n","import { Expand } from \"../type_utils.js\";\nimport { GenericId } from \"./index.js\";\nimport {\n OptionalProperty,\n VAny,\n VArray,\n VBoolean,\n VBytes,\n VFloat64,\n VId,\n VInt64,\n VLiteral,\n VNull,\n VObject,\n VOptional,\n VRecord,\n VString,\n VUnion,\n Validator,\n} from \"./validators.js\";\n\n/**\n * The type that all validators must extend.\n *\n * @public\n */\nexport type GenericValidator = Validator<any, any, any>;\n\nexport function isValidator(v: any): v is GenericValidator {\n return !!v.isConvexValidator;\n}\n\n/**\n * Coerce an object with validators as properties to a validator.\n * If a validator is passed, return it.\n *\n * @public\n */\nexport function asObjectValidator<\n V extends Validator<any, any, any> | PropertyValidators,\n>(\n obj: V,\n): V extends Validator<any, any, any>\n ? V\n : V extends PropertyValidators\n ? Validator<ObjectType<V>>\n : never {\n if (isValidator(obj)) {\n return obj as any;\n } else {\n return v.object(obj as PropertyValidators) as any;\n }\n}\n\n/**\n * Coerce an object with validators as properties to a validator.\n * If a validator is passed, return it.\n *\n * @public\n */\nexport type AsObjectValidator<\n V extends Validator<any, any, any> | PropertyValidators,\n> =\n V extends Validator<any, any, any>\n ? V\n : V extends PropertyValidators\n ? Validator<ObjectType<V>>\n : never;\n\n/**\n * The validator builder.\n *\n * This builder allows you to build validators for Convex values.\n *\n * Validators can be used in [schema definitions](https://docs.convex.dev/database/schemas)\n * and as input validators for Convex functions.\n *\n * @public\n */\nexport const v = {\n /**\n * Validates that the value corresponds to an ID of a document in given table.\n * @param tableName The name of the table.\n */\n id: <TableName extends string>(tableName: TableName) => {\n return new VId<GenericId<TableName>>({\n isOptional: \"required\",\n tableName,\n });\n },\n\n /**\n * Validates that the value is of type Null.\n */\n null: () => {\n return new VNull({ isOptional: \"required\" });\n },\n\n /**\n * Validates that the value is of Convex type Float64 (Number in JS).\n *\n * Alias for `v.float64()`\n */\n number: () => {\n return new VFloat64({ isOptional: \"required\" });\n },\n\n /**\n * Validates that the value is of Convex type Float64 (Number in JS).\n */\n float64: () => {\n return new VFloat64({ isOptional: \"required\" });\n },\n\n /**\n * @deprecated Use `v.int64()` instead\n */\n bigint: () => {\n return new VInt64({ isOptional: \"required\" });\n },\n\n /**\n * Validates that the value is of Convex type Int64 (BigInt in JS).\n */\n int64: () => {\n return new VInt64({ isOptional: \"required\" });\n },\n\n /**\n * Validates that the value is of type Boolean.\n */\n boolean: () => {\n return new VBoolean({ isOptional: \"required\" });\n },\n\n /**\n * Validates that the value is of type String.\n */\n string: () => {\n return new VString({ isOptional: \"required\" });\n },\n\n /**\n * Validates that the value is of Convex type Bytes (constructed in JS via `ArrayBuffer`).\n */\n bytes: () => {\n return new VBytes({ isOptional: \"required\" });\n },\n\n /**\n * Validates that the value is equal to the given literal value.\n * @param literal The literal value to compare against.\n */\n literal: <T extends string | number | bigint | boolean>(literal: T) => {\n return new VLiteral<T>({ isOptional: \"required\", value: literal });\n },\n\n /**\n * Validates that the value is an Array of the given element type.\n * @param element The validator for the elements of the array.\n */\n array: <T extends Validator<any, \"required\", any>>(element: T) => {\n return new VArray<T[\"type\"][], T>({ isOptional: \"required\", element });\n },\n\n /**\n * Validates that the value is an Object with the given properties.\n * @param fields An object specifying the validator for each property.\n */\n object: <T extends PropertyValidators>(fields: T) => {\n return new VObject<ObjectType<T>, T>({ isOptional: \"required\", fields });\n },\n\n /**\n * Validates that the value is a Record with keys and values that match the given types.\n * @param keys The validator for the keys of the record. This cannot contain string literals.\n * @param values The validator for the values of the record.\n */\n record: <\n Key extends Validator<string, \"required\", any>,\n Value extends Validator<any, \"required\", any>,\n >(\n keys: Key,\n values: Value,\n ) => {\n return new VRecord<Record<Infer<Key>, Value[\"type\"]>, Key, Value>({\n isOptional: \"required\",\n key: keys,\n value: values,\n });\n },\n\n /**\n * Validates that the value matches one of the given validators.\n * @param members The validators to match against.\n */\n union: <T extends Validator<any, \"required\", any>[]>(...members: T) => {\n return new VUnion<T[number][\"type\"], T>({\n isOptional: \"required\",\n members,\n });\n },\n\n /**\n * Does not validate the value.\n */\n any: () => {\n return new VAny({ isOptional: \"required\" });\n },\n\n /**\n * Allows not specifying a value for a property in an Object.\n * @param value The property value validator to make optional.\n *\n * ```typescript\n * const objectWithOptionalFields = v.object({\n * requiredField: v.string(),\n * optionalField: v.optional(v.string()),\n * });\n * ```\n */\n optional: <T extends GenericValidator>(value: T) => {\n return value.asOptional() as VOptional<T>;\n },\n\n /**\n * Allows specifying a value or null.\n */\n nullable: <T extends Validator<any, \"required\", any>>(value: T) => {\n return v.union(value, v.null());\n },\n};\n\n/**\n * Validators for each property of an object.\n *\n * This is represented as an object mapping the property name to its\n * {@link Validator}.\n *\n * @public\n */\nexport type PropertyValidators = Record<\n string,\n Validator<any, OptionalProperty, any>\n>;\n\n/**\n * Compute the type of an object from {@link PropertyValidators}.\n *\n * @public\n */\nexport type ObjectType<Fields extends PropertyValidators> = Expand<\n // Map each key to the corresponding property validator's type making\n // the optional ones optional.\n {\n // This `Exclude<..., undefined>` does nothing unless\n // the tsconfig.json option `\"exactOptionalPropertyTypes\": true,`\n // is used. When it is it results in a more accurate type.\n // When it is not the `Exclude` removes `undefined` but it is\n // added again by the optional property.\n [Property in OptionalKeys<Fields>]?: Exclude<\n Infer<Fields[Property]>,\n undefined\n >;\n } & {\n [Property in RequiredKeys<Fields>]: Infer<Fields[Property]>;\n }\n>;\n\ntype OptionalKeys<PropertyValidators extends Record<string, GenericValidator>> =\n {\n [Property in keyof PropertyValidators]: PropertyValidators[Property][\"isOptional\"] extends \"optional\"\n ? Property\n : never;\n }[keyof PropertyValidators];\n\ntype RequiredKeys<PropertyValidators extends Record<string, GenericValidator>> =\n Exclude<keyof PropertyValidators, OptionalKeys<PropertyValidators>>;\n\n/**\n * Extract a TypeScript type from a validator.\n *\n * Example usage:\n * ```ts\n * const objectSchema = v.object({\n * property: v.string(),\n * });\n * type MyObject = Infer<typeof objectSchema>; // { property: string }\n * ```\n * @typeParam V - The type of a {@link Validator} constructed with {@link v}.\n *\n * @public\n */\nexport type Infer<T extends Validator<any, OptionalProperty, any>> = T[\"type\"];\n","/**\n * Taken from https://github.com/rocicorp/compare-utf8/blob/main/LICENSE\n * (Apache Version 2.0, January 2004)\n */\n\n/**\n * This is copied here instead of added as a dependency to avoid bundling issues.\n */\n\n/**\n * Compares two JavaScript strings as if they were UTF-8 encoded byte arrays.\n * @param {string} a\n * @param {string} b\n * @returns {number}\n */\nexport function compareUTF8(a: string, b: string): number {\n const aLength = a.length;\n const bLength = b.length;\n const length = Math.min(aLength, bLength);\n for (let i = 0; i < length; ) {\n const aCodePoint = a.codePointAt(i)!;\n const bCodePoint = b.codePointAt(i)!;\n if (aCodePoint !== bCodePoint) {\n // Code points below 0x80 are represented the same way in UTF-8 as in\n // UTF-16.\n if (aCodePoint < 0x80 && bCodePoint < 0x80) {\n return aCodePoint - bCodePoint;\n }\n\n // get the UTF-8 bytes for the code points\n const aLength = utf8Bytes(aCodePoint, aBytes);\n const bLength = utf8Bytes(bCodePoint, bBytes);\n return compareArrays(aBytes, aLength, bBytes, bLength);\n }\n\n i += utf16LengthForCodePoint(aCodePoint);\n }\n\n return aLength - bLength;\n}\n\n/**\n * @param {number[]} a\n * @param {number} aLength\n * @param {number[]} b\n * @param {number} bLength\n * @returns {number}\n */\nfunction compareArrays(\n a: number[],\n aLength: number,\n b: number[],\n bLength: number,\n) {\n const length = Math.min(aLength, bLength);\n for (let i = 0; i < length; i++) {\n const aValue = a[i];\n const bValue = b[i];\n if (aValue !== bValue) {\n return aValue - bValue;\n }\n }\n return aLength - bLength;\n}\n\n/**\n * @param {number} aCodePoint\n * @returns {number}\n */\nexport function utf16LengthForCodePoint(aCodePoint: number) {\n return aCodePoint > 0xffff ? 2 : 1;\n}\n\n// 2 preallocated arrays for utf8Bytes.\nconst arr = () => Array.from({ length: 4 }, () => 0);\nconst aBytes = arr();\nconst bBytes = arr();\n\n/**\n * @param {number} codePoint\n * @param {number[]} bytes\n * @returns {number}\n */\nfunction utf8Bytes(codePoint: number, bytes: number[]) {\n if (codePoint < 0x80) {\n bytes[0] = codePoint;\n return 1;\n }\n\n let count;\n let offset;\n\n if (codePoint <= 0x07ff) {\n count = 1;\n offset = 0xc0;\n } else if (codePoint <= 0xffff) {\n count = 2;\n offset = 0xe0;\n } else if (codePoint <= 0x10ffff) {\n count = 3;\n offset = 0xf0;\n } else {\n throw new Error(\"Invalid code point\");\n }\n\n bytes[0] = (codePoint >> (6 * count)) + offset;\n let i = 1;\n for (; count > 0; count--) {\n const temp = codePoint >> (6 * (count - 1));\n bytes[i++] = 0x80 | (temp & 0x3f);\n }\n return i;\n}\n\n/**\n * @param {string} a\n * @param {string} b\n * @returns {boolean}\n */\nexport function greaterThan(a: string, b: string) {\n return compareUTF8(a, b) > 0;\n}\n\n/**\n * @param {string} a\n * @param {string} b\n * @returns {boolean}\n */\nexport function greaterThanEq(a: string, b: string) {\n return compareUTF8(a, b) >= 0;\n}\n\n/**\n * @param {string} a\n * @param {string} b\n * @returns {boolean}\n */\nexport function lessThan(a: string, b: string) {\n return compareUTF8(a, b) < 0;\n}\n\n/**\n * @param {string} a\n * @param {string} b\n * @returns {boolean}\n */\nexport function lessThanEq(a: string, b: string) {\n return compareUTF8(a, b) <= 0;\n}\n","import { asObjectValidator, v } from \"convex/values\";\nimport { assert } from \"./index.js\";\n/**\n * Helper for defining a union of literals more concisely.\n *\n * e.g. `literals(\"a\", 1, false)` is equivalent to\n * `v.union(v.literal(\"a\"), v.literal(1), v.literal(false))`\n * To use with an array:\n * ```ts\n * const myLiterals = [\"a\", 1, false] as const;\n * const literalValidator = literals(...myLiterals)\n * ```\n * A similar result can be achieved with `v.union(...myLiterals.map(v.literal))`\n * however the type of each union member will be the union of literal types,\n * rather than each member being a specific literal type.\n *\n * @param args Values you want to use in a union of literals.\n * @returns A validator for the union of the literals.\n */\nexport const literals = (...args) => {\n return v.union(...args.map(v.literal));\n};\n/**\n * nullable define a validator that can be the value or null more consisely.\n *\n * @param x The validator to make nullable. As in, it can be the value or null.\n * @returns A new validator that can be the value or null.\n */\nexport const nullable = (x) => v.union(v.null(), x);\nexport function partial(fieldsOrObjOrUnion) {\n if (fieldsOrObjOrUnion.isConvexValidator) {\n if (fieldsOrObjOrUnion.kind === \"object\") {\n return partialVObject(fieldsOrObjOrUnion);\n }\n if (fieldsOrObjOrUnion.kind === \"union\") {\n return partialUnion(fieldsOrObjOrUnion);\n }\n throw new Error(\"partial only works with union or object Validators, or a Record<string, Validator> currently\");\n }\n return partialFields(fieldsOrObjOrUnion);\n}\n/**\n * partialFields helps you define an object of optional validators more concisely.\n *\n * e.g. `partialFields({a: v.string(), b: v.number()})` is equivalent to\n * `{a: v.optional(v.string()), b: v.optional(v.number())}`\n *\n * @param obj The object of validators to make optional. e.g. {a: v.string()}\n * @returns A new object of validators that can be the value or undefined.\n */\nfunction partialFields(obj) {\n return Object.fromEntries(Object.entries(obj).map(([k, vv]) => [\n k,\n vv.isOptional === \"optional\" ? vv : v.optional(vv),\n ]));\n}\n/**\n * partialObject helps you define an object of optional validators more concisely.\n *\n * e.g. `partialObject({a: v.string(), b: v.number()})` is equivalent to\n * `{a: v.optional(v.string()), b: v.optional(v.number())}`\n *\n * @param obj The object of validators to make optional. e.g. {a: v.string()}\n * @returns A new object of validators that can be the value or undefined.\n */\nfunction partialVObject(obj) {\n const o = v.object(partialFields(obj.fields));\n if (obj.isOptional === \"optional\") {\n return v.optional(o);\n }\n return o;\n}\nfunction partialUnion(union) {\n const u = v.union(...union.members.map((m) => {\n assert(m.isOptional === \"required\", \"Union members cannot be optional\");\n if (m.kind === \"object\") {\n return partialVObject(m);\n }\n if (m.kind === \"union\") {\n return partialUnion(m);\n }\n throw new Error(`Invalid union member type: ${m.kind}`);\n }));\n if (union.isOptional === \"optional\") {\n return v.optional(u);\n }\n return u;\n}\n// Shorthand for defining validators that look like types.\n/** @deprecated Use `v.string()` instead. Any string value. */\nexport const string = v.string();\n/** @deprecated Use `v.float64()` instead. JavaScript number, represented as a float64 in the database. */\nexport const number = v.float64();\n/** @deprecated Use `v.float64()` instead. JavaScript number, represented as a float64 in the database. */\nexport const float64 = v.float64();\n/** @deprecated Use `v.boolean()` instead. boolean value. For typing it only as true, use `l(true)` */\nexport const boolean = v.boolean();\n/** @deprecated Use `v.int64()` instead. bigint, though stored as an int64 in the database. */\nexport const biging = v.int64();\n/** @deprecated Use `v.int64()` instead. bigint, though stored as an int64 in the database. */\nexport const int64 = v.int64();\n/** @deprecated Use `v.any()` instead. Any Convex value */\nexport const any = v.any();\n/** @deprecated Use `v.null()` instead. Null value. Underscore is so it doesn't shadow the null builtin */\nexport const null_ = v.null();\n/** @deprecated Use `v.*()` instead. */\nexport const { id, object, array, bytes, literal, optional, union } = v;\n/** @deprecated Use `v.bytes()` instead. ArrayBuffer validator. */\nexport const arrayBuffer = v.bytes();\n/**\n * Utility to get the validators for fields associated with a table.\n * e.g. for systemFields(\"users\") it would return:\n * { _id: v.id(\"users\"), _creationTime: v.number() }\n *\n * @param tableName The table name in the schema.\n * @returns Validators for the system fields: _id and _creationTime\n */\nexport const systemFields = (tableName) => ({\n _id: v.id(tableName),\n _creationTime: v.number(),\n});\n/**\n * Utility to add system fields to an object with fields mapping to validators.\n * e.g. withSystemFields(\"users\", { name: v.string() }) would return:\n * { name: v.string(), _id: v.id(\"users\"), _creationTime: v.number() }\n *\n * @param tableName Table name in the schema.\n * @param fields The fields of the table mapped to their validators.\n * @returns The fields plus system fields _id and _creationTime.\n */\nexport const withSystemFields = (tableName, fields) => {\n const system = systemFields(tableName);\n return {\n ...fields,\n ...system,\n };\n};\nexport function addFieldsToValidator(validatorOrFields, fields) {\n const validator = asObjectValidator(validatorOrFields);\n if (Object.keys(fields).length === 0) {\n return validator;\n }\n switch (validator.kind) {\n case \"object\":\n return v.object(intersectValidators(validator.fields, fields));\n case \"union\":\n return v.union(...validator.members.map((m) => addFieldsToValidator(m, fields)));\n default:\n throw new Error(\"Cannot add arguments to a validator that is not an object or union.\");\n }\n}\nfunction intersectValidators(fields, fields2) {\n const specificFields = { ...fields };\n for (const [k, v] of Object.entries(fields2)) {\n const existing = specificFields[k];\n if (existing) {\n if (existing.kind !== v.kind) {\n // TODO: handle unions & literals & other sub-types (incl. optionals)\n throw new Error(`Cannot intersect validators with different kinds: ${existing.kind} and ${v.kind}`);\n }\n if (existing.isOptional !== v.isOptional) {\n if (existing.isOptional === \"optional\") {\n // prefer the required validator\n specificFields[k] = v;\n }\n }\n }\n else {\n specificFields[k] = v;\n }\n }\n return specificFields;\n}\nexport const doc = (schema, tableName) => {\n function addSystemFields(validator) {\n if (validator.kind === \"object\") {\n return v.object({\n ...validator.fields,\n ...systemFields(tableName),\n });\n }\n if (validator.kind !== \"union\") {\n throw new Error(\"Only object and union validators are supported for documents\");\n }\n return v.union(...validator.members.map(addSystemFields));\n }\n return addSystemFields(schema.tables[tableName].validator);\n};\n/**\n * Creates a validator with a type-safe `.id(table)` and a new `.doc(table)`.\n * Can be used instead of `v` for function arugments & return validators.\n * However, it cannot be used as part of defining a schema, since it would be\n * circular.\n * ```ts\n * import schema from \"./schema\";\n * export const vv = typedV(schema);\n *\n * export const myQuery = query({\n * args: { docId: vv.id(\"mytable\") },\n * returns: vv.doc(\"mytable\"),\n * handler: (ctx, args) => ctx.db.get(args.docId),\n * })\n *\n * @param schema Typically from `import schema from \"./schema\"`.\n * @returns A validator like `v` with type-safe `v.id` and a new `v.doc`\n */\nexport function typedV(schema) {\n return {\n ...v,\n /**\n * Similar to v.id but is type-safe on the table name.\n * @param tableName A table named in your schema.\n * @returns A validator for an ID to the named table.\n */\n id: (tableName) => v.id(tableName),\n /**\n * Generates a validator for a document, including system fields.\n * To be used in validators when passing a full document in or out of a\n * function.\n * @param tableName A table named in your schema.\n * @returns A validator that matches the schema validator, adding _id and\n * _creationTime. If the validator was a union, it will update all documents\n * recursively, but will currently lose the VUnion-specific type.\n */\n doc: (tableName) => doc(schema, tableName),\n };\n}\n/**\n * A string validator that is a branded string type.\n *\n * Read more at https://stack.convex.dev/using-branded-types-in-validators\n *\n * @param _brand - A unique string literal to brand the string with\n */\nexport const brandedString = (_brand) => v.string();\n/** Mark fields as deprecated with this permissive validator typed as null */\nexport const deprecated = v.optional(v.any());\n/** A maximally permissive validator that type checks as a given validator.\n *\n * If you want to have types that match some validator but you have invalid data\n * and you want to temporarily not validate schema for this field,\n * you can use this function to cast the permissive validator.\n *\n * Example in a schema:\n * ```ts\n * export default defineSchema({\n * myTable: defineTable({\n * myString: pretend(v.array(v.string())),\n * }),\n * });\n * //...in some mutation\n * ctx.db.insert(\"myTable\", { myString: 123 as any }); // no runtime error\n * ```\n * Example in function argument validation:\n * ```ts\n * const myQuery = defineQuery({\n * args: { myNumber: pretend(v.number()) },\n * handler: async (ctx, args) => {\n * // args.myNumber is typed as number, but it's not validated.\n * const num = typeof args.myNumber === \"number\" ?\n * args.myNumber : Number(args.myNumber);\n * },\n * });\n */\nexport const pretend = (_typeToImmitate) => v.optional(v.any());\n/** A validator that validates as optional but type checks as required.\n *\n * If you want to assume a field is set for type checking, but your data may not\n * actually have it set for all documents (e.g. when adding a new field),\n * you can use this function to allow the field to be unset at runtime.\n * This is unsafe, but can be convenient in these situations:\n *\n * 1. You are developing locally and want to add a required field and write\n * code assuming it is set. Once you push the code & schema, you can update\n * the data to match before running your code.\n * 2. You are going to run a migration right after pushing code, and are ok with\n * and you don't want to edit your code to handle the field being unset,\n * your app being in an inconsistent state until the migration completes.\n *\n * This differs from {@link pretend} in that it type checks the inner validator,\n * if the value is provided.\n *\n * Example in a schema:\n * ```ts\n * export default defineSchema({\n * myTable: defineTable({\n * myString: pretendRequired(v.array(v.string())),\n * }),\n * });\n * //...in some mutation\n * ctx.db.insert(\"myTable\", { myString: undefined }); // no runtime error\n * ```\n * Example in function argument validation:\n * ```ts\n * const myQuery = defineQuery({\n * args: { myNumber: pretendRequired(v.number()) },\n * handler: async (ctx, args) => {\n * // args.myNumber is typed as number, but it might be undefined\n * const num = args.myNumber || 0;\n * },\n * });\n */\nexport const pretendRequired = (optionalType) => v.optional(optionalType);\nexport class ValidationError extends Error {\n expected;\n got;\n path;\n constructor(expected, got, path) {\n const message = `Validator error${path ? ` for ${path}` : \"\"}: Expected \\`${expected}\\`, got \\`${got}\\``;\n super(message);\n this.expected = expected;\n this.got = got;\n this.path = path;\n this.name = \"ValidationError\";\n }\n}\n/**\n * Validate a value against a validator.\n *\n * WARNING: This does not validate that v.id is an ID for the given table.\n * It only validates that the ID is a string. Function `args`, `returns` and\n * schema definitions will validate that the ID is an ID for the given table.\n *\n * @param validator The validator to validate against.\n * @param value The value to validate.\n * @returns Whether the value is valid against the validator.\n */\nexport function validate(validator, value, opts) {\n let valid = true;\n let expected = validator.kind;\n let got;\n if (value === undefined) {\n if (validator.isOptional !== \"optional\") {\n valid = false;\n }\n }\n else {\n switch (validator.kind) {\n case \"null\": {\n if (value !== null) {\n valid = false;\n }\n break;\n }\n case \"float64\": {\n if (typeof value !== \"number\") {\n expected = \"number\";\n valid = false;\n }\n break;\n }\n case \"int64\": {\n if (typeof value !== \"bigint\") {\n expected = \"bigint\";\n valid = false;\n }\n break;\n }\n case \"boolean\": {\n if (typeof value !== \"boolean\") {\n valid = false;\n }\n break;\n }\n case \"string\": {\n if (typeof value !== \"string\") {\n valid = false;\n }\n break;\n }\n case \"bytes\": {\n if (!(value instanceof ArrayBuffer)) {\n valid = false;\n }\n break;\n }\n case \"any\": {\n break;\n }\n case \"literal\": {\n if (value !== validator.value) {\n valid = false;\n expected = validator.value;\n if ([\"string\", \"number\", \"boolean\", \"bigint\"].includes(typeof value)) {\n got = `\"${value}\"`;\n }\n }\n break;\n }\n case \"id\": {\n if (typeof value !== \"string\") {\n valid = false;\n }\n else if (opts?.db) {\n expected = `Id<${validator.tableName}>`;\n const id = opts.db.normalizeId(validator.tableName, value);\n if (!id) {\n valid = false;\n }\n }\n break;\n }\n case \"array\": {\n if (!Array.isArray(value)) {\n valid = false;\n break;\n }\n for (const [index, v] of value.entries()) {\n const path = `${opts?._pathPrefix ?? \"\"}[${index}]`;\n valid = validate(validator.element, v, {\n ...opts,\n _pathPrefix: path,\n });\n if (!valid) {\n expected = validator.element.kind;\n break;\n }\n }\n break;\n }\n case \"object\": {\n if (typeof value !== \"object\" || value === null) {\n valid = false;\n break;\n }\n const prototype = Object.getPrototypeOf(value);\n const isSimple = prototype === null ||\n prototype === Object.prototype ||\n // Objects generated from other contexts (e.g. across Node.js `vm` modules) will not satisfy the previous\n // conditions but are still simple objects.\n prototype?.constructor?.name === \"Object\";\n if (!isSimple) {\n expected =\n (prototype?.constructor?.name ?? typeof prototype) || \"object\";\n valid = false;\n break;\n }\n for (const [k, fieldValidator] of Object.entries(validator.fields)) {\n valid = validate(fieldValidator, value[k], {\n ...opts,\n _pathPrefix: appendPath(opts, k),\n });\n if (!valid) {\n break;\n }\n }\n if (!opts?.allowUnknownFields) {\n for (const k of Object.keys(value)) {\n if (validator.fields[k] === undefined &&\n value[k] !== undefined) {\n if (opts?.throw) {\n throw new ValidationError(\"nothing\", typeof value[k], appendPath(opts, k));\n }\n valid = false;\n break;\n }\n }\n }\n break;\n }\n case \"union\": {\n valid = false;\n let error;\n for (const member of validator.members) {\n try {\n if (validate(member, value, opts)) {\n valid = true;\n break;\n }\n }\n catch (e) {\n error = e;\n }\n }\n if (!valid && error) {\n throw error;\n }\n break;\n }\n case \"record\": {\n if (typeof value !== \"object\" || value === null) {\n valid = false;\n break;\n }\n for (const [k, fieldValue] of Object.entries(value)) {\n // Skip validation for undefined values as they will be stripped out\n if (fieldValue === undefined) {\n continue;\n }\n valid = validate(validator.key, k, {\n ...opts,\n _pathPrefix: appendPath(opts, k),\n });\n if (!valid) {\n expected = validator.key.kind;\n break;\n }\n valid = validate(validator.value, fieldValue, {\n ...opts,\n _pathPrefix: appendPath(opts, k),\n });\n if (!valid) {\n expected = validator.value.kind;\n break;\n }\n }\n break;\n }\n }\n }\n if (!valid && opts?.throw) {\n throw new ValidationError(expected, got ?? (value === null ? \"null\" : typeof value), opts?._pathPrefix);\n }\n return valid;\n}\n/**\n * Parse a value, using a Convex validator. This differs from `validate` in that\n * it strips unknown fields instead of throwing an error on them.\n *\n * @param validator - The Convex validator to parse the value against.\n * @param value - The value to parse.\n * @returns The parsed value, without fields not specified in the validator.\n */\nexport function parse(validator, value) {\n validate(validator, value, { allowUnknownFields: true, throw: true });\n return stripUnknownFields(validator, value);\n}\nfunction stripUnknownFields(validator, value) {\n if (validator.isOptional === \"optional\" && value === undefined) {\n return value;\n }\n assert(value !== undefined);\n switch (validator.kind) {\n case \"object\": {\n const result = {};\n for (const [k, v] of Object.entries(value)) {\n if (validator.fields[k] !== undefined && v !== undefined) {\n result[k] = stripUnknownFields(validator.fields[k], v);\n }\n }\n return result;\n }\n case \"record\": {\n const result = {};\n for (const [k, v] of Object.entries(value)) {\n if (v !== undefined) {\n result[k] = stripUnknownFields(validator.value, v);\n }\n }\n return result;\n }\n case \"array\": {\n return value.map((e) => stripUnknownFields(validator.element, e));\n }\n case \"union\": {\n // First try a strict match\n for (const member of validator.members) {\n if (validate(member, value, { allowUnknownFields: false })) {\n return stripUnknownFields(member, value);\n }\n }\n // Then try a permissive match\n for (const member of validator.members) {\n if (validate(member, value, { allowUnknownFields: true })) {\n return stripUnknownFields(member, value);\n }\n }\n throw new Error(\"No matching member in union\");\n }\n default: {\n return value;\n }\n }\n}\nfunction appendPath(opts, path) {\n return opts?._pathPrefix ? `${opts._pathPrefix}.${path}` : path;\n}\n/**\n * Converts an optional validator to a required validator.\n *\n * This is the inverse of `v.optional()`. It takes a validator that may be optional\n * and returns the equivalent required validator.\n *\n * ```ts\n * const optionalString = v.optional(v.string());\n * const requiredString = vRequired(optionalString); // v.string()\n *\n * // Already required validators are returned as-is\n * const alreadyRequired = v.string();\n * const stillRequired = vRequired(alreadyRequired); // v.string()\n * ```\n *\n * @param validator The validator to make required.\n * @returns A required version of the validator.\n */\nexport function vRequired(validator) {\n const { kind, isOptional } = validator;\n if (isOptional === \"required\") {\n // TypeScript can't prove T is already VRequired<T>, so we go via unknown.\n return validator;\n }\n switch (kind) {\n case \"id\":\n return v.id(validator.tableName);\n case \"string\":\n return v.string();\n case \"float64\":\n return v.float64();\n case \"int64\":\n return v.int64();\n case \"boolean\":\n return v.boolean();\n case \"null\":\n return v.null();\n case \"any\":\n return v.any();\n case \"literal\":\n return v.literal(validator.value);\n case \"bytes\":\n return v.bytes();\n case \"object\":\n return v.object(validator.fields);\n case \"array\":\n return v.array(validator.element);\n case \"record\":\n return v.record(validator.key, validator.value);\n case \"union\":\n return v.union(...validator.members);\n default:\n kind;\n throw new Error(\"Unknown Convex validator type: \" + kind);\n }\n}\n","import { ConvexError, v } from \"convex/values\";\nimport * as zCore from \"zod/v4/core\";\nimport * as z from \"zod/v4\";\nimport { pick } from \"../index.js\";\nimport { NoOp } from \"./customFunctions.js\";\nimport { addFieldsToValidator, vRequired, } from \"../validators.js\";\n// #region Convex function definition with Zod\n/**\n * zCustomQuery is like customQuery, but allows validation via zod.\n * You can define custom behavior on top of `query` or `internalQuery`\n * by passing a function that modifies the ctx and args. Or NoOp to do nothing.\n *\n * Example usage:\n * ```ts\n * const myQueryBuilder = zCustomQuery(query, {\n * args: { sessionId: v.id(\"sessions\") },\n * input: async (ctx, args) => {\n * const user = await getUserOrNull(ctx);\n * const session = await db.get(sessionId);\n * const db = wrapDatabaseReader({ user }, ctx.db, rlsRules);\n * return { ctx: { db, user, session }, args: {} };\n * },\n * });\n *\n * // Using the custom builder\n * export const getSomeData = myQueryBuilder({\n * args: { someArg: z.string() },\n * handler: async (ctx, args) => {\n * const { db, user, session, scheduler } = ctx;\n * const { someArg } = args;\n * // ...\n * }\n * });\n * ```\n *\n * Simple usage only modifying ctx:\n * ```ts\n * const myInternalQuery = zCustomQuery(\n * internalQuery,\n * customCtx(async (ctx) => {\n * return {\n * // Throws an exception if the user isn't logged in\n * user: await getUserByTokenIdentifier(ctx),\n * };\n * })\n * );\n *\n * // Using it\n * export const getUser = myInternalQuery({\n * args: { email: z.string().email() },\n * handler: async (ctx, args) => {\n * console.log(args.email);\n * return ctx.user;\n * },\n * });\n *\n * @param query The query to be modified. Usually `query` or `internalQuery`\n * from `_generated/server`.\n * @param customization The customization to be applied to the query, changing ctx and args.\n * @returns A new query builder using zod validation to define queries.\n */\nexport function zCustomQuery(query, customization) {\n return customFnBuilder(query, customization);\n}\n/**\n * zCustomMutation is like customMutation, but allows validation via zod.\n * You can define custom behavior on top of `mutation` or `internalMutation`\n * by passing a function that modifies the ctx and args. Or NoOp to do nothing.\n *\n * Example usage:\n * ```ts\n * const myMutationBuilder = zCustomMutation(mutation, {\n * args: { sessionId: v.id(\"sessions\") },\n * input: async (ctx, args) => {\n * const user = await getUserOrNull(ctx);\n * const session = await db.get(sessionId);\n * const db = wrapDatabaseReader({ user }, ctx.db, rlsRules);\n * return { ctx: { db, user, session }, args: {} };\n * },\n * });\n *\n * // Using the custom builder\n * export const getSomeData = myMutationBuilder({\n * args: { someArg: z.string() },\n * handler: async (ctx, args) => {\n * const { db, user, session, scheduler } = ctx;\n * const { someArg } = args;\n * // ...\n * }\n * });\n * ```\n *\n * Simple usage only modifying ctx:\n * ```ts\n * const myInternalMutation = zCustomMutation(\n * internalMutation,\n * customCtx(async (ctx) => {\n * return {\n * // Throws an exception if the user isn't logged in\n * user: await getUserByTokenIdentifier(ctx),\n * };\n * })\n * );\n *\n * // Using it\n * export const getUser = myInternalMutation({\n * args: { email: z.string().email() },\n * handler: async (ctx, args) => {\n * console.log(args.email);\n * return ctx.user;\n * },\n * });\n *\n * @param mutation The mutation to be modified. Usually `mutation` or `internalMutation`\n * from `_generated/server`.\n * @param customization The customization to be applied to the mutation, changing ctx and args.\n * @returns A new mutation builder using zod validation to define queries.\n */\nexport function zCustomMutation(mutation, customization) {\n return customFnBuilder(mutation, customization);\n}\n/**\n * zCustomAction is like customAction, but allows validation via zod.\n * You can define custom behavior on top of `action` or `internalAction`\n * by passing a function that modifies the ctx and args. Or NoOp to do nothing.\n *\n * Example usage:\n * ```ts\n * const myActionBuilder = zCustomAction(action, {\n * args: { sessionId: v.id(\"sessions\") },\n * input: async (ctx, args) => {\n * const user = await getUserOrNull(ctx);\n * const session = await db.get(sessionId);\n * const db = wrapDatabaseReader({ user }, ctx.db, rlsRules);\n * return { ctx: { db, user, session }, args: {} };\n * },\n * });\n *\n * // Using the custom builder\n * export const getSomeData = myActionBuilder({\n * args: { someArg: z.string() },\n * handler: async (ctx, args) => {\n * const { db, user, session, scheduler } = ctx;\n * const { someArg } = args;\n * // ...\n * }\n * });\n * ```\n *\n * Simple usage only modifying ctx:\n * ```ts\n * const myInternalAction = zCustomAction(\n * internalAction,\n * customCtx(async (ctx) => {\n * return {\n * // Throws an exception if the user isn't logged in\n * user: await getUserByTokenIdentifier(ctx),\n * };\n * })\n * );\n *\n * // Using it\n * export const getUser = myInternalAction({\n * args: { email: z.string().email() },\n * handler: async (ctx, args) => {\n * console.log(args.email);\n * return ctx.user;\n * },\n * });\n *\n * @param action The action to be modified. Usually `action` or `internalAction`\n * from `_generated/server`.\n * @param customization The customization to be applied to the action, changing ctx and args.\n * @returns A new action builder using zod validation to define queries.\n */\nexport function zCustomAction(action, customization) {\n return customFnBuilder(action, customization);\n}\n// #endregion\n// #region Convex IDs\n/**\n * Creates a validator for a Convex `Id`.\n *\n * - When **used within Zod**, it will only check that the ID is a string.\n * - When **converted to a Convex validator** (e.g. through {@link zodToConvex}),\n * it will check that it's for the right table.\n *\n * @param tableName - The table that the `Id` references. i.e. `Id<tableName>`\n * @returns A Zod schema representing a Convex `Id`\n */\nexport const zid = (tableName) => {\n const result = z.custom((val) => typeof val === \"string\");\n _zidRegistry.add(result, { tableName });\n return result;\n};\n// #endregion\n// #region Zod → Convex\n/**\n * Turns a Zod or Zod Mini validator into a Convex validator.\n *\n * The Convex validator will be as close to possible to the Zod validator,\n * but might be broader than the Zod validator:\n *\n * ```ts\n * zodToConvex(z.string().email()) // → v.string()\n * ```\n *\n * This function is useful when running the Zod validator _after_ running the Convex validator\n * (i.e. the Convex validator validates the input of the Zod validator). Hence, the Convex types\n * will match the _input type_ of Zod transformations:\n * ```ts\n * zodToConvex(z.object({\n * name: z.string().default(\"Nicolas\"),\n * })) // → v.object({ name: v.optional(v.string()) })\n *\n * zodToConvex(z.object({\n * name: z.string().transform(s => s.length)\n * })) // → v.object({ name: v.string() })\n * ````\n *\n * This function is useful for:\n * * **Validating function arguments with Zod**: through {@link zCustomQuery},\n * {@link zCustomMutation} and {@link zCustomAction}, you can define the argument validation logic\n * using Zod validators instead of Convex validators. `zodToConvex` will generate a Convex validator\n * from your Zod validator. This will allow you to:\n * - validate at run time that Convex IDs are from the right table (using {@link zid})\n * - allow some features of Convex to understand the expected shape of the arguments\n * (e.g. argument validation/prefilling in the function runner on the Convex dashboard)\n * - still run the full Zod validation when the function runs\n * (which is useful for more advanced Zod validators like `z.string().email()`)\n * * **Validating data after reading it from the database**: if you want to write your DB schema\n * with Zod, you can run Zod whenever you read from the database to check that the data\n * still matches the schema. Note that this approach won’t ensure that the data stored in the DB\n * matches the Zod schema; see\n * https://stack.convex.dev/typescript-zod-function-validation#can-i-use-zod-to-define-my-database-types-too\n * for more details.\n *\n * Note that some values might be valid in Zod but not in Convex,\n * in the same way that valid JavaScript values might not be valid\n * Convex values for the corresponding Convex type.\n * (see the limits of Convex data types on https://docs.convex.dev/database/types).\n *\n * ```\n * ┌─────────────────────────────────────┬─────────────────────────────────────┐\n * │ **zodToConvex** │ zodOutputToConvex │\n * ├─────────────────────────────────────┼─────────────────────────────────────┤\n * │ For when the Zod validator runs │ For when the Zod validator runs │\n * │ _after_ the Convex validator │ _before_ the Convex validator │\n * ├─────────────────────────────────────┼─────────────────────────────────────┤\n * │ Convex types use the _input types_ │ Convex types use the _return types_ │\n * │ of Zod transformations │ of Zod transformations │\n * ├─────────────────────────────────────┼─────────────────────────────────────┤\n * │ The Convex validator can be less │ The Convex validator can be less │\n * │ strict (i.e. some inputs might be │ strict (i.e. the type in Convex can │\n * │ accepted by Convex then rejected │ be less precise than the type in │\n * │ by Zod) │ the Zod output) │\n * ├─────────────────────────────────────┼─────────────────────────────────────┤\n * │ When using Zod schemas │ When using Zod schemas │\n * │ for function definitions: │ for function definitions: │\n * │ used for _arguments_ │ used for _return values_ │\n * ├─────────────────────────────────────┼─────────────────────────────────────┤\n * │ When validating contents of the │ When validating contents of the │\n * │ database with a Zod schema: │ database with a Zod schema: │\n * │ used to validate data │ used to validate data │\n * │ _after reading_ │ _before writing_ │\n * └─────────────────────────────────────┴─────────────────────────────────────┘\n * ```\n *\n * @param zod Zod validator can be a Zod object, or a Zod type like `z.string()`\n * @returns Convex Validator (e.g. `v.string()` from \"convex/values\")\n * @throws If there is no equivalent Convex validator for the value (e.g. `z.date()`)\n */\nexport function zodToConvex(validator) {\n const visited = new WeakSet();\n function zodToConvexInner(validator) {\n // Circular validator definitions are not supported by Convex validators,\n // so we use v.any() when there is a cycle.\n if (visited.has(validator)) {\n return v.any();\n }\n visited.add(validator);\n const result = validator instanceof zCore.$ZodDefault\n ? v.optional(zodToConvexInner(validator._zod.def.innerType))\n : validator instanceof zCore.$ZodPipe\n ? zodToConvexInner(validator._zod.def.in)\n : zodToConvexCommon(validator, zodToConvexInner);\n // After returning, we remove the validator from the visited set because\n // we only want to detect circular types, not cases where part of a type\n // is reused (e.g. `v.object({ field1: mySchema, field2: mySchema })`).\n visited.delete(validator);\n return result;\n }\n // `as any` because ConvexValidatorFromZod is defined from the behavior of zodToConvex.\n // We assume the type is correct to simplify the life of the compiler.\n return zodToConvexInner(validator);\n}\n/**\n * Converts a Zod or Zod Mini validator to a Convex validator that checks the value _after_\n * it has been validated (and possibly transformed) by the Zod validator.\n *\n * This is similar to {@link zodToConvex}, but is meant for cases where the Convex\n * validator runs _after_ the Zod validator. Thus, the Convex type refers to the\n * _output_ type of the Zod transformations:\n * ```ts\n * zodOutputToConvex(z.object({\n * name: z.string().default(\"Nicolas\"),\n * })) // → v.object({ name: v.string() })\n *\n * zodOutputToConvex(z.object({\n * name: z.string().transform(s => s.length)\n * })) // → v.object({ name: v.number() })\n * ````\n *\n * This function can be useful for:\n * - **Validating function return values with Zod**: through {@link zCustomQuery},\n * {@link zCustomMutation} and {@link zCustomAction}, you can define the `returns` property\n * of a function using Zod validators instead of Convex validators.\n * - **Validating data after reading it from the database**: if you want to write your DB schema\n * Zod validators, you can run Zod whenever you write to the database to ensure your data matches\n * the expected format. Note that this approach won’t ensure that the data stored in the DB\n * isn’t modified manually in a way that doesn’t match your Zod schema; see\n * https://stack.convex.dev/typescript-zod-function-validation#can-i-use-zod-to-define-my-database-types-too\n * for more details.\n *\n * ```\n * ┌─────────────────────────────────────┬─────────────────────────────────────┐\n * │ zodToConvex │ **zodOutputToConvex** │\n * ├─────────────────────────────────────┼─────────────────────────────────────┤\n * │ For when the Zod validator runs │ For when the Zod validator runs │\n * │ _after_ the Convex validator │ _before_ the Convex validator │\n * ├─────────────────────────────────────┼─────────────────────────────────────┤\n * │ Convex types use the _input types_ │ Convex types use the _return types_ │\n * │ of Zod transformations │ of Zod transformations │\n * ├─────────────────────────────────────┼─────────────────────────────────────┤\n * │ The Convex validator can be less │ The Convex validator can be less │\n * │ strict (i.e. some inputs might be │ strict (i.e. the type in Convex can │\n * │ accepted by Convex then rejected │ be less precise than the type in │\n * │ by Zod) │ the Zod output) │\n * ├─────────────────────────────────────┼─────────────────────────────────────┤\n * │ When using Zod schemas │ When using Zod schemas │\n * │ for function definitions: │ for function definitions: │\n * │ used for _arguments_ │ used for _return values_ │\n * ├─────────────────────────────────────┼─────────────────────────────────────┤\n * │ When validating contents of the │ When validating contents of the │\n * │ database with a Zod schema: │ database with a Zod schema: │\n * │ used to validate data │ used to validate data │\n * │ _after reading_ │ _before writing_ │\n * └─────────────────────────────────────┴─────────────────────────────────────┘\n * ```\n *\n * @param z The zod validator\n * @returns Convex Validator (e.g. `v.string()` from \"convex/values\")\n * @throws If there is no equivalent Convex validator for the value (e.g. `z.date()`)\n */\nexport function zodOutputToConvex(validator) {\n const visited = new WeakSet();\n function zodOutputToConvexInner(validator) {\n // Circular validator definitions are not supported by Convex validators,\n // so we use v.any() when there is a cycle.\n if (visited.has(validator)) {\n return v.any();\n }\n visited.add(validator);\n const result = validator instanceof zCore.$ZodDefault\n ? zodOutputToConvexInner(validator._zod.def.innerType)\n : validator instanceof zCore.$ZodPipe\n ? zodOutputToConvexInner(validator._zod.def.out)\n : validator instanceof zCore.$ZodTransform\n ? v.any()\n : zodToConvexCommon(validator, zodOutputToConvexInner);\n // After returning, we remove the validator from the visited set because\n // we only want to detect circular types, not cases where part of a type\n // is reused (e.g. `v.object({ field1: mySchema, field2: mySchema })`).\n visited.delete(validator);\n return result;\n }\n // `as any` because ConvexValidatorFromZodOutput is defined from the behavior of zodOutputToConvex.\n // We assume the type is correct to simplify the life of the compiler.\n return zodOutputToConvexInner(validator);\n}\n/**\n * Like {@link zodToConvex}, but it takes in a bare object, as expected by Convex\n * function arguments, or the argument to {@link defineTable}.\n *\n * ```ts\n * zodToConvexFields({\n * name: z.string().default(\"Nicolas\"),\n * }) // → { name: v.optional(v.string()) }\n * ```\n *\n * @param fields Object with string keys and Zod validators as values\n * @returns Object with the same keys, but with Convex validators as values\n */\nexport function zodToConvexFields(fields) {\n return Object.fromEntries(Object.entries(fields).map(([k, v]) => [k, zodToConvex(v)]));\n}\n/**\n * Like {@link zodOutputToConvex}, but it takes in a bare object, as expected by\n * Convex function arguments, or the argument to {@link defineTable}.\n *\n * ```ts\n * zodOutputToConvexFields({\n * name: z.string().default(\"Nicolas\"),\n * }) // → { name: v.string() }\n * ```\n *\n * This is different from {@link zodToConvexFields} because it generates the\n * Convex validator for the output of the Zod validator, not the input;\n * see the documentation of {@link zodToConvex} and {@link zodOutputToConvex}\n * for more details.\n *\n * @param zod Object with string keys and Zod validators as values\n * @returns Object with the same keys, but with Convex validators as values\n */\nexport function zodOutputToConvexFields(fields) {\n return Object.fromEntries(Object.entries(fields).map(([k, v]) => [k, zodOutputToConvex(v)]));\n}\n// #endregion\n// #region Convex → Zod\n/**\n * Turns a Convex validator into a Zod validator.\n *\n * This is useful when you want to use types you defined using Convex validators\n * with external libraries that expect to receive a Zod validator.\n *\n * ```ts\n * convexToZod(v.string()) // → z.string()\n * ```\n *\n * This function returns Zod validators, not Zod Mini validators.\n *\n * @param convexValidator Convex validator can be any validator from \"convex/values\" e.g. `v.string()`\n * @returns Zod validator (e.g. `z.string()`) with inferred type matching the Convex validator\n */\nexport function convexToZod(convexValidator) {\n const isOptional = convexValidator.isOptional === \"optional\";\n let zodValidator;\n const { kind } = convexValidator;\n switch (kind) {\n case \"id\":\n convexValidator;\n zodValidator = zid(convexValidator.tableName);\n break;\n case \"string\":\n zodValidator = z.string();\n break;\n case \"float64\":\n zodValidator = z.number();\n break;\n case \"int64\":\n zodValidator = z.bigint();\n break;\n case \"boolean\":\n zodValidator = z.boolean();\n break;\n case \"null\":\n zodValidator = z.null();\n break;\n case \"any\":\n zodValidator = z.any();\n break;\n case \"array\": {\n convexValidator;\n zodValidator = z.array(convexToZod(convexValidator.element));\n break;\n }\n case \"object\": {\n convexValidator;\n zodValidator = z.object(convexToZodFields(convexValidator.fields));\n break;\n }\n case \"union\": {\n convexValidator;\n if (convexValidator.members.length === 0) {\n zodValidator = z.never();\n break;\n }\n if (convexValidator.members.length === 1) {\n zodValidator = convexToZod(convexValidator.members[0]);\n break;\n }\n const memberValidators = convexValidator.members.map((member) => convexToZod(member));\n zodValidator = z.union([...memberValidators]);\n break;\n }\n case \"literal\": {\n const literalValidator = convexValidator;\n zodValidator = z.literal(literalValidator.value);\n break;\n }\n case \"record\": {\n convexValidator;\n zodValidator = z.record(convexToZod(convexValidator.key), convexToZod(convexValidator.value));\n break;\n }\n case \"bytes\":\n throw new Error(\"v.bytes() is not supported\");\n default:\n kind;\n throw new Error(`Unknown convex validator type: ${kind}`);\n }\n return isOptional\n ? z.optional(zodValidator)\n : zodValidator;\n}\n/**\n * Like {@link convexToZod}, but it takes in a bare object, as expected by Convex\n * function arguments, or the argument to {@link defineTable}.\n *\n * ```ts\n * convexToZodFields({\n * name: v.string(),\n * }) // → { name: z.string() }\n * ```\n *\n * @param convexValidators Object with string keys and Convex validators as values\n * @returns Object with the same keys, but with Zod validators as values\n */\nexport function convexToZodFields(convexValidators) {\n return Object.fromEntries(Object.entries(convexValidators).map(([k, v]) => [k, convexToZod(v)]));\n}\n// #endregion\n// #region Utils\n/**\n * Zod helper for adding Convex system fields to a record to return.\n *\n * ```ts\n * withSystemFields(\"users\", {\n * name: z.string(),\n * })\n * // → {\n * // name: z.string(),\n * // _id: zid(\"users\"),\n * // _creationTime: z.number(),\n * // }\n * ```\n *\n * @param tableName - The table where records are from, i.e. Doc<tableName>\n * @param zObject - Validators for the user-defined fields on the document.\n * @returns Zod shape for use with `z.object(shape)` that includes system fields.\n */\nexport function withSystemFields(tableName, zObject) {\n return { ...zObject, _id: zid(tableName), _creationTime: z.number() };\n}\nfunction customFnBuilder(builder, customization) {\n // Most of the code in here is identical to customFnBuilder in zod3.ts.\n // If making changes, please keep zod3.ts in sync.\n // Looking forward to when input / args / ... are optional\n const customInput = customization.input ?? NoOp.input;\n const inputArgs = customization.args ?? NoOp.args;\n return function customBuilder(fn) {\n const { args, handler = fn, skipConvexValidation = false, returns: maybeObject, ...extra } = fn;\n const returns = maybeObject && !(maybeObject instanceof zCore.$ZodType)\n ? z.object(maybeObject)\n : maybeObject;\n const returnValidator = returns && !skipConvexValidation\n ? { returns: zodOutputToConvex(returns) }\n : null;\n if (args) {\n let argsValidator = args;\n if (argsValidator instanceof zCore.$ZodType) {\n if (argsValidator instanceof zCore.$ZodObject) {\n argsValidator = argsValidator._zod.def.shape;\n }\n else {\n throw new Error(\"Unsupported zod type as args validator: \" +\n argsValidator.constructor.name);\n }\n }\n const convexValidator = zodToConvexFields(argsValidator);\n return builder({\n args: skipConvexValidation\n ? undefined\n : addFieldsToValidator(convexValidator, inputArgs),\n ...returnValidator,\n handler: async (ctx, allArgs) => {\n const added = await customInput(ctx, pick(allArgs, Object.keys(inputArgs)), extra);\n const rawArgs = pick(allArgs, Object.keys(argsValidator));\n const parsed = await z.object(argsValidator).safeParseAsync(rawArgs);\n if (!parsed.success) {\n throw new ConvexError({\n ZodError: JSON.parse(JSON.stringify(parsed.error.issues, null, 2)),\n });\n }\n const args = parsed.data;\n const finalCtx = { ...ctx, ...added.ctx };\n const finalArgs = { ...args, ...added.args };\n const ret = await handler(finalCtx, finalArgs);\n // We don't catch the error here. It's a developer error and we\n // don't want to risk exposing the unexpected value to the client.\n const result = returns\n ? await returns.parseAsync(ret === undefined ? null : ret)\n : ret;\n if (added.onSuccess) {\n await added.onSuccess({ ctx, args, result });\n }\n return result;\n },\n });\n }\n if (skipConvexValidation && Object.keys(inputArgs).length > 0) {\n throw new Error(\"If you're using a custom function with arguments for the input \" +\n \"customization, you cannot skip convex validation.\");\n }\n return builder({\n ...returnValidator,\n handler: async (ctx, args) => {\n const added = await customInput(ctx, args, extra);\n const finalCtx = { ...ctx, ...added.ctx };\n const finalArgs = { ...args, ...added.args };\n const ret = await handler(finalCtx, finalArgs);\n // We don't catch the error here. It's a developer error and we\n // don't want to risk exposing the unexpected value to the client.\n const result = returns\n ? await returns.parseAsync(ret === undefined ? null : ret)\n : ret;\n if (added.onSuccess) {\n await added.onSuccess({ ctx, args, result });\n }\n return result;\n },\n });\n };\n}\nfunction zodToConvexCommon(validator, toConvex) {\n // Check for zid (Convex ID) validators\n const idTableName = _zidRegistry.get(validator);\n if (idTableName !== undefined) {\n return v.id(idTableName.tableName);\n }\n if (validator instanceof zCore.$ZodString) {\n return v.string();\n }\n if (validator instanceof zCore.$ZodNumber ||\n validator instanceof zCore.$ZodNaN) {\n return v.number();\n }\n if (validator instanceof zCore.$ZodBigInt) {\n return v.int64();\n }\n if (validator instanceof zCore.$ZodBoolean) {\n return v.boolean();\n }\n if (validator instanceof zCore.$ZodNull) {\n return v.null();\n }\n if (validator instanceof zCore.$ZodAny ||\n validator instanceof zCore.$ZodUnknown) {\n return v.any();\n }\n if (validator instanceof zCore.$ZodArray) {\n const inner = toConvex(validator._zod.def.element);\n if (inner.isOptional === \"optional\") {\n throw new Error(\"Arrays of optional values are not supported\");\n }\n return v.array(inner);\n }\n if (validator instanceof zCore.$ZodObject) {\n return v.object(Object.fromEntries(Object.entries(validator._zod.def.shape).map(([k, v]) => [\n k,\n toConvex(v),\n ])));\n }\n if (validator instanceof zCore.$ZodUnion) {\n return v.union(...validator._zod.def.options.map(toConvex));\n }\n if (validator instanceof zCore.$ZodNever) {\n return v.union();\n }\n if (validator instanceof zCore.$ZodTuple) {\n const { items, rest } = validator._zod.def;\n return v.array(v.union(...[\n ...items,\n // + rest if set\n ...(rest !== null ? [rest] : []),\n ].map(toConvex)));\n }\n if (validator instanceof zCore.$ZodLiteral) {\n const { values } = validator._zod.def;\n if (values.length === 1) {\n return convexToZodLiteral(values[0]);\n }\n return v.union(...values.map(convexToZodLiteral));\n }\n if (validator instanceof zCore.$ZodEnum) {\n return v.union(...Object.entries(validator._zod.def.entries)\n .filter(([key, value]) => key === value || isNaN(Number(key)))\n .map(([_key, value]) => v.literal(value)));\n }\n if (validator instanceof zCore.$ZodOptional) {\n return v.optional(toConvex(validator._zod.def.innerType));\n }\n if (validator instanceof zCore.$ZodNonOptional) {\n return vRequired(toConvex(validator._zod.def.innerType));\n }\n if (validator instanceof zCore.$ZodNullable) {\n const inner = toConvex(validator._zod.def.innerType);\n // Invert z.optional().nullable() → v.optional(v.nullable())\n if (inner.isOptional === \"optional\") {\n return v.optional(v.union(vRequired(inner), v.null()));\n }\n return v.union(inner, v.null());\n }\n if (validator instanceof zCore.$ZodRecord) {\n const { keyType, valueType } = validator._zod.def;\n const isPartial = keyType._zod.values === undefined;\n // Convert value type, stripping optional\n const valueValidator = toConvex(valueType);\n // Convert key type\n const keyValidator = toConvex(keyType);\n // key = string literals?\n // If so, not supported by v.record() → use v.object() instead\n const stringLiterals = extractStringLiterals(keyValidator);\n if (stringLiterals !== null) {\n const fieldValue = isPartial || valueValidator.isOptional === \"optional\"\n ? v.optional(valueValidator)\n : vRequired(valueValidator);\n const fields = {};\n for (const literal of stringLiterals) {\n fields[literal] = fieldValue;\n }\n return v.object(fields);\n }\n return v.record(isValidRecordKey(keyValidator) ? keyValidator : v.string(), vRequired(valueValidator));\n }\n if (validator instanceof zCore.$ZodReadonly) {\n return toConvex(validator._zod.def.innerType);\n }\n if (validator instanceof zCore.$ZodLazy) {\n return toConvex(validator._zod.def.getter());\n }\n if (validator instanceof zCore.$ZodTemplateLiteral) {\n return v.string();\n }\n if (validator instanceof zCore.$ZodCustom ||\n validator instanceof zCore.$ZodIntersection) {\n return v.any();\n }\n if (validator instanceof zCore.$ZodCatch) {\n return toConvex(validator._zod.def.innerType);\n }\n if (validator instanceof zCore.$ZodDate ||\n validator instanceof zCore.$ZodSymbol ||\n validator instanceof zCore.$ZodMap ||\n validator instanceof zCore.$ZodSet ||\n validator instanceof zCore.$ZodPromise ||\n validator instanceof zCore.$ZodFile ||\n validator instanceof zCore.$ZodFunction ||\n validator instanceof zCore.$ZodVoid ||\n validator instanceof zCore.$ZodUndefined) {\n throw new Error(`Validator ${validator.constructor.name} is not supported in Convex`);\n }\n // Unsupported type\n return v.any();\n}\nfunction convexToZodLiteral(literal) {\n if (literal === undefined) {\n throw new Error(\"undefined is not a valid Convex value\");\n }\n if (literal === null) {\n return v.null();\n }\n return v.literal(literal);\n}\nfunction extractStringLiterals(validator) {\n if (validator.kind === \"literal\") {\n const literalValidator = validator;\n if (typeof literalValidator.value === \"string\") {\n return [literalValidator.value];\n }\n return null;\n }\n if (validator.kind === \"union\") {\n const unionValidator = validator;\n const literals = [];\n for (const member of unionValidator.members) {\n const memberLiterals = extractStringLiterals(member);\n if (memberLiterals === null) {\n return null; // Not all members are string literals\n }\n literals.push(...memberLiterals);\n }\n return literals;\n }\n return null; // Not a literal or union of literals\n}\nfunction isValidRecordKey(validator) {\n if (validator.kind === \"string\" || validator.kind === \"id\") {\n return true;\n }\n if (validator.kind === \"union\") {\n const unionValidator = validator;\n return unionValidator.members.every(isValidRecordKey);\n }\n return false;\n}\n// #endregion\n// #region Implementation: zid\n/** Stores the table names for each `Zid` instance that is created. */\nconst _zidRegistry = zCore.registry();\n// #endregion\n","import { z } from 'zod'\nimport { zid } from 'convex-helpers/server/zod4'\n\nexport const BaseDocumentSchema = <T extends string>(tableName: T) =>\n z.object({\n _id: zid(tableName),\n _creationTime: z.number(),\n })\n","import { z } from 'zod'\nimport { zid } from 'convex-helpers/server/zod4'\nimport { BaseDocumentSchema } from '@/shared/types/convex/base'\n\n// Decided to use undefined instead of null just because it's more natural here\n// and any operation with with a notification will be done after checking its category\n\nconst BaseNotificationSchema = BaseDocumentSchema('notifications').extend({\n organizationId: zid('organizations'),\n read: z.boolean(),\n title: z.string().min(1),\n message: z.string(),\n})\n\nexport const GeneralNotificationSchema = BaseNotificationSchema.extend({\n category: z.literal('general'),\n link: z.url().nullable(),\n})\n\nexport const ChatNotificationSchema = BaseNotificationSchema.extend({\n category: z.literal('chat'),\n conversationId: zid('conversations'),\n})\n\nexport const SpacesNotificationSchema = BaseNotificationSchema.extend({\n category: z.literal('spaces'),\n spaceUrlPath: z.string(),\n})\n\nexport const NotificationSchema = z.discriminatedUnion('category', [\n GeneralNotificationSchema,\n ChatNotificationSchema,\n SpacesNotificationSchema,\n])\n\nexport type Notification = z.infer<typeof NotificationSchema>\nexport type NotificationCategory = Notification['category']\n","import {\n ChatNotificationSchema,\n GeneralNotificationSchema,\n SpacesNotificationSchema,\n} from '@/shared/types/convex/notification/notification'\nimport z from 'zod'\n\nconst omitFields = { _id: true, _creationTime: true, organizationId: true, read: true } as const\n\nexport const BareGeneralNotificationSchema = GeneralNotificationSchema.omit(omitFields)\nexport const BareChatNotificationSchema = ChatNotificationSchema.omit(omitFields)\nexport const BareSpacesNotificationSchema = SpacesNotificationSchema.omit(omitFields)\n\nexport const BareNotificationSchema = z.discriminatedUnion('category', [\n BareGeneralNotificationSchema,\n BareChatNotificationSchema,\n BareSpacesNotificationSchema,\n])\n\nexport type BareNotification = z.infer<typeof BareNotificationSchema>\n","import { ConversationWithTags } from '@/shared/types/convex/conversation'\r\nimport { TemplateContent, TextContent } from '@/shared/types/convex/message/message-content'\r\nimport { BareNotificationSchema } from '@/shared/types/convex/notification/bare-notification'\r\nimport { z } from 'zod'\r\n\r\n// ============================================================\r\n// Assign Tags\r\n// ============================================================\r\n\r\nexport const AssignTagsSchema = z.object({\r\n waId: z.string().min(1, 'WhatsApp ID is required'),\r\n tags: z.array(z.string()).min(1, 'At least one tag is required'),\r\n})\r\n\r\nexport type AssignTagsPayload = z.infer<typeof AssignTagsSchema>\r\n\r\nexport type AssignTagsResponse = {\r\n message: string\r\n}\r\n\r\n// ============================================================\r\n// Send Notification\r\n// ============================================================\r\n\r\nconst SEND_OPTIONS = ['dashboard', 'email', 'push'] as const\r\n\r\nexport const SendNotificationSchema = z.object({\r\n sendOptions: z.array(z.enum(SEND_OPTIONS)).min(1),\r\n notification: BareNotificationSchema,\r\n})\r\n\r\nexport type SendNotificationPayload = z.infer<typeof SendNotificationSchema>\r\n\r\nexport type SendNotificationResponse = {\r\n message: string\r\n}\r\n\r\n// ============================================================\r\n// Send Template/Message\r\n// ============================================================\r\n\r\nexport const SendMessageSchema = z.object({\r\n waId: z.string().min(1, 'WhatsApp ID is required'),\r\n message: z.discriminatedUnion('type', [\r\n z.object({\r\n type: z.literal('text'),\r\n content: TextContent,\r\n }),\r\n z.object({\r\n type: z.literal('note'),\r\n content: TextContent,\r\n }),\r\n z.object({\r\n type: z.literal('template'),\r\n content: TemplateContent.omit({ renderedText: true }),\r\n }),\r\n ]),\r\n clientName: z.string().optional(),\r\n})\r\n\r\nexport type SendMessagePayload = z.infer<typeof SendMessageSchema>\r\n\r\nexport type SendMessageResponse = {\r\n message: string\r\n}\r\n\r\n// ============================================================\r\n// Stop Conversation AI\r\n// ============================================================\r\n\r\nexport const StopConversationAiSchema = z.object({\r\n waId: z.string().min(1, 'WhatsApp ID is required'),\r\n stopAi: z.boolean(),\r\n})\r\n\r\nexport type StopConversationAiPayload = z.infer<typeof StopConversationAiSchema>\r\n\r\nexport type StopConversationAiResponse = {\r\n message: string\r\n}\r\n\r\n// ============================================================\r\n// Upsert Conversation\r\n// ============================================================\r\n\r\nexport const UpsertConversationSchema = z.object({\r\n waId: z.string().min(1, 'WhatsApp ID is required'),\r\n clientName: z.string().min(1, 'Client name is required'),\r\n})\r\n\r\nexport type UpsertConversationPayload = z.infer<typeof UpsertConversationSchema>\r\n\r\nexport type UpsertConversationResponse = {\r\n message: string\r\n data: ConversationWithTags\r\n}\r\n","import { err, ok, Result } from '@/shared/errors/neverthrow'\r\nimport { HttpService } from '@/shared/services/http/http.service'\r\nimport {\r\n AssignTagsPayload,\r\n AssignTagsResponse,\r\n AssignTagsSchema,\r\n SendNotificationPayload,\r\n SendNotificationResponse,\r\n SendNotificationSchema,\r\n SendMessagePayload,\r\n SendMessageResponse,\r\n SendMessageSchema,\r\n StopConversationAiPayload,\r\n StopConversationAiResponse,\r\n StopConversationAiSchema,\r\n UpsertConversationPayload,\r\n UpsertConversationResponse,\r\n UpsertConversationSchema,\r\n} from './schemas'\r\n\r\nexport interface KortexClientConfig {\r\n /**\r\n * Base URL of the Kortex Hub API\r\n * @default 'https://kortex-dashboard.vercel.app'\r\n */\r\n baseUrl?: string\r\n\r\n /**\r\n * API token for authentication\r\n */\r\n apiToken: string\r\n}\r\n\r\nexport type KortexAPIError = {\r\n message: string\r\n statusCode?: number\r\n response?: unknown\r\n}\r\n\r\nexport class KortexClient {\r\n private readonly baseUrl: string\r\n private readonly apiToken: string\r\n\r\n constructor(config: KortexClientConfig) {\r\n this.baseUrl = config.baseUrl || 'https://kortex-dashboard.vercel.app'\r\n this.apiToken = config.apiToken\r\n }\r\n\r\n /**\r\n * Internal method to make API requests\r\n */\r\n private async request<TResponse>(endpoint: string, payload: unknown): Promise<Result<TResponse, KortexAPIError>> {\r\n const result = await HttpService.post<TResponse>(`${this.baseUrl}${endpoint}`, payload, {\r\n Authorization: `Bearer ${this.apiToken}`,\r\n })\r\n\r\n if (result.error) {\r\n return err({\r\n message: result.error.message,\r\n })\r\n }\r\n\r\n return ok(result.data)\r\n }\r\n\r\n /**\r\n * Assign tags to a conversation\r\n * @param payload - The waId and tags to assign\r\n * @returns Result with the success message or error\r\n */\r\n async assignTags(payload: AssignTagsPayload): Promise<Result<AssignTagsResponse, KortexAPIError>> {\r\n try {\r\n const validated = AssignTagsSchema.parse(payload)\r\n return this.request<AssignTagsResponse>('/api/external/assign-tags', validated)\r\n } catch (error) {\r\n return err({ message: error instanceof Error ? error.message : 'Validation error' })\r\n }\r\n }\r\n\r\n /**\r\n * Send a notification through specified channels\r\n * @param payload - The notification and send options\r\n * @returns Result with the success message or error\r\n */\r\n async sendNotification(payload: SendNotificationPayload): Promise<Result<SendNotificationResponse, KortexAPIError>> {\r\n try {\r\n const validated = SendNotificationSchema.parse(payload)\r\n return this.request<SendNotificationResponse>('/api/external/send-notification', validated)\r\n } catch (error) {\r\n return err({ message: error instanceof Error ? error.message : 'Validation error' })\r\n }\r\n }\r\n\r\n /**\r\n * Send a message (text, note, or template) to a WhatsApp conversation\r\n * @param payload - The message details (waId, message type and content)\r\n * @returns Result with the success message or error\r\n */\r\n async sendMessage(payload: SendMessagePayload): Promise<Result<SendMessageResponse, KortexAPIError>> {\r\n try {\r\n const validated = SendMessageSchema.parse(payload)\r\n return this.request<SendMessageResponse>('/api/external/send-template', validated)\r\n } catch (error) {\r\n return err({ message: error instanceof Error ? error.message : 'Validation error' })\r\n }\r\n }\r\n\r\n /**\r\n * Stop or start AI for a conversation\r\n * @param payload - The waId and stopAi boolean\r\n * @returns Result with the success message or error\r\n */\r\n async stopConversationAi(\r\n payload: StopConversationAiPayload,\r\n ): Promise<Result<StopConversationAiResponse, KortexAPIError>> {\r\n try {\r\n const validated = StopConversationAiSchema.parse(payload)\r\n return this.request<StopConversationAiResponse>('/api/external/stop-conversation-ai', validated)\r\n } catch (error) {\r\n return err({ message: error instanceof Error ? error.message : 'Validation error' })\r\n }\r\n }\r\n\r\n /**\r\n * Create or update a conversation\r\n * @param payload - The waId and client name\r\n * @returns Result with the conversation data or error\r\n */\r\n async upsertConversation(\r\n payload: UpsertConversationPayload,\r\n ): Promise<Result<UpsertConversationResponse, KortexAPIError>> {\r\n try {\r\n const validated = UpsertConversationSchema.parse(payload)\r\n return this.request<UpsertConversationResponse>('/api/external/upsert-conversation', validated)\r\n } catch (error) {\r\n return err({ message: error instanceof Error ? error.message : 'Validation error' })\r\n }\r\n }\r\n}\r\n"]}