@prisma-next/sql-relational-core 0.5.0-dev.9 → 0.5.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.
Files changed (82) hide show
  1. package/README.md +59 -25
  2. package/dist/codec-types-BUfBna4G.d.mts +107 -0
  3. package/dist/codec-types-BUfBna4G.d.mts.map +1 -0
  4. package/dist/{errors-D3xmG4h-.mjs → errors-BF7W5uUd.mjs} +2 -2
  5. package/dist/{errors-D3xmG4h-.mjs.map → errors-BF7W5uUd.mjs.map} +1 -1
  6. package/dist/{errors-CDvhnH7P.d.mts → errors-BgNpVAT8.d.mts} +2 -2
  7. package/dist/errors-BgNpVAT8.d.mts.map +1 -0
  8. package/dist/exports/ast.d.mts +189 -112
  9. package/dist/exports/ast.d.mts.map +1 -1
  10. package/dist/exports/ast.mjs +207 -1322
  11. package/dist/exports/ast.mjs.map +1 -1
  12. package/dist/exports/codec-descriptor-registry.d.mts +18 -0
  13. package/dist/exports/codec-descriptor-registry.d.mts.map +1 -0
  14. package/dist/exports/codec-descriptor-registry.mjs +40 -0
  15. package/dist/exports/codec-descriptor-registry.mjs.map +1 -0
  16. package/dist/exports/errors.d.mts +1 -4
  17. package/dist/exports/errors.mjs +2 -3
  18. package/dist/exports/expression.d.mts +84 -0
  19. package/dist/exports/expression.d.mts.map +1 -0
  20. package/dist/exports/expression.mjs +62 -0
  21. package/dist/exports/expression.mjs.map +1 -0
  22. package/dist/exports/middleware.d.mts +2 -0
  23. package/dist/exports/middleware.mjs +2 -0
  24. package/dist/exports/plan.d.mts +3 -3
  25. package/dist/exports/plan.mjs +27 -10
  26. package/dist/exports/plan.mjs.map +1 -1
  27. package/dist/exports/query-lane-context.d.mts +2 -3
  28. package/dist/exports/query-lane-context.mjs +1 -1
  29. package/dist/exports/types.d.mts +2 -4
  30. package/dist/exports/types.mjs +1 -1
  31. package/dist/index.d.mts +12 -12
  32. package/dist/index.mjs +8 -5
  33. package/dist/middleware-D2Wv9QIf.mjs +82 -0
  34. package/dist/middleware-D2Wv9QIf.mjs.map +1 -0
  35. package/dist/middleware-USDeR8p1.d.mts +121 -0
  36. package/dist/middleware-USDeR8p1.d.mts.map +1 -0
  37. package/dist/plan-DFpOIsKB.d.mts +44 -0
  38. package/dist/plan-DFpOIsKB.d.mts.map +1 -0
  39. package/dist/query-lane-context-C2tLZGp4.d.mts +72 -0
  40. package/dist/query-lane-context-C2tLZGp4.d.mts.map +1 -0
  41. package/dist/{sql-execution-plan-DY0WvJOW.d.mts → sql-execution-plan-ffz8TSfr.d.mts} +2 -3
  42. package/dist/sql-execution-plan-ffz8TSfr.d.mts.map +1 -0
  43. package/dist/{types-C3Hg-CVz.d.mts → types-BZcKgaYA.d.mts} +61 -24
  44. package/dist/types-BZcKgaYA.d.mts.map +1 -0
  45. package/dist/types-CK9ZJ6OU.mjs +1112 -0
  46. package/dist/types-CK9ZJ6OU.mjs.map +1 -0
  47. package/dist/{types-B5XsBeaT.d.mts → types-CL18G37a.d.mts} +3 -4
  48. package/dist/types-CL18G37a.d.mts.map +1 -0
  49. package/dist/{types-CG3u534i.d.mts → types-D6Pk1DTr.d.mts} +11 -13
  50. package/dist/types-D6Pk1DTr.d.mts.map +1 -0
  51. package/dist/util-DWmhUCEO.mjs +34 -0
  52. package/dist/util-DWmhUCEO.mjs.map +1 -0
  53. package/package.json +16 -13
  54. package/src/ast/adapter-types.ts +13 -16
  55. package/src/ast/codec-types.ts +87 -419
  56. package/src/ast/sql-codec-helpers.ts +79 -0
  57. package/src/ast/sql-codecs.ts +285 -125
  58. package/src/ast/types.ts +222 -173
  59. package/src/ast/util.ts +23 -0
  60. package/src/ast/validate-param-refs.ts +39 -0
  61. package/src/codec-descriptor-registry.ts +52 -0
  62. package/src/exports/ast.ts +2 -0
  63. package/src/exports/codec-descriptor-registry.ts +1 -0
  64. package/src/exports/expression.ts +1 -0
  65. package/src/exports/middleware.ts +8 -0
  66. package/src/expression.ts +134 -0
  67. package/src/index.ts +2 -0
  68. package/src/middleware/param-ref-mutator.ts +230 -0
  69. package/src/plan.ts +32 -16
  70. package/src/query-lane-context.ts +35 -55
  71. package/src/types.ts +1 -3
  72. package/dist/codec-types-B2Xdq0Wr.d.mts +0 -167
  73. package/dist/codec-types-B2Xdq0Wr.d.mts.map +0 -1
  74. package/dist/errors-CDvhnH7P.d.mts.map +0 -1
  75. package/dist/plan-CRPxW2Jj.d.mts +0 -32
  76. package/dist/plan-CRPxW2Jj.d.mts.map +0 -1
  77. package/dist/query-lane-context-DDRW5NBG.d.mts +0 -89
  78. package/dist/query-lane-context-DDRW5NBG.d.mts.map +0 -1
  79. package/dist/sql-execution-plan-DY0WvJOW.d.mts.map +0 -1
  80. package/dist/types-B5XsBeaT.d.mts.map +0 -1
  81. package/dist/types-C3Hg-CVz.d.mts.map +0 -1
  82. package/dist/types-CG3u534i.d.mts.map +0 -1
