@orpc/json-schema 2.0.0-beta.49 → 2.0.0-beta.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/ref-utils.js CHANGED
@@ -1,253 +1,203 @@
1
+ import { JSON_SCHEMA_LITERAL_KEYWORDS, JSON_SCHEMA_LOGIC_KEYWORDS, JSON_SCHEMA_RECORD_KEYWORDS } from "./constants.js";
2
+ import { get, isPlainObject, setOwn } from "@orpc/shared";
3
+ // src/ref-utils.ts
1
4
  /**
2
- * These utilities assume the schema has only one root-level `$defs` object
3
- * and exclusively use absolute JSON pointers for `$ref` values.
4
- */
5
- import { get, isPlainObject, setOwn } from '@orpc/shared';
6
- import { JSON_SCHEMA_LITERAL_KEYWORDS, JSON_SCHEMA_LOGIC_KEYWORDS, JSON_SCHEMA_RECORD_KEYWORDS, } from './constants.js';
5
+ * These utilities assume the schema has only one root-level `$defs` object
6
+ * and exclusively use absolute JSON pointers for `$ref` values.
7
+ */
7
8
  /**
8
- * Encodes a JSON Pointer segment according to RFC 6901.
9
- *
10
- * https://datatracker.ietf.org/doc/html/rfc6901
11
- */
12
- export function encodeJsonPointerSegment(segment) {
13
- return segment.replaceAll('~', '~0').replaceAll('/', '~1');
9
+ * Encodes a JSON Pointer segment according to RFC 6901.
10
+ *
11
+ * https://datatracker.ietf.org/doc/html/rfc6901
12
+ */
13
+ function encodeJsonPointerSegment(segment) {
14
+ return segment.replaceAll("~", "~0").replaceAll("/", "~1");
14
15
  }
15
16
  /**
16
- * Decodes a JSON Pointer segment according to RFC 6901.
17
- *
18
- * https://datatracker.ietf.org/doc/html/rfc6901
19
- */
20
- export function decodeJsonPointerSegment(segment) {
21
- return segment.replaceAll('~1', '/').replaceAll('~0', '~');
17
+ * Decodes a JSON Pointer segment according to RFC 6901.
18
+ *
19
+ * https://datatracker.ietf.org/doc/html/rfc6901
20
+ */
21
+ function decodeJsonPointerSegment(segment) {
22
+ return segment.replaceAll("~1", "/").replaceAll("~0", "~");
22
23
  }
23
24
  /**
24
- * Resolves a local JSON pointer ref (`#` or `#/...`) against the root schema.
25
- * Returns `undefined` for non-local refs and missing targets.
26
- */
27
- export function resolveJsonSchemaLocalPointer(root, ref) {
28
- if (ref === '#') {
29
- return root;
30
- }
31
- if (!ref.startsWith('#/')) {
32
- return undefined;
33
- }
34
- return get(root, ref.slice(2).split('/').map(decodeJsonPointerSegment));
25
+ * Resolves a local JSON pointer ref (`#` or `#/...`) against the root schema.
26
+ * Returns `undefined` for non-local refs and missing targets.
27
+ */
28
+ function resolveJsonSchemaLocalPointer(root, ref) {
29
+ if (ref === "#") return root;
30
+ if (!ref.startsWith("#/")) return;
31
+ return get(root, ref.slice(2).split("/").map(decodeJsonPointerSegment));
35
32
  }
36
33
  /**
37
- * Classifies `value` under `key` in a schema object, as traversed by {@link visitJsonSchemaRefs}
38
- * and {@link mapJsonSchemaRefs}: a `$ref` string, an OpenAPI `discriminator`, a subschema (or list
39
- * of subschemas), a record of subschemas, or data that holds no refs (including `const`/`enum`).
40
- *
41
- * @param schemaLevel `false` when the object is itself a record of subschemas, e.g. `properties`.
42
- */
43
- export function getJsonSchemaKeywordKind(key, value, schemaLevel = true) {
44
- if (key === '$ref' && typeof value === 'string') {
45
- return 'ref';
46
- }
47
- if (!schemaLevel) {
48
- return 'schema';
49
- }
50
- if (key === 'discriminator') {
51
- return 'discriminator';
52
- }
53
- if (JSON_SCHEMA_RECORD_KEYWORDS.has(key)) {
54
- return 'schema-record';
55
- }
56
- if (JSON_SCHEMA_LOGIC_KEYWORDS.has(key) && !JSON_SCHEMA_LITERAL_KEYWORDS.has(key)) {
57
- return 'schema';
58
- }
59
- return 'data';
34
+ * Classifies `value` under `key` in a schema object, as traversed by {@link visitJsonSchemaRefs}
35
+ * and {@link mapJsonSchemaRefs}: a `$ref` string, an OpenAPI `discriminator`, a subschema (or list
36
+ * of subschemas), a record of subschemas, or data that holds no refs (including `const`/`enum`).
37
+ *
38
+ * @param schemaLevel `false` when the object is itself a record of subschemas, e.g. `properties`.
39
+ */
40
+ function getJsonSchemaKeywordKind(key, value, schemaLevel = true) {
41
+ if (key === "$ref" && typeof value === "string") return "ref";
42
+ if (!schemaLevel) return "schema";
43
+ if (key === "discriminator") return "discriminator";
44
+ if (JSON_SCHEMA_RECORD_KEYWORDS.has(key)) return "schema-record";
45
+ if (JSON_SCHEMA_LOGIC_KEYWORDS.has(key) && !JSON_SCHEMA_LITERAL_KEYWORDS.has(key)) return "schema";
46
+ return "data";
60
47
  }
61
48
  /**
62
- * OpenAPI `discriminator.mapping` and `discriminator.defaultMapping` values are refs when they
63
- * are local JSON pointers; other values (bare schema names, external refs) are left alone.
64
- */
49
+ * OpenAPI `discriminator.mapping` and `discriminator.defaultMapping` values are refs when they
50
+ * are local JSON pointers; other values (bare schema names, external refs) are left alone.
51
+ */
65
52
  function isDiscriminatorRef(value) {
66
- return typeof value === 'string' && value.startsWith('#');
53
+ return typeof value === "string" && value.startsWith("#");
67
54
  }
68
55
  function visitDiscriminatorRefs(discriminator, visit) {
69
- if (!isPlainObject(discriminator)) {
70
- return;
71
- }
72
- const { mapping, defaultMapping } = discriminator;
73
- const values = isPlainObject(mapping)
74
- ? [...Object.values(mapping), defaultMapping]
75
- : [defaultMapping];
76
- for (const value of values) {
77
- if (isDiscriminatorRef(value)) {
78
- visit(value);
79
- }
80
- }
56
+ if (!isPlainObject(discriminator)) return;
57
+ const { mapping, defaultMapping } = discriminator;
58
+ const values = isPlainObject(mapping) ? [...Object.values(mapping), defaultMapping] : [defaultMapping];
59
+ for (const value of values) if (isDiscriminatorRef(value)) visit(value);
81
60
  }
82
61
  /**
83
- * Visits every `$ref` in a schema, traversing the same keywords as {@link mapJsonSchemaRefs}.
84
- * Local pointers in OpenAPI `discriminator.mapping`/`defaultMapping` values are visited too.
85
- * Shared or cyclic object instances are visited once.
86
- */
87
- export function visitJsonSchemaRefs(value, visit, schemaLevel = true, seen = new Set()) {
88
- if (!value || typeof value !== 'object' || seen.has(value)) {
89
- return;
90
- }
91
- seen.add(value);
92
- if (Array.isArray(value)) {
93
- for (const item of value) {
94
- visitJsonSchemaRefs(item, visit, schemaLevel, seen);
95
- }
96
- return;
97
- }
98
- for (const key of Object.keys(value)) {
99
- const val = value[key];
100
- switch (getJsonSchemaKeywordKind(key, val, schemaLevel)) {
101
- case 'ref':
102
- visit(val);
103
- break;
104
- case 'discriminator':
105
- visitDiscriminatorRefs(val, visit);
106
- break;
107
- case 'schema':
108
- visitJsonSchemaRefs(val, visit, true, seen);
109
- break;
110
- case 'schema-record':
111
- visitJsonSchemaRefs(val, visit, false, seen);
112
- break;
113
- }
114
- }
62
+ * Visits every `$ref` in a schema, traversing the same keywords as {@link mapJsonSchemaRefs}.
63
+ * Local pointers in OpenAPI `discriminator.mapping`/`defaultMapping` values are visited too.
64
+ * Shared or cyclic object instances are visited once.
65
+ */
66
+ function visitJsonSchemaRefs(value, visit, schemaLevel = true, seen = /* @__PURE__ */ new Set()) {
67
+ if (!value || typeof value !== "object" || seen.has(value)) return;
68
+ seen.add(value);
69
+ if (Array.isArray(value)) {
70
+ for (const item of value) visitJsonSchemaRefs(item, visit, schemaLevel, seen);
71
+ return;
72
+ }
73
+ for (const key of Object.keys(value)) {
74
+ const val = value[key];
75
+ switch (getJsonSchemaKeywordKind(key, val, schemaLevel)) {
76
+ case "ref":
77
+ visit(val);
78
+ break;
79
+ case "discriminator":
80
+ visitDiscriminatorRefs(val, visit);
81
+ break;
82
+ case "schema":
83
+ visitJsonSchemaRefs(val, visit, true, seen);
84
+ break;
85
+ case "schema-record": visitJsonSchemaRefs(val, visit, false, seen);
86
+ }
87
+ }
115
88
  }
116
- export function mapJsonSchemaRefs(value, map, schemaLevel = true, path = []) {
117
- if (!value || typeof value !== 'object') {
118
- return value;
119
- }
120
- if (Array.isArray(value)) {
121
- return value.map((item, index) => mapJsonSchemaRefs(item, map, schemaLevel, [...path, index]));
122
- }
123
- const result = {};
124
- for (const key of Object.keys(value)) {
125
- const val = value[key];
126
- switch (getJsonSchemaKeywordKind(key, val, schemaLevel)) {
127
- case 'ref':
128
- setOwn(result, key, map(val, [...path, key]));
129
- break;
130
- case 'discriminator':
131
- setOwn(result, key, mapDiscriminatorRefs(val, map, path));
132
- break;
133
- case 'schema':
134
- setOwn(result, key, mapJsonSchemaRefs(val, map, true, [...path, key]));
135
- break;
136
- case 'schema-record':
137
- setOwn(result, key, mapJsonSchemaRefs(val, map, false, [...path, key]));
138
- break;
139
- default:
140
- setOwn(result, key, val);
141
- }
142
- }
143
- return result;
89
+ function mapJsonSchemaRefs(value, map, schemaLevel = true, path = []) {
90
+ if (!value || typeof value !== "object") return value;
91
+ if (Array.isArray(value)) return value.map((item, index) => mapJsonSchemaRefs(item, map, schemaLevel, [...path, index]));
92
+ const result = {};
93
+ for (const key of Object.keys(value)) {
94
+ const val = value[key];
95
+ switch (getJsonSchemaKeywordKind(key, val, schemaLevel)) {
96
+ case "ref":
97
+ setOwn(result, key, map(val, [...path, key]));
98
+ break;
99
+ case "discriminator":
100
+ setOwn(result, key, mapDiscriminatorRefs(val, map, path));
101
+ break;
102
+ case "schema":
103
+ setOwn(result, key, mapJsonSchemaRefs(val, map, true, [...path, key]));
104
+ break;
105
+ case "schema-record":
106
+ setOwn(result, key, mapJsonSchemaRefs(val, map, false, [...path, key]));
107
+ break;
108
+ default: setOwn(result, key, val);
109
+ }
110
+ }
111
+ return result;
144
112
  }
145
113
  function mapDiscriminatorRefs(discriminator, map, path) {
146
- if (!isPlainObject(discriminator)) {
147
- return discriminator;
148
- }
149
- const { mapping, defaultMapping } = discriminator;
150
- let mappedMapping;
151
- if (isPlainObject(mapping)) {
152
- for (const key of Object.keys(mapping)) {
153
- const ref = mapping[key];
154
- if (isDiscriminatorRef(ref)) {
155
- mappedMapping ??= { ...mapping };
156
- setOwn(mappedMapping, key, map(ref, [...path, 'discriminator', 'mapping', key]));
157
- }
158
- }
159
- }
160
- const hasDefaultMappingRef = isDiscriminatorRef(defaultMapping);
161
- if (!mappedMapping && !hasDefaultMappingRef) {
162
- return discriminator;
163
- }
164
- return {
165
- ...discriminator,
166
- ...(mappedMapping && { mapping: mappedMapping }),
167
- ...(hasDefaultMappingRef && {
168
- defaultMapping: map(defaultMapping, [...path, 'discriminator', 'defaultMapping']),
169
- }),
170
- };
114
+ if (!isPlainObject(discriminator)) return discriminator;
115
+ const { mapping, defaultMapping } = discriminator;
116
+ let mappedMapping;
117
+ if (isPlainObject(mapping)) for (const key of Object.keys(mapping)) {
118
+ const ref = mapping[key];
119
+ if (isDiscriminatorRef(ref)) {
120
+ mappedMapping ??= { ...mapping };
121
+ setOwn(mappedMapping, key, map(ref, [
122
+ ...path,
123
+ "discriminator",
124
+ "mapping",
125
+ key
126
+ ]));
127
+ }
128
+ }
129
+ const hasDefaultMappingRef = isDiscriminatorRef(defaultMapping);
130
+ if (!mappedMapping && !hasDefaultMappingRef) return discriminator;
131
+ return {
132
+ ...discriminator,
133
+ ...mappedMapping && { mapping: mappedMapping },
134
+ ...hasDefaultMappingRef && { defaultMapping: map(defaultMapping, [
135
+ ...path,
136
+ "discriminator",
137
+ "defaultMapping"
138
+ ]) }
139
+ };
171
140
  }
172
141
  /**
173
- * Rewrites recursive root `#` refs by moving the schema body into `$defs`.
174
- */
175
- export function hoistRecursiveRefToDef(schema) {
176
- if (typeof schema !== 'object') {
177
- return schema;
178
- }
179
- const isRootRef = (ref) => ref === '#' ||
180
- (!ref.startsWith('#/$defs/') && resolveJsonSchemaLocalPointer(schema, ref) !== undefined);
181
- // most schemas have no root ref, so detect one without copying the schema
182
- let hasRootRef = false;
183
- visitJsonSchemaRefs(schema, (ref) => {
184
- hasRootRef ||= isRootRef(ref);
185
- });
186
- if (!hasRootRef) {
187
- return schema;
188
- }
189
- const defName = findRecursiveJsonSchemaDefName(schema.$defs);
190
- const defRef = `#/$defs/${encodeJsonPointerSegment(defName)}`;
191
- const { $defs, ...rest } = mapJsonSchemaRefs(schema, (ref) => isRootRef(ref) ? `${defRef}${ref.slice(1)}` : ref);
192
- return {
193
- $ref: defRef,
194
- $defs: {
195
- ...$defs,
196
- [defName]: rest,
197
- },
198
- };
142
+ * Rewrites recursive root `#` refs by moving the schema body into `$defs`.
143
+ */
144
+ function hoistRecursiveRefToDef(schema) {
145
+ if (typeof schema !== "object") return schema;
146
+ const isRootRef = (ref) => ref === "#" || !ref.startsWith("#/$defs/") && resolveJsonSchemaLocalPointer(schema, ref) !== void 0;
147
+ let hasRootRef = false;
148
+ visitJsonSchemaRefs(schema, (ref) => {
149
+ hasRootRef ||= isRootRef(ref);
150
+ });
151
+ if (!hasRootRef) return schema;
152
+ const defName = findRecursiveJsonSchemaDefName(schema.$defs);
153
+ const defRef = `#/$defs/${encodeJsonPointerSegment(defName)}`;
154
+ const { $defs, ...rest } = mapJsonSchemaRefs(schema, (ref) => isRootRef(ref) ? `${defRef}${ref.slice(1)}` : ref);
155
+ return {
156
+ $ref: defRef,
157
+ $defs: {
158
+ ...$defs,
159
+ [defName]: rest
160
+ }
161
+ };
199
162
  }
200
163
  /**
201
- * Resolves a local `$ref` at the **root level** of the given schema, if present.
202
- *
203
- * Only handles refs of the form `#/$defs/<name>` pointing into the provided
204
- * (or schema-embedded) `$defs` map. Nested `$ref`s inside sub-schemas are
205
- * intentionally left untouched.
206
- *
207
- * If the ref cannot be resolved (missing `$defs`, unknown key, etc.) the
208
- * schema is returned as-is. Chained refs are followed until one repeats,
209
- * which is kept.
210
- *
211
- * @param schema - The schema whose root-level `$ref` should be resolved.
212
- * @param $defs - Definition map to resolve against. If omitted, falls back to
213
- * `schema.$defs`. When provided, takes precedence over any `$defs` embedded
214
- * in the schema.
215
- */
216
- export function resolveJsonSchemaRootLocalRef(schema, $defs) {
217
- if (typeof schema === 'boolean') {
218
- return schema;
219
- }
220
- if (arguments.length === 1) {
221
- $defs = schema.$defs;
222
- }
223
- if (!$defs) {
224
- return schema;
225
- }
226
- const followedRefs = new Set();
227
- let current = schema;
228
- while (typeof current.$ref === 'string' &&
229
- current.$ref.startsWith('#/$defs/') &&
230
- !followedRefs.has(current.$ref)) {
231
- followedRefs.add(current.$ref);
232
- const resolved = get($defs, current.$ref.slice('#/$defs/'.length).split('/').map(decodeJsonPointerSegment));
233
- if (resolved === undefined) {
234
- return current;
235
- }
236
- if (typeof resolved !== 'object') {
237
- return resolved;
238
- }
239
- const { $ref: _ref, ...rest } = current;
240
- current = {
241
- ...rest,
242
- ...resolved,
243
- };
244
- }
245
- return current;
164
+ * Resolves a local `$ref` at the **root level** of the given schema, if present.
165
+ *
166
+ * Only handles refs of the form `#/$defs/<name>` pointing into the provided
167
+ * (or schema-embedded) `$defs` map. Nested `$ref`s inside sub-schemas are
168
+ * intentionally left untouched.
169
+ *
170
+ * If the ref cannot be resolved (missing `$defs`, unknown key, etc.) the
171
+ * schema is returned as-is. Chained refs are followed until one repeats,
172
+ * which is kept.
173
+ *
174
+ * @param schema - The schema whose root-level `$ref` should be resolved.
175
+ * @param $defs - Definition map to resolve against. If omitted, falls back to
176
+ * `schema.$defs`. When provided, takes precedence over any `$defs` embedded
177
+ * in the schema.
178
+ */
179
+ function resolveJsonSchemaRootLocalRef(schema, $defs) {
180
+ if (typeof schema === "boolean") return schema;
181
+ if (arguments.length === 1) $defs = schema.$defs;
182
+ if (!$defs) return schema;
183
+ const followedRefs = /* @__PURE__ */ new Set();
184
+ let current = schema;
185
+ while (typeof current.$ref === "string" && current.$ref.startsWith("#/$defs/") && !followedRefs.has(current.$ref)) {
186
+ followedRefs.add(current.$ref);
187
+ const resolved = get($defs, current.$ref.slice(8).split("/").map(decodeJsonPointerSegment));
188
+ if (resolved === void 0) return current;
189
+ if (typeof resolved !== "object") return resolved;
190
+ const { $ref: _ref, ...rest } = current;
191
+ current = {
192
+ ...rest,
193
+ ...resolved
194
+ };
195
+ }
196
+ return current;
246
197
  }
247
198
  function findRecursiveJsonSchemaDefName(defs) {
248
- let index = 0;
249
- while (defs?.[`__schema${index}`] !== undefined) {
250
- index++;
251
- }
252
- return `__schema${index}`;
199
+ let index = 0;
200
+ while (defs?.[`__schema${index}`] !== void 0) index++;
201
+ return `__schema${index}`;
253
202
  }
203
+ export { decodeJsonPointerSegment, encodeJsonPointerSegment, getJsonSchemaKeywordKind, hoistRecursiveRefToDef, mapJsonSchemaRefs, resolveJsonSchemaLocalPointer, resolveJsonSchemaRootLocalRef, visitJsonSchemaRefs };
@@ -1,9 +1,9 @@
1
- import type { Context } from '@orpc/server';
2
- import type { StandardHandlerOptions, StandardHandlerPlugin } from '@orpc/server/standard';
3
- import type { JsonSchemaCoercerOptions } from './coercer.ts';
4
- import type { JsonSchemaConverter } from './convert.ts';
1
+ import { JsonSchemaCoercerOptions } from "./coercer.js";
2
+ import { JsonSchemaConverter } from "./convert.js";
3
+ import { Context } from "@orpc/server";
4
+ import { StandardHandlerOptions, StandardHandlerPlugin } from "@orpc/server/standard";
5
5
  export interface SmartCoercionHandlerPluginOptions extends JsonSchemaCoercerOptions {
6
- converters?: JsonSchemaConverter[] | undefined;
6
+ converters?: JsonSchemaConverter[] | undefined;
7
7
  }
8
8
  /**
9
9
  * Coerces incoming request data to match the expected `.input` schema types before validation,
@@ -12,11 +12,11 @@ export interface SmartCoercionHandlerPluginOptions extends JsonSchemaCoercerOpti
12
12
  * @see {@link https://orpc.dev/docs/plugins/smart-coercion | Smart Coercion Plugin}
13
13
  */
14
14
  export declare class SmartCoercionHandlerPlugin<T extends Context> implements StandardHandlerPlugin<T> {
15
- name: string;
16
- private readonly converter;
17
- private readonly coercer;
18
- private readonly cache;
19
- constructor(options?: SmartCoercionHandlerPluginOptions);
20
- init(options: StandardHandlerOptions<T>): StandardHandlerOptions<T>;
21
- private coerceValue;
22
- }
15
+ name: string;
16
+ private readonly converter;
17
+ private readonly coercer;
18
+ private readonly cache;
19
+ constructor(options?: SmartCoercionHandlerPluginOptions);
20
+ init(options: StandardHandlerOptions<T>): StandardHandlerOptions<T>;
21
+ private coerceValue;
22
+ }
@@ -1,50 +1,47 @@
1
- import { toArray } from '@orpc/shared';
2
- import { JsonSchemaCoercer } from './coercer.js';
3
- import { DelegatingJsonSchemaConverter } from './convert.js';
4
- import { StandardJsonSchemaConverter } from './standard-json-schema-converter.js';
1
+ import { JsonSchemaCoercer } from "./coercer.js";
2
+ import { DelegatingJsonSchemaConverter } from "./convert.js";
3
+ import { StandardJsonSchemaConverter } from "./standard-json-schema-converter.js";
4
+ import { toArray } from "@orpc/shared";
5
+ // src/smart-coercion-handler-plugin.ts
5
6
  /**
6
- * Coerces incoming request data to match the expected `.input` schema types before validation,
7
- * based on JSON schemas produced by the configured converters.
8
- *
9
- * @see {@link https://orpc.dev/docs/plugins/smart-coercion | Smart Coercion Plugin}
10
- */
11
- export class SmartCoercionHandlerPlugin {
12
- name = '~smart-coercion';
13
- converter;
14
- coercer;
15
- cache = new WeakMap();
16
- constructor(options = {}) {
17
- this.converter = new DelegatingJsonSchemaConverter([
18
- ...toArray(options.converters),
19
- new StandardJsonSchemaConverter(),
20
- ]);
21
- this.coercer = new JsonSchemaCoercer(options);
22
- }
23
- init(options) {
24
- return {
25
- ...options,
26
- clientInterceptors: [
27
- ({ next, input, ...interceptorOptions }) => {
28
- const inputSchemas = interceptorOptions.procedure['~orpc'].inputSchemas;
29
- if (!inputSchemas) {
30
- return next();
31
- }
32
- const coercedInput = this.coerceValue(inputSchemas, input);
33
- return next({ ...interceptorOptions, input: coercedInput });
34
- },
35
- ...toArray(options.clientInterceptors),
36
- ],
37
- };
38
- }
39
- coerceValue(schemas, value) {
40
- for (const schema of schemas) {
41
- let converted = this.cache.get(schema);
42
- if (!converted) {
43
- converted = this.converter.convert(schema, 'input');
44
- this.cache.set(schema, converted);
45
- }
46
- value = this.coercer.coerce(converted, value);
47
- }
48
- return value;
49
- }
50
- }
7
+ * Coerces incoming request data to match the expected `.input` schema types before validation,
8
+ * based on JSON schemas produced by the configured converters.
9
+ *
10
+ * @see {@link https://orpc.dev/docs/plugins/smart-coercion | Smart Coercion Plugin}
11
+ */
12
+ var SmartCoercionHandlerPlugin = class {
13
+ name = "~smart-coercion";
14
+ converter;
15
+ coercer;
16
+ cache = /* @__PURE__ */ new WeakMap();
17
+ constructor(options = {}) {
18
+ this.converter = new DelegatingJsonSchemaConverter([...toArray(options.converters), new StandardJsonSchemaConverter()]);
19
+ this.coercer = new JsonSchemaCoercer(options);
20
+ }
21
+ init(options) {
22
+ return {
23
+ ...options,
24
+ clientInterceptors: [({ next, input, ...interceptorOptions }) => {
25
+ const inputSchemas = interceptorOptions.procedure["~orpc"].inputSchemas;
26
+ if (!inputSchemas) return next();
27
+ const coercedInput = this.coerceValue(inputSchemas, input);
28
+ return next({
29
+ ...interceptorOptions,
30
+ input: coercedInput
31
+ });
32
+ }, ...toArray(options.clientInterceptors)]
33
+ };
34
+ }
35
+ coerceValue(schemas, value) {
36
+ for (const schema of schemas) {
37
+ let converted = this.cache.get(schema);
38
+ if (!converted) {
39
+ converted = this.converter.convert(schema, "input");
40
+ this.cache.set(schema, converted);
41
+ }
42
+ value = this.coercer.coerce(converted, value);
43
+ }
44
+ return value;
45
+ }
46
+ };
47
+ export { SmartCoercionHandlerPlugin };
@@ -1,10 +1,10 @@
1
- import type { ClientContext } from '@orpc/client';
2
- import type { StandardLinkOptions, StandardLinkPlugin } from '@orpc/client/standard';
3
- import type { RouterContract } from '@orpc/contract';
4
- import type { JsonSchemaCoercerOptions } from './coercer.ts';
5
- import type { JsonSchemaConverter } from './convert.ts';
1
+ import { JsonSchemaCoercerOptions } from "./coercer.js";
2
+ import { JsonSchemaConverter } from "./convert.js";
3
+ import { ClientContext } from "@orpc/client";
4
+ import { RouterContract } from "@orpc/contract";
5
+ import { StandardLinkOptions, StandardLinkPlugin } from "@orpc/client/standard";
6
6
  export interface SmartCoercionLinkPluginOptions extends JsonSchemaCoercerOptions {
7
- converters?: JsonSchemaConverter[] | undefined;
7
+ converters?: JsonSchemaConverter[] | undefined;
8
8
  }
9
9
  /**
10
10
  * Coerces server responses to match the expected `.output` or `.errors` schema types before validation,
@@ -13,16 +13,16 @@ export interface SmartCoercionLinkPluginOptions extends JsonSchemaCoercerOptions
13
13
  * @see {@link https://orpc.dev/docs/plugins/smart-coercion | Smart Coercion Plugin}
14
14
  */
15
15
  export declare class SmartCoercionLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
16
- private readonly contract;
17
- name: string;
18
- /**
19
- * Output and error values should be coerced before validation.
20
- */
21
- after: string[];
22
- private readonly converter;
23
- private readonly coercer;
24
- private readonly cache;
25
- constructor(contract: RouterContract, options?: SmartCoercionLinkPluginOptions);
26
- init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
27
- private coerceValue;
28
- }
16
+ private readonly contract;
17
+ name: string;
18
+ /**
19
+ * Output and error values should be coerced before validation.
20
+ */
21
+ after: string[];
22
+ private readonly converter;
23
+ private readonly coercer;
24
+ private readonly cache;
25
+ constructor(contract: RouterContract, options?: SmartCoercionLinkPluginOptions);
26
+ init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
27
+ private coerceValue;
28
+ }