@orpc/json-schema 2.0.0-beta.5 → 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.
@@ -0,0 +1,310 @@
1
+ import { JSON_SCHEMA_LOGIC_KEYWORDS } from "./constants.js";
2
+ import { decodeJsonPointerSegment, encodeJsonPointerSegment, hoistRecursiveRefToDef, mapJsonSchemaRefs, resolveJsonSchemaRootLocalRef } from "./ref-utils.js";
3
+ import { ensureJsonSchemaObject, isJsonArraySchema, isUnconstrainedSchema } from "./utils.js";
4
+ import { get, isDeepEqual, omit, toArray } from "@orpc/shared";
5
+ // src/composition-utils.ts
6
+ /**
7
+ * These utilities assume the schema has only one root-level `$defs` object
8
+ * and exclusively use absolute JSON pointers for `$ref` values.
9
+ */
10
+ /**
11
+ * Moves a schema's `$defs` into the shared root map, renaming only the names whose bodies
12
+ * conflict with an already promoted def, and returns the schema body rebased onto `basePath`.
13
+ *
14
+ * Refs inside the promoted def bodies are rewritten too: they share the schema's namespace, so
15
+ * a rename left unapplied there would silently bind the body to another schema's defs.
16
+ */
17
+ function promoteJsonSchemaDefs(schema, mergedDefs, basePath) {
18
+ const { $defs, ...rootBody } = schema;
19
+ const renameMap = /* @__PURE__ */ new Map();
20
+ /**
21
+ * `basePath` is where `rootBody` lands in the combined document, so pointers resolved against
22
+ * the original root are rebased onto it, while `#/$defs/` pointers follow the promoted defs.
23
+ */
24
+ const mapRef = (ref) => {
25
+ if (ref === "#") return basePath;
26
+ if (ref.startsWith("#/$defs/")) {
27
+ const [encodedName, ...segments] = ref.slice(8).split("/");
28
+ const newName = renameMap.get(decodeJsonPointerSegment(encodedName));
29
+ return newName === void 0 ? ref : [
30
+ "#/$defs",
31
+ encodeJsonPointerSegment(newName),
32
+ ...segments
33
+ ].join("/");
34
+ }
35
+ if (ref.startsWith("#/") && get(rootBody, ref.slice(2).split("/").map(decodeJsonPointerSegment)) !== void 0) return `${basePath}/${ref.slice(2)}`;
36
+ return ref;
37
+ };
38
+ const defs = Object.entries($defs ?? {}).filter(([, def]) => def !== void 0);
39
+ if (defs.length > 0) {
40
+ const promoted = /* @__PURE__ */ new Map();
41
+ const reserved = /* @__PURE__ */ new Set([...mergedDefs.keys(), ...defs.map(([name]) => name)]);
42
+ /**
43
+ * A def body must be rewritten into the merged namespace before it can be compared for
44
+ * deduplication, and each rename invalidates every body pointing at the renamed def, so
45
+ * keep rewriting until a full pass renames nothing.
46
+ */
47
+ for (let changed = true; changed;) {
48
+ changed = false;
49
+ for (const [name, def] of defs) {
50
+ const body = mapJsonSchemaRefs(def, mapRef);
51
+ promoted.set(name, body);
52
+ if (renameMap.has(name) || !mergedDefs.has(name) || isDeepEqual(mergedDefs.get(name), body)) continue;
53
+ let counter = 2;
54
+ while (reserved.has(`${name}${counter}`)) counter++;
55
+ reserved.add(`${name}${counter}`);
56
+ renameMap.set(name, `${name}${counter}`);
57
+ changed = true;
58
+ }
59
+ }
60
+ for (const [name, body] of promoted) mergedDefs.set(renameMap.get(name) ?? name, body);
61
+ }
62
+ return mapJsonSchemaRefs(rootBody, mapRef);
63
+ }
64
+ /**
65
+ * Combines multiple schemas under the requested composition keyword, promoting branch `$defs` to the root.
66
+ */
67
+ function combineJsonSchemasWithComposition(keyword, schemas) {
68
+ if (schemas.length <= 1) return schemas[0] ?? true;
69
+ const mergedDefs = /* @__PURE__ */ new Map();
70
+ const compositionBranches = [];
71
+ for (let i = 0; i < schemas.length; i++) {
72
+ const schema = schemas[i];
73
+ compositionBranches.push(typeof schema === "boolean" ? schema : promoteJsonSchemaDefs(schema, mergedDefs, `#/${keyword}/${i}`));
74
+ }
75
+ const result = { [keyword]: compositionBranches };
76
+ if (mergedDefs.size > 0) result.$defs = Object.fromEntries(mergedDefs);
77
+ return result;
78
+ }
79
+ /**
80
+ * Combines object property entries back into a single object schema.
81
+ * When given, `additionalProperties` constrains every property the entries do not name.
82
+ */
83
+ function combineJsonObjectSchemaEntries(entries, additionalProperties) {
84
+ const properties = /* @__PURE__ */ new Map();
85
+ const required = [];
86
+ const mergedDefs = /* @__PURE__ */ new Map();
87
+ for (const [name, propertySchema, optional] of entries) {
88
+ if (!optional) required.push(name);
89
+ properties.set(name, typeof propertySchema === "boolean" ? propertySchema : promoteJsonSchemaDefs(propertySchema, mergedDefs, `#/properties/${encodeJsonPointerSegment(name)}`));
90
+ }
91
+ const schema = {
92
+ type: "object",
93
+ properties: Object.fromEntries(properties)
94
+ };
95
+ if (required.length > 0) schema.required = required;
96
+ if (additionalProperties !== void 0) schema.additionalProperties = typeof additionalProperties === "boolean" ? additionalProperties : promoteJsonSchemaDefs(additionalProperties, mergedDefs, "#/additionalProperties");
97
+ if (mergedDefs.size > 0) schema.$defs = Object.fromEntries(mergedDefs);
98
+ return schema;
99
+ }
100
+ /**
101
+ * Parses an object schema, or a composition of object schemas, into property entries.
102
+ */
103
+ function extractJsonObjectSchemaEntries(schema) {
104
+ schema = hoistRecursiveRefToDef(schema);
105
+ if (typeof schema !== "object") return;
106
+ const result = extractJsonObjectSchemaEntriesInternal(omit(schema, ["$defs"]), schema.$defs, /* @__PURE__ */ new Set());
107
+ if (!result.objectLike) return;
108
+ return result.entries.map(([n, s, ...r]) => [
109
+ n,
110
+ withRootDefs(s, schema.$defs),
111
+ ...r
112
+ ]);
113
+ }
114
+ /**
115
+ * Returns the `additionalProperties` an object schema declares at its root, following root-local refs,
116
+ * with the root `$defs` attached so it can be passed to {@link combineJsonObjectSchemaEntries}.
117
+ * Composition branches are not inspected, since their keyword only constrains that branch.
118
+ */
119
+ function extractJsonObjectSchemaAdditionalProperties(schema) {
120
+ schema = hoistRecursiveRefToDef(schema);
121
+ if (typeof schema !== "object") return;
122
+ const resolved = resolveJsonSchemaRootLocalRef(schema);
123
+ if (typeof resolved !== "object" || resolved.additionalProperties === void 0) return;
124
+ return withRootDefs(resolved.additionalProperties, schema.$defs);
125
+ }
126
+ const JSON_SCHEMA_OBJECT_KEYWORDS = [
127
+ "properties",
128
+ "patternProperties",
129
+ "additionalProperties",
130
+ "required",
131
+ "propertyNames",
132
+ "minProperties",
133
+ "maxProperties"
134
+ ];
135
+ /**
136
+ * Returns true when an object can stand for every value the schema describes: the schema constrains objects,
137
+ * by `type` or object keywords, composes only such schemas, or is unconstrained, since an object satisfies it.
138
+ * Unlike {@link extractJsonObjectSchemaEntries}, an unconstrained schema counts as object-like.
139
+ */
140
+ function isJsonObjectLikeSchema(schema) {
141
+ return isJsonObjectLikeSchemaInternal(schema, typeof schema === "object" ? schema.$defs : void 0, /* @__PURE__ */ new Set());
142
+ }
143
+ function isJsonObjectLikeSchemaInternal(schema, $defs, followedRefs) {
144
+ if (typeof schema === "object" && typeof schema.$ref === "string") {
145
+ if (followedRefs.has(schema.$ref)) return false;
146
+ followedRefs = new Set(followedRefs).add(schema.$ref);
147
+ }
148
+ const resolved = resolveJsonSchemaRootLocalRef(schema, $defs);
149
+ if (typeof resolved === "boolean") return true;
150
+ if (resolved.type !== void 0) return resolved.type === "object";
151
+ if (JSON_SCHEMA_OBJECT_KEYWORDS.some((keyword) => keyword in resolved)) return true;
152
+ for (const keyword of [
153
+ "allOf",
154
+ "anyOf",
155
+ "oneOf"
156
+ ]) {
157
+ const members = resolved[keyword];
158
+ if (Array.isArray(members) && members.length > 0) return members.every((member) => isJsonObjectLikeSchemaInternal(member, $defs, followedRefs));
159
+ }
160
+ return isUnconstrainedSchema(resolved);
161
+ }
162
+ function extractJsonObjectSchemaEntriesInternal(schema, $defs, resolvingRefs) {
163
+ if (typeof schema !== "object") return {
164
+ entries: [],
165
+ objectLike: false
166
+ };
167
+ if (typeof schema.$ref === "string") {
168
+ if (resolvingRefs.has(schema.$ref)) return {
169
+ entries: [],
170
+ objectLike: true
171
+ };
172
+ const resolved = resolveJsonSchemaRootLocalRef(schema, $defs);
173
+ if (resolved !== schema) return extractJsonObjectSchemaEntriesInternal(resolved, $defs, new Set(resolvingRefs).add(schema.$ref));
174
+ }
175
+ const sources = [];
176
+ if (schema.properties) sources.push({
177
+ entries: Object.entries(schema.properties).map(([name, propertySchema]) => {
178
+ return [
179
+ name,
180
+ propertySchema,
181
+ !schema.required?.includes(name)
182
+ ];
183
+ }),
184
+ source: "direct"
185
+ });
186
+ let objectLike = schema.type === "object" || schema.properties !== void 0 || schema.required !== void 0 || schema.additionalProperties !== void 0;
187
+ for (const keyword of [
188
+ "anyOf",
189
+ "oneOf",
190
+ "allOf"
191
+ ]) {
192
+ const branches = schema[keyword];
193
+ if (branches === void 0) continue;
194
+ const branchResults = branches.map((branch) => extractJsonObjectSchemaEntriesInternal(branch, $defs, resolvingRefs));
195
+ if (branchResults.some((result) => !result.objectLike)) return {
196
+ entries: [],
197
+ objectLike: false
198
+ };
199
+ const entriesByName = /* @__PURE__ */ new Map();
200
+ for (const result of branchResults) for (const entry of result.entries) {
201
+ const entries = entriesByName.get(entry[0]);
202
+ if (entries) entries.push(entry);
203
+ else entriesByName.set(entry[0], [entry]);
204
+ }
205
+ objectLike = true;
206
+ sources.push({
207
+ entries: Array.from(entriesByName.entries()).map(([name, entries]) => {
208
+ const schemas = deduplicateJsonSchemas(entries.map((entry) => entry[1]));
209
+ const required = keyword === "allOf" ? entries.some((entry) => !entry[2]) : branchResults.every((result) => {
210
+ const entry = result.entries.find((item) => item[0] === name);
211
+ return entry !== void 0 && !entry[2];
212
+ });
213
+ return [
214
+ name,
215
+ schemas.length === 1 ? schemas[0] : keyword === "allOf" ? { allOf: schemas } : { anyOf: schemas },
216
+ !required
217
+ ];
218
+ }),
219
+ source: keyword
220
+ });
221
+ }
222
+ const sourceEntries = /* @__PURE__ */ new Map();
223
+ for (const { entries, source } of sources) for (const entry of entries) {
224
+ const existing = sourceEntries.get(entry[0]);
225
+ if (existing) existing[source] = entry;
226
+ else sourceEntries.set(entry[0], { [source]: entry });
227
+ }
228
+ return {
229
+ entries: Array.from(sourceEntries.entries()).map(([name, entries]) => {
230
+ const schemas = deduplicateJsonSchemas([
231
+ entries.direct?.[1],
232
+ entries.allOf?.[1],
233
+ entries.anyOf?.[1],
234
+ entries.oneOf?.[1]
235
+ ].filter((schema) => schema !== void 0));
236
+ return [
237
+ name,
238
+ schemas.length === 1 ? schemas[0] : { allOf: schemas },
239
+ !schema.required?.includes(name) && [
240
+ entries.allOf,
241
+ entries.anyOf,
242
+ entries.oneOf
243
+ ].every((entry) => entry === void 0 || entry[2])
244
+ ];
245
+ }),
246
+ objectLike
247
+ };
248
+ }
249
+ /**
250
+ * Flattens `anyOf` and `oneOf` unions when they are the only active constraints.
251
+ */
252
+ function flattenJsonUnionSchema(schema) {
253
+ return deduplicateJsonSchemas(flattenJsonUnionSchemaInternal(schema, /* @__PURE__ */ new Set()));
254
+ }
255
+ function flattenJsonUnionSchemaInternal(schema, resolvingRefs) {
256
+ if (typeof schema !== "object") return [schema];
257
+ if (typeof schema.$ref === "string") {
258
+ if (resolvingRefs.has(schema.$ref)) return [];
259
+ const resolved = resolveJsonSchemaRootLocalRef(schema);
260
+ if (resolved !== schema) {
261
+ const result = flattenJsonUnionSchemaInternal(resolved, new Set(resolvingRefs).add(schema.$ref));
262
+ if (result.length > 1) return result;
263
+ }
264
+ }
265
+ const { anyOf: _anyOf, oneOf: _oneOf, ...rest } = schema;
266
+ const entries = Object.entries(rest).filter(([, val]) => val !== void 0);
267
+ for (const keyword of ["anyOf", "oneOf"]) if (schema[keyword]) return schema[keyword].flatMap((s) => {
268
+ s = ensureJsonSchemaObject(s);
269
+ const mergedSchema = {
270
+ ...s,
271
+ ...Object.fromEntries(entries.filter(([key]) => s[key] === void 0)),
272
+ $defs: schema.$defs
273
+ };
274
+ const conflicts = entries.filter(([key]) => s[key] !== void 0);
275
+ if (conflicts.length) mergedSchema.allOf = [...toArray(mergedSchema.allOf), Object.fromEntries(conflicts)];
276
+ return flattenJsonUnionSchemaInternal(mergedSchema, resolvingRefs);
277
+ });
278
+ return [schema];
279
+ }
280
+ /**
281
+ * Matches a union made of a single item schema and its array form.
282
+ */
283
+ function matchArrayableJsonSchema(schema) {
284
+ const schemas = flattenJsonUnionSchema(schema);
285
+ if (schemas.length !== 2) return;
286
+ const arraySchema = schemas.find(isJsonArraySchema);
287
+ if (arraySchema === void 0) return;
288
+ const items1 = arraySchema.items ?? true;
289
+ const items2 = schemas.find((s) => s !== arraySchema);
290
+ const logicItem1 = Object.fromEntries(Object.entries(ensureJsonSchemaObject(items1)).filter(([key]) => JSON_SCHEMA_LOGIC_KEYWORDS.has(key)));
291
+ const logicItem2 = Object.fromEntries(Object.entries(ensureJsonSchemaObject(items2)).filter(([key]) => JSON_SCHEMA_LOGIC_KEYWORDS.has(key)));
292
+ if (!isDeepEqual(logicItem1, logicItem2)) return;
293
+ return [items2, arraySchema];
294
+ }
295
+ function deduplicateJsonSchemas(schemas) {
296
+ const result = [];
297
+ for (const schema of schemas) {
298
+ if (result.some((i) => isDeepEqual(i, schema))) continue;
299
+ result.push(schema);
300
+ }
301
+ return result;
302
+ }
303
+ function withRootDefs(schema, $defs) {
304
+ if (typeof schema === "boolean" || !$defs) return schema;
305
+ return {
306
+ ...schema,
307
+ $defs
308
+ };
309
+ }
310
+ export { combineJsonObjectSchemaEntries, combineJsonSchemasWithComposition, deduplicateJsonSchemas, extractJsonObjectSchemaAdditionalProperties, extractJsonObjectSchemaEntries, flattenJsonUnionSchema, isJsonObjectLikeSchema, matchArrayableJsonSchema };
@@ -0,0 +1,67 @@
1
+ // src/constants.ts
2
+ const JSON_SCHEMA_LOGIC_KEYWORDS = /* @__PURE__ */ new Set([
3
+ "$dynamicRef",
4
+ "$ref",
5
+ "additionalItems",
6
+ "additionalProperties",
7
+ "allOf",
8
+ "anyOf",
9
+ "const",
10
+ "contains",
11
+ "contentEncoding",
12
+ "contentMediaType",
13
+ "contentSchema",
14
+ "dependencies",
15
+ "dependentRequired",
16
+ "dependentSchemas",
17
+ "else",
18
+ "enum",
19
+ "exclusiveMaximum",
20
+ "exclusiveMinimum",
21
+ "format",
22
+ "if",
23
+ "items",
24
+ "maxContains",
25
+ "maximum",
26
+ "maxItems",
27
+ "maxLength",
28
+ "maxProperties",
29
+ "minContains",
30
+ "minimum",
31
+ "minItems",
32
+ "minLength",
33
+ "minProperties",
34
+ "multipleOf",
35
+ "not",
36
+ "oneOf",
37
+ "pattern",
38
+ "patternProperties",
39
+ "prefixItems",
40
+ "properties",
41
+ "propertyNames",
42
+ "required",
43
+ "then",
44
+ "type",
45
+ "unevaluatedItems",
46
+ "unevaluatedProperties",
47
+ "uniqueItems"
48
+ ]);
49
+ const JSON_SCHEMA_PRIMITIVE_TYPES = /* @__PURE__ */ new Set([
50
+ "string",
51
+ "number",
52
+ "integer",
53
+ "boolean",
54
+ "null"
55
+ ]);
56
+ const JSON_SCHEMA_RECORD_KEYWORDS = /* @__PURE__ */ new Set([
57
+ "properties",
58
+ "patternProperties",
59
+ "dependentSchemas",
60
+ "dependencies",
61
+ "$defs"
62
+ ]);
63
+ /**
64
+ * Keywords whose values are literal instance data, never subschemas.
65
+ */
66
+ const JSON_SCHEMA_LITERAL_KEYWORDS = /* @__PURE__ */ new Set(["const", "enum"]);
67
+ export { JSON_SCHEMA_LITERAL_KEYWORDS, JSON_SCHEMA_LOGIC_KEYWORDS, JSON_SCHEMA_PRIMITIVE_TYPES, JSON_SCHEMA_RECORD_KEYWORDS };
@@ -0,0 +1,29 @@
1
+ import { JsonSchema } from "./types.js";
2
+ import { AnySchema } from "@orpc/contract";
3
+ /**
4
+ * The conversion direction: `input` targets the schema's input type, `output` targets its output type.
5
+ *
6
+ * @see {@link https://orpc.dev/docs/integrations/standard-schema | Standard Schema Integration}
7
+ */
8
+ export type JsonSchemaConverterDirection = "input" | "output";
9
+ /**
10
+ * Interface for converting validation schemas into JSON Schema representations,
11
+ * used by tools such as the OpenAPI Generator and Smart Coercion plugins.
12
+ *
13
+ * @see {@link https://orpc.dev/docs/integrations/standard-schema | Standard Schema Integration}
14
+ */
15
+ export interface JsonSchemaConverter {
16
+ /**
17
+ * Determines whether this converter can handle the given schema.
18
+ */
19
+ condition(schema: AnySchema | undefined, direction: JsonSchemaConverterDirection): boolean;
20
+ /**
21
+ * Converts an ORPC schema to a JSON Schema representation.
22
+ */
23
+ convert(schema: AnySchema | undefined, direction: JsonSchemaConverterDirection): [jsonSchema: JsonSchema, optional: boolean];
24
+ }
25
+ export declare class DelegatingJsonSchemaConverter implements Pick<JsonSchemaConverter, "convert"> {
26
+ private readonly converters;
27
+ constructor(converters?: JsonSchemaConverter[]);
28
+ convert(schema: AnySchema | undefined, direction: JsonSchemaConverterDirection): [jsonSchema: JsonSchema, optional: boolean];
29
+ }
@@ -0,0 +1,12 @@
1
+ // src/convert.ts
2
+ var DelegatingJsonSchemaConverter = class {
3
+ converters;
4
+ constructor(converters = []) {
5
+ this.converters = converters;
6
+ }
7
+ convert(schema, direction) {
8
+ for (const converter of this.converters) if (converter.condition(schema, direction)) return converter.convert(schema, direction);
9
+ return [{}, true];
10
+ }
11
+ };
12
+ export { DelegatingJsonSchemaConverter };
package/dist/index.d.ts CHANGED
@@ -1,187 +1,11 @@
1
- import * as Draft2020 from 'json-schema-typed/draft-2020-12';
2
- export { Format as JsonSchemaFormat, TypeName as JsonSchemaType } from 'json-schema-typed/draft-2020-12';
3
- import { AnySchema, RouterContract } from '@orpc/contract';
4
- export { AnySchema, Schema } from '@orpc/contract';
5
- import { Promisable } from '@orpc/shared';
6
- import { Context } from '@orpc/server';
7
- import { StandardHandlerPlugin, StandardHandlerOptions } from '@orpc/server/standard';
8
- import { ClientContext } from '@orpc/client';
9
- import { StandardLinkPlugin, StandardLinkOptions } from '@orpc/client/standard';
10
- import { StandardJSONSchemaV1 } from '@standard-schema/spec';
11
-
12
- type JsonSchema = Draft2020.JSONSchema;
13
- type JsonSchemaKeywords = typeof Draft2020.keywords[number];
14
- declare enum JsonSchemaXNativeType {
15
- BigInt = "bigint",
16
- RegExp = "regexp",
17
- Date = "date",
18
- Url = "url",
19
- Set = "set",
20
- Map = "map"
21
- }
22
-
23
- declare class JsonSchemaCoercer {
24
- coerce([schema, optional]: [schema: JsonSchema, optional: boolean], value: unknown): unknown;
25
- private coerceInternal;
26
- }
27
-
28
- /**
29
- * These utilities assume the schema has only one root-level `$defs` object
30
- * and exclusively use absolute JSON pointers for `$ref` values.
31
- */
32
-
33
- declare function isJsonPrimitiveSchema(schema: JsonSchema): schema is JsonSchema & object;
34
- type JsonFileSchema = JsonSchema & object & {
35
- type: 'string';
36
- contentMediaType?: string;
37
- };
38
- /**
39
- * Returns true when the schema is a file-like string schema.
40
- */
41
- declare function isJsonFileSchema(schema: JsonSchema): schema is JsonFileSchema;
42
- type JsonObjectSchema = JsonSchema & object & {
43
- type: 'object';
44
- };
45
- /**
46
- * Returns true when the schema is an object schema.
47
- */
48
- declare function isJsonObjectSchema(schema: JsonSchema): schema is JsonObjectSchema;
49
- type JsonArraySchema = JsonSchema & object & {
50
- type: 'array';
51
- };
52
- /**
53
- * Returns true when the schema is an array schema.
54
- */
55
- declare function isJsonArraySchema(schema: JsonSchema): schema is JsonArraySchema;
56
- /**
57
- * Returns true when the schema does not apply any recognized constraints.
58
- */
59
- declare function isUnconstrainedSchema(schema: JsonSchema): boolean;
60
- /**
61
- * Ensures a JSON Schema is represented as an object schema document.
62
- */
63
- declare function ensureJsonSchemaObject(schema: JsonSchema): Exclude<JsonSchema, boolean>;
64
-
65
- /**
66
- * These utilities assume the schema has only one root-level `$defs` object
67
- * and exclusively use absolute JSON pointers for `$ref` values.
68
- */
69
-
70
- /**
71
- * Combines multiple schemas under the requested composition keyword, promoting branch `$defs` to the root.
72
- */
73
- declare function combineJsonSchemasWithComposition(keyword: 'allOf' | 'anyOf' | 'oneOf', schemas: JsonSchema[]): JsonSchema;
74
- type JsonObjectSchemaEntry = [name: string, schema: JsonSchema, optional: boolean];
75
- /**
76
- * Combines object property entries back into a single object schema.
77
- */
78
- declare function combineJsonObjectSchemaEntries(entries: JsonObjectSchemaEntry[]): JsonObjectSchema;
79
- /**
80
- * Parses an object schema, or a composition of object schemas, into property entries.
81
- */
82
- declare function extractJsonObjectSchemaEntries(schema: JsonSchema): JsonObjectSchemaEntry[] | undefined;
83
- /**
84
- * Flattens `anyOf` and `oneOf` unions when they are the only active constraints.
85
- */
86
- declare function flattenJsonUnionSchema(schema: JsonSchema): JsonSchema[];
87
- /**
88
- * Matches a union made of a single item schema and its array form.
89
- */
90
- declare function matchArrayableJsonSchema(schema: JsonSchema): undefined | [itemSchema: JsonSchema, arraySchema: JsonArraySchema];
91
- declare function deduplicateJsonSchemas(schemas: JsonSchema[]): JsonSchema[];
92
-
93
- type JsonSchemaConverterDirection = 'input' | 'output';
94
- interface JsonSchemaConverter {
95
- /**
96
- * Determines whether this converter can handle the given schema.
97
- */
98
- condition(schema: AnySchema | undefined, direction: JsonSchemaConverterDirection): Promisable<boolean>;
99
- /**
100
- * Converts an ORPC schema to a JSON Schema representation.
101
- */
102
- convert(schema: AnySchema | undefined, direction: JsonSchemaConverterDirection): Promisable<[jsonSchema: JsonSchema, optional: boolean]>;
103
- }
104
- declare class DelegatingJsonSchemaConverter implements Pick<JsonSchemaConverter, 'convert'> {
105
- private readonly converters;
106
- constructor(converters?: JsonSchemaConverter[]);
107
- convert(schema: AnySchema | undefined, direction: JsonSchemaConverterDirection): Promise<[jsonSchema: JsonSchema, optional: boolean]>;
108
- }
109
-
110
- /**
111
- * These utilities assume the schema has only one root-level `$defs` object
112
- * and exclusively use absolute JSON pointers for `$ref` values.
113
- */
114
-
115
- /**
116
- * Encodes a JSON Pointer segment according to RFC 6901.
117
- *
118
- * https://datatracker.ietf.org/doc/html/rfc6901
119
- */
120
- declare function encodeJsonPointerSegment(segment: string): string;
121
- /**
122
- * Decodes a JSON Pointer segment according to RFC 6901.
123
- *
124
- * https://datatracker.ietf.org/doc/html/rfc6901
125
- */
126
- declare function decodeJsonPointerSegment(segment: string): string;
127
- declare function mapJsonSchemaRefs(value: JsonSchema, map: (ref: string, path: Array<string | number>) => string, schemaLevel?: boolean, path?: Array<string | number>): JsonSchema;
128
- /**
129
- * Rewrites recursive root `#` refs by moving the schema body into `$defs`.
130
- */
131
- declare function hoistRecursiveRefToDef(schema: JsonSchema): JsonSchema;
132
- /**
133
- * Resolves a local `$ref` at the **root level** of the given schema, if present.
134
- *
135
- * Only handles refs of the form `#/$defs/<name>` pointing into the provided
136
- * (or schema-embedded) `$defs` map. Nested `$ref`s inside sub-schemas are
137
- * intentionally left untouched.
138
- *
139
- * If the ref cannot be resolved (missing `$defs`, unknown key, etc.) the
140
- * schema is returned as-is.
141
- *
142
- * @param schema - The schema whose root-level `$ref` should be resolved.
143
- * @param $defs - Definition map to resolve against. If omitted, falls back to
144
- * `schema.$defs`. When provided, takes precedence over any `$defs` embedded
145
- * in the schema.
146
- */
147
- declare function resolveJsonSchemaRootLocalRef(schema: JsonSchema, $defs?: Exclude<JsonSchema, boolean>['$defs']): JsonSchema;
148
-
149
- interface SmartCoercionHandlerPluginOptions {
150
- converters?: undefined | JsonSchemaConverter[];
151
- }
152
- declare class SmartCoercionHandlerPlugin<T extends Context> implements StandardHandlerPlugin<T> {
153
- name: string;
154
- private readonly converter;
155
- private readonly coercer;
156
- private readonly cache;
157
- constructor(options?: SmartCoercionHandlerPluginOptions);
158
- init(options: StandardHandlerOptions<T>): StandardHandlerOptions<T>;
159
- private coerceValue;
160
- }
161
-
162
- interface SmartCoercionLinkPluginOptions {
163
- converters?: undefined | JsonSchemaConverter[];
164
- }
165
- declare class SmartCoercionLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
166
- private readonly contract;
167
- name: string;
168
- /**
169
- * Output and error values should be coerced before validation.
170
- */
171
- after: string[];
172
- private readonly converter;
173
- private readonly coercer;
174
- private readonly cache;
175
- constructor(contract: RouterContract, options?: SmartCoercionLinkPluginOptions);
176
- init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
177
- private coerceValue;
178
- }
179
-
180
- declare class StandardJsonSchemaConverter implements JsonSchemaConverter {
181
- condition(schema: AnySchema | undefined, _direction: JsonSchemaConverterDirection): boolean;
182
- convert(schema: AnySchema | undefined, direction: JsonSchemaConverterDirection): [jsonSchema: JsonSchema, optional: boolean];
183
- convertInternal(schema: StandardJSONSchemaV1 & AnySchema, direction: JsonSchemaConverterDirection): [jsonSchema: JsonSchema, optional: boolean];
184
- }
185
-
186
- export { DelegatingJsonSchemaConverter, JsonSchemaCoercer, JsonSchemaXNativeType, SmartCoercionHandlerPlugin, SmartCoercionLinkPlugin, StandardJsonSchemaConverter, combineJsonObjectSchemaEntries, combineJsonSchemasWithComposition, decodeJsonPointerSegment, deduplicateJsonSchemas, encodeJsonPointerSegment, ensureJsonSchemaObject, extractJsonObjectSchemaEntries, flattenJsonUnionSchema, hoistRecursiveRefToDef, isJsonArraySchema, isJsonFileSchema, isJsonObjectSchema, isJsonPrimitiveSchema, isUnconstrainedSchema, mapJsonSchemaRefs, matchArrayableJsonSchema, resolveJsonSchemaRootLocalRef };
187
- export type { JsonArraySchema, JsonFileSchema, JsonObjectSchema, JsonObjectSchemaEntry, JsonSchema, JsonSchemaConverter, JsonSchemaConverterDirection, JsonSchemaKeywords, SmartCoercionHandlerPluginOptions, SmartCoercionLinkPluginOptions };
1
+ import { JsonSchemaCoercer, JsonSchemaCoercerOptions } from "./coercer.js";
2
+ import { JsonObjectSchemaEntry, combineJsonObjectSchemaEntries, combineJsonSchemasWithComposition, deduplicateJsonSchemas, extractJsonObjectSchemaAdditionalProperties, extractJsonObjectSchemaEntries, flattenJsonUnionSchema, isJsonObjectLikeSchema, matchArrayableJsonSchema } from "./composition-utils.js";
3
+ import { DelegatingJsonSchemaConverter, JsonSchemaConverter, JsonSchemaConverterDirection } from "./convert.js";
4
+ import { JsonSchemaKeywordKind, decodeJsonPointerSegment, encodeJsonPointerSegment, getJsonSchemaKeywordKind, hoistRecursiveRefToDef, mapJsonSchemaRefs, resolveJsonSchemaLocalPointer, resolveJsonSchemaRootLocalRef, visitJsonSchemaRefs } from "./ref-utils.js";
5
+ import { SmartCoercionHandlerPlugin, SmartCoercionHandlerPluginOptions } from "./smart-coercion-handler-plugin.js";
6
+ import { SmartCoercionLinkPlugin, SmartCoercionLinkPluginOptions } from "./smart-coercion-link-plugin.js";
7
+ import { StandardJsonSchemaConverter, isStandardSchemaOptional } from "./standard-json-schema-converter.js";
8
+ import { JsonSchema, JsonSchemaFormat, JsonSchemaKeywords, JsonSchemaType, JsonSchemaXNativeType } from "./types.js";
9
+ import { JsonArraySchema, JsonFileSchema, JsonObjectSchema, containsJsonFileSchema, ensureJsonSchemaObject, isJsonArraySchema, isJsonFileSchema, isJsonObjectSchema, isJsonPrimitiveSchema, isUnconstrainedSchema } from "./utils.js";
10
+ import { AnySchema, Schema } from "@orpc/contract";
11
+ export { type AnySchema, DelegatingJsonSchemaConverter, JsonArraySchema, JsonFileSchema, JsonObjectSchema, JsonObjectSchemaEntry, JsonSchema, JsonSchemaCoercer, JsonSchemaCoercerOptions, JsonSchemaConverter, JsonSchemaConverterDirection, JsonSchemaFormat, JsonSchemaKeywordKind, JsonSchemaKeywords, JsonSchemaType, JsonSchemaXNativeType, type Schema, SmartCoercionHandlerPlugin, SmartCoercionHandlerPluginOptions, SmartCoercionLinkPlugin, SmartCoercionLinkPluginOptions, StandardJsonSchemaConverter, combineJsonObjectSchemaEntries, combineJsonSchemasWithComposition, containsJsonFileSchema, decodeJsonPointerSegment, deduplicateJsonSchemas, encodeJsonPointerSegment, ensureJsonSchemaObject, extractJsonObjectSchemaAdditionalProperties, extractJsonObjectSchemaEntries, flattenJsonUnionSchema, getJsonSchemaKeywordKind, hoistRecursiveRefToDef, isJsonArraySchema, isJsonFileSchema, isJsonObjectLikeSchema, isJsonObjectSchema, isJsonPrimitiveSchema, isStandardSchemaOptional, isUnconstrainedSchema, mapJsonSchemaRefs, matchArrayableJsonSchema, resolveJsonSchemaLocalPointer, resolveJsonSchemaRootLocalRef, visitJsonSchemaRefs };
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
1
+ export { JsonSchemaCoercer } from "./coercer.js";
2
+ export { combineJsonObjectSchemaEntries, combineJsonSchemasWithComposition, deduplicateJsonSchemas, extractJsonObjectSchemaAdditionalProperties, extractJsonObjectSchemaEntries, flattenJsonUnionSchema, isJsonObjectLikeSchema, matchArrayableJsonSchema } from "./composition-utils.js";
3
+ export { DelegatingJsonSchemaConverter } from "./convert.js";
4
+ export { decodeJsonPointerSegment, encodeJsonPointerSegment, getJsonSchemaKeywordKind, hoistRecursiveRefToDef, mapJsonSchemaRefs, resolveJsonSchemaLocalPointer, resolveJsonSchemaRootLocalRef, visitJsonSchemaRefs } from "./ref-utils.js";
5
+ export { SmartCoercionHandlerPlugin } from "./smart-coercion-handler-plugin.js";
6
+ export { SmartCoercionLinkPlugin } from "./smart-coercion-link-plugin.js";
7
+ export { StandardJsonSchemaConverter, isStandardSchemaOptional } from "./standard-json-schema-converter.js";
8
+ export { JsonSchemaFormat, JsonSchemaType, JsonSchemaXNativeType } from "./types.js";
9
+ export { containsJsonFileSchema, ensureJsonSchemaObject, isJsonArraySchema, isJsonFileSchema, isJsonObjectSchema, isJsonPrimitiveSchema, isUnconstrainedSchema } from "./utils.js";