cvx-kit 0.1.30 → 0.1.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/effect.d.mts +5 -1
- package/dist/effect.mjs +1 -1
- package/dist/modules/contracts/binding.d.mts +1 -1
- package/dist/modules/contracts/binding.mjs +1 -1
- package/dist/modules/contracts/binding.mjs.map +1 -1
- package/dist/modules/contracts/domain.d.mts +5 -1
- package/dist/modules/contracts/domain.mjs +1 -1
- package/dist/modules/contracts/domain.mjs.map +1 -1
- package/dist/modules/contracts/errors.d.mts +4 -0
- package/dist/modules/contracts/errors.mjs +1 -1
- package/dist/modules/contracts/errors.mjs.map +1 -1
- package/dist/modules/effect/action.d.mts +64 -0
- package/dist/modules/effect/action.mjs +2 -0
- package/dist/modules/effect/action.mjs.map +1 -0
- package/dist/modules/effect/client.d.mts +5 -1
- package/dist/modules/effect/client.mjs +1 -1
- package/dist/modules/effect/command.d.mts +15 -9
- package/dist/modules/effect/command.mjs +1 -1
- package/dist/modules/effect/command.mjs.map +1 -1
- package/dist/modules/effect/crud.d.mts +17 -16
- package/dist/modules/effect/domain.d.mts +19 -8
- package/dist/modules/effect/domain.mjs +1 -1
- package/dist/modules/effect/domain.mjs.map +1 -1
- package/dist/modules/effect/errors.d.mts +5 -1
- package/dist/modules/effect/errors.mjs +1 -1
- package/dist/modules/effect/errors.mjs.map +1 -1
- package/dist/modules/effect/failure-audit.d.mts +48 -0
- package/dist/modules/effect/failure-audit.mjs +2 -0
- package/dist/modules/effect/failure-audit.mjs.map +1 -0
- package/dist/modules/effect/failures.d.mts +22 -0
- package/dist/modules/effect/failures.mjs +2 -0
- package/dist/modules/effect/failures.mjs.map +1 -0
- package/dist/modules/effect/foundation.d.mts +6 -1
- package/dist/modules/effect/foundation.mjs +1 -1
- package/dist/modules/effect/foundation.mjs.map +1 -1
- package/dist/modules/effect/operation.d.mts +10 -2
- package/dist/modules/effect/operation.mjs +1 -1
- package/dist/modules/effect/operation.mjs.map +1 -1
- package/dist/modules/effect/query.d.mts +5 -1
- package/dist/modules/effect/query.mjs +1 -1
- package/dist/modules/effect/query.mjs.map +1 -1
- package/dist/modules/effect/scope.d.mts +27 -0
- package/dist/modules/effect/scope.mjs +2 -0
- package/dist/modules/effect/scope.mjs.map +1 -0
- package/dist/zod-table.d.mts +72 -1
- package/dist/zod-table.mjs +1 -1
- package/dist/zod-table.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"foundation.mjs","names":["createEffectFoundation","observability","Observability","options","dependencies","bindEffectCommand","bindEffectQuery"],"sources":["../../../src/modules/effect/foundation.ts"],"sourcesContent":["// oxlint-disable-next-line cvx/component-boundaries -- SAFETY: Internal optional adapter shares the Effect-free Foundation lifecycle and types without entering the Convex component deployment graph.\nimport {\n\tObservability,\n\ttype ObservabilityOptions,\n} from '../../components/foundation/modules/observability/observability'\nimport { bindEffectCommand, type EffectCommandDependencies } from './command'\nimport { bindEffectQuery } from './query'\n\n/** Shared host capabilities are bound once; registry resolvers stay invocation-local. */\nexport type EffectFoundationOptions = Omit<EffectCommandDependencies, 'observability'> & {\n\tobservability: ObservabilityOptions\n}\nexport type EffectFoundation<Options extends EffectFoundationOptions> = {\n\tCommand: ReturnType<typeof bindEffectCommand<Options & { observability: Observability }>>\n\tQuery: ReturnType<typeof bindEffectQuery<Options & { observability: Observability }>>\n\tobservability: Observability\n}\n\nexport function createEffectFoundation<const Options extends EffectFoundationOptions>(\n\toptions: Options,\n): EffectFoundation<Options> {\n\tconst observability = new Observability(options.observability)\n\tconst dependencies = { ...options, observability }\n\treturn {\n\t\tCommand: bindEffectCommand(dependencies),\n\t\tQuery: bindEffectQuery(dependencies),\n\t\tobservability,\n\t}\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"foundation.mjs","names":["createEffectFoundation","observability","Observability","options","dependencies","bindEffectCommand","bindEffectQuery","bindEffectAction"],"sources":["../../../src/modules/effect/foundation.ts"],"sourcesContent":["// oxlint-disable-next-line cvx/component-boundaries -- SAFETY: Internal optional adapter shares the Effect-free Foundation lifecycle and types without entering the Convex component deployment graph.\nimport {\n\tObservability,\n\ttype ObservabilityOptions,\n} from '../../components/foundation/modules/observability/observability'\nimport { bindEffectCommand, type EffectCommandDependencies } from './command'\nimport { bindEffectQuery } from './query'\nimport { bindEffectAction, type EffectActionDependencies } from './action'\n\n/** Shared host capabilities are bound once; registry resolvers stay invocation-local. */\nexport type EffectFoundationOptions = Omit<EffectCommandDependencies, 'observability'> &\n\tPick<EffectActionDependencies, 'writeActionAudit'> & {\n\t\tobservability: ObservabilityOptions\n\t}\nexport type EffectFoundation<Options extends EffectFoundationOptions> = {\n\tCommand: ReturnType<typeof bindEffectCommand<Options & { observability: Observability }>>\n\tQuery: ReturnType<typeof bindEffectQuery<Options & { observability: Observability }>>\n\t/** Contract-typed Convex actions with context injection, guards, middleware and optional audit. */\n\tAction: ReturnType<typeof bindEffectAction<Options & { observability: Observability }>>\n\tobservability: Observability\n}\n\nexport function createEffectFoundation<const Options extends EffectFoundationOptions>(\n\toptions: Options,\n): EffectFoundation<Options> {\n\tconst observability = new Observability(options.observability)\n\tconst dependencies = { ...options, observability }\n\treturn {\n\t\tCommand: bindEffectCommand(dependencies),\n\t\tQuery: bindEffectQuery(dependencies),\n\t\tAction: bindEffectAction(dependencies),\n\t\tobservability,\n\t}\n}\n"],"mappings":"oPAsBA,SAAgBA,EACf,EAC4B,CAC5B,IAAMC,EAAgB,IAAIC,EAAcC,EAAQ,aAAa,EACvDC,EAAe,CAAE,GAAGD,EAAS,eAAc,EACjD,MAAO,CACN,QAASE,EAAkBD,CAAY,EACvC,MAAOE,EAAgBF,CAAY,EACnC,OAAQG,EAAiBH,CAAY,EACrC,eACD,CACD"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { ContractInput, ContractOutput, ContractSchema } from "../contracts/contract.mjs";
|
|
2
2
|
import { AuditEntryInput } from "../../components/foundation/client.mjs";
|
|
3
3
|
import { ContractDecoderError, ContractDecoderRequirements } from "./schema.mjs";
|
|
4
|
+
import { RequestScope } from "./scope.mjs";
|
|
4
5
|
import { Effect } from "effect";
|
|
5
6
|
//#region src/modules/effect/operation.d.ts
|
|
6
7
|
/** Ordinary failures are defects; only an explicit Effect supplies a typed error. */
|
|
@@ -108,7 +109,7 @@ export type OperationDefinition<Context, Input extends ContractSchema, Output ex
|
|
|
108
109
|
audit?: (resolution: {
|
|
109
110
|
command: ContractOutput<Input>;
|
|
110
111
|
result: ContractOutput<Output>;
|
|
111
|
-
}, context: Context) => AuditResult;
|
|
112
|
+
}, context: Context, scope: RequestScope | undefined) => AuditResult;
|
|
112
113
|
} & (keyof Extension extends never ? {
|
|
113
114
|
middleware?: (input: EffectMiddlewareInput<Context, ContractOutput<Input>, ContractInput<Output>, Extension, BaseError | CallbackError<Handler | Guard>, BaseRequirements | CallbackRequirements<Handler | Guard>>) => Middleware;
|
|
114
115
|
} : {
|
|
@@ -128,7 +129,7 @@ export declare function effectOperationFactory<Context, Extension extends Record
|
|
|
128
129
|
audit: (resolution: {
|
|
129
130
|
command: ContractOutput<Input>;
|
|
130
131
|
result: ContractOutput<Output>;
|
|
131
|
-
}, context: Context) => AuditResult;
|
|
132
|
+
}, context: Context, scope: RequestScope | undefined) => AuditResult;
|
|
132
133
|
} : {})) => CheckedEffectDefinition<Context, typeof definition, BaseError, BaseRequirements>;
|
|
133
134
|
query: <const Input extends ContractSchema, const Output extends ContractSchema, Handler extends Supported<ContractInput<Output>>, Guard extends Supported<void> = never, Middleware extends Supported<ContractInput<Output>> = never, const Metadata extends object = Record<never, never>, const Wire extends ContractSchema = ContractSchema, const Replay extends ContractSchema = never, const Definition extends object = object>(definition: Definition & OperationDefinition<Context, Input, Output, Extension, readonly string[], Handler, Guard, never, never, Middleware, Metadata, BaseError, BaseRequirements, Wire, Replay> & {
|
|
134
135
|
prepare?: never;
|
|
@@ -137,5 +138,12 @@ export declare function effectOperationFactory<Context, Extension extends Record
|
|
|
137
138
|
replayResult?: never;
|
|
138
139
|
}) => CheckedEffectDefinition<Context, typeof definition, BaseError, BaseRequirements>;
|
|
139
140
|
};
|
|
141
|
+
export declare function effectActionFactory<Context, BaseError = never, BaseRequirements = never>(): {
|
|
142
|
+
action: <const Input extends ContractSchema, const Output extends ContractSchema, Handler extends Supported<ContractInput<Output>>, Guard extends Supported<void> = never, const Aggregates extends readonly string[] = readonly string[], AuditResult extends Supported<Audit<Aggregates> | null> = never, Middleware extends Supported<ContractInput<Output>> = never, const Metadata extends object = Record<never, never>, const Wire extends ContractSchema = ContractSchema, const Definition extends object = object>(definition: Definition & OperationDefinition<Context, Input, Output, Record<never, never>, Aggregates, Handler, Guard, never, AuditResult, Middleware, Metadata, BaseError, BaseRequirements, Wire, never> & {
|
|
143
|
+
prepare?: never;
|
|
144
|
+
permission?: never;
|
|
145
|
+
replayResult?: never;
|
|
146
|
+
}) => CheckedEffectDefinition<Context, typeof definition, BaseError, BaseRequirements>;
|
|
147
|
+
};
|
|
140
148
|
//#endregion
|
|
141
149
|
//# sourceMappingURL=operation.d.mts.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function e(){function e(e){return e}function t(e){return e}function n(e){return e}return{operation:e,command:t,query:n}}export{e as effectOperationFactory};
|
|
1
|
+
function e(){function e(e){return e}function t(e){return e}function n(e){return e}return{operation:e,command:t,query:n}}function t(){function e(e){return e}return{action:e}}export{t as effectActionFactory,e as effectOperationFactory};
|
|
2
2
|
//# sourceMappingURL=operation.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"operation.mjs","names":["effectOperationFactory","operation","definition","command","query"],"sources":["../../../src/modules/effect/operation.ts"],"sourcesContent":["import type { Effect } from 'effect'\nimport type { ContractSchema, ContractInput, ContractOutput } from '../contracts/contract'\nimport type { ContractDecoderError, ContractDecoderRequirements } from './schema'\nimport type { AuditEntryInput } from '../../components/foundation/client'\n\n/** Ordinary failures are defects; only an explicit Effect supplies a typed error. */\nexport type CallbackError<Value> = Value extends (...arguments_: never[]) => infer Returned\n\t? CallbackError<Returned>\n\t: Value extends Effect.Effect<infer Success, infer Error, unknown>\n\t\t? Error | CallbackError<Success>\n\t\t: Value extends PromiseLike<infer Awaited>\n\t\t\t? CallbackError<Awaited>\n\t\t\t: Value extends readonly (infer Item)[]\n\t\t\t\t? CallbackError<Item>\n\t\t\t\t: Value extends { kind: 'execute'; complete?: infer Complete }\n\t\t\t\t\t? CallbackError<Complete>\n\t\t\t\t\t: never\n\nexport type CallbackRequirements<Value> = Value extends (...arguments_: never[]) => infer Returned\n\t? CallbackRequirements<Returned>\n\t: Value extends Effect.Effect<infer Success, unknown, infer Requirements>\n\t\t? Requirements | CallbackRequirements<Success>\n\t\t: Value extends PromiseLike<infer Awaited>\n\t\t\t? CallbackRequirements<Awaited>\n\t\t\t: Value extends readonly (infer Item)[]\n\t\t\t\t? CallbackRequirements<Item>\n\t\t\t\t: Value extends { kind: 'execute'; complete?: infer Complete }\n\t\t\t\t\t? CallbackRequirements<Complete>\n\t\t\t\t\t: never\n\nexport type EffectValue<Value> =\n\tValue extends Effect.Effect<infer Success, unknown, unknown>\n\t\t? EffectValue<Success>\n\t\t: Value extends PromiseLike<infer Awaited>\n\t\t\t? EffectValue<Awaited>\n\t\t\t: Value\n\ndeclare const checkedOperation: unique symbol\n/** Type-only evidence that the helper checked callbacks against the base context and schemas. */\nexport type CheckedEffectOperation<Context> = {\n\treadonly [checkedOperation]: {\n\t\tcontext: (context: Context) => void\n\t\terror: unknown\n\t\trequirements: unknown\n\t\tdefinition: unknown\n\t}\n}\ntype CheckedChannels<Context, Error, Requirements, Definition> = {\n\treadonly [checkedOperation]: {\n\t\tcontext: (context: Context) => void\n\t\terror: Error\n\t\trequirements: Requirements\n\t\tdefinition: Definition\n\t}\n}\n/** Named checked-definition boundary keeps the private evidence marker inside this module's declarations. */\nexport type CheckedEffectDefinition<\n\tContext,\n\tDefinition,\n\tError = never,\n\tRequirements = never,\n> = NoInfer<Omit<Definition, typeof checkedOperation>> &\n\tCheckedChannels<Context, Error, Requirements, Omit<Definition, typeof checkedOperation>>\n/** Reject stale helper evidence after callbacks or schemas are replaced. */\nexport type ValidatedEffectOperations<Operations> = {\n\t[Key in keyof Operations]: Operations[Key] extends {\n\t\treadonly [checkedOperation]: { definition: infer Definition }\n\t}\n\t\t? Operations[Key] extends Definition\n\t\t\t? Operations[Key]\n\t\t\t: never\n\t\t: never\n}\n/** Only middleware whose next contract captured a default policy can discharge its channels. */\nexport type UnwrappedDefaultError<Definition, Guard> = Definition extends { middleware: Function }\n\t? Definition extends CheckedChannels<never, infer Error, unknown, unknown>\n\t\t? Exclude<CallbackError<Guard>, Error>\n\t\t: CallbackError<Guard>\n\t: CallbackError<Guard>\nexport type UnwrappedDefaultRequirements<Definition, Guard> = Definition extends {\n\tmiddleware: Function\n}\n\t? Definition extends CheckedChannels<never, unknown, infer Requirements, unknown>\n\t\t? Exclude<CallbackRequirements<Guard>, Requirements>\n\t\t: CallbackRequirements<Guard>\n\t: CallbackRequirements<Guard>\nexport type EffectOperationArgument<Definition extends { input: ContractSchema }> = ContractInput<\n\tDefinition['input']\n>\nexport type EffectOperationInput<Definition extends { input: ContractSchema }> = ContractOutput<\n\tDefinition['input']\n>\nexport type EffectOperationHandlerResult<Definition extends { result: ContractSchema }> =\n\tContractInput<Definition['result']>\nexport type EffectOperationResult<Definition extends { result: ContractSchema }> = ContractOutput<\n\tDefinition['result']\n>\n\ntype Hook<Definition, Key extends PropertyKey> = Key extends keyof Definition\n\t? Definition[Key]\n\t: never\ntype Returned<Callback> = Callback extends (...arguments_: never[]) => infer Value ? Value : never\n/** A conditional wrapper must retain the unwrapped channels for its absent branch. */\ntype CoreValue<Definition> = [Returned<Hook<Definition, 'middleware'>>] extends [never]\n\t? Returned<Hook<Definition, 'handler'>> | Returned<Hook<Definition, 'guard'>>\n\t: undefined extends Hook<Definition, 'middleware'>\n\t\t?\n\t\t\t\t| Returned<Hook<Definition, 'handler'>>\n\t\t\t\t| Returned<Hook<Definition, 'guard'>>\n\t\t\t\t| Returned<Hook<Definition, 'middleware'>>\n\t\t: Returned<Hook<Definition, 'middleware'>>\ntype OutsideHooks = 'prepare' | 'audit' | 'checkPermission' | 'writeAudit'\nexport type EffectOperationError<Definition> =\n\t| ContractDecoderError<Hook<Definition, 'input'>>\n\t| ContractDecoderError<Hook<Definition, 'result'>>\n\t| ContractDecoderError<Hook<Definition, 'replayResult'>>\n\t| CallbackError<CoreValue<Definition>>\n\t| CallbackError<Definition[Extract<keyof Definition, OutsideHooks>]>\nexport type EffectOperationRequirements<Definition> =\n\t| ContractDecoderRequirements<Hook<Definition, 'input'>>\n\t| ContractDecoderRequirements<Hook<Definition, 'result'>>\n\t| ContractDecoderRequirements<Hook<Definition, 'replayResult'>>\n\t| CallbackRequirements<CoreValue<Definition>>\n\t| CallbackRequirements<Definition[Extract<keyof Definition, OutsideHooks>]>\n\ntype Supported<Value, Error = unknown, Requirements = unknown> =\n\t| Value\n\t| PromiseLike<Value>\n\t| Effect.Effect<Value, Error, Requirements>\nexport type EffectPreparation<Result, Error = never, Requirements = never> =\n\t| { kind: 'replay'; result: unknown }\n\t| { kind: 'execute'; complete?: (result: Result) => Supported<void, Error, Requirements> }\nexport type EffectMiddlewareInput<\n\tContext,\n\tInput,\n\tResult,\n\tExtension,\n\tError = never,\n\tRequirements = never,\n> = {\n\toperation: string\n\tcontext: Context\n\tcommand: Input\n\tinput: Input\n\tnext: keyof Extension extends never\n\t\t? (options?: { context?: Extension }) => Effect.Effect<Result, Error, Requirements>\n\t\t: (options: { context: Extension }) => Effect.Effect<Result, Error, Requirements>\n}\ntype Audit<Aggregates extends readonly string[]> = Omit<\n\tAuditEntryInput,\n\t'classification' | 'aggregate'\n> & {\n\taggregate: { type: Aggregates[number]; id: string }\n}\nexport type OperationDefinition<\n\tContext,\n\tInput extends ContractSchema,\n\tOutput extends ContractSchema,\n\tExtension,\n\tAggregates extends readonly string[],\n\tHandler,\n\tGuard,\n\tPreparation,\n\tAuditResult,\n\tMiddleware,\n\tMetadata,\n\tBaseError,\n\tBaseRequirements,\n\tWire extends ContractSchema,\n\tReplay extends ContractSchema,\n> = {\n\tinput: Input\n\tresult: Output\n\thandler: (input: ContractOutput<Input>, context: Context & Extension) => Handler\n\tclassification?: string\n\tpermission?: string\n\tmetadata?: Metadata\n\taggregates?: Aggregates\n\treplayResult?: Replay & (ContractOutput<Replay> extends ContractOutput<Output> ? unknown : never)\n\twire?: { schema: Wire; project: (value: ContractOutput<Output>) => ContractInput<Wire> }\n\tguard?: (context: Context & Extension, input: ContractOutput<Input>) => Guard\n\tprepare?: (context: Context, input: ContractOutput<Input>) => Preparation\n\taudit?: (\n\t\tresolution: { command: ContractOutput<Input>; result: ContractOutput<Output> },\n\t\tcontext: Context,\n\t) => AuditResult\n} & (keyof Extension extends never\n\t? {\n\t\t\tmiddleware?: (\n\t\t\t\tinput: EffectMiddlewareInput<\n\t\t\t\t\tContext,\n\t\t\t\t\tContractOutput<Input>,\n\t\t\t\t\tContractInput<Output>,\n\t\t\t\t\tExtension,\n\t\t\t\t\tBaseError | CallbackError<Handler | Guard>,\n\t\t\t\t\tBaseRequirements | CallbackRequirements<Handler | Guard>\n\t\t\t\t>,\n\t\t\t) => Middleware\n\t\t}\n\t: {\n\t\t\tmiddleware: (\n\t\t\t\tinput: EffectMiddlewareInput<\n\t\t\t\t\tContext,\n\t\t\t\t\tContractOutput<Input>,\n\t\t\t\t\tContractInput<Output>,\n\t\t\t\t\tExtension,\n\t\t\t\t\tBaseError | CallbackError<Handler | Guard>,\n\t\t\t\t\tBaseRequirements | CallbackRequirements<Handler | Guard>\n\t\t\t\t>,\n\t\t\t) => Middleware\n\t\t})\n\n/**\n * Bind context once; middleware wraps the handler/guard channels and may discharge them.\n * Declare contextual guards/handlers before middleware, or annotate their parameters\n * and returned Effect channels when middleware comes first. TypeScript processes\n * context-sensitive object callbacks in declaration order.\n */\nexport function effectOperationFactory<\n\tContext,\n\tExtension extends Record<string, unknown> = Record<never, never>,\n\tBaseError = never,\n\tBaseRequirements = never,\n\tAuditRequired extends boolean = true,\n>() {\n\tfunction operation<\n\t\tconst Input extends ContractSchema,\n\t\tconst Output extends ContractSchema,\n\t\tHandler extends Supported<ContractInput<Output>>,\n\t\tGuard extends Supported<void> = never,\n\t\tPreparation extends Supported<EffectPreparation<ContractOutput<Output>, unknown, unknown>> =\n\t\t\tnever,\n\t\tconst Aggregates extends readonly string[] = readonly string[],\n\t\tAuditResult extends Supported<Audit<Aggregates> | null> = never,\n\t\tMiddleware extends Supported<ContractInput<Output>> = never,\n\t\tconst Metadata extends object = Record<never, never>,\n\t\t// Retain whether middleware is guaranteed, conditional, or omitted.\n\t\tconst Wire extends ContractSchema = ContractSchema,\n\t\tconst Replay extends ContractSchema = never,\n\t\tconst Definition extends object = object,\n\t>(\n\t\tdefinition: Definition &\n\t\t\tOperationDefinition<\n\t\t\t\tContext,\n\t\t\t\tInput,\n\t\t\t\tOutput,\n\t\t\t\tExtension,\n\t\t\t\tAggregates,\n\t\t\t\tHandler,\n\t\t\t\tGuard,\n\t\t\t\tPreparation,\n\t\t\t\tAuditResult,\n\t\t\t\tMiddleware,\n\t\t\t\tMetadata,\n\t\t\t\tBaseError,\n\t\t\t\tBaseRequirements,\n\t\t\t\tWire,\n\t\t\t\tReplay\n\t\t\t>,\n\t) {\n\t\t// SAFETY: the marker is type-only proof of the helper's checked callback contract.\n\t\treturn definition as CheckedEffectDefinition<\n\t\t\tContext,\n\t\t\ttypeof definition,\n\t\t\tBaseError,\n\t\t\tBaseRequirements\n\t\t>\n\t}\n\tfunction command<\n\t\tconst Input extends ContractSchema,\n\t\tconst Output extends ContractSchema,\n\t\tHandler extends Supported<ContractInput<Output>>,\n\t\tGuard extends Supported<void> = never,\n\t\tPreparation extends Supported<EffectPreparation<ContractOutput<Output>, unknown, unknown>> =\n\t\t\tnever,\n\t\tconst Aggregates extends readonly string[] = readonly string[],\n\t\tAuditResult extends Supported<Audit<Aggregates> | null> = never,\n\t\tMiddleware extends Supported<ContractInput<Output>> = never,\n\t\tconst Metadata extends object = Record<never, never>,\n\t\t// Retain whether middleware is guaranteed, conditional, or omitted.\n\t\tconst Wire extends ContractSchema = ContractSchema,\n\t\tconst Replay extends ContractSchema = never,\n\t\tconst Definition extends object = object,\n\t>(\n\t\tdefinition: Definition &\n\t\t\tOperationDefinition<\n\t\t\t\tContext,\n\t\t\t\tInput,\n\t\t\t\tOutput,\n\t\t\t\tExtension,\n\t\t\t\tAggregates,\n\t\t\t\tHandler,\n\t\t\t\tGuard,\n\t\t\t\tPreparation,\n\t\t\t\tAuditResult,\n\t\t\t\tMiddleware,\n\t\t\t\tMetadata,\n\t\t\t\tBaseError,\n\t\t\t\tBaseRequirements,\n\t\t\t\tWire,\n\t\t\t\tReplay\n\t\t\t> & {\n\t\t\t\tclassification: string\n\t\t\t} & (AuditRequired extends true\n\t\t\t\t? {\n\t\t\t\t\t\taudit: (\n\t\t\t\t\t\t\tresolution: { command: ContractOutput<Input>; result: ContractOutput<Output> },\n\t\t\t\t\t\t\tcontext: Context,\n\t\t\t\t\t\t) => AuditResult\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t) {\n\t\t// SAFETY: the marker is type-only proof of the helper's checked callback contract.\n\t\t// oxlint-disable-next-line anti-slop/no-chained-type-assertions -- SAFETY: The private marker is type-only callback evidence, not a runtime field.\n\t\treturn definition as unknown as CheckedEffectDefinition<\n\t\t\tContext,\n\t\t\ttypeof definition,\n\t\t\tBaseError,\n\t\t\tBaseRequirements\n\t\t>\n\t}\n\tfunction query<\n\t\tconst Input extends ContractSchema,\n\t\tconst Output extends ContractSchema,\n\t\tHandler extends Supported<ContractInput<Output>>,\n\t\tGuard extends Supported<void> = never,\n\t\tMiddleware extends Supported<ContractInput<Output>> = never,\n\t\tconst Metadata extends object = Record<never, never>,\n\t\tconst Wire extends ContractSchema = ContractSchema,\n\t\tconst Replay extends ContractSchema = never,\n\t\tconst Definition extends object = object,\n\t>(\n\t\tdefinition: Definition &\n\t\t\tOperationDefinition<\n\t\t\t\tContext,\n\t\t\t\tInput,\n\t\t\t\tOutput,\n\t\t\t\tExtension,\n\t\t\t\treadonly string[],\n\t\t\t\tHandler,\n\t\t\t\tGuard,\n\t\t\t\tnever,\n\t\t\t\tnever,\n\t\t\t\tMiddleware,\n\t\t\t\tMetadata,\n\t\t\t\tBaseError,\n\t\t\t\tBaseRequirements,\n\t\t\t\tWire,\n\t\t\t\tReplay\n\t\t\t> & {\n\t\t\t\tprepare?: never\n\t\t\t\taudit?: never\n\t\t\t\taggregates?: never\n\t\t\t\treplayResult?: never\n\t\t\t},\n\t) {\n\t\t// SAFETY: the marker is type-only proof of the helper's checked callback contract.\n\t\treturn definition as CheckedEffectDefinition<\n\t\t\tContext,\n\t\t\ttypeof definition,\n\t\t\tBaseError,\n\t\t\tBaseRequirements\n\t\t>\n\t}\n\treturn { operation, command, query }\n}\n"],"mappings":"AA0NA,SAAgBA,GAMZ,CACH,SAASC,EAgBR,EAkBC,CAED,OAAOC,CAMR,CACA,SAASC,EAgBR,EA2BC,CAGD,OAAOD,CAMR,CACA,SAASE,EAWR,EAuBC,CAED,OAAOF,CAMR,CACA,MAAO,CAAE,YAAW,UAAS,OAAM,CACpC"}
|
|
1
|
+
{"version":3,"file":"operation.mjs","names":["effectOperationFactory","operation","definition","command","query","effectActionFactory","action"],"sources":["../../../src/modules/effect/operation.ts"],"sourcesContent":["import type { Effect } from 'effect'\nimport type { ContractSchema, ContractInput, ContractOutput } from '../contracts/contract'\nimport type { ContractDecoderError, ContractDecoderRequirements } from './schema'\nimport type { AuditEntryInput } from '../../components/foundation/client'\nimport type { RequestScope } from './scope'\n\n/** Ordinary failures are defects; only an explicit Effect supplies a typed error. */\nexport type CallbackError<Value> = Value extends (...arguments_: never[]) => infer Returned\n\t? CallbackError<Returned>\n\t: Value extends Effect.Effect<infer Success, infer Error, unknown>\n\t\t? Error | CallbackError<Success>\n\t\t: Value extends PromiseLike<infer Awaited>\n\t\t\t? CallbackError<Awaited>\n\t\t\t: Value extends readonly (infer Item)[]\n\t\t\t\t? CallbackError<Item>\n\t\t\t\t: Value extends { kind: 'execute'; complete?: infer Complete }\n\t\t\t\t\t? CallbackError<Complete>\n\t\t\t\t\t: never\n\nexport type CallbackRequirements<Value> = Value extends (...arguments_: never[]) => infer Returned\n\t? CallbackRequirements<Returned>\n\t: Value extends Effect.Effect<infer Success, unknown, infer Requirements>\n\t\t? Requirements | CallbackRequirements<Success>\n\t\t: Value extends PromiseLike<infer Awaited>\n\t\t\t? CallbackRequirements<Awaited>\n\t\t\t: Value extends readonly (infer Item)[]\n\t\t\t\t? CallbackRequirements<Item>\n\t\t\t\t: Value extends { kind: 'execute'; complete?: infer Complete }\n\t\t\t\t\t? CallbackRequirements<Complete>\n\t\t\t\t\t: never\n\nexport type EffectValue<Value> =\n\tValue extends Effect.Effect<infer Success, unknown, unknown>\n\t\t? EffectValue<Success>\n\t\t: Value extends PromiseLike<infer Awaited>\n\t\t\t? EffectValue<Awaited>\n\t\t\t: Value\n\ndeclare const checkedOperation: unique symbol\n/** Type-only evidence that the helper checked callbacks against the base context and schemas. */\nexport type CheckedEffectOperation<Context> = {\n\treadonly [checkedOperation]: {\n\t\tcontext: (context: Context) => void\n\t\terror: unknown\n\t\trequirements: unknown\n\t\tdefinition: unknown\n\t}\n}\ntype CheckedChannels<Context, Error, Requirements, Definition> = {\n\treadonly [checkedOperation]: {\n\t\tcontext: (context: Context) => void\n\t\terror: Error\n\t\trequirements: Requirements\n\t\tdefinition: Definition\n\t}\n}\n/** Named checked-definition boundary keeps the private evidence marker inside this module's declarations. */\nexport type CheckedEffectDefinition<\n\tContext,\n\tDefinition,\n\tError = never,\n\tRequirements = never,\n> = NoInfer<Omit<Definition, typeof checkedOperation>> &\n\tCheckedChannels<Context, Error, Requirements, Omit<Definition, typeof checkedOperation>>\n/** Reject stale helper evidence after callbacks or schemas are replaced. */\nexport type ValidatedEffectOperations<Operations> = {\n\t[Key in keyof Operations]: Operations[Key] extends {\n\t\treadonly [checkedOperation]: { definition: infer Definition }\n\t}\n\t\t? Operations[Key] extends Definition\n\t\t\t? Operations[Key]\n\t\t\t: never\n\t\t: never\n}\n/** Only middleware whose next contract captured a default policy can discharge its channels. */\nexport type UnwrappedDefaultError<Definition, Guard> = Definition extends { middleware: Function }\n\t? Definition extends CheckedChannels<never, infer Error, unknown, unknown>\n\t\t? Exclude<CallbackError<Guard>, Error>\n\t\t: CallbackError<Guard>\n\t: CallbackError<Guard>\nexport type UnwrappedDefaultRequirements<Definition, Guard> = Definition extends {\n\tmiddleware: Function\n}\n\t? Definition extends CheckedChannels<never, unknown, infer Requirements, unknown>\n\t\t? Exclude<CallbackRequirements<Guard>, Requirements>\n\t\t: CallbackRequirements<Guard>\n\t: CallbackRequirements<Guard>\nexport type EffectOperationArgument<Definition extends { input: ContractSchema }> = ContractInput<\n\tDefinition['input']\n>\nexport type EffectOperationInput<Definition extends { input: ContractSchema }> = ContractOutput<\n\tDefinition['input']\n>\nexport type EffectOperationHandlerResult<Definition extends { result: ContractSchema }> =\n\tContractInput<Definition['result']>\nexport type EffectOperationResult<Definition extends { result: ContractSchema }> = ContractOutput<\n\tDefinition['result']\n>\n\ntype Hook<Definition, Key extends PropertyKey> = Key extends keyof Definition\n\t? Definition[Key]\n\t: never\ntype Returned<Callback> = Callback extends (...arguments_: never[]) => infer Value ? Value : never\n/** A conditional wrapper must retain the unwrapped channels for its absent branch. */\ntype CoreValue<Definition> = [Returned<Hook<Definition, 'middleware'>>] extends [never]\n\t? Returned<Hook<Definition, 'handler'>> | Returned<Hook<Definition, 'guard'>>\n\t: undefined extends Hook<Definition, 'middleware'>\n\t\t?\n\t\t\t\t| Returned<Hook<Definition, 'handler'>>\n\t\t\t\t| Returned<Hook<Definition, 'guard'>>\n\t\t\t\t| Returned<Hook<Definition, 'middleware'>>\n\t\t: Returned<Hook<Definition, 'middleware'>>\ntype OutsideHooks = 'prepare' | 'audit' | 'checkPermission' | 'writeAudit'\nexport type EffectOperationError<Definition> =\n\t| ContractDecoderError<Hook<Definition, 'input'>>\n\t| ContractDecoderError<Hook<Definition, 'result'>>\n\t| ContractDecoderError<Hook<Definition, 'replayResult'>>\n\t| CallbackError<CoreValue<Definition>>\n\t| CallbackError<Definition[Extract<keyof Definition, OutsideHooks>]>\nexport type EffectOperationRequirements<Definition> =\n\t| ContractDecoderRequirements<Hook<Definition, 'input'>>\n\t| ContractDecoderRequirements<Hook<Definition, 'result'>>\n\t| ContractDecoderRequirements<Hook<Definition, 'replayResult'>>\n\t| CallbackRequirements<CoreValue<Definition>>\n\t| CallbackRequirements<Definition[Extract<keyof Definition, OutsideHooks>]>\n\ntype Supported<Value, Error = unknown, Requirements = unknown> =\n\t| Value\n\t| PromiseLike<Value>\n\t| Effect.Effect<Value, Error, Requirements>\nexport type EffectPreparation<Result, Error = never, Requirements = never> =\n\t| { kind: 'replay'; result: unknown }\n\t| { kind: 'execute'; complete?: (result: Result) => Supported<void, Error, Requirements> }\nexport type EffectMiddlewareInput<\n\tContext,\n\tInput,\n\tResult,\n\tExtension,\n\tError = never,\n\tRequirements = never,\n> = {\n\toperation: string\n\tcontext: Context\n\tcommand: Input\n\tinput: Input\n\tnext: keyof Extension extends never\n\t\t? (options?: { context?: Extension }) => Effect.Effect<Result, Error, Requirements>\n\t\t: (options: { context: Extension }) => Effect.Effect<Result, Error, Requirements>\n}\ntype Audit<Aggregates extends readonly string[]> = Omit<\n\tAuditEntryInput,\n\t'classification' | 'aggregate'\n> & {\n\taggregate: { type: Aggregates[number]; id: string }\n}\nexport type OperationDefinition<\n\tContext,\n\tInput extends ContractSchema,\n\tOutput extends ContractSchema,\n\tExtension,\n\tAggregates extends readonly string[],\n\tHandler,\n\tGuard,\n\tPreparation,\n\tAuditResult,\n\tMiddleware,\n\tMetadata,\n\tBaseError,\n\tBaseRequirements,\n\tWire extends ContractSchema,\n\tReplay extends ContractSchema,\n> = {\n\tinput: Input\n\tresult: Output\n\thandler: (input: ContractOutput<Input>, context: Context & Extension) => Handler\n\tclassification?: string\n\tpermission?: string\n\tmetadata?: Metadata\n\taggregates?: Aggregates\n\treplayResult?: Replay & (ContractOutput<Replay> extends ContractOutput<Output> ? unknown : never)\n\twire?: { schema: Wire; project: (value: ContractOutput<Output>) => ContractInput<Wire> }\n\tguard?: (context: Context & Extension, input: ContractOutput<Input>) => Guard\n\tprepare?: (context: Context, input: ContractOutput<Input>) => Preparation\n\taudit?: (\n\t\tresolution: { command: ContractOutput<Input>; result: ContractOutput<Output> },\n\t\tcontext: Context,\n\t\tscope: RequestScope | undefined,\n\t) => AuditResult\n} & (keyof Extension extends never\n\t? {\n\t\t\tmiddleware?: (\n\t\t\t\tinput: EffectMiddlewareInput<\n\t\t\t\t\tContext,\n\t\t\t\t\tContractOutput<Input>,\n\t\t\t\t\tContractInput<Output>,\n\t\t\t\t\tExtension,\n\t\t\t\t\tBaseError | CallbackError<Handler | Guard>,\n\t\t\t\t\tBaseRequirements | CallbackRequirements<Handler | Guard>\n\t\t\t\t>,\n\t\t\t) => Middleware\n\t\t}\n\t: {\n\t\t\tmiddleware: (\n\t\t\t\tinput: EffectMiddlewareInput<\n\t\t\t\t\tContext,\n\t\t\t\t\tContractOutput<Input>,\n\t\t\t\t\tContractInput<Output>,\n\t\t\t\t\tExtension,\n\t\t\t\t\tBaseError | CallbackError<Handler | Guard>,\n\t\t\t\t\tBaseRequirements | CallbackRequirements<Handler | Guard>\n\t\t\t\t>,\n\t\t\t) => Middleware\n\t\t})\n\n/**\n * Bind context once; middleware wraps the handler/guard channels and may discharge them.\n * Declare contextual guards/handlers before middleware, or annotate their parameters\n * and returned Effect channels when middleware comes first. TypeScript processes\n * context-sensitive object callbacks in declaration order.\n */\nexport function effectOperationFactory<\n\tContext,\n\tExtension extends Record<string, unknown> = Record<never, never>,\n\tBaseError = never,\n\tBaseRequirements = never,\n\tAuditRequired extends boolean = true,\n>() {\n\tfunction operation<\n\t\tconst Input extends ContractSchema,\n\t\tconst Output extends ContractSchema,\n\t\tHandler extends Supported<ContractInput<Output>>,\n\t\tGuard extends Supported<void> = never,\n\t\tPreparation extends Supported<EffectPreparation<ContractOutput<Output>, unknown, unknown>> =\n\t\t\tnever,\n\t\tconst Aggregates extends readonly string[] = readonly string[],\n\t\tAuditResult extends Supported<Audit<Aggregates> | null> = never,\n\t\tMiddleware extends Supported<ContractInput<Output>> = never,\n\t\tconst Metadata extends object = Record<never, never>,\n\t\t// Retain whether middleware is guaranteed, conditional, or omitted.\n\t\tconst Wire extends ContractSchema = ContractSchema,\n\t\tconst Replay extends ContractSchema = never,\n\t\tconst Definition extends object = object,\n\t>(\n\t\tdefinition: Definition &\n\t\t\tOperationDefinition<\n\t\t\t\tContext,\n\t\t\t\tInput,\n\t\t\t\tOutput,\n\t\t\t\tExtension,\n\t\t\t\tAggregates,\n\t\t\t\tHandler,\n\t\t\t\tGuard,\n\t\t\t\tPreparation,\n\t\t\t\tAuditResult,\n\t\t\t\tMiddleware,\n\t\t\t\tMetadata,\n\t\t\t\tBaseError,\n\t\t\t\tBaseRequirements,\n\t\t\t\tWire,\n\t\t\t\tReplay\n\t\t\t>,\n\t) {\n\t\t// SAFETY: the marker is type-only proof of the helper's checked callback contract.\n\t\treturn definition as CheckedEffectDefinition<\n\t\t\tContext,\n\t\t\ttypeof definition,\n\t\t\tBaseError,\n\t\t\tBaseRequirements\n\t\t>\n\t}\n\tfunction command<\n\t\tconst Input extends ContractSchema,\n\t\tconst Output extends ContractSchema,\n\t\tHandler extends Supported<ContractInput<Output>>,\n\t\tGuard extends Supported<void> = never,\n\t\tPreparation extends Supported<EffectPreparation<ContractOutput<Output>, unknown, unknown>> =\n\t\t\tnever,\n\t\tconst Aggregates extends readonly string[] = readonly string[],\n\t\tAuditResult extends Supported<Audit<Aggregates> | null> = never,\n\t\tMiddleware extends Supported<ContractInput<Output>> = never,\n\t\tconst Metadata extends object = Record<never, never>,\n\t\t// Retain whether middleware is guaranteed, conditional, or omitted.\n\t\tconst Wire extends ContractSchema = ContractSchema,\n\t\tconst Replay extends ContractSchema = never,\n\t\tconst Definition extends object = object,\n\t>(\n\t\tdefinition: Definition &\n\t\t\tOperationDefinition<\n\t\t\t\tContext,\n\t\t\t\tInput,\n\t\t\t\tOutput,\n\t\t\t\tExtension,\n\t\t\t\tAggregates,\n\t\t\t\tHandler,\n\t\t\t\tGuard,\n\t\t\t\tPreparation,\n\t\t\t\tAuditResult,\n\t\t\t\tMiddleware,\n\t\t\t\tMetadata,\n\t\t\t\tBaseError,\n\t\t\t\tBaseRequirements,\n\t\t\t\tWire,\n\t\t\t\tReplay\n\t\t\t> & {\n\t\t\t\tclassification: string\n\t\t\t} & (AuditRequired extends true\n\t\t\t\t? {\n\t\t\t\t\t\taudit: (\n\t\t\t\t\t\t\tresolution: { command: ContractOutput<Input>; result: ContractOutput<Output> },\n\t\t\t\t\t\t\tcontext: Context,\n\t\t\t\t\t\t\tscope: RequestScope | undefined,\n\t\t\t\t\t\t) => AuditResult\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t) {\n\t\t// SAFETY: the marker is type-only proof of the helper's checked callback contract.\n\t\t// oxlint-disable-next-line anti-slop/no-chained-type-assertions -- SAFETY: The private marker is type-only callback evidence, not a runtime field.\n\t\treturn definition as unknown as CheckedEffectDefinition<\n\t\t\tContext,\n\t\t\ttypeof definition,\n\t\t\tBaseError,\n\t\t\tBaseRequirements\n\t\t>\n\t}\n\tfunction query<\n\t\tconst Input extends ContractSchema,\n\t\tconst Output extends ContractSchema,\n\t\tHandler extends Supported<ContractInput<Output>>,\n\t\tGuard extends Supported<void> = never,\n\t\tMiddleware extends Supported<ContractInput<Output>> = never,\n\t\tconst Metadata extends object = Record<never, never>,\n\t\tconst Wire extends ContractSchema = ContractSchema,\n\t\tconst Replay extends ContractSchema = never,\n\t\tconst Definition extends object = object,\n\t>(\n\t\tdefinition: Definition &\n\t\t\tOperationDefinition<\n\t\t\t\tContext,\n\t\t\t\tInput,\n\t\t\t\tOutput,\n\t\t\t\tExtension,\n\t\t\t\treadonly string[],\n\t\t\t\tHandler,\n\t\t\t\tGuard,\n\t\t\t\tnever,\n\t\t\t\tnever,\n\t\t\t\tMiddleware,\n\t\t\t\tMetadata,\n\t\t\t\tBaseError,\n\t\t\t\tBaseRequirements,\n\t\t\t\tWire,\n\t\t\t\tReplay\n\t\t\t> & {\n\t\t\t\tprepare?: never\n\t\t\t\taudit?: never\n\t\t\t\taggregates?: never\n\t\t\t\treplayResult?: never\n\t\t\t},\n\t) {\n\t\t// SAFETY: the marker is type-only proof of the helper's checked callback contract.\n\t\treturn definition as CheckedEffectDefinition<\n\t\t\tContext,\n\t\t\ttypeof definition,\n\t\t\tBaseError,\n\t\t\tBaseRequirements\n\t\t>\n\t}\n\treturn { operation, command, query }\n}\n\nexport function effectActionFactory<Context, BaseError = never, BaseRequirements = never>() {\n\ttype Extension = Record<never, never>\n\t/** Actions have no transaction to replay and no permission host; guards authorize them. */\n\tfunction action<\n\t\tconst Input extends ContractSchema,\n\t\tconst Output extends ContractSchema,\n\t\tHandler extends Supported<ContractInput<Output>>,\n\t\tGuard extends Supported<void> = never,\n\t\tconst Aggregates extends readonly string[] = readonly string[],\n\t\tAuditResult extends Supported<Audit<Aggregates> | null> = never,\n\t\tMiddleware extends Supported<ContractInput<Output>> = never,\n\t\tconst Metadata extends object = Record<never, never>,\n\t\tconst Wire extends ContractSchema = ContractSchema,\n\t\tconst Definition extends object = object,\n\t>(\n\t\tdefinition: Definition &\n\t\t\tOperationDefinition<\n\t\t\t\tContext,\n\t\t\t\tInput,\n\t\t\t\tOutput,\n\t\t\t\tExtension,\n\t\t\t\tAggregates,\n\t\t\t\tHandler,\n\t\t\t\tGuard,\n\t\t\t\tnever,\n\t\t\t\tAuditResult,\n\t\t\t\tMiddleware,\n\t\t\t\tMetadata,\n\t\t\t\tBaseError,\n\t\t\t\tBaseRequirements,\n\t\t\t\tWire,\n\t\t\t\tnever\n\t\t\t> & {\n\t\t\t\tprepare?: never\n\t\t\t\tpermission?: never\n\t\t\t\treplayResult?: never\n\t\t\t},\n\t) {\n\t\t// SAFETY: the marker is type-only proof of the helper's checked callback contract.\n\t\treturn definition as CheckedEffectDefinition<\n\t\t\tContext,\n\t\t\ttypeof definition,\n\t\t\tBaseError,\n\t\t\tBaseRequirements\n\t\t>\n\t}\n\treturn { action }\n}\n"],"mappings":"AA4NA,SAAgBA,GAMZ,CACH,SAASC,EAgBR,EAkBC,CAED,OAAOC,CAMR,CACA,SAASC,EAgBR,EA4BC,CAGD,OAAOD,CAMR,CACA,SAASE,EAWR,EAuBC,CAED,OAAOF,CAMR,CACA,MAAO,CAAE,YAAW,UAAS,OAAM,CACpC,CAEA,SAAgBG,GAA4E,CAG3F,SAASC,EAYR,EAsBC,CAED,OAAOJ,CAMR,CACA,MAAO,CAAE,QAAO,CACjB"}
|
|
@@ -3,6 +3,7 @@ import { OperationPublicResult, SelectedOperation } from "../contracts/exposure.
|
|
|
3
3
|
import { Observability, ObservabilityOptions } from "../../components/foundation/modules/observability/observability.mjs";
|
|
4
4
|
import { DomainContract, DomainQueryContract } from "../contracts/domain.mjs";
|
|
5
5
|
import { CallbackError, CallbackRequirements, CheckedEffectOperation, EffectOperationArgument, EffectOperationError, EffectOperationRequirements, EffectOperationResult, EffectValue, UnwrappedDefaultError, UnwrappedDefaultRequirements, ValidatedEffectOperations, effectOperationFactory } from "./operation.mjs";
|
|
6
|
+
import { FailureAuditOptions } from "./failure-audit.mjs";
|
|
6
7
|
import { BoundOperations } from "../contracts/binding.mjs";
|
|
7
8
|
import { DomainEffectFactory, DomainEffectImplementations, ExactDomainOperations } from "./domain.mjs";
|
|
8
9
|
import { Effect } from "effect";
|
|
@@ -38,6 +39,8 @@ export declare function createEffectQuery<Host, ContextReturned, const Operation
|
|
|
38
39
|
guard?: (context: EffectValue<ContextReturned>) => GuardReturned;
|
|
39
40
|
};
|
|
40
41
|
observability?: ObservabilityOptions | Observability;
|
|
42
|
+
auditFailure?: FailureAuditOptions;
|
|
43
|
+
contract?: Pick<DomainContract, 'errors'>;
|
|
41
44
|
}): {
|
|
42
45
|
exec: <const Key extends OperationKey<Operations>>(operation: Key, input: EffectOperationArgument<Operations[Key]>, host: Host) => Effect.Effect<EffectOperationResult<Operations[Key]>, EffectOperationError<Operations[Key]> | CallbackError<ContextReturned | PermissionReturned> | UnwrappedDefaultError<Operations[Key], GuardReturned>, EffectOperationRequirements<Operations[Key]> | CallbackRequirements<ContextReturned | PermissionReturned> | UnwrappedDefaultRequirements<Operations[Key], GuardReturned>>;
|
|
43
46
|
expose: <const Owner extends symbol, const Key extends OperationKey<Operations>>(owner: Owner, operation: Key) => SelectedOperation<Owner, Key, Operations[Key]['input'], OperationPublicResult<Operations[Key]>>;
|
|
@@ -53,6 +56,7 @@ type PolicyHost<Dependencies> = [CallbackHost<Policy<Dependencies>>] extends [ne
|
|
|
53
56
|
type PolicyReturned<Dependencies> = CallbackReturned<Policy<Dependencies>>;
|
|
54
57
|
export type EffectQueryDependencies = {
|
|
55
58
|
observability: Observability;
|
|
59
|
+
auditFailure?: FailureAuditOptions;
|
|
56
60
|
checkPermission?: (host: never, input: {
|
|
57
61
|
permission: string;
|
|
58
62
|
operation: string;
|
|
@@ -65,7 +69,7 @@ export declare function bindEffectQuery<const Dependencies extends EffectQueryDe
|
|
|
65
69
|
}, const Operations extends DomainEffectImplementations<EffectValue<ContextReturned>, Contract['queries']>, Mode extends false, GuardReturned extends Supported<void> = never>(configuration: {
|
|
66
70
|
contract: Contract & NoInfer<Operations extends ExactDomainOperations<Operations, Contract['queries']> & ValidatedEffectOperations<Operations> ? unknown : never>;
|
|
67
71
|
context: (host: Host) => ContextReturned;
|
|
68
|
-
operations: (define: DomainEffectFactory<EffectValue<ContextReturned>, Contract['queries'], Mode, never, NoInfer<CallbackError<GuardReturned>>, NoInfer<CallbackRequirements<GuardReturned
|
|
72
|
+
operations: (define: DomainEffectFactory<EffectValue<ContextReturned>, Contract['queries'], Mode, never, NoInfer<CallbackError<GuardReturned>>, NoInfer<CallbackRequirements<GuardReturned>>, Contract['errors']>) => Operations;
|
|
69
73
|
defaults?: {
|
|
70
74
|
metadata?: object;
|
|
71
75
|
guard?: (context: EffectValue<ContextReturned>) => GuardReturned;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{selectOperation as e}from"../contracts/exposure.mjs";import{memoize as t,registerLazyRegistry as n}from"../contracts/lazy.mjs";import{normalizeEffect as r,observationFailure as i}from"./normalize.mjs";import{effectOperationFactory as a}from"./operation.mjs";import{Observability as o}from"../../components/foundation/modules/observability/observability.mjs";import{decodeEffectContract as s}from"./schema.mjs";import{
|
|
1
|
+
import{selectOperation as e}from"../contracts/exposure.mjs";import{memoize as t,registerLazyRegistry as n}from"../contracts/lazy.mjs";import{normalizeEffect as r,observationFailure as i}from"./normalize.mjs";import{effectOperationFactory as a}from"./operation.mjs";import{Observability as o}from"../../components/foundation/modules/observability/observability.mjs";import{decodeEffectContract as s}from"./schema.mjs";import{reportFailure as c}from"./failure-audit.mjs";import{enterRequestScope as l}from"./scope.mjs";import{snapshotOperations as u}from"../contracts/binding.mjs";import{domainEffectFactory as d}from"./domain.mjs";import{Effect as f,Exit as p}from"effect";var m=class extends Error{code=`QUERY_MIDDLEWARE_NEXT_REUSED`;name=`QueryMiddlewareError`;constructor(){super(`A query middleware called next() more than once`)}},h=class extends Error{code=`QUERY_OPERATION_NOT_CONFIGURED`;name=`QueryConfigurationError`;constructor(){super(`The selected query operation is not configured`)}},g=class extends Error{code=`QUERY_PERMISSION_CHECKER_MISSING`;name=`QueryPermissionError`;constructor(){super(`Query permission requires an injected permission checker`)}};function _(u){let d=a(),_=t(()=>u.operations(d)),v=u.observability instanceof o?u.observability:new o(u.observability??{enabled:!1,classifyError:()=>({outcome:`failed`,errorCode:`UNEXPECTED`})});function y(e,t,n){return f.suspend(()=>{let a=_();if(!Object.prototype.hasOwnProperty.call(a,e))return f.die(new h);let o=a[e];return f.flatMap(s(o.input,t),t=>{let a=v.start({operation:e,classification:o.classification??`query`}),d=f.gen(function*(){if(o.permission!==void 0){let t=u.checkPermission;if(!t)return yield*f.die(new g);yield*r(()=>t(n,{permission:o.permission,operation:e}))}let i=yield*r(()=>u.context(n)),a={...u.defaults?.metadata,...o.metadata},c=e=>f.gen(function*(){let n=u.defaults?.guard;return n&&(yield*r(()=>n(e))),o.guard&&(yield*r(()=>o.guard(e,t))),yield*r(()=>o.handler(t,e))}),l=!1,d=o.middleware,p=d?yield*r(()=>d({operation:e,input:t,command:t,context:i,metadata:a,next:e=>f.suspend(()=>l?f.die(new m):(l=!0,c(e?.context?Object.assign({},i,e.context):i)))})):yield*c(i);return yield*s(o.result,p)});return l(e,!1,(n,r)=>d.pipe(f.onExit(s=>f.sync(()=>{p.isSuccess(s)?a.completed():a.failed(i(s.cause))}).pipe(f.andThen(c(u.auditFailure,s,{kind:`query`,operation:e,classification:o.classification??`query`,input:t,contract:u.contract?.errors,entered:n,current:r}))))))})})}function b(t,n){let r=_();if(!Object.hasOwn(r,n))throw new h;return e(t,`query`,n,r[n])}return n({exec:y,expose:b,withContext(e){return{exec:(t,n)=>y(t,n,e)}}},_)}function v(e){function t(t){let n=()=>{let e=t.contract?d(t.contract.queries??{},!1,t.contract.errors):a();return u(t.operations(e),t.contract,`queries`)};return _({...t,...e,operations:n})}return t}export{v as bindEffectQuery,_ as createEffectQuery};
|
|
2
2
|
//# sourceMappingURL=query.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"query.mjs","names":["QueryMiddlewareError","QueryConfigurationError","QueryPermissionError","createEffectQuery","definitions","effectOperationFactory","getOperations","memoize","configuration","observability","Observability","exec","Effect","operations","operation","definition","decodeEffectContract","input","observation","check","normalizeEffect","host","context","metadata","core","guard","current","parsedInput","usedNext","middleware","output","options","Exit","exit","observationFailure","expose","selectOperation","owner","registerLazyRegistry","bindEffectQuery","query","buildOperations","domainEffectFactory","snapshotOperations","dependencies"],"sources":["../../../src/modules/effect/query.ts"],"sourcesContent":["import { memoize, registerLazyRegistry } from '../contracts/lazy'\n/* oxlint-disable anti-slop/no-unknown-returns, anti-slop/no-unsafe-dictionary-type -- Overload implementation storage is erased; public signatures retain concrete values, errors and services. */\nimport { Effect, Exit } from 'effect'\nimport type { ContractSchema } from '../contracts/contract'\nimport {\n\tselectOperation,\n\ttype SelectedOperation,\n\ttype OperationPublicResult,\n} from '../contracts/exposure'\nimport { decodeEffectContract } from './schema'\n// oxlint-disable-next-line cvx/component-boundaries -- SAFETY: Internal optional adapter shares the Effect-free Foundation lifecycle and types without entering the Convex component deployment graph.\nimport {\n\tObservability,\n\ttype ObservabilityOptions,\n} from '../../components/foundation/modules/observability/observability'\nimport { normalizeEffect, observationFailure } from './normalize'\nimport {\n\teffectOperationFactory,\n\ttype CallbackError,\n\ttype CallbackRequirements,\n\ttype EffectOperationArgument,\n\ttype EffectOperationError,\n\ttype EffectOperationRequirements,\n\ttype EffectOperationResult,\n\ttype EffectValue,\n\ttype CheckedEffectOperation,\n\ttype UnwrappedDefaultError,\n\ttype UnwrappedDefaultRequirements,\n\ttype ValidatedEffectOperations,\n} from './operation'\n\nimport type { DomainContract, DomainQueryContract } from '../contracts/domain'\nimport { snapshotOperations, type BoundOperations } from '../contracts/binding'\nimport {\n\tdomainEffectFactory,\n\ttype DomainEffectFactory,\n\ttype DomainEffectImplementations,\n\ttype ExactDomainOperations,\n} from './domain'\n\ntype Supported<Value> = Value | PromiseLike<Value> | Effect.Effect<Value, unknown, unknown>\ntype QueryDefinition = {\n\tinput: ContractSchema\n\tresult: ContractSchema\n\t// oxlint-disable-next-line anti-slop/no-unknown-returns -- Internal heterogeneous storage; selected schemas restore the concrete result at exec.\n\thandler: (input: never, context: never) => unknown\n\tclassification?: string\n\tpermission?: string\n\tmetadata?: object\n\t// oxlint-disable-next-line anti-slop/no-unknown-returns -- Internal hook storage retains the concrete definition separately.\n\tguard?: (context: never, input: never) => unknown\n\t// oxlint-disable-next-line anti-slop/no-unknown-returns -- Internal hook storage retains the concrete definition separately.\n\tmiddleware?: (input: never) => unknown\n}\ntype QueryRegistry<Context> = Readonly<\n\tRecord<\n\t\tstring,\n\t\tPick<QueryDefinition, 'input' | 'result' | 'handler'> &\n\t\t\tCheckedEffectOperation<Context> & {\n\t\t\t\tprepare?: never\n\t\t\t\taudit?: never\n\t\t\t\taggregates?: never\n\t\t\t\treplayResult?: never\n\t\t\t}\n\t>\n>\ntype OperationKey<Operations> = Extract<keyof Operations, string>\n\nclass QueryMiddlewareError extends Error {\n\treadonly code = 'QUERY_MIDDLEWARE_NEXT_REUSED'\n\treadonly name = 'QueryMiddlewareError'\n\tconstructor() {\n\t\tsuper('A query middleware called next() more than once')\n\t}\n}\nclass QueryConfigurationError extends Error {\n\treadonly code = 'QUERY_OPERATION_NOT_CONFIGURED'\n\treadonly name = 'QueryConfigurationError'\n\tconstructor() {\n\t\tsuper('The selected query operation is not configured')\n\t}\n}\nclass QueryPermissionError extends Error {\n\treadonly code = 'QUERY_PERMISSION_CHECKER_MISSING'\n\treadonly name = 'QueryPermissionError'\n\tconstructor() {\n\t\tsuper('Query permission requires an injected permission checker')\n\t}\n}\n\n/** Injectable domain queries compose lazily; the API chooses native function kind. */\nexport function createEffectQuery<\n\tHost,\n\tContextReturned,\n\tconst Operations extends QueryRegistry<EffectValue<ContextReturned>>,\n\tPermissionReturned = never,\n\tGuardReturned extends Supported<void> = never,\n>(configuration: {\n\tcontext: (host: Host) => ContextReturned\n\toperations: (\n\t\tdefinitions: ReturnType<\n\t\t\ttypeof effectOperationFactory<\n\t\t\t\tEffectValue<ContextReturned>,\n\t\t\t\tRecord<never, never>,\n\t\t\t\tNoInfer<CallbackError<GuardReturned>>,\n\t\t\t\tNoInfer<CallbackRequirements<GuardReturned>>\n\t\t\t>\n\t\t>,\n\t) => Operations & NoInfer<ValidatedEffectOperations<Operations>>\n\tcheckPermission?: (\n\t\thost: Host,\n\t\tinput: { permission: string; operation: string },\n\t) => PermissionReturned\n\tdefaults?: { metadata?: object; guard?: (context: EffectValue<ContextReturned>) => GuardReturned }\n\tobservability?: ObservabilityOptions | Observability\n}) {\n\tconst definitions = effectOperationFactory<\n\t\tEffectValue<ContextReturned>,\n\t\tRecord<never, never>,\n\t\tCallbackError<GuardReturned>,\n\t\tCallbackRequirements<GuardReturned>\n\t>()\n\tconst getOperations = memoize<Operations>(() => configuration.operations(definitions))\n\tconst observability =\n\t\tconfiguration.observability instanceof Observability\n\t\t\t? configuration.observability\n\t\t\t: new Observability(\n\t\t\t\t\tconfiguration.observability ?? {\n\t\t\t\t\t\tenabled: false,\n\t\t\t\t\t\tclassifyError: () => ({ outcome: 'failed', errorCode: 'UNEXPECTED' }),\n\t\t\t\t\t},\n\t\t\t\t)\n\n\tfunction exec<const Key extends OperationKey<Operations>>(\n\t\toperation: Key,\n\t\tinput: EffectOperationArgument<Operations[Key]>,\n\t\thost: Host,\n\t): Effect.Effect<\n\t\tEffectOperationResult<Operations[Key]>,\n\t\t| EffectOperationError<Operations[Key]>\n\t\t| CallbackError<ContextReturned | PermissionReturned>\n\t\t| UnwrappedDefaultError<Operations[Key], GuardReturned>,\n\t\t| EffectOperationRequirements<Operations[Key]>\n\t\t| CallbackRequirements<ContextReturned | PermissionReturned>\n\t\t| UnwrappedDefaultRequirements<Operations[Key], GuardReturned>\n\t> {\n\t\tconst execution = Effect.suspend(() => {\n\t\t\tconst operations = getOperations()\n\t\t\tif (!Object.prototype.hasOwnProperty.call(operations, operation)) {\n\t\t\t\treturn Effect.die(new QueryConfigurationError())\n\t\t\t}\n\t\t\t// SAFETY: operation helpers check hooks before this heterogeneous storage seam.\n\t\t\tconst definition: QueryDefinition = operations[operation]\n\t\t\treturn Effect.flatMap(decodeEffectContract(definition.input, input), (parsedInput) => {\n\t\t\t\tconst observation = observability.start({\n\t\t\t\t\toperation,\n\t\t\t\t\tclassification: definition.classification ?? 'query',\n\t\t\t\t})\n\t\t\t\tconst run = Effect.gen(function* () {\n\t\t\t\t\tif (definition.permission !== undefined) {\n\t\t\t\t\t\tconst check = configuration.checkPermission\n\t\t\t\t\t\tif (!check) return yield* Effect.die(new QueryPermissionError())\n\t\t\t\t\t\tyield* normalizeEffect(() =>\n\t\t\t\t\t\t\tcheck(host, { permission: definition.permission!, operation }),\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t\tconst context = yield* normalizeEffect(() => configuration.context(host))\n\t\t\t\t\tconst metadata = { ...configuration.defaults?.metadata, ...definition.metadata }\n\t\t\t\t\tconst core = (current: EffectValue<ContextReturned>) =>\n\t\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\t\tconst guard = configuration.defaults?.guard\n\t\t\t\t\t\t\tif (guard) yield* normalizeEffect(() => guard(current))\n\t\t\t\t\t\t\tif (definition.guard)\n\t\t\t\t\t\t\t\tyield* normalizeEffect(() => {\n\t\t\t\t\t\t\t\t\t// SAFETY: selected schemas and context own the stored guard parameters.\n\t\t\t\t\t\t\t\t\treturn definition.guard!(current as never, parsedInput as never)\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\treturn yield* normalizeEffect(() => {\n\t\t\t\t\t\t\t\t// SAFETY: selected schemas and context own the stored handler parameters.\n\t\t\t\t\t\t\t\treturn definition.handler(parsedInput as never, current as never)\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t})\n\t\t\t\t\tlet usedNext = false\n\t\t\t\t\tconst middleware = definition.middleware\n\t\t\t\t\tconst output = middleware\n\t\t\t\t\t\t? yield* normalizeEffect(() => {\n\t\t\t\t\t\t\t\t// SAFETY: the selected helper checked this middleware's input and next contract.\n\t\t\t\t\t\t\t\treturn middleware({\n\t\t\t\t\t\t\t\t\toperation,\n\t\t\t\t\t\t\t\t\tinput: parsedInput,\n\t\t\t\t\t\t\t\t\tcommand: parsedInput,\n\t\t\t\t\t\t\t\t\tcontext,\n\t\t\t\t\t\t\t\t\tmetadata,\n\t\t\t\t\t\t\t\t\tnext: (options?: { context?: object }) =>\n\t\t\t\t\t\t\t\t\t\tEffect.suspend(() => {\n\t\t\t\t\t\t\t\t\t\t\tif (usedNext) return Effect.die(new QueryMiddlewareError())\n\t\t\t\t\t\t\t\t\t\t\tusedNext = true\n\t\t\t\t\t\t\t\t\t\t\treturn core(\n\t\t\t\t\t\t\t\t\t\t\t\toptions?.context ? Object.assign({}, context, options.context) : context,\n\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t} as never)\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t: yield* core(context)\n\t\t\t\t\treturn yield* decodeEffectContract(definition.result, output)\n\t\t\t\t})\n\t\t\t\treturn run.pipe(\n\t\t\t\t\tEffect.onExit((exit) =>\n\t\t\t\t\t\tEffect.sync(() => {\n\t\t\t\t\t\t\tif (Exit.isSuccess(exit)) observation.completed()\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tobservation.failed(observationFailure(exit.cause))\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t})\n\t\t})\n\t\t// SAFETY: selected schemas own A; concrete callbacks and the wrapped middleware\n\t\t// own E/R. No interpreter or runner executes this Effect before the caller does.\n\t\treturn execution as ReturnType<typeof exec<Key>>\n\t}\n\tfunction expose<const Owner extends symbol, const Key extends OperationKey<Operations>>(\n\t\towner: Owner,\n\t\toperation: Key,\n\t): SelectedOperation<\n\t\tOwner,\n\t\tKey,\n\t\tOperations[Key]['input'],\n\t\tOperationPublicResult<Operations[Key]>\n\t> {\n\t\tconst operations = getOperations()\n\t\tif (!Object.hasOwn(operations, operation)) throw new QueryConfigurationError()\n\t\treturn selectOperation(owner, 'query', operation, operations[operation])\n\t}\n\treturn registerLazyRegistry(\n\t\t{\n\t\t\texec,\n\t\t\texpose,\n\t\t\t/** Bind invocation context without resolving it or running an operation. */\n\t\t\twithContext(context: Host) {\n\t\t\t\treturn {\n\t\t\t\t\texec: <const Key extends OperationKey<Operations>>(\n\t\t\t\t\t\toperation: Key,\n\t\t\t\t\t\tinput: EffectOperationArgument<Operations[Key]>,\n\t\t\t\t\t) => exec(operation, input, context),\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\tgetOperations,\n\t)\n}\n\ntype Policy<Dependencies> = 'checkPermission' extends keyof Dependencies\n\t? Dependencies['checkPermission']\n\t: never\n// oxlint-disable-next-line anti-slop/no-unknown-returns -- Conditional type extracts the host; no unknown result is exposed by the registry.\ntype CallbackHost<Callback> = Callback extends (host: infer Host, input: never) => unknown\n\t? Host\n\t: never\ntype CallbackReturned<Callback> = Callback extends (...arguments_: never[]) => infer Returned\n\t? Returned\n\t: never\ntype PolicyHost<Dependencies> = [CallbackHost<Policy<Dependencies>>] extends [never]\n\t? unknown\n\t: CallbackHost<Policy<Dependencies>>\ntype PolicyReturned<Dependencies> = CallbackReturned<Policy<Dependencies>>\nexport type EffectQueryDependencies = {\n\tobservability: Observability\n\t// oxlint-disable-next-line anti-slop/no-unknown-returns -- Host policy storage is erased; the bound generic dependency retains its concrete E/R.\n\tcheckPermission?: (host: never, input: { permission: string; operation: string }) => unknown\n}\n\n/** The public Foundation binds trusted application policies once. */\nexport function bindEffectQuery<const Dependencies extends EffectQueryDependencies>(\n\tdependencies: Dependencies,\n) {\n\tfunction query<\n\t\tHost extends PolicyHost<Dependencies>,\n\t\tContextReturned,\n\t\tconst Contract extends DomainContract & {\n\t\t\tqueries: Readonly<Record<string, DomainQueryContract>>\n\t\t},\n\t\tconst Operations extends DomainEffectImplementations<\n\t\t\tEffectValue<ContextReturned>,\n\t\t\tContract['queries']\n\t\t>,\n\t\tMode extends false,\n\t\tGuardReturned extends Supported<void> = never,\n\t>(configuration: {\n\t\tcontract: Contract &\n\t\t\tNoInfer<\n\t\t\t\tOperations extends ExactDomainOperations<Operations, Contract['queries']> &\n\t\t\t\t\tValidatedEffectOperations<Operations>\n\t\t\t\t\t? unknown\n\t\t\t\t\t: never\n\t\t\t>\n\t\tcontext: (host: Host) => ContextReturned\n\t\toperations: (\n\t\t\tdefine: DomainEffectFactory<\n\t\t\t\tEffectValue<ContextReturned>,\n\t\t\t\tContract['queries'],\n\t\t\t\tMode,\n\t\t\t\tnever,\n\t\t\t\tNoInfer<CallbackError<GuardReturned>>,\n\t\t\t\tNoInfer<CallbackRequirements<GuardReturned>>\n\t\t\t>,\n\t\t) => Operations\n\t\tdefaults?: {\n\t\t\tmetadata?: object\n\t\t\tguard?: (context: EffectValue<ContextReturned>) => GuardReturned\n\t\t}\n\t}): ReturnType<\n\t\ttypeof createEffectQuery<\n\t\t\tHost,\n\t\t\tContextReturned,\n\t\t\tBoundOperations<Operations, Contract['queries']>,\n\t\t\tPolicyReturned<Dependencies>,\n\t\t\tGuardReturned\n\t\t>\n\t>\n\n\tfunction query<\n\t\tHost extends PolicyHost<Dependencies>,\n\t\tContextReturned,\n\t\tconst Operations extends QueryRegistry<EffectValue<ContextReturned>>,\n\t\tGuardReturned extends Supported<void> = never,\n\t>(configuration: {\n\t\tcontext: (host: Host) => ContextReturned\n\t\toperations: (\n\t\t\tdefinitions: ReturnType<\n\t\t\t\ttypeof effectOperationFactory<\n\t\t\t\t\tEffectValue<ContextReturned>,\n\t\t\t\t\tRecord<never, never>,\n\t\t\t\t\tNoInfer<CallbackError<GuardReturned>>,\n\t\t\t\t\tNoInfer<CallbackRequirements<GuardReturned>>\n\t\t\t\t>\n\t\t\t>,\n\t\t) => Operations & NoInfer<ValidatedEffectOperations<Operations>>\n\t\tdefaults?: {\n\t\t\tmetadata?: object\n\t\t\tguard?: (context: EffectValue<ContextReturned>) => GuardReturned\n\t\t}\n\t}): ReturnType<\n\t\ttypeof createEffectQuery<\n\t\t\tHost,\n\t\t\tContextReturned,\n\t\t\tOperations,\n\t\t\tPolicyReturned<Dependencies>,\n\t\t\tGuardReturned\n\t\t>\n\t>\n\n\tfunction query(configuration: {\n\t\tcontext: (host: never) => unknown\n\t\tcontract?: DomainContract\n\t\toperations: (define: never) => Readonly<Record<string, object>>\n\t\tdefaults?: { metadata?: object; guard?: (context: never) => Supported<void> }\n\t}): unknown {\n\t\tconst buildOperations = () => {\n\t\t\tconst definitions = configuration.contract\n\t\t\t\t? domainEffectFactory(configuration.contract.queries ?? {}, false)\n\t\t\t\t: effectOperationFactory()\n\t\t\treturn snapshotOperations(\n\t\t\t\tconfiguration.operations(\n\t\t\t\t\t// SAFETY: the overload chooses this exact inline or contracted helper factory.\n\t\t\t\t\tdefinitions as never,\n\t\t\t\t),\n\t\t\t\tconfiguration.contract,\n\t\t\t\t'queries',\n\t\t\t)\n\t\t}\n\n\t\t// SAFETY: the overload verifies callback types; exact binding ownership is verified before execution.\n\t\treturn createEffectQuery({\n\t\t\t...configuration,\n\t\t\t...dependencies,\n\t\t\toperations: buildOperations,\n\t\t} as never)\n\t}\n\treturn query\n}\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"query.mjs","names":["QueryMiddlewareError","QueryConfigurationError","QueryPermissionError","createEffectQuery","definitions","effectOperationFactory","getOperations","memoize","configuration","observability","Observability","exec","Effect","operations","operation","definition","decodeEffectContract","input","observation","run","check","normalizeEffect","host","context","metadata","core","guard","current","parsedInput","usedNext","middleware","output","options","enterRequestScope","Exit","exit","observationFailure","reportFailure","expose","selectOperation","owner","registerLazyRegistry","bindEffectQuery","query","buildOperations","domainEffectFactory","snapshotOperations","dependencies"],"sources":["../../../src/modules/effect/query.ts"],"sourcesContent":["import { memoize, registerLazyRegistry } from '../contracts/lazy'\n/* oxlint-disable anti-slop/no-unknown-returns, anti-slop/no-unsafe-dictionary-type -- Overload implementation storage is erased; public signatures retain concrete values, errors and services. */\nimport { Effect, Exit } from 'effect'\nimport type { ContractSchema } from '../contracts/contract'\nimport {\n\tselectOperation,\n\ttype SelectedOperation,\n\ttype OperationPublicResult,\n} from '../contracts/exposure'\nimport { decodeEffectContract } from './schema'\n// oxlint-disable-next-line cvx/component-boundaries -- SAFETY: Internal optional adapter shares the Effect-free Foundation lifecycle and types without entering the Convex component deployment graph.\nimport {\n\tObservability,\n\ttype ObservabilityOptions,\n} from '../../components/foundation/modules/observability/observability'\nimport { normalizeEffect, observationFailure } from './normalize'\nimport { enterRequestScope } from './scope'\nimport { reportFailure, type FailureAuditOptions } from './failure-audit'\nimport {\n\teffectOperationFactory,\n\ttype CallbackError,\n\ttype CallbackRequirements,\n\ttype EffectOperationArgument,\n\ttype EffectOperationError,\n\ttype EffectOperationRequirements,\n\ttype EffectOperationResult,\n\ttype EffectValue,\n\ttype CheckedEffectOperation,\n\ttype UnwrappedDefaultError,\n\ttype UnwrappedDefaultRequirements,\n\ttype ValidatedEffectOperations,\n} from './operation'\n\nimport type { DomainContract, DomainQueryContract } from '../contracts/domain'\nimport { snapshotOperations, type BoundOperations } from '../contracts/binding'\nimport {\n\tdomainEffectFactory,\n\ttype DomainEffectFactory,\n\ttype DomainEffectImplementations,\n\ttype ExactDomainOperations,\n} from './domain'\n\ntype Supported<Value> = Value | PromiseLike<Value> | Effect.Effect<Value, unknown, unknown>\ntype QueryDefinition = {\n\tinput: ContractSchema\n\tresult: ContractSchema\n\t// oxlint-disable-next-line anti-slop/no-unknown-returns -- Internal heterogeneous storage; selected schemas restore the concrete result at exec.\n\thandler: (input: never, context: never) => unknown\n\tclassification?: string\n\tpermission?: string\n\tmetadata?: object\n\t// oxlint-disable-next-line anti-slop/no-unknown-returns -- Internal hook storage retains the concrete definition separately.\n\tguard?: (context: never, input: never) => unknown\n\t// oxlint-disable-next-line anti-slop/no-unknown-returns -- Internal hook storage retains the concrete definition separately.\n\tmiddleware?: (input: never) => unknown\n}\ntype QueryRegistry<Context> = Readonly<\n\tRecord<\n\t\tstring,\n\t\tPick<QueryDefinition, 'input' | 'result' | 'handler'> &\n\t\t\tCheckedEffectOperation<Context> & {\n\t\t\t\tprepare?: never\n\t\t\t\taudit?: never\n\t\t\t\taggregates?: never\n\t\t\t\treplayResult?: never\n\t\t\t}\n\t>\n>\ntype OperationKey<Operations> = Extract<keyof Operations, string>\n\nclass QueryMiddlewareError extends Error {\n\treadonly code = 'QUERY_MIDDLEWARE_NEXT_REUSED'\n\treadonly name = 'QueryMiddlewareError'\n\tconstructor() {\n\t\tsuper('A query middleware called next() more than once')\n\t}\n}\nclass QueryConfigurationError extends Error {\n\treadonly code = 'QUERY_OPERATION_NOT_CONFIGURED'\n\treadonly name = 'QueryConfigurationError'\n\tconstructor() {\n\t\tsuper('The selected query operation is not configured')\n\t}\n}\nclass QueryPermissionError extends Error {\n\treadonly code = 'QUERY_PERMISSION_CHECKER_MISSING'\n\treadonly name = 'QueryPermissionError'\n\tconstructor() {\n\t\tsuper('Query permission requires an injected permission checker')\n\t}\n}\n\n/** Injectable domain queries compose lazily; the API chooses native function kind. */\nexport function createEffectQuery<\n\tHost,\n\tContextReturned,\n\tconst Operations extends QueryRegistry<EffectValue<ContextReturned>>,\n\tPermissionReturned = never,\n\tGuardReturned extends Supported<void> = never,\n>(configuration: {\n\tcontext: (host: Host) => ContextReturned\n\toperations: (\n\t\tdefinitions: ReturnType<\n\t\t\ttypeof effectOperationFactory<\n\t\t\t\tEffectValue<ContextReturned>,\n\t\t\t\tRecord<never, never>,\n\t\t\t\tNoInfer<CallbackError<GuardReturned>>,\n\t\t\t\tNoInfer<CallbackRequirements<GuardReturned>>\n\t\t\t>\n\t\t>,\n\t) => Operations & NoInfer<ValidatedEffectOperations<Operations>>\n\tcheckPermission?: (\n\t\thost: Host,\n\t\tinput: { permission: string; operation: string },\n\t) => PermissionReturned\n\tdefaults?: { metadata?: object; guard?: (context: EffectValue<ContextReturned>) => GuardReturned }\n\tobservability?: ObservabilityOptions | Observability\n\tauditFailure?: FailureAuditOptions\n\tcontract?: Pick<DomainContract, 'errors'>\n}) {\n\tconst definitions = effectOperationFactory<\n\t\tEffectValue<ContextReturned>,\n\t\tRecord<never, never>,\n\t\tCallbackError<GuardReturned>,\n\t\tCallbackRequirements<GuardReturned>\n\t>()\n\tconst getOperations = memoize<Operations>(() => configuration.operations(definitions))\n\tconst observability =\n\t\tconfiguration.observability instanceof Observability\n\t\t\t? configuration.observability\n\t\t\t: new Observability(\n\t\t\t\t\tconfiguration.observability ?? {\n\t\t\t\t\t\tenabled: false,\n\t\t\t\t\t\tclassifyError: () => ({ outcome: 'failed', errorCode: 'UNEXPECTED' }),\n\t\t\t\t\t},\n\t\t\t\t)\n\n\tfunction exec<const Key extends OperationKey<Operations>>(\n\t\toperation: Key,\n\t\tinput: EffectOperationArgument<Operations[Key]>,\n\t\thost: Host,\n\t): Effect.Effect<\n\t\tEffectOperationResult<Operations[Key]>,\n\t\t| EffectOperationError<Operations[Key]>\n\t\t| CallbackError<ContextReturned | PermissionReturned>\n\t\t| UnwrappedDefaultError<Operations[Key], GuardReturned>,\n\t\t| EffectOperationRequirements<Operations[Key]>\n\t\t| CallbackRequirements<ContextReturned | PermissionReturned>\n\t\t| UnwrappedDefaultRequirements<Operations[Key], GuardReturned>\n\t> {\n\t\tconst execution = Effect.suspend(() => {\n\t\t\tconst operations = getOperations()\n\t\t\tif (!Object.prototype.hasOwnProperty.call(operations, operation)) {\n\t\t\t\treturn Effect.die(new QueryConfigurationError())\n\t\t\t}\n\t\t\t// SAFETY: operation helpers check hooks before this heterogeneous storage seam.\n\t\t\tconst definition: QueryDefinition = operations[operation]\n\t\t\treturn Effect.flatMap(decodeEffectContract(definition.input, input), (parsedInput) => {\n\t\t\t\tconst observation = observability.start({\n\t\t\t\t\toperation,\n\t\t\t\t\tclassification: definition.classification ?? 'query',\n\t\t\t\t})\n\t\t\t\tconst run = Effect.gen(function* () {\n\t\t\t\t\tif (definition.permission !== undefined) {\n\t\t\t\t\t\tconst check = configuration.checkPermission\n\t\t\t\t\t\tif (!check) return yield* Effect.die(new QueryPermissionError())\n\t\t\t\t\t\tyield* normalizeEffect(() =>\n\t\t\t\t\t\t\tcheck(host, { permission: definition.permission!, operation }),\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t\tconst context = yield* normalizeEffect(() => configuration.context(host))\n\t\t\t\t\tconst metadata = { ...configuration.defaults?.metadata, ...definition.metadata }\n\t\t\t\t\tconst core = (current: EffectValue<ContextReturned>) =>\n\t\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\t\tconst guard = configuration.defaults?.guard\n\t\t\t\t\t\t\tif (guard) yield* normalizeEffect(() => guard(current))\n\t\t\t\t\t\t\tif (definition.guard)\n\t\t\t\t\t\t\t\tyield* normalizeEffect(() => {\n\t\t\t\t\t\t\t\t\t// SAFETY: selected schemas and context own the stored guard parameters.\n\t\t\t\t\t\t\t\t\treturn definition.guard!(current as never, parsedInput as never)\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\treturn yield* normalizeEffect(() => {\n\t\t\t\t\t\t\t\t// SAFETY: selected schemas and context own the stored handler parameters.\n\t\t\t\t\t\t\t\treturn definition.handler(parsedInput as never, current as never)\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t})\n\t\t\t\t\tlet usedNext = false\n\t\t\t\t\tconst middleware = definition.middleware\n\t\t\t\t\tconst output = middleware\n\t\t\t\t\t\t? yield* normalizeEffect(() => {\n\t\t\t\t\t\t\t\t// SAFETY: the selected helper checked this middleware's input and next contract.\n\t\t\t\t\t\t\t\treturn middleware({\n\t\t\t\t\t\t\t\t\toperation,\n\t\t\t\t\t\t\t\t\tinput: parsedInput,\n\t\t\t\t\t\t\t\t\tcommand: parsedInput,\n\t\t\t\t\t\t\t\t\tcontext,\n\t\t\t\t\t\t\t\t\tmetadata,\n\t\t\t\t\t\t\t\t\tnext: (options?: { context?: object }) =>\n\t\t\t\t\t\t\t\t\t\tEffect.suspend(() => {\n\t\t\t\t\t\t\t\t\t\t\tif (usedNext) return Effect.die(new QueryMiddlewareError())\n\t\t\t\t\t\t\t\t\t\t\tusedNext = true\n\t\t\t\t\t\t\t\t\t\t\treturn core(\n\t\t\t\t\t\t\t\t\t\t\t\toptions?.context ? Object.assign({}, context, options.context) : context,\n\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t} as never)\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t: yield* core(context)\n\t\t\t\t\treturn yield* decodeEffectContract(definition.result, output)\n\t\t\t\t})\n\t\t\t\treturn enterRequestScope(operation, false, (entered, current) =>\n\t\t\t\t\trun.pipe(\n\t\t\t\t\t\tEffect.onExit((exit) =>\n\t\t\t\t\t\t\tEffect.sync(() => {\n\t\t\t\t\t\t\t\tif (Exit.isSuccess(exit)) observation.completed()\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tobservation.failed(observationFailure(exit.cause))\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}).pipe(\n\t\t\t\t\t\t\t\tEffect.andThen(\n\t\t\t\t\t\t\t\t\treportFailure(configuration.auditFailure, exit, {\n\t\t\t\t\t\t\t\t\t\tkind: 'query',\n\t\t\t\t\t\t\t\t\t\toperation,\n\t\t\t\t\t\t\t\t\t\tclassification: definition.classification ?? 'query',\n\t\t\t\t\t\t\t\t\t\tinput: parsedInput,\n\t\t\t\t\t\t\t\t\t\tcontract: configuration.contract?.errors,\n\t\t\t\t\t\t\t\t\t\tentered,\n\t\t\t\t\t\t\t\t\t\tcurrent,\n\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t})\n\t\t})\n\t\t// SAFETY: selected schemas own A; concrete callbacks and the wrapped middleware\n\t\t// own E/R. No interpreter or runner executes this Effect before the caller does.\n\t\treturn execution as ReturnType<typeof exec<Key>>\n\t}\n\tfunction expose<const Owner extends symbol, const Key extends OperationKey<Operations>>(\n\t\towner: Owner,\n\t\toperation: Key,\n\t): SelectedOperation<\n\t\tOwner,\n\t\tKey,\n\t\tOperations[Key]['input'],\n\t\tOperationPublicResult<Operations[Key]>\n\t> {\n\t\tconst operations = getOperations()\n\t\tif (!Object.hasOwn(operations, operation)) throw new QueryConfigurationError()\n\t\treturn selectOperation(owner, 'query', operation, operations[operation])\n\t}\n\treturn registerLazyRegistry(\n\t\t{\n\t\t\texec,\n\t\t\texpose,\n\t\t\t/** Bind invocation context without resolving it or running an operation. */\n\t\t\twithContext(context: Host) {\n\t\t\t\treturn {\n\t\t\t\t\texec: <const Key extends OperationKey<Operations>>(\n\t\t\t\t\t\toperation: Key,\n\t\t\t\t\t\tinput: EffectOperationArgument<Operations[Key]>,\n\t\t\t\t\t) => exec(operation, input, context),\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\tgetOperations,\n\t)\n}\n\ntype Policy<Dependencies> = 'checkPermission' extends keyof Dependencies\n\t? Dependencies['checkPermission']\n\t: never\n// oxlint-disable-next-line anti-slop/no-unknown-returns -- Conditional type extracts the host; no unknown result is exposed by the registry.\ntype CallbackHost<Callback> = Callback extends (host: infer Host, input: never) => unknown\n\t? Host\n\t: never\ntype CallbackReturned<Callback> = Callback extends (...arguments_: never[]) => infer Returned\n\t? Returned\n\t: never\ntype PolicyHost<Dependencies> = [CallbackHost<Policy<Dependencies>>] extends [never]\n\t? unknown\n\t: CallbackHost<Policy<Dependencies>>\ntype PolicyReturned<Dependencies> = CallbackReturned<Policy<Dependencies>>\nexport type EffectQueryDependencies = {\n\tobservability: Observability\n\tauditFailure?: FailureAuditOptions\n\t// oxlint-disable-next-line anti-slop/no-unknown-returns -- Host policy storage is erased; the bound generic dependency retains its concrete E/R.\n\tcheckPermission?: (host: never, input: { permission: string; operation: string }) => unknown\n}\n\n/** The public Foundation binds trusted application policies once. */\nexport function bindEffectQuery<const Dependencies extends EffectQueryDependencies>(\n\tdependencies: Dependencies,\n) {\n\tfunction query<\n\t\tHost extends PolicyHost<Dependencies>,\n\t\tContextReturned,\n\t\tconst Contract extends DomainContract & {\n\t\t\tqueries: Readonly<Record<string, DomainQueryContract>>\n\t\t},\n\t\tconst Operations extends DomainEffectImplementations<\n\t\t\tEffectValue<ContextReturned>,\n\t\t\tContract['queries']\n\t\t>,\n\t\tMode extends false,\n\t\tGuardReturned extends Supported<void> = never,\n\t>(configuration: {\n\t\tcontract: Contract &\n\t\t\tNoInfer<\n\t\t\t\tOperations extends ExactDomainOperations<Operations, Contract['queries']> &\n\t\t\t\t\tValidatedEffectOperations<Operations>\n\t\t\t\t\t? unknown\n\t\t\t\t\t: never\n\t\t\t>\n\t\tcontext: (host: Host) => ContextReturned\n\t\toperations: (\n\t\t\tdefine: DomainEffectFactory<\n\t\t\t\tEffectValue<ContextReturned>,\n\t\t\t\tContract['queries'],\n\t\t\t\tMode,\n\t\t\t\tnever,\n\t\t\t\tNoInfer<CallbackError<GuardReturned>>,\n\t\t\t\tNoInfer<CallbackRequirements<GuardReturned>>,\n\t\t\t\tContract['errors']\n\t\t\t>,\n\t\t) => Operations\n\t\tdefaults?: {\n\t\t\tmetadata?: object\n\t\t\tguard?: (context: EffectValue<ContextReturned>) => GuardReturned\n\t\t}\n\t}): ReturnType<\n\t\ttypeof createEffectQuery<\n\t\t\tHost,\n\t\t\tContextReturned,\n\t\t\tBoundOperations<Operations, Contract['queries']>,\n\t\t\tPolicyReturned<Dependencies>,\n\t\t\tGuardReturned\n\t\t>\n\t>\n\n\tfunction query<\n\t\tHost extends PolicyHost<Dependencies>,\n\t\tContextReturned,\n\t\tconst Operations extends QueryRegistry<EffectValue<ContextReturned>>,\n\t\tGuardReturned extends Supported<void> = never,\n\t>(configuration: {\n\t\tcontext: (host: Host) => ContextReturned\n\t\toperations: (\n\t\t\tdefinitions: ReturnType<\n\t\t\t\ttypeof effectOperationFactory<\n\t\t\t\t\tEffectValue<ContextReturned>,\n\t\t\t\t\tRecord<never, never>,\n\t\t\t\t\tNoInfer<CallbackError<GuardReturned>>,\n\t\t\t\t\tNoInfer<CallbackRequirements<GuardReturned>>\n\t\t\t\t>\n\t\t\t>,\n\t\t) => Operations & NoInfer<ValidatedEffectOperations<Operations>>\n\t\tdefaults?: {\n\t\t\tmetadata?: object\n\t\t\tguard?: (context: EffectValue<ContextReturned>) => GuardReturned\n\t\t}\n\t}): ReturnType<\n\t\ttypeof createEffectQuery<\n\t\t\tHost,\n\t\t\tContextReturned,\n\t\t\tOperations,\n\t\t\tPolicyReturned<Dependencies>,\n\t\t\tGuardReturned\n\t\t>\n\t>\n\n\tfunction query(configuration: {\n\t\tcontext: (host: never) => unknown\n\t\tcontract?: DomainContract\n\t\toperations: (define: never) => Readonly<Record<string, object>>\n\t\tdefaults?: { metadata?: object; guard?: (context: never) => Supported<void> }\n\t}): unknown {\n\t\tconst buildOperations = () => {\n\t\t\tconst definitions = configuration.contract\n\t\t\t\t? domainEffectFactory(\n\t\t\t\t\t\tconfiguration.contract.queries ?? {},\n\t\t\t\t\t\tfalse,\n\t\t\t\t\t\tconfiguration.contract.errors,\n\t\t\t\t\t)\n\t\t\t\t: effectOperationFactory()\n\t\t\treturn snapshotOperations(\n\t\t\t\tconfiguration.operations(\n\t\t\t\t\t// SAFETY: the overload chooses this exact inline or contracted helper factory.\n\t\t\t\t\tdefinitions as never,\n\t\t\t\t),\n\t\t\t\tconfiguration.contract,\n\t\t\t\t'queries',\n\t\t\t)\n\t\t}\n\n\t\t// SAFETY: the overload verifies callback types; exact binding ownership is verified before execution.\n\t\treturn createEffectQuery({\n\t\t\t...configuration,\n\t\t\t...dependencies,\n\t\t\toperations: buildOperations,\n\t\t} as never)\n\t}\n\treturn query\n}\n"],"mappings":"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"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
//#region src/modules/effect/scope.d.ts
|
|
3
|
+
/** The request an operation joined: its outermost operation, its direct caller, and its nesting depth. */
|
|
4
|
+
export type RequestScope = Readonly<{
|
|
5
|
+
root: string;
|
|
6
|
+
parent: string;
|
|
7
|
+
depth: number;
|
|
8
|
+
}>;
|
|
9
|
+
/** How nested operations audit when an enclosing operation already declares an audit callback. */
|
|
10
|
+
export type NestedAuditMode = 'fold' | 'separate';
|
|
11
|
+
/** Request-wide state shared by every operation yielded inside the same Effect program. */
|
|
12
|
+
export type ScopeState = Readonly<{
|
|
13
|
+
scope: RequestScope;
|
|
14
|
+
/** Whether some enclosing operation declares an audit callback. */
|
|
15
|
+
audited: boolean;
|
|
16
|
+
/** Failure values already reported to the failure-audit sink in this request. */
|
|
17
|
+
reported: WeakSet<object>;
|
|
18
|
+
}>;
|
|
19
|
+
/**
|
|
20
|
+
* Run an operation inside the current request scope, opening one when none exists.
|
|
21
|
+
* `run` receives the state the operation entered (`undefined` for a root) and the
|
|
22
|
+
* state it provides to the operations yielded inside it.
|
|
23
|
+
*/
|
|
24
|
+
export declare function enterRequestScope<Value, Error, Requirements>(operation: string, audits: boolean, run: (entered: ScopeState | undefined, current: ScopeState) => Effect.Effect<Value, Error, Requirements>): Effect.Effect<Value, Error, Requirements>;
|
|
25
|
+
export declare function auditFolded(mode: NestedAuditMode | undefined, entered: ScopeState | undefined): boolean;
|
|
26
|
+
//#endregion
|
|
27
|
+
//# sourceMappingURL=scope.d.mts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{Context as e,Effect as t}from"effect";const n=e.Reference(`cvx-kit/effect/RequestScope`,{defaultValue:()=>void 0});function r(e,r,i){return n.use(a=>{let o={scope:{root:a?.scope.root??e,parent:e,depth:(a?.scope.depth??0)+1},audited:r||(a?.audited??!1),reported:a?.reported??/* @__PURE__ */ new WeakSet};return i(a,o).pipe(t.provideService(n,o))})}function i(e,t){return(e??`fold`)===`fold`&&t?.audited===!0}export{i as auditFolded,r as enterRequestScope};
|
|
2
|
+
//# sourceMappingURL=scope.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scope.mjs","names":["CurrentScope","Context","enterRequestScope","current","entered","operation","audits","run","Effect","auditFolded","mode"],"sources":["../../../src/modules/effect/scope.ts"],"sourcesContent":["import { Context, Effect } from 'effect'\n\n/** The request an operation joined: its outermost operation, its direct caller, and its nesting depth. */\nexport type RequestScope = Readonly<{ root: string; parent: string; depth: number }>\n\n/** How nested operations audit when an enclosing operation already declares an audit callback. */\nexport type NestedAuditMode = 'fold' | 'separate'\n\n/** Request-wide state shared by every operation yielded inside the same Effect program. */\nexport type ScopeState = Readonly<{\n\tscope: RequestScope\n\t/** Whether some enclosing operation declares an audit callback. */\n\taudited: boolean\n\t/** Failure values already reported to the failure-audit sink in this request. */\n\treported: WeakSet<object>\n}>\n\nconst CurrentScope = Context.Reference<ScopeState | undefined>('cvx-kit/effect/RequestScope', {\n\tdefaultValue: () => undefined,\n})\n\n/**\n * Run an operation inside the current request scope, opening one when none exists.\n * `run` receives the state the operation entered (`undefined` for a root) and the\n * state it provides to the operations yielded inside it.\n */\nexport function enterRequestScope<Value, Error, Requirements>(\n\toperation: string,\n\taudits: boolean,\n\trun: (\n\t\tentered: ScopeState | undefined,\n\t\tcurrent: ScopeState,\n\t) => Effect.Effect<Value, Error, Requirements>,\n): Effect.Effect<Value, Error, Requirements> {\n\treturn CurrentScope.use((entered) => {\n\t\tconst current: ScopeState = {\n\t\t\tscope: {\n\t\t\t\troot: entered?.scope.root ?? operation,\n\t\t\t\tparent: operation,\n\t\t\t\tdepth: (entered?.scope.depth ?? 0) + 1,\n\t\t\t},\n\t\t\taudited: audits || (entered?.audited ?? false),\n\t\t\treported: entered?.reported ?? new WeakSet(),\n\t\t}\n\t\treturn run(entered, current).pipe(Effect.provideService(CurrentScope, current))\n\t})\n}\n\nexport function auditFolded(mode: NestedAuditMode | undefined, entered: ScopeState | undefined) {\n\treturn (mode ?? 'fold') === 'fold' && entered?.audited === true\n}\n"],"mappings":"6CAiBA,MAAMA,EAAeC,EAAQ,UAAkC,8BAA+B,CAC7F,iBAAoB,IAAA,EACrB,CAAC,EAOD,SAAgBC,EACf,EACA,EACA,EAI4C,CAC5C,OAAOF,EAAa,IAAK,GAAY,CACpC,IAAMG,EAAsB,CAC3B,MAAO,CACN,KAAMC,GAAS,MAAM,MAAQC,EAC7B,OAAQA,EACR,OAAQD,GAAS,MAAM,OAAS,GAAK,CACtC,EACA,QAASE,IAAWF,GAAS,SAAW,IACxC,SAAUA,GAAS,0BAAY,IAAI,OACpC,EACA,OAAOG,EAAIH,EAASD,CAAO,CAAC,CAAC,KAAKK,EAAO,eAAeR,EAAcG,CAAO,CAAC,CAC/E,CAAC,CACF,CAEA,SAAgBM,EAAY,EAAmC,EAAiC,CAC/F,OAAQC,GAAQ,UAAY,QAAUN,GAAS,UAAY,EAC5D"}
|
package/dist/zod-table.d.mts
CHANGED
|
@@ -130,8 +130,79 @@ export declare function tenantTable<Table extends string, Fields extends FieldSc
|
|
|
130
130
|
* Merges per-module table maps into the application schema map, rejecting
|
|
131
131
|
* duplicate table names across modules — the module-registry combinator for
|
|
132
132
|
* domain/table.ts: `defineSchema(createModule(catalogTables, salesTables))`.
|
|
133
|
+
* Accepts plain maps and `namespace(...)` maps side by side; namespaces add
|
|
134
|
+
* no keys, so the result is the same flat `{ tableName: TableDefinition }`.
|
|
133
135
|
*/
|
|
134
|
-
export declare function createModule<const Maps extends readonly Record<string, TableDefinition<any>>[]>(...maps: Maps): UnionToIntersection<Maps[number]
|
|
136
|
+
export declare function createModule<const Maps extends readonly Record<string, TableDefinition<any>>[]>(...maps: Maps): FlatTables<UnionToIntersection<Maps[number]>>;
|
|
137
|
+
type FlatTables<Map> = { [Key in keyof Map as Key extends string ? Key : never]: Map[Key]; };
|
|
138
|
+
declare const namespaceKey: unique symbol;
|
|
139
|
+
/** Declaration-level metadata carried by a `namespace(...)` table map. */
|
|
140
|
+
export type NamespaceInfo<Name extends string, Tables extends string> = {
|
|
141
|
+
readonly name: Name;
|
|
142
|
+
readonly tables: readonly Tables[];
|
|
143
|
+
};
|
|
144
|
+
/**
|
|
145
|
+
* A table map tagged with a namespace. It is still a plain
|
|
146
|
+
* `{ tableName: TableDefinition }` map (the tag is a non-enumerable symbol),
|
|
147
|
+
* so `createModule`/`defineSchema` see exactly the tables they saw before.
|
|
148
|
+
*/
|
|
149
|
+
export type Namespace<Name extends string, Tables extends Record<string, TableDefinition<any>>> = Tables & NamespaceTag<Name, keyof Tables & string>;
|
|
150
|
+
/** The metadata-only shape of a `namespace(...)` map. */
|
|
151
|
+
export type NamespaceTag<Name extends string, Tables extends string> = {
|
|
152
|
+
readonly [namespaceKey]: NamespaceInfo<Name, Tables>;
|
|
153
|
+
};
|
|
154
|
+
/** PascalCase member name of a table: `itemLedgerEntries` → `ItemLedgerEntries`. */
|
|
155
|
+
export type MemberName<TableName extends string> = Capitalize<TableName>;
|
|
156
|
+
/** Fully qualified name: `<Namespace>.<Member>`, e.g. `Inventory.Items`. */
|
|
157
|
+
export type QualifiedName<Name extends string, TableName extends string> = `${Name}.${MemberName<TableName>}`;
|
|
158
|
+
type NamespaceMember = TableDefinition<any> | {
|
|
159
|
+
tableName: string;
|
|
160
|
+
table: TableDefinition<any>;
|
|
161
|
+
};
|
|
162
|
+
type MemberTables<Members extends Record<string, NamespaceMember>> = { [Key in keyof Members]: Members[Key] extends {
|
|
163
|
+
table: infer Table extends TableDefinition<any>;
|
|
164
|
+
} ? Table : Extract<Members[Key], TableDefinition<any>>; };
|
|
165
|
+
type CheckedMembers<Members extends Record<string, NamespaceMember>> = { [Key in keyof Members]: Members[Key] extends {
|
|
166
|
+
tableName: infer TableName;
|
|
167
|
+
} ? TableName extends Key ? Members[Key] : {
|
|
168
|
+
tableName: Key;
|
|
169
|
+
table: TableDefinition<any>;
|
|
170
|
+
} : Members[Key]; };
|
|
171
|
+
type CheckedNamespaceName<Name extends string> = Name extends '' ? never : Name extends `${string}..${string}` | `.${string}` | `${string}.` ? never : Name;
|
|
172
|
+
/**
|
|
173
|
+
* Groups tables under a declaration-level namespace, like AL's
|
|
174
|
+
* `namespace Microsoft.Inventory.Item;`. Keys are the real (stored) table
|
|
175
|
+
* names, exactly as in an un-namespaced module map; each table's member name
|
|
176
|
+
* is the PascalCase form of its key (`items` → `Items`) and its qualified
|
|
177
|
+
* name is `<Namespace>.<Member>` (`Inventory.Items`). Storage, `id('items')`,
|
|
178
|
+
* `ctx.db.query('items')` and generated types are unchanged.
|
|
179
|
+
*
|
|
180
|
+
* A member may be a `TableDefinition` (`items.table.index(...)`) or a table
|
|
181
|
+
* boundary (`items`); a boundary whose `tableName` differs from its key is a
|
|
182
|
+
* type error and a runtime error. Dotted names (`Microsoft.Inventory`) are
|
|
183
|
+
* allowed; each segment must be PascalCase.
|
|
184
|
+
*/
|
|
185
|
+
export declare function namespace<const Name extends string, const Members extends Record<string, NamespaceMember>>(name: Name & CheckedNamespaceName<Name>, members: Members & CheckedMembers<Members>): Namespace<Name, MemberTables<Members>>;
|
|
186
|
+
/** PascalCase member name of a table name. */
|
|
187
|
+
export declare function memberName<const TableName extends string>(tableName: TableName): MemberName<TableName>;
|
|
188
|
+
/** The namespace name of a `namespace(...)` map. */
|
|
189
|
+
export declare function namespaceName<const Name extends string>(ns: NamespaceTag<Name, string>): Name;
|
|
190
|
+
/** The stored table names declared in a namespace, in declaration order. */
|
|
191
|
+
export declare function tablesOf<const Tables extends string>(ns: NamespaceTag<string, Tables>): readonly Tables[];
|
|
192
|
+
type NamespaceEntries<Spaces extends readonly NamespaceTag<string, string>[]> = { [Index in keyof Spaces]: Spaces[Index] extends NamespaceTag<infer Name, infer Tables> ? { [TableName in Tables]: Name; } : never; }[number];
|
|
193
|
+
/**
|
|
194
|
+
* Typed, read-only qualified-name lookup over namespaces (no global registry:
|
|
195
|
+
* build one next to `createModule` and import it where labels are needed).
|
|
196
|
+
* Rejects duplicate namespace names and tables claimed by two namespaces.
|
|
197
|
+
*/
|
|
198
|
+
export declare function namespaceIndex<const Spaces extends readonly NamespaceTag<string, string>[]>(...spaces: Spaces): {
|
|
199
|
+
qualifiedName<const Table extends keyof UnionToIntersection<NamespaceEntries<Spaces>> & string>(table: Table): { [Key in Table]: QualifiedName<UnionToIntersection<NamespaceEntries<Spaces>>[Key] & string, Key>; }[Table];
|
|
200
|
+
namespaceOf<const Table extends keyof UnionToIntersection<NamespaceEntries<Spaces>> & string>(table: Table): UnionToIntersection<NamespaceEntries<Spaces>>[Table];
|
|
201
|
+
memberName: typeof memberName;
|
|
202
|
+
tablesOf<const Name extends Spaces[number] extends NamespaceTag<infer Name_1 extends string, string> ? Name_1 : never>(name: Name): readonly { [Table in keyof UnionToIntersection<NamespaceEntries<Spaces>> & string]: UnionToIntersection<NamespaceEntries<Spaces>>[Table] extends Name ? Table : never; }[keyof UnionToIntersection<NamespaceEntries<Spaces>> & string][];
|
|
203
|
+
namespaces: readonly (Spaces[number] extends NamespaceTag<infer Name_1 extends string, string> ? Name_1 : never)[];
|
|
204
|
+
has(table: string): table is keyof UnionToIntersection<NamespaceEntries<Spaces>> & string;
|
|
205
|
+
};
|
|
135
206
|
type UnionToIntersection<Union> = (Union extends unknown ? (member: Union) => void : never) extends ((member: infer Intersection) => void) ? Intersection : never;
|
|
136
207
|
/**
|
|
137
208
|
* Cursor-pagination boundary schemas bridged from Convex's own validators:
|
package/dist/zod-table.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{zodToConvex as e}from"./zod-convex.mjs";import{memoize as t}from"./modules/contracts/lazy.mjs";import{pageResult as n}from"./querying/shared/page.mjs";import{scalarPaginationSchema as r}from"./querying/filters.mjs";import{convexToZod as i,convexToZod as a,zid as o,zid as s}from"convex-helpers/server/zod4";import{defineTable as c,paginationOptsValidator as l}from"convex/server";import{z as u}from"zod";const d={createdAt:u.number().optional(),updatedAt:u.number().optional(),archivedAt:u.number().optional()},f=[`createdAt`,`updatedAt`,`archivedAt`];function p(n,i,a={}){let o=i(s);k(o,[`_id`,`_creationTime`,...f]);let l={...o,...d};A(l,a.serverFields??[],a.commandFields??[],a.publicFields??[]);let p=u.strictObject({...l}),m=t(()=>T(l,n)),h=[...f,...a.serverFields??[]],g=[...a.commandFields??[]],_=[...a.publicFields??[]],v=t(()=>D(l,h)),y=t(()=>E(l,g)),x=t(()=>u.strictObject({...v()})),S=t(()=>u.strictObject({...v()}).partial()),C=t(()=>u.strictObject({...y()})),j=t(()=>u.strictObject(E(l,_))),M={get schema(){return m()},get insertSchema(){return x()},get updateSchema(){return S()},get commandInput(){return C()},get publicDto(){return j()}},N=t(()=>u.strictObject({})),P=t(()=>/* @__PURE__ */ new Set([`_id`,`_creationTime`,`tenant`,`__proto__`,...f]));function F(e){return I(e)}function I(e){let t=e===!0||e===!1?{_id:e}:e,n=t?.extend??{};if(L(n),!t?._id&&Object.keys(n).length===0)return M.publicDto;let r=u.strictObject({...M.publicDto.shape,...n});return t?._id?r.extend({_id:M.schema.shape._id}):r}function L(e){for(let t of Object.keys(e)){if(P().has(t)||Object.hasOwn(M.publicDto.shape,t))throw Error(`DTO extension collision for field "${t}" on table "${n}"`);O(e[t])}}function R(e,t){let n=t===!0||t===!1?{_id:t}:t;L(n?.extend??{});let r=M.publicDto.parse(Object.fromEntries(Object.keys(M.publicDto.shape).map(t=>[t,e[t]]))),i=n?.extend,a=(i==null?N():u.strictObject(i)).parse(n?.values??{}),o={...r,...a};return n?._id&&(o._id=M.schema.shape._id.parse(`_id`in e?e._id:void 0)),o}function z(e){return e?M.insertSchema.omit(e):M.insertSchema}function B(e){return e?M.updateSchema.omit(e):M.updateSchema}let V=e(p),H=c(V),U=()=>Object.fromEntries(Object.entries(M.schema.shape).map(([t,n])=>[t,e(n)]));function W(e,t){return r(U(),e,t)}let G=t(()=>({insert:M.commandInput,update:u.strictObject({data:u.strictObject({...y()}).partial(),id:b(n)}),id:u.strictObject({id:b(n)})}));return{tableName:n,get schema(){return M.schema},set schema(e){w(this,`schema`,e)},storage:p,get insertSchema(){return M.insertSchema},set insertSchema(e){w(this,`insertSchema`,e)},get updateSchema(){return M.updateSchema},set updateSchema(e){w(this,`updateSchema`,e)},get commandInput(){return M.commandInput},set commandInput(e){w(this,`commandInput`,e)},get publicDto(){return M.publicDto},set publicDto(e){w(this,`publicDto`,e)},dto:F,toPublicDto:R,paginationOpts:W,table:H,insert:z,update:B,get tools(){return G()},set tools(e){w(this,`tools`,e)}}}function m(e){return k(e,[`_id`,`_creationTime`,...f]),function(t,n,r={}){return p(t,r=>{let i=n(r);for(let n of Object.keys(i))if(Object.hasOwn(e,n))throw Error(`Duplicate shared table field "${n}" on table "${t}"`);return k(i,[`_id`,`_creationTime`,...f]),{...e,...i}},r)}}const h={tenant:u.string().min(1)};function g(e,t,n={}){return p(e,e=>{let n=t(e);return k(n,[`tenant`,`_id`,`_creationTime`,...f]),{...n,...h}},{...n,serverFields:[...n.serverFields??[],`tenant`]})}function _(...e){let t={};for(let n of e)for(let[e,r]of Object.entries(n)){if(e in t)throw Error(`Table "${e}" is declared by more than one module`);t[e]=r}return t}function v(e){return{args:{paginationOpts:a(l)},result:n(e)}}function y(t,n,r){return r?x(t,n,r):{tableName:t,storage:n,insertSchema:n,table:c(e(n))}}function b(e){let t=s(e);return u.string().refine(e=>t.safeParse(e).success).describe(`Convex document id for table "${e}"; validated against the table by Convex`)}function x(n,r,i){if(!(r instanceof u.ZodDiscriminatedUnion)||r.def.discriminator!==i.discriminator)throw Error(`Variant boundaries require a discriminated union with the configured discriminator`);if(r.def.checks?.length)throw Error(`Variant boundaries do not support union-level refinements`);let a=i.timestamps,o=i.discriminator;if([`_id`,`_creationTime`,...f].includes(o))throw Error(`Variant discriminator cannot be a reserved field`);let l=/* @__PURE__ */ new Map;for(let e of r.options){if(!(e instanceof u.ZodObject)||!(e.def.catchall instanceof u.ZodNever))throw Error(`Variant boundaries require strict object branches`);if(e.def.checks?.length)throw Error(`Variant boundaries do not support object-level refinements`);try{O(e,/* @__PURE__ */ new Set,!0)}catch(e){throw Error(`Variant boundaries require supported value-preserving field validators without object catchalls`,{cause:e})}let r=e.shape[o];if(!(r instanceof u.ZodLiteral)||r.values.size!==1)throw Error(`Variant branches require one string literal discriminator`);let s=[...r.values][0];if(!u.string().safeParse(s).success)throw Error(`Variant branches require a string discriminator`);let c=s;if(l.has(c))throw Error(`Duplicate variant discriminator "${c}"`);if(!Object.hasOwn(i.variants,c))throw Error(`Missing variant configuration "${c}"`);let p={serverFields:[...i.variants[c].serverFields??[]],commandFields:[...i.variants[c].commandFields??[]],publicFields:[...i.variants[c].publicFields??[]]};k(e.shape,[`_id`,`_creationTime`,...a===!1?[]:f]);let m={...e.shape};a&&Object.assign(m,d),A(m,p.serverFields??[],p.commandFields??[],p.publicFields??[],a!==!1);for(let e of[p.serverFields,p.commandFields,p.publicFields])if(e?.includes(o))throw Error(`The variant discriminator is retained automatically and cannot appear in masks`);for(let e of p.commandFields)S(m[e]);let h=u.strictObject({...m}),g=t(()=>u.strictObject(D(m,[...a===!1?[]:f,...p.serverFields??[]]))),_=t(()=>u.strictObject(E(m,[o,...p.commandFields??[]]))),v=e=>e.partial().extend({[o]:r}),y=t(()=>T(m,n)),b=t(()=>v(u.strictObject(D(m,[...a===!1?[]:f,...p.serverFields])))),x=t(()=>v(u.strictObject(E(m,[o,...p.commandFields])))),C=t(()=>u.strictObject(E(m,[o,...p.commandFields]))),w=t(()=>u.strictObject(E(m,[o,...p.publicFields??[]])));l.set(c,{storage:h,get document(){return y()},get insert(){return g()},get update(){return b()},get command(){return _()},get commandUpdate(){return x()},get toolCommand(){return C()},get public(){return w()}})}for(let e of Object.keys(i.variants))if(!l.has(e))throw Error(`Unknown variant configuration "${e}"`);function p(e,t=!1,r=!1){let i=[...l.values()].map(i=>{let a=r&&e===`command`?i.toolCommand:i[e];return r?u.strictObject(Object.fromEntries(Object.entries(a.shape).map(([e,t])=>[e,C(t)]))):t?a.extend({_id:s(n)}):a});if(!i.length)throw Error(`Variant boundaries require at least one branch`);return u.discriminatedUnion(o,i)}let m=p(`storage`),h=t(()=>p(`document`)),g=t(()=>p(`insert`)),_=t(()=>p(`update`)),v=t(()=>p(`command`)),y=t(()=>p(`public`));function x(e=!1){return e?p(`public`,!0):y()}let j;function M(e,t=!1){let r=u.string().parse(e[o]),i=l.get(r);if(!i)throw Error(`Unknown variant discriminator "${r}"`);let a=t?i.public.extend({_id:j??=s(n)}):i.public;return a.parse(Object.fromEntries(Object.keys(a.shape).filter(t=>Object.hasOwn(e,t)).map(t=>[t,e[t]])))}let N=t(()=>({id:u.strictObject({id:b(n)}),insert:p(`command`,!1,!0),update:u.strictObject({id:b(n),data:p(`commandUpdate`,!1,!0)})}));return{tableName:n,storage:m,get schema(){return h()},set schema(e){w(this,`schema`,e)},get insertSchema(){return g()},set insertSchema(e){w(this,`insertSchema`,e)},get updateSchema(){return _()},set updateSchema(e){w(this,`updateSchema`,e)},get commandInput(){return v()},set commandInput(e){w(this,`commandInput`,e)},get publicDto(){return y()},set publicDto(e){w(this,`publicDto`,e)},dto:x,toPublicDto:M,table:c(e(m)),get tools(){return N()},set tools(e){w(this,`tools`,e)}}}function S(e){if(!(e instanceof u.ZodType))throw Error(`Variant tools require classic Zod field schemas`);if(e instanceof u.ZodBigInt||e instanceof u.ZodLiteral&&[...e.values].some(e=>u.bigint().safeParse(e).success))throw Error(`Variant tool command fields cannot contain bigint; JSON Schema cannot represent it`);e instanceof u.ZodOptional||e instanceof u.ZodNullable||e instanceof u.ZodNonOptional?S(e.unwrap()):e instanceof u.ZodArray?S(e.element):e instanceof u.ZodObject?Object.values(e.shape).forEach(S):e instanceof u.ZodUnion?e.options.forEach(S):e instanceof u.ZodRecord?(S(e.keyType),S(e.valueType)):e instanceof u.ZodTuple?(e.def.items.forEach(S),e.def.rest&&S(e.def.rest)):e instanceof u.ZodIntersection&&(S(e.def.left),S(e.def.right))}function C(t){if(!(t instanceof u.ZodType))throw Error(`Variant tools require classic Zod field schemas`);if(t instanceof u.ZodBigInt||t instanceof u.ZodLiteral&&[...t.values].some(e=>u.bigint().safeParse(e).success))throw Error(`Variant tool command fields cannot contain bigint; JSON Schema cannot represent it`);let n=e(t);if(n.kind===`id`){let e=b(n.tableName);return n.isOptional===`optional`?e.optional().refine(e=>t.safeParse(e).success):e.refine(e=>t.safeParse(e).success)}if(t instanceof u.ZodOptional||t instanceof u.ZodNullable||t instanceof u.ZodNonOptional)return t.clone({...t.def,innerType:C(t.unwrap())});if(t instanceof u.ZodArray)return t.clone({...t.def,element:C(t.element)});if(t instanceof u.ZodObject){let e=Object.fromEntries(Object.entries(t.shape).map(([e,t])=>[e,C(t)]));return t.clone(Object.assign({},t.def,{shape:e}))}return t instanceof u.ZodUnion?t.clone({...t.def,options:t.options.map(C)}):t instanceof u.ZodRecord?t.clone({...t.def,keyType:C(t.keyType),valueType:C(t.valueType)}):t instanceof u.ZodTuple?t.clone({...t.def,items:t.def.items.map(C),rest:t.def.rest?C(t.def.rest):null}):t instanceof u.ZodIntersection?t.clone({...t.def,left:C(t.def.left),right:C(t.def.right)}):t}function w(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function T(e,t){return u.strictObject({...e,_id:s(t),_creationTime:u.number()})}function E(e,t){return Object.fromEntries(t.map(t=>[t,e[t]]))}function D(e,t){let n=new Set(t);return Object.fromEntries(Object.entries(e).filter(([e])=>!n.has(e)))}function O(t,n=/* @__PURE__ */ new Set,r=!1){if(n.has(t))return;n.add(t);let i=t._zod.def,a=()=>{throw Error(`DTO extensions require supported value-preserving validation schemas`)};`coerce`in i&&i.coerce&&a(),`normalize`in i&&i.normalize&&a();let o=e=>O(e,n,r);for(let e of i.checks??[])if(e._zod.def.check===`overwrite`&&a(),`normalize`in e._zod.def&&e._zod.def.normalize&&a(),e._zod.def.check===`property`&&o(e._zod.def.schema),e._zod.def.check===`properties`)for(let t of Object.values(e._zod.def.shape))o(t);switch(i.type){case`custom`:if(r&&e(t).kind===`id`)return;a();return;case`string`:case`number`:case`boolean`:case`bigint`:case`date`:case`symbol`:case`null`:case`undefined`:case`void`:case`never`:case`literal`:case`enum`:return;case`object`:if(r&&i.catchall&&i.catchall._zod.def.type!==`never`)throw Error(`Variant fields cannot use object catchalls; use a record field instead`);for(let e of Object.values(i.shape))o(e);i.catchall&&o(i.catchall);return;case`array`:o(i.element);return;case`optional`:case`nullable`:case`nonoptional`:o(i.innerType);return;case`union`:for(let e of i.options)o(e);return;case`intersection`:o(i.left),o(i.right);return;case`tuple`:for(let e of i.items)o(e);i.rest&&o(i.rest);return;case`record`:o(i.keyType),o(i.valueType);return;default:a()}}function k(e,t){for(let n of t)if(Object.hasOwn(e,n))throw Error(`Reserved table field "${n}" cannot be declared`)}function A(e,t,n,r,i=!0){for(let i of[...t,...n,...r])if(!Object.hasOwn(e,i))throw Error(`Unknown table field "${i}"`);let a=/* @__PURE__ */ new Set([...i?f:[],...t]);for(let e of n)if(a.has(e))throw Error(`Server-owned field "${e}" cannot be a command input`)}export{f as TIMESTAMP_FIELDS,i as convexToZod,_ as createModule,m as createTable,b as jsonSafeZid,v as paginated,g as tenantTable,o as zid,p as zodTable,e as zodToConvex,y as zodVariantTable};
|
|
1
|
+
import{zodToConvex as e}from"./zod-convex.mjs";import{memoize as t}from"./modules/contracts/lazy.mjs";import{pageResult as n}from"./querying/shared/page.mjs";import{scalarPaginationSchema as r}from"./querying/filters.mjs";import{convexToZod as i,convexToZod as a,zid as o,zid as s}from"convex-helpers/server/zod4";import{defineTable as c,paginationOptsValidator as l}from"convex/server";import{z as u}from"zod";const d={createdAt:u.number().optional(),updatedAt:u.number().optional(),archivedAt:u.number().optional()},f=[`createdAt`,`updatedAt`,`archivedAt`];function p(n,i,a={}){let o=i(s);L(o,[`_id`,`_creationTime`,...f]);let l={...o,...d};R(l,a.serverFields??[],a.commandFields??[],a.publicFields??[]);let p=u.strictObject({...l}),m=t(()=>N(l,n)),h=[...f,...a.serverFields??[]],g=[...a.commandFields??[]],_=[...a.publicFields??[]],v=t(()=>F(l,h)),y=t(()=>P(l,g)),b=t(()=>u.strictObject({...v()})),x=t(()=>u.strictObject({...v()}).partial()),S=t(()=>u.strictObject({...y()})),C=t(()=>u.strictObject(P(l,_))),w={get schema(){return m()},get insertSchema(){return b()},get updateSchema(){return x()},get commandInput(){return S()},get publicDto(){return C()}},T=t(()=>u.strictObject({})),E=t(()=>/* @__PURE__ */ new Set([`_id`,`_creationTime`,`tenant`,`__proto__`,...f]));function D(e){return k(e)}function k(e){let t=e===!0||e===!1?{_id:e}:e,n=t?.extend??{};if(A(n),!t?._id&&Object.keys(n).length===0)return w.publicDto;let r=u.strictObject({...w.publicDto.shape,...n});return t?._id?r.extend({_id:w.schema.shape._id}):r}function A(e){for(let t of Object.keys(e)){if(E().has(t)||Object.hasOwn(w.publicDto.shape,t))throw Error(`DTO extension collision for field "${t}" on table "${n}"`);I(e[t])}}function j(e,t){let n=t===!0||t===!1?{_id:t}:t;A(n?.extend??{});let r=w.publicDto.parse(Object.fromEntries(Object.keys(w.publicDto.shape).map(t=>[t,e[t]]))),i=n?.extend,a=(i==null?T():u.strictObject(i)).parse(n?.values??{}),o={...r,...a};return n?._id&&(o._id=w.schema.shape._id.parse(`_id`in e?e._id:void 0)),o}function z(e){return e?w.insertSchema.omit(e):w.insertSchema}function B(e){return e?w.updateSchema.omit(e):w.updateSchema}let V=e(p),H=c(V),U=()=>Object.fromEntries(Object.entries(w.schema.shape).map(([t,n])=>[t,e(n)]));function W(e,t){return r(U(),e,t)}let G=t(()=>({insert:w.commandInput,update:u.strictObject({data:u.strictObject({...y()}).partial(),id:O(n)}),id:u.strictObject({id:O(n)})}));return{tableName:n,get schema(){return w.schema},set schema(e){M(this,`schema`,e)},storage:p,get insertSchema(){return w.insertSchema},set insertSchema(e){M(this,`insertSchema`,e)},get updateSchema(){return w.updateSchema},set updateSchema(e){M(this,`updateSchema`,e)},get commandInput(){return w.commandInput},set commandInput(e){M(this,`commandInput`,e)},get publicDto(){return w.publicDto},set publicDto(e){M(this,`publicDto`,e)},dto:D,toPublicDto:j,paginationOpts:W,table:H,insert:z,update:B,get tools(){return G()},set tools(e){M(this,`tools`,e)}}}function m(e){return L(e,[`_id`,`_creationTime`,...f]),function(t,n,r={}){return p(t,r=>{let i=n(r);for(let n of Object.keys(i))if(Object.hasOwn(e,n))throw Error(`Duplicate shared table field "${n}" on table "${t}"`);return L(i,[`_id`,`_creationTime`,...f]),{...e,...i}},r)}}const h={tenant:u.string().min(1)};function g(e,t,n={}){return p(e,e=>{let n=t(e);return L(n,[`tenant`,`_id`,`_creationTime`,...f]),{...n,...h}},{...n,serverFields:[...n.serverFields??[],`tenant`]})}function _(...e){let t={},n=/* @__PURE__ */ new Set;for(let r of e){let e=x(r);if(e){if(n.has(e.name))throw Error(`Namespace "${e.name}" is declared more than once`);n.add(e.name)}for(let[e,n]of Object.entries(r)){if(e in t)throw Error(`Table "${e}" is declared by more than one module`);t[e]=n}}return t}const v=Symbol.for(`cvx-kit/zod-table/namespace`),y=/^[A-Z][A-Za-z0-9]*$/;function b(e,t){if(!e.split(`.`).every(e=>y.test(e)))throw Error(`Namespace "${e}" must be dot-separated PascalCase segments (e.g. "Microsoft.Inventory")`);let n={};for(let[r,i]of Object.entries(t)){if(!/^[a-z][A-Za-z0-9]*$/.test(r))throw Error(`Namespace "${e}" member "${r}" must be a camelCase table name`);if(`tableName`in i){if(i.tableName!==r)throw Error(`Namespace "${e}" member "${r}" holds table "${i.tableName}"; keys must be the table name`);n[r]=i.table}else n[r]=i}return Object.defineProperty(n,v,{value:Object.freeze({name:e,tables:Object.freeze(Object.keys(n))}),enumerable:!1}),n}function x(e){return e[v]}function S(e){return e.charAt(0).toUpperCase()+e.slice(1)}function C(e){return x(e).name}function w(e){return x(e).tables}function T(...e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map;for(let r of e){let e=x(r);if(!e)throw Error(`namespaceIndex accepts only namespace(...) maps`);if(n.has(e.name))throw Error(`Namespace "${e.name}" is declared more than once`);n.set(e.name,e.tables);for(let n of e.tables){let r=t.get(n);if(r)throw Error(`Table "${n}" is declared by namespaces "${r}" and "${e.name}"`);t.set(n,e.name)}}let r=e=>{let n=t.get(e);if(n===void 0)throw Error(`Table "${e}" is not in a namespace`);return n};return{qualifiedName(e){return`${r(e)}.${S(e)}`},namespaceOf(e){return r(e)},memberName:S,tablesOf(e){let t=n.get(e);if(!t)throw Error(`Namespace "${e}" is not indexed`);return t},namespaces:[...n.keys()],has(e){return t.has(e)}}}function E(e){return{args:{paginationOpts:a(l)},result:n(e)}}function D(t,n,r){return r?k(t,n,r):{tableName:t,storage:n,insertSchema:n,table:c(e(n))}}function O(e){let t=s(e);return u.string().refine(e=>t.safeParse(e).success).describe(`Convex document id for table "${e}"; validated against the table by Convex`)}function k(n,r,i){if(!(r instanceof u.ZodDiscriminatedUnion)||r.def.discriminator!==i.discriminator)throw Error(`Variant boundaries require a discriminated union with the configured discriminator`);if(r.def.checks?.length)throw Error(`Variant boundaries do not support union-level refinements`);let a=i.timestamps,o=i.discriminator;if([`_id`,`_creationTime`,...f].includes(o))throw Error(`Variant discriminator cannot be a reserved field`);let l=/* @__PURE__ */ new Map;for(let e of r.options){if(!(e instanceof u.ZodObject)||!(e.def.catchall instanceof u.ZodNever))throw Error(`Variant boundaries require strict object branches`);if(e.def.checks?.length)throw Error(`Variant boundaries do not support object-level refinements`);try{I(e,/* @__PURE__ */ new Set,!0)}catch(e){throw Error(`Variant boundaries require supported value-preserving field validators without object catchalls`,{cause:e})}let r=e.shape[o];if(!(r instanceof u.ZodLiteral)||r.values.size!==1)throw Error(`Variant branches require one string literal discriminator`);let s=[...r.values][0];if(!u.string().safeParse(s).success)throw Error(`Variant branches require a string discriminator`);let c=s;if(l.has(c))throw Error(`Duplicate variant discriminator "${c}"`);if(!Object.hasOwn(i.variants,c))throw Error(`Missing variant configuration "${c}"`);let p={serverFields:[...i.variants[c].serverFields??[]],commandFields:[...i.variants[c].commandFields??[]],publicFields:[...i.variants[c].publicFields??[]]};L(e.shape,[`_id`,`_creationTime`,...a===!1?[]:f]);let m={...e.shape};a&&Object.assign(m,d),R(m,p.serverFields??[],p.commandFields??[],p.publicFields??[],a!==!1);for(let e of[p.serverFields,p.commandFields,p.publicFields])if(e?.includes(o))throw Error(`The variant discriminator is retained automatically and cannot appear in masks`);for(let e of p.commandFields)A(m[e]);let h=u.strictObject({...m}),g=t(()=>u.strictObject(F(m,[...a===!1?[]:f,...p.serverFields??[]]))),_=t(()=>u.strictObject(P(m,[o,...p.commandFields??[]]))),v=e=>e.partial().extend({[o]:r}),y=t(()=>N(m,n)),b=t(()=>v(u.strictObject(F(m,[...a===!1?[]:f,...p.serverFields])))),x=t(()=>v(u.strictObject(P(m,[o,...p.commandFields])))),S=t(()=>u.strictObject(P(m,[o,...p.commandFields]))),C=t(()=>u.strictObject(P(m,[o,...p.publicFields??[]])));l.set(c,{storage:h,get document(){return y()},get insert(){return g()},get update(){return b()},get command(){return _()},get commandUpdate(){return x()},get toolCommand(){return S()},get public(){return C()}})}for(let e of Object.keys(i.variants))if(!l.has(e))throw Error(`Unknown variant configuration "${e}"`);function p(e,t=!1,r=!1){let i=[...l.values()].map(i=>{let a=r&&e===`command`?i.toolCommand:i[e];return r?u.strictObject(Object.fromEntries(Object.entries(a.shape).map(([e,t])=>[e,j(t)]))):t?a.extend({_id:s(n)}):a});if(!i.length)throw Error(`Variant boundaries require at least one branch`);return u.discriminatedUnion(o,i)}let m=p(`storage`),h=t(()=>p(`document`)),g=t(()=>p(`insert`)),_=t(()=>p(`update`)),v=t(()=>p(`command`)),y=t(()=>p(`public`));function b(e=!1){return e?p(`public`,!0):y()}let x;function S(e,t=!1){let r=u.string().parse(e[o]),i=l.get(r);if(!i)throw Error(`Unknown variant discriminator "${r}"`);let a=t?i.public.extend({_id:x??=s(n)}):i.public;return a.parse(Object.fromEntries(Object.keys(a.shape).filter(t=>Object.hasOwn(e,t)).map(t=>[t,e[t]])))}let C=t(()=>({id:u.strictObject({id:O(n)}),insert:p(`command`,!1,!0),update:u.strictObject({id:O(n),data:p(`commandUpdate`,!1,!0)})}));return{tableName:n,storage:m,get schema(){return h()},set schema(e){M(this,`schema`,e)},get insertSchema(){return g()},set insertSchema(e){M(this,`insertSchema`,e)},get updateSchema(){return _()},set updateSchema(e){M(this,`updateSchema`,e)},get commandInput(){return v()},set commandInput(e){M(this,`commandInput`,e)},get publicDto(){return y()},set publicDto(e){M(this,`publicDto`,e)},dto:b,toPublicDto:S,table:c(e(m)),get tools(){return C()},set tools(e){M(this,`tools`,e)}}}function A(e){if(!(e instanceof u.ZodType))throw Error(`Variant tools require classic Zod field schemas`);if(e instanceof u.ZodBigInt||e instanceof u.ZodLiteral&&[...e.values].some(e=>u.bigint().safeParse(e).success))throw Error(`Variant tool command fields cannot contain bigint; JSON Schema cannot represent it`);e instanceof u.ZodOptional||e instanceof u.ZodNullable||e instanceof u.ZodNonOptional?A(e.unwrap()):e instanceof u.ZodArray?A(e.element):e instanceof u.ZodObject?Object.values(e.shape).forEach(A):e instanceof u.ZodUnion?e.options.forEach(A):e instanceof u.ZodRecord?(A(e.keyType),A(e.valueType)):e instanceof u.ZodTuple?(e.def.items.forEach(A),e.def.rest&&A(e.def.rest)):e instanceof u.ZodIntersection&&(A(e.def.left),A(e.def.right))}function j(t){if(!(t instanceof u.ZodType))throw Error(`Variant tools require classic Zod field schemas`);if(t instanceof u.ZodBigInt||t instanceof u.ZodLiteral&&[...t.values].some(e=>u.bigint().safeParse(e).success))throw Error(`Variant tool command fields cannot contain bigint; JSON Schema cannot represent it`);let n=e(t);if(n.kind===`id`){let e=O(n.tableName);return n.isOptional===`optional`?e.optional().refine(e=>t.safeParse(e).success):e.refine(e=>t.safeParse(e).success)}if(t instanceof u.ZodOptional||t instanceof u.ZodNullable||t instanceof u.ZodNonOptional)return t.clone({...t.def,innerType:j(t.unwrap())});if(t instanceof u.ZodArray)return t.clone({...t.def,element:j(t.element)});if(t instanceof u.ZodObject){let e=Object.fromEntries(Object.entries(t.shape).map(([e,t])=>[e,j(t)]));return t.clone(Object.assign({},t.def,{shape:e}))}return t instanceof u.ZodUnion?t.clone({...t.def,options:t.options.map(j)}):t instanceof u.ZodRecord?t.clone({...t.def,keyType:j(t.keyType),valueType:j(t.valueType)}):t instanceof u.ZodTuple?t.clone({...t.def,items:t.def.items.map(j),rest:t.def.rest?j(t.def.rest):null}):t instanceof u.ZodIntersection?t.clone({...t.def,left:j(t.def.left),right:j(t.def.right)}):t}function M(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function N(e,t){return u.strictObject({...e,_id:s(t),_creationTime:u.number()})}function P(e,t){return Object.fromEntries(t.map(t=>[t,e[t]]))}function F(e,t){let n=new Set(t);return Object.fromEntries(Object.entries(e).filter(([e])=>!n.has(e)))}function I(t,n=/* @__PURE__ */ new Set,r=!1){if(n.has(t))return;n.add(t);let i=t._zod.def,a=()=>{throw Error(`DTO extensions require supported value-preserving validation schemas`)};`coerce`in i&&i.coerce&&a(),`normalize`in i&&i.normalize&&a();let o=e=>I(e,n,r);for(let e of i.checks??[])if(e._zod.def.check===`overwrite`&&a(),`normalize`in e._zod.def&&e._zod.def.normalize&&a(),e._zod.def.check===`property`&&o(e._zod.def.schema),e._zod.def.check===`properties`)for(let t of Object.values(e._zod.def.shape))o(t);switch(i.type){case`custom`:if(r&&e(t).kind===`id`)return;a();return;case`string`:case`number`:case`boolean`:case`bigint`:case`date`:case`symbol`:case`null`:case`undefined`:case`void`:case`never`:case`literal`:case`enum`:return;case`object`:if(r&&i.catchall&&i.catchall._zod.def.type!==`never`)throw Error(`Variant fields cannot use object catchalls; use a record field instead`);for(let e of Object.values(i.shape))o(e);i.catchall&&o(i.catchall);return;case`array`:o(i.element);return;case`optional`:case`nullable`:case`nonoptional`:o(i.innerType);return;case`union`:for(let e of i.options)o(e);return;case`intersection`:o(i.left),o(i.right);return;case`tuple`:for(let e of i.items)o(e);i.rest&&o(i.rest);return;case`record`:o(i.keyType),o(i.valueType);return;default:a()}}function L(e,t){for(let n of t)if(Object.hasOwn(e,n))throw Error(`Reserved table field "${n}" cannot be declared`)}function R(e,t,n,r,i=!0){for(let i of[...t,...n,...r])if(!Object.hasOwn(e,i))throw Error(`Unknown table field "${i}"`);let a=/* @__PURE__ */ new Set([...i?f:[],...t]);for(let e of n)if(a.has(e))throw Error(`Server-owned field "${e}" cannot be a command input`)}export{f as TIMESTAMP_FIELDS,i as convexToZod,_ as createModule,m as createTable,O as jsonSafeZid,S as memberName,b as namespace,T as namespaceIndex,C as namespaceName,E as paginated,w as tablesOf,g as tenantTable,o as zid,p as zodTable,e as zodToConvex,D as zodVariantTable};
|
|
2
2
|
//# sourceMappingURL=zod-table.mjs.map
|