@@ -1,39 +1,51 @@
1
- import type { JsonValue } from '@prisma-next/contract/types';
2
- import type { Codec as BaseCodec, CodecTrait } from '@prisma-next/framework-components/codec';
3
- import { ifDefined } from '@prisma-next/utils/defined';
4
- import type { Type } from 'arktype';
5
- import type { O } from 'ts-toolbelt';
6
-
7
- export type { CodecTrait } from '@prisma-next/framework-components/codec';
1
+ import type {
2
+ Codec as BaseCodec,
3
+ CodecCallContext,
4
+ CodecDescriptor,
5
+ CodecInstanceContext,
6
+ CodecTrait,
7
+ } from '@prisma-next/framework-components/codec';
8
+
9
+ export type {
10
+ CodecCallContext,
11
+ CodecDescriptor,
12
+ CodecTrait,
13
+ } from '@prisma-next/framework-components/codec';
8
14
 
9
15
  /**
10
- * Descriptor for parameterized codecs that require type parameter validation.
11
- * Shared between adapter (compile-time) and runtime layers to avoid duplication.
16
+ * SQL-family addressing of a single column. The decode site populates a `SqlColumnRef` whenever it can resolve the cell to a single underlying `(table, column)` (the typical case for projected columns from a single-table source); cells the runtime cannot resolve (aggregate aliases, include aggregate fields, computed projections without a simple ref) get `column = undefined`.
12
17
  *
13
- * @template TParams - The shape of the type parameters (e.g., `{ length: number }`)
14
- * @template THelper - The type returned by the optional `init` hook
18
+ * The shape is a structural projection of the runtime's `ColumnRef` so the SQL decode site can reuse the resolution it already performs for `RUNTIME.DECODE_FAILED` envelope construction without allocating twice per cell.
15
19
  */
