@prisma-next/framework-components 0.5.0-dev.8 → 0.5.0-dev.81

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.
Files changed (94) hide show
  1. package/README.md +53 -4
  2. package/dist/authoring.d.mts +2 -2
  3. package/dist/authoring.mjs +2 -122
  4. package/dist/codec-m_-FAyQn.d.mts +168 -0
  5. package/dist/codec-m_-FAyQn.d.mts.map +1 -0
  6. package/dist/codec.d.mts +48 -2
  7. package/dist/codec.d.mts.map +1 -0
  8. package/dist/codec.mjs +67 -4
  9. package/dist/codec.mjs.map +1 -1
  10. package/dist/components.d.mts +1 -1
  11. package/dist/components.mjs +2 -3
  12. package/dist/control.d.mts +420 -74
  13. package/dist/control.d.mts.map +1 -1
  14. package/dist/control.mjs +83 -49
  15. package/dist/control.mjs.map +1 -1
  16. package/dist/emission-types-BKa4bR9m.d.mts +39 -0
  17. package/dist/emission-types-BKa4bR9m.d.mts.map +1 -0
  18. package/dist/emission.d.mts +2 -2
  19. package/dist/emission.mjs +1 -1
  20. package/dist/execution.d.mts +5 -5
  21. package/dist/execution.d.mts.map +1 -1
  22. package/dist/execution.mjs +4 -6
  23. package/dist/execution.mjs.map +1 -1
  24. package/dist/{framework-authoring-D1-JZ37B.d.mts → framework-authoring-DGIQbNPt.d.mts} +43 -12
  25. package/dist/framework-authoring-DGIQbNPt.d.mts.map +1 -0
  26. package/dist/framework-authoring-DxXcjyJX.mjs +209 -0
  27. package/dist/framework-authoring-DxXcjyJX.mjs.map +1 -0
  28. package/dist/{framework-components-DFZMi2h7.d.mts → framework-components-BGo7HsbL.d.mts} +45 -55
  29. package/dist/framework-components-BGo7HsbL.d.mts.map +1 -0
  30. package/dist/{framework-components-C8ZhSwXe.mjs → framework-components-FdqmlGUj.mjs} +3 -3
  31. package/dist/framework-components-FdqmlGUj.mjs.map +1 -0
  32. package/dist/psl-ast-Ckn_G-jv.d.mts +159 -0
  33. package/dist/psl-ast-Ckn_G-jv.d.mts.map +1 -0
  34. package/dist/psl-ast.d.mts +2 -0
  35. package/dist/psl-ast.mjs +1 -0
  36. package/dist/runtime.d.mts +395 -19
  37. package/dist/runtime.d.mts.map +1 -1
  38. package/dist/runtime.mjs +256 -7
  39. package/dist/runtime.mjs.map +1 -1
  40. package/dist/{types-import-spec-C4sc7wbb.d.mts → types-import-spec-BxI5cSQy.d.mts} +2 -2
  41. package/dist/types-import-spec-BxI5cSQy.d.mts.map +1 -0
  42. package/package.json +10 -6
  43. package/src/control/control-capabilities.ts +96 -0
  44. package/src/{control-descriptors.ts → control/control-descriptors.ts} +7 -7
  45. package/src/{control-instances.ts → control/control-instances.ts} +52 -6
  46. package/src/{control-migration-types.ts → control/control-migration-types.ts} +251 -63
  47. package/src/control/control-operation-preview.ts +23 -0
  48. package/src/control/control-spaces.ts +82 -0
  49. package/src/{control-stack.ts → control/control-stack.ts} +77 -94
  50. package/src/control/emission-types.ts +49 -0
  51. package/src/control/psl-ast.ts +193 -0
  52. package/src/{execution-descriptors.ts → execution/execution-descriptors.ts} +7 -7
  53. package/src/{execution-instances.ts → execution/execution-instances.ts} +1 -1
  54. package/src/{execution-requirements.ts → execution/execution-requirements.ts} +1 -1
  55. package/src/execution/query-plan.ts +53 -0
  56. package/src/execution/race-against-abort.ts +89 -0
  57. package/src/execution/run-with-middleware.ts +153 -0
  58. package/src/execution/runtime-core.ts +133 -0
  59. package/src/execution/runtime-error.ts +94 -0
  60. package/src/execution/runtime-middleware.ts +235 -0
  61. package/src/exports/authoring.ts +5 -2
  62. package/src/exports/codec.ts +27 -2
  63. package/src/exports/components.ts +2 -2
  64. package/src/exports/control.ts +41 -13
  65. package/src/exports/emission.ts +2 -2
  66. package/src/exports/execution.ts +5 -5
  67. package/src/exports/psl-ast.ts +1 -0
  68. package/src/exports/runtime.ts +18 -5
  69. package/src/shared/codec-descriptor.ts +87 -0
  70. package/src/shared/codec-types.ts +79 -0
  71. package/src/shared/codec.ts +80 -0
  72. package/src/shared/column-spec.ts +83 -0
  73. package/src/{framework-authoring.ts → shared/framework-authoring.ts} +210 -23
  74. package/src/{framework-components.ts → shared/framework-components.ts} +22 -48
  75. package/src/{mutation-default-types.ts → shared/mutation-default-types.ts} +22 -2
  76. package/dist/authoring.mjs.map +0 -1
  77. package/dist/codec-types-DQ1Agjom.d.mts +0 -58
  78. package/dist/codec-types-DQ1Agjom.d.mts.map +0 -1
  79. package/dist/emission-types-BPAALJbF.d.mts +0 -24
  80. package/dist/emission-types-BPAALJbF.d.mts.map +0 -1
  81. package/dist/framework-authoring-D1-JZ37B.d.mts.map +0 -1
  82. package/dist/framework-components-C8ZhSwXe.mjs.map +0 -1
  83. package/dist/framework-components-DFZMi2h7.d.mts.map +0 -1
  84. package/dist/types-import-spec-C4sc7wbb.d.mts.map +0 -1
  85. package/src/codec-types.ts +0 -64
  86. package/src/control-capabilities.ts +0 -34
  87. package/src/emission-types.ts +0 -28
  88. package/src/runtime-error.ts +0 -55
  89. package/src/runtime-middleware.ts +0 -83
  90. /package/src/{control-result-types.ts → control/control-result-types.ts} +0 -0
  91. /package/src/{control-schema-view.ts → control/control-schema-view.ts} +0 -0
  92. /package/src/{async-iterable-result.ts → execution/async-iterable-result.ts} +0 -0
  93. /package/src/{execution-stack.ts → execution/execution-stack.ts} +0 -0
  94. /package/src/{types-import-spec.ts → shared/types-import-spec.ts} +0 -0
