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
package/dist/effect.d.mts
CHANGED
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
import { OperationExecutor, OperationPublicResult, OperationTool, OperationToolConverter, OperationToolDefinition, OperationToolJsonSchema, OperationToolOutcome, SelectedOperation, bindOperationExecutor, createOperationTools, operationToolDialect, selectOperation } from "./modules/contracts/exposure.mjs";
|
|
2
2
|
import { ContractDecoderError, ContractDecoderRequirements, ContractValidationError, EffectDecoder, decodeEffectContract, effectContract, effectSchema, effectStandardSchema } from "./modules/effect/schema.mjs";
|
|
3
|
+
import { NestedAuditMode, RequestScope } from "./modules/effect/scope.mjs";
|
|
3
4
|
import { CallbackError, CallbackRequirements, EffectMiddlewareInput, EffectOperationArgument, EffectOperationError, EffectOperationHandlerResult, EffectOperationInput, EffectOperationRequirements, EffectOperationResult, EffectPreparation, EffectValue, effectOperationFactory } from "./modules/effect/operation.mjs";
|
|
4
5
|
import { EffectZodApiBuilder, effectZodApiBuilder } from "./modules/effect/api-zod.mjs";
|
|
5
6
|
import { EffectAuthFunctions, createEffectAuthFunctions } from "./modules/effect/auth.mjs";
|
|
7
|
+
import { FailureAuditEntry, FailureAuditOptions } from "./modules/effect/failure-audit.mjs";
|
|
8
|
+
import { EffectErrors, effectErrors } from "./modules/effect/failures.mjs";
|
|
9
|
+
import { ActionAuditWriterError, EffectActionDependencies, EffectActionRegistry } from "./modules/effect/action.mjs";
|
|
6
10
|
import { EffectFoundationOptions, createEffectFoundation } from "./modules/effect/foundation.mjs";
|
|
7
11
|
import { EffectIdempotencyPreparation, effectTransactionalIdempotency } from "./modules/effect/idempotency.mjs";
|
|
8
12
|
import { EffectCrudConfig, EffectCrudContext, EffectCrudPage, EffectCrudPagination, EffectCrudRepository, EffectCrudTable, createEffectCrud } from "./modules/effect/crud.mjs";
|
|
@@ -10,4 +14,4 @@ import { EffectApiBuilder, effectApiBuilder } from "./modules/effect/api.mjs";
|
|
|
10
14
|
import { projectErrorCause } from "./modules/effect/errors.mjs";
|
|
11
15
|
import { EffectReceiptProtectedWorkflowMutation, effectReceiptWorkflowMutation, effectTerminalWorkflowAttempt, effectWorkflowAttempt, effectWorkflowStatusBindings } from "./modules/effect/workflow.mjs";
|
|
12
16
|
import "./modules/effect/client.mjs";
|
|
13
|
-
export { type CallbackError, type CallbackRequirements, type ContractDecoderError, type ContractDecoderRequirements, ContractValidationError, type EffectApiBuilder, type EffectAuthFunctions, type EffectCrudConfig, type EffectCrudContext, type EffectCrudPage, type EffectCrudPagination, type EffectCrudRepository, type EffectCrudTable, type EffectDecoder, type EffectFoundationOptions, type EffectIdempotencyPreparation, type EffectMiddlewareInput, type EffectOperationArgument, type EffectOperationError, type EffectOperationHandlerResult, type EffectOperationInput, type EffectOperationRequirements, type EffectOperationResult, type EffectPreparation, type EffectReceiptProtectedWorkflowMutation, type EffectValue, type EffectZodApiBuilder, type OperationExecutor, type OperationPublicResult, type OperationTool, type OperationToolConverter, type OperationToolDefinition, type OperationToolJsonSchema, type OperationToolOutcome, type SelectedOperation, bindOperationExecutor, createEffectAuthFunctions, createEffectCrud, createEffectFoundation, createOperationTools, decodeEffectContract, effectApiBuilder, effectContract, effectOperationFactory, effectReceiptWorkflowMutation, effectSchema, effectStandardSchema, effectTerminalWorkflowAttempt, effectTransactionalIdempotency, effectWorkflowAttempt, effectWorkflowStatusBindings, effectZodApiBuilder, operationToolDialect, projectErrorCause, selectOperation };
|
|
17
|
+
export { ActionAuditWriterError, type CallbackError, type CallbackRequirements, type ContractDecoderError, type ContractDecoderRequirements, ContractValidationError, type EffectActionDependencies, type EffectActionRegistry, type EffectApiBuilder, type EffectAuthFunctions, type EffectCrudConfig, type EffectCrudContext, type EffectCrudPage, type EffectCrudPagination, type EffectCrudRepository, type EffectCrudTable, type EffectDecoder, type EffectErrors, type EffectFoundationOptions, type EffectIdempotencyPreparation, type EffectMiddlewareInput, type EffectOperationArgument, type EffectOperationError, type EffectOperationHandlerResult, type EffectOperationInput, type EffectOperationRequirements, type EffectOperationResult, type EffectPreparation, type EffectReceiptProtectedWorkflowMutation, type EffectValue, type EffectZodApiBuilder, type FailureAuditEntry, type FailureAuditOptions, type NestedAuditMode, type OperationExecutor, type OperationPublicResult, type OperationTool, type OperationToolConverter, type OperationToolDefinition, type OperationToolJsonSchema, type OperationToolOutcome, type RequestScope, type SelectedOperation, bindOperationExecutor, createEffectAuthFunctions, createEffectCrud, createEffectFoundation, createOperationTools, decodeEffectContract, effectApiBuilder, effectContract, effectErrors, effectOperationFactory, effectReceiptWorkflowMutation, effectSchema, effectStandardSchema, effectTerminalWorkflowAttempt, effectTransactionalIdempotency, effectWorkflowAttempt, effectWorkflowStatusBindings, effectZodApiBuilder, operationToolDialect, projectErrorCause, selectOperation };
|
package/dist/effect.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{bindOperationExecutor as e,createOperationTools as t,operationToolDialect as n,selectOperation as r}from"./modules/contracts/exposure.mjs";import{projectErrorCause as i}from"./modules/effect/errors.mjs";import{effectZodApiBuilder as a}from"./modules/effect/api-zod.mjs";import{createEffectAuthFunctions as o}from"./modules/effect/auth.mjs";import{effectOperationFactory as s}from"./modules/effect/operation.mjs";import{ContractValidationError as c,decodeEffectContract as l,effectContract as u,effectSchema as d,effectStandardSchema as f}from"./modules/effect/schema.mjs";import{
|
|
1
|
+
import{bindOperationExecutor as e,createOperationTools as t,operationToolDialect as n,selectOperation as r}from"./modules/contracts/exposure.mjs";import{projectErrorCause as i}from"./modules/effect/errors.mjs";import{effectZodApiBuilder as a}from"./modules/effect/api-zod.mjs";import{createEffectAuthFunctions as o}from"./modules/effect/auth.mjs";import{effectOperationFactory as s}from"./modules/effect/operation.mjs";import{ContractValidationError as c,decodeEffectContract as l,effectContract as u,effectSchema as d,effectStandardSchema as f}from"./modules/effect/schema.mjs";import{effectErrors as p}from"./modules/effect/failures.mjs";import{ActionAuditWriterError as m}from"./modules/effect/action.mjs";import{createEffectFoundation as h}from"./modules/effect/foundation.mjs";import{effectTransactionalIdempotency as g}from"./modules/effect/idempotency.mjs";import{createEffectCrud as _}from"./modules/effect/crud.mjs";import{effectApiBuilder as v}from"./modules/effect/api.mjs";import{effectReceiptWorkflowMutation as y,effectTerminalWorkflowAttempt as b,effectWorkflowAttempt as x,effectWorkflowStatusBindings as S}from"./modules/effect/workflow.mjs";export{m as ActionAuditWriterError,c as ContractValidationError,e as bindOperationExecutor,o as createEffectAuthFunctions,_ as createEffectCrud,h as createEffectFoundation,t as createOperationTools,l as decodeEffectContract,v as effectApiBuilder,u as effectContract,p as effectErrors,s as effectOperationFactory,y as effectReceiptWorkflowMutation,d as effectSchema,f as effectStandardSchema,b as effectTerminalWorkflowAttempt,g as effectTransactionalIdempotency,x as effectWorkflowAttempt,S as effectWorkflowStatusBindings,a as effectZodApiBuilder,n as operationToolDialect,i as projectErrorCause,r as selectOperation};
|
|
@@ -19,6 +19,6 @@ export declare function domainHelpers(entries: Readonly<Record<string, object>>)
|
|
|
19
19
|
/** Bind only opaque schema references; never invoke user callbacks at construction. */
|
|
20
20
|
export declare function bindDomainImplementation(key: string, declaration: object, implementation: object): {};
|
|
21
21
|
/** Snapshot records and verify key ownership before the executor closes over them. */
|
|
22
|
-
export declare function snapshotOperations(operations: Readonly<Record<string, object>>, contract: DomainContract | undefined, section: 'commands' | 'queries', audit?: (resolution: never, context: never) => unknown): Readonly<Record<string, Readonly<Record<string, unknown>>>>;
|
|
22
|
+
export declare function snapshotOperations(operations: Readonly<Record<string, object>>, contract: DomainContract | undefined, section: 'commands' | 'queries' | 'actions', audit?: (resolution: never, context: never, scope: never) => unknown): Readonly<Record<string, Readonly<Record<string, unknown>>>>;
|
|
23
23
|
//#endregion
|
|
24
24
|
//# sourceMappingURL=binding.d.mts.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{memoize as e}from"./lazy.mjs";const t=[`input`,`result`,`classification`,`replayResult`,`wire`],n=/* @__PURE__ */ new WeakMap,r=/* @__PURE__ */ new WeakMap,i=/* @__PURE__ */ new WeakMap;function a(e){let t=Object.fromEntries(Object.keys(e).map(t=>[t,n=>{if(!c(e,t))return o(t,e[t],n);let r={...n};return i.set(r,{key:t,entries:e}),r}])),n=t.handler;return t.handler=(t,i)=>{if(typeof t!=`function`&&n)return n(t);if(typeof t!=`function`)throw Error(`Invalid operation handler`);let a={...i,handler:t};return r.set(a,e),a},t}function o(e,r,i){for(let t of[`handler`,`audit`,`prepare`,`guard`,`middleware`,`context`])if(Object.prototype.hasOwnProperty.call(r,t))throw Error(`Domain contract ${e} cannot contain ${t}`);for(let n of t)if(Object.prototype.hasOwnProperty.call(i,n))throw Error(`Contracted operation ${e} cannot override ${n}`);let a={...i,...r};return n.set(a,{key:e,declaration:r}),a}function s(a,s,l,u){if(u!==void 0&&typeof u!=`function`)throw Error(`Invalid registry audit callback`);let d=s?.[l];if(s&&!d)throw Error(`Domain contract has no ${l} section`);let f=Object.keys(a);if(d&&(f.length!==Object.keys(d).length||f.some(e=>!Object.prototype.hasOwnProperty.call(d,e))))throw Error(`Contract operation keys must match exactly`);let p=e=>{let s=a[e],c=i.get(s);if(c&&(s=o(c.key,c.entries[c.key],s)),d){if(r.has(s)){if(r.get(s)!==d)throw Error(`Operation ${e} must use its own contract helper`);s=o(e,d[e],s)}let i=n.get(s);if(!i||i.key!==e||i.declaration!==d[e]||t.some(t=>s[t]!==d[e][t]))throw Error(`Operation ${e} must use its own contract helper`)}let f={...s};if(f.wire&&=Object.freeze({...f.wire}),l===`commands`){let t=f.audit;if(t!==void 0&&typeof t!=`function`)throw Error(`Invalid audit for ${e}`);if(t===void 0
|
|
1
|
+
import{memoize as e}from"./lazy.mjs";const t=[`input`,`result`,`classification`,`replayResult`,`wire`],n=/* @__PURE__ */ new WeakMap,r=/* @__PURE__ */ new WeakMap,i=/* @__PURE__ */ new WeakMap;function a(e){let t=Object.fromEntries(Object.keys(e).map(t=>[t,n=>{if(!c(e,t))return o(t,e[t],n);let r={...n};return i.set(r,{key:t,entries:e}),r}])),n=t.handler;return t.handler=(t,i)=>{if(typeof t!=`function`&&n)return n(t);if(typeof t!=`function`)throw Error(`Invalid operation handler`);let a={...i,handler:t};return r.set(a,e),a},t}function o(e,r,i){for(let t of[`handler`,`audit`,`prepare`,`guard`,`middleware`,`context`])if(Object.prototype.hasOwnProperty.call(r,t))throw Error(`Domain contract ${e} cannot contain ${t}`);for(let n of t)if(Object.prototype.hasOwnProperty.call(i,n))throw Error(`Contracted operation ${e} cannot override ${n}`);let a={...i,...r};return n.set(a,{key:e,declaration:r}),a}function s(a,s,l,u){if(u!==void 0&&typeof u!=`function`)throw Error(`Invalid registry audit callback`);let d=s?.[l];if(s&&!d)throw Error(`Domain contract has no ${l} section`);let f=Object.keys(a);if(d&&(f.length!==Object.keys(d).length||f.some(e=>!Object.prototype.hasOwnProperty.call(d,e))))throw Error(`Contract operation keys must match exactly`);let p=e=>{let s=a[e],c=i.get(s);if(c&&(s=o(c.key,c.entries[c.key],s)),d){if(r.has(s)){if(r.get(s)!==d)throw Error(`Operation ${e} must use its own contract helper`);s=o(e,d[e],s)}let i=n.get(s);if(!i||i.key!==e||i.declaration!==d[e]||t.some(t=>s[t]!==d[e][t]))throw Error(`Operation ${e} must use its own contract helper`)}let f={...s};if(f.wire&&=Object.freeze({...f.wire}),l===`commands`||l===`actions`){let t=f.audit;if(t!==void 0&&typeof t!=`function`)throw Error(`Invalid audit for ${e}`);if(t===void 0&&!u&&l===`commands`)throw Error(`Command ${e} requires an audit callback`);t===void 0&&u&&(f.audit=(t,n,r)=>u({operation:e,input:t.command,result:t.result},n,r))}return Object.freeze(f)},m={};for(let t of f)d&&c(d,t)?Object.defineProperty(m,t,{enumerable:!0,get:e(()=>p(t))}):m[t]=p(t);return Object.freeze(m)}function c(e,n){let r=Object.getOwnPropertyDescriptor(e,n);if(!r)return!1;if(r.get)return!0;let i=r.value;return!!i&&typeof i==`object`&&t.some(e=>!!Object.getOwnPropertyDescriptor(i,e)?.get)}export{o as bindDomainImplementation,a as domainHelpers,s as snapshotOperations};
|
|
2
2
|
//# sourceMappingURL=binding.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"binding.mjs","names":["protectedFields","bindings","pending","deferred","domainHelpers","helpers","entries","key","isLazyOperation","bindDomainImplementation","implementation","draft","namedHandler","handler","options","field","declaration","definition","snapshotOperations","audit","declarations","contract","section","keys","operations","bind","original","binding","override","resolution","context","snapshot","memoize","descriptor","value"],"sources":["../../../src/modules/contracts/binding.ts"],"sourcesContent":["/* oxlint-disable anti-slop/no-object-parameters, anti-slop/no-unsafe-dictionary-type, anti-slop/no-known-value-widening, anti-slop/no-runtime-typeof, anti-slop/no-unknown-parameters, anti-slop/no-unknown-returns -- Configuration boundary validates heterogeneous own-key records and callback presence; validators remain opaque identities. */\nimport { memoize } from './lazy'\nimport type { DomainContract, DomainOperationContract } from './domain'\n\ndeclare const declaredSchemas: unique symbol\n/** Private evidence for contextual inference; schemas are installed only at registration. */\nexport type DeclaredSchemas<Entry> = { readonly [declaredSchemas]: Entry }\nexport type BoundOperations<\n\tOperations extends Readonly<\n\t\tRecord<keyof Entries, { handler: (...arguments_: never[]) => unknown }>\n\t>,\n\tEntries extends Readonly<Record<string, DomainOperationContract>>,\n> = {\n\t[Key in keyof Entries]: Entries[Key] &\n\t\tOperations[Key] & {\n\t\t\tinput: Entries[Key]['input']\n\t\t\tresult: Entries[Key]['result']\n\t\t\thandler: Operations[Key]['handler']\n\t\t}\n}\n\n// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\nconst protectedFields = ['input', 'result', 'classification', 'replayResult', 'wire'] as const\nconst bindings = new WeakMap<object, { key: string; declaration: object }>()\nconst pending = new WeakMap<object, Readonly<Record<string, object>>>()\nconst deferred = new WeakMap<object, { key: string; entries: Readonly<Record<string, object>> }>()\n\n/** Both adapters bind declarations through the same configuration boundary. */\nexport function domainHelpers(entries: Readonly<Record<string, object>>) {\n\tconst helpers = Object.fromEntries(\n\t\tObject.keys(entries).map((key) => [\n\t\t\tkey,\n\t\t\t(implementation: object) => {\n\t\t\t\tif (!isLazyOperation(entries, key))\n\t\t\t\t\treturn bindDomainImplementation(key, entries[key], implementation)\n\t\t\t\tconst draft = { ...implementation }\n\t\t\t\tdeferred.set(draft, { key, entries })\n\t\t\t\treturn draft\n\t\t\t},\n\t\t]),\n\t)\n\tconst namedHandler = helpers.handler\n\thelpers.handler = (handler: Function | object, options?: object) => {\n\t\tif (typeof handler !== 'function' && namedHandler) return namedHandler(handler)\n\t\tif (typeof handler !== 'function') throw Error('Invalid operation handler')\n\t\tconst implementation = { ...options, handler }\n\t\tpending.set(implementation, entries)\n\t\treturn implementation\n\t}\n\treturn helpers\n}\n\n/** Bind only opaque schema references; never invoke user callbacks at construction. */\nexport function bindDomainImplementation(key: string, declaration: object, implementation: object) {\n\tfor (const field of ['handler', 'audit', 'prepare', 'guard', 'middleware', 'context']) {\n\t\tif (Object.prototype.hasOwnProperty.call(declaration, field))\n\t\t\tthrow Error(`Domain contract ${key} cannot contain ${field}`)\n\t}\n\tfor (const field of protectedFields) {\n\t\tif (Object.prototype.hasOwnProperty.call(implementation, field))\n\t\t\tthrow Error(`Contracted operation ${key} cannot override ${field}`)\n\t}\n\tconst definition = { ...implementation, ...declaration }\n\tbindings.set(definition, { key, declaration })\n\treturn definition\n}\n\n/** Snapshot records and verify key ownership before the executor closes over them. */\nexport function snapshotOperations(\n\toperations: Readonly<Record<string, object>>,\n\tcontract: DomainContract | undefined,\n\tsection: 'commands' | 'queries',\n\taudit?: (resolution: never, context: never) => unknown,\n) {\n\tif (audit !== undefined && typeof audit !== 'function')\n\t\tthrow Error('Invalid registry audit callback')\n\tconst declarations = contract?.[section]\n\tif (contract && !declarations) throw Error(`Domain contract has no ${section} section`)\n\tconst keys = Object.keys(operations)\n\tif (\n\t\tdeclarations &&\n\t\t(keys.length !== Object.keys(declarations).length ||\n\t\t\tkeys.some((key) => !Object.prototype.hasOwnProperty.call(declarations, key)))\n\t)\n\t\tthrow Error('Contract operation keys must match exactly')\n\tconst bind = (key: string) => {\n\t\tlet original = operations[key]\n\t\t// A deferred helper result binds to its own declaration wherever it is registered.\n\t\tconst draft = deferred.get(original)\n\t\tif (draft) original = bindDomainImplementation(draft.key, draft.entries[draft.key], original)\n\t\tif (declarations) {\n\t\t\tif (pending.has(original)) {\n\t\t\t\tif (pending.get(original) !== declarations)\n\t\t\t\t\tthrow Error(`Operation ${key} must use its own contract helper`)\n\t\t\t\toriginal = bindDomainImplementation(key, declarations[key], original)\n\t\t\t}\n\t\t\tconst binding = bindings.get(original)\n\t\t\tif (\n\t\t\t\t!binding ||\n\t\t\t\tbinding.key !== key ||\n\t\t\t\tbinding.declaration !== declarations[key] ||\n\t\t\t\tprotectedFields.some(\n\t\t\t\t\t(field) =>\n\t\t\t\t\t\t// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\n\t\t\t\t\t\t(original as Record<string, unknown>)[field] !==\n\t\t\t\t\t\t// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\n\t\t\t\t\t\t(declarations[key] as Record<string, unknown>)[field],\n\t\t\t\t)\n\t\t\t)\n\t\t\t\tthrow Error(`Operation ${key} must use its own contract helper`)\n\t\t}\n\t\t// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\n\t\tconst definition = { ...original } as Record<string, unknown>\n\t\tif (definition.wire) {\n\t\t\t// SAFETY: wire is configuration, while its schema stays an opaque reference.\n\t\t\tdefinition.wire = Object.freeze({ ...(definition.wire as object) })\n\t\t}\n\t\tif (section === 'commands') {\n\t\t\tconst override = definition.audit\n\t\t\tif (override !== undefined && typeof override !== 'function')\n\t\t\t\tthrow Error(`Invalid audit for ${key}`)\n\t\t\tif (override === undefined) {\n\t\t\t\tif (!audit) throw Error(`Command ${key} requires an audit callback`)\n\t\t\t\tdefinition.audit = (resolution: { command: unknown; result: unknown }, context: unknown) =>\n\t\t\t\t\taudit(\n\t\t\t\t\t\t// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\n\t\t\t\t\t\t{ operation: key, input: resolution.command, result: resolution.result } as never,\n\t\t\t\t\t\t// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\n\t\t\t\t\t\tcontext as never,\n\t\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\t// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\n\t\treturn Object.freeze(definition)\n\t}\n\tconst snapshot: Record<string, Readonly<Record<string, unknown>>> = {}\n\tfor (const key of keys) {\n\t\tif (declarations && isLazyOperation(declarations, key))\n\t\t\tObject.defineProperty(snapshot, key, { enumerable: true, get: memoize(() => bind(key)) })\n\t\telse snapshot[key] = bind(key)\n\t}\n\treturn Object.freeze(snapshot)\n}\n\n/** Getter-declared operations, or operations with getter-declared protected fields, bind on first access. */\nfunction isLazyOperation(entries: Readonly<Record<string, object>>, key: string) {\n\tconst descriptor = Object.getOwnPropertyDescriptor(entries, key)\n\tif (!descriptor) return false\n\tif (descriptor.get) return true\n\tconst value: unknown = descriptor.value\n\treturn (\n\t\t!!value &&\n\t\ttypeof value === 'object' &&\n\t\tprotectedFields.some((field) => !!Object.getOwnPropertyDescriptor(value, field)?.get)\n\t)\n}\n"],"mappings":"qCAsBA,MAAMA,EAAkB,CAAC,QAAS,SAAU,iBAAkB,eAAgB,MAAM,EAC9EC,kBAAW,IAAI,QACfC,kBAAU,IAAI,QACdC,kBAAW,IAAI,QAGrB,SAAgBC,EAAc,EAA2C,CACxE,IAAMC,EAAU,OAAO,YACtB,OAAO,KAAKC,CAAO,CAA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AEvEC,CACD,CACF,CACD,CAEA,OAAO,OAAO,OAAOb,CAAU,CAChC,EACMc,EAA8D,CAAC,EACrE,IAAK,IAAMxB,KAAOgB,EACbH,GAAgBZ,EAAgBY,EAAcb,CAAG,EACpD,OAAO,eAAewB,EAAUxB,EAAK,CAAE,WAAY,GAAM,IAAKyB,MAAcP,EAAKlB,CAAG,CAAC,CAAE,CAAC,EACpF,EAASA,GAAOkB,EAAKlB,CAAG,EAE9B,OAAO,OAAO,OAAOwB,CAAQ,CAC9B,CAGA,SAASvB,EAAgB,EAA2C,EAAa,CAChF,IAAMyB,EAAa,OAAO,yBAAyB3B,EAASC,CAAG,EAC/D,GAAI,CAAC0B,EAAY,MAAO,GACxB,GAAIA,EAAW,IAAK,MAAO,GAC3B,IAAMC,EAAiBD,EAAW,MAClC,MACC,CAAC,CAACC,GACF,OAAOA,GAAU,UACjBlC,EAAgB,KAAM,GAAU,CAAC,CAAC,OAAO,yBAAyBkC,EAAOnB,CAAK,CAAC,EAAE,GAAG,CAEtF"}
|
|
1
|
+
{"version":3,"file":"binding.mjs","names":["protectedFields","bindings","pending","deferred","domainHelpers","helpers","entries","key","isLazyOperation","bindDomainImplementation","implementation","draft","namedHandler","handler","options","field","declaration","definition","snapshotOperations","audit","declarations","contract","section","keys","operations","bind","original","binding","override","resolution","context","scope","snapshot","memoize","descriptor","value"],"sources":["../../../src/modules/contracts/binding.ts"],"sourcesContent":["/* oxlint-disable anti-slop/no-object-parameters, anti-slop/no-unsafe-dictionary-type, anti-slop/no-known-value-widening, anti-slop/no-runtime-typeof, anti-slop/no-unknown-parameters, anti-slop/no-unknown-returns -- Configuration boundary validates heterogeneous own-key records and callback presence; validators remain opaque identities. */\nimport { memoize } from './lazy'\nimport type { DomainContract, DomainOperationContract } from './domain'\n\ndeclare const declaredSchemas: unique symbol\n/** Private evidence for contextual inference; schemas are installed only at registration. */\nexport type DeclaredSchemas<Entry> = { readonly [declaredSchemas]: Entry }\nexport type BoundOperations<\n\tOperations extends Readonly<\n\t\tRecord<keyof Entries, { handler: (...arguments_: never[]) => unknown }>\n\t>,\n\tEntries extends Readonly<Record<string, DomainOperationContract>>,\n> = {\n\t[Key in keyof Entries]: Entries[Key] &\n\t\tOperations[Key] & {\n\t\t\tinput: Entries[Key]['input']\n\t\t\tresult: Entries[Key]['result']\n\t\t\thandler: Operations[Key]['handler']\n\t\t}\n}\n\n// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\nconst protectedFields = ['input', 'result', 'classification', 'replayResult', 'wire'] as const\nconst bindings = new WeakMap<object, { key: string; declaration: object }>()\nconst pending = new WeakMap<object, Readonly<Record<string, object>>>()\nconst deferred = new WeakMap<object, { key: string; entries: Readonly<Record<string, object>> }>()\n\n/** Both adapters bind declarations through the same configuration boundary. */\nexport function domainHelpers(entries: Readonly<Record<string, object>>) {\n\tconst helpers = Object.fromEntries(\n\t\tObject.keys(entries).map((key) => [\n\t\t\tkey,\n\t\t\t(implementation: object) => {\n\t\t\t\tif (!isLazyOperation(entries, key))\n\t\t\t\t\treturn bindDomainImplementation(key, entries[key], implementation)\n\t\t\t\tconst draft = { ...implementation }\n\t\t\t\tdeferred.set(draft, { key, entries })\n\t\t\t\treturn draft\n\t\t\t},\n\t\t]),\n\t)\n\tconst namedHandler = helpers.handler\n\thelpers.handler = (handler: Function | object, options?: object) => {\n\t\tif (typeof handler !== 'function' && namedHandler) return namedHandler(handler)\n\t\tif (typeof handler !== 'function') throw Error('Invalid operation handler')\n\t\tconst implementation = { ...options, handler }\n\t\tpending.set(implementation, entries)\n\t\treturn implementation\n\t}\n\treturn helpers\n}\n\n/** Bind only opaque schema references; never invoke user callbacks at construction. */\nexport function bindDomainImplementation(key: string, declaration: object, implementation: object) {\n\tfor (const field of ['handler', 'audit', 'prepare', 'guard', 'middleware', 'context']) {\n\t\tif (Object.prototype.hasOwnProperty.call(declaration, field))\n\t\t\tthrow Error(`Domain contract ${key} cannot contain ${field}`)\n\t}\n\tfor (const field of protectedFields) {\n\t\tif (Object.prototype.hasOwnProperty.call(implementation, field))\n\t\t\tthrow Error(`Contracted operation ${key} cannot override ${field}`)\n\t}\n\tconst definition = { ...implementation, ...declaration }\n\tbindings.set(definition, { key, declaration })\n\treturn definition\n}\n\n/** Snapshot records and verify key ownership before the executor closes over them. */\nexport function snapshotOperations(\n\toperations: Readonly<Record<string, object>>,\n\tcontract: DomainContract | undefined,\n\tsection: 'commands' | 'queries' | 'actions',\n\taudit?: (resolution: never, context: never, scope: never) => unknown,\n) {\n\tif (audit !== undefined && typeof audit !== 'function')\n\t\tthrow Error('Invalid registry audit callback')\n\tconst declarations = contract?.[section]\n\tif (contract && !declarations) throw Error(`Domain contract has no ${section} section`)\n\tconst keys = Object.keys(operations)\n\tif (\n\t\tdeclarations &&\n\t\t(keys.length !== Object.keys(declarations).length ||\n\t\t\tkeys.some((key) => !Object.prototype.hasOwnProperty.call(declarations, key)))\n\t)\n\t\tthrow Error('Contract operation keys must match exactly')\n\tconst bind = (key: string) => {\n\t\tlet original = operations[key]\n\t\t// A deferred helper result binds to its own declaration wherever it is registered.\n\t\tconst draft = deferred.get(original)\n\t\tif (draft) original = bindDomainImplementation(draft.key, draft.entries[draft.key], original)\n\t\tif (declarations) {\n\t\t\tif (pending.has(original)) {\n\t\t\t\tif (pending.get(original) !== declarations)\n\t\t\t\t\tthrow Error(`Operation ${key} must use its own contract helper`)\n\t\t\t\toriginal = bindDomainImplementation(key, declarations[key], original)\n\t\t\t}\n\t\t\tconst binding = bindings.get(original)\n\t\t\tif (\n\t\t\t\t!binding ||\n\t\t\t\tbinding.key !== key ||\n\t\t\t\tbinding.declaration !== declarations[key] ||\n\t\t\t\tprotectedFields.some(\n\t\t\t\t\t(field) =>\n\t\t\t\t\t\t// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\n\t\t\t\t\t\t(original as Record<string, unknown>)[field] !==\n\t\t\t\t\t\t// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\n\t\t\t\t\t\t(declarations[key] as Record<string, unknown>)[field],\n\t\t\t\t)\n\t\t\t)\n\t\t\t\tthrow Error(`Operation ${key} must use its own contract helper`)\n\t\t}\n\t\t// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\n\t\tconst definition = { ...original } as Record<string, unknown>\n\t\tif (definition.wire) {\n\t\t\t// SAFETY: wire is configuration, while its schema stays an opaque reference.\n\t\t\tdefinition.wire = Object.freeze({ ...(definition.wire as object) })\n\t\t}\n\t\tif (section === 'commands' || section === 'actions') {\n\t\t\tconst override = definition.audit\n\t\t\tif (override !== undefined && typeof override !== 'function')\n\t\t\t\tthrow Error(`Invalid audit for ${key}`)\n\t\t\tif (override === undefined && !audit && section === 'commands')\n\t\t\t\tthrow Error(`Command ${key} requires an audit callback`)\n\t\t\tif (override === undefined && audit) {\n\t\t\t\tdefinition.audit = (\n\t\t\t\t\tresolution: { command: unknown; result: unknown },\n\t\t\t\t\tcontext: unknown,\n\t\t\t\t\tscope: unknown,\n\t\t\t\t) =>\n\t\t\t\t\taudit(\n\t\t\t\t\t\t// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\n\t\t\t\t\t\t{ operation: key, input: resolution.command, result: resolution.result } as never,\n\t\t\t\t\t\t// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\n\t\t\t\t\t\tcontext as never,\n\t\t\t\t\t\t// SAFETY: the registry audit signature declares the scope its executor passes.\n\t\t\t\t\t\tscope as never,\n\t\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\t// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\n\t\treturn Object.freeze(definition)\n\t}\n\tconst snapshot: Record<string, Readonly<Record<string, unknown>>> = {}\n\tfor (const key of keys) {\n\t\tif (declarations && isLazyOperation(declarations, key))\n\t\t\tObject.defineProperty(snapshot, key, { enumerable: true, get: memoize(() => bind(key)) })\n\t\telse snapshot[key] = bind(key)\n\t}\n\treturn Object.freeze(snapshot)\n}\n\n/** Getter-declared operations, or operations with getter-declared protected fields, bind on first access. */\nfunction isLazyOperation(entries: Readonly<Record<string, object>>, key: string) {\n\tconst descriptor = Object.getOwnPropertyDescriptor(entries, key)\n\tif (!descriptor) return false\n\tif (descriptor.get) return true\n\tconst value: unknown = descriptor.value\n\treturn (\n\t\t!!value &&\n\t\ttypeof value === 'object' &&\n\t\tprotectedFields.some((field) => !!Object.getOwnPropertyDescriptor(value, field)?.get)\n\t)\n}\n"],"mappings":"qCAsBA,MAAMA,EAAkB,CAAC,QAAS,SAAU,iBAAkB,eAAgB,MAAM,EAC9EC,kBAAW,IAAI,QACfC,kBAAU,IAAI,QACdC,kBAAW,IAAI,QAGrB,SAAgBC,EAAc,EAA2C,CACxE,IAAMC,EAAU,OAAO,YACtB,OAAO,KAAKC,CAAO,CAAC,CAAC,IAAK,GAAQ,CACjCC,EACC,GAA2B,CAC3B,GAAI,CAACC,EAAgBF,EAASC,CAAG,EAChC,OAAOE,EAAyBF,EAAKD,EAAQC,GAAMG,CAAc,EAClE,IAAMC,EAAQ,CAAE,GAAGD,CAAe,EAElC,OADAP,EAAS,IAAIQ,EAAO,CAAE,MAAK,SAAQ,CAAC,EAC7BA,CACR,CACD,CAAC,CACF,EACMC,EAAeP,EAAQ,QAQ7B,MAPA,GAAQ,SAAW,EAA4B,IAAqB,CACnE,GAAI,OAAOQ,GAAY,YAAcD,EAAc,OAAOA,EAAaC,CAAO,EAC9E,GAAI,OAAOA,GAAY,WAAY,MAAM,MAAM,2BAA2B,EAC1E,IAAMH,EAAiB,CAAE,GAAGI,EAAS,SAAQ,EAE7C,OADAZ,EAAQ,IAAIQ,EAAgBJ,CAAO,EAC5BI,CACR,EACOL,CACR,CAGA,SAAgBI,EAAyB,EAAa,EAAqB,EAAwB,CAClG,IAAK,IAAMM,IAAS,CAAC,UAAW,QAAS,UAAW,QAAS,aAAc,SAAS,EACnF,GAAI,OAAO,UAAU,eAAe,KAAKC,EAAaD,CAAK,EAC1D,MAAM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ainOperationContract & {
|
|
|
18
18
|
export type DomainQueryContract = DomainOperationContract & {
|
|
19
19
|
readonly replayResult?: never;
|
|
20
20
|
};
|
|
21
|
+
export type DomainActionContract = DomainOperationContract & {
|
|
22
|
+
readonly replayResult?: never;
|
|
23
|
+
};
|
|
21
24
|
export type DomainContract = {
|
|
22
25
|
readonly errors?: Pick<ErrorContract<ErrorDefinitions>, 'project'>;
|
|
23
26
|
readonly commands?: Readonly<Record<string, DomainCommandContract>>;
|
|
24
27
|
readonly queries?: Readonly<Record<string, DomainQueryContract>>;
|
|
28
|
+
readonly actions?: Readonly<Record<string, DomainActionContract>>;
|
|
25
29
|
};
|
|
26
30
|
type CheckedEntry<Entry extends DomainOperationContract> = {
|
|
27
31
|
readonly handler?: never;
|
|
@@ -44,7 +48,7 @@ type CheckedEntry<Entry extends DomainOperationContract> = {
|
|
|
44
48
|
readonly replayResult: ContractOutput<Replay> extends ContractOutput<Entry['result']> ? Replay : never;
|
|
45
49
|
} : {});
|
|
46
50
|
type CheckedSection<Section> = { readonly [Key in keyof Section]: Section[Key] extends DomainOperationContract ? CheckedEntry<Section[Key]> : never; };
|
|
47
|
-
type CheckedDomain<Definition> = { readonly [Section in Extract<keyof Definition, 'commands' | 'queries'>]: CheckedSection<Definition[Section]>; };
|
|
51
|
+
type CheckedDomain<Definition> = { readonly [Section in Extract<keyof Definition, 'commands' | 'queries' | 'actions'>]: CheckedSection<Definition[Section]>; };
|
|
48
52
|
/** Preserve the declaration's literal keys and opaque validator/error-contract identities. */
|
|
49
53
|
export declare function defineDomainContract<const Definition extends DomainContract>(definition: (Definition & NoInfer<CheckedDomain<Definition>>) | (() => Definition & NoInfer<CheckedDomain<Definition>>)): Definition;
|
|
50
54
|
/** Exactness applies to variables as well as fresh object literals. */
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{memoize as e}from"./lazy.mjs";function t(t){if(typeof t!=`function`)return a(t);let n={},r=e(()=>{let e=a(t());return Object.defineProperties(n,Object.getOwnPropertyDescriptors(e)),Object.setPrototypeOf(n,Object.getPrototypeOf(e)),n});return new Proxy(n,{get:(e,t,n)=>Reflect.get(r(),t,n),has:(e,t)=>Reflect.has(r(),t),ownKeys:()=>Reflect.ownKeys(r()),getOwnPropertyDescriptor:(e,t)=>Reflect.getOwnPropertyDescriptor(r(),t),set:(e,t,n)=>Reflect.set(r(),t,n),defineProperty:(e,t,n)=>Reflect.defineProperty(r(),t,n),deleteProperty:(e,t)=>Reflect.deleteProperty(r(),t),getPrototypeOf:()=>Reflect.getPrototypeOf(r()),setPrototypeOf:(e,t)=>Reflect.setPrototypeOf(r(),t),preventExtensions:()=>Reflect.preventExtensions(r()),isExtensible:()=>Reflect.isExtensible(r())})}const n=[`input`,`result`,`replayResult`,`wire`];function r(t,n,r){for(let i of n){let n=Object.getOwnPropertyDescriptor(t,i);if(!n?.get||!n.configurable)continue;let a=n.get;Object.defineProperty(t,i,{configurable:!0,enumerable:n.enumerable,get:e(()=>r(a.call(t)))})}}function i(e){return e&&typeof e==`object`&&r(e,n,e=>e),e}function a(e){for(let t of[`commands`,`queries`]){let n=e?.[t];if(n&&typeof n==`object`){for(let e of Object.keys(n)){let t=Object.getOwnPropertyDescriptor(n,e);t&&`value`in t&&i(t.value)}r(n,Object.keys(n),i)}}return e}export{t as defineDomainContract};
|
|
1
|
+
import{memoize as e}from"./lazy.mjs";function t(t){if(typeof t!=`function`)return a(t);let n={},r=e(()=>{let e=a(t());return Object.defineProperties(n,Object.getOwnPropertyDescriptors(e)),Object.setPrototypeOf(n,Object.getPrototypeOf(e)),n});return new Proxy(n,{get:(e,t,n)=>Reflect.get(r(),t,n),has:(e,t)=>Reflect.has(r(),t),ownKeys:()=>Reflect.ownKeys(r()),getOwnPropertyDescriptor:(e,t)=>Reflect.getOwnPropertyDescriptor(r(),t),set:(e,t,n)=>Reflect.set(r(),t,n),defineProperty:(e,t,n)=>Reflect.defineProperty(r(),t,n),deleteProperty:(e,t)=>Reflect.deleteProperty(r(),t),getPrototypeOf:()=>Reflect.getPrototypeOf(r()),setPrototypeOf:(e,t)=>Reflect.setPrototypeOf(r(),t),preventExtensions:()=>Reflect.preventExtensions(r()),isExtensible:()=>Reflect.isExtensible(r())})}const n=[`input`,`result`,`replayResult`,`wire`];function r(t,n,r){for(let i of n){let n=Object.getOwnPropertyDescriptor(t,i);if(!n?.get||!n.configurable)continue;let a=n.get;Object.defineProperty(t,i,{configurable:!0,enumerable:n.enumerable,get:e(()=>r(a.call(t)))})}}function i(e){return e&&typeof e==`object`&&r(e,n,e=>e),e}function a(e){for(let t of[`commands`,`queries`,`actions`]){let n=e?.[t];if(n&&typeof n==`object`){for(let e of Object.keys(n)){let t=Object.getOwnPropertyDescriptor(n,e);t&&`value`in t&&i(t.value)}r(n,Object.keys(n),i)}}return e}export{t as defineDomainContract};
|
|
2
2
|
//# sourceMappingURL=domain.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"domain.mjs","names":["defineDomainContract","definition","memoizeAccessors","target","read","memoize","value","key","receiver","descriptor","prototype","lazyFields","memoizeGetters","keys","get","wrap","memoizeOperation","operation","name","section"],"sources":["../../../src/modules/contracts/domain.ts"],"sourcesContent":["import { memoize } from './lazy'\nimport type { ContractSchema, ContractInput, ContractOutput } from './contract'\nimport type { ErrorContract, ErrorDefinitions } from './errors'\n\n/** Schema-only domain vocabulary; implementations and host policies live in registries. */\nexport type DomainOperationContract = {\n\treadonly input: ContractSchema\n\treadonly result: ContractSchema\n\treadonly classification?: string\n\treadonly wire?: { readonly schema: ContractSchema; readonly project: Function }\n}\nexport type DomainCommandContract = DomainOperationContract & {\n\treadonly classification: string\n\treadonly replayResult?: ContractSchema\n}\nexport type DomainQueryContract = DomainOperationContract & { readonly replayResult?: never }\nexport type DomainContract = {\n\treadonly errors?: Pick<ErrorContract<ErrorDefinitions>, 'project'>\n\treadonly commands?: Readonly<Record<string, DomainCommandContract>>\n\treadonly queries?: Readonly<Record<string, DomainQueryContract>>\n}\n\ntype CheckedEntry<Entry extends DomainOperationContract> = {\n\treadonly handler?: never\n\treadonly audit?: never\n\treadonly prepare?: never\n\treadonly guard?: never\n\treadonly middleware?: never\n\treadonly context?: never\n\treadonly wire?: Entry extends { wire: { schema: infer Wire } }\n\t\t? {\n\t\t\t\treadonly schema: Wire\n\t\t\t\treadonly project: (value: ContractOutput<Entry['result']>) => ContractInput<Wire>\n\t\t\t}\n\t\t: never\n} & (Entry extends { replayResult: infer Replay }\n\t? {\n\t\t\treadonly replayResult: ContractOutput<Replay> extends ContractOutput<Entry['result']>\n\t\t\t\t? Replay\n\t\t\t\t: never\n\t\t}\n\t: {})\ntype CheckedSection<Section> = {\n\treadonly [Key in keyof Section]: Section[Key] extends DomainOperationContract\n\t\t? CheckedEntry<Section[Key]>\n\t\t: never\n}\ntype CheckedDomain<Definition> = {\n\treadonly [
|
|
1
|
+
{"version":3,"file":"domain.mjs","names":["defineDomainContract","definition","memoizeAccessors","target","read","memoize","value","key","receiver","descriptor","prototype","lazyFields","memoizeGetters","keys","get","wrap","memoizeOperation","operation","name","section"],"sources":["../../../src/modules/contracts/domain.ts"],"sourcesContent":["import { memoize } from './lazy'\nimport type { ContractSchema, ContractInput, ContractOutput } from './contract'\nimport type { ErrorContract, ErrorDefinitions } from './errors'\n\n/** Schema-only domain vocabulary; implementations and host policies live in registries. */\nexport type DomainOperationContract = {\n\treadonly input: ContractSchema\n\treadonly result: ContractSchema\n\treadonly classification?: string\n\treadonly wire?: { readonly schema: ContractSchema; readonly project: Function }\n}\nexport type DomainCommandContract = DomainOperationContract & {\n\treadonly classification: string\n\treadonly replayResult?: ContractSchema\n}\nexport type DomainQueryContract = DomainOperationContract & { readonly replayResult?: never }\nexport type DomainActionContract = DomainOperationContract & { readonly replayResult?: never }\nexport type DomainContract = {\n\treadonly errors?: Pick<ErrorContract<ErrorDefinitions>, 'project'>\n\treadonly commands?: Readonly<Record<string, DomainCommandContract>>\n\treadonly queries?: Readonly<Record<string, DomainQueryContract>>\n\treadonly actions?: Readonly<Record<string, DomainActionContract>>\n}\n\ntype CheckedEntry<Entry extends DomainOperationContract> = {\n\treadonly handler?: never\n\treadonly audit?: never\n\treadonly prepare?: never\n\treadonly guard?: never\n\treadonly middleware?: never\n\treadonly context?: never\n\treadonly wire?: Entry extends { wire: { schema: infer Wire } }\n\t\t? {\n\t\t\t\treadonly schema: Wire\n\t\t\t\treadonly project: (value: ContractOutput<Entry['result']>) => ContractInput<Wire>\n\t\t\t}\n\t\t: never\n} & (Entry extends { replayResult: infer Replay }\n\t? {\n\t\t\treadonly replayResult: ContractOutput<Replay> extends ContractOutput<Entry['result']>\n\t\t\t\t? Replay\n\t\t\t\t: never\n\t\t}\n\t: {})\ntype CheckedSection<Section> = {\n\treadonly [Key in keyof Section]: Section[Key] extends DomainOperationContract\n\t\t? CheckedEntry<Section[Key]>\n\t\t: never\n}\ntype CheckedDomain<Definition> = {\n\treadonly [\n\t\tSection in Extract<keyof Definition, 'commands' | 'queries' | 'actions'>\n\t]: CheckedSection<Definition[Section]>\n}\n\n/** Preserve the declaration's literal keys and opaque validator/error-contract identities. */\nexport function defineDomainContract<const Definition extends DomainContract>(\n\tdefinition:\n\t\t| (Definition & NoInfer<CheckedDomain<Definition>>)\n\t\t| (() => Definition & NoInfer<CheckedDomain<Definition>>),\n): Definition {\n\t// oxlint-disable-next-line anti-slop/no-runtime-typeof -- The public input is a checked declaration or its explicitly supported thunk.\n\tif (typeof definition !== 'function') return memoizeAccessors(definition)\n\t// SAFETY: the first read installs the inferred declaration's own descriptors on this target.\n\tconst target = {} as Definition\n\tconst read = memoize(() => {\n\t\tconst value = memoizeAccessors(definition())\n\t\tObject.defineProperties(target, Object.getOwnPropertyDescriptors(value))\n\t\tObject.setPrototypeOf(target, Object.getPrototypeOf(value))\n\t\treturn target\n\t})\n\treturn new Proxy(target, {\n\t\t// oxlint-disable-next-line anti-slop/no-reflect-get -- Preserve accessor receiver semantics for the forwarded declaration.\n\t\tget: (_target, key, receiver) => Reflect.get(read(), key, receiver),\n\t\thas: (_target, key) => Reflect.has(read(), key),\n\t\townKeys: () => Reflect.ownKeys(read()),\n\t\tgetOwnPropertyDescriptor: (_target, key) => Reflect.getOwnPropertyDescriptor(read(), key),\n\t\tset: (_target, key, value) => Reflect.set(read(), key, value),\n\t\tdefineProperty: (_target, key, descriptor) => Reflect.defineProperty(read(), key, descriptor),\n\t\tdeleteProperty: (_target, key) => Reflect.deleteProperty(read(), key),\n\t\tgetPrototypeOf: () => Reflect.getPrototypeOf(read()),\n\t\tsetPrototypeOf: (_target, prototype) => Reflect.setPrototypeOf(read(), prototype),\n\t\tpreventExtensions: () => Reflect.preventExtensions(read()),\n\t\tisExtensible: () => Reflect.isExtensible(read()),\n\t})\n}\n\n/** Exactness applies to variables as well as fresh object literals. */\nexport type ExactOperationKeys<Operations, Contracts> =\n\tExclude<keyof Operations, keyof Contracts> extends never\n\t\t? Exclude<keyof Contracts, keyof Operations> extends never\n\t\t\t? string extends keyof Contracts\n\t\t\t\t? never\n\t\t\t\t: unknown\n\t\t\t: never\n\t\t: never\n\n/** Correlated callback envelope for registry-level command audit. */\nexport type DomainAuditInput<Commands> = {\n\t[Key in Extract<keyof Commands, string>]: Commands[Key] extends DomainOperationContract\n\t\t? {\n\t\t\t\toperation: Key\n\t\t\t\tinput: ContractOutput<Commands[Key]['input']>\n\t\t\t\tresult: ContractOutput<Commands[Key]['result']>\n\t\t\t}\n\t\t: never\n}[Extract<keyof Commands, string>]\n\n/* oxlint-disable anti-slop/no-object-parameters, anti-slop/no-unknown-parameters, anti-slop/no-unknown-returns, anti-slop/no-unsafe-dictionary-type, anti-slop/no-runtime-typeof -- Wrapping walks checked declarations by descriptor and keeps schemas as opaque identities. */\nconst lazyFields = ['input', 'result', 'replayResult', 'wire'] as const\n\n/** Replace configurable getters with memoized ones in place, without invoking any of them. */\nfunction memoizeGetters(\n\ttarget: object,\n\tkeys: readonly PropertyKey[],\n\twrap: (value: unknown) => unknown,\n) {\n\tfor (const key of keys) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(target, key)\n\t\tif (!descriptor?.get || !descriptor.configurable) continue\n\t\tconst get = descriptor.get\n\t\tObject.defineProperty(target, key, {\n\t\t\tconfigurable: true,\n\t\t\tenumerable: descriptor.enumerable,\n\t\t\tget: memoize(() => wrap(get.call(target))),\n\t\t})\n\t}\n}\n\nfunction memoizeOperation(operation: unknown) {\n\tif (operation && typeof operation === 'object')\n\t\tmemoizeGetters(operation, lazyFields, (value) => value)\n\treturn operation\n}\n\n/** Getter-declared operations and fields build at most once and keep a stable identity. */\nfunction memoizeAccessors<Definition>(definition: Definition): Definition {\n\tfor (const name of ['commands', 'queries', 'actions'] as const) {\n\t\t// SAFETY: the checked declaration's sections are plain records of operation declarations.\n\t\tconst section = (definition as Record<string, unknown> | undefined)?.[name]\n\t\tif (!section || typeof section !== 'object') continue\n\t\tfor (const key of Object.keys(section)) {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(section, key)\n\t\t\tif (descriptor && 'value' in descriptor) memoizeOperation(descriptor.value)\n\t\t}\n\t\tmemoizeGetters(section, Object.keys(section), memoizeOperation)\n\t}\n\treturn definition\n}\n/* oxlint-enable anti-slop/no-object-parameters, anti-slop/no-unknown-parameters, anti-slop/no-unknown-returns, anti-slop/no-unsafe-dictionary-type, anti-slop/no-runtime-typeof */\n"],"mappings":"qCAwDA,SAAgBA,EACf,EAGa,CAEb,GAAI,OAAOC,GAAe,WAAY,OAAOC,EAAiBD,CAAU,EAExE,IAAME,EAAS,CAAC,EACVC,EAAOC,MAAc,CAC1B,IAAMC,EAAQJ,EAAiBD,EAAW,CAAC,EAG3C,OAFA,OAAO,iBAAiBE,EAAQ,OAAO,0BAA0BG,CAAK,CAAC,EACvE,OAAO,eAAeH,EAAQ,OAAO,eAAeG,CAAK,CAAC,EACnDH,CACR,CAAC,EACD,OAAO,IAAI,MAAMA,EAAQ,CAExB,KAAM,EAAS,EAAK,IAAa,QAAQ,IAAIC,EAAK,EAAGG,EAAKC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C,KAAK,IAAMZ,KAAO,OAAO,KAAKY,CAAO,EAAG,CACvC,IAAMV,EAAa,OAAO,yBAAyBU,EAASZ,CAAG,EAC3DE,GAAc,UAAWA,GAAYO,EAAiBP,EAAW,KAAK,CAC3E,CACAG,EAAeO,EAAS,OAAO,KAAKA,CAAO,EAAGH,CAAgB,CAD9D,CAED,CACA,OAAOf,CACR"}
|
|
@@ -10,6 +10,8 @@ export type ErrorDefinitions = Readonly<Record<string, Readonly<{
|
|
|
10
10
|
}>>>;
|
|
11
11
|
type Code<Definitions extends ErrorDefinitions> = Extract<keyof Definitions, string>;
|
|
12
12
|
type Details<Definition extends ErrorDefinitions[string]> = Definition extends ErrorDefinitions[string] ? { [Field in keyof Definition['details']]: ReturnType<Definition['details'][Field]['parse']>; } : never;
|
|
13
|
+
/** The parsed detail fields one declared code carries. */
|
|
14
|
+
export type DeclaredErrorDetails<Definitions extends ErrorDefinitions, Key extends Code<Definitions>> = Details<Definitions[Key]>;
|
|
13
15
|
declare const declaredErrorBrand: unique symbol;
|
|
14
16
|
/** Server failures are trusted only by the contract that created them. */
|
|
15
17
|
export type DeclaredError<Definitions extends ErrorDefinitions> = { [Key in Code<Definitions>]: Readonly<{
|
|
@@ -570,5 +572,7 @@ export declare const queryErrors: Readonly<{
|
|
|
570
572
|
};
|
|
571
573
|
}>;
|
|
572
574
|
}>;
|
|
575
|
+
/** Plain object records only: no arrays, class instances or exotic prototypes. */
|
|
576
|
+
export declare function isRecord(value: unknown): value is Record<string, unknown>;
|
|
573
577
|
//#endregion
|
|
574
578
|
//# sourceMappingURL=errors.d.mts.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ConvexError as e}from"convex/values";const t=Object.freeze({_tag:`UnknownFailure`,version:1});function n(n){let r=Object.fromEntries(Object.entries(n).map(([e,t])=>{if(!e||!t.message||t.message.length>200)throw Error(`Declared errors require a code and a public message of 1–200 characters`);return[e,{message:t.message,details:{...t.details}}]})),i=/* @__PURE__ */ new WeakMap,a={create(e,t){let n;try{if(!Object.hasOwn(r,e))throw Error(`Undeclared code`);let i=r[e];n={_tag:`DeclaredFailure`,version:1,code:e,message:i.message,details:c(i,t,!1)}}catch{throw Error(`Invalid declared error details`)}let a=Object.freeze({_tag:`DeclaredError`,code:e,details:s(n.details)});return i.set(a,n),a},envelope(e,t){return a.project(a.create(e,t))},toConvexError(t,n){return new e(a.envelope(t,n))},project(e){if(typeof e!=`object`||!e)return t;let n=i.get(e);return n?s(n):t},decode(e){try{if(!o(e)||e._tag!==`DeclaredFailure`||e.version!==1||typeof e.code!=`string`||!Object.hasOwn(r,e.code)||Object.keys(e).length!==5||![`message`,`details`,`_tag`,`version`,`code`].every(t=>Object.hasOwn(e,t)))return t;let n=r[e.code];return e.message===n.message?(s(e.details),{_tag:`DeclaredFailure`,version:1,code:e.code,message:n.message,details:c(n,e.details,!0)}):t}catch{return t}}};return a}function r(n,r){try{if(n instanceof e){let e=n.data;if(typeof e==`string`){if(e.length>65536||new TextEncoder().encode(e).byteLength>65536)return t;e=JSON.parse(e)}return r.decode(e)}}catch{}return t}function i(...e){let n=t;return{project(t){for(let n of e){let e=n.project(t);if(e._tag===`DeclaredFailure`)return e;let i=r(t,n);if(i._tag===`DeclaredFailure`)return i}return n},decode(t){for(let n of e){let e=n.decode(t);if(e._tag===`DeclaredFailure`)return e}return n}}}const a=n({"invalid-cursor":{message:`Invalid cursor`,details:{}},FIELD_GROUP_DENIED:{message:`Field group access denied`,details:{}},QUERY_FANOUT:{message:`Query fan-out limit exceeded`,details:{}},SEARCH_TEXT_REQUIRED:{message:`Search text required`,details:{}},SEARCH_END_CURSOR_UNSUPPORTED:{message:`Search end cursor unsupported`,details:{}},SEARCH_ORDER_UNSUPPORTED:{message:`Search ordering unsupported`,details:{}},SEARCH_RELATION_UNSUPPORTED:{message:`Relation search unsupported`,details:{}},SEARCH_OPTIONS_UNSUPPORTED:{message:`Search options unsupported`,details:{}},SEARCH_PROTOCOL_UNSUPPORTED:{message:`Search pagination protocol unsupported`,details:{}}});function o(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function s(e,t=/* @__PURE__ */ new Set){if(e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return e;if(typeof e!=`object`||!e||t.has(e))throw Error(`Invalid JSON`);t.add(e);try{if(Array.isArray(e)){let n=[];for(let r=0;r<e.length;r++)n.push(s(e[r],t));return n}if(!o(e))throw Error(`Invalid JSON`);return Object.fromEntries(Object.entries(e).map(([e,n])=>[e,s(n,t)]))}finally{t.delete(e)}}function c(e,t,n){if(!o(t))throw Error(`Invalid details`);let r=Object.keys(e.details);if(n&&Object.keys(t).some(t=>!Object.hasOwn(e.details,t)))throw Error(`Undeclared detail`);return Object.fromEntries(r.map(n=>{if(!Object.hasOwn(t,n))throw Error(`Missing detail`);return[n,s(e.details[n].parse(t[n]))]}))}export{i as combineErrorContracts,r as decodeFailure,n as defineErrorContract,a as queryErrors};
|
|
1
|
+
import{ConvexError as e}from"convex/values";const t=Object.freeze({_tag:`UnknownFailure`,version:1});function n(n){let r=Object.fromEntries(Object.entries(n).map(([e,t])=>{if(!e||!t.message||t.message.length>200)throw Error(`Declared errors require a code and a public message of 1–200 characters`);return[e,{message:t.message,details:{...t.details}}]})),i=/* @__PURE__ */ new WeakMap,a={create(e,t){let n;try{if(!Object.hasOwn(r,e))throw Error(`Undeclared code`);let i=r[e];n={_tag:`DeclaredFailure`,version:1,code:e,message:i.message,details:c(i,t,!1)}}catch{throw Error(`Invalid declared error details`)}let a=Object.freeze({_tag:`DeclaredError`,code:e,details:s(n.details)});return i.set(a,n),a},envelope(e,t){return a.project(a.create(e,t))},toConvexError(t,n){return new e(a.envelope(t,n))},project(e){if(typeof e!=`object`||!e)return t;let n=i.get(e);return n?s(n):t},decode(e){try{if(!o(e)||e._tag!==`DeclaredFailure`||e.version!==1||typeof e.code!=`string`||!Object.hasOwn(r,e.code)||Object.keys(e).length!==5||![`message`,`details`,`_tag`,`version`,`code`].every(t=>Object.hasOwn(e,t)))return t;let n=r[e.code];return e.message===n.message?(s(e.details),{_tag:`DeclaredFailure`,version:1,code:e.code,message:n.message,details:c(n,e.details,!0)}):t}catch{return t}}};return a}function r(n,r){try{if(n instanceof e){let e=n.data;if(typeof e==`string`){if(e.length>65536||new TextEncoder().encode(e).byteLength>65536)return t;e=JSON.parse(e)}return r.decode(e)}}catch{}return t}function i(...e){let n=t;return{project(t){for(let n of e){let e=n.project(t);if(e._tag===`DeclaredFailure`)return e;let i=r(t,n);if(i._tag===`DeclaredFailure`)return i}return n},decode(t){for(let n of e){let e=n.decode(t);if(e._tag===`DeclaredFailure`)return e}return n}}}const a=n({"invalid-cursor":{message:`Invalid cursor`,details:{}},FIELD_GROUP_DENIED:{message:`Field group access denied`,details:{}},QUERY_FANOUT:{message:`Query fan-out limit exceeded`,details:{}},SEARCH_TEXT_REQUIRED:{message:`Search text required`,details:{}},SEARCH_END_CURSOR_UNSUPPORTED:{message:`Search end cursor unsupported`,details:{}},SEARCH_ORDER_UNSUPPORTED:{message:`Search ordering unsupported`,details:{}},SEARCH_RELATION_UNSUPPORTED:{message:`Relation search unsupported`,details:{}},SEARCH_OPTIONS_UNSUPPORTED:{message:`Search options unsupported`,details:{}},SEARCH_PROTOCOL_UNSUPPORTED:{message:`Search pagination protocol unsupported`,details:{}}});function o(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function s(e,t=/* @__PURE__ */ new Set){if(e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return e;if(typeof e!=`object`||!e||t.has(e))throw Error(`Invalid JSON`);t.add(e);try{if(Array.isArray(e)){let n=[];for(let r=0;r<e.length;r++)n.push(s(e[r],t));return n}if(!o(e))throw Error(`Invalid JSON`);return Object.fromEntries(Object.entries(e).map(([e,n])=>[e,s(n,t)]))}finally{t.delete(e)}}function c(e,t,n){if(!o(t))throw Error(`Invalid details`);let r=Object.keys(e.details);if(n&&Object.keys(t).some(t=>!Object.hasOwn(e.details,t)))throw Error(`Undeclared detail`);return Object.fromEntries(r.map(n=>{if(!Object.hasOwn(t,n))throw Error(`Missing detail`);return[n,s(e.details[n].parse(t[n]))]}))}export{i as combineErrorContracts,r as decodeFailure,n as defineErrorContract,o as isRecord,a as queryErrors};
|
|
2
2
|
//# sourceMappingURL=errors.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.mjs","names":["unknownFailure","defineErrorContract","declarations","definitions","code","definition","trusted","contract","envelope","parseDetails","details","error","copyJson","ConvexError","isRecord","payload","key","decodeFailure","combineErrorContracts","contracts","unmatched","projected","decoded","queryErrors","value","prototype","ancestors","result","index","child","fields","strict","field"],"sources":["../../../src/modules/contracts/errors.ts"],"sourcesContent":["/* oxlint-disable anti-slop/no-unknown-parameters, anti-slop/no-unknown-returns, anti-slop/no-unknown-type-aliases, anti-slop/no-runtime-typeof, anti-slop/no-unsafe-dictionary-type -- This neutral contract validates unknown transport data and an explicitly keyed code/detail declaration. */\n\nimport { ConvexError } from 'convex/values'\n\n/** Explicit synchronous validators for the final public detail representation. */\nexport type ErrorDetailParser<Output = unknown> = Readonly<{\n\tparse: (value: unknown) => Output\n}>\n\nexport type ErrorDefinitions = Readonly<\n\tRecord<\n\t\tstring,\n\t\tReadonly<{\n\t\t\tmessage: string\n\t\t\tdetails: Readonly<Record<string, ErrorDetailParser>>\n\t\t}>\n\t>\n>\n\ntype Code<Definitions extends ErrorDefinitions> = Extract<keyof Definitions, string>\ntype Details<Definition extends ErrorDefinitions[string]> =\n\tDefinition extends ErrorDefinitions[string]\n\t\t? { [Field in keyof Definition['details']]: ReturnType<Definition['details'][Field]['parse']> }\n\t\t: never\n\ndeclare const declaredErrorBrand: unique symbol\n\n/** Server failures are trusted only by the contract that created them. */\nexport type DeclaredError<Definitions extends ErrorDefinitions> = {\n\t[Key in Code<Definitions>]: Readonly<{\n\t\t_tag: 'DeclaredError'\n\t\tcode: Key\n\t\tdetails: Details<Definitions[Key]>\n\t\t[declaredErrorBrand]: true\n\t}>\n}[Code<Definitions>]\n\nexport type DeclaredFailure<Definitions extends ErrorDefinitions> = {\n\t[Key in Code<Definitions>]: Readonly<{\n\t\t_tag: 'DeclaredFailure'\n\t\tversion: 1\n\t\tcode: Key\n\t\tmessage: string\n\t\tdetails: Details<Definitions[Key]>\n\t}>\n}[Code<Definitions>]\n\nexport type UnknownFailure = Readonly<{ _tag: 'UnknownFailure'; version: 1 }>\nexport type DecodedFailure<Definitions extends ErrorDefinitions> =\n\t| DeclaredFailure<Definitions>\n\t| UnknownFailure\n\nexport type ErrorContract<Definitions extends ErrorDefinitions> = Readonly<{\n\tcreate: <Key extends Code<Definitions>>(\n\t\tcode: Key,\n\t\tdetails: Details<Definitions[NoInfer<Key>]>,\n\t) => Extract<DeclaredError<Definitions>, { code: Key }>\n\tenvelope: <Key extends Code<Definitions>>(\n\t\tcode: Key,\n\t\tdetails: Details<Definitions[NoInfer<Key>]>,\n\t) => Extract<DeclaredFailure<Definitions>, { code: Key }>\n\ttoConvexError: <Key extends Code<Definitions>>(\n\t\tcode: Key,\n\t\tdetails: Details<Definitions[NoInfer<Key>]>,\n\t) => ConvexError<Extract<DeclaredFailure<Definitions>, { code: Key }>>\n\tproject: (error: unknown) => DecodedFailure<Definitions>\n\t/** Receives envelope data, e.g. ConvexError.data; never parses error messages. */\n\tdecode: (payload: unknown) => DecodedFailure<Definitions>\n}>\n\nconst unknownFailure: UnknownFailure = Object.freeze({\n\t_tag: 'UnknownFailure',\n\tversion: 1,\n})\ntype Json = null | boolean | number | string | Json[] | { [key: string]: Json }\n\n/** Closed safe codes, allowlisted details, and a versioned checked transport union. */\nexport function defineErrorContract<const Definitions extends ErrorDefinitions>(\n\tdefinitions: Definitions,\n): ErrorContract<Definitions> {\n\t// SAFETY: the snapshot copies every declaration without changing its code, message or paired parsers.\n\tconst declarations = Object.fromEntries(\n\t\tObject.entries(definitions).map(([code, definition]) => {\n\t\t\tif (!code || !definition.message || definition.message.length > 200) {\n\t\t\t\tthrow Error('Declared errors require a code and a public message of 1–200 characters')\n\t\t\t}\n\t\t\treturn [code, { message: definition.message, details: { ...definition.details } }]\n\t\t}),\n\t) as Definitions\n\tconst trusted = new WeakMap<object, DeclaredFailure<Definitions>>()\n\tconst contract: ErrorContract<Definitions> = {\n\t\tcreate(code, details) {\n\t\t\tlet envelope: DeclaredFailure<Definitions>\n\t\t\ttry {\n\t\t\t\tif (!Object.hasOwn(declarations, code)) throw Error('Undeclared code')\n\t\t\t\tconst definition = declarations[code]\n\t\t\t\t// SAFETY: the selected closed declaration validates every field before construction.\n\t\t\t\tenvelope = {\n\t\t\t\t\t_tag: 'DeclaredFailure',\n\t\t\t\t\tversion: 1,\n\t\t\t\t\tcode,\n\t\t\t\t\tmessage: definition.message,\n\t\t\t\t\tdetails: parseDetails(definition, details, false),\n\t\t\t\t} as DeclaredFailure<Definitions>\n\t\t\t} catch {\n\t\t\t\t// Validator messages, issue paths and provider causes remain private.\n\t\t\t\tthrow Error('Invalid declared error details')\n\t\t\t}\n\t\t\t// SAFETY: identity is registered below; the inaccessible brand cannot confer trust by itself.\n\t\t\tconst error = Object.freeze({\n\t\t\t\t_tag: 'DeclaredError',\n\t\t\t\tcode,\n\t\t\t\tdetails: copyJson(envelope.details),\n\t\t\t}) as Extract<DeclaredError<Definitions>, { code: typeof code }>\n\t\t\ttrusted.set(error, envelope)\n\t\t\treturn error\n\t\t},\n\t\tenvelope(code, details) {\n\t\t\t// SAFETY: create validates the selected code; project retrieves its private validated envelope.\n\t\t\treturn contract.project(contract.create(code, details)) as Extract<\n\t\t\t\tDeclaredFailure<Definitions>,\n\t\t\t\t{ code: typeof code }\n\t\t\t>\n\t\t},\n\t\ttoConvexError(code, details) {\n\t\t\treturn new ConvexError(contract.envelope(code, details))\n\t\t},\n\t\tproject(error) {\n\t\t\tif (error === null || typeof error !== 'object') return unknownFailure\n\t\t\tconst envelope = trusted.get(error)\n\t\t\t// SAFETY: only validated contract-owned envelopes enter the private map.\n\t\t\treturn envelope ? (copyJson(envelope) as DeclaredFailure<Definitions>) : unknownFailure\n\t\t},\n\t\tdecode(payload) {\n\t\t\ttry {\n\t\t\t\tif (\n\t\t\t\t\t!isRecord(payload) ||\n\t\t\t\t\tpayload._tag !== 'DeclaredFailure' ||\n\t\t\t\t\tpayload.version !== 1 ||\n\t\t\t\t\ttypeof payload.code !== 'string' ||\n\t\t\t\t\t!Object.hasOwn(declarations, payload.code) ||\n\t\t\t\t\tObject.keys(payload).length !== 5 ||\n\t\t\t\t\t!['message', 'details', '_tag', 'version', 'code'].every((key) =>\n\t\t\t\t\t\tObject.hasOwn(payload, key),\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\treturn unknownFailure\n\t\t\t\t}\n\t\t\t\tconst definition = declarations[payload.code]\n\t\t\t\tif (payload.message !== definition.message) return unknownFailure\n\t\t\t\t// Validate raw transport JSON too: parsers must not hide non-JSON payloads.\n\t\t\t\tcopyJson(payload.details)\n\t\t\t\t// SAFETY: code membership and every allowlisted field have been checked independently.\n\t\t\t\treturn {\n\t\t\t\t\t_tag: 'DeclaredFailure',\n\t\t\t\t\tversion: 1,\n\t\t\t\t\tcode: payload.code,\n\t\t\t\t\tmessage: definition.message,\n\t\t\t\t\tdetails: parseDetails(definition, payload.details, true),\n\t\t\t\t} as DeclaredFailure<Definitions>\n\t\t\t} catch {\n\t\t\t\treturn unknownFailure\n\t\t\t}\n\t\t},\n\t}\n\treturn contract\n}\n\n/** A structural decoder also accepts combined contracts without requiring constructors. */\nexport type FailureContract = Pick<ErrorContract<ErrorDefinitions>, 'decode'>\nexport type FailureOf<Contract extends FailureContract> = ReturnType<Contract['decode']>\ntype ProjectingContract = FailureContract & Pick<ErrorContract<ErrorDefinitions>, 'project'>\n\n/** Extract only ConvexError.data, including one bounded serialized JSON envelope. */\nexport function decodeFailure<Contract extends FailureContract>(\n\terror: unknown,\n\tcontract: Contract,\n): FailureOf<Contract> {\n\ttry {\n\t\tif (error instanceof ConvexError) {\n\t\t\tlet payload: unknown = error.data\n\t\t\tif (typeof payload === 'string') {\n\t\t\t\tif (payload.length > 65536 || new TextEncoder().encode(payload).byteLength > 65536)\n\t\t\t\t\t// SAFETY: every failure decoder includes UnknownFailure.\n\t\t\t\t\treturn unknownFailure as FailureOf<Contract>\n\t\t\t\tpayload = JSON.parse(payload)\n\t\t\t}\n\t\t\t// SAFETY: the structural contract owns the decoded union.\n\t\t\treturn contract.decode(payload) as FailureOf<Contract>\n\t\t}\n\t} catch {\n\t\t// Foreign errors, accessors and invalid JSON expose no diagnostics.\n\t}\n\t// SAFETY: every failure decoder includes UnknownFailure.\n\treturn unknownFailure as FailureOf<Contract>\n}\n\ntype CombinedErrorContract<Contracts extends readonly ProjectingContract[]> = Readonly<{\n\tproject: (error: unknown) => FailureOf<Contracts[number]> | UnknownFailure\n\tdecode: (payload: unknown) => FailureOf<Contracts[number]> | UnknownFailure\n}>\n\n/** Ordered projection and decoding; duplicate codes retain the union of member details. */\nexport function combineErrorContracts<const Contracts extends readonly ProjectingContract[]>(\n\t...contracts: Contracts\n): CombinedErrorContract<Contracts> {\n\tconst unmatched = unknownFailure\n\treturn {\n\t\tproject(error) {\n\t\t\tfor (const contract of contracts) {\n\t\t\t\tconst projected = contract.project(error)\n\t\t\t\tif (projected._tag === 'DeclaredFailure') {\n\t\t\t\t\t// SAFETY: this result belongs to a member of the inferred tuple.\n\t\t\t\t\treturn projected as FailureOf<Contracts[number]>\n\t\t\t\t}\n\t\t\t\tconst decoded = decodeFailure(error, contract)\n\t\t\t\tif (decoded._tag === 'DeclaredFailure') {\n\t\t\t\t\t// SAFETY: strict transported decoding preserves the same member union.\n\t\t\t\t\treturn decoded as FailureOf<Contracts[number]>\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn unmatched\n\t\t},\n\t\tdecode(payload) {\n\t\t\tfor (const contract of contracts) {\n\t\t\t\tconst decoded = contract.decode(payload)\n\t\t\t\tif (decoded._tag === 'DeclaredFailure') {\n\t\t\t\t\t// SAFETY: this result belongs to a member of the inferred tuple.\n\t\t\t\t\treturn decoded as FailureOf<Contracts[number]>\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn unmatched\n\t\t},\n\t}\n}\n\n/** Fixed, diagnostic-free transport shared by query endpoints and client recovery. */\nexport const queryErrors = defineErrorContract({\n\t'invalid-cursor': { message: 'Invalid cursor', details: {} },\n\tFIELD_GROUP_DENIED: { message: 'Field group access denied', details: {} },\n\tQUERY_FANOUT: { message: 'Query fan-out limit exceeded', details: {} },\n\tSEARCH_TEXT_REQUIRED: { message: 'Search text required', details: {} },\n\tSEARCH_END_CURSOR_UNSUPPORTED: {\n\t\tmessage: 'Search end cursor unsupported',\n\t\tdetails: {},\n\t},\n\tSEARCH_ORDER_UNSUPPORTED: {\n\t\tmessage: 'Search ordering unsupported',\n\t\tdetails: {},\n\t},\n\tSEARCH_RELATION_UNSUPPORTED: {\n\t\tmessage: 'Relation search unsupported',\n\t\tdetails: {},\n\t},\n\tSEARCH_OPTIONS_UNSUPPORTED: {\n\t\tmessage: 'Search options unsupported',\n\t\tdetails: {},\n\t},\n\tSEARCH_PROTOCOL_UNSUPPORTED: {\n\t\tmessage: 'Search pagination protocol unsupported',\n\t\tdetails: {},\n\t},\n})\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\tif (value === null || typeof value !== 'object' || Array.isArray(value)) return false\n\tconst prototype = Object.getPrototypeOf(value)\n\treturn prototype === Object.prototype || prototype === null\n}\n\n/** Copy data without invoking toJSON or retaining mutable provider objects. */\nfunction copyJson(value: unknown, ancestors = new Set<object>()): Json {\n\tif (value === null || typeof value === 'string' || typeof value === 'boolean') return value\n\tif (typeof value === 'number' && Number.isFinite(value)) return value\n\tif (typeof value !== 'object' || value === null || ancestors.has(value))\n\t\tthrow Error('Invalid JSON')\n\tancestors.add(value)\n\ttry {\n\t\tif (Array.isArray(value)) {\n\t\t\tconst result: Json[] = []\n\t\t\tfor (let index = 0; index < value.length; index++)\n\t\t\t\tresult.push(copyJson(value[index], ancestors))\n\t\t\treturn result\n\t\t}\n\t\tif (!isRecord(value)) throw Error('Invalid JSON')\n\t\treturn Object.fromEntries(\n\t\t\tObject.entries(value).map(([key, child]) => [key, copyJson(child, ancestors)]),\n\t\t)\n\t} finally {\n\t\tancestors.delete(value)\n\t}\n}\n\nfunction parseDetails<const Definition extends ErrorDefinitions[string]>(\n\tdefinition: Definition,\n\tvalue: unknown,\n\tstrict: boolean,\n): Details<Definition> {\n\tif (!isRecord(value)) throw Error('Invalid details')\n\tconst fields = Object.keys(definition.details)\n\tif (strict && Object.keys(value).some((key) => !Object.hasOwn(definition.details, key))) {\n\t\tthrow Error('Undeclared detail')\n\t}\n\t// SAFETY: each declared field is validated by its paired parser before its JSON-safe copy is returned.\n\treturn Object.fromEntries(\n\t\tfields.map((field) => {\n\t\t\tif (!Object.hasOwn(value, field)) throw Error('Missing detail')\n\t\t\treturn [field, copyJson(definition.details[field].parse(value[field]))]\n\t\t}),\n\t) as Details<Definition>\n}\n"],"mappings":"4CAsEA,MAAMA,EAAiC,OAAO,OAAO,CACpD,KAAM,iBACN,QAAS,CACV,CAAC,EAID,SAAgBC,EACf,EAC6B,CAE7B,IAAMC,EAAe,OAAO,YAC3B,OAAO,QAAQC,CAAW,CAAC,CAAC,KAAK,CAACC,EAAMC,KAAgB,CACvD,GAAI,CAACD,GAAQ,CAACC,EAAW,SAAWA,EAAW,QAAQ,OAAS,IAC/D,MAAM,MAAM,yEAAyE,EAEtF,MAAO,CAACD,EAAM,CAAE,QAASC,EAAW,QAAS,QAAS,CAAE,GAAGA,EAAW,OAAQ,CAAE,CAAC,CAClF,CAAC,CACF,EACMC,kBAAU,IAAI,QACdC,EAAuC,CAC5C,OAAO,EAAM,EAAS,CACrB,IAAIC,EACJ,GAAI,CACH,GAAI,CAAC,OAAO,OAAON,EAAcE,CAAI,EAAG,MAAM,MAAM,iBAAi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AAW,QAASW,CAAG,CAAC,EACrF,MAAM,MAAM,mBAAmB,EAGhC,OAAO,OAAO,YACbc,EAAO,IAAK,GAAU,CACrB,GAAI,CAAC,OAAO,OAAON,EAAOQ,CAAK,EAAG,MAAM,MAAM,gBAAgB,EAC9D,MAAO,CAACA,EAAOpB,EAASP,EAAW,QAAQ2B,EAAM,CAAC,MAAMR,EAAMQ,EAAM,CAAC,CAAC,CACvE,CAAC,CACF,CACD"}
|
|
1
|
+
{"version":3,"file":"errors.mjs","names":["unknownFailure","defineErrorContract","declarations","definitions","code","definition","trusted","contract","envelope","parseDetails","details","error","copyJson","ConvexError","isRecord","payload","key","decodeFailure","combineErrorContracts","contracts","unmatched","projected","decoded","queryErrors","value","prototype","ancestors","result","index","child","fields","strict","field"],"sources":["../../../src/modules/contracts/errors.ts"],"sourcesContent":["/* oxlint-disable anti-slop/no-unknown-parameters, anti-slop/no-unknown-returns, anti-slop/no-unknown-type-aliases, anti-slop/no-runtime-typeof, anti-slop/no-unsafe-dictionary-type -- This neutral contract validates unknown transport data and an explicitly keyed code/detail declaration. */\n\nimport { ConvexError } from 'convex/values'\n\n/** Explicit synchronous validators for the final public detail representation. */\nexport type ErrorDetailParser<Output = unknown> = Readonly<{\n\tparse: (value: unknown) => Output\n}>\n\nexport type ErrorDefinitions = Readonly<\n\tRecord<\n\t\tstring,\n\t\tReadonly<{\n\t\t\tmessage: string\n\t\t\tdetails: Readonly<Record<string, ErrorDetailParser>>\n\t\t}>\n\t>\n>\n\ntype Code<Definitions extends ErrorDefinitions> = Extract<keyof Definitions, string>\ntype Details<Definition extends ErrorDefinitions[string]> =\n\tDefinition extends ErrorDefinitions[string]\n\t\t? { [Field in keyof Definition['details']]: ReturnType<Definition['details'][Field]['parse']> }\n\t\t: never\n/** The parsed detail fields one declared code carries. */\nexport type DeclaredErrorDetails<\n\tDefinitions extends ErrorDefinitions,\n\tKey extends Code<Definitions>,\n> = Details<Definitions[Key]>\n\ndeclare const declaredErrorBrand: unique symbol\n\n/** Server failures are trusted only by the contract that created them. */\nexport type DeclaredError<Definitions extends ErrorDefinitions> = {\n\t[Key in Code<Definitions>]: Readonly<{\n\t\t_tag: 'DeclaredError'\n\t\tcode: Key\n\t\tdetails: Details<Definitions[Key]>\n\t\t[declaredErrorBrand]: true\n\t}>\n}[Code<Definitions>]\n\nexport type DeclaredFailure<Definitions extends ErrorDefinitions> = {\n\t[Key in Code<Definitions>]: Readonly<{\n\t\t_tag: 'DeclaredFailure'\n\t\tversion: 1\n\t\tcode: Key\n\t\tmessage: string\n\t\tdetails: Details<Definitions[Key]>\n\t}>\n}[Code<Definitions>]\n\nexport type UnknownFailure = Readonly<{ _tag: 'UnknownFailure'; version: 1 }>\nexport type DecodedFailure<Definitions extends ErrorDefinitions> =\n\t| DeclaredFailure<Definitions>\n\t| UnknownFailure\n\nexport type ErrorContract<Definitions extends ErrorDefinitions> = Readonly<{\n\tcreate: <Key extends Code<Definitions>>(\n\t\tcode: Key,\n\t\tdetails: Details<Definitions[NoInfer<Key>]>,\n\t) => Extract<DeclaredError<Definitions>, { code: Key }>\n\tenvelope: <Key extends Code<Definitions>>(\n\t\tcode: Key,\n\t\tdetails: Details<Definitions[NoInfer<Key>]>,\n\t) => Extract<DeclaredFailure<Definitions>, { code: Key }>\n\ttoConvexError: <Key extends Code<Definitions>>(\n\t\tcode: Key,\n\t\tdetails: Details<Definitions[NoInfer<Key>]>,\n\t) => ConvexError<Extract<DeclaredFailure<Definitions>, { code: Key }>>\n\tproject: (error: unknown) => DecodedFailure<Definitions>\n\t/** Receives envelope data, e.g. ConvexError.data; never parses error messages. */\n\tdecode: (payload: unknown) => DecodedFailure<Definitions>\n}>\n\nconst unknownFailure: UnknownFailure = Object.freeze({\n\t_tag: 'UnknownFailure',\n\tversion: 1,\n})\ntype Json = null | boolean | number | string | Json[] | { [key: string]: Json }\n\n/** Closed safe codes, allowlisted details, and a versioned checked transport union. */\nexport function defineErrorContract<const Definitions extends ErrorDefinitions>(\n\tdefinitions: Definitions,\n): ErrorContract<Definitions> {\n\t// SAFETY: the snapshot copies every declaration without changing its code, message or paired parsers.\n\tconst declarations = Object.fromEntries(\n\t\tObject.entries(definitions).map(([code, definition]) => {\n\t\t\tif (!code || !definition.message || definition.message.length > 200) {\n\t\t\t\tthrow Error('Declared errors require a code and a public message of 1–200 characters')\n\t\t\t}\n\t\t\treturn [code, { message: definition.message, details: { ...definition.details } }]\n\t\t}),\n\t) as Definitions\n\tconst trusted = new WeakMap<object, DeclaredFailure<Definitions>>()\n\tconst contract: ErrorContract<Definitions> = {\n\t\tcreate(code, details) {\n\t\t\tlet envelope: DeclaredFailure<Definitions>\n\t\t\ttry {\n\t\t\t\tif (!Object.hasOwn(declarations, code)) throw Error('Undeclared code')\n\t\t\t\tconst definition = declarations[code]\n\t\t\t\t// SAFETY: the selected closed declaration validates every field before construction.\n\t\t\t\tenvelope = {\n\t\t\t\t\t_tag: 'DeclaredFailure',\n\t\t\t\t\tversion: 1,\n\t\t\t\t\tcode,\n\t\t\t\t\tmessage: definition.message,\n\t\t\t\t\tdetails: parseDetails(definition, details, false),\n\t\t\t\t} as DeclaredFailure<Definitions>\n\t\t\t} catch {\n\t\t\t\t// Validator messages, issue paths and provider causes remain private.\n\t\t\t\tthrow Error('Invalid declared error details')\n\t\t\t}\n\t\t\t// SAFETY: identity is registered below; the inaccessible brand cannot confer trust by itself.\n\t\t\tconst error = Object.freeze({\n\t\t\t\t_tag: 'DeclaredError',\n\t\t\t\tcode,\n\t\t\t\tdetails: copyJson(envelope.details),\n\t\t\t}) as Extract<DeclaredError<Definitions>, { code: typeof code }>\n\t\t\ttrusted.set(error, envelope)\n\t\t\treturn error\n\t\t},\n\t\tenvelope(code, details) {\n\t\t\t// SAFETY: create validates the selected code; project retrieves its private validated envelope.\n\t\t\treturn contract.project(contract.create(code, details)) as Extract<\n\t\t\t\tDeclaredFailure<Definitions>,\n\t\t\t\t{ code: typeof code }\n\t\t\t>\n\t\t},\n\t\ttoConvexError(code, details) {\n\t\t\treturn new ConvexError(contract.envelope(code, details))\n\t\t},\n\t\tproject(error) {\n\t\t\tif (error === null || typeof error !== 'object') return unknownFailure\n\t\t\tconst envelope = trusted.get(error)\n\t\t\t// SAFETY: only validated contract-owned envelopes enter the private map.\n\t\t\treturn envelope ? (copyJson(envelope) as DeclaredFailure<Definitions>) : unknownFailure\n\t\t},\n\t\tdecode(payload) {\n\t\t\ttry {\n\t\t\t\tif (\n\t\t\t\t\t!isRecord(payload) ||\n\t\t\t\t\tpayload._tag !== 'DeclaredFailure' ||\n\t\t\t\t\tpayload.version !== 1 ||\n\t\t\t\t\ttypeof payload.code !== 'string' ||\n\t\t\t\t\t!Object.hasOwn(declarations, payload.code) ||\n\t\t\t\t\tObject.keys(payload).length !== 5 ||\n\t\t\t\t\t!['message', 'details', '_tag', 'version', 'code'].every((key) =>\n\t\t\t\t\t\tObject.hasOwn(payload, key),\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\treturn unknownFailure\n\t\t\t\t}\n\t\t\t\tconst definition = declarations[payload.code]\n\t\t\t\tif (payload.message !== definition.message) return unknownFailure\n\t\t\t\t// Validate raw transport JSON too: parsers must not hide non-JSON payloads.\n\t\t\t\tcopyJson(payload.details)\n\t\t\t\t// SAFETY: code membership and every allowlisted field have been checked independently.\n\t\t\t\treturn {\n\t\t\t\t\t_tag: 'DeclaredFailure',\n\t\t\t\t\tversion: 1,\n\t\t\t\t\tcode: payload.code,\n\t\t\t\t\tmessage: definition.message,\n\t\t\t\t\tdetails: parseDetails(definition, payload.details, true),\n\t\t\t\t} as DeclaredFailure<Definitions>\n\t\t\t} catch {\n\t\t\t\treturn unknownFailure\n\t\t\t}\n\t\t},\n\t}\n\treturn contract\n}\n\n/** A structural decoder also accepts combined contracts without requiring constructors. */\nexport type FailureContract = Pick<ErrorContract<ErrorDefinitions>, 'decode'>\nexport type FailureOf<Contract extends FailureContract> = ReturnType<Contract['decode']>\ntype ProjectingContract = FailureContract & Pick<ErrorContract<ErrorDefinitions>, 'project'>\n\n/** Extract only ConvexError.data, including one bounded serialized JSON envelope. */\nexport function decodeFailure<Contract extends FailureContract>(\n\terror: unknown,\n\tcontract: Contract,\n): FailureOf<Contract> {\n\ttry {\n\t\tif (error instanceof ConvexError) {\n\t\t\tlet payload: unknown = error.data\n\t\t\tif (typeof payload === 'string') {\n\t\t\t\tif (payload.length > 65536 || new TextEncoder().encode(payload).byteLength > 65536)\n\t\t\t\t\t// SAFETY: every failure decoder includes UnknownFailure.\n\t\t\t\t\treturn unknownFailure as FailureOf<Contract>\n\t\t\t\tpayload = JSON.parse(payload)\n\t\t\t}\n\t\t\t// SAFETY: the structural contract owns the decoded union.\n\t\t\treturn contract.decode(payload) as FailureOf<Contract>\n\t\t}\n\t} catch {\n\t\t// Foreign errors, accessors and invalid JSON expose no diagnostics.\n\t}\n\t// SAFETY: every failure decoder includes UnknownFailure.\n\treturn unknownFailure as FailureOf<Contract>\n}\n\ntype CombinedErrorContract<Contracts extends readonly ProjectingContract[]> = Readonly<{\n\tproject: (error: unknown) => FailureOf<Contracts[number]> | UnknownFailure\n\tdecode: (payload: unknown) => FailureOf<Contracts[number]> | UnknownFailure\n}>\n\n/** Ordered projection and decoding; duplicate codes retain the union of member details. */\nexport function combineErrorContracts<const Contracts extends readonly ProjectingContract[]>(\n\t...contracts: Contracts\n): CombinedErrorContract<Contracts> {\n\tconst unmatched = unknownFailure\n\treturn {\n\t\tproject(error) {\n\t\t\tfor (const contract of contracts) {\n\t\t\t\tconst projected = contract.project(error)\n\t\t\t\tif (projected._tag === 'DeclaredFailure') {\n\t\t\t\t\t// SAFETY: this result belongs to a member of the inferred tuple.\n\t\t\t\t\treturn projected as FailureOf<Contracts[number]>\n\t\t\t\t}\n\t\t\t\tconst decoded = decodeFailure(error, contract)\n\t\t\t\tif (decoded._tag === 'DeclaredFailure') {\n\t\t\t\t\t// SAFETY: strict transported decoding preserves the same member union.\n\t\t\t\t\treturn decoded as FailureOf<Contracts[number]>\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn unmatched\n\t\t},\n\t\tdecode(payload) {\n\t\t\tfor (const contract of contracts) {\n\t\t\t\tconst decoded = contract.decode(payload)\n\t\t\t\tif (decoded._tag === 'DeclaredFailure') {\n\t\t\t\t\t// SAFETY: this result belongs to a member of the inferred tuple.\n\t\t\t\t\treturn decoded as FailureOf<Contracts[number]>\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn unmatched\n\t\t},\n\t}\n}\n\n/** Fixed, diagnostic-free transport shared by query endpoints and client recovery. */\nexport const queryErrors = defineErrorContract({\n\t'invalid-cursor': { message: 'Invalid cursor', details: {} },\n\tFIELD_GROUP_DENIED: { message: 'Field group access denied', details: {} },\n\tQUERY_FANOUT: { message: 'Query fan-out limit exceeded', details: {} },\n\tSEARCH_TEXT_REQUIRED: { message: 'Search text required', details: {} },\n\tSEARCH_END_CURSOR_UNSUPPORTED: {\n\t\tmessage: 'Search end cursor unsupported',\n\t\tdetails: {},\n\t},\n\tSEARCH_ORDER_UNSUPPORTED: {\n\t\tmessage: 'Search ordering unsupported',\n\t\tdetails: {},\n\t},\n\tSEARCH_RELATION_UNSUPPORTED: {\n\t\tmessage: 'Relation search unsupported',\n\t\tdetails: {},\n\t},\n\tSEARCH_OPTIONS_UNSUPPORTED: {\n\t\tmessage: 'Search options unsupported',\n\t\tdetails: {},\n\t},\n\tSEARCH_PROTOCOL_UNSUPPORTED: {\n\t\tmessage: 'Search pagination protocol unsupported',\n\t\tdetails: {},\n\t},\n})\n\n/** Plain object records only: no arrays, class instances or exotic prototypes. */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n\tif (value === null || typeof value !== 'object' || Array.isArray(value)) return false\n\tconst prototype = Object.getPrototypeOf(value)\n\treturn prototype === Object.prototype || prototype === null\n}\n\n/** Copy data without invoking toJSON or retaining mutable provider objects. */\nfunction copyJson(value: unknown, ancestors = new Set<object>()): Json {\n\tif (value === null || typeof value === 'string' || typeof value === 'boolean') return value\n\tif (typeof value === 'number' && Number.isFinite(value)) return value\n\tif (typeof value !== 'object' || value === null || ancestors.has(value))\n\t\tthrow Error('Invalid JSON')\n\tancestors.add(value)\n\ttry {\n\t\tif (Array.isArray(value)) {\n\t\t\tconst result: Json[] = []\n\t\t\tfor (let index = 0; index < value.length; index++)\n\t\t\t\tresult.push(copyJson(value[index], ancestors))\n\t\t\treturn result\n\t\t}\n\t\tif (!isRecord(value)) throw Error('Invalid JSON')\n\t\treturn Object.fromEntries(\n\t\t\tObject.entries(value).map(([key, child]) => [key, copyJson(child, ancestors)]),\n\t\t)\n\t} finally {\n\t\tancestors.delete(value)\n\t}\n}\n\nfunction parseDetails<const Definition extends ErrorDefinitions[string]>(\n\tdefinition: Definition,\n\tvalue: unknown,\n\tstrict: boolean,\n): Details<Definition> {\n\tif (!isRecord(value)) throw Error('Invalid details')\n\tconst fields = Object.keys(definition.details)\n\tif (strict && Object.keys(value).some((key) => !Object.hasOwn(definition.details, key))) {\n\t\tthrow Error('Undeclared detail')\n\t}\n\t// SAFETY: each declared field is validated by its paired parser before its JSON-safe copy is returned.\n\treturn Object.fromEntries(\n\t\tfields.map((field) => {\n\t\t\tif (!Object.hasOwn(value, field)) throw Error('Missing detail')\n\t\t\treturn [field, copyJson(definition.details[field].parse(value[field]))]\n\t\t}),\n\t) as Details<Definition>\n}\n"],"mappings":"4CA2EA,MAAMA,EAAiC,OAAO,OAAO,CACpD,KAAM,iBACN,QAAS,CACV,CAAC,EAID,SAAgBC,EACf,EAC6B,CAE7B,IAAMC,EAAe,OAAO,YAC3B,OAAO,QAAQC,CAAW,CAAC,CAAC,KAAK,CAACC,EAAMC,KAAgB,CACvD,GAAI,CAACD,GAAQ,CAACC,EAAW,SAAWA,EAAW,QAAQ,OAAS,IAC/D,MAAM,MAAM,yEAAyE,EAEtF,MAAO,CAACD,EAAM,CAAE,QAASC,EAAW,QAAS,QAAS,CAAE,GAAGA,EAAW,OAAQ,CAAE,CAAC,CAClF,CAAC,CACF,EACMC,kBAAU,IAAI,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,EACnD,IAAMM,EAAS,OAAO,KAAKzB,EAAW,OAAO,EAC7C,GAAI0B,GAAU,OAAO,KAAKP,CAAK,CAAC,CAAC,KAAM,GAAQ,CAAC,OAAO,OAAOnB,EAAW,QAASW,CAAG,CAAC,EACrF,MAAM,MAAM,mBAAmB,EAGhC,OAAO,OAAO,YACbc,EAAO,IAAK,GAAU,CACrB,GAAI,CAAC,OAAO,OAAON,EAAOQ,CAAK,EAAG,MAAM,MAAM,gBAAgB,EAC9D,MAAO,CAACA,EAAOpB,EAASP,EAAW,QAAQ2B,EAAM,CAAC,MAAMR,EAAMQ,EAAM,CAAC,CAAC,CACvE,CAAC,CACF,CACD"}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { Observability } from "../../components/foundation/modules/observability/observability.mjs";
|
|
2
|
+
import { AuditEntryInput } from "../../components/foundation/client.mjs";
|
|
3
|
+
import { DomainActionContract, DomainAuditInput, DomainContract } from "../contracts/domain.mjs";
|
|
4
|
+
import { NestedAuditMode, RequestScope } from "./scope.mjs";
|
|
5
|
+
import { CallbackError, CallbackRequirements, ValidatedEffectOperations, effectActionFactory } from "./operation.mjs";
|
|
6
|
+
import { FailureAuditOptions } from "./failure-audit.mjs";
|
|
7
|
+
import { BoundOperations } from "../contracts/binding.mjs";
|
|
8
|
+
import { AuditValue, AuditedOperations, DomainEffectFactory, DomainEffectImplementations, ExactDomainOperations } from "./domain.mjs";
|
|
9
|
+
import { DomainOf, HostOf, HostParameter, Registry, Resolver, createEffectCommand } from "./command.mjs";
|
|
10
|
+
import { Effect } from "effect";
|
|
11
|
+
//#region src/modules/effect/action.d.ts
|
|
12
|
+
type Supported<Value> = Value | PromiseLike<Value> | Effect.Effect<Value, unknown, unknown>;
|
|
13
|
+
/** Host policies an Action registry uses; actions have no mutation-side permission host. */
|
|
14
|
+
export type EffectActionDependencies = {
|
|
15
|
+
observability: Observability;
|
|
16
|
+
/** Writes action audit entries, typically through `ctx.runMutation`; required once any action audits. */
|
|
17
|
+
writeActionAudit?: (host: never, entry: AuditEntryInput) => Supported<unknown>;
|
|
18
|
+
auditFailure?: FailureAuditOptions;
|
|
19
|
+
nestedAudit?: NestedAuditMode;
|
|
20
|
+
};
|
|
21
|
+
type ActionWriter<Dependencies extends EffectActionDependencies> = [Exclude<Dependencies['writeActionAudit'], undefined>] extends [never] ? (host: never, entry: AuditEntryInput) => void : Exclude<Dependencies['writeActionAudit'], undefined>;
|
|
22
|
+
/** The command kernel runs actions with the action writer in its audit-writer slot. */
|
|
23
|
+
type KernelDependencies<Dependencies extends EffectActionDependencies> = {
|
|
24
|
+
observability: Observability;
|
|
25
|
+
writeAudit: ActionWriter<Dependencies>;
|
|
26
|
+
auditFailure?: FailureAuditOptions;
|
|
27
|
+
nestedAudit?: NestedAuditMode;
|
|
28
|
+
};
|
|
29
|
+
type ActionCompatible<Resolve extends Resolver, Dependencies extends EffectActionDependencies> = [HostOf<Resolve>] extends [HostParameter<Dependencies['writeActionAudit']>] ? unknown : {
|
|
30
|
+
context: never;
|
|
31
|
+
};
|
|
32
|
+
type ActionFactory<Resolve extends Resolver, Guard> = ReturnType<typeof effectActionFactory<DomainOf<Resolve>, NoInfer<CallbackError<Guard>>, NoInfer<CallbackRequirements<Guard>>>>;
|
|
33
|
+
type Kernel<Resolve extends Resolver, Operations extends Registry<DomainOf<Resolve>>, Dependencies extends EffectActionDependencies, Guard> = ReturnType<typeof createEffectCommand<Resolve, Operations, KernelDependencies<Dependencies>, Guard>>;
|
|
34
|
+
/** Actions are executed by their own Convex action functions; they are never exposed as mutations. */
|
|
35
|
+
export type EffectActionRegistry<Resolve extends Resolver, Operations extends Registry<DomainOf<Resolve>>, Dependencies extends EffectActionDependencies, Guard> = Pick<Kernel<Resolve, Operations, Dependencies, Guard>, 'exec' | 'withContext'>;
|
|
36
|
+
export declare class ActionAuditWriterError extends Error {
|
|
37
|
+
readonly code = "ACTION_AUDIT_WRITER_MISSING";
|
|
38
|
+
readonly name = "ActionAuditWriterError";
|
|
39
|
+
constructor(operation: string);
|
|
40
|
+
}
|
|
41
|
+
/** Bind trusted application policies once; each registry resolves its own invocation context. */
|
|
42
|
+
export declare function bindEffectAction<const Dependencies extends EffectActionDependencies>(dependencies: Dependencies): {
|
|
43
|
+
<Resolve extends Resolver, const Contract extends DomainContract & {
|
|
44
|
+
actions: Readonly<Record<string, DomainActionContract>>;
|
|
45
|
+
}, const Operations extends DomainEffectImplementations<DomainOf<Resolve>, Contract['actions']>, Returned extends AuditValue = never, Guard = never>(configuration: {
|
|
46
|
+
contract: Contract & NoInfer<Operations extends ExactDomainOperations<Operations, Contract['actions']> & ValidatedEffectOperations<Operations> ? unknown : never>;
|
|
47
|
+
context: Resolve;
|
|
48
|
+
audit?: (resolution: DomainAuditInput<Contract['actions']>, context: DomainOf<Resolve>, scope: RequestScope | undefined) => Returned;
|
|
49
|
+
operations: (define: DomainEffectFactory<DomainOf<Resolve>, Contract['actions'], 'action', never, NoInfer<CallbackError<Guard>>, NoInfer<CallbackRequirements<Guard>>, Contract['errors']>) => Operations;
|
|
50
|
+
defaults?: {
|
|
51
|
+
guard?: (context: DomainOf<Resolve>) => Guard;
|
|
52
|
+
};
|
|
53
|
+
} & ActionCompatible<Resolve, Dependencies>): EffectActionRegistry<Resolve, [Returned] extends [never] ? BoundOperations<Operations, Contract['actions']> : AuditedOperations<BoundOperations<Operations, Contract['actions']>, (resolution: never, context: never) => Returned>, Dependencies, Guard>;
|
|
54
|
+
<Resolve extends Resolver, const Operations extends Registry<DomainOf<Resolve>>, Returned extends AuditValue = never, Guard = never>(configuration: {
|
|
55
|
+
context: Resolve;
|
|
56
|
+
audit?: (resolution: DomainAuditInput<Operations>, context: DomainOf<Resolve>, scope: RequestScope | undefined) => Returned;
|
|
57
|
+
operations: (define: ActionFactory<Resolve, Guard>) => Operations & NoInfer<ValidatedEffectOperations<Operations>>;
|
|
58
|
+
defaults?: {
|
|
59
|
+
guard?: (context: DomainOf<Resolve>) => Guard;
|
|
60
|
+
};
|
|
61
|
+
} & ActionCompatible<Resolve, Dependencies>): EffectActionRegistry<Resolve, [Returned] extends [never] ? Operations : AuditedOperations<Operations, (resolution: never, context: never) => Returned>, Dependencies, Guard>;
|
|
62
|
+
};
|
|
63
|
+
//#endregion
|
|
64
|
+
//# sourceMappingURL=action.d.mts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{memoize as e,registerLazyRegistry as t}from"../contracts/lazy.mjs";import{effectActionFactory as n}from"./operation.mjs";import{snapshotOperations as r}from"../contracts/binding.mjs";import{domainEffectFactory as i}from"./domain.mjs";import{createEffectCommand as a}from"./command.mjs";var o=class extends Error{code=`ACTION_AUDIT_WRITER_MISSING`;name=`ActionAuditWriterError`;constructor(e){super(`Action "${e}" declares an audit but the Foundation has no writeActionAudit`)}};function s(s){function c(c){let l=e(()=>{let e=r(c.operations(c.contract?i(c.contract.actions??{},`action`,c.contract.errors):n()),c.contract,`actions`,c.audit);if(!s.writeActionAudit){for(let[t,n]of Object.entries(e))if(`audit`in n&&n.audit!==void 0)throw new o(t)}return e}),u=a({...c,observability:s.observability,auditFailure:s.auditFailure,nestedAudit:s.nestedAudit,writeAudit:s.writeActionAudit??(()=>void 0),operations:l,mode:`action`});return t({exec:u.exec,withContext:u.withContext},l)}return c}export{o as ActionAuditWriterError,s as bindEffectAction};
|
|
2
|
+
//# sourceMappingURL=action.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"action.mjs","names":["ActionAuditWriterError","operation","bindEffectAction","action","getOperations","memoize","operations","snapshotOperations","configuration","domainEffectFactory","effectActionFactory","dependencies","definition","kernel","createEffectCommand","registerLazyRegistry"],"sources":["../../../src/modules/effect/action.ts"],"sourcesContent":["/* 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 type { Effect } from 'effect'\nimport type { AuditEntryInput } from '../../components/foundation/client'\n// oxlint-disable-next-line cvx/component-boundaries -- SAFETY: Internal optional adapter shares the Effect-free Foundation observability without entering the Convex component deployment graph.\nimport type { Observability } from '../../components/foundation/modules/observability/observability'\nimport type { DomainActionContract, DomainAuditInput, DomainContract } from '../contracts/domain'\nimport { snapshotOperations, type BoundOperations } from '../contracts/binding'\nimport { memoize, registerLazyRegistry } from '../contracts/lazy'\nimport {\n\tcreateEffectCommand,\n\ttype DomainOf,\n\ttype HostOf,\n\ttype HostParameter,\n\ttype Registry,\n\ttype Resolver,\n} from './command'\nimport {\n\tdomainEffectFactory,\n\ttype AuditedOperations,\n\ttype AuditValue,\n\ttype DomainEffectFactory,\n\ttype DomainEffectImplementations,\n\ttype ExactDomainOperations,\n} from './domain'\nimport type { FailureAuditOptions } from './failure-audit'\nimport {\n\teffectActionFactory,\n\ttype CallbackError,\n\ttype CallbackRequirements,\n\ttype ValidatedEffectOperations,\n} from './operation'\nimport type { NestedAuditMode, RequestScope } from './scope'\n\ntype Supported<Value> = Value | PromiseLike<Value> | Effect.Effect<Value, unknown, unknown>\n\n/** Host policies an Action registry uses; actions have no mutation-side permission host. */\nexport type EffectActionDependencies = {\n\tobservability: Observability\n\t/** Writes action audit entries, typically through `ctx.runMutation`; required once any action audits. */\n\twriteActionAudit?: (host: never, entry: AuditEntryInput) => Supported<unknown>\n\tauditFailure?: FailureAuditOptions\n\tnestedAudit?: NestedAuditMode\n}\ntype ActionWriter<Dependencies extends EffectActionDependencies> = [\n\tExclude<Dependencies['writeActionAudit'], undefined>,\n] extends [never]\n\t? (host: never, entry: AuditEntryInput) => void\n\t: Exclude<Dependencies['writeActionAudit'], undefined>\n/** The command kernel runs actions with the action writer in its audit-writer slot. */\ntype KernelDependencies<Dependencies extends EffectActionDependencies> = {\n\tobservability: Observability\n\twriteAudit: ActionWriter<Dependencies>\n\tauditFailure?: FailureAuditOptions\n\tnestedAudit?: NestedAuditMode\n}\ntype ActionCompatible<Resolve extends Resolver, Dependencies extends EffectActionDependencies> = [\n\tHostOf<Resolve>,\n] extends [HostParameter<Dependencies['writeActionAudit']>]\n\t? unknown\n\t: { context: never }\ntype ActionFactory<Resolve extends Resolver, Guard> = ReturnType<\n\ttypeof effectActionFactory<\n\t\tDomainOf<Resolve>,\n\t\tNoInfer<CallbackError<Guard>>,\n\t\tNoInfer<CallbackRequirements<Guard>>\n\t>\n>\ntype Kernel<\n\tResolve extends Resolver,\n\tOperations extends Registry<DomainOf<Resolve>>,\n\tDependencies extends EffectActionDependencies,\n\tGuard,\n> = ReturnType<\n\ttypeof createEffectCommand<Resolve, Operations, KernelDependencies<Dependencies>, Guard>\n>\n/** Actions are executed by their own Convex action functions; they are never exposed as mutations. */\nexport type EffectActionRegistry<\n\tResolve extends Resolver,\n\tOperations extends Registry<DomainOf<Resolve>>,\n\tDependencies extends EffectActionDependencies,\n\tGuard,\n> = Pick<Kernel<Resolve, Operations, Dependencies, Guard>, 'exec' | 'withContext'>\n\nexport class ActionAuditWriterError extends Error {\n\treadonly code = 'ACTION_AUDIT_WRITER_MISSING'\n\treadonly name = 'ActionAuditWriterError'\n\tconstructor(operation: string) {\n\t\tsuper(`Action \"${operation}\" declares an audit but the Foundation has no writeActionAudit`)\n\t}\n}\n\n/** Bind trusted application policies once; each registry resolves its own invocation context. */\nexport function bindEffectAction<const Dependencies extends EffectActionDependencies>(\n\tdependencies: Dependencies,\n) {\n\tfunction action<\n\t\tResolve extends Resolver,\n\t\tconst Contract extends DomainContract & {\n\t\t\tactions: Readonly<Record<string, DomainActionContract>>\n\t\t},\n\t\tconst Operations extends DomainEffectImplementations<DomainOf<Resolve>, Contract['actions']>,\n\t\tReturned extends AuditValue = never,\n\t\tGuard = never,\n\t>(\n\t\tconfiguration: {\n\t\t\tcontract: Contract &\n\t\t\t\tNoInfer<\n\t\t\t\t\tOperations extends ExactDomainOperations<Operations, Contract['actions']> &\n\t\t\t\t\t\tValidatedEffectOperations<Operations>\n\t\t\t\t\t\t? unknown\n\t\t\t\t\t\t: never\n\t\t\t\t>\n\t\t\tcontext: Resolve\n\t\t\taudit?: (\n\t\t\t\tresolution: DomainAuditInput<Contract['actions']>,\n\t\t\t\tcontext: DomainOf<Resolve>,\n\t\t\t\tscope: RequestScope | undefined,\n\t\t\t) => Returned\n\t\t\toperations: (\n\t\t\t\tdefine: DomainEffectFactory<\n\t\t\t\t\tDomainOf<Resolve>,\n\t\t\t\t\tContract['actions'],\n\t\t\t\t\t'action',\n\t\t\t\t\tnever,\n\t\t\t\t\tNoInfer<CallbackError<Guard>>,\n\t\t\t\t\tNoInfer<CallbackRequirements<Guard>>,\n\t\t\t\t\tContract['errors']\n\t\t\t\t>,\n\t\t\t) => Operations\n\t\t\tdefaults?: { guard?: (context: DomainOf<Resolve>) => Guard }\n\t\t} & ActionCompatible<Resolve, Dependencies>,\n\t): EffectActionRegistry<\n\t\tResolve,\n\t\t[Returned] extends [never]\n\t\t\t? BoundOperations<Operations, Contract['actions']>\n\t\t\t: AuditedOperations<\n\t\t\t\t\tBoundOperations<Operations, Contract['actions']>,\n\t\t\t\t\t(resolution: never, context: never) => Returned\n\t\t\t\t>,\n\t\tDependencies,\n\t\tGuard\n\t>\n\tfunction action<\n\t\tResolve extends Resolver,\n\t\tconst Operations extends Registry<DomainOf<Resolve>>,\n\t\tReturned extends AuditValue = never,\n\t\tGuard = never,\n\t>(\n\t\tconfiguration: {\n\t\t\tcontext: Resolve\n\t\t\taudit?: (\n\t\t\t\tresolution: DomainAuditInput<Operations>,\n\t\t\t\tcontext: DomainOf<Resolve>,\n\t\t\t\tscope: RequestScope | undefined,\n\t\t\t) => Returned\n\t\t\toperations: (\n\t\t\t\tdefine: ActionFactory<Resolve, Guard>,\n\t\t\t) => Operations & NoInfer<ValidatedEffectOperations<Operations>>\n\t\t\tdefaults?: { guard?: (context: DomainOf<Resolve>) => Guard }\n\t\t} & ActionCompatible<Resolve, Dependencies>,\n\t): EffectActionRegistry<\n\t\tResolve,\n\t\t[Returned] extends [never]\n\t\t\t? Operations\n\t\t\t: AuditedOperations<Operations, (resolution: never, context: never) => Returned>,\n\t\tDependencies,\n\t\tGuard\n\t>\n\tfunction action(configuration: {\n\t\tcontext: Resolver\n\t\tcontract?: DomainContract\n\t\taudit?: (resolution: never, context: never, scope: never) => AuditValue\n\t\toperations: (define: never) => Readonly<Record<string, object>>\n\t\tdefaults?: { guard?: (context: never) => unknown }\n\t}): unknown {\n\t\tconst buildOperations = () => {\n\t\t\tconst operations = snapshotOperations(\n\t\t\t\tconfiguration.operations(\n\t\t\t\t\t// SAFETY: each overload checks callbacks against this exact inline or contracted helper factory.\n\t\t\t\t\t(configuration.contract\n\t\t\t\t\t\t? domainEffectFactory(\n\t\t\t\t\t\t\t\tconfiguration.contract.actions ?? {},\n\t\t\t\t\t\t\t\t'action',\n\t\t\t\t\t\t\t\tconfiguration.contract.errors,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t: effectActionFactory()) as never,\n\t\t\t\t),\n\t\t\t\tconfiguration.contract,\n\t\t\t\t'actions',\n\t\t\t\tconfiguration.audit,\n\t\t\t)\n\t\t\tif (!dependencies.writeActionAudit) {\n\t\t\t\tfor (const [operation, definition] of Object.entries(operations))\n\t\t\t\t\tif ('audit' in definition && definition.audit !== undefined)\n\t\t\t\t\t\tthrow new ActionAuditWriterError(operation)\n\t\t\t}\n\t\t\treturn operations\n\t\t}\n\t\tconst getOperations = memoize(buildOperations)\n\t\t// SAFETY: overloads check callbacks and schemas; binding validates exact keys and snapshots runtime records.\n\t\tconst kernel = createEffectCommand({\n\t\t\t...configuration,\n\t\t\tobservability: dependencies.observability,\n\t\t\tauditFailure: dependencies.auditFailure,\n\t\t\tnestedAudit: dependencies.nestedAudit,\n\t\t\twriteAudit: dependencies.writeActionAudit ?? (() => undefined),\n\t\t\toperations: getOperations,\n\t\t\tmode: 'action',\n\t\t} as never)\n\t\treturn registerLazyRegistry(\n\t\t\t{ exec: kernel.exec, withContext: kernel.withContext },\n\t\t\tgetOperations,\n\t\t)\n\t}\n\treturn action\n}\n"],"mappings":"qSAmFA,IAAaA,EAAb,cAA4C,KAAM,CACjD,KAAgB,8BAChB,KAAgB,yBAChB,YAAY,EAAmB,CAC9B,MAAM,WAAWC,EAAU,+DAA+D,CAC3F,CACD,EAGA,SAAgBC,EACf,EACC,CA0ED,SAASC,EAAO,EAMJ,CAwBX,IAAMC,EAAgBC,MAvBQ,CAC7B,IAAMC,EAAaC,EAClBC,EAAc,WAEZA,EAAc,SACZC,EACAD,EAAc,SAAS,SAAW,CAAC,EACnC,SACAA,EAAc,SAAS,MACxB,EACCE,EAAoB,CACxB,EACAF,EAAc,SACd,UACAA,EAAc,KACf,EACA,GAAI,CAACG,EAAa,iBACZ,KAAA,GAAM,CAACV,EAAWW,KAAe,OAAO,QAAQN,CAAU,EAC9D,GAAI,UAAWM,GAAcA,EAAW,QAAU,IAAA,GACjD,MAAM,IAAIZ,EAAuBC,CAAS,CAAA,CAE7C,OAAOK,CACR,CAC6C,EAEvCO,EAASC,EAAoB,CAClC,GAAGN,EACH,cAAeG,EAAa,cAC5B,aAAcA,EAAa,aAC3B,YAAaA,EAAa,YAC1B,WAAYA,EAAa,uBAA2B,IAAA,IACpD,WAAYP,EACZ,KAAM,QACP,CAAU,EACV,OAAOW,EACN,CAAE,KAAMF,EAAO,KAAM,YAAaA,EAAO,WAAY,EACrDT,CACD,CACD,CACA,OAAOD,CACR"}
|
|
@@ -1,12 +1,16 @@
|
|
|
1
1
|
import { OperationExecutor, OperationPublicResult, OperationTool, OperationToolConverter, OperationToolDefinition, OperationToolJsonSchema, OperationToolOutcome, SelectedOperation, bindOperationExecutor, createOperationTools, operationToolDialect, selectOperation } from "../contracts/exposure.mjs";
|
|
2
2
|
import { ContractDecoderError, ContractDecoderRequirements, ContractValidationError, EffectDecoder, decodeEffectContract, effectContract, effectSchema, effectStandardSchema } from "./schema.mjs";
|
|
3
|
+
import { NestedAuditMode, RequestScope } from "./scope.mjs";
|
|
3
4
|
import { CallbackError, CallbackRequirements, EffectMiddlewareInput, EffectOperationArgument, EffectOperationError, EffectOperationHandlerResult, EffectOperationInput, EffectOperationRequirements, EffectOperationResult, EffectPreparation, EffectValue, effectOperationFactory } from "./operation.mjs";
|
|
4
5
|
import { EffectZodApiBuilder, effectZodApiBuilder } from "./api-zod.mjs";
|
|
5
6
|
import "./agent-tools.mjs";
|
|
7
|
+
import { FailureAuditEntry, FailureAuditOptions } from "./failure-audit.mjs";
|
|
8
|
+
import { EffectErrors, effectErrors } from "./failures.mjs";
|
|
9
|
+
import { ActionAuditWriterError, EffectActionDependencies, EffectActionRegistry } from "./action.mjs";
|
|
6
10
|
import { EffectFoundationOptions, createEffectFoundation } from "./foundation.mjs";
|
|
7
11
|
import { EffectIdempotencyPreparation, effectTransactionalIdempotency } from "./idempotency.mjs";
|
|
8
12
|
import { EffectCrudConfig, EffectCrudContext, EffectCrudPage, EffectCrudPagination, EffectCrudRepository, EffectCrudTable, createEffectCrud } from "./crud.mjs";
|
|
9
13
|
import { EffectApiBuilder, effectApiBuilder } from "./api.mjs";
|
|
10
14
|
import { projectErrorCause } from "./errors.mjs";
|
|
11
15
|
import { EffectReceiptProtectedWorkflowMutation, effectReceiptWorkflowMutation, effectTerminalWorkflowAttempt, effectWorkflowAttempt, effectWorkflowStatusBindings } from "./workflow.mjs";
|
|
12
|
-
export { type CallbackError, type CallbackRequirements, type ContractDecoderError, type ContractDecoderRequirements, ContractValidationError, type EffectApiBuilder, type EffectCrudConfig, type EffectCrudContext, type EffectCrudPage, type EffectCrudPagination, type EffectCrudRepository, type EffectCrudTable, type EffectDecoder, type EffectFoundationOptions, type EffectIdempotencyPreparation, type EffectMiddlewareInput, type EffectOperationArgument, type EffectOperationError, type EffectOperationHandlerResult, type EffectOperationInput, type EffectOperationRequirements, type EffectOperationResult, type EffectPreparation, type EffectReceiptProtectedWorkflowMutation, type EffectValue, type EffectZodApiBuilder, type OperationExecutor, type OperationPublicResult, type OperationTool, type OperationToolConverter, type OperationToolDefinition, type OperationToolJsonSchema, type OperationToolOutcome, type SelectedOperation, bindOperationExecutor, createEffectCrud, createEffectFoundation, createOperationTools, decodeEffectContract, effectApiBuilder, effectContract, effectOperationFactory, effectReceiptWorkflowMutation, effectSchema, effectStandardSchema, effectTerminalWorkflowAttempt, effectTransactionalIdempotency, effectWorkflowAttempt, effectWorkflowStatusBindings, effectZodApiBuilder, operationToolDialect, projectErrorCause, selectOperation };
|
|
16
|
+
export { ActionAuditWriterError, type CallbackError, type CallbackRequirements, type ContractDecoderError, type ContractDecoderRequirements, ContractValidationError, type EffectActionDependencies, type EffectActionRegistry, type EffectApiBuilder, type EffectCrudConfig, type EffectCrudContext, type EffectCrudPage, type EffectCrudPagination, type EffectCrudRepository, type EffectCrudTable, type EffectDecoder, type EffectErrors, type EffectFoundationOptions, type EffectIdempotencyPreparation, type EffectMiddlewareInput, type EffectOperationArgument, type EffectOperationError, type EffectOperationHandlerResult, type EffectOperationInput, type EffectOperationRequirements, type EffectOperationResult, type EffectPreparation, type EffectReceiptProtectedWorkflowMutation, type EffectValue, type EffectZodApiBuilder, type FailureAuditEntry, type FailureAuditOptions, type NestedAuditMode, type OperationExecutor, type OperationPublicResult, type OperationTool, type OperationToolConverter, type OperationToolDefinition, type OperationToolJsonSchema, type OperationToolOutcome, type RequestScope, type SelectedOperation, bindOperationExecutor, createEffectCrud, createEffectFoundation, createOperationTools, decodeEffectContract, effectApiBuilder, effectContract, effectErrors, effectOperationFactory, effectReceiptWorkflowMutation, effectSchema, effectStandardSchema, effectTerminalWorkflowAttempt, effectTransactionalIdempotency, effectWorkflowAttempt, effectWorkflowStatusBindings, effectZodApiBuilder, operationToolDialect, projectErrorCause, selectOperation };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{bindOperationExecutor as e,createOperationTools as t,operationToolDialect as n,selectOperation as r}from"../contracts/exposure.mjs";import{projectErrorCause as i}from"./errors.mjs";import{effectZodApiBuilder as a}from"./api-zod.mjs";import{effectOperationFactory as o}from"./operation.mjs";import{ContractValidationError as s,decodeEffectContract as c,effectContract as l,effectSchema as u,effectStandardSchema as d}from"./schema.mjs";import{
|
|
1
|
+
import{bindOperationExecutor as e,createOperationTools as t,operationToolDialect as n,selectOperation as r}from"../contracts/exposure.mjs";import{projectErrorCause as i}from"./errors.mjs";import{effectZodApiBuilder as a}from"./api-zod.mjs";import{effectOperationFactory as o}from"./operation.mjs";import{ContractValidationError as s,decodeEffectContract as c,effectContract as l,effectSchema as u,effectStandardSchema as d}from"./schema.mjs";import{effectErrors as f}from"./failures.mjs";import{ActionAuditWriterError as p}from"./action.mjs";import{createEffectFoundation as m}from"./foundation.mjs";import{effectTransactionalIdempotency as h}from"./idempotency.mjs";import{createEffectCrud as g}from"./crud.mjs";import{effectApiBuilder as _}from"./api.mjs";import{effectReceiptWorkflowMutation as v,effectTerminalWorkflowAttempt as y,effectWorkflowAttempt as b,effectWorkflowStatusBindings as x}from"./workflow.mjs";export{p as ActionAuditWriterError,s as ContractValidationError,e as bindOperationExecutor,g as createEffectCrud,m as createEffectFoundation,t as createOperationTools,c as decodeEffectContract,_ as effectApiBuilder,l as effectContract,f as effectErrors,o as effectOperationFactory,v as effectReceiptWorkflowMutation,u as effectSchema,d as effectStandardSchema,y as effectTerminalWorkflowAttempt,h as effectTransactionalIdempotency,b as effectWorkflowAttempt,x as effectWorkflowStatusBindings,a as effectZodApiBuilder,n as operationToolDialect,i as projectErrorCause,r as selectOperation};
|
|
@@ -3,16 +3,18 @@ import { OperationPublicResult, SelectedOperation } from "../contracts/exposure.
|
|
|
3
3
|
import { Observability } from "../../components/foundation/modules/observability/observability.mjs";
|
|
4
4
|
import { AuditEntryInput } from "../../components/foundation/client.mjs";
|
|
5
5
|
import { DomainAuditInput, DomainCommandContract, DomainContract } from "../contracts/domain.mjs";
|
|
6
|
+
import { NestedAuditMode, RequestScope } from "./scope.mjs";
|
|
6
7
|
import { CallbackError, CallbackRequirements, CheckedEffectOperation, EffectOperationArgument, EffectOperationError, EffectOperationRequirements, EffectOperationResult, EffectValue, UnwrappedDefaultError, UnwrappedDefaultRequirements, ValidatedEffectOperations, effectOperationFactory } from "./operation.mjs";
|
|
8
|
+
import { FailureAuditOptions } from "./failure-audit.mjs";
|
|
7
9
|
import { BoundOperations } from "../contracts/binding.mjs";
|
|
8
10
|
import { AuditValue, AuditedOperations, DomainEffectFactory, DomainEffectImplementations, ExactDomainOperations, SharedEffectFactory } from "./domain.mjs";
|
|
9
11
|
import { Effect } from "effect";
|
|
10
12
|
//#region src/modules/effect/command.d.ts
|
|
11
13
|
type Supported<Value> = Value | PromiseLike<Value> | Effect.Effect<Value, unknown, unknown>;
|
|
12
14
|
type Callback = (...arguments_: never[]) => Supported<unknown>;
|
|
13
|
-
type Resolver = (host: never) => Supported<unknown>;
|
|
14
|
-
type HostOf<Resolve extends Resolver> = Parameters<Resolve>[0];
|
|
15
|
-
type DomainOf<Resolve extends Resolver> = EffectValue<ReturnType<Resolve>>;
|
|
15
|
+
export type Resolver = (host: never) => Supported<unknown>;
|
|
16
|
+
export type HostOf<Resolve extends Resolver> = Parameters<Resolve>[0];
|
|
17
|
+
export type DomainOf<Resolve extends Resolver> = EffectValue<ReturnType<Resolve>>;
|
|
16
18
|
type Operation = {
|
|
17
19
|
input: ContractSchema;
|
|
18
20
|
result: ContractSchema;
|
|
@@ -26,7 +28,7 @@ type Operation = {
|
|
|
26
28
|
aggregates?: readonly string[];
|
|
27
29
|
replayResult?: ContractSchema;
|
|
28
30
|
};
|
|
29
|
-
type Registry<Context> = Readonly<Record<string, Pick<Operation, 'input' | 'result' | '
|
|
31
|
+
export type Registry<Context> = Readonly<Record<string, Pick<Operation, 'input' | 'result' | 'handler'> & Partial<Pick<Operation, 'classification' | 'audit'>> & CheckedEffectOperation<Context>>>;
|
|
30
32
|
export type EffectCommandDependencies = {
|
|
31
33
|
observability: Observability;
|
|
32
34
|
checkPermission?: (host: never, input: {
|
|
@@ -34,8 +36,12 @@ export type EffectCommandDependencies = {
|
|
|
34
36
|
operation: string;
|
|
35
37
|
}) => Supported<void>;
|
|
36
38
|
writeAudit: (host: never, entry: AuditEntryInput) => Supported<unknown>;
|
|
39
|
+
/** `fold` (default): an operation nested under an auditing operation leaves the audit to it. */
|
|
40
|
+
nestedAudit?: NestedAuditMode;
|
|
41
|
+
/** Host-free sink for failed operations; see `FailureAuditOptions`. */
|
|
42
|
+
auditFailure?: FailureAuditOptions;
|
|
37
43
|
};
|
|
38
|
-
type HostParameter<Policy> = [Exclude<Policy, undefined>] extends [never] ? unknown : Exclude<Policy, undefined> extends ((...arguments_: infer Arguments) => Supported<unknown>) ? Arguments extends [] ? unknown : Arguments[0] : unknown;
|
|
44
|
+
export type HostParameter<Policy> = [Exclude<Policy, undefined>] extends [never] ? unknown : Exclude<Policy, undefined> extends ((...arguments_: infer Arguments) => Supported<unknown>) ? Arguments extends [] ? unknown : Arguments[0] : unknown;
|
|
39
45
|
type PolicyHost<Dependencies extends EffectCommandDependencies> = HostParameter<Dependencies['writeAudit']> & HostParameter<Dependencies['checkPermission']>;
|
|
40
46
|
type HostCompatible<Resolve extends Resolver, Dependencies extends EffectCommandDependencies> = [HostOf<Resolve>] extends [PolicyHost<Dependencies>] ? unknown : {
|
|
41
47
|
context: never;
|
|
@@ -67,7 +73,7 @@ export declare function bindEffectCommand<const Dependencies extends EffectComma
|
|
|
67
73
|
contract: Contract & NoInfer<Operations extends ExactDomainOperations<Operations, Contract['commands']> & ValidatedEffectOperations<Operations> ? unknown : never>;
|
|
68
74
|
context: Resolve;
|
|
69
75
|
audit?: never;
|
|
70
|
-
operations: (define: DomainEffectFactory<DomainOf<Resolve>, Contract['commands'], Mode, never, NoInfer<CallbackError<Guard>>, NoInfer<CallbackRequirements<Guard
|
|
76
|
+
operations: (define: DomainEffectFactory<DomainOf<Resolve>, Contract['commands'], Mode, never, NoInfer<CallbackError<Guard>>, NoInfer<CallbackRequirements<Guard>>, Contract['errors']>) => Operations;
|
|
71
77
|
defaults?: {
|
|
72
78
|
guard?: (context: DomainOf<Resolve>) => Guard;
|
|
73
79
|
};
|
|
@@ -80,15 +86,15 @@ export declare function bindEffectCommand<const Dependencies extends EffectComma
|
|
|
80
86
|
}, const Operations extends DomainEffectImplementations<DomainOf<Resolve>, Contract['commands']>, Returned extends AuditValue, Guard = never>(configuration: {
|
|
81
87
|
contract: Contract & NoInfer<Operations extends ExactDomainOperations<Operations, Contract['commands']> & ValidatedEffectOperations<Operations> ? unknown : never>;
|
|
82
88
|
context: Resolve;
|
|
83
|
-
audit: (resolution: DomainAuditInput<Contract['commands']>, context: DomainOf<Resolve
|
|
84
|
-
operations: (define: DomainEffectFactory<DomainOf<Resolve>, Contract['commands'], true, [Returned] extends [never] ? never : (resolution: never, context: never) => Returned, NoInfer<CallbackError<Guard>>, NoInfer<CallbackRequirements<Guard
|
|
89
|
+
audit: (resolution: DomainAuditInput<Contract['commands']>, context: DomainOf<Resolve>, scope: RequestScope | undefined) => Returned;
|
|
90
|
+
operations: (define: DomainEffectFactory<DomainOf<Resolve>, Contract['commands'], true, [Returned] extends [never] ? never : (resolution: never, context: never) => Returned, NoInfer<CallbackError<Guard>>, NoInfer<CallbackRequirements<Guard>>, Contract['errors']>) => Operations;
|
|
85
91
|
defaults?: {
|
|
86
92
|
guard?: (context: DomainOf<Resolve>) => Guard;
|
|
87
93
|
};
|
|
88
94
|
} & HostCompatible<Resolve, Dependencies>): ReturnType<typeof createEffectCommand<Resolve, AuditedOperations<BoundOperations<Operations, Contract['commands']>, (resolution: never, context: never) => Returned>, Dependencies, Guard>>;
|
|
89
95
|
<Resolve extends Resolver, const Operations extends Readonly<Record<string, Pick<Operation, "classification" | "handler" | "input" | "result"> & CheckedEffectOperation<EffectValue<ReturnType<Resolve>>>>>, Returned extends AuditValue, Guard>(configuration: {
|
|
90
96
|
context: Resolve;
|
|
91
|
-
audit: (resolution: DomainAuditInput<Operations>, context: DomainOf<Resolve
|
|
97
|
+
audit: (resolution: DomainAuditInput<Operations>, context: DomainOf<Resolve>, scope: RequestScope | undefined) => Returned;
|
|
92
98
|
operations: (define: SharedEffectFactory<DomainOf<Resolve>, Guard>) => Operations & NoInfer<ValidatedEffectOperations<Operations>>;
|
|
93
99
|
defaults?: {
|
|
94
100
|
guard?: (context: DomainOf<Resolve>) => Guard;
|
|
@@ -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{decodeEffectContract as o}from"./schema.mjs";import{CommandPermissionError as s,executeCommandLifecycle as c}from"../../components/foundation/modules/command/lifecycle.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{decodeEffectContract as o}from"./schema.mjs";import{CommandPermissionError as s,executeCommandLifecycle as c}from"../../components/foundation/modules/command/lifecycle.mjs";import{reportAuditWriteFailure as l,reportFailure as u}from"./failure-audit.mjs";import{auditFolded as d,enterRequestScope as f}from"./scope.mjs";import{snapshotOperations as p}from"../contracts/binding.mjs";import{domainEffectFactory as m}from"./domain.mjs";import{Cause as h,Effect as g,Exit as _}from"effect";const v={succeed:g.succeed,suspend:g.suspend,flatMap:g.flatMap};function y(p){let m=t(()=>p.operations(a())),y=p,b=y.contract?.errors,S=y.mode??`command`,C=(e,t,n)=>g.suspend(()=>{let a=m();if(!Object.prototype.hasOwnProperty.call(a,e))throw Error(`The selected command operation is not configured`);let y=a[e];return g.flatMap(o(y.input,t),t=>{let a=t,m=y.classification??S,C=y.audit,w=p.observability.start({operation:e,classification:m}),T=p.context;return f(e,C!==void 0,(t,f)=>r(()=>T(n)).pipe(g.flatMap(i=>c(v,{operation:e,classification:m,context:i,command:a,permission:y.permission===void 0?void 0:()=>r(()=>{if(!p.checkPermission)throw new s(e);return p.checkPermission(n,{permission:y.permission,operation:e})}).pipe(g.asVoid),prepare:()=>r(()=>y.prepare?.(i,a)).pipe(g.map(e=>e?.kind===`execute`?{kind:`execute`,complete:e.complete?t=>r(()=>e.complete(t)).pipe(g.asVoid):void 0}:e)),decodeReplay:e=>o(y.replayResult??y.result,e),middleware:y.middleware?[e=>x(()=>y.middleware({...e,input:a}))]:[],defaultGuard:e=>r(()=>p.defaults?.guard?.(e)).pipe(g.asVoid),guard:e=>r(()=>y.guard?.(e,a)).pipe(g.asVoid),run:e=>x(()=>y.handler(a,e)),decodeResult:e=>o(y.result,e),audit:e=>!C||S!==`action`&&d(p.nestedAudit,t)?g.succeed(null):r(()=>C({command:a,result:e},i,t?.scope)),writeAudit:i=>{let a=r(()=>p.writeAudit(n,i));return S===`action`?a.pipe(g.catchCause(n=>h.hasInterrupts(n)?g.failCause(n):l(p.auditFailure,{operation:e,classification:m,entered:t}))):a},aggregates:y.aggregates})),g.onExit(n=>g.sync(()=>{_.isSuccess(n)?w.completed():w.failed(i(n.cause))}).pipe(g.andThen(u(p.auditFailure,n,{kind:S,operation:e,classification:m,input:a,contract:b,entered:t,current:f}))))))})});return n({withContext(e){return{exec:(t,n)=>C(t,n,e)}},expose(t,n){let r=m();if(!Object.hasOwn(r,n))throw Error(`The selected command operation is not configured`);return e(t,`mutation`,n,r[n])},exec:C},m)}function b(e){function t(t){let n=()=>{let e=t.contract?m(t.contract.commands??{},!0,t.contract.errors):a();return p(t.operations(e),t.contract,`commands`,t.audit)};return y({...t,...e,operations:n})}return t}function x(e){return r(e)}export{b as bindEffectCommand,y as createEffectCommand};
|
|
2
2
|
//# sourceMappingURL=command.mjs.map
|