16
- export interface CodecParamsDescriptor<TParams = Record<string, unknown>, THelper = unknown> {
17
- /** The codec ID this descriptor applies to (e.g., 'pg/vector@1') */
18
- readonly codecId: string;
20
+ export interface SqlColumnRef {
21
+ readonly table: string;
22
+ readonly name: string;
23
+ }
19
24
 
20
- /**
21
- * Arktype schema for validating typeParams.
22
- * Used to validate both storage.types entries and inline column typeParams.
23
- */
24
- readonly paramsSchema: Type<TParams>;
25
+ /**
26
+ * SQL-family per-call context. Extends the framework {@link CodecCallContext} (which carries `signal` only) with `column?: SqlColumnRef`, populated on **decode** call sites that can resolve a single underlying column ref. Encode call sites currently leave `column` undefined (encode-time column context is the middleware's domain).
27
+ *
28
+ * SQL codec authors writing codec methods observe this type via {@link SqlCodec}. The framework codec dispatch surface (and Mongo) sees only the base `CodecCallContext`.
29
+ */
30
+ export interface SqlCodecCallContext extends CodecCallContext {
31
+ readonly column?: SqlColumnRef;
32
+ }
25
33
 
26
- /**
27
- * Optional init hook called during runtime context creation.
28
- * Receives validated params and returns a helper object to be stored in context.types.
29
- * If not provided, the validated params are stored directly.
30
- */
31
- readonly init?: (params: TParams) => THelper;
34
+ /**
35
+ * SQL-family per-instance context. Extends the framework {@link CodecInstanceContext} (`name` only) with `usedAt`, the set of `(table, column)` pairs the resolved codec serves.
36
+ *
37
+ * - For `typeRef` columns sharing one named `storage.types` instance, the array lists every referencing column — a column-scoped stateful codec (e.g. encryption) can derive aggregated per-instance state across all the columns sharing the named instance.
38
+ * - For inline-`typeParams` columns, the array has exactly one entry — the column that owns the inline params.
39
+ * - For shared non-parameterized codecs, the array carries one representative entry (the column that triggered materialization); the codec is shared across every column with that codec id, so the `usedAt` is informational only.
40
+ *
41
+ * SQL extensions consuming `usedAt` (e.g. column-scoped state derivation) type their factory parameter as `SqlCodecInstanceContext`. Extensions that don't read `usedAt` type their factory parameter as the family-agnostic {@link CodecInstanceContext} — a `SqlCodecInstanceContext` is structurally assignable to the base.
42
+ */
43
+ export interface SqlCodecInstanceContext extends CodecInstanceContext {
44
+ readonly usedAt: ReadonlyArray<{ readonly table: string; readonly column: string }>;
32
45
  }
33
46
 
34
47
  /**
35
- * Codec metadata for database-specific type information.
36
- * Used for schema introspection and verification.
48
+ * Codec metadata for database-specific type information. Used for schema introspection and verification.
37
49
  */
38
50
  export interface CodecMeta {
39
51
  readonly db?: {
@@ -46,429 +58,85 @@ export interface CodecMeta {
46
58
  }
47
59
 
48
60
  /**
49
- * SQL codec — extends the framework codec base with SQL-specific metadata:
50
- * driver-native type info (`meta.db.sql.<dialect>.nativeType`) and an
51
- * optional parameterized-codec descriptor (`paramsSchema` + `init`) for
52
- * codecs that require type-parameter validation (e.g. `pg/vector@1`).
61
+ * SQL codec — extends the framework codec base by narrowing the per-call context to the SQL-family {@link SqlCodecCallContext} (adds `column?: SqlColumnRef`). TypeScript treats method-syntax declarations bivariantly, so the SQL narrowing is structurally compatible with the framework {@link BaseCodec} super-interface.
62
+ *
63
+ * Codec-id-keyed static metadata (`traits`, `targetTypes`, `meta`, `paramsSchema`, `renderOutputType`) lives on the unified {@link import('@prisma-next/framework-components/codec').CodecDescriptor} — the codec instance itself only carries `id` plus the four conversion methods.
53
64
  *
54
- * See `Codec` in `@prisma-next/framework-components/codec` for the codec
55
- * contract that this interface extends.
65
+ * See `Codec` in `@prisma-next/framework-components/codec` for the codec contract that this interface extends.
56
66
  */
57
67
  export interface Codec<
58
68
  Id extends string = string,
59
69
  TTraits extends readonly CodecTrait[] = readonly CodecTrait[],
60
70
  TWire = unknown,
61
71
  TInput = unknown,
62
- TParams = Record<string, unknown>,
63
- THelper = unknown,
64
72
  > extends BaseCodec<Id, TTraits, TWire, TInput> {
65
- readonly meta?: CodecMeta;
66
- readonly paramsSchema?: Type<TParams>;
67
- readonly init?: (params: TParams) => THelper;
73
+ encode(value: TInput, ctx: SqlCodecCallContext): Promise<TWire>;
74
+ decode(wire: TWire, ctx: SqlCodecCallContext): Promise<TInput>;
68
75
  }
69
76
 
70
77
  /**
71
- * Registry interface for codecs organized by ID and by contract scalar type.
78
+ * Contract-bound codec registry.
72
79
  *
73
- * The registry allows looking up codecs by their namespaced ID or by the
74
- * contract scalar types they handle. Multiple codecs may handle the same
75
- * scalar type; ordering in byScalar reflects preference (adapter first,
76
- * then packs, then app overrides).
77
- */
78
- export interface CodecRegistry {
79
- get(id: string): Codec<string> | undefined;
80
- has(id: string): boolean;
81
- getByScalar(scalar: string): readonly Codec<string>[];
82
- getDefaultCodec(scalar: string): Codec<string> | undefined;
83
- register(codec: Codec<string>): void;
84
- /** Returns true if the codec with this ID has the given trait. */
85
- hasTrait(codecId: string, trait: CodecTrait): boolean;
86
- /** Returns all traits for a codec, or an empty array if not found. */
87
- traitsOf(codecId: string): readonly CodecTrait[];
88
- [Symbol.iterator](): Iterator<Codec<string>>;
89
- values(): IterableIterator<Codec<string>>;
90
- }
91
-
92
- /**
93
- * Implementation of CodecRegistry.
80
+ * The dispatch interface for encode/decode at runtime: built once at `ExecutionContext` construction time by walking the contract's `storage.tables[].columns[]` and resolving each column through its descriptor's factory (per-instance for parameterized columns; the cached shared codec for non-parameterized columns). The dispatch path calls `forColumn(table, column).encode/decode(...)` and doesn't know whether the codec
81
+ * is parameterized.
82
+ *
83
+ * `forCodecId(codecId)` is the refs-less fallback. Every column-bound `ParamRef` carries `refs: { table; column }` and the builder-pipeline `validateParamRefRefs` pass enforces refs on every parameterized `ParamRef` before encode runs, so this fallback is only reached for non-parameterized codec ids.
94
84
  */
95
- class CodecRegistryImpl implements CodecRegistry {
96
- private readonly _byId = new Map<string, Codec<string>>();
97
- private readonly _byScalar = new Map<string, Codec<string>[]>();
98
-
99
- /**
100
- * Map-like interface for codec lookup by ID.
101
- * Example: registry.get('pg/text@1')
102
- */
103
- get(id: string): Codec<string> | undefined {
104
- return this._byId.get(id);
105
- }
106
-
85
+ export interface ContractCodecRegistry {
107
86
  /**
108
- * Check if a codec with the given ID is registered.
87
+ * Resolve the codec for `(table, column)`. Returns the per-instance parameterized codec for parameterized columns, the shared codec for non-parameterized columns, or `undefined` if the column is unknown or the codec isn't registered.
109
88
  */
110
- has(id: string): boolean {
111
- return this._byId.has(id);
112
- }
89
+ forColumn(table: string, column: string): Codec | undefined;
113
90
 
114
91
  /**
115
- * Get all codecs that handle a given scalar type.
116
- * Returns an empty frozen array if no codecs are found.
117
- * Example: registry.getByScalar('text') → [codec1, codec2, ...]
92
+ * Resolve a codec by id. For non-parameterized codecs this returns the canonical shared instance materialized once at context construction; for parameterized codecs it returns the column-resolved instance when a single column declares the codec id, or the `factory(undefined)` representative when the descriptor's factory is parameter-tolerant. Used by refs-less call sites; the validator pass guarantees the call site's
93
+ * `codecId` is non-parameterized (or parameter-tolerant) at this boundary.
118
94
  */
119
- getByScalar(scalar: string): readonly Codec<string>[] {
120
- return this._byScalar.get(scalar) ?? Object.freeze([]);
121
- }
122
-
123
- /**
124
- * Get the default codec for a scalar type (first registered codec).
125
- * Returns undefined if no codec handles this scalar type.
126
- */
127
- getDefaultCodec(scalar: string): Codec<string> | undefined {
128
- const _codecs = this._byScalar.get(scalar);
129
- return _codecs?.[0];
130
- }
131
-
132
- /**
133
- * Register a codec in the registry.
134
- * Throws an error if a codec with the same ID is already registered.
135
- *
136
- * @param codec - The codec to register
137
- * @throws Error if a codec with the same ID already exists
138
- */
139
- register(codec: Codec<string>): void {
140
- if (this._byId.has(codec.id)) {
141
- throw new Error(`Codec with ID '${codec.id}' is already registered`);
142
- }
143
-
144
- this._byId.set(codec.id, codec);
145
-
146
- // Update byScalar mapping
147
- for (const scalarType of codec.targetTypes) {
148
- const existing = this._byScalar.get(scalarType);
149
- if (existing) {
150
- existing.push(codec);
151
- } else {
152
- this._byScalar.set(scalarType, [codec]);
153
- }
154
- }
155
- }
156
-
157
- hasTrait(codecId: string, trait: CodecTrait): boolean {
158
- const codec = this._byId.get(codecId);
159
- return codec?.traits?.includes(trait) ?? false;
160
- }
161
-
162
- traitsOf(codecId: string): readonly CodecTrait[] {
163
- return this._byId.get(codecId)?.traits ?? [];
164
- }
165
-
166
- /**
167
- * Returns an iterator over all registered codecs.
168
- * Useful for iterating through codecs from another registry.
169
- */
170
- *[Symbol.iterator](): Iterator<Codec<string>> {
171
- for (const codec of this._byId.values()) {
172
- yield codec;
173
- }
174
- }
175
-
176
- /**
177
- * Returns an iterable of all registered codecs.
178
- */
179
- values(): IterableIterator<Codec<string>> {
180
- return this._byId.values();
181
- }
95
+ forCodecId(codecId: string): Codec | undefined;
182
96
  }
183
97
 
184
98
  /**
185
- * Conditional bundle for `encodeJson`/`decodeJson`: when `TInput` is
186
- * structurally assignable to `JsonValue` the identity defaults are
187
- * sound and both fields are optional; otherwise both fields are
188
- * required so an author cannot silently produce a non-JSON-safe
189
- * contract artifact.
99
+ * Variance-erased descriptor type used for heterogeneous storage in collection containers and on the unified contributor `codecs:` slot. The descriptor's `factory` and `renderOutputType` are contravariant in `P`, so descriptors with different params shapes are not in a subtype relationship; collecting them into one container needs an explicit variance erasure rather than `CodecDescriptor<unknown>` (which is the
100
+ * narrowest, not the widest, of the family).
190
101
  */
191
- type JsonRoundTripConfig<TInput> = [TInput] extends [JsonValue]
192
- ? {
193
- encodeJson?: (value: TInput) => JsonValue;
194
- decodeJson?: (json: JsonValue) => TInput;
195
- }
196
- : {
197
- encodeJson: (value: TInput) => JsonValue;
198
- decodeJson: (json: JsonValue) => TInput;
199
- };
102
+ // biome-ignore lint/suspicious/noExplicitAny: descriptor variance erasure — `P` is contravariant on the factory and renderOutputType slots, so heterogeneous descriptor storage cannot use `unknown`.
103
+ export type AnyCodecDescriptor = CodecDescriptor<any>;
104
+
105
+ type DescriptorResolvedCodec<D> =
106
+ D extends CodecDescriptor<infer _P> ? ReturnType<ReturnType<D['factory']>> : never;
107
+
108
+ export type DescriptorCodecId<D> = D extends AnyCodecDescriptor ? D['codecId'] : never;
109
+
110
+ export type DescriptorCodecInput<D> =
111
+ DescriptorResolvedCodec<D> extends BaseCodec<string, readonly CodecTrait[], unknown, infer In>
112
+ ? In
113
+ : never;
200
114
 
201
115
  /**
202
- * Construct a SQL codec from author functions and optional metadata.
203
- *
204
- * Author `encode` and `decode` as sync or async functions; the factory
205
- * produces a {@link Codec} whose query-time methods follow the boundary
206
- * contract documented on `Codec`.
116
+ * Resolve the trait union for a descriptor `D`.
207
117
  *
208
- * `encode` is optionalwhen omitted, an identity default is installed
209
- * (declaring "the input value already is the wire value", so `TInput` and
210
- * `TWire` are interchangeable for that codec). `decode` is always
211
- * required. `encodeJson` and `decodeJson` default to identity **only when
212
- * `TInput` is assignable to `JsonValue`**; otherwise both are required
213
- * so the contract artifact stays JSON-safe.
118
+ * Reads `traits` directly off the descriptor concrete descriptor classes declare `override readonly traits = [...] as const`, which preserves the literal trait tuple at the descriptor type. Reading from the resolved codec instance (`CodecImpl<…, TTraits, …>`) would lose the literal because `Codec` carries `TTraits` only on its optional phantom slot (`readonly __codecTraits?: TTraits`); codecs extending `CodecImpl`
119
+ * have no required structural site that pins `TTraits`, so a descriptor-keyed extractor reading from the codec instance would widen to the broad `CodecTrait` union.
214
120
  */
215
- export function codec<
216
- Id extends string,
217
- const TTraits extends readonly CodecTrait[] = readonly [],
218
- TWire = unknown,
219
- TInput = unknown,
220
- TParams = Record<string, unknown>,
221
- THelper = unknown,
222
- >(
223
- config: {
224
- typeId: Id;
225
- targetTypes: readonly string[];
226
- encode?: (value: TInput) => TWire | Promise<TWire>;
227
- decode: (wire: TWire) => TInput | Promise<TInput>;
228
- meta?: CodecMeta;
229
- paramsSchema?: Type<TParams>;
230
- init?: (params: TParams) => THelper;
231
- traits?: TTraits;
232
- renderOutputType?: (typeParams: Record<string, unknown>) => string | undefined;
233
- } & JsonRoundTripConfig<TInput>,
234
- ): Codec<Id, TTraits, TWire, TInput, TParams, THelper> {
235
- const identity = (v: unknown) => v;
236
- // The synchronous identity default is only safe when the author has
237
- // declared "the input is already the wire value" (i.e. TInput == TWire);
238
- // it returns the value directly, never a Promise.
239
- const userEncode = config.encode ?? ((value: TInput) => value as unknown as TWire);
240
- const userDecode = config.decode;
241
- // The conditional JsonRoundTripConfig narrows TInput|JsonValue at the
242
- // boundary; widen back to the generic shape inside the factory body.
243
- const widenedConfig = config as {
244
- encodeJson?: (value: TInput) => JsonValue;
245
- decodeJson?: (json: JsonValue) => TInput;
246
- };
247
- return {
248
- id: config.typeId,
249
- targetTypes: config.targetTypes,
250
- ...ifDefined('meta', config.meta),
251
- ...ifDefined('paramsSchema', config.paramsSchema),
252
- ...ifDefined('init', config.init),
253
- ...ifDefined(
254
- 'traits',
255
- config.traits ? (Object.freeze([...config.traits]) as TTraits) : undefined,
256
- ),
257
- ...ifDefined('renderOutputType', config.renderOutputType),
258
- encode: (value) => {
259
- try {
260
- return Promise.resolve(userEncode(value));
261
- } catch (error) {
262
- return Promise.reject(error);
263
- }
264
- },
265
- decode: (wire) => {
266
- try {
267
- return Promise.resolve(userDecode(wire));
268
- } catch (error) {
269
- return Promise.reject(error);
270
- }
271
- },
272
- encodeJson: (widenedConfig.encodeJson ?? identity) as (value: TInput) => JsonValue,
273
- decodeJson: (widenedConfig.decodeJson ?? identity) as (json: JsonValue) => TInput,
274
- };
121
+ export type DescriptorCodecTraits<D> = D extends {
122
+ readonly traits: infer TTraits extends readonly CodecTrait[];
275
123
  }
124
+ ? TTraits[number] & CodecTrait
125
+ : never;
276
126
 
277
127
  /**
278
- * Type helpers to extract codec types.
279
- */
280
- export type CodecId<T> =
281
- T extends Codec<infer Id> ? Id : T extends { readonly id: infer Id } ? Id : never;
282
- export type CodecInput<T> =
283
- T extends Codec<string, readonly CodecTrait[], unknown, infer In> ? In : never;
284
- export type CodecTraits<T> =
285
- T extends Codec<string, infer TTraits> ? TTraits[number] & CodecTrait : never;
286
-
287
- /**
288
- * Type helper to extract codec types from builder instance.
128
+ * Project a record of {@link AnyCodecDescriptor}s keyed by scalar name onto the codec-id-keyed `CodecTypes` shape consumed by emit and no-emit type pipelines (`{ readonly [codecId]: { input; output; traits } }`).
129
+ *
130
+ * Canonical extractor for the descriptor-keyed type pipeline; the legacy instance-keyed extractor and its `mkCodec`-bound builder retired alongside the carrier deletion.
289
131
  */
290
132
  export type ExtractCodecTypes<
291
- ScalarNames extends { readonly [K in keyof ScalarNames]: Codec<string> } = Record<never, never>,
133
+ ScalarNames extends {
134
+ readonly [K in keyof ScalarNames]: AnyCodecDescriptor;
135
+ } = Record<never, never>,
292
136
  > = {
293
- readonly [K in keyof ScalarNames as ScalarNames[K] extends Codec<infer Id> ? Id : never]: {
294
- readonly input: CodecInput<ScalarNames[K]>;
295
- readonly output: CodecInput<ScalarNames[K]>;
296
- readonly traits: CodecTraits<ScalarNames[K]>;
137
+ readonly [K in keyof ScalarNames as DescriptorCodecId<ScalarNames[K]>]: {
138
+ readonly input: DescriptorCodecInput<ScalarNames[K]>;
139
+ readonly output: DescriptorCodecInput<ScalarNames[K]>;
140
+ readonly traits: DescriptorCodecTraits<ScalarNames[K]>;
297
141
  };
298
142
  };
299
-
300
- /**
301
- * Type helper to extract data type IDs from builder instance.
302
- * Uses ExtractCodecTypes which preserves literal types as keys.
303
- * Since ExtractCodecTypes<Record<K, ScalarNames[K]>> has exactly one key (the Id),
304
- * we extract it by creating a mapped type that uses the Id as both key and value,
305
- * then extract the value type. This preserves literal types.
306
- */
307
- export type ExtractDataTypes<
308
- ScalarNames extends { readonly [K in keyof ScalarNames]: Codec<string> },
309
- > = {
310
- readonly [K in keyof ScalarNames]: {
311
- readonly [Id in keyof ExtractCodecTypes<Record<K, ScalarNames[K]>>]: Id;
312
- }[keyof ExtractCodecTypes<Record<K, ScalarNames[K]>>];
313
- };
314
-
315
- /**
316
- * Builder interface for declaring codecs.
317
- */
318
- export interface CodecDefBuilder<
319
- ScalarNames extends { readonly [K in keyof ScalarNames]: Codec<string> } = Record<never, never>,
320
- > {
321
- readonly CodecTypes: ExtractCodecTypes<ScalarNames>;
322
-
323
- add<ScalarName extends string, CodecImpl extends Codec<string>>(
324
- scalarName: ScalarName,
325
- codecImpl: CodecImpl,
326
- ): CodecDefBuilder<
327
- O.Overwrite<ScalarNames, Record<ScalarName, CodecImpl>> & Record<ScalarName, CodecImpl>
328
- >;
329
-
330
- readonly codecDefinitions: {
331
- readonly [K in keyof ScalarNames]: {
332
- readonly typeId: ScalarNames[K] extends Codec<infer Id extends string> ? Id : never;
333
- readonly scalar: K;
334
- readonly codec: ScalarNames[K];
335
- readonly input: CodecInput<ScalarNames[K]>;
336
- readonly output: CodecInput<ScalarNames[K]>;
337
- readonly jsType: CodecInput<ScalarNames[K]>;
338
- };
339
- };
340
-
341
- readonly dataTypes: {
342
- readonly [K in keyof ScalarNames]: {
343
- readonly [Id in keyof ExtractCodecTypes<Record<K, ScalarNames[K]>>]: Id;
344
- }[keyof ExtractCodecTypes<Record<K, ScalarNames[K]>>];
345
- };
346
- }
347
-
348
- /**
349
- * Implementation of CodecDefBuilder.
350
- */
351
- class CodecDefBuilderImpl<
352
- ScalarNames extends { readonly [K in keyof ScalarNames]: Codec<string> } = Record<never, never>,
353
- > implements CodecDefBuilder<ScalarNames>
354
- {
355
- private readonly _codecs: ScalarNames;
356
-
357
- public readonly CodecTypes: ExtractCodecTypes<ScalarNames>;
358
- public readonly dataTypes: {
359
- readonly [K in keyof ScalarNames]: {
360
- readonly [Id in keyof ExtractCodecTypes<Record<K, ScalarNames[K]>>]: Id;
361
- }[keyof ExtractCodecTypes<Record<K, ScalarNames[K]>>];
362
- };
363
-
364
- constructor(codecs: ScalarNames) {
365
- this._codecs = codecs;
366
-
367
- // Populate CodecTypes from codecs
368
- const codecTypes: Record<
369
- string,
370
- { readonly input: unknown; readonly output: unknown; readonly traits: unknown }
371
- > = {};
372
- for (const [, codecImpl] of Object.entries(this._codecs)) {
373
- const codecImplTyped = codecImpl as Codec<string>;
374
- codecTypes[codecImplTyped.id] = {
375
- input: undefined as unknown as CodecInput<typeof codecImplTyped>,
376
- output: undefined as unknown as CodecInput<typeof codecImplTyped>,
377
- traits: undefined as unknown as CodecTraits<typeof codecImplTyped>,
378
- };
379
- }
380
- this.CodecTypes = codecTypes as ExtractCodecTypes<ScalarNames>;
381
-
382
- // Populate dataTypes from codecs - extract id property from each codec
383
- // Build object preserving keys from ScalarNames
384
- // Type assertion is safe because we know ScalarNames structure matches the return type
385
- // biome-ignore lint/suspicious/noExplicitAny: dynamic codec mapping requires any
386
- const dataTypes = {} as any;
387
- for (const key in this._codecs) {
388
- if (Object.hasOwn(this._codecs, key)) {
389
- const codec = this._codecs[key] as Codec<string>;
390
- dataTypes[key] = codec.id;
391
- }
392
- }
393
- this.dataTypes = dataTypes as {
394
- readonly [K in keyof ScalarNames]: {
395
- readonly [Id in keyof ExtractCodecTypes<Record<K, ScalarNames[K]>>]: Id;
396
- }[keyof ExtractCodecTypes<Record<K, ScalarNames[K]>>];
397
- };
398
- }
399
-
400
- add<ScalarName extends string, CodecImpl extends Codec<string>>(
401
- scalarName: ScalarName,
402
- codecImpl: CodecImpl,
403
- ): CodecDefBuilder<
404
- O.Overwrite<ScalarNames, Record<ScalarName, CodecImpl>> & Record<ScalarName, CodecImpl>
405
- > {
406
- return new CodecDefBuilderImpl({
407
- ...this._codecs,
408
- [scalarName]: codecImpl,
409
- } as O.Overwrite<ScalarNames, Record<ScalarName, CodecImpl>> & Record<ScalarName, CodecImpl>);
410
- }
411
-
412
- /**
413
- * Derive codecDefinitions structure.
414
- */
415
- get codecDefinitions(): {
416
- readonly [K in keyof ScalarNames]: {
417
- readonly typeId: ScalarNames[K] extends Codec<infer Id> ? Id : never;
418
- readonly scalar: K;
419
- readonly codec: ScalarNames[K];
420
- readonly input: CodecInput<ScalarNames[K]>;
421
- readonly output: CodecInput<ScalarNames[K]>;
422
- readonly jsType: CodecInput<ScalarNames[K]>;
423
- };
424
- } {
425
- const result: Record<
426
- string,
427
- {
428
- typeId: string;
429
- scalar: string;
430
- codec: Codec;
431
- input: unknown;
432
- output: unknown;
433
- jsType: unknown;
434
- }
435
- > = {};
436
-
437
- for (const [scalarName, codecImpl] of Object.entries(this._codecs)) {
438
- const codec = codecImpl as Codec<string>;
439
- result[scalarName] = {
440
- typeId: codec.id,
441
- scalar: scalarName,
442
- codec: codec,
443
- input: undefined as unknown as CodecInput<typeof codec>,
444
- output: undefined as unknown as CodecInput<typeof codec>,
445
- jsType: undefined as unknown as CodecInput<typeof codec>,
446
- };
447
- }
448
-
449
- return result as {
450
- readonly [K in keyof ScalarNames]: {
451
- readonly typeId: ScalarNames[K] extends Codec<infer Id extends string> ? Id : never;
452
- readonly scalar: K;
453
- readonly codec: ScalarNames[K];
454
- readonly input: CodecInput<ScalarNames[K]>;
455
- readonly output: CodecInput<ScalarNames[K]>;
456
- readonly jsType: CodecInput<ScalarNames[K]>;
457
- };
458
- };
459
- }
460
- }
461
-
462
- /**
463
- * Create a new codec registry.
464
- */
465
- export function createCodecRegistry(): CodecRegistry {
466
- return new CodecRegistryImpl();
467
- }
468
-
469
- /**
470
- * Create a new codec definition builder.
471
- */
472
- export function defineCodecs(): CodecDefBuilder<Record<never, never>> {
473
- return new CodecDefBuilderImpl({});
474
- }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Shared encode/decode/render constants and codec id literals for the six SQL base codecs (`sql/char@1`, `sql/varchar@1`, `sql/int@1`, `sql/float@1`, `sql/text@1`, `sql/timestamp@1`).
3
+ *
4
+ * The codec implementations live in `sql-codecs.ts` (TML-2357). This module retains only the conversion helpers + emit-path renderers the codec methods compose with — keeping a single source of truth for non-trivial conversions while the codec methods provide the framework-required `Promise<…>` boundary.
5
+ */
6
+
7
+ import type { JsonValue } from '@prisma-next/contract/types';
8
+
9
+ export const SQL_CHAR_CODEC_ID = 'sql/char@1' as const;
10
+ export const SQL_VARCHAR_CODEC_ID = 'sql/varchar@1' as const;
11
+ export const SQL_INT_CODEC_ID = 'sql/int@1' as const;
12
+ export const SQL_FLOAT_CODEC_ID = 'sql/float@1' as const;
13
+ export const SQL_TEXT_CODEC_ID = 'sql/text@1' as const;
14
+ export const SQL_TIMESTAMP_CODEC_ID = 'sql/timestamp@1' as const;
15
+
16
+ export const sqlCharEncode = (value: string): string => value;
17
+ export const sqlCharDecode = (wire: string): string => wire.trimEnd();
18
+ export const sqlCharRenderOutputType = (typeParams: { readonly length?: number }) => {
19
+ const length = typeParams.length;
20
+ if (length === undefined) return undefined;
21
+ if (typeof length !== 'number' || !Number.isFinite(length) || !Number.isInteger(length)) {
22
+ throw new Error(
23
+ `renderOutputType: expected integer "length" in typeParams for Char, got ${String(length)}`,
24
+ );
25
+ }
26
+ return `Char<${length}>`;
27
+ };
28
+
29
+ export const sqlVarcharEncode = (value: string): string => value;
30
+ export const sqlVarcharDecode = (wire: string): string => wire;
31
+ export const sqlVarcharRenderOutputType = (typeParams: { readonly length?: number }) => {
32
+ const length = typeParams.length;
33
+ if (length === undefined) return undefined;
34
+ if (typeof length !== 'number' || !Number.isFinite(length) || !Number.isInteger(length)) {
35
+ throw new Error(
36
+ `renderOutputType: expected integer "length" in typeParams for Varchar, got ${String(length)}`,
37
+ );
38
+ }
39
+ return `Varchar<${length}>`;
40
+ };
41
+
42
+ export const sqlIntEncode = (value: number): number => value;
43
+ export const sqlIntDecode = (wire: number): number => wire;
44
+
45
+ export const sqlFloatEncode = (value: number): number => value;
46
+ export const sqlFloatDecode = (wire: number): number => wire;
47
+
48
+ export const sqlTextEncode = (value: string): string => value;
49
+ export const sqlTextDecode = (wire: string): string => wire;
50
+
51
+ export const sqlTimestampEncode = (value: Date): Date => value;
52
+ export const sqlTimestampDecode = (wire: Date): Date => wire;
53
+ export const sqlTimestampEncodeJson = (value: Date): JsonValue => value.toISOString();
54
+ export const sqlTimestampDecodeJson = (json: JsonValue): Date => {
55
+ if (typeof json !== 'string') {
56
+ throw new Error(`Expected ISO date string for sql/timestamp@1, got ${typeof json}`);
57
+ }
58
+ const date = new Date(json);
59
+ if (Number.isNaN(date.getTime())) {
60
+ throw new Error(`Invalid ISO date string for sql/timestamp@1: ${json}`);
61
+ }
62
+ return date;
63
+ };
64
+ export const sqlTimestampRenderOutputType = (typeParams: { readonly precision?: number }) => {
65
+ const precision = typeParams.precision;
66
+ if (precision === undefined) {
67
+ return 'Timestamp';
68
+ }
69
+ if (
70
+ typeof precision !== 'number' ||
71
+ !Number.isFinite(precision) ||
72
+ !Number.isInteger(precision)
73
+ ) {
74
+ throw new Error(
75
+ `renderOutputType: expected integer "precision" in typeParams for Timestamp, got ${String(precision)}`,
76
+ );
77
+ }
78
+ return `Timestamp<${precision}>`;
79
+ };