@@ -1,21 +1,34 @@
1
- export type { MigratableTargetDescriptor, SchemaViewCapable } from '../control-capabilities';
2
- export { hasMigrations, hasSchemaView } from '../control-capabilities';
1
+ export type { ImportRequirement } from '@prisma-next/ts-render';
2
+ export type {
3
+ MigratableTargetDescriptor,
4
+ OperationPreviewCapable,
5
+ PslContractInferCapable,
6
+ SchemaViewCapable,
7
+ } from '../control/control-capabilities';
8
+ export {
9
+ hasMigrations,
10
+ hasMultiSpaceRunner,
11
+ hasOperationPreview,
12
+ hasPslContractInfer,
13
+ hasSchemaView,
14
+ } from '../control/control-capabilities';
3
15
  export type {
4
16
  ControlAdapterDescriptor,
5
17
  ControlDriverDescriptor,
6
18
  ControlExtensionDescriptor,
7
19
  ControlFamilyDescriptor,
8
20
  ControlTargetDescriptor,
9
- } from '../control-descriptors';
21
+ } from '../control/control-descriptors';
10
22
  export type {
11
23
  ControlAdapterInstance,
12
24
  ControlDriverInstance,
13
25
  ControlExtensionInstance,
14
26
  ControlFamilyInstance,
15
27
  ControlTargetInstance,
16
- } from '../control-instances';
28
+ } from '../control/control-instances';
17
29
  export type {
18
- DataTransformOperation,
30
+ MigrationHints,
31
+ MigrationMetadata,
19
32
  MigrationOperationClass,
20
33
  MigrationOperationPolicy,
21
34
  MigrationPlan,
@@ -32,10 +45,19 @@ export type {
32
45
  MigrationRunnerResult,
33
46
  MigrationRunnerSuccessValue,
34
47
  MigrationScaffoldContext,
48
+ MultiSpaceCapableRunner,
49
+ MultiSpaceRunnerFailure,
50
+ MultiSpaceRunnerPerSpaceOptions,
51
+ MultiSpaceRunnerResult,
52
+ MultiSpaceRunnerSuccessValue,
35
53
  OpFactoryCall,
36
54
  SerializedQueryPlan,
37
55
  TargetMigrationsCapability,
38
- } from '../control-migration-types';
56
+ } from '../control/control-migration-types';
57
+ export type {
58
+ OperationPreview,
59
+ OperationPreviewStatement,
60
+ } from '../control/control-operation-preview';
39
61
  export type {
40
62
  BaseSchemaIssue,
41
63
  EmitContractResult,
@@ -47,25 +69,31 @@ export type {
47
69
  SignDatabaseResult,
48
70
  VerifyDatabaseResult,
49
71
  VerifyDatabaseSchemaResult,
50
- } from '../control-result-types';
72
+ } from '../control/control-result-types';
51
73
  export {
52
74
  VERIFY_CODE_HASH_MISMATCH,
53
75
  VERIFY_CODE_MARKER_MISSING,
54
76
  VERIFY_CODE_SCHEMA_FAILURE,
55
77
  VERIFY_CODE_TARGET_MISMATCH,
56
- } from '../control-result-types';
78
+ } from '../control/control-result-types';
57
79
  export type {
58
80
  CoreSchemaView,
59
81
  SchemaNodeKind,
60
82
  SchemaTreeNodeOptions,
61
83
  SchemaTreeVisitor,
62
- } from '../control-schema-view';
63
- export { SchemaTreeNode } from '../control-schema-view';
84
+ } from '../control/control-schema-view';
85
+ export { SchemaTreeNode } from '../control/control-schema-view';
86
+ export type {
87
+ ContractSpace,
88
+ ContractSpaceHeadRef,
89
+ MigrationPackage,
90
+ } from '../control/control-spaces';
91
+ export { APP_SPACE_ID } from '../control/control-spaces';
64
92
  export type {
65
93
  AssembledAuthoringContributions,
66
94
  ControlStack,
67
95
  CreateControlStackInput,
68
- } from '../control-stack';
96
+ } from '../control/control-stack';
69
97
  export {
70
98
  assembleAuthoringContributions,
71
99
  assembleControlMutationDefaults,
@@ -77,7 +105,7 @@ export {
77
105
  extractComponentIds,
78
106
  extractOperationTypeImports,
79
107
  extractQueryOperationTypeImports,
80
- } from '../control-stack';
108
+ } from '../control/control-stack';
81
109
  export type {
82
110
  ControlMutationDefaultEntry,
83
111
  ControlMutationDefaultRegistry,
@@ -92,4 +120,4 @@ export type {
92
120
  ParsedDefaultFunctionCall,
93
121
  SourceDiagnostic,
94
122
  SourceSpan,
95
- } from '../mutation-default-types';
123
+ } from '../shared/mutation-default-types';
@@ -2,5 +2,5 @@ export type {
2
2
  EmissionSpi,
3
3
  GenerateContractTypesOptions,
4
4
  ValidationContext,
5
- } from '../emission-types';
6
- export type { TypesImportSpec } from '../types-import-spec';
5
+ } from '../control/emission-types';
6
+ export type { TypesImportSpec } from '../shared/types-import-spec';
@@ -4,14 +4,14 @@ export type {
4
4
  RuntimeExtensionDescriptor,
5
5
  RuntimeFamilyDescriptor,
6
6
  RuntimeTargetDescriptor,
7
- } from '../execution-descriptors';
7
+ } from '../execution/execution-descriptors';
8
8
  export type {
9
9
  RuntimeAdapterInstance,
10
10
  RuntimeDriverInstance,
11
11
  RuntimeExtensionInstance,
12
12
  RuntimeFamilyInstance,
13
13
  RuntimeTargetInstance,
14
- } from '../execution-instances';
15
- export { assertRuntimeContractRequirementsSatisfied } from '../execution-requirements';
16
- export type { ExecutionStack, ExecutionStackInstance } from '../execution-stack';
17
- export { createExecutionStack, instantiateExecutionStack } from '../execution-stack';
14
+ } from '../execution/execution-instances';
15
+ export { assertRuntimeContractRequirementsSatisfied } from '../execution/execution-requirements';
16
+ export type { ExecutionStack, ExecutionStackInstance } from '../execution/execution-stack';
17
+ export { createExecutionStack, instantiateExecutionStack } from '../execution/execution-stack';
@@ -0,0 +1 @@
1
+ export * from '../control/psl-ast';
@@ -1,11 +1,24 @@
1
- export { AsyncIterableResult } from '../async-iterable-result';
2
- export type { RuntimeErrorEnvelope } from '../runtime-error';
3
- export { isRuntimeError, runtimeError } from '../runtime-error';
1
+ export { AsyncIterableResult } from '../execution/async-iterable-result';
2
+ export type { ExecutionPlan, QueryPlan, ResultType } from '../execution/query-plan';
3
+ export { checkAborted, raceAgainstAbort } from '../execution/race-against-abort';
4
+ export { runWithMiddleware } from '../execution/run-with-middleware';
5
+ export type { RuntimeCoreOptions } from '../execution/runtime-core';
6
+ export { RuntimeCore } from '../execution/runtime-core';
7
+ export type { RuntimeAbortedPhase, RuntimeErrorEnvelope } from '../execution/runtime-error';
8
+ export {
9
+ isRuntimeError,
10
+ RUNTIME_ABORTED,
11
+ runtimeAborted,
12
+ runtimeError,
13
+ } from '../execution/runtime-error';
4
14
  export type {
5
15
  AfterExecuteResult,
16
+ InterceptResult,
17
+ ParamRefMutator,
18
+ RuntimeExecuteOptions,
6
19
  RuntimeExecutor,
7
20
  RuntimeLog,
8
21
  RuntimeMiddleware,
9
22
  RuntimeMiddlewareContext,
10
- } from '../runtime-middleware';
11
- export { checkMiddlewareCompatibility } from '../runtime-middleware';
23
+ } from '../execution/runtime-middleware';
24
+ export { checkMiddlewareCompatibility } from '../execution/runtime-middleware';
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Codec descriptor interface (consumer surface) and abstract `CodecDescriptorImpl` base (codec-author surface).
3
+ *
4
+ * Consumers depend on the {@link CodecDescriptor} interface — it is the codec-id-keyed source of truth for static metadata (`traits`, `targetTypes`, `meta`) and registration concerns (`paramsSchema`; optional `renderOutputType`). The runtime `Codec` instance returned by `factory(params)(ctx)` carries only the conversion behavior.
5
+ *
6
+ * Codec authors `extend` the {@link CodecDescriptorImpl} abstract class to declare their codec id, traits, target types, params schema, the `factory(params)` that materializes a typed `Codec<...>`, and (optionally) a `renderOutputType(params)` for the emit path.
7
+ *
8
+ * The factory's method-level generic is the load-bearing piece for literal preservation: per-codec column helpers invoke `descriptor.factory(...)` *directly*, and the direct call binds the generic at its call site. Type extraction (`ReturnType<D['factory']>`, structural matching) widens method generics to their constraint — that's why the column-helper surface is per-codec, not polymorphic.
9
+ */
10
+
11
+ import type { StandardSchemaV1 } from '@standard-schema/spec';
12
+ import type { Codec } from './codec';
13
+ import {
14
+ type CodecInstanceContext,
15
+ type CodecMeta,
16
+ type CodecTrait,
17
+ voidParamsSchema,
18
+ } from './codec-types';
19
+
20
+ /**
21
+ * Unified codec descriptor. Every codec in the framework registers through this shape — non-parameterized codecs use `P = void` and a constant factory that returns the same shared codec instance for every column; parameterized codecs use a non-empty `P` and a curried higher-order factory that returns a per-instance codec.
22
+ *
23
+ * The descriptor is the codec-id-keyed source of truth for static metadata (`traits`, `targetTypes`, `meta`) and registration concerns (`paramsSchema` for JSON-boundary validation; optional `renderOutputType` for the `contract.d.ts` emit path). The runtime `Codec` instance returned by `factory(params)(ctx)` carries only the conversion behavior.
24
+ *
25
+ * Whether a codec id "is parameterized" stops being a registration-time distinction — it's a property of `P` on the descriptor. The descriptor map indexes every descriptor by `codecId`; both `descriptorFor(codecId)` and `forColumn(table, column)` resolve through the same map without branching on parameterization.
26
+ *
27
+ * @template P - The shape of the params accepted by the factory (`void` for non-parameterized codecs; a record like `{ length: number }` for parameterized codecs).
28
+ *
29
+ * Codec-registry-unification project § Decision.
30
+ */
31
+ export interface CodecDescriptor<P = void> {
32
+ /** The codec ID this descriptor applies to (e.g. `pg/vector@1`, `pg/text@1`). */
33
+ readonly codecId: string;
34
+ /** Semantic traits for operator gating (e.g. equality, order, numeric). */
35
+ readonly traits: readonly CodecTrait[];
36
+ /** Database-native type names this codec handles (e.g. `['timestamptz']`). */
37
+ readonly targetTypes: readonly string[];
38
+ /** Optional family-specific metadata (e.g. SQL-side `db.sql.postgres.nativeType`). */
39
+ readonly meta?: CodecMeta;
40
+ /** Standard Schema validator for the factory's params. Validates JSON-sourced params at the contract boundary (PSL → IR; `contract.json` → runtime). For non-parameterized codecs (`P = void`), the schema validates `void`/`undefined` — the framework supplies no params at the call boundary. */
41
+ readonly paramsSchema: StandardSchemaV1<P>;
42
+ /** Whether this descriptor is parameterized — i.e. its `paramsSchema` is something other than the singleton `voidParamsSchema`. Consumers that need to gate column-aware dispatch (e.g. the `validateParamRefRefs` AST-builder pass) read this directly rather than threading a free-floating `(codecId) => boolean` callback. */
43
+ readonly isParameterized: boolean;
44
+ /** Emit-path string renderer for `contract.d.ts`. Returns the TypeScript output type expression for given params (e.g. `Vector<1536>`). Optional; absent renderers cause the emitter to fall back to the codec's base output type. Non-parameterized codecs typically omit it. */
45
+ readonly renderOutputType?: (params: P) => string | undefined;
46
+ /** The curried higher-order codec. For non-parameterized codecs, the factory is constant — every call returns the same shared codec instance. For parameterized codecs, the factory is called once per `storage.types` instance (or once per inline-`typeParams` column), with `ctx` carrying the column set the resulting codec serves. */
47
+ readonly factory: (params: P) => (ctx: CodecInstanceContext) => Codec;
48
+ }
49
+
50
+ /**
51
+ * Variance-erased {@link CodecDescriptor} alias. `CodecDescriptor<P>` is invariant in `P` (the `factory` and `renderOutputType` slots use `P` contravariantly), so `CodecDescriptor<P>` does not extend `CodecDescriptor<unknown>` for specific `P`. Heterogeneous descriptor collections — e.g. `SqlStaticContributions.codecs:` returning a list that mixes parameterized and non-parameterized descriptors — type against this alias and narrow per codec id at the consumer.
52
+ *
53
+ * Codec-registry-unification spec § Decision: every codec resolves through one descriptor map; reads are non-branching.
54
+ */
55
+ // biome-ignore lint/suspicious/noExplicitAny: variance erasure for heterogeneous descriptor collections
56
+ export type AnyCodecDescriptor = CodecDescriptor<any>;
57
+
58
+ /**
59
+ * Abstract base class for concrete codec descriptors.
60
+ *
61
+ * Codec authors extend this class with their typed `TParams` and declare `codecId`, `traits`, `targetTypes`, `paramsSchema`, the curried `factory(params)`, and (optionally) `renderOutputType`.
62
+ *
63
+ * Implements the {@link CodecDescriptor} interface so a concrete subclass instance is directly usable wherever the framework expects a `CodecDescriptor<P>`.
64
+ */
65
+ export abstract class CodecDescriptorImpl<TParams = void> implements CodecDescriptor<TParams> {
66
+ abstract readonly codecId: string;
67
+ abstract readonly traits: readonly CodecTrait[];
68
+ abstract readonly targetTypes: readonly string[];
69
+ readonly meta?: CodecMeta;
70
+
71
+ abstract readonly paramsSchema: StandardSchemaV1<TParams>;
72
+
73
+ /** Boolean derived from `paramsSchema`: `true` whenever the schema is not the singleton `voidParamsSchema`. The framework registry's `validateParamRefRefs` pass reads this through `descriptorFor(codecId).isParameterized` to gate column-ref enforcement. */
74
+ get isParameterized(): boolean {
75
+ return this.paramsSchema !== voidParamsSchema;
76
+ }
77
+
78
+ /** Optional emit-path string renderer for `contract.d.ts`. Returns the TypeScript output type expression for the given params (e.g. `Vector<1536>`). Non-parameterized codecs typically omit it. */
79
+ renderOutputType?(params: TParams): string | undefined;
80
+
81
+ /**
82
+ * Materialize a curried codec factory for the given params. Concrete subclasses override with a typed return type (e.g. `factory<N>(params: { length: N }): (ctx) => VectorCodec<N>`); per-codec helpers read the typed return at the *direct* call site, which is what preserves method-level generics. Type extraction (e.g. `ReturnType<D['factory']>`) widens method generics to their constraint — that's why the column-helper surface is per-codec, not polymorphic.
83
+ */
84
+ abstract factory(
85
+ params: TParams,
86
+ ): (ctx: CodecInstanceContext) => Codec<string, readonly CodecTrait[], unknown, unknown>;
87
+ }
@@ -0,0 +1,79 @@
1
+ import type { StandardSchemaV1 } from '@standard-schema/spec';
2
+ import type { Codec } from './codec';
3
+
4
+ export type CodecTrait = 'equality' | 'order' | 'boolean' | 'numeric' | 'textual';
5
+
6
+ /**
7
+ * Per-call context the runtime threads to every `codec.encode` / `codec.decode` invocation for a single `runtime.execute()` call.
8
+ *
9
+ * The framework-level shape is family-agnostic and carries one field:
10
+ *
11
+ * - `signal?: AbortSignal` — per-query cancellation. The runtime returns a `RUNTIME.ABORTED` envelope when the signal aborts; codec authors who forward `signal` to their underlying SDK get true cancellation of in-flight network calls.
12
+ *
13
+ * Family layers extend this base with their own shape-of-call metadata: the SQL family adds `column?: SqlColumnRef` via `SqlCodecCallContext` (see `@prisma-next/sql-relational-core`). Mongo currently uses this framework type unchanged. Column metadata is intentionally **not** on the framework type — it is a SQL-family concept rooted in SQL's `(table, column)` addressing model and would not generalise to other families.
14
+ *
15
+ * The interface is named explicitly (not inlined) so future framework fields and family extensions can land additively without breaking codec author signatures.
16
+ */
17
+ export interface CodecCallContext {
18
+ readonly signal?: AbortSignal;
19
+ }
20
+
21
+ /**
22
+ * Codec-id-keyed read surface threaded into emit and authoring paths.
23
+ *
24
+ * - `get(id)` returns the runtime {@link Codec} instance for the codec id (used by `validateContract` for `decodeJson` of literal column defaults).
25
+ * - `targetTypesFor(id)` exposes the codec-id-keyed `targetTypes` metadata the runtime instance no longer carries (TML-2357). Returns the same array `CodecDescriptor.targetTypes` would; for Mongo (whose registration doesn't yet resolve through the unified descriptor map — TML-2324) the family-side assembly populates this directly from the contributor's codec metadata.
26
+ * - `metaFor(id)` exposes the codec-id-keyed `meta` (e.g. SQL-side `db.sql.postgres.nativeType`) the runtime instance no longer carries.
27
+ * - `renderOutputTypeFor(id, params)` exposes the codec-id-keyed `renderOutputType` renderer the runtime instance no longer carries. Returns `undefined` when the codec doesn't render a custom type or when the codec id is unknown.
28
+ */
29
+ export interface CodecLookup {
30
+ get(id: string): Codec | undefined;
31
+ targetTypesFor(id: string): readonly string[] | undefined;
32
+ metaFor(id: string): CodecMeta | undefined;
33
+ renderOutputTypeFor(id: string, params: Record<string, unknown>): string | undefined;
34
+ }
35
+
36
+ export const emptyCodecLookup: CodecLookup = {
37
+ get: () => undefined,
38
+ targetTypesFor: () => undefined,
39
+ metaFor: () => undefined,
40
+ renderOutputTypeFor: () => undefined,
41
+ };
42
+
43
+ /**
44
+ * Family-agnostic per-instance context supplied by the framework when applying a higher-order codec factory. Allows stateful codecs (e.g. column-scoped encryption) to derive per-instance state from the materialization site.
45
+ *
46
+ * - `name` — the family-agnostic instance identity. For SQL, the runtime populates this as the `storage.types` instance name (e.g. `Embedding1536`) for typeRef-shaped columns, the synthesized anonymous instance name (`<anon:Document.embedding>`) for inline-`typeParams` columns, or a shared sentinel (`<shared:pg/text@1>`) for non-parameterized codec ids. Other families pick the analogous identity for their materialization sites.
47
+ *
48
+ * Family-specific extensions (e.g. {@link import('@prisma-next/sql-relational-core/ast').SqlCodecInstanceContext} in the SQL layer) augment this base with domain-shaped column-set metadata. Codec authors target the base when they don't read family-specific metadata; they target the family extension when they do.
49
+ */
50
+ export interface CodecInstanceContext {
51
+ readonly name: string;
52
+ }
53
+
54
+ /**
55
+ * Family-agnostic codec metadata. Family-specific extensions augment the base `db.<family>.<target>` block with native-type information; the base shape is an empty object so non-relational codecs can carry no metadata.
56
+ */
57
+ export interface CodecMeta {
58
+ readonly db?: Record<string, unknown>;
59
+ }
60
+
61
+ /**
62
+ * Standard Schema validator for `void` params. Accepts only `undefined` (or absent input); rejects any other value so a contract that tries to thread `typeParams` through a non-parameterized codec id fails fast at the JSON boundary instead of silently coercing the value away. Used by the framework-supplied non-parameterized descriptor synthesizer.
63
+ */
64
+ export const voidParamsSchema: StandardSchemaV1<void> = {
65
+ '~standard': {
66
+ version: 1,
67
+ vendor: 'prisma-next',
68
+ validate: (input) =>
69
+ input === undefined
70
+ ? { value: undefined }
71
+ : {
72
+ issues: [
73
+ {
74
+ message: 'unexpected typeParams for non-parameterized codec (void params expected)',
75
+ },
76
+ ],
77
+ },
78
+ },
79
+ };
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Codec interface (consumer surface) and abstract `CodecImpl` base (codec-author surface).
3
+ *
4
+ * Consumers depend on the {@link Codec} interface — it describes the runtime instance returned by a descriptor's curried factory and is what the framework threads through emit, validate, and execute paths.
5
+ *
6
+ * Codec authors `extend` the {@link CodecImpl} abstract class to declare a typed runtime codec instance. The class carries a variance-erased descriptor reference (`CodecDescriptor<any>`); `id` proxies through the descriptor so one source of truth governs both metadata reads and aliasing semantics (alias subclasses inherit the descriptor's id automatically).
7
+ *
8
+ * Class generic shape: `Id`, `TTraits`, `TWire`, `TInput`. Method generics on the codec subclass's own surface (e.g. arktype-json's schema generic, pgvector's dimension generic) flow through the subclass's constructor and propagate via the descriptor's typed `factory(params)` return at *direct* call sites.
9
+ */
10
+
11
+ import type { JsonValue } from '@prisma-next/contract/types';
12
+ import type { CodecDescriptor } from './codec-descriptor';
13
+ import type { CodecCallContext, CodecTrait } from './codec-types';
14
+
15
+ /**
16
+ * A codec is the contract between an application value and its on-wire and on-contract-disk representations.
17
+ *
18
+ * The author's mental model is two JS-side types — `TInput` (the application JS type) and `TWire` (the database driver wire format) — plus `JsonValue` for build-time contract artifacts. The codec translates `TInput` to `TWire` on writes and back on reads, and to/from `JsonValue` during contract emission and loading.
19
+ *
20
+ * Three representations participate:
21
+ * - **Input** (`TInput`): the JS type at the application boundary.
22
+ * - **Wire** (`TWire`): the format exchanged with the database driver.
23
+ * - **JSON** (`JsonValue`): a JSON-safe form used in contract artifacts.
24
+ *
25
+ * The runtime instance carries only its `id` (the descriptor's `codecId`, set by the factory) and the four conversion methods. Static metadata (`traits`, `targetTypes`, `meta`) and the build-time `renderOutputType` renderer live on the {@link CodecDescriptor} keyed by `codecId` — the read-surface single source of truth. Consumers that need them resolve through `descriptorFor(codecId)`.
26
+ *
27
+ * Codec methods split into two groups:
28
+ *
29
+ * - **Query-time** methods (`encode`, `decode`) run per row/parameter at the IO boundary; they are required and Promise-returning. The per-family codec factory accepts sync or async author functions and lifts sync ones to Promise-shaped methods automatically.
30
+ * - **Build-time** methods (`encodeJson`, `decodeJson`) run when the contract is serialized or loaded. They stay synchronous so contract validation and client construction are synchronous.
31
+ *
32
+ * Target-family codec interfaces extend this base; family-specific concerns (e.g. the SQL `column?` per-call context) layer on through the `CodecCallContext` extension pattern.
33
+ */
34
+ export interface Codec<
35
+ Id extends string = string,
36
+ TTraits extends readonly CodecTrait[] = readonly CodecTrait[],
37
+ TWire = unknown,
38
+ TInput = unknown,
39
+ > {
40
+ /** Unique codec identifier in `namespace/name@version` format (e.g. `pg/timestamptz@1`). The factory sets this to the descriptor's `codecId`; consumers use it as a back-reference for descriptor lookups and for decode-error diagnostics. */
41
+ readonly id: Id;
42
+ /** Phantom carrier for the `TTraits` generic; type-only, undefined at runtime. Runtime traits live on {@link CodecDescriptor.traits}. Implemented as a string-key phantom (`__codecTraits`) rather than `unique symbol` so bundlers that split `.d.ts` chunks do not strand symbol identity on chunk-private paths (the same `TS2742` family that the public re-export of `CodecTypes` works around). */
43
+ readonly __codecTraits?: TTraits;
44
+ /** Converts a JS value to the wire format expected by the database driver. Always Promise-returning at the boundary. The {@link CodecCallContext} is supplied by the runtime on every call (allocated once per `runtime.execute()`); family layers may narrow the ctx to extend it (e.g. SQL adds `column`). Author-side single-arg `(value) => …` functions remain legal via TypeScript's bivariance for trailing parameters. */
45
+ encode(value: TInput, ctx: CodecCallContext): Promise<TWire>;
46
+ /** Converts a wire value from the database driver into the JS application type. Always Promise-returning at the boundary. The {@link CodecCallContext} is supplied by the runtime on every call (allocated once per `runtime.execute()`); family layers may narrow the ctx to extend it (e.g. SQL adds `column`). Author-side single-arg `(wire) => …` functions remain legal via TypeScript's bivariance for trailing parameters. */
47
+ decode(wire: TWire, ctx: CodecCallContext): Promise<TInput>;
48
+ /** Converts a JS value to a JSON-safe representation for contract serialization. Synchronous; called during contract emission. */
49
+ encodeJson(value: TInput): JsonValue;
50
+ /** Converts a JSON representation back to the JS input type. Synchronous; called during contract loading via `validateContract`. */
51
+ decodeJson(json: JsonValue): TInput;
52
+ }
53
+
54
+ /**
55
+ * Abstract base class for concrete codec implementations.
56
+ *
57
+ * Codec authors extend this class with their typed `Id`, `TTraits`, `TWire`, `TInput` and override `encode`/`decode` (and optionally `encodeJson`/`decodeJson`). The runtime instance carries only its `id` (proxied through the descriptor so alias subclasses inherit the descriptor's id automatically) and the conversion methods — static metadata lives on the {@link CodecDescriptor}.
58
+ */
59
+ export abstract class CodecImpl<
60
+ Id extends string = string,
61
+ TTraits extends readonly CodecTrait[] = readonly CodecTrait[],
62
+ TWire = unknown,
63
+ TInput = unknown,
64
+ > implements Codec<Id, TTraits, TWire, TInput>
65
+ {
66
+ /**
67
+ * Variance-erased descriptor reference. Concrete codec subclasses receive the typed descriptor in their own constructors and forward it via `super(descriptor)`; the variance erasure lives at this base because the abstract surface can't carry the concrete `TParams`.
68
+ */
69
+ // biome-ignore lint/suspicious/noExplicitAny: variance-erased descriptor reference; subclasses retain typed access via their own state
70
+ constructor(public readonly descriptor: CodecDescriptor<any>) {}
71
+
72
+ get id(): Id {
73
+ return this.descriptor.codecId as Id;
74
+ }
75
+
76
+ abstract encode(value: TInput, ctx: CodecCallContext): Promise<TWire>;
77
+ abstract decode(wire: TWire, ctx: CodecCallContext): Promise<TInput>;
78
+ abstract encodeJson(value: TInput): JsonValue;
79
+ abstract decodeJson(json: JsonValue): TInput;
80
+ }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * `column()` packager + `ColumnSpec<R, P>` shape + `ColumnHelperFor<D>` variants for tying per-codec column helpers to their descriptor.
3
+ *
4
+ * `ColumnSpec<R, P>` extends {@link ColumnTypeDescriptor} so it remains a drop-in for contract authoring sites that consume `ColumnTypeDescriptor` shapes — both types live at the framework-components layer so the `extends` clause is real (no structural mirror).
5
+ *
6
+ * `column()` is a trivial, non-polymorphic packager. Generic over `R` (the codec instance type returned by the descriptor's curried factory) and `P` (the typeParams record). The framework does NOT try to infer `R` and `P` from a descriptor — that path is the variance trap. Per-codec helpers absorb the descriptor relationship instead and tie themselves to their descriptor via `satisfies ColumnHelperFor<D>` or `satisfies ColumnHelperForStrict<D>`.
7
+ */
8
+
9
+ import type { CodecDescriptor } from './codec-descriptor';
10
+ import type { CodecInstanceContext } from './codec-types';
11
+
12
+ /**
13
+ * Authored column-type descriptor — the data shape an authoring site (PSL or TypeScript builders) attaches to a column to identify its codec and its native database type.
14
+ *
15
+ * Lives at the framework-components layer alongside the codec types so codec-author packages (e.g. column-spec / `column()` packagers) can extend it directly without crossing layer boundaries.
16
+ *
17
+ * @template TCodecId Narrowed codec id literal for sites that thread a specific codec id through the type system.
18
+ */
19
+ export type ColumnTypeDescriptor<TCodecId extends string = string> = {
20
+ readonly codecId: TCodecId;
21
+ readonly nativeType: string;
22
+ readonly typeParams?: Record<string, unknown> | undefined;
23
+ readonly typeRef?: string;
24
+ };
25
+
26
+ /**
27
+ * Column spec carrying the codec factory closure alongside the {@link ColumnTypeDescriptor} fields. Codec authors return a `ColumnSpec` from per-codec column helpers; the runtime materializes the codec instance by calling `codecFactory(ctx)` once it knows the column's `CodecInstanceContext`.
28
+ *
29
+ * Extends {@link ColumnTypeDescriptor} so `ColumnSpec` instances flow directly into contract-authoring sites that consume the descriptor shape — no structural mirroring required.
30
+ */
31
+ export interface ColumnSpec<R, P extends Record<string, unknown> | undefined>
32
+ extends ColumnTypeDescriptor {
33
+ readonly codecFactory: (ctx: CodecInstanceContext) => R;
34
+ readonly typeParams: P;
35
+ }
36
+
37
+ /**
38
+ * Trivial column packager. Per-codec helpers call this directly with the result of `descriptor.factory(params)` — direct method invocation binds the descriptor's method-level generic at the call site and the literal flows through `R`.
39
+ *
40
+ * `nativeType` is the column's database-native type spelling — the value the postgres adapter's migration planner, the SQL renderer's cast policy, and the contract's `meta.db.<family>.<target>.nativeType` slot read. Per-codec helpers pass the literal native-type string for their codec (e.g. `'text'`, `'int4'`, `'character varying'`); for codecs whose native-type spelling depends on parameters (none today; reserved for future shapes), the helper computes the rendered string before calling `column`. The framework does not derive the value from `codecId` — that mapping is target-specific and lives at the helper.
41
+ */
42
+ export function column<R, P extends Record<string, unknown> | undefined>(
43
+ codecFactory: (ctx: CodecInstanceContext) => R,
44
+ codecId: string,
45
+ typeParams: P,
46
+ nativeType: string,
47
+ ): ColumnSpec<R, P> {
48
+ return {
49
+ codecFactory,
50
+ codecId,
51
+ typeParams,
52
+ nativeType,
53
+ };
54
+ }
55
+
56
+ /**
57
+ * Coarse `satisfies` shape — checks the helper's typeParams record matches the descriptor's factory params. Catches "wrong typeParams shape" wiring mistakes; does NOT catch "wrong descriptor's factory" mistakes (the codec slot is left as `unknown`).
58
+ *
59
+ * Use when the codec's `ReturnType<factory>` is unstable (e.g. heavily overloaded factories where extraction widens too much).
60
+ */
61
+ // biome-ignore lint/suspicious/noExplicitAny: variance erasure — `CodecDescriptor<P>` is invariant in P, so concrete subclasses do not extend `CodecDescriptor<unknown>`; matches the existing `AnyCodecDescriptor` pattern
62
+ export type ColumnHelperFor<D extends CodecDescriptor<any>> = (
63
+ // biome-ignore lint/suspicious/noExplicitAny: helper signature is the verification subject; satisfies clauses can't narrow this without circular inference
64
+ ...args: any[]
65
+ ) => ColumnSpec<unknown, ColumnHelperParams<D>>;
66
+
67
+ /**
68
+ * Strict `satisfies` shape — also checks the helper's codec is at least the *base* codec instance type the descriptor's factory returns. `ReturnType<ReturnType<D['factory']>>` widens method generics to their constraint, so this only sanity-checks the wiring at the base type level. Literal preservation comes from the direct `descriptor.factory(...)` call inside the helper, not from `satisfies`.
69
+ */
70
+ // biome-ignore lint/suspicious/noExplicitAny: variance erasure — `CodecDescriptor<P>` is invariant in P, so concrete subclasses do not extend `CodecDescriptor<unknown>`; matches the existing `AnyCodecDescriptor` pattern
71
+ export type ColumnHelperForStrict<D extends CodecDescriptor<any>> = (
72
+ // biome-ignore lint/suspicious/noExplicitAny: helper signature is the verification subject; satisfies clauses can't narrow this without circular inference
73
+ ...args: any[]
74
+ ) => ColumnSpec<ReturnType<ReturnType<D['factory']>>, ColumnHelperParams<D>>;
75
+
76
+ /**
77
+ * Coerce a descriptor's `factory` first parameter into the typeParams shape `ColumnSpec` accepts. Non-parameterized descriptors (factory with no params, or `params: void`) collapse to `undefined`; parameterized descriptors keep the params record shape.
78
+ */
79
+ // biome-ignore lint/suspicious/noExplicitAny: variance erasure — see above
80
+ type ColumnHelperParams<D extends CodecDescriptor<any>> =
81
+ Parameters<D['factory']>[0] extends Record<string, unknown>
82
+ ? Parameters<D['factory']>[0]
83
+ : undefined;