@prisma-next/framework-components 0.5.0-dev.3 → 0.5.0-dev.31

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 (85) hide show
  1. package/README.md +61 -0
  2. package/dist/authoring.d.mts +1 -1
  3. package/dist/authoring.mjs +1 -1
  4. package/dist/authoring.mjs.map +1 -1
  5. package/dist/codec-types-CB0jWeHU.d.mts +207 -0
  6. package/dist/codec-types-CB0jWeHU.d.mts.map +1 -0
  7. package/dist/codec.d.mts +2 -2
  8. package/dist/codec.mjs +38 -2
  9. package/dist/codec.mjs.map +1 -1
  10. package/dist/components.d.mts +1 -1
  11. package/dist/components.mjs +1 -1
  12. package/dist/control.d.mts +80 -27
  13. package/dist/control.d.mts.map +1 -1
  14. package/dist/control.mjs +11 -5
  15. package/dist/control.mjs.map +1 -1
  16. package/dist/emission-types-D6t3_a0x.d.mts +39 -0
  17. package/dist/emission-types-D6t3_a0x.d.mts.map +1 -0
  18. package/dist/emission.d.mts +2 -2
  19. package/dist/execution.d.mts +5 -5
  20. package/dist/execution.d.mts.map +1 -1
  21. package/dist/execution.mjs +3 -3
  22. package/dist/execution.mjs.map +1 -1
  23. package/dist/{framework-authoring-D1-JZ37B.d.mts → framework-authoring-BdrFDx4x.d.mts} +2 -2
  24. package/dist/framework-authoring-BdrFDx4x.d.mts.map +1 -0
  25. package/dist/{framework-components-EJXe-pum.d.mts → framework-components-AHI6V96G.d.mts} +6 -6
  26. package/dist/framework-components-AHI6V96G.d.mts.map +1 -0
  27. package/dist/{framework-components-C8ZhSwXe.mjs → framework-components-BsWST1Rn.mjs} +2 -2
  28. package/dist/framework-components-BsWST1Rn.mjs.map +1 -0
  29. package/dist/psl-ast-9X5rwo98.d.mts +159 -0
  30. package/dist/psl-ast-9X5rwo98.d.mts.map +1 -0
  31. package/dist/psl-ast.d.mts +2 -0
  32. package/dist/psl-ast.mjs +1 -0
  33. package/dist/runtime.d.mts +251 -19
  34. package/dist/runtime.d.mts.map +1 -1
  35. package/dist/runtime.mjs +215 -4
  36. package/dist/runtime.mjs.map +1 -1
  37. package/dist/{types-import-spec-C4sc7wbb.d.mts → types-import-spec-D-O6GotH.d.mts} +2 -2
  38. package/dist/types-import-spec-D-O6GotH.d.mts.map +1 -0
  39. package/package.json +8 -6
  40. package/src/control/control-capabilities.ts +71 -0
  41. package/src/{control-descriptors.ts → control/control-descriptors.ts} +7 -7
  42. package/src/{control-instances.ts → control/control-instances.ts} +6 -6
  43. package/src/{control-migration-types.ts → control/control-migration-types.ts} +27 -15
  44. package/src/control/control-operation-preview.ts +23 -0
  45. package/src/{control-stack.ts → control/control-stack.ts} +13 -13
  46. package/src/control/emission-types.ts +49 -0
  47. package/src/control/psl-ast.ts +193 -0
  48. package/src/{execution-descriptors.ts → execution/execution-descriptors.ts} +7 -7
  49. package/src/{execution-instances.ts → execution/execution-instances.ts} +1 -1
  50. package/src/{execution-requirements.ts → execution/execution-requirements.ts} +1 -1
  51. package/src/execution/query-plan.ts +53 -0
  52. package/src/execution/race-against-abort.ts +85 -0
  53. package/src/execution/run-with-middleware.ts +77 -0
  54. package/src/execution/runtime-core.ts +133 -0
  55. package/src/execution/runtime-error.ts +83 -0
  56. package/src/{runtime-middleware.ts → execution/runtime-middleware.ts} +32 -12
  57. package/src/exports/authoring.ts +2 -2
  58. package/src/exports/codec.ts +14 -2
  59. package/src/exports/components.ts +2 -2
  60. package/src/exports/control.ts +26 -12
  61. package/src/exports/emission.ts +2 -2
  62. package/src/exports/execution.ts +5 -5
  63. package/src/exports/psl-ast.ts +1 -0
  64. package/src/exports/runtime.ts +16 -5
  65. package/src/shared/codec-types.ts +261 -0
  66. package/dist/codec-types-B58nCJiu.d.mts +0 -40
  67. package/dist/codec-types-B58nCJiu.d.mts.map +0 -1
  68. package/dist/emission-types-BPAALJbF.d.mts +0 -24
  69. package/dist/emission-types-BPAALJbF.d.mts.map +0 -1
  70. package/dist/framework-authoring-D1-JZ37B.d.mts.map +0 -1
  71. package/dist/framework-components-C8ZhSwXe.mjs.map +0 -1
  72. package/dist/framework-components-EJXe-pum.d.mts.map +0 -1
  73. package/dist/types-import-spec-C4sc7wbb.d.mts.map +0 -1
  74. package/src/codec-types.ts +0 -46
  75. package/src/control-capabilities.ts +0 -34
  76. package/src/emission-types.ts +0 -28
  77. package/src/runtime-error.ts +0 -39
  78. /package/src/{control-result-types.ts → control/control-result-types.ts} +0 -0
  79. /package/src/{control-schema-view.ts → control/control-schema-view.ts} +0 -0
  80. /package/src/{async-iterable-result.ts → execution/async-iterable-result.ts} +0 -0
  81. /package/src/{execution-stack.ts → execution/execution-stack.ts} +0 -0
  82. /package/src/{framework-authoring.ts → shared/framework-authoring.ts} +0 -0
  83. /package/src/{framework-components.ts → shared/framework-components.ts} +0 -0
  84. /package/src/{mutation-default-types.ts → shared/mutation-default-types.ts} +0 -0
  85. /package/src/{types-import-spec.ts → shared/types-import-spec.ts} +0 -0
