@orpc/json-schema 2.0.0-beta.5 → 2.0.0-beta.51
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +139 -102
- package/dist/coercer.d.ts +29 -0
- package/dist/coercer.js +354 -0
- package/dist/composition-utils.d.ts +45 -0
- package/dist/composition-utils.js +335 -0
- package/dist/constants.js +67 -0
- package/dist/convert.d.ts +29 -0
- package/dist/convert.js +12 -0
- package/dist/index.d.ts +11 -187
- package/dist/index.js +9 -0
- package/dist/ref-utils.d.ts +55 -0
- package/dist/ref-utils.js +203 -0
- package/dist/smart-coercion-handler-plugin.d.ts +22 -0
- package/dist/smart-coercion-handler-plugin.js +47 -0
- package/dist/smart-coercion-link-plugin.d.ts +28 -0
- package/dist/smart-coercion-link-plugin.js +63 -0
- package/dist/standard-json-schema-converter.d.ts +16 -0
- package/dist/standard-json-schema-converter.js +36 -0
- package/dist/types.d.ts +51 -0
- package/dist/types.js +42 -0
- package/dist/utils.d.ts +41 -0
- package/dist/utils.js +74 -0
- package/package.json +29 -22
- package/dist/index.d.mts +0 -187
- package/dist/index.mjs +0 -997
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { JsonSchema } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Encodes a JSON Pointer segment according to RFC 6901.
|
|
4
|
+
*
|
|
5
|
+
* https://datatracker.ietf.org/doc/html/rfc6901
|
|
6
|
+
*/
|
|
7
|
+
export declare function encodeJsonPointerSegment(segment: string): string;
|
|
8
|
+
/**
|
|
9
|
+
* Decodes a JSON Pointer segment according to RFC 6901.
|
|
10
|
+
*
|
|
11
|
+
* https://datatracker.ietf.org/doc/html/rfc6901
|
|
12
|
+
*/
|
|
13
|
+
export declare function decodeJsonPointerSegment(segment: string): string;
|
|
14
|
+
/**
|
|
15
|
+
* Resolves a local JSON pointer ref (`#` or `#/...`) against the root schema.
|
|
16
|
+
* Returns `undefined` for non-local refs and missing targets.
|
|
17
|
+
*/
|
|
18
|
+
export declare function resolveJsonSchemaLocalPointer(root: JsonSchema, ref: string): JsonSchema | undefined;
|
|
19
|
+
export type JsonSchemaKeywordKind = "ref" | "discriminator" | "schema" | "schema-record" | "data";
|
|
20
|
+
/**
|
|
21
|
+
* Classifies `value` under `key` in a schema object, as traversed by {@link visitJsonSchemaRefs}
|
|
22
|
+
* and {@link mapJsonSchemaRefs}: a `$ref` string, an OpenAPI `discriminator`, a subschema (or list
|
|
23
|
+
* of subschemas), a record of subschemas, or data that holds no refs (including `const`/`enum`).
|
|
24
|
+
*
|
|
25
|
+
* @param schemaLevel `false` when the object is itself a record of subschemas, e.g. `properties`.
|
|
26
|
+
*/
|
|
27
|
+
export declare function getJsonSchemaKeywordKind(key: string, value: unknown, schemaLevel?: boolean): JsonSchemaKeywordKind;
|
|
28
|
+
/**
|
|
29
|
+
* Visits every `$ref` in a schema, traversing the same keywords as {@link mapJsonSchemaRefs}.
|
|
30
|
+
* Local pointers in OpenAPI `discriminator.mapping`/`defaultMapping` values are visited too.
|
|
31
|
+
* Shared or cyclic object instances are visited once.
|
|
32
|
+
*/
|
|
33
|
+
export declare function visitJsonSchemaRefs(value: JsonSchema, visit: (ref: string) => void, schemaLevel?: boolean, seen?: Set<object>): void;
|
|
34
|
+
export declare function mapJsonSchemaRefs(value: JsonSchema, map: (ref: string, path: Array<string | number>) => string, schemaLevel?: boolean, path?: Array<string | number>): JsonSchema;
|
|
35
|
+
/**
|
|
36
|
+
* Rewrites recursive root `#` refs by moving the schema body into `$defs`.
|
|
37
|
+
*/
|
|
38
|
+
export declare function hoistRecursiveRefToDef(schema: JsonSchema): JsonSchema;
|
|
39
|
+
/**
|
|
40
|
+
* Resolves a local `$ref` at the **root level** of the given schema, if present.
|
|
41
|
+
*
|
|
42
|
+
* Only handles refs of the form `#/$defs/<name>` pointing into the provided
|
|
43
|
+
* (or schema-embedded) `$defs` map. Nested `$ref`s inside sub-schemas are
|
|
44
|
+
* intentionally left untouched.
|
|
45
|
+
*
|
|
46
|
+
* If the ref cannot be resolved (missing `$defs`, unknown key, etc.) the
|
|
47
|
+
* schema is returned as-is. Chained refs are followed until one repeats,
|
|
48
|
+
* which is kept.
|
|
49
|
+
*
|
|
50
|
+
* @param schema - The schema whose root-level `$ref` should be resolved.
|
|
51
|
+
* @param $defs - Definition map to resolve against. If omitted, falls back to
|
|
52
|
+
* `schema.$defs`. When provided, takes precedence over any `$defs` embedded
|
|
53
|
+
* in the schema.
|
|
54
|
+
*/
|
|
55
|
+
export declare function resolveJsonSchemaRootLocalRef(schema: JsonSchema, $defs?: Exclude<JsonSchema, boolean>["$defs"]): JsonSchema;
|
|
@@ -0,0 +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
|
|
4
|
+
/**
|
|
5
|
+
* These utilities assume the schema has only one root-level `$defs` object
|
|
6
|
+
* and exclusively use absolute JSON pointers for `$ref` values.
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
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");
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
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", "~");
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
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));
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
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";
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
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
|
+
*/
|
|
52
|
+
function isDiscriminatorRef(value) {
|
|
53
|
+
return typeof value === "string" && value.startsWith("#");
|
|
54
|
+
}
|
|
55
|
+
function visitDiscriminatorRefs(discriminator, visit) {
|
|
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);
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
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
|
+
}
|
|
88
|
+
}
|
|
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;
|
|
112
|
+
}
|
|
113
|
+
function mapDiscriminatorRefs(discriminator, map, path) {
|
|
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
|
+
};
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
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
|
+
};
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
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;
|
|
197
|
+
}
|
|
198
|
+
function findRecursiveJsonSchemaDefName(defs) {
|
|
199
|
+
let index = 0;
|
|
200
|
+
while (defs?.[`__schema${index}`] !== void 0) index++;
|
|
201
|
+
return `__schema${index}`;
|
|
202
|
+
}
|
|
203
|
+
export { decodeJsonPointerSegment, encodeJsonPointerSegment, getJsonSchemaKeywordKind, hoistRecursiveRefToDef, mapJsonSchemaRefs, resolveJsonSchemaLocalPointer, resolveJsonSchemaRootLocalRef, visitJsonSchemaRefs };
|
|
@@ -0,0 +1,22 @@
|
|
|
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
|
+
export interface SmartCoercionHandlerPluginOptions extends JsonSchemaCoercerOptions {
|
|
6
|
+
converters?: JsonSchemaConverter[] | undefined;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Coerces incoming request data to match the expected `.input` schema types before validation,
|
|
10
|
+
* based on JSON schemas produced by the configured converters.
|
|
11
|
+
*
|
|
12
|
+
* @see {@link https://orpc.dev/docs/plugins/smart-coercion | Smart Coercion Plugin}
|
|
13
|
+
*/
|
|
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
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
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
|
|
6
|
+
/**
|
|
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 };
|
|
@@ -0,0 +1,28 @@
|
|
|
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
|
+
export interface SmartCoercionLinkPluginOptions extends JsonSchemaCoercerOptions {
|
|
7
|
+
converters?: JsonSchemaConverter[] | undefined;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Coerces server responses to match the expected `.output` or `.errors` schema types before validation,
|
|
11
|
+
* based on JSON schemas produced by the configured converters.
|
|
12
|
+
*
|
|
13
|
+
* @see {@link https://orpc.dev/docs/plugins/smart-coercion | Smart Coercion Plugin}
|
|
14
|
+
*/
|
|
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
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { JsonSchemaCoercer } from "./coercer.js";
|
|
2
|
+
import { DelegatingJsonSchemaConverter } from "./convert.js";
|
|
3
|
+
import { StandardJsonSchemaConverter } from "./standard-json-schema-converter.js";
|
|
4
|
+
import { getOwn, toArray } from "@orpc/shared";
|
|
5
|
+
import { ORPCError, cloneORPCError } from "@orpc/client";
|
|
6
|
+
import { getProcedureContractOrThrow } from "@orpc/contract";
|
|
7
|
+
// src/smart-coercion-link-plugin.ts
|
|
8
|
+
/**
|
|
9
|
+
* Coerces server responses to match the expected `.output` or `.errors` schema types before validation,
|
|
10
|
+
* based on JSON schemas produced by the configured converters.
|
|
11
|
+
*
|
|
12
|
+
* @see {@link https://orpc.dev/docs/plugins/smart-coercion | Smart Coercion Plugin}
|
|
13
|
+
*/
|
|
14
|
+
var SmartCoercionLinkPlugin = class {
|
|
15
|
+
contract;
|
|
16
|
+
name = "~smart-coercion";
|
|
17
|
+
/**
|
|
18
|
+
* Output and error values should be coerced before validation.
|
|
19
|
+
*/
|
|
20
|
+
after = ["~response-validation"];
|
|
21
|
+
converter;
|
|
22
|
+
coercer;
|
|
23
|
+
cache = /* @__PURE__ */ new WeakMap();
|
|
24
|
+
constructor(contract, options = {}) {
|
|
25
|
+
this.contract = contract;
|
|
26
|
+
this.converter = new DelegatingJsonSchemaConverter([...toArray(options.converters), new StandardJsonSchemaConverter()]);
|
|
27
|
+
this.coercer = new JsonSchemaCoercer(options);
|
|
28
|
+
}
|
|
29
|
+
init(options) {
|
|
30
|
+
return {
|
|
31
|
+
...options,
|
|
32
|
+
interceptors: [...toArray(options.interceptors), async ({ next, path }) => {
|
|
33
|
+
const procedure = getProcedureContractOrThrow(this.contract, path);
|
|
34
|
+
try {
|
|
35
|
+
const output = await next();
|
|
36
|
+
const outputSchemas = procedure["~orpc"].outputSchemas;
|
|
37
|
+
if (!outputSchemas) return output;
|
|
38
|
+
return this.coerceValue(outputSchemas, output);
|
|
39
|
+
} catch (error) {
|
|
40
|
+
if (!(error instanceof ORPCError) || !error.defined) throw error;
|
|
41
|
+
const errorMap = procedure["~orpc"].errorMap;
|
|
42
|
+
const dataSchema = getOwn(errorMap, error.code)?.data;
|
|
43
|
+
if (!dataSchema) throw error;
|
|
44
|
+
const cloned = cloneORPCError(error);
|
|
45
|
+
cloned.data = this.coerceValue([dataSchema], cloned.data);
|
|
46
|
+
throw cloned;
|
|
47
|
+
}
|
|
48
|
+
}]
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
coerceValue(schemas, value) {
|
|
52
|
+
for (const schema of schemas) {
|
|
53
|
+
let converted = this.cache.get(schema);
|
|
54
|
+
if (!converted) {
|
|
55
|
+
converted = this.converter.convert(schema, "output");
|
|
56
|
+
this.cache.set(schema, converted);
|
|
57
|
+
}
|
|
58
|
+
value = this.coercer.coerce(converted, value);
|
|
59
|
+
}
|
|
60
|
+
return value;
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
export { SmartCoercionLinkPlugin };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { JsonSchemaConverter, JsonSchemaConverterDirection } from "./convert.js";
|
|
2
|
+
import { JsonSchema } from "./types.js";
|
|
3
|
+
import { AnySchema } from "@orpc/contract";
|
|
4
|
+
import { StandardJSONSchemaV1 } from "@standard-schema/spec";
|
|
5
|
+
/**
|
|
6
|
+
* Returns true when the schema accepts `undefined` in the given direction,
|
|
7
|
+
* found by validating `undefined` against it. For `output`, the validated value must also be `undefined`.
|
|
8
|
+
*
|
|
9
|
+
* Returns false when validation throws or is async. An async result is never left as an unhandled rejection.
|
|
10
|
+
*/
|
|
11
|
+
export declare function isStandardSchemaOptional(schema: AnySchema, direction: JsonSchemaConverterDirection): boolean;
|
|
12
|
+
export declare class StandardJsonSchemaConverter implements JsonSchemaConverter {
|
|
13
|
+
condition(schema: AnySchema | undefined, _direction: JsonSchemaConverterDirection): boolean;
|
|
14
|
+
convert(schema: AnySchema | undefined, direction: JsonSchemaConverterDirection): [jsonSchema: JsonSchema, optional: boolean];
|
|
15
|
+
convertInternal(schema: StandardJSONSchemaV1 & AnySchema, direction: JsonSchemaConverterDirection): [jsonSchema: JsonSchema, optional: boolean];
|
|
16
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { isNonPrimitive } from "@orpc/shared";
|
|
2
|
+
// src/standard-json-schema-converter.ts
|
|
3
|
+
/**
|
|
4
|
+
* Returns true when the schema accepts `undefined` in the given direction,
|
|
5
|
+
* found by validating `undefined` against it. For `output`, the validated value must also be `undefined`.
|
|
6
|
+
*
|
|
7
|
+
* Returns false when validation throws or is async. An async result is never left as an unhandled rejection.
|
|
8
|
+
*/
|
|
9
|
+
function isStandardSchemaOptional(schema, direction) {
|
|
10
|
+
try {
|
|
11
|
+
const result = schema["~standard"].validate(void 0);
|
|
12
|
+
if (result instanceof Promise) {
|
|
13
|
+
result.catch(() => {});
|
|
14
|
+
return false;
|
|
15
|
+
}
|
|
16
|
+
return !result.issues && (direction === "input" || result.value === void 0);
|
|
17
|
+
} catch {
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
var StandardJsonSchemaConverter = class {
|
|
22
|
+
condition(schema, _direction) {
|
|
23
|
+
return Boolean(schema && "jsonSchema" in schema["~standard"] && isNonPrimitive(schema["~standard"].jsonSchema) && "input" in schema["~standard"].jsonSchema && typeof schema["~standard"].jsonSchema.input === "function" && "output" in schema["~standard"].jsonSchema && typeof schema["~standard"].jsonSchema.output === "function");
|
|
24
|
+
}
|
|
25
|
+
convert(schema, direction) {
|
|
26
|
+
return this.convertInternal(schema, direction);
|
|
27
|
+
}
|
|
28
|
+
convertInternal(schema, direction) {
|
|
29
|
+
try {
|
|
30
|
+
return [direction === "input" ? schema["~standard"].jsonSchema.input({ target: "draft-2020-12" }) : schema["~standard"].jsonSchema.output({ target: "draft-2020-12" }), isStandardSchemaOptional(schema, direction)];
|
|
31
|
+
} catch {
|
|
32
|
+
return [{}, true];
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
export { StandardJsonSchemaConverter, isStandardSchemaOptional };
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import * as OpenAPIV3_2 from "@openapi-spec/types/v3.2";
|
|
2
|
+
/**
|
|
3
|
+
* A JSON Schema (draft 2020-12) representation used across oRPC's JSON schema tooling.
|
|
4
|
+
*
|
|
5
|
+
* @remarks
|
|
6
|
+
* It is also the OpenAPI 3.2 Schema Object, so converted schemas embed into OpenAPI documents as-is.
|
|
7
|
+
*
|
|
8
|
+
* @see {@link https://orpc.dev/docs/integrations/standard-schema | Standard Schema Integration}
|
|
9
|
+
*/
|
|
10
|
+
export type JsonSchema<Value = any> = OpenAPIV3_2.SchemaObject<Value>;
|
|
11
|
+
/**
|
|
12
|
+
* The declared JSON Schema keywords, the index signature is filtered out.
|
|
13
|
+
*/
|
|
14
|
+
export type JsonSchemaKeywords = keyof { [K in keyof OpenAPIV3_2.SchemaObjectFields as string extends K ? never : K]: unknown; };
|
|
15
|
+
export declare enum JsonSchemaType {
|
|
16
|
+
Array = "array",
|
|
17
|
+
Boolean = "boolean",
|
|
18
|
+
Integer = "integer",
|
|
19
|
+
Null = "null",
|
|
20
|
+
Number = "number",
|
|
21
|
+
Object = "object",
|
|
22
|
+
String = "string"
|
|
23
|
+
}
|
|
24
|
+
export declare enum JsonSchemaFormat {
|
|
25
|
+
Date = "date",
|
|
26
|
+
DateTime = "date-time",
|
|
27
|
+
Duration = "duration",
|
|
28
|
+
Email = "email",
|
|
29
|
+
Hostname = "hostname",
|
|
30
|
+
IDNEmail = "idn-email",
|
|
31
|
+
IDNHostname = "idn-hostname",
|
|
32
|
+
IPv4 = "ipv4",
|
|
33
|
+
IPv6 = "ipv6",
|
|
34
|
+
IRI = "iri",
|
|
35
|
+
IRIReference = "iri-reference",
|
|
36
|
+
JSONPointer = "json-pointer",
|
|
37
|
+
RegEx = "regex",
|
|
38
|
+
RelativeJSONPointer = "relative-json-pointer",
|
|
39
|
+
Time = "time",
|
|
40
|
+
URI = "uri",
|
|
41
|
+
URIReference = "uri-reference",
|
|
42
|
+
URITemplate = "uri-template",
|
|
43
|
+
UUID = "uuid"
|
|
44
|
+
}
|
|
45
|
+
export declare enum JsonSchemaXNativeType {
|
|
46
|
+
BigInt = "bigint",
|
|
47
|
+
Date = "date",
|
|
48
|
+
Url = "url",
|
|
49
|
+
Set = "set",
|
|
50
|
+
Map = "map"
|
|
51
|
+
}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// src/types.ts
|
|
2
|
+
let JsonSchemaType = /* @__PURE__ */ function(JsonSchemaType) {
|
|
3
|
+
JsonSchemaType["Array"] = "array";
|
|
4
|
+
JsonSchemaType["Boolean"] = "boolean";
|
|
5
|
+
JsonSchemaType["Integer"] = "integer";
|
|
6
|
+
JsonSchemaType["Null"] = "null";
|
|
7
|
+
JsonSchemaType["Number"] = "number";
|
|
8
|
+
JsonSchemaType["Object"] = "object";
|
|
9
|
+
JsonSchemaType["String"] = "string";
|
|
10
|
+
return JsonSchemaType;
|
|
11
|
+
}({});
|
|
12
|
+
let JsonSchemaFormat = /* @__PURE__ */ function(JsonSchemaFormat) {
|
|
13
|
+
JsonSchemaFormat["Date"] = "date";
|
|
14
|
+
JsonSchemaFormat["DateTime"] = "date-time";
|
|
15
|
+
JsonSchemaFormat["Duration"] = "duration";
|
|
16
|
+
JsonSchemaFormat["Email"] = "email";
|
|
17
|
+
JsonSchemaFormat["Hostname"] = "hostname";
|
|
18
|
+
JsonSchemaFormat["IDNEmail"] = "idn-email";
|
|
19
|
+
JsonSchemaFormat["IDNHostname"] = "idn-hostname";
|
|
20
|
+
JsonSchemaFormat["IPv4"] = "ipv4";
|
|
21
|
+
JsonSchemaFormat["IPv6"] = "ipv6";
|
|
22
|
+
JsonSchemaFormat["IRI"] = "iri";
|
|
23
|
+
JsonSchemaFormat["IRIReference"] = "iri-reference";
|
|
24
|
+
JsonSchemaFormat["JSONPointer"] = "json-pointer";
|
|
25
|
+
JsonSchemaFormat["RegEx"] = "regex";
|
|
26
|
+
JsonSchemaFormat["RelativeJSONPointer"] = "relative-json-pointer";
|
|
27
|
+
JsonSchemaFormat["Time"] = "time";
|
|
28
|
+
JsonSchemaFormat["URI"] = "uri";
|
|
29
|
+
JsonSchemaFormat["URIReference"] = "uri-reference";
|
|
30
|
+
JsonSchemaFormat["URITemplate"] = "uri-template";
|
|
31
|
+
JsonSchemaFormat["UUID"] = "uuid";
|
|
32
|
+
return JsonSchemaFormat;
|
|
33
|
+
}({});
|
|
34
|
+
let JsonSchemaXNativeType = /* @__PURE__ */ function(JsonSchemaXNativeType) {
|
|
35
|
+
JsonSchemaXNativeType["BigInt"] = "bigint";
|
|
36
|
+
JsonSchemaXNativeType["Date"] = "date";
|
|
37
|
+
JsonSchemaXNativeType["Url"] = "url";
|
|
38
|
+
JsonSchemaXNativeType["Set"] = "set";
|
|
39
|
+
JsonSchemaXNativeType["Map"] = "map";
|
|
40
|
+
return JsonSchemaXNativeType;
|
|
41
|
+
}({});
|
|
42
|
+
export { JsonSchemaFormat, JsonSchemaType, JsonSchemaXNativeType };
|
package/dist/utils.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { JsonSchema } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Returns true when the schema only describes primitive values, by a primitive `type`
|
|
4
|
+
* (or a non-empty list of them, such as `['string', 'null']`), a `const`, or an `enum`.
|
|
5
|
+
* Composition keywords are not inspected, so flatten unions with {@link flattenJsonUnionSchema} first.
|
|
6
|
+
*/
|
|
7
|
+
export declare function isJsonPrimitiveSchema(schema: JsonSchema): schema is JsonSchema & object;
|
|
8
|
+
export type JsonFileSchema = JsonSchema & object & {
|
|
9
|
+
type: "string";
|
|
10
|
+
contentMediaType?: string;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Returns true when the schema is a file-like string schema.
|
|
14
|
+
*/
|
|
15
|
+
export declare function isJsonFileSchema(schema: JsonSchema): schema is JsonFileSchema;
|
|
16
|
+
/**
|
|
17
|
+
* Returns true when a file schema is reachable from the schema, such as through a property, a composition, or a local `$ref`.
|
|
18
|
+
*/
|
|
19
|
+
export declare function containsJsonFileSchema(schema: JsonSchema): boolean;
|
|
20
|
+
export type JsonObjectSchema = JsonSchema & object & {
|
|
21
|
+
type: "object";
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Returns true when the schema is an object schema.
|
|
25
|
+
*/
|
|
26
|
+
export declare function isJsonObjectSchema(schema: JsonSchema): schema is JsonObjectSchema;
|
|
27
|
+
export type JsonArraySchema = JsonSchema & object & {
|
|
28
|
+
type: "array";
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Returns true when the schema is an array schema.
|
|
32
|
+
*/
|
|
33
|
+
export declare function isJsonArraySchema(schema: JsonSchema): schema is JsonArraySchema;
|
|
34
|
+
/**
|
|
35
|
+
* Returns true when the schema does not apply any recognized constraints.
|
|
36
|
+
*/
|
|
37
|
+
export declare function isUnconstrainedSchema(schema: JsonSchema): boolean;
|
|
38
|
+
/**
|
|
39
|
+
* Ensures a JSON Schema is represented as an object schema document.
|
|
40
|
+
*/
|
|
41
|
+
export declare function ensureJsonSchemaObject(schema: JsonSchema): Exclude<JsonSchema, boolean>;
|