{"version":3,"file":"errors.mjs","names":["unknownFailure","defineErrorContract","declarations","definitions","code","definition","trusted","contract","envelope","parseDetails","details","error","copyJson","ConvexError","isRecord","payload","key","decodeFailure","combineErrorContracts","contracts","unmatched","projected","decoded","queryErrors","value","prototype","ancestors","result","index","child","fields","strict","field"],"sources":["../../../src/modules/contracts/errors.ts"],"sourcesContent":["/* oxlint-disable anti-slop/no-unknown-parameters, anti-slop/no-unknown-returns, anti-slop/no-unknown-type-aliases, anti-slop/no-runtime-typeof, anti-slop/no-unsafe-dictionary-type -- This neutral contract validates unknown transport data and an explicitly keyed code/detail declaration. */\n\nimport { ConvexError } from 'convex/values'\n\n/** Explicit synchronous validators for the final public detail representation. */\nexport type ErrorDetailParser<Output = unknown> = Readonly<{\n\tparse: (value: unknown) => Output\n}>\n\nexport type ErrorDefinitions = Readonly<\n\tRecord<\n\t\tstring,\n\t\tReadonly<{\n\t\t\tmessage: string\n\t\t\tdetails: Readonly<Record<string, ErrorDetailParser>>\n\t\t}>\n\t>\n>\n\ntype Code<Definitions extends ErrorDefinitions> = Extract<keyof Definitions, string>\ntype Details<Definition extends ErrorDefinitions[string]> =\n\tDefinition extends ErrorDefinitions[string]\n\t\t? { [Field in keyof Definition['details']]: ReturnType<Definition['details'][Field]['parse']> }\n\t\t: never\n\ndeclare const declaredErrorBrand: unique symbol\n\n/** Server failures are trusted only by the contract that created them. */\nexport type DeclaredError<Definitions extends ErrorDefinitions> = {\n\t[Key in Code<Definitions>]: Readonly<{\n\t\t_tag: 'DeclaredError'\n\t\tcode: Key\n\t\tdetails: Details<Definitions[Key]>\n\t\t[declaredErrorBrand]: true\n\t}>\n}[Code<Definitions>]\n\nexport type DeclaredFailure<Definitions extends ErrorDefinitions> = {\n\t[Key in Code<Definitions>]: Readonly<{\n\t\t_tag: 'DeclaredFailure'\n\t\tversion: 1\n\t\tcode: Key\n\t\tmessage: string\n\t\tdetails: Details<Definitions[Key]>\n\t}>\n}[Code<Definitions>]\n\nexport type UnknownFailure = Readonly<{ _tag: 'UnknownFailure'; version: 1 }>\nexport type DecodedFailure<Definitions extends ErrorDefinitions> =\n\t| DeclaredFailure<Definitions>\n\t| UnknownFailure\n\nexport type ErrorContract<Definitions extends ErrorDefinitions> = Readonly<{\n\tcreate: <Key extends Code<Definitions>>(\n\t\tcode: Key,\n\t\tdetails: Details<Definitions[NoInfer<Key>]>,\n\t) => Extract<DeclaredError<Definitions>, { code: Key }>\n\tenvelope: <Key extends Code<Definitions>>(\n\t\tcode: Key,\n\t\tdetails: Details<Definitions[NoInfer<Key>]>,\n\t) => Extract<DeclaredFailure<Definitions>, { code: Key }>\n\ttoConvexError: <Key extends Code<Definitions>>(\n\t\tcode: Key,\n\t\tdetails: Details<Definitions[NoInfer<Key>]>,\n\t) => ConvexError<Extract<DeclaredFailure<Definitions>, { code: Key }>>\n\tproject: (error: unknown) => DecodedFailure<Definitions>\n\t/** Receives envelope data, e.g. ConvexError.data; never parses error messages. */\n\tdecode: (payload: unknown) => DecodedFailure<Definitions>\n}>\n\nconst unknownFailure: UnknownFailure = Object.freeze({\n\t_tag: 'UnknownFailure',\n\tversion: 1,\n})\ntype Json = null | boolean | number | string | Json[] | { [key: string]: Json }\n\n/** Closed safe codes, allowlisted details, and a versioned checked transport union. */\nexport function defineErrorContract<const Definitions extends ErrorDefinitions>(\n\tdefinitions: Definitions,\n): ErrorContract<Definitions> {\n\t// SAFETY: the snapshot copies every declaration without changing its code, message or paired parsers.\n\tconst declarations = Object.fromEntries(\n\t\tObject.entries(definitions).map(([code, definition]) => {\n\t\t\tif (!code || !definition.message || definition.message.length > 200) {\n\t\t\t\tthrow Error('Declared errors require a code and a public message of 1–200 characters')\n\t\t\t}\n\t\t\treturn [code, { message: definition.message, details: { ...definition.details } }]\n\t\t}),\n\t) as Definitions\n\tconst trusted = new WeakMap<object, DeclaredFailure<Definitions>>()\n\tconst contract: ErrorContract<Definitions> = {\n\t\tcreate(code, details) {\n\t\t\tlet envelope: DeclaredFailure<Definitions>\n\t\t\ttry {\n\t\t\t\tif (!Object.hasOwn(declarations, code)) throw Error('Undeclared code')\n\t\t\t\tconst definition = declarations[code]\n\t\t\t\t// SAFETY: the selected closed declaration validates every field before construction.\n\t\t\t\tenvelope = {\n\t\t\t\t\t_tag: 'DeclaredFailure',\n\t\t\t\t\tversion: 1,\n\t\t\t\t\tcode,\n\t\t\t\t\tmessage: definition.message,\n\t\t\t\t\tdetails: parseDetails(definition, details, false),\n\t\t\t\t} as DeclaredFailure<Definitions>\n\t\t\t} catch {\n\t\t\t\t// Validator messages, issue paths and provider causes remain private.\n\t\t\t\tthrow Error('Invalid declared error details')\n\t\t\t}\n\t\t\t// SAFETY: identity is registered below; the inaccessible brand cannot confer trust by itself.\n\t\t\tconst error = Object.freeze({\n\t\t\t\t_tag: 'DeclaredError',\n\t\t\t\tcode,\n\t\t\t\tdetails: copyJson(envelope.details),\n\t\t\t}) as Extract<DeclaredError<Definitions>, { code: typeof code }>\n\t\t\ttrusted.set(error, envelope)\n\t\t\treturn error\n\t\t},\n\t\tenvelope(code, details) {\n\t\t\t// SAFETY: create validates the selected code; project retrieves its private validated envelope.\n\t\t\treturn contract.project(contract.create(code, details)) as Extract<\n\t\t\t\tDeclaredFailure<Definitions>,\n\t\t\t\t{ code: typeof code }\n\t\t\t>\n\t\t},\n\t\ttoConvexError(code, details) {\n\t\t\treturn new ConvexError(contract.envelope(code, details))\n\t\t},\n\t\tproject(error) {\n\t\t\tif (error === null || typeof error !== 'object') return unknownFailure\n\t\t\tconst envelope = trusted.get(error)\n\t\t\t// SAFETY: only validated contract-owned envelopes enter the private map.\n\t\t\treturn envelope ? (copyJson(envelope) as DeclaredFailure<Definitions>) : unknownFailure\n\t\t},\n\t\tdecode(payload) {\n\t\t\ttry {\n\t\t\t\tif (\n\t\t\t\t\t!isRecord(payload) ||\n\t\t\t\t\tpayload._tag !== 'DeclaredFailure' ||\n\t\t\t\t\tpayload.version !== 1 ||\n\t\t\t\t\ttypeof payload.code !== 'string' ||\n\t\t\t\t\t!Object.hasOwn(declarations, payload.code) ||\n\t\t\t\t\tObject.keys(payload).length !== 5 ||\n\t\t\t\t\t!['message', 'details', '_tag', 'version', 'code'].every((key) =>\n\t\t\t\t\t\tObject.hasOwn(payload, key),\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\treturn unknownFailure\n\t\t\t\t}\n\t\t\t\tconst definition = declarations[payload.code]\n\t\t\t\tif (payload.message !== definition.message) return unknownFailure\n\t\t\t\t// Validate raw transport JSON too: parsers must not hide non-JSON payloads.\n\t\t\t\tcopyJson(payload.details)\n\t\t\t\t// SAFETY: code membership and every allowlisted field have been checked independently.\n\t\t\t\treturn {\n\t\t\t\t\t_tag: 'DeclaredFailure',\n\t\t\t\t\tversion: 1,\n\t\t\t\t\tcode: payload.code,\n\t\t\t\t\tmessage: definition.message,\n\t\t\t\t\tdetails: parseDetails(definition, payload.details, true),\n\t\t\t\t} as DeclaredFailure<Definitions>\n\t\t\t} catch {\n\t\t\t\treturn unknownFailure\n\t\t\t}\n\t\t},\n\t}\n\treturn contract\n}\n\n/** A structural decoder also accepts combined contracts without requiring constructors. */\nexport type FailureContract = Pick<ErrorContract<ErrorDefinitions>, 'decode'>\nexport type FailureOf<Contract extends FailureContract> = ReturnType<Contract['decode']>\ntype ProjectingContract = FailureContract & Pick<ErrorContract<ErrorDefinitions>, 'project'>\n\n/** Extract only ConvexError.data, including one bounded serialized JSON envelope. */\nexport function decodeFailure<Contract extends FailureContract>(\n\terror: unknown,\n\tcontract: Contract,\n): FailureOf<Contract> {\n\ttry {\n\t\tif (error instanceof ConvexError) {\n\t\t\tlet payload: unknown = error.data\n\t\t\tif (typeof payload === 'string') {\n\t\t\t\tif (payload.length > 65536 || new TextEncoder().encode(payload).byteLength > 65536)\n\t\t\t\t\t// SAFETY: every failure decoder includes UnknownFailure.\n\t\t\t\t\treturn unknownFailure as FailureOf<Contract>\n\t\t\t\tpayload = JSON.parse(payload)\n\t\t\t}\n\t\t\t// SAFETY: the structural contract owns the decoded union.\n\t\t\treturn contract.decode(payload) as FailureOf<Contract>\n\t\t}\n\t} catch {\n\t\t// Foreign errors, accessors and invalid JSON expose no diagnostics.\n\t}\n\t// SAFETY: every failure decoder includes UnknownFailure.\n\treturn unknownFailure as FailureOf<Contract>\n}\n\ntype CombinedErrorContract<Contracts extends readonly ProjectingContract[]> = Readonly<{\n\tproject: (error: unknown) => FailureOf<Contracts[number]> | UnknownFailure\n\tdecode: (payload: unknown) => FailureOf<Contracts[number]> | UnknownFailure\n}>\n\n/** Ordered projection and decoding; duplicate codes retain the union of member details. */\nexport function combineErrorContracts<const Contracts extends readonly ProjectingContract[]>(\n\t...contracts: Contracts\n): CombinedErrorContract<Contracts> {\n\tconst unmatched = unknownFailure\n\treturn {\n\t\tproject(error) {\n\t\t\tfor (const contract of contracts) {\n\t\t\t\tconst projected = contract.project(error)\n\t\t\t\tif (projected._tag === 'DeclaredFailure') {\n\t\t\t\t\t// SAFETY: this result belongs to a member of the inferred tuple.\n\t\t\t\t\treturn projected as FailureOf<Contracts[number]>\n\t\t\t\t}\n\t\t\t\tconst decoded = decodeFailure(error, contract)\n\t\t\t\tif (decoded._tag === 'DeclaredFailure') {\n\t\t\t\t\t// SAFETY: strict transported decoding preserves the same member union.\n\t\t\t\t\treturn decoded as FailureOf<Contracts[number]>\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn unmatched\n\t\t},\n\t\tdecode(payload) {\n\t\t\tfor (const contract of contracts) {\n\t\t\t\tconst decoded = contract.decode(payload)\n\t\t\t\tif (decoded._tag === 'DeclaredFailure') {\n\t\t\t\t\t// SAFETY: this result belongs to a member of the inferred tuple.\n\t\t\t\t\treturn decoded as FailureOf<Contracts[number]>\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn unmatched\n\t\t},\n\t}\n}\n\n/** Fixed, diagnostic-free transport shared by query endpoints and client recovery. */\nexport const queryErrors = defineErrorContract({\n\t'invalid-cursor': { message: 'Invalid cursor', details: {} },\n\tFIELD_GROUP_DENIED: { message: 'Field group access denied', details: {} },\n\tQUERY_FANOUT: { message: 'Query fan-out limit exceeded', details: {} },\n\tSEARCH_TEXT_REQUIRED: { message: 'Search text required', details: {} },\n\tSEARCH_END_CURSOR_UNSUPPORTED: {\n\t\tmessage: 'Search end cursor unsupported',\n\t\tdetails: {},\n\t},\n\tSEARCH_ORDER_UNSUPPORTED: {\n\t\tmessage: 'Search ordering unsupported',\n\t\tdetails: {},\n\t},\n\tSEARCH_RELATION_UNSUPPORTED: {\n\t\tmessage: 'Relation search unsupported',\n\t\tdetails: {},\n\t},\n\tSEARCH_OPTIONS_UNSUPPORTED: {\n\t\tmessage: 'Search options unsupported',\n\t\tdetails: {},\n\t},\n\tSEARCH_PROTOCOL_UNSUPPORTED: {\n\t\tmessage: 'Search pagination protocol unsupported',\n\t\tdetails: {},\n\t},\n})\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\tif (value === null || typeof value !== 'object' || Array.isArray(value)) return false\n\tconst prototype = Object.getPrototypeOf(value)\n\treturn prototype === Object.prototype || prototype === null\n}\n\n/** Copy data without invoking toJSON or retaining mutable provider objects. */\nfunction copyJson(value: unknown, ancestors = new Set<object>()): Json {\n\tif (value === null || typeof value === 'string' || typeof value === 'boolean') return value\n\tif (typeof value === 'number' && Number.isFinite(value)) return value\n\tif (typeof value !== 'object' || value === null || ancestors.has(value))\n\t\tthrow Error('Invalid JSON')\n\tancestors.add(value)\n\ttry {\n\t\tif (Array.isArray(value)) {\n\t\t\tconst result: Json[] = []\n\t\t\tfor (let index = 0; index < value.length; index++)\n\t\t\t\tresult.push(copyJson(value[index], ancestors))\n\t\t\treturn result\n\t\t}\n\t\tif (!isRecord(value)) throw Error('Invalid JSON')\n\t\treturn Object.fromEntries(\n\t\t\tObject.entries(value).map(([key, child]) => [key, copyJson(child, ancestors)]),\n\t\t)\n\t} finally {\n\t\tancestors.delete(value)\n\t}\n}\n\nfunction parseDetails<const Definition extends ErrorDefinitions[string]>(\n\tdefinition: Definition,\n\tvalue: unknown,\n\tstrict: boolean,\n): Details<Definition> {\n\tif (!isRecord(value)) throw Error('Invalid details')\n\tconst fields = Object.keys(definition.details)\n\tif (strict && Object.keys(value).some((key) => !Object.hasOwn(definition.details, key))) {\n\t\tthrow Error('Undeclared detail')\n\t}\n\t// SAFETY: each declared field is validated by its paired parser before its JSON-safe copy is returned.\n\treturn Object.fromEntries(\n\t\tfields.map((field) => {\n\t\t\tif (!Object.hasOwn(value, field)) throw Error('Missing detail')\n\t\t\treturn [field, copyJson(definition.details[field].parse(value[field]))]\n\t\t}),\n\t) as Details<Definition>\n}\n"],"mappings":"4CAsEA,MAAMA,EAAiC,OAAO,OAAO,CACpD,KAAM,iBACN,QAAS,CACV,CAAC,EAID,SAAgBC,EACf,EAC6B,CAE7B,IAAMC,EAAe,OAAO,YAC3B,OAAO,QAAQC,CAAW,CAAC,CAAC,KAAK,CAACC,EAAMC,KAAgB,CACvD,GAAI,CAACD,GAAQ,CAACC,EAAW,SAAWA,EAAW,QAAQ,OAAS,IAC/D,MAAM,MAAM,yEAAyE,EAEtF,MAAO,CAACD,EAAM,CAAE,QAASC,EAAW,QAAS,QAAS,CAAE,GAAGA,EAAW,OAAQ,CAAE,CAAC,CAClF,CAAC,CACF,EACMC,kBAAU,IAAI,QACdC,EAAuC,CAC5C,OAAO,EAAM,EAAS,CACrB,IAAIC,EACJ,GAAI,CACH,GAAI,CAAC,OAAO,OAAON,EAAcE,CAAI,EAAG,MAAM,MAAM,iBAAiB,EACrE,IAAMC,EAAaH,EAAaE,GAEhC,EAAW,CACV,KAAM,kBACN,QAAS,EACT,OACA,QAASC,EAAW,QACpB,QAASI,EAAaJ,EAAYK,EAAS,EAAK,CACjD,CACD,MAAQ,CAEP,MAAM,MAAM,gCAAgC,CAC7C,CAEA,IAAMC,EAAQ,OAAO,OAAO,CAC3B,KAAM,gBACN,OACA,QAASC,EAASJ,EAAS,OAAO,CACnC,CAAC,EAED,OADAF,EAAQ,IAAIK,EAAOH,CAA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