@@ -0,0 +1,83 @@
1
+ export interface RuntimeErrorEnvelope extends Error {
2
+ readonly code: string;
3
+ readonly category: 'PLAN' | 'CONTRACT' | 'LINT' | 'BUDGET' | 'RUNTIME';
4
+ readonly severity: 'error';
5
+ readonly details?: Record<string, unknown>;
6
+ }
7
+
8
+ /**
9
+ * Stable code emitted by the runtime when an in-flight `execute()`
10
+ * is cancelled via the per-query `AbortSignal`. The envelope's
11
+ * `details.phase` distinguishes where the abort was observed:
12
+ *
13
+ * - `'encode'` — abort fired during `encodeParams` (SQL) or
14
+ * `resolveValue` (Mongo).
15
+ * - `'decode'` — abort fired during `decodeRow` / `decodeField`.
16
+ * - `'stream'` — abort fired between rows or before any codec call
17
+ * (already-aborted at entry).
18
+ */
19
+ export const RUNTIME_ABORTED = 'RUNTIME.ABORTED' as const;
20
+
21
+ /** Discriminator placed in `details.phase` of a `RUNTIME.ABORTED` envelope. */
22
+ export type RuntimeAbortedPhase = 'encode' | 'decode' | 'stream';
23
+
24
+ /**
25
+ * Type guard for the runtime-error envelope produced by `runtimeError`.
26
+ *
27
+ * Prefer this over duck-typing on `error.code` directly so consumers stay
28
+ * insulated from the envelope's internal shape.
29
+ */
30
+ export function isRuntimeError(error: unknown): error is RuntimeErrorEnvelope {
31
+ return (
32
+ error instanceof Error &&
33
+ 'code' in error &&
34
+ typeof (error as { code?: unknown }).code === 'string' &&
35
+ 'category' in error &&
36
+ 'severity' in error
37
+ );
38
+ }
39
+
40
+ export function runtimeError(
41
+ code: string,
42
+ message: string,
43
+ details?: Record<string, unknown>,
44
+ ): RuntimeErrorEnvelope {
45
+ const error = new Error(message) as RuntimeErrorEnvelope;
46
+ Object.defineProperty(error, 'name', {
47
+ value: 'RuntimeError',
48
+ configurable: true,
49
+ });
50
+
51
+ return Object.assign(error, {
52
+ code,
53
+ category: resolveCategory(code),
54
+ severity: 'error' as const,
55
+ message,
56
+ details,
57
+ });
58
+ }
59
+
60
+ function resolveCategory(code: string): RuntimeErrorEnvelope['category'] {
61
+ const prefix = code.split('.')[0] ?? 'RUNTIME';
62
+ switch (prefix) {
63
+ case 'PLAN':
64
+ case 'CONTRACT':
65
+ case 'LINT':
66
+ case 'BUDGET':
67
+ return prefix;
68
+ default:
69
+ return 'RUNTIME';
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Construct a `RUNTIME.ABORTED` envelope. Phase distinguishes where the
75
+ * abort was observed (encode / decode / stream); cause carries `signal.reason`
76
+ * verbatim from the platform — native abort produces a `DOMException`,
77
+ * explicit `controller.abort(reason)` produces whatever the caller passed.
78
+ * No synthesis happens here.
79
+ */
80
+ export function runtimeAborted(phase: RuntimeAbortedPhase, cause?: unknown): RuntimeErrorEnvelope {
81
+ const envelope = runtimeError(RUNTIME_ABORTED, `Operation aborted during ${phase}`, { phase });
82
+ return Object.assign(envelope, { cause });
83
+ }
@@ -1,5 +1,5 @@
1
- import type { PlanMeta } from '@prisma-next/contract/types';
2
1
  import type { AsyncIterableResult } from './async-iterable-result';
2
+ import type { QueryPlan } from './query-plan';
3
3
  import { runtimeError } from './runtime-error';
4
4
 
5
5
  export interface RuntimeLog {
@@ -22,33 +22,53 @@ export interface AfterExecuteResult {
22
22
  readonly completed: boolean;
23
23
  }
24
24
 
25
- export interface RuntimeMiddleware {
25
+ /**
26
+ * Family-agnostic middleware SPI parameterized over the plan marker.
27
+ *
28
+ * `TPlan` defaults to the framework `QueryPlan` marker so a generic
29
+ * middleware (e.g. cross-family telemetry) can be authored without
30
+ * naming a family. Family-specific middleware (`SqlMiddleware`,
31
+ * `MongoMiddleware`) narrow `TPlan` to their concrete plan type.
32
+ */
33
+ export interface RuntimeMiddleware<TPlan extends QueryPlan = QueryPlan> {
26
34
  readonly name: string;
27
35
  readonly familyId?: string;
28
36
  readonly targetId?: string;
29
- beforeExecute?(plan: { readonly meta: PlanMeta }, ctx: RuntimeMiddlewareContext): Promise<void>;
30
- onRow?(
31
- row: Record<string, unknown>,
32
- plan: { readonly meta: PlanMeta },
33
- ctx: RuntimeMiddlewareContext,
34
- ): Promise<void>;
37
+ beforeExecute?(plan: TPlan, ctx: RuntimeMiddlewareContext): Promise<void>;
38
+ onRow?(row: Record<string, unknown>, plan: TPlan, ctx: RuntimeMiddlewareContext): Promise<void>;
35
39
  afterExecute?(
36
- plan: { readonly meta: PlanMeta },
40
+ plan: TPlan,
37
41
  result: AfterExecuteResult,
38
42
  ctx: RuntimeMiddlewareContext,
39
43
  ): Promise<void>;
40
44
  }
41
45
 
46
+ /**
47
+ * Optional per-`execute` options accepted by every family runtime.
48
+ *
49
+ * `signal` is the per-query cancellation signal. The runtime threads the
50
+ * signal through to every codec call for the query and uses it to short-
51
+ * circuit the row stream with `RUNTIME.ABORTED` when the caller aborts.
52
+ * Omitting the option (or passing `undefined`) preserves today's behavior
53
+ * bit-for-bit.
54
+ */
55
+ export interface RuntimeExecuteOptions {
56
+ readonly signal?: AbortSignal;
57
+ }
58
+
42
59
  /**
43
60
  * Cross-family SPI for any runtime that can execute plans and be shut down.
44
61
  * Each family runtime (SQL, Mongo) satisfies this interface — SQL nominally,
45
62
  * Mongo structurally (due to its phantom Row parameter using a unique symbol).
46
63
  *
47
64
  * The `_row` intersection on `execute` connects the `Row` type parameter to the
48
- * plan, mirroring how `ExecutionPlan<Row>` carries a phantom `_row?: Row`.
65
+ * plan, mirroring how `QueryPlan<Row>` carries a phantom `_row?: Row`.
49
66
  */
50
- export interface RuntimeExecutor<TPlan extends { readonly meta: PlanMeta }> {
51
- execute<Row>(plan: TPlan & { readonly _row?: Row }): AsyncIterableResult<Row>;
67
+ export interface RuntimeExecutor<TPlan extends QueryPlan> {
68
+ execute<Row>(
69
+ plan: TPlan & { readonly _row?: Row },
70
+ options?: RuntimeExecuteOptions,
71
+ ): AsyncIterableResult<Row>;
52
72
  close(): Promise<void>;
53
73
  }
54
74
 
@@ -10,7 +10,7 @@ export type {
10
10
  AuthoringTemplateValue,
11
11
  AuthoringTypeConstructorDescriptor,
12
12
  AuthoringTypeNamespace,
13
- } from '../framework-authoring';
13
+ } from '../shared/framework-authoring';
14
14
  export {
15
15
  instantiateAuthoringFieldPreset,
16
16
  instantiateAuthoringTypeConstructor,
@@ -19,4 +19,4 @@ export {
19
19
  isAuthoringTypeConstructorDescriptor,
20
20
  resolveAuthoringTemplateValue,
21
21
  validateAuthoringHelperArguments,
22
- } from '../framework-authoring';
22
+ } from '../shared/framework-authoring';
@@ -1,2 +1,14 @@
1
- export type { Codec, CodecLookup, CodecTrait } from '../codec-types';
2
- export { emptyCodecLookup } from '../codec-types';
1
+ export type {
2
+ Codec,
3
+ CodecCallContext,
4
+ CodecDescriptor,
5
+ CodecInstanceContext,
6
+ CodecLookup,
7
+ CodecMeta,
8
+ CodecTrait,
9
+ } from '../shared/codec-types';
10
+ export {
11
+ emptyCodecLookup,
12
+ synthesizeNonParameterizedDescriptor,
13
+ voidParamsSchema,
14
+ } from '../shared/codec-types';
@@ -20,5 +20,5 @@ export type {
20
20
  TargetDescriptor,
21
21
  TargetInstance,
22
22
  TargetPackRef,
23
- } from '../framework-components';
24
- export { checkContractComponentRequirements } from '../framework-components';
23
+ } from '../shared/framework-components';
24
+ export { checkContractComponentRequirements } from '../shared/framework-components';
@@ -1,19 +1,29 @@
1
- export type { MigratableTargetDescriptor, SchemaViewCapable } from '../control-capabilities';
2
- export { hasMigrations, hasSchemaView } from '../control-capabilities';
1
+ export type {
2
+ MigratableTargetDescriptor,
3
+ OperationPreviewCapable,
4
+ PslContractInferCapable,
5
+ SchemaViewCapable,
6
+ } from '../control/control-capabilities';
7
+ export {
8
+ hasMigrations,
9
+ hasOperationPreview,
10
+ hasPslContractInfer,
11
+ hasSchemaView,
12
+ } from '../control/control-capabilities';
3
13
  export type {
4
14
  ControlAdapterDescriptor,
5
15
  ControlDriverDescriptor,
6
16
  ControlExtensionDescriptor,
7
17
  ControlFamilyDescriptor,
8
18
  ControlTargetDescriptor,
9
- } from '../control-descriptors';
19
+ } from '../control/control-descriptors';
10
20
  export type {
11
21
  ControlAdapterInstance,
12
22
  ControlDriverInstance,
13
23
  ControlExtensionInstance,
14
24
  ControlFamilyInstance,
15
25
  ControlTargetInstance,
16
- } from '../control-instances';
26
+ } from '../control/control-instances';
17
27
  export type {
18
28
  DataTransformOperation,
19
29
  MigrationOperationClass,
@@ -35,7 +45,11 @@ export type {
35
45
  OpFactoryCall,
36
46
  SerializedQueryPlan,
37
47
  TargetMigrationsCapability,
38
- } from '../control-migration-types';
48
+ } from '../control/control-migration-types';
49
+ export type {
50
+ OperationPreview,
51
+ OperationPreviewStatement,
52
+ } from '../control/control-operation-preview';
39
53
  export type {
40
54
  BaseSchemaIssue,
41
55
  EmitContractResult,
@@ -47,25 +61,25 @@ export type {
47
61
  SignDatabaseResult,
48
62
  VerifyDatabaseResult,
49
63
  VerifyDatabaseSchemaResult,
50
- } from '../control-result-types';
64
+ } from '../control/control-result-types';
51
65
  export {
52
66
  VERIFY_CODE_HASH_MISMATCH,
53
67
  VERIFY_CODE_MARKER_MISSING,
54
68
  VERIFY_CODE_SCHEMA_FAILURE,
55
69
  VERIFY_CODE_TARGET_MISMATCH,
56
- } from '../control-result-types';
70
+ } from '../control/control-result-types';
57
71
  export type {
58
72
  CoreSchemaView,
59
73
  SchemaNodeKind,
60
74
  SchemaTreeNodeOptions,
61
75
  SchemaTreeVisitor,
62
- } from '../control-schema-view';
63
- export { SchemaTreeNode } from '../control-schema-view';
76
+ } from '../control/control-schema-view';
77
+ export { SchemaTreeNode } from '../control/control-schema-view';
64
78
  export type {
65
79
  AssembledAuthoringContributions,
66
80
  ControlStack,
67
81
  CreateControlStackInput,
68
- } from '../control-stack';
82
+ } from '../control/control-stack';
69
83
  export {
70
84
  assembleAuthoringContributions,
71
85
  assembleControlMutationDefaults,
@@ -77,7 +91,7 @@ export {
77
91
  extractComponentIds,
78
92
  extractOperationTypeImports,
79
93
  extractQueryOperationTypeImports,
80
- } from '../control-stack';
94
+ } from '../control/control-stack';
81
95
  export type {
82
96
  ControlMutationDefaultEntry,
83
97
  ControlMutationDefaultRegistry,
@@ -92,4 +106,4 @@ export type {
92
106
  ParsedDefaultFunctionCall,
93
107
  SourceDiagnostic,
94
108
  SourceSpan,
95
- } from '../mutation-default-types';
109
+ } 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,22 @@
1
- export { AsyncIterableResult } from '../async-iterable-result';
2
- export type { RuntimeErrorEnvelope } from '../runtime-error';
3
- export { 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
+ RuntimeExecuteOptions,
6
17
  RuntimeExecutor,
7
18
  RuntimeLog,
8
19
  RuntimeMiddleware,
9
20
  RuntimeMiddlewareContext,
10
- } from '../runtime-middleware';
11
- export { checkMiddlewareCompatibility } from '../runtime-middleware';
21
+ } from '../execution/runtime-middleware';
22
+ export { checkMiddlewareCompatibility } from '../execution/runtime-middleware';
@@ -0,0 +1,261 @@
1
+ import type { JsonValue } from '@prisma-next/contract/types';
2
+ import type { StandardSchemaV1 } from '@standard-schema/spec';
3
+
4
+ export type CodecTrait =
5
+ | 'equality'
6
+ | 'order'
7
+ | 'boolean'
8
+ | 'numeric'
9
+ | 'textual'
10
+ /**
11
+ * The codec carries a per-instance `validate(value: unknown) =>
12
+ * JsonSchemaValidationResult` function on the resolved codec object that
13
+ * the framework's `JsonSchemaValidatorRegistry` consults at runtime. The
14
+ * trait gates the `extractValidator` cast from structurally-typed
15
+ * `unknown` to a typed validator view.
16
+ *
17
+ * Retirement target. The unified `CodecDescriptor` model moves
18
+ * validation into the resolved codec's `decode` body; the parallel
19
+ * `JsonSchemaValidatorRegistry` (and this trait alongside it) retires
20
+ * under TML-2357 (T3.5.12). Per-library JSON extensions like
21
+ * `@prisma-next/extension-arktype-json` already follow the new pattern.
22
+ */
23
+ | 'json-validator';
24
+
25
+ /**
26
+ * Per-call context the runtime threads to every `codec.encode` /
27
+ * `codec.decode` invocation for a single `runtime.execute()` call.
28
+ *
29
+ * The framework-level shape is family-agnostic and carries one field:
30
+ *
31
+ * - `signal?: AbortSignal` — per-query cancellation. The runtime returns
32
+ * a `RUNTIME.ABORTED` envelope when the signal aborts; codec authors
33
+ * who forward `signal` to their underlying SDK get true cancellation
34
+ * of in-flight network calls.
35
+ *
36
+ * Family layers extend this base with their own shape-of-call metadata:
37
+ * the SQL family adds `column?: SqlColumnRef` via `SqlCodecCallContext`
38
+ * (see `@prisma-next/sql-relational-core`). Mongo currently uses this
39
+ * framework type unchanged. Column metadata is intentionally **not** on
40
+ * the framework type — it is a SQL-family concept rooted in SQL's
41
+ * `(table, column)` addressing model and would not generalise to other
42
+ * families.
43
+ *
44
+ * The interface is named explicitly (not inlined) so future framework
45
+ * fields and family extensions can land additively without breaking
46
+ * codec author signatures.
47
+ */
48
+ export interface CodecCallContext {
49
+ readonly signal?: AbortSignal;
50
+ }
51
+
52
+ /**
53
+ * A codec is the contract between an application value and its on-wire and
54
+ * on-contract-disk representations.
55
+ *
56
+ * The author's mental model is two JS-side types — `TInput` (the
57
+ * application JS type) and `TWire` (the database driver wire format) —
58
+ * plus `JsonValue` for build-time contract artifacts. The codec translates
59
+ * `TInput` to `TWire` on writes and back on reads, and to/from `JsonValue`
60
+ * during contract emission and loading.
61
+ *
62
+ * Three representations participate:
63
+ * - **Input** (`TInput`): the JS type at the application boundary.
64
+ * - **Wire** (`TWire`): the format exchanged with the database driver.
65
+ * - **JSON** (`JsonValue`): a JSON-safe form used in contract artifacts.
66
+ *
67
+ * Codec methods split into two groups:
68
+ *
69
+ * - **Query-time** methods (`encode`, `decode`) run per row/parameter at the
70
+ * IO boundary; they are required and Promise-returning. The per-family
71
+ * codec factory accepts sync or async author functions and lifts sync
72
+ * ones to Promise-shaped methods automatically.
73
+ * - **Build-time** methods (`encodeJson`, `decodeJson`, `renderOutputType`)
74
+ * run when the contract is serialized, loaded, or when client types are
75
+ * emitted. They stay synchronous so contract validation and client
76
+ * construction are synchronous.
77
+ *
78
+ * Target-family codec interfaces extend this base with target-shaped
79
+ * metadata.
80
+ */
81
+ export interface Codec<
82
+ Id extends string = string,
83
+ TTraits extends readonly CodecTrait[] = readonly CodecTrait[],
84
+ TWire = unknown,
85
+ TInput = unknown,
86
+ > {
87
+ /** Unique codec identifier in `namespace/name@version` format (e.g. `pg/timestamptz@1`). */
88
+ readonly id: Id;
89
+ /** Database-native type names this codec handles (e.g. `['timestamptz']`). */
90
+ readonly targetTypes: readonly string[];
91
+ /** Semantic traits for operator gating (e.g. equality, order, numeric). */
92
+ readonly traits?: TTraits;
93
+ /** 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. */
94
+ encode(value: TInput, ctx: CodecCallContext): Promise<TWire>;
95
+ /** 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. */
96
+ decode(wire: TWire, ctx: CodecCallContext): Promise<TInput>;
97
+ /** Converts a JS value to a JSON-safe representation for contract serialization. Synchronous; called during contract emission. */
98
+ encodeJson(value: TInput): JsonValue;
99
+ /** Converts a JSON representation back to the JS input type. Synchronous; called during contract loading via `validateContract`. */
100
+ decodeJson(json: JsonValue): TInput;
101
+ /** Produces the TypeScript output type expression for a field given its `typeParams`. Synchronous; used during contract.d.ts emission. */
102
+ renderOutputType?(typeParams: Record<string, unknown>): string | undefined;
103
+ }
104
+
105
+ export interface CodecLookup {
106
+ get(id: string): Codec | undefined;
107
+ }
108
+
109
+ export const emptyCodecLookup: CodecLookup = {
110
+ get: () => undefined,
111
+ };
112
+
113
+ /**
114
+ * Family-agnostic per-instance context supplied by the framework when
115
+ * applying a higher-order codec factory. Allows stateful codecs (e.g.
116
+ * column-scoped encryption) to derive per-instance state from the
117
+ * materialization site.
118
+ *
119
+ * - `name` — the family-agnostic instance identity. For SQL, the runtime
120
+ * populates this as the `storage.types` instance name (e.g.
121
+ * `Embedding1536`) for typeRef-shaped columns, the synthesized
122
+ * anonymous instance name (`<anon:Document.embedding>`) for inline-
123
+ * `typeParams` columns, or a shared sentinel (`<shared:pg/text@1>`)
124
+ * for non-parameterized codec ids. Other families pick the analogous
125
+ * identity for their materialization sites.
126
+ *
127
+ * Family-specific extensions (e.g. {@link import('@prisma-next/sql-relational-core/ast').SqlCodecInstanceContext}
128
+ * in the SQL layer) augment this base with domain-shaped column-set
129
+ * metadata. Codec authors target the base when they don't read family-
130
+ * specific metadata; they target the family extension when they do.
131
+ */
132
+ export interface CodecInstanceContext {
133
+ readonly name: string;
134
+ }
135
+
136
+ /**
137
+ * Family-agnostic codec metadata. Family-specific extensions augment the
138
+ * base `db.<family>.<target>` block with native-type information; the base
139
+ * shape is an empty object so non-relational codecs can carry no metadata.
140
+ */
141
+ export interface CodecMeta {
142
+ readonly db?: Record<string, unknown>;
143
+ }
144
+
145
+ /**
146
+ * Unified codec descriptor. Every codec in the framework registers through
147
+ * this shape — non-parameterized codecs use `P = void` and a constant
148
+ * factory that returns the same shared codec instance for every column;
149
+ * parameterized codecs use a non-empty `P` and a curried higher-order
150
+ * factory that returns a per-instance codec.
151
+ *
152
+ * The descriptor is the codec-id-keyed source of truth for static metadata
153
+ * (`traits`, `targetTypes`, `meta`) and registration concerns
154
+ * (`paramsSchema` for JSON-boundary validation; optional `renderOutputType`
155
+ * for the `contract.d.ts` emit path). The runtime `Codec` instance returned
156
+ * by `factory(params)(ctx)` carries only the conversion behavior.
157
+ *
158
+ * Whether a codec id "is parameterized" stops being a registration-time
159
+ * distinction — it's a property of `P` on the descriptor. The descriptor
160
+ * map indexes every descriptor by `codecId`; both `descriptorFor(codecId)`
161
+ * and `forColumn(table, column)` resolve through the same map without
162
+ * branching on parameterization.
163
+ *
164
+ * @template P - The shape of the params accepted by the factory (`void` for
165
+ * non-parameterized codecs; a record like `{ length: number }` for
166
+ * parameterized codecs).
167
+ *
168
+ * Codec-registry-unification project § Decision.
169
+ */
170
+ export interface CodecDescriptor<P = void> {
171
+ /** The codec ID this descriptor applies to (e.g. `pg/vector@1`, `pg/text@1`). */
172
+ readonly codecId: string;
173
+ /** Semantic traits for operator gating (e.g. equality, order, numeric). */
174
+ readonly traits: readonly CodecTrait[];
175
+ /** Database-native type names this codec handles (e.g. `['timestamptz']`). */
176
+ readonly targetTypes: readonly string[];
177
+ /** Optional family-specific metadata (e.g. SQL-side `db.sql.postgres.nativeType`). */
178
+ readonly meta?: CodecMeta;
179
+ /**
180
+ * Standard Schema validator for the factory's params. Validates JSON-
181
+ * sourced params at the contract boundary (PSL → IR; `contract.json` →
182
+ * runtime). For non-parameterized codecs (`P = void`), the schema
183
+ * validates `void`/`undefined` — the framework supplies no params at the
184
+ * call boundary.
185
+ */
186
+ readonly paramsSchema: StandardSchemaV1<P>;
187
+ /**
188
+ * Emit-path string renderer for `contract.d.ts`. Returns the TypeScript
189
+ * output type expression for given params (e.g. `Vector<1536>`).
190
+ * Optional; absent renderers cause the emitter to fall back to the
191
+ * codec's base output type. Non-parameterized codecs typically omit it.
192
+ */
193
+ readonly renderOutputType?: (params: P) => string | undefined;
194
+ /**
195
+ * The curried higher-order codec. For non-parameterized codecs, the
196
+ * factory is constant — every call returns the same shared codec
197
+ * instance. For parameterized codecs, the factory is called once per
198
+ * `storage.types` instance (or once per inline-`typeParams` column),
199
+ * with `ctx` carrying the column set the resulting codec serves.
200
+ */
201
+ readonly factory: (params: P) => (ctx: CodecInstanceContext) => Codec;
202
+ }
203
+
204
+ /**
205
+ * Standard Schema validator for `void` params. Accepts only `undefined`
206
+ * (or absent input); rejects any other value so a contract that tries to
207
+ * thread `typeParams` through a non-parameterized codec id fails fast at
208
+ * the JSON boundary instead of silently coercing the value away. Used by
209
+ * the framework-supplied non-parameterized descriptor synthesizer.
210
+ */
211
+ export const voidParamsSchema: StandardSchemaV1<void> = {
212
+ '~standard': {
213
+ version: 1,
214
+ vendor: 'prisma-next',
215
+ validate: (input) =>
216
+ input === undefined
217
+ ? { value: undefined }
218
+ : {
219
+ issues: [
220
+ {
221
+ message: 'unexpected typeParams for non-parameterized codec (void params expected)',
222
+ },
223
+ ],
224
+ },
225
+ },
226
+ };
227
+
228
+ /**
229
+ * Synthesize a `CodecDescriptor<void>` for a non-parameterized codec
230
+ * runtime instance. The factory is constant — every call returns the same
231
+ * shared codec instance — so columns sharing this codec id share one
232
+ * resolved codec.
233
+ *
234
+ * Codec-registry-unification spec § Decision (Case T — non-parameterized
235
+ * text codec). This is the bridge while non-parameterized codec
236
+ * contributors still register through the legacy `codecs:` slot; once they
237
+ * migrate to ship descriptors directly (TML-2357 T3.5.3), this synthesis
238
+ * steps aside.
239
+ */
240
+ export function synthesizeNonParameterizedDescriptor(codec: Codec): CodecDescriptor<void> {
241
+ // The descriptor's `factory: (params: void) => (ctx: CodecInstanceContext)
242
+ // => Codec` is a constant for non-parameterized codecs — `params` is
243
+ // never read and the returned ctx-applier always yields the same shared
244
+ // codec. We rely on the descriptor's typed `factory` slot to infer the
245
+ // signatures rather than naming `void` locally (biome's
246
+ // `noConfusingVoidType` flags `void` outside return positions).
247
+ const sharedFactory = () => () => codec;
248
+ // Family-extended codecs (SQL `Codec`) carry an optional `meta` field
249
+ // that the base interface doesn't declare. Read it through a structural
250
+ // narrow so the synthesizer forwards it to the descriptor without losing
251
+ // type safety on the base shape.
252
+ const codecMeta = (codec as { readonly meta?: CodecMeta }).meta;
253
+ return {
254
+ codecId: codec.id,
255
+ traits: codec.traits ?? [],
256
+ targetTypes: codec.targetTypes,
257
+ paramsSchema: voidParamsSchema,
258
+ factory: sharedFactory,
259
+ ...(codecMeta !== undefined ? { meta: codecMeta } : {}),
260
+ };
261
+ }
@@ -1,40 +0,0 @@
1
- import { JsonValue } from "@prisma-next/contract/types";
2
-
3
- //#region src/codec-types.d.ts
4
- type CodecTrait = 'equality' | 'order' | 'boolean' | 'numeric' | 'textual';
5
- /**
6
- * Base codec interface for all target families.
7
- *
8
- * A codec maps between three representations of a value:
9
- * - **JS** (`TJs`): the JavaScript type used in application code
10
- * - **Wire** (`TWire`): the format sent to/from the database driver
11
- * - **JSON** (`JsonValue`): the JSON-safe form stored in contract artifacts
12
- *
13
- * Family-specific codec interfaces (SQL `Codec`, Mongo `MongoCodec`) extend
14
- * this base to add family-specific metadata.
15
- */
16
- interface Codec<Id extends string = string, TTraits extends readonly CodecTrait[] = readonly CodecTrait[], TWire = unknown, TJs = unknown> {
17
- /** Unique codec identifier in `namespace/name@version` format (e.g. `pg/timestamptz@1`). */
18
- readonly id: Id;
19
- /** Database-native type names this codec handles (e.g. `['timestamptz']`). */
20
- readonly targetTypes: readonly string[];
21
- /** Semantic traits for operator gating (e.g. equality, order, numeric). */
22
- readonly traits?: TTraits;
23
- /** Converts a JS value to the wire format expected by the database driver. Optional when the driver accepts the JS type directly. */
24
- encode?(value: TJs): TWire;
25
- /** Converts a wire value from the database driver into the JS type. */
26
- decode(wire: TWire): TJs;
27
- /** Converts a JS value to a JSON-safe representation for contract serialization. Called during contract emission. */
28
- encodeJson(value: TJs): JsonValue;
29
- /** Converts a JSON representation back to the JS type. Called during contract loading via `validateContract`. */
30
- decodeJson(json: JsonValue): TJs;
31
- /** Produces the TypeScript output type expression for a field given its `typeParams`. Used during contract.d.ts emission. */
32
- renderOutputType?(typeParams: Record<string, unknown>): string | undefined;
33
- }
34
- interface CodecLookup {
35
- get(id: string): Codec | undefined;
36
- }
37
- declare const emptyCodecLookup: CodecLookup;
38
- //#endregion
39
- export { emptyCodecLookup as i, CodecLookup as n, CodecTrait as r, Codec as t };
40
- //# sourceMappingURL=codec-types-B58nCJiu.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"codec-types-B58nCJiu.d.mts","names":[],"sources":["../src/codec-types.ts"],"sourcesContent":[],"mappings":";;;KAEY,UAAA;;AAAZ;AAaA;;;;;;;;;AAiBoB,UAjBH,KAiBG,CAAA,WAAA,MAAA,GAAA,MAAA,EAAA,gBAAA,SAfO,UAeP,EAAA,GAAA,SAf+B,UAe/B,EAAA,EAAA,QAAA,OAAA,EAAA,MAAA,OAAA,CAAA,CAAA;EAAM;EAEP,SAAA,EAAA,EAZJ,EAYI;EAAY;EAEC,SAAA,WAAA,EAAA,SAAA,MAAA,EAAA;EAAM;EAGrB,SAAA,MAAW,CAAA,EAbR,OAcD;EAGN;iBAfI,MAAM;;eAER,QAAQ;;oBAEH,MAAM;;mBAEP,YAAY;;gCAEC;;UAGf,WAAA;mBACE;;cAGN,kBAAkB"}