cvx-kit 0.2.0 → 2.0.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +556 -99
- package/dist/agent-tools.d.mts +39 -26
- package/dist/agent-tools.mjs +1 -1
- package/dist/agent-tools.mjs.map +1 -1
- package/dist/auth.d.mts +120 -308
- package/dist/auth.mjs +1 -1
- package/dist/auth.mjs.map +1 -1
- package/dist/components/approvals/_generated/api.d.mts +7 -9
- package/dist/components/approvals/_generated/api.mjs.map +1 -1
- package/dist/components/approvals/_generated/component.d.mts +1 -4
- package/dist/components/approvals/_generated/dataModel.d.mts +5 -8
- package/dist/components/approvals/_generated/server.d.mts +12 -15
- package/dist/components/approvals/_generated/server.mjs.map +1 -1
- package/dist/components/approvals/audit.d.mts +8 -9
- package/dist/components/approvals/audit.mjs +1 -1
- package/dist/components/approvals/audit.mjs.map +1 -1
- package/dist/components/approvals/client.d.mts +11 -12
- package/dist/components/approvals/client.mjs +1 -1
- package/dist/components/approvals/client.mjs.map +1 -1
- package/dist/components/approvals/constants.d.mts +30 -31
- package/dist/components/approvals/constants.mjs.map +1 -1
- package/dist/components/approvals/convex.config.d.mts +0 -2
- package/dist/components/approvals/convex.config.mjs.map +1 -1
- package/dist/components/approvals/decisions.d.mts +13 -17
- package/dist/components/approvals/decisions.mjs +1 -1
- package/dist/components/approvals/decisions.mjs.map +1 -1
- package/dist/components/approvals/functions.d.mts +3 -4
- package/dist/components/approvals/functions.mjs +1 -1
- package/dist/components/approvals/functions.mjs.map +1 -1
- package/dist/components/approvals/health.d.mts +2 -3
- package/dist/components/approvals/health.mjs.map +1 -1
- package/dist/components/approvals/requests.d.mts +114 -131
- package/dist/components/approvals/requests.mjs +1 -1
- package/dist/components/approvals/requests.mjs.map +1 -1
- package/dist/components/approvals/schema.d.ts +106 -315
- package/dist/components/approvals/schema.js +1 -1
- package/dist/components/approvals/validators.d.mts +323 -395
- package/dist/components/approvals/validators.mjs +1 -1
- package/dist/components/approvals/validators.mjs.map +1 -1
- package/dist/components/approvals/workflow.d.mts +4 -5
- package/dist/components/approvals/workflow.mjs +1 -1
- package/dist/components/approvals/workflow.mjs.map +1 -1
- package/dist/components/approvals/workflow_steps.d.mts +16 -17
- package/dist/components/approvals/workflow_steps.mjs +1 -1
- package/dist/components/approvals/workflow_steps.mjs.map +1 -1
- package/dist/components/foundation/_generated/api.d.mts +6 -8
- package/dist/components/foundation/_generated/api.mjs.map +1 -1
- package/dist/components/foundation/_generated/component.d.mts +1 -4
- package/dist/components/foundation/_generated/dataModel.d.mts +5 -8
- package/dist/components/foundation/_generated/server.d.mts +12 -15
- package/dist/components/foundation/_generated/server.mjs.map +1 -1
- package/dist/components/foundation/client.d.mts +45 -38
- package/dist/components/foundation/client.mjs +1 -1
- package/dist/components/foundation/client.mjs.map +1 -1
- package/dist/components/foundation/convex.config.d.mts +0 -2
- package/dist/components/foundation/convex.config.mjs.map +1 -1
- package/dist/components/foundation/functions.d.mts +2 -3
- package/dist/components/foundation/functions.mjs.map +1 -1
- package/dist/components/foundation/modules/command/command.d.mts +65 -17
- package/dist/components/foundation/modules/command/command.mjs +1 -1
- package/dist/components/foundation/modules/command/command.mjs.map +1 -1
- package/dist/components/foundation/modules/command/lifecycle.d.mts +78 -0
- package/dist/components/foundation/modules/command/lifecycle.mjs +2 -0
- package/dist/components/foundation/modules/command/lifecycle.mjs.map +1 -0
- package/dist/components/foundation/modules/observability/observability.d.mts +13 -6
- package/dist/components/foundation/modules/observability/observability.mjs +1 -1
- package/dist/components/foundation/modules/observability/observability.mjs.map +1 -1
- package/dist/components/foundation/modules/query/query.d.mts +11 -12
- package/dist/components/foundation/modules/query/query.mjs +1 -1
- package/dist/components/foundation/modules/query/query.mjs.map +1 -1
- package/dist/components/foundation/operation.d.mts +72 -0
- package/dist/components/foundation/operation.mjs +2 -0
- package/dist/components/foundation/operation.mjs.map +1 -0
- package/dist/components/foundation/result.d.mts +7 -8
- package/dist/components/foundation/result.mjs.map +1 -1
- package/dist/components/foundation/schema.d.ts +0 -2
- package/dist/components/foundation/telemetry.d.mts +2 -3
- package/dist/components/foundation/telemetry.mjs +1 -1
- package/dist/components/foundation/telemetry.mjs.map +1 -1
- package/dist/contracts.d.mts +5 -0
- package/dist/contracts.mjs +1 -0
- package/dist/crud.d.mts +185 -27
- package/dist/crud.mjs +1 -1
- package/dist/crud.mjs.map +1 -1
- package/dist/effect.d.mts +16 -0
- package/dist/effect.mjs +1 -0
- package/dist/errors.d.mts +6 -6
- package/dist/errors.mjs +1 -1
- package/dist/errors.mjs.map +1 -1
- package/dist/filters.d.mts +4 -0
- package/dist/filters.mjs +1 -0
- package/dist/idempotency.d.mts +2 -0
- package/dist/idempotency.mjs +1 -0
- package/dist/index.d.mts +14 -7
- package/dist/index.mjs +1 -1
- package/dist/json-schema.d.mts +40 -0
- package/dist/json-schema.mjs +2 -0
- package/dist/json-schema.mjs.map +1 -0
- package/dist/k/compile.d.mts +17 -0
- package/dist/k/compile.mjs +2 -0
- package/dist/k/compile.mjs.map +1 -0
- package/dist/k/dates.d.mts +23 -0
- package/dist/k/dates.mjs +2 -0
- package/dist/k/dates.mjs.map +1 -0
- package/dist/k/formats.d.mts +24 -0
- package/dist/k/formats.mjs +2 -0
- package/dist/k/formats.mjs.map +1 -0
- package/dist/k/index.d.mts +32 -0
- package/dist/k/index.mjs +2 -0
- package/dist/k/index.mjs.map +1 -0
- package/dist/k/issues.d.mts +31 -0
- package/dist/k/issues.mjs +2 -0
- package/dist/k/issues.mjs.map +1 -0
- package/dist/k/kinds.d.mts +81 -0
- package/dist/k/kinds.mjs +2 -0
- package/dist/k/kinds.mjs.map +1 -0
- package/dist/k/object.d.mts +43 -0
- package/dist/k/object.mjs +2 -0
- package/dist/k/object.mjs.map +1 -0
- package/dist/k/parse.d.mts +29 -0
- package/dist/k/parse.mjs +2 -0
- package/dist/k/parse.mjs.map +1 -0
- package/dist/k/schema.d.mts +100 -0
- package/dist/k/schema.mjs +2 -0
- package/dist/k/schema.mjs.map +1 -0
- package/dist/k/standard.d.mts +8 -0
- package/dist/k/standard.mjs +2 -0
- package/dist/k/standard.mjs.map +1 -0
- package/dist/k/types.d.mts +64 -0
- package/dist/k/types.mjs +1 -0
- package/dist/k.d.mts +8 -0
- package/dist/k.mjs +1 -0
- package/dist/middleware.d.mts +8 -11
- package/dist/middleware.mjs +1 -1
- package/dist/middleware.mjs.map +1 -1
- package/dist/modules/contracts/binding.d.mts +23 -0
- package/dist/modules/contracts/binding.mjs +2 -0
- package/dist/modules/contracts/binding.mjs.map +1 -0
- package/dist/modules/contracts/contract.d.mts +67 -0
- package/dist/modules/contracts/contract.mjs +2 -0
- package/dist/modules/contracts/contract.mjs.map +1 -0
- package/dist/modules/contracts/convex.d.mts +18 -0
- package/dist/modules/contracts/convex.mjs +2 -0
- package/dist/modules/contracts/convex.mjs.map +1 -0
- package/dist/modules/contracts/domain.d.mts +62 -0
- package/dist/modules/contracts/domain.mjs +2 -0
- package/dist/modules/contracts/domain.mjs.map +1 -0
- package/dist/modules/contracts/errors.d.mts +737 -0
- package/dist/modules/contracts/errors.mjs +2 -0
- package/dist/modules/contracts/errors.mjs.map +1 -0
- package/dist/modules/contracts/exposure.d.mts +103 -0
- package/dist/modules/contracts/exposure.mjs +2 -0
- package/dist/modules/contracts/exposure.mjs.map +1 -0
- package/dist/modules/contracts/idempotency.d.mts +85 -0
- package/dist/modules/contracts/idempotency.mjs +2 -0
- package/dist/modules/contracts/idempotency.mjs.map +1 -0
- package/dist/modules/contracts/lazy.d.mts +6 -0
- package/dist/modules/contracts/lazy.mjs +2 -0
- package/dist/modules/contracts/lazy.mjs.map +1 -0
- package/dist/modules/contracts/standard.d.mts +17 -0
- package/dist/modules/contracts/standard.mjs +2 -0
- package/dist/modules/contracts/standard.mjs.map +1 -0
- package/dist/modules/contracts/workflow.d.mts +165 -0
- package/dist/modules/contracts/workflow.mjs +2 -0
- package/dist/modules/contracts/workflow.mjs.map +1 -0
- package/dist/modules/effect/action.d.mts +63 -0
- package/dist/modules/effect/action.mjs +2 -0
- package/dist/modules/effect/action.mjs.map +1 -0
- package/dist/modules/effect/agent-tools.d.mts +2 -0
- package/dist/modules/effect/agent-tools.mjs +1 -0
- package/dist/modules/effect/api-runtime.d.mts +36 -0
- package/dist/modules/effect/api-runtime.mjs +2 -0
- package/dist/modules/effect/api-runtime.mjs.map +1 -0
- package/dist/modules/effect/api.d.mts +46 -0
- package/dist/modules/effect/api.mjs +2 -0
- package/dist/modules/effect/api.mjs.map +1 -0
- package/dist/modules/effect/auth.d.mts +46 -0
- package/dist/modules/effect/auth.mjs +2 -0
- package/dist/modules/effect/auth.mjs.map +1 -0
- package/dist/modules/effect/client.d.mts +15 -0
- package/dist/modules/effect/client.mjs +1 -0
- package/dist/modules/effect/command.d.mts +108 -0
- package/dist/modules/effect/command.mjs +2 -0
- package/dist/modules/effect/command.mjs.map +1 -0
- package/dist/modules/effect/crud.d.mts +885 -0
- package/dist/modules/effect/crud.mjs +2 -0
- package/dist/modules/effect/crud.mjs.map +1 -0
- package/dist/modules/effect/domain.d.mts +82 -0
- package/dist/modules/effect/domain.mjs +2 -0
- package/dist/modules/effect/domain.mjs.map +1 -0
- package/dist/modules/effect/errors.d.mts +13 -0
- package/dist/modules/effect/errors.mjs +2 -0
- package/dist/modules/effect/errors.mjs.map +1 -0
- 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 +21 -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 +23 -0
- package/dist/modules/effect/foundation.mjs +2 -0
- package/dist/modules/effect/foundation.mjs.map +1 -0
- package/dist/modules/effect/idempotency.d.mts +29 -0
- package/dist/modules/effect/idempotency.mjs +2 -0
- package/dist/modules/effect/idempotency.mjs.map +1 -0
- package/dist/modules/effect/input.d.mts +10 -0
- package/dist/modules/effect/input.mjs +2 -0
- package/dist/modules/effect/input.mjs.map +1 -0
- package/dist/modules/effect/normalize.d.mts +7 -0
- package/dist/modules/effect/normalize.mjs +2 -0
- package/dist/modules/effect/normalize.mjs.map +1 -0
- package/dist/modules/effect/operation.d.mts +148 -0
- package/dist/modules/effect/operation.mjs +2 -0
- package/dist/modules/effect/operation.mjs.map +1 -0
- package/dist/modules/effect/query.d.mts +90 -0
- package/dist/modules/effect/query.mjs +2 -0
- package/dist/modules/effect/query.mjs.map +1 -0
- package/dist/modules/effect/schema.d.mts +30 -0
- package/dist/modules/effect/schema.mjs +2 -0
- package/dist/modules/effect/schema.mjs.map +1 -0
- package/dist/modules/effect/scope.d.mts +25 -0
- package/dist/modules/effect/scope.mjs +2 -0
- package/dist/modules/effect/scope.mjs.map +1 -0
- package/dist/modules/effect/workflow.d.mts +75 -0
- package/dist/modules/effect/workflow.mjs +2 -0
- package/dist/modules/effect/workflow.mjs.map +1 -0
- package/dist/modules/foundation/foundation.d.mts +108 -0
- package/dist/modules/foundation/foundation.mjs +2 -0
- package/dist/modules/foundation/foundation.mjs.map +1 -0
- package/dist/modules/foundation/operation.d.mts +139 -0
- package/dist/modules/foundation/operation.mjs +2 -0
- package/dist/modules/foundation/operation.mjs.map +1 -0
- package/dist/namespace.d.mts +104 -0
- package/dist/namespace.mjs +2 -0
- package/dist/namespace.mjs.map +1 -0
- package/dist/oxlint/architecture.d.mts +23 -0
- package/dist/oxlint/architecture.mjs +2 -0
- package/dist/oxlint/architecture.mjs.map +1 -0
- package/dist/oxlint/ast.d.mts +51 -0
- package/dist/oxlint/ast.mjs +2 -0
- package/dist/oxlint/ast.mjs.map +1 -0
- package/dist/oxlint/components.d.mts +4 -0
- package/dist/oxlint/components.mjs +2 -0
- package/dist/oxlint/components.mjs.map +1 -0
- package/dist/oxlint/ownership.d.mts +59 -0
- package/dist/oxlint/ownership.mjs +2 -0
- package/dist/oxlint/ownership.mjs.map +1 -0
- package/dist/oxlint/reserved-files.d.mts +4 -0
- package/dist/oxlint/reserved-files.mjs +2 -0
- package/dist/oxlint/reserved-files.mjs.map +1 -0
- package/dist/oxlint.d.mts +9 -0
- package/dist/oxlint.mjs +2 -0
- package/dist/oxlint.mjs.map +1 -0
- package/dist/querying/cursors.d.mts +94 -0
- package/dist/querying/cursors.mjs +2 -0
- package/dist/querying/cursors.mjs.map +1 -0
- package/dist/querying/execution.d.mts +40 -0
- package/dist/querying/execution.mjs +2 -0
- package/dist/querying/execution.mjs.map +1 -0
- package/dist/querying/failures.d.mts +11 -0
- package/dist/querying/failures.mjs +2 -0
- package/dist/querying/failures.mjs.map +1 -0
- package/dist/querying/filter-boundary.d.mts +25 -0
- package/dist/querying/filter-boundary.mjs +2 -0
- package/dist/querying/filter-boundary.mjs.map +1 -0
- package/dist/querying/filters.d.mts +180 -0
- package/dist/querying/filters.mjs +2 -0
- package/dist/querying/filters.mjs.map +1 -0
- package/dist/querying/planner.d.mts +61 -0
- package/dist/querying/planner.mjs +2 -0
- package/dist/querying/planner.mjs.map +1 -0
- package/dist/querying/relationships.d.mts +58 -0
- package/dist/querying/relationships.mjs +2 -0
- package/dist/querying/relationships.mjs.map +1 -0
- package/dist/querying/search.d.mts +69 -0
- package/dist/querying/search.mjs +2 -0
- package/dist/querying/search.mjs.map +1 -0
- package/dist/querying/security.d.mts +123 -0
- package/dist/querying/security.mjs +2 -0
- package/dist/querying/security.mjs.map +1 -0
- package/dist/querying/shared/ast.d.mts +26 -0
- package/dist/querying/shared/ast.mjs +2 -0
- package/dist/querying/shared/ast.mjs.map +1 -0
- package/dist/querying/shared/contract.d.mts +98 -0
- package/dist/querying/shared/contract.mjs +2 -0
- package/dist/querying/shared/contract.mjs.map +1 -0
- package/dist/querying/shared/evaluate.d.mts +5 -0
- package/dist/querying/shared/evaluate.mjs +2 -0
- package/dist/querying/shared/evaluate.mjs.map +1 -0
- package/dist/querying/shared/filters.d.mts +65 -0
- package/dist/querying/shared/filters.mjs +2 -0
- package/dist/querying/shared/filters.mjs.map +1 -0
- package/dist/querying/shared/native-json.d.mts +7 -0
- package/dist/querying/shared/native-json.mjs +2 -0
- package/dist/querying/shared/native-json.mjs.map +1 -0
- package/dist/querying/shared/page.d.mts +20 -0
- package/dist/querying/shared/page.mjs +2 -0
- package/dist/querying/shared/page.mjs.map +1 -0
- package/dist/querying.d.mts +82 -0
- package/dist/querying.mjs +2 -0
- package/dist/querying.mjs.map +1 -0
- package/dist/react/failures.d.mts +24 -0
- package/dist/react/failures.mjs +2 -0
- package/dist/react/failures.mjs.map +1 -0
- package/dist/react/optimistic.d.mts +46 -0
- package/dist/react/optimistic.mjs +2 -0
- package/dist/react/optimistic.mjs.map +1 -0
- package/dist/react/pagination-state.d.mts +39 -0
- package/dist/react/pagination-state.mjs +2 -0
- package/dist/react/pagination-state.mjs.map +1 -0
- package/dist/react/use-command.d.mts +22 -0
- package/dist/react/use-command.mjs +2 -0
- package/dist/react/use-command.mjs.map +1 -0
- package/dist/react/use-paginated-list.d.mts +34 -0
- package/dist/react/use-paginated-list.mjs +2 -0
- package/dist/react/use-paginated-list.mjs.map +1 -0
- package/dist/react.d.mts +6 -0
- package/dist/react.mjs +1 -0
- package/dist/registration.d.mts +65 -0
- package/dist/registration.mjs +2 -0
- package/dist/registration.mjs.map +1 -0
- package/dist/relations-public.d.mts +2 -0
- package/dist/relations-public.mjs +1 -0
- package/dist/relations.d.mts +274 -0
- package/dist/relations.mjs +2 -0
- package/dist/relations.mjs.map +1 -0
- package/dist/state-machine.d.mts +1 -4
- package/dist/state-machine.mjs.map +1 -1
- package/dist/table.d.mts +222 -0
- package/dist/table.mjs +2 -0
- package/dist/table.mjs.map +1 -0
- package/dist/tenancy.d.mts +6 -8
- package/dist/tenancy.mjs +1 -1
- package/dist/tenancy.mjs.map +1 -1
- package/dist/triggers.d.mts +12 -10
- package/dist/triggers.mjs +1 -1
- package/dist/triggers.mjs.map +1 -1
- package/dist/webhooks.d.mts +22 -112
- package/dist/webhooks.mjs +1 -1
- package/dist/webhooks.mjs.map +1 -1
- package/dist/workflow.d.mts +2 -0
- package/dist/workflow.mjs +1 -0
- package/dist/zod.d.mts +30 -0
- package/dist/zod.mjs +2 -0
- package/dist/zod.mjs.map +1 -0
- package/package.json +145 -33
- package/src/test.ts +9 -17
- package/CHANGELOG.md +0 -145
- package/ROADMAP.md +0 -126
- package/dist/zod-table.d.mts +0 -175
- package/dist/zod-table.mjs +0 -2
- package/dist/zod-table.mjs.map +0 -1
- package/docs/agent-tools.md +0 -41
- package/docs/approvals.md +0 -200
- package/docs/architecture.md +0 -124
- package/docs/auth.md +0 -218
- package/docs/commands.md +0 -278
- package/docs/conventions.md +0 -291
- package/docs/crud.md +0 -62
- package/docs/llms.md +0 -220
- package/docs/maintainability.md +0 -124
- package/docs/migration.md +0 -351
- package/docs/plans/2026-08-14-001-feat-v0.1.0-feature-set-plan.md +0 -461
- package/docs/plans/2026-08-21-0930-feat-resolve-organization-hook-plan.md +0 -178
- package/docs/tenancy.md +0 -179
- package/docs/triggers.md +0 -75
- package/docs/upgrading.md +0 -175
- package/docs/webhooks.md +0 -58
- package/docs/zod-table.md +0 -173
- package/scripts/convex-config-bridge.mjs +0 -55
- package/scripts/extract-changelog.mjs +0 -29
- package/scripts/smoke-packed-components.mjs +0 -374
package/dist/crud.d.mts
CHANGED
|
@@ -1,27 +1,37 @@
|
|
|
1
|
+
import { KFields, KType } from "./k/types.mjs";
|
|
2
|
+
import { KOptional } from "./k/schema.mjs";
|
|
3
|
+
import { KId, KLiteral } from "./k/kinds.mjs";
|
|
4
|
+
import { KObject } from "./k/object.mjs";
|
|
5
|
+
import { k } from "./k/index.mjs";
|
|
6
|
+
import "./k.mjs";
|
|
7
|
+
import { Parseable, SchemaInput, SchemaOutput } from "./components/foundation/modules/command/command.mjs";
|
|
8
|
+
import { AnyCommandMiddleware, ApplicationCommand, AuditedOperation, CommandConstructor } from "./components/foundation/client.mjs";
|
|
1
9
|
import { ErrorFactory } from "./errors.mjs";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
//#region src/crud.d.ts
|
|
10
|
+
import { Value } from "convex/values";
|
|
11
|
+
import { GenericDataModel, GenericMutationCtx } from "convex/server";
|
|
5
12
|
/**
|
|
6
|
-
* The
|
|
7
|
-
*
|
|
13
|
+
* The table surface the factory consumes — structural, so any kTable / createTable / tenantTable
|
|
14
|
+
* boundary satisfies it.
|
|
8
15
|
*/
|
|
9
16
|
type CrudTable = {
|
|
10
|
-
tableName: string;
|
|
11
|
-
commandInput:
|
|
12
|
-
storage:
|
|
17
|
+
readonly tableName: string;
|
|
18
|
+
readonly commandInput: KType & Parseable<CommandRow>;
|
|
19
|
+
readonly storage: KType & {
|
|
20
|
+
readonly shape: KFields;
|
|
21
|
+
};
|
|
22
|
+
};
|
|
23
|
+
/** A parsed command: the commandFields' values. */
|
|
24
|
+
type CommandRow = {
|
|
25
|
+
readonly [field: string]: Value | undefined;
|
|
13
26
|
};
|
|
14
27
|
type CrudContext = {
|
|
15
|
-
db:
|
|
16
|
-
insert: (table: never, value: never) => Promise<unknown>;
|
|
17
|
-
patch: (id: never, value: never) => Promise<unknown>;
|
|
18
|
-
};
|
|
28
|
+
db: Pick<GenericMutationCtx<GenericDataModel>['db'], 'insert' | 'patch'>;
|
|
19
29
|
};
|
|
20
30
|
type MaybePromise<Value> = Value | Promise<Value>;
|
|
21
|
-
type CrudConfig<Context extends CrudContext> = {
|
|
31
|
+
export type CrudConfig<Context extends CrudContext, Table extends CrudTable = CrudTable> = {
|
|
22
32
|
/** The Foundation-bound Command class (destructured from the facade). */
|
|
23
33
|
Command: CommandConstructor;
|
|
24
|
-
table:
|
|
34
|
+
table: Table;
|
|
25
35
|
/** Audit aggregate type; enforced by the aggregates allowlist. */
|
|
26
36
|
aggregateType: string;
|
|
27
37
|
/** Observability/audit classification. Default 'business'. */
|
|
@@ -33,7 +43,7 @@ type CrudConfig<Context extends CrudContext> = {
|
|
|
33
43
|
* REQUIRED when the table is a tenantTable — forgetting it would insert
|
|
34
44
|
* untenanted rows; the factory fails fast at construction instead.
|
|
35
45
|
*/
|
|
36
|
-
enrich?: (context: Context, command:
|
|
46
|
+
enrich?: (context: Context, command: SchemaOutput<Table['commandInput']>) => MaybePromise<Partial<k.input<Table['storage']>>>;
|
|
37
47
|
/** Per-operation preconditions; run before the handlers. */
|
|
38
48
|
guards?: {
|
|
39
49
|
create?: (context: Context, command: never) => MaybePromise<void>;
|
|
@@ -45,7 +55,7 @@ type CrudConfig<Context extends CrudContext> = {
|
|
|
45
55
|
errors?: ErrorFactory;
|
|
46
56
|
};
|
|
47
57
|
/**
|
|
48
|
-
* Generates the standard create/update/archive operations from one
|
|
58
|
+
* Generates the standard create/update/archive operations from one kTable
|
|
49
59
|
* declaration, fully inside the audited command pipeline: strict command
|
|
50
60
|
* inputs from `commandFields`, mandatory audit with the declared aggregate
|
|
51
61
|
* type, soft delete only (archive sets `archivedAt` — no hard-delete
|
|
@@ -55,25 +65,173 @@ type CrudConfig<Context extends CrudContext> = {
|
|
|
55
65
|
* used — it bypasses the command pipeline (no audits, no guards, and hard
|
|
56
66
|
* deletes). See docs/crud.md.
|
|
57
67
|
*/
|
|
58
|
-
type CrudCommands<Context extends CrudContext> =
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
68
|
+
export type CrudCommands<Context extends CrudContext, Table extends CrudTable = CrudTable> = ReturnType<typeof createCrudCommands<Context, Table>>;
|
|
69
|
+
export declare function createCrudCommands<Context extends CrudContext, Table extends CrudTable = CrudTable>(config: CrudConfig<Context, Table>): {
|
|
70
|
+
commands: ApplicationCommand<Context, NamedOperation<`${string}.create`, {
|
|
71
|
+
command: Table["commandInput"];
|
|
72
|
+
result: KObject<{
|
|
73
|
+
id: KId<string>;
|
|
74
|
+
}>;
|
|
75
|
+
classification: string;
|
|
76
|
+
aggregates: string[];
|
|
77
|
+
middleware: readonly AnyCommandMiddleware[] | undefined;
|
|
78
|
+
guard: ((context: Context, command: never) => MaybePromise<void>) | undefined;
|
|
79
|
+
audit: (resolution: {
|
|
80
|
+
result: k.infer<KObject<{
|
|
81
|
+
id: KId<string>;
|
|
82
|
+
}>>;
|
|
83
|
+
}, context: Context) => {
|
|
84
|
+
operation: `${string}.create`;
|
|
85
|
+
actorId: string;
|
|
86
|
+
aggregate: {
|
|
87
|
+
type: string;
|
|
88
|
+
id: import("convex/values").GenericId<string>;
|
|
89
|
+
};
|
|
90
|
+
};
|
|
91
|
+
}> & NamedOperation<`${string}.update`, {
|
|
92
|
+
command: KObject<{
|
|
93
|
+
id: KId<string>;
|
|
94
|
+
data: KObject<{
|
|
95
|
+
readonly [x: string]: KOptional<KType>;
|
|
96
|
+
}>;
|
|
97
|
+
}>;
|
|
98
|
+
result: KObject<{
|
|
99
|
+
ok: KLiteral<true>;
|
|
100
|
+
}>;
|
|
101
|
+
classification: string;
|
|
102
|
+
aggregates: string[];
|
|
103
|
+
middleware: readonly AnyCommandMiddleware[] | undefined;
|
|
104
|
+
guard: ((context: Context, command: never) => MaybePromise<void>) | undefined;
|
|
105
|
+
audit: (resolution: {
|
|
106
|
+
command: k.infer<KObject<{
|
|
107
|
+
id: KId<string>;
|
|
108
|
+
data: KObject<{
|
|
109
|
+
readonly [x: string]: KOptional<KType>;
|
|
110
|
+
}>;
|
|
111
|
+
}>>;
|
|
112
|
+
}, context: Context) => {
|
|
113
|
+
operation: `${string}.update`;
|
|
114
|
+
actorId: string;
|
|
115
|
+
aggregate: {
|
|
116
|
+
type: string;
|
|
117
|
+
id: import("convex/values").GenericId<string>;
|
|
118
|
+
};
|
|
119
|
+
};
|
|
120
|
+
}> & NamedOperation<`${string}.archive`, {
|
|
121
|
+
command: KObject<{
|
|
122
|
+
id: KId<string>;
|
|
123
|
+
}>;
|
|
124
|
+
result: KObject<{
|
|
125
|
+
ok: KLiteral<true>;
|
|
126
|
+
}>;
|
|
127
|
+
classification: string;
|
|
128
|
+
aggregates: string[];
|
|
129
|
+
middleware: readonly AnyCommandMiddleware[] | undefined;
|
|
130
|
+
guard: ((context: Context, command: never) => MaybePromise<void>) | undefined;
|
|
131
|
+
audit: (resolution: {
|
|
132
|
+
command: k.infer<KObject<{
|
|
133
|
+
id: KId<string>;
|
|
134
|
+
}>>;
|
|
135
|
+
}, context: Context) => {
|
|
136
|
+
operation: `${string}.archive`;
|
|
137
|
+
actorId: string;
|
|
138
|
+
aggregate: {
|
|
139
|
+
type: string;
|
|
140
|
+
id: import("convex/values").GenericId<string>;
|
|
141
|
+
};
|
|
142
|
+
};
|
|
143
|
+
}>>;
|
|
144
|
+
operations: NamedOperation<`${string}.create`, {
|
|
145
|
+
command: Table["commandInput"];
|
|
146
|
+
result: KObject<{
|
|
147
|
+
id: KId<string>;
|
|
148
|
+
}>;
|
|
149
|
+
classification: string;
|
|
150
|
+
aggregates: string[];
|
|
151
|
+
middleware: readonly AnyCommandMiddleware[] | undefined;
|
|
152
|
+
guard: ((context: Context, command: never) => MaybePromise<void>) | undefined;
|
|
153
|
+
audit: (resolution: {
|
|
154
|
+
result: k.infer<KObject<{
|
|
155
|
+
id: KId<string>;
|
|
156
|
+
}>>;
|
|
157
|
+
}, context: Context) => {
|
|
158
|
+
operation: `${string}.create`;
|
|
159
|
+
actorId: string;
|
|
160
|
+
aggregate: {
|
|
161
|
+
type: string;
|
|
162
|
+
id: import("convex/values").GenericId<string>;
|
|
163
|
+
};
|
|
164
|
+
};
|
|
165
|
+
}> & NamedOperation<`${string}.update`, {
|
|
166
|
+
command: KObject<{
|
|
167
|
+
id: KId<string>;
|
|
168
|
+
data: KObject<{
|
|
169
|
+
readonly [x: string]: KOptional<KType>;
|
|
170
|
+
}>;
|
|
171
|
+
}>;
|
|
172
|
+
result: KObject<{
|
|
173
|
+
ok: KLiteral<true>;
|
|
174
|
+
}>;
|
|
175
|
+
classification: string;
|
|
176
|
+
aggregates: string[];
|
|
177
|
+
middleware: readonly AnyCommandMiddleware[] | undefined;
|
|
178
|
+
guard: ((context: Context, command: never) => MaybePromise<void>) | undefined;
|
|
179
|
+
audit: (resolution: {
|
|
180
|
+
command: k.infer<KObject<{
|
|
181
|
+
id: KId<string>;
|
|
182
|
+
data: KObject<{
|
|
183
|
+
readonly [x: string]: KOptional<KType>;
|
|
184
|
+
}>;
|
|
185
|
+
}>>;
|
|
186
|
+
}, context: Context) => {
|
|
187
|
+
operation: `${string}.update`;
|
|
188
|
+
actorId: string;
|
|
189
|
+
aggregate: {
|
|
190
|
+
type: string;
|
|
191
|
+
id: import("convex/values").GenericId<string>;
|
|
192
|
+
};
|
|
193
|
+
};
|
|
194
|
+
}> & NamedOperation<`${string}.archive`, {
|
|
195
|
+
command: KObject<{
|
|
196
|
+
id: KId<string>;
|
|
197
|
+
}>;
|
|
198
|
+
result: KObject<{
|
|
199
|
+
ok: KLiteral<true>;
|
|
200
|
+
}>;
|
|
201
|
+
classification: string;
|
|
202
|
+
aggregates: string[];
|
|
203
|
+
middleware: readonly AnyCommandMiddleware[] | undefined;
|
|
204
|
+
guard: ((context: Context, command: never) => MaybePromise<void>) | undefined;
|
|
205
|
+
audit: (resolution: {
|
|
206
|
+
command: k.infer<KObject<{
|
|
207
|
+
id: KId<string>;
|
|
208
|
+
}>>;
|
|
209
|
+
}, context: Context) => {
|
|
210
|
+
operation: `${string}.archive`;
|
|
211
|
+
actorId: string;
|
|
212
|
+
aggregate: {
|
|
213
|
+
type: string;
|
|
214
|
+
id: import("convex/values").GenericId<string>;
|
|
215
|
+
};
|
|
216
|
+
};
|
|
217
|
+
}>;
|
|
218
|
+
executeCreate: (context: Context, command: SchemaInput<Table["commandInput"]>) => Promise<{
|
|
219
|
+
id: import("convex/values").GenericId<string>;
|
|
63
220
|
}>;
|
|
64
221
|
executeUpdate: (context: Context, command: {
|
|
65
|
-
|
|
66
|
-
|
|
222
|
+
data: {
|
|
223
|
+
[x: string]: any;
|
|
224
|
+
};
|
|
225
|
+
id: import("convex/values").GenericId<string>;
|
|
67
226
|
}) => Promise<{
|
|
68
227
|
ok: true;
|
|
69
228
|
}>;
|
|
70
229
|
executeArchive: (context: Context, command: {
|
|
71
|
-
id: string
|
|
230
|
+
id: import("convex/values").GenericId<string>;
|
|
72
231
|
}) => Promise<{
|
|
73
232
|
ok: true;
|
|
74
233
|
}>;
|
|
75
234
|
};
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
export { CrudCommands, CrudConfig, createCrudCommands };
|
|
235
|
+
type NamedOperation<Name extends string, Definition extends AuditedOperation> = { [Key in Name]: Definition; };
|
|
236
|
+
export {};
|
|
79
237
|
//# sourceMappingURL=crud.d.mts.map
|
package/dist/crud.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{defaultErrors as e}from"./errors.mjs";import{
|
|
1
|
+
import{defaultErrors as e}from"./errors.mjs";import{k as t}from"./k/index.mjs";function n(n){let a=n.errors??e,o=n.table.tableName,s=n.classification??`business`;if(`tenant`in n.table.storage.shape&&!n.enrich)return a.throw({code:`CRUD_ENRICH_REQUIRED`,message:`Table "${o}" is a tenantTable: createCrudCommands requires an enrich callback that stamps ctx.tenant`});let c=n.table.commandInput,l=t.id(o),u=t.object({id:l}),d=t.object({ok:t.literal(!0)}),f=t.object({id:l,data:r(c).partial()}),p=t.object({id:l}),m=`${o}.create`,h=`${o}.update`,g=`${o}.archive`,_=Object.assign({},i(m,{command:c,result:u,classification:s,aggregates:[n.aggregateType],middleware:n.middleware,guard:n.guards?.create,audit:(e,t)=>({operation:m,actorId:n.actor(t),aggregate:{type:n.aggregateType,id:e.result.id}})}),i(h,{command:f,result:d,classification:s,aggregates:[n.aggregateType],middleware:n.middleware,guard:n.guards?.update,audit:(e,t)=>({operation:h,actorId:n.actor(t),aggregate:{type:n.aggregateType,id:e.command.id}})}),i(g,{command:p,result:d,classification:s,aggregates:[n.aggregateType],middleware:n.middleware,guard:n.guards?.archive,audit:(e,t)=>({operation:g,actorId:n.actor(t),aggregate:{type:n.aggregateType,id:e.command.id}})})),v=new n.Command(_);return{commands:v,operations:_,executeCreate:v.exec({operation:m,handler:async(e,t)=>{let r=n.enrich?await n.enrich(e,t):{},i=t,a=r,s={};for(let[e,t]of Object.entries({...i,...a}))t!==void 0&&(s[e]=t);return{id:await e.db.insert(o,s)}}}),executeUpdate:v.exec({operation:h,handler:async(e,t)=>(await e.db.patch(t.id,t.data),{ok:!0})}),executeArchive:v.exec({operation:g,handler:async(e,t)=>(await e.db.patch(t.id,{archivedAt:Date.now()}),{ok:!0})})}}function r(e){return e}function i(e,t){return{[e]:t}}export{n as createCrudCommands};
|
|
2
2
|
//# sourceMappingURL=crud.mjs.map
|
package/dist/crud.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"crud.mjs","names":[],"sources":["../src/crud.ts"],"sourcesContent":["import { zid } from 'convex-helpers/server/zod4'\nimport { z } from 'zod'\nimport type {\n\tAnyCommandMiddleware,\n\tApplicationCommand,\n\tAuditedRegistry,\n\tCommandConstructor,\n} from './components/foundation/client'\nimport { defaultErrors, type ErrorFactory } from './errors'\n\n/**\n * The zodTable surface the factory consumes — structural, so any zodTable /\n * tenantTable return satisfies it.\n */\ntype CrudTable = {\n\ttableName: string\n\t// biome-ignore format: structural zod surface\n\tcommandInput: z.ZodObject<Record<string, z.ZodType>>\n\tstorage: z.ZodObject<Record<string, z.ZodType>>\n}\n\ntype CrudContext = {\n\tdb: {\n\t\tinsert: (table: never, value: never) => Promise<unknown>\n\t\tpatch: (id: never, value: never) => Promise<unknown>\n\t}\n}\n\ntype MaybePromise<Value> = Value | Promise<Value>\n\nexport type CrudConfig<Context extends CrudContext> = {\n\t/** The Foundation-bound Command class (destructured from the facade). */\n\tCommand: CommandConstructor\n\ttable: CrudTable\n\t/** Audit aggregate type; enforced by the aggregates allowlist. */\n\taggregateType: string\n\t/** Observability/audit classification. Default 'business'. */\n\tclassification?: string\n\t/** Derives the audited actor id from the ctx (usually ctx.actor.userId). */\n\tactor: (context: Context) => string\n\t/**\n\t * Stamps server-owned fields onto creates (tenant, denormalized ids...).\n\t * REQUIRED when the table is a tenantTable — forgetting it would insert\n\t * untenanted rows; the factory fails fast at construction instead.\n\t */\n\tenrich?: (\n\t\tcontext: Context,\n\t\tcommand: Record<string, unknown>,\n\t) => Record<string, unknown> | Promise<Record<string, unknown>>\n\t/** Per-operation preconditions; run before the handlers. */\n\tguards?: {\n\t\tcreate?: (context: Context, command: never) => MaybePromise<void>\n\t\tupdate?: (context: Context, command: never) => MaybePromise<void>\n\t\tarchive?: (context: Context, command: never) => MaybePromise<void>\n\t}\n\t/** Per-operation middleware applied to all three generated operations. */\n\tmiddleware?: readonly AnyCommandMiddleware[]\n\terrors?: ErrorFactory\n}\n\n/**\n * Generates the standard create/update/archive operations from one zodTable\n * declaration, fully inside the audited command pipeline: strict command\n * inputs from `commandFields`, mandatory audit with the declared aggregate\n * type, soft delete only (archive sets `archivedAt` — no hard-delete\n * operation is generated, per kit doctrine).\n *\n * convex-helpers ships a same-named `crud` helper; it was deliberately not\n * used — it bypasses the command pipeline (no audits, no guards, and hard\n * deletes). See docs/crud.md.\n */\nexport type CrudCommands<Context extends CrudContext> = {\n\tcommands: ApplicationCommand<Context, AuditedRegistry>\n\toperations: AuditedRegistry\n\texecuteCreate: (\n\t\tcontext: Context,\n\t\tcommand: Record<string, unknown>,\n\t) => Promise<{ id: string }>\n\texecuteUpdate: (\n\t\tcontext: Context,\n\t\tcommand: { id: string; data: Record<string, unknown> },\n\t) => Promise<{ ok: true }>\n\texecuteArchive: (\n\t\tcontext: Context,\n\t\tcommand: { id: string },\n\t) => Promise<{ ok: true }>\n}\n\nexport function createCrudCommands<Context extends CrudContext>(\n\tconfig: CrudConfig<Context>,\n): CrudCommands<Context> {\n\tconst errors = config.errors ?? defaultErrors\n\tconst name = config.table.tableName\n\tconst classification = config.classification ?? 'business'\n\tconst isTenantTable = 'tenant' in config.table.storage.shape\n\tif (isTenantTable && !config.enrich) {\n\t\treturn errors.throw({\n\t\t\tcode: 'CRUD_ENRICH_REQUIRED',\n\t\t\tmessage: `Table \"${name}\" is a tenantTable: createCrudCommands requires an enrich callback that stamps ctx.tenant`,\n\t\t})\n\t}\n\n\tconst id = zid(name)\n\tconst createResult = z.object({ id }).strict()\n\tconst okResult = z.object({ ok: z.literal(true) }).strict()\n\tconst updateInput = z\n\t\t.object({ id, data: config.table.commandInput.partial().strict() })\n\t\t.strict()\n\tconst archiveInput = z.object({ id }).strict()\n\n\tconst operations = {\n\t\t[`${name}.create`]: {\n\t\t\tcommand: config.table.commandInput,\n\t\t\tresult: createResult,\n\t\t\tclassification,\n\t\t\taggregates: [config.aggregateType],\n\t\t\t...(config.middleware ? { middleware: config.middleware } : {}),\n\t\t\t...(config.guards?.create ? { guard: config.guards.create } : {}),\n\t\t\taudit: (\n\t\t\t\tresolution: { command: unknown; result: { id: string } },\n\t\t\t\tcontext: Context,\n\t\t\t) => ({\n\t\t\t\toperation: `${name}.create`,\n\t\t\t\tactorId: config.actor(context),\n\t\t\t\taggregate: { type: config.aggregateType, id: resolution.result.id },\n\t\t\t}),\n\t\t},\n\t\t[`${name}.update`]: {\n\t\t\tcommand: updateInput,\n\t\t\tresult: okResult,\n\t\t\tclassification,\n\t\t\taggregates: [config.aggregateType],\n\t\t\t...(config.middleware ? { middleware: config.middleware } : {}),\n\t\t\t...(config.guards?.update ? { guard: config.guards.update } : {}),\n\t\t\taudit: (\n\t\t\t\tresolution: { command: { id: string }; result: unknown },\n\t\t\t\tcontext: Context,\n\t\t\t) => ({\n\t\t\t\toperation: `${name}.update`,\n\t\t\t\tactorId: config.actor(context),\n\t\t\t\taggregate: { type: config.aggregateType, id: resolution.command.id },\n\t\t\t}),\n\t\t},\n\t\t[`${name}.archive`]: {\n\t\t\tcommand: archiveInput,\n\t\t\tresult: okResult,\n\t\t\tclassification,\n\t\t\taggregates: [config.aggregateType],\n\t\t\t...(config.middleware ? { middleware: config.middleware } : {}),\n\t\t\t...(config.guards?.archive ? { guard: config.guards.archive } : {}),\n\t\t\taudit: (\n\t\t\t\tresolution: { command: { id: string }; result: unknown },\n\t\t\t\tcontext: Context,\n\t\t\t) => ({\n\t\t\t\toperation: `${name}.archive`,\n\t\t\t\tactorId: config.actor(context),\n\t\t\t\taggregate: { type: config.aggregateType, id: resolution.command.id },\n\t\t\t}),\n\t\t},\n\t} as never\n\n\tconst commands = new config.Command<Context, AuditedRegistry>(operations)\n\n\tconst executeCreate = commands.exec({\n\t\toperation: `${name}.create` as never,\n\t\thandler: (async (context: Context, command: Record<string, unknown>) => {\n\t\t\tconst enrichment = config.enrich\n\t\t\t\t? await config.enrich(context, command)\n\t\t\t\t: {}\n\t\t\tconst inserted = await context.db.insert(\n\t\t\t\tname as never,\n\t\t\t\t{ ...command, ...enrichment } as never,\n\t\t\t)\n\t\t\treturn { id: inserted }\n\t\t}) as never,\n\t})\n\n\tconst executeUpdate = commands.exec({\n\t\toperation: `${name}.update` as never,\n\t\thandler: (async (\n\t\t\tcontext: Context,\n\t\t\tcommand: { id: string; data: Record<string, unknown> },\n\t\t) => {\n\t\t\tawait context.db.patch(command.id as never, command.data as never)\n\t\t\treturn { ok: true }\n\t\t}) as never,\n\t})\n\n\tconst executeArchive = commands.exec({\n\t\toperation: `${name}.archive` as never,\n\t\thandler: (async (context: Context, command: { id: string }) => {\n\t\t\tawait context.db.patch(\n\t\t\t\tcommand.id as never,\n\t\t\t\t{ archivedAt: Date.now() } as never,\n\t\t\t)\n\t\t\treturn { ok: true }\n\t\t}) as never,\n\t})\n\n\treturn {\n\t\tcommands,\n\t\toperations: operations as AuditedRegistry,\n\t\texecuteCreate,\n\t\texecuteUpdate,\n\t\texecuteArchive,\n\t} as unknown as CrudCommands<Context>\n}\n"],"mappings":"sHAwFA,SAAgB,EACf,EACwB,CACxB,IAAM,EAAS,EAAO,QAAU,EAC1B,EAAO,EAAO,MAAM,UACpB,EAAiB,EAAO,gBAAkB,WAEhD,GADsB,WAAY,EAAO,MAAM,QAAQ,OAClC,CAAC,EAAO,OAC5B,OAAO,EAAO,MAAM,CACnB,KAAM,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AI,EAAO,WAAa,CAAE,WAAY,EAAO,UAAW,EAAI,CAAC,EAC7D,GAAI,EAAO,QAAQ,QAAU,CAAE,MAAO,EAAO,OAAO,OAAQ,EAAI,CAAC,EACjE,OACC,EACA,KACK,CACL,UAAW,GAAG,EAAK,UACnB,QAAS,EAAO,MAAM,CAAO,EAC7B,UAAW,CAAE,KAAM,EAAO,cAAe,GAAI,EAAW,QAAQ,EAAG,CACpE,EACD,CACD,EAEM,EAAW,IAAI,EAAO,QAAkC,CAAU,EAsCxE,MAAO,CACN,WACY,aACZ,cAvCqB,EAAS,KAAK,CACnC,UAAW,GAAG,EAAK,SACnB,SAAU,MAAO,EAAkB,IAAqC,CACvE,IAAM,EAAa,EAAO,OACvB,MAAM,EAAO,OAAO,EAAS,CAAO,EACpC,CAAC,EAKJ,MAAO,CAAE,GAAI,MAJU,EAAQ,GAAG,OACjC,EACA,CAAE,GAAG,EAAS,GAAG,CAAW,CAC7B,CACsB,CACvB,EACD,CA2Ba,EACZ,cA1BqB,EAAS,KAAK,CACnC,UAAW,GAAG,EAAK,SACnB,SAAU,MACT,EACA,KAEA,MAAM,EAAQ,GAAG,MAAM,EAAQ,GAAa,EAAQ,IAAa,EAC1D,CAAE,GAAI,EAAK,GAEpB,CAiBa,EACZ,eAhBsB,EAAS,KAAK,CACpC,UAAW,GAAG,EAAK,UACnB,SAAU,MAAO,EAAkB,KAClC,MAAM,EAAQ,GAAG,MAChB,EAAQ,GACR,CAAE,WAAY,KAAK,IAAI,CAAE,CAC1B,EACO,CAAE,GAAI,EAAK,GAEpB,CAOc,CACd,CACD"}
|
|
1
|
+
{"version":3,"file":"crud.mjs","names":["createCrudCommands","errors","config","defaultErrors","name","classification","commandSchema","id","k","createResult","okResult","updateInput","commandObject","archiveInput","createName","updateName","archiveName","operations","namedOperation","context","resolution","commands","enrichment","command","row","stamped","values","field","value","schema","definition"],"sources":["../src/crud.ts"],"sourcesContent":["import type { Value } from 'convex/values'\nimport type { GenericDataModel, GenericMutationCtx } from 'convex/server'\nimport type {\n\tAnyCommandMiddleware,\n\tApplicationCommand,\n\tAuditedOperation,\n\tCommandConstructor,\n\tParseable,\n\tSchemaOutput,\n} from './components/foundation/client'\nimport { defaultErrors, type ErrorFactory } from './errors'\nimport { k, type KFields, type KObject, type KType } from './k'\n\n/**\n * The table surface the factory consumes — structural, so any kTable / createTable / tenantTable\n * boundary satisfies it.\n */\ntype CrudTable = {\n\treadonly tableName: string\n\treadonly commandInput: KType & Parseable<CommandRow>\n\t// oxlint-disable-next-line anti-slop/no-shape-in-symbol-names -- `.shape` is the k object field map the table boundary exposes.\n\treadonly storage: KType & { readonly shape: KFields }\n}\n\n/** A parsed command: the commandFields' values. */\ntype CommandRow = { readonly [field: string]: Value | undefined }\n\ntype CrudContext = { db: Pick<GenericMutationCtx<GenericDataModel>['db'], 'insert' | 'patch'> }\n\ntype MaybePromise<Value> = Value | Promise<Value>\n\nexport type CrudConfig<Context extends CrudContext, Table extends CrudTable = CrudTable> = {\n\t/** The Foundation-bound Command class (destructured from the facade). */\n\tCommand: CommandConstructor\n\ttable: Table\n\t/** Audit aggregate type; enforced by the aggregates allowlist. */\n\taggregateType: string\n\t/** Observability/audit classification. Default 'business'. */\n\tclassification?: string\n\t/** Derives the audited actor id from the ctx (usually ctx.actor.userId). */\n\tactor: (context: Context) => string\n\t/**\n\t * Stamps server-owned fields onto creates (tenant, denormalized ids...).\n\t * REQUIRED when the table is a tenantTable — forgetting it would insert\n\t * untenanted rows; the factory fails fast at construction instead.\n\t */\n\tenrich?: (\n\t\tcontext: Context,\n\t\tcommand: SchemaOutput<Table['commandInput']>,\n\t) => MaybePromise<Partial<k.input<Table['storage']>>>\n\t/** Per-operation preconditions; run before the handlers. */\n\tguards?: {\n\t\tcreate?: (context: Context, command: never) => MaybePromise<void>\n\t\tupdate?: (context: Context, command: never) => MaybePromise<void>\n\t\tarchive?: (context: Context, command: never) => MaybePromise<void>\n\t}\n\t/** Per-operation middleware applied to all three generated operations. */\n\tmiddleware?: readonly AnyCommandMiddleware[]\n\terrors?: ErrorFactory\n}\n\n/**\n * Generates the standard create/update/archive operations from one kTable\n * declaration, fully inside the audited command pipeline: strict command\n * inputs from `commandFields`, mandatory audit with the declared aggregate\n * type, soft delete only (archive sets `archivedAt` — no hard-delete\n * operation is generated, per kit doctrine).\n *\n * convex-helpers ships a same-named `crud` helper; it was deliberately not\n * used — it bypasses the command pipeline (no audits, no guards, and hard\n * deletes). See docs/crud.md.\n */\nexport type CrudCommands<\n\tContext extends CrudContext,\n\tTable extends CrudTable = CrudTable,\n> = ReturnType<typeof createCrudCommands<Context, Table>>\n\nexport function createCrudCommands<\n\tContext extends CrudContext,\n\tTable extends CrudTable = CrudTable,\n>(config: CrudConfig<Context, Table>) {\n\tconst errors = config.errors ?? defaultErrors\n\tconst name = config.table.tableName\n\tconst classification = config.classification ?? 'business'\n\tconst isTenantTable = 'tenant' in config.table.storage.shape\n\tif (isTenantTable && !config.enrich) {\n\t\treturn errors.throw({\n\t\t\tcode: 'CRUD_ENRICH_REQUIRED',\n\t\t\tmessage: `Table \"${name}\" is a tenantTable: createCrudCommands requires an enrich callback that stamps ctx.tenant`,\n\t\t})\n\t}\n\n\tconst commandSchema: Table['commandInput'] = config.table.commandInput\n\t// k objects are strict: an update naming a field outside commandFields fails with VALIDATION.\n\tconst id = k.id(name)\n\tconst createResult = k.object({ id })\n\tconst okResult = k.object({ ok: k.literal(true) })\n\tconst updateInput = k.object({ id, data: commandObject(commandSchema).partial() })\n\tconst archiveInput = k.object({ id })\n\n\tconst createName = `${name}.create` as const\n\tconst updateName = `${name}.update` as const\n\tconst archiveName = `${name}.archive` as const\n\tconst operations = Object.assign(\n\t\t{},\n\t\tnamedOperation(createName, {\n\t\t\tcommand: commandSchema,\n\t\t\tresult: createResult,\n\t\t\tclassification,\n\t\t\taggregates: [config.aggregateType],\n\t\t\tmiddleware: config.middleware,\n\t\t\tguard: config.guards?.create,\n\t\t\taudit: (resolution: { result: k.infer<typeof createResult> }, context: Context) => ({\n\t\t\t\toperation: createName,\n\t\t\t\tactorId: config.actor(context),\n\t\t\t\taggregate: { type: config.aggregateType, id: resolution.result.id },\n\t\t\t}),\n\t\t}),\n\t\tnamedOperation(updateName, {\n\t\t\tcommand: updateInput,\n\t\t\tresult: okResult,\n\t\t\tclassification,\n\t\t\taggregates: [config.aggregateType],\n\t\t\tmiddleware: config.middleware,\n\t\t\tguard: config.guards?.update,\n\t\t\taudit: (resolution: { command: k.infer<typeof updateInput> }, context: Context) => ({\n\t\t\t\toperation: updateName,\n\t\t\t\tactorId: config.actor(context),\n\t\t\t\taggregate: { type: config.aggregateType, id: resolution.command.id },\n\t\t\t}),\n\t\t}),\n\t\tnamedOperation(archiveName, {\n\t\t\tcommand: archiveInput,\n\t\t\tresult: okResult,\n\t\t\tclassification,\n\t\t\taggregates: [config.aggregateType],\n\t\t\tmiddleware: config.middleware,\n\t\t\tguard: config.guards?.archive,\n\t\t\taudit: (resolution: { command: k.infer<typeof archiveInput> }, context: Context) => ({\n\t\t\t\toperation: archiveName,\n\t\t\t\tactorId: config.actor(context),\n\t\t\t\taggregate: { type: config.aggregateType, id: resolution.command.id },\n\t\t\t}),\n\t\t}),\n\t)\n\tconst commands: ApplicationCommand<Context, typeof operations> = new config.Command<\n\t\tContext,\n\t\ttypeof operations\n\t>(operations)\n\tconst executeCreate = commands.exec({\n\t\toperation: createName,\n\t\thandler: async (context, command) => {\n\t\t\tconst enrichment = config.enrich ? await config.enrich(context, command) : {}\n\t\t\tconst row: CommandRow = command\n\t\t\tconst stamped: CommandRow = enrichment\n\t\t\tconst values: Record<string, Value> = {}\n\t\t\tfor (const [field, value] of Object.entries({ ...row, ...stamped })) {\n\t\t\t\tif (value !== undefined) values[field] = value\n\t\t\t}\n\t\t\tconst inserted = await context.db.insert(name, values)\n\t\t\treturn { id: inserted }\n\t\t},\n\t})\n\tconst executeUpdate = commands.exec({\n\t\toperation: updateName,\n\t\thandler: async (context, command) => {\n\t\t\tawait context.db.patch(command.id, command.data)\n\t\t\treturn { ok: true }\n\t\t},\n\t})\n\tconst executeArchive = commands.exec({\n\t\toperation: archiveName,\n\t\thandler: async (context, command) => {\n\t\t\tawait context.db.patch(command.id, { archivedAt: Date.now() })\n\t\t\treturn { ok: true }\n\t\t},\n\t})\n\n\treturn {\n\t\tcommands,\n\t\toperations,\n\t\texecuteCreate,\n\t\texecuteUpdate,\n\t\texecuteArchive,\n\t}\n}\n\n/** The command input as an object schema, for its `partial()` patch shape. */\nfunction commandObject(schema: KType): KObject<KFields> {\n\t// SAFETY: every table boundary's commandInput is a k.object (kTable picks the commandFields into one).\n\treturn schema as KObject<KFields>\n}\n\nfunction namedOperation<Name extends string, Definition extends AuditedOperation>(\n\tname: Name,\n\tdefinition: Definition,\n) {\n\t// SAFETY: this object contains exactly the computed name and its corresponding definition.\n\treturn { [name]: definition } as NamedOperation<Name, Definition>\n}\n\ntype NamedOperation<Name extends string, Definition extends AuditedOperation> = {\n\t[Key in Name]: Definition\n}\n"],"mappings":"A,+EA6EA,SAAgBA,EAGd,EAAoC,CACrC,IAAMC,EAASC,EAAO,QAAUC,EAC1BC,EAAOF,EAAO,MAAM,UACpBG,EAAiBH,EAAO,gBAAkB,WAEhD,GADsB,WAAYA,EAAO,MAAM,QAAQ,OAClC,CAACA,EAAO,OAC5B,OAAOD,EAAO,MAAM,CACnB,KAAM,uBACN,QAAS,UAAUG,EAAK,0FACzB,CAAC,EAGF,IAAME,EAAuCJ,EAAO,MAAM,aAEpDK,EAAKC,EAAE,GAAGJ,CAAI,EACdK,EAAeD,EAAE,OAAO,CAAE,IAAG,CAAC,EAC9BE,EAAWF,EAAE,OAAO,CAAE,GAAIA,EAAE,QAAQ,EAAI,CAAE,CAAC,EAC3CG,EAAcH,EAAE,OAAO,CAAE,KAAI,KAAMI,EAAcN,CAAa,CAAC,CAAC,QAAQ,CAAE,CAAC,EAC3EO,EAAeL,EAAE,OAAO,CAAE,IAAG,CAAC,EAE9BM,EAAa,GAAGV,EAAK,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C,KAAU,OAAO,QAAQ,CAAE,GAAGJ,EAAK,GAAGC,CAAQ,CAAC,EAC7DG,IAAU,IAAA,KAAW,EAAOD,GAASC,GAG1C,MAAO,CAAE,GAAI,MADUT,EAAQ,GAAG,OAAOf,EAAMsB,CAAM,CAC/B,CACvB,CACD,CAmBa,EACZ,cAnBqBL,EAAS,KAAK,CACnC,UAAWN,EACX,QAAS,MAAO,EAAS,KACxB,MAAMI,EAAQ,GAAG,MAAMI,EAAQ,GAAIA,EAAQ,IAAI,EACxC,CAAE,GAAI,EAAK,EAEpB,CAaa,EACZ,eAbsBF,EAAS,KAAK,CACpC,UAAWL,EACX,QAAS,MAAO,EAAS,KACxB,MAAMG,EAAQ,GAAG,MAAMI,EAAQ,GAAI,CAAE,WAAY,KAAK,IAAI,CAAE,CAAC,EACtD,CAAE,GAAI,EAAK,EAEpB,CAOc,CACd,CACD,CAGA,SAASX,EAAc,EAAiC,CAEvD,OAAOiB,CACR,CAEA,SAASX,EACR,EACA,EACC,CAED,MAAO,EAAGd,GAAO0B,CAAW,CAC7B,C"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { OperationExecutor, OperationPublicResult, OperationTool, OperationToolConverter, OperationToolDefinition, OperationToolJsonSchema, OperationToolOutcome, SelectedOperation, bindOperationExecutor, createOperationTools, operationToolDialect, selectOperation } from "./modules/contracts/exposure.mjs";
|
|
2
|
+
import { ContractDecoderError, ContractDecoderRequirements, ContractValidationError, EffectDecoder, decodeEffectContract, effectContract, effectSchema, effectStandardSchema } from "./modules/effect/schema.mjs";
|
|
3
|
+
import { NestedAuditMode, RequestScope } from "./modules/effect/scope.mjs";
|
|
4
|
+
import { CallbackError, CallbackRequirements, EffectMiddlewareInput, EffectOperationArgument, EffectOperationError, EffectOperationHandlerResult, EffectOperationInput, EffectOperationRequirements, EffectOperationResult, EffectPreparation, EffectValue, effectOperationFactory } from "./modules/effect/operation.mjs";
|
|
5
|
+
import { EffectApiBuilder, effectApiBuilder } from "./modules/effect/api.mjs";
|
|
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";
|
|
10
|
+
import { EffectFoundationOptions, createEffectFoundation } from "./modules/effect/foundation.mjs";
|
|
11
|
+
import { EffectIdempotencyPreparation, effectTransactionalIdempotency } from "./modules/effect/idempotency.mjs";
|
|
12
|
+
import { EffectCrudConfig, EffectCrudContext, EffectCrudPage, EffectCrudPagination, EffectCrudRepository, EffectCrudTable, createEffectCrud } from "./modules/effect/crud.mjs";
|
|
13
|
+
import { projectErrorCause } from "./modules/effect/errors.mjs";
|
|
14
|
+
import { EffectReceiptProtectedWorkflowMutation, effectReceiptWorkflowMutation, effectTerminalWorkflowAttempt, effectWorkflowAttempt, effectWorkflowStatusBindings } from "./modules/effect/workflow.mjs";
|
|
15
|
+
import "./modules/effect/client.mjs";
|
|
16
|
+
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 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, operationToolDialect, projectErrorCause, selectOperation };
|
package/dist/effect.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createEffectAuthFunctions as e}from"./modules/effect/auth.mjs";import{bindOperationExecutor as t,createOperationTools as n,operationToolDialect as r,selectOperation as i}from"./modules/contracts/exposure.mjs";import{effectOperationFactory as a}from"./modules/effect/operation.mjs";import{createEffectFoundation as o}from"./modules/effect/foundation.mjs";import{ActionAuditWriterError as s}from"./modules/effect/action.mjs";import{effectErrors as c}from"./modules/effect/failures.mjs";import{effectTransactionalIdempotency as l}from"./modules/effect/idempotency.mjs";import{createEffectCrud as u}from"./modules/effect/crud.mjs";import{effectApiBuilder as d}from"./modules/effect/api.mjs";import{projectErrorCause as f}from"./modules/effect/errors.mjs";import{ContractValidationError as p,decodeEffectContract as m,effectContract as h,effectSchema as g,effectStandardSchema as _}from"./modules/effect/schema.mjs";import{effectReceiptWorkflowMutation as v,effectTerminalWorkflowAttempt as y,effectWorkflowAttempt as b,effectWorkflowStatusBindings as x}from"./modules/effect/workflow.mjs";export{s as ActionAuditWriterError,p as ContractValidationError,t as bindOperationExecutor,e as createEffectAuthFunctions,u as createEffectCrud,o as createEffectFoundation,n as createOperationTools,m as decodeEffectContract,d as effectApiBuilder,h as effectContract,c as effectErrors,a as effectOperationFactory,v as effectReceiptWorkflowMutation,g as effectSchema,_ as effectStandardSchema,y as effectTerminalWorkflowAttempt,l as effectTransactionalIdempotency,b as effectWorkflowAttempt,x as effectWorkflowStatusBindings,r as operationToolDialect,f as projectErrorCause,i as selectOperation};
|
package/dist/errors.d.mts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
|
|
1
|
+
import { ARGUMENT_ISSUE_LIMITS, ArgumentFailure, ArgumentFailurePolicy, ArgumentIssue, DeclaredError, DeclaredFailure, DecodedFailure, ErrorContract, ErrorDefinitions, ErrorDetailParser, UnknownFailure, argumentErrors, combineErrorContracts, decodeFailure, defineErrorContract, queryErrors, sanitizeArgumentIssues } from "./modules/contracts/errors.mjs";
|
|
2
|
+
import { FailureHandlers, failureOf, isFailure, matchFailure } from "./react/failures.mjs";
|
|
2
3
|
/** Structured application error carried across Convex function boundaries. */
|
|
3
|
-
declare class KitError extends Error {
|
|
4
|
+
export declare class KitError extends Error {
|
|
4
5
|
readonly code: string;
|
|
5
6
|
constructor(input: {
|
|
6
7
|
code: string;
|
|
@@ -12,13 +13,12 @@ declare class KitError extends Error {
|
|
|
12
13
|
* (e.g. an App.errors singleton) adapt it to this shape; everyone else uses
|
|
13
14
|
* the default factory below.
|
|
14
15
|
*/
|
|
15
|
-
type ErrorFactory = {
|
|
16
|
+
export type ErrorFactory = {
|
|
16
17
|
throw(input: {
|
|
17
18
|
code: string;
|
|
18
19
|
message?: string;
|
|
19
20
|
}): never;
|
|
20
21
|
};
|
|
21
|
-
declare const defaultErrors: ErrorFactory;
|
|
22
|
-
|
|
23
|
-
export { ErrorFactory, KitError, defaultErrors };
|
|
22
|
+
export declare const defaultErrors: ErrorFactory;
|
|
23
|
+
export { ARGUMENT_ISSUE_LIMITS, type ArgumentFailure, type ArgumentFailurePolicy, type ArgumentIssue, type DeclaredError, type DeclaredFailure, type DecodedFailure, type ErrorContract, type ErrorDefinitions, type ErrorDetailParser, type FailureHandlers, type UnknownFailure, argumentErrors, combineErrorContracts, decodeFailure, defineErrorContract, failureOf, isFailure, matchFailure, queryErrors, sanitizeArgumentIssues };
|
|
24
24
|
//# sourceMappingURL=errors.d.mts.map
|
package/dist/errors.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
1
|
+
import{ARGUMENT_ISSUE_LIMITS as e,argumentErrors as t,combineErrorContracts as n,decodeFailure as r,defineErrorContract as i,queryErrors as a,sanitizeArgumentIssues as o}from"./modules/contracts/errors.mjs";import{failureOf as s,isFailure as c,matchFailure as l}from"./react/failures.mjs";var u=class extends Error{code;constructor(e){super(e.message??e.code),this.name=`KitError`,this.code=e.code}};const d={throw(e){throw new u(e)}};export{e as ARGUMENT_ISSUE_LIMITS,u as KitError,t as argumentErrors,n as combineErrorContracts,r as decodeFailure,d as defaultErrors,i as defineErrorContract,s as failureOf,c as isFailure,l as matchFailure,a as queryErrors,o as sanitizeArgumentIssues};
|
|
2
2
|
//# sourceMappingURL=errors.mjs.map
|
package/dist/errors.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.mjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/** Structured application error carried across Convex function boundaries. */\nexport class KitError extends Error {\n\treadonly code: string\n\n\tconstructor(input: { code: string; message?: string }) {\n\t\tsuper(input.message ?? input.code)\n\t\tthis.name = 'KitError'\n\t\tthis.code = input.code\n\t}\n}\n\n/**\n * Injection seam for host error policy. Hosts with their own error taxonomy\n * (e.g. an App.errors singleton) adapt it to this shape; everyone else uses\n * the default factory below.\n */\nexport type ErrorFactory = {\n\tthrow(input: { code: string; message?: string }): never\n}\n\nexport const defaultErrors: ErrorFactory = {\n\tthrow(input) {\n\t\tthrow new KitError(input)\n\t},\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"errors.mjs","names":["KitError","input","defaultErrors","ARGUMENT_ISSUE_LIMITS","argumentErrors","combineErrorContracts","decodeFailure","defineErrorContract","failureOf","isFailure","matchFailure","queryErrors","sanitizeArgumentIssues"],"sources":["../src/errors.ts"],"sourcesContent":["/** Structured application error carried across Convex function boundaries. */\nexport class KitError extends Error {\n\treadonly code: string\n\n\tconstructor(input: { code: string; message?: string }) {\n\t\tsuper(input.message ?? input.code)\n\t\tthis.name = 'KitError'\n\t\tthis.code = input.code\n\t}\n}\n\nexport {\n\tdefineErrorContract,\n\tqueryErrors,\n\targumentErrors,\n\tsanitizeArgumentIssues,\n\tARGUMENT_ISSUE_LIMITS,\n\tcombineErrorContracts,\n\ttype ArgumentIssue,\n\ttype ArgumentFailure,\n\ttype ArgumentFailurePolicy,\n\ttype ErrorContract,\n\ttype ErrorDefinitions,\n\ttype ErrorDetailParser,\n\ttype DeclaredError,\n\ttype DeclaredFailure,\n\ttype DecodedFailure,\n\ttype UnknownFailure,\n} from './modules/contracts/errors'\n\n/**\n * Injection seam for host error policy. Hosts with their own error taxonomy\n * (e.g. an App.errors singleton) adapt it to this shape; everyone else uses\n * the default factory below.\n */\nexport type ErrorFactory = {\n\tthrow(input: { code: string; message?: string }): never\n}\n\nexport const defaultErrors: ErrorFactory = {\n\tthrow(input) {\n\t\tthrow new KitError(input)\n\t},\n}\n\n// Pure helpers do not import React or server query-engine modules.\nexport {\n\tdecodeFailure,\n\tmatchFailure,\n\tfailureOf,\n\tisFailure,\n\ttype FailureHandlers,\n} from './react/failures'\n"],"mappings":"A,iSACA,IAAaA,EAAb,cAA8B,KAAM,CACnC,KAEA,YAAY,EAA2C,CACtD,MAAMC,EAAM,SAAWA,EAAM,IAAI,EACjC,KAAK,KAAO,WACZ,KAAK,KAAOA,EAAM,IACnB,CACD,EA8BA,MAAaC,EAA8B,CAC1C,MAAM,EAAO,CACZ,MAAM,IAAIF,EAASC,CAAK,CACzB,CACD,E"}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { FilterContract, FilterDescriptor, SharedField, SharedFilters, defineFilterContract } from "./querying/shared/contract.mjs";
|
|
2
|
+
import { evaluateFilter } from "./querying/shared/evaluate.mjs";
|
|
3
|
+
import { FilterAst, FilterOperator, FilterScalar } from "./querying/shared/ast.mjs";
|
|
4
|
+
export { type FilterAst, type FilterContract, type FilterDescriptor, type FilterOperator, type FilterScalar, type SharedField, type SharedFilters, defineFilterContract, evaluateFilter };
|
package/dist/filters.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{defineFilterContract as e}from"./querying/shared/contract.mjs";import{evaluateFilter as t}from"./querying/shared/evaluate.mjs";export{e as defineFilterContract,t as evaluateFilter};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { CanonicalConvexBounds, IdempotencyCapture, IdempotencyError, IdempotencyErrorCode, IdempotencyIdentity, IdempotencyInvocation, IdempotencyPreparation, IdempotencyReceipt, IdempotencyVersions, canonicalConvexBytes, captureIdempotencyInvocation, transactionalIdempotency } from "./modules/contracts/idempotency.mjs";
|
|
2
|
+
export { type CanonicalConvexBounds, type IdempotencyCapture, IdempotencyError, type IdempotencyErrorCode, type IdempotencyIdentity, type IdempotencyInvocation, type IdempotencyPreparation, type IdempotencyReceipt, type IdempotencyVersions, canonicalConvexBytes, captureIdempotencyInvocation, transactionalIdempotency };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{IdempotencyError,canonicalConvexBytes,captureIdempotencyInvocation,transactionalIdempotency}from"./modules/contracts/idempotency.mjs";
|
package/dist/index.d.mts
CHANGED
|
@@ -1,13 +1,20 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { k } from "./k/index.mjs";
|
|
2
2
|
import { ErrorFactory, KitError, defaultErrors } from "./errors.mjs";
|
|
3
|
+
import { EnginePaginationResult, KDtoOptions, KTableBoundary, KTableOptions, KVariantOptions, KVariantTableBoundary, PageCompleteness, TIMESTAMP_FIELDS, createTable, kTable, kVariantTable, paginated, tenantTable } from "./table.mjs";
|
|
3
4
|
import { RLSConfig, Rules, TENANT_FIELD, assertTenantOwned, composeRules, createTenantRules, requireTenantReference } from "./tenancy.mjs";
|
|
4
|
-
import { Actor, AuthBundle, AuthFunctionsConfig, DefaultRole, Include, IncludedQuery, SecurityConfig, createAuthFunctions, createInclude, defaultRoleMap } from "./auth.mjs";
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
5
|
+
import { Actor, AuthBundle, AuthFunctions, AuthFunctionsConfig, DefaultRole, Include, IncludedQuery, SecurityBundle, SecurityConfig, ServiceMutation, ServicePrincipal, ServiceQuery, createAuthFunctions, createInclude, defaultRoleMap } from "./auth.mjs";
|
|
6
|
+
import { Namespace, NamespaceTag, createModule, memberName, namespace, namespaceIndex, namespaceName, namespacePrefix, tablesOf } from "./namespace.mjs";
|
|
7
|
+
import { AgentToolHandlers, AgentToolRecord, createAgentTools } from "./agent-tools.mjs";
|
|
7
8
|
import { CrudConfig, createCrudCommands } from "./crud.mjs";
|
|
8
|
-
import { TIMESTAMP_FIELDS, TableBoundaryOptions, createModule, jsonSafeZid, paginated, tenantTable, zodTable, zodVariantTable } from "./zod-table.mjs";
|
|
9
9
|
import { RateLimiterLike, rateLimit } from "./middleware.mjs";
|
|
10
10
|
import { WebhookBoundaryConfig, createWebhookBoundary, recordWebhookEvent, webhookEventsTable } from "./webhooks.mjs";
|
|
11
|
+
import { AnyQueryMiddleware, QueryMiddleware } from "./components/foundation/modules/query/query.mjs";
|
|
11
12
|
import { createStateMachine } from "./state-machine.mjs";
|
|
12
|
-
import { Change, Trigger, Triggers, appendOnly, createTriggers, noDelete, tenantOwnership, timestamps } from "./triggers.mjs";
|
|
13
|
-
|
|
13
|
+
import { Change, Trigger, Triggers, appendOnly, createTriggers, noDelete, tenantOwnership, timestamps, triggerContext } from "./triggers.mjs";
|
|
14
|
+
import { AnyCommandMiddleware, ApplicationCommand, AuditEntryInput, AuditWriter, AuditedOperation, AuditedRegistry, CommandConstructor, CommandDefaults, CommandMiddleware, Foundation, FoundationOptions, PermissionChecker } from "./components/foundation/client.mjs";
|
|
15
|
+
import { FoundationRegistry, FoundationRegistryOptions, createFoundation } from "./modules/foundation/foundation.mjs";
|
|
16
|
+
import { FieldReference, RelationBuilder, RelationDeclarations, RelationEdge, RelationFilterSelection, RelationFilters, RelationRegistry, RelationRegistryIdentity, RelationRow, RelationSelection, RelationTable, RelationTableHelpers, RelationTables, ThroughReference, defineRelations } from "./relations.mjs";
|
|
17
|
+
import { ScalarFilters, ScalarSelection, ServerFilter } from "./querying/filters.mjs";
|
|
18
|
+
import { QueryEngineConfig, createQueryEngine } from "./querying.mjs";
|
|
19
|
+
import "./k.mjs";
|
|
20
|
+
export { type Actor, type AgentToolHandlers, type AgentToolRecord, type AnyCommandMiddleware, type AnyQueryMiddleware, type ApplicationCommand, type AuditEntryInput, type AuditWriter, type AuditedOperation, type AuditedRegistry, type AuthBundle, type AuthFunctions, type AuthFunctionsConfig, type Change, type CommandConstructor, type CommandDefaults, type CommandMiddleware, type CrudConfig, type DefaultRole, type KDtoOptions as DtoOptions, type EnginePaginationResult, type ErrorFactory, type FieldReference, Foundation, type FoundationOptions, type FoundationRegistry, type FoundationRegistryOptions, type Include, type IncludedQuery, type KDtoOptions, type KTableBoundary, type KTableOptions, type KVariantOptions, type KVariantTableBoundary, KitError, type Namespace, type NamespaceTag, type PageCompleteness, type PermissionChecker, type QueryEngineConfig, type QueryMiddleware, type RLSConfig, type RateLimiterLike, type RelationBuilder, type RelationDeclarations, type RelationEdge, type RelationFilterSelection, type RelationFilters, type RelationRegistry, type RelationRegistryIdentity, type RelationRow, type RelationSelection, type RelationTable, type RelationTableHelpers, type RelationTables, type Rules, type ScalarFilters, type ScalarSelection, type SecurityBundle, type SecurityConfig, type ServerFilter, type ServiceMutation, type ServicePrincipal, type ServiceQuery, TENANT_FIELD, TIMESTAMP_FIELDS, type KTableOptions as TableBoundaryOptions, type ThroughReference, type Trigger, Triggers, type WebhookBoundaryConfig, appendOnly, assertTenantOwned, composeRules, createAgentTools, createAuthFunctions, createCrudCommands, createFoundation, createInclude, createModule, createQueryEngine, createStateMachine, createTable, createTenantRules, createTriggers, createWebhookBoundary, defaultErrors, defaultRoleMap, defineRelations, k, kTable, kVariantTable, memberName, namespace, namespaceIndex, namespaceName, namespacePrefix, noDelete, paginated, rateLimit, recordWebhookEvent, requireTenantReference, tablesOf, tenantOwnership, tenantTable, timestamps, triggerContext, webhookEventsTable };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{KitError as e,defaultErrors as t}from"./errors.mjs";import{TIMESTAMP_FIELDS as n,createTable as r,kTable as i,kVariantTable as a,paginated as o,tenantTable as s}from"./table.mjs";import{TENANT_FIELD as c,assertTenantOwned as l,composeRules as u,createTenantRules as d,requireTenantReference as f}from"./tenancy.mjs";import{createAuthFunctions as p,createInclude as m,defaultRoleMap as h}from"./auth.mjs";import{createAgentTools as g}from"./agent-tools.mjs";import{createCrudCommands as _}from"./crud.mjs";import{createModule as v,memberName as y,namespace as b,namespaceIndex as x,namespaceName as S,namespacePrefix as C,tablesOf as w}from"./namespace.mjs";import{rateLimit as T}from"./middleware.mjs";import{createWebhookBoundary as E,recordWebhookEvent as D,webhookEventsTable as O}from"./webhooks.mjs";import{createStateMachine as k}from"./state-machine.mjs";import{Triggers as A,appendOnly as j,createTriggers as M,noDelete as N,tenantOwnership as P,timestamps as F,triggerContext as I}from"./triggers.mjs";import{Foundation as L}from"./components/foundation/client.mjs";import{createFoundation as R}from"./modules/foundation/foundation.mjs";import{defineRelations as z}from"./relations.mjs";import{createQueryEngine as B}from"./querying.mjs";import{k as V}from"./k/index.mjs";export{L as Foundation,e as KitError,c as TENANT_FIELD,n as TIMESTAMP_FIELDS,A as Triggers,j as appendOnly,l as assertTenantOwned,u as composeRules,g as createAgentTools,p as createAuthFunctions,_ as createCrudCommands,R as createFoundation,m as createInclude,v as createModule,B as createQueryEngine,k as createStateMachine,r as createTable,d as createTenantRules,M as createTriggers,E as createWebhookBoundary,t as defaultErrors,h as defaultRoleMap,z as defineRelations,V as k,i as kTable,a as kVariantTable,y as memberName,b as namespace,x as namespaceIndex,S as namespaceName,C as namespacePrefix,N as noDelete,o as paginated,T as rateLimit,D as recordWebhookEvent,f as requireTenantReference,w as tablesOf,P as tenantOwnership,s as tenantTable,F as timestamps,I as triggerContext,O as webhookEventsTable};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { KType } from "./k/types.mjs";
|
|
2
|
+
import { JSONValue } from "convex/values";
|
|
3
|
+
/** The JSON Schema (draft 2020-12) subset `toJsonSchema` emits. */
|
|
4
|
+
export interface JsonSchema {
|
|
5
|
+
$schema?: string;
|
|
6
|
+
type?: 'string' | 'number' | 'integer' | 'boolean' | 'null' | 'array' | 'object';
|
|
7
|
+
format?: 'date' | 'date-time';
|
|
8
|
+
contentEncoding?: 'base64';
|
|
9
|
+
description?: string;
|
|
10
|
+
const?: JSONValue;
|
|
11
|
+
enum?: string[];
|
|
12
|
+
default?: JSONValue;
|
|
13
|
+
minLength?: number;
|
|
14
|
+
maxLength?: number;
|
|
15
|
+
pattern?: string;
|
|
16
|
+
minimum?: number;
|
|
17
|
+
maximum?: number;
|
|
18
|
+
minItems?: number;
|
|
19
|
+
maxItems?: number;
|
|
20
|
+
items?: JsonSchema;
|
|
21
|
+
properties?: Record<string, JsonSchema>;
|
|
22
|
+
required?: string[];
|
|
23
|
+
additionalProperties?: boolean | JsonSchema;
|
|
24
|
+
propertyNames?: JsonSchema;
|
|
25
|
+
anyOf?: JsonSchema[];
|
|
26
|
+
oneOf?: JsonSchema[];
|
|
27
|
+
allOf?: JsonSchema[];
|
|
28
|
+
}
|
|
29
|
+
export type JsonSchemaOptions = {
|
|
30
|
+
/** Add `$schema: "https://json-schema.org/draft/2020-12/schema"` to the root. */
|
|
31
|
+
readonly $schema?: boolean;
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* The input-side JSON Schema of a `k` schema, for agent tool inputs and forms: optional and defaulted
|
|
35
|
+
* fields are not required (a JSON-compatible default is emitted), ids are strings, transforms and pipes
|
|
36
|
+
* emit their input schema, and descriptions come from `.describe()`. Custom refinements are not
|
|
37
|
+
* expressible and are omitted.
|
|
38
|
+
*/
|
|
39
|
+
export declare function toJsonSchema(schema: KType, options?: JsonSchemaOptions): JsonSchema;
|
|
40
|
+
//# sourceMappingURL=json-schema.d.mts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{membersOf as e}from"./k/compile.mjs";import{maxTimestamp as t}from"./k/formats.mjs";function n(e,t){let n=r(e);return t?.$schema===!0?{$schema:`https://json-schema.org/draft/2020-12/schema`,...n}:n}function r(e){let t=[];for(let n=e;n!==null;n=n.prev)t.push(n);let n=i(t.pop()),r=!1,a=!1,o,c;for(let e=t.length-1;e>=0;e--){let i=t[e];switch(i.op){case`transform`:case`pipe`:r=!0;break;case`describe`:o=h(i);break;case`nullable`:a=!0;break;case`default`:r||(c=u(f(i)));break;case`min`:case`max`:case`length`:case`regex`:case`int`:r||s(n,i)}}let l=a?{anyOf:[n,{type:`null`}]}:n;return o!==void 0&&(l.description=o),c!==void 0&&(l.default=c),l}function i(n){switch(n.op){case`string`:case`id`:return{type:`string`};case`isoDate`:return{type:`string`,format:`date`};case`isoDateTime`:return{type:`string`,format:`date-time`};case`number`:return{type:`number`};case`int`:case`int64`:return{type:`integer`};case`timestamp`:return{type:`integer`,minimum:0,maximum:t};case`boolean`:return{type:`boolean`};case`null`:return{type:`null`};case`bytes`:return{type:`string`,contentEncoding:`base64`};case`any`:case`json`:return{};case`literal`:return l(m(n));case`enum`:return{type:`string`,enum:[...n.arg]};case`array`:return{type:`array`,items:r(d(n.arg))};case`object`:return a(p(n));case`record`:{let[e,t]=n.arg;return{type:`object`,propertyNames:r(e),additionalProperties:r(t)}}case`union`:return{anyOf:e(n).map(r)};case`discriminatedUnion`:{let{options:e}=n.arg;return{oneOf:e.map(r)}}default:throw Error(`toJsonSchema: '${n.op}' is not a root operation`)}}function a(e){let t={},n=[];for(let i in e)t[i]=r(e[i]),o(e[i])&&n.push(i);let i={type:`object`,properties:t,additionalProperties:!1};return n.length>0&&(i.required=n),i}function o(e){for(let t=e;t!==null;t=t.prev)if(t.op===`optional`||t.op===`partial`||t.op==="default")return!1;return!0}function s(e,t){if(t.op===`int`){e.type=`integer`;return}if(t.op===`regex`){let n=t.arg.source;e.pattern===void 0?e.pattern=n:(e.allOf??=[]).push({pattern:n});return}let n=t.arg,r=t.op===`min`||t.op===`length`,i=t.op===`max`||t.op===`length`;e.type===`string`?(r&&(e.minLength=c(e.minLength,n,Math.max)),i&&(e.maxLength=c(e.maxLength,n,Math.min))):e.type===`array`?(r&&(e.minItems=c(e.minItems,n,Math.max)),i&&(e.maxItems=c(e.maxItems,n,Math.min))):(r&&(e.minimum=c(e.minimum,n,Math.max)),i&&(e.maximum=c(e.maximum,n,Math.min)))}function c(e,t,n){return e===void 0?t:n(e,t)}function l(e){switch(typeof e){case`string`:return{type:`string`,const:e};case`boolean`:return{type:`boolean`,const:e};case`bigint`:return{type:`integer`,const:Number(e)};default:return{type:`number`,const:e}}}function u(e){if(e===null)return null;switch(typeof e){case`string`:case`boolean`:return e;case`number`:return Number.isFinite(e)?e:void 0;case`bigint`:return}if(e instanceof ArrayBuffer)return;if(Array.isArray(e)){let t=[];for(let n of e){let e=u(n);if(e===void 0)return;t.push(e)}return t}let t={};for(let[n,r]of Object.entries(e)){if(r===void 0)continue;let e=u(r);if(e===void 0)return;t[n]=e}return t}function d(e){return e}function f(e){return e.arg}function p(e){return e.arg}function m(e){return e.arg}function h(e){return e.arg}export{n as toJsonSchema};
|
|
2
|
+
//# sourceMappingURL=json-schema.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"json-schema.mjs","names":["toJsonSchema","out","convert","schema","options","records","current","node","rootSchema","transformed","nullable","description","fallback","index","record","textOf","jsonOf","defaultOf","applyCheck","wrapped","root","maxTimestamp","literalSchema","literalOf","argNode","objectSchema","fieldsOf","key","value","membersOf","properties","required","fields","isRequired","pattern","limit","low","high","strongest","pick","items","item","json","arg"],"sources":["../src/json-schema.ts"],"sourcesContent":["/** JSON Schema for `k` schemas (KTD8): a separate entry, so core function bundles never load it. */\nimport type { JSONValue, Value } from 'convex/values'\nimport { membersOf } from './k/compile'\nimport { maxTimestamp } from './k/formats'\nimport type { KDiscriminated, KFields, KLiteralValue, KNode, KType } from './k/types'\n\n/** The JSON Schema (draft 2020-12) subset `toJsonSchema` emits. */\nexport interface JsonSchema {\n\t$schema?: string\n\ttype?: 'string' | 'number' | 'integer' | 'boolean' | 'null' | 'array' | 'object'\n\tformat?: 'date' | 'date-time'\n\tcontentEncoding?: 'base64'\n\tdescription?: string\n\tconst?: JSONValue\n\tenum?: string[]\n\tdefault?: JSONValue\n\tminLength?: number\n\tmaxLength?: number\n\tpattern?: string\n\tminimum?: number\n\tmaximum?: number\n\tminItems?: number\n\tmaxItems?: number\n\titems?: JsonSchema\n\tproperties?: Record<string, JsonSchema>\n\trequired?: string[]\n\tadditionalProperties?: boolean | JsonSchema\n\tpropertyNames?: JsonSchema\n\tanyOf?: JsonSchema[]\n\toneOf?: JsonSchema[]\n\tallOf?: JsonSchema[]\n}\n\nexport type JsonSchemaOptions = {\n\t/** Add `$schema: \"https://json-schema.org/draft/2020-12/schema\"` to the root. */\n\treadonly $schema?: boolean\n}\n\n/**\n * The input-side JSON Schema of a `k` schema, for agent tool inputs and forms: optional and defaulted\n * fields are not required (a JSON-compatible default is emitted), ids are strings, transforms and pipes\n * emit their input schema, and descriptions come from `.describe()`. Custom refinements are not\n * expressible and are omitted.\n */\nexport function toJsonSchema(schema: KType, options?: JsonSchemaOptions): JsonSchema {\n\tconst out = convert(schema)\n\tif (options?.$schema === true)\n\t\treturn { $schema: 'https://json-schema.org/draft/2020-12/schema', ...out }\n\treturn out\n}\n\nfunction convert(node: KNode): JsonSchema {\n\tconst records: KNode[] = []\n\tfor (let current: KNode | null = node; current !== null; current = current.prev)\n\t\trecords.push(current)\n\t// SAFETY: a chain always ends at a root record.\n\tconst out = rootSchema(records.pop() as KNode)\n\tlet transformed = false\n\tlet nullable = false\n\tlet description: string | undefined\n\tlet fallback: JSONValue | undefined\n\tfor (let index = records.length - 1; index >= 0; index--) {\n\t\tconst record = records[index]\n\t\tswitch (record.op) {\n\t\t\tcase 'transform':\n\t\t\tcase 'pipe':\n\t\t\t\ttransformed = true\n\t\t\t\tbreak\n\t\t\tcase 'describe':\n\t\t\t\tdescription = textOf(record)\n\t\t\t\tbreak\n\t\t\tcase 'nullable':\n\t\t\t\tnullable = true\n\t\t\t\tbreak\n\t\t\tcase 'default':\n\t\t\t\tif (!transformed) fallback = jsonOf(defaultOf(record))\n\t\t\t\tbreak\n\t\t\tcase 'min':\n\t\t\tcase 'max':\n\t\t\tcase 'length':\n\t\t\tcase 'regex':\n\t\t\tcase 'int':\n\t\t\t\tif (!transformed) applyCheck(out, record)\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\tbreak\n\t\t}\n\t}\n\tconst wrapped: JsonSchema = nullable ? { anyOf: [out, { type: 'null' }] } : out\n\tif (description !== undefined) wrapped.description = description\n\tif (fallback !== undefined) wrapped.default = fallback\n\treturn wrapped\n}\n\nfunction rootSchema(root: KNode): JsonSchema {\n\tswitch (root.op) {\n\t\tcase 'string':\n\t\tcase 'id':\n\t\t\treturn { type: 'string' }\n\t\tcase 'isoDate':\n\t\t\treturn { type: 'string', format: 'date' }\n\t\tcase 'isoDateTime':\n\t\t\treturn { type: 'string', format: 'date-time' }\n\t\tcase 'number':\n\t\t\treturn { type: 'number' }\n\t\tcase 'int':\n\t\tcase 'int64':\n\t\t\treturn { type: 'integer' }\n\t\tcase 'timestamp':\n\t\t\treturn { type: 'integer', minimum: 0, maximum: maxTimestamp }\n\t\tcase 'boolean':\n\t\t\treturn { type: 'boolean' }\n\t\tcase 'null':\n\t\t\treturn { type: 'null' }\n\t\tcase 'bytes':\n\t\t\treturn { type: 'string', contentEncoding: 'base64' }\n\t\tcase 'any':\n\t\tcase 'json':\n\t\t\treturn {}\n\t\tcase 'literal':\n\t\t\treturn literalSchema(literalOf(root))\n\t\tcase 'enum':\n\t\t\t// SAFETY: k.enum stores its value list as the root argument.\n\t\t\treturn { type: 'string', enum: [...(root.arg as readonly string[])] }\n\t\tcase 'array':\n\t\t\treturn { type: 'array', items: convert(argNode(root.arg)) }\n\t\tcase 'object':\n\t\t\treturn objectSchema(fieldsOf(root))\n\t\tcase 'record': {\n\t\t\t// SAFETY: k.record stores its key and value schemas as the root argument.\n\t\t\tconst [key, value] = root.arg as readonly KType[]\n\t\t\treturn { type: 'object', propertyNames: convert(key), additionalProperties: convert(value) }\n\t\t}\n\t\tcase 'union':\n\t\t\treturn { anyOf: membersOf(root).map(convert) }\n\t\tcase 'discriminatedUnion': {\n\t\t\t// SAFETY: k.discriminatedUnion stores its key and options as the root argument.\n\t\t\tconst { options } = root.arg as KDiscriminated\n\t\t\treturn { oneOf: options.map(convert) }\n\t\t}\n\t\tdefault:\n\t\t\tthrow new Error(`toJsonSchema: '${root.op}' is not a root operation`)\n\t}\n}\n\nfunction objectSchema(fields: KFields): JsonSchema {\n\tconst properties: Record<string, JsonSchema> = {}\n\tconst required: string[] = []\n\tfor (const key in fields) {\n\t\tproperties[key] = convert(fields[key])\n\t\tif (isRequired(fields[key])) required.push(key)\n\t}\n\tconst out: JsonSchema = { type: 'object', properties, additionalProperties: false }\n\tif (required.length > 0) out.required = required\n\treturn out\n}\n\nfunction isRequired(node: KNode): boolean {\n\tfor (let current: KNode | null = node; current !== null; current = current.prev) {\n\t\tif (current.op === 'optional' || current.op === 'partial' || current.op === 'default')\n\t\t\treturn false\n\t}\n\treturn true\n}\n\nfunction applyCheck(out: JsonSchema, record: KNode): void {\n\tif (record.op === 'int') {\n\t\tout.type = 'integer'\n\t\treturn\n\t}\n\tif (record.op === 'regex') {\n\t\t// SAFETY: .regex stores its pattern as the record argument.\n\t\tconst pattern = (record.arg as RegExp).source\n\t\tif (out.pattern === undefined) out.pattern = pattern\n\t\telse (out.allOf ??= []).push({ pattern })\n\t\treturn\n\t}\n\t// SAFETY: min, max and length store their numeric limit as the record argument.\n\tconst limit = record.arg as number\n\tconst low = record.op === 'min' || record.op === 'length'\n\tconst high = record.op === 'max' || record.op === 'length'\n\tif (out.type === 'string') {\n\t\tif (low) out.minLength = strongest(out.minLength, limit, Math.max)\n\t\tif (high) out.maxLength = strongest(out.maxLength, limit, Math.min)\n\t} else if (out.type === 'array') {\n\t\tif (low) out.minItems = strongest(out.minItems, limit, Math.max)\n\t\tif (high) out.maxItems = strongest(out.maxItems, limit, Math.min)\n\t} else {\n\t\tif (low) out.minimum = strongest(out.minimum, limit, Math.max)\n\t\tif (high) out.maximum = strongest(out.maximum, limit, Math.min)\n\t}\n}\n\n/** Repeated bounds all apply when parsing, so the schema keeps the strongest one. */\nfunction strongest(\n\tcurrent: number | undefined,\n\tlimit: number,\n\tpick: (a: number, b: number) => number,\n): number {\n\treturn current === undefined ? limit : pick(current, limit)\n}\n\nfunction literalSchema(value: KLiteralValue): JsonSchema {\n\t// oxlint-disable-next-line anti-slop/no-runtime-typeof -- A declared literal's JSON type follows its representation.\n\tswitch (typeof value) {\n\t\tcase 'string':\n\t\t\treturn { type: 'string', const: value }\n\t\tcase 'boolean':\n\t\t\treturn { type: 'boolean', const: value }\n\t\tcase 'bigint':\n\t\t\treturn { type: 'integer', const: Number(value) }\n\t\tdefault:\n\t\t\treturn { type: 'number', const: value }\n\t}\n}\n\n/** The JSON form of a declared default, or undefined when it has none (bigint, bytes). */\nfunction jsonOf(value: Value): JSONValue | undefined {\n\tif (value === null) return null\n\t// oxlint-disable-next-line anti-slop/no-runtime-typeof -- A declared default is a Convex value whose JSON form follows its representation.\n\tswitch (typeof value) {\n\t\tcase 'string':\n\t\tcase 'boolean':\n\t\t\treturn value\n\t\tcase 'number':\n\t\t\treturn Number.isFinite(value) ? value : undefined\n\t\tcase 'bigint':\n\t\t\treturn undefined\n\t\tdefault:\n\t\t\tbreak\n\t}\n\tif (value instanceof ArrayBuffer) return undefined\n\tif (Array.isArray(value)) {\n\t\tconst items: JSONValue[] = []\n\t\tfor (const item of value) {\n\t\t\tconst json = jsonOf(item)\n\t\t\tif (json === undefined) return undefined\n\t\t\titems.push(json)\n\t\t}\n\t\treturn items\n\t}\n\tconst out: { [key: string]: JSONValue } = {}\n\tfor (const [key, item] of Object.entries(value)) {\n\t\tif (item === undefined) continue\n\t\tconst json = jsonOf(item)\n\t\tif (json === undefined) return undefined\n\t\tout[key] = json\n\t}\n\treturn out\n}\n\nfunction argNode(arg: KNode['arg']): KNode {\n\t// SAFETY: k.array stores its element schema as the root argument.\n\treturn arg as KType\n}\n\nfunction defaultOf(record: KNode): Value {\n\t// SAFETY: a default record stores a Convex value as its argument.\n\treturn record.arg as Value\n}\n\nfunction fieldsOf(root: KNode): KFields {\n\t// SAFETY: k.object stores its field map as the root argument.\n\treturn root.arg as KFields\n}\n\nfunction literalOf(root: KNode): KLiteralValue {\n\t// SAFETY: k.literal stores its value as the root argument.\n\treturn root.arg as KLiteralValue\n}\n\nfunction textOf(record: KNode): string {\n\t// SAFETY: a describe record stores its text as the record argument.\n\treturn record.arg as string\n}\n"],"mappings":"A,2FA4CA,SAAgBA,EAAa,EAAe,EAAyC,CACpF,IAAMC,EAAMC,EAAQC,CAAM,EAG1B,OAFIC,GAAS,UAAY,GACjB,CAAE,QAAS,+CAAgD,GAAGH,CAAI,EACnEA,CACR,CAEA,SAASC,EAAQ,EAAyB,CACzC,IAAMG,EAAmB,CAAC,EAC1B,IAAK,IAAIC,EAAwBC,EAAMD,IAAY,KAAM,EAAUA,EAAQ,KAC1ED,EAAQ,KAAKC,CAAO,EAErB,IAAML,EAAMO,EAAWH,EAAQ,IAAI,CAAU,EACzCI,EAAc,GACdC,EAAW,GACXC,EACAC,EACJ,IAAK,IAAIC,EAAQR,EAAQ,OAAS,EAAGQ,GAAS,EAAG,IAAS,CACzD,IAAMC,EAAST,EAAQQ,GACvB,OAAQC,EAAO,GAAf,CACC,IAAK,YACL,IAAK,OACJ,EAAc,GACd,MACD,IAAK,WACJ,EAAcC,EAAOD,CAAM,EAC3B,MACD,IAAK,WACJ,EAAW,GACX,MACD,IAAK,UACCL,IAAa,EAAWO,EAAOC,EAAUH,CAAM,CAAC,GACrD,MACD,IAAK,MACL,IAAK,MACL,IAAK,SACL,IAAK,QACL,IAAK,MACCL,GAAaS,EAAWjB,EAAKa,CAA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CAAC0B,EAAKc,KAAS,OAAO,QAAQb,CAAK,EAAG,CAChD,GAAIa,IAAS,IAAA,GAAW,SACxB,IAAMC,EAAO1B,EAAOyB,CAAI,EACxB,GAAIC,IAAS,IAAA,GAAW,OACxB,EAAIf,GAAOe,CACZ,CACA,OAAOzC,CACR,CAEA,SAASuB,EAAQ,EAA0B,CAE1C,OAAOmB,CACR,CAEA,SAAS1B,EAAU,EAAsB,CAExC,OAAOH,EAAO,GACf,CAEA,SAASY,EAAS,EAAsB,CAEvC,OAAON,EAAK,GACb,CAEA,SAASG,EAAU,EAA4B,CAE9C,OAAOH,EAAK,GACb,CAEA,SAASL,EAAO,EAAuB,CAEtC,OAAOD,EAAO,GACf,C"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { KNode } from "./types.mjs";
|
|
2
|
+
import { GenericValidator } from "convex/values";
|
|
3
|
+
/**
|
|
4
|
+
* Build the input-side native validator for a chain record in one walk to its root. The root's validator
|
|
5
|
+
* is memoised on the root, so check records reuse it; `nullable` wraps it and `optional`/`default` make it
|
|
6
|
+
* optional. Transform and pipe records keep their input schema's validator.
|
|
7
|
+
*/
|
|
8
|
+
export declare function compileNative(node: KNode): GenericValidator;
|
|
9
|
+
/**
|
|
10
|
+
* Build the output-side native validator: a defaulted chain is required, a transform is `v.any()` and a
|
|
11
|
+
* pipe is its target's output side. A chain whose output side equals its input side returns the very
|
|
12
|
+
* same validator instance.
|
|
13
|
+
*/
|
|
14
|
+
export declare function compileOutput(node: KNode): GenericValidator;
|
|
15
|
+
/** The members of a union or discriminated union root. */
|
|
16
|
+
export declare function membersOf(root: KNode): readonly KNode[];
|
|
17
|
+
//# sourceMappingURL=compile.d.mts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{v as e}from"convex/values";const t=e.null(),n=e.any();function r(n){let r=!1,i=!1,a=n;for(;a.prev!==null;)a.op===`optional`||a.op===`partial`||a.op==="default"?r=!0:a.op===`nullable`&&(i=!0),a=a.prev;let o=a.native??=l(a);return i&&(o=e.union(o,t)),r?e.optional(o):o}function i(e){return o(e,!1)}function a(e){return e.op===`union`?e.arg:e.arg.options}function o(r,i){if(r.prev===null)return c(r);let a,o=!1,l=!1,u,f=r;for(;u===void 0;){if(f.prev===null){u=s(f),u!==f.validator&&(l=!0);break}f.op===`optional`||f.op===`partial`?a??=!0:f.op==="default"?(a??=!1,l=!0):f.op===`nullable`?o=!0:f.op===`transform`?(u=n,l=!0):f.op===`pipe`&&(u=d(f.arg),l=!0),f=f.prev}return!l&&!i?r.validator:(o&&(u=e.union(u,t)),a===!0&&!i?e.optional(u):u)}function s(e){return e.outputNative??=i(e)}function c(t){switch(t.op){case`object`:{let n=t.arg,r={},i=!1;for(let e in n){let t=n[e],a=s(t);a!==t.validator&&(i=!0),r[e]=a}return i?e.object(r):t.validator}case`array`:{let n=t.arg,r=d(n);return r===u(n)?t.validator:e.array(r)}case`record`:{let[n,r]=t.arg,i=d(r);return i===u(r)?t.validator:e.record(u(n),i)}case`union`:case`discriminatedUnion`:{let n=a(t),r=[],i=!1;for(let e of n){let t=d(e);t!==u(e)&&(i=!0),r.push(t)}return i?e.union(...r):t.validator}default:return t.validator}}function l(t){switch(t.op){case`string`:case`isoDate`:case`isoDateTime`:return e.string();case`number`:case`int`:case`timestamp`:return e.number();case`int64`:return e.int64();case`boolean`:return e.boolean();case`null`:return e.null();case`bytes`:return e.bytes();case`any`:return e.any();case`json`:return e.union(e.string(),e.number(),e.boolean(),e.null(),e.array(e.any()),e.record(e.string(),e.any()));case`literal`:return e.literal(t.arg);case`id`:return e.id(t.arg);case`enum`:return p(t.arg);case`array`:return e.array(u(t.arg));case`object`:return e.object(m(t.arg));case`record`:{let[n,r]=t.arg;return e.record(u(n),u(r))}case`union`:case`discriminatedUnion`:return e.union(...a(t).map(u));default:throw Error(`k: '${t.op}' is not a root operation`)}}function u(e){let t=e.validator;return t.isOptional===`optional`?f(e):t}function d(e){let t=s(e);return t.isOptional===`optional`?o(e,!0):t}function f(n){let r=!1,i=n;for(;i.prev!==null;)i.op===`nullable`&&(r=!0),i=i.prev;let a=i.validator;return r?e.union(a,t):a}function p(t){let n=[];for(let r of t)n.push(e.literal(r));return e.union(...n)}function m(e){let t={};for(let n in e)t[n]=e[n].validator;return t}export{r as compileNative,i as compileOutput,a as membersOf};
|
|
2
|
+
//# sourceMappingURL=compile.mjs